code:
import json, subprocess

def remove_unused_snaps(region):
    line = 'aws ec2 describe-images --region {} --owners self'.format(region)
    p = subprocess.Popen(line.split(),
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    obj = json.loads(out.decode("utf-8"))

    snaps_used = set(i['BlockDeviceMappings'][0]['Ebs']['SnapshotId'] for i in obj['Images'])

    line = 'aws ec2 describe-snapshots --region {} --owner-ids self'.format(region)
    p = subprocess.Popen(line.split(),
                         stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    obj = json.loads(out.decode("utf-8"))

    snaps_old = set(i['SnapshotId'] for i in obj['Snapshots'])

    line = 'aws ec2 delete-snapshot --region {} --snapshot-id'.format(region)
    for snap in list(snaps_old - snaps_used):
        p = subprocess.Popen(line.split() + [snap],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate()
        print(snap, out, err)

rawDescription: Remove unused Amazon EC2 Snapshots

description: Remove unused Amazon EC2 Snapshots


code:
from django.utils.safestring import mark_safe

@register.filter(name='shorten')
def shorten(content, post_id):
    #will show up to the first 500 characters of the post content
    if len(content) > 500:
        output = "{0}... (cont.)".format(content[:500], post_id)
    else:
        output = "{0}".format(content)

    return mark_safe(output)

rawDescription: Include a URL in a Django template tag

description: Include a URL in a Django template tag


code:
a = ('one', 'two')
b = ('ten', 'ten')
z = [('four', 'five', 'six'), ('one', 'two', 'twenty')]
next((x[2] for x in z if x[:2] == a), None)
next((x[2] for x in z if x[:2] == b), None)

rawDescription: Python - Matching

description: Python - Matching


code:
def has_user_defined_init_in(clazz):
    return "__init__" in clazz.__dict__

rawDescription: Determinate if class has user defined __init__


code:
Read_data = open("finename.txt","r")
Write_data = open('newfile.txt', 'a')

for text_line in Read_data.readline():
    text_line = '$' + text_line.strip() + '$\n'
    Write_data.write(text_line)

Write_data.close()

rawDescription: Trying to insert a character $ for beginning and end of a string using python, but i got them just in the beginning


code:
import matplotlib.pyplot as plt

plt.plot(range(20))
plt.savefig("1.png")

plt.xlim(0,10)
plt.savefig("2.png")

plt.xlim(0,30)
plt.savefig("3.png")

rawDescription: Save images of a matplotlib figure at different coordinates?


code:
import urllib2
import mmap

# Open the file as a memory mapped string. Looks like a string, but
# actually accesses the file behind the scenes.
f = open('somelargefile.zip','rb')
mmapped_file_as_string = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)

# Do the request
request = urllib2.Request(url, mmapped_file_as_string)
request.add_header("Content-Type", "application/zip")
response = urllib2.urlopen(request)

#close everything
mmapped_file_as_string.close()
f.close()

rawDescription: Python: HTTP Post a large file with streaming


code:
import itertools
def isplit(iterable,splitters):
    return [list(g) for k,g in itertools.groupby(iterable,lambda x:x in splitters) if not k]

l = ['19841018 ID1\n', ' Plunging oil... \n', 'cut in the price \n', '\n', '19841018 ID2\n', ' The U.S. dollar...  \n', 'the foreign-exchange markets \n', 'late New York trading \n', '\n']
res = {}
for sublist in isplit(l,('\n',)):
    id_parts = sublist[0].split()
    story    = ' '.join (sentence.strip() for sentence in sublist[1:])
    res[id_parts[1].strip()] = [id_parts[0].strip(), story]

res

rawDescription: Python: Parse a list of strings into a dictionnary


code:
dtype={
    'names' : ('name','offset','bit_span'),
    'formats' : ('U20','U20','U20')}

instance= np.zeros(3,dtype)

instance[0]=('register','00','0')
instance[1]=('register_1','02','0')
instance[2]=('register_2','04','0')

instance[1]['offset']
# '02'

rawDescription: In a numpy record array how to access certain element value in python


code:
from numpy import *
a = array([1,0,1,-1])
nonzero(a!=0)
nonzero((a != 0) and (a < 0))
nonzero((a != 0) & (a < 0))
where((a != 0) & (a < 0))

rawDescription: Finding elements in a numpy array with multiple criteria


code:
txt = fig.suptitle('A test title')
txt.set_text('A better title')
plt.draw()

rawDescription: Matplotlib suptitle prints over old title


rawDescription: Get user group as string in django

description: Get user group as string in django


code:
import boto
c = boto.connect_s3()
bucket = c.lookup('mybucketname')
l = [(k.last_modified, k) for k in bucket]
key_to_download = sorted(l, cmp=lambda x,y: cmp(x[0], y[0]))[-1][1]
key_to_download.get_contents_to_filename('myfile')

rawDescription: Boto script to download latest file from s3 bucket


code:
nowDate = date.today()

for line in sourceFile:
    s = re.compile('(\d{2}\/\d{2}\/\d{4})\s(C\d{3}\sS\d{3})')
    s1 = re.search(s, line)
    if s1:
        date = s1.group(1)
        date = datetime.strptime(date, '%d/%m/%Y')
        date = date.date()
        endDate = date + timedelta(days=731)
        if endDate <= nowDate:
            fileLst.write(s1.group())
            fileLst.write('\n')
        else:
            print ('not ready: ', date.strftime('%d-%m-%Y'))
            ntrdLst.write(s1.group(1))
            ntrdLst.write('\n')

rawDescription: Searching and sorting in Python

description: Searching and sorting in Python


code:
import ctypes
p1= ctypes.c_char_p("hi mom")
ctypes.cast( p1, ctypes.c_void_p )

rawDescription: Python: converting strings for use with ctypes.c_void_p()


code:
import demjson
demjson.decode('{ hotel: { id: "123", name: "hotel_name"} }')

rawDescription: How to decode an invalid json string in python

description: Decode an invalid json string in python


code:
df = pd.read_csv('.../temp.csv')

# Replace quotes
[df.replace(x, 0, inplace=True) for x in ['""', "''"]]

# Replace NAs
df.fillna(0, inplace=True)

# Save to csv
df.to_csv('.../Fixed.csv')

rawDescription: Python: Writing a Dict to CSV

description: Python: Writing a Dict to CSV


code:
from bs4 import BeautifulSoup

content='''

    text

    text

    text

    text

    text

'''

soup = BeautifulSoup(content, 'html.parser')

all_a = soup.select('.test5 a')

for a in all_a:
    print(a['href'])

# www.ios.com

rawDescription: how can i get the href tag in beautifulsoup?

description: Get the href tag in beautifulsoup


code:
import csv
from itertools import groupby

with open(yourfile) as fin:
    tabin = csv.reader(fin, delimiter='\t')
    sentences = [[el[1] for el in g] for k, g in groupby(tabin, bool) if k]

rawDescription: Python parsing a huge file

description: Python parsing a huge file


code:
match = re.search("[^/\\]+", subject)
if match:
    result = match.group()
else:
    result = ""

rawDescription: Regex for escaping path separator in url


code:
s = '2 - 3'
two, three = s.split(' - ')
two
three

rawDescription: Easy parsing in Python

description: Easy parsing in Python


code:
import re
re.sub(r'\d+?', lambda m: str(int(m.group(0))+resline), YOUR_STR)

rawDescription: Update numbers in the middle of a string


code:
index = pd.date_range(start='1952', periods=10**6, freq='s')
big = pd.Series(np.ones(len(index))*97, index)
small = pd.Series(np.ones(len(index))*2, index)

alternating = big[big.index.second % 10 >= 5].combine_first(small)

rawDescription: How can I efficiently combine two time series to alternate?

description: Efficiently combine two time series to alternate


code: ab = list(range(20))

rawDescription: Print range in Python 2.7 and 3.4 different


code:
with open('file.txt', 'w') as textfile:
    textfile.writelines(str(i) + "\n" for i in range(1, 6))

rawDescription: Python - List comprehension within File I/O code


code:
class Order(models.Model):
    items_in_order=models.ManyToManyField('Item', through='Quantity')

class Item(models.Mode):
    name=models.Charfield()
    price=models.DecimalField()

class Quantity(models.Model):
    quantity = models.IntegerField()
    order = models.ForeignKey('Order')
    item = models.ForeignKey('Item')

rawDescription: understand models relationship . Its python, Django my q is ideologic

description: Understand models relationship . Its python, Django my q is ideologic


code:
import numpy as np
import matplotlib.pylab as pl

x = np.arange(10)
y = np.random.random(10)

pl.figure()
pl.subplot(121)
pl.plot(x, y, '-o', markersize=30)
pl.subplot(122)
pl.plot(x, y, '-o', markersize=30, markevery=x.size)

rawDescription: Plot marker at one point instead of start and end point in Python matplotlib


code:
from google.appengine.ext import db

# get unique ID number - I just get 1 here, but you could get many ...
new_ids = db.allocate_ids(handmade_key, 1)

# db.allocate_ids() may return longs but db.Key.from_path requires an int (issue 2970)
new_id_num = int(new_id[0])

# assign the new ID to an entity
new_key = db.Key.from_path('MyModel', new_id_num)
new_instance = MyModel(key=new_key)
...
new_instance.put()

rawDescription: Generating unique number sequence for use as entity key for app engine datastore


code:
def resolve(path):
    "fully resolve a schema that includes other schemas"
    data = open(path).read()
    # fill in any while they remain
    while True:
        beg = data.find('`')
        end = data.find('`', beg + 1)
        if beg < 0:
            break
        path = os.path.join(os.path.dirname(path), data[beg+1:end] + '.avsc')
        data = data[:beg] + resolve(path) + data[end+1:]
    return data

rawDescription: Compiling avro schemas (python) when the message contains more than one message


rawDescription: Tick marks disappear on secondary x-axis in Matplotlib


code:
def hide(iterable):
    for v in iterable:
        yield v

def group_func(iterable,p):
    result = []
    for i in iterable:
         result.append(i)
         if p(i):
             yield result
             result = []
    yield result

print([v for v in group_func('combustibles', lambda x : x in 'aeiou')])
print([v for v in group_func(hide('combustibles'), lambda x : x in 'aeiou')])

rawDescription: Python generator function with predicate


code:
#!/usr/bin/python

"""Write on a canvas, store on-line data."""

from gi.repository import Gtk, Gdk
import time
import math
__version__ = '0.1'

class FormulaWriter(Gtk.Window):

    def __init__(self):
        super(FormulaWriter, self).__init__()
        self.odata = []  # On-line writing information, grouped by strokes

        # General properties
        self.set_title("Formula Writer %s" % __version__)
        self.resize(400, 400)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.connect("delete-event", Gtk.main_quit)

        # Set up canvas
        self.canvas = Gtk.DrawingArea()
        self.canvas.connect("draw", self.on_draw)
        self.canvas.connect("button-press-event", self.on_button_press)
        self.canvas.connect("motion-notify-event", self.on_mouse_move)
        self.canvas.connect("motion-notify-event", self.on_mouse_move)
        self.canvas.set_events(self.canvas.get_events() |
                               Gdk.EventMask.BUTTON_MOTION_MASK |
                               Gdk.EventMask.BUTTON1_MOTION_MASK |
                               Gdk.EventMask.BUTTON2_MOTION_MASK |
                               Gdk.EventMask.BUTTON3_MOTION_MASK |
                               Gdk.EventMask.BUTTON_PRESS_MASK)

        self.add(self.canvas)
        self.show_all()

    def on_button_press(self, w, event):
        """When a button is pressed, the location gets stored and the canvas
        gets updated.
        """
        self.odata.append([{'x': event.x, 'y': event.y, 'time': time.time()}])
        self.canvas.queue_draw()

    def on_mouse_move(self, w, event):
        """When mouse is moved, the mouse position gets stored."""
        point = {'x': event.x, 'y': event.y, 'time': time.time()}
        self.odata[-1].append(point)
        self.canvas.queue_draw()

    def on_draw(self, wid, cr):
        """Handler for drawing action. Draw all strokes.
        :param wid: The DrawingArea
        :param cr: Context
        """

        cr.set_source_rgb(1, 0, 0)  # All strokes get drawn in red
        cr.set_line_width(2.5)

        for stroke in self.odata:
            for i, point in enumerate(stroke):
                if len(stroke) == 1:
                    radius = 2
                    cr.arc(point['x'], point['y'], radius, 0, 2.0*math.pi)
                    cr.fill()
                    cr.stroke()
                elif i != 0:
                    cr.move_to(stroke[i-1]['x'], stroke[i-1]['y'])
                    cr.line_to(point['x'], point['y'])
                    cr.stroke()

def main():
    FormulaWriter()
    Gtk.main()

if __name__ == "__main__":
    main()

rawDescription: How can I record the position where the user pressed the mouse button with Python and GTK?

description: Record the position where the user pressed the mouse button with Python and GTK


code: { key: getattr(user, key) for key in dir(user) if not key.startswith('_') }

rawDescription: convert class to dictionary

description: Convert class to dictionary


code: dictionary[(tuple(list1), tuple(list2))] = scorevalue(list1, list2)

rawDescription: Python: how can I store map between pairs or string arrays and float for fast access?


code:
import threading
import time
import logging

logging.basicConfig(
    format='%(threadName)s:%(message)s',
    level=logging.DEBUG,
)

NUM_OF_THREADS = 10
TIMEOUT = 5

def sleeping_thread(delay, cond):
    logging.debug("Hi, I'm going to delay by %d sec." % delay)
    time.sleep(delay)
    logging.debug("I was sleeping for %d sec." % delay)
    cond.acquire()
    logging.debug("Calling notify().")
    cond.notify()
    cond.release()

def create_sleeping_thread(delay, cond):
    return threading.Thread(target=sleeping_thread,
                            args=(delay, cond))

if __name__ == '__main__':
    cond = threading.Condition(threading.Lock())
    cond.acquire()

    working_counter = NUM_OF_THREADS
    for i in xrange(NUM_OF_THREADS):
        t = create_sleeping_thread(i, cond)
        t.start()

    start_time = time.time()
    while working_counter > 0 and (time.time() - start_time < TIMEOUT):
        cond.wait()
        working_counter -= 1
        logging.debug('%d workers still working', working_counter)
    cond.release()
    logging.debug('Finish waiting for threads (%d workers still working)',
                 working_counter)

rawDescription: Python: threads using join() in while loop


code:
validate = re.compile(r'(([0-9]+):([^:;]+)(?:;|$)*)*$')
validate.match("1:name;2:another name;3:one last name;")
validate.match("1:name;dummy:another name;3:one last name;") # is None
validate.match("1:name;a2:another name;3:one last name;") # is also None

rawDescription: Use a Python regex to check a key:value;key:value; string is well-formed


code:
def main():
    result = []

    while 1:
        dag = nx.Graph()
        order = int(input())
        if not order: # check if it's 0
            break # end the loop
        for i in range (order):
            dag.add_node(i)
        for j in range(order):
            vertexList = input().split() # no need to put this single string into a list
            for element in vertexList:
                dag.add_edge(j,int(element))
        result.append(nx.number_connected_components(dag))

    print (result)

rawDescription: Using multiple inputs at once

description: Using multiple inputs at once


code:
import os
import json

foo = [1,2,5,9] #default

#if safe file exists, load its contents into foo list
if os.path.isfile("save.json"):
    with open("save.json", "r") as file:
        foo = json.loads(file.read())

foo.append(int(input("Enter a number to add to foo")))
print(foo)

#write foo list to file
with open("save.json", "w") as file:
    file.write(json.dumps(foo))

rawDescription: How to I modify an external list?

description: I modify an external list


code:
from PIL import Image
img = Image.open('/pathto/file', 'r')
img_w, img_h = img.size
background = Image.new('RGBA', (1440, 900), (255, 255, 255, 255))
bg_w, bg_h = background.size
offset = ((bg_w - img_w) / 2, (bg_h - img_h) / 2)
background.paste(img, offset)
background.save('out.png')

rawDescription: How do you composite an image onto another image with PIL in Python?

description: Composite an image onto another image with PIL in Python


rawDescription: Python LDAP - Move user to different OU

description: Python LDAP - Move user to different OU


code:
import ast
import collections
import re

def main():
    parser = GDFParser()
    with open('network.gdf') as file:
        parser.read(file)
    print(*parser.data, sep='\n')

def pivot(iterable):
    columns = []
    for row in iterable:
        columns.extend([] for _ in range(len(row) - len(columns)))
        for column, cell in zip(columns, row):
            column.append(cell)
    return columns

class GDFParser:

    HEADER = re.compile('\w+:')
    DEF = re.compile('\w+>\w+ (?:DOUBLE|VARCHAR)(?:,\w+ (?:DOUBLE|VARCHAR))*')
    CAST = dict(DOUBLE=float, VARCHAR=str)

    def __init__(self):
        self.__header = None
        self.__type = []
        self.__data = []

    @property
    def header(self):
        return self.__header

    @property
    def data(self):
        return tuple(self.__data)

    def read(self, file):
        for line in file:
            self.__read_line(line.strip())

    def __read_line(self, line):
        if self.HEADER.fullmatch(line):
            self.__process_header(line)
        elif self.DEF.fullmatch(line):
            self.__process_def(line)
        else:
            self.__process_data(line)

    def __process_header(self, line):
        if self.header:
            raise ValueError('header was previously set')
        self.__header = line[:-1]

    def __process_def(self, line):
        name, fields = line.split('>')
        columns, casts = pivot(field.split() for field in fields.split(','))
        self.__type.append((collections.namedtuple(name, columns),
                            tuple(map(self.CAST.__getitem__, casts))))

    def __process_data(self, line):
        if not self.__type:
            raise ValueError('a definition must come before its data')
        kind, casts = self.__type[-1]
        self.__data.append(kind(*(cast(item) for cast, item in
                                  zip(casts, ast.literal_eval(line)))))

if __name__ == '__main__':
    main()

rawDescription: Python: how to parse and and add contents to a text file


code:
hash_obj = hashlib.md5(open(flist[0], 'rb').read())
for fname in flist[1:]:
    hash_obj.update(open(fname, 'rb').read())
checksum = hash_obj.digest()

rawDescription: Generating one MD5/SHA1 checksum of multiple files in Python


code: parent_map = dict((c, p) for p in tree.getiterator() for c in p)

rawDescription: access ElementTree node parent node

description: Access ElementTree node parent node


code:
gr = df.sort('timestamp').groupby('group_name')
df['order_within_group'] = gr.cumcount()
df['rolling_sum_of_condition'] = gr['condition'].cumsum()

rawDescription: How to add "order within group" column in pandas?

description: Add "order within group" column in pandas


code:
def almost_equal(x,y):
    epsilon = 0.00001
    return abs(x-y) < epsilon

rawDescription: How a Python newbie might overcome problems with floating point comparisons


code:
import importlib.machinery
loader = importlib.machinery.SourceFileLoader('a_b', '/tmp/a-b.txt')
mod = loader.load_module()
mod

rawDescription: Import abitrary python source file. (Python 3.3+)


code:
def compfiles(file1, file2):
    lines1 = [l.strip() for l in open(file1).read().split("\n")]
    lines2 = set([l.strip() for l in open(file2).read().split("\n")])
    for line in lines1:
        if not line in lines2:
            print("Miss: file %s contains '%s', but file %s does not!" % (file1, line, file2))
    print("%i lines compared between %s and %s." % (len(lines1), file1, file2))

rawDescription: Shorten Python code

description: Shorten Python code


code:
def in_both(s1, s2):
    s1 = s1.lower()
    s2 = s2.lower()
    s1_chars = set(s1)
    s2_chars = set(s2)
    result = sorted(s1_chars.intersection(s2_chars))
    return result

rawDescription: Similar Character's in two strings, return all similar characters (no repetitive characters) problemsetquestion in Python


code:
class SecuredStaticFlask(Flask):
    def send_static_file(self, filename):
        # Get user from session
        if user.is_authenticated():
            return super(SecuredStaticFlask, self).send_static_file(filename)
        else:
            abort(403)
            # Or 401 (or 404), whatever is most appropriate for your situation

rawDescription: Secure static files with flask

description: Secure static files with flask


code:
# This is a real comment.

"useless normal string"

"""useless triple-quoted
multi-line
string"""

[1, "two"]  # <-- useless list

42  # <-- useless number

rawDescription: What is the difference between multi-line comment and multi-line string in python?


code:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = webdriver.ChromeOptions()
options.add_argument("download.default_directory=C:/Downloads")

driver = webdriver.Chrome(chrome_options=options)

rawDescription: Downloading a file at a specified location through python and selenium using Chrome driver


code:
from matplotlib import pyplot as plt
import numpy as np
import scipy.interpolate as spinp
import scipy.optimize as spop

fig = plt.figure(figsize=(16,4))
ax1 = fig.add_subplot(121)
x  = [0,10,20,30,40,50,60,70,80,90,100]
yr = [1,1,1,1,1,0,0,0,0,0,0]
yg = [0,0,0,0,0,1,1,1,1,1,1]
turn_pt = np.interp(45, x, yr) #change 45 to whatever.
yb = [0.,turn_pt,turn_pt]
ax1.plot(x, yr, '-r')
ax1.plot(x, yg, '-g')
xb = [45, 45, 200]
ll = plt.plot(xb,yb, '-b')
ll[0].set_clip_on(False)
plt.axis([0,100,0,1.2])
#the above three lines to draw the line out of the box.

ax2 = fig.add_subplot(122)
yr = [1,1,1,1,0,0,0,0,0]
yg = [0,0,0,0,1,1,1,1,1]
x  = [0,5,10,15,20,25,30,35,40]
brk_pt_f = lambda X, V: (spinp.interp1d(x, yr)(X)-V)**2
brk_pt = spop.fmin(brk_pt_f, 17., args=(turn_pt,), disp=0) #17. is you inital guess,
#the above two lines solve for the intersection between the blue line and the red line
zero_pt = 20.
start_pt= 0.
xb = np.hstack((start_pt, brk_pt, zero_pt))
yb = [turn_pt,turn_pt,0]
ax2.plot(x, yr, '-r')
ax2.plot(x, yg, '-g')
ax2.plot(xb, yb, '-b')
ax2.hlines(turn_pt,0, 40, 'b', alpha=0.)
ax2.fill_between(xb, yb, 0, alpha=0.4)
ax2.set_ylim([0, 1.2])
ax2.set_xlim([0, 40])

rawDescription: Creating Matplotlib Graph with common line across subplots in Python


code:
import matplotlib as mpl
import pyplot as plt
from numpy import arange,meshgrid,sqrt

u,v = arange(-50,51,10),arange(-50,51,10)
u,v = meshgrid(u,v)
x,y = u,v
C = sqrt(u**2 + v**2)
cmap=plt.cm.jet
bounds = [10, 20, 40, 60]
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
img=plt.barbs(x,y,u,v,C,cmap=cmap,norm=norm)
plt.colorbar(img, cmap=cmap, norm=norm, boundaries=bounds, ticks=bounds)
plt.show()

rawDescription: Python matplotlib barbs/quiver map colors to different sets of values


code:
import subprocess
import time

p = subprocess.Popen(['notepad.exe'])
time.sleep(10)
p.kill()

rawDescription: Starting a new process from python script and then killing it from the same script


code:
import re
searcher = re.compile(r'\b(?:2[0-3]|[01][0-9])[0-5][0-9]\b').search
with open(filename) as text:
        for line in text:
            m = searcher(line)
            if m:
                do_something_1(line, m)
            if line.startswith("BREAK"): # equivalent to your code; is that what you really mean??
                break
        for line in text:
            m = searcher(line)
            if m:
                do_something_2(line, m)
            if line.startswith("STOP"): # equivalent to your code; is that what you really mean??
                break

rawDescription: starting and stoping using a regular expression

description: Starting and stoping using a regular expression


code:
widget = canvas.get_tk_widget()
widget.config(highlightcolor="white")

rawDescription: Remove extra line in matplotlib sides

description: Remove extra line in matplotlib sides


code:
def smooth_gaussian(data,window,std):
  g = sp.signal.gaussian(window,std,sym=True)
  con = np.convolve(g/g.sum(),data,mode='valid')
  con_shift = np.r_[np.full((window*0.5),np.nan),con,np.full((window*0.5),np.nan)]
  return con_shift

rawDescription: Pandas rolling window function offsets data


code:
for row in rows:
    (alpha,
     beta,
     charlie,
     delta,
     echo,
     foxtrot,
     gamma,
     horseshoe,
     indigo,
     jimmy,
     killshot) = row

rawDescription: How do you include newlines in a python list unpack?

description: Include newlines in a python list unpack


code:
import cv2

fin_image = cv2.bitwise_or(src_image, masking_image)

rawDescription: How to do OR masking operation in Image processing in python?

description: Do OR masking operation in Image processing in python


code:
import readline
output_buffer = []
output_buffer_lock = threading.Lock()

# Wherever you would normally print the output
if readline.get_line_buffer():
    with output_buffer_lock:
        output_buffer.append(output)
else:
    with output_buffer_lock:
        print('\n'.join(output_buffer + [output]))
        output_buffer = []

# Wherever you're reading the input
line = input()
with output_buffer_lock:
    print('\n'.join(output_buffer + [output]))
    output_buffer = []

rawDescription: Python Threading - Prioritising Input Over Output


code:
hdata = """

Class1

Class2

Class3

"""
import re
lire = re.compile(r'
.*?>(.*?)<.*')
[lire.search(x).groups()[0] for x in hdata.splitlines() if lire.search(x)]

rawDescription: How do I extract HTML list entries into a Python list?

description: Extract HTML list entries into a Python list


code:
def my_func():
    order = [1,2,3,4,5,6,7]
    intermediate_results = (is_odd(o) for o in order)
    # alternatively filter using `filter(None, intermediate_results)`
    return [i for i in intermediate_results if i]

rawDescription: Declaring variable in one line for loop in Python


code:
for patn in pat:
    if re.search(patn, i):
        i  = re.sub(patn, '', i)
if i:
    new.append(i)

rawDescription: more efficient way to replace items on a list based on a condition

description: More efficient way to replace items on a list based on a condition


code:
import bge

var1 = 1

def myfunc(cont):
    global var1
    var1 += 1
    update()

def update():
    global var1
    scene = bge.logic.getCurrentScene()
    scene.objects['Text']['Text'] = str(var1)

rawDescription: blender game engine as simulation tool how to include one time calculations

description: Blender game engine as simulation tool how to include one time calculations


code:
def branchFinder(L, S, r):
    S, L = map(list, zip(*sorted(zip(S, L))))
    SS = [0.] + map(lambda x: x/10., S)

    probs = {}
    for i in range(len(L)):
        probs[L[i]] = (sum(SS[:i+1]), SS[i+1] + sum(SS[:i+1]))

    for key, value in probs.iteritems():
        if value[0] < r <= value[1]:
             return key

rawDescription: Mapping elements of a list to Intervals to create a cumulative probability distribution


rawDescription: How to remove a certain part of a string in scrapy for python

description: Remove a certain part of a string in scrapy for python


rawDescription: Sort numpy array according to tags

description: Sort numpy array according to tags


code:
from PIL import Image
from PIL.ExifTags import TAGS

def get_exif(fn):
    ret = {}
    i = Image.open(fn)
    info = i._getexif()
    for tag, value in info.items():
        decoded = TAGS.get(tag, tag)
        ret[decoded] = value
    return ret

rawDescription: Extract Image Metadata in Django

description: Extract Image Metadata in Django


code:
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.tree = QTreeWidget(self)
        self.tree.setColumnCount(1)
        self.tree.setItemDelegate(MyDelegate(self))
        self.setCentralWidget(self.tree)

        itemWidget = QTreeWidgetItem()
        itemWidget.setFlags(itemWidget.flags() | Qt.ItemIsEditable)
        itemWidget.setText(0, "very Small Text Edit")
        self.tree.addTopLevelItem(itemWidget)

        itemWidget2 = QTreeWidgetItem()
        itemWidget2.setFlags(itemWidget.flags() | Qt.ItemIsEditable)
        itemWidget2.setText(0, """very Small Text Edit\n
        very Small Text Edit\n
        very Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Editvery Small Text Edit""")
        self.tree.addTopLevelItem(itemWidget2)

class MyDelegate(QStyledItemDelegate):

    def sizeHint(self, option, index):
        default = QStyledItemDelegate.sizeHint(self, option, index)
        return QSize(default.width(), default.height() + 12)

    def createEditor(self, parent, option, index):
        editor = QTextEdit(parent)
        return editor

    def setEditorData(self, editor, index):
        text = index.model().data(index, Qt.DisplayRole).toString()
        editor.setText(text)

    def setModelData(self, editor, model, index):
        model.setData(index, QVariant(editor.toPlainText()))

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    ui = MyMainWindow()
    ui.show()
    sys.exit(app.exec_())

rawDescription: Minimizing the size of a QTextEdit in a QTreeWidgetItem


code:
import unittest
from getpass import getpass

class TestCommon(unittest.TestCase):
    pwd = getpass()

class test_A(TestCommon):
    def test_a(self):
        self.assertEqual(self.pwd, 'secret')

class test_B(TestCommon):
    def test_b(self):
        reversed_pwd = self.pwd[::-1]
        self.assertEqual(reversed_pwd, 'terces')

rawDescription: Python Unit Test with User-Entered Password


rawDescription: How to link a mysql record and a MongoDB document?

description: Link a mysql record and a MongoDB document


code:
def visualize_dct(d):
    d = d + abs(d.min())
    h = np.histogram(d, bins=1000, range=(0, d.max()))
    c = 255.0*np.cumsum(h[0])/sum(h[0])
    new_img = np.zeros(d.shape)
    for index,value in np.ndenumerate( d ):
        new_img[index] = c[999.0*value/d.max()]
    return new_img

rawDescription: nice way to visualize dct coefficients as an image

description: Nice way to visualize dct coefficients as an image


code:
# min85data and min37data from your file
dx = xedges[1] - xedges[0]
dy = yedges[1] - yedges[0]
min85inds = np.floor((min85data - yedges[1]) / dx).astype(np.int)
min37inds = np.floor((min37data - yedges[0]) / dy).astype(np.int)

# Pretend you didn't do all that flipping of H, or make a copy of it first
hvals = h_orig[min85inds, min37ends]

rawDescription: Referencing Data From a 2D Histogram

description: Referencing Data From a 2D Histogram


code:
clients = list(client_response.clients.client)
clients.extend(list(client_response2.clients.client))

rawDescription: How to concat python lxml trees

description: Concat python lxml trees


code: {{ my_object.my_property or '' }}

rawDescription: Print None object properties as empty string


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

# generate 20 points from uniform (-3,3)
x = np.random.uniform(-3, 3, size=20)
y = np.sin(x)

fig, ax = plt.subplots()
ax.scatter(x,y)

rawDescription: Plotting random point on Function - Pandas


code:
def get_actions(self, request):
    actions = super(YourAdmin, self).get_actions(request)
    if 'delete_selected' in actions:
        del actions['delete_selected']
    return actions

rawDescription: Remove the default delete action in Django admin


code:
from random import randint

while True:
    correct = 0

    userrange = int(input("How many questions would you like?\n"))

    difficulty = input("Choose your difficulty: beginner, intermediate or advanced?\n")

    if difficulty == "beginner":
            no = 10
    if difficulty == "intermediate":
            no = 25
    if difficulty == "advanced":
            no = 100

    qtype = input("Would you like to do addition, subtraction or multiplication?\n")

    for i in range(userrange):  # Move the loop to start here, instead of under each if / elif
        n1 = randint(1, no)  # We can go ahead and generate our random numbers here also
        n2 = randint(1, no)
        if qtype == "addition":
            prod = n1 + n2
            lo = "plus"
        elif qtype == "subtraction":
            prod = n1 - n2
            lo = "minus"
        elif qtype == "multiplication":
            prod = n1 * n2
            lo = "times"

        ans = int(input("What's %d %s %d?"  % (n1 ,lo ,n2)))  # We also need to move the question into the loop, so that it is asked each time
        if ans == prod:
            print ("That's right -- well done.\n")
            correct = correct + 1
        else:
            print ("No, I'm afraid the answer is %d.\n" % prod)

    print ("\nI asked you %d questions.  You got %d of them right." %(userrange, correct))
    if correct >= (userrange%3)*2:
        print ("Well done!")
    elif (userrange%3) < correct < (userrange%3)*2:
        print ("You need more practice")
    else:
        print ("Please ask your maths teacher for help!")

    try_again = int(input("\nPress 1 to try again, press 0 to exit.\n "))
    if try_again == 0:
        break

rawDescription: Maths Quiz Task Python

description: Maths Quiz Task Python


code:
send_buf = ctypes.create_string_buffer(b'\0' * 18 + payload + b'\0' * 4)
lws.libwebsocket_write(wsi, ctypes.byref(send_buf, 18), len(payload), 0)

send_buf.value # null terminated
send_buf.raw   # complete array

rawDescription: Passing a padded string with Ctypes

description: Passing a padded string with Ctypes


code:
from django.db.models import Count
teams = Team.objects.annotate(num_wins=Count('alliance__winner')).order_by('-num_wins')

rawDescription: Ordering a query set based on the length of another query set


code:
from math import sqrt

def k_means(data_pts, k=None):
    """ Return k (x,y) pairs where:
            k = number of clusters
        and each
            (x,y) pair = centroid of cluster

        data_pts should be a list of (x,y) tuples, e.g.,
            data_pts=[ (0,0), (0,5), (1,3) ]
    """

    """ Helper functions """
    def lists_are_same(la, lb): # see if two lists have the same elements
        out = False
        for item in la:
            if item not in lb:
                out = False
                break
            else:
                out = True
        return out
    def distance(a, b): # distance between (x,y) points a and b
        return sqrt(abs(a[0]-b[0])**2 + abs(a[1]-b[1])**2)
    def average(a): # return the average of a one-dimensional list (e.g., [1, 2, 3])
        return sum(a)/float(len(a))

    """ Set up some initial values """
    if k is None: # if the user didn't supply a number of means to look for, try to estimate how many there are
        n = len(data_pts)# number of points in the dataset
        k = int(sqrt(n/2))  # number of clusters - see
                        #   http://en.wikipedia.org/wiki/Determining_the_number_of_clusters_in_a_data_set#Rule_of_thumb
    if k < 1: # make sure there's at least one cluster
        k = 1

    """ Randomly generate k clusters and determine the cluster centers,
        or directly generate k random points as cluster centers. """

    init_clusters = data_pts[:]         # put all of the data points into clusters
    shuffle(init_clusters)          # put the data points in random order
    init_clusters = init_clusters[0:k]  # only keep the first k random clusters

    old_clusters, new_clusters = {}, {}
    for item in init_clusters:
        old_clusters[item] = [] # every cluster has a list of points associated with it. Initially, it's 0

    while 1: # just keep going forever, until our break condition is met
        tmp = {}
        for k in old_clusters: # create an editable version of the old_clusters dictionary
            tmp[k] = []

        """ Associate each point with the closest cluster center. """
        for point in data_pts: # for each (x,y) data point
            min_clust = None
            min_dist = 1000000000 # absurdly large, should be larger than the maximum distance for most data sets
            for pc in tmp: # for every possible closest cluster
                pc_dist = distance(point, pc)
                if pc_dist < min_dist: # if this cluster is the closest, have it be the closest (duh)
                    min_dist = pc_dist
                    min_clust = pc
            tmp[min_clust].append(point) # add each point to its closest cluster's list of associated points

        """ Recompute the new cluster centers. """
        for k in tmp:
            associated = tmp[k]
            xs = [pt[0] for pt in associated] # build up a list of x's
            ys = [pt[1] for pt in associated] # build up a list of y's
            x = average(xs) # x coordinate of new cluster
            y = average(ys) # y coordinate of new cluster
            new_clusters[(x,y)] = associated # these are the points the center was built off of, they're *probably* still associated

        if lists_are_same(old_clusters.keys(), new_clusters.keys()): # if we've reached equilibrium, return the points
            return old_clusters.keys()
        else: # otherwise, we'll go another round. let old_clusters = new_clusters, and clear new_clusters.
            old_clusters = new_clusters
            new_clusters = {}

rawDescription: Get point IDs after clustering, using python


code:
def flatten(d):
    """Recursively flatten dictionary values in `d`.

    >>> hat = {'cat': ['images/cat-in-the-hat.png'],
    ...        'fish': {'colours': {'red': [0xFF0000], 'blue': [0x0000FF]},
    ...                 'numbers': {'one': [1], 'two': [2]}},
    ...        'food': {'eggs': {'green': [0x00FF00]},
    ...                 'ham': ['lean', 'medium', 'fat']}}
    >>> set_of_values = set(flatten(hat))
    >>> sorted(set_of_values)
    [1, 2, 255, 65280, 16711680, 'fat', 'images/cat-in-the-hat.png', 'lean', 'medium']
    """
    try:
        for v in d.itervalues():
            for nested_v in flatten(v):
                yield nested_v
    except AttributeError:
        for list_v in d:
            yield list_v

rawDescription: Flatten a dictionary of dictionaries (2 levels deep) of lists in Python


code:
my_list = [[3, 0, 2, 1, 5, 4], [5, 2, 1, 3, 0, 4]]
rande = 3  # for this example
distances = [len(L) - L.index(rande) -1 for L in my_list]

rawDescription: Determining the length from any random element to the last element in a last (inside a list)


code:
ftp.cwd("TXNnIGZvbGRlcg==/")
file = open('msg.txt', 'rb')
file.storbinary('STOR msg.txt', file)
file.close
ftp.cwd("../")

rawDescription: How to go backwards in an FTP connection : PYTHON

description: Go backwards in an FTP connection : PYTHON


rawDescription: Writing a 3D numpy array into a slice of a larger 3D array using a 2D mask


code:
def test_something(self):
    original_config_get = config.get

    def side_effect(key):
        if key == 'expected_argument':
            return mocked_result
        else:
            return original_config_get(key)

        config.get = Mock(side_effect=side_effect)

rawDescription: Python mock function with only specific argument


code:
import numpy as np
image = get_some_image() # your source data
image = image.astype(np.float32) # convert to float
image -= image.min() # ensure the minimal value is 0.0
image /= image.max() # maximum value in image is now 1.0

rawDescription: Python - Applying a color map to a grayscale numpy array and converting it to an image


code:
...
boxPolygon = Polygon(boxCoords, facecolor=boxColors[k])
boxPolygon.set_hatch('*')
ax1.add_patch(boxPolygon)
...

rawDescription: Boxplots in Matplotlib: fill markers in the boxes


code:
import requests
img_url = 'http://upic.me/i/fj/the_wonderful_mist_once_again_01.jpg'

r = requests.get(img_url, allow_redirects=False)   #  stop redirect 302 , capture redirects url

headers = {}
headers['Referer'] = r.headers['location']    # add this url to referer 'http://upic.me/show/55132055'

r = requests.get(img_url, headers=headers)
filename = img_url.split('/')[-1]             # find the file name in `img_url`
with open(filename, 'wb') as fh:             # use 'wb' to write in binary mode
    fh.write(r.content)

rawDescription: Try to scrape image from image url (using python urllib ) but get html instead


code:
import BeautifulSoup

doc = '''<title>Page title</title>
This is paragraph one.
This is paragraph two.'''
soup = BeautifulSoup.BeautifulSoup(doc)

for tag in soup.recursiveChildGenerator():
    if isinstance(tag,BeautifulSoup.Tag) and tag.name not in ('a'):
        print(tag.string)
    elif isinstance(tag,BeautifulSoup.Tag) and tag.name in ('a'):
        print(tag)

rawDescription: Is it possible to use Python / BeautifulSoup to strip all tags from a chunk of HTML EXCEPT anchor / links?


code:
import datetime
datetime.datetime.now()

rawDescription: How to get the time in python on android?

description: Get the time in python on android


code:
import pandas.io.data as web
import datetime
import numpy
import qpython.qconnection as qconnection # requires installation of qPython module from https://github.com/exxeleron/qPython

from qpython import MetaData
from qpython.qtype import QKEYED_TABLE

start = datetime.datetime(2010, 1, 1)
end = datetime.datetime(2015, 2, 6)
f=web.DataReader("F", 'yahoo', start, end) # download Ford stock data (ticker "F") from Yahoo Finance web service
f.ix[:5]  # explore first 5 rows of the DataFrame
# Out:
#             Open  High  Low  Close    Volume  Adj Close
#    Date
# 2010-01-04 10.17 10.28 10.05 10.28  60855800       9.43
# 2010-01-05 10.45 11.24 10.40 10.96 215620200      10.05
# 2010-01-06 11.21 11.46 11.13 11.37 200070600      10.43
# 2010-01-07 11.46 11.69 11.32 11.66 130201700      10.69
# 2010-01-08 11.67 11.74 11.46 11.69 130463000      10.72

q = qconnection.QConnection(host = 'localhost', port = 5000, pandas = True) # define connection interface parameters. Assumes we have previously started q server on port 5000 with `q.exe -p 5000` command
q.open() # open connection
f.meta = MetaData(**{'qtype': QKEYED_TABLE}) # enforce to serialize DataFrame as keyed table
q('set', numpy.string_('yahoo'), f) # pass DataFrame to q table named `yahoo`
q('5#yahoo') # display top 5 rows from newly created table on q server
# Out:
#              Open   High    Low  Close     Volume  Adj Close
# Date
# 2010-01-04  10.17  10.28  10.05  10.28   60855800       9.43
# 2010-01-05  10.45  11.24  10.40  10.96  215620200      10.05
# 2010-01-06  11.21  11.46  11.13  11.37  200070600      10.43
# 2010-01-07  11.46  11.69  11.32  11.66  130201700      10.69
# 2010-01-08  11.67  11.74  11.46  11.69  130463000      10.72

rawDescription: pandas DataFrame drops index when passing to kdb+ (using qPython API)

description: Pandas DataFrame drops index when passing to kdb+ (using qPython API)


code:
cool = "cool°"
cool = cool.replace("°","")
cool
'cool'

rawDescription: How to remove certain characters from a string? [Python]

description: Remove certain characters from a string? [Python]


code:
import re
l = ["2007 ford falcon xr8 ripcurl bf mkii utility 5.4l v8 cyl 6 sp manual bionic ", "2004 nissan x-trail ti 4x4 t30 4d wagon 2.5l 4 cyl 5 sp manual twilight ", "2002 subaru liberty rx my03 4d sedan 2.5l 4 cyl 5 sp manual silver"]
for item in l:
    print(re.sub(r"(\b[0-9.]+l\b|\d+d (?:wagon|sedan)).*$", "", item))

rawDescription: Python truncate string at regex defined index


rawDescription: Selecting characters in string numpy array (Python)


code:
import numpy as np
import pandas as pd
import pylab as pl

data = np.random.random((60,1))
df1  = pd.DataFrame(data)

pl.figure()
pl.subplot(211)
df1.iloc[:30][0].plot(kind='bar')
pl.subplot(212)
df1.iloc[30:][0].plot(kind='bar')

rawDescription: Too many columns for one figure using matplotlib


code:
variables = arr[0].keys()
df = pd.DataFrame([[getattr(i,j) for j in variables] for i in arr], columns = variables)

rawDescription: How to convert list of model objects to pandas dataframe?

description: Convert list of model objects to pandas dataframe


code:
KEY_MASK = 0xf0f0  # or whichever mask you need

class Key(object):
    __slots__ = 'num',
    def __init__(self, num):
        self.num = num
    def __hash__(self):
        return hash(self.num & KEY_MASK)
    def __eq__(self, other):
        return self.num & KEY_MASK == other.num & KEY_MASK
    def __ne__(self, other):
        return not self == other

rawDescription: Using a hash function as a key in a dictonary in python


code:
from openpyxl import Workbook
import getpass
wb = Workbook()
ws1 = wb.active
ws1.title = "1st Hour"
wb.save('/home/'+getpass.getuser()+'/Desktop/FileName.xlsx')

rawDescription: Save XLSX file to a specified location using OpenPyXL


code:
import wx
import wx.stc as stc

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)

        self.text = stc.StyledTextCtrl(self.panel)
        self.text.SetWindowStyle(self.text.GetWindowStyle() | wx.DOUBLE_BORDER)
        self.text.StyleSetSpec(stc.STC_STYLE_DEFAULT, "size:15,face:Courier New")
        self.text.SetWrapMode(stc.STC_WRAP_WORD)
        self.text.SetMarginLeft(50)

        self.menu = wx.Menu()
        self.menu.Append(wx.ID_ABOUT, "&About", "Information about this program")
        self.menu_bar = wx.MenuBar()
        self.menu_bar.Append(self.menu, "&File")
        self.SetMenuBar(self.menu_bar)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.text, 1, wx.ALL | wx.EXPAND, 5)

        self.panel.SetSizerAndFit(self.sizer)

        self.text.Bind(stc.EVT_STC_CHANGE, self.OnChange)
        self.Show()

        self.text.SetText("Line!\n"*98)

    def OnChange(self, e):
        lines = self.text.GetLineCount()
        width = self.text.TextWidth(stc.STC_STYLE_LINENUMBER, str(lines)+" ")
        self.text.SetMarginWidth(0, width)

if __name__ == "__main__":
    app = wx.App(False)
    win = MainWindow(None)
    app.MainLoop()

rawDescription: Insert a space into my stc.StyledTextCtrl so the code isnt so close to the line numbers


code:
plt.figure()
plt.plot([0, 100], [5, 5], linewidth=50, linestyle="-", c="blue",
         solid_capstyle="butt")
plt.plot([0, 100], [15, 15], linewidth=50, linestyle="-", c="red",
         solid_capstyle="round")
plt.plot([0, 100], [25, 25], linewidth=50, linestyle="-", c="purple",
         solid_capstyle="projecting")
plt.axvline(x=100, c="black")
plt.xlim(0, 125)
plt.ylim(0, 30)
plt.savefig("cap.png")

rawDescription: Matplotlib: linewidth is added to the length of a line


rawDescription: gql does not work for get paramters for keys

description: Gql does not work for get paramters for keys


code:
f = open('file', 'w')
old = sys.stdout
sys.stdout = f
cgi.print_environ()
f.flush()
sys.stdout = old
f.close()

rawDescription: writing output of python cgi.print_environ() and cgi.print_form() to file

description: Writing output of python cgi.print_environ() and cgi.print_form() to file


rawDescription: search elements of list in another list

description: Search elements of list in another list


code:
with open(colA_file, "rb") as file_h:
    noun_a = set(line.strip() for line in file_h)

with open(colB_file, "rb") as file_h:
    noun_b = set(line.strip() for line in file_h)

with open(output_file, "wb") as outfile:
    with open(input_file, "rb") as opened_input:
        for line in opened_input:
            split_line = line.split()
            if split_line[0] in noun_a and split_line[1] in noun_b:
                outfile.write(line)

rawDescription: Extracting information from 2 separate lists


code:
pal1 = sns.color_palette('rainbow', sum(ix1))
pal2 = sns.color_palette('coolwarm', sum(ix2))

fig, ax = plt.subplots(figsize=(4, 4))
ax.scatter(x_data[ix1], y[ix1], c=pal1, s=60, label="smaller")
ax.scatter(x_data[ix2], y[ix2], c=pal2, s=60, label="larger")
ax.legend(loc="lower right", scatterpoints=5)

rawDescription: How to use multiple colormaps in seaborn on same plot

description: Use multiple colormaps in seaborn on same plot


code:
class requiresparams(object):
    """

    Used as a decorator with an iterable passed in, this will look for each item
    in the iterable given as a key in the params argument of the function being
    decorated. It was built for a series of PayPal methods that require
    different params, and AOP was the best way to handle it while staying DRY.

    >>> @requiresparams(['name', 'pass', 'code'])
    ... def complex_function(params):
    ...     print(params['name'])
    ...     print(params['pass'])
    ...     print(params['code'])
    >>>
    >>> params = {
    ...     'name': 'John Doe',
    ...     'pass': 'OpenSesame',
    ...     #'code': '1134',
    ... }
    >>>
    >>> complex_function(params=params)
    Traceback (most recent call last):
        ...
    ValueError: Missing from "params" dictionary: code
    """
    def __init__(self, required):
        self.required = set(required)

    def __call__(self, func):
        def wrapper(*args, **kwargs):
            if not kwargs.get('params', None):
                raise KeyError('"params" kwarg required for {0}'.format(func.__name__))
            missing = self.required.difference(kwargs['params'])
            if missing:
                raise ValueError('Missing from "params" dictionary: %s' % ', '.join(sorted(missing)))
            return func(*args, **kwargs)
        return wrapper

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

rawDescription: Python: Why can't I get my decorator to work?


code:
plt.figure()
X_plot = np.arange(255)[:, None]  # predefined grid
# estimate density on samples
kde = KernelDensity(kernel='gaussian', bandwidth=0.2).fit(X.ravel()[:, None])
log_dens = kde.score_samples(X_plot)  # evaluate the density model on the data.
plt.plot(np.exp(log_dens))
plt.show()

rawDescription: Kernel density estimation of the histogram of an image


code:
import xlwt
from bs4 import BeautifulSoup
from urllib2 import urlopen

html = urlopen("http://www.chicagoreader.com").read()
soup = BeautifulSoup(html, "lxml")

workbook = xlwt.Workbook()
sheet = workbook.add_sheet('test')

sheet.write(0, 0, soup.title.text)

workbook.save('output.xls')

rawDescription: Is the webpage read? How can I save it to an excel file?


rawDescription: how to convert a list of tuples into a lists of part of tuples in python

description: Convert a list of tuples into a lists of part of tuples in python


rawDescription: Modifying a list in place: Calculating a sieve of primes in a python list


code:
# out is your file
out.readline().split() # result is ['francesco', '10']

rawDescription: Python reading 2 strings from the same line


code:
user_inp = ""
while len(user_inp) < 10:
    inp = raw_input("Enter a digit")
    if len(inp) == 1 and inp.isdigit(): # check length and make sure a digit is entered
        user_inp += inp
    else:
        print("Invalid input")
print("The numbers you have entered are: {}".format(user_inp))

rawDescription: trying to make a program that only accepts single digit inputs and then displays after it hits the 10th input

description: Trying to make a program that only accepts single digit inputs and then displays after it hits the 10th input


code:
def func2():
    print('success')
def run(f):
    f.__code__ = func2.__code__

rawDescription: Replace function in main module from imported module in Python


code:
s = int(self.newTime)
date = datetime(year=s[0:4], month=s[4], day=s[5:2], hour=s[8:2], minute=s[10:2], second=s[12])
utime = time.mktime(date.timetuple())
os.utime(self.fileName, (utime, utime))

rawDescription: how to convert format of date to 'os.utime()' format

description: Convert format of date to 'os.utime()' format


code:
from PyQt4 import QtCore, QtGui

class Widget(QtGui.QWidget):

    def __init__(self, *args, **kwargs):
        super(Widget, self).__init__(*args, **kwargs)
        self.resize(800,600)

        self.vlayout = QtGui.QVBoxLayout(self)
        self.table = QtGui.QTableView()
        self.vlayout.addWidget(self.table)

        self.hlayout = QtGui.QHBoxLayout()
        self.list1 = QtGui.QListView()
        self.list2 = QtGui.QListView()
        self.list3 = QtGui.QListView()
        self.hlayout.addWidget(self.list1)
        self.hlayout.addWidget(self.list2)
        self.hlayout.addWidget(self.list3)

        self.vlayout.addLayout(self.hlayout)

        self.model = QtGui.QStandardItemModel(10,10,self)
        self.table.setModel(self.model)

        self.list1.setModel(self.model)
        self.list1.setModelColumn(0)
        self.list2.setModel(self.model)
        self.list2.setModelColumn(1)
        self.list3.setModel(self.model)
        self.list3.setModelColumn(2)

        self.populateTable()

    def populateTable(self):
        for row in xrange(10):
            for col in xrange(10):
                item = QtGui.QStandardItem('%d-%d' % (row, col))
                self.model.setItem(row, col, item)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication([])
    window = Widget()
    window.show()
    window.raise_()
    sys.exit(app.exec_())

rawDescription: Python and PyQt: Get Input from QTableWidget?


code:
from sqlalchemy.orm import eagerload, eagerload_all
...
controlled_docs = (m.Session.query(m.Controlled)
    .options(eagerload_all('changes.dco'))
    .order_by('number')
    .all())

rawDescription: SQLAlchemy - full load instance before detach


code:
from datetime import datetime
import datetime as dt
dt_90 = datetime.now() - dt.timedelta(days=90)
dt_90
dt_90.strftime("%Y %d")

rawDescription: Better way to get a Julian date?

description: Better way to get a Julian date


code:
import glob
import shutil

deldirs = glob.glob("path/to/master/test.directory.*")
for dir_ in deldirs:
    shutil.rmtree(dir_)

rawDescription: Python - shutil How to select multiple directories for deletion with similar names


code:
def time_delta(age):
    now = datetime.fromtimestamp(int(time.time()))
    return now - relativedelta(**{age.time_unit: int(age.value)})

rawDescription: Pass expression as named argument name

description: Pass expression as named argument name


code:
import re
string = '"first, element", second element, third element, "fourth, element", fifth element'
m = re.split(r', (?=(?:"[^"]*?(?: [^"]*)*))|, (?=[^",]+(?:,|$))', string)
m

rawDescription: Split on comma not enclosed by quotes

description: Split on comma not enclosed by quotes


code:
import Tkinter

class Application(Tkinter.Frame):
    def __init__(self, master):
        Tkinter.Frame.__init__(self, master)
        self.master.minsize(width=256, height=256)
        self.master.config()
        self.pack()

        self.main_frame = Tkinter.Frame()

        self.some_list = [
            'One',
            'Two',
            'Three',
            'Four'
        ]

        self.some_listbox = Tkinter.Listbox(self.main_frame)
        self.some_listbox.pack(fill='both', expand=True)
        self.main_frame.pack(fill='both', expand=True)

        # insert our items into the list box
        for i, item in enumerate(self.some_list):
            self.some_listbox.insert(i, item)

        # add a button to select the next item
        self.some_button = Tkinter.Button(
            self.main_frame, text="Next", command=self.next_selection)
        self.some_button.pack(side='top')

        # not really necessary, just make things look nice and centered
        self.main_frame.place(in_=self.master, anchor='c', relx=.5, rely=.5)

    def next_selection(self):
        selection_indices = self.some_listbox.curselection()

        # default next selection is the beginning
        next_selection = 0

        # make sure at least one item is selected
        if len(selection_indices) > 0:
            # Get the last selection, remember they are strings for some reason
            # so convert to int
            last_selection = int(selection_indices[-1])

            # clear current selections
            self.some_listbox.selection_clear(selection_indices)

            # Make sure we're not at the last item
            if last_selection < self.some_listbox.size() - 1:
                next_selection = last_selection + 1

        self.some_listbox.activate(next_selection)
        self.some_listbox.selection_set(next_selection)

root = Tkinter.Tk()
app = Application(root)
app.mainloop()

rawDescription: Python 2.7 - Tkinter - Button to move to next item in listbox


code:
text=open(original_file).read()
text=re.sub('FY91/92','',text)
f = open(original_file, 'w')
f.write(text)
f.close()

rawDescription: Duplicate Lines with Python and regex text manipulation


code:
#lis = some list with NoneType's
filter(None, lis)

rawDescription: Native Python function to remove NoneType elements from list?


code:
with open(path_to_file, 'rb') as f:
    f.read()[:-4]

rawDescription: how to read first X bytes from binary file in python

description: Read first X bytes from binary file in python


code:
# stuff to run always here such as class/def
def main():
    pass

if __name__ == "__main__":
   # stuff only to run when not called via 'import' here
   main()

rawDescription: Why is Python running my module when I import it, and how do I stop it?


code:
import cv2
import numpy as np

def nothing(x):
    return()

cap = cv2.VideoCapture('movie.MOV')

trackbar = np.zeros((300,512,3), np.uint8)
trackbar2 = np.zeros((300,512,3), np.uint8)
cv2.namedWindow("trackbar")
cv2.namedWindow("trackbar2")

cv2.createTrackbar('RL','trackbar',0,255,nothing)
cv2.createTrackbar('GL','trackbar',0,255,nothing)
cv2.createTrackbar('BL','trackbar',0,255,nothing)

cv2.createTrackbar('RH','trackbar2',0,255,nothing)
cv2.createTrackbar('GH','trackbar2',0,255,nothing)
cv2.createTrackbar('BH','trackbar2',0,255,nothing)

while(1):

    #Gets retval and frames from each video

    ret ,frame = cap.read()

    #Check to see if retval is not None or empty
    if not ret:
        break;

    r = cv2.getTrackbarPos('RL','trackbar')
    g = cv2.getTrackbarPos('GL','trackbar')
    b = cv2.getTrackbarPos('BL','trackbar')

    rh = cv2.getTrackbarPos('RH','trackbar2')
    gh = cv2.getTrackbarPos('GH','trackbar2')
    bh = cv2.getTrackbarPos('BH','trackbar2')

    trackbar[:] = [b,g,r]
    trackbar2[:] = [bh,gh,rh]

    boundaries = [([r,g,b],[rh,gh,bh])]

    for (lower,upper) in boundaries:
            lower = np.array(lower, dtype = "uint8")
            upper = np.array(upper, dtype = "uint8")

            mask = cv2.inRange(frame,lower,upper)
            output = cv2.bitwise_and(frame, frame, mask = mask)
            cv2.imshow("video", np.hstack([frame, output]))

    if (cv2.waitKey(1) & 0xFF) == ord("q"):
        break

cv2.destroyAllWindows()

rawDescription: Can't move trackbars in OpenCV. They instantly go back to zero.


code:
pyramid_sqlalchemy.py
# -*- coding: utf-8 -*-

""" Pyramid sqlalchemy lib.

Session will be available as dbsession attribute on request.

! Do not close session on your own.

"""

import sqlalchemy
from sqlalchemy.orm import sessionmaker, scoped_session
from zope.sqlalchemy import ZopeTransactionExtension

Session = scoped_session(sessionmaker(
    extension=ZopeTransactionExtension()
))

def includeme(config):
    """ Setup sqlalchemy session connection for pyramid app.

    :param config: Pyramid configuration

    """
    config.include('pyramid_tm')
    # creates database engine from ini settings passed to pyramid wsgi
    engine = sqlalchemy.engine_from_config(
        config.get_settings(), connect_args={
            'charset': 'utf8'
        }
    )
    # scoped session gives us thread safe session
    Session.configure(bind=engine)
    # make database session available in every request
    config.add_request_method(
        callable=lambda request: Session, name='dbsession', property=True
    )

rawDescription: pyramid transaction manager not committing on update

description: Pyramid transaction manager not committing on update


code:
files = glob(r'path\*.h5')
out_csv = csv.writer(open('output_file.csv', 'rb'))

def extract_data_from_filename(filename):
    return extract_data_from_handle(hdf5.File(filename, 'r'))

for filename in files:
  data = extract_data_from_filename(filename)
  for row in data:
     out_csv.writerow((filename, ) +row)

rawDescription: Python HDF5 H5Py issues opening multiple files


code:
plt.figure(figsize = (4,4))
gs1 = gridspec.GridSpec(4, 4)
gs1.update(wspace=0.0, hspace=0.) # set the spacing between axes.

for i in range(16):
    ax1 = plt.subplot(gs1[i])
    plt.axis('on')
    ax1.set_xticklabels([])
    ax1.set_yticklabels([])
    ax1.set_aspect('equal')
#     plt.subp

plt.show()

rawDescription: Concatenate multiple histograms in matplotlib


code:
def f(a,N):
    return np.argsort(a)[::-1][:N]

rawDescription: Finding the Index of N biggest elements in Python Array / List Efficiently


code:
from operator import getitem
d = {'a': {'b': {'c': 100}}}
reduce(getitem, ['a', 'b', 'c'], d)
d['a']['b']['c']

rawDescription: How to retrieve values from nested dictionary given list of keys?

description: Retrieve values from nested dictionary given list of keys


code: sorted_list = sorted(d.keys(), key=lambda i: d[i]['priority'], reverse=True)

rawDescription: Sorting python by value in a value dict

description: Sorting python by value in a value dict


code:
from django.core.files.base import ContentFile

# get_pdf_contents should return the binary information for
# a properly formed pdf doc.
pdf_contents = get_pdf_contents()

file_to_be_saved = ContentFile(pdf_contents)

item = Item.objects.get(pk=1)

item.myfilefield.save('blarg.pdf', file_to_be_saved)

rawDescription: Django - Creating & Store PDF Files using XHTML2PDF


code:
for i in range(-1, 2):
    if arr[i-1] == arr[i]:
        arr[i+1] = arr[i]

rawDescription: Python Check if item in list is free

description: Python Check if item in list is free


code:
class Default(object):
    def __repr__(self):
        return '-'.join(
            str(getattr(self,key)) for key in self.__dict__ if not key.startswith('_'))
    def __eq__(self,other):
        try:
            return all(getattr(self,key)==getattr(other,key)
                       for key in self.__dict__ if not key.startswith('_'))
        except AttributeError:
            return False

class Foo(Default):
    def __init__(self):
        self.bar=1
        self.baz='hi'

foo=Foo()
print(foo)
# hi-1

foo2=Foo()
print(foo==foo2)
# True

foo2.bar=100
print(foo==foo2)
# False

rawDescription: Default method implementations in python(__str__,__eq__,__repr__,ect.)


code:
def trailing_zeros(longint):
    manipulandum = str(longint)
    return len(manipulandum)-len(manipulandum.rstrip('0'))

rawDescription: In Python, how do I count the trailing zeros in a string or integer?


code:
def makeWheel(population):
    wheel = []
    total = sum(fitness(p) for p in population)
    top = 0
    for p in population:
        f = fitness(p)/total
        wheel.append((top, top+f, p))
        top += f
    return wheel

def binSearch(wheel, num):
    mid = len(wheel)//2
    low, high, answer = wheel[mid]
    if low<=num<=high:
        return answer
    elif low > num:
        return binSearch(wheel[mid+1:], num)
    else:
        return binSearch(wheel[:mid], num)

def select(wheel, N):
    stepSize = 1.0/N
    answer = []
    r = random.random()
    answer.append(binSearch(wheel, r))
    while len(answer) < N:
        r += stepSize
        if r>1:
            r %= 1
        answer.append(binSearch(wheel, r))
    return answer

rawDescription: Stochastic Universal Sampling GA in python


code:
def add_1_year(x):
    x['End_Date'] = x['Start_Date']+ timedelta(days=365)
    return x

df.apply(add_1_year,axis=1)

rawDescription: Python Pandas: Using a user defined function to fill in a blank variable


code:
s = "chapter1 in chapters"
re.sub(r'chapter(\d+)',r'chapter \1',s)

rawDescription: How to replace part of string via regex with saving part of pattern?

description: Replace part of string via regex with saving part of pattern


rawDescription: Unpivot dataframe in pandas

description: Unpivot dataframe in pandas


code:
import matplotlib as mpl
mpl.use('Agg') #setup the backend
import matplotlib.figure as mfigure
from matplotlib.backends.backend_agg import FigureCanvasAgg #canvas

time = [0,1,2,3,4]
cell = [1,2,1,2,1]
sample = [3,2,3,4,4]

(figHt, figWd) = (5, 8) # in
lBorderWidth = bBorderWidth = rBorderWidth = tBorderWidth = 0.1
lbwh = (lBorderWidth, bBorderWidth,
        (1-lBorderWidth-rBorderWidth),
        (1-tBorderWidth-bBorderWidth)) # left, bottom, width, height

fig = mfigure.Figure(figsize=(figHt, figWd))
canvas = FigureCanvasAgg(fig) #create the canvas

ax = fig.add_axes(lbwh)
lines1, = ax.plot(time,cell,'k--')
lines2, = ax.plot(time,sample,'k-')

fig.legend([lines1,lines2],['p','q'],'upper left')
fig.savefig('test.png') #save the figure

rawDescription: Matplotlib says fig.canvas is None, so I can't use fig.canvas.draw


code:
from user.models import *
for u in User.query.all():
    # \u2013 is unicode for en-dash
    if u"\u2013" in u.occupation:
        # replace with normal hyphen
        u.occupation = u.occupation.replace(u"\u2013", "-")
        db.session.commit()

rawDescription: Replace Character For All Rows using SQLAlchemy on Flask


code:
from Tkinter import *
from threading import Thread

def updateA(textA, tempText):
    while 1:
        tempText.set(textA.get())

class Interface(Frame):

    def __init__(self, fenetre, **kwargs):
        Frame.__init__(self, fenetre, width=0, height=0, **kwargs)
        self.pack(fill=BOTH)

        self.textA = StringVar()
        self.textE = Entry(self, textvariable=self.textA, width=30)
        self.textE.pack()

        self.newWindow = Toplevel(fenetre)
        self.app = Interface2(self.newWindow, self.textA)

class Interface2(Frame):

    def __init__(self, fenetre, textA, **kwargs):
        Frame.__init__(self, fenetre, width=0, height=0, **kwargs)
        self.pack(fill=BOTH)
        fenetre.geometry("700x700")

        self.tempText = StringVar()
        self.textW = Label(self, textvariable=self.tempText)
        self.textW.pack()
        t = Thread(target=updateA, args=(textA,self.tempText))
        t.start()

fenetre = Tk()
interface = Interface(fenetre)

interface.mainloop()
interface.destroy()

rawDescription: Get Entry text in another class

description: Get Entry text in another class


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

# Some fake data
n = 1001
data = np.arange(n*n).reshape(n,n)%2
data = data[:n//2,:]

def get_bitmap_frame(data, dpi=None):
    """
    Construct a figure for overlaying elements on top of bitmap data.

    Returns
    -------
    fig, ax
        Matplotlib figure and axis objects
    """
    if dpi is None:
        dpi = matplotlib.rcParams['savefig.dpi']
    dpi = float(dpi)

    fig = plt.figure(figsize=(data.shape[1]/dpi, data.shape[0]/dpi), dpi=dpi)
    ax = fig.add_axes([0, 0, 1, 1], frame_on=False)
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    ax.imshow(data, interpolation='none')

    # Note: it can happen that floating point rounding error in
    # bbox calculation results to the bbox size being off by one
    # pixel. Because of this, we set it manually
    fig.bbox = matplotlib.transforms.Bbox.from_bounds(0, 0, data.shape[1], data.shape[0])
    return fig, ax

fig, ax = get_bitmap_frame(data)

# Annotate
ax.text(100, 100, 'Hello!', color='w')

fig.savefig("test.png")

rawDescription: Numpy-compatible image drawing library

description: Numpy-compatible image drawing library


code:
while True:
    raw = raw_input('Please enter 64 bits: ')
    try:
        num = int(raw,2)
    except ValueError:
        print("Not a valid binary number")
        continue
    if len(raw)==64:
        print ('Accepted')
        break
    else:
        print ('Not Accepted, need exactly 64 bits.  Try again')

rawDescription: Restricting user input to 64 bits?

description: Restricting user input to 64 bits


code:
class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

    def __eq__(self, other):
        return (self.name, self.location) == (other.name, other.location)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

rawDescription: Object of custom type as dictionary key

description: Object of custom type as dictionary key


code:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# encoding: utf-8

import re

list1 = []
separators = [u'।', ',', '.']
text = open('hinstest1.txt').read().decode('UTF-8')
output_file = ('ophwp1.txt')

for line in text.splitlines():
    counter = 1
    output = ''
    for word in line.split():
        # Special case for the number at the start of the line
        # The regex matches one or more decimal digits (\d+) followed by a dot (\.)
        if re.match(r'\d+\.', word):
            output += word + ' '
            continue
        # Special case: the last char is a separator joined to the word
        if word[-1] in separators and len(word) > 1:
            # word up to the second to last char
            output += word[:-1] + u'(%d) ' % counter
            counter += 1
            # last char
            output += word[-1] + u'(%d) ' % counter
            counter += 1
        else:
            output += word + u'(%d) ' % counter
            counter += 1
    output += u'\n'
    list1.append(output.encode('UTF-8'))

f1=open(output_file,'w')
f1.write(''.join(list1))
f1.close()

rawDescription: Python - appending word position nos. to Unicode text


rawDescription: 16 byte random string with increasing entropy


code:
from PIL import Image, ImageDraw

points = (20,20), (20, 100), (100,20)

im = Image.new('RGB', (255, 255))
draw = ImageDraw.Draw(im)
draw.polygon(points) # outline='red', fill='blue'
im.save('triangle.jpg')

rawDescription: how to create a jpeg picture with a triangle of 3 specific point and specific color

description: Create a jpeg picture with a triangle of 3 specific point and specific color


code:
def exclamation(s):
    'string ==> string, returns the string with every vowel repeating four times and an exclamation mark at the end'
    vowels = 'aeiouAEIOU'
    for vowel in vowels:
        s = s.replace(vowel, vowel * 4)
    return s + '!'

rawDescription: Multiplying vowels in a string

description: Multiplying vowels in a string


code: lex = words.lower().split()

rawDescription: Accepting all alphabetical input as valid regardless of case


code:
import re

re_offers = re.compile(r'''
    \b  # Word boundary
        (?:  # Non capturing parenthesis
            deals?  # Deal or deals
            |  # or ...
            offers?  # Offer or offers
            |
            discount
            |
            promotion
            |
            sale
            |
            rs\.?  # rs or rs.
            |
            inr\d+  # INR then digits
            |
            \d+inr  # Digits then INR
        )  # And group
    \b  # Word boundary
    |  # or ...
    \b\d+%  # Digits (1 or more) then percent
    |
    \$\d+\b  # Dollar then digits (didn't care of thousand separator yet)
    ''',
    re.I|re.X)  # Ignore case, verbose format - for you :)

abc = re_offers.findall("e misio $1 is inr123 discount 1INR a 1% and deal")
print(abc)

rawDescription: Python: Match strings for certain terms

description: Python: Match strings for certain terms


code:
import zlib

...
# f=urllib2.urlopen(url)
decompressed_data=zlib.decompress(f.read(), 16+zlib.MAX_WBITS)

rawDescription: In Python, how do I decode GZIP encoding?


code: df.to_excel( ..., index=False)

rawDescription: how do you remove the index from a dataframe before using xlwriter to convert the dataframe to a excel file

description: Remove the index from a dataframe before using xlwriter to convert the dataframe to a excel file


code:
class Marble(object):
    def __init__(self,color=None):
        self.color=color # I'm assuming this is necessary,
                         # just because "colored marbles in
                         # a box" is so typical
    def __repr__(self):
        return "Marble({})".format(self.color)

class Box(object):
    def __init__(self,name=None,marbles=None):
        self.name = name
        if marbles is None:
            marbles = list()
        self.marbles = marbles
    def addMarble(self,color=None):
        self.marbles.append(Marble(color))
    def giveMarble(self,other):
        # import random
        index = random.randint(0,len(self.marbles)-1)
        try:
            other.marbles.append(self.marbles.pop(index))
        except AttributeError:
            raise NotImplementedError("Can't currently pass marbles to an "
                                      "object without a marbles list")
    def __str__(self):
        return '\n'.join([str(marble) for marble in self.marbles])

a = Box()
b = Box()
for _ in range(10): a.addMarble()
print(a)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
# Marble(None)
a.giveMarble(b)
print(b)
# Marble(None)

rawDescription: Python composition: marbles in a box

description: Python composition: marbles in a box


code:
import urllib2
import json
response = urllib.request.urlopen('https://api.ripple.com/v1/accounts/rssc7gemsZBsseHxyb5NmjfYpJD6aUJirq/balances')
html = response.read()
json_data = json.loads(html)

rawDescription: How to process and return information in API (JSON to Python and back)?

description: Process and return information in API (JSON to Python and back)


code:
class CanonPersonFactory(django_factory.DjangoModelFactory):
    class Meta:
        model = CanonPerson
    ...
    @classmethod
    def _get_manager(cls, model_class):
        manager = super(CanonPersonFactory, cls)._get_manager(model_class)
        return manager.using('global')
    ...

rawDescription: How to specify the database for Factory Boy?

description: Specify the database for Factory Boy


code:
class Article(models.Model):
    title = models.CharField(max_length=X)
    ...

class Part(models.Model):
    article = models.ForeignKey(Article)
    order = models.IntegerField()
    subtitle = models.CharField(max_length=X)
    content = models.TextField()
    ...

    class Meta:
        ordering = ('order',)

rawDescription: Modelling a book in Django

description: Modelling a book in Django


code:
continent_lookup = {1: 'Africa', 2: 'Asia', 3: 'Africa', 4: 'Asia'}
df['Continent'] = df.Country.map(continent_lookup)

rawDescription: pandas.cut with enumerated bins

description: Pandas.cut with enumerated bins


code:
#!/usr/bin/env python
import os
import subprocess

def runprog(name):
    processes = [subprocess.Popen([os.path.abspath(name)], cwd=str(i)) for i in xrange(1,2)]
    for process in processes:
        process.wait()
    print('----------Finaly Done------------')

runprog('cctfiles')

rawDescription: Python breaking from a while loop + exeptions


code:
import numpy as np
from pylab import *

data = { (3, 3): 1.7314, (3,4):-6.99, (4, 3):-17.3, (4, 4):-100.0 }
matrix = np.zeros((5, 5))
for (x, y), z in data.items():
    matrix[y,x] = z

imshow(matrix[3:, 3:], origin='lower', interpolation='none', extent=[2.5, 4.5, 2.5, 4.5])
show()

rawDescription: Heatmap for 3 dimensional scatterplot values (Python)


rawDescription: How to take n-th order discrete sum of numpy array (sum equivalent of numpy.diff)

description: Take n-th order discrete sum of numpy array (sum equivalent of numpy.diff)


code: result = urlfetch.fetch(url, headers = {'Cache-Control' : 'max-age=240'})

rawDescription: Does Google appengine cache external requests?


code:
import re

datetimestring = re.sub('[-.:]', '/', datetimestring)

rawDescription: Parse dates with any separator using python's strptime


rawDescription: Scatter plot with arrows using matplotlib


code:
from collections import defaultdict
all_classes = defaultdict(set)
for group in groups_and_classes.values():
    for c, vals in group.iteritems():
        all_classes[c].update(set(vals))

rawDescription: What is a faster way of merging the values of this Python structure into a single dictionary?


code:
from collections import deque

def item_with_context(predicate, seq, before=0, after=0):
    q = deque(maxlen=before)
    it = iter(seq)

    for s in it:
        if predicate(s):
            return list(q) + [s] + [x for _,x in zip(range(after), it)]
        q.append(s)

rawDescription: Match an element in a list, then return `n` elements before it and `m` elements after it


code:
import cherrypy

class HelloSessionWorld(object):
    @cherrypy.tools.sessions()
    def index(self):
        if 'data' in cherrypy.session:
            return "You have a cookie! It says: %r" % cherrypy.session['data']
        else:
            return "You don't have a cookie. Get one."
    index.exposed = True

    @cherrypy.tools.sessions()
    def getcookie(self):
        cherrypy.session['data'] = 'Hello World'
        return "Done. Please return to see it"
    getcookie.exposed = True

application = cherrypy.tree.mount(HelloSessionWorld(), '/')

if __name__ == '__main__':
    cherrypy.quickstart(application)

rawDescription: python: interact with the session in cgi scripts

description: Python: interact with the session in cgi scripts


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
email = raw_input("Email: ")
password = raw_input("Password: ")
person =raw_input("Enter the messages link for the one you want to spam\n\
Example: https://www.facebook.com/messages/someone: ")
driver.get("http://www.facebook.com")
elem = driver.find_element_by_id("email")
elem.send_keys(email)
elem = driver.find_element_by_id("pass")
elem.send_keys(password)
elem.send_keys(Keys.RETURN)
driver.get("https://facebook.com/messages/"+person)
elem = driver.find_element_by_css_selector("div textarea.uiTextareaNoResize")
elem.send_keys("python test")
elem.send_keys(Keys.RETURN)

rawDescription: Mechanize not showing FB messages form

description: Mechanize not showing FB messages form


code:
def checkAllCommitMessage(ui, repo, node, **kwargs):
    """
    Checks all inbound changeset messages from a push for adherence to the commit message rules.
    """

    # for each change being submitted
    # get all the details, and call the trigger
    fail = False

    for rev in xrange(repo[node].rev(), len(repo)):
        # get context (change)
        ctx = repo[rev]

        # user who commited the change (NOT necessarily the one who is doing push)
        user = ctx.user()

        # do the hook stuff here...
        # set fail to True if something goes wrong

    return fail

rawDescription: Automating Review Requests with ReviewBoard and Mercurial using Python hooks


code:
import random

def get_regions(i, Chr, Start, End, Len):
    n = EndN = 0
    while 0 < (End - Start) <= int(Len)+15:
        End = int(Dict[i+1].split("\t")[2])
        EndN = int(Dict[i].split("\t")[2])
        i +=1
        n +=1
    if int(Len)-15 <= (EndN - Start) <= int(Len)+15:
        OutFile.write(Chr + '\t'+str(Start)+ '\t'+str(EndN) +'\t'+ str(n) +'\t'+str(int(EndN)-int(Start))+ '\n')
        NewList =[]
    else:
        Chr, Start, End, i = get_random(Keys)

def get_random(Keys):
    i = random.sample(Keys, 1)[0]
    Chr = Dict[i].split('\t')[0]
    Start = int(Dict[i].split('\t')[1])
    End = int(Dict[i+10].split('\t')[2])
    get_regions(i, Chr, Start, End, Len)
    return Chr, Start, End, i

InFile = open(FileB, 'r')
OutFile = open(OutFile, 'w')
Dict = {}
LineCount = 0

for Line in InFile:
    if LineCount > 0:
        Dict[LineCount-1] = Line
    LineCount +=1

LineCount = 0
DiffFile = open(FileA, "r")
for Line in DiffFile:
    if LineCount ==0:
        Header = Line
        OutFile.write(Header)
    else:
        Entries, Len = Line.strip("\n").split("\t")[3:5]
        Keys = Dict.keys()
        Chr, Start, End, i = get_random(Keys)
    LineCount +=1

rawDescription: Get random regions from single sites

description: Get random regions from single sites


code:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import scipy.optimize
import functools

def plane(x, y, params):
    a = params[0]
    b = params[1]
    c = params[2]
    z = a*x + b*y + c
    return z

def error(params, points):
    result = 0
    for (x,y,z) in points:
        plane_z = plane(x, y, params)
        diff = abs(plane_z - z)
        result += diff**2
    return result

def cross(a, b):
    return [a[1]*b[2] - a[2]*b[1],
            a[2]*b[0] - a[0]*b[2],
            a[0]*b[1] - a[1]*b[0]]

points = [(1.1,2.1,8.1),
          (3.2,4.2,8.0),
          (5.3,1.3,8.2),
          (3.4,2.4,8.3),
          (1.5,4.5,8.0)]

fun = functools.partial(error, points=points)
params0 = [0, 0, 0]
res = scipy.optimize.minimize(fun, params0)

a = res.x[0]
b = res.x[1]
c = res.x[2]

xs, ys, zs = zip(*points)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

ax.scatter(xs, ys, zs)

point  = np.array([0.0, 0.0, c])
normal = np.array(cross([1,0,a], [0,1,b]))
d = -point.dot(normal)
xx, yy = np.meshgrid([-5,10], [-5,10])
z = (-normal[0] * xx - normal[1] * yy - d) * 1. /normal[2]
ax.plot_surface(xx, yy, z, alpha=0.2, color=[0,1,0])

ax.set_xlim(-10,10)
ax.set_ylim(-10,10)
ax.set_zlim(  0,10)

plt.show()

rawDescription: Find and draw regression plane to a set of points


code:
def find_descriptor(instance, attrname):
    '''Find the descriptor handling a given attribute, if any.

    If the attribute named attrname of the given instance is handled by a
    descriptor, this will return the descriptor object handling the attribute.
    Otherwise, it will return None.

    '''

    for klass in type(instance).__mro__:
        if attrname in klass.__dict__:
            descriptor = klass.__dict__[attrname]
            if not (hasattr(descriptor, '__get__') or
                    hasattr(descriptor, '__set__') or
                    hasattr(descriptor, '__delete__')):
                # Attribute isn't a descriptor
                return None
            if (attrname in instance.__dict__ and
                not hasattr(descriptor, '__set__') and
                not hasattr(descriptor, '__delete__')):
                # Would be handled by the descriptor, but the descriptor isn't
                # a data descriptor and the object has a dict entry overriding
                # it.
                return None
            return descriptor
    return None

rawDescription: Is it possible to test if object property uses a descriptor?


code:
import pandas as pd
def full_data(dataframe):
    allframes = []
    for i in dataframe.index:
        newframe = pd.DataFrame()
        newframe['dates'] = pd.date_range(dataframe.iloc[i].start, dataframe.iloc[i].end, freq = 'D')
        newframe['name'] = dataframe.iloc[i]['name']
        newframe['address'] = dataframe.iloc[i]['address']
        allframes.append(newframe)
    return concat(allframes)

rawDescription: How to efficiently unfold a date range span in Pandas?

description: Efficiently unfold a date range span in Pandas


code:
def index_containing_substring(the_list, substring):
    for i, s in enumerate(the_list):
        if substring in s:
              return i
    return -1

rawDescription: Get first list index containing sub string in Python


rawDescription: How do I create a list from a single string without splitting the string in python

description: Create a list from a single string without splitting the string in python


code:
import os
import win32com.client

#Launch Excel and Open Wrkbook
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\Full Location\To\excelsheet.xlsm") #opens workbook in readonly mode.

#Run Macro
xl.Application.Run("excelsheet.xlsm!modulename.macroname")

#Save Document and Quit.
xl.Application.Save()
xl.Application.Quit()

#Cleanup the com reference.
del xl

rawDescription: Is there any way I can call Excel VBA function through Python?


code:
G.add_node('a') # adds node 'a'
G.add_edge('b','c') # adds edge 'b'-'c' (and also nodes 'b', 'c')

rawDescription: Better approach to build graph from list clustering related items by two properties


code:
def parse_article(self,response):
    item = response.meta['item']
    item['parameterA'] = response.xpath('somepath').extract_first()

    if item['parameterA'] != "0":
        yield item

rawDescription: Scrapy: How to do I prevent a yield request with a conditional item value?


rawDescription: Where clause with numpy

description: Where clause with numpy


code:
ContactTabClone = TabItem()
ContactTabClone.Name = "ContactClone"
ContactTabClone.Header = "ContactClone"
window.ContactTabs.Items.Add(ContactTabClone)

rawDescription: How can I add a WPF tabitem from Ironpython code and not XAML?

description: Add a WPF tabitem from Ironpython code and not XAML


code:
df
df.groupby("date").agg({"duration": np.sum, "user_id": pd.Series.nunique})
df.groupby("date").agg({"duration": np.sum, "user_id": lambda x: x.nunique()})

rawDescription: Pandas aggregate count distinct

description: Pandas aggregate count distinct


code:
try:
    start_thread()
except (KeyboardInterrupt, SystemExit):
    cleanup_stop_thread();
    sys.exit()

rawDescription: python: how to terminate a thread when main program ends

description: Python: how to terminate a thread when main program ends


code:
field_name = funct()
params = {field_name + '__lte': arg1,       # field_name should still contain string
          'some_other_field_name': arg2}

locations = Locations.objects.filter(**params)

# is the same as (assuming field_name = 'some_name'):
# Locations.objects.filter(some_name__lte=arg1, some_other_field_name=arg2)

rawDescription: Dynamic variable name in python

description: Dynamic variable name in python


code:
from urlparse import urlparse
o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
o
o.scheme
o.port
o.geturl()

rawDescription: how to validate url and redirect to some url using flask

description: Validate url and redirect to some url using flask


code:
def stringify(d, prefix=[]):
    try:
       for k,l in d.items():
           return ['_'.join(prefix+[k])]+[f for e in l for f in stringify(e,prefix+[k])]
    except AttributeError:
        return ['_'.join(prefix+[d])]
stringify(input_dictionary)

rawDescription: how to convert python dictionary into parent-child relation?

description: Convert python dictionary into parent-child relation


code:
def days(n):
    if n == 0:
        return "Sunday"
    elif n == 1:
        return "Monday"
    elif n == 2:
        return "Tuesday"
    elif n == 3:
        return "Wednesday"
    elif n == 4:
        return "Thrusday"
    elif n == 5:
        return "Friday"
    elif n == 6:
        return "Saturday"
    elif n >= 7:
        return days(n % 7)

rawDescription: Always get printed value of "None"

description: Always get printed value of "None"


rawDescription: Python Pandas - How to format and split a text in column ?


code:
import matplotlib
matplotlib.__file__

rawDescription: Python: How can I know which package I am importing?


code:
from email.mime.text import MIMEText
from subprocess import Popen, PIPE

msg = MIMEText("Here is the body of my message")
msg["From"] = "me@example.com"
msg["To"] = "you@example.com"
msg["Subject"] = "This is the subject."
p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
p.communicate(msg.as_string())

rawDescription: Sending mail via sendmail from python

description: Sending mail via sendmail from python


code:
with open("filename", "r+") as file:
    for line in file:
        if needle in line:
           break
    else: # not found, we are at the eof
        file.write(needle) # append missing data

rawDescription: Python: Open a file, search then append, if not exist


code:
import csv
import glob
import os

directory = raw_input("INPUT Folder:")
output = raw_input("OUTPUT Folder:")

txt_files = os.path.join(directory, '*.txt')

for txt_file in glob.glob(txt_files):
    with open(txt_file, "rb") as input_file:
        in_txt = csv.reader(input_file, delimiter='=')
        filename = os.path.splitext(os.path.basename(txt_file))[0] + '.csv'

        with open(os.path.join(output, filename), 'wb') as output_file:
            out_csv = csv.writer(output_file)
            out_csv.writerows(in_txt)

rawDescription: batch process text to csv using python

description: Batch process text to csv using python


code:
def combo_changed(self, widget):
    row = widget.get_active()  # the ID of the requested row
    print(row)
    self.treeview.row_activated(Gtk.TreePath(row), Gtk.TreeViewColumn(None))
    self.treeview.set_cursor(Gtk.TreePath(row))

rawDescription: Python GTK+ 3: How to set row in TreeView active


code:
import re
filename='/tmp/test.txt'
with open(filename,'w') as f:
    f.write(r'\"Hello,\s\"\s*\+\s*\"world!\"')

with open(filename,'r') as f:
    pat = f.readline()
    print(pat)
    # \"Hello,\s\"\s*\+\s*\"world!\"
    print(repr(pat))
    # '\\"Hello,\\s\\"\\s*\\+\\s*\\"world!\\"'
    assert re.search(pat,'  "Hello, " +   "world!"')  # Shows match was found

rawDescription: How to prevent Python from escaping special characters when reading a regex from a text file?

description: Prevent Python from escaping special characters when reading a regex from a text file


code:
options = ['X1', 'X2', 'X3']
qs = [Q(attribute_name=option) for option in options] #or attribute_name__icontains - or whatever

query = qs.pop() #get the first element

for q in qs:
    query |= q

qs = MyModel.objects.filter(query)

rawDescription: How to filter a Django query set by passing in a list of options?

description: Filter a Django query set by passing in a list of options


code:
import pprint
import sodapy

client = sodapy.Socrata(domain='data.energystar.gov', app_token=None)
rows = client.get('ebvx-pb7r', limit=5000)
for row in rows:
    pprint.pprint(row)

rawDescription: Trying to get all fields in a Socrata python API call


code:
from django.db.models import Count

Diagnosis.objects.values(
                         'diagnosis_option','patient__country_of_birth'
                        ).annotate(c = Count('diagnosis_option'))

rawDescription: Django: How to perform correlated query from two tables?


code:
#UNTESTED
def mailer(sender, to, path):

    msg = MIMEMultipart()
    msg['Subject'] = 'UMR_EOD_RECONCILLATIONS'
    msg['From']    = sender
    msg['To']      = to

    msg.attach(MIMEText('Here are the reports you asked for.'))

    for file in os.listdir(path):
        f = open( path + file, 'rb')
        csv = MIMEText(f.read(), 'csv')
        f.close()
        csv.add_header('Content-Disposition', 'attachment', filename=file)

        msg.attach(csv)

    mailer = smtplib.SMTP('localhost')
    mailer.sendmail(sender,to, msg.as_string())
    mailer.quit()

rawDescription: Funny name/ Incomplete Attachment / wrong extension - Mail Python


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

def z_func(x, y):
    return (1 - (x ** 2 + y ** 3)) * np.exp(-(x ** 2 + y ** 2) / 2)

x = np.arange(-3.0, 3.0, 0.1)
y = np.arange(-3.0, 3.0, 0.1)
X, Y = np.meshgrid(x, y)
Z = z_func(X, Y)

im = plt.imshow(Z, cmap=plt.cm.RdBu, extent=(-3, 3, 3, -3))
cset = plt.contour(Z, np.arange(-1, 1.5, 0.2), linewidths=2,
                   cmap=plt.cm.Set2,
                   extent=(-3, 3, -3, 3))
plt.clabel(cset, inline=True, fmt='%1.1f', fontsize=10)
plt.colorbar(im)

plt.title('$z=(1-x^2+y^3) e^{-(x^2+y^2)/2}$')

plt.show()

rawDescription: Python: 2D color map with imshow

description: Python: 2D color map with imshow


code:
import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

rawDescription: How to set the min and max height or width of a Frame?

description: Set the min and max height or width of a Frame


code:
def some_view(request):
    # ...
    return render_to_response('my_template.html',
                              my_data_dictionary,
                              context_instance=RequestContext(request))

rawDescription: Django not recognizing the MEDIA_URL path?


code:
twitter = OAuth1Service(
    name='twitter',
    consumer_key='YOUR_CONSUMER_KEY',
    consumer_secret='YOUR_CONSUMER_SECRET',
    request_token_url='https://api.twitter.com/oauth/request_token',
    access_token_url='https://api.twitter.com/oauth/access_token',
    authorize_url='https://api.twitter.com/oauth/authorize',
    header_auth=True)

params = {'include_rts': 1,  # Include retweets
          'count': 10}       # 10 tweets

response = twitter.get('https://api.twitter.com/1/statuses/home_timeline.json',
                       params=params,
                       access_token=access_token,
                       access_token_secret=access_token_secret,
                       header_auth=True)

rawDescription: Connect to Twitter given already have token?


code:
fig = plt.figure()
ax = fig.gca(projection='3d')
row = np.linspace(-1, 1, 400)
X,Y = np.meshgrid(row,row)
CS = ax.contour(X, Y, im, cmap=cm.coolwarm)
plt.clabel(CS, inline=1, fontsize=10)
plt.savefig("ContourLevel3D.png")

rawDescription: Plot 3D Contour from an Image using extent with Matplotlib


code:
from mptt.models import MPTTModel, TreeForeignKey

class Category(MPTTModel):
    title = models.CharField(max_length=200, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name="children")
    # other fields

    class MPTTMeta:
        order_insertion_by = ['title']

class Item(models.Model):
    title = models.CharField(max_length=200)
    category = models.ForeignKey(Category, related_name='items')
    # other fields

rawDescription: Dynamic categories to models

description: Dynamic categories to models


code:
import numpy as np

def my_func(xs,param1,param2,param3):
    values = xs**param1 + xs*param2**2 + param3*xs
    return values

xs = np.arange(0,10,0.1)
params1 = np.arange(1,2,0.1)
params2 = np.arange(1,2,0.1)
params3 = np.arange(1,5,0.1)

X, P1, P2, P3 = np.meshgrid(xs, params1, params2, params3, sparse=True, indexing='ij')
my_func(X, P1, P2, P3)

rawDescription: Computing an array of values for each meshgrid point


code:
import datetime
datetime.datetime.max

rawDescription: Is there a datetime ± infinity?

description: Is there a datetime ± infinity


code:
import keyword
keyword.kwlist

rawDescription: Is it possible to get a list of keywords in Python?


code:
for ch in "\x1f\xa0#+\x01":
    print("%6s %3d" % (repr(ch), ord(ch)))

rawDescription: os.urandom and byte representation

description: Os.urandom and byte representation


code:
for item in ( x for x in list if condition(x) ):
    pass

rawDescription: for key in dictionary if key ==x:

description: For key in dictionary if key ==x:


code:
urlpatterns = patterns('',
(r'^(?i)admin/(.*)', admin.site.root),
(r'^(?i)static/(?P<path>.*)$', 'django.views.static.serve',
    {'document_root': settings.STATIC_DOC_ROOT, 'show_indexes': True}),
(r'^(?i)login/$', 'django.contrib.auth.views.login'),
(r'^(?i)logout/$', do_logout),
)

rawDescription: Case insensitive urls for Django?

description: Case insensitive urls for Django


code:
import re
text = " T?e  qu!ck ' brown 1 fox! jumps-.ver. the 'lazy' doG?  !"
re.split('(?<=[.!?]) +',text)

rawDescription: Split string on ". ","! " or "? " keeping the punctuation mark


code: selected = random.sample(xrange(100000, 1000000), 500)

rawDescription: Fix a function returning duplicates over time?


code:
def plot_version_data(title, dates, versions, version_ys, savename=None):
    print("Prepping plot for \"{0}\"".format(title))
    fig = plt.figure()
    theplot = fig.add_subplot(111)

    # Our x axis is going to be the dates, but we need them as numbers
    x = [date2num(date) for date in dates]

    # Use these colors
    colormap = "bgrcmy"
    theplot.stackplot(x, version_ys, colors=colormap)

    # Make some proxy artists for the legend
    p = []
    i = 0
    for _ in versions:
        p.append(plt.Rectangle((0, 0), 1, 1, fc=colormap[i]))
        i = (i + 1) % len(colormap)

    theplot.legend(p, versions)
    theplot.set_ylabel(versions) # Cheating way to handle the legend

    theplot.set_title(title)

    # Setup the X axis - rotate to keep from overlapping, display like Oct-16,
    # make sure there's no random whitespace on either end
    plt.xticks(rotation=315)
    theplot.set_xticks(x)
    theplot.set_xticklabels([date.strftime("%b-%d") for date in dates])
    plt.xlim(x[0],x[-1])

    if savename:
        print("Saving output as \"{0}\"".format(savename))
        fig.savefig(os.path.join(sys.path[0], savename))
    else:
        plt.show()

rawDescription: Empty square for legend for stackplot

description: Empty square for legend for stackplot


code: cat if isinstance(cat, Animal) else None

rawDescription: What is the python way to declare an existing object as an instance of a class?


code:
spam= [1,2,3]
stuff = [spam]
eval('spam') in stuff

rawDescription: How to check for a variable name using a string in Python?

description: Check for a variable name using a string in Python


code:
driver.find_element_by_css_selector('description').click()

# extract the data

driver.back()

rawDescription: Open new window after click button

description: Open new window after click button


code:
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(4,2,1)
ax2 = fig.add_subplot(4,2,4)
ax3 = fig.add_subplot(4,2,5)
ax4 = fig.add_subplot(4,2,8)

fig.subplots_adjust(hspace=1)

plt.show()

rawDescription: Python Subplot function parameters

description: Python Subplot function parameters


code:
mydata = simplejson.loads(json_file)

def foo(request):
    ...
    return render(request, 'template.html', {"mydata": mydata},
        content_type="application/xhtml+xml")

rawDescription: Passing static JSON to Django Template - best practices?