Beware when using dict.keys() and dict.values()
Starting with Python3.7 dict.keys() and dict.values() preserves an insertion order [1] [2] [3]. That's not true for older versions, so the code below ``` data = { 'one': 1, 'two': 2, 'three': 3, 'four': 4, } keys = ['one', 'two', 'three', 'four'] values = [1, 2, 3, 4] data_keys = list(data.keys()) data_values = list(data.values()) k_equals = data_keys == keys v_equals = data_values == values if not k_equals: print('wrong keys', data_keys) if not v_equals: print('wrong va...
Пишемо просту нейронну мережу з нуля у 100 рядків коду
Привіт, зараз дуже популярними є напрямки штучного інтелекту, нейронних мереж та машинного навчання. Все це побудовано на досить нескладних концептах, які можна відтворити, знаючи трохи математики та програмування. Саме це ми і зробимо сьогодні, використовуючи Python 3. Для початку потрібно розуміти, що собою буде являти нейронна мережа. Будемо думати про неї, як про функцію, що отримує деякий набір вхідних даних та видає для них результат. Ззовні це виглядає як чорний ящик, внутрішню будову яко...
Симуляція руху кубика
Привіт, сьогодні ми розглянемо модифікацію задачі оптимізації для знаходження найкоротшого (найдешевшого) шляху. Умова така: маємо кубик, на кожній стороні якого позначено додатнє число. Коли куб знаходиться на цій стороні - це число додається до загальної вартості шляху. Також маємо площину, поділену на рівні частини (квадрати), які відповідають розміру граней куба. Кубик може переміщуватися по цій площині в чотирьох напрямках (вперед, назад, вправо, вліво) і рух відбувається поворотом у відп...
Serialize arbitrary objects to YAML with Python
When working with YAML files in Python you probably are using PyYAML library. This is handy when storing configuration files, nested structures or sequence-like data. The nice thing about it is the ability to dump/load Python objects as well (not only regular int's, str's, float's, list's). In this article we are going to talk about customizing this serialization process and adapting resulting format to our needs. Suppose we have a User model written with a help of another great library named at...
Proxy usage when making requests with Python
In this article I would like to describe proxy usage techniques within Python code, starting from basic usage to advanced requests through intermediate proxy pool service. Why? Sometimes you need to connect to some resource that may be blocked by your ISP, sometimes you want to hide your real IP address, sometimes you need to bypass rate limiting when using a web-crawler. (NOTE: not all proxies support all the features, see classification below). When talking about anonymity (hiding real user wh...
Use multiple versions of Vagrant on the same machine
Recently I faced an issue of running Vagrant version 1.8 because of plugin incompatibility. I've removed my original installation (which was 2.1) and did the work needed. But a while after that I had to use that old version once again. So not to repeat this boring process once again I decided to make my system work with two different versions of Vagrant simultaneously. To accomplish that we need to throw away regular installation process and build everything from sources. $ cd /opt $ sudo mkdir...
Method overloading in Python
Python does not support method/functions overloading as other languages do. For example in C++ we can define three different methods that will support different types of arguments class printData { public: void print(int i) { cout << "Printing int: " << i << endl; } void print(double f) { cout << "Printing float: " << f << endl; } void print(char* c) { cout << "Printing character: " << c << endl; } }; But in Python only the last dec...
Advanced wtforms usage
WTForms is a powerful form validation and rendering library especially for web development. It's framework agnostic but there are packages that integrate it with popular web frameworks (e.g. Flask WTF ). In this article I'm going to cover some advanced techniques which is not covered in documentation. Creating custom fields If you want to add some non-standard field to your form you can create a custom field. First you need to inherit from appropriate field to describe which type of value you w...
bz2 ModuleNotFoundError
This error means that you have missing bz2 headers (probably because you've built python from sources without this option enabled), so you need to install them first (for Ubuntu/Debian): ```bash apt-get install libbz2-dev Now we need to reconfigure your python and reinstall it once again (version `3.6.5` for example below)bash $ tar -xvf Python-3.6.5.tar.xz $ cd Python-3.6.5/ $ ./configure $ make $ sudo make install Check whether it works properly nowbash $ python3.6 - c "import bz2" should ret...
Django integrity error while running migration
Recently I've got an error when invoking python manage.py migrate Traceback (most recent call last): File "/home/ubuntu/virt/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey" DETAIL: Key (id)=(99) already exists. This one means that you have out of date sequence within your database (improper previous migrations or jumps betwe...
I read. I read long, complicated books about very smart things. And I read short, silly books about very stupid things. I read until their stories are more fascinating to me than the people actually around me.
theoatmeal

What's inside?