TGTGInsighttelegram intelligenceLIVE / telegram public index
← Python Заметки

TGINSIGHT SIMILAR POSTS

Најди сличен содржај

Изворен канал @pythonotes · Post #241 · 5 мај

Можно ли в Python создавать бинарные файлы? Конечно можно. Для этого в Python есть следующие инструменты: ▫️ тип данных bytes и bytearray ▫️ открытие файла в режиме wb (write binary) или rb (read binary) ▫️ модуль struct Про модуль struct поговорим в первую очередь. Файл в формате JSON или Yaml внутри себя содержит разметку данных. Всегда можно определить где список начался а где закончился. Где записана строка а где словарь. То есть формат записи данных содержит в себе элементы разметки данных. В binary-файле данные не имеют визуальной разметки. Это просто байты, записанные один за другим. Правила записи и чтения находятся вне файла. Модуль struct как раз и помогает с организацией данных в таком файле с помощью определения форматов записи для разных частей файла. Модуль struct преобразует Python-объекты в массив байт, готовый к записи в файл и имеющий определённый вид. Для этого всегда следует указывать формат преобразования (или, как оно здесь называется - запаковки). Формат нужен для того, чтобы выделить достаточное количество байт для записи конкретного типа объекта. В последствии с помощью того же формата будет производиться чтение. При этом следует помнить что мы говорим о типах языка С а не Python. Именно формат определяет, что записано в конкретном месте файла, число, строка или что-то еще. Вот какие токены формата у нас есть. Помимо этого, первым символом можно указать порядок байтов. На разных системах одни и те же типы данных могут записываться по-разному, поэтому желательно указать конкретный способ из доступных. Если этого не сделать, то используется символ '@', то есть нативный для текущей системы. В строке формата мы пишем в каком порядке и какие типы собираемся преобразовать в байты. Запакуем в байты простое число, токен "i". >>> import struct >>> struct.pack('=i', 10) b'\n\x00\x00\x00' Теперь несколько float, при этом нужно передавать элементы не массивом а последовательностью аргументов. >>> struct.pack('=fff', 1.0, 2.5, 4.1) b'\x00\x00\x80?\x00\x00 @33\x83@' Вместо нескольких токенов можно просто указать нужное количество элементов перед одним токеном, результат будет тот же. >>> struct.pack('=3f', 1.0, 2.5, 4.1) b'\x00\x00\x80?\x00\x00 @33\x83@' Теперь запакуем разные типы >>> data = struct.pack('=fiQ', 1.0, 4, 100500) я запаковал типы float, int и unsigned long long (очень большой int, на 8 байт) b'\x00\x00\x80?\x04\x00\x00...' Распаковка происходит аналогично, но нужно указать тот же формат, который использовался при запаковке. Результат возвращается всегда в виде кортежа. >>> struct.unpack('=fiQ', data) (1.0, 4, 100500) Как видите, ничего страшного! #lib#basic

Hashtags

Резултати

Пронајдени 3 слични објави

Пребарај: #securitytheater

当前筛选 #securitytheater清除筛选
American Оbserver

@american_observer · Post #5447 · 22.03.2026 г., 21:59

Trump Turns Airport Chaos Into a Deportation Stage Trump is now officially turning TSA’s funding crisis into live theater: he says ICE agents will start deploying to airports on Monday, not because they’re trained to run X-ray machines, but because Democrats won’t sign his Homeland Security deal on immigration enforcement. ICE, he says, will “help our wonderful TSA Agents” and “do Security like no one has ever seen before,” including arrests of “all Illegal Immigrants … with heavy emphasis on those from Somalia.” In other words, your stalled spring break line is leverage — and a backdrop. Even his own former officials say the plan makes no operational sense. The bottlenecks are at X-ray belts, baggage screening and ID checks — jobs that require specialized training — while the administration admits ICE will mostly guard doors and glance at IDs. The point isn’t efficiency; it’s optics and pressure. Democrats are trying to pay TSA separately while forcing basic constraints on ICE raids after federal agents killed two protesters in Minneapolis. Republicans stapled TSA paychecks to full ICE and CBP funding with minimal new rules — and now the White House is dangling “untrained ICE at your gate” as the price of saying no. So the picture at the terminal is simple: TSA officers working without pay for more than a month, walking off the job in growing numbers, security lines stretching for hours — and a president who would rather drop deportation cops into that mess than tell his own party to pass a clean bill to pay them. If you’re flying tomorrow, the message from Washington is clear: welcome to security theater, season two — this time, the show is about scaring Congress, and you’re the unpaid extra. #Trump#ICE#TSA#shutdown#airports#immigration#DHS#USA#securityTheater 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5440 · 22.03.2026 г., 00:59

Trump Turns TSA Meltdown Into an ICE Photo Op Trump just found a way to turn a payless TSA crisis into a campaign stunt: threaten to flood airport checkpoints with ICE agents unless Democrats sign his Homeland Security funding deal. Spring break traffic is colliding with a month-long DHS shutdown that’s forced 50,000 TSA officers to work without pay, driven resignations and sick-outs, and already closed lanes at major hubs — and his answer isn’t “pay them,” it’s “bring in deportation cops with a special focus on Somalis.” Democrats are trying to fund TSA separately and tie new money for ICE and CBP to basic guardrails — warrants before home raids, no masks, cameras on, no grabbing people in hospitals and schools — after federal agents killed protesters in Minneapolis. Republicans have stapled TSA paychecks to full ICE funding without reforms, then act shocked when queues hit three hours. Trump’s “solution” is to use that pain as leverage: either fund the enforcement machine on his terms, or watch it move from the border into the departure hall. Former ICE officials are blunt: this kind of dragnet at airports would mostly scoop up long‑time residents with no criminal record, because that’s who actually flies, while doing almost nothing for real security. But that’s the point. The message isn’t “we’ll keep you safe,” it’s “we’ll turn your delayed vacation into a live deportation show unless Democrats cave.” For travelers stuck in unpaid-screeners’ lines, the new choice is charming: miss your flight — or clear security and risk having an ICE agent decide you’re the next headline. #Trump#ICE#TSA#shutdown#airports#immigration#DHS#USA#securityTheater 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5449 · 23.03.2026 г., 01:59

Oil at Monday’s Open: Trading a 48‑Hour Threat Clock Oil just stopped pretending this is about “volatility” and started trading directly on Trump’s ego and Iran’s survival instinct. At Friday’s close, Brent was at 112.19 dollars — a near four‑year high — before the president slapped a 48‑hour ultimatum on Tehran: fully reopen Hormuz “without threat” or watch the U.S. “obliterate” your power plants. Just the day before he was musing about “winding down” the war; now markets get a countdown clock to see whether he takes out the grid that keeps 100‑plus Iranian gas power stations feeding cities and industry. Tehran’s answer is simple: hit our power, and we hit yours — or at least the stuff that keeps your friends’ cities habitable. Iran is openly threatening U.S.‑linked energy and desalination plants across the Gulf, after already striking ports and refineries in Saudi Arabia, Kuwait, Bahrain, the UAE and Qatar; four days of global supply — roughly 440 million barrels — have already vanished during 22 days of quasi‑closure in Hormuz. Analysts aren’t talking about price “noise” anymore: one calls Trump’s move a “48‑hour ticking time bomb of elevated uncertainty”; another says the real story isn’t Iran caving but “scorched earth for Gulf infrastructure.” The real nightmare isn’t just crude; it’s water. Iran has so far held back from hitting the big desalination plants in Saudi Arabia and the UAE — the ones that keep entire Gulf metros alive — but Western risk assessments are stark: sustained attacks could leave some cities unlivable in weeks, triggering mass evacuations and cascading power failures. Fatih Birol at the IEA says fixing Middle East Gulf supply could take up to six months even without that scenario. Meanwhile the Trump team is floating plans to blockade or occupy Iran’s Kharg Island to “force open” Hormuz, as if physically sitting on another country’s export terminal has no blowback risk in a region already pricing 112‑dollar Brent, double‑digit weekly gains in crude and the widest WTI–Brent spread in 11 years. So Monday’s trade isn’t about “whether oil ticks up”; it’s about whether the White House walks back its own threat, or lets the deadline run and turns a shipping crisis into a test of who’s willing to bomb water plants first. Traders will tell you this is uncertainty; civilians in the Gulf might call it something else: a market run by men who treat your tap, your light switch and your plane ticket as expendable props in a pricing experiment. #oil#IranWar#Trump#Hormuz#energy#desalination#Gulf#markets#inflation#recession#securityTheater 📱American Оbserver - Stay up to date on all important events 🇺🇸