code:
import itertools

row_template = """\
{{0:{idx_length}}}{{<1:{teamname_length}}}{{>2:{point_length}}}{{>3:{diff_length}}}{{=4:{goals_length}}}"""

with open('path/to/output.csv') as inf:  # same filename we used before
    reader = csv.reader(inf)  # no need to sort it this time!
    pre_process, reader = itertools.tee(reader)
    # we need to get max lengths for each column to build our table, so
    # we will need to iterate through twice!
    columns = zip(*pre_process)  # this is magic
    col_widths = {k: len(max(col, key=len)) for k,col in zip(
        ['teamname_length', 'point_length', 'diff_length', 'goals_length'],
        columns)}

rawDescription: Print csv input file into a table of columns/rows


code:
def find_elements(tree, child_tag, parent_tag):
    parent_map = dict((c, p) for p in tree.iter() for c in p)
    for el in tree.iter(child_tag):
        parent = parent_map[el]
        if parent.tag == parent_tag:
            yield el, parent

rawDescription: Adding a parent tag to a nested structure with ElementTree (Python)


code:
f = open('test.txt','r')

string = f.read()

words = string.split('\t')
ind = words.index('seven')
desired = words[ind+1]

rawDescription: Scan through txt, append certain data to an empty list in Python


code: a =a.replace('moto', '')

rawDescription: Remove letters from sting

description: Remove letters from sting


code:
def callback2(_):
    ...

rawDescription: How can I prevent Tkinter from passing the event object in a binding? Is there any workaround to do this?

description: Prevent Tkinter from passing the event object in a binding? Is there any workaround to do this


code:
def printing_func(inarg, file=None):
    # (do some stuff...)

    if file is None:
        file = sys.stdout

    print(result, file=file)

rawDescription: How to determine whether code is running in a doctest?

description: Determine whether code is running in a doctest


code:
import re
f = open("test.txt", "rb+")
# Set l to be the last line
for l in f:
    pass
# Get the numbers in the line
numstrings = re.findall('(\d+)', l)
# Handle no numbers
if len(numstrings) == 0:
    num = 0
else:
    num = int(numstrings[0])
f.write("line %d\n"%num)
f.close()

rawDescription: How to make automated writer to append lines in Python

description: Make automated writer to append lines in Python


code:
sql = """SELECT devices.id, devices.names, devices.addresses,
devices.charging, devices.covered, record_temperatures.time
FROM devices
WHERE devices.imei like '%0444258';
"""

rawDescription: SQL formatting examples for long queries in python for psycopg2 connections


code:
index_dict = dict(zip(
    catalogue.index.values.tolist(),
    range(collection.shape[0])))

rawDescription: Selecting rows from a sparse matrix based on the index of a panda dataframe


code:
class Either(Comparator):
    def __init__(self, left, right):
        self.left = left
        self.right = right

    def __eq__(self, other):
        return or_(other == self.left, other == self.right)

class User(Base):
    # ...

    @name.comparator
    def name(self):
        return Either(self.first_name, self.alias)

rawDescription: SQLAlchemy: How can I create a hybrid property for the disjunction of columns?


code: plt.savefig('my_fig.png', dpi=my_dpi)

rawDescription: Specifying and saving a figure with exact size in pixels


rawDescription: How can I clear the Maya Script Editor programatically?

description: Clear the Maya Script Editor programatically


code:
from pprint import pprint

data = {u'jobs': {u'_total': 301746, u'_count': 10, u'_start': 0, u'values': [{u'position':       {u'title': u'Director of Sales, New York '}, u'id': 7489651}, {u'position': {u'title': u'Senior Software Development Engineer'}, u'id': 7489610}, {u'position': {u'title': u'Senior Analyst, Marketing Analytics'}, u'id': 7489572}, {u'position': {u'title': u'Director,  Quantitative Analytics'}, u'id': 7489559}, {u'position': {u'title': u'Senior Quantitative Analyst'}, u'id': 7489542}, {u'position': {u'title': u'Director - Progam Lead and Project Manager - Collateral Management'}, u'id': 7489520}, {u'position': {u'title': u'Accounting and Finance Manager'}, u'id': 7489519}, {u'position': {u'title': u'Software Development Engineer - Test'}, u'id': 7489508}, {u'position': {u'title': u'Sr. Sales Executive - Technology'}, u'id': 7489462}, {u'position': {u'title': u'Recruitment Manager'}, u'id': 7489264}]}}

pprint(data['jobs']['values'])

rawDescription: Parsing object in python

description: Parsing object in python


code:
button = driver.find_element_by_id("#mybutton")
is_hovered(driver, button)

rawDescription: xpath for capturing hover css property from selenium webelement in python

description: Xpath for capturing hover css property from selenium webelement in python


rawDescription: Storing a dict with np.savez gives unexpected result?


code:
h = len(a)
w = len(a[1])
top_left =  [a[i][:h / 2] for i in range(w / 2)]
top_right = [a[i][h / 2:] for i in range(w / 2)]
bot_left =  [a[i][:h / 2] for i in range(w / 2, w)]
bot_right = [a[i][h / 2:] for i in range(w / 2, w)]

rawDescription: Slicing python matrix into quadrants

description: Slicing python matrix into quadrants


code:
from itertools import chain
from operator import itemgetter

sorted_urls = tuple(chain.from_iterable(sorted(zip(urls[::2],
                                                   urls[1::2]),
                                               key=itemgetter(0), reverse=True)))

rawDescription: Is there a way to sort custom objects in a custom way in Python?


code:
d = {}
for i in range(100):
    if not i % 4:
        if 'Four' not in d:
            d['Four'] = []
        d['Four'].append(i)

rawDescription: Is it possible to alter the values in a dictionary, keeping the key value constant?


code:
from collections import namedtuple
Projection = namedtuple('Projection', ['lastq', 'fcast_yr', 'projections', 'yrahead', 'aname', 'actdf', 'merged2', 'mergederrs', 'montdist', 'ols_test', 'mergedfcst'])

rawDescription: Create a summary Pandas DataFrame using concat/append via a for loop


code:
s = "Date Time ProcessName ActivityName : 55 34 00 aa c9 00 11 45 55"
re.findall(r'(?<!\S)[A-Za-z\d]{2}(?!\S)', s)

rawDescription: How to add a set of alphanumeric contents into a list using python?

description: Add a set of alphanumeric contents into a list using python


rawDescription: Find Unique Dates in Numpy Datetime Array


rawDescription: Regular expression to match comma separated list of key=value where value can contain commas


code:
max_len = max(map(len, sequences))
d = defaultdict(lambda: [0]*max_len)  # d[char] = [pos0, pos12, ...]
for seq in sequences:
    for i, char in enumerate(seq):
        d[char][i] += 1

d['G']  # [2, 0, 0, 0, 1, 1]

rawDescription: Counting the number of times a letter occurs at a certain position using python


code:
df = pd.melt(frame, id_vars=['genotype', 'environment'])

sns.factorplot(data=df, x='genotype', y='value',
               hue='environment', col='variable',
               kind='box', legend=True)

rawDescription: Boxplots by group for multivariate two-factorial designs using matplotlib + pandas


code:
d = {}
for (st,sh,le,en) in zip(start,shape,length,end):
    d[st] = (sh,le,en)

rawDescription: Using a dictionary to index parallel arrays?


code:
import numpy as np
def bla(a, b):
    f = a + b
    return f

A, B = np.meshgrid([0.2,0.4], [2,4], sparse=True)
bla(A, B)

rawDescription: Python: obtain multidimensional matrix as results from a function


code:
from Tkinter import *
import subprocess

root = Tk()

e = Entry(root)
e.grid()

b = Button(root,text='QUIT',command=root.quit)
b.grid()

def entryreturn(event):
    proc.stdin.write(e.get()+'\n') # the '\n' is important to flush stdin
    e.delete(0,END)

# when you press Return in Entry, use this as stdin
# and remove it
e.bind("<Return>", entryreturn)

proc = subprocess.Popen('./test.py',stdin=subprocess.PIPE)

root.mainloop()

rawDescription: subprocess.call() interacting with GUI (Tkinter)

description: Subprocess.call() interacting with GUI (Tkinter)


code:
def depth_frame_ready(frame):
    frame.image.copy_bits(tmp_s._pixels_address)

    arr2d = (pygame.surfarray.pixels2d(tmp_s) >> 3) & 4095
    # arr2d[x,y] is the actual depth measured in mm at (x,y)

rawDescription: Access Kinect Depth Data with Pykinect

description: Access Kinect Depth Data with Pykinect


code:
class Person(object):
    def __init__(self, name):
        self.name = name
        self._friends = {}
    def __getattribute__(self, attr):
        if not attr.startswith("friend") or not attr[len("friend"):].isdigit():
            return super(Person, self).__getattribute__(attr)
        index = int(attr[len("friend"):])
        if index in self._friends:
            return self._friends[index]
        return None
    def __setattr__(self, attr, value):
        if not attr.startswith("friend") or not attr[len("friend"):].isdigit():
            return super(Person, self).__setattr__(attr, value)
        index = int(attr[len("friend"):])
        if index in self._friends:
            raise ValueError("%s already defined for %s " % (attr, self.name))
        if not isinstance(value, Person):
            raise TypeError("Friends have to be persons")
        self._friends[index] = value

rawDescription: Initializing values that point to uninitiated classes. Python @property to control setting of elements within a collection


code:
sample = [[0, 3, 7], [0, 3, 7, 9], [0, 2, 3, 4, 7, 8, 9], [2, 4, 8, 9], [2, 4, 7, 8, 9], [5, 6]]
def eliminate_shorter(list_of_lists):
    inputlist = sorted(list_of_lists, key=len)
    outputlist = [inputlist.pop()]
    numbers = set(outputlist[0])
    for sublist in reversed(inputlist):
        if not numbers.intersection(sublist):
            numbers.update(sublist)
            outputlist.append(sublist)
    return outputlist

eliminate_shorter(sample)

rawDescription: How to remove list with in a list if an element in one list is present in the other

description: Remove list with in a list if an element in one list is present in the other


code:
from tkinter import *
import tkinter.scrolledtext as scr

class WorkPlace(Frame):
    def __init__(self, boss = None):
        Frame.__init__(self)

        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(0, weight=1)

        self.scrText = scr.ScrolledText(self)
        self.scrText.grid(sticky="NEWS")

        self.label = Label(self,text = "Label")
        self.label.grid()

rawDescription: Fill space with widgets on resize

description: Fill space with widgets on resize


rawDescription: django max folders number per user

description: Django max folders number per user


code:
class TeamStatsView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'team-stats.html',
            {'team_numbers':Team.objects.values('team_number')})

rawDescription: django model dropdown missing in html view

description: Django model dropdown missing in html view


code:
class Classes(Base):
    students = relationship("Students", secondary=junction_table)

class Students(Base):
    classes = relationship("Classes", secondary=junction_table)

junction_table = Table('enrollment', Base.metadata,
   Column('class_id', Integer, ForeignKey('classes.id')),
   Column('student_id', Integer, ForeignKey('students.id')),
)

rawDescription: Should I use flask sqlalchemy many-to-many relationship?


code:
with open ("data.txt", "r") as myfile:
    data=myfile.readlines()

rawDescription: Parsing text file and storing it in a list


code:
n = 4
a = np.arange(1,n+1)

rawDescription: Generating repetitive data in numpy / pandas in a fast vectorized way


code:
class jpeg(...):
    ...

rawDescription: Avoid double typing class names in python


code:
df
df.dropna(subset=[0,1])
df.dropna(subset=[0,1]).replace('X', 0)

rawDescription: python pandas to drop lines and substitute values in specific columns of a csv file

description: Python pandas to drop lines and substitute values in specific columns of a csv file


code: setattr(test, attr_name, 10)

rawDescription: How can I assign a new class attribute via __dict__ in python?

description: Assign a new class attribute via __dict__ in python


code: from STATIC import basePrice

rawDescription: Cross class variable only initialized once


code:
def prime(x):
    if (2**(x-1))%x ==1:
        return x

rawDescription: Python Generator returning stop iteration?


rawDescription: python list reverse and merge

description: Python list reverse and merge


code:
# Import the module
from docx import *

# Open the .docx file
document = opendocx('yourDocInDocx.docx')

# Search returns true if found
search(document,'your search string')

rawDescription: Make simple edits on Word document programmatically


rawDescription: Scapy padding.load what is the meaning of 'g' and '|' symbols


code:
times = [
    '1434615010.27858',
    '1434615010.27858',
    ]

time_dict = {}

for time in times:
    time_dict[time] = 1

for time in time_dict.keys():
    date = datetime.fromtimestamp(float(time))
    print((str(date).split('.')[0])[:-3])

rawDescription: Python timedate match

description: Python timedate match


code:
# Let's get a list of key=value strings
list_of_items = ['%s=%s' % (k, v) for k, v in xml_dict.iteritems()]
# Now join those items together
new_xml_text = ','.join(list_of_items)
d.text = new_xml_text

rawDescription: Update dictionary in xml from csv file in python


rawDescription: Writing python chunking loops with reference to another txt


code:
# pyclusters.py
# May-02-2013
# -John Taylor

# latlng.tsv is located at http://pastebin.com/cyvEdx3V
# use the "RAW Paste Data" to preserve the tab characters

import math
from collections import defaultdict

# See also: http://www.geomidpoint.com/example.html
# See also: http://www.movable-type.co.uk/scripts/latlong.html

to_rad = math.pi / 180.0  # convert lat or lng to radians
fname = "latlng.tsv"      # file format: LAT\tLONG
threshhold_dist=20        # adjust to your needs
threshhold_locations=20   # minimum # of locations needed in a cluster
earth_radius_km = 6371

def coord2cart(lat,lng):
    x = math.cos(lat) * math.cos(lng)
    y = math.cos(lat) * math.sin(lng)
    z = math.sin(lat)
    return (x,y,z)

def cart2corrd(x,y,z):
    lon = math.atan2(y,x)
    hyp = math.sqrt(x*x + y*y)
    lat = math.atan2(z,hyp)
    return(lat,lng)

def dist(lat1,lng1,lat2,lng2):
    global to_rad, earth_radius_km

    dLat = (lat2-lat1) * to_rad
    dLon = (lng2-lng1) * to_rad
    lat1_rad = lat1 * to_rad
    lat2_rad = lat2 * to_rad

    a = math.sin(dLat/2) * math.sin(dLat/2) + math.sin(dLon/2) * math.sin(dLon/2) * math.cos(lat1_rad) * math.cos(lat2_rad)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a));
    dist = earth_radius_km * c
    return dist

def bounding_box(src, neighbors):
    neighbors.append(src)
    # nw = NorthWest se=SouthEast
    nw_lat = -360
    nw_lng = 360
    se_lat = 360
    se_lng = -360

    for (y,x) in neighbors:
        if y > nw_lat: nw_lat = y
        if x > se_lng: se_lng = x

        if y < se_lat: se_lat = y
        if x < nw_lng: nw_lng = x

    # add some padding
    pad = 0.5
    nw_lat += pad
    nw_lng -= pad
    se_lat -= pad
    se_lng += pad

    #print("answer:")
    #print("nw lat,lng : %s %s" % (nw_lat,nw_lng))
    #print("se lat,lng : %s %s" % (se_lat,se_lng))

    # sutiable for r's map() function
    return (se_lat,nw_lat,nw_lng,se_lng)

def sitesDist(site1,site2):
    # just a helper to shorted list comprehensioin below
    return dist(site1[0],site1[1], site2[0], site2[1])

def load_site_data():
    global fname
    sites = defaultdict(tuple)

    data = open(fname,encoding="latin-1")
    data.readline() # skip header
    for line in data:
        line = line[:-1]
        slots = line.split("\t")
        lat = float(slots[0])
        lng = float(slots[1])
        lat_rad = lat * math.pi / 180.0
        lng_rad = lng * math.pi / 180.0
        sites[(lat,lng)] = (lat,lng) #(lat_rad,lng_rad)
    return sites

def main():
    color_list = ( "red", "blue", "green", "yellow", "orange", "brown", "pink", "purple" )
    color_idx = 0
    sites_dict = {}
    sites = load_site_data()
    for site in sites:
        #for each site put it in a dictionarry with its value being an array of neighbors
        sites_dict[site] = [x for x in sites if x != site and sitesDist(site,x) < threshhold_dist]

    print("")
    print('map("state", plot=T)') # or use: county instead of state
    print("")

    results = {}
    for site in sites:
        j = len(sites_dict[site])
        if j >= threshhold_locations:
            coord = bounding_box( site, sites_dict[site] )
            results[coord] = coord

    for bbox in results:
        yx="ylim=c(%s,%s), xlim=c(%s,%s)" % (results[bbox]) #(se_lat,nw_lat,nw_lng,se_lng)

        # important!
        # if you want an individual map for each cluster, uncomment this line
        #print('map("county", plot=T, fill=T, col=palette(), %s)' % yx)
        if len(color_list) == color_idx:
            color_idx = 0
        rect='rect(%s,%s, %s,%s, col=c("%s"))' % (results[bbox][2], results[bbox][0], results[bbox][3], results[bbox][1], color_list[color_idx])
        color_idx += 1
        print(rect)
    print("")

main()

rawDescription: Detecting geographic clusters

description: Detecting geographic clusters


code:
Z = np.zeros(Xi.shape)
for i in xi:
    for j in xj:
        xy_pair = (xi[i], yi[j])
        Z[j,i] = calcZ(xy_pair)

rawDescription: python matplotlib : ploting 3d surface from string indexed arrays

description: Python matplotlib : ploting 3d surface from string indexed arrays


rawDescription: Selecting top n elements from each group in pandas groupby


code:
import Image
import numpy as np
img = Image.open("Chess_Board.bmp")
a = np.array(img.convert('P', palette=Image.ADAPTIVE, colors=4))
blockLengthX = np.argmin(a[0]==a[0,0])
blockLengthY = np.argmin(a[:,0]==a[0,0])
result = a[::blockLengthX, ::blockLengthY]

rawDescription: convert image to value matrix

description: Convert image to value matrix


code:
from timeit import timeit
import random
testdata = [i*random.random() for i in range(1000)]
def slow_moving_average(samples, n=3):
    return [float(sum(samples[i-j] for j in range(n)))/n for i in range(n-1, len(samples))]

def fast_moving_average(samples, n=3):
    return [sum(samples[i - n + 1:i + 1], 0.0) / n for i in range(n-1, len(samples))]

def verbose_moving_average(samples, n=3):
    l =[]
    for i in range(n-1, len(samples)):
        x = 0.0
        for j in range(n):
            x+= samples[i-j]
        l.append(x / n)
    return l

timeit('f(s)', 'from __main__ import verbose_moving_average as f, testdata as s', number=1000)
timeit('f(s)', 'from __main__ import slow_moving_average as f, testdata as s', number=1000)
timeit('f(s)', 'from __main__ import fast_moving_average as f, testdata as s', number=1000)

rawDescription: Python: Why is list comprehension slower than for loop


code: scores['Mr K'] += 1

rawDescription: Python: reading txt file containing (alphabet and number) and updating the number


code:
def foo(a: int, b: str):
    """Take your arguments back, I don't want them!"""

    return a, b

rawDescription: Is there a python IDE that will tell you the type of a variable when you hover over it?


code:
def __getattr__(self, key):
    return self.get(key)

rawDescription: Is there any trick to "overload the dot operator"?


code:
def disjoin(*fns):
    def disjoined(x):
        for fn in fns:
            if fn(x): return True
        return False
    return disjoined

rawDescription: Concise way to call ifilter with multiple predicates in python


code:
cursor.execute('''
    CREATE TABLE foo (bar INTEGER, baz INTEGER, bing INTEGER, UNIQUE (bar, baz))''')

rawDescription: Basic pySQLite example?

description: Basic pySQLite example


code:
def sort_dns(l):

    to_return = []
    # Get top-level domains: the domains that contain the less amount of dots.
    count_list = [i.count('.') for i in l]
    min_dots = min(count_list)
    top_domains = [i for i in l if i.count('.') == min_dots]
    # Now for each domain, we find it subdomains.
    for domain in top_domains:
        sub_domains = [i for i in l if domain in i and i is not domain]
        #And untill we aren't at the deepest level, we continue looking for sub domains and repeat the structure
        sub_sub_domains = sort_dns(sub_domains) if not len(sub_domains) == 0 else None
        to_return.append({'name' : domain, 'childrens' : sub_sub_domains})

    return to_return

rawDescription: Sorting and organizing DNS records

description: Sorting and organizing DNS records


code: ('/home/unutbu/pybin/foo.py', 4, '<module>', 'import bar')

rawDescription: Is it possible to get "importing module" in "imported module" in Python?


code:
myapp/forms.py
from django.forms import ModelForm
from myapp.models import Article

# Create the form class.
class ArticleForm(ModelForm):
     class Meta:
         model = Article
         fields = ['pub_date', 'headline', 'content', 'reporter']

rawDescription: What is the appropriate way to set up a form and view in Django to accommodate both creating and updating a model


code:
stringin = "470115572 cms_trk_dcs_05:CAEN/CMS_TRACKER_SY1527_7/branchController00/easyCrate3/easyBoard16/channel003"
splitstring = stringin.split(' ')
num = splitstring[0]
stringlist = splitstring[1].split('/')
num
stringlist

rawDescription: separate line in words by slash and use /W but avoid :

description: Separate line in words by slash and use /W but avoid :


code:
from glob import glob
with open('output.csv', 'w') as out:
    for file in glob('*.log'):
        with open(file, 'r') as f:
            for line in f:
                if 'KEYWORD' in line:
                    out.write(line)

rawDescription: Copy select lines from many text files and paste to new file


rawDescription: Pandas: return a Dataframe with multiple aggregate values conditioned on another value


code:
from xml.etree.cElementTree import ElementTree, Element

class XElement( object ):
    '''
    Simple XML serializable field
    '''

    def __init__( self, path):
        self.path = path
        self._xml = Element(path) # using an ElementTree or lxml element as internal storage

    def get_xml( self, inst ):
        return inst._xml

    def _get_element( self ):
        return self.path

    def _get_attribute( self ):
        return None

    # the getter and setter push values into the underlying xml and return them from there
    def __get__( self, instance, owner=None ):
         myxml = self.get_xml( instance )
         underlying = myxml.find( self.path )
         return underlying.text

    def __set__( self, instance, value, owner=None ):
        myxml= self._get_xml( instance )
        underlying = myxml.find( self.path )
        underlying.text = value

rawDescription: Python XML Serialisation using attributes


code:
# create memmap
data = num.memmap('filename', mode='w+', dtype=num.float, offset=myoffset, shape=(my_shape), order='C')
# put some data into in:
data[1:10] = num.random.rand(9)
# flush to disk:
data.flush()
del data

rawDescription: How to write variables as binary data with Python?

description: Write variables as binary data with Python


code:
client = xmlrpclib.ServerProxy('http://user:password@blah.com/plone')
completePath = '/'.join(client.getPhysicalPath()) + '/sites/ng/path/to/folder'
if len(client.portal_catalog.searchResults(path=completePath)):
    return True

rawDescription: How to check if a folder exists by its complete path in Plone?

description: Check if a folder exists by its complete path in Plone


code: (r".", unknown)

rawDescription: Tokenize and label text

description: Tokenize and label text


code:
similarity_score(['apple', 'orange', 'apple', 'apple', 'banana', 'orange'], ['apple', 'orange', 'grapefruit', 'apple'])
similarity_score(['apple', 'apple', 'orange', 'orange'], ['apple', 'orange'])

rawDescription: Compute the similarity between two lists


rawDescription: Order record array by unique occurances

description: Order record array by unique occurances


code:
def get_min_max(x, pad=0.05):
    '''
    Find min and max values such that
    all the data lies within 90% of
    of the axis range
    '''
    r = np.max(x) - np.min(x)
    x_min = np.min(x) - pad * r
    x_max = np.max(x) + pad * r
    return x_min, x_max

rawDescription: Adjust exponent text after setting scientific limits on matplotlib axis


code: {'Mammals': ['dog', 'cat'], 'Reptiles': ['snake', 'turtle'], 'Birds': ['seagull', 'owl']}

rawDescription: Iterate over both text and elements in lxml etree


code:
class Test(object):

    def __init__(self):
        self.a = 20
        self.b = 30

if __name__ == '__main__':
    test_instance = Test()

rawDescription: Class Inheritance

description: Class Inheritance


code:
import re
s_pat = re.escape(r'*text*')
assert s_pat[0] == '\\'
assert s_pat[1] == '*'

rawDescription: why \* escapes even when it is a raw string?

description: Why \* escapes even when it is a raw string


rawDescription: ascii file parsing based on position and length in line using python

description: Ascii file parsing based on position and length in line using python


code:
import datetime
result = sorted(conversations, key=lambda x: datetime.datetime.strptime(x['last_message']['sent_at'],'%Y-%m-%dT%H:%M:%S.%fZ'))

rawDescription: Python sorting a list of deeply nested dictionaries by value


code:
increase_event = pygame.USEREVENT + 1
pygame.time.set_timer(increase_event, number_change_time_in_milliseconds)

rawDescription: Watch numbers add up in pygame

description: Watch numbers add up in pygame


rawDescription: Groupby - taking last element - how do I keep nan's?


code: fReplace = lambda k: d.get(k, sensible_default_value)

rawDescription: Mapping list of lists to pandas Series

description: Mapping list of lists to pandas Series


rawDescription: Given a list of lists in Python, return the maximum length uniquely-valued sublists


code:
from ctypes import *
from ctypes.wintypes import *

GetRate = windll.YOURLIB.GetRate
GetRate.restype = c_int
GetRate.argtypes = [HANDLE, POINTER(c_int)]

# now call GetRate as something like:
#
# hDev = ... # handle
# Data = c_int()
#
# GetRate(hDev, byref(Data)) # GetRate(hDev, &Data)
# print Data

rawDescription: Python ctypes integer pointer

description: Python ctypes integer pointer


rawDescription: Is there a way to check whether a related object is already fetched?


code:
import sys
from _io import TextIOWrapper

class StdoutFilter(TextIOWrapper):

    def __init__(self, stdout):
        super().__init__(stdout)
        self.stdout = stdout

    def write(self, output):
        if output != "don't write this":
            self.stdout.write(output)

sys.stdout = StdoutFilter(sys.stdout)

print("hello, world!")
print("don't write this")

sys.stdout = sys.__stdout__

rawDescription: Prevent string being printed python

description: Prevent string being printed python


rawDescription: Regex to match space and a string until a forward slash


code: ['Crystal Palace 2.95', 'X 3.20', 'Everton FC 2.40']

rawDescription: Selenium and phantomjs not opening javascript page


code:
x = (u'Republican', u'ORGANIZATION', u'Party', u'ORGANIZATION')
x[::2]
x[-1]

rawDescription: Chunking Stanford Named Entity Recognizer (NER) outputs from NLTK format


code: lambda x, regexobject=re.compile(r'foobar'): regexobject.match(x)

rawDescription: Can I have anonymous function with "static" variables in Python?

description: Have anonymous function with "static" variables in Python


code:
for k, v in mydict.items():
    if v == 3:
        del mydict[k]
mydict

rawDescription: How to delete items from a dictionary while iterating over it?

description: Delete items from a dictionary while iterating over it


code:
def letterGuess(letter, button):
    button.config(state=DISABLED)

rawDescription: Sneaky way of disabling a button once it's been pressed?


code: fractExpr = Optional(number) + Optional(fraction)

rawDescription: How can fractional number expressions be parsed using pyparsing?


code:
entry = Entry('test', 'entry')
entry.uppercase()

db.session.add(entry)
db.session.commit()

rawDescription: What alterations do I need to make for my Flask python application to use a MySQL database?


code: middle = lambda x: x[[slice(np.floor(d/4.),np.ceil(3*d/4.)) for d in x.shape]]

rawDescription: Index the middle of a numpy array?

description: Index the middle of a numpy array


code: items[0][1].extend([i for i in reversed(range(1, num + 1))])

rawDescription: Appending numbers into a list in reverse


rawDescription: Python, lxml - get a sibling tag's (grand)child's text


rawDescription: Convert multiple lines to single line and store in a variable in python


code: Dict1 = {c[0]: {} for c in PriceList}

rawDescription: 'int' object has no attribute 'update' - dictionary within dictionary - python2.7


code:
for line in my_text:
    outputfile.writelines(data_parser(line, reps))

rawDescription: Text File Parsing with Python

description: Text File Parsing with Python


code:
# First example
if T[s - c * x, i]:
    T[s, i+1] = True
    # Key is (s, i+1)

# Second example
elif cursor.rowcount == 1:
    cursor.execute (""" UPDATE data_table SET state=True WHERE value = '%s'""" % ([s - c * x, i]))
    # Key is (s - c * x, i)

rawDescription: Results are different between python and mysql for similar command


code:
# initially, points is a list of lists of lists
points = itertools.chain.from_iterable(points)
# now points is an iterable producing lists
points = itertools.chain.from_iterable(points)
# now points is an iterable producing coordinates
points = itertools.chain.from_iterable(points)
# now points is an iterable producing individual floating points values
data = numpy.fromiter(points, float)
# data is a numpy array containing all the coordinates
data = data.reshape( data.size/2,2)
# data has now been reshaped to be an nx2 array

rawDescription: numpy arrays: filling and extracting data quickly

description: Numpy arrays: filling and extracting data quickly


code: dict(k.partition('=')[::2] for k in split)

rawDescription: how to separate string from unformed string

description: Separate string from unformed string


code:
from re import split
lista = ['janu', 'manu', 'tanu', 'banu']
listb = []
for item in lista:
    data = split("(^[^aeiou]+)(?=[aeiouy])", item)
    listb.append(data[2]+data[1]+"doc")
listb

rawDescription: Applying regex on each item of a list in Python


code:
import argparse
parser = argparse.ArgumentParser(description='Python Grep.')
parser.add_argument('--debug', action='store_true', help='Print debug messages')
parser.add_argument('pattern', type=str, nargs='+', help='Pattern(s) for pgrepping')
parser.print_help()
parser.parse_args(['where'])
parser.parse_args(['were'])
parser.parse_args(['were', 'you'])
parser.parse_args(['--debug', 'were', 'you'])

rawDescription: Take multiple patterns from cli. argparse Python3


code:
delta_to_start_and_end(2012, 32)
delta_to_start_and_end(2011, 32)
delta_to_start_and_end(2012, 34)
delta_to_start_and_end(2012, 364)

rawDescription: Python: Date manipulation code

description: Python: Date manipulation code


code:
idlist = [ ]
with open(filename, "rb") as f:
    while True:
        bytes_read = f.read(struct.calcsize("=l"))
        if not bytes_read: break
        oneid = struct.unpack("=l", bytes_read)[0]
        idlist.append(oneid)

rawDescription: Reading a binary file in Python into a struct


code:
for k,v in sorted(class1.items()):
    print(k, v)

rawDescription: How do I print a sorted Dictionary in Python 3.4.3

description: Print a sorted Dictionary in Python 3.4.3


code: result = [x for x in zip(datarelmax_0[0], datarelmax_0[1]) if x in zip(datarelmax_1[0], datarelmax_1[1])]

rawDescription: How to create a numpy array from two lists of tuples, but only when the tuples are the same

description: Create a numpy array from two lists of tuples, but only when the tuples are the same


code:
from collections import Counter
x = Counter(['abc','def','abc'])
y = ['abc', 'def', 'abc', 'abc', 'ghi', 'jkl','jkl']
x.update(dict.fromkeys(y, 0))

rawDescription: How to create a list of counts from a unique list and a Counter object?

description: Create a list of counts from a unique list and a Counter object


code:
from itertools import islice
from collections import deque

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

rawDescription: Incrementing itertools.imap without reading to object in Python for performance


code:
def group_day(date):
    if date.weekday() in [5,6]:
        return 'weekend'
    elif date.date() in bday_over_df:
        return 'weekday'
    else:
        return 'holiday'

df['day_group'] = df.index.map(group_day)

rawDescription: Average hourly week profile for a year excluding weekend days and holidays


code:
def any_function_7():
    return any_function(7)
b = Button(app_name, text="..." , command = any_function_7)

rawDescription: tkinter , python , buttons

description: Tkinter , python , buttons


code:
# my_setup_file.py
def my_setup():
    do_something()
    do_something_else()

rawDescription: Call python file from suite setup in robot framework


code:
class YourTestCase(unittest.TestCase):
    def setUp(self):
        self.current_url = 'xyz'

    def test_check_url(self):
        self.assertEqual(self.current_url, 'xyz')

rawDescription: Python unit test how do I pass variable from one function to another


code:
from matplotlib.ticker import ScalarFormatter
for axis in [ax.xaxis, ax.yaxis]:
    axis.set_major_formatter(ScalarFormatter())

rawDescription: Matplotlib log scale tick label number formatting


code:
import dis
D = {"a": 1, "b": 2, "c": 3}
def gt(): return D.get('a', 1)

dis.dis(gt)

rawDescription: Why is an inline if/else faster than a .get() in Python?


code:
OVERTIMERATE = 1.5 # maybe 2?
first,last,hours,wage = line.split(',')
hours, wage = int(hours), float(wage) # Decimal is better here, but...
OTpay, regPay = 0,0 # initialize
while hours > 40:
    hours -= 1
    OTpay += wage*OVERTIMERATE
while hours > 0:
    hours -= 1
    regPay += wage

rawDescription: How to select a range of numbers to multiply an hourly wage by

description: Select a range of numbers to multiply an hourly wage by


code:
class Foo:
    def bar(self): pass

f = Foo()
f.bar is f.bar

rawDescription: What is the right way to test for equality between a Python variable and a callable?


code:
X_pos
X_neg
X_pos.A
X_neg.A

rawDescription: splitting a sparse matrix into two

description: Splitting a sparse matrix into two


code:
def subtract_score(d):
    d = d.copy()
    d['score'] -= 1
    return d

rawDescription: List of dictionaries - subtract a constant from each dictionary value


code:
def update_condition(self, type, params):
    for i,condition in enumerate(self.conditions):
        condition_loaded = json.loads(condition)
        if condition_loaded['type'] == type:
            condition_loaded['params'] = params
            self.conditions[i] = json.dumps(condition_loaded)

rawDescription: Modify values of a list while iterating over it in Python?


code: log4j.rootCategory=INFO, console

rawDescription: How to turn off INFO logging in PySpark?

description: Turn off INFO logging in PySpark


code:
import dis
dis.dis(palindrome)
dis.dis(palindrome_2)

rawDescription: Why is this method of testing for palindromes so much slower?


code:
def cycle_file(filename):
    while True:
        yield from open(filename)

rawDescription: Re-reading file when cycling over a file object in Python


code: ['feature1', 'feature2', 'feature3', 'target=no', 'target=yes']

rawDescription: change a list of dictionaries to feature vector and target in scikit

description: Change a list of dictionaries to feature vector and target in scikit


rawDescription: Pandas: Counting the proportion of zeros in rows and columns of dataframe


code: datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%a')

rawDescription: Convert Date String to Day of Week

description: Convert Date String to Day of Week


code:
myclass_list = []

class MyClass(object):

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def power(self):
        print(self.x**self.y)

    def divide(self):
        print(self.x/self.y)

myclass_list.append(MyClass(2, 3))
myclass_list.append(MyClass(4, 7))
all_powers = [i.power() for i in myclass_list]

rawDescription: Is there a way to run a method for all instances of a class in python?


code:
html_data = """

    Card balance
    $18.30

    Card name
    NAMEn

    Account holder
    NAME

    Card number
    1234

    Status
    Active

"""

rawDescription: Convert a HTML Table to JSON

description: Convert a HTML Table to JSON


rawDescription: Ordereddict Merge by Month, and Week python


code:
loop=1
choice=0

print("Welcome to Calculator Function!")
n = input("How many operations do you want to do?: ")
for _ in xrange(n):
        print("Your options are:")
        print(" ")
        print("1) Addition")
        print("2) Subtraction")
        print("3) Multiplication")
        print("4) Division")
        print("5) Quit CalculatorFunction.py")
        print(" ")

rawDescription: Creating A Program That terminates After X Amount times


rawDescription: converting python source code to utf-8

description: Converting python source code to utf-8


code:
def valid(s):
    return re.match('[0-9]+(\.[0-9]*)?$', s) is not None

assert valid("42")
assert valid("13.37")
assert valid("1.")
assert not valid("1.2.3.4")
assert not valid("abcd")

rawDescription: regex for character appearing at most once

description: Regex for character appearing at most once


code:
from itertools import islice

numbers = iter(range(10))
for i in numbers:
    if i == 2:
        next(islice(numbers, 3, 3), None)  # consume 3

rawDescription: How do I skip a few iterations in a for loop

description: Skip a few iterations in a for loop


code: result = defaultdict(dict).update({bigkey: {k: v / sum(d.values()) for k,v in d.items()} for bigkey,d in yourdict.items()})

rawDescription: Accessing dictionary within dictionary

description: Accessing dictionary within dictionary


code:
import numpy as np
import pandas as pd
from scipy.spatial import KDTree
import pylab as pl

xc1, xc2, yc1, yc2 = 113.49805889531724, 115.5030664238035, 37.39995194888143, 38.789235929357105

N = 1000
GSIZE = 20
x, y = np.random.multivariate_normal([(xc1 + xc2)*0.5, (yc1 + yc2)*0.5], [[0.1, 0.02], [0.02, 0.1]], size=N).T
value = np.ones(N)

df_points = pd.DataFrame({"x":x, "y":y, "v":value})

rawDescription: Find a easier way to cluster 2-d scatter data into grid array data


code:
with open(file, 'r') as f:
    blobs = []
    lines = [x for x in unuuencode(f, collector=blobs)]

rawDescription: Python - delete uuencoding lines

description: Python - delete uuencoding lines


rawDescription: lxml python load html string without header and body and add element around targeted elements

description: Lxml python load html string without header and body and add element around targeted elements


rawDescription: List species names in local MySQL EnsEMBL database via PyCogent?


code:
new_text=""
for line in lines:
    new_text= new_text + fix_line(line)

def fix_line(line):
     for i, j in dic.iteritems():
          new_line = re.sub("\\b"+i+"\\b", j, line)
          if new_line != line: #line changed stop loop
               return new_line
     return line #line didn't match

print(new_text)

rawDescription: Python: Replace multiple strings with multiple strings in files


code:
import ConfigParser
parser = ConfigParser.RawConfigParser()
parser.optionxform = str # make option names case sensitive
parser.read("/etc/skel/examples.desktop")
parser.set("Desktop Entry", "Name", replace_name)
parser.write(open("modified.desktop", "w"))

rawDescription: Replacing variable text in between two known elements


code: os.system('bash -c "source /Users/YOUR_USER_NAME/.bash_profile;vpn-connect"')

rawDescription: How to call a self-defined command line function in Python

description: Call a self-defined command line function in Python


code:
{"author": "string", "name": "\"string in quotes\"", "description": "string", "info": "string", "year": "number"}
{"author": "string2", "name": "\"other string in quotes\"", "description": "string2", "info": "string2", "year": "number2"}

rawDescription: How to parse text file in Python and convert to JSON

description: Parse text file in Python and convert to JSON


code: sTable += '\n%s' % sRow

rawDescription: Why is variable1 += variable2 much faster than variable1 = variable1 + variable2?


code:
from itertools import chain
from collections import defaultdict

a = {'I': [1,2], 'II': [1,2], 'IV': [1,2]}
b = {'I': [3,4], 'II': [3,4], 'V': [3,4]}

d = defaultdict(list)
for key, value in chain(a.iteritems(), b.iteritems()):
    d[key].extend(value)
d

rawDescription: Merging two dictionaries with nested arrays


code: nums = [int(num) for num in raw_input('Enter some numbers: ').split(',')]

rawDescription: user inputs ipython

description: User inputs ipython


code:
import csv
with open('data.csv') as f:
    data = [row for row in csv.reader(f)]

rawDescription: Python List splitting, sorting by date, then joining


code:
times = {'open': '08:00', 'close': '17:00'}
SubElement(schedule, 'Sunday', times)

rawDescription: What is the proper way to automate use of ElementTree in Python?


code: make_acronym('light amplification by the simulated emission of radiation')

rawDescription: How to sort specific string, in the following situation (PYTHON)

description: Sort specific string, in the following situation (PYTHON)


code: ax3.plot_surface(xi, ti, u_int, cmap=cm.coolwarm)

rawDescription: Why is my 2D interpolant generating a matrix with swapped axes in SciPy?


rawDescription: How does np.multiply work?

description: How does np.multiply work


code:
url_text = filehandle.readlines()
for line in url_text:
    pass

# can be shortened to:
for line in filehandle:
    pass

rawDescription: Adding for-loop elements to a list

description: Adding for-loop elements to a list


code:
amounts = request.form.getlist('amount')
item_ids = request.form.getlist('item_id')
for item_id, idx in enumerate(item_id):
    amount = amounts[idx]
    # do something with item_id and amount

rawDescription: Get multiple values from one HTML input through Python Flask


code:
bigramsset = set( [ ("the","end"), ("end","of"), ("of","the"), ("the","world") ] )
L1 = ["the","end"]
tuple(L1) in bigramsset

rawDescription: comparing lists with tuples in python

description: Comparing lists with tuples in python


code:
optparse
#!/usr/bin/env python
import fileinput
import sys
from optparse import OptionParser

parser = OptionParser()
parser.add_option('-o', '--output',
    help='Specifies the output file.  The default is stdout.')
options, files = parser.parse_args()
if options.output and options.output != '-':
   sys.stdout = open(options.output, 'w')

for line in fileinput.input(files):
    process(line)

rawDescription: Consistent way to redirect both stdin & stdout to files in python using optparse


code:
from numpy import *
from numba import jit

myarray=random.randint(0,2,64).astype(uint64)

def convert1(arr) : return (arr*(2**arange(arr.size,dtype=uint64))).sum()

pow2=2**arange(64,dtype=uint64)
def convert2(arr) : return (arr*pow2[:arr.size]).sum()

@jit("uint64(uint64[:])")
def convert3(arr):
    m=1
    y=0
    for i in range(arr.size):
        y=y + pow2[i] * arr[i]
    return y

rawDescription: Efficiently build an integer from bits of a boolean Numpy array


code:
data = rand(600,600)
extent = [.002, .018, 10, 80]

ax = gca()
ax.imshow(data, extent=extent, aspect='auto', interpolation='nearest')

plt.draw()

rawDescription: matplotlib 2d data with floating values ranges

description: Matplotlib 2d data with floating values ranges


code:
def _translate(args, kwargs):
    for key in kwargs.keys():
        if key in __translation.keys():
            kwargs[__translation[key]] = kwargs[key]
            del kwargs[key]
    return args, kwargs

class WorkersManager(models.Manager):
    def filter(self, *args, **kwargs):
        args, kwargs = _translate(args, kwargs)
        return super(WorkersManager, self).filter(*args, **kwargs)

    # etc...

rawDescription: Django : how could I overload Q in django.db.models.query QuerySet to use for a special purpose in my Manager


code:
def minor(arr,i,j):
    # ith row, jth column removed
    return arr[np.array(range(i)+range(i+1,arr.shape[0]))[:,np.newaxis],
               np.array(range(j)+range(j+1,arr.shape[1]))]

rawDescription: Numpy Routine for Computing Matrix Minors?


code:
len(df_all[df_all['infraspecific_name'] == 'NA'])
1825

rawDescription: .fillna column if two cells are empty in Pandas


rawDescription: Using data from pythons pandas dataframes to sample from normal distributions


code:
datarr = ['PowUse', 'PowHea', 'PowSol', 'Top']
data = dict((name, {}) for name in datarr)

rawDescription: looping dictionaries of {tuple:NumPy.array}

description: Looping dictionaries of {tuple:NumPy.array}


code:
import numpy as np
k = k[..., np.newaxis]

rawDescription: Is this the best way to add an extra dimension to a numpy array in one line of code?


code:
class Camera(Node):
    def __init__(self, name="", attributes=None, children=None, enabled=True):
        super(Camera, self).__init__(name=name, attributes=attributes, children=children)
        self.enabled = enabled

        # defaults
        self.add_node_attributes()

rawDescription: python subclasses have general functions shared across them

description: Python subclasses have general functions shared across them


rawDescription: Creating New Array when Second Array is > 0


rawDescription: Swap axes of a multidimensional Python list


code:
def comp(list1, list2):
    for val in list1:
        if val in list2:
            return True
    return False

rawDescription: Python - Comparing two lists

description: Python - Comparing two lists


code:
elements = driver.find_elements_by_css_selector(".dropdown.right")
# elements[0]
# elements[1]
# ...

rawDescription: Selenium with Python - find elements of more than one css class


rawDescription: Order a NXM Numpy Array according to cumulative sums of each sub-array


code:
aux = {
                    'location_id' : location['id'],
                    'name' : location['name'] or " ",
                    'units' : location['units'] or 0.0,
                    'area' : location['area'] or 0.0,
                    'day_meter' : location['day_meter'] or 0.0,
                    'free' : location['free'] or 0.0,
                    'type' : location['type'] or " ",
                    'loc_type' : location['loc_type'] or " ",
                    'image' : base64.b64encode(str(location['image'])),
               }

rawDescription: Get binary data (Image file) in Java from Python with xml-rpc protocol


code: conn.row_factory = sqlite3.Row

rawDescription: Mapping result rows to namedtuple in python sqlite


code:
import marshal, types

code = marshal.loads(code_string)
func = types.FunctionType(code, globals(), "some_func_name")

func(10)  # gives 100

rawDescription: Is there an easy way to pickle a python function (or otherwise serialize its code)?


rawDescription: checking if pandas dataframe is indexed?

description: Checking if pandas dataframe is indexed


code: Pos = collections.namedtuple('Pos', 'x y')

rawDescription: Best way to "overload" function in python?

description: "overload" function in python


code:
import rijndael
import base64

KEY_SIZE = 16
BLOCK_SIZE = 32

def encrypt(key, plaintext):
    padded_key = key.ljust(KEY_SIZE, '\0')
    padded_text = plaintext + (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE) * '\0'

    # could also be one of
    #if len(plaintext) % BLOCK_SIZE != 0:
    #    padded_text = plaintext.ljust((len(plaintext) / BLOCK_SIZE) + 1 * BLOCKSIZE), '\0')
    # -OR-
    #padded_text = plaintext.ljust((len(plaintext) + (BLOCK_SIZE - len(plaintext) % BLOCK_SIZE)), '\0')

    r = rijndael.rijndael(padded_key, BLOCK_SIZE)

    ciphertext = ''
    for start in range(0, len(padded_text), BLOCK_SIZE):
        ciphertext += r.encrypt(padded_text[start:start+BLOCK_SIZE])

    encoded = base64.b64encode(ciphertext)

    return encoded

def decrypt(key, encoded):
    padded_key = key.ljust(KEY_SIZE, '\0')

    ciphertext = base64.b64decode(encoded)

    r = rijndael.rijndael(padded_key, BLOCK_SIZE)

    padded_text = ''
    for start in range(0, len(ciphertext), BLOCK_SIZE):
        padded_text += r.decrypt(ciphertext[start:start+BLOCK_SIZE])

    plaintext = padded_text.split('\x00', 1)[0]

    return plaintext

rawDescription: Decrypting strings in Python that were encrypted with MCRYPT_RIJNDAEL_256 in PHP


code:
rx = re.compile("^TEMPLATES = \(.+\)")
rx.match(w)

rawDescription: Python regex: matching a parenthesis within parenthesis


code: data = [{'name': cards['name']} for cards in jsonList]

rawDescription: Django Iterating Json Response In Template


code:
#!/usr/bin/python
import sys

# Print a Hello notice
sys.stdout.write("I have been invoked!\n")

# Read the value coming from the pipe
value = sys.stdin.readline()

# Return a "processed" value
sys.stdout.write("New: " + value)

description: Python subprocess.stdout.readline doesn't


code:
import sets
s1 = sets.Set(iFollow)
unfollowThese = s1.difference(followsMe)

rawDescription: Create new list containing list x but not elements in list y that are the same as in list x - python


rawDescription: Exporting Beautiful Soup table scrape results to CSV


code: print("Your number is {}.".format(a))

rawDescription: Need assistance on Print function

description: Need assistance on Print function


code:
class B(object):
    def __init__(self):
        self.x = 10
    @property
    def x(self):
        return "I ain't returning x but something weird, and x is %s... FYI"\
                % self._x
    @x.setter
    def x(self, x):
        self._x = int(self._x if hasattr(self, '_x') else 0 + 2 * x)

def A():
    return B()

rawDescription: Duck-typable classes, ABC, iheritance, __new__


code:
with open('in.txt') as fin:
    lines = fin.readlines()
lines[0] = lines[0].replace('old_value', 'new_value')

with open('out.txt', 'w') as fout:
    for line in lines:
        fout.write(line)

rawDescription: Replace certain element in only first line of the text file


code:
octave:4> last_v = ones(N, 1) * inf;
octave:10> norm(v - last_v, 2)
ans = Inf
octave:13> norm(v - last_v, 2) > v_quadratic_error
ans =  1

rawDescription: PageRank python implementation, algorithm


code:
mnu1 = Team("ManUtd")
mnu2 = Team("MNU")
mnu1 == mnu2
ars = Team("ARS")
ars == mnu1
fail = Team("Not a name")

rawDescription: Finding equality between different strings that should be equal


code:
class Stats:
    def __init__(self, age=None, address=None):
        self.age = age
        self.address = address

data = {}
for name in names:
    age, addr = request(name)
    data[name] = Stats(age, addr)

rawDescription: How to populate a dict

description: Populate a dict


code:
k = subprocess.Popen(['python', 'test2.py', 'w:\bin\test2.py'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
k.communicate()
k = subprocess.Popen(['python', r'w:\bin\test2.py', r'w:\bin\test2.py'], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
k.communicate()

rawDescription: Python on Windows: path as subprocess argument gets modified and generating error


code: hour, minute, second, am_pm, long, lat = mat.groups()

rawDescription: Finding text in a string matching patterns


code:
def get_waveforms_views(data, spiketimes, lookback=100, lookahead=100) :
    ret = []
    for j in spiketimes :
        if j < lookback or j + lookahead >= len(data) :
            ret.append(None)
        else :
            ret.append(data[j - lookback:j + lookahead])
    return ret

rawDescription: Most efficient way to extract parts of one array based on another


code: params = urllib.urlencode({k: v for k, v in (('orange', orange), ('apple', apple)) if v is not None})

rawDescription: Only add to a dict if a condition is met


code:
if symbol in reps or letter in reps.values():
    print("You already used either the symbol or the letter")

rawDescription: Updating dictionaries in python

description: Updating dictionaries in python


code:
from __future__ import division
(10 - 20) / (100 - 10)

rawDescription: Python division

description: Python division


rawDescription: Strings- taking out a letter at the start of each string in a list


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--inputdir', help="Specify the input directory")
parser.print_help()
parser.parse_args(['-i', '/some/dir'])
parser.parse_args(['--inputdir', '/some/dir'])

rawDescription: How to make a short and long version of a required argument using Python Argparse?

description: Make a short and long version of a required argument using Python Argparse


code:
keyvals_for_source = [(key, val)
                      for key, items in the_dict.iteritems()
                      for src, val in items
                      if src == source]

rawDescription: python data structure suggestion

description: Python data structure suggestion


code:
def create_closure(objs):
    creat_cell = lambda x: (lambda: x).__closure__[0]
    return tuple(create_cell(obj) for obj in objs)

rawDescription: How to apply a decorator to subroutines in python

description: Apply a decorator to subroutines in python


code:
def countdown(start):
    return list(range(start,0,-1))

rawDescription: Python: How to countdown a number, and append that countdown to a list


code:
db = sqlite3.connect('temp.sqlite')
c = db.cursor()
c.execute('CREATE TABLE Things (tid, ua)')
for thing in things:
    for ua in thing['ua']:
        c.execute('INSERT INTO Things (tid, ua) VALUES (?, ?)',
                  thing['id'], ua)
c.commit()
c.execute('SELECT tid, ua FROM Things ORDER BY tid')
rows = iter(c.fetchone, None)
grouped_things = itertools.groupby(rows, key=operator.itemgetter(0))
new_things = (merge(list(group)) for key, group in grouped_things)
with open('eggs.json', 'w') as f:
    for thing in new_things:
        f.write(json.dumps(thing) + '\n')

rawDescription: Combining JSON values based on key

description: Combining JSON values based on key


code:
class BST:
    def __init__(self):
        self.root = None

    def insert(self, x):
        def recurse(p):
            if x<p.data:
                if p.left==None:
                    p.left = BSTNode(x)
                else:
                    recurse(p.left)
            else:
                if p.right==None:
                    p.right = BSTNode(x)
                else:
                    recurse(p.right)
        if self.root==None:
            self.root = BSTNode(x)
        else:
            recurse(self.root)

rawDescription: Output BST in Nested Form

description: Output BST in Nested Form


code: df.unstack(['lat', 'lon'])

rawDescription: Multiindex to different columns in Pandas Dataframe


code:
with open("test.txt",encoding="utf-8") as f:
    rep = re.compile(r"""
                        http[s]?://.*?\s
                        |www.*?\s
                        |(\n)
                        """, re.X)
    non_asc = re.compile(r"[^\x00-\x7F]")
    for line in f:
        non = non_asc.search(line)
        if non:
            continue
        m = rep.search(line)
        if m:
            line = line.replace(m.group(), "")
            if line.strip():
                print(line.strip())

rawDescription: Remove urls, empty lines, and unicode characters in python


code:
class user_class(object):
    def __init__(self, x):
        self.x = x

    def __call__(self, y, z): # No x as parameter!
        return do_anything_with(self.x, y, z) # use the predefined x here

rawDescription: Python: Passing function with arguments to a function


code:
Output
Namespace(weeks=[1, 2, 3])

rawDescription: How to pass flexible amount of arguments using getopt in python?

description: Pass flexible amount of arguments using getopt in python


rawDescription: Random Trees in OpenCV from python

description: Random Trees in OpenCV from python


code:
with open("testnucsv.csv", "w") as f:
   for sent in bdictionary:
        f.write(" ".join([" ".join(v) for v in sent])+"\n")

rawDescription: Python - Remove Braces and Commas from a Tuple CSV File


code:
import heapq
files = open('a.txt'), open('b.txt')
with open('merged.txt', 'w') as out:
    out.writelines(map('{}\n'.format,
                       heapq.merge(*(map(int, f)
                                     for f in files))))

rawDescription: Implementing an external merge sort

description: Implementing an external merge sort


rawDescription: numpy large array indexing crashes the interpreter

description: Numpy large array indexing crashes the interpreter


code:
def index(request):
    if 'q' in request.GET:
        company_list = Company.objects.filter(
            Q(company__icontains = request.GET['q']) |
            Q(county__icontains = request.GET['q']) |
            Q(city__icontains = request.GET['q']) |
            Q(product_description__icontains = request.GET['q'])
        )
        query = request.GET['q']
        companies = pagination(request, company_list, 10)
        return render_response(request, 'database/index.html', {"companies": companies, "query": query})
    else:
        company_list = Company.objects.all()
        companies = pagination(request, company_list, 10)
        return render_response(request, 'database/index.html', {"companies": companies})

rawDescription: Refactoring Index/Search View

description: Refactoring Index/Search View


code:
infile = "listdata.txt"
data = open(infile, "r").readlines()

dataDict = []
columns = []

# Create a dictionary list
for line in data:
    row = line.split(";");
    rowData = {}
    for cell in row:
        cell = cell.strip()[1:-1].split(",")
        if len(cell) > 1:
            rowData[cell[0].strip().strip('"').strip("'")] = cell[1].strip().strip('"').strip("'")
    keys = rowData.keys()
    dataDict.append(rowData)
    columns = list(set(columns) | set(keys))

# Write dictionary list to file
outfile = "listdata.csv"
fp = open(outfile, "w")

for key in columns:
    fp.write(key + ", ")

fp.write("\n")

for data in dataDict:
    for key in columns:
        if key in data:
            fp.write(data[key] + ",")
        else:
            fp.write(",")
    fp.write("\n")

fp.close()

rawDescription: Parsing a semi colon delimited file in python to create a CSV


code:
import pygame

# Constants
WIDTH = 700
HEIGHT = 500
SCREEN_AREA = pygame.Rect(0, 0, WIDTH, HEIGHT)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# Initialization
pygame.init()
screen = pygame.display.set_mode([WIDTH, HEIGHT])
pygame.mouse.set_visible(0)
pygame.display.set_caption("Breakout Recreation WIP")
clock = pygame.time.Clock()

# Variables
paddle = pygame.Rect(350, 480, 50, 10)
ball = pygame.Rect(10, 250, 15, 15)
paddle_movement_x = 0
ball_direction = (1, 1)
balls = 3
done = False

while not done and balls > 0:

    # Process events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            paddle_movement_x = -2
        elif keys[pygame.K_RIGHT]:
            paddle_movement_x = 2
        else:
            paddle_movement_x = 0

    # Move paddle
    paddle.move_ip(paddle_movement_x, 0)
    paddle.clamp_ip(SCREEN_AREA)

    # Move ball
    ball.move_ip(*ball_direction)
    if ball.right > WIDTH or ball.left < 0:
        ball_direction = -ball_direction[0], ball_direction[1]
    elif ball.top < 0 or ball.bottom > HEIGHT or paddle.colliderect(ball):
        ball_direction = ball_direction[0], -ball_direction[1]
    ball.clamp_ip(SCREEN_AREA)

    # Redraw screen
    screen.fill(BLACK)
    pygame.draw.rect(screen, WHITE, paddle)
    pygame.draw.rect(screen, WHITE, ball)
    pygame.display.flip()
    clock.tick(100)

pygame.quit()

rawDescription: How to Make the Ball Bounce only if it Hits the Paddle in Python, Pygame (Breakout Recreation)


code:
class MyHandler(webapp.RequestHandler):
    def get(self):
        foo_list = db.GqlQuery(...)
        ...
        template_values['foos'] = foo_list
        template_values['foo_count'] = len(foo_list)
        template_values['one_foo'] = len(foo_list) == 1
        handler.response.out.write(template.render(...))

rawDescription: Can I compare a template variable to an integer in Django/App Engine templates?

description: Compare a template variable to an integer in Django/App Engine templates


code:
engine = create_engine(
    'sqlite+pysqlcipher://:{0}@/{1}?'
    'cipher=aes-256-cfb&kdf_iter=64000'.format(key, DB_NAME))

rawDescription: Using pysqlcipher with SqlAlchemy?

description: Using pysqlcipher with SqlAlchemy


code:
for individual in table1:
    age, diploma = individual
    for age_bucket, dip_bucket in iterate_buckets(age, diploma):
        matches = age_bucket.intersection(dip_bucket)
        if matches:
            match = get_best_match(matches, age, diploma)
            all_matches.append((individual, match))
            remove_individual(age_groups, match)
            remove_individual(dip_groups, match)

rawDescription: fastest way to read a table2 for each value of a table1 with Python?

description: Fastest way to read a table2 for each value of a table1 with Python


code:
del a
del a,b
del l[0]
del l[:]

rawDescription: Calling "del" on result of Function call results in "SyntaxError: can't delete function call"


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

# create some data
xy = np.random.rand(4, 2)
xy_line = (0, 1)

# set up figure and ax
fig, ax = plt.subplots(figsize=(8,8))

# create the scatter plots
ax.scatter(xy[:, 0], xy[:, 1], c='blue')
for point, name in zip(xy, 'ABCD'):
    ax.annotate(name, xy=point, xytext=(0, -10), textcoords='offset points',
                color='blue', ha='center', va='center')
ax.scatter([0], [1], c='black', s=60)
ax.annotate('Perfect Classification', xy=(0, 1), xytext=(0.1, 0.9),
            arrowprops=dict(arrowstyle='->'))

# create the line
ax.plot(xy_line, 'r--', label='Random guess')
ax.annotate('Better', xy=(0.3, 0.3), xytext=(0.2, 0.4),
            arrowprops=dict(arrowstyle='<-'), ha='center', va='center')
ax.annotate('Worse', xy=(0.3, 0.3), xytext=(0.4, 0.2),
            arrowprops=dict(arrowstyle='<-'), ha='center', va='center')
# add labels, legend and make it nicer
ax.set_xlabel('FPR or (1 - specificity)')
ax.set_ylabel('TPR or sensitivity')
ax.set_title('ROC Space')
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.legend()
plt.tight_layout()
plt.savefig('scatter_line.png', dpi=80)

rawDescription: How to draw line inside a scatter plot

description: Draw line inside a scatter plot


code: rules.update(rule.split('=', 1) for rule in recurrence.split(';'))

rawDescription: Add a 2 value tuple to dict as key:value


code:
conditions = lambda x: 10 < x.cost < 20 and 0 < x.risk < 10
filter(conditions, result)

rawDescription: Is there an elegant alternative to filtering these results without using lots of if statements?


code:
import sys, os
import matplotlib.pyplot as plt

path = sys.path[0]
sizes = [(12,3,), (4,3,)]
x =  range(20)

for i, size in enumerate(sizes):
    fig = plt.figure(figsize = size, dpi = 80, facecolor='white', edgecolor=None,linewidth=0.0, frameon=True, subplotpars=None)
    ax = fig.add_subplot(111)
    ax.plot(x)
    plt.ylabel ('Some label')

    plt.tight_layout()

    fig.savefig(os.path.join(path, 'size_'+str(i)+'.png'), dpi=80,facecolor=fig.get_facecolor(), edgecolor=None, papertype=None, format='png',transparent=False)

rawDescription: How to align subplot with specified size?

description: Align subplot with specified size


code: map(sum, zip(*values))

rawDescription: Sum float values at each index point in nested lists


code:
import optparse

parser = optparse.OptionParser()
parser.add_option("-i","--input",dest="filename")
(options,args) = parser.parse_args()

thefile = options.filename
reader = csv.reader(thefile,"rb")

rawDescription: User defined input csv file

description: User defined input csv file


code: AS = S.vs.select(lambda vertex: T.outdegree(vertex["name"]) < 1.01 * E(S,T)/S.vcount())

rawDescription: python, igraph coping with vertex renumbering

description: Python, igraph coping with vertex renumbering


code:
import dis
def a():
    return None
def b():
    return
dis.dis(a)
dis.dis(b)

rawDescription: What does return alone do in python?

description: What does return alone do in python


code:
s = sorted(p)
for i in range(1, len(s)):
   if s[i] == s[i - 1]:
      return True
return False

rawDescription: Python Lists: How can I search for another element or duplicate item in a list


rawDescription: Delete list via referent ? > Was : How do you alias variable in Python ? or similar?


rawDescription: Python Pandas: Get single max numeric value from df with floats and characters/alphas


code:
import example
queuer = example.Queuer()
queuer(example.Agent(), example.Message())
queuer(example.Queue(), example.Message())
queuer(example.Spam(), example.Message())

rawDescription: boost python overload operator ()

description: Boost python overload operator ()


code:
screen.nodelay(1)
maxy, maxx = screen.getmaxyx()
begin_x = 2; begin_y = maxy-5
height = 5; width = maxx-4
win = curses.newwin(height, width, begin_y, begin_x)
curses.setsyx(-1, -1)
screen.addstr("Testing my curses app")
screen.refresh()
win.refresh()
win.scrollok(True)
win.idlok(True)
win.leaveok(True)
mh = CursesHandler(win)
mh.setFormatter(formatterDisplay)
logger.addHandler(mh)

rawDescription: How to manage logging in curses

description: Manage logging in curses


rawDescription: what is a good way of setting up ranges on a number line?

description: What is a good way of setting up ranges on a number line


code:
increment = ((df.Value[:-1] != df.Value[1:]) | (df.ID[:-1] != df.ID[1:])).cumsum()
df["extra"] = pd.concat((pd.Series([0]),increment),ignore_index=True)

rawDescription: Taking Min and Max of Contigous Rows in a Pandas Dataframe


code: for k in xrange(1000000): a[k] = k

rawDescription: How many elements may python dictionary hold?


rawDescription: Pandas: Selection with MultiIndex

description: Pandas: Selection with MultiIndex


code:
from ipywidgets import interact
import numpy as np

from bokeh.io import push_notebook
from bokeh.plotting import figure, show, output_notebook

x = np.linspace(0, 2*np.pi, 2000)
y = np.sin(x)

output_notebook()

p = figure(plot_height=300, plot_width=600, y_range=(-5,5))
p.line(x, y, color="#2222aa", line_width=3)

def update(range_max=6):
    p.x_range.end = range_max
    push_notebook()

show(p)

interact(update, range_max=(1,10))

rawDescription: Set x_axis_limit in Bokeh live plot embedded in Jupyter notebook


rawDescription: How multiarray.correlate2(a, v, mode) is actually implemented?


code: sigma1 = covariance(exponential_kernel, x, x, theta)

rawDescription: Gaussian Process scikit-learn - Exception


code:
from skimage import morphology
close_mask = morphology.binary_closing(valid_mask, morphology.square(3))
interpolated[:] = np.where(close_mask, interpolated, np.nan)

rawDescription: Interpolation of numpy array with a maximum interpolation distance


rawDescription: what is the best way to represent a char in its bits representation(Python)

description: What is the best way to represent a char in its bits representation(Python)


code: idx = [0 if i in axes else slice(None) for i in range(G.ndim)]

rawDescription: How do I make a function that slices an array depending on parameters

description: Make a function that slices an array depending on parameters


code:
def estim(x):
    x = abs(x)
    a=("{:.2e}".format(x))
    print(a)
    return a

rawDescription: Assign scientific notation to variable in Python


code:
change = [0] # first price always zero change
for a, b in zip(self.list_of_prices, self.list_of_prices[1:]):
    if a < b: # price went up
        change.append(1)
    elif a > b: # price went down
        change.append(-1)
    else: # price stayed the same
        change.append(0)

rawDescription: Class based directional indicator

description: Class based directional indicator


code:
{
    "group": "main",
    "color": {
        "border": "black",
        "background": "pink"
    },
    "label": "Main",
    "shape": "icon",
    "font": {
        "size": 60
    },
    "id": 0,
    "icon": {
        "size": 200,
        "color": "#f0a30a",
        "code": "\xef\x89\xb6",
        "face": "Ionicons"
    }
}

rawDescription: Python Unicode string to Javascript

description: Python Unicode string to Javascript


rawDescription: Dynamic variables in Python

description: Dynamic variables in Python


code: [[frame1_1, frame2_1, frame3_1], [frame1_2, frame2_2, frame3_2]]

rawDescription: Frame list with Tkinter and python

description: Frame list with Tkinter and python


code:
for line in content:
    line = ...

rawDescription: Why is my code printing incorrectly to the text file?


code:
set_param(proof=True)
ctx = Context()
s = Solver(ctx=ctx)
x = Int('x', ctx=ctx)
s.add(x > 0)
s.add(x == 0)
s.check()
s.proof()

rawDescription: Getting proof from z3py

description: Getting proof from z3py


code:
import urllib2
from bs4 import BeautifulSoup

def filter_function(tag):
    return ((tag.name=='h3' and tag.parent.name=='td' and '2' in
             [tag.parent[attrib] for attrib in tag.parent.attrs.keys()]) or
            (tag.name == 'p' and tag.parent.name=='td' and '2' in
             [tag.parent[attrib] for attrib in tag.parent.attrs.keys()]))

our_url = 'http://www.teauction.com/industry/buyer/coimbuyera-z.asp'

our_page = urllib2.urlopen(our_url).read()

our_soup = BeautifulSoup(our_page)

nodes_we_want = our_soup.find_all(filter_function)

text_we_want = [node.text for node in nodes_we_want]

rawDescription: How can I find my desired table inside a set of nested tables, using bs4/python, if there are no class or id attributes?

description: Find my desired table inside a set of nested tables, using bs4/python, if there are no class or id attributes


rawDescription: numpy.ma.cov - pairwise correlations for with missing values?

description: Numpy.ma.cov - pairwise correlations for with missing values


code: subparser = parser.add_subparsers(help='sub-command help')

rawDescription: With argparse are subparsers inherently mutually exclusive?


rawDescription: Python Collections Counter for a List of Dictionaries


code:
class File(models.model):
    user = models.ForeignKey(User, related_name='files', null=False)
    filename = models.CharField(max_length=255, blank=False, null=False)
    data = models.BinaryField()

rawDescription: View function is not being called in Django


code:
def sorted_by_score():
    with open("highscores.txt", "r") as f:
        result = list(f)
    return sorted(result, key=minus_score)

rawDescription: Write to file python - Linebreak issue (\n)


rawDescription: get "1" for a one-dimensional numpy.array using a shape-like function

description: Get "1" for a one-dimensional numpy.array using a shape-like function


rawDescription: Pandas count number of rows that match on certain fields but don't match on other fields


code:
print(numbers)
labels

rawDescription: how can i plot histogram like this?

description: Plot histogram like this


code:
import dateutil.parser as parser
parser.parse("19970902T090000")
import datetime as dt
now = dt.datetime.now()
now.isoformat()
parser.parse('2012-11-06T15:08:51.393631')
parser.parse('November 6, 2012')

rawDescription: Convert "unknown format" strings to datetime objects?


rawDescription: python loading several matlab files

description: Python loading several matlab files


code: [a+b if a not in special else a for a,b in zip(first_list, second_list)]

rawDescription: How to exempt a list item from iteration?

description: Exempt a list item from iteration


code:
df["num"] = df.groupby("cid")["price"].cumcount() + 1
df.head(10)

rawDescription: Pivot each group in Pandas

description: Pivot each group in Pandas


code:
class EntryPopup(Entry):

    def __init__(self, parent, text, **kw):
        ''' If relwidth is set, then width is ignored '''
        super().__init__(parent, **kw)

        self.insert(0, text)
        self['state'] = 'readonly'
        self['readonlybackground'] = 'white'
        self['selectbackground'] = '#1BA1E2'
        self['exportselection'] = False

        self.focus_force()
        self.bind("<Control-a>", self.selectAll)
        self.bind("<Escape>", lambda *ignore: self.destroy())

    def selectAll(self, *ignore):
        ''' Set selection on the whole text '''
        self.selection_range(0, 'end')

        # returns 'break' to interrupt default key-bindings
        return 'break'

rawDescription: How to make ttk.Treeview's rows editable?

description: Make ttk.Treeview's rows editable


code:
table = soup.find('table', attrs={'class':'layout'})
table.find_all("td")[-1].get_text()

rawDescription: BeautifulSoup4 table

description: BeautifulSoup4 table


code:
import threading

threading.Thread(target=lambda a: print("Hello, {}".format(a)), args=(["world"]))

rawDescription: Is it possible to use an inline function in a Thread call?


code:
d = []
d.extend(['hello'])
print(d)

rawDescription: Array.extend(string) adds every character instead of just the string


rawDescription: Removing <wbr> tags and grabbing the info between


rawDescription: Python3.4 - math with index numbers

description: Python3.4 - math with index numbers


code:
from django.forms.models import modelformset_factory
MyFormSet = modelformset_factory(MyModel, formset=MyBaseFormSet)

rawDescription: django inlineformset, how to allow only 1 boolean field to be true at a time?

description: Django inlineformset, how to allow only 1 boolean field to be true at a time


code: slice = cv2.reduce(image, 1, cv2.cv.CV_REDUCE_SUM, dtype=numpy.int32)

rawDescription: How to use opencv reduce using cv2 python API

description: Use opencv reduce using cv2 python API


code:
listLen = 10
low = 0
for L in itertools.product(*[range(low,random.randint(0,100)) for _ in range(listLen)]):
  print(L)

rawDescription: Python: Algorithm to walk all the integers in a list and come up with all possible values?


code:
from numpy import random as rnd
from pyximport import install
install(setup_args={'include_dirs':rnd.__path__[0] + '/'})

rawDescription: Cython: dynamic "cdef extern from xxx"

description: Cython: dynamic "cdef extern from xxx"


code:
with open("records.tsv", "w") as record_file:
    for record in SeqIO.parse("/home/fil/Desktop/420_2_03_074.fastq", "fastq"):
        record_file.write("%s %s %s\n" % (record.id,record.seq, record.format("qual")))

rawDescription: How to save output from python like tsv

description: Save output from python like tsv


code:
# M is a connected IMAP4 instance...
typ, msgnums = M.search(None, 'FROM', '"LDJ"')

rawDescription: find all items in list object

description: Find all items in list object


code:
d = { range(1, 5): '???',
      range(5, ub_tries): 'next',
      range(ub_tries, ub_tries + 1): 'last' }

rawDescription: use a range as a dictionary key in Python, what option do I have?

description: Use a range as a dictionary key in Python, what option do I have


code:
format_to_year_to_value_dict = defaultdict(dict)
...
format_to_year_to_value_dict[format_str][year] = value

rawDescription: How to initialize nested dictionaries in Python

description: Initialize nested dictionaries in Python


code: df_new['Year'] = df_new['Year'].apply(lambda x: x[-4:])

rawDescription: Reshape Pandas Dataframe

description: Reshape Pandas Dataframe


code:
beta = np.zeros(x.shape[:2])
for i in range(x.shape[0]):
    for j in range(x.shape[1]):
        beta[i,j] = foo(x[i,j,:],y[j,:])

rawDescription: apply a function on two ndarrays's corresponding rows at once(without for loop)

description: Apply a function on two ndarrays's corresponding rows at once(without for loop)


code:
from collections import defaultdict

outerdict = defaultdict(dict)
outerdict[name][type_] = [v1, v2, v3]

rawDescription: Python idiom for creating dict of dict of list


rawDescription: Efficient way to multiply/add/devide each element of a list with each element of another list in Python


code:
connection_count = "lsof -i tcp | grep ESTABLISHED"
proc = subprocess.POPEN(connection_count, shell=True, stdout=subprocess.PIPE)
# line counting moved to python :-)
count = sum(1 for unused_line in proc.stdout)

rawDescription: How can I get my Python script to work using bash?

description: Get my Python script to work using bash


rawDescription: How do you convert time series data with pandas and show graph via highstock

description: Convert time series data with pandas and show graph via highstock


code:
import threading
import alice, bob

def get_work_data():
    return 'data'

def main():
    tasks = [alice.do_stuff, bob.do_stuff]
    data = get_work_data()
    for task in tasks:
        t = threading.Thread(target=task, args=(data,))
        t.start()

rawDescription: Spawning a thread in python

description: Spawning a thread in python


rawDescription: Retrieving cell data from a selected cell in a tablewidget


code: 0, 1, ..., len(p) - 1 # in your case, len(p) = 5, thus x ranges from 0 to 4

rawDescription: How can I pass multiple values in a function parameter?

description: Pass multiple values in a function parameter


code: {{ your_python_data }}

rawDescription: passing unicode strings from django to javascript

description: Passing unicode strings from django to javascript


code:
class MyObjects(object):
    q=0
    def __init__(self):
       MyObjects.q+=1
       self.q=MyObjects.q

    def f(self,x,y):
        return self.q*y+x
inp=input("Enter number of objects: ")
dic={}
for x in range(1,inp+1):
    dic[x]=MyObjects()

rawDescription: Python: Automatic object generation plus naming


rawDescription: pySQLite integration to pyGtk treeview

description: PySQLite integration to pyGtk treeview


code:
my_input = '1x'
output = my_input[0] + '*' + my_input[1]
output

rawDescription: Python: place a characters in string

description: Python: place a characters in string


rawDescription: Selecting the value in a row closest to zero in a pandas DataFrame


code:
import cv2

img = cv2.cv.LoadImage('rgbw.png')
height = img.height
width = img.width
raw_data = img.tostring()

# iplImage->imageData requires rows to be padded with zero bytes at the end
# so they be divisible by 4
pad_bytes_per_row = width % 4

# create the ctypes structure
ubyte_array_type = c_ubyte * (len(raw_data) + (height * pad_bytes_per_row))
ubyte_array = ubyte_array_type()
index = 0
for ch in raw_data:
    ubyte_array[index] = ord(ch)
    index += 1
    if 0 == index % width: # end of row
        pad_index = 0
        while pad_index < pad_bytes_per_row:
            ubyte_array[index] = 0
            pad_index += 1
            index += 1

rawDescription: How do you marshal Python cv2.cv.LoadImage tostring data into C IplImage->imageData struct

description: Marshal Python cv2.cv.LoadImage tostring data into C IplImage->imageData struct


rawDescription: Append/replace string from one file with information from another


code: [random.choice(coordinaten) for _ in xrange(20)]

rawDescription: Python pick 20 random results from list

description: Python pick 20 random results from list


rawDescription: Find an item in list and change the next item in list as 'RD_PUNC'


code: np.random.randint(2, size=(3, 3))

rawDescription: Generate a new numpy array of order 2 filling in each element with a random number in a certain range


code:
[
    {u'infoUrl': u'http://www.shipito.com/postage#tnt', u'isPromoted': False, u'popularity': 1, u'name': u'TNT Economy', u'deliveryTime': 6, u'insurable': True, u'usesDimWeight': True, u'shippingRate': 68.38, u'separateShippingRate': None, u'bonusShippingRate': 68.38, u'deliveryTimeInfo': u'4-6 business days', u'mps': False, u'insuranceRate': 0, u'logoImg': u'tnt.png'},
    ...
]

rawDescription: Scrapy and Selenium submit form that renders dynamically


code:
import os
# returns the next word in the file
def words_generator(fileobj):
    for line in fileobj:
        for word in line.split():
            yield word
word_count_dict = {}
for dirpath, dnames, fnames in os.walk("./"):
    for file in fnames:
        f = open(file,"r")
        words = words_generator(f)
        for word in words:
            if word not in word_count_dict:
                  word_count_dict[word] = {"total":0}
            if file not in word_count_dict[word]:
                  word_count_dict[word][file] = 0
            word_count_dict[word][file] += 1
            word_count_dict[word]["total"] += 1

rawDescription: how to find frequency of the keys in a dictionary across multiple text files?

description: Find frequency of the keys in a dictionary across multiple text files


code: length = dbroot.dict_length()

rawDescription: Counting len() of BTree saved in ZODB takes much time


code:
# Import the `randint` function from `random`.
from random import randint
# This will hold the results that will later be used to calculate the average.
a = []
# This loops 100 times (to get data for a calculation of the average).
for _ in range(100):
    # This will be the number of times the while-loop loops.
    b = 0
    # This is a set to hold the choices of `random.randint`.
    # When it reaches 5 items, all numbers from 1-5 have been found.
    c = set()
    # Loop while the length of the set is less than 5.
    while len(c) < 5:
        # Add a new random number to the set,
        # If the number is already there, nothing happens.
        c.add(randint(1, 5))
        # Record a completed iteration of the while-loop.
        b += 1
    # Add the number of while-loop loops to `a`.
    a.append(b)
# The average is calculated by dividing the sum of `a` by the length of `a`.
# It is then rounded to the nearest integer.
d = round(sum(a)/len(a))
# Print the results.
print("{}\nAverage loops: {}".format(c, d))

rawDescription: Python random numbers loop

description: Python random numbers loop


code:
from ctypes import c_uint16
_int = int

def int(x):
    return c_uint16(x)

rawDescription: Overflowing ints in python

description: Overflowing ints in python


code: (x-min)/(max-min)

rawDescription: How do I modify the settings of the coordinates of the canvas using "Turtle" in Python 2.7.9?

description: Modify the settings of the coordinates of the canvas using "Turtle" in Python 2.7.9


code:
@celery.task(bind=True, max_retries=None)
def count_until(self, stop, current=0):
    print(current)

    if current < stop:
        raise self.retry(args=(stop, current + 1), countdown=5)

    print('done')

rawDescription: Wait for data from one task in a second independently scheduled task


rawDescription: Cronjobs per package

description: Cronjobs per package


code:
#x.py
import y
y.lol = 1
y.func()

rawDescription: What are all the ways to add an object to the local scope in Python?


S: someString

rawDescription: What should be the format of "Date" in text file to be read as Json and then inserted into MongoDB using Python?


code:
np.random.seed([3,1415])

def xover(ts, cut):
    x = ts > cut
    return x.argmax() if x.any() else -1

ts_array = np.random.random(5).round(4)

rawDescription: First element of series to cross threshold in numpy, with handling of series that never cross


code:
df_l = pd.DataFrame(l_)
df_1['a_'] = pd.Series(a_list, index=df_1.index)

rawDescription: Append a list of arrays as column to pandas Data Frame with same column indices


code: XMLFILES_FOLDER = os.path.join(PROJECT_ROOT, 'f1/f2/xml_files/')

rawDescription: How can I use relative path to read local files in Django app?

description: Use relative path to read local files in Django app


code: (a.reshape(50, 40) > np.percentile(a.reshape(50, 40), 99, axis=0)).flatten()

rawDescription: Calculate percentile per set interval in python array


code:
d = {}
for col_index in xrange(sheet.ncols):
    d[keys[col_index]] = sheet.cell(row_index, col_index).value

rawDescription: XLRD/Python: Reading Excel file into dict with for-loops


rawDescription: Merge dictionaries with key combinations


rawDescription: How to find duplicate values in next lines?

description: Find duplicate values in next lines


code:
board = []
for i in range(d):
    row = []
    for j in range(d):
        row.append(d*d-1-i-d*j)
    board.append(row)

rawDescription: How to create a game board on Python

description: Create a game board on Python


code:
f1(None)
C.f1(None)
class D(object): pass
f1.__get__(D(), D)
C.f1.__get__(D(), D)

rawDescription: What is the difference between a function, an unbound method and a bound method?


rawDescription: Python sort by values that are lists of numbers


code: result = mp.Array(ctypes.c_uint16, img.shape[0]*img.shape[1], lock = False)

rawDescription: How to use Python and OpenCV with multiprocessing?

description: Use Python and OpenCV with multiprocessing


rawDescription: Numpy Savetxt does not export delimiter when defining fmt for each column


code:
import inspect
spec = inspect.getargspec(myFunction)

rawDescription: How to find out the default values of a particular function's argument in another function in Python?

description: Find out the default values of a particular function's argument in another function in Python


rawDescription: Find a value in a sublist and substract a previous element value with their element value


code:
import random
random.shuffle(first_list_ordered)
first_list_ordered
indices = {c: i for i, c in enumerate(first_list_ordered)}
sorted(second_list_unordered, key=lambda d: indices.get(d['id']))
pprint(_)

rawDescription: Sort list of dictionaries by appearance of key in a second ordered list


code:
if node.name == "p":
    group.append(node)

rawDescription: How to determine a logic part with python's beautiful soup when crawling

description: Determine a logic part with python's beautiful soup when crawling


rawDescription: Effective way to iteratively append to a string in Python?


code:
objects = B.objects.get(user=a.user)
objects += A.objects.get(user=user)

rawDescription: Generic object "ownership" in Django

description: Generic object "ownership" in Django


code: values = [" : ".join(x) for x in zip(labels,results)]

rawDescription: List of tuples in django template

description: List of tuples in django template


code:
a = {'ground': 'obj1', 'floor 1': 'obj2', 'basement': 'obj3'}
a_list = ('floor 1', 'ground', 'basement')
sorted(a.items(), key=lambda pair: a_list.index(pair[0]))
index_map = {v: i for i, v in enumerate(a_list)}
sorted(a.items(), key=lambda pair: index_map[pair[0]])

rawDescription: How to sort a dictionary based on a list in python

description: Sort a dictionary based on a list in python


code: lst = [(j, k) for j in s1 for k in s2]

rawDescription: Nested For Loops Using List Comprehension


code:
# Input object dtype array
data = np.array([[1, 2, 3, 4],
                 [2, 3, 1],
                 [5, 5, 5, 5],
                 [1, 1]])

# Get lengths of each row of data
lens = np.array([len(data[i]) for i in range(len(data))])

# Mask of valid places in each row
mask = np.arange(lens.size) < lens[:,None]

# Setup output array and put elements from data into masked positions
out = np.zeros(mask.shape)
out[mask] = np.hstack((data[:]))

rawDescription: Numpy: Fix array with rows of different lengths by filling the empty elements with zeros


rawDescription: Why does numpy indexing work differently in higher dimensions?


code:
multi = Multi(2)
multi.attribute_times_ten # returns 20
Multi.times_ten(8) # returns 80, note the capital M!
multi.generate_number(3) # self.attribute is now 6
multi.attribute_times_ten # returns 60

rawDescription: Property set correctly inside an object but not accessible outside


code:
for data in process_file('data.txt'):
    print('-'*20)
    for i in data:
        print('%s:'%(i), data[i])

    print()

rawDescription: Python - reading data from file with variable attributes and line lengths


code:
AUTHENTICATION_BACKENDS = (
    'myoursite.backends.EmailOrUsernameBackend', # Custom Authentication to accept usernamee or email
)

rawDescription: How to make customer's email as the username in UserCreationForm / User Model in Django?

description: Make customer's email as the username in UserCreationForm / User Model in Django


code:
data = self.request.recv(1024)
cur_thread = threading.currentThread()

data = data.split()
gfile = os.path.abspath(data[-1])
fopen = open(gfile, 'r')
fread = fopen.read()
self.server.app.static.SetLabel(fread)

rawDescription: Single Instance Application - Passing commands


code:
x_sublists = [x[i:i+3] for i in range(0, len(x), 3)]
pd.DataFrame(x_sublists [1:], columns=x_sublists [0])

rawDescription: Converting and reshaping a list into a DataFrame in Pandas


rawDescription: string to list conversion in python

description: String to list conversion in python


Model: El Camino

WrapperName: Car Wrapper

rawDescription: Passing inherited object to a WCF service using JSON


code:
a = [['mange'], ['ton', 'ont'], ['orange','onagre','organe','rongea']]
from itertools import product
[' '.join(x) for x in product(*a)]

rawDescription: Concatenate list items

description: Concatenate list items


code:
sample = [['a'],['b']]
[item for sublist in sample for item in sublist]

rawDescription: List of list to string

description: List of list to string


rawDescription: Selecting specific rows from a python dataframe for an ols regression in PANDAS


code: result = Foo(value1, value2)

rawDescription: Can a class in python behave like a specified class based on a passed parameter?


code:
from __future__ import division
import numpy as np
from PIL import Image

def halve_image(image) :
    rows, cols, planes = image.shape
    image = image.astype('uint16')
    image = image.reshape(rows // 2, 2, cols // 2, 2, planes)
    image = image.sum(axis=3).sum(axis=1)
    return ((image + 2) >> 2).astype('uint8')

def mipmap(image) :
    img = image.copy()
    rows, cols, planes = image.shape
    mipmap = np.zeros((rows, cols * 3 // 2, planes), dtype='uint8')
    mipmap[:, :cols, :] = img
    row = 0
    while rows > 1:
        img = halve_image(img)
        rows = img.shape[0]
        mipmap[row:row + rows, cols:cols + img.shape[1], :] = img
        row += rows
    return mipmap

img = np.asarray(Image.open('lena.png'))
Image.fromarray(mipmap(img)).save('lena_mipmap.png')

rawDescription: Mipmap of image in numpy?

description: Mipmap of image in numpy


code:
def convert(s):
    mins, secs = s.split(':')
    mins = int(mins)
    secs = float(secs)
    secs = 60 * mins + secs
    return secs

rawDescription: Converting time from (mm:ss.ddd) to (ss.ddd)


rawDescription: Insert tree kind of data taken from a database into a python dictionary


code:
mypad = curses.newpad(40,60)
mypad_pos = 0
mypad.refresh(mypad_pos, 0, 5, 5, 10, 60)

rawDescription: How to scroll text in Python/Curses subwindow?

description: Scroll text in Python/Curses subwindow


code:
class Foo(object):
    def __init__(self):
        self.some_attr = ''
        self.a_list = []
    @property
    def empty_check(self):
        return bool(self.a_list)
myFoo = Foo()
print(myFoo.empty_check)
myFoo.a_list.append(1)
print(myFoo.empty_check)
myFoo.empty_check = True

rawDescription: attribute that updates based on the value of another attribute in python 3

description: Attribute that updates based on the value of another attribute in python 3


code:
import requests
url = 'http://httpbin.org/post'
r = requests.post(url, data=[('interests', 'football'), ('interests', 'basketball')])
r.json()['form']

rawDescription: how to post multiple value with same key in python requests?

description: Post multiple value with same key in python requests


code:
with open('file.txt', 'r') as handle:
    numbers = [map(int, line.split()) for line in handle]

rawDescription: Python - reading from file into a list

description: Python - reading from file into a list


code:
from StringIO import StringIO

def foo(sstream):
    for line in sstream:
        res = doSomethingWith(line)
        yield res

sio = StringIO(mystring)
try:
    for bar in foo(sio):
        if condition(bar):
            break
finally:
    sio.close()

rawDescription: Freeing a generators resources after iterating only over a part of the sequence


code:
def func(arg1):
    if (arg1 > 5
            and arg1 != 10):
        return "something"

rawDescription: Style when indenting a wrapped, parenthesized if condition


code: map(float, feature[1:-1].split(','))

rawDescription: Writing and reading floats and strings in a CSV file - python


code:
Company = {"Apple": 1, "Apple Computer": 1, "AAPL": 1, "Apple, Inc": 1,
           "Apple Vacations": 2, "Applebee's Restaurant": 3 }

sum[Company[name]] += amount

rawDescription: Python CSV and Sum

description: Python CSV and Sum


code:
import pandas as pd
df = pd.DataFrame({'cat':['a','b','c','d'],'val':[1,2,5,10]})
df1 = pd.get_dummies(pd.DataFrame({'cat':['a'],'val':[1]}))
dummies_frame = pd.get_dummies(df)
df1.reindex(columns = dummies_frame.columns, fill_value=0)

rawDescription: Easy way to apply transformation from `pandas.get_dummies` to new data?


code:
shorten_title = lambda x, y: x[:x.rindex(' ', 0, y)]
shorten_title('Shorten title to a certain length', 20)

rawDescription: Shorten title to a certain length

description: Shorten title to a certain length


code:
class MyVar(object):
    def __init__(self, var2, var3):
        self.var2 = var2
        self.var3 = var3

    @property
    def var1(self):
        return self.var2 + self.var3

var = MyVar(4, 2)
print(var.var1)  # 6
var.var3 = 8
print(var.var1)  # 12

rawDescription: How to recalculate a variable value every time it is used?

description: Recalculate a variable value every time it is used


code:
import threading
import time

class waiter(object):
    def __init__(self, action, delay = 0.5, *args, **kwargs):
        self.action_lockout_timeout = threading.Thread()
        self.action_lockout_event   = threading.Event()
        self.action                 = action
        self.delay                  = delay
        self.action_prevent()

    def action_prevent(self):
        def action_enable():
            self.action_lockout_event.wait(self.delay)
            if not self.action_lockout_event._Event__flag:
                self.action()

        if self.action_lockout_timeout.isAlive():
            self.action_lockout_event.set()
            self.action_lockout_timeout.join()
        self.action_lockout_event.clear()
        self.action_lockout_timeout = threading.Thread(target = action_enable)
        self.action_lockout_timeout.setDaemon(True)
        self.action_lockout_timeout.start()

def thanks():
    print("Person 2: Thank you ...")

polite = waiter(thanks, 3)
print("Person 1: After you")
polite.action_prevent()
time.sleep(2)
print("Person 2: No, after you")
polite.action_prevent()
time.sleep(2)
print("Person 1: No I insist")
polite.action_prevent()
time.sleep(2)
print("Person 2: But it would be rude")
polite.action_prevent()
time.sleep(2)
print("---Akward Silence---")
time.sleep(2)

rawDescription: Most efficient way to perform a deferred action in Python


code:
np.array([b'Hello', b'World']) # 2.7
np.array([b'Hello', b'World']) # 3.2

rawDescription: ASCII string as dtype for numpy array of strings in Python 3


code:
import numpy as np
import scipy.ndimage.filters as filters
import scipy.ndimage.morphology as morphology

def detect_local_minima(arr):
    # http://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array/3689710#3689710
    """
    Takes an array and detects the troughs using the local maximum filter.
    Returns a boolean mask of the troughs (i.e. 1 when
    the pixel's value is the neighborhood maximum, 0 otherwise)
    """
    # define an connected neighborhood
    # http://www.scipy.org/doc/api_docs/SciPy.ndimage.morphology.html#generate_binary_structure
    neighborhood = morphology.generate_binary_structure(len(arr.shape),2)
    # apply the local minimum filter; all locations of minimum value
    # in their neighborhood are set to 1
    # http://www.scipy.org/doc/api_docs/SciPy.ndimage.filters.html#minimum_filter
    local_min = (filters.minimum_filter(arr, footprint=neighborhood)==arr)
    # local_min is a mask that contains the peaks we are
    # looking for, but also the background.
    # In order to isolate the peaks we must remove the background from the mask.
    #
    # we create the mask of the background
    background = (arr==0)
    #
    # a little technicality: we must erode the background in order to
    # successfully subtract it from local_min, otherwise a line will
    # appear along the background border (artifact of the local minimum filter)
    # http://www.scipy.org/doc/api_docs/SciPy.ndimage.morphology.html#binary_erosion
    eroded_background = morphology.binary_erosion(
        background, structure=neighborhood, border_value=1)
    #
    # we obtain the final mask, containing only peaks,
    # by removing the background from the local_min mask
    detected_minima = local_min - eroded_background
    return np.where(detected_minima)

rawDescription: How to find the local minima of a smooth multidimensional array in NumPy efficiently?

description: Find the local minima of a smooth multidimensional array in NumPy efficiently


code:
def powerset_generator(it, rev=False):
    rn = range(len(it), 0, -1) if rev else range(1, len(it) + 1)
    for r in rn:
        yield from map(list,combinations(it, r))

rawDescription: Python inverse power set generator

description: Python inverse power set generator


code:
tp = tensorproduct(X, W)
tp
tp.shape

rawDescription: python symbolic summation and differentiation of a vector of parametric size

description: Python symbolic summation and differentiation of a vector of parametric size


code:
class HasSonMeta(type):

    def __new__(cls, name, bases, attrs):

        attrs['son_func'] = staticmethod(attrs.pop('__son_func__'))
        return type.__new__(cls, name, bases, attrs)

class Son1(object):

     __metaclass__ = HasSonMeta
     __son_func__ = func_1

class Son2(object):

    __metaclass__ = HasSonMeta
    __son_func__ = func_2

rawDescription: Python, how to keep a non-class method as non-class method?