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

Резултати

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

Пребарај: #challenging

当前筛选 #challenging清除筛选
We want you

@we_want_youu · Post #4764 · 17.09.2024 г., 09:35

According to Al-Quran, Surah Ar-Rahman (55:19-23), Allah Almighty presents a powerful and miraculous sign of His creation: He released two seas, meeting side by side. Between them is a barrier, so they do not mix. So which of the favors of your Lord will you deny? In these verses, Allah highlights His supreme authority and wisdom. The reference is to two bodies of water — saltwater and freshwater — that meet but do not mix, remaining separate due to a divine barrier. This natural phenomenon, which scientists have now confirmed, is a profound example of Allah’s control over the natural world. Despite their proximity, the two waters retain their distinct properties, showcasing the perfect balance and system designed by the Creator. #Miracle of the #Quran The Quran was revealed over 1400 years ago, long before modern science understood this phenomenon. The concept of two seas meeting without mixing is something that early humans would have had no scientific means to explain. However, this fact has been witnessed in places like the Mediterranean Sea and the Atlantic Ocean, as well as at river mouths where freshwater meets saltwater. These verses from Surah Ar-Rahman serve as a miraculous scientific truth that confirms the divine knowledge in the Quran, as such occurrences were unknown to humans at the time of revelation. This miracle demonstrates that the Quran is not just a religious text, but also a source of knowledge beyond human capacity. It contains signs that have been confirmed by modern scientific discoveries, proving its authenticity for generations. #Hadeeth and the Understanding of Nature The Quran’s miraculous signs are supported by several teachings in the Hadith (the sayings and actions of the Prophet Muhammad, peace be upon him). The Prophet (PBUH) emphasized reflection on the natural world as a way to understand the power and wisdom of Allah. He encouraged believers to observe the universe as a sign of Allah’s existence, greatness, and mercy. For instance, in one hadith, the Prophet (PBUH) said : "Verily, in the creation of the heavens and the earth, and in the alternation of the night and the day, there are indeed signs for men of understanding. (Sahih Muslim) This emphasizes that everything in the natural world — from the vastness of the cosmos to the interaction of rivers and seas — is a sign of #Allah’s greatness. The separation of the seas is not just a scientific reality, but a reflection of Allah’s control over every element of creation. #Challenging Other #Religions #Islam, through the Quran and Hadith, presents a clear and rational understanding of the world that aligns with both spiritual insight and scientific discovery. Other religions, such as Hinduism, Christianity, and Judaism, do not offer such precise and scientifically verifiable details in their scriptures. While they contain teachings about faith and morality, no other religious scripture provides such detailed descriptions of natural phenomena that can be later confirmed by science, as is the case with the Quran. Why Deny the Truth? The repeated question, "So which of the favors of your Lord will you deny?" is a reminder to humanity that all the signs of Allah’s existence and mercy are evident, yet many people continue to deny or ignore them. These verses challenge the deniers of faith by presenting clear, undeniable evidence of Allah’s creation and control over the universe. In conclusion, this verse from Surah Ar-Rahman, alongside many other Quranic miracles, serves as a testament to the truth of Islam and the divine nature of the Quran. It stands as a proof for both believers and skeptics, showing that no other religion can provide such clear and scientifically proven signs of divine wisdom and knowledge. The separation of the seas is just one of many miracles in the Quran that continue to be confirmed by modern discoveries, making it clear that the Quran is the ultimate source of truth. Thanks for your kindly time