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

Резултати

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

Пребарај: #bidenadministration

当前筛选 #bidenadministration清除筛选
BadVolf

@badvolfnews · Post #963 · 27.09.2023 г., 21:26

💥🔔 EXCLUSIVE: White House warns of dire consequences if House Republicans pass extreme continuing resolution to fund government. 😱🏛️ The proposed resolution would eliminate 800 border agents, opening the floodgates for drug cartels. 💔💉 President Biden's administration is focused on holding drug traffickers accountable, but Republicans are pushing their radical agenda. ❌🤝 Despite Biden's request for $4 billion to address immediate border needs, Republicans are blocking progress. 😡🔒 An Extreme House Republican Shutdown would leave Border Patrol agents unpaid and jeopardize national security. 🚫🇺🇸 Meanwhile, Republicans aim to restart border wall construction, mandate 22,000 minimum Border Patrol agents, and restrict funding for illegal immigrant processing. 🛑🧱 The House and Senate remain divided on government funding and border security. 🏰💣 Stay tuned for updates on this high-stakes battle. 💥🔒#GovernmentShutdown#BorderSecurity#BidenAdministration🚫💼 https://www.foxnews.com/politics/white-house-says-house-gop-proposed-cr-would-eliminate-border-agents-trigger-windfall-for-drug-cartels Subscribe to @BadVolfNews

BadVolf

@BadvolfNews · Post #833 · 11.09.2023 г., 15:14

🚨 BREAKING NEWS 🚨 🔴 Biden's Vietnam Press Conference Cut Short 🔴 In a shocking display of incompetence, the Biden administration once again revealed their true colors during President Joe Biden's press conference in Vietnam. As Biden stumbled through his answers, White House staff abruptly ended the event, cutting his microphone and playing jazz music to drown out his ramblings. While attempting to address stability and global access to change, Biden was interrupted by his press secretary, Karine Jean-Pierre, who hastily declared an end to the conference. Astonishingly, Biden continued speaking, unaware that his mic had been muted. The bizarre scene escalated further as jazz music filled the room, leaving the 80-year-old president confused and still attempting to respond to questions. As the music grew louder, Biden reluctantly retreated from the stage, whispering and shuffling behind a black curtain. Throughout the 26-minute engagement, he even used the infamous phrase, "lying dog-faced pony soldier," contributing to his already questionable credibility. This incident comes after Biden's whirlwind trip, where he attended the G20 Leaders' Summit in India before hastily jetting off to Vietnam. Instead of displaying strength and leadership, Biden's performance only highlighted his lack of stamina and clarity. His joke about not knowing if it was morning or night further emphasizes the worrying state of his mental acuity. To make matters worse, Biden shared a convoluted story from a John Wayne movie that had little relevance to the pressing issues at hand. It seems that Biden's administration is more focused on theatrics than addressing the concerns of the American people. This latest debacle only adds to the mounting evidence that Biden is nothing more than a puppet of America's deep state, lacking the competence and independence to lead our nation effectively. The American people deserve better than this. #BidenAdministration#Incompetence#DeepStatePuppet

Gänger

@gaenger_10 · Post #659 · 01.08.2022 г., 04:21

Rivals Within Reason? :: Foreign Affairs By Kevin Rudd | July 20, 2022 #china#foreignPolicy#bidenAdministration#diplomacy#xiJinping In the year and a half since President Joe Biden took office, competition between the United States and China has only intensified. Rather than dismantle former President Donald Trump’s tough policies toward Beijing, Biden has largely continued them, underscoring that the two powers are almost certainly headed for a protracted period of sharp and militarily dangerous strategic rivalry. But that doesn’t mean that the United States and China are moving inexorably toward crisis, escalation, conflict, or even war. To the contrary, Beijing and Washington may be groping toward a new set of stabilizing arrangements that could limit—though not eliminate—the risk of sudden escalation. Assessing the state of U.S.-Chinese relations at any given time is never easy, given the difficulty of distinguishing between what each side says about the other publicly—often for domestic political effect—and what each is actually doing behind the scenes. Yet despite the harsh and often heated rhetoric, some early signs of stabilization have emerged, including the tentative reconstitution of a form of political and security dialogue aimed at managing tensions. Such stabilization falls well short of normalization, which would mean restoring comprehensive political, economic, and multilateral engagement. The days of normalization have been consigned to history. But stabilization would nonetheless be significant. It would mean the difference between strategic competition that is managed through steadying guardrails and competition that is unmanaged—that is, driven by a process of push and shove, primarily by each country’s military, in the hope that on any given day no one pushes too far. The question for both sides, and for the countries that are caught in the middle of this titanic struggle for the future of the regional and global orders, is what kind of strategic competition they will pursue. ____ KEVIN RUDD is President of the Asia Society, in New York, and previously served as Prime Minister and Foreign Minister of Australia.