code:
import matplotlib.pyplot as plt

from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

import numpy as np

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

fig = plt.figure(1, [5,4])
ax = fig.add_subplot(111)

# prepare the demo image
Z, extent = get_demo_image()
Z2 = np.zeros([150, 150], dtype="d")
ny, nx = Z.shape
Z2[30:30+ny, 30:30+nx] = Z

# extent = [-3, 4, -4, 3]
ax.imshow(Z2, extent=extent, interpolation="nearest",
          origin="lower")

axins = zoomed_inset_axes(ax, 6, loc=1) # zoom = 6
axins.imshow(Z2, extent=extent, interpolation="nearest",
             origin="lower")

# sub region of the original image
x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)

axins1 = zoomed_inset_axes(ax, 8, loc=2) # zoom = 6
axins1.imshow(Z2, extent=extent, interpolation="nearest",
             origin="lower")

# sub region of the original image
x1, x2, y1, y2 = -1.2, -0.9, -2.2, -1.9
axins1.set_xlim(x1, x2)
axins1.set_ylim(y1, y2)

plt.xticks(visible=False)
plt.yticks(visible=False)

# draw a bbox of the region of the inset axes in the parent axes and
# connecting lines between the bbox and the inset axes area
mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5")
mark_inset(ax, axins1, loc1=2, loc2=4, fc="none", ec="0.5")

plt.draw()
plt.show()

rawDescription: matplotlib: inset axes for multiple boxplots

description: Matplotlib: inset axes for multiple boxplots


rawDescription: Regular Expression to Remove Rows

description: Regular Expression to Remove Rows


code:
html = '
TEST MESSAGE
'
snippet = BeautifulSoup(html).p.extract()
paragraph.insert_before(snippet)

rawDescription: Building paragraph tag in beautifulsoup

description: Building paragraph tag in beautifulsoup


code:
return render_to_response('results.html',
    {'data': sorted(results_dict.iteritems())})

rawDescription: How to render an ordered dictionary in django templates?

description: Render an ordered dictionary in django templates


code:
from itertools import izip
sentences_en = [[u'sid(s1).', u'sentence1', 'sentence1_info'], [u'sid(s2).', u'sentence2', 'sentence2_info']]
sentences_de = [['sid(s1).', 'Satz1', 'Staz1_info'], ['sid(s2).', 'Satz2', 'Staz2_info']]
mapping = {s_en[1]: s_de[1] for (s_en ,s_de) in izip(sentences_en, sentences_de)}

rawDescription: Combine two lists of lists into a dictionary python


code:
encode(a)
encode(b)

rawDescription: Why does a label permutation produce a different Huffman code?


rawDescription: find duplicates within list

description: Find duplicates within list


code:
import re
def dissect(text):
  return re.search(r'^(\D*)(.*)$', text).groups()

dissect('The entire apartment is 250m2')
dissect('three bedrooms (5m2, 12m2 and 15m2)')

rawDescription: Parsing text with regex in Python: determine match order and mapping value to object type?


code:
def myfunc(*args):
    keys = ', '.join(str(x) for x in list(args.keys()))
    values = ', '.join(str(val) for k, val in list(args.items()))
    statement = "INSERT INTO table (" + keys + ") VALUES(" + values + ");"
    db.execute(statement)

rawDescription: How to efficiently unravel arguments to a database in Python

description: Efficiently unravel arguments to a database in Python


code:
s = "Name: John, Name: Abby, Name: Kate"
[x[len('Name: '):] for x in s.split(', ')]

rawDescription: Regex extract element after string

description: Regex extract element after string


code: sorted(['apples', 'oranges', 'cherries', 'banana'])

rawDescription: Max() function does not return largest value in Python 3.4


code:
#! /usr/bin/python
import time
import sys
sys.stdout.write("in test1\n")
time.sleep(20)
sys.stdout.write("Done")

rawDescription: defining timeout on execution of shell/python script

description: Defining timeout on execution of shell/python script


code: dict( (name,eval(name)) for name in ['some','list','of','vars'] )

rawDescription: How to get a variable name as a string in Python?

description: Get a variable name as a string in Python


code:
gender_ambiguous_numbers_2014 = gender_ambiguous_data_2014.groupby('name').number.sum()
# get the max and find the list of names:
gender_ambiguous_max_2014 = gender_ambiguous_numbers_2014[gender_ambiguous_numbers_2014 == gender_ambiguous_numbers_2014.max()]

rawDescription: comparing column values based on other column values in pandas

description: Comparing column values based on other column values in pandas


code:
from itertools import chain

def iter_data(fileobj):
    for line in fileobj:
        yield from line.split()

def read_triangular_array(path):
    with open(path) as fileobj:
        first = fileobj.readline().split()
        n = len(first)
        count = int(n*(n+1)/2)
        data = chain(first, iter_data(fileobj))
        return np.fromiter(data, int, count=count)

rawDescription: Using numpy's genfromtxt to load a triangular matrix with python


code:
flat_sitemap = {
    'section_one': 0,
    'section_two': 1,
    'section_two/c_sect_2_1': 10,
       # ...
    'section_two/c_sect_2_2/c_sect_2_2_1': 110
       # ...
    }

rawDescription: In Python with a nested dictionary should I check the type? What other approach can I use?


code:
from itertools import product

lsts = [['A', 'G'], ['A', 'C', 'G'], 'T']
output = [''.join(combo) for combo in product(*lsts)]

rawDescription: Generate permutations of a list of lists with variable lengths


code:
valueLst = []
for i in f:
    valueLst.append(tuple(i.split('\t')))

rawDescription: Cumulative style calculations of entries in a data table using class initialisation in Python


rawDescription: How do I compare two arrays element-wise in Python using specific rules?

description: Compare two arrays element-wise in Python using specific rules


code:
FullArgSpec(args=['a', 'b', 'c', 'd', 'e', 'f'],
            varargs='g',
            varkw='h',
            defaults=(2,),
            kwonlyargs=[],
            kwonlydefaults=None,
            annotations={})

rawDescription: Is it possible to determine the minimum arity and the relevant parameter names of a Python function without calling it?


code:
def keyfun(p):
    return p.name.split()[-1]

persons = sorted(Person.objects.all(), key = keyfun)

rawDescription: Group related objects in Django

description: Group related objects in Django


rawDescription: Python storing Arabic in an Array?

description: Python storing Arabic in an Array


code:
import random
moves = [('r', "rock"), ('p', "paper"), ('s', "scissors")]
random.choice(moves)

rawDescription: Return random value from list tuple

description: Return random value from list tuple


code:
_pattern = r"""(?x)
    (?P<target1>
        [€$£]
        \d{1,3}
        [,.]?
        \d{0,3}
        (?:[,.]\d{3})*
        (?P<multiplyer1>[kKmM]?\s?[mM]?)
    )
    (?P<more>\s(?:\-|\band\b|\bto\b)\s)?
    """

match = re.search(_pattern, line)
target1, more = match.groups()
if more:
    target2 = re.search(_pattern, line, start=match.end())

rawDescription: regex - matching number with optional range

description: Regex - matching number with optional range


rawDescription: Powerball winnings using if else statements in python


code:
from itertools import chain, imap
np.fromiter(chain.from_iterable(imap(xrange, lengths)), dtype=int,
            count=np.sum(lengths))

rawDescription: repeat array in arbitary length

description: Repeat array in arbitary length


rawDescription: Python data manipulation for a particular data set


code:
g = df.groupby([1,2]).count()
g.loc[pd.MultiIndex.from_product(g.index.levels)]
g.loc[pd.MultiIndex.from_product(g.index.levels)].fillna(0)

rawDescription: when using groupby with multiple columns, how to NOT drop an unobserved combination of columns

description: When using groupby with multiple columns, how to NOT drop an unobserved combination of columns


code:
class XMLDataHelper:
    @staticmethod
    def import_something_from_xml(data):
        #logic
        return a, b, c

rawDescription: split up classmethods in python

description: Split up classmethods in python


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

npoints = 1000
x, y = np.random.normal(10, 2, (2, npoints))

fig, ax = plt.subplots()
artist = ax.hexbin(x, y, gridsize=20, cmap='gray_r', edgecolor='white')

cax = fig.add_axes([0.8, 0.15, 0.05, 0.3])
cbar = fig.colorbar(artist, cax=cax)

ax.spines['right'].set(visible=False)
ax.spines['top'].set(visible=False)
ax.tick_params(top=False, right=False)

cbar.set_ticks([5, 10, 15])
cbar.ax.set_title('Bin Counts', ha='left', x=0)
cbar.ax.tick_params(axis='y', color='white', left=True, right=True,
                    length=5, width=1.5)
cbar.outline.remove()

plt.show()

rawDescription: Add axis to colorbar in python matplotlib


code:
#!/usr/bin/env python2
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button

Builder.load_string('''
#:kivy 1.6
[SideBar@BoxLayout]:
    content: content
    orientation: 'vertical'
    size_hint: ctx.size_hint if hasattr(ctx, 'size_hint') else (1, 1)
    Image:
        source: ctx.image
        size_hint: (1, None)
        height: root.width
    GridLayout:
        cols: 2
        # just add a id that can be accessed later on
        id: content

<Root>:
    Button:
        center_x: root.center_x
        text: 'press to add_widgets'
        size_hint: .2, .2
        on_press:
            # what comes after `:` is basically normal python code
            sb.content.clear_widgets()
            # however using a callback that you can control in python
            # gives you more control
            root.load_content(sb.content)
    SideBar:
        id: sb
        size_hint: .2, 1
        image: 'data/images/image-loading.gif'
''')

class Root(FloatLayout):

    def load_content(self, content):
        for but in range(20):
            content.add_widget(Button(
                                text=str(but)))

class MyApp(App):
    def build(self):
        return Root()

if __name__ == '__main__':
    MyApp().run()

rawDescription: Kivy template with dynamic grid layout

description: Kivy template with dynamic grid layout


code: max_1 = max([i[1] for i in data])

rawDescription: Indexing Elements in a list of tuples

description: Indexing Elements in a list of tuples


code: callback = span_selected.bind(null, coordinate)

rawDescription: Python alternative to Javascript function.bind()?


code:
with open("test.txt") as f, open('test_output.txt',"w") as out:
    wr = csv.writer(out, delimiter=",")
    for line in f:
        wr.writerow(filter(None, line.rstrip().translate(None, "|").split(",")))

rawDescription: (Python) Breaking an output text file into tokens


code:
keys = ['c', 'l']
i1 = df1.set_index(keys).index
i2 = df2.set_index(keys).index
df1[~i1.isin(i2)]

rawDescription: pandas - filter dataframe by another dataframe by row elements

description: Pandas - filter dataframe by another dataframe by row elements


code:
import csv
import sys
csv_file = sys.stdout
writer = csv.writer(csv_file, delimiter="|")
soup = BeautifulSoup("
1 3",
                     convertEntities=BeautifulSoup.HTML_ENTITIES)
writer.writerows([''.join(t.encode('utf-8') for t in td(text=True))
                  for td in tr('td')] for tr in soup('tr'))

rawDescription: How to only print certain text using BeautifulSoup

description: Only print certain text using BeautifulSoup


code: np.min(list_a, axis=1)

rawDescription: Iteratively find minimum values in sub-lists


rawDescription: Choose Pandas dataframe index after which data in a column is all higher than a specific value


code: result = random.sample(deck, n)

rawDescription: List comprehension without using an iterable


rawDescription: sum for list of lists

description: Sum for list of lists


code:
def add_hidden_argument(*args, **kwargs):
    if not show_hidden_args:
        kwargs['help'] = argparse.SUPPRESS
    opt.add_argument(*args, **kwargs)

rawDescription: Show hidden option using argparse

description: Show hidden option using argparse


code:
import argparse
args = argparse.Namespace(key1=None,key2='value')
{k:v for k,v in args._get_kwargs() if v is not None}

rawDescription: Using argparse arguments as keyword arguments


code: MODULES = dict([(s.key, s) for s in ALL_MODULES if s.enabled])

rawDescription: Only include enabled objects in dict() - Python


code:
f = open("outputFile","wb")
subprocess.call(argsArray,stdout=f)

rawDescription: Python: How do I redirect this output?

description: Python: How do I redirect this output


code:
import cv2
import cPickle

im=cv2.imread("/home/bikz05/Desktop/dataset/checkered-3.jpg")

index = cPickle.loads(open("/home/bikz05/Desktop/dataset/keypoints.txt").read())

kp = []

for point in index:
    temp = cv2.KeyPoint(x=point[0][0],y=point[0][1],_size=point[1], _angle=point[2],
                            _response=point[3], _octave=point[4], _class_id=point[5])
    kp.append(temp)

# Draw the keypoints
imm=cv2.drawKeypoints(im, kp);
cv2.imshow("Image", imm);
cv2.waitKey(0)

rawDescription: OpenCV-Python : Find a code for writing keypoins to a file


code:
def instantiate(cls):
    return cls()

@instantiate
class ClassifierZ(object):
    def __call__(self, data):
        return some_classification

rawDescription: Fudging the line between classes and functions


rawDescription: add a number to all odd or even indexed elements in numpy array without loops

description: Add a number to all odd or even indexed elements in numpy array without loops


rawDescription: how to Merge two strings based on some conditions


code:
result = Element(element, None)
self.tail = result
self.tail.next = result

rawDescription: Issue with Python implementation of assignment chaining


rawDescription: A puzzle concerning Q objects and Foreign Keys


code:
import re

hyphensplit = re.compile('(-[a-z]+)').split
images = [part for img in images for part in hyphensplit(img) if part]

rawDescription: How to split list element into two?

description: Split list element into two


rawDescription: Creation and usage coordinates grid

description: Creation and usage coordinates grid


rawDescription: Python data structure for sorted key-value pairs


code:
guess = 'a'
guess.upper()

rawDescription: Python: hangman program

description: Python: hangman program


code:
from operator import itemgetter
list(map(itemgetter(0),lis))

rawDescription: Convert list of single element tuples to list of elements


rawDescription: Partial replacement with re.sub()

description: Partial replacement with re.sub()


code:
scores = {(True, True): 1, (True, False): 2,
          (False, True): 3, (False, False): 4}

rawDescription: Assign scores based on truth table without the use of if-else constructs


code:
foo.com
foobar.com
bar.com
foobar.com

rawDescription: Find http:// and or www. and strip from domain. leaving domain.com


code:
...
self.canvas.create_rectangle(..., tags=("obj1",))
self.canvas.create_rectangle(..., tags=("obj2",))
...

rawDescription: Tkinter Resizable Objects Python Canvas

description: Tkinter Resizable Objects Python Canvas


rawDescription: Generating a string with python using loops with logic conditions issues against join function alternative?


code: foo = Test(value)  # will None if value <= 1

rawDescription: return something other than the object on creation of object

description: Return something other than the object on creation of object


code:
lin = [map(int, i.strip().split(', ')) for i in open(sys.argv[1]).readlines()]
lin = sorted(lin)

rawDescription: Pythonic Way to Sort a List of Comma Separated Numbers


code:
@register.filter
def has_voted(obj, user):
    return self.has_voted(user)

rawDescription: Is it possible to perform model methods in a template?


code:
with open("2013indiv_unit_reported_data.txt") as fp:
    all_data = {}
    for line in fp:
        rowcol, data = line.split()
        row, col = rowcol[:14], rowcol[14:]
        all_data[row, col] = data

import csv
rows, cols = [sorted({key[i] for key in all_data}) for i in range(2)]
with open("table2.dat", "wb") as fp: # python 2
    writer = csv.writer(fp)
    writer.writerow(cols)
    for row in rows:
        line = [all_data.get((row, col), '') for col in cols]
        writer.writerow(line)

rawDescription: Transpose Census Flat Files in Python

description: Transpose Census Flat Files in Python


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

url = "http://www.afl.com.au/match-centre/2014/20/rich-v-esshttp://www.afl.com.au/match-centre/2014/19/fre-v-carl"
soup = BeautifulSoup(urlopen(url))

# get team names
home_team_name = soup.find('div', class_='home-team').p.a.text.strip()
away_team_name = soup.find('div', class_='away-team').p.a.text.strip()

# get stats
season_stats = soup.find('div', id='season-stats')
home_stats = [li.text for li in season_stats.select('ul#home-team-stats > li')]
away_stats = [li.text for li in season_stats.select('ul#away-team-stats > li')]
params = [li.text for li in season_stats.select('ul.headers > li')]

stats = {home_team_name: zip(params, home_stats),
         away_team_name: zip(params, away_stats)}

pprint(stats)

rawDescription: Fetch Stats using Beautiful Soup

description: Fetch Stats using Beautiful Soup


rawDescription: python pandas: computing argmax of column in matrix subset

description: Python pandas: computing argmax of column in matrix subset


code:
self                     # Get the value of self (typically the current object)
self._setup              # Get the attribute "_setup" of that value
self._setup['bar']       # Get the item "bar" of the attribute value
foo = self._setup['bar'] # Assign the result to the variable foo

rawDescription: python syntax - meaning of self._setup

description: Python syntax - meaning of self._setup


code:
@app.route('/api/search')
def search():
    res = querydb(request.args)
    return jsonify(res)

@app.route('/')
def index():
    return render_template('index.html')

rawDescription: Pass url params from flask to angular

description: Pass url params from flask to angular


code:
import datetime as DT
with open(file, 'rb') as csvfile:
    reader = csv.reader(csvfile, dialect='excel')
    for row in reader:
        try:
            date = DT.datetime.strptime(row[0], '%m/%d/%Y')
        except ValueError:
            continue
    args = [logID] + row
    sql = "INSERT INTO table VALUES ({})".format(', '.join(['?']*len(args)))
    cursor.execute(sql, args)

rawDescription: Only inserting specific rows from csv file into Sqlite3 database using python


code:
cherrypy.session.regenerate()
cherrypy.session['_cp_username'] = cherrypy.request.login

rawDescription: I am struggling to understand sessions in CherryPy


rawDescription: how to make subprocess called with call/Popen inherit environment variables

description: Make subprocess called with call/Popen inherit environment variables


code: input.lower() in map(lambda x: x.lower(), all_names['all'])

rawDescription: Python Search a Set using case-insensitive


code:
if cur_b in res:  # this asks if cur_b is in the set of keys of res
    res[cur_b] += cur_a
else:
    res[cur_b] = cur_a

rawDescription: How to sum elements of a list corresponding to elements of another list in python

description: Sum elements of a list corresponding to elements of another list in python


code:
x = np.arange(10)
xdset = file.create_dataset('x', data=x)
x1 = xdset[:]

rawDescription: How to share memory from an HDF5 dataset with a NumPy ndarray

description: Share memory from an HDF5 dataset with a NumPy ndarray


code: QTimer.singleShot(1000, f)

rawDescription: QLCDNumber updating with processEvents() - Python 3


code:
from __future__ import print_function
import turtle

LIMIT = 3
SCALAR = 0.5 ** 0.5
INDENT = ' ' * 4

def drawTree(size, depth, branch):
    print(INDENT * depth, branch, depth, 'start')

    drawSquare(size)

    if depth + 1 <= LIMIT:

        t.left(90)
        t.forward(size)
        t.right(45)
        drawTree(size * SCALAR, depth + 1, 'left ')

        t.forward(size * SCALAR)
        t.right(90)
        drawTree(size * SCALAR, depth + 1, 'right')

        t.left(90)
        t.backward(size * SCALAR)
        t.left(45)
        t.backward(size)
        t.right(90)

    print(INDENT * depth, branch, depth, 'stop')

def drawSquare(sideLength):
    t.down()
    for i in range(4):
        t.forward(sideLength)
        t.left(90)
    t.up()

t = turtle.Pen()
t.up()
t.goto(-100, -200)
drawTree(100.0, 0, 'root')

turtle.mainloop()

rawDescription: Unable to understand this recursive turtle python code


code: bar(x, y, width=[(x[j+1]-x[j]).days for j in range(len(x)-1)] + [30])

rawDescription: Controling bars width in matplotlib with per-month data


code:
#! /usr/bin/env python
import pprint

from_this = [
        ("global.module1.submodule1.function1", "some data"),
        ("global.module1.func1", "other data"),
        ("global.module1.submodule1.func2", "data again"),
        ("global.module1.submodule1.func3", "data"),
        ("global.module2.func3", "data"),
        ("global.module4.submodule1.func3", "data"),
        ("global.module4.submodule2.func4", "daata"),
        ("global.module4.submodule2", "da_ta")
]

def make_node():
    d = {
         "name": "",
         "data": "",
         "children": []
         }
    return d

path_sep = "."
tree = make_node()
tree["name"] = "root"
for path, data in from_this:
    current = tree
    path_list = path.split(path_sep)
    for name in path_list:
        next_node = None
        for child in current["children"]:
            if child["name"] == name:
                next_node = child
                break
        if next_node is None:
            n = make_node()
            n["name"] = name
            current["children"].append(n)
            current = n
        else:
            current = next_node
    current["data"] = data
pprint.pprint(tree, indent=1)

rawDescription: An idiomatic way to construct a tree in python from a list of locations / namespaces?


code:
values = ['Limpets', 'Mussels', 'Phytoplankton', 'Zooplankton', 'Prawn', 'Crab', 'Whelk', 'Seaweed']

keys = ['Whelk', 'Mussels', 'Bird', 'Prawn', 'Fish', 'Zooplankton', 'Crab', 'Lobster', 'Limpets']

for item in values:
   if item not in keys:
       print(item)

rawDescription: Checking if an item in a list is in another list


code:
answer = reportSuite.RP_UniqueUsers * 100
return render_to_response('template_link', {'reports':reportSuites, 'ans':answer})

rawDescription: Django development - Accessing results from a model


code:
from ast import literal_eval

def sort_key(line):
    # split "name: scores" into ["name", " scores"]
    name, score_str = line.split(":")

    # convert " [\"1.9\", \"3.8\"]" into ["1.9", "3.8"]
    scores = literal_eval(score_str.strip())

    # convert ["1.9", "3.8"] into [1.9, 3.8]
    scores = [float(f) for f in scores]

    # calculate average score
    avg = sum(scores) / len(scores)
    return avg

rawDescription: how to sort files by the value of a dictionary using python

description: Sort files by the value of a dictionary using python


code:
from itertools import combinations
terms = ['A', 'B', 'C', 'D']
list(combinations(terms, r=2))

rawDescription: Python create many-to-many relationships from a list


code:
for f in list_of_files:
    button = file_open_button(f)
    button.pack()

rawDescription: Create numerous unique events

description: Create numerous unique events


code:
import csv

FILE_NAME = "paintingJobs.txt"
COL_HEADERS = ['title 1', 'title 2', '3', '4', '5', '6']
NUM_COLS = len(COL_HEADERS)

# read file once to determine maximum width of data in columns
with open(FILE_NAME) as f:
    reader = csv.reader(f, delimiter=',')
    # determine the maximum width of the data in each column
    max_col_widths = [len(col_header) for col_header in COL_HEADERS]
    for columns in reader:
        if "A" in columns and int(columns[5]) < int(columns[3]):
            for i, col in enumerate(columns):
                    max_col_widths[i] = max(max_col_widths[i], len(repr(col)))
    # add 1 to each for commas
    max_col_widths = [col_width+1 for col_width in max_col_widths]

# read file second time to display its contents with the headers
with open(FILE_NAME) as f:
    reader = csv.reader(f, delimiter=',')
    # display justified column headers
    print(' ' + ' '.join(col_header.ljust(max_col_widths[i])
                            for i, col_header in enumerate(COL_HEADERS)))
    # display column data
    for columns in reader:
        if "A" in columns and int(columns[5]) < int(columns[3]):
            print(columns)

rawDescription: How do i add headers to my list (csv)

description: Add headers to my list (csv)


rawDescription: passing value to other module python

description: Passing value to other module python


code:
from geographiclib.geodesic import Geodesic
Geodesic.WGS84.Inverse(-41.32, 174.81, 40.96, -5.50)

rawDescription: Geopy: calculating GPS heading / bearing


code:
def save(self):
  instance = forms.ModelForm.save(self)
  instance.topping_set.clear()
  for topping in self.cleaned_data['toppings']:
    instance.topping_set.add(topping)

rawDescription: Django ModelForm for Many-to-Many fields


code:
import inflect
p = inflect.engine()

words = ["apples", "sheep", "oranges", "cats", "people", "dice", "pence"]

for word in words:
    print("The singular of ", word, " is ", p.singular_noun(word))

rawDescription: convert plural nouns to singular NLP

description: Convert plural nouns to singular NLP


code:
def get_top_sets(mylist):
    """ Returns a list of minimal subsets of the original"""
    m = [set(sublist) for sublist in mylist] # Convert into list of sets
    # If there is no element t that is a subset of s, add s to the new list
    return [list(s) for s in m if not any(not s == t and t.issubset(s) for t in m)]

rawDescription: python match lists

description: Python match lists


code:
from foo import ModClass as Foo
Foo.class_method()

rawDescription: In Python how do I use a class method without passing an instance to it?


code: matrix_result = matrix_a + matrix_b

rawDescription: How to efficiently add sparse matrices in Python

description: Efficiently add sparse matrices in Python


code:
import pygame, sys
from PIL import Image
pygame.init()

def displayImage(screen, px, topleft, prior):
    # ensure that the rect always has positive width, height
    x, y = topleft
    width =  pygame.mouse.get_pos()[0] - topleft[0]
    height = pygame.mouse.get_pos()[1] - topleft[1]
    if width < 0:
        x += width
        width = abs(width)
    if height < 0:
        y += height
        height = abs(height)

    # eliminate redundant drawing cycles (when mouse isn't moving)
    current = x, y, width, height
    if not (width and height):
        return current
    if current == prior:
        return current

    # draw transparent box and blit it onto canvas
    screen.blit(px, px.get_rect())
    im = pygame.Surface((width, height))
    im.fill((128, 128, 128))
    pygame.draw.rect(im, (32, 32, 32), im.get_rect(), 1)
    im.set_alpha(128)
    screen.blit(im, (x, y))
    pygame.display.flip()

    # return current box extents
    return (x, y, width, height)

rawDescription: Image Cropping using Python

description: Image Cropping using Python


code:
# we want just the rows where column 'b' is null:
data[data.b.isnull()]

# now construct a dataset of the length of this dataframe starting from 1:
range(1,len(data[data.b.isnull()]) + 1) # note we have to add a 1 at the end

# construct a new dataframe from this and crucially use the index of the null values:
pd.DataFrame({'c':range(1,len(data[data.b.isnull()]) + 1)}, index=data[data.b.isnull()].index)

# now perform a merge and tell it we want to perform a left merge and use both sides indices, I've removed the verbose dataframe construction and replaced with new_df here but you get the point
data.merge(new_df,how='left', left_index=True, right_index=True)

rawDescription: Fill non-consecutive missings with consecutive numbers


code:
str = "AIG $30 AIG is an international renowned insurance company listed on the NYSE. A period is required. Manual Auto Active 3 0.0510, 0.0500, 0.0300 [EXTRACT]"
list = str.split()
dict = { "Name": list[0], "CurrentPrice": list[1], "Status": list[19], "WorldRanking": list[20], "History": ' '.join((list[21], list[22], list[23])) }
dict

rawDescription: What is the most efficient method to parse this line of text?


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

fig, ax = plt.subplots()
im = ax.imshow(np.random.random((10, 10)), cmap='gist_earth')
cbar = fig.colorbar(im)
cbar.set_label('Test', y=0, ha='left')
plt.show()

rawDescription: How to move a colorbar label downward?

description: Move a colorbar label downward


code:
figure()
ax1 = plt.subplot(111)
ax2 = ax1.twinx()
ax2.plot([1, 2, 3], [0.3, 0.2, 0.1], 'r')
ax1.plot([1, 2, 3], [1, 2, 3], 'b', label='ax1')
ax1.legend(loc=2)

ax1.set_zorder(1) # make it on top
ax1.set_frame_on(False) # make it transparent
ax2.set_frame_on(True) # make sure there is any background

plt.show()

rawDescription: Legend transparency, when using secondary axis


code:
class OutpostBurrowNew(amp.AMP, Protocol):
    protocol = OutpostGopher
    #...
    def rfidTest(self):
        #print("Checking tag - Deferred called: %s" % str(self.defer.called))
        print('Tag check')
        (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
        if status == MIFAREReader.MI_OK:
            # print "Card detected"
            status,uid = self.verifyCard()
            cardid = '-'.join([str(x) for x in uid])
            print('Card detected: %s' % str(cardid))
            #self.defer.callback()
            self.connectEndpoint()

def main3():
    ''' main3() is for testing reactor usage of RFID-card reading '''
    burrow = OutpostBurrowNew('client')
    burrow.protocol = OutpostGopher
    #burrow.connectEndpoint()  # A deferred is created, set on burrow.defer
    looper = LoopingCall(burrow.rfidTest)
    loopdef = looper.start(1, now=False)
    reactor.run()

rawDescription: What is causing my Deferred to fire, having done nothing but add a callback, start the reactor, and connected an endpoint?


code:
data = ['C01234' , 'pass' , 'pass' , 'C2456' , 'fail' , 'pass' , 'C53675' , 'pass' , 'pass']
od = {} # Output dictionary.
key = None
for x in data:
  if x.startswith("C"):
    key = x
    od[key] = []
  elif key is not None:
    od[key].append(x)

rawDescription: Convert a list to dictionary in Python based on first index of list value


code:
class WrappedObject(object):

    def __init__(self, cls):
        dct = cls.__dict__.copy()
        for attr, item in dct.items():
            if attr != '__init__' and callable(item):
                dct[attr] =  my_decorator(item)
            elif  isinstance(item, property):
                new_property = property(my_decorator(item.__get__), item.__set__, item.__delattr__)
                dct[attr] = new_property
        self._cls = type("wrapped_" + cls.__name__, (cls,), dct)

    def __call__(self, *args, **kwargs):
        return self._cls(*args, **kwargs)

rawDescription: Decorating a class method after @property


code:
df1 = sqlContext.createDataFrame(rdd1, ('k', 'v1'))
df2 = sqlContext.createDataFrame(rdd2, ('k', 'v2'))

# Register temporary tables to be able to use sqlContext.sql
df1.registerTempTable('df1')
df2.registerTempTable('df2')

rawDescription: How do you perform basic joins of two RDD tables in Spark using Python?

description: Perform basic joins of two RDD tables in Spark using Python


code:
unique_x, unique_inverse = np.unique(x, return_inverse=True)
unique_inverse

rawDescription: Numpy: fast/easy way to get indices of array whose value is equal to another array?


code:
class Namespace(object):
    pass

namespaceA = Namespace()
namespaceA.x = 1

rawDescription: How can I create a separate namespace within a Python script?

description: Create a separate namespace within a Python script


code: df[grouped[0].transform(lambda x: x.name != group_name).astype('bool')]

rawDescription: Delete a group after pandas groupby

description: Delete a group after pandas groupby


code:
class Qux(object):
    pass
q = Qux()
q.foobar = 'hello'
q.foobar

rawDescription: Python class members with dynamic names

description: Python class members with dynamic names


code: from __future__ import print_function

rawDescription: Print without line feed

description: Print without line feed


code:
def get_frequencies(lemma):
    counter = Counter()
    related_lemmas = set()
    for index, entry in enumerate(corpus):
        counter[entry.lemma] += 1
        if entry.lemma == lemma:
            if index > 0:
                related_lemmas.add(corpus[index-1].lemma)
            if index < len(corpus)-1:
                related_lemmas.add(corpus[index+1].lemma)
    return {lemma: frequency for lemma, frequency in counter.iteritems()
            if lemma in related_lemmas}

rawDescription: How to count word frequency from a list in the whole file?

description: Count word frequency from a list in the whole file


code:
import zlib

decompressed = zlib.decompress(data)

rawDescription: decoding, little endian, uncompressed and float array

description: Decoding, little endian, uncompressed and float array


code:
if n not in l:
    print("New item.")
else:
    index = max(i for i, v in enumerate(l) if v == n)
    print("Item found at index {0}.".format(index))
l.append(n)

rawDescription: Randint number into a Dict

description: Randint number into a Dict


rawDescription: Isolating coastal grids using convolving window (python)


code:
b'\x03~'.decode('utf-16be')
import unicodedata as UDAT
UDAT.name(u'\u037e')
u'\N{GREEK QUESTION MARK}' == u';'
u'\N{GREEK QUESTION MARK}'.encode('utf-16be')

rawDescription: Produce unicode obj from string in python?


rawDescription: How do I find an xml node that does not have an attribute

description: Find an xml node that does not have an attribute


code: [np.bincount(x)[2] for x in a]

rawDescription: How to count occurrences of specific element for arrays in a list?

description: Count occurrences of specific element for arrays in a list


code:
import Tkinter as tk

class GUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        bF = tk.Frame(self, bd=8, relief='sunken')
        bF.pack(expand='true', fill='x')

        var = tk.StringVar()
        var.set('Hello')
        entryLabel = tk.Label(self, textvariable=var)
        entryLabel.pack()

        mEntry = tk.Entry(self, bd=4, relief='sunken', textvariable=var)
        mEntry.pack()

gui = GUI()
gui.mainloop()

rawDescription: How to call an action when a button is clicked in Tkinter

description: Call an action when a button is clicked in Tkinter


code: repeat(lambda: bar(42))

rawDescription: Python, how to pass an argument to a function pointer parameter?


code:
class Monster(object):
    pass

class Lochness(Monster):
    pass

class Yeti(Monster):
    pass

Monster.__subclasses__()

rawDescription: Executing code after construction of class object


rawDescription: General techniques to work with huge amounts of data on a non-super computer


rawDescription: Python: Remove numbers at the beginning of a string


code:
nextmatch = next(((t,p) for t,p in product(targets,prefixes) if t.startswith(p)), None)
print(nextmatch)

rawDescription: checking if any element in a list starts with any of a number of prefixes in Python?

description: Checking if any element in a list starts with any of a number of prefixes in Python


code:
data = pd.DataFrame({'A':range(3), 'B':range(3,0,-1), 'C':list('abc')})
data
data.columns = map(str.lower, data.columns)
data

rawDescription: python: make pandas dataframe column headers all lowercase

description: Python: make pandas dataframe column headers all lowercase


rawDescription: convert list of tuples to multiple lists in Python

description: Convert list of tuples to multiple lists in Python


rawDescription: To stop finding running average once the condition fails?


rawDescription: MongoDB, what does bulk find return

description: MongoDB, what does bulk find return


code:
mywords = ['red', 'blue', 'red', 'green', 'blue', 'blue']
cnt = Counter(mywords)
cnt

rawDescription: Sorting a list by frequency of letter in python (decreasing order)


code:
class MyAdmin(...):
    list_display = ('_my_field',)
    readonly_fields = ('_my_field', )

    def _my_field(self, obj):
        return obj.get_full_name()
    _my_field.short_description = 'my custom label'

rawDescription: How can I rename a column label in Django Admin for a field that is a method//property?

description: Rename a column label in Django Admin for a field that is a method//property


code:
from blessings import Terminal
term = Terminal()

raw_input("Question: ")
print(term.move_up() + "Correct!" + term.clear_eol())

rawDescription: How to print over raw_input's line in Python?

description: Print over raw_input's line in Python


code:
def checkmessage(msg):
    banned_words = "badword1 badword2 badword3"
    banned_list= banned_words.split()

    for word in banned_list:
         if word in msg:
             print("banned for saying: " + word)
             return
    print("not banned")

msg1 = "Nothing special here"
msg2 = "I say the badword2."

checkmessage(msg1)
checkmessage(msg2)

rawDescription: IRC bot, making a list of banned words?

description: IRC bot, making a list of banned words


code:
dt64 = numpy.datetime64('2002-06-28T01:00:00.000000000+0100', 's')
dt64.dtype
datetime.utcfromtimestamp(dt64.astype(int))

rawDescription: Converting between datetime, Timestamp and datetime64


code:
#!/usr/bin/env python
import time
from flask import Flask, Response

app = Flask(__name__)

@app.route('/')
def index():
    def g():
        yield """<!doctype html>
<title>Send javascript snippets demo</title>

nothing received yet

"""

        for i, c in enumerate("hello"):
            yield """

""".format(i=i, c=c)
            time.sleep(1)  # an artificial delay
    return Response(g())

if __name__ == "__main__":
    app.run(host='localhost', port=23423)

rawDescription: Streaming data with Python and Flask

description: Streaming data with Python and Flask


rawDescription: Add vertex attributes to a weighted igraph Graph in python


code: sum(1 if len(i) > 20 else 0 for i in s)

rawDescription: Python 2.7 counting number of strings

description: Python 2.7 counting number of strings


rawDescription: relation between two columns Python

description: Relation between two columns Python


code:
import requests
import shutil

r = requests.get(settings.STATICMAP_URL.format(**data), stream=True)
if r.status_code == 200:
    with open(path, 'wb') as f:
        r.raw.decode_content = True
        shutil.copyfileobj(r.raw, f)

rawDescription: How to download image using requests

description: Download image using requests


code:
from datetime import datetime
import pandas as pd

start = datetime(2014, 9, 1)
end = datetime(2014, 10, 30)
d = pd.date_range(start, end) # use bdate_range for business days

rawDescription: Resample a pandas timeseries by "1st Monday of month" etc


rawDescription: Django ORM Query to limit for the specific key instance


code: t.mark_set('insert', '2.3')

rawDescription: Setting the position of the insert character in the tkinter text widget


rawDescription: Parsing text within block "|-" and "|- or }"


code:
mask_fill = pd.isnull(df['B']) & pd.isnull(df['C'])
mask_fill

rawDescription: Fill NaN in candlestick OHLCV data

description: Fill NaN in candlestick OHLCV data


rawDescription: Accessing function arguments from decorator


rawDescription: XGBoost XGBClassifier Defaults in Python


code:
def filter_down(phrase, filters):
    new = []
    for word in phrase.split():
        if word.lower() in filters:
                new.append(word)
        else:
                new.extend(list(word)) # list(word) is ['w', 'a', 'l', 'k', 'i', 'n', 'g']
        new.append(' ')
    return new

rawDescription: Filtering through a list of Words (Python)


code:
N = B.shape[0]
pcorr # Pearson Correlation Coefficient array
out # elements corresponding to absolute argmax along columns

rawDescription: Efficient pairwise correlation for two matrices of features


code:
tag = (x,y)
canvas.create_rectangle(..., tags=(tag,))

rawDescription: Python tkinter delete tuple tag

description: Python tkinter delete tuple tag


code: addrs = (net + str(x) for x in range(1, 255))

rawDescription: Create list with for loop for incrementing IP address


rawDescription: Is it possible to explicitly to refer to indexes by their name in pandas data frame?


code: return ast.copy_location(node, none)

rawDescription: How can I abort an AST visitor and leave the original node unchanged?

description: Abort an AST visitor and leave the original node unchanged


code:
htmlparser = etree.HTMLParser(encoding=enc)
root = etree.HTML(content, parser=htmlparser)

rawDescription: Problems with encoding while parsing html document with lxml


code:
class Main(QTreeView):
    def __init__(self):
        # ...
        self.setModel(model)
        self.doubleClicked.connect(self.test)  # Note that the the signal is now a attribute of the widget.

rawDescription: Python: PyQt QTreeview example - selection


rawDescription: What is a maximum number of arguments in a Python function?


rawDescription: Fastest way to sort each row in a pandas dataframe


rawDescription: Dynamically get class name at class level variable in python


code:
a = 2
type(a) is int
type(a) is str
a = '2'
type(a) is str
type(a) is int

rawDescription: How to get python to not print something

description: Get python to not print something


code:
from django.db.models import Count
...
last_names = Person.objects.values('last_name').annotate(Count('last_name')) # This will return all the unique last_names
values = dict( ((last_name['last_name'], Person.objects.all().filter(last_name = last_name['last_name'])) for last_name in last_names if last_name['last_name__count']) )
# This will create a dictionary where the keys are all the unique names and the values are querysect of all the values that have that lastname

rawDescription: Split queryset or get multiple querysets by field instead of just ordering by field


code:
@app.route('/<lang_code>/about')
@app.route('/<lang_code>/sobre')
def about():
    pass

rawDescription: Format canonical URL structure correctly with URL Processors


code:
with open(fname) as f:
    for line in f:
        line_count += 1
    f.seek(0)
    for line in f:
        line_processed += 1

rawDescription: python with statement and 2 for loops

description: Python with statement and 2 for loops


code:
from tkinter import *
import random
from tkinter import messagebox

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

    def drawBox(self):
        color = hex(random.randrange(4095))[2:6]
        color = '#' + color.zfill(3)
        self.canvas.itemconfig(self.rect, fill=color)
        self.after_id = self.after(100, self.drawBox)

    def initUI(self):
        self.parent.title('after_cancel test')
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self)
        self.rect = self.canvas.create_rectangle(100,100,200,200,fill='red')
        self.canvas.pack()
        self.drawBox()
        if messagebox.askokcancel('Turn that thing off','Click OK to stop'):
            print('OK clicked')
            self.after_cancel(self.after_id)

def main():
    root = Tk()
    root.geometry("300x250+300+300")
    app = Example(root)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Break out of a Python after loop using a messagebox


rawDescription: Python Eval executing enviroment

description: Python Eval executing enviroment


rawDescription: How can I write this query in Django? (datetime)

description: Write this query in Django? (datetime)


code:
df = DataFrame(randn(100000,3),columns=list('ABC'))
df['one'] = 'foo'
df['two'] = 'bar'
df.ix[50000:,'two'] = 'bah'
mi = df.set_index(['one','two'])
mi

rawDescription: Pandas HDFStore of MultiIndex DataFrames: how to efficiently get all indexes


code:
import os

def splitext(path):
    for ext in ['.tar.gz', '.tar.bz2']:
        if path.endswith(ext):
            path, ext = path[:-len(ext)], path[-len(ext):]
            break
    else:
        path, ext = os.path.splitext(path)
    return path, ext[1:]

assert splitext('20090209.02s1.1_sequence.txt')[1] == 'txt'
assert splitext('SRR002321.fastq.bz2')[1] == 'bz2'
assert splitext('hello.tar.gz')[1] == 'tar.gz'
assert splitext('ok.txt')[1] == 'txt'

rawDescription: What's the way to extract file extension from file name in Python?


rawDescription: Casting a string containing comma separated values into an integer


code:
from functools import partial
median = partial(quantile, p=0.5)

rawDescription: How to find median using Spark

description: Find median using Spark


code:
results = s.findAll('td', {'class': None})
results

rawDescription: How to select specific content from table type structure in html

description: Select specific content from table type structure in html


rawDescription: Pandas Time Grouper: Custom Ranges

description: Pandas Time Grouper: Custom Ranges


code:
for i, elem in enumerate(some_list):
    some_list[i] == elem #True, unless you've mutated the list (don't!)
    ...

rawDescription: How does this for loop know which list to sort through?


code: "//*[contains(text(), 'some_value')]"

rawDescription: XPath for sub-element's text value in lxml


code:
def myexec(ssh, cmd, timeout, want_exitcode=False):
  # one channel per command
  stdin, stdout, stderr = ssh.exec_command(cmd)
  # get the shared channel for stdout/stderr/stdin
  channel = stdout.channel

  # we do not need stdin.
  stdin.close()
  # indicate that we're not going to write to that channel anymore
  channel.shutdown_write()

  # read stdout/stderr in order to prevent read block hangs
  stdout_chunks = []
  stdout_chunks.append(stdout.channel.recv(len(stdout.channel.in_buffer)))
  # chunked read to prevent stalls
  while not channel.closed or channel.recv_ready() or channel.recv_stderr_ready():
      # stop if channel was closed prematurely, and there is no data in the buffers.
      got_chunk = False
      readq, _, _ = select.select([stdout.channel], [], [], timeout)
      for c in readq:
          if c.recv_ready():
              stdout_chunks.append(stdout.channel.recv(len(c.in_buffer)))
              got_chunk = True
          if c.recv_stderr_ready():
              # make sure to read stderr to prevent stall
              stderr.channel.recv_stderr(len(c.in_stderr_buffer))
              got_chunk = True
      '''
      1) make sure that there are at least 2 cycles with no data in the input buffers in order to not exit too early (i.e. cat on a >200k file).
      2) if no data arrived in the last loop, check if we already received the exit code
      3) check if input buffers are empty
      4) exit the loop
      '''
      if not got_chunk \
          and stdout.channel.exit_status_ready() \
          and not stderr.channel.recv_stderr_ready() \
          and not stdout.channel.recv_ready():
          # indicate that we're not going to read from this channel anymore
          stdout.channel.shutdown_read()
          # close the channel
          stdout.channel.close()
          break    # exit as remote side is finished and our bufferes are empty

  # close all the pseudofiles
  stdout.close()
  stderr.close()

  if want_exitcode:
      # exit code is always ready at this point
      return (''.join(stdout_chunks), stdout.channel.recv_exit_status())
  return ''.join(stdout_chunks)

rawDescription: Do you have to check exit_status_ready if you are going to check recv_ready()?


rawDescription: python: How to get column names from pandas dataframe - but only for continuous data type?

description: Python: How to get column names from pandas dataframe - but only for continuous data type


code:
import xml.dom.minidom as MD
root = MD.parseString(raw)
node = root.childNodes[0].getElementsByTagName("hudson.model.StringParameterDefinition")[0]
defaultValue = node.getElementsByTagName("defaultValue")[0]
defaultValue.childNodes[0].replaceWholeText(node.getElementsByTagName("name")[0].childNodes[0].nodeValue)

rawDescription: How to modify a tag text value based on its sibling tag text value in xml with python?

description: Modify a tag text value based on its sibling tag text value in xml with python


code:
for key, value in sub.BACKENDS.items():
    if value.enabled():
        backends[key] = value

rawDescription: Python dictionary commands with dynamic functions?


code:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.2') # Change to a different version as you like

rawDescription: how to render django template from code instead of file

description: Render django template from code instead of file


code:
lis = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
se = set(range(0, len(lis),9))   #use a list if the lis is not huge.
[x for i,x in enumerate(lis) if i not in se]
[x for i,x in enumerate(lis) if i%9 != 0]

rawDescription: Selecting List Elements Periodically in Python 3


code:
directors = [director.strip() for director in directors.split(',')] if directors else []
# etc.

rawDescription: DRY version of similar string processing


code:
import copy
l = []
d = {}
d['key'] = 4
l.append(copy.deepcopy(d))
d['key'] = 5
l.append(copy.deepcopy(d))

rawDescription: Making a list of a "master" dictionary

description: Making a list of a "master" dictionary


code:
import operator
list(scanl(operator.add, 0, range(1,11)))

rawDescription: Equivalent of Haskell scanl in python

description: Equivalent of Haskell scanl in python


code: join = lambda list_of_lists: (val for sublist in list_of_lists for val in sublist if isinstance(sublist, list))

rawDescription: Flattening shallow list with pandas

description: Flattening shallow list with pandas


code:
value = [val[5] for col,val in dictionary.iteritems()]
25.5416321754
value = df.loc[5]
5.68071913719
value = df.iloc[5]
4.56006002426

rawDescription: Pandas DataFrame performance

description: Pandas DataFrame performance


code:
stmt = select([addresses.c.email_address]).\
            where(addresses.c.user_id == users.c.id).\
            limit(1)
conn.execute(users.update().values(fullname=stmt))

rawDescription: Sqlalchemy: bulk correlated update to link tables


code:
import numpy as np
import datetime as dt
def mkdate(text):
    return dt.datetime.strptime(text, '%Y-%m-%dT%H:%M:%S:%f')
data = np.genfromtxt(
    'example.txt',
    names=('data','num','date')+tuple('col{i}'.format(i=i) for i in range(19)),
    converters={'date':mkdate},
    dtype=None)

rawDescription: Python array of datetime objects from numpy ndarray


code:
class EnumerationType(type(c_uint)):
    def __new__(metacls, name, bases, dict):
        if not "_members_" in dict:
            _members_ = {}
            for key, value in dict.items():
                if not key.startswith("_"):
                    _members_[key] = value

            dict["_members_"] = _members_
        else:
            _members_ = dict["_members_"]

        dict["_reverse_map_"] = { v: k for k, v in _members_.items() }
        cls = type(c_uint).__new__(metacls, name, bases, dict)
        for key,value in cls._members_.items():
            globals()[key] = value
        return cls

    def __repr__(self):
        return "<Enumeration %s>" % self.__name__

class CEnumeration(c_uint):
    __metaclass__ = EnumerationType
    _members_     = {}

    def __repr__(self):
        value = self.value
        return "<%s.%s: %d>" % (
            self.__class__.__name__,
            self._reverse_map_.get(value, '(unknown)'),
            value
        )

    def __eq__(self, other):
        if isinstance(other, (int, long)):
            return self.value == other

        return type(self) == type(other) and self.value == other.value

rawDescription: How to define C-Enumeration types in python

description: Define C-Enumeration types in python


code:
def append():
  l = []
  for i in range(3):
    l.append(str(i))
  return l
l = append()
l

rawDescription: Python: issue in adding elements to a list


rawDescription: How can you store user input within a loop without overwriting?

description: Store user input within a loop without overwriting


code:
import argparse

def foo(path):
    print('Running foo(%r)' % (path, ))

def bar(path):
    print('Running bar(%r)' % (path, ))

dispatch = {
    'foo': foo,
    'bar': bar,
}

def parse_args(cmd):
    parser = argparse.ArgumentParser()
    parser.add_argument('function')
    parser.add_argument('arguments', nargs='*')
    args = parser.parse_args(cmd.split())
    return args

rawDescription: Python - passing parameters in a command line app


code:
for i in xrange (Ix_Ix_blur.shape[1]):
    for j in xrange(Ix_Ix_blur.shape[0]):
        a, b, c = Ix_Ix_blur.item(j, i), Ix_Iy_blur.item(j, i), Iy_Iy_blur.item(j, i)
        detA = a*c - b*b
        traceA = a + c
        harmonic_mean = detA/traceA
        if harmonic_mean > thresh:
            cv2.circle(img, (i,j), 1, (0, 0, 255), -1, 8)

rawDescription: Speed up iteration over Numpy arrays / OpenCV cv2 image


code: DATA_ROOT = pathlib.Path(__file__).resolve().parents[3] / 'Data' / 'MyAppData'

rawDescription: Referencing relative directories outside of project


code:
class Media:
    js = ('/static/js/jquery.min.js',
          '/static/js/slug.js')

rawDescription: How to use prepopulated_fields in Django w/o transliteration?

description: Use prepopulated_fields in Django w/o transliteration


code:
dataDefault2 = []
for i in dataDefault:
    if ": " in i:
        dataDefault2.append(i.split(": ")[1])
    else:
        dataDefault2.append(i)

for elem in setData:  # We iterate over each element of the list
    for val in elem.values() :  # We iterate over each value of the element dictionary
    # If there is any other value which is not a dictionary it will complain with an error
        if val in dataDefault2:
            print("If this prints then something Matches")

rawDescription: Compare Entries in a dictionary with a list and print the results


code:
from ctypes import c_uint32
l = c_uint32(0x12345678)
bytes(l)

rawDescription: Convert n-byte int to bytes in python3

description: Convert n-byte int to bytes in python3


code: fh1, fh2, fh3 = [open("somefile.txt") for i in range(3)]

rawDescription: Is there a way to shallow copy an existing file-object?


rawDescription: How to remove : after a + or - in python

description: Remove : after a + or - in python


code: {'Paper': 3, 'cars': 1, 'Pens': 1, 'stores': 4, 'Pencils': 2, 'schools': 3, 'houses': 2}

rawDescription: combine two json dictionary python

description: Combine two json dictionary python


code:
def key(item):
    return something_hashable
for index, item in enumerate(somelist):
    dups[key(item)].append(index)

rawDescription: Find index of item with duplicates

description: Find index of item with duplicates


code:
"""gunicorn WSGI server configuration."""
from multiprocessing import cpu_count
from os import environ

def max_workers():
    return cpu_count()

bind = '0.0.0.0:' + environ.get('PORT', '8000')
max_requests = 1000
worker_class = 'gevent'
workers = max_workers()

rawDescription: Where is the Gunicorn config file?

description: Where is the Gunicorn config file


code:
from sqlalchemy import sessionmaker

# There should already be some initialization similar to this
Session = sessionmaker(bind=db_engine)
session = Session()

session.query = query_wrapper(session.query)

rawDescription: SQLAlchemy: Is there a way to track the line number and calling class of a query done through SQLAlchemy?


rawDescription: How to get a string to relate to a specific value in an array in Python3

description: Get a string to relate to a specific value in an array in Python3


code:
import re

temperature_row = soup.find(text=re.compile('Temperature')).find_parent('tr')
temperature = temperature_row.find_all('td')[-1].get_text()

rawDescription: Trying to get data with BeautifulSoup

description: Trying to get data with BeautifulSoup


rawDescription: re module in Python

description: Re module in Python


code:
l.append(MagicList([0, (0,)]))
l
bool(l)

rawDescription: Python, how to implement a list subclass that evaluates as False if its items evaluate False?


code:
import matplotlib.pyplot as plt
import numpy

# Simple example
numpy.random.seed(4)
x = range(10)
y = numpy.random.rand(10)

# Create three 'lines' (here, as x-y arrays) with different lenghts
a = numpy.array((x, y*10)).T
b = numpy.array((x[:5]*y[:5], y[:5]**2)).T
c = numpy.array((x[3:7], x[3:7])).T

# Use this to break up the original objects.
# plt.plot does not like NaN's, so will break the line there.
linebreak=[[numpy.NaN,numpy.NaN]]

# Combine a, b, and c in one object to be called many times later
abc = numpy.concatenate((a, linebreak, b, linebreak, c))

# Plot
fig = plt.figure(figsize=(9,3))

ax0 = fig.add_subplot(131)
ax0.plot(a[:,0], a[:,1], color='b')
ax0.plot(b[:,0], b[:,1], color='r')
ax0.plot(c[:,0], c[:,1], color='g')
ax0.set_title("3 lines to be combined")

ax1 = fig.add_subplot(132)
ax1.plot(a[:,0], a[:,1], color='b')
ax1.plot(b[:,0], b[:,1], color='b')
ax1.plot(c[:,0], c[:,1], color='b')
ax1.set_title("Desired output")

ax2 = fig.add_subplot(133)
ax2.plot(abc[:,0], abc[:,1], color='b') # 1-line command
ax2.set_title("Single object with breaks")

rawDescription: Matplotlib: combine different lines into a single object to be plotted many times


code: target.write("%s %s %s %s %s %s" % (line1, linebreak, line2, linebreak, line3, linebreak))

rawDescription: Total Python Noob: why doesn't this work?


code:
ax.tripcolor(triang, z2**2, shading='gouraud', cmap='Greens', alpha=0.5)
ax.tripcolor(triang, z1**2, shading='gouraud', cmap='Reds', alpha=0.5)

rawDescription: Plot multiple sets of data with tripcolor - transparency in colormaps


code:
import email

infolder = "C:\\emlfiles\\"
for infile in os.listdir(infolder):
    fp = open(os.path.join(infolder, infile))
    msg = email.message_from_file(fp)
    # etc

rawDescription: Python code applying to multiple files or folder


code:
with open("myFile.bed")as f:
    for line in f:
        L = line.strip().split()
        # ... do something with L

rawDescription: Working with "bed" files in python

description: Working with "bed" files in python


code: import sys

rawDescription: How can I change the prompt displayed by Sphinx when documenting interactive sessions?

description: Change the prompt displayed by Sphinx when documenting interactive sessions


code:
subjects = ["Accounts", "History", "Geography", "Chemistry", "Computer Science", "Maths", "Add maths", "English"]

def get_marks(i):
    name = input("Enter the name of student %d: " % i)  # (the name is only used for the subject prompts below)
    if not name:  # If the user doesn't enter a name, don't query for subjects either.
        return  # (implicitly returns None)
    marks = {}
    for subject in subjects:  # Loop over the subjects -- this is OP's code :)
        marks[subject] = float(input("Enter " + name + "'s " + subject + " marks: "))
    return marks

def get_student_marks():
    student_marks = []  # Gather the students' marks (as dicts) into this list.
    for i in range(10):  # Query for 10 students at most.
        marks = get_marks(i + 1)  # Get an individual student's marks as a dict.
        if not marks:  # If no name was entered (and None was thus returned)...
            break  # ... assume the user won't want to enter any more students and break out of the loop.
        student_marks.append(marks)  # Otherwise, save the marks...
    return student_marks  # and when the loop finishes, one way or another, return the list of dicts.

def print_total_marks(student_marks):
    total_marks = dict.fromkeys(subjects, 0)
    for marks in student_marks:  # Loop over each student...
        for subject, mark in marks.items():  # And then each pair of subject/mark...
            # (dict.fromkeys assures us that there's a key for every subject; no need to check at this point.)
            total_marks[subject] += mark  # ... and add that to the total.
    print ("Total marks for whole class are", total_marks)

student_marks = get_student_marks()
print_total_marks(student_marks)

rawDescription: How to add more than 2 dictionaries together in python

description: Add more than 2 dictionaries together in python


code:
weights = np.array([1,2,3,4,5])
(df * weights).sum(axis=1)

rawDescription: Creating a weighted score column from Pandas pivot table


code:
INTs = data[data[1]=='INT']
EXTs = data[data[1]=='EXT']

int_dist = INTs[3]  # x-axis data for INT
ext_dist = EXTs[3]

# plotting time as minutes in range [0 720]
int_time = INTs[5]  # y-axis data for INT
ext_time = EXTs[5]

time = ['0:00', '1:00', '2:00', '3:00', '4:00', '5:00',
        '6:00', '7:00', '8:00', '9:00', '10:00', '11:00', '12:00']
# this will place the strings above at every 60 min
tick_location = [t*60 for t in range(13)]

rawDescription: Fixed y axis in Python plotting times in 12 hr format


code:
(ctypes.c_int * len(x))(*x)
#                      ^^^^

rawDescription: What does (ctypes.c_int * len(x))(*x) do?


code:
a = [1, 2, 3, 4, 5]
def sanitize(lst):
    # predefined list
    b = {1, 2}
    return sorted(lst, key=lambda v: v in b)

sanitize(a)

rawDescription: Python list popping and appending

description: Python list popping and appending


code: pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")

rawDescription: Python replace multiple strings

description: Python replace multiple strings


code:
# File /home/myhome/test.wsgi
import logging

from rpclib.application import Application
from rpclib.decorator import srpc
from rpclib.interface.wsdl import Wsdl11
from rpclib.protocol.soap import Soap11
from rpclib.service import ServiceBase
from rpclib.model.complex import Iterable
from rpclib.model.primitive import Integer
from rpclib.model.primitive import String
from rpclib.server.wsgi import WsgiApplication

class HelloWorldService(ServiceBase):
    @srpc(String, Integer, _returns=Iterable(String))
    def say_hello(name, times):
        '''
        Docstrings for service methods appear as documentation in the wsdl
        <b>what fun</b>
        @param name the name to say hello to
        @param the number of times to say hello
        @return the completed array
        '''

        for i in xrange(times):
            yield 'Hello, %s' % name

application = WsgiApplication(Application([HelloWorldService], 'rpclib.examples.hello.soap',
                interface=Wsdl11(), in_protocol=Soap11(), out_protocol=Soap11()))

rawDescription: Python library for a SOAP server that handles multiple requests simultaneously?


rawDescription: Django turn list of objects into a table


code:
data = json.loads(POST['data'])
data['login_user']

rawDescription: jquery: post with json will actually post array

description: Jquery: post with json will actually post array


code:
from itertools import groupby
import re

with open("test.txt") as f:
    data = []
    # find NO_USERS= 1+ digits or id_info= 1_ digits
    r = re.compile("NO_USERS=\d+|id_info=\d+")
    grps = groupby(f,key=lambda x:x.strip().startswith("BLOCK"))
    for k,v in grps:
        # if k is True we have a block line
        if k:
            # get name after BLOCK
            name = next(v).split(None,2)[1]
            # get lines after BLOCK and get the second of those
            t = next(grps)[1]
            # we want two lines after BLOCK
            _, l = next(t), next(t)
            d = dict(s.split("=") for s in r.findall(l))
            # add name to dict
            d["Name"] = name
            # add sict to data list
            data.append(d)

print(data)

rawDescription: How to read a file block-wise in python

description: Read a file block-wise in python


code: df = df.join(df.col2.apply(lambda x: pd.Series(x)))

rawDescription: Pandas Groupby : group **by** a column containing tuples


rawDescription: Python web scrape failing

description: Python web scrape failing


code:
my_dict = {
    "Apple": ["Green", "Healthy", "Sweet"],
    "Banana": ["Yellow", "Squishy", "Bland"],
    "Steak": ["Red", "Protein", "Savory"]
}
import random
food=[random.choice(i) for i in my_dict.values()]
food

rawDescription: Python: How do I randomly select a value from a dictionary key?


code:
  # in class Worm...
def __init__(self, surface, x, y, length):
    self.surface = surface
    self.x = x
    self.y = y
    self.length = length
    self.dir_x = 0
    self.dir_y = -1
    self.body = []
    self.crashed = False

    self.rect = pygame.Rect(x,y,1,1)  # the 1,1 in there is the size of each worm segment!
      # ^ Gives the 'head' of the worm a rect to collide into things with.

  #...

def move(self):
    """ Move the worm. """
    self.x += self.dir_x
    self.y += self.dir_y

    if (self.x, self.y) in self.body:
        self.crashed = True

    self.body.insert(0, (self.x, self.y))

    if len(self.body) > self.length:
        self.body.pop()

    self.rect.topleft = self.x, self.y
      # ^ Add this line to move the worm's 'head' to the newest pixel.

rawDescription: colliderect() triggers unexpectedly

description: Colliderect() triggers unexpectedly


code:
True
True
True
False
True
False

rawDescription: Is there code out there to subclass set in Python for big xranges?


rawDescription: Filter pandas dataframe based on values in multiple columns


rawDescription: Sort list of strings by substring using Python


code:
[('http://www.test.tw/in/15', 'tree'),
 ('http://www.test.tw/in/15?page=2', 'tree'),
 ('http://www.test.tw/in/15/#/?page=3', 'tree'),
 ('http://www.test.tw/in/20/#/?page=2', 'flower'),
 ('http://www.test.tw/in/3/?page=5', 'bird')]

rawDescription: Url parsing with regex

description: Url parsing with regex


code:
def expansion(n):
    return (numpy.arange(n))

def task(n):
    if is_low(n)==True:
        return (expansion(n))
    if is_low(n)==False:
        return "SORRY"

rawDescription: How to limit the parallel python code for specific/ required value

description: Limit the parallel python code for specific/ required value


code:
def my_function(*passed_arguments):
    query = Session.query(t).filter(t.column_c.in_(passed_arguments)).all()
    # ... do some work with query
    return some_value

rawDescription: SQLAlchemy querying function

description: SQLAlchemy querying function


code:
import string
import random
string.ascii_uppercase
numcount = 5
chars = []
for num in range(19): #strings are 19 characters long
    if numcount and random.random() < 0.5:
        chars.append(str(random.randint(0, 9)))
        numcount -= 1
    else:
        chars.append(random.choice(string.ascii_uppercase))

''.join(chars)
len(chars)

rawDescription: Random String generator python

description: Random String generator python


code:
def craftPick(self):
    self.stone -= 1
    self.wood -= 1
    self.pickaxe += 1
    if self.stone < 1 and self.wood < 1:
        self.CraftPickaxe.config(state=DISABLED)
    elif self.stone > 0 and self.wood > 0:
        self.CraftPickaxe.config(state=NORMAL)

rawDescription: Disable a Tkinter button when variables are at 0


rawDescription: Datetime ints in fewer lines

description: Datetime ints in fewer lines


code:
import re
def other_func(match):
    return match.group()
def some_func():
    return map(other_func, re.finditer(regex, string))
regex = '.'
string = 'abc'
list(some_func())

rawDescription: Apply function for objects from "yield from" in python


code:
instances = {}         #use a dictionary to store the instances

#open the file using `with` statement, it'll automatically close the
#file for you
with open('abc') as f:
    next(f)                 #skip header
    for line in f:          #now iterate over the file line by line
        data = line.strip('[]').split(', ')  #strip [] first and then split at ', '
        #for first line it'll return:
            #['Rohan', '111111', '28', 'Ithaca', 'New Caanan']  , a list object

        #Now we can use the first item of this list as the key
        #and store the instance in the instances dict
        #Note that if the names are not always unique then it's better to use ID as the
        #key for the dict, i.e instances[data[1]] = Person(*data)
        instances[data[0]] = Person(*data)  # *data  unpacks the data list into Person

#Example: call Rohan's introduce_myself
instances['Rohan'].introduce_myself()

rawDescription: Calling from a txt to define something... Python


code:
path = "/directory/date/2011/2009-01-11 This is a file's path/file.jpg"
new_file=os.path.splitext(path)[0]+".MOV"

rawDescription: Fastest way to replace elements of a file's path and extension?


code:
params = {'uname':'j.doe'}
wrapperfunc('john', 'doe', **params)

rawDescription: Using variable length argument lists and named parameters together


code:
class FileInfo(UserDict):
    "store file metadata"
    def __init__(self, filename=None):
        super(UserDict, self).__init__()
        self["name"] = filename

rawDescription: understanding python self and init

description: Understanding python self and init


code:
List1  = [['A'],['b']]
List2 = ['a','A','c','A','b','b','A','b' ]

from collections import Counter

# gets the frequency count of each element in List2
c = Counter(List2)

# create frequency + 1 objects using the value from our Counter dict
# which is how many times it appears in List2
print([sub * (c[sub[0]] + 1) for sub in List1])
[['A', 'A', 'A', 'A'], ['b', 'b', 'b', 'b']]

rawDescription: How to compare two unequal lists and append matching elements value back to the first List

description: Compare two unequal lists and append matching elements value back to the first List


rawDescription: Function called when using binary operators, python


code:
inventory['sword'] = chest['sword']
inventory

rawDescription: Adding items to dictionary from a dictionary


code:
managedServer = create(ServerName,'Server')
managedServer.setListenPort(ListenPort)
managedServer.setCluster(Clustername)
managedServer.setMachine(Machinename)

rawDescription: Anyone tried Cluster automation with WLST?


code:
try:
    # python 2.x
    from urllib import urlretrieve
except ImportError:
    # python 3.x
    from urllib.request import urlretrieve

urlretrieve(theurl, local_filename)

rawDescription: Python: How to suppress the output of os.system


code:
if selection == 2:
    add_member(members)

rawDescription: Reload a function in python?

description: Reload a function in python


code: new_list = filter(None, old_list)

rawDescription: Looking for a strategy for parsing a file


code: dic = {name: Country(*value) for name, value in dic.items()}

rawDescription: python, how to update the dictionaries by mutating its format?

description: Python, how to update the dictionaries by mutating its format


code:
import os
import sys

try:
    r, w = os.pipe()
    print('grandparent {}'.format(os.getpid()))
    child = os.fork()
    if child > 0:
        grandchild_pid = int(os.fdopen(r).readline().strip())
        print('grand child pid: {}'.format(grandchild_pid))
        sys.exit(0)
except OSError:
    print("fork 1 failed")
    sys.exit(1)
try:
    print('parent {}'.format(os.getpid()))
    child = os.fork()
    if child > 0:
        # Pass child (grandchild)'s pid to parent.
        os.write(w, '{}\n'.format(child))
        sys.exit(0)
except OSError:
    print("fork 2 failed")
    sys.exit(1)

print('child {}'.format(os.getpid()))

rawDescription: How to to get the pid of a daemon created by a double fork?

description: To get the pid of a daemon created by a double fork


code: self.newFrame = NewFrame(self)

rawDescription: wxPython SetLabel outside frame's class?

description: WxPython SetLabel outside frame's class


rawDescription: create timestemps for given data

description: Create timestemps for given data


code:
if set(royalFlush).issubset(set(davesCards)):
    return True

rawDescription: How to check if an array contains multiple specific elements

description: Check if an array contains multiple specific elements


code:
from collections import OrderedDict
aDict = OrderedDict((name, 42) for name in list1)

rawDescription: Use list of strings elements as arrays

description: Use list of strings elements as arrays


code:
b.append(5)      # doesn't change what b points to, just changes the list
b += [6]         # also (somewhat counterintuitively) doesn't change what b
                 # points to, even though it did with integers
print(d)         # prints [1, 2, 3, 4, 5, 6] because b and d still point to
                 # the same list

rawDescription: When does python know an initialization is a copy, so that change at one place automatically changes another place?


code:
parser = argparse.ArgumentParser(
    # ... other options ...
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)

rawDescription: Argparse: Way to include default values in '--help'?


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

# Generate some data...
data = np.random.random((10,10))
data[[2, 5, 7], [5, 8, 1]] = np.nan

# Convert it to a masked array instead of just using nan's..
data = np.ma.masked_invalid(data)

# Plot a version with the invalid data replaced with the mean...
plt.imshow(data.filled(data.mean()))

# Now plot a white (or whatever color you'd like), nearest-interpolated array
# over the invalid values...
bad_data = np.ma.masked_where(~data.mask, data.mask)
plt.imshow(bad_data, interpolation='nearest', cmap=mpl.cm.gray_r)

plt.show()

rawDescription: cleaning blurred border between good and bad data in matplotlib imshow

description: Cleaning blurred border between good and bad data in matplotlib imshow


rawDescription: Python removing delimiters from strings

description: Python removing delimiters from strings


code: items_dict.update({x: to_string_and_select(x) for x in we_need_this})

rawDescription: list comprehension with some equal action python

description: List comprehension with some equal action python


code: UserNumbers = int(input('whatever you want it to ask...'))

rawDescription: How to store numbers from a tkinter entrybox into an existing variable?

description: Store numbers from a tkinter entrybox into an existing variable


code:
#Build StdLib.DLL
gb1 = glob.glob(r".\Lib\*.py")
gb2 = glob.glob(r".\Lib\*\*.py")
gb3 = glob.glob(r".\Lib\*\*\*.py")
gb = list(set(gb1 + gb2 + gb3))
gb.append("/out:StdLib")

rawDescription: Compiling IronPython into an exe that uses standard library packages


code: [ '{}{:05d}'.format('IT',x) for x in range(10) ]

rawDescription: How do you create a list of values in Python within a certain range?

description: Create a list of values in Python within a certain range


code:
import csv
import sys

filename = sys.argv[1]

with open(filename, 'rb') as csvfile:
    reader = csv.reader(csvfile)
    data = {}
    next(reader, None)  # skip the headers
    for row in reader:
        size = int(row[1])
        time1 = float(row[3])

        if not size in data:
            data[size] = []

        data[size].append(time1)

writer = csv.writer(sys.stdout)
writer.writerow(["Size","S1","S2","S3","S4"])
for item in data:
    row = [item]
    row.extend(data[item])
    writer.writerow(row)

rawDescription: Reformat CSV file using Python and Pandas, (AWK)?


code:
blocks = blocks[ty1['name'].notnull()]
blocks

rawDescription: distinct contiguous blocks in pandas dataframe

description: Distinct contiguous blocks in pandas dataframe


code:
class MongoBase(object):
    def insert(self, field, value):
        setattr(self, field, value)
    def update(self, field, value):
        setattr(self, field, value)

class User(MongoBase):
    def __init__(self, name):
        self.name = name

rawDescription: How is it possible to access fields of a class in its base class?


rawDescription: Python re.search regx using or condition


code:
class BaseClass:
    def m1(self):
        return 1

class MyClass(BaseClass):
    def m1(self):
        return BaseClass.m1(self)

rawDescription: Python : method resolution order of old-style (or classic) and new-style objects


code:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media_root")

rawDescription: Django Rest get file from FileField url

description: Django Rest get file from FileField url


code: writePictureTo(pict,file)

rawDescription: Saving a picture in Python

description: Saving a picture in Python


rawDescription: Set values in matrix to 1 where index matches value


code:
grouped = df.groupby(['userid','catname'])
aggregated = grouped['amount'].agg([len,sum])
result = aggregated.unstack('catname')

rawDescription: Pandas better way to aggregate over multiple series


code:
mask = (masked_img > 1).any(2)
count = mask.sum()
mean_bgr = (masked_img*(mask[...,None])).sum(axis=(0,1))

rawDescription: Python nested for loop in RGB average

description: Python nested for loop in RGB average


rawDescription: Is a Python function stored as an object?


code:
class segmentation_Rules(models.Model):
    Segmentation_Rules_CHOICES = (
        (1, 'At least one order'),
        (2, 'Have reward points'),
    )
    Rules = models.CharField(max_length=100, blank=True, verbose_name="Select rules for customer segmentation")

rawDescription: Show multiple choices to admin in django


code:
map(lambda x: x**2, a)
map(lambda x: x**2, b)

rawDescription: for loop returning unexpected values when squaring values

description: For loop returning unexpected values when squaring values


code:
import csv
from urlparse import urljoin

from bs4 import BeautifulSoup
import requests

base_url = 'http://www.basketball-reference.com'
data = requests.get("http://www.basketball-reference.com/leagues/NBA_2014_games.html")
soup = BeautifulSoup(data.content)

links = [[urljoin(base_url, link['href']) if not link['href'].startswith('http') else link['href']]
         for link in soup.select("a[href]")]

with open('output.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerows(links)

rawDescription: Python Scraper for Links

description: Python Scraper for Links


code:
a,b,*rest = range(30)
print(a) #0
print(b) #1
print(rest == list(range(2,30))) #True

rawDescription: "variable, variable =" syntax in python?

description: "variable, variable =" syntax in python


code: False

rawDescription: Easy way to check precedence of ( "and", "or") in python


code:
maxval = a[-1]
[elem / maxval for elem in a]

rawDescription: Change from list of integers to weights between 0 and 1?


rawDescription: Choose Python version for egg installation or install parallel versions of site-package


code:
import numpy as np

data = np.arange(30).reshape((10, 3))
n1, n2 = 2, 5
max_value = data[n1:n2, :].max()

rawDescription: How to find the maximum value of a numpy array between given indicies?

description: Find the maximum value of a numpy array between given indicies


code:
cursor.execute ("SELECT winnings, user FROM round_lb WHERE r_id = 5 ORDER BY winnings DESC")
rows = cursor.fetchall()
for rank, (winnings, user) in enumerate(rows, start=1):
    params = (winnings, user, rank)
    cursor.execute("INSERT INTO round_lb (winnings, user, rank) VALUES (%s, %s, %s)", params)

rawDescription: Sort and rank list python and write back to MySQL using python


code:
import module
help(module)

rawDescription: How to find out what methods, properties, etc a python module possesses

description: Find out what methods, properties, etc a python module possesses


code:
from random import randint

guessesTaken = 0
randomNumber = []

Guess = []
for x in range(4):
        tempNumber = str(randint(1, 9)) # compare string to string
        randomNumber.append(tempNumber)
        Guess.append(input("Guess Number: "))

print("".join(["Y" if a==b else "N" for a,b in zip(Guess,randomNumber)]))

rawDescription: Python multiple number guessing game

description: Python multiple number guessing game


code:
template = "%(filename)s %(directory)s %(counter)03d"
template % {"filename": "file", "directory": "dir", "counter": 42}
template % {"filename": "file2", "directory": "dir2", "counter": 5}

rawDescription: Python library for string formatting with custom placeholders


code:
setdictvalto(c, 100)
c

rawDescription: How to set all values of a complex dict to the same one?

description: Set all values of a complex dict to the same one


code:
import string
allChars = string.digits+string.lowercase #get a list of all the 'characters' which represent digits
def toInt(srep,base):
    charMap = dict(zip(allChars,range(len(allChars)))) #map each 'character' to the base10 number
    num = 0 #the current total
    index = len(srep)-1 #the current exponent
    for digit in srep:
        num += charMap[digit]*base**index
        index -= 1
    return num

rawDescription: Python int method

description: Python int method


rawDescription: Algorithm to offset a list of data

description: Algorithm to offset a list of data


code:
from operator import itemgetter
getter = itemgetter("someKey")
hits = []
for idx, first_dic in enumerate(set_of_pk_values[:-1]):
    hits += (getter(first_dic), filter(lambda dic: getter(dic) == getter(first_dic), set_of_pk_values[idx:1]) )

rawDescription: Python Nested For Loop Array Comparison - Possibility of Optimization?


code: list(bytearray(data)) == [ord(c) for c in data]

rawDescription: capturing data from clients as hex using twisted Python

description: Capturing data from clients as hex using twisted Python


rawDescription: PyQt QTableWidget horizontalheaderlabel stylesheet


code:
a = "15-105;ZH0311;TZZGJJ; ZH0311; ZH0311;DOC"
a = map(str.strip,a.split(';'))
a
a = sorted(set(a),key=lambda x:a.index(x))
a
";".join(a)

rawDescription: Remove duplicated string(s) in strings in a list


code:
phone = objectify.Element('phone')
phone.type = data_dict['PRIMARY PHONE1']
phone.number = data_dict['PRIMARY PHONE TYPE 1']
root.customers.customer.append(phone)

phone = objectify.Element('phone')
phone.type = data_dict['PRIMARY PHONE2']
phone.number = data_dict['PRIMARY PHONE TYPE 2']
root.customers.customer.append(phone)

rawDescription: Python - How to append the same XML element multiple times with lxml.objectify


code:
import modulegraph.modulegraph

m = modulegraph.modulegraph.ModuleGraph()
m.run_script("test.py")
m.create_xref()

rawDescription: Using Numpy creates a tcl folder when using py2exe


code:
inputs=["one","two"]   # square brackets, so it's an array
themap={"one":1, "two":2}   # braces, so it's a dictionary
map(lambda x: themap[x], inputs)  # evaluates to [1, 2]

rawDescription: A map of string replacements in Python2.7


rawDescription: Classify elements of a numpy array using a second array as reference


code: return sum(array[1::2])

rawDescription: In Python, loop for don't "save" items with same value in a list


code:
('Imperial College of Business Studies', 'Lahore')
('Government College University', 'Faisalabad')
('Imperial College of Business Studies', 'Lahore')
('University of Peshawar', 'Peshawar')
('University of Sindh', 'Jamshoro')

rawDescription: how to get string values using index method in Python

description: Get string values using index method in Python


code:
lst = 3 * [3 * [None]]
lst[0] is lst[1]
lst[0] is lst[2]

rawDescription: python operator "*" with List， any others like it?

description: Python operator "*" with List， any others like it


code: df = pd.read_csv(file_name, sep=',\s+', header=None)

rawDescription: python pandas date_range when importing with read_csv

description: Python pandas date_range when importing with read_csv


code:
from subprocess import *

class CommandSubstituter(object):
    def __init__(self):
        self._procs = []

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        pass

    def subst(self, *args, **kwargs):
        proc = Popen(*args, stdout=PIPE, **kwargs)
        self._procs.append(proc)
        return "/dev/fd/%d" % proc.stdout.fileno()

with CommandSubstituter() as c:
    Popen(['wc', '-l',
           c.subst(['comm', '-12',
                    c.subst(['sort', 'file1.txt']),
                    c.subst(['sort', 'file2.txt'])])])

rawDescription: use subprocess.Popen to run a unix tool that requires multiple input redirects

description: Use subprocess.Popen to run a unix tool that requires multiple input redirects


code:
from Tkinter import *

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

rawDescription: How to set default text for a Tkinter Entry widget

description: Set default text for a Tkinter Entry widget


code:
import eav
from app.models import Patient, Encounter

eav.register(Encounter)
eav.register(Patient)
Attribute.objects.create(name='age', datatype=Attribute.TYPE_INT)
Attribute.objects.create(name='height', datatype=Attribute.TYPE_FLOAT)
Attribute.objects.create(name='weight', datatype=Attribute.TYPE_FLOAT)
Attribute.objects.create(name='city', datatype=Attribute.TYPE_TEXT)
Attribute.objects.create(name='country', datatype=Attribute.TYPE_TEXT)

self.yes = EnumValue.objects.create(value='yes')
self.no = EnumValue.objects.create(value='no')
self.unkown = EnumValue.objects.create(value='unkown')
ynu = EnumGroup.objects.create(name='Yes / No / Unknown')
ynu.enums.add(self.yes)
ynu.enums.add(self.no)
ynu.enums.add(self.unkown)

Attribute.objects.create(name='fever', datatype=Attribute.TYPE_ENUM,\
                                       enum_group=ynu)

# When you register a model within EAV,
# you can access all of EAV attributes:

Patient.objects.create(name='Bob', eav__age=12,
                           eav__fever=no, eav__city='New York',
                           eav__country='USA')
# You can filter queries based on their EAV fields:

query1 = Patient.objects.filter(Q(eav__city__contains='Y'))
query2 = Q(eav__city__contains='Y') |  Q(eav__fever=no)

rawDescription: Django dynamic model fields

description: Django dynamic model fields


code:
a = iter(list(range(10)))
for i in a:
   print(i)
   _ = next(a)

rawDescription: Python list iterator behavior and next(iterator)


code:
f = open("output.xml", "w")
try:
    f.write(doc.toprettyxml(indent="  "))
finally:
    f.close()

rawDescription: How to save an xml file to disk?

description: Save an xml file to disk


code:
sql = "INSERT IGNORE INTO users_time_zone (user_id, email, username, gcm_reg_id, time_zone) " \
      "VALUES(%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE gcm_reg_id =%s, id=LAST_INSERT_ID(id) "

data = (user_data['user_id'], user_data['email'], user_data['username'],
        user_data['gcm_reg_id'], user_data['time_zone'], user_data['gcm_reg_id'])

cursor = conn.cursor()
cursor.execute(sql, data)

rawDescription: Wrong sql syntax because of single or double quote in string


rawDescription: How to add list to dictionary by using index of list as key and item of list as value?

description: Add list to dictionary by using index of list as key and item of list as value


code:
var_names=['a','b','c','d','e']
values=[1,2,3,4,5]

my_dict = {i:f(j) for i,j in zip(var_names,values)}
my_dict

rawDescription: Declaring multiple variables using the same function in Python


code:
XYZ,Mon-FR,ABC
XY,Mo-Fr,AB
Xy,M-F,AbC
xyz,MON-FRI,ABC
XYZ,Mon-Su,ABC
XYZ,Sat-Sun,ABC
XXX,SaSu,ABC
XY,MF & Sa,ABC

rawDescription: Regex to pick days of the week from a string in Python


code:
linear_function = sensor["convert"]["linear"]

globals()[linear_function[0]](*linear_function[1:])

rawDescription: Can I store Python function on a MongoDB collection?

description: Store Python function on a MongoDB collection


code:
def ul_handler(el):
    yield list(itertext(el, with_tail=False))
    if el.tail:
        yield el.tail

def itertext(root, handlers=dict(ul=ul_handler), with_tail=True):
    if root.text:
        yield root.text
    for el in root:
        yield from handlers.get(el.tag, itertext)(el)
    if with_tail and root.tail:
        yield root.tail

print(list(joinadj(itertext(html.fromstring(
                    "text0text1

item1
"
                    "
item2

sub1
sub2

"
                    "text2sib")))))

rawDescription: Python, lxml - access text

description: Python, lxml - access text


code:
me = Person()
me.rebound = unbound
type(me.rebound)
type(me.unbound)
me.rebound
me.rebound()

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


code:
import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')

workbook.add_worksheet()
workbook.add_worksheet()
workbook.add_worksheet()
workbook.add_worksheet()

for worksheet in workbook.worksheets():
    worksheet.write('A1', 'Hello')

workbook.close()

rawDescription: python xlsxwriter worksheet object reuse

description: Python xlsxwriter worksheet object reuse


rawDescription: Order a django queryset by ManyToManyField = Value


code:
lock = RLock()

def f():
  with lock:
    g()
    h()

def g():
  with lock:
    h()
    do_something1()

def h():
  with lock:
    do_something2()

rawDescription: What is the difference between Lock and RLock


code:
i = 0
while i < 15:
    logging.info('-----  packing iteration %i started  ------' % (i))
    po_selection_list = po_sel.get_po_lists(TrayID,TrayHeight,Materials,TrayName,i) # get po lists for this iteration
    po_count = 0
    for po_list in po_selection_list: # loop through all lists
        if po_list: # load po's in tray
            po_count += len(po_list)
            functions_library.AddPOs_Stage1(po_list,driver)
            if not functions_library.AddPOs_trayIDSearch(driver):
                break
            functions_library.AddPOs_Stage2(driver)

            functions_library.ImportParts()
    else:
        # break didn't occur
        if po_count: # pack and sync in netfabb
            functions_library.MovePartsZHeight()
            functions_library.NetfabbPacking(TrayID,TrayHeight,Materials)
            functions_library.RemoveNetfabbExtraParts()
            functions_library.NetfabbSync(driver)
        i += 1

rawDescription: PYTHON - Restart same for loop iteration


code: string.rfind("\n\n", 0, pos) # searches for "\n\n" from the beginning up-to `pos` but will return you the last match

rawDescription: How can I find the boundaries of a paragraph with Python `string.find()`?

description: Find the boundaries of a paragraph with Python `string.find()`


code: self.l_user, = self.ax.plot([],self.user, label='Total %')

rawDescription: matplotlib axes formatting

description: Matplotlib axes formatting


code:
from django import template
from django.contrib.auth.models import User

register = template.Library()

########################

def get_user(username):
    try:
        user = User.objects.get(username__iexact=username)
    except User.DoesNotExist:
        user = User.objects.none()
    return user

register.filter('get_user',get_user)

rawDescription: Custom Django template tag to look up a string username and return it as a user object


code:
import csv

# Result dictionary
result = {}
# Open the file in Universal mode
with open('Fruit.csv', 'rU') as f:
    # Get the CSV reader and skip header
    reader = csv.reader(f)
    reader.next()

    for row in reader:
       #First column is the key, the rest is value
       result[row[0]] = row[1:]

rawDescription: Load excel file into dictionary in Python


code:
import scrapy

class BotItem(scrapy.Item):
    name = scrapy.Field()

rawDescription: Crawl spider not crawling ~ Rule Issue

description: Crawl spider not crawling ~ Rule Issue


code:
a = 'hello i am stackoverflow.com user "+-'
print(re.sub(r'((?![\s"])\W)', r'\\\1', a))

rawDescription: How can I find a match and update it with RegEx?

description: Find a match and update it with RegEx


code:
from io import open
for fname in glob.glob("*.html") :
    with open(fname, encoding="utf-8") as f:
        text = BeautifulSoup(f.read(), 'html.parser').getText()
        scantext(text, ii)

rawDescription: Regular expressions in python where text is read from file


rawDescription: How to recursively read all characters in a list?

description: Recursively read all characters in a list


code:
from selenium.common.exceptions import NoSuchElementException

while True:
    try:
        myServerIP = driver.find_element_by_xpath("//select[@name='servers']/option").text
    except NoSuchElementException:
        break

rawDescription: While statement not evaluating to false for Selenium Webdriver


code:
with open("input.txt", "rb") as f:
    text = f.read().rstrip()  # rstrip to remove trailing spaces
decoded = text.decode('unicode-escape').encode('latin1').decode('utf-8')
with open("output.txt", "wb") as f:
    f.write(decoded.encode('unicode-escape'))

rawDescription: How do I convert unicode to unicode-escaped text

description: Convert unicode to unicode-escaped text


code:
curs.execute('''
    SELECT date, price
    FROM prices
    WHERE date <= ?
        AND date >= ?
        AND id = ?''', (max(date), min(date), id))

rawDescription: Query Sqlite for multiple arguments at once and handling missing values


rawDescription: Python to extract unique CSV rows

description: Python to extract unique CSV rows


code:
for a, b, c, d in zip(anno_st(), anno_ex(), anno_mr(), anno_nc()):
    if d != "0":
        write_to_file(d)
    elif c != "0":
        write_to_file(c)
    elif b != "0":
        write_to_file(b)
    else:
        write_to_file(a)

rawDescription: Memoryerror with too big list

description: Memoryerror with too big list


code:
def execute(lst):
    result = ()
    for func, args in list:
        args = result + args
        result = func(*args)

rawDescription: Hashing the code of a Python function (including lambdas)


code:
a.append
b.append

rawDescription: Python Lists and Equality

description: Python Lists and Equality


code: print(result)

rawDescription: pandas count values for last 7 days from each date

description: Pandas count values for last 7 days from each date


code: vel = np.vstack([velx, vely]).T

rawDescription: Defining velocity in a boid simulation

description: Defining velocity in a boid simulation


code:
import re
my_string = "Alex - 30% / Bob - 23.33%"
r = re.findall(r'([a-zA-Z]*) - (\S+)%', my_string)
r

rawDescription: Python string parsing name and number

description: Python string parsing name and number


code:
def Ilim(self): # Prints How many lines are in
    info =  int(tbox.index('end-1c').split('.')[0])
    print(info)
    return "break"

rawDescription: Remove tkinter text default binding

description: Remove tkinter text default binding


code:
a = [3, 2]
b = [3, 2]
a is b
c = [[4, 3], a, [5, 7], b, [6, 3]]
def index_by_identity(lst, target):
    for i, obj in enumerate(lst):
        if obj is target:
            return i
    # no object matches
    raise IndexError(target)

index_by_identity(c, b)
def index_by_identity(lst, target):
    try:
        return next(i for i, obj in enumerate(lst) if obj is target)
    except StopIteration:
        # no object matches
        raise IndexError(target)

index_by_identity(c, b)

rawDescription: Using .index() with duplicate values that have separate identifiers


code:
from django.conf import settings
settings.configure()

rawDescription: Using Django log

description: Using Django log


code: {'2': 'Green tea', '1': 'Chocolate ice cream', '8': 'Shrimp roll'}

rawDescription: Converting file to dict

description: Converting file to dict


code:
changer = ChangingClass(5)
changer.x = 6
changer.x = 6
# nothing printed
changer.x = None
changer.x = 6

rawDescription: Decorating a class to monitor attribute changes


code: matline = yentry.copy()

rawDescription: Python: array values somehow getting changed


code:
soup=BeautifulSoup(r.content,"html.parser")
tbl = soup.find("table")
len(tbl.find_all("tr"))
len(tbl.find_all("tr")[3:])
soup=BeautifulSoup(r.content,"lxml")
tbl = soup.find("table")
len(tbl.find_all("tr")[3:])
len(tbl.find_all("tr"))

rawDescription: BeautifulSoup Iteration not working

description: BeautifulSoup Iteration not working


rawDescription: How to loop backwards in python?

description: Loop backwards in python


rawDescription: How do I retain row-and-column arrangement while performing regular expression manipulations in Python

description: Retain row-and-column arrangement while performing regular expression manipulations in Python


code:
stylesheet = "QSplitter::handle{background: gray; width: 2px; height: 2px;}"
self.splitter.setStyleSheet(stylesheet )

rawDescription: How to control qsplitter handle using buttons

description: Control qsplitter handle using buttons


code:
xs = np.random.randint(0, 10, 100)
xs
val, cnt = np.unique(xs, return_counts=True)
pmf = cnt / len(xs)
# values along with probability mass function
np.column_stack((val, pmf))

rawDescription: How to plot a PMF of a sample?

description: Plot a PMF of a sample


code:
from random import random

def allele_generator(p):
    while True:
        yield 'p' if random() < p else 'q'

agen = allele_generator(0.001)
for i in range(3):
    print(next(agen))

rawDescription: Robust weighted random string generator

description: Robust weighted random string generator


code:
def OnUpdate(*args):
    try:
        status_text.set(my_queue.get())
    except Queue.Empty:
        pass

rawDescription: How do I make a button in my tk UI that makes the program do a whole ton of stuff when it is pressed not freeze the window?

description: Make a button in my tk UI that makes the program do a whole ton of stuff when it is pressed not freeze the window


code: record[NEW_FIELD] = 'whatever'

rawDescription: How can I rename the field names of a .dbf file when reading it with dbfpy?

description: Rename the field names of a .dbf file when reading it with dbfpy


code:
import glob

def padStr( x, n ):
    x += ' '
    return x + '.'*(n - len(x) )

for file in glob.glob('*.*'):
    with open(file) as f:
        contents = f.read()
    if 'HOST_POWER="OFF"' in contents:
        print('%s %s' % ( padStr(file[:-4], 38 ),"ON"))

for file in glob.glob('*'):
    with open(file) as f:
        contents = f.read()
    if 'HOST_POWER="OFF"' in contents:
        print('%s %s' % ( padStr(file[:-4], 38 ),"OFF"))

rawDescription: Python print format with dot leader

description: Python print format with dot leader