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

Резултати

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

Пребарај: #fantom

当前筛选 #fantom清除筛选
Algebra DEX Engine

@cryptoalgebra · Post #2012 · 18.09.2024 г., 13:00

🦄 V3 DEXes featuring concentrated liquidity & dynamic fees powered by Algebra are taking over! 💪 Shoutout to SuperSonic DEX, the advanced DEX built natively on Sonic Labs (fka #Fantom) with Algebra's groundbreaking V3 AMM. 🤖🔧 ⚡️ Get ready for up to 95% efficiency soon on the Sonic Network!

Hashtags

🎉🎄НОВОГОДНИЕ УТРЕННИКИ В ПОДРАЗДЕЛЕНИИ СЛУЖБЫ ПСИХОЛОГО-ПЕДАГОГИЧЕСКОГО И МЕДИКО-СОЦИАЛЬНОГО СОПРОВОЖДЕНИЯ! 🎉🎄 Хотим поделиться с вами замечательной новостью! В нашем подразделении службы психолого-педагогического и медико-социального сопровождения началась серия ярких и волшебных новогодних утренников! 🎄🎁 Наши талантливые педагоги показали театральную зарисовку «Сказочный хоровод». Дети получили море положительных эмоций и незабываемые впечатления. Атмосфера праздника, радости и веселья царила на протяжении всего мероприятия. Украшенный зал, яркие костюмы, сверкающая ёлка, Дед Мороз со Снегурочкой и, конечно же, долгожданные подарки – всё это создало ощущение настоящего новогоднего чуда. 🌟🎉 Выражаем благодарность Установочному центру Fantom, который оказал благотворительную помощь в приобретении новогодних подарков для детей. #fantom https://vk.com/fantom_tmb

Hashtags

JJ.ai (NFA)🪽

@jsmjsmxyz · Post #1201 · 23.03.2023 г., 19:51

The #FantomHackathon Q1 2023 was a huge success! 🎉 Winners include familiar faces, plus introduce many new projects to the #Fantom ecosystem 🏆⤵️ 🥇 $10k @EstforKingdom (#GameFi) 🥈 $7.5k Rezy (recycling) 🥉 $5k Hazed (privacy) Congrats all! Full list: https://fantomq12023.devpost.com/project-gallery https://twitter.com/FantomFDN/status/1638988754659713024?s=20

Nomis | Onchain Reputation Protocol

@nomis_protocol · Post #538 · 14.11.2024 г., 14:03

✉️ Nomis x EYWA Protocol: Real utilities for the real DeFi guys Meet EYWA Reputation Score: Prove Your Cross-Сhain Activity and Be Eligible For the Airdrop SCORE YOUR WALLET TO START FARMING We've partnered with EYWA, the cross-chain trading powerhouse that aggregates Curve Finance pools, to ensure airdrops go where they're earned—right to real degens like YOU 🫵 🖥HOW TO GET STARTED: 1. Visit THE SCORE PAGE to get your Score 2. Go to THE SWAP PAGE 3. Make cross-chain swaps using EYWA and farm extra points 4. Check your total points HERE 5. Wait for the airdrop date to be revealed! 🔝 In the meantime, make more swaps, increase your EYWA Score, and farm points! ➡️HOW TO BOOST YOUR SCORE: Make swaps across #Ethereum, #Optimism, #BSC, #Polygon, #Fantom, #Arbitrum, and #Avalanche The higher swaps volume, the higher your Score! ➡️HOW TO GET MORE POINTS: The higher your Score, the bigger rewards! 🚨 EXTRA REWARDS TIPS: • Score < 60: Earn 15 points per Score • Score 60-80: Earn 18 points per Score • Score 80+: Earn 20 points per Score (max 2000 points) It seems like we've covered all the questions 🧐 Missed anything? Reach out in the comments! And now... Get in, Get yours, LFG⚡️

Venture Village Wall 🦄

@venturevillagewall · Post #3814 · 07.01.2025 г., 19:00

Bitcoin Caps and Central Banks 🌍 *Salvador Nasralla*, Honduras' leading presidential candidate, recently wore a Bitcoin cap in an interview. 💬 *Michael Saylor* claims Bitcoin at $100,000 is still a 90% discount. 📉 In a dramatic case on Chinese Twitter, a recent fight between a BTC whale and founder of Solv Protocol led to the creation of the *ZachAI* ($ZAI) token, with the whale dumping on followers post-launch. 🇨🇿 Czech Central Bank is considering BTC as a reserve asset. 🔥 50 million USDC burned at USDC Treasury. 🏗️ President-elect Trump announces $20 billion investment in new data centers in the U.S. #Bitcoin#BTC#Crypto#USDC#Solv#AI#ZAI#CzechRepublic#Honduras#Investment#Trump#DataCenters#Curve#Treasury#Ethereum#Blockchain#CryptoWhale#Fantom#Sonic

SIGNAL

@finsignal · Post #3295 · 22.06.2024 г., 07:33

📰 CRYPTO NEWS 🆕️The founder and CEO of #CryptoQuant stated that compared to the previous cyclical peak, the fundamental elements of the bitcoin network can maintain a market value three times higher than the current one. He considers it "possible" to "keep" the bitcoin price at $265,000. 🆕️As part of the presale, #WATER raised $41 million. Which also makes WATER the largest Memecoin pre-sale to date, with over 26,000 wallets participating. The team has regained control of its account in X. 🆕️50 Cent's #Twitter account was hacked in order to promote the Solana Meme Coin. 🆕️Internet Computer will launch the #ICP Hub Accelerator Program 2024, which aims to help early blockchain projects transform their concepts into market solutions, create a strong blockchain innovation ecosystem and promote technological progress in the ICP community. 🔹 21 million #LINKS ($295 million) of non-convertible Chainlink contracts have been unblocked today. 🆕️DAO Osmosis supports a commission-free bridge for transferring bitcoin to the #Cosmos ecosystem. 🆕️Scroll ZKP presents "Scroll Sessions", a loyalty program to reward the Scroll Marks community for their participation and involvement in the #Scroll ecosystem. 🆕️Arbitrum introduces the "Layer Leap", a single-stage bridge from L1 to L3 for the #Orbit ecosystem. 🆕️#Reef plans to launch a new product on June 26. ‼️ Dogwifhat Whales dropped #WIF by 16 million in a week. 🆕️#Fantom has released #Sonic's third management offering, which includes an annual token destruction mechanism, as well as the launch of Sonic Spark and Sonic University. 🆕️#Bluefin announces integration with Wormhole Connect. The Wormhole community will participate in the future release of Bluefin tokens. 🆕️#StacksNakamoto has announced the completion of 90% of the work on the project and is preparing for the official launch on July 15. The Nakamoto Stacks update should increase the transaction speed to 5-10 seconds, which is about 100 times faster than the current speed. ➡️ This is a significant event for the Stacks project and the Bitcoin ecosystem, will improve the speed, overall efficiency and scalability of Layer2 on #Bitcoin, promising faster and more efficient transactions for users.