code:
import os
if os.name == 'posix':
    from subprocess import check_output
elif os.name == 'nt':
    import win32api, win32con, win32process
    from ctypes import windll
    user32 = windll.user32

def get_locale(self):
    if os.name == 'nt':
        w = user32.GetForegroundWindow()
        tid = user32.GetWindowThreadProcessId(w, 0)
        return hex(user32.GetKeyboardLayout(tid))
    elif os.name == 'posix':
        return check_output(["xkblayout-state", "print", "%s"])

rawDescription: Detect keyboard layout in *nix in Python


code:
from another_class import doit
from another_class import dataholder
from descriptive_name import getSomeStuff
from descriptive_name import hold_more_data
del another_class, descriptive_name
__all__ = ['doit', 'dataholder', 'getSomeStuff', 'hold_more_data']

rawDescription: How to organize multiple python files into a single module without it behaving like a package?

description: Organize multiple python files into a single module without it behaving like a package


code:
import copy
B = copy.deepcopy(A)

rawDescription: python dictionary update in Monte Carlo algorithm

description: Python dictionary update in Monte Carlo algorithm


code:
N = 5
M = 4
np.tile(np.arange(N), (M, 1))

rawDescription: Initializing a N x M matrix in python

description: Initializing a N x M matrix in python


code:
import logging
import os
import errno

def mkdir_p(path):
    """http://stackoverflow.com/a/600612/190597 (tzot)"""
    try:
        os.makedirs(path, exist_ok=True)  # Python>3.2
    except TypeError:
        try:
            os.makedirs(path)
        except OSError as exc: # Python >2.5
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else: raise

class MakeFileHandler(logging.FileHandler):
    def __init__(self, filename, mode='a', encoding=None, delay=0):
        mkdir_p(os.path.dirname(filename))
        logging.FileHandler.__init__(self, filename, mode, encoding, delay)

rawDescription: python logging: how to ensure logfile directory is created?

description: Python logging: how to ensure logfile directory is created


code:
from kivy.lang import Builder
Builder.load_file('kivi.kv')

rawDescription: How to load .kv files?

description: Load .kv files


code:
my_text ="\U0001F602  and all of this \U0001F605"
re.sub('[\U0001F602-\U0001F64F]', lambda m: unicodedata.name(m.group()), my_text)

rawDescription: Substitute Emoji with its description or name


code:
def app(env, start):
    start('200 OK', [('Content-type', 'text/plain')])
    return ['Hello, world!']
server = cherrypy.wsgiserver.CherryPyWSGIServer(('0.0.0.0', 0), app,
                                                server_name='localhost')
server.bind(socket.AF_INET, socket.SOCK_STREAM)
addr, port = server.socket.getsockname()
print(port)
server.start()

rawDescription: Can I get CherryPy to find its own available port?

description: Get CherryPy to find its own available port


code:
from z3 import *
x,y,z = Ints('x y z')
s = 'x + y + 2*z == 5'
F = eval(s)
solve(F)

rawDescription: z3python: converting string to expression

description: Z3python: converting string to expression


code:
class Post(models.Model):
    ...

    def save(self, *args, **kwargs):
        if self.is_published:
            self.time_publish = datetime.now() # don't forget import datetime
        super(Post, self).save(*args, **kwargs)
        ...

rawDescription: django automated dateTime field

description: Django automated dateTime field


code:
from collections import Counter
a = Counter({'menu': 20, 'good': 15, 'happy': 10, 'bar': 5})
b = Counter({'menu': 1, 'good': 1, 'bar': 3})
a + b

rawDescription: Summing the contents of two collections.Counter() objects


code:
employees_output_list = []
for emp in emp_list:
  name_rank_str = "%s (%s)" % (emp.first_name, emp.rank)
  emp_dict = {
    "id": emp.pk,
    "label": name_rank_str,
    "value": name_rank_str,
  }
  employees_output_list.append(emp_dict)
return HttpResponse(json.dumps(employees_output_list))

rawDescription: Parsing Django Queryset JSON

description: Parsing Django Queryset JSON


code:
import os
import sys

# the command like this: python rename dirs /your/path/name/ tst
if __name__ == '__main__':
    mode = sys.argv[1]  # dirs or files
    pathname = sys.argv[2]
    pattern = sys.argv[3]

    ndict = {'dirs': '', 'files': ''}
    topdown = {'dirs': False, 'files': True}

    for root, ndict['dirs'], ndict['files'] in os.walk(
            pathname, topdown[mode]):
        for name in enumerate(ndict[mode]):
            newname = name.replace(pattern, '')
            if newname != name:
                os.rename(
                    os.path.join(root, name),
                    os.path.join(root, newname))

rawDescription: Recursively renaming directory/file structures on a local file system


code:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

def geometric_brownian_motion(T = 1, N = 100, mu = 0.1, sigma = 0.01, S0 = 20):
    dt = float(T)/N
    t = np.linspace(0, T, N)
    W = np.random.standard_normal(size = N)
    W = np.cumsum(W)*np.sqrt(dt) ### standard brownian motion ###
    X = (mu-0.5*sigma**2)*t + sigma*W
    S = S0*np.exp(X) ### geometric brownian motion ###
    return S

dates = pd.date_range('2012-01-01', '2013-02-22')
T = (dates.max()-dates.min()).days / 365
N = dates.size
start_price = 100
y = pd.Series(
    geometric_brownian_motion(T, N, sigma=0.1, S0=start_price), index=dates)
y.plot()
plt.show()

rawDescription: Random walk pandas

description: Random walk pandas


rawDescription: fetching certain elements in a list in python

description: Fetching certain elements in a list in python


code:
def doMatching(file, origPattern):
    entireFile = file.read()
    patterns = []
    startIndices = {}

    for pattern in generateFuzzyPatterns(origPattern):
        patterns.append(pattern)
        startIndices.update((m.start(), (m.end(), m.group())) for m in re.finditer(pattern, entireFile))

    print('Used {} patterns:'.format(len(patterns)))
    for i, p in enumerate(patterns, 1):
        print('- [{}]  {}'.format(i, p))

    nonOverlapping = []
    lastEnd = 0
    for start in sorted(startIndices):
        if start >= lastEnd:
            lastEnd = startIndices[start][0]
            nonOverlapping.append(start)

    print()
    print('Found {} matches:'.format(len(startIndices)))
    for i in sorted(startIndices):
        print('- [{}:{}]  {}'.format(i, *startIndices[i]))

    print()
    print('Found {} non-overlapping matches:'.format(len(nonOverlapping)))
    for i in nonOverlapping:
        print('- [{}:{}]  {}'.format(i, *startIndices[i]))

def generateFuzzyPatterns(origPattern):
    # Escape individual symbols.
    origPattern = [re.escape(c) for c in origPattern]

    # Find exact matches.
    pattern = ''.join(origPattern)
    yield pattern

    # Find matches with changes.
    for i in range(len(origPattern)):
        t = origPattern[:]
        t[i] = '.'
        pattern = ''.join(t)
        yield pattern

    # Find matches with deletions.
    for i in range(len(origPattern)):
        t = origPattern[:]
        t[i] = ''
        pattern = ''.join(t)
        yield pattern

    # Find matches with insertions.
    for i in range(len(origPattern) + 1):
        t = origPattern[:]
        t.insert(i, '.')
        pattern = ''.join(t)
        yield pattern

    # Find two adjacent characters being swapped.
    for i in range(len(origPattern) - 1):
        t = origPattern[:]
        if t[i] != t[i + 1]:
            t[i], t[i + 1] = t[i + 1], t[i]
            pattern = ''.join(t)
            yield pattern

rawDescription: Python regex problems with string matching


code:
class UserView(sqla.ModelView):
    # Hide `hash_name` in list and form views
    column_exclude_list = ('hash_name',)
    form_excluded_columns = ('hash_name',)

    # Generate new hash on `name` change
    def on_model_change(self, form, model, is_created):
        if len(model.name):
            model.hash_name = generate_hash_name(model.name)

rawDescription: How to set hash of a column in another column in flask-admin?

description: Set hash of a column in another column in flask-admin


code:
ffffffff # big endian
ffffffff # little endian

rawDescription: endianness using struct.pack struct.unpack

description: Endianness using struct.pack struct.unpack


code: pd.set_option('display.max_rows', 120)

rawDescription: Python Pandas: dtypes not show column types for all columns


code:
from Tkinter import *

root = Tk()
global colour
global colourselection
global count
colour = ""
colourselection= ['red', 'blue']
count = 1

def start(parent):
    Tk.after(parent, 1000, change)

def change():
    global colour
    global colourselection
    global count
    if (count < 2 ):
        colour = colourselection[count]
        button.configure(bg = colour)
        count + 1
    else:
        colour = colourselection[count]
        button.configure(bg = colour)
        count = 1
    start(root)

button = Button(text = 'start', command = lambda: start(root))
button.pack()

root.mainloop()

rawDescription: Dynamically change widget background color in Tkinter


code:
import random
from math import *

number_of_points = 10000
points_in = []
points_outside = []

for i in range(number_of_points):
    rand_number1 = random.random()
    rand_number2 = random.random()
    if rand_number2 < (exp(-1*rand_number1))*(rand_number1**(-0.5)):
        points_in.append(1)
    else:
        points_outside.append(1)

rawDescription: Estimate pi with Gamma function in Python Monte Carlo method


code:
fig, ax = plt.subplots(1,1)

ax.hist(hamdists, bins=bins, align='left')
ax.set_xticks(bins[:-1])

rawDescription: Matplotlib histograms (basic questions)

description: Matplotlib histograms (basic questions)


code:
data = [...] # a list of int values
from scipy.stats import itemfreq
tmp = itemfreq(data) # Get the item frequencies
x = tmp[:, 0] # unique values in data
y = tmp[:, 1] # freq

import matplotlib.pyplot as plt
plt.loglog(x, y, basex=2, basey=2, linestyle='None',
           marker='x', markeredgecolor='red')
plt.show()

rawDescription: Draw loglog graph using pyplot

description: Draw loglog graph using pyplot


code:
from memsql.common.query_builder import multi_insert
from memsql.common.database import connect

sql, params = multi_insert("my_table", { "foo": 1 }, { "foo": 2 })
# sql = 'INSERT INTO `my_table` (`foo`) VALUES (%(_QB_ROW_0)s), (%(_QB_ROW_1)s)'
# params = {'_QB_ROW_0': [1], '_QB_ROW_1': [2]}

with connect(...) as conn:
    conn.execute(sql, **params)

rawDescription: Implement batch insert to improve performance


code:
import json, requests

url = 'http://maps.googleapis.com/maps/api/directions/json'

params = dict(
    origin='Chicago,IL',
    destination='Los+Angeles,CA',
    waypoints='Joplin,MO|Oklahoma+City,OK',
    sensor='false'
)

resp = requests.get(url=url, params=params)
data = json.loads(resp.text)

rawDescription: HTTP requests and JSON parsing in Python


code:
def UnicodeDictReader(utf8_data, **kwargs):
    csv_reader = csv.DictReader(utf8_data, **kwargs)
    for row in csv_reader:
        yield {key: unicode(value, 'utf-8') for key, value in row.iteritems()}

rawDescription: Python CSV DictReader with UTF-8 data

description: Python CSV DictReader with UTF-8 data


code:
d = dict(foo=42)
d["foo"]
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'], verbose=True)
p = Point(11, y=22)     # instantiate with positional or keyword arguments
p[0] + p[1]             # indexable like the plain tuple (11, 22) 33
x, y = p                # unpack like a regular tuple
x, y (11, 22)
p.x + p.y               # fields also accessible by name 33
p                       # readable __repr__ with a name=value style Point(x=11, y=22)

rawDescription: AttributeError when using object.__setattr__


code:
def do_work(work_info):
    q = mp.Queue()
    for (worker, dataset) in work_info.items():
      xworker = __import__(worker)
      p = mp.Process(target=xworker.do_work, args=dataset).start()
      q.put(p)
    while not q.empty():
      r = q.get()

rawDescription: Dynamically loading modules in Python (+ multi processing question)


code:
from git import *

repo = Repo(".")

test_file = None
with open("test_file.txt","r") as f:
    test_file = f.read()

test_file = test_file.replace("cake", "pie")

with open("test_file.txt","w") as f:
    f.write(test_file)

repo.index.add(['test_file.txt']) # could also use '*' to add all changed files
repo.index.commit(message="this is not cake!")
#repo.push(repo.head)

rawDescription: GitPython returns exit status of 1 when trying to commit


code:
request = requests.get(url)
file = zipfile.ZipFile(BytesIO(request.content))

rawDescription: Download a zip file and extract it in memory using Python3


code:
class QuestionOptionInline(admin.StackedInline):
    model = QuestionOption

    extra = 1 # show only one QuestionOption form

    def queryset(self, request):
         # hack: don't show existed QuestionOption
         return QuestionOption.objects.none()

class QuestionAdmin(admin.ModelAdmin):
    fields = ['text', 'is_free_text']
    inlines = [QuestionOptionInline]

rawDescription: django admin - force users to create new records rather then utilizing existing ones

description: Django admin - force users to create new records rather then utilizing existing ones


code:
import my_long_module_name as mlmn
import my_long_module_name.submodule

mlmn.submodule.function()

rawDescription: Python - How can you use a module's alias to import its submodules?


code:
chunker = pd.read_csv('DATASET.csv', chunksize=500, header=0)
dtypes = pd.DataFrame([chunk.dtypes for chunk in chunker])
dtypes.values[:5]
dtypes.max().values

rawDescription: Get inferred dataframe types iteratively using chunksize


code: plt.setp(h,edgecolor = "black")

rawDescription: Changing a barchart edge color after plotting it


code: [person for person in people if person.MAR_STATUS == 'MARRIED']

rawDescription: How to create a dynamically updating list of class instances, satisfying a particular condition? (Python)

description: Create a dynamically updating list of class instances, satisfying a particular condition? (Python)


code: is_power_supply_on = lambda mydict: mydict['state'].lower() == 'ok'

rawDescription: Best practice for "get" functions

description: Best practice for "get" functions


code:
from lxml import etree
from StringIO import StringIO
x = """<?xml version="1.0" encoding="utf-8"?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >\n<aa> â</aa>"""
p = etree.XMLParser(remove_blank_text=True, resolve_entities=False)
r = etree.parse(StringIO(x), p)
etree.tostring(r) # '<aa> â</aa>'

rawDescription: What's the best way to handle  -like entities in XML documents with lxml?


rawDescription: Calculate increase between periods or rows


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("https://www.google.co.in/search?q=Fortis+Escorts+Heart+Institute+%26+Research+Centre,+Okhla+Road,+Opp+Holy+Family+Hospital,+New+Friends+Colony,+New+Delhi,+Delhi+110025&ludocid=8685206163378021720#lrd=0x390ce4759f47e68d:0x78880cfd492e2558,1")

while True:  # TODO: decide on when to stop the loop
    reviews = driver.find_elements_by_css_selector("._ju")
    driver.execute_script("arguments[0].scrollIntoView();", reviews[-1])

rawDescription: Web Scraping through Selenium

description: Web Scraping through Selenium


code:
...
win1=Tk()
win1.bind("<ButtonPress>", lambda event: distance(event), gravitationalForce(event))
dchain = Label( win1)
...

rawDescription: Same bind for two commands in tkinter

description: Same bind for two commands in tkinter


code:
for row in cr:
    if row or any(row) or any(field.strip() for field in row):
         ca.writerow(row)

# add these two lines
outputCSV.close()
appendCSV.close()

f=csv.reader(open('C:\\..\\OUTPUT.csv','rb'))
for column in f:
     if column or any(column) or any(fields.strip() for fields in column):
         ca_final.writerow(column[3:]) # put a colon here

# close files
inputCSV.close()
outputCSV.close()
appendCSV.close()

rawDescription: Extracting from csv files with python code


code:
import requests
symbol = "mtgoxUSD"
url = 'http://api.bitcoincharts.com/v1/trades.csv?symbol={}'.format(symbol)
data = requests.get(url)

# dump resulting text to file
with open("trades_{}.csv".format(symbol), "w") as out_f:
    out_f.write(data.text)

rawDescription: Copy text from website to text/excel file


rawDescription: In Python, how is `datetime.datetime.now()` an "unaware" datetime object?


code:
from reportlab.platypus import Flowable
from reportlab.graphics.barcode import qr
from reportlab.graphics import renderPDF
from reportlab.graphics.shapes import Drawing

class QRFlowable(Flowable):
    # usage :
    # story.append(QRFlowable("http://google.fr"))
    def __init__(self, qr_value):
        # init and store rendering value
        Flowable.__init__(self)
        self.qr_value = qr_value

    def wrap(self, availWidth, availHeight):
        # optionnal, here I ask for the biggest square available
        self.width = self.height = min(availWidth, availHeight)
        return self.width, self.height

    def draw(self):
        # here standard and documented QrCodeWidget usage on
        # Flowable canva
        qr_code = qr.QrCodeWidget(self.qr_value)
        bounds = qr_code.getBounds()
        qr_width = bounds[2] - bounds[0]
        qr_height = bounds[3] - bounds[1]
        w = float(self.width)
        d = Drawing(w, w, transform=[w/qr_width, 0, 0, w/qr_height, 0, 0])
        d.add(qr_code)
        renderPDF.draw(d, self.canv, 0, 0)

rawDescription: Use QrCodeWidget (or PlotArea) with platypus


rawDescription: How to define a long hex literal over several lines?

description: Define a long hex literal over several lines


code:
df['HardwareId_list'] = df['HardwareId'].str.split(' ')
df['hardware_updated'] = df['HardwareId_list'].apply(lambda x: x[0] if type(x) == list else x)

rawDescription: Loop through a dataframe that is a result of groupby


code:
from PIL import Image
from math import sqrt

RED = 0
GREEN = 1
BLUE = 2
COLORS = [RED, GREEN, BLUE]
RED_HEALTH = (234, 105, 112)
BLUE_HEALTH = (84, 165, 226)
HEALTH_BORDER = (0, 0, 0)
image = Image.open("image.jpg")

def close_enough_to(src, target, delta):
    diff = 0
    for color in COLORS:
        diff += (src[color] - target[color]) ** 2
    diff = sqrt(diff)
    return diff <= delta

class HealthBar:
    def __init__(self, team, health_percentage, length, pos):
        self.team = team
        self.health_percentage = health_percentage
        self.length = length
        self.pos = pos

    def __str__(self):
        return "team {}, percentage {}, length {}, pos {}".format(self.team,
                self.health_percentage,
                self.length,
                self.pos
                )

    def __repr__(self):
        return str(self)

def flood_fill_health_bar(image, pos, color, traversed):
    (x, y) = pos
    health_pixels = 0
    while close_enough_to(image.getpixel((x, y)), color) \
        and (x, y) not in traversed:
        health_pixels += 1
        traversed.add((x, y))
        x += 1
    black_pixels = 0
    while close_enough_to(image.getpixel((x, y)), HEALTH_BORDER, 50) \
        and (x, y) not in traversed:
        black_pixels += 1
        traversed.add((x, y))
        x += 1
    if black_pixels > 0:
        if color is RED_HEALTH:
            team = "red"
        else:
            team = "blue"
        percent_health = health_pixels / (health_pixels + black_pixels)
        return HealthBar(team, percent_health, health_pixels + black_pixels, pos)

def in_bounds(image, pos):
    return pos[0] >= 0 and pos[1] >= 0 \
            and pos[0] < image.width and pos[1] < image.height

def flood_fill_image(image, start, delta):
    flood_fill_queue = [start]
    traversed = []
    color = image.getpixel(start)
    pos = start
    pix = image.load()
    while len(flood_fill_queue):
        (x, y) = flood_fill_queue.pop()
        positions = [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]
        for position in positions:
            if in_bounds(image, position) \
                    and close_enough_to(image.getpixel(position), color, delta):
                if position not in traversed:
                    flood_fill_queue.append(position)
                    traversed.append(position)
                    (x, y) = position
                    pix[x, y] = (0, 0, 255)
    return traversed

def get_width(positions):
    return get_max_x(positions) - get_min_x(positions)

def get_height(positions):
    return get_max_y(positions) - get_min_y(positions)

def get_max_x(positions):
    return sorted(list(positions), key=lambda x: x[0])[-1][0]

def get_max_y(positions):
    return sorted(list(positions), key=lambda x: x[1])[-1][1]

def get_min_x(positions):
    return sorted(list(positions), key=lambda x: x[0])[0][0]

def get_min_y(positions):
    return sorted(list(positions), key=lambda x: x[1])[0][1]

def find_health_bars(image):
    traversed = set()
    health_bars = []
    pix = image.load()
    (width, height) = image.size
    for col in range(0, width):
        for row in range(0, height):
            #  pix = image.getpixel((col, row))
            if (col, row) in traversed:
                continue
            for health_color in [RED_HEALTH, BLUE_HEALTH]:
                border_pixels = []
                if close_enough_to(image.getpixel((col, row)), health_color, 10):
                    health_pixels = flood_fill_image(image, (col, row), 100)
                    for pos in health_pixels:
                        (x, y) = pos
                        traversed.add(pos)
                        pix[x, y] = (255, 255, 0)
                    border_pixels = flood_fill_image(image, (col - 1, row - 1), 30)
                    if len(border_pixels) is 0:
                        continue
                    health_bar_width = get_width(border_pixels)
                    health_bar_height = get_height(border_pixels)
                    health_width = get_width(health_pixels)
                    if abs(health_bar_width / health_bar_height) - 10 <= 0.5:
                        team = "blue" if health_color == BLUE_HEALTH else "red"
                        percent_health = health_width / health_bar_width
                        health_bar = HealthBar(team, percent_health, health_bar_width, (col, row))
                        health_bars.append(health_bar)

                for pos in border_pixels:
                    (x, y) = pos
                    traversed.add(pos)
                    pix[x, y] = (0, 255, 255)
    health_bars = [health_bar for health_bar in health_bars if health_bar is not None]
    health_bars.sort(key=lambda x: x.length)
    return health_bars

health_bars = find_health_bars(image)

print(health_bars)

rawDescription: How to track rectangle with specific color

description: Track rectangle with specific color


code:
result = []
temp_result = MyModel.objects.all()
for temp in temp_result:
    if query.lower() in temp.first_name.lower():
        result.append(temp)

rawDescription: Encrypting Django User Model Fields

description: Encrypting Django User Model Fields


code:
import re #regular expressions module

file = open('text_to_process.txt', 'r') #opening your file

text = file.readlines()

file.close()

flag = False #flag to mark start/end of description

for line in text:
    if re.match(r"#### \*\*Description\*\*", line):
        flag = True
        continue
    if flag:
        if not re.match("####", line):
            print(line.strip()) #just printing the line, alternatively you could write it into file or variable
        else:
            flag = False

rawDescription: python extract text description from large text file

description: Python extract text description from large text file


code: {{ post.body | safe }}

rawDescription: render html strings in flask templates

description: Render html strings in flask templates


code:
import itertools
l = [0, 1, 2, 3, 4, 5]
tuple(itertools.permutations(l))

rawDescription: find all possible combination sequences in a list of python

description: Find all possible combination sequences in a list of python


code:
for line in someopenfile:
  if line.isspace():
    empty_line()

rawDescription: How to detect lines with only a white space in a text?

description: Detect lines with only a white space in a text


rawDescription: replace each column of pandas dataframe with each value of array

description: Replace each column of pandas dataframe with each value of array


code:
import numpy as np
class A(np.ndarray):
    """ class overloading a numpy array for addition
    """
    def __init__(self, values):
        self.values = values
    def __add__(self, x):
        """ addition
        """
        x = np.array(x) # make sure input is numpy compatible
        return A(self.values + x)
    def __radd__(self, x):
        """ reversed-order (LHS <-> RHS) addition
        """
        x = np.array(x) # make sure input is numpy compatible
        return A(x + self.values)
    def __array__(self):
        """ so that numpy's array() returns values
        """
        return self.values
    def __repr__(self):
        return "A object: "+repr(self.values)

a = A(np.arange(5))
a + np.ones(5)
np.ones(5) + a

rawDescription: How to make numpy overloading of __add__ independent on operand order?

description: Make numpy overloading of __add__ independent on operand order


code:
while shape.lower() not in ["octagon", "heptagon", "hexagon"] :
    print("You have to select a shape from the specified list.")
    shape = input("What shape would you like to draw: ")

rawDescription: Python: Why does my inner-nested while-loop continue to execute indefinitely


code: return render(request, 'bprofile/init.html', targs)

rawDescription: Convert the Django direct_to_template function to use class based view


code:
import netCDF4 as nc

dataset = nc.Dataset('/path/to/data.nc', 'r+')

cntry = dataset.variables['cntry_codes'][:]
shape = dataset.variables['data'].shape

for i in range(shape[0]):
    data_i = dataset.variables['data'][i]
    data_i[cntry == 840.0] = 0.8
    dataset.variables['data'][i] = data_i

dataset.close()

rawDescription: Subset netCDF in python based on another variable


code:
#!/usr/bin/env python

import curses
import curses.textpad as textpad

try:
    mainwindow = curses.initscr()
    # Some curses-friendly terminal settings
    curses.cbreak(); mainwindow.keypad(1); curses.noecho()
    textpad.Textbox(mainwindow).edit()
finally:
    # Reverse curses-friendly terminal settings
    curses.nocbreak(); mainwindow.keypad(0); curses.echo()
    curses.endwin()

rawDescription: python curses textbox widget

description: Python curses textbox widget


code:
from matplotlib import ticker
import numpy as np

def ticks_format(value, index):
    """
    get the value and returns the value as:
       integer: [0,99]
       1 digit float: [0.1, 0.99]
       n*10^m: otherwise
    To have all the number of the same size they are all returned as latex strings
    """
    exp = np.floor(np.log10(value))
    base = value/10**exp
    if exp == 0 or exp == 1:
        return '${0:d}$'.format(int(value))
    if exp == -1:
        return '${0:.1f}$'.format(value)
    else:
        return '${0:d}\\times10^{{{1:d}}}$'.format(int(base), int(exp))

subs = [1.0, 2.0, 3.0, 6.0]  # ticks to show per decade
ax.xaxis.set_minor_locator(ticker.LogLocator(subs=subs)) #set the ticks position
ax.xaxis.set_major_formatter(ticker.NullFormatter())   # remove the major ticks
ax.xaxis.set_minor_formatter(ticker.FuncFormatter(ticks_format))  #add the custom ticks
#same for ax.yaxis

rawDescription: Matplotlib: show labels for minor ticks also


code:
def Button_Build(gamesnum): # 'gamesnum' is the amount of detected files
    Screensize = 200 #size of given screen space
    button_size = Screensize/len(gamesnum) * 2   #Size of the button according to amount of files found/size of screen

    StartX = 9
    StartY = 20
    x = StartX #button's original x coordinate
    y = StartY #button's original y coordinate

    butrow = 0  #Counter for how many buttons that can fit inside of the given screen space
    butmax = int(ScreenSize / (button_size + 2)) #Maximum amount of buttons that can fit inside of given screen space

    for i in gamesnum: #Going through the number of files counted
        print(x) #Print the drawn buttons' x coordinate

        #If next button doesn't go out of given screen space
        if butrow < butmax:
            lebutton=GUI_Helper(white, red9, x, y)
            lebutton.Standard_button_make(button_size, button_size-2)
            x += (button_size + 2)
            butrow += 1
        else:
            #When maximum amount of buttons that can fit across the screen is reached
            butrow = 0 #Reset the counter
            x = StartX #Reset button's x coordinate
            y += (button_size + 2) #Move next buttons down a row

    pygame.display.update()

rawDescription: Python/Pygame: How to make buttons scale on screen with amount of buttons and screen size?


code:
import time
start = time.time()
end = time.time()
end - start

rawDescription: Time measure script in python

description: Time measure script in python


code:
# iOS-produced base64 value
'ZTU1MzZhNjUxMDc1MjYyNDU0ODllNTIzZDAzYjlmODFlNTFiYjg3NA=='.decode('base64')
# Python-produced base64 value
'5VNqZRB1JiRUieUj0DufgeUbuHQ='.decode('base64')
from binascii import hexlify
# Python-produced value converted to a hex representation
hexlify('5VNqZRB1JiRUieUj0DufgeUbuHQ='.decode('base64'))

rawDescription: Base64 encoding of CryptoDigest / SHA1 - string doesn't match the result from Java / Python


code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage as ndimage

X, Y = np.mgrid[-70:70, -70:70]
Z = np.cos((X**2+Y**2)/200.)+ np.random.normal(size=X.shape)

# Increase the value of sigma to increase the amount of blurring.
# order=0 means gaussian kernel
Z2 = ndimage.gaussian_filter(Z, sigma=1.0, order=0)
fig=plt.figure()
ax=fig.add_subplot(1,2,1)
ax.imshow(Z)
ax=fig.add_subplot(1,2,2)
ax.imshow(Z2)
plt.show()

rawDescription: Smoothing Data in Contour Plot with Matplotlib


code:
from mock import MagicMock
mock_obj = MagicMock()
mock_obj.__getitem__().__getitem__().__getitem__.return_value = 3
assert 3 ==  mock_obj['some']['test']['structure']

rawDescription: Mocking Numpy Structured Arrays

description: Mocking Numpy Structured Arrays


code:
d = r['LastContact'].split('/') # mm/dd/yyyy
try:
    r['LastContact'] = datetime(int(d[2]), int(d[0]), int(d[1]))
except Exception as e:
    r['LastContact'] = datetime.now()

if 'TaxExempt' not in r:
    r['TaxExempt'] = 0

query = """
    INSERT INTO
        Clients
    VALUES
        (NULL,
         :FirstName,
         :LastName,
         :Address1,
         :Address2,
         :City,
         :State,
         :Zip,
         :HomePhone,
         :CellPhone,
         :WorkPhone,
         :Email,
         :ContactMethod,
         :ContactFrequency,
         :ContactTime,
         :LastContact,
         :TaxExempt,
         :TaxID,
         :Notes)
"""
c.execute(query, r)

rawDescription: Insert form fields into database (Bottle, sqlite)


code:
def addObject(name, x, y):
    globals()[name] = [x,y]

addObject('Home', 3,3)
print(Home)

rawDescription: Python referance to varible based on another variable


code:
def __init__(self):
    fp = open('image.txt')
    s = fp.readlines()
    self.a = 0
    self.line = s[a]
    self.ent_date.insert(0, line[0])

def forms(self):
    b = tk.Button(bd ='4', text="Auto Fill", width = 20, command = self.autosave)
    ...

def autosave(self):
    # save the current state, e.g.,
    # self.ent_date.insert(0, line[0]) - we'll leave it to the OP
    box.showinfo('Success','Saved Successfully')
    self.a += 1

rawDescription: Auto increment line of the text file

description: Auto increment line of the text file


code: [item for item in line.split(',')[1:] if item.isdigit()][0]

rawDescription: How do I grab a number sandwiched between commas?

description: Grab a number sandwiched between commas


code:
class A:
    a = 3
    b = 5
    c = 6

{key:value for key, value in A.__dict__.items() if not key.startswith('__') and not callable(key)}

rawDescription: getting a dictionary of class variables and values

description: Getting a dictionary of class variables and values


code:
import inspect

def b():
    f = inspect.currentframe()
    current = inspect.getframeinfo(f)
    caller = inspect.getframeinfo(f.f_back)
    #caller = inspect.getframeinfo(inspect.getouterframes(f)[1][0])
    print(__name__, current.filename, current.function, current.lineno, caller.function)

def a():
    b()

a()

rawDescription: getting the module and line that a function was called from

description: Getting the module and line that a function was called from


code:
from pandas.tseries.offsets import WeekOfMonth

wom = WeekOfMonth(week=2, weekday=4)
df['days'] = df['d'].apply(lambda x: (wom.rollforward(x) - x).days)

rawDescription: Calculate days before next third Friday in a month for a Dataframe


code:
import os
os.system('cls' if os.name == 'nt' else 'clear')

rawDescription: How to clear cmd/terminal while running a python script

description: Clear cmd/terminal while running a python script


code:
import re
r = re.compile(r'^[a-zA-Z0-9]') # match @ beginning anything that's not alpha numeric
s = '#abc\ndef\nghi'
l = [r.sub('', x) for x in s.split()]
# join this list with comma (if that's required else you got the list already)
','.join(l)

rawDescription: How to convert a multiline string into a list of lines?

description: Convert a multiline string into a list of lines


code:
filename = sorted(os.listdir(location))[-1]
data = open(os.path.join(location, filename)).read()

rawDescription: Asynchronous tasks in Plone to query Python Package Index


code:
val = "mandy"
mydict = {}
mydict[val] = []
mydict[val].append("Hello")
mydict[val].append("Mandy")
mydict

rawDescription: How to create a new variable from the contents of another variable in python?

description: Create a new variable from the contents of another variable in python


code: uSplit('theuser!host')

rawDescription: comparing two strings with 'is' -- not performing as expected

description: Comparing two strings with 'is' -- not performing as expected


code: z = [" ".join(item) for item in zip(x, y)]

rawDescription: How to zip two arrays in Python and keep the original shape?

description: Zip two arrays in Python and keep the original shape


code:
import atexit
import multiprocessing as mp
from time import sleep
def runner():
    while True:
        sleep(2)

def kill_runner(runner):
    runner.terminate()

runner = mp.Process(target=runner)
runner.start()
atexit.register(kill_runner, runner)
exit()

rawDescription: Python multiprocessing: Kill worker on exit


code:
class SomeParentClass(object):
    # ...
    pass

def Child(parent):
    class Child(parent):
        # ...
        pass

    return Child()

instance = Child(SomeParentClass)

rawDescription: Pass a parent class as an argument?

description: Pass a parent class as an argument


code:
from sqlalchemy import event
from sqlalchemy.util.langhelpers import symbol

class NonUpdateableColumnError(AttributeError):
    def __init__(self, cls, column, old_value, new_value, message=None):
        self.cls = cls
        self.column = column
        self.old_value = old_value
        self.new_value = new_value

        if message is None:
            self.message = 'Cannot update column {} on model {} from {} to {}: column is non-updateable.'.format(
                column, cls, old_value, new_value)

def make_nonupdateable(col):
    @event.listens_for(col, 'set')
    def unupdateable_column_set_listener(target, value, old_value, initiator):
        if old_value != symbol('NEVER_SET') and old_value != symbol('NO_VALUE') and old_value != value:
            raise NonUpdateableColumnError(col.class_.__name__, col.name, old_value, value)

class Person(Base):
    email = Column(String)

make_nonupdateable(Person.email)

rawDescription: Make a column "immutable" in SQLAlchemy

description: Make a column "immutable" in SQLAlchemy


code:
def getInt(low, high):
    while True:
        try:
            num = int(input("Enter a number for your calculation in range of 1- 9: "))
        except ValueError:
            print("Error: Please only enter numbers")
            continue

        if num not in range(1, 10):
            print("Error: Please only enter numbers between 1-9")
        else:
            return num

rawDescription: Python: How to check if a number is in range and if not have the user enter a new number?


code: OrderedDict(sorted(list_sequences.items(), key=lambda e:datetime.strptime(e[1][0][1], '%Y-%m-%d')))

rawDescription: Sorting a python dictionary of lists by date


code:
def slice(alist, start, end):
    s = alist.index(start)
    e = alist.index(end)
    return alist[s:e+1]

rawDescription: Function that takes a list and returns value?


code:
import numpy as np
points = np.array([[1,2],[4,0],[3,0],[2,4]])
a = np.array([[1,2], [3,0]])

np.array([np.argwhere((points==a[i]).all(axis=1))[0][0] for i in xrange(a.shape[0])])
# returns array([0, 2])

rawDescription: Retreive indices of matching points in another array


code:
from datetime import datetime

class ExtendedRegisterForm(RegisterForm):
    pay_month = SelectField()

    def __init__(self, *args, **kwargs):
        super(ExtendedRegsiterForm, self).__init__(*args, **kwargs)
        now = datetime.utcnow()
        self.pay_month.choices = [(i, i) for i in range(1, now.day + 1)]

rawDescription: Custom choices in WTForms SelectField bsed on current date


code:
connections = []

def web_socket_do_extra_handshake(request):
    connections.append(request);
    pass

def web_socket_transfer_data(request):
    while True:
        line = msgutil.receive_message(request)
        for connection in connections[:]:
            msgutil.send_message(connection, line)
        if line == "Bye":
            return

rawDescription: Python "pywbsocket" HTML5 websocket server Configuration Issue?


code: df.groupby(df.sum(), axis=1).sum()

rawDescription: Group by value of sum of columns with Pandas


code:
#!/usr/bin/env python

import cherrypy

class Tree(cherrypy._cptree.Tree):

  def __call__(self, environ, start_response):
    # do more complex check likewise
    if environ['PATH_INFO'].startswith('/api/badurl'):
      start_response('404 Not Found', [])
      return []

    return super(Tree, self).__call__(environ, start_response)

cherrypy.tree = Tree()

globalConf = {
  'server.socket_host': '0.0.0.0',
  'server.socket_port': 8080,
}
cherrypy.config.update(globalConf)

class HelloApiWsgi:

  def __call__(self, environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return ['Hello World from WSGI']

class HelloApi:

  @cherrypy.expose
  def index(self):
    return "Hello from api"

cherrypy.tree.graft(HelloApiWsgi(), '/api')
cherrypy.tree.mount(HelloApi(), '/api/hello')

if __name__ == '__main__':
  cherrypy.engine.signals.subscribe()
  cherrypy.engine.start()
  cherrypy.engine.block()

rawDescription: Cherrypy routing with WSGI

description: Cherrypy routing with WSGI


code:
import string

# Lists os components
chars = [' '] + list(string.ascii_lowercase) + ['.',',','?','!']

# Your target
target = 'hello world!'

# Your array
array = [chars.index(target[t]) for t in range(len(target))]

rawDescription: python string to array

description: Python string to array


code:
import re

def text2html(text):
    """ Convert a text in a certain format to html.

    Examples:
    >>> text2html('Hello, my name is /bJane/b')
    'Hello, my name is Jane'
    >>> text2html('/iHello/i, my /uname/u is /b/i/uJane/u/i/b')
    'Hello, my name is Jane'

    """

    elem = []

    def to_tag(match_obj):
        match = match_obj.group(0)
        if match in elem:
            elem.pop(elem.index(match))
            return "</{0}>".format(match[1])
        else:
            elem.append(match)
            return "<{0}>".format(match[1])

    return re.sub(r'/.', to_tag, text)

if __name__ == "__main__":
    import doctest
    doctest.testmod()

rawDescription: How to replace pairs of tokens in a string?

description: Replace pairs of tokens in a string


code:
import gzip
import requests
import shutil

r = requests.get(url, stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        r.raw.decode_content = True  # just in case transport encoding was applied
        gzip_file = gzip.GzipFile(fileobj=r.raw)
        shutil.copyfileobj(gzip_file, f)

rawDescription: Having Trouble Getting requests==2.7.0 to Automatically Decompress gzip


code:
x = np.arange(5)
y = np.array([2, 1, 1, 2, 2])
np.repeat(x,y)

rawDescription: transform an array of array to an array of numbers

description: Transform an array of array to an array of numbers


code:
#! /usr/bin/python3

import signal
import time, os

def callme(num, frame):
    pass

# register the callback:
signal.signal(signal.SIGUSR1, callme)

print("py: Hi, I'm %d, talk to me with 'kill -SIGUSR1 %d'"
      % (os.getpid(),os.getpid()))

# wait for signal info:
while True:
    siginfo = signal.sigwaitinfo({signal.SIGUSR1})
    print("py: got %d from %d by user %d\n" % (siginfo.si_signo,
                                             siginfo.si_pid,
                                             siginfo.si_uid))

rawDescription: Get pid of the process which has triggered some signal


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        # create a prompt, an input box, an output label,
        # and a button to do the computation
        self.prompt = tk.Label(self, text="Enter a number:", anchor="w")
        self.entry = tk.Entry(self)
        self.submit = tk.Button(self, text="Submit", command = self.calculate)
        self.output = tk.Label(self, text="")

        # lay the widgets out on the screen.
        self.prompt.pack(side="top", fill="x")
        self.entry.pack(side="top", fill="x", padx=20)
        self.output.pack(side="top", fill="x", expand=True)
        self.submit.pack(side="right")

    def calculate(self):
        # get the value from the input widget, convert
        # it to an int, and do a calculation
        try:
            i = int(self.entry.get())
            result = "%s*2=%s" % (i, i*2)
        except ValueError:
            result = "Please enter digits only"

        # set the output widget to have our result
        self.output.configure(text=result)

# if this is run as a program (versus being imported),
# create a root window and an instance of our example,
# then start the event loop

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: How to make a window with buttons in python

description: Make a window with buttons in python


rawDescription: Visa credit card regular expression: grouping assertion


code: [''.join(x) for x in s]

rawDescription: merge all the elements in a list python

description: Merge all the elements in a list python


code:
from PIL import ImageFont

def get_latex_length(string, font, fontsize):
    font = ImageFont.truetype(font, fontsize)
    return font.getsize(string)

print(get_latex_length('Some text', 'Arial.ttf', 12))

rawDescription: Can I get a string length in physical units (cm, pixels, dots) as printed by latex from python?

description: Get a string length in physical units (cm, pixels, dots) as printed by latex from python


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.text = tk.Text(self, wrap="word")
        self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview)
        self.text.configure(yscrollcommand=self.text_yview)
        self.vsb.pack(side="right", fill="y")
        self.text.pack(side="left", fill="both", expand=True)

        # create an info window in the bottom right corner and
        # inset a couple of pixels
        self.info = tk.Label(self.text, width=20, borderwidth=1, relief="solid")
        self.info.place(relx=1.0, rely=1.0, x=-2, y=-2,anchor="se")

    def text_yview(self, *args):
        '''
        This gets called whenever the yview changes.  For this example
        we'll update the label to show the line number of the first
        visible row.
        '''
        # first, update the scrollbar to reflect the state of the widget
        self.vsb.set(*args)

        # get index of first visible line, and put that in the label
        index = self.text.index("@0,0")
        self.info.configure(text=index)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: How do you overlap widgets/frames in python tkinter?

description: Overlap widgets/frames in python tkinter


code:
class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    def __init__(self,*args,**kwargs):
        forms.Form.__init__(self,*args,**kwargs)
        #first argument, index is the position of the field you want it to come before
        self.fields.insert(0,'sender',forms.EmailField(initial=str(time.time())))

rawDescription: How does Django Know the Order to Render Form Fields?


code:
myQuery.filter().extra(
    select={'myinteger': 'CAST(mycharfield AS UNSIGNED)'}
).order_by('myinteger')

rawDescription: Sorting numerically get order as 1,2,3 not 1, 10, 11, 12 in Django Python


code:
def minimize(self):
    x0 = np.random.rand(50)
    #fmin_tnc(self.func, x0, fprime=self.fprime, messages=0, callback = self.callback)
    import thread
    thread.start_new_thread(fmin_tnc, (self.func, x0), {'fprime':self.fprime, 'messages':0, 'callback':self.callback})

rawDescription: traits ui (enthought) and callback from C

description: Traits ui (enthought) and callback from C


code:
async def main():
    read, write = os.pipe()
    process_1 = await create_subprocess_exec('ls', stdout=write)
    os.close(write)
    process_2 = await create_subprocess_exec('wc', stdin=read, stdout=PIPE)
    os.close(read)
    return await process_2.stdout.read()

rawDescription: Connect two processes started with asyncio.subprocess.create_subprocess_exec()


code:
def sceneQuestion(question, Aone, Atwo, Athree=None, Afour=None, Afive=None):
    print(question)
    global choice
    choice="?"
    print(' ')
    print("  <a> "+Aone)
    print("  <b> "+Atwo)
    if Athree is not None: print (' <c> '+Athree)
    if Afour is not None:  print (' <d> '+Afour)
    if Afive is not None:  print (' <e> '+Afive)

rawDescription: How to have a function continue even if its parameters are not defined

description: Have a function continue even if its parameters are not defined


code:
def myfunc(a,b):
    c = a.intersection(b)
    return bool(c)

rawDescription: Returning boolean if set is empty

description: Returning boolean if set is empty


code:
from PIL import Image
import colorsys

def colorize(im, h, s, l_adjust):
    h /= 360.0
    s /= 100.0
    l_adjust /= 100.0
    if im.mode != 'L':
        im = im.convert('L')
    result = Image.new('RGB', im.size)
    pixin = im.load()
    pixout = result.load()
    for y in range(im.size[1]):
        for x in range(im.size[0]):
            l = pixin[x, y] / 255.99
            l += l_adjust
            l = min(max(l, 0.0), 1.0)
            r, g, b = colorsys.hls_to_rgb(h, l, s)
            r, g, b = int(r * 255.99), int(g * 255.99), int(b * 255.99)
            pixout[x, y] = (r, g, b)
    return result

rawDescription: Python: Want to change image HSL like photoshop


code:
def iter_new_list(old_list):
    for x in old_list:
       if needs_expanding(x):
           for y in expand(x):
               yield y
       else:
           yield x

new_list = list(iter_new_list(old_list))

rawDescription: Expanding elements in a list

description: Expanding elements in a list


code:
import csv
r = csv.reader(open("data.csv"))
line1=r.next()
line2=r.next()

rawDescription: Reading .csv in Python without looping through the whole file?


rawDescription: How to combine 2 numpy.ndarray in numpy

description: Combine 2 numpy.ndarray in numpy


code:
def sparse_rolling_corr(ts, other, window):
    return rolling_corr(ts.dropna(), other[ts.name].dropna(), window).reindex_like(ts)

hey.apply(sparse_rolling_corr, args=(hoo, 4))

rawDescription: How can I use apply with pandas rolling_corr()

description: Use apply with pandas rolling_corr()


code: result = "('%s')" % "','".join(mylist)

rawDescription: How to extract string from python list?

description: Extract string from python list


code:
request_uri = environ['REQUEST_URI']
request_uri = re.sub(r'%2f', '****', request_uri, re.I)
environ['PATH_INFO'] = urllib.unquote(request_uri)

rawDescription: How can I receive percent encoded slashes with Django on App Engine?

description: Receive percent encoded slashes with Django on App Engine


rawDescription: search specific tuples in list and dictionaries

description: Search specific tuples in list and dictionaries


code:
#Function that recursively extracts values out of the object into a flattened dictionary
def flatten_json(data):
    flat = [] #list of flat dictionaries
    def flatten(y):
        out = {}

        def flatten2(x, name=''):
            if type(x) is dict:
                for a in x:
                    if a == "name":
                            flatten2(x["value"], name + x[a] + '_')
                    else:
                        flatten2(x[a], name + a + '_')
            elif type(x) is list:
                for a in x:
                    flatten2(a, name + '_')
            else:
                out[name[:-1]] = x

        flatten2(y)
        return out

#Loop needed to flatten multiple objects
    for i in range(len(data)):
        flat.append(flatten(data[i]).copy())

    return json_normalize(flat)

rawDescription: Nested json to csv - generic approach

description: Nested json to csv - generic approach


code:
MOUSE_LEFTDOWN = 0x0002     # left button down
MOUSE_LEFTUP = 0x0004       # left button up
MOUSE_RIGHTDOWN = 0x0008    # right button down
MOUSE_RIGHTUP = 0x0010      # right button up
MOUSE_MIDDLEDOWN = 0x0020   # middle button down
MOUSE_MIDDLEUP = 0x0040     # middle button up

rawDescription: Right Click in Python using ctypes

description: Right Click in Python using ctypes


code:
class _object: __slots__ = '_MetaSafe__exec', '__dict__'

class MetaSafe(type):

    __REGISTRY = {object: _object}

    @classmethod
    def clone(cls, old):
        return cls(old.__name__, old.__bases__, dict(old.__dict__), old)

    def __new__(cls, name, bases, classdict, old=None):
        # Check on a few classdict keys.
        assert '__new__' not in classdict, '__new__ must not be defined!'
        assert '__slots__' not in classdict, '__slots__ must not be defined!'
        assert '__module__' in classdict, '__module__ must be defined!'
        # Validate all the parent classes.
        valid = []
        for base in bases:
            if base in cls.__REGISTRY:
                valid.append(cls.__REGISTRY[base])
            elif base in cls.__REGISTRY.values():
                valid.append(base)
            else:
                valid.append(cls.clone(base))
        # Wrap callables without thread mark.
        for key, value in classdict.items():
            if callable(value):
                classdict[key] = cls.__wrap(value)
        # Fix classdict and create new class.
        classdict.update({'__new__': cls.__new, '__slots__': (), '__module__':
                          '{}.{}'.format(__name__, classdict['__module__'])})
        cls.__REGISTRY[old] = new = \
            super().__new__(cls, name, tuple(valid), classdict)
        return new

    def __init__(self, name, bases, classdict, old=None):
        return super().__init__(name, bases, classdict)

    @staticmethod
    def __wrap(func):
        @functools.wraps(func)
        def safe(self, *args, **kwargs):
            return self.__exec(func, self, *args, **kwargs)
        return safe

    @classmethod
    def __new(meta, cls, *args, **kwargs):
        self = object.__new__(cls, *args, **kwargs)
        if 'master' in kwargs:
            self.__exec = kwargs['master'].__exec
        else:
            array = tuple(meta.__REGISTRY.values())
            for value in args:
                if isinstance(value, array):
                    self.__exec = value.__exec
                    break
            else:
                self.__exec = Affinity()
        return self

rawDescription: Cannot inherit from multiple classes defining __slots__?


code:
import json
import numpy as np
with open('muti.txt', 'r') as f: arr = json.load(f)
np_arr = np.array([n for subarr in arr for n in subarr]).astype(np.int64)
np_arr

rawDescription: python read 2d in to a 1d array

description: Python read 2d in to a 1d array


rawDescription: Widget Layering in Tkinter

description: Widget Layering in Tkinter


code: "Some sort of general menu^a_sub_menu_title^^pagNumber".split("^")

rawDescription: Split string with caret character in python


code:
def total_cost(i):
    return round(i * 1.0002, 2)

rawDescription: Python insurance rate

description: Python insurance rate


code:
some_dict.setdefault('list_key', []).extend([item1, item2])

a_list.append(element)  # adds an element to the end of a_list
a_list.extend(another_list)  # concatenates a_list with another_list.

rawDescription: Possible to concatenate a list with setdefault in Python?


code:
from collections import OrderedDict

a_dict=OrderedDict((k, v) for k,v in [["a",1],["b",2],["c",3]])
b_dict=OrderedDict((k, v) for k,v in [["A",5],["B",6],["C",7]])

for (k,v),(k1,v1) in zip(a_dict.items(),b_dict.items()):
    print(k,v);
    print(k1,v1);

rawDescription: iterating elements of dictionaries sequentially using single loop

description: Iterating elements of dictionaries sequentially using single loop


code:
s = "AAAGCTTACGAAAAAAACGTA"
s.split("AAAA", 1)[0]

rawDescription: Trim string after 5 of the same chars are found


code:
ns = {"re": "http://exslt.org/regular-expressions"}
query = "//definition//variable[re:test(@name, '^{0}$', 'i')]".format(tag_name)
result = tree.xpath(query, namespaces=ns)

rawDescription: python lxml: case insensitive xpath tag name matching

description: Python lxml: case insensitive xpath tag name matching


code:
for line in fp:
    parts = line.split('|') # or line.split('|', 2) if the last part can contain |
    # use parts[0], parts[1]

rawDescription: How to extract string with regular expressions in python

description: Extract string with regular expressions in python


code:
obj = http.request(
        uri='https://www.googleapis.com/gmail/v1/users/me/drafts',
        method='POST',
        body={
          'message': {
            'raw':base64.urlsafe_b64encode( message.as_string() )
           }
        },
        headers={'content-type':'application/json'}
    )

rawDescription: Create Gmail Draft with a HTTP Request

description: Create Gmail Draft with a HTTP Request


rawDescription: replace any character except for a given list of characters

description: Replace any character except for a given list of characters


code:
import re

def network():
    filepath = '/etc/network/interfaces'
    filedata = []
    regex = r'^address ((\d+\.?)+)'

    with open(filepath, 'r') as f:
        for line in f:
            match = re.match(regex, line)
            if match:
                ipaddr = input('Dirección ip [' + match.group(1) + ']: ')
                line = line.replace(match.group(1), ipaddr)
            filedata.append(line)

    with open(filepath, 'w') as f:
        f.writelines(filedata)

rawDescription: Python - Replace value in a file with re


code:
class Genres(models.Model):
    genre = models.CharField(max_length = 128, unique = True)

    def __str__(self):
        return '%s'%self.genre

rawDescription: Django Rest Framework: Converting a model object number into its corresponding string


code:
TEMPLATE_DIRS = (
   os.path.join(PROJECT_DIR, 'templates').replace('\\', '/'),
   os.path.join(BASE_DIR, 'App1/templates').replace('\\', '/'),
   os.path.join(BASE_DIR, 'App2/templates').replace('\\', '/')
)

rawDescription: Django 1.7 Configure App Directory Templates


code:
def my_function(f, value):
  yield value
  while True:
    value = f(value)
    yield value

rawDescription: yield python add previous function result

description: Yield python add previous function result


code:
with open('mybackup.ab', 'rb') as f:
    f.seek(24)  # skip 24 bytes
    data = f.read()  # read the rest

tarstream = zlib.decompress(data)
tf = tarfile.open(fileobj=io.BytesIO(tarstream))

rawDescription: Python: unpack android backup?

description: Python: unpack android backup


code:
def midnights(dt1, dt2):
    dt1 = dt1.replace(hour=0, minute=0, second=0, microsecond=0)
    dt2 = dt2.replace(hour=0, minute=0, second=0, microsecond=0)
    return (dt2 - dt1).days

rawDescription: Count occurrences of midnight between datetimes


code:
files = glob.glob('main/**/Type 2/*.csv')
dfs = [pd.read_csv(fp) for fp in files]
df = pd.concat(dfs)

rawDescription: how to read files from multiple folders in python

description: Read files from multiple folders in python


code:
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        Button(self, text='Task A', command=self._a).pack()
        Button(self, text='Task B', command=self._b).pack()

        self.current_task = None # this var will hold the current task (red, blue, etc)

    def _a(self):

        self.current_task = 'a' # set the current task

        for i in range(1000):
            if self.current_task == 'a': # only continue this loop if its the current task
                print('a')
                self.update()

    def _b(self):

        self.current_task = 'b'

        for i in range(1000):
            if self.current_task == 'b':
                print('b')
                self.update()

root = Tk()
Example(root).pack()
root.mainloop()

rawDescription: How to stop other processes or finish processes in Python / Tkinter program

description: Stop other processes or finish processes in Python / Tkinter program


code:
import urlparse
url = "http://www.example.org/default.html?ct=32&op=92&item=98"
urlparse.urlsplit(url)
urlparse.parse_qs(urlparse.urlsplit(url).query)
dict(urlparse.parse_qsl(urlparse.urlsplit(url).query))

rawDescription: URL query parameters to dict python

description: URL query parameters to dict python


code:
import matplotlib.pyplot as plt

fig = plt.figure(facecolor='white')
ax = fig.add_subplot(1,1,1)
ax.bar(left=[0,4,5],height=[-100,10,110],color=['red','green','green'],width=0.1)
ax.grid(b=True)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')

plt.show()

rawDescription: Add an x-axis at 0 to a pyplot histogram with negative bars


code:
def main():
    states1 = ['AL', 'AK', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FL']
    print(states1)
    states2 = states1[3:7]
    print(states2)

    list_func(states2)

def list_func(states):
    states.remove('CA')
    states.insert(1,'TX')
    user_st = input('Enter a new state: ')
    states.append(user_st)
    states.reverse()

    print(states)

main()

rawDescription: Python 3.3 - Lists

description: Python 3.3 - Lists


code:
#Models

class ExpedienteConsultaInicial(models.Model):
    #max_legth=10 might be too small
    credencial_consultainicial = models.CharField(max_length=100, null=True, blank=True)

    def __unicode__(self):
        return self.credencial_consultainicial

class ConsultasSubsecuentes(models.Model):
     #related_name is name of attribute of instance of model
     #to (not from!) which ForeignKey points.
     #Like:
     #assuming that `related_name` is 'consultations'
     #instance = ExpedienteConsultaInicial.objects.get(
     #                     credencial_consultainicial='text text text'
     #)
     #instaqnce.consultations.all()
     #So I suggest to change `related_name` to something that will explain what data of this model means in context of model to which it points with foreign key.
     consultasbc_credencial = models.ForeignKey(ExpedienteConsultaInicial,
     related_name='consultations')

#View

def expediente_detalle(request, credencial):
    #Another suggestion is to not abuse CamelCase - look for PEP8
    #It is Python's code-style guide.
    detalle = get_object_or_404(ExpedienteConsultaInicial, credencial_consultainicial=credencial)
    subsequent_consultations = detalle.csb_credencial.all()
    return render(request, 'ExpedienteDetalle.html', {'Expediente_Detalle': detalle, 'consultations': subsequent_consultations})

rawDescription: 2 different search in a view

description: 2 different search in a view


code:
from mpl_toolkits.axes_grid1 import ImageGrid

def get_demo_image():
    import numpy as np
    from matplotlib.cbook import get_sample_data
    f = get_sample_data("axes_grid/bivariate_normal.npy", asfileobj=False)
    z = np.load(f)
    # z is a numpy array of 15x15
    return z, (-3,4,-4,3)

def demo_grid_with_single_cbar(fig):
    """
    A grid of 2x2 images with a single colorbar
    """
    grid = ImageGrid(fig, 132, # similar to subplot(132)
                    nrows_ncols = (2, 2),
                    axes_pad = 0.0,
                    share_all=True,
                    label_mode = "L",
                    cbar_location = "top",
                    cbar_mode="single",
                    )

    Z, extent = get_demo_image()
    for i in range(4):
        im = grid[i].imshow(Z, extent=extent, interpolation="nearest")
    #plt.colorbar(im, cax = grid.cbar_axes[0])
    grid.cbar_axes[0].colorbar(im)

    for cax in grid.cbar_axes:
        cax.toggle_label(False)

    # This affects all axes as share_all = True.
    grid.axes_llc.set_xticks([-2, 0, 2])
    grid.axes_llc.set_yticks([-2, 0, 2])

    for i in range(4):
        ax = grid[i]
        ax.yaxis.set_minor_locator(MultipleLocator(.5))

rawDescription: Changing the MinorLocator when plotting with AxisGrid


code: bool(float('nan'))

rawDescription: Why do "Not a Number" values equal True when cast as boolean in Python/Numpy?


code:
from wagtail.wagtailsnippets.models import register_snippet
from wagtail.wagtailadmin.edit_handlers import StreamFieldPanel

@register_snippet
class Contact(models.Model):
    contact_info = StreamField([
        ('email', MyBlocks.ContactEmail()),
        ('phone', MyBlocks.ContactPhone()),
        ('address', MyBlocks.ContactAddress()),
    ])

    panels = [StreamFieldPanel('contact_info')]

rawDescription: Use of StreamField in Snippets on Wagtail


code:
GPIO.setup(PIN_COIN_INTERRUPT,GPIO.IN)
GPIO.add_event_detect(PIN_COIN_INTERRUPT,GPIO.FALLING,callback=coinEventHandler)
def coinEvenHandler(*arguments):
 try:
   f = open("coin.txt","rt")
   cnt = int(f.read())
   f.close()
 except: # handle file doesn't exist and file doesn't contain an int
   cnt = 0
 f = open("coin.txt","wt")
 f.write(str(cnt))
 f.close()

rawDescription: How to use WebIOPi in existing website

description: Use WebIOPi in existing website


code:
import hashlib
hashlib.md5('some random title').hexdigest()

rawDescription: Better way to create dictionary keys

description: Better way to create dictionary keys


code:
chromosome = [1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0,
              0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0,
              1, 0, 0, 1, 0, 0, 1, 1]

def makeIntList(chrom):
    intlist = []
    for j in range(0, len(chrom), 4):
        intlist.append(chrom[j]*8 + chrom[j+1]*4 + chrom[j+2]*2 + chrom[j+3])
    return intlist

intlist = makeIntList(chromosome)
print(intlist)

rawDescription: Error "'int' object is not subscriptable" though object is a list


code:
class Foo(object):

    @classmethod
    def get_value(self, name):
        # read and return value from database
        return -1
    @classmethod
    def set_value(self,  name, value):
        # store value in database
        pass

def add_metadata_property(name):
    setattr(Foo, name, property(Foo.get_value, Foo.set_value))

add_metadata_property('spam')
f = Foo()
f.spam # works!
f.spam = 2

rawDescription: Dynamically adding a property to a class


code:
from datetime import datetime

sortedArray = sorted(
    unsortedArray,
    key=lambda x: datetime.strptime(x['Created'], '%m/%d/%y %H:%M'), reverse=True
)

rawDescription: How to sort an array of objects by datetime in Python?

description: Sort an array of objects by datetime in Python


code:
import random
#Create a function to randomize a given string
def makerandom(seq):
    return ''.join(random.sample(seq, len(seq)))
def randomDNA(n, probA=0.25, probC=0.25, probG=0.25, probT=0.25):
    notrandom=''
    A=int(n*probA)
    C=int(n*probC)
    T=int(n*probT)
    G=int(n*probG)

#The remainder part here is used to make sure all n are used, as one cannot
#have half an A for example.
    remainder=''
    for i in range(0, n-(A+G+C+T)):
        ramainder+=random.choice("ATGC")
    notrandom=notrandom+ 'A'*A+ 'C'*C+ 'G'*G+ 'T'*T + remainder
    return makerandom(notrandom)

rawDescription: I need a Python Function that will output a random string of 4 different characters when given the desired probabilites of the characters


code:
import sys

from PyQt5.QtCore import Qt, QRectF, QPointF
from PyQt5.QtGui import QBrush, QPainterPath, QPainter, QColor, QPen, QPixmap
from PyQt5.QtWidgets import QGraphicsRectItem, QApplication, QGraphicsView, QGraphicsScene, QGraphicsItem

class GraphicsRectItem(QGraphicsRectItem):

    handleTopLeft = 1
    handleTopMiddle = 2
    handleTopRight = 3
    handleMiddleLeft = 4
    handleMiddleRight = 5
    handleBottomLeft = 6
    handleBottomMiddle = 7
    handleBottomRight = 8

    handleSize = +8.0
    handleSpace = -4.0

    handleCursors = {
        handleTopLeft: Qt.SizeFDiagCursor,
        handleTopMiddle: Qt.SizeVerCursor,
        handleTopRight: Qt.SizeBDiagCursor,
        handleMiddleLeft: Qt.SizeHorCursor,
        handleMiddleRight: Qt.SizeHorCursor,
        handleBottomLeft: Qt.SizeBDiagCursor,
        handleBottomMiddle: Qt.SizeVerCursor,
        handleBottomRight: Qt.SizeFDiagCursor,
    }

    def __init__(self, *args):
        """
        Initialize the shape.
        """
        super().__init__(*args)
        self.handles = {}
        self.handleSelected = None
        self.mousePressPos = None
        self.mousePressRect = None
        self.setAcceptHoverEvents(True)
        self.setFlag(QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QGraphicsItem.ItemIsSelectable, True)
        self.setFlag(QGraphicsItem.ItemSendsGeometryChanges, True)
        self.setFlag(QGraphicsItem.ItemIsFocusable, True)
        self.updateHandlesPos()

    def handleAt(self, point):
        """
        Returns the resize handle below the given point.
        """
        for k, v, in self.handles.items():
            if v.contains(point):
                return k
        return None

    def hoverMoveEvent(self, moveEvent):
        """
        Executed when the mouse moves over the shape (NOT PRESSED).
        """
        if self.isSelected():
            handle = self.handleAt(moveEvent.pos())
            cursor = Qt.ArrowCursor if handle is None else self.handleCursors[handle]
            self.setCursor(cursor)
        super().hoverMoveEvent(moveEvent)

    def hoverLeaveEvent(self, moveEvent):
        """
        Executed when the mouse leaves the shape (NOT PRESSED).
        """
        self.setCursor(Qt.ArrowCursor)
        super().hoverLeaveEvent(moveEvent)

    def mousePressEvent(self, mouseEvent):
        """
        Executed when the mouse is pressed on the item.
        """
        self.handleSelected = self.handleAt(mouseEvent.pos())
        if self.handleSelected:
            self.mousePressPos = mouseEvent.pos()
            self.mousePressRect = self.boundingRect()
        super().mousePressEvent(mouseEvent)

    def mouseMoveEvent(self, mouseEvent):
        """
        Executed when the mouse is being moved over the item while being pressed.
        """
        if self.handleSelected is not None:
            self.interactiveResize(mouseEvent.pos())
        else:
            super().mouseMoveEvent(mouseEvent)

    def mouseReleaseEvent(self, mouseEvent):
        """
        Executed when the mouse is released from the item.
        """
        super().mouseReleaseEvent(mouseEvent)
        self.handleSelected = None
        self.mousePressPos = None
        self.mousePressRect = None
        self.update()

    def boundingRect(self):
        """
        Returns the bounding rect of the shape (including the resize handles).
        """
        o = self.handleSize + self.handleSpace
        return self.rect().adjusted(-o, -o, o, o)

    def updateHandlesPos(self):
        """
        Update current resize handles according to the shape size and position.
        """
        s = self.handleSize
        b = self.boundingRect()
        self.handles[self.handleTopLeft] = QRectF(b.left(), b.top(), s, s)
        self.handles[self.handleTopMiddle] = QRectF(b.center().x() - s / 2, b.top(), s, s)
        self.handles[self.handleTopRight] = QRectF(b.right() - s, b.top(), s, s)
        self.handles[self.handleMiddleLeft] = QRectF(b.left(), b.center().y() - s / 2, s, s)
        self.handles[self.handleMiddleRight] = QRectF(b.right() - s, b.center().y() - s / 2, s, s)
        self.handles[self.handleBottomLeft] = QRectF(b.left(), b.bottom() - s, s, s)
        self.handles[self.handleBottomMiddle] = QRectF(b.center().x() - s / 2, b.bottom() - s, s, s)
        self.handles[self.handleBottomRight] = QRectF(b.right() - s, b.bottom() - s, s, s)

    def interactiveResize(self, mousePos):
        """
        Perform shape interactive resize.
        """
        offset = self.handleSize + self.handleSpace
        boundingRect = self.boundingRect()
        rect = self.rect()
        diff = QPointF(0, 0)

        self.prepareGeometryChange()

        if self.handleSelected == self.handleTopLeft:

            fromX = self.mousePressRect.left()
            fromY = self.mousePressRect.top()
            toX = fromX + mousePos.x() - self.mousePressPos.x()
            toY = fromY + mousePos.y() - self.mousePressPos.y()
            diff.setX(toX - fromX)
            diff.setY(toY - fromY)
            boundingRect.setLeft(toX)
            boundingRect.setTop(toY)
            rect.setLeft(boundingRect.left() + offset)
            rect.setTop(boundingRect.top() + offset)
            self.setRect(rect)

        elif self.handleSelected == self.handleTopMiddle:

            fromY = self.mousePressRect.top()
            toY = fromY + mousePos.y() - self.mousePressPos.y()
            diff.setY(toY - fromY)
            boundingRect.setTop(toY)
            rect.setTop(boundingRect.top() + offset)
            self.setRect(rect)

        elif self.handleSelected == self.handleTopRight:

            fromX = self.mousePressRect.right()
            fromY = self.mousePressRect.top()
            toX = fromX + mousePos.x() - self.mousePressPos.x()
            toY = fromY + mousePos.y() - self.mousePressPos.y()
            diff.setX(toX - fromX)
            diff.setY(toY - fromY)
            boundingRect.setRight(toX)
            boundingRect.setTop(toY)
            rect.setRight(boundingRect.right() - offset)
            rect.setTop(boundingRect.top() + offset)
            self.setRect(rect)

        elif self.handleSelected == self.handleMiddleLeft:

            fromX = self.mousePressRect.left()
            toX = fromX + mousePos.x() - self.mousePressPos.x()
            diff.setX(toX - fromX)
            boundingRect.setLeft(toX)
            rect.setLeft(boundingRect.left() + offset)
            self.setRect(rect)

        elif self.handleSelected == self.handleMiddleRight:
            print("MR")
            fromX = self.mousePressRect.right()
            toX = fromX + mousePos.x() - self.mousePressPos.x()
            diff.setX(toX - fromX)
            boundingRect.setRight(toX)
            rect.setRight(boundingRect.right() - offset)
            self.setRect(rect)

        elif self.handleSelected == self.handleBottomLeft:

            fromX = self.mousePressRect.left()
            fromY = self.mousePressRect.bottom()
            toX = fromX + mousePos.x() - self.mousePressPos.x()
            toY = fromY + mousePos.y() - self.mousePressPos.y()
            diff.setX(toX - fromX)
            diff.setY(toY - fromY)
            boundingRect.setLeft(toX)
            boundingRect.setBottom(toY)
            rect.setLeft(boundingRect.left() + offset)
            rect.setBottom(boundingRect.bottom() - offset)
            self.setRect(rect)

        elif self.handleSelected == self.handleBottomMiddle:

            fromY = self.mousePressRect.bottom()
            toY = fromY + mousePos.y() - self.mousePressPos.y()
            diff.setY(toY - fromY)
            boundingRect.setBottom(toY)
            rect.setBottom(boundingRect.bottom() - offset)
            self.setRect(rect)

        elif self.handleSelected == self.handleBottomRight:

            fromX = self.mousePressRect.right()
            fromY = self.mousePressRect.bottom()
            toX = fromX + mousePos.x() - self.mousePressPos.x()
            toY = fromY + mousePos.y() - self.mousePressPos.y()
            diff.setX(toX - fromX)
            diff.setY(toY - fromY)
            boundingRect.setRight(toX)
            boundingRect.setBottom(toY)
            rect.setRight(boundingRect.right() - offset)
            rect.setBottom(boundingRect.bottom() - offset)
            self.setRect(rect)

        self.updateHandlesPos()

    def shape(self):
        """
        Returns the shape of this item as a QPainterPath in local coordinates.
        """
        path = QPainterPath()
        path.addRect(self.rect())
        if self.isSelected():
            for shape in self.handles.values():
                path.addEllipse(shape)
        return path

    def paint(self, painter, option, widget=None):
        """
        Paint the node in the graphic view.
        """
        painter.setBrush(QBrush(QColor(255, 0, 0, 100)))
        painter.setPen(QPen(QColor(0, 0, 0), 1.0, Qt.SolidLine))
        painter.drawRect(self.rect())

        painter.setRenderHint(QPainter.Antialiasing)
        painter.setBrush(QBrush(QColor(255, 0, 0, 255)))
        painter.setPen(QPen(QColor(0, 0, 0, 255), 1.0, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
        for handle, rect in self.handles.items():
            if self.handleSelected is None or handle == self.handleSelected:
                painter.drawEllipse(rect)

def main():

    app = QApplication(sys.argv)

    grview = QGraphicsView()
    scene = QGraphicsScene()
    scene.setSceneRect(0, 0, 680, 459)

    scene.addPixmap(QPixmap('01.png'))
    grview.setScene(scene)

    item = GraphicsRectItem(0, 0, 300, 150)
    scene.addItem(item)

    grview.fitInView(scene.sceneRect(), Qt.KeepAspectRatio)
    grview.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: Resize a QGraphicsItem with the mouse

description: Resize a QGraphicsItem with the mouse


code: doc_topic_distrib = lda.transform(tf)

rawDescription: Topic modelling - Assign a document with top 2 topics as category label - sklearn Latent Dirichlet Allocation


code:
import prog1
creature_obj = prog1.new_creature() # where new_creature is a class in prog1
...

rawDescription: Python programs communicating

description: Python programs communicating


rawDescription: best way to assign variable length strings to list elements in python3.4

description: Assign variable length strings to list elements in python3.4


code:
_PCEP_ERR_types = {1: "PCEP session establishment failure",
                   3: "Unknown Object"}

_PCEP_ERR_values = {
    1: {1: "Reception of an invalid Open message or a non Open message",
        2: "No Open message received before the expiration of the OpenWait timer",
        3: "Unacceptable and non-negotiable session characteristics",
        4: "Unacceptable but negotiable session characteristics",
        5: "Reception of a second Open message with still unacceptable session characteristics",
        6: "Reception of a PCErr message proposing unacceptable session characteristics",
        7: "No Keepalive or PCErr message received before the expiration of the KeepWait timer"},
    3: {1: "Unrecognized object class",
        2: "Unrecognized object Type"}
}

class PCEPErrorObject(Packet):
    '''PCEP-ERROR Object to notify error conditions in a PCEP session'''
    name = 'PCEP-ERROR OBJECT'
    common_object = PCEPCommonObjectHeader(oclass=13,oType=1)
    fields_desc =     [PacketField("common_object_header",common_object,PCEPCommonObjectHeader),
                       ByteField("Reserved",0),
                       ByteField("flags",0),
                       ByteEnumField("ET", 0, _PCEP_ERR_types),
                       MultiEnumField("EV", 0, _PCEP_ERR_values,
                                      depends_on=lambda pkt: pkt.ET,
                                      fmt="B")]

rawDescription: scapy: Unable to pass dict with sub keys to ByteEnum Field

description: Scapy: Unable to pass dict with sub keys to ByteEnum Field


code:
import random
classes = (RoomSpider, RoomSoldier, RoomDragon,
           RoomElephant, RoomPixie)

# choose a random class from the list and instantiate it
instance = random.choice(classes)()

rawDescription: Create an instance of a random class

description: Create an instance of a random class


code:
def find_file(filename, search_path):
    for dirpath, dirnames, filenames in os.walk(search_path):
        if filename in filenames:
            return 1
    return 0

rawDescription: Python recursively search directory for presence of file


code:
widgetForm, baseClass= uic.loadUiType("addTilesWidget.ui")

class windowTest(baseClass, widgetForm):
    def __init__(self, parent = None):
        super(windowTest, self).__init__(parent)
        self.setupUi(self)

rawDescription: PyQt4 custom widget (uic loaded) added to layout is invisible


code:
from lxml.etree import fromstring
# We have XMLs with different root tag
tree1 = fromstring("<model><foo/><bar/></model>")
tree2 = fromstring("<page><baz/><blah/></page>")
# We have different treatments
def modelTreatement(etree):
    return etree.xpath('//bar')
def pageTreatment(etree):
    return etree.xpath('//blah')
# Here is a recipe to read the root tag
tree1.getroottree().getroot().tag
tree2.getroottree().getroot().tag
# So, by building an appropriated dict :
tag_to_treatment_map = {'model': modelTreatement, 'page': pageTreatment}
# You can run the right method on the right tree
for tree in [tree1, tree2]:
    tag_to_treatment_map[tree.getroottree().getroot().tag](tree)

rawDescription: How to detect starting tag of xml and then parse and objectify

description: Detect starting tag of xml and then parse and objectify


code:
import os
import re
import subprocess

def available_cpu_count():
    """ Number of available virtual or physical CPUs on this system, i.e.
    user/real as output by time(1) when called with an optimally scaling
    userspace-only program"""

    # cpuset
    # cpuset may restrict the number of *available* processors
    try:
        m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',
                      open('/proc/self/status').read())
        if m:
            res = bin(int(m.group(1).replace(',', ''), 16)).count('1')
            if res > 0:
                return res
    except IOError:
        pass

    # Python 2.6+
    try:
        import multiprocessing
        return multiprocessing.cpu_count()
    except (ImportError, NotImplementedError):
        pass

    # http://code.google.com/p/psutil/
    try:
        import psutil
        return psutil.cpu_count()   # psutil.NUM_CPUS on old versions
    except (ImportError, AttributeError):
        pass

    # POSIX
    try:
        res = int(os.sysconf('SC_NPROCESSORS_ONLN'))

        if res > 0:
            return res
    except (AttributeError, ValueError):
        pass

    # Windows
    try:
        res = int(os.environ['NUMBER_OF_PROCESSORS'])

        if res > 0:
            return res
    except (KeyError, ValueError):
        pass

    # jython
    try:
        from java.lang import Runtime
        runtime = Runtime.getRuntime()
        res = runtime.availableProcessors()
        if res > 0:
            return res
    except ImportError:
        pass

    # BSD
    try:
        sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],
                                  stdout=subprocess.PIPE)
        scStdout = sysctl.communicate()[0]
        res = int(scStdout)

        if res > 0:
            return res
    except (OSError, ValueError):
        pass

    # Linux
    try:
        res = open('/proc/cpuinfo').read().count('processor\t:')

        if res > 0:
            return res
    except IOError:
        pass

    # Solaris
    try:
        pseudoDevices = os.listdir('/devices/pseudo/')
        res = 0
        for pd in pseudoDevices:
            if re.match(r'^cpuid@[0-9]+$', pd):
                res += 1

        if res > 0:
            return res
    except OSError:
        pass

    # Other UNIXes (heuristic)
    try:
        try:
            dmesg = open('/var/run/dmesg.boot').read()
        except IOError:
            dmesgProcess = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE)
            dmesg = dmesgProcess.communicate()[0]

        res = 0
        while '\ncpu' + str(res) + ':' in dmesg:
            res += 1

        if res > 0:
            return res
    except OSError:
        pass

    raise Exception('Can not determine number of CPUs on this system')

rawDescription: How to find out the number of CPUs using python

description: Find out the number of CPUs using python


code:
from gi.repository import Gtk

class Application(object):
    def __init__(self):
        self.window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
        self.window.set_title("Alignment Editor")
        self.window.set_default_size(200, 150)
        self.window.connect("delete_event", lambda w,e: Gtk.main_quit())

        self.row = ["a", "b"]
        self.store = Gtk.ListStore(*[str]*len(self.row)) #create len(word) columns
        self.store.append(self.row)

        cra = Gtk.CellRendererText()
        twcolumna = Gtk.TreeViewColumn("Column a")
        twcolumna.pack_start(cra, True)
        twcolumna.add_attribute(cra, 'text', 0)

        crb = Gtk.CellRendererText()
        twcolumnb = Gtk.TreeViewColumn("Column b")
        twcolumnb.pack_start(crb, True)
        twcolumnb.add_attribute(crb, 'text', 1)

        self.treeview = Gtk.TreeView(self.store)

        self.treeview.append_column(twcolumna)
        self.treeview.append_column(twcolumnb)

        self.treeview.set_reorderable(True)
        self.window.add(self.treeview)
        self.window.show_all()

if __name__ == "__main__":
    Application()
    Gtk.main()

rawDescription: GTK TreeView: 20-line minimal script won't show TreeView itself within the window: what's wrong?


code:
from django.db.models import F

active_tickets = Ticket.objects.filter(active_at__lte=now,
                                       active_at__gt=now-F('duration'))

rawDescription: Using Django, how I can achieve this in a single query?


code:
from Tkinter import *

class AnimatedGif(object):
    """ Animated GIF Image Container. """
    def __init__(self, image_file_path):
        self.image_file_path = image_file_path
        self._frames = []
        self._load()

    def __len__(self):
        return len(self._frames)

    def __getitem__(self, frame_num):
        return self._frames[frame_num]

    def _load(self):
        """ Read in all the frames of a multi-frame gif image. """
        while True:
            frame_num = len(self._frames)  # number of next frame to read
            try:
                frame = PhotoImage(file=self.image_file_path,
                                   format="gif -index {}".format(frame_num))
            except TclError:
                break
            self._frames.append(frame)

def update_label_image(label, ani_img, ms_delay, frame_num):
    global cancel_id
    label.configure(image=ani_img[frame_num])
    frame_num = (frame_num+1) % len(ani_img)
    cancel_id = root.after(
        ms_delay, update_label_image, label, ani_img, ms_delay, frame_num)

def enable_animation():
    global cancel_id
    ms_delay = 1000 // len(ani_img)
    cancel_id = root.after(
        ms_delay, update_label_image, label, ani_img, ms_delay, 0)

def cancel_animation():
    global cancel_id
    if cancel_id is not None:
        root.after_cancel(cancel_id)
        cancel_id = None

cancel_id = None
root = Tk()
root.title("Animation Demo")

image_file_path = "small_globe.gif"
ani_img = AnimatedGif(image_file_path)

label = Label(image=ani_img[0])  # display first frame initially
label.pack()
start_animation = Button(root, text="start animation", command=enable_animation)
start_animation.pack()
stop_animation = Button(root, text="stop animation", command=cancel_animation)
stop_animation.pack()
exit_program = Button(root, text="exit", command=root.quit)
exit_program.pack()

root.geometry("250x125+100+100")
root.mainloop()

rawDescription: Tkinter animation will not work

description: Tkinter animation will not work


code:
ld = [{'a': 10, 'b': 20}, {'p': 10, 'u': 100}]
[[(k,v) for k,v in d.items()] for d in ld]
[[(k,v) for k,v in d.items() if k not in ['b','u']] for d in ld]

rawDescription: List of dictionaries with comprehension in python


code:
reporter = Reporters.objects.get(pk=reporter.pk)
# Or, more succinctly:
reporter.refresh_from_db()

rawDescription: Django Incrementing Model Instance Attribute in Views w/ F()+1 and Accessing from Template


code:
def rand_sample(arr, nr, nc):
    "sample a nr x nc submatrix starting from a random element of arr, with wrap"
    r, c = arr.shape
    i, j = np.random.randint(r), np.random.randint(c)
    r = np.arange(i, i+nr) % r
    c = np.arange(j, j+nc) % c
    return arr[r][:,c]

rawDescription: Efficient Numpy sampling of subarray in a wrapped 2D array


rawDescription: How to get objects if user is in a field of another django model's many-to-many field?

description: Get objects if user is in a field of another django model's many-to-many field


code:
from django.template.defaultfilters import slice_filter

@register.filter("slice_default", is_safe=True)
def slice_filter_20(value, arg=":20"):
    return slice_filter(value, arg)

rawDescription: Django: set default behavior in include template


code:
import pickle
from os import path

user_to_delete = 'user2'

# Open the database if it exists, otherwise create one...
if path.isfile('database.db'):
    with open('database.db','rb') as f:
        db = pickle.load(f)
else: # Create some database.db with users&passwords to test this program..
    db = {'user1':'password1', 'user2':'password2', 'user3':'password3'}
    with open('database.db', 'wb') as f:
        pickle.dump(db, f)

# try to delete the given user, handle if the user doesn't exist.
try:
    del db[user_to_delete]
except KeyError:
    print("{user} doesn't exist in db".format(user=user_to_delete))

# write the 'new' db to the file.
with open('database.db', 'wb') as f:
    pickle.dump(db, f)

rawDescription: Python remove entry from pickle saved data


code:
from collections import defaultdict
d = defaultdict(int)
for item in collection:
    d[(item.name, item.path)] += item.bytes

rawDescription: Aggregating objects based on it's two data members in python


code:
skip = 2
with open('path/to/infile') as infile:
    for _ in range(skip):
        infile.readline()
    answer = [[float(num) for num in line.strip()[1:-1].split(',')] for line in infile]

rawDescription: Parsing a data file into a 2d array

description: Parsing a data file into a 2d array


code:
class ClassA():
    class Foo():
        pass

    @classmethod
    def getFoo(cls):
        return cls.Foo

rawDescription: Inheritance and accessing parent class in unbound method in python


rawDescription: is it possible to launch a window that does not stop the mainloop in python

description: Is it possible to launch a window that does not stop the mainloop in python


rawDescription: AxesGrid with imshow : do plots have to have the same extent?


code:
def revers_e(s1, s2):
    print(*[i for i in s1 if i in s2])    # Print all characters to be deleted from s1
    s1 = ''.join([i for i in s1 if i not in s2])    # Delete them from s1

rawDescription: How can I delete the letter that occurs in the two strings using python?

description: Delete the letter that occurs in the two strings using python


code: DF.LastFirst = DF.LastFirst.str.replace(' ,', ',')

rawDescription: Pandas DF: Replace Middle Part of String


code:
from __future__ import print_function
import sys, warnings

from matplotlib.cbook import flatten, is_string_like, exception_to_str, \
     silent_list, iterable, dedent

import matplotlib as mpl
# make mpl.finance module available for backwards compatability, in case folks
# using pylab interface depended on not having to import it
import matplotlib.finance

from matplotlib.dates import date2num, num2date,\
        datestr2num, strpdate2num, drange,\
        epoch2num, num2epoch, mx2num,\
        DateFormatter, IndexDateFormatter, DateLocator,\
        RRuleLocator, YearLocator, MonthLocator, WeekdayLocator,\
        DayLocator, HourLocator, MinuteLocator, SecondLocator,\
        rrule, MO, TU, WE, TH, FR, SA, SU, YEARLY, MONTHLY,\
        WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY, relativedelta

import matplotlib.dates  # Do we need this at all?

# bring all the  symbols in so folks can import them from
# pylab in one fell swoop

## We are still importing too many things from mlab; more cleanup is needed.

from matplotlib.mlab import griddata, stineman_interp, slopes, \
    inside_poly, poly_below, poly_between, \
    is_closed_polygon, path_length, distances_along_curve, vector_lengths

from matplotlib.mlab import window_hanning, window_none,  detrend, demean, \
     detrend_mean, detrend_none, detrend_linear, entropy, normpdf, levypdf, \
     find, longest_contiguous_ones, longest_ones, prepca, \
     prctile, prctile_rank, \
     center_matrix, rk4, bivariate_normal, get_xyz_where, \
     get_sparse_matrix, dist, \
     dist_point_to_segment, segments_intersect, fftsurr, movavg, \
     exp_safe, \
     amap, rms_flat, l1norm, l2norm, norm_flat, frange,  identity, \
     base_repr, binary_repr, log2, ispower2, \
     rec_append_fields, rec_drop_fields, rec_join, csv2rec, rec2csv, isvector

import matplotlib.mlab as mlab
import matplotlib.cbook as cbook

from numpy import *
from numpy.fft import *
from numpy.random import *
from numpy.linalg import *

from matplotlib.pyplot import *

# provide the recommended module abbrevs in the pylab namespace
import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma

# don't let numpy's datetime hide stdlib
import datetime

if sys.version_info > (2, 6, 0):
    bytes = __builtins__['bytes']

rawDescription: pylab.X vs pylab.plt.X

description: Pylab.X vs pylab.plt.X


code:
di['earnlower'] = di['earncat'].apply(lambda x: int(x[1:].split(',')[0]))
di['earnhigher'] = di['earncat'].apply(lambda x: int(x[:-2].split(',')[1]))

di_everyone=di.groupby(['earnlower', 'earnhigher']).sum()[['counts']]

rawDescription: pandas: how to sort results of groupby using a pd.cut categorical variable

description: Pandas: how to sort results of groupby using a pd.cut categorical variable


code: added = [f for f in after if not f in before and '_status' not in f]

rawDescription: If list object contains something remove from list


code:
from scipy.integrate import quad
a = 0
b = 1
[quad(lambda x, d: x/(d**2)-x**2, a, b, args=d) for d in range(2, 5)]

rawDescription: Integration using qudrature

description: Integration using qudrature


rawDescription: Name of view inside decorator_from_middleware class


code:
import numpy as np
matrix = np.zeros((3,3))

# Setting a row
matrix[1] = 10

# Setting a column
matrix[:,1] = 20

rawDescription: Modifying a matrix using Nested list comprehension in python


code:
import pprint
import subprocess

df = subprocess.check_output('lsusb', shell=True)
device_ids = []
for line in filter(lambda s: s.startswith('Bus'), df.split('\n')):
    businfo, id, _ = line.split(':')
    id = id.split()[1]
    device_ids.append(id)

pprint.pprint(device_ids)

rawDescription: How to get usb serial number python

description: Get usb serial number python


code:
from matplotlib.pyplot import savefig
savefig( 'stitched.png', dpi=400 )

rawDescription: Import png files and save as subplots using matplotlib


code:
import turtle

def draw_square(x, y):
    global target_region

    turtle.penup()
    turtle.goto(x, y)
    turtle.setheading(0)
    turtle.pendown()
    square = []
    for i in range(4):
        square.append(turtle.pos())  # Save turtle coords
        turtle.forward(30)
        turtle.left(90)

    # Find min and max coordinates of region
    min_x = min(square, key=lambda p: p[0])[0]
    min_y = min(square, key=lambda p: p[1])[1]
    max_x = max(square, key=lambda p: p[0])[0]
    max_y = max(square, key=lambda p: p[1])[1]
    target_region = [min_x, min_y, max_x, max_y]

    turtle.hideturtle()
    turtle.onscreenclick(check_click)  # Switch to next event handler

def check_click(x, y):
    if (target_region[0] <= x <= target_region[2] and
        target_region[1] <= y <= target_region[3]):  # Within square region?
        within_square_region_function()  # Call activate function

def within_square_region_function():
    print('clicked in square')

turtle.onscreenclick(draw_square)  # Set initial event handler
turtle.mainloop()

rawDescription: Define a region in python turtle

description: Define a region in python turtle


code:
from openpyxl import load_workbook,Workbook
book  = load_workbook(filename=file_name)
sheet = book['sheet name']
for row in sheet.rows:
    col_0           = row[0].value
    col_1           = row[1].value

rawDescription: xlrd data extraction python

description: Xlrd data extraction python


code:
from Tkinter import *

root = Tk()
entry = MaxLengthEntry(root, maxlength=10)
entry.pack(side=LEFT)
root.mainloop()

rawDescription: How to set maximum width in characters for the Text widget?

description: Set maximum width in characters for the Text widget


code: import x as y

rawDescription: Module and Parameter with the same name

description: Module and Parameter with the same name


code:
def custom_path(instance, filename):
    path = os.path.join('upload', 'media', slugify(instance.student.user.username))
    try:
        os.path.mkdir(path)
    except OSError:
        # path already exists
        pass

rawDescription: how to search for folder name under media - or create one - django

description: Search for folder name under media - or create one - django


code:
class Task(Base):
    __tablename__ = 'tasks'
    id = Column(Integer, primary_key=True)
    hostID = Column(Integer, ForeignKey('hosts.id'))
    name = Column(String)
    host = relationship("Host", backref=backref("tasks", cascade_backrefs=False))

    def __init__(self, host, name):
        self.host = host
        self.name = name

rawDescription: Creating non persistent objects with SQLAlchemy: wrong employment of backref in a relationship?


code:
from csv import DictWriter

players = [{'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player1', 'bank': 0.06},
{'dailyWinners': 3, 'dailyFreePlayed': 2, 'user': 'Player2', 'bank': 4.0},
{'dailyWinners': 1, 'dailyFree': 2, 'user': 'Player3', 'bank': 3.1},
{'dailyWinners': 3, 'dailyFree': 2, 'user': 'Player4', 'bank': 0.32}]

with open('spreadsheet.csv','w') as outfile:
    writer = DictWriter(outfile, ('dailyWinners','dailyFreePlayed','dailyFree','user','bank'))
    writer.writeheader()
    writer.writerows(players)

rawDescription: How do I output a list of dictionaries to an excel sheet?

description: Output a list of dictionaries to an excel sheet


code:
legend = ax1.legend(loc=0, ncol=1, bbox_to_anchor=(0, 0, 1, 1),
           prop = fontP,fancybox=True,shadow=False,title='LEGEND')

plt.setp(legend.get_title(),fontsize='xx-small')

rawDescription: How to set font size of Matplotlib axis Legend?

description: Set font size of Matplotlib axis Legend


rawDescription: Django - Advanced query depending of the relationships of a model


code:
import numpy as np
import matplotlib.pyplot as plt
import time

@interact
def _(f=(1,10,1)):
    plt.cla()
    n = 100
    T = 1
    dt = T/n

    x = np.arange(1, step=dt)

    W = np.zeros(n, np.dtype(float))

    t = np.arange(2.8,3.0,0.1)
    l = np.sqrt(2*t*ln(ln(t)))
    plt.plot(l) # <= add subplot

    # Z variable, N(0,1)
    mu, sig = 0, 1

    for ITER in range(1, f+1):
        for i in range(1, len(W)):
            W[i] = W[i-1] + np.random.normal(mu, sig) * np.sqrt(dt)
        plt.plot(x,W)
    plt.show()

rawDescription: show many graphics in one plot (sage)

description: Show many graphics in one plot (sage)


rawDescription: Giving value to text boxes in forms using Flask and Python


code:
from reportlab.platypus import BaseDocTemplate, Frame, Paragraph, PageBreak, PageTemplate
from reportlab.lib.styles import getSampleStyleSheet
import random

words = "lorem ipsum dolor sit amet consetetur sadipscing elitr sed diam nonumy eirmod tempor invidunt ut labore et".split()

styles=getSampleStyleSheet()
Elements=[]

doc = BaseDocTemplate('basedoc.pdf',showBoundary=1)

#Two Columns
frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col1')
frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='col2')

Elements.append(Paragraph(" ".join([random.choice(words) for i in range(1000)]),styles['Normal']))
doc.addPageTemplates([PageTemplate(id='TwoCol',frames=[frame1,frame2]), ])

#start the construction of the pdf
doc.build(Elements)

rawDescription: Reportlab. Floating Text with two Columns


code:
import re
s = "Apple apple apple what is a watermelon have to do to get an apple?"
re.sub(r'(?i)^(.*?)\b(?:Watermelon|Pear|Peach|Orange|Apple|Banana|Grapes)\b', r'\1brussel sprouts', s)
re.sub(r'(?i)^(.*?)\b(?:Watermelon|Pear|Peach|Orange|Apple|Banana|Grapes)\b', r'\1brussel sprouts', 'The apple likes orange')

rawDescription: Python: Replace First Word That Shows Up with Another Word


code:
from timeit import timeit
timeit('range(100000)[:]', number=1000)
timeit('range(100000)', number=1000)

rawDescription: pymongo find() vs find()[:]?

description: Pymongo find() vs find()[:]