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 слични објави

Пребарај: #criminel

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

@american_observer · Post #5532 · 01.04.2026 г., 14:59

🔤🔤🔤🔤2️⃣ The Spanish prime minister, Pedro Sánchez, wrote on X: “It is an asymmetric measure that would not apply to Israelis who committed the same crimes. Same crime, different punishment. That is not justice. It is a step closer to apartheid.” Germany, traditionally one of Israel’s closest allies in Europe, said it could not endorse the law. “The German government views the law passed yesterday with great concern,” the government spokesperson Stefan Kornelius said in a statement. “The rejection of the death penalty is a fundamental principle of German policy,” Kornelius said, adding: “Such a law would likely apply exclusively to Palestinians in the Palestinian territories.” The legislation makes the death penalty the default punishment for Palestinians in the Israeli-occupied West Bank found guilty of intentionally carrying out deadly attacks deemed acts of terrorism by a military court. According to the bill, those sentenced to death would be held in a separate facility with no visits except from authorised personnel, and legal consultations conducted only by video link. Executions would be carried out within 90 days of sentencing. Israel has rarely used the death penalty, applying it only in exceptional cases. The Nazi war criminal Adolf Eichmann was the last person to be executed, in 1962. The national security minister, Itamar Ben-Gvir, one of the bill’s strongest backers, has repeatedly worn a noose-shaped lapel pin, symbolising executions under the proposal. A security committee made some amendments to the bill, which last week passed its first vote. Israel’s public broadcaster, Kan, reported that executions would be carried out by hanging. The measure would allow courts to impose the death penalty without a request from prosecutors and without requiring unanimity, instead permitting a simple majority decision. Military courts in the occupied West Bank would also be empowered to hand down death sentences, with the defence minister able to submit an opinion. Adam Coogle, the deputy Middle East director of Human Rights Watch, said: “Israeli officials argue that imposing the death penalty is about security, but in reality it entrenches discrimination and a two-tiered system of justice, both hallmarks of apartheid. “The death penalty is irreversible and cruel. Combined with its severe restrictions on appeals and its 90-day execution timeline, this bill aims to kill Palestinian detainees faster and with less scrutiny.” Shaista Aziz, Oxfam’s campaign engagement lead, said: “This bill is another horrifying act of violence. Israel is violating international law. This new law effectively ensures that the death penalty in Israel will apply only to Palestinians, even as the illegal Israeli occupation has lately seen a surge in the coordinated attacks and executions of Palestinians by settler militias and military. “Israel holds more than 9,000 Palestinians in its jails – many unlawfully and subject to inhumane conditions, starvation and torture as state policy.” In Israel, the law is already facing legal challenges. Several Israeli human rights groups and three members of parliament filed petitions to the supreme court seeking to overturn it. The Association for Civil Rights in Israel said the law created “two parallel tracks, both designed to apply to Palestinians” and should be struck down on constitutional grounds. #israel#palestinians#court#criminel#war 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5531 · 01.04.2026 г., 13:59

Israel: The Dangerous Turn To Death Penalty 🔤🔤🔤🔤1️⃣ A new Israeli law that would allow the execution of Palestinians convicted on terror charges for deadly attacks, but not Jewish extremists accused of similar crimes, would constitute a war crime if enacted, according to one of the UN’s most senior human rights officials. Speaking amid mounting international condemnation of the bill, the UN’s high commissioner for human rights, Volker Türk, described the law as “patently inconsistent with Israel’s international law obligations, including in relation to the right to life”. He added that it “raises serious concerns about due process violations, is deeply discriminatory, and must be promptly repealed”. “Its application in a discriminatory manner would constitute an additional, particularly egregious violation of international law. Its application to residents of the occupied Palestinian territory would constitute a war crime,” Türk said. The legislation, passed on Monday by the Israeli Knesset, has faced a wave of criticism, including from European leaders and human rights groups. “The death penalty bill in Israel is very concerning to us in the EU,” the EU spokesperson Anouar El Anouni said in Brussels. “This is a clear step backwards – the introduction of the death penalty, together with the discriminatory nature of the law.” #israel#palestinians#court#criminel#war 📱American Оbserver - Stay up to date on all important events 🇺🇸