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

Резултати

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

Пребарај: #dodik

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

@american_observer · Post #5691 · 23.04.2026 г., 14:00

The War Between the EU and the US Is Real Than Never The EU risks a confrontation with Trump after it sought to stall the awarding of a lucrative Balkans pipeline contract to a company fronted by his personal lawyer, documents seen by the Guardian show. Brussels has clashed with Trump over trade, Ukraine and military spending, but the intervention in the Southern Interconnection pipeline project appears to mark the first time it has challenged a commercial venture by those close to the president. The pipeline will run through Bosnia and Herzegovina. Under what Bosnian sources say have been months of pressure from US officials, its leaders have been moving quickly to award the contract to a previously little-known company based in Wyoming. AAFS Infrastructure and Energy was incorporated in November last year and has not disclosed its owners. It is fronted by two leading members of Trump’s campaign to overturn his 2020 election defeat : Jesse Binnall, a lawyer who defended him against allegations of inciting the Capitol riots after his defeat, and Joe Flynn, the brother of the president’s former national security adviser. Despite lacking any apparent track record, AAFS is planning to invest $1.5bn in the pipeline and other Bosnian infrastructure projects, its local representative has said. In March, lawmakers approved legislation that Transparency International said would set a “dangerous precedent” by stipulating that the contract must go to AAFS without a tender. Days later, Brussels’ representative in Sarajevo delivered a private warning to Bosnia’s leaders that they were jeopardising the country’s hopes of joining the EU. In a letter sent on 13 April, obtained by the Bosnian investigative outlet istraga.ba and seen by the Guardian, the EU official Luigi Soreca wrote that, under an energy agreement between Bosnia and Brussels, it was “crucial that draft laws are thoroughly coordinated” with the EU. Soreca said Brussels should have a say in the pipeline legislation. “In this way, Bosnia and Herzegovina can continue to progress on its European path and avoid missing out on opportunities for further integration, as well as financial opportunities,” he said. Binnall has said the pipeline is a “priority for the Trump administration”. Asked about the EU’s intervention, he said: “AAFS will never lose sight of what truly matters in this project: delivering energy security and fostering economic development for the people of Bosnia and Herzegovina. We are committed to working closely with all relevant authorities to develop the infrastructure needed to make this vision a reality.” By connecting Bosnia to a liquefied natural gas terminal off the Croatian coast, the pipeline would allow US gas to reach a country that depends on Russia for its entire supply. After Putin launched Russia’s full-scale invasion of Ukraine in 2022, Brussels set a deadline for EU members – plus aspiring members, such as Bosnia – to stop buying Russian gas by 2028. Nonetheless, Brussels faces the prospect of a crucial new piece of Europe’s energy chessboard falling under the control of not just a US company, but one personally connected to an antagonistic president. Binnall and Flynn are not the only ones from Trump’s circle to have shown an interest in Bosnia. Joe Flynn’s brother Michael – a former US intelligence chief whose conviction for lying to the FBI about his dealings with Russia was quashed by a pardon from Trump in 2020 – has been lobbying for the head of Bosnia’s Serb nationalist faction. The lobbying campaign succeeded in October in having US sanctions lifted from Milorad Dodik, the Bosnian Serb leader who has been undermining the 1995 peace accord that ended a three-year war in which more than 100,000 people were killed. In April, Donald Trump Jr, who runs the family business empire, visited Sarajevo. Although neither he nor Michael Flynn appear to be directly involved in the pipeline project, Dodik has thrown his support behind it. #trump#dodik#gaz 📱American Оbserver - Stay up to date on all important events🇺🇸

Tutto Elezioni

@tuttoelezioni · Post #1390 · 23.11.2025 г., 10:02

#BosniaErzegovina🇧🇦 #RepublikaSrpska #Presidenziali 🗒Breve panoramica della Republika Srpska La Repubblica Serba (Republika Srpska) è una delle due entità che compongono la Bosnia ed Erzegovina, insieme alla Federazione di Bosnia ed Erzegovina. Nata dagli Accordi di Dayton del 1995, è l’area in cui è maggioritaria la popolazione serba di Bosnia (nella Federazione si concentra la popolazione croata e bosgnacca). Il centro amministrativo della Repubblica è Banja Luka. La Republika Srpska è politicamente dominata da partiti nazional-conservatori serbi, in particolare l’Alleanza dei Socialdemocratici Indipendenti (#SNSD|Nazionalisti serbi russofili) di Milorad #Dodik, e i rapporti con il governo di Sarajevo sono spesso tesi, soprattutto sul tema dei poteri delle istituzioni centrali e dell’Alto Rappresentante. Le elezioni nell’entità hanno sempre un impatto significativo sull’equilibrio complessivo della Bosnia ed Erzegovina. ❓Come si vota? Per le elezioni presidenziali, è previsto un unico turno ed è eletto Presidente il candidato che ottiene il maggior numero di voti. Il mandato dura 4 anni. @TuttoElezioni