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

Резултати

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

Пребарај: #judiciary

当前筛选 #judiciary清除筛选
Indian Development News 🇮🇳

@developmentnewsindia · Post #44104 · 27.04.2026 г., 05:56

Calcutta HC (Single Bench) overturned the Election Commission order to Ban Bikes in Poll Bound Areas from 48 hrs to just 12 hrs. This Ban was imposed in Phase I but overturned on April 24. Now Election Commission has moved to Division Bench of Calcutta HC to appeal against this order. #Judiciary

Hashtags

Indian Development News 🇮🇳

@developmentnewsindia · Post #44013 · 24.04.2026 г., 07:03

Election Duty Officers move SC saying they themselves are not on West Bengal SIR List Se Adv MR Shamshad: These are 65 petitioners who are on Election duty. Their duty orders mention EPIC numbers. Now those numbers are deleted. Now the persons conducting elections cannot vote! This is on the face Arbitrary. Many not given reasons. CJI: Make these arguments before the Appellate Tribunal. Let the tribunal look into it. Justice Bagchi: Appropriate orders will be passed by the Tribunal. This election yes perhaps they can't vote. The more valuable right to remain on the Rolls shall be preserved. #Judiciary

Hashtags

Indian Development News 🇮🇳

@developmentnewsindia · Post #43911 · 22.04.2026 г., 09:12

Center says the SC "Government doesn't want to control the temple at all" Center also conveyed SC directly that it is not competent to decide on matters of belief and practices of Religious Denominations and should restrict itself to matters of Constitution. #Judiciary

Hashtags

Indian Development News 🇮🇳

@developmentnewsindia · Post #43409 · 09.04.2026 г., 16:06

Center to Supreme Court Decriminalising adultery and Same-Sex consensual relationships were based on a "subjective" interpretation of constitutional morality and should be considered "not a good law." Solicitor General Tushar Mehta – " Constitutional morality" is a vague concept and cannot serve as a standalone test for Judicial Review of laws. He said in a democracy, laws reflect the will of the majority, raising questions about how morality should be defined in that context. #Judiciary

Hashtags

AI & Law

@ai_and_law · Post #680 · 16.10.2025 г., 07:04

🇺🇸New York Courts Establish Formal AI Use Policy for Judges and Staff New York Unified Court System has issued its first official policy governing the use of generative AI by judges, justices, and court personnel. The interim rules limit the use of AI to approved tools and mandate training for all users. The policy explicitly prohibits entering confidential or privileged information into any generative AI tool that is not operated as a private model under the control of the court system. The document emphasizes that judges and staff remain fully responsible for their work product and must ensure that AI output does not reflect harmful bias, stereotypes, or prejudice. “While AI can enhance productivity, it must be utilized with great care,” said Chief Administrative Judge Joseph Zayas. “It is not designed to replace human judgment, discretion, or decision-making.” #AI#AIethics#Judiciary#AIGovernance

Hong Kong Democracy Movement

@hkdmovement · Post #7992 · 13.05.2025 г., 03:46

#HongKong’s top court plans to appoint New Zealand judge William Young, sparking protests in New Zealand. Critics accuse him of endorsing Hong Kong’s #CCP-controlled judiciary, which has jailed thousands of #politicalprisoners facing unfair trials. Protesters gathered outside Young’s office, demanding he reconsider. When Hong Kong journalists asked for comment, Young replied: “I would not accept appointment unless satisfied it was proper. Apart from that, I have nothing to add and won’t debate my appointment.” His decision raises concerns about legitimizing #Beijing’s judicial control. #Judiciary#CourtOfFinalAppeal#CCPControl #香港#終審法院 計劃任命新西蘭法官楊威廉 ,在紐西蘭引發抗議。批評者指責他為中共控制的司法制度背書 ,該制度已讓數千名 #政治犯 遭受不公正審判。 抗議者在楊威廉的辦公室外集會,要求他重新考慮。香港記者向他提問,他回應: 「除非確信適當,否則不會接受任命。此外,我沒有新內容可補充,也不會討論此事。」 #中共控制