Skip to content

Instantly share code, notes, and snippets.

View aliev's full-sized avatar
🎯
Focusing

Ali Aliyev aliev

🎯
Focusing
View GitHub Profile

Easy parallel python with concurrent.futures

As of version 3.3, python includes the very promising concurrent.futures module, with elegant context managers for running tasks concurrently. Thanks to the simple and consistent interface you can use both threads and processes with minimal effort.

For most CPU bound tasks - anything that is heavy number crunching - you want your program to use all the CPUs in your PC. The simplest way to get a CPU bound task to run in parallel is to use the ProcessPoolExecutor, which will create enough sub-processes to keep all your CPUs busy.

We use the context manager thusly:

with concurrent.futures.ProcessPoolExecutor() as executor:
@aliev
aliev / tree.md
Created March 16, 2014 22:58 — forked from hrldcpr/tree.md

One-line Tree in Python

Using Python's built-in defaultdict we can easily define a tree data structure:

def tree(): return defaultdict(tree)

That's it!

#!/usr/bin/python
from __future__ import print_function
import pathlib
import argparse
import os
from neovim import attach
@aliev
aliev / gist:b62f78e6f3112208cae6
Created June 10, 2015 13:57
Django and Content Types
class FirstModel(models.Model):
pass
class SecondModel(models.Model):
pass
class BaseModel(models.Model):
content_type = models.ForeignKey(ContentType)
@aliev
aliev / .tmux.conf
Created August 16, 2015 17:04
My Tmux Configuration
# Terminal
set -g default-terminal "screen-256color"
# No delay for escape key press
set -sg escape-time 0
# This tmux statusbar config was created by tmuxline.vim
# on Wed, 25 Feb 2015
set -g status-bg "colour238"
set -g message-command-fg "colour188"
" | incsearch.vim | / ? g/ n N * # g* g# | {{{
let g:incsearch#auto_nohlsearch = 1
map / <Plug>(incsearch-forward)
map ? <Plug>(incsearch-backward)
map g/ <Plug>(incsearch-stay)
map n <Plug>(incsearch-nohl-n)
map N <Plug>(incsearch-nohl-N)
map * <Plug>(incsearch-nohl-*)
map # <Plug>(incsearch-nohl-#)
@aliev
aliev / .settings
Last active September 10, 2015 16:51
Django project specific options for Vim
"let g:django_settings_module=".settings."
let $PYTHONPATH=""
if !exists("g:django_settings_module")
let $DJANGO_SETTINGS_MODULE = printf("%s.settings", split(getcwd(), '/')[-1:][0])
else
let $DJANGO_SETTINGS_MODULE = g:django_settings_module
endif
# Terminal
set -g default-terminal "screen-256color"
# No delay for escape key press
set -sg escape-time 0
# Enable mouse
set -g mode-mouse on
set -g mouse-resize-pane on
set -g mouse-select-pane on
from django import template
register = template.Library()
@register.simple_tag
def url_encode(request, **kwargs):
"""
For example, on the page, we have
1. filters,

Вступление

Во-первых, это моё мнение, и я его никому не навязываю. Во-вторых, список не обязательно исчерпывающий. В-третьих, он ориентирован на определённую "философию", которая тоже не является исчерпывающей или абсолютно правильной. Поэтому, если Вам эти рекомендации не подходят -- не следуйте им.

Философия такова. Для того чтобы осмысленно программировать на начальном этапе не нужно знать Computer Science, теорию алгоритмов и сложности вычислений или детально разбираться в устройстве и работе компьютера. Достаточно хорошо делать две вещи:

  1. алгоритмизировать решение задачи (разбивать его на простые последовательные шаги: сначала это, а потом вот это),
  2. знать, понимать смысл и назначение, использовать и подгонять друг к другу стандартные элементы решений (условия, циклы, структуры данных, алгоритмы и прочие "паттерны")