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

Резултати

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

Пребарај: #november2022

当前筛选 #november2022清除筛选
The Open Platform

@topco · Post #20 · 28.12.2022 г., 08:38

DeFi: key November headlines: - Multiple exchanges and lenders suspended withdrawals following the turmoil surrounding FTX: crypto lenders Genesis (source), SALT (source), BlockFi (source), exchange AAX (source) - Aave and Compound froze market and capped loans to mitigate risks after an attempted short squeeze that happened in November (source) - Value locked in DeFi is at its lowest point since March 2021: TVL has dropped to $43 billion losing more than $22 billion in 36 days - Solana saw more than $700M in value wiped out after FTX collapse: lending and borrowing platform Solend took the biggest hit both in percentage and value terms, losing $250 million (89%) of its value (source) - Ether staking yields are at ATH: since the Merge the yields jumped up to 25% (source) - Yahoo Finance released a new industry report: DeFi is expected to reach $125.1 billion by 2028, rising at 42.8% CAGR (source) - JPMorgan executes first DeFi trade on a public blockchain: Polygon and modified Aave were used to issue a tokenized Singapore Dollar (TSD) deposit and trade it for the Japanese Yen (source) #DeFi#November2022#trends

The Open Platform

@topco · Post #24 · 30.12.2022 г., 09:04

Metaverse: November headlines: - Meta is laying 11,000 employees or 13% of its workforce after its aggressive hiring during the pandemic to maintain its momentum on Metaverse, meanwhile Metaverse remains a fuzzy concept and MAU targets are not met - Meta had expected 500,000 active monthly users on its VR platform, Horizon Worlds (which is accessed by VR headsets), by the end of this year; but the current figure is fewer than 200,000 (source) - Animoca Brands announces $2 billion Metaverse fund, the fund's focus "will be everything on digital property rights" (source) - The tiny island nation of Tuvalu recently announced that it would be the first country to fully replicate itself as a virtual reproduction in the metaverse (source) - Deloitte’s new report, titled “The Metaverse in Asia: Strategies for Accelerating Economic Impact,” examined the potential influence of the metaverse on 12 Asian economies: the metaverse’s contribution to gross domestic product in Asia could be between $800 billion and $1.4 trillion per year (1.3% to 2.4% of overall GDP) by 2035, according to Deloitte (source) - Yahoo Finance releases a new industry report: the metaverse market size to grow by $677.98 billion between 2021 and 2026, however, the growth momentum is expected to decelerate at a CAGR of 33.26% (source) #metaverse#November2022#trends

The Open Platform

@topco · Post #22 · 29.12.2022 г., 09:04

Crypto Payments: November headlines: - Binance CEO proposes Binance Pay for Twitter payments: Binance has plunged $500 million into Elon Musk’s takeover of social media platform Twitter, with a view to giving crypto a “seat at the table” (source) - Dogecoin jumped 22% in a week amid Twitter payments speculation (source) - Ramp Network, a U.K.-based startup offering payment infrastructure to connect crypto and traditional finance, raised $70M: the round was co-led by UAE wealth fund Mubadala Capital and Korelya Capital (source) - Crypto payments with USDC are now available on Apple Pay: Circle, the issuer of the USDC stablecoin, added support for Apple Pay (AAPL) to help to boost the use of the coin by allowing crypto businesses to accept the payment method (source) -Gate.io launches its crypto payment product Gate Pay (source) - Revolut embraces crypto: Revolut launched a feature that lets customers make purchases using crypto on their Revolut card (source) #paymentsolutions#November2022#trends

The Open Platform

@topco · Post #23 · 29.12.2022 г., 15:04

Web3 Creator Economy: November headlines: - Meta’s Instagram plans NFT minting: Instagram will soon have NFT creation and trading tools built in, but in-app purchases will be "subject to applicable app store fees" (source) - Former Meta and Pinterest executive joins Sequoia-backed Decentralized Social (DeSo) as COO to scale the business - DeSo is a new layer-1 blockchain built from the ground up to decentralize social media with a mission of reimagining the creator economy (source) - Nike will let people design and sell sneakers for the metaverse, previously Nike created a metaverse called .Swoosh, a Web3-enabled platform where people will be able to buy its virtual products, which acts as a marketplace (source) - Pearpop, a marketplace for social collaborations, raised $18M at a $300M valuation - Pearpop allows creators to buy collaborations with other creators or celebrities and currently has more than 200,000 users on the platform (source) #creatoreconomy#November2022#trends

The Open Platform

@topco · Post #21 · 28.12.2022 г., 15:04

Wallets: November headlines: - Twitter may possibly be working on it own crypto wallet (source), while some sources claim that the work on crypto wallet was halted (source) - As of November 2022, Reddit users opened 2.5 million crypto wallets following the launch of NFT marketplace (source) - Trust Wallet token soared 47% in value after Binance CEO tweeted about the importance of self-custody and prompted users to use the Trust wallet. Other self-custody wallet provider tokens also rallied, including SafePal (SFP), which increased by 27% in value (source) - Cold wallets moon after FTX collapse: Ledger saw its highest askes week in November, Trezor also reported a similar surge in demand (source) - JPMorgan registered trademark for crypto wallet: “J.P. Morgan Wallet” will see the legacy bank offer crypto and bitcoin services to its existing pool of customers (source) - Yahoo Finance released a new industry report: crypto wallet market size was valued at $6127.2 million in 2021 and is expected to expand at a CAGR of 30.78% reaching $30659.33 million by 2027 (source) #wallets#November2022#trends