Один из самых удобных способов записать данные это использование готовых форматов, такие как JSON или YAML.
Из плюсов такого подхода стоит отметить вот что:
🔸 готовый, повсеместно используемый и поддерживаемый формат
🔸 простой и понятный файл, удобочитаемый для человека
🔸 можно легко редактировать в любом текстовом редакторе без специальных программ и библиотек
Но есть и минусы
🔹 затраты времени при записи файла (кодирование данных в нужный формат строки)
🔹 затраты времени при чтении файла (декодирование данных в Python объекты)
🔹 размер файла увеличивается из-за разметки данных (скобки, запятые, переносы, отступы...)
🔹 перед записью все данные должны быть помещены в память в полном объёме (не всегда)
🔹 при чтении необходимо считать весь файл в память и только потом декодировать данные
Если нужно писать немного данных в несколько файлов, то затраты по времени не ощутимы. Обычно это файлы конфига или какие-либо метаданные. Это отличный вариант под такие задачи.
Есть и другой поход к записи файлов - это бинарные файлы. Используется, когда данных достаточно много и никто их не собирается читать глазками😳.
🔸 очень быстрая запись
🔸 чтение значительно быстрей чем JSON, YAML итд
🔸 размер файла значительно меньше, так как нет разметки
🔸 можно записывать данные по мере поступления не загружая всё в память
🔸 можно извлечь любую часть данных независимо
Из минусов
🔹 нужно определить свой формат записи данных (если не используете готовую спецификацию определённого формата)
🔹 не получится открыть файл и визуально понять что там записано, а для чтения файла потребуется знать его спецификацию.
🔹 не так-то просто создать такой файл без специальной библиотеки
В таком виде удобно записывать большой массив любых однородных данных. Например, мониторинг валютной биржи или кэшированная анимация 3D геометрии.
(Это не означает что нельзя записать данные разного типа, просто это будет не так удобно)
Представьте себе JPG-картинку. По сути это немного мета-информации и большой массив пикселей. Тоже самое со звуком или видео файлом. Поэтому, если вы попробуете открыть картинку в текстовом редакторе вы увидите что-то вроде такого
f15d cd29 a564 4578 ...
09e2 9bc4 a696 1253 ...
84e9 4de1 3b23 c24a ...
2534 5161 28e0 709d ...
...
Это и есть записанные байтики. И для их чтения требуется определённый софт который знает что с ними делать. Под каждый тип файла.
К чему это я? Читайте в следующем посте...
#tricks#basic
#OFFTOPIC - Il ministro dello Sviluppo economico Giancarlo Giorgetti ha confermato le voci sulla trattativa con Intel per la produzione di microchip in Italia, ma la pubblicazione della notizia “non giova”.
“Sì - ha detto rispondendo alle domande dei giornalisti, all’ambasciata d’Italia a Washington - la trattativa c’è, ci sono stati una serie di incontri, ma credo che sarebbe stato meglio se queste voci non fossero uscite. La riservatezza aiuta in questi casi”.
@amiciapple
#OFFTOPIC — Jeff Bezos passerà il testimone come amministratore delegato di Amazon a Andy Jassy nel terzo trimestre. Bezos diventerà presidente esecutivo.
✍🏻@amiciapple
If there is one thing you should know about me, it is this: I am quite big on word games, not necessarily puns — just a normal play of fancy words. There's just something satisfying about throwing around big words like "Tell me about it".
#OffTopic
#OffTopic
¿Creen que se haga una tercer guerra?
O si se logre detener a tiempo todo esto?
Y ojo, no me refiero a quizá guerra con armas y bombas nucleares
Presiento que va más por la onda cibernética
Porque Iran tiene un buen armamento en ese sentido
Iran confirma si habrá represalias contra USA
#offtopic
You want to congratulate someone on their birthday, but it occurs to you you are late, because their birthday was yesterday. 😅
What phrase would you use to wish this person a happy birthday?
The answer is Happy Belated Birthday!
𓂃◗🏄♀️10COSAS PARA HACER ANTES DE QUE ACABE EL VERANO 🪸. . Ꮺ
1. Termina un libro en tus lista de pendientes
2. Haz un picnic con tus amigos
3. Visitar un acuario
4. Sentarte en un parque a leer o dibujar
5. Aprender crochet
6. Remodelar tu habitación o decorarla
7. Ver o leer "Call me by Your Name"
8. Noche de juegos de mesa en familia
9. Hacer una cápsula del tiempo con tus amigos
10. Resolver un puzzle o rompecabezas
⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ
para más 𓂃◗ @apuntes_digitales
#offtopic#ideas
⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ⸦ ⸧ִֹ
🤳 Social Media Dopamine Loop — Introduction
❗️Disclaimer: I am not gonna dive deep into the biological origin and purposes of dopamine as a hormone. Writing this post I just wanna emphasize how dangerous it is to follow and crave dopamine without control.
What’s the dopamine loop after all? This article sums it up pretty well. In a nutshell, it is a constant seeking of small and fast dopamine portions (or hits) that bring us short-term pleasure. It can be sugary food or drinks, it can be sex, binge-watching Netflix, playing video games, or even simple human interactions.
🤯Fun Fact: some scientists and writers were deliberately limiting their interactions with other people in the first part of the day in order to stay focused and not be distracted by peoples’ faces. Such an extreme approach comes from the fact that humans are extremely susceptible to faces. It takes a lot of our “RAM” to analyze and understand other human beings based on their facial expressions. So in order to perform at the highest, they made such sacrifices.
Coming back to dopamine. The main problem with such dopamine hits is that they can be achieved pretty effortlessly, without working hard to attain them (and I am not saying that in order to enjoy something you should “deserve” it only by working hard). ☹️
Let’s have a step back for a while and imagine how it all looked like thousands of years ago. Obviously, we won’t compare the lifestyle of people living then and now. The basic brain functions and frameworks, however, haven’t changed much since then. 🧠
What we need as humans basically are 2 things: calories and bits of information. The first ones feed our body and brain in order to function, and the second ones are crucial for our brain and therefore for our survival. How? Our brain is an extremely energy-consuming organ since it constantly gathers data around us, analyses it, and makes decisions that, at that time, were crucial for our survival.
🏹 From that standpoint, in order to get enough calories, you had to hunt. Hunts can be extremely long and unsuccessful. Once you get it you should start thinking about getting more later. Total pain in the a**, to be honest. Same with bits of information — we are especially receptive to visual clues, movements, and changes in the landscape in order to detect potential predators, food, etc. We are simply wired that way which enabled us to survive till that day. All this brainwork performed by us is exhausting. The same behavioral and neural patterns apply today.
What does it mean nowadays? Neither of these 2 resources is scarce now. Food — almost unlimited access. It’s nothing compared to thousands of years ago. Information — all around us. It’s actually overwhelming. No wonder obesity is taking over in developed countries and people are suffering more and more from depression, anxiety, and lack of energy. Like it or not, we (humanity) unconsciously broke the pattern that provided us with a healthy existence.
🍟 Funny enough, we actually can stop eating — that’s good news because otherwise we die or become less attractive mate partners. This mechanism works pretty well (on the other hand, given the amount of free porn and 0 effort to get sexual arousal I am not sure about that). However, when it comes to information therewas no need for evolution to develop a mechanism that would stop us from getting more information. I mean, why would you want that, right? More information means more chances of survival. Noone however expected that information will become available on THAT scale. Which has led, ironically, to disrupting our existence instead of improving it (apart from the overall civilizational progress, I mean).
📱So now, why can’t I stop scrolling on my app feeds? This question is connected to another one: why am I constantly in a bad mood, having depression or anxiety?
I am gonna cover some tips in the next post since it’s gotten pretty big already. Let’s collect 20 “🔥”, so I will see if you liked the post.
To be continued 🔜
#TooDeep
#OffTopic
#offtopic#CrazyEnglish
English is crazy: it's one of the languages where 'there is only so much we can do' means the same thing as 'we can't do much'.
@ieltsulugbeks