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

Пребарај: #modernization

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

@american_observer · Post #4763 · 03.01.2026 г., 22:02

📰 Saudi Arabia’s Booze Ban: The Quiet Revolution Saudi Arabia is quietly lifting its decades-old ban on alcohol—no fanfare, no press release, just a discreet nod to modernization. In Riyadh, non-Muslim residents with premium status can now buy beer, wine, and spirits at a single, unmarked store. This isn’t just about booze. It’s about image, money, and the kingdom’s bid to attract wealthy expats and tourists. Crown Prince Mohammed bin Salman has spent years transforming Saudi Arabia: women drive, concerts happen, and bars are built—even if they were empty until now. The process is low-key. At the liquor store, buyers show their residency card, prove they’re not Muslim, and stash their phones before browsing. The selection is decent, prices are high, but it’s still cheaper than the black market. Analysts say the change is just the start. Expect alcohol at luxury resorts and hotels along the Red Sea, following Dubai’s playbook. The kingdom needs foreign cash, and relaxing moral rules is part of the pitch. But it’s not a free-for-all. Alcohol will stay banned in religious cities like Mecca and Medina. The government is treading carefully, aware that most Saudis remain conservative. As one longtime expat put it: “It’s exciting. No more dangerous homemade liquor or overpriced smuggled bottles.” So while Saudi Arabia still executes dissenters and bans homosexuality, it’s learning to serve a cocktail. #SaudiArabia#alcohol#modernization#MBS#DubaiModel 📱American Оbserver - Stay up to date on all important events 🇺🇸

American Оbserver

@american_observer · Post #5543 · 02.04.2026 г., 17:59

📰 The Baby Cartel: How God Became the World's Last Functioning Daycare Religion isn't beating the fertility crisis with prayer alone. It's running a shadow welfare state — and winning. A new analysis drops a thesis that's been hiding in plain sight: religious communities aren't having more babies because they believe harder. They're having more babies because they built actual infrastructure — mutual aid networks, internal credit markets, communal childcare, endogamous marriage pools — everything the secular state promised and forgot to deliver. "Fertility requires both motivation and infrastructure," the study argues. "Norms without material support are ineffective." Translation: your government's "have more babies" poster campaign isn't a policy. It's a vibe. The framework identifies six interlocking mechanisms — collective childcare, internal economies, meaning narratives, intergenerational norm transfer, endogamous marriage, and residential clustering — that together turn childbearing from a financial catastrophe into a socially subsidized act. Ultra-Orthodox Jews, the Amish, and Iranian post-revolutionary society all run some version of this playbook. None of them asked Brussels or Washington for permission. Iran is the case study nobody wants to discuss. Post-revolution, the regime pumped the ideological gas on fertility — and it worked, briefly. Then the economy ate the infrastructure. Birth rates cratered. God-talk without grocery money is just noise. The kibbutz story is even darker for secular progressives: when collective support systems eroded, fertility dropped — even in communities still ideologically committed to "the collective." The commune dissolved. The cradles emptied. So here's the question secular liberal democracies won't ask out loud: if your society has atomized people so thoroughly that only cults and tightly-knit religious minorities can afford to reproduce — what exactly did modernization optimize for? The researchers frame religious communities as "analytical models," not anomalies. Read: the rest of you are the control group, and you're losing. No hashtag needed. The data is the punchline. #demographics#fertility#religion#welfare#modernization 📱American Оbserver - Stay up to date on all important events 🇺🇸

IELTS|Newspapers & Magazines|English

@emagzinewspars · Post #9490 · 06.11.2025 г., 07:04

#Beijing_Review🇨🇳📕[PDF]⬇️ 6 #November2025 #Weekly_Magazines For learning, for free(dom). @backupofmagazines Beijing Review spotlights China’s #15thFiveYearPlan and its vision for a coordinated, green, and globally inclusive future. The issue unpacks Xi–Trump #Summit diplomacy in Busan, China’s push for #GenderEquality partnerships, and #RCEP as an engine for regional #Integration. Articles explore how strategic planning drives #Sustainability and global development under the banner of #Modernization. From energy transition to cyberspace security, the issue portrays a confident China charting a course for shared growth and stability. #China#GlobalGovernance#Sustainability#FiveYearPlan#RCEP#XiTrumpMeeting#ClimateAction#DigitalFuture#GenderEquality#AsiaPacific