code:
from itertools import *
def ntuples(seq, n):
    iseq = iter(seq)
    curr = head = tuple(islice(iseq, n))
    for x in chain(iseq, head):
        yield curr
        curr = curr[1:] + (x,)

rawDescription: Iterate over pairs in a list (circular fashion) in Python


code:
from operator import add
reduce(add, ([x+':'+y for x in i.split(',')]
             for i, y in map(lambda l: map(str.strip, l.split(':')), dinner)), [])

rawDescription: Using Python Higher Order Functions to Manipulate Lists


code:
def process_df(df):
    # drop all columns except for A
    df.drop(df.columns[df.columns != 'A'], axis=1, inplace=True)

df = DataFrame({'A':[1,2,3], 'B':[1,2,3]})
process_df(df)

rawDescription: How to modify a pandas DataFrame in a function so that changes are seen by the caller?

description: Modify a pandas DataFrame in a function so that changes are seen by the caller


code: "His thoughts trailed away... His heart wasn't in it!"

rawDescription: Python regex : Replacing dots and signs followed by spaces


code:
import itertools
def kpdynamic1(max_weight, iterable):
    K = [(0, [(0, 0)])]
    for w in range(1, max_weight + 1):
        l = [(0, [(0, 0)])] + \
            [(K[w - weight][0] + value, K[w - weight][1] + [(value, weight)])
            for (value, weight) in
            itertools.compress(iterable,
                                (1 if (weight <= w) else 0
                                 for (value, weight) in iterable))]
        K.append(max(l, key=lambda x: x[0]))
    return K[max_weight]

max_size = 30
values = (3, 1.9, 30)
sizes = (3, 2, 14)
iterable = zip(values, sizes)
kpdynamic1(max_size, iterable)

rawDescription: Python: List is a int, TypeError

description: Python: List is a int, TypeError


code:
import csv
with open('eggs.csv', 'a') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

rawDescription: opening an excel file and writing to it in python

description: Opening an excel file and writing to it in python


rawDescription: Manipulating fields and values in dict and transforming into tuples in Python


code:
int_colors = rgb2int(color)
int_colors

rawDescription: Convert a 3D array to 2D array based on dictionary


code:
def tracify(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        traceback.print_stack()
        func(*args, **kwargs)
    return wrapper

rawDescription: Using the source code of a opensource project to learn


code: 'The quick brown fox jumps over the lazy dog, 42 times!'.translate(transmap)[::-1]

rawDescription: How to replace every character from input? (python3.x)

description: Replace every character from input? (python3.x)


code:
from selenium import webdriver
from bs4 import BeautifulSoup

url = "http://biology.burke.washington.edu/conus/accounts/../recordview/record.php?ID=1ll&tabs=21100111&frms=1&res=&pglimit=A"

driver = webdriver.Firefox()
driver.get(url)
driver.switch_to_frame(driver.find_elements_by_tag_name('iframe')[0])
soup = BeautifulSoup(driver.page_source)
tables = soup.find_all('table')
#print(tables)
driver.quit()

rawDescription: Extracting table info using BeautifulSoup (bs4)


code:
n = df["value"].isnull()
clusters = (n != n.shift()).cumsum()
df["cumsum"] = df["value"].groupby(clusters).cumsum().fillna(0)

to_zero = n & (df["value"].groupby(clusters).transform('size') == 1)
tmp_value = df["value"].where(~to_zero, 0)
n2 = tmp_value.isnull()
new_clusters = (n2 != n2.shift()).cumsum()
df["cumsum_skip1"] = tmp_value.groupby(new_clusters).cumsum().fillna(0)

rawDescription: Calculating the accumulated summation of clustered data in data frame in pandas


rawDescription: Sorting a group of words inside a list

description: Sorting a group of words inside a list


code:
print('hi\nmom')
# hi
# mom

print(repr('hi\nmom'))
# 'hi\nmom'

rawDescription: Replacing a string by a string with backslashes


code:
HP = 100

def atack():
    global HP
    hitChance = randint(0,1)
    damage = 10 + randint(0, 15)

    if hitChance == 0:
        print("Missed")

    elif hitChance == 1:
        HP -= damage
        print("{} delt".format(damage))
        print("{} HP left".format(HP))

rawDescription: Keep getting the same random values when using a function


code:
import tkinter as tk

def onKeyPress(event):
    global speed # alter the global speed variable inside a function

    text.insert('end', 'You pressed %s\n' % (event.char, ))

    if event.char == 'w':
        speed += 1
    elif event.char == 's':
        speed -= 1
    print(speed) # print current speed

speed = 50

root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)

root.mainloop()

rawDescription: Python - While Loop changing a variable

description: Python - While Loop changing a variable


rawDescription: How do I generate a list like the one in the example using a non-inclusive range? (Python)

description: Generate a list like the one in the example using a non-inclusive range? (Python)


rawDescription: Updating integer values of a dictionary in python


code:
a = np.zeros(shape=(6,6))
ma = np.matrix(a)
ma
ma[0,:]

rawDescription: How can I create a matrix, or convert a 2D array into matrix in Python?

description: Create a matrix, or convert a 2D array into matrix in Python


code:
import os

log_file = open(log_file_path, 'r+')
log_file.seek(0, os.SEEK_END)

rawDescription: python subprocess is overwriting file used for stdout - I need it to append to the file (windows)

description: Python subprocess is overwriting file used for stdout - I need it to append to the file (windows)


code:
fmt = '>' + str(592*600) + 'H'
pix = struct.unpack(fmt, trimdata)
scaled_pix = ''.join(chr(p/256) for p in pix)
im = Image.fromstring('L', (592,600), scaled_pix, 'raw')

rawDescription: Reading data from a 16-bit unsigned big endian raw image file in python


code: return render_template('index.html')

rawDescription: Use AJAX to upload a file, process, and return a result to Javascript using Flask


code: links = root.cssselect('td.dt1')

rawDescription: Python scraper (Scraperwiki) only getting half of the table


code:
for l in string.punctuation:
     if l in text:
        text = text.replace(l,'')

rawDescription: Most Common letter in a string

description: Most Common letter in a string


code:
my_dict = {'A7':'alphaNumeric', '36':'number', 'red':'string', 'green':'string', 'blue':'string'}
my_queries = ['A7', '', '', '', '36', '', '', '', 'green']

rawDescription: Returning key of value found in dictionary using 'value in dict.values()'


code:
ax.cla()
[n,X, V]=ax.hist(stat,bins=33,normed=True)
plt.draw()

rawDescription: Histogram update in a for loop with matplotlib.pylab


code:
class MyWindow(Window):
    def __init__(self):
        wpf.LoadComponent(self, 'IronPyWpf.xaml')
        self.button.Content = 'My Button'
        self.textbox.Text = 'My Text'

rawDescription: GUI development with IronPython and Visual Studio 2010


code:
img3 = alpha_composite(img1, img2)
img3.save('/tmp/img3.png')

rawDescription: With the Python Imaging Library (PIL), how does one compose an image with an alpha channel over another image?


code: "network" in key

rawDescription: python key unknown in yaml

description: Python key unknown in yaml


code:
f0 = [0,1,2]
f1 = []
f2 = [4,5,6]

features = [f0, f1, f2]

def get_nonempty_len(features):
    """
    returns the length of the first non-empty element
        of features.
    """
    for f in features:
        if len(f) > 0:
            return len(f)
    return 0

def generate_matrix(features):
    rows = len(features)
    cols = get_nonempty_len(features)
    m = np.zeros((rows, cols))
    for i, f in enumerate(features):
        m[i,:len(f)]=f
    return m

print(generate_matrix(features))

rawDescription: Filling empty list with zero vector using numpy


code:
my_dict = CountedOrderedDict({(123,1): 'sda', (232,1) : 'bfd', (234,2) : 'csd', (6745,2) : 'ds', (456,3) : 'rd'})
my_dict.counter
del my_dict[(123,1)]
my_dict.counter
my_dict[(150,1)] = "asdf"
my_dict.counter

rawDescription: Get key count from OrderedDict where key is a tuple


code: [(a, b) for a in iterable_a for b in iterable_b]

rawDescription: Understanding the map function

description: Understanding the map function


rawDescription: Column-wise (or row-wise) operations on matrices in sympy


rawDescription: Get coordinates from location_once_scrolled_into_view result


code: result = (df1.values * df2.values).sum(axis=1)

rawDescription: Applying np.dot to each row of two DataFrames


code:
from itertools import izip_longest
dictionary = dict(izip_longest(('key1', 'key2', 'key3'), list_of_values[:3]))

rawDescription: Python - How to use try/except statement in dictionary


code:
from functools import partial
...

for search_term in search_terms:
    func = partial(search_method, search_term)
    results = pool.map(func, partitions)

rawDescription: How can I improve CPU utilization when using the multiprocessing module?

description: Improve CPU utilization when using the multiprocessing module


code:
with patch.object(module_name, 'func_b') as mock_function:
    mock_function.return_value = "Fake value"
    self.assertEqual(func_a(), "The result of func_b is 'Fake value'")

rawDescription: Fake subfunction in django UnitTest Case (Mocking)


code: element = webdriver.find_element_by_xpath("//tr[contains(td, '8')]")

rawDescription: Python Selenium return HTML location

description: Python Selenium return HTML location


rawDescription: subsets [that are of length l] of list in S size

description: Subsets [that are of length l] of list in S size


code:
class Case(Base):
    # Column definitions go here...

    def as_dict(self):
        return {c.name: (getattr(self, c.name), c.info.get('description'))
                for c in self.__table__.c}

rawDescription: SQLAlchemy Declarative: Adding a static text attribute to a column


rawDescription: Use python requests to download CSV

description: Use python requests to download CSV


code: average_interval = total_interval / len(intervals)

rawDescription: Sum elements of a list (datetime) in one value


code: n1.body += n2.body

rawDescription: Python AST - merging two ASTs

description: Python AST - merging two ASTs


code:
d2
d2 = {name: pd.Series(arr) for name, arr in d2.iteritems()}
d2

rawDescription: Concatenating dictionaries of numpy arrays of different lengths (avoiding manual loops if possible)


rawDescription: What is an efficient way to slice a Pandas Series with a MultiIndex along multiple dimensions?


code:
params = {}
if name != '*':
    params['name'] = name
if age != '*':
    params['age'] = age

info = list(db.test.find(params))

rawDescription: How to use '*' in Mongodb?

description: Use '*' in Mongodb


rawDescription: Pandas : Proper way to set values based on condition for subset of multiindex dataframe


code:
import http.client
import json

connection = http.client.HTTPSConnection('api.github.com')

headers = {'Content-type': 'application/json'}

foo = {'text': 'Hello world github/linguist#1 **cool**, and #1!'}
json_foo = json.dumps(foo)

connection.request('POST', '/markdown', json_foo, headers)

response = connection.getresponse()
print(response.read().decode())

rawDescription: Python http.client json request and response. How?


code: print (a)

rawDescription: How do I make a variable created inside a function become global?

description: Make a variable created inside a function become global


code:
(ast.literal_eval(x) for x in f)  #turn each line in your file into a tuple
key=lambda z:(int(z[1]),z[0])     #function to determine how things are sorted.  Basically
                                  #sort as tuples:  `( int(z[1]),z[0] )`
reverse=True                      #descending order instead of ascending

rawDescription: Python Sorting Text File From Highest To Lowest Based On Column Values


code:
# Read in the source data
with open('input.txt', 'r') as handle:
    lines = handle.readlines()
# Open the output file
with open('input.txt', 'w') as handle:
    # Examine each line of the source data
    for line in lines:
        # If it doesn't end with a '0', write it
        if line.strip()[-1] != '0':
            handle.write(line)

rawDescription: Deleting lines in external text files

description: Deleting lines in external text files


code:
TIME_FORMAT = "%b %d"
arr = [d.strftime(TIME_FORMAT) for d in dates]

rawDescription: python django: convert the postgresql timestamp to datetime

description: Python django: convert the postgresql timestamp to datetime


rawDescription: How to select all data from Data Frame?

description: Select all data from Data Frame


code:
def decorate(function):
    def wrap_function(*args, **kwargs):
        str = 'Hello!'
        args.insert(1, str)
        return function(*args, **kwargs)
    return wrap_function

class Printer:
    @decorate
    def print_message(self, str, *args, **kwargs):
        print(str)

rawDescription: How can I pass a variable in a decorator to function's argument in a decorated function?

description: Pass a variable in a decorator to function's argument in a decorated function


rawDescription: Why are Python 3.6 literal formatted strings so slow?


code:
def triangle_random(count):
    x = random.randint(0, count-1) # randint includes both ends, so we need count-1
    y = random.randint(0, count)
    if x + y < count:
        return x
    else:
        return count-1 - x

rawDescription: Choose random element in list influenced by its position


code:
def tokenize(s):
  import re
  pattern = re.compile("(\-|\+\=|\=\=|\=|\+)|\s+")
  return [ x for x in pattern.split(s) if x ]

rawDescription: Python regex -- extraneous matchings

description: Python regex -- extraneous matchings


code: re.match(owner[j], str(team.value)) and (not re.findall('Defense|K,|KFG|KKO', str(position.value)))

rawDescription: Match multiple strings using re.search within an if condition


rawDescription: How to create a pandas Timestamp object?

description: Create a pandas Timestamp object


code:
master = repo.branches['master']
master

rawDescription: How do you merge the master branch into a feature branch with GitPython?

description: Merge the master branch into a feature branch with GitPython


code: not re1_matches and re2_matches

rawDescription: Merge several regular expressions into one RE


code:
form = LimitedJobForm(request.POST)

if form.is_valid():
    form.instance.color = pick_random_color()
    form.save()

rawDescription: Set form value without user input

description: Set form value without user input


code:
sel = treeview.get_selection()
sel.set_mode(gtk.SELECTION_NONE)

rawDescription: How can I disable "selection by clicking " on GTK+3 treeview

description: Disable "selection by clicking " on GTK+3 treeview


code:
@decorator
def foo(): pass

rawDescription: Python dynamic decorators - why so many wraps?


rawDescription: Extract matplotlib colormap in hex-format


code: user_likes.filter(is_active=1).exists() # user has liked an article and it is active

rawDescription: check for existence and active state in django filter

description: Check for existence and active state in django filter


rawDescription: Creating infinity and negative infinity in python for any object


code:
s = "     0000000125  1196672  9.2  The Shawshank Redemption (1994)"
s.split()
s.split(maxsplit=3)

rawDescription: Split a string into a list in Python

description: Split a string into a list in Python


code:
def make_from(inputString):
    if inputString.endswith('y'):
        fixed = inputString[:-1] + 'ies'
    elif inputString.endswith(('o', 'ch', 's', 'sh', 'x', 'z')):
        fixed = inputString[:] + 'es'
    else:
        fixed = inputString + 's'
    return fixed

rawDescription: str.endswith() does not seem to consider the first if statment

description: Str.endswith() does not seem to consider the first if statment


code: df["C"] = df.max(axis=1)

rawDescription: How should I take the max of 2 columns in a dataframe and make it another column?


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('
ignore thisget this
')
soup.div.find(text=True, recursive=False)

rawDescription: how to get text from within a tag, but ignore other child tags

description: Get text from within a tag, but ignore other child tags


code:
from operator import itemgetter
cat_sorted = zip(*sorted(zip(*cat), key=itemgetter(2)))

rawDescription: Python - Sorting elements in a list of lists


code:
tree = list_to_tree(data)
import pprint
pprint.pprint(tree)

rawDescription: Building a menu tree from an adjacency list in Python


code: np.savetxt('data.txt', data, fmt='%s', delimiter=",")

rawDescription: How can I load a csv file and store its contents into an (numpy) array in python?

description: Load a csv file and store its contents into an (numpy) array in python


code:
from kivy.properties import BooleanProperty

class Picture(Scatter):
    # ...
    do_scale =  BooleanProperty(False)

rawDescription: How to disable image stretching In the application kivy-example/demo/pictures/main.py

description: Disable image stretching In the application kivy-example/demo/pictures/main.py


rawDescription: python/pandas:need help adding double quotes to columns

description: Python/pandas:need help adding double quotes to columns


code:
import copy

def prune(CKK_branch):
    def pruner(list_, flag=None):
        internal_list = copy.deepcopy(list_)
        if flag is None:
            pruner.min = float("inf")
        # Check whether end of branch or whether optimal solution achieved
        if pruner.min == 0.:
            return pruner.min
        elif len(internal_list) == 1:
            return list_[0]
        # Sort branch
        internal_list.sort(reverse=True)
        # Prune branch
        if pruner.min < internal_list[0] - sum(internal_list[1:]):
            return internal_list[0]
        # Find minimum in branch and track minimum of all branches
        min_branch = CKK_branch(internal_list)
        pruner.min = min(pruner.min, min_branch)
        return min_branch
    pruner.__name__ = CKK_branch.__name__
    return pruner

@prune
def CKK(list_):
    internal_list = copy.deepcopy(list_)
    # Replace maximum two numbers by their difference and their sum in two
    # branches
    diff = internal_list[0] - internal_list[1]
    sum_ = internal_list[0] + internal_list[1]
    sum_tree = copy.deepcopy(internal_list)
    diff_tree = copy.deepcopy(internal_list)
    del sum_tree[0:2]
    del diff_tree[0:2]
    sum_tree.append(sum_)
    diff_tree.append(diff)
    return min(CKK(diff_tree,True), CKK(sum_tree,True))

rawDescription: Reset decorator for recursive function in Python


code:
for line in fList[:20]:
    print(line)

rawDescription: Converting .txt file to list AND be able to index and print list line by line


code:
a = set()
b = a
b.add(1)
b
a

rawDescription: Unwanted behaviour from dict.fromkeys

description: Unwanted behaviour from dict.fromkeys


code:
import re
s = """

/dev/sda:

ATA device, with non-removable media
    Model Number:       ST500DM002-1BD142
    Serial Number:      W2AQHKME
    Firmware Revision:  KC45
    Transport:          Serial, SATA Rev 3.0"""
m = re.search(r'Model Number:\s*([^\n]+)', s)
m.group(1)

rawDescription: Extract word from string Using python regex


code:
field1 = text_value1
field2 = text_value2
field3 = some_text

rawDescription: python's lxml and iterparse method

description: Python's lxml and iterparse method


code:
def sortOnFloat(sublist):
    return [v for v in sublist if isinstance(v, float)]

rawDescription: Sorting a list containing lists

description: Sorting a list containing lists


code:
for line in ips.readlines():
    ip = line.strip()
for line2 in pwd.readlines():
    Passwords = line2.strip()

rawDescription: While loop using text file, only uses last line - Python 2.x


code:
from Queue import Queue

class VoyeurQueue(Queue):

    def peek(self, block=True, timeout=None):
        self.not_empty.acquire()
        try:
            if not block:
                if not self._qsize():
                    raise Empty
            elif timeout is None:
                while not self._qsize():
                    self.not_empty.wait()
            elif timeout < 0:
                raise ValueError("'timeout' must be a non-negative number")
            else:
                endtime = _time() + timeout
                while not self._qsize():
                    remaining = endtime - _time()
                    if remaining <= 0.0:
                        raise Empty
                    self.not_empty.wait(remaining)
            item = self._peek()
            return item
        finally:
            self.not_empty.release()

    def _peek(self):
        return self.queue[0]

rawDescription: How to wait until a multithread queue is not empty without wasting too much cpu cycles

description: Wait until a multithread queue is not empty without wasting too much cpu cycles


rawDescription: Line-by-line Remote Data Transmission in Python


code:
import itertools

def lists(n):
    return itertools.product(xrange(n), repeat=n)

rawDescription: Generate all permutations of n by n list with max value n-1 without recursion python


code: rows = decoded.items()

rawDescription: Saving a dictionary as a file with columns which i can continously add to


code:
def one_percentage(data):
    #get total number of rows for calculating percentages
    size = len(data)
    #get type so only grabbing the correct rows
    x = data.columns[1]
    x = data[x].dtype
    #list of touples to hold amount of 1s and the column names
    ones = [(i,sum(data[i])) for i in data if data[i].dtype == x]
    my_dict = {}
    #create dictionary with column names and percent
    for x in ones:
        percent = x[1]/float(size)
        my_dict[x[0]] = percent
    return my_dict

rawDescription: Python Import data dictionary and pattern


code:
def agent_loc(a_maze):
    coor_list = str()
    for row, i in enumerate(a_maze):
         column = -1
         try:
             while True:
                  column = i.index("E", column+1)
                  coor_list = coor_list + str(row) + ";" + str(column) + "|"
         except ValueError:
             pass
    print(coor_list)

rawDescription: (Python) Index stops after finding one element in the row


code: Word(nums,exact=3) + '-' + Word(nums,exact=2) + '-' + Word(nums,exact=4)

rawDescription: pyparsing - defining keywords - compare Literal, Word, Keyword and Combine

description: Pyparsing - defining keywords - compare Literal, Word, Keyword and Combine


rawDescription: How to make List from Numpy Matrix in Python

description: Make List from Numpy Matrix in Python


code: {'and': ['more'], 'direction': ['implies'], 'implies': ['dimension', 'direction', 'measurement'], 'less': ['the'], 'measurement': ['implies'], 'the': ['implies', 'and'], 'dimension': [''], 'more': ['the']}

rawDescription: Python - sentence to a dictionary

description: Python - sentence to a dictionary


code:
import re

def replace_FOO(m):
    if m.group(1) is None:
        return m.group()

    return m.group().replace("FOO", "XXX")

string = "' FOO ' abc 123 ' def FOO ghi 345 ' FOO '' FOO ' lmno 678 FOO '"

output = re.sub(r"'[^']*'|([^']*)", replace_FOO, string)

print(string)
print(output)

rawDescription: Python regex to replace a string if not surrounded by single quotes


code:
arm = RobotArm()
print(arm.joints)
arm.joints = [1] * 5
arm.joints[0] = 5

rawDescription: When a list is used as a property in Python, the setter isn't actually called when you change an individual value in the list


rawDescription: Python Hash not being updated in csv file output


code:
import cv2
import numpy as np

#... Put your other code here....
#....

# Call if necessary
#img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Call cv2.findContours
contours,_ = cv2.findContours(img, cv2.RETR_LIST, cv2.cv.CV_CHAIN_APPROX_NONE)

rawDescription: Access pixel values within a contour boundary using OpenCV in Python


code:
m = np.ma.masked_array([1, 2, 3, 4], mask=[False, False, True, False])
m
m.count()

rawDescription: Most efficient way to determine if a numpy masked array contains any non-masked values?


code:
# Create a class to represent the planets.  Each planet will be an
# instance of this class, with attributes 'm' and 'p'.
class Planet(object):
    def __init__(self, m, p):
        self.m = m
        self.p = p

# Iterate over the three lists "in parallel" using zip().
for name, m, p in zip(planet, planetv, planetp):
    # Create a Planet and store it as a module-global variable,
    # using the name from the 'planet' list.
    globals()[name] = Planet(m, p)

rawDescription: Manipulating a list to increase code efficiency, struggling


rawDescription: Why no append() method on Django ValuesListQuerySet?


code:
from lxml import etree

xml = """your xml as posted in question here"""
root = etree.fromstring(xml)
nsmap = {'d': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
         'em': 'http://www.mozilla.org/2004/em-rdf#'}
result = root.xpath("/d:RDF/d:Description/em:targetApplication/d:Description/em:id/text()",
                    namespaces=nsmap)
print(result)

rawDescription: lxml xpath RDF not working

description: Lxml xpath RDF not working


code:
match = reg.match("binghamton ny 13905")
match.groupdict()

rawDescription: Extracting 2 strings from regular expression Python


code:
class Node(object):
    def __init__(self, x, *children):
        self.x = x
        self.children = []
        if children:
            self.children.extend(children)

    def updateLeafs(self, newx):
        if self.children:
            # This node has children: it is not a Leaf
            for c in self.children:
                c.updateLeafs(newx)
        else:
            # This node has no children -> Definition of a leaf !
            self.x = newx

    def __str__(self):
        "Pretty printing of the tree"
        if self.children:
            # A node
            return 'Node(%s -> [%s])' % (repr(self.x), ','.join(str(c) for c in self.children))
        else:
            # A leaf
            return 'Node(%s)' % repr(self.x)

rawDescription: Updating all objects in a class

description: Updating all objects in a class


code:
users[Q['uid']] = Q['uname']
userorders[Q['uid']].append(Q['order_id'])
orders[Q['orderid']].append(Q['item_id'])
items[Q['item_id']] = Q['itemname']

rawDescription: Re-organize a list using python with 1 to many relation


code:
try:
    doStuff(self.model.documents)
except AttributeError:
    otherStuff()

rawDescription: Django how to check if the object has property in view


code:
larray=tarray.tolist()
larray

rawDescription: separating mutidimensional array numpy python

description: Separating mutidimensional array numpy python


code:
with open('filetest') as f:
    for ligne in f:
        print(re.sub('E:.*\\\\','',ligne).rstrip('\n'))

rawDescription: Remove directory path from a text file

description: Remove directory path from a text file


rawDescription: Transform slow pandas iterrows into apply


code:
GOOGLE_APP_ENGINE_SDK = None # with your sdk path
# unless you are running with it included

rawDescription: Appengine non-interactive remote script

description: Appengine non-interactive remote script


code: myuniquelist = list(set(myuniquelist))

rawDescription: Extract subset from several file names using python


code: data.execute("select * from audio if filename LIKE ?", ('%{}%'.format(keywrd),))

rawDescription: return two lists from a list comprehension -- performance

description: Return two lists from a list comprehension -- performance


code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1977)

# Generate data
bins = np.arange(0, 10000, 100)
values = 3e7 * np.random.random(100)

# Don't use scientific notation
plt.rcParams['axes.formatter.limits'] = [-100, 100]

# Plot...
plt.bar(bins, values, width=100)
plt.margins(0.05, 0)
plt.show()

rawDescription: Matplotlib display error - narrow bars and distorted axis


code:
tabl = soup.find('table', {'class': 'content-table'})
rows = tabl.find_all('tr')

rawDescription: parsing html table using beautiful soup

description: Parsing html table using beautiful soup


code:
d = np.dtype([('value1','<f8'),('value2','<f8')])
[x[0] for x in d.descr]

rawDescription: Parsing complex numpy dtypes (i.e. dtypes consisting of an array of tuples) into lists?


code:
import itertools
OPS = ('+', '-', '*', '/')
def SearchTrees(current, target):
    ''' current is the current set of expressions.
        target is the target number.
    '''
    for a,b in itertools.combinations(current, 2):
        current.remove(a)
        current.remove(b)
        for o in OPS:
            # This checks whether this operation is commutative
            if o == '-' or o == '/':
                conmut = ((a,b), (b,a))
            else:
                conmut = ((a,b),)

            for aa, bb in conmut:
                # You do not specify what to do with the division.
                # I'm assuming that only integer divisions are allowed.
                if o == '/' and (bb.value == 0 or aa.value % bb.value != 0):
                    continue
                e = Expr(aa, o, bb)
                # If a solution is found, print it
                if e.value == target:
                    print(e.value, '=', e)
                current.add(e)
                # Recursive call!
                SearchTrees(current, target)
                # Do not forget to leave the set as it were before
                current.remove(e)
        # Ditto
        current.add(b)
        current.add(a)

rawDescription: Generate equation with the result value closest to the requested one, have speed problems


rawDescription: Create a list of Hex value in python

description: Create a list of Hex value in python


code:
from collections import Counter
Set1 = Counter({('soda','coca cola'): 5})
Set2 = Counter({('soda','coca cola'): 3, ('chocolate','mars'): 10})
Set1 + Set2

rawDescription: Python merge sets partially

description: Python merge sets partially


code:
import networkx as nx
import itertools

G = nx.complete_graph(10) # or DiGraph, MultiGraph, MultiDiGraph, etc
# Concatenate all the paths and keep unique nodes (in one line)
all_path_nodes = set(itertools.chain(*list(nx.all_simple_paths(G, source=0, target=3))))
# Extract the induced subgraph from a given list of nodes
H = G.subgraph(all_path_nodes)
print(nx.info(H))

rawDescription: Prune nodes not in networkx simple path?

description: Prune nodes not in networkx simple path


code:
import nltk
import itertools
from nltk.probability import FreqDist
texts = ['cat on the cat','angel eyes has','blue red angel','one two blue','blue whales eat','hot tin roof','angel eyes has','have a cat']
texts = [nltk.word_tokenize(text) for text in texts]
# collapse into a single list
tokens = list(itertools.chain(*texts))

FD =FreqDist(tokens)

rawDescription: Python/Pandas aggregation combined with NLTK


code:
class BitArray(object):
    def __init__(self, array):
        """Takes a bytearray object storing the bit data"""
        self.array = array

    def setbit(self, pos, value):
        byte, bit = divmod(pos, 8)
        if value:
            self.array[byte] |= (128 >> bit)
        else:
            self.array[byte] &= ~(128 >> bit)

rawDescription: Is there a correct way of creating a bit by bit binary string?


code:
import random

print('1. Flip a coin')
print('2. Pick a card')

choice = int(input('Enter a coice: '))

if choice == 1:
    HorT = random.randint(0,1)
    if HorT == 0:
        print('You got Heads')
    else:
        print('You got Tails')

elif choice == 2:
    print()
    print('1. Hearts')
    print('2. Clubs')
    print('3. Diamonds')
    print('4. Spades')
    print()
    suitno = int(input('Choose a suit: '))
    if suitno == 1:
        suit = "Hearts"
    elif suitno == 2:
        suit = 'Clubs'
    elif suitno == 3:
        suit = 'Diamonds'
    else:
        suit = 'Spades'

    value = random.randint(1, 13)
    print()
    print('You picked', value, 'of', suit)

rawDescription: Coin Flipping/Card picking program not working


rawDescription: how to access elements by path?

description: Access elements by path


code:
def trans(string):
    result = ""
    do_upper = False
    for character in string:
        if character == "*":
            do_upper = not do_upper  # change state; false to true and true to false
            continue  # no need to add the star to the output
        result += character.upper() if do_upper else character
    return result

rawDescription: Upper case between a char python

description: Upper case between a char python


code:
def __init__(self, file):
    if isinstance(file, basestring):
        # If a string filename was passed in, open the file before proceeding
        file = open(file)
    # Now you can handle file as a file object

rawDescription: The most 'Pythonic' way to handle overloading


code:
def ifibonacci():
    a, b = 0, 1
    while b < 3000:
        a, b = b, a + b
        yield a

rawDescription: How to get nth result from simple function in python?

description: Get nth result from simple function in python


code: A[np.in1d(A, B)]

rawDescription: Efficient way to compute intersecting values between two numpy arrays


code:
[('year', 'title', 'medium'),
 ('1962', 'Amazing Fantasy #15', 'comic book'),
 ('1967', 'Spider-Man', 'animation'),
 ('1977', 'The Amazing Spider-Man', 'television'),
 ('1978', 'Questprobe #2 Spider-Man', 'video game'),
 ('2002', 'Spider-Man', 'movie')]

rawDescription: Converting one string with multiple lists/arrays into separate lists


code:
cmap.set_under(color='black')
plt.imshow(a, interpolation='none', cmap=cmap, vmin=0.0000001)

rawDescription: Python color map but with all zero values mapped to black


code: res = es.index(index="article-index", doc_type='article', body=doc, id="some_unique_id")

rawDescription: ElasticSearch and Python - Correct methodolgy


code:
for b in rows:
    row = list(result_dict.get((a, b), None) for a in cols)
    # print the row

rawDescription: In Python: create a table to visualize pairwise data


code:
indices = list(range(len(names) - 1))
random.shuffle(indices)
for index in indices:
    print('I picked: {}'.format(names[index]))
    nextname = input('Who is next?')
    if nextname == names[index + 1]:
        print('Correct! It is indeed {}'.format(names[index + 1]))

rawDescription: how to find unknown variable in list?

description: Find unknown variable in list


code:
agg = df.resample('M',how='mean')
agg['cnt'] = range(len(agg))
agg

rawDescription: Python - Aggregate by month and calculate average


rawDescription: Algorithm for distributing tasks to two printers?


code:
print(xbest.sum())
1

rawDescription: Solving system using linalg with constraints


code:
import urllib2
import BeautifulSoup

def main():
    url = "http://allrecipes.com/Recipe/Slow-Cooker-Pork-Chops-II/Detail.aspx"
    data = urllib2.urlopen(url).read()
    bs = BeautifulSoup.BeautifulSoup(data)

    ingreds = bs.find('div', {'class': 'ingredients'})
    ingreds = [s.getText().strip() for s in ingreds.findAll('li')]

    fname = 'PorkChopsRecipe.txt'
    with open(fname, 'w') as outf:
        outf.write('\n'.join(ingreds))

if __name__=="__main__":
    main()

rawDescription: Python using Beautiful Soup for HTML processing on specific content


code: gr = P.Group(key_equal+val)

rawDescription: Non greedy parsing with pyparsing

description: Non greedy parsing with pyparsing


code: df

rawDescription: Pandas: rare data form disrupts normal statistical analysis


code:
import csv
from collections import Counter

strs="1 00; 1 00; 1 00; 5 16;"
c=Counter(tuple(map(int,x.split())) for x in strs.split(";") if x.strip())

#c is Counter({(1, 0): 3, (5, 16): 1})
#here I used a tuple (day,hour) as key and item after `,` as value

with open('master.csv', 'rb') as f1,open("newfile.csv","w") as f2:
     spamreader = csv.reader(f1, delimiter=',')
     header=next(spamreader)
     f2.write(",".join(header)+'\n')
     for row in spamreader:
         key,val=tuple(map(int,row[0].split())),int(row[1])
         #fetch tuple (day,hour) from the current line
         #val is the value after `,`

         val+=c[key] #new value is count from c + count from csv file

         f2.write("{0},{1}\n".format(" ".join(map(str,key)),val))

rawDescription: Count of an exact string in a given string, update count


code: form = FORM(Field('username'), requires=IS_IN_DB(db, db.users.username))

rawDescription: Web2Py minimal User authentication (username only)


code:
from optparse import OptionParser
import inspect
inspect.getmembers(OptionParser, predicate=inspect.ismethod)

rawDescription: How do I get list of methods in a Python class?

description: Get list of methods in a Python class


rawDescription: Python connected components

description: Python connected components


rawDescription: Changes in re module between Python 2 and Python 3


code:
alpha = open('alpha.csv','r')
csv_alpha = csv.reader(alpha)

alpha_file = dict()
for row in csv_alpha:
    if row[0] in alpha_file:
        alpha_file[row[0]].append(row[1])
    else:
        alpha_file[row[0]] = [row[1]]

rawDescription: Duplicate values in a dictionary

description: Duplicate values in a dictionary


code: count_all('1111', '11') # this returns 3

rawDescription: Does Python have a string contains how many substring method, allowing for overlap?


code:
import string
a = '"("This is your:, House")"'
''.join(x for x in a if x not in string.punctuation)

rawDescription: Better code then a regex sub() python 2.7


code:
yourNestedList = [[0,0]]*4
yourNestedList[1][1] = 5
print('Original wrong: %s' % yourNestedList)

my_nested_list = [[0,0] for count in range(4)]
my_nested_list[1][1] = 5
print('Corrected: %s' % my_nested_list)

# your nested list is actually like this
one_list = [0,0]
your_nested_list = [ one_list for count in range(4) ]
one_list[1] = 5
print('Another way same: %s' % your_nested_list)

rawDescription: Python: Replacing an element in a list of lists (#2)


code:
ilocs_window = pd.rolling_apply(df, window=5, func=lambda x: x.argmax(), min_periods=1)
ilocs = ilocs_window['value'] + ([0, 0, 0, 0] + range(len(ilocs_window)-4))
df['rolling_max_date'] = df.index.take(ilocs)

rawDescription: Most recent max/min value

description: Most recent max/min value


code:
from Tkinter import *
import time

class MyLoop():
    def __init__(self, root):
        self.running = True
        self.aboutToQuit = False
        self.root = root
        self.someVar = 0
        self.root.bind("<space>", self.switch)
        self.root.bind("<Escape>", self.exit)

        while not self.aboutToQuit:
            self.root.update() # always process new events

            if self.running:
                # do stuff
                self.someVar += 1
                print(self.someVar)
                time.sleep(.1)

            else: # If paused, don't do anything
                time.sleep(.1)

    def switch(self, event):
        print(['Unpausing','Pausing'][self.running])
        self.running = not(self.running)

    def exit(self, event):
        self.aboutToQuit = True
        self.root.destroy()

if __name__ == "__main__":
    root = Tk()
    root.withdraw() # don't show the tkinter window
    MyLoop(root)
    root.mainloop()

rawDescription: Pause an infinite while loop with a single keypress


code: list(map(str.strip, x.split('or')))

rawDescription: Regex for location matching - Python

description: Regex for location matching - Python


code:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class Product(RandomPrimaryIdModel):

    feature1 = models.CharField(max_length=20, blank=True, null=True)
    feature2 = models.CharField(max_length=20, blank=True, null=True)
    feature3 = models.CharField(max_length=20, blank=True, null=True)

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

rawDescription: How to access method of "sub-model" in Django?

description: Access method of "sub-model" in Django


code:
inputs = []
for i in range(1, 6):
    inputs.append(raw_input('Enter fruit for box {}: '.format(i)))

rawDescription: python lists values

description: Python lists values


code: n = ['"%s"' % x for x in folderlist]

rawDescription: Wxpython drag and drop folder path, Popen not working with spaces on Windows


code: total_result = [x.get() for x in jobs]

rawDescription: Gevent incremental process through non blocking joinall()


code:
from dis import dis
form_1 = compile("'Python' <> 'Python'", "string", 'exec')
form_2 = compile("'Python' != 'Python'", "string", 'exec')
dis(form_1)
dis(form_2)

rawDescription: When to use `<>` and `!=` operators?

description: When to use `<>` and `!=` operators


code: make_pair = lambda x,y: lambda m: x if m == 0 else y if m == 1 else None

rawDescription: How to create dispatch style lambda function using Python?

description: Create dispatch style lambda function using Python


code:
import random #preferably at the top of the script
myline = random.choice(lines)

rawDescription: How to make an annonimizer with random proxy/UA from files?

description: Make an annonimizer with random proxy/UA from files


rawDescription: Consecutive, conflicting regex substitutions


code:
val = next(my_gen)
print("--received {} from generator".format(val))

rawDescription: Python yield vs Ruby yield

description: Python yield vs Ruby yield


rawDescription: How to manipulate a URL string in order to extract a single piece?

description: Manipulate a URL string in order to extract a single piece


code:
with open('path/to/input') as infile:
    answer = {}
    for line in infile:
        x,y,v = line.split()
        k = (x,y)
        if k not in answer:
            answer[k] = []
        answer[k].append(v)
answer = {k:tuple(v) for k,v in answer.items()}

rawDescription: Python dictionary having tuple keys and values


code:
with open(f.name) as f:
    print(f.read())

rawDescription: How to download a file and pass it to a function

description: Download a file and pass it to a function


code:
realm = Realm("admin", "FDS$#%")
blog = realm.add(Blog("Kittens!"))
post = blog.add(Post("Cute kitten", "Some HTML blah blah"))

rawDescription: Python API design pattern question

description: Python API design pattern question


code:
if len(df.columns) > 1:
    lim1 = boundaries_list[0]
    locs = axes[0][1].yaxis.get_majorticklocs()
    locs = locs[(lim1[0] <= locs) & (locs <= lim1[1])]
    adj = (locs - lim1[0]) / (lim1[1] - lim1[0])

    lim0 = axes[0][0].get_ylim()
    adj = adj * (lim0[1] - lim0[0]) + lim0[0]
    axes[0][0].yaxis.set_ticks(adj)

    if np.all(locs == locs.astype(int)):
        # if all ticks are int
        locs = locs.astype(int)
    axes[0][0].yaxis.set_ticklabels(locs)

rawDescription: "Faking" axis ticks and labels with Matplotlib


code:
import re

inputlist = '''\
Project="Sparcy" Desc=""
Project="Libs" Desc=""
Project="Darwin" Desc=""
Project="Aaple" Desc="The big project"
Site="Phoenix" Protocol="Cheese"'''

regex = re.compile('([^ =]+) *= *("[^"]*"|[^ ]*)')

results = []
for project in inputlist.split("\n"):
    items = [ (k.strip(), v.strip()) for k, v in regex.findall(project)]
    if len(items) < 2:
        print("Houston we have a problem - Only %s k/v pair found for %s" % (len(items), project))
        continue
    item_dict = dict(items[1:])
    item_dict['name'] = items[0][1]
    projectname=items[0][0]
    metametaklass=type('meta_'+projectname,(type,),{'__repr__':lambda cls: cls.__name__})
    metaklass=metametaklass(projectname,(type,),{'__repr__':lambda cls: cls.name})
    klass=metaklass(projectname+'_class', (object,), item_dict)
    results.append(klass)

print(results)

rawDescription: Dynamically creating classes in python and __repr__


rawDescription: Compare 2 columns and select the same name


rawDescription: Identify groups of continuous numbers in a list


code:
sorted_inner = [[k, sorted(l)] for k, l in list_1]
sorted_outer = sorted(sorted_inner)

rawDescription: sorting a nested list by both members of an element

description: Sorting a nested list by both members of an element


code:
def my_decorator(thedecoratedfunction):
    def wrapped(*allofthearguments):
        print("This function has been decorated!") #something interesting
        thedecoratedfunction(*allofthearguments)   #calls the function as normal
    return wrapped

@my_decorator
def myfunction(arg1, arg2):
    pass

rawDescription: Dynamically update attributes of an object that depend on the state of other attributes of same object


code: split('ABC ; DEF123,GHI_JKL ; MN OP', (',', ';'))

rawDescription: Python: Split string by list of separators


code: keywords = ([line.strip() for line in f])

rawDescription: Search for a word in two files and print the the two lines with tabular separation


code: 你好

rawDescription: python - Retrieving Non English Text from MS SQL

description: Python - Retrieving Non English Text from MS SQL


code:
import unittest
import datetime

def fnc(a, b):
    return a + b

class MyTest(unittest.TestCase):
    def test_one(self):
        self.assertEqual(fnc(1,1), 2)

start = datetime.datetime.now()
tmp = unittest.main(module = '__main__', exit = False)
end = datetime.datetime.now()
duraction = end - start
print(duration)

rawDescription: Capture the run time from running a unittest TestCase into a Python variable


code:
import netaddr
import bisect

def subnets_overlap(subnets):
    # ranges will be a sorted list of alternating start and end addresses
    ranges = []
    for subnet in subnets:
        # find indices to insert start and end addresses
        first = bisect.bisect_left(ranges, subnet.first)
        last = bisect.bisect_right(ranges, subnet.last)
        # check the overlap conditions and return if one is met
        if first != last or first % 2 == 1:
            return True
        ranges[first:first] = [subnet.first, subnet.last]
    return False

rawDescription: Best approach to detect subnet overlap in a postgresql db


rawDescription: Dropping rows in python pandas

description: Dropping rows in python pandas


code:
for line in outputfile:
    print(line)

rawDescription: Reading arabic text encoded in utf-8 in python


code:
def opposing_numbers(increment, maximum):
     yield 0
     value = increment
     while value <= maximum:
         yield -value
         yield value
         value += increment

rawDescription: How do I write a custom generator function with python

description: Write a custom generator function with python


rawDescription: Numpy subset array between first and last occurence of logical expression match


code:
import numpy
data = numpy.array([(2, 4, 8), (3, 6, 5), (7, 5, 2)])
data
data.sum()  # product of all elements
data.sum(axis=1)   # sum of elements in rows
data.sum(axis=0)   # sum of elements in columns
numpy.product(data, axis=1)   # product of elements in rows
numpy.product(data, axis=0)   # product of elements in columns
numpy.product(data)      # product of all elements

rawDescription: Which Python module is suitable for data manipulation in a list?


rawDescription: Python: divide elements of a list based on a condition


code:
def subgen_1(i):
    yield i + 1
    yield i + 2
    yield i + 3

rawDescription: How to make Python recognize a function as a generator function?

description: Make Python recognize a function as a generator function


code: sorted_list = sorted(my_list, key=lambda x: x.lives_in)

rawDescription: How can I sort this list in Python?

description: Sort this list in Python


code:
import random
vector = [0]*(x-y) + [1]*y  # We can do this because numbers are immutable
vector.shuffle()

rawDescription: Picking subset in python and changing values of subset


rawDescription: .htaccess seemingly ignored on OpenShift


code: np.all(im == im2, axis=-1)

rawDescription: Opencv: How to detect pixel color change


code:
def b_spline_to_bezier_series(tck, per = False):
  """Convert a parametric b-spline into a sequence of Bezier curves of the same degree.

  Inputs:
    tck : (t,c,k) tuple of b-spline knots, coefficients, and degree returned by splprep.
    per : if tck was created as a periodic spline, per *must* be true, else per *must* be false.

  Output:
    A list of Bezier curves of degree k that is equivalent to the input spline.
    Each Bezier curve is an array of shape (k+1,d) where d is the dimension of the
    space; thus the curve includes the starting point, the k-1 internal control
    points, and the endpoint, where each point is of d dimensions.
  """
  from fitpack import insert
  from numpy import asarray, unique, split, sum
  t,c,k = tck
  t = asarray(t)
  try:
    c[0][0]
  except:
    # I can't figure out a simple way to convert nonparametric splines to
    # parametric splines. Oh well.
    raise TypeError("Only parametric b-splines are supported.")
  new_tck = tck
  if per:
    # ignore the leading and trailing k knots that exist to enforce periodicity
    knots_to_consider = unique(t[k:-k])
  else:
    # the first and last k+1 knots are identical in the non-periodic case, so
    # no need to consider them when increasing the knot multiplicities below
    knots_to_consider = unique(t[k+1:-k-1])
  # For each unique knot, bring it's multiplicity up to the next multiple of k+1
  # This removes all continuity constraints between each of the original knots,
  # creating a set of independent Bezier curves.
  desired_multiplicity = k+1
  for x in knots_to_consider:
    current_multiplicity = sum(t == x)
    remainder = current_multiplicity%desired_multiplicity
    if remainder != 0:
      # add enough knots to bring the current multiplicity up to the desired multiplicity
      number_to_insert = desired_multiplicity - remainder
      new_tck = insert(x, new_tck, number_to_insert, per)
  tt,cc,kk = new_tck
  # strip off the last k+1 knots, as they are redundant after knot insertion
  bezier_points = numpy.transpose(cc)[:-desired_multiplicity]
  if per:
    # again, ignore the leading and trailing k knots
    bezier_points = bezier_points[k:-k]
  # group the points into the desired bezier curves
  return split(bezier_points, len(bezier_points) / desired_multiplicity, axis = 0)

rawDescription: Approximating data with a multi segment cubic bezier curve and a distance as well as a curvature contraint


code:
['\n                ',
 '\n                    ',
 'Century Square',
 '\n                    2 Tampines Central 5',
 '\n                    #01-44-47 Century Square',
 '\n                    Singapore 529509',
 '\n                ',
 '\n                    ',
 'Opening Hours:',
 u'\n                    7am to 12am (Sun-Thu &\xa0PH)',
 u'\n                    24 Hours (Fri & Sat\xa0&',
 '\n                ',
 '\n                    Eve of PH)',
 '\n                    Telephone: 6789 0457',
 '\n            ']

rawDescription: scrapy, how to separate text within a HTML tag element

description: Scrapy, how to separate text within a HTML tag element


code: procs = [multiprocessing.Process(target=f, args=()) for _ in xrange(4)]

rawDescription: CPU (all cores) become idle during python multiprocessing on windows


code:
functions = [lambda x: x + 2, lambda x: x * 2]
reduce(lambda x, y: y(x), functions, 1)

rawDescription: How to apply an array of functions to a value using list comprehension?

description: Apply an array of functions to a value using list comprehension


code:
sorted_no = defaultdict(int)
for line in customers:
    rows = line.split(";")
    sorted_no[rows[0]] += 1

rawDescription: Assign values to dictionary by order they were added


code:
print (1) # since num_list[1] holds 1
print (1) # since num_list[1] holds 1
print (2) # since num_list[2] holds 2
print (3) # since num_list[3] holds 3
print (8) # since num_list[5] holds 8

rawDescription: Can someone tell me where the numbers disappear?


code:
from django import http
from django.core.urlresolvers import reverse

class SetUserTypeMiddleware(object):
    urls = ['/some/path/that/requires/user/type/',]

    def process_request(self, request):
        if not request.user.is_authenticated():
            return

        for url in urls: # customize url matching to your taste
            if url in request.path_info:
                return http.HttpResponseRedirect(reverse('setUserType'))

rawDescription: Execute a function in several views in Django


rawDescription: hashing different tuples in python give identical result

description: Hashing different tuples in python give identical result


code:
from itertools import repeat

def get_color_generator():
    # This will return a tuple with the colors on each iteration
    COLORS = repeat(("blue", "red", "yellow"))
    # This will never terminate ('repeat' without a second argument
    # creates an endless generator)
    for color_set in COLORS:
        for color in color_set:
            yield color

color_generator = get_color_generator()

def b1():
    bl = Label(master, text="Hell yeah!", fg=next(color_generator), bd = 3).pack()

rawDescription: Printing out different color text with each button press?


code:
# note this is different from the minimal change above
def parse_preflop_hand(hand, value):
    if len(hand) < 3 and hand[0] != hand[1]:
        return {hand + 's': value, hand+'o': value}
    else:
        return {hand: value}

final_dict = {}
for token in handstring.split(','):
    for unparsed_hand, value in token.split(":"):
        final_dict.update(parse_preflop_hand(unparsed_hand))

rawDescription: Python: Best way to parse the following

description: Python: Best way to parse the following


code:
a = Button(master, text="A", width=1, command=lambda: letter_toevoegen(nieuw_station, "a"))
a.pack()

rawDescription: Button excecutes command once (Tkinter)

description: Button excecutes command once (Tkinter)


rawDescription: When function can only be called once

description: When function can only be called once


rawDescription: Regex to retrieve at least 5 same numbers in a row


code: df.drop( labels=['x0', 'x1', 'x2', 'x3'], axis=1, inplace=True )

rawDescription: Calculating previous chance figure for use in chi square test


rawDescription: Using regex to find a string starting with /team/ and ending with /Euro_2012


rawDescription: Multiply array of vectors with array of matrices; return array of vectors?


rawDescription: How to delete all the odd ordinal items in a list?

description: Delete all the odd ordinal items in a list


code:
def printAllWorkers():
    strList = str(workers).strip('[]')
    with open('EmployeeList.txt','w') as file:
        file.write(strList)

rawDescription: All items in list duplicated when saved to text file - Python


code: [int("".join(map(str, bits[i:i+8])), 2) for i in range(0, len(bits), 8)]

rawDescription: Python bit list to byte list

description: Python bit list to byte list


code:
import os
basedir = 'tmp/example'
names = os.listdir(basedir)
names

rawDescription: How to check size of the files in a directory with python?

description: Check size of the files in a directory with python


code:
import requests
r = requests.post("http://127.0.0.1/search", data=allparams)

rawDescription: How to send bulk data in url?

description: Send bulk data in url


hello: stack overflow

rawDescription: Import JSON data into Python

description: Import JSON data into Python


code: [item for item in d.items() if [val for val in d.values()].count(item[1]) > 1]

rawDescription: Getting duplicates in dict

description: Getting duplicates in dict


code:
from random import randint
from datetime import datetime

day = randint(1, 29)
month = randint(5, 10)
year = 2015

dt = datetime(year=year, month=month, day=day)
dt_str = dt.strftime('%Y-%m-%d')

print(dt_str)

rawDescription: Basic string manipulation to make correct date formatting


code: pd.Series([[1, 2, 3]]).apply(lambda x: x[2])

rawDescription: How to recover lists that are saved in Series

description: Recover lists that are saved in Series


code:
import re

DATA = "allOrderProducts2"
RESULT = "test"

order_items = re.compile("<OrderProducts at 0x[\da-f]+, ({.*?})>", re.I).findall

with open(DATA) as inf, open(RESULT, "w", "utf-8") as outf:
    # Instead of reading each line separately,
    # we can just parse the whole file in one gulp
    for item_str in order_items(inf.read()):
        # Also no need to convert the data
        # just to cast it back to a string again
        outf.write(item_str + "\n")

rawDescription: Converting an unknown data structure to a known data structure in Python


code:
for row in sims:
    key = (tuple(row[:4]), row[4])

    row[5] = d[key]

rawDescription: Matching array elements to dictionary keys in Python


code:
import fileinput
for line in fileinput.input("Class {} data.txt".format(classNo),inplace=True):
    if surname.lower() in line:
        print("{} {}".format(line.rstrip(), score))
    else:
        print(line.rstrip())

rawDescription: Searching for string in text file and writing on the same line as this string


code:
def get_all_possible_items(max_no_users):
    range_dict = {}
    for i in range(0,max_no_users+1, 50):
        if i+49 < max_no_users:
            range_dict[i] = i+49
        else:
            range_dict[i] = max_no_users
    return range_dict

rawDescription: Python- Most efficient way to return batches of numbers


code: balls[:] = [ x for x in balls if x.times_bounced <= N ]

rawDescription: How to remove specific object from a list, if I can't use the variable it is attached to, to find its index?

description: Remove specific object from a list, if I can't use the variable it is attached to, to find its index


code:
import string
from functools import *
from itertools import *

def take(n, iterable): return islice(iterable, n)
def drop(n, iterable): return islice(iterable, n, None)

def splitOn(sep): return partial(string.split, sep=sep)

transitions = imap(splitOn(','), chain(*imap(splitOn('->'), drop(5, input))))

rawDescription: How to easily transition from Haskell to Python 3

description: Easily transition from Haskell to Python 3


code:
def mapper(f):
    def wrapper(items):
        for x in items:
            yield f(x)
    return rename_code_object(wrapper, f.__name__)

rawDescription: Changing the __name__ of a generator

description: Changing the __name__ of a generator


code: set.intersection(*(set(s) for s in list_of_lists if s))

rawDescription: Find common denominator for list entries Python


code:
class RangeShift:
    def __init__(self, rangeob, shift):
        self._range = rangeob
        self.shift = shift

    @property
    def start(self):
        r = self._range
        return (r.start + self.shift * r.step) % r.stop

    @property
    def stop(self):
        r = self._range
        return (r.stop + self.shift * r.step) % r.stop

    def index(self, value):
        idx = self._range.index(value)
        return (idx - self.shift) % len(self._range)

    def __getattr__(self, attr):
        return getattr(self._range, attr)

    def __getitem__(self, index):
        r = self._range
        return (r[index] + self.shift * r.step) % r.stop

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

    def __iter__(self):
        size, shift = self._range.stop, self.shift * self._range.step
        return ((i + shift) % size for i in self._range)

rawDescription: Python 3.x Shifting Ranges

description: Python 3.x Shifting Ranges


code:
rotate("hello", 2)
rotate("hello", -1)
rotate("hello", 1)
rotate("hello", 4)
rotate("hello", -3)
rotate("hello", 6)  # same with -6: no change if n > len(strg)

rawDescription: swap letters in a string in python

description: Swap letters in a string in python


code:
use1 = make_C(a=True)
use2 = make_C(b=True)

rawDescription: conditional class inheritance in python

description: Conditional class inheritance in python


rawDescription: Iterating members within lists within a tuple


code:
arg_names = ['command', 'x', 'y', 'operation', 'option']
args = dict(zip(arg_names, sys.argv))

rawDescription: Checking if sys.argv[x] is defined

description: Checking if sys.argv[x] is defined


rawDescription: Python: How to perform division according to its representation?


code:
x = pd.DataFrame([range(10),range(2,12)])
X = np.asarray(x)
arr

rawDescription: pandas build matrix of row by row comparisons

description: Pandas build matrix of row by row comparisons


code:
example.py
from flask import Flask, render_template
from flask_wtf import Form
from wtforms import validators, RadioField

app = Flask(__name__)

app.secret_key = 'TEST'

class TestForm(Form):
    choice_switcher = RadioField(
        'Choice?',
        [validators.Required()],
        choices=[('choice1', 'Choice One'), ('choice2', 'Choice Two')], default='choice1'
    )

@app.route('/')
def hello_world():
    testform = TestForm()
    return render_template('test_form.html', form=testform)

if __name__ == '__main__':
    app.run(debug=True)

rawDescription: How to make radio field show default value with flask and wtforms

description: Make radio field show default value with flask and wtforms


code: f = lambda y, z: math.sqrt(y**2 + z**2)

rawDescription: Distance Calculation Not Working

description: Distance Calculation Not Working


code:
from collections import defaultdict
d = defaultdict(set)
for num in datasource:
    d[key].add(num)

rawDescription: Creating a dictionary and adding a set as its value


code:
subprocess.Popen('sh abc.sh < /dev/null',
                 shell=True,
                 stdout=subprocess.PIPE)

rawDescription: Press enter as command input

description: Press enter as command input


code:
def login_user_with_secret_session(user, remember=False, force=False):
    auth_session_token = random.getrandbits(128)
    auth_session_token = '%032x' % auth_session_token
    # store `auth_session_token` in user table
    set_user_auth_session_token(user, auth_session_token)
    return login_user(user, remember=remember, force=force)

rawDescription: Ensuring single-user per account with flask-login


rawDescription: Numpy elementwise product of 3d array

description: Numpy elementwise product of 3d array


code:
from itertools import groupby
from operator import itemgetter

result = [''.join([c for i, c in group])
          for key, group in groupby(zip(idx, phon), itemgetter(0))]

rawDescription: Combine Python List Elements Based On Another List


code:
4495640448 # First instance and this is now stored in the set
           # hence it is not going to be garbage collected.
4495640840 # Python is now using new memory space.
4495640896 # Right now 4495640840 is still owned by the
           # previous instance, hence use new memory address
           # But after this assignment the instance at 4495640840
           # has no more references, i.e ins now points to 4495640896
4495640840 # Re-use 4495640840
4495640896 # Repeat...

rawDescription: How do I make sure an attribute value is unique in Python?

description: Make sure an attribute value is unique in Python


code:
from minimocktest import MockTestCase
from django.test import TestCase
from django.test.client import Client

class DjangoTestCase(TestCase, MockTestCase):
    '''
    A TestCase class that combines minimocktest and django.test.TestCase
    '''

    def _pre_setup(self):
        MockTestCase.setUp(self)
        TestCase._pre_setup(self)
        # optional: shortcut client handle for quick testing
        self.client = Client()

    def _post_teardown(self):
        TestCase._post_teardown(self)
        MockTestCase.tearDown(self)

rawDescription: Cleanly Mocking Remote Servers and APIs for Django Unittests


code:
df = pd.DataFrame({'id' : [1,1,1,2,2,3,3,3,3,4,4,5,6,6,6,7,7],
                   'value'  : [np.nan,"second","second","first",
                               "second","first","third","fourth",
                               "fifth","second","fifth","first",
                               "first","second","third","fourth","fifth"]})

rawDescription: What's the difference between groupby.first() and groupby.head(1)


code:
[['Col{}'.format(i) for i, t in enumerate(zip(*pair), 1) if t[0]!=t[1]] for pair
    in [(tuple1, tuple2), (tuple1, tuple3), (tuple2, tuple3)]]

rawDescription: Element by element comparison in tuple to return set of sets - python


rawDescription: How to increase the ipython qtconsole scrollback buffer limit

description: Increase the ipython qtconsole scrollback buffer limit


code:
import os
smallNum= int(input('smaller integer a: '))
bigNum= int(input('bigger integer b: '))

with open('filename.txt' ,'w') as myFile:
    myFile.write(" ".join([str(x) for x in list(range(smallNum+1,bigNum))]))

rawDescription: I want to write a code that can take two numbers and create a txt file between those numbers in decreasing order


rawDescription: Python-How to find length of the longest run of monotonically increasing numbers?


rawDescription: How do I slice a Multindex timeseries dataframe on Pandas?

description: Slice a Multindex timeseries dataframe on Pandas


code:
for file in def_scons_exe:
    if file == item[-len(file):]:
        filelist.append(filepath)
        break

rawDescription: finding specific type of files in mac (python)

description: Finding specific type of files in mac (python)


code:
for tablelist in list:
    for var in tablelist[1:]:
        print(tl[0] + '.' + var)

rawDescription: Extracting multiple values from multiple tables from Database using python


code:
with open('mediumWordList.txt') as f:
   sum(word.startswith('co') for line in f for word in line.split())

rawDescription: How to count number of words that start with a string

description: Count number of words that start with a string


code:
if type == "a":
    os.system("python script_a.py")
elif type == "b":
    os.system("python script_b.py")
else:
    print("Invalid option.")

rawDescription: Run Code based on User Input (Python3,Pandas)


code: unstack(df.year)    # suggested convention

rawDescription: Passing an argument as a attribute in a function?


code:
fn = 'cooltemp.dat'
c_values = loadtxt(fn,unpack=True,usecols=[1])

I=[]
for c in c_values: #can iterate over numpy arrays directly.  No need for `range(len(...))`

    # equation
    #eqn = 2*x*c[n] #This doesn't work, x not defined yet.

    # integrate
    result,error = integrate.quad(lambda x: 2*c*x, 0, 1)

    I.append(result)

I = array(I)

rawDescription: Numerical integration Loop Python

description: Numerical integration Loop Python


code:
type(Person.bound)
type(Person().bound)
type(unbound)
Person.unbound = unbound

rawDescription: Why isn't self being automatically passed to a method that is set on an object after its instantiation?


rawDescription: shuffle list with repetition constraint 2-back python

description: Shuffle list with repetition constraint 2-back python


rawDescription: python : lxml xpath tag name with colon

description: Python : lxml xpath tag name with colon


code:
def test():
    num1 = random.randint(1, 10)
    num2 = random.randint(1, num1)

    ops = {
        '+': lambda x, y: x + y,  #You can define the function right where you want to use it.
        '-': lambda x, y: x - y,
        '*': lambda x, y: x * y,
    }

    keys = list(ops.keys()) ##=> ['+', '*', '-']
    rand_key = random.choice(keys)  #e.g. '*'
    operation = ops[rand_key]  #e.g. lambda x, y: x*y

    correct_result = operation(num1, num2)

rawDescription: python: Primary school Arithmetic quiz- saving results to a .txt file

description: Python: Primary school Arithmetic quiz- saving results to a .txt file


rawDescription: Click the mouse to continue python 2

description: Click the mouse to continue python 2


rawDescription: How to redirect utf-8 output into txt file

description: Redirect utf-8 output into txt file


code:
import re
s = "5n7x Jahalducro) P4J99UMH9 (MD) auntud C D T)"
word_to_enclose = '5n7x'
enclosed_s = re.sub(r'(%s)' % word_to_enclose, r'~\1~', s)
re.sub(r'((?:[A-Za-z](?=\d+(?![A-Za-z\d]*~)))' \
    + r'|(?:\d+(?=[A-Za-z](?![A-Za-z\d]*~))))', r'\1 ', enclosed_s)

rawDescription: Avoid regex on a substring enclosed by a character


code:
from Crypto.Cipher import Blowfish
import binascii

# See @falsetru answer for the following method
#
def PKCS5Padding(string):
    byteNum = len(string)
    packingLength = 8 - byteNum % 8
    appendage = chr(packingLength) * packingLength
    return string + appendage

def PandoraEncrypt(string):
    key = b'6#26FRL$ZWD'
    c1  = Blowfish.new(key, Blowfish.MODE_ECB)
    packedString = PKCS5Padding(string)
    return c1.encrypt(packedString)

if __name__ == '__main__':
    s = 'testings'
    c = PandoraEncrypt(s)
    print(binascii.hexlify(c))

rawDescription: Python Blowfish Encryption

description: Python Blowfish Encryption


code:
df['ageD'], bins = pd.qcut(df.iloc[:, 0], 2, retbins=True)
left = (df["age"].values <= bins[:,None]).T.astype(int)
dl = pd.DataFrame(left, columns=["(-inf, {}]".format(b) for b in bins])
dr = pd.DataFrame(1-left, columns=["({}, +inf)".format(b) for b in bins])
dout = pd.concat([pd.get_dummies(df), dl, dr], axis=1)

rawDescription: Create open bounds indicators from pandas get_dummies on discretized numerical


code:
TimeSeries = pd.Series(tuple(zip(*(Value1, Value2, Value3))), index=Time)
TimeSeries.head()

rawDescription: Python: Creating a multicolumn serie with Pandas


code:
test1.func
Test.func

rawDescription: python functions

description: Python functions


code:
vertex_pair_indexes
first = vertex_pair_indexes[:, 0]
second = vertex_pair_indexes[:, 1]
np.linalg.norm(V[first] - V[second], axis=-1)

rawDescription: Tetrahedron side lengths from vertices (numpy)


rawDescription: numpy.power() and math.pow() don't give the same result

description: Numpy.power() and math.pow() don't give the same result


rawDescription: Modular addition in python

description: Modular addition in python


rawDescription: Fix values that are typed into a doublespinbox in PyQt


code:
def main():
    records = [
      # You know how you're acquiring these records; I don't.
      ]
    processed_records = [process_record(record) for record in records]
    for record in sorted(processed_records):
        print(",".join(str(dat) for dat in record))
    return

rawDescription: Combine multiple variable results into a single list in Python


rawDescription: Pandas Dataframe: get index of max element


code:
from django.contrib.formtools.wizard import FormWizard
from django import forms

class SubjectForm(forms.Form):
    subjects = forms.MultipleChoiceField(choices = (('language', 'language'),
    													('sport','sport')))

class RelatedQForm(forms.Form):
    """Overload the __init__ operator to take a list of forms as the first input and generate the
    fields that way."""
    def __init__(self, interested_subjects, *args, **kwargs):
    	super(RelatedQForm, self).__init__(*args, **kwargs)
    	for sub in interested_subjects:
    		self.field[sub] = forms.CharField(label = "What do you think about %s" % subject)

class SubjectWizard(FormWizard):
    def done(self, request, form_list):
    	process_form_list(form_list)

    def process_step(self, request, form, step):
    	if step == 1:
    		chosen_subs = form.cleaned_data['subjects']
    		self.form_list[1] = RelatedQForm(chosen_subs)

rawDescription: Django 1.1 FormWizard, Dynamically extend form


rawDescription: Including non-Python files with setup.py


code:
import re

camel_pat = re.compile(r'([A-Z])')
under_pat = re.compile(r'_([a-z])')

def camel_to_underscore(name):
    return camel_pat.sub(lambda x: '_' + x.group(1).lower(), name)

def underscore_to_camel(name):
    return under_pat.sub(lambda x: x.group(1).upper(), name)

rawDescription: Converting identifier naming between camelCase and underscores during JSON serialization/deserialization


code:
count = 0
phrase = "hello, world"
for iteration in range(5):
    count = count + len(phrase)
    print("Iteration " + str(iteration) + "; count is: " + str(count))

rawDescription: Can somebody please explain this code to me?


code:
x
out

rawDescription: Numpy sum running length of non-zero values


code: foo()

rawDescription: Defining a function multiple times

description: Defining a function multiple times


code:
# first multiplication (in both solutions)
np.dot(w, covar).shape
(3, 2)
# second, my solution
(np.dot(w, covar) * w).shape
(3, 2)
# second, Adam's solution
np.dot(np.dot(w,covar),w.T).shape
(3, 3)

rawDescription: Vectorized Portfolio Risk

description: Vectorized Portfolio Risk


code: difference = datetime.now() - start

rawDescription: Python: How to time script from beginning to end?


code:
import hashlib

class shad_256(object):
    """
    Double SHA - sha256(sha256(data).digest())
    Less susceptible to length extension attacks than sha256 alone.

    >>> s = shad_256('hello world')
    >>> s.digest_size
    32
    >>> s.block_size
    64
    >>> s.sha256.hexdigest()
    'b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9'
    >>> s.hexdigest()
    'bc62d4b80d9e36da29c16c5d4d9f11731f36052c72401a76c23c0fb5a9b74423'
    >>> s.nonexistant()
    Traceback (most recent call last):
    ...
    AttributeError: '_hashlib.HASH' object has no attribute 'nonexistant'
    >>> s2 = s.copy()
    >>> s2.digest() == s.digest()
    True
    >>> s2.update("text")
    >>> s2.digest() == s.digest()
    False
    """
    def __init__(self, data=None):
        self.sha256 = hashlib.sha256()
        if data is not None:
            self.update(data)

    def __getattr__(self, key):
        return getattr(self.sha256, key)

    def _get_final_sha256(self):
        return hashlib.sha256(self.sha256.digest())

    def digest(self):
        return self._get_final_sha256().digest()

    def hexdigest(self):
        return self._get_final_sha256().hexdigest()

    def copy(self):
        result = shad_256()
        result.sha256 = self.sha256.copy()
        return result

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

rawDescription: How do I derive from hashlib.sha256 in Python?

description: Derive from hashlib.sha256 in Python


code:
import getpass
import subprocess

password = getpass.getpass()
subprocess.call(["myscript", password ])

rawDescription: How to get input from user when connecting to remote servers? [Python]

description: Get input from user when connecting to remote servers? [Python]


code:
import re
s = "Take dog1 and dog5 to the dog kennel"
m = re.sub(r'dog(\d)', r'animal_\1', s)
m

rawDescription: Python regex sub with 1 following paramter


code:
from sqlalchemy.sql import or_

query = MyTable.q.filter(
        or_(MyTable.id == some_number, MyTable.id == some_other_number)
    )

rawDescription: Using OR in SQLAlchemy ORM query

description: Using OR in SQLAlchemy ORM query


code:
Formula
Value = A << 24 | R << 16 | G << 8 | B

rawDescription: Why is there bit shifting when converting to an image from an array?


code:
df = df.dropna()
df['date'] = df.apply(lambda x: pd.Timestamp('{year}-{month}-{day}'
                                .format(year=int(x.Year),
                                        month=int(x.Month),
                                        day=int(x.Day))),
                      axis=1)

rawDescription: How to use Pandas to take multi year average in Python

description: Use Pandas to take multi year average in Python


code:
def strpdelta(s):
    hr, min, sec = map(float, s.split(':'))
    return datetime.timedelta(hours=hr, minutes=min, seconds=sec)

rawDescription: Adding a timedelta of the type "hh.mm.ss.ms" to a datetime object


rawDescription: Partitioning a set of values in Python

description: Partitioning a set of values in Python


code:
@app.route('/get_data', methods=['GET'])
def get_data():
    df = sqlio.read_sql(query, conn)
    value = df['my_column'][0]
    return value

rawDescription: Refresh Javascript to get new values from Flask


code:
class Musician(models.Model):
    name = models.CharField(max_length=128)
    initial_band = models.ForeignKey("Band", related_name = 'initial_band_members')
    final_band = models.ForeignKey("Band", related_name = 'final_band_members')

class Band(models.Model):
    name = models.CharField(max_length=128)
    genre = models.CharField(max_length=50)

try: ## create some objects
    cream,_ = Band.objects.get_or_create(name="Cream", genre="Classic Rock")
    derek, _ = Band.objects.get_or_create(name="Derek and the Dominos", genre="Classic Rock")
    beatles, _ = Band.objects.get_or_create(name="The Beatles", genre="Classic Rock")
    wings, _ = Band.objects.get_or_create(name="Wings", genre="Classic Rock")
    Musician.objects.get_or_create(name="Eric Clapton", initial_band=cream, final_band=derek)
    Musician.objects.get_or_create(name="Paul McCartney", initial_band=beatles, final_band=wings)
    Musician.objects.get_or_create(name="John Lennon", initial_band=beatles, final_band=beatles)

except:
    pass

rawDescription: django: is there a black magic on extra fields on many-to-many relationships?

description: Django: is there a black magic on extra fields on many-to-many relationships


code:
def leftshift(ba, count):
    return ba[count:] + (bitarray('0') * count)

def rightshift(ba, count):
    return (bitarray('0') * count) + ba[:-count]

rawDescription: How to left shift a bitarray in python

description: Left shift a bitarray in python


code:
from re import findall
line = "Hello my name is {{ name }} and I am {{ age }} years old."
findall("{{\s(.*?)\s}}", line)

rawDescription: Finding a string pattern in a string

description: Finding a string pattern in a string


code: sum('\n' in item for item in data)

rawDescription: Python .count: Can't find correct syntax to count \n


code:
def check(string, counter=0):
  if not string:
    return "Balanced" if counter == 0 else "Unbalanced"
  elif counter < 0:
    return "Unbalanced"
  elif string[0] == "(":
    return check(string[1:], counter+1)
  elif string[0] == ")":
    return check(string[1:], counter-1)
  else:
    return check(string[1:], counter)

rawDescription: Turning iteration into recursion

description: Turning iteration into recursion


code:
import re

regex = re.match(r'''(
    ^\s*clns\s+routing$ |
    ^\s*bfd\s+graceful-restart$ |
    ^\s*ip\s+default-network$ |
    ^\s*ip\s+default-gateway$ |
    ^\s*ip\s+subnet-zero$ |
    ^\s*ip\s+cef\s*$
)+''', re.MULTILINE | re.VERBOSE)

rawDescription: Match multiple lines in a file using regular expression python


code:
def dist(lat1, long1, lat2, long2):
    return np.abs((lat1-lat2)+(long1-long2))

rawDescription: How to find the closest match based on 2 keys from one dataframe to another?

description: Find the closest match based on 2 keys from one dataframe to another


code: ['the green fox', 'the yellow fox', 'the yellow rabbit']

rawDescription: Python Nested List Comprehensions on Multiple Lists


rawDescription: convert entire pandas dataframe to integers in pandas (0.17.0)

description: Convert entire pandas dataframe to integers in pandas (0.17.0)


rawDescription: Get value of attribute using CSS Selectors with BeutifulSoup


code:
with open('filename','rb') as f:
    var = pickle.load(f)

rawDescription: Python serialization - Why pickle?

description: Python serialization - Why pickle


rawDescription: Python Wacom Interface

description: Python Wacom Interface


code:
from unittest import TestCase
from nose.plugins.attrib import attr

@attr(speed='slow')
class MyTestCase(TestCase):
    def test_long_integration(self):
        pass
    def test_end_to_end_something(self):
        pass

class MyOtherTestCase(TestCase):
    def test_super_long_integration(self):
        pass

rawDescription: How to skip nosetests of class decorated with nose.plugins.attrib.attr in shell

description: Skip nosetests of class decorated with nose.plugins.attrib.attr in shell


code:
i = 0
while i < 10:
    print(i)
    i += 2

rawDescription: Changing while and for loops in python

description: Changing while and for loops in python


rawDescription: Conditionally combine columns in pandas data frame


code:
import numpy as np
maxdim = np.max(wv.shape)
indi = ~np.abs(indexd)
wav = (np.sum(wv))/(maxdim*(maxdim-1))
thetau = (np.sign(np.sign(wv - wav) - 0.1) + 1)/2
thetad = (np.sign(np.sign(wav - wv) - 0.1) + 1)/2

rawDescription: Translating mathematical functions from MATLAB to Python


rawDescription: Plotting the difference between two datetime64[ns]


code:
n = int(raw_input(':'))
["c{}".format(x) for x in xrange(1, n+1)]

rawDescription: How to generate a string with user specifying the length

description: Generate a string with user specifying the length


code:
def Tower(Properties):
    Button = Properties[5]
    Button.onclick(make_movement(Properties))

rawDescription: Towers of hanoi in python with turtle graphics moving disks


code:
for i, letter in enumerate(text):
    #stuff
    if i < len(text) - 1:
        sys.stdout.write(', ')

rawDescription: Taking input containing " or ' with argparse


code:
class C:
    def f(self):
        return 'hello world'

a = C()
b = C()
print(a.f == b.f)  # False

class C:
    @staticmethod
    def f():
        return 'hello world'

a = C()
b = C()
print(a.f == b.f)  # True

rawDescription: Is every function in the class with `self` an instance variable even if it just does something unrelated to the specific instance?


code:
class FooForm(forms.Form):
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super(FooForm, self).__init__(*args, **kwargs)
        if user:
            # calculate the list of years based on user's information and the rules you have
            # e.g. years = range(2010, 2016)
            self.fields['birthday'] = forms.DateField(widget=SelectDateWidget(empty_label=('Year', 'Month', 'Day'),
                                                      years=years))

rawDescription: Set Months and Day Ranges for SelectDateWidget in Django


code:
dff = {}
for i, r in enumerate(rows[:-1]):
    dff[i] = df[r+1: rows[i+1]]

rawDescription: Split pandas dataframe by String

description: Split pandas dataframe by String


rawDescription: How can I iterate through the indices of the list?

description: Iterate through the indices of the list


code:
vocab = np.asarray(['a', 'aaa', 'b', 'c', 'd', 'e', 'f'])
out = np.searchsorted(vocab,sentence,'left').astype(float)
out

rawDescription: match non-unique, un-sorted array to indexes in unique, sorted array

description: Match non-unique, un-sorted array to indexes in unique, sorted array


code:
DF['Season'] = ""
for row in DF.index:
    DF.Season[row] = SeasonDict[row.month]
DFWinter = DF[DF.Season == 'Winter']

rawDescription: Pandas, groupby and summing over specific months


code:
standardDeduction = 6300
personalExemption = 4000
tax_brackets = [ (     0,   9225, 0.10),
                 (  9225,  37450, 0.15),
                 ( 37450,  90750, 0.25),
                 ( 90750, 189300, 0.28),
                 (189300, 411500, 0.33),
                 (411500, 413200, 0.35),
                 (413200,   None, 0.396) ]

def calculate_tax(total):
    no_tax = standardDeduction + personalExemption
    taxable = total - no_tax
    total_tax = 0.0
    for min_val, max_val, tax in tax_brackets :
        if taxable <= 0:
            break
        amount = (max_val - min_val) if max_val is not None else min_val
        if taxable <= amount:
            amount = taxable
        total_tax += amount * tax
        taxable -= amount
    return total_tax

rawDescription: Powerball winnings using if else statements in python


code:
def remove(x):
    for phrase in remove_l:
        if re.search(phrase, x):
            if phrase == '-':
                x = x.replace(phrase, ' ')
            else:
                x = x[re.search(phrase, x).span()[1]:].strip()
    return x

rawDescription: using a for loop within a .apply() for pandas dataframes

description: Using a for loop within a .apply() for pandas dataframes


rawDescription: How can I create a user defined data structure in python

description: Create a user defined data structure in python


code:
x = [1, 2, 3]
x.extend([4, 5]) # nothing is returned here
x

rawDescription: how to pass self to function inside python dictionary

description: Pass self to function inside python dictionary


code: from uncertainties.numpy_ops import *  # Work on everything (scalars, arrays, numbers with uncertainties, arrays with uncertainties)

rawDescription: Definition of mathematical operations (sin…) on NumPy arrays containing objects


rawDescription: how do I separate each tr in a table in python?

description: Separate each tr in a table in python


code: x1 = sys.argv[1:]

rawDescription: how to pass command line string arguments and compare them python

description: Pass command line string arguments and compare them python


code:
def read(filename, rows):
    x = open(filename)
    y = csv.reader(x)
    for row in y:
        rows.append(row)
    x.close()
    return rows

# One list per file:
list1 = []
read("file1.csv", list1)

# Multiple files combined into one list:
listCombined = []
read("file2.csv", listCombined)
read("file3.csv", listCombined)

rawDescription: Condensing Repetitive Code

description: Condensing Repetitive Code


code: I,J=m.row, m.col

rawDescription: Scipy sparse matrix assignment using only stored elements


rawDescription: Get the value of a tag which has another tag before its value with BeautifulSoup


code:
import time
NAMES = [
    {'name': 'Fred Flintstone', 'id': 1},
    {'name': 'Barney Rubble', 'id': 2},
    {'name': 'Henry Ford', 'id': 3}
]

class Fred (object):
    def __init__ (self):
        self._names = []

    @property
    def names (self):
        if not self._names:
            print('Load the data here; might take a while.')
            time.sleep(5)
            self._names = NAMES
        return self._names

    def getNames (self):
        return [x['name'] for x in self.names]

    def searchNameById (self, id):
        return filter(lambda x: x['id'] == id, self.names)

    def searchNameByName (self, name):
        return filter(lambda x: x['name'] == name, self.names)

f = Fred()

print('Querying some stuff:')
print(f.searchNameById(2))
print(f.searchNameByName('Fred Flintstone'))
print(f.names)
print(f.getNames())

rawDescription: Multiple Python decorators when using "replacing" functions


code:
class AuthorSerializer(serializers.ModelSerializer):
    class Meta:
        model = Author
        fields = ('id', 'name')

class BookSerializer(serializers.ModelSerializer):
    book_written_by = AuthorSerializer()

rawDescription: What is the easiest way to get custom serialized model with ForeignKey field


code:
for name,*items in dataReader:
    my_dict.setdefault(name,[]).append(items)

rawDescription: Parse a file into a dictionary of arrays


code:
from __future__ import print_function
from subprocess import PIPE, Popen
from threading  import Thread
import sys

try:
    from Queue import Queue, Empty
except ImportError:
    from queue import Queue, Empty  # python 3.x

ON_POSIX = 'posix' in sys.builtin_module_names

def enqueue_output(out, queue):
    for line in iter(out.readline, b''):
        line = line.decode(sys.stdout.encoding)
        queue.put(line)
    out.close()

def main():
    p = Popen(['c/main.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX)
    q = Queue()
    t = Thread(target=enqueue_output, args=(p.stdout, q))
    t.daemon = True # thread dies with the program
    t.start()

    #initially the queue is empty and stdout is open
    #stdout is closed when enqueue_output finishes
    #then continue printing until the queue is empty

    while not p.stdout.closed or not q.empty():
        try:
            line = q.get_nowait()
        except Empty:
            continue
        else:
            print(line, end='')
    return 0

if __name__ == '__main__':
    sys.exit(main())

rawDescription: Python capture stdout from subprocess line by line


code: filtered = [x for x in os.listdir('.') if not re.search(r'\.py~?$', x)]

rawDescription: Python: removing multiple values from a list where using filters is more awkward


code: map("world", plot=T )

rawDescription: Detecting geographic clusters

description: Detecting geographic clusters


code:
def fixer(q,r):
    if q == '-':
        return r
    if r == '-':
        return ''
    return q

fixed = ''.join(map(fixer, query, ref))
fixed

rawDescription: Repair one string relative to another in Python


code:
import BeautifulSoup

def get_tables(htmldoc):
    soup = BeautifulSoup.BeautifulSoup(htmldoc)
    return soup.findAll('table')

rawDescription: How to convert an HTML table to an array in python

description: Convert an HTML table to an array in python


code:
data = np.random.randint(256, size=(1000000,)).astype('uint8')
data[-1] = 0 # to avoid errors with last element

rawDescription: Iterating over a numpy array, selectively picking one or two values, given a criterion


code:
import datetime as DT
import pytz
utc = pytz.utc
def tzones(timestamp, utcoffset):
    result = []
    date = utc.localize(DT.datetime.utcfromtimestamp(timestamp/float(1000)))
    for name in pytz.all_timezones:
        timezone = pytz.timezone(name)
        date = date.astimezone(timezone)
        if date.utcoffset().total_seconds() == utcoffset:
            result.append(name)
    return result

print(tzones(1456865863633, -14400))

rawDescription: Python - Timezone name given timestamp UTC and UTC offset


code:
import json
import pyodbc
cnxn = pyodbc.connect("DSN=myDb_SQLEXPRESS")
cursor = cnxn.cursor()
sql = """
SELECT '1-3580671' AS SRNumber, 'foo' AS thing
UNION ALL
SELECT '1-3580156' AS SRNumber, 'bar' AS thing
"""
cursor.execute(sql)
columns = [column[0] for column in cursor.description]

results = []
for row in cursor.fetchall():
    result = dict(zip(columns, row))
    results.append({"MetaData": {}, "SRData": result})

cnxn.close()

print(json.dumps(results, sort_keys=True, indent=4))

rawDescription: How to assign one JSON key to all output dictionaries?

description: Assign one JSON key to all output dictionaries


code:
from itertools import chain
seen = set()
[x for x in chain(s1,s2) if x[0] not in seen and not seen.add(x[0])]

rawDescription: Python Operations (Intersection, Union, Duplicate) with nested Lists/Tuples possible?


code:
import itertools

def necklaces_with_multiplicity(n):
    assert isinstance(n, int)
    assert n > 0
    w = [1] * n
    i = 1
    while True:
        if n % i == 0:
            s = sum(w)
            if s > 0:
                yield (tuple(w), i * 2)
            elif s == 0:
                yield (tuple(w), i)
        i = n - 1
        while w[i] == -1:
            if i == 0:
                return
            i -= 1
        w[i] = -1
        i += 1
        for j in range(n - i):
            w[i + j] = w[j]

def leading_zero_counts(n):
    assert isinstance(n, int)
    assert n > 0
    assert n % 2 == 0
    counts = [0] * n
    necklaces = list(necklaces_with_multiplicity(n))
    for combo in itertools.combinations(range(n - 1), n // 2):
        for v, multiplicity in necklaces:
            w = list(v)
            for j in combo:
                w[j] *= -1
            for i in range(n):
                counts[i] += multiplicity * 2
                product = 0
                for j in range(n):
                    product += v[j - (i + 1)] * w[j]
                if product != 0:
                    break
    return counts

if __name__ == '__main__':
    print(leading_zero_counts(12))

rawDescription: How to speed up multiple inner products in python

description: Speed up multiple inner products in python


code: f = lambda x, y : x * y

rawDescription: How to use filter() on a string and get multiple word occurences?

description: Use filter() on a string and get multiple word occurences


code:
import urllib
ip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()

rawDescription: Finding a public facing IP address in Python?


code:
import csv
genes = {}
with open('mydata.txt', 'rb') as f:
    for row in csv.DictReader(f, delimiter='\t'):
        gene = genes.setdefault(row['geneid'], {})
        transcript = gene.setdefault(row['tx_id'], {})
        transcript['colname1'] = row['colname1']
        transcript['colname2'] = row['colname2']

rawDescription: Initialize/Create/Populate a Dict of a Dict of a Dict in Python


code: ':'.join([dpid_string[i:i + 2] for i in range(0, len(dpid_string), 2)])

rawDescription: String formating by inserting ':'

description: String formating by inserting ':'


code: plt.scatter(sigma_flat, mu_flat, accuracy_flat, defect)

rawDescription: How to reformat data for a 4 Dimensional Heatmap (3 space dimensions + intensity)

description: Reformat data for a 4 Dimensional Heatmap (3 space dimensions + intensity)


rawDescription: How do I select an element by its style from css (not inline) using webdriver (python)

description: Select an element by its style from css (not inline) using webdriver (python)


code:
person.make_statement
ms = person.make_statement
ms()

rawDescription: How are arguments passed to a function through __getattr__


code:
areas = Column(u'AREAS', VARCHAR(80))

@property
def areasList(self):
    return self.areas.split(';')

@areasList.setter
def areasList(self, areas):
    self.areas = ';'.join(areas)

rawDescription: WTForms - multi-value string to SelectMultipleField


code:
extract_keys(abc, 's')
extract_keys(abc, 'b')

rawDescription: dictionary that contains list

description: Dictionary that contains list


code: r.apply(lambda x: pd.Series(norm.pdf(x, mean, variance), index=k))

rawDescription: I have a gaussian function with two independent discrete variables. How do I create a matrix of all possible values?


code:
x = 'this is a test'
x.rsplit(None, 1)[-1]  # Splits at most once from right on whitespace runs

rawDescription: Split off the contents of a variable after the last space in python?


code:
import io
from csv import DictReader

csvfile = io.StringIO('''Names,Size,State,time1,time2
S1,    22,   MD  , 0.022 ,  523.324
S2,    22,   MD  , 4.32  , 342.54
S3,    22,   MD  , 3.54  ,   0.32
S4,    22,   MD  , 4.32  ,  0.54
S1,    33,   MD  , 5.32  ,  0.43
S2,    33,   MD  , 11.54 ,  0.65
S3,    33,   MD  , 22.5  ,  0.324
S4,    33,   MD  , 45.89 ,  0.32
S1,    44,   MD  , 3.53  ,  3.32
S2,    44,   MD  ,  4.5  ,  0.322
S3,    44,   MD  , 43.65 ,   45.78
S4,    44,   MD,   43.54 , 0.321
''')

reader = DictReader(csvfile, delimiter=',')
first = True
data={}
col_name = input("What column do you want to see:  (x,y,z)")
for row in reader:
    # print(row)
    size = int(row['Size'])
    column = float(row[col_name])
    if not size in data:
        data[size] = []
    data[size].append(column)

print(data)

rawDescription: Change values of CSV based on user Response


code:
#      id  event  eventDate  direction idEventNumber      nextEvent daysUntilNextEvent
#  1: id1  apple 1977-06-26 positive            1000     negative                 1040
#  2: id1  apple 1980-07-01 positive            1002     positive                  143
#  3: id1  candy 1980-05-01 negative            1001     positive                   61
#  4: id1  apple 1980-11-21 positive            1003 noFurtherEvent                 -1
#  5: id2  fruit 1980-06-26 positive            1000     negative                 3652
#  6: id2 cookie 1990-06-26 negative            1001     negative                  384
#  7: id2 cavity 1991-07-15 negative            1002     positive                    1
#  8: id2  apple 1991-07-16 positive            1003     positive                 2011
#  9: id2  apple 1997-01-16 positive            1004 noFurtherEvent                 -1
# 10: id3 cookie 2010-04-20 negative            1000 noFurtherEvent                 -1
# 11: id4 cookie 2010-04-20 negative            1000     negative                    0
# 12: id4 cookie 2010-04-20 negative            1001 noFurtherEvent                 -1

rawDescription: Create new column based on next row

description: Create new column based on next row


code: [l for l in open(dr+"/"+f).readlines()[22:25]]

rawDescription: Code for coyping specific lines from multiple files to a single file (and removing part of the copied lines)


code:
import re
regex =  re.compile('\n^(.*?):(.*?)$|,', re.MULTILINE) #compile regex
js_text = re.findall(regex, js_text) #  find first item @ new line to : and 2nd item @ from : to the end of the line or ,
js_text = [jt.strip() for jt in js_text] #  to strip away all of the extra white space.

rawDescription: Parsing JS with Beautiful soup

description: Parsing JS with Beautiful soup


code:
def test():
    """test"""
    doc = test.__doc__
    name = test.__name__
    return doc, name

test()

rawDescription: Python introspection: access function name and docstring inside function definition


code: words =  f.read().split()

rawDescription: Removing a space from a list element?

description: Removing a space from a list element


code:
class College:
    def __init__(self, url='http://dummy', courses=None):
        self.url = url
        self.courses = courses or set()

rawDescription: Why does JSONDecoder deserialize json String to Python Objects intuitively?


code:
from sqlalchemy.orm.collections import InstrumentedList
from sqlalchemy.ext.associationproxy import association_proxy

class ListNodeAssociation(Base):
    __tablename__ = 'nodes_list_nodes'
    parent_id = Column(None, ForeignKey('nodes_list.id'), primary_key=True)
    child_id = Column(None, ForeignKey(Node.id), primary_key=True)
    order = Column(Integer, nullable=False, default=0)
    child = relation(Node)
    __table_args__ = (
        PrimaryKeyConstraint('parent_id', 'child_id'),
        {},
    )

class OrderedList(InstrumentedList):

    def append(self, item):
        if self:
            item.order = self[-1].order+1
        else:
            item.order = 1
        InstrumentedList.append(self, item)

class ListNode(Node):
    __mapper_args__ = {'polymorphic_identity': 'list'}
    __tablename__ = 'nodes_list'
    id = Column(None, ForeignKey('nodes.id'), primary_key=True)
    _items = relation(ListNodeAssociation,
                      order_by=ListNodeAssociation.order,
                      collection_class=OrderedList,
                      cascade='all, delete-orphan')
    items = association_proxy(
                '_items', 'child',
                creator=lambda item: ListNodeAssociation(child=item))

rawDescription: Creating container relationship in declarative SQLAlchemy


rawDescription: Find length of string matched by regex

description: Find length of string matched by regex


code:
from pipes import quote
quote("""some'horrible"string\with lots of junk!$$!""")

rawDescription: Quote POSIX shell special characters in Python output


rawDescription: What is the best way to do multi-dimensional indexing with numpy?