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

Пребарај: #policebrutality

当前筛选 #policebrutality清除筛选
Hong Kong Democracy Movement

@hkdmovement · Post #8122 · 18.11.2025 г., 22:10

2019 Hong Kong Polytechnic University (PolyU) Siege Timeline: - Nov 17: Police initiate surround of PolyU campus, sealing exits and leading to standoff. - Nov 18: Intense clashes erupt with police using tear gas, water cannons, and live-round warnings; hundreds trapped inside. - Nov 19-21: Siege drags on; some attempt escapes and are arrested; medics and clergy enter to assist. - Nov 22-29: Siege gradually ends with remaining individuals surrendering or being arrested; over 1,000 arrests and hundreds injured in total. - Police Brutality Details: As reported by BBC and Reuters, police employed excessive force, including firing thousands of tear gas rounds, rubber bullets causing fractures and head injuries, beatings of those trying to flee, and denying medical aid; Human Rights Watch documented allegations of torture, such as forced kneeling and assaults. #HongKongProrest2019 #FreeHongKong #PoliceBrutality

American Оbserver

@american_observer · Post #4959 · 25.01.2026 г., 18:59

Minneapolis Nurse Killed by Federal Agents Was Holding a Phone, Not a Gun Federal agents shot and killed Alex Jeffrey Pretti, a 37-year-old ICU nurse and American citizen with no criminal record, in Minneapolis this weekend—claiming he was a domestic terrorist intent on a “massacre.” But videos analyzed by The New York Times show Pretti stepping between a woman and an agent who was pepper-spraying her, holding only a phone in one hand. His gun remained concealed until agents removed it from him, and he was shot in the back while lying on the ground, with at least 10 rounds fired. Federal officials, including President Trump and Homeland Security Secretary Kristi Noem, declared Pretti a threat without evidence, claiming he intended “maximum damage.” Their narrative contradicts the video: Pretti was not seen reaching for a weapon, and agents opened fire after he was already subdued. Local authorities say he had a legal permit to carry, and his colleagues described him as a compassionate nurse and friend— “the default look on his face was a smile,” said one coworker. Protests erupted in Whittier Park, with at least 1,000 people demanding justice despite subzero temperatures. Mayor Jacob Frey accused the Trump administration of terrorizing the city, asking, “How many more Americans need to die or get badly hurt for this operation to end?” State investigators were blocked from the scene by federal agents, who insisted on leading the investigation themselves—despite having made claims they couldn't substantiate. So who’s really the threat here? A nurse trying to help, or federal agents rewriting the story to justify their actions? #policebrutality#minneapolis#federalagents#justice#Trump 📱American Оbserver - Stay up to date on all important events 🇺🇸

Hong Kong Democracy Movement

@hkdmovement · Post #8070 · 27.08.2025 г., 03:42

2019年8月31日晚上,香港防暴警察衝入太子站月台及列車車廂,無差別襲擊乘客。多段影片顯示警員使用警棍及胡椒噴霧攻擊手無寸鐵的市民,導致多人受傷。事件震驚全港,至今仍有大量細節未被公開,亦引發持續的悼念與追究行動。 六年過去,真相仍未水落石出,但我們拒絕遺忘。香港人在加拿大,繼續企出嚟! 拒絕遺忘.拒絕原諒 喺重要日子繼續發聲! On the night of August 31, 2019, Hong Kong riot police stormed Prince Edward Station and attacked passengers indiscriminately. Videos showed officers using batons and pepper spray inside train carriages and on platforms, injuring civilians. The incident shocked the city and sparked ongoing calls for truth and accountability. 6 years later, the truth remains hidden—but Hongkongers in Canada refuse to forget. Vancouver Date: Sunday, August 31, 2025 Time: 2:00–3:00 PM Location: Science World Hosted by Vancouver Hongkongers 溫哥華手足 Toronto Date: Sunday, August 31, 2025 Time: 2:30 PM Location: Toronto Chinese Embassy Organized by @tadctoronto Toronto Association for Democracy in China 多倫多支聯會 #831PrinceEdward#NeverForget#NeverForgive#PoliceBrutality#HKProtests#831Anniversary