code:
myurls = {}
urls = []
for x in range(1, 15):
    for y in range(1, 87):

        with open("C:\\Python33\\NASDAQ Stock Strings\\NASDAQ_Config_File_{}_{}.txt".format(x,y), "r") as f:
            thisfile = f.read().replace('\n', '')
            myurls[x,y] = thisfile
            urls.append(thisfile)
            print("myurls[%d,%d] = %s" % (x, y, thisfile))

rawDescription: How to globally declare this Python list

description: Globally declare this Python list


code: get_X_of_Y("CEO", companies[0])

rawDescription: Efficiently find objects satisfying relationship


code: return ','.join([i['name'] for i in items])

rawDescription: Taking a list of items and displaying a value from each item as a string


code:
employee_template = {"role": "minion"}
e = Employee(employee_template, name="abc", age=32)

rawDescription: Set attributes from dictionary in python


code:
import tkinter as tk

root = tk.Tk()

global entry
entry = tk.Entry(state = 'disabled')
entry.pack()

def create():
    global entry
    entry.config(state = 'normal')

def destroy():
    global entry
    entry.config(state = 'disabled')

button1 = tk.Button(text = 'create entry', command = create)
button1.pack()

button2 = tk.Button(text = 'destroy entry', command = destroy)
button2.pack()

root.mainloop()

rawDescription: Python: Using Tkinter radio-buttons to add/remove fields from GUI


code:
@jit(nopython=True)
def numba_get_pos_neg_bitwise(df, mask):
    posneg = np.zeros((df.shape[0], 2))
    vandmask = np.bitwise_and(df[:, 1:], mask)

    for idx in range(df.shape[0]):

        # numba fail with # if np.all(vandmask == mask):
        vandm_equal_m = 1
        for i, val in enumerate(vandmask[idx]):
            if val != mask[i]:
                vandm_equal_m = 0
                break
        if vandm_equal_m == 1:
            if df[idx, 0] == 1:
                posneg[idx, 0] = 1
            else:
                posneg[idx, 1] = 1
    pos = np.nonzero(posneg[:, 0])[0]
    neg = np.nonzero(posneg[:, 1])[0]
    return (pos, neg)

rawDescription: Numba 3x slower than numpy

description: Numba 3x slower than numpy


code:
class MutableDefault(object):
    def __init__(self, start=0):
        self.value = start
    def __iadd__(self, other):
        self.value += other
        return self
    def value(self):
        return self.value

rawDescription: Adding attributes to instance methods in Python


code:
class Test1:
    pass

class Test2:
    def __bool__(self):
        return False

class Test3:
    def __len__(self):
        return 0

t1 = Test1()
t2 = Test2()
t3 = Test3()

rawDescription: The reason of foo.__x__ and x(foo) in Python (i.e. len and __len__)


code:
def my_abs(value):
    return value if value >= 0 else -value

rawDescription: Basic Python. "Boolean-valued functions"


code:
from django.db import models

class Value(models.Model):
    val = models.IntegerField(unique=True)

class Key(models.Model):
    key = models.CharField(max_length=50)
    value = models.ManyToManyField(Value, related_name='values')

rawDescription: How to design Django models where one key have multiple corresponding values?

description: Design Django models where one key have multiple corresponding values


rawDescription: How do I filter a python list containing dates according to the given start date and end date?

description: Filter a python list containing dates according to the given start date and end date


code:
from scipy.spatial import Delaunay, delaunay_plot_2d
x = randn(100,2)
d = Delaunay(x)
a = delaunay_plot_2d(d)
patch = [l for l in a.axes[0].get_children() if type(l) is matplotlib.patches.PathPatch][0]

rawDescription: How to change matplotlib line color in scipy.spatial.delaunay_plot_2d

description: Change matplotlib line color in scipy.spatial.delaunay_plot_2d


code:
from mayavi.mlab import *
contour3d(F,contours=8,opacity=.2 )

rawDescription: 3D Contour plot from data using Mayavi / Python


code: primes = [x for x in range(2, 50) if x not in noprimes]

rawDescription: No Primes list Comprehension

description: No Primes list Comprehension


code: df2 = pd.concat([df]*10000)   # df2 has a non-unique index

rawDescription: How to subset a data frame using Pandas based on a group criteria?

description: Subset a data frame using Pandas based on a group criteria


code:
import datetime, pymongo
created_at = 'Mon Jun 8 10:51:32 +0000 2009' # Get this string from the Twitter API
dt = datetime.strptime(created_at, '%a %b %d %H:%M:%S +0000 %Y')

rawDescription: How do I compare dates from Twitter data stored in MongoDB via PyMongo?

description: Compare dates from Twitter data stored in MongoDB via PyMongo


code:
class P(Function):
    def fdiff(self, argindex=1):
        if argindex == 1:
            return self.args[2]/self.args[0]*E(*self.args)
        else:
            raise ArgumentIndexError(self, argindex)

class E(Function):
    pass

rawDescription: How to overload the fdiff method of a personal function inheriting from the Function class?

description: Overload the fdiff method of a personal function inheriting from the Function class


code:
('apple', 'banana', 'tomato', 'onion', 'juice', 'soda', 12)
('apple', 'banana', 'cucumber', 'onion', 'water', 'soda', 12)
('apple', 'banana', 'cucumber', 'onion', 'juice', 'soda', 13)
('apple', 'orange', 'tomato', 'cucumber', 'juice', 'soda', 12)
('apple', 'orange', 'tomato', 'onion', 'water', 'soda', 12)
('apple', 'orange', 'tomato', 'onion', 'juice', 'soda', 13)
('apple', 'orange', 'cucumber', 'onion', 'water', 'juice', 12)
('apple', 'orange', 'cucumber', 'onion', 'water', 'soda', 13)
('apple', 'orange', 'cucumber', 'onion', 'juice', 'soda', 14)
('banana', 'orange', 'tomato', 'cucumber', 'water', 'soda', 12)
('banana', 'orange', 'tomato', 'cucumber', 'juice', 'soda', 13)
('banana', 'orange', 'tomato', 'onion', 'water', 'juice', 12)
('banana', 'orange', 'tomato', 'onion', 'water', 'soda', 13)
('banana', 'orange', 'tomato', 'onion', 'juice', 'soda', 14)
('banana', 'orange', 'cucumber', 'onion', 'water', 'juice', 13)
('banana', 'orange', 'cucumber', 'onion', 'water', 'soda', 14)

rawDescription: python - check if permutation exists/combination is unique

description: Python - check if permutation exists/combination is unique


code: AccessCode.objects.bulk_create([AccessCode() for i in range(100)])

rawDescription: Creating multiple objects of Model using one button in Django


code:
from django.http import HttpResponseRedirect
return HttpResponseRedirect(reverse('dyn_display'))

rawDescription: pass kwargs for the view in reverse; django 1.5

description: Pass kwargs for the view in reverse; django 1.5


rawDescription: Finding reachable vertices of a vertice in a graph


rawDescription: Python replacing max values in array

description: Python replacing max values in array


code:
from ply.lex import TOKEN

KEYWORDS = [
    r'some', r'keyword',
    r'keyword with token',
    r'other keyword',
]

keyword = '|'.join(keyword.replace(' ', '\s+') for keyword in KEYWORDS)

@TOKEN(keyword)
def t_KEYWORD(t):
    # remove spaces
    value = ''.join(x for x in t.value if not x.isspace())
    return value.upper()

rawDescription: Identifying keyword pairs in lex

description: Identifying keyword pairs in lex


code:
for i in root.iter('ForexBuying'):
    print(i.text)

rawDescription: Web Mining with Python

description: Web Mining with Python


code: newDict = {}

rawDescription: How can I create a nested list from an existing one where the first x items are the outer items?

description: Create a nested list from an existing one where the first x items are the outer items


rawDescription: How to remove blank element in between non-blank elements in list?

description: Remove blank element in between non-blank elements in list


code:
from bs4 import BeautifulSoup

html = """

        Russia

         St. Petersburg

        Russian Area Studies, St. Petersburg - Fall

Council on International Educational Exchange, St. Petersburg

St. Petersburg State University

"""

soup = BeautifulSoup(html, "html.parser")
cities = soup.find_all('div', attrs={'class': 'result'})
for city in cities:
    spans = city.find_all('span')
    for span in spans:
        span.decompose()
    text_you_need = BeautifulSoup(str(city),"html.parser").find('div').text
    university = text_you_need.strip().split('\n')[1].strip()
    print(university)

rawDescription: Parsing HTML text that isn't labeled

description: Parsing HTML text that isn't labeled


code:
strlist = ['the', 'the', 'boy', 'happy', 'boy', 'happy']
from collections import defaultdict
D = defaultdict(set)
for i, s in enumerate(strlist):
    D[s].add(i)

D

rawDescription: Generating an inverse index

description: Generating an inverse index


code: button = tk.Button(root, text="exit", command=root.destroy)

rawDescription: Alternative to using global parameters in Tkinter


code:
import threading
import time

X = 2
lock = threading.Lock()

def function():
    with lock:
        print("Thread {} starting.".format(threading.current_thread()))
        threading.Timer(X, function).start()
        time.sleep(2*X)
        print("Thread {} done.".format(threading.current_thread()))

function()

rawDescription: Python threading timer

description: Python threading timer


code:
import numpy as np

def diffs(a,b):
    # collect sliding window differences
    # length of window determined by the shorter array
    # if a,b are not arrays, need to replace b[...]-a with
    # a list comprehension
    n,m=len(a),len(b)
    if n>m:
        # ensure s is the shorter
        b,a=a,b # switch
        n,m=len(a),len(b)
        # may need to correct for sign switch
    result=[]
    for i in range(0,1+m-n):
        result.append(b[i:i+n]-a)
    return result

def alldiffs(a,b):
    # collect all the differences for elements of a and b
    # a,b could be lists or arrays of arrays, or 2d arrays
    result=[]
    for aa in a:
        for bb in b:
            result.append(diffs(aa,bb))
    return result

# define the 3 arrays
# each is a list of 1d arrays

a=[np.array([2,2,1,2]),np.array([1,3])]
b=[np.array([4,2,1])]
c=[np.array([1,2]),np.array([4,3])]

# display the differences
print(alldiffs(a,b))
print(alldiffs(a,c))
print(alldiffs(b,c))

rawDescription: Python: Cell arrays comparison using minus function


code:
import pandas as pd
import glob

#change path by your
df = pd.concat((pd.read_csv(f,
                            sep='|',
                            header=None,
                            names=['cmte_id', '2', '3', '4', '5', 'trans_typ', 'entity_typ', '8', '9', 'state', '11', 'employer', 'occupation', 'date', 'amount', 'fec_id', 'cand_id', '18', '19', '20', '21', '22'],
                            usecols= ['date', 'cmte_id', 'trans_typ', 'entity_typ', 'state', 'employer', 'occupation', 'amount', 'fec_id', 'cand_id'],
                            dtype={'date': str}
                           ) for f in glob.glob('test/itpas2_data/itpas2**.txt')), ignore_index=True)

#parse column date to datetime
df['date'] = pd.to_datetime(df['date'], format='%m%d%Y')

#remove rows, where date is NaN
df = df[df['date'].notnull()]

#set column date to index
df = df.set_index('date')

g = df.groupby([pd.TimeGrouper('1M'), 'cand_id', 'trans_typ'])['amount'].sum()

rawDescription: Using Timegrouper '1M' to group and sum by columns is messing up my date index pandas python


code:
ABCDEFGHIJKLMNOPQRSTUVWXYZ
BCDEFGHIJKLMNOPQRSTUVWXYZA
CDEFGHIJKLMNOPQRSTUVWXYZAB
DEFGHIJKLMNOPQRSTUVWXYZABC
EFGHIJKLMNOPQRSTUVWXYZABCD
FGHIJKLMNOPQRSTUVWXYZABCDE
GHIJKLMNOPQRSTUVWXYZABCDEF
HIJKLMNOPQRSTUVWXYZABCDEFG
IJKLMNOPQRSTUVWXYZABCDEFGH
JKLMNOPQRSTUVWXYZABCDEFGHI
KLMNOPQRSTUVWXYZABCDEFGHIJ
LMNOPQRSTUVWXYZABCDEFGHIJK
MNOPQRSTUVWXYZABCDEFGHIJKL
NOPQRSTUVWXYZABCDEFGHIJKLM
OPQRSTUVWXYZABCDEFGHIJKLMN
PQRSTUVWXYZABCDEFGHIJKLMNO
QRSTUVWXYZABCDEFGHIJKLMNOP
RSTUVWXYZABCDEFGHIJKLMNOPQ
STUVWXYZABCDEFGHIJKLMNOPQR
TUVWXYZABCDEFGHIJKLMNOPQRS
UVWXYZABCDEFGHIJKLMNOPQRST
VWXYZABCDEFGHIJKLMNOPQRSTU
WXYZABCDEFGHIJKLMNOPQRSTUV
XYZABCDEFGHIJKLMNOPQRSTUVW
YZABCDEFGHIJKLMNOPQRSTUVWX
ZABCDEFGHIJKLMNOPQRSTUVWXY

rawDescription: For Kasiski Test,How to implement 26x26 table in Python


code:
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 465
EMAIL_USE_TLS = True

EMAIL_HOST_USER = 'my@gmail.com'
EMAIL_HOST_PASSWORD = 'my_emails_password'

rawDescription: send activate-email with django-registration

description: Send activate-email with django-registration


code:
for i, j in twolines(file):
    x = information()
    x.filename, x.hashvalue = i,j
    list.append(x)

rawDescription: Manually read lines in python

description: Manually read lines in python


code:
nr = format(s,'02') + format(d.year,'04') + format(d.month, '02') + format(d.day, '02') + format(d.hour, '02') + format(d.minute, '02') + format(int(p*0.2), '04')
outfile.write(nr + '\n')

rawDescription: Print strings with line break Python

description: Print strings with line break Python


code:
# create data
df = pd.DataFrame([1, 1, 1, 1, 0.5, 0.5, 0, 0], columns=['known'])

df['fudge'] = df.known + 0.01 * (np.random.rand(len(df)) - 0.5)

df.known[df.fudge > df.fudge.quantile(0.75)]

rawDescription: Getting quartiles in pandas when data has low variance


code:
def increment_counter(classname):
    counter_attribute = '_{}__COUNTER'.format(classname)
    def increment_counter_decorator(method):
        def wrapper(self, *args, **kw):
            setattr(self, counter_attribute, getattr(self, counter_attribute) + 1)
            return method(self, *args, **kw)
        return wrapper

rawDescription: How can I increase counter properties of class when a instance is called?

description: Increase counter properties of class when a instance is called


code:
# ...
data = data.split()
data.pop(0) # remove Rosalind_10
original = data.pop(0) # store sequence for Rosalind_10
introns = []
for piece in data:
    if piece.startswith('>'):
        continue
    else:
        introns.append(piece)
print('original', original)
print('introns', introns)

rawDescription: Python for loop skips over '>' symbol fasta format


code:
class Parameters(object):
    def __init__(self):
        super(Parameters, self).__setattr__('paramOrder', [])

    # etc.

rawDescription: How to handle call to __setattr__ from __init__?

description: Handle call to __setattr__ from __init__


code: is_tty = os.isatty(sys.stdout.fileno())

rawDescription: Save a Python script's output with > in bash while using raw_input()


code:
events = [Quartz.CGEventCreateKeyboardEvent(None, 56, True),
          Quartz.CGEventCreateKeyboardEvent(None, 6, True),
          Quartz.CGEventCreateKeyboardEvent(None, 6, False),
          Quartz.CGEventCreateKeyboardEvent(None, 56, False)]

rawDescription: How to use CGEventCreateKeyboardEvent in Python on Mac?

description: Use CGEventCreateKeyboardEvent in Python on Mac


code:
import wx
import wx.grid as grid
#
class Button(wx.Frame):
    def __init__(self, parent, source):
        wx.Frame.__init__(self, parent, -1, size=(100,100))
        self.source = source
        self.pos = 0
        self.button = wx.Button(self, label='0')
        self.Bind(wx.EVT_BUTTON, self.onbutton, self.button)
        self.Show()

    def onbutton(self, evt):
        self.pos += 1
        self.source.grid.Scroll(self.pos, self.pos)
        self.button.SetLabel(str(self.pos))

class Frame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, -1, "Grid", size=(350,250))
        self.grid = grid.Grid(self)
        self.grid.CreateGrid(20, 20)
        self.but = Button(None, self)

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = Frame(None)
    frame.Show()
    app.MainLoop()

rawDescription: How to make auto scrolling wx.grid table?

description: Make auto scrolling wx.grid table


code:
def __init__(self):
    self.f = open("file.txt", "r")
    self.a = self.f.readlines()

    # you must copy the list to make another list
    self.b = self.a[:]

    random.shuffle(self.b)

rawDescription: Class and while loop?

description: Class and while loop


code: filelist = [row[0] for row in csv.reader(expenses)]

rawDescription: Creating a list using csv.reader()

description: Creating a list using csv.reader()


code:
soup.find_all("a", href=re.compile(r"^/markets/NZSX/securities/"))
soup.find_all("a", href=lambda href: href and href.startswith("/markets/NZSX/securities/"))

rawDescription: Finding partial matches in an href tag

description: Finding partial matches in an href tag


rawDescription: Python nested html tags with Beautifulsoup


code: tester = hand.copy()

rawDescription: Unsure why dictionary is mutating

description: Unsure why dictionary is mutating


rawDescription: python: how to create list of/iterate through multiple instances of a variable

description: Python: how to create list of/iterate through multiple instances of a variable


rawDescription: numpy.where equivalent for csr_matrix python

description: Numpy.where equivalent for csr_matrix python


rawDescription: How do you express binary literals in Python?

description: Express binary literals in Python


code: [list(group) for key, group in groupby(L, key=bool) if key]

rawDescription: Make a new sublist of preceding characters every time there's a zero in a list, excluding the zero


code:
h1,h2,h3
a,b,c
g,h,i

rawDescription: How to Delete Rows CSV in python

description: Delete Rows CSV in python


code:
class MyModel(models.Model):
    connection_name="asterisk"
    #etc...

rawDescription: Multiple Database Config in Django 1.2

description: Multiple Database Config in Django 1.2


code: Dict2 = eval(repr(Dict))

rawDescription: Python how to use a string to fill a dictionary in one go?


code:
x=(sum(similarity(i,j) for i in a for j in b) if isinstance(a,(dict,list,tuple))
   else 0)

rawDescription: Python, best way to write a sum of two for loops


code:
parent = relationship(
    Parent,
    primaryjoin=(
        foreign(child_id) ==
        remote(Parent.parent_letter + cast(Parent.parent_id, String))
    ),
    backref="children",
    uselist=False,
)

rawDescription: relationship with a sliced and casted value of the column in SQLAlchemy

description: Relationship with a sliced and casted value of the column in SQLAlchemy


rawDescription: Use xlrd to convert XLSX to XML

description: Use xlrd to convert XLSX to XML


code:
everything_ever = Everything()
def check_allowed(x, whitelist=everything_ever):
    if x in whitelist:
        print("x is ok")
    else:
        print("x is not ok")

rawDescription: A Python "Everything" keyword that always returns True for membership tests


code: print(enteredMonth(month), year, "has", numberOfDays(month, year), "days")

rawDescription: date handling issue in Python

description: Date handling issue in Python


code:
def resolve_object(name):
    names = name.split('.')
    return reduce(getattr, names[1:], globals()[names[0]])

rawDescription: Resolving a Python object in global namespace by string look up


code:
def XX(func, a, b, c, d, x, s, ac):
    res=0
    res=res+a+func(b,c,d)
    res+=x
    res+=ac
    res=res & 0xffffffff
    res=rol(res,s)
    res=res & 0xffffffff
    res+=b
    return res & 0xffffffff

rawDescription: MD5 Python Implementation

description: MD5 Python Implementation


code: data = {'character1':{'lives':3, 'health':100}, 'character2':{'lives':4, 'health':85}}

rawDescription: Overwrite flags in a file python

description: Overwrite flags in a file python


code:
import struct
struct.pack('>H', 4)

rawDescription: Python3 editing hex string

description: Python3 editing hex string


code:
import pylab as pl
from random import randint
import numpy as np
from skimage import draw

W, H = 800, 600

def make_poly(x0, y0, r, n):
    a = np.linspace(0, np.pi*2, n, endpoint=False)
    x = x0 + r * np.cos(a)
    y = y0 + r * np.sin(a)
    return y, x

count_buf = np.zeros((H, W))
sum_buf = np.zeros((H, W))

N = 2000

polys = []
for i in range(N):
    x0, y0, r, n = randint(10, W-10), randint(10, H-10), randint(10, 50), randint(3, 10)
    polys.append((make_poly(x0, y0, r, n), randint(1, 10)))

rawDescription: Overlapping polygons in Python PIL

description: Overlapping polygons in Python PIL


rawDescription: Using for-loop to create a Pandas DataFrame (non-dictionary based)


code:
import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    outfile.write( yaml.dump(data, default_flow_style=True) )

rawDescription: How can I write data in YAML format in a file?

description: Write data in YAML format in a file


code:
import functools
def change(row, col):
    '''changes the column of a pyodbc row

    returns modified pyodbc row
    '''
    return setattr(row, col, str(getattr(row, col)))

# partial function that specifies the 'foo' column
change_foo = functools.partial(change, col = 'foo')

if include_headers:
    f.writerow([d[0] for d in c.description])
    rows = c.fetchall()
    # modify the column in each row
    rows = map(change_foo, rows)
    for row in rows:
        f.writerow(row)

rawDescription: Cast Column as Text or Prefix with Apostrophe When Writing a CSV File in Python 2.7


code: newstring = "".join([s1[i] for i in lst])

rawDescription: How to construct a string by joining characters efficiently?

description: Construct a string by joining characters efficiently


code:
i = 2
left = sum(li[:i])
right = sum(li[i+1:])

rawDescription: Find sum of right and left hand of list element in python


rawDescription: Union of dict objects in Python

description: Union of dict objects in Python


code: df.groupby(lambda x: x/2).mean()

rawDescription: How to downsample a pandas dataframe

description: Downsample a pandas dataframe


rawDescription: Python swapping lists

description: Python swapping lists


code: merge = functools.partial(pd.merge, on=['org', 'name'])

rawDescription: Pandas: merge multiple dataframes and control column names?


rawDescription: Partioning non-unique entities into unique sets with Python


code:
from string import ascii_letters as letters
mystring
sorted((mystring.count(l),l) for l in letters)[:-5:-1]

rawDescription: Find amount of times that the chosen letters appear


code:
text = '15" approx. length from waist to hem, 26" waist#Measured from Small#Shell: 100% Polyester, Lining: 100% Polyester#Machine wash cold, tumble dry low#Imported'
matches = [line for line in text.split('#') if '%' in line]

rawDescription: Python non-greedy regex match with pattern in between


code:
url = "http://www.pullandbear.com/es/es/mujer/vestidos-c29016.html"
from selenium import webdriver

dr = webdriver.PhantomJS()
dr.get(url)

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(dr, 5).until(
    EC.presence_of_element_located((By.CLASS_NAME, "grid_itemContainer"))
)

rawDescription: How to retrieve the exact HTML as in a browser

description: Retrieve the exact HTML as in a browser


code:
def shutdown_server():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()

@app.route('/shutdown', methods=['POST'])
def shutdown():
    shutdown_server()
    return 'Server shutting down...'

rawDescription: How to stop flask application without using ctrl-c

description: Stop flask application without using ctrl-c


code:
from numpy import arange, newaxis
powers_of_two = 2**arange(4)[::-1]
(arange(2**4)[:, newaxis] & powers_of_two) / powers_of_two

rawDescription: Convert decimal range to Numpy array, with each bit being an array element


rawDescription: Calculation and construction of two dimensional array with nested loop


code:
a = Pokemon('charmander', 'fire')
a.name
a.poketype

rawDescription: Error with a simple program, printing error (python)


code:
# b.py
import pymc, a

training_pool = [0]
m = pymc.MCMC(a.model(training_pool))

rawDescription: import a module with parameter in python

description: Import a module with parameter in python


rawDescription: Delete Column in Pandas based on Condition


code:
for word, value in words_dict.items():
    if value == frequency:
        max_word_list += [word]

rawDescription: Dictionary Issue Python

description: Dictionary Issue Python


code:
plt.figure(0, figsize=(10, 10))
plt.clf() #clears figure

rawDescription: Numpy and matplotlib garbage collection

description: Numpy and matplotlib garbage collection


rawDescription: How to find floating point numbers in binary file with Python?

description: Find floating point numbers in binary file with Python


code: infos = [info.strip('\n :') in re.split(exp, contents_of_file)][1:]

rawDescription: Storing multiple lines from a file to a variable using a delimiter


code:
def my_prod(lst):
    return product(*[permutations(sub) for sub in  lst])

rawDescription: Python itertools get permutations and combinations of a list of lists


rawDescription: Removing a column from a DictField in MongoDB [Flask + MongoEngine]


code:
def __init__(self):
    ...
    self.amplitude = 10
    self.t = 0
    ...

rawDescription: How to update a realtime plot and use buttons to interact in pyqtgraph?

description: Update a realtime plot and use buttons to interact in pyqtgraph


code:
class A:
    d = {2:3}
    @classmethod
    def c(cls):
        print (cls.d)

class B(A):
    d = A.d.copy()
    d.update({0:1})

B.c()
A.c()

rawDescription: Class attribute overriding: keep parent class changes


rawDescription: combine list of dictionaries with same key

description: Combine list of dictionaries with same key


code:
ret_a = [t[1] for t in res.items()]
ret_b = [t[0] for t in res.items()]

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: y[mask][:, mask]

rawDescription: Restricting a sparse matrix to a subspace in scipy


rawDescription: __getitem__ for a list vs a dict

description: __getitem__ for a list vs a dict


code:
class Migration(migrations.Migration):

    dependencies = [
        ('characters', '0004_remove_mage_arcana'),
    ]

    operations = [
        migrations.DeleteModel(
            name='SpellDicePool',
        ),
        migrations.RemoveField(
            model_name='mage',
            name='spells',
        ),
        migrations.AddField(
            model_name='spell',
            name='contested',
            field=models.BooleanField(default=False),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='spell',
            name='contested_attribute',
            field=models.ForeignKey(related_name='spell_by_contested_attribute', default=None, to='characters.Attribute'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='spell',
            name='contested_skill',
            field=models.ForeignKey(related_name='spell_by_contested_skill', default=None, to='characters.Skill'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='spell',
            name='mage',
            field=models.ForeignKey(related_name='spell_by_mage', default=None, to='characters.Mage'),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='spell',
            name='resisted',
            field=models.BooleanField(default=False),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='spell',
            name='resisted_by_attribute',
            field=models.ForeignKey(related_name='dice_pools_by_resistance_attribute', default=None, to='characters.Attribute', choices=[('Mental', (('Intelligence', 'Intelligence'), ('Wits', 'Wits'), ('Resolve', 'Resolve'))), ('Physical', (('Strength', 'Strength'), ('Dexterity', 'Dexterity'), ('Stamina', 'Stamina'))), ('Social', (('Presence', 'Presence'), ('Manipulation', 'Manipulation'), ('Composure', 'Composure')))]),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='spell',
            name='rote_attribute',
            field=models.ForeignKey(related_name='spell_by_rote_attribute', default=None, to='characters.Attribute', choices=[('Mental', (('Intelligence', 'Intelligence'), ('Wits', 'Wits'), ('Resolve', 'Resolve'))), ('Physical', (('Strength', 'Strength'), ('Dexterity', 'Dexterity'), ('Stamina', 'Stamina'))), ('Social', (('Presence', 'Presence'), ('Manipulation', 'Manipulation'), ('Composure', 'Composure')))]),
            preserve_default=False,
        ),
        migrations.AddField(
            model_name='spell',
            name='rote_skill',
            field=models.ForeignKey(related_name='spell_by_rote_skill', default=None, to='characters.Skill', choices=[('Mental', (('Academics', 'Academics'), ('Computer', 'Computer'), ('Crafts', 'Crafts'), ('Investigation', 'Investigation'), ('Medicine', 'Medicine'), ('Occult', 'Occult'), ('Politics', 'Politics'), ('Science', 'Science'))), ('Physical', (('Athletics', 'Athletics'), ('Brawl', 'Brawl'), ('Drive', 'Drive'), ('Firearms', 'Firearms'), ('Larceny', 'Larceny'), ('Stealth', 'Stealth'), ('Survival', 'Survival'), ('Weaponry', 'Weaponry'))), ('Social', (('Animal Ken', 'Animal Ken'), ('Empathy', 'Empathy'), ('Expression', 'Expression'), ('Intimidation', 'Intimidation'), ('Persuasion', 'Persuasion'), ('Socialize', 'Socialize'), ('Streetwise', 'Streetwise'), ('Subterfuge', 'Subterfuge')))]),
            preserve_default=False,
        ),
    ]

rawDescription: So, I have a Django migrate error when removing classes and their subclasses at the same time, which appears as an sql syntax error, with sqlite3


code:
import math
def gcd(a, b):
    ndigits = int(math.log10(b)) + 1
    count = 0
    while b:
        a, b = b, a%b
        count += 1
    print(count)
    print("Lame's theorem holds?", count <= 5*ndigits)
    return a

rawDescription: counting-steps Euclidean algorithm program in python

description: Counting-steps Euclidean algorithm program in python


code:
# Some generic startup stuff
import sympy, sympy.galgebra.ga
metric = '1 0 0,0 1 0,0 0 1'
gamma_x,gamma_y,gamma_z = sympy.galgebra.ga.MV.setup('gamma_x gamma_y gamma_z',metric)

# Setup nice printing for the notebook
sympy.init_printing()
sympy.galgebra.ga.Format(ipy=True)
def MVlatex(mv, *args) :
    mv.base_to_blade()
    return '$$'+str(mv).replace(r'\W', r'\wedge').replace(r'\bm', r'\boldsymbol').replace(r'\lp',r'\left(').replace(r'\rp',r'\right)')+'$$'
sympy.galgebra.ga.MV._repr_latex_ = MVlatex

# Show a couple examples
display(gamma_x ^ gamma_y)
display( 3*gamma_x*gamma_y/2 + (gamma_z^gamma_x) )

rawDescription: Nice output for geometric algebra in ipython notebook


code:
n, _ = np.histogram(x, bins=xbins)
sy, _ = np.histogram(x, bins=xbins, weights=y)
sy2, _ = np.histogram(x, bins=xbins, weights=y*y)

rawDescription: Mean values depending on binning with respect to second variable


code:
class MyForm(forms.ModelForm):
  def __init__(self, request, *args, **kwargs):
    self._request = request
    super(MyForm, self).__init__(*args, **kwargs)

  def save(self, commit=False):
    obj = super(MyForm, self).save(commit=False)
    obj.sender = self._request.user
    if commit:
      obj.save()

    return obj

rawDescription: What's the cleanest way to add arbitrary data to ModelForm?


rawDescription: Creating nested dict using csv.DictReader


code:
print(cv_fit.toarray().sum(axis=0))
#[2 3 2 2]

rawDescription: Scikit Learn CountVectorizer

description: Scikit Learn CountVectorizer


code:
gl = globals()
gl.update({'f':f})

rawDescription: Exec, closures and scopes

description: Exec, closures and scopes


code: self.button = Button(self.Container, text="Get", command=curry(self.TestFunction, self.on_button()))

rawDescription: Python 3.4.4 settin argument in Tkinter?

description: Python 3.4.4 settin argument in Tkinter


code:
def ignore_none_valued_kwargs(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        newkwargs = dict((k,v) for (k,v) in d.iteritems() if not v is None)
        return f(*args, **kwargs)
    return wrapper

my_connect = ignore_none_valued_kwargs(psycopg2)
conn = my_connect(database=options.db, hostname=options.hostname, port=options.port)

rawDescription: Passing optional arguments from optparse


code:
def evens(n):
    return range(2, 2*n+1, 2)

rawDescription: Python Program that takes an integer and returns a list of n even integers


code: event.wait() # wait for event

rawDescription: Python chatserver - Unable to close server because of blocking call


code:
class Node(object):
    def __init__(self, name, branches):
        self.branches = branches # This is a list of Node objects
        self.value = 0
        self.name = name

    def __repr__(self):
        return '<Node {}>'.format(self.name)

rawDescription: Mapping a list of inputs to the lowest level of nested lists


code:
from skimage import data, transform
import numpy as np
import matplotlib.pyplot as plt

img = data.camera()

theta = np.deg2rad(10)
tx = 0
ty = 0

S, C = np.sin(theta), np.cos(theta)

# Rotation matrix, angle theta, translation tx, ty
H = np.array([[C, -S, tx],
              [S,  C, ty],
              [0,  0, 1]])

# Translation matrix to shift the image center to the origin
r, c = img.shape
T = np.array([[1, 0, -c / 2.],
              [0, 1, -r / 2.],
              [0, 0, 1]])

# Skew, for perspective
S = np.array([[1, 0, 0],
              [0, 1.3, 0],
              [0, 1e-3, 1]])

img_rot = transform.homography(img, H)
img_rot_center_skew = transform.homography(img, S.dot(np.linalg.inv(T).dot(H).dot(T)))

f, (ax0, ax1, ax2) = plt.subplots(1, 3)
ax0.imshow(img, cmap=plt.cm.gray, interpolation='nearest')
ax1.imshow(img_rot, cmap=plt.cm.gray, interpolation='nearest')
ax2.imshow(img_rot_center_skew, cmap=plt.cm.gray, interpolation='nearest')
plt.show()

rawDescription: 3d rotation on image

description: 3d rotation on image


code:
# this code assumes Python 3
def make_weighted_sum_fn(weights):
    """
    Given a list of weights, return a function which
      calculates a final weighted score
    """
    weights = list(weights)
    len_ = len(weights)
    def weighted_sum_fn(values):
        values = list(values)
        assert len(values) == len_
        return sum(w * v for w, v in zip(weights, values))
    return weighted_sum_fn

def average(lst):
    """
    Find the mean value of a list

    eg
        average([1., 2., 6.])   # => 3.

    If the list is empty, return 0.
    """
    if lst:
        return sum(lst) / len(lst)
    else:
        return 0.

def get_curves_fn(N):
    weights = [float(input("What is curve #{}? ".format(n))) for n in range(1, N + 1)]
    return make_weighted_sum_fn(weights)

def get_cat_scores(cat):
    return [
        float(f)
        for f in input("What is the {}th set of grades (space-delimited)? ".format(cat)).split()
    ]

def get_categories_scores(num_categories):
    return [get_cat_scores(cat) for cat in range(1, num_categories + 1)]

def main():
    N   = int(input("How many curves? "))
    cfn = get_curves_fn(N)

    while True:
        name = input("\nEnter student name (or Enter to quit): ").strip()
        if name:
            categories = get_categories_scores(N)
            final = cfn(average(cat) for cat in categories)
            print("{}'s final mark is {}".format(name, final))
        else:
            break

if __name__ == "__main__":
    main()

rawDescription: Find current grade with curve [Python]

description: Find current grade with curve [Python]


code:
app1 = Application([SomeServiceFactory()], tns=tns,
        in_protocol=Soap11(), out_protocol=Soap11())
app2 = Application([SomeServiceFactory()], tns=tns,
        in_protocol=Soap11(), out_protocol=Soap11())

rawDescription: Deploy multiple web services, i.e. multiple wsdl files, in python


code: M = loadtxt (filename, delimiter=delimiter) [R1:R2+1,C1:C2+1]

rawDescription: numpy: How to load a bounded (R1 C1 to R2 C2) matrix from file

description: Numpy: How to load a bounded (R1 C1 to R2 C2) matrix from file


code:
def foo(): x[x <= 3]+=3

dis.dis(foo)

rawDescription: Changing a list with a twist: whats going on behind the scenes


code: {key: set(value) for key, value in cities.items()}

rawDescription: Converting to a set dictionary in Python


code:
np.allclose(sps.vstack(csr_vecs).A, csr_stack(csr_vecs).A)
np.allclose(csr_stack(csr_vecs).A, lil_stack(lil_vecs).A)

rawDescription: mongodb to python sparse matrix, how to make it faster?

description: Mongodb to python sparse matrix, how to make it faster


code: response = input("What would you like to do next?")

rawDescription: Present blank screen, wait for key press -- how?


code:
def test(num):
    a = [1, 2, 3]
    if num in a :
        return True
    else :
        return False

rawDescription: Compare to multiple values in an if statement


code:
def process_onclick(value):
    m = re.search("window.open\('(.+?)'", value)
    if m:
        return m.group(1)

rawDescription: How can i use scrapy to parse links in JS?

description: Use scrapy to parse links in JS


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


rawDescription: Python - Should I be using string prefix r when looking for a period (full stop or .) using regex?


code: timeit("from linecache import getline; getline('afile', 4003) + getline('afile', 4004)", number=10**5)

rawDescription: Python fastest access to line in file

description: Python fastest access to line in file


rawDescription: Python: pairing up element from one list with every single element from other list


rawDescription: Python: Decode base64 multiple strings in a file


code:
from django.contrib.auth.backends import RemoteUserBackend

class MyRemoteUserBackend(RemoteUserBackend):

    MY_DOMAIN = 'my.domain.tld'

    def configure_user(self, user):
        user.email = '%s@%s' % (user.username, self.MY_DOMAIN)
        user.save()
        return user

rawDescription: Fill in Email When Authenticating Via LDAP in Django


code:
import re
regex = re.compile('i', flags=re.IGNORECASE)
txt = input("Enter text: ")
# re.sub() always searches from left, so we reverse txt using slice [::-1]
# to find the last match. Then we flip it again.
txt = regex.sub('', txt[::-1], 1)
txt = regex.sub('', txt[::-1], 1)
print(txt)

rawDescription: Remove first and last specific symbol

description: Remove first and last specific symbol


code:
import re

if re.match('\w{4} \d{4}\w{2}', ProductCode):
    message = 'Next Product'
else:
    message = 'Non-Standard Product Code'

rawDescription: how do I choose specific items from a list using python and save in a new list

description: Choose specific items from a list using python and save in a new list


code:
if self.returncode is None:
    _subprocess.WaitForSingleObject(self._handle,
                                    _subprocess.INFINITE)
    self.returncode = _subprocess.GetExitCodeProcess(self._handle)
return self.returncode

rawDescription: Is it necessary to call Popen.wait() to "clean up" after the Popen object?


code: shellreturn = shellreturn.decode()

rawDescription: Python split string by \n character

description: Python split string by \n character


code:
from fileinput import input
from sys import stdout

with open("changes.txt") as f:
    next(f)
    data = {int(r): {"st": int(st), "ed": int(ed), "val": val} for r, st, ed, val in map(str.split, f)}
    for ind, line in enumerate(input("test.txt"), 1):
        if ind in data:
            d = data[ind]
            new = line[:d["st"] - 1] + d["val"] + line[d["ed"]:]
            stdout.write(new)
        else:
            stdout.write(line)

rawDescription: change a value in a specific location in a text file in python

description: Change a value in a specific location in a text file in python


code:
dict[key].append(vals)
dict[key].sort()

rawDescription: Best way to implement 2-D array of series elements in Python

description: Implement 2-D array of series elements in Python


rawDescription: Turning off ticks in matplotlib for all plots (using rc)


rawDescription: How assignment works with python list slice


rawDescription: wxPython - wx.TextCtrl - forcing styles

description: WxPython - wx.TextCtrl - forcing styles


code:
df = pd.DataFrame(['hello', 'world'], columns=['words'])
df
df.words.str.contains(r'[hw]')
df.words.str.contains(r'he|wo')

rawDescription: Count occurrences of certain words in pandas dataframe


code:
df1
df2
df3 = pd.concat([df1, df2], axis=1)
df3.columns = ['population', 'population_movav']

rawDescription: Concatenating/Merging Data Frames and Editing column names - Python/Pandas


code:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

rawDescription: What are prevalent techniques for enabling user code extensions in Python?


rawDescription: PyQt4 WindowFlags don't close program

description: PyQt4 WindowFlags don't close program


code:
print(max(my_dictionary, key=lambda v: my_dictionary[v]['c']
     if isinstance(my_dictionary[v]['c'],int) else float("-inf")))

rawDescription: key in nested dictionary if it contains NaN value?

description: Key in nested dictionary if it contains NaN value


code: for index, row in enumerate(seats, start=1): ...

rawDescription: Finding consecutive values in a multidimensional array - python


code:
import clr
clr.AddReference("System.Xml")
from System.Xml import *

rawDescription: How do I reference classes using IronPython?

description: Reference classes using IronPython


code:
def dynamic_assertion(response, field, value):
    for item in response["items"]:
        for key in field:
            item = item[key] # go deeper into the nested dictionary
        if item != value:
            return False # raising an exception might be more Pythonic
    return True

rawDescription: Create Dynamic Python Dictionary Reference Path


code: index, match, text = tn.expect([eof])

rawDescription: Read until an only partially known line - Python


rawDescription: How to replace all occurrences of regex as if applying replace repeatedly

description: Replace all occurrences of regex as if applying replace repeatedly


code:
from sklearn.cluster import KMeans
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

img = cv2.imread('red_shirt.jpg')
height, width, dim = img.shape

rawDescription: Color detection of object in Image

description: Color detection of object in Image


code:
def common_count(t0, t1):
  "returns the length of the longest common prefix"
  for i, pair in enumerate(zip(t0, t1)):
    if pair[0] != pair[1]:
      return i
  return i

def group_by_longest_prefix(iterable):
  "given a sorted list of strings, group by longest common prefix"
  longest = 0
  out = []

  for t in iterable:
    if out: # if there are previous entries

      # determine length of prefix in common with previous line
      common = common_count(t, out[-1])

      # if the current entry has a shorted prefix, output previous
      # entries as a group then start a new group
      if common < longest:
        yield out
        longest = 0
        out = []
      # otherwise, just update the target prefix length
      else:
        longest = common

    # add the current entry to the group
    out.append(t)

  # return remaining entries as the last group
  if out:
    yield out

rawDescription: longest common sequence group

description: Longest common sequence group


code:
array = [['X', 'Y', 'Z'], [1, 2, 3], [4, 5, 6]]
return render_to_response('page2.html', {'array': json.dumps(array)})

rawDescription: Passing data to Google Charts with Django


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

dpi = 80
margin = 0.05 # (5% of the width/height of the figure...)
xpixels, ypixels = 800, 800

# Make a figure big enough to accomodate an axis of xpixels by ypixels
# as well as the ticklabels, etc...
figsize = (1 + margin) * ypixels / dpi, (1 + margin) * xpixels / dpi

fig = plt.figure(figsize=figsize, dpi=dpi)
# Make the axis the right size...
ax = fig.add_axes([margin, margin, 1 - 2*margin, 1 - 2*margin])

ax.imshow(np.random.random((xpixels, ypixels)), interpolation='none')
plt.show()

rawDescription: Display image with a zoom = 1 with Matplotlib imshow() (how to?)


rawDescription: Method for generating row-column arrays with other arrays


rawDescription: merge identity matrices in specific way

description: Merge identity matrices in specific way


code: {z[0]:list(z[1:]) for z in zip(list1,list2,list3)}

rawDescription: How to map multiple lists to one dictionary?

description: Map multiple lists to one dictionary


code:
app.windows_()
app.process
app.connect(title_re=u'^μTorrent.*(build \d+).*')
app.process

rawDescription: uTorrent Automation using pywinauto

description: UTorrent Automation using pywinauto


code: func_list = [f1, f2, f3, f4]

rawDescription: Python: pass a function call's list index as its own argument


code:
for animal in animals:
    if isinstance(animal, Mammal):
        ...
    elif isinstance(animal, Fish):
        ...
    else:
        ...

rawDescription: get the name of the class and wrap it in an if statement

description: Get the name of the class and wrap it in an if statement


code:
def toBinary(n):
    l = []
    while n:
        l.append(n & 1)
        n >>= 1
    return ''.join(map(str, reversed(l)))

rawDescription: Python algorithm for converting an integer to binary: questions about efficiency


code: ani = QPropertyAnimation(self,"color")

rawDescription: PySide QPropertyAnimation Not Starting

description: PySide QPropertyAnimation Not Starting


code:
class _Interactify(type):
    def __init__(cls, name, bases, d):
        super(_Interactify, cls).__init__(name, bases, d)
        for base in bases:
            for attrname in dir(base):
                if attrname in d: continue # If overridden, don't reset
                attr = getattr(cls, attrname)
                if type(attr) == types.MethodType:
                    if attrname.startswith("add_"):
                        setattr(cls, attrname, wrap_pylab_newplot(attr))
                    elif attrname.startswith("set_"):
                        setattr(cls, attrname, wrap_pylab_show(attr))

rawDescription: What are your (concrete) use-cases for metaclasses in Python?


code:
def solve(self):
    v = set()

    q = [(0, self)]
    i = 0
    while True:
        c = q[i]
        i += 1

        for el in c[1].next():
            t = el.tuple()

            if t not in v:
                if el.solved():
                    return c[0] + 1
                v.add(t)
                q.append((c[0] + 1, el))

rawDescription: Avoid a deepcopy when doing a BFS

description: Avoid a deepcopy when doing a BFS


code: reload(mymod)

rawDescription: Python meta-debugging

description: Python meta-debugging


code:
url     = 'http://HOST/createItem?name=NEW_JOB_NAME'
auth    = ('USER', 'PASS')
payload = '<project><builders/><publishers/><buildWrappers/></project>'
headers = {"Content-Type": "application/xml"}
r = requests.post(url, data=payload, auth=auth, headers=headers)

rawDescription: Creating a new Jenkins job with python Requests


rawDescription: What is the fastest way to do greedy set cover with Pandas?


code:
# combine the last two
def is_full(self):  # python functions/methods are usually lower case
    for row in self.data:  # no need to index everything like c
        if any(cell == ' ' for cell in row):  # any/all are convenient testers
            return False  # if you find even one, it's done.
    return True  # if you couldn't disqualify it, then it looks full

rawDescription: Python Check a 2d list for empty strings?


code: counts.E + counts.A

rawDescription: Pandas calcuating percentage in data summary


code:
my_buttons['new_button'] = Button(font_size=16, size_hint_y=None, height=100,
                                  text=i["dia"] + " - " + i["hora"])

rawDescription: Create variables dynamically inside loop in python


code:
def a(x,y,z):
    if x:
       return y
    else:
       return z

rawDescription: I cannot understand function comparisons in Python


code:
in_file = open("weather.json", "r")
result = json.load(self.in_file)
in_file.close()

rawDescription: Save app data in Weather App

description: Save app data in Weather App


code: indices = [i for i, c in enumerate(besedilo) if c == 'o']

rawDescription: Find indexes for a certain character in string


code:
df = pd.concat([my_series,my_series.index.to_series().str.split(expand=True)], axis=1).reset_index(drop=True)
df.rename(columns={'sample1': 'Score', 0: 'probe', 1: 'genes'})

rawDescription: How to convert Series index into two columns as a DataFrame

description: Convert Series index into two columns as a DataFrame


code: return {'timestamps': list_of_timestamps, 'values': list_of_values}

rawDescription: Best approach for extensible return object in python


code:
new_hdr = 'New Header: value'
hdr = old_hdr.split('\r\n') # This is a crappy hack. Parsing HTTP headers
hdr.insert(new_hdr, 2)      # is a [solved problem][1].
send_hdr = '\r\n'.join(hdr)
pkt[TCP].payload = send_hdr

rawDescription: how to add http headers to a packet sniffed using scapy

description: Add http headers to a packet sniffed using scapy


code:
class UnixStreamHTTPConnection(httplib.HTTPConnection, object):
    def __init__(self, *args, **kwargs):
        self.socketpath = kwargs.pop('socketpath')
        super(UnixStreamHTTPConnection, self).__init__(*args, **kwargs)

    def connect(self):
        self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self.sock.connect_ex(self.socketpath)

class UnixStreamTransport(xmlrpclib.Transport, object):
    def __init__(self, *args, **kwargs):
        self.socketpath = kwargs.pop('socketpath')
        super(UnixStreamTransport, self).__init__(*args, **kwargs)

rawDescription: Use Python xmlrpclib with unix domain sockets?


rawDescription: Sorting a list of tuples, where each tuple consists of a string and a set


code: q, r = divmod(x, y) # ((x - x%y)/y, x%y) Invariant: div*y + mod == x

rawDescription: Is it pythonic for a function to return multiple values?


code: b = {str(i+1): {'name': j.split(',')[0], 'qty': sum([int(qty['qty']) for qty in a.values() if (qty['name']==j.split(',')[0]) and (qty['sub']==j.split(',')[1:])]), 'sub': j.split(',')[1:]} for i, j in enumerate(set(data))}

rawDescription: Exclude repeated values from a dictionary and increment the 'qty' field accordingly


code: foo = "/directory/"

rawDescription: Flask Odd Behavior w/ Folder Creation/File Uploading


code:
import enemies

class Encounter:
    def __init__(self):
        self.counter = 1
        self.number = 0
        self.who = "We've encountered no one."

    def forward(self):
        if self.counter == 1:
            enemies.knightofni(self)
        elif self.counter == 2:
            enemies.frenchman(self)
        else:
            self.number = 42
            self.who = "We've found the Grail!"
        self.counter += 1

knight = Encounter()
for i in range(4):
    print(str(knight.number) + " " + knight.who)
    knight.forward()

rawDescription: Change object's variable from different file


code: cartesian_tuples = list(map(list, list(product(perms, repeat=3))))

rawDescription: How to generate all possible combinations from all permutations?

description: Generate all possible combinations from all permutations


code:
import pandas as pd
areas = pd.DataFrame({'Com':[1,2,3], 'Ind':[4,5,6]})
demand = pd.DataFrame({'Water':[4,3],
                       'Elec':[8,9]}, index=['Com', 'Ind'])

areas = pd.DataFrame({'area': areas.stack()})
areas.index.names = ['Edge', 'Type']
both = areas.reset_index(1).join(demand, on='Type')
both['Elec'] = both['Elec'] * both['area']
both['Water'] = both['Water'] * both['area']
both.reset_index(inplace=True)
both = both.pivot_table(values=['Elec', 'Water'], rows='Edge', cols='Type')
both = both.reorder_levels([1,0], axis=1)
both = both.reindex(columns=both.columns[[0,2,1,3]])
print(both)

rawDescription: Pandas: join with outer product

description: Pandas: join with outer product


code: df.xs('B', axis=1)

rawDescription: Benefits of panda's multiindex?

description: Benefits of panda's multiindex


code:
for c_i in range(k):
    c[c_i] = np.mean(data[label == c_i, :], axis=0)

rawDescription: A quick way to compute the average of multiple timeseries?


code:
from collections import Counter

def merge_value(acc, x):
    acc.update(x)
    return acc

def merge_combiners(acc1, acc2):
    acc1.update(acc2)
    return acc1

aggregated_counts_ = (data
    .combineByKey(Counter, merge_value, merge_combiners)
    .mapValues(lambda cnt: (cnt, sum(cnt.values()))))

aggregated_counts_.collect()
## [('a', (Counter({'u': 1, 'v': 1}), 2)), ('b', (Counter({'w': 1, 'x': 2}), 3))]

rawDescription: Apache Spark CombineByKey with list of elements in Python


code:
try:
    module_path = modules[TMP_Service.__module__].__file__
except AttributeError:
    # maybe py2exe went by
    from sys import executable
    module_path = executable

module_file = splitext(abspath(module_path))[0]
TMP_Service._svc_reg_class = '%s.%s' % (module_file, TMP_Service.__name__)

rawDescription: pywin32 service start error: no module named 'tmp'

description: Pywin32 service start error: no module named 'tmp'


code:
for lastlast, last, value in triplets(my_sequence):
    do_something(lastlast, value)

rawDescription: How can you manipulate the iterator in a for loop in python?

description: Manipulate the iterator in a for loop in python


rawDescription: Indexing a pandas dataframe by integer

description: Indexing a pandas dataframe by integer


code: map( self.createMatcher( REGEX ), mySetOfStrings )

rawDescription: Equivalent of assertRegexMatches in python 2.4


code:
def removeVowels(word):
    letters = []            # make an empty list to hold the non-vowels
    for char in word:       # for each character in the word
        if char.lower() not in 'aeiou':    # if the letter is not a vowel
            letters.append(char)           # add it to the list of non-vowels
    return ''.join(letters) # join the list of non-vowels together into a string

rawDescription: string replace vowels in python?

description: String replace vowels in python


code:
canonical_ids = set()
canonical_objs = {}
canonical_tuples = {}

def canonical_object(obj):
    if id(obj) in canonical_ids:
        return obj
    if isinstance(obj, tuple):
        operator, left_operand, right_operand = map(canonical_object, obj)
        if operator in {'+', '*'} and id(left_operand) > id(right_operand):
            left_operand, right_operand = right_operand, left_operand
        obj = operator, left_operand, right_operand
        canon_obj = canonical_tuples.setdefault(tuple(map(id, obj)), obj)
    else:
        canon_obj = canonical_objs.setdefault(obj, obj)
    canonical_ids.add(id(canon_obj))
    return canon_obj

rawDescription: Comparing data flow graphs quickly in Python


code:
from MyFuncs import utilFunctions

utilFunctions.aFunctionYouCode()

rawDescription: How to create a functions py and call those functions?

description: Create a functions py and call those functions


code:
for i in range(3):
    if i == 1:
        print(i)
        break
else:
    print('Through')

for i in range(3):
    if i == 5:
        print(i)
        break
else:
    print('Through')

rawDescription: Python Programming for Absolute Beginner Chapter 5 Challenge 4


code: list(map(lambda l,v: l.append(v), (list1, list2), func()))

rawDescription: Appending the return values to a set of list directly


code:
unpaired = [1, 3, 5, 7, 8]
paired = [(2,4), (6,9)]

print(list(yourDict.values()))

rawDescription: How to store values in list based on another list and tuple

description: Store values in list based on another list and tuple


code:
AllSands = ["GREEN", "RED", "PINK", "BLACK", "WHITE", "ORANGE", "PURPLE", "BROWN", "GREY"]
random.shuffle(AllSands)
found_sand = AllSands.pop()  # Each time you call pop, you "find" a new value

rawDescription: Take a string out of a tuple - python

description: Take a string out of a tuple - python


rawDescription: Converting data and time columns in csv to relative time


code:
import urllib2
# that's really cool!
IP = urllib2.urlopen("http://ipinfo.io/ip").read().strip()

rawDescription: How to use a bash variable in python

description: Use a bash variable in python


code:
lambdafunc = lambda x: pd.Series([x['mytime'].hour,
                                  x['mydate'].isocalendar()[1],
                                  x['mydate'].weekday()])

newcols = df.apply(lambdafunc, axis=1)
newcols.columns = ['hour', 'weekday', 'weeknum']
newdf = df.join(newcols)

rawDescription: Add Multiple Columns to Pandas Dataframe from Function


code:
values = (n.foo(args) for n in L) # this is a generator expression
# it is similar to a list comprehension, but doesn't compute or store
# everything immediately

def keyfunc(x):
  return ClassFred.objects.get(arg1=x)

result = min(values, key=keyfunc)

rawDescription: Is this control structure a code smell?

description: Is this control structure a code smell


rawDescription: getting rid of some elements that contain just white space in a list

description: Getting rid of some elements that contain just white space in a list


rawDescription: How to declare an array in python

description: Declare an array in python


code:
d = { "id" : "abcde",
    "key1" : "blah",
    "key2" : "blah blah",
    "nestedlist" : [
    { "id" : "qwerty",
        "nestednestedlist" : [
        { "id" : "xyz", "keyA" : "blah blah blah" },
        { "id" : "fghi", "keyZ" : "blah blah blah" }],
        "anothernestednestedlist" : [
        { "id" : "asdf", "keyQ" : "blah blah" },
        { "id" : "yuiop", "keyW" : "blah" }] } ] }

def fun(d):
    if 'id' in d:
        yield d['id']
    for k in d:
        if isinstance(d[k], list):
            for i in d[k]:
                for j in fun(i):
                    yield j

rawDescription: Find all occurences of a key in nested python dictionaries and lists


rawDescription: Indentation of pformat() output

description: Indentation of pformat() output


code:
d = defaultdict(int)
for x in xs: d[x] += 1

rawDescription: python histogram one-liner

description: Python histogram one-liner


code:
{u'Monday, June 09': ['http://www.afl.com.au/match-centre/2014/12/melb-v-coll'],
 u'Sunday, June 08': ['http://www.afl.com.au/match-centre/2014/12/gcfc-v-syd',
                      'http://www.afl.com.au/match-centre/2014/12/fre-v-adel',
                      'http://www.afl.com.au/match-centre/2014/12/nmfc-v-rich']}

rawDescription: Extracting data from a web page using BS4 in Python


code:
c.tobytes()
bytearray(c)

rawDescription: Is it possible to get a proxy onto a bytearray?


rawDescription: Plot (x, y, z) triples on 2d plane with a colormap


code:
def reader(fd):
    with os.fdopen(fd, bufsize=bufsize) as f:
        while True:
            data = f.read(bufsize)
            if not data:
                break
            chomp(data)

rawDescription: Flushing a pipe (os.pipe) before closing


code:
[('Nancy', 'Hip-hop extravaganza tonight 9pm at The Firetrap!')]
[('Mike', "I'd gladly say it again, Hi")]
[('Mike', 'Hi'),
 ('Joe', 'Like Mike said, Hi.'),
 ('Mike', "I'd gladly say it again, Hi"),
 ('Nancy', 'Hip-hop extravaganza tonight 9pm at The Firetrap!')]
[('Mike', 'Hi'),
 ('Joe', 'Like Mike said, Hi.'),
 ('Mike', "I'd gladly say it again, Hi"),
 ('Nancy', 'Hip-hop extravaganza tonight 9pm at The Firetrap!'),
 ('Clem', 'Yo.')]

rawDescription: How do I search a list that is located in a class?

description: Search a list that is located in a class


code:
class MyMessageView(BrowserPage):
    __call__ = ViewPageTemplateFile('read.pt')

rawDescription: Custom traversal and page templates

description: Custom traversal and page templates


code:
# Get all comments from a post
# Submission is a praw submission, obtained via:
r = redApi.getPraw()
submission = r.get_submission(submission_id='2zysz7') # (or some other submission id, found via https://www.reddit.com/r/test/comments/2zysz7/ayy/ - the thing after /comments/)
comments = redApi.getComments(submission)

rawDescription: Get all comments from a specific reddit thread in python


rawDescription: How to set hierarchy on Django objects of the same class?

description: Set hierarchy on Django objects of the same class


code:
class Cart(models.Model):
    ...
    item.description = unicode(variation)

rawDescription: How to break the item name and size in Django Cartridge cart page?

description: Break the item name and size in Django Cartridge cart page


code:
df
ignorelist = ['grey.caulfu@ymail.com','deren.e.torcs87@gmail.com']
ignorere = '|'.join(ignorelist)
df[~df.From.str.contains(ignorere)]

rawDescription: Removing rows in a pandas DataFrame where the row contains a string present in a list?


code:
# default with a level of 0, and an indent of 4 characters
def write(p, depth=0, indent=4):
    if p==None:
        return
    # here we multiply the level by the number of indents
    # and then you multiply that number with a space character
    # which will magically show as that number of spaces.
    print("{}{}".format(" "*(indent*depth), p.value))
    if p.down!=None:
        # then you do not need your print(…, end='') hack
        # simply increase the depth
        write(p.down, depth=depth+1, indent=indent)
    # and for siblings, do not increase the depth
    write(p.right, depth=depth, indent=indent)

rawDescription: Print tree with indentations

description: Print tree with indentations


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

x, y = np.meshgrid(np.linspace(0, 5, 100), np.linspace(0, 5, 100))
f = x ** y
g = y ** x
cs = plt.contour(x, y, (f - g))
for collection in cs.collections:
    paths = collection.get_paths()
    for path in paths:
        print(path.vertices.shape)

plt.show()

rawDescription: Get levels (contour) of a scalar field (Matplotlib / Python)


code:
to_sql_k(pandas_sql, df2save, 'tmp',
        index=True, index_label='id', keys='id', if_exists='replace')

rawDescription: Python Pandas to_sql, how to create a table with a primary key?


code:
def setDelegate(self, delegate):
    self.delegate = delegate

rawDescription: Python Delegate Pattern - How to avoid circular reference?


rawDescription: Python: sorting string numbers not lexicographically


rawDescription: Calling the 'hex' builtin from the python C API


code:
for name in BtnLst:
    button = Checkbutton(frame, text=name, onvalue = 1, offvalue = 0, height=1, width = 10)
    button.pack(side=LEFT)

rawDescription: Can I use a loop to quicky produce x amount of checkbuttons?

description: Use a loop to quicky produce x amount of checkbuttons


code:
from wadofstuff.django.serializers.json import Serializer
class BetterSerializer(Serializer):
    """
    Convert a queryset to JSON.
    """
    def end_serialization(self):
        """Output a JSON encoded queryset."""
        self.options.pop('stream', None)
        self.options.pop('fields', None)
        self.options.pop('excludes', None)
        self.options.pop('relations', None)
        self.options.pop('extras', None)
        simplejson.dump(self.objects, self.stream, cls=MyJSONEncoder,
            **self.options)

rawDescription: Changing default date printing format in python


code: final_result = dict((frozenset(A, B, C), [x, y, z]) for A, B, C, x, y, z in result)

rawDescription: AMPL vs. Python - Importing tables (multi-dimensional dictionaries?)


code:
import pandas as pd
import csv

def read_only_csv(fle, keep, col,sep=",", **kwargs):
    with open(fle) as f:
        return pd.DataFrame.from_records((r for r in csv.reader(f, delimiter=sep) if r[col] == keep),
                                       **kwargs)

df = read_only_csv("test.txt", "A", 0, sep=" ",columns=['a', 's', 'd', 'f'])

rawDescription: Skip certain lines from file using Python Pandas


code:
vals = np.arange(9).reshape(3,3)
df1 = pd.DataFrame(vals, columns=list('def'), index=list('abc'))
df2 = pd.DataFrame(vals, columns=list('efd'), index=list('bac'))

rawDescription: Apply permutation matrix to pandas DataFrame


code:
import operator
sum(map(operator.mul, topo[:-1], topo[1:]))

rawDescription: Can this be written as a python reduce function?


rawDescription: Split file and turn it into dictionary in python


code:
if c.getresponse().status == 200:
   print('web site exists')

rawDescription: Checking if a link is active from an array


code:
from sqlobject.sqlbuilder import IN
TableClass.select(IN(TableClass.q.id, [1, 2, 4]))

rawDescription: how to do 'select in' operation in sqlobject

description: Do 'select in' operation in sqlobject


code:
if len(sentence) <= 1:
    return True

rawDescription: Better approach to check if a sentence is a palindrome in Python


code:
combined = df.apply(lambda x: pd.to_datetime(x['Date'], dayfirst=True) + timedelta(hours=int(x['hour'])), axis=1)
combined

rawDescription: How to rearrange a python pandas dataframe?

description: Rearrange a python pandas dataframe


rawDescription: Spawn subprocess that expects console input without blocking?


code:
def tetrahedron_volume(a, b, c, d):
    return np.abs(np.einsum('ij,ij->i', a-d, np.cross(b-d, c-d))) / 6

from scipy.spatial import Delaunay

pts = np.random.rand(10, 3)
dt = Delaunay(pts)
tets = dt.points[dt.simplices]
vol = np.sum(tetrahedron_volume(tets[:, 0], tets[:, 1],
                                tets[:, 2], tets[:, 3]))

rawDescription: Volume of convex hull with QHull from SciPy


rawDescription: Pandas groupby two columns then get dict for values


code:
updated_rows = (
    session.query(YourTable)
    .filter(YourTable.your_field.like('%est%'))
    .update({YourTable.your_field: func.replace(YourTable.your_field, 'from_str', 'to_str')},
            synchronize_session=False)
    )
print("Updated {} rows".format(updated_rows))

rawDescription: MySQL string replace using SQLAlchemy

description: MySQL string replace using SQLAlchemy


rawDescription: Row counting with conditional range

description: Row counting with conditional range


rawDescription: Check if current thread is main thread, in Python


code:
def find_dupe(lists, target):
    seen = set()
    for lst in lists:
        for item in lst:
            if item == target and item in seen:
                return True
            seen.add(item)

rawDescription: Find duplicate element in a list of lists


code: results = [t.age for t in mylist if t.person_id == 10]

rawDescription: Select value from list of tuples where condition


code:
import re
from bs4 import BeautifulSoup

data = """

 Name of Article

First Paragraph I want

More Html I'm interested in

 Subheading in the article I also want

Even more Html i want to pull out of the document.

 References

Html I do not want...

"""
soup = BeautifulSoup(data, "lxml")

references = soup.find("h2", text=re.compile("References"))
for elm in references.find_next_siblings():
    elm.extract()
references.extract()

print(soup)

rawDescription: Cutting/Slicing an HTML document into pieces with BeautifulSoup?


rawDescription: Print current call stack from a method in Python code


code: ['hello']

rawDescription: Python partially apply a string equality function


code:
prs = Person.objects.create(name="Tom")
GroupMembers.objects.create(person=prs, group=grp, is_main_user=True)

rawDescription: Getting the first item item in a many-to-many relation in Django


code:
d = {i+1:v for i,v in enumerate(zip(minValueRange, maxValueRange))}
d

rawDescription: Python: How to create new variable in each iteration of a for loop?


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

top10 = pd.DataFrame({'amount' : - np.sort(np.random.rand(10))})
bottom10 = pd.DataFrame({'amount' : np.sort(np.random.rand(10))[::-1]})

# Create figure and axes for top10
fig = plt.figure()
axt = fig.add_subplot(1,1,1)
axb = fig.add_subplot(1,1,1)

# Plot top10 on axt
bar_red = top10.plot.barh(color='red', edgecolor='k', align='edge', ax=axt, legend=False, picker=True)
# Plot bottom10 on axb
bar_green = bottom10.plot.barh(color='green', edgecolor='k', align='edge', ax=axb, legend=False, picker=True)

#add event handler
def onpick(event):
    if isinstance(event.artist, Rectangle):
        print("got the artist", event.artist)

fig.canvas.mpl_connect('pick_event', onpick)
plt.show()

rawDescription: matplotlib pick_event doesn't work for barh?

description: Matplotlib pick_event doesn't work for barh


code:
my_sheet = MyWorksheet()
my_sheet.add_worksheet("Listky_obce_nad_300")

my_sheet.create_footer("Listky_obce_nad_300", suma, starting, flag)

rawDescription: Using "object" of mainfile, in function saved in other file


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

browser = webdriver.Chrome()  # or webdriver.Firefox(), or webdriver.PhantomJS() or etc.
wait = WebDriverWait(browser, 10)

browser.get('https://www.indiegogo.com/projects/protest-the-hero-new-album--3#/')

# waiting for the frame to become present
frame = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "#vimeoPlayer")))
browser.switch_to.frame(frame)

# get video url
url = browser.find_element_by_tag_name("video").get_attribute("src")
print(url)

browser.close()

rawDescription: Video url cannot be found when scraping page


code:
def hello():
    ...

hello = decorator_factory(...)(hello)

rawDescription: Understanding the difference between these two decorators


code:
rows = root.clipboard_get().split('\n')
rows = [row.strip() for row in rows]    # removes leading and trailing whitespace from each row
print(rows)
print(rows[0])    # the first row
print(rows[1])    # the second row

rawDescription: Create variables no matter the nr of rows of the data in clipboard


code: order_dict = dict((x, i) for i, x in enumerate(ordered_branches))

rawDescription: Sorting the contents of one list via the contents of another (Python)


code: X_2nd_order = (X_1hot[:, np.newaxis, :] * X_1hot[:, :, np.newaxis]).reshape(len(X_1hot), -1)

rawDescription: How can an interaction design matrix be created from categorical variables?


code:
class DependentModel(models.Model):

    def threshold_default(model_instance=None):
        if model_instance is None:
            return 10
        return model_instance.number*10

    number = models.IntegerField(null=True, blank=True, default=10)
    threshold = FieldDepends(models.IntegerField)(null=True, blank=True, default=threshold_default,editable=False)

rawDescription: Simple multiplication in model's attribute django?


code:
if __name__ == "__main__":
   f = open('test.txt','w+')
   output = main() # Notice how we assign the returned item to a variable
   f.write('line 1: ' + output[item1]) # We refer to the dictionary we just created.
   f.write('line 2: ' + output[item2]) # Same here
   f.close()

rawDescription: passing dictionaries to other functions

description: Passing dictionaries to other functions


code:
class monster():
    def __init__(self,health):
        self.health = health

    def attack(self):
        return random.randint(5,15)

rawDescription: random.randint function isnt working the way i would like it to

description: Random.randint function isnt working the way i would like it to


code:
@main.route('/search/', methods=['GET', 'POST'])
def search():
    form = SearchForm()
    if form.validate_on_submit():
        return redirect(url_for('.view_results', data=request.form), code=303)
    return render_template('search.html', form=form)

rawDescription: redirect data to the next view in Flask

description: Redirect data to the next view in Flask


code:
[('a', 'b', 'letters-letters'),
 ('a', 'c', 'letters-letters'),
 ('a', 'here', 'letters-others'),
 ...
 ('two', 'here', 'numbers-others'),
 ('two', 'there', 'numbers-others'),
 ('two', 'one', 'numbers-numbers')]

rawDescription: Combinations between values of lists

description: Combinations between values of lists


code:
for bullet in self.bullets:
    bullet_image.blit(bullet.x, bullet.y)
    bullet.x += 5

rawDescription: Create many classes and be able to reference to them


code:
def unstuff(self, s):
    return s.replace('\xFE\xDC', '\xFC').replace('\xFE\xDD', '\xFE').replace('\xFE\xDE', '\xFE')
def stuff(self, s):
    return s.replace('\xFC', '\xFE\xDC').replace('\xFD', '\xFE\xDD').replace('\xFE', '\xFE\xDE')

rawDescription: Octet (byte) stuffing and unstuffing, i.e. replacing one byte with two or v.v


code:
from itertools import product

def print_good_points(p, dimensions=7):
    for coords in product(range(p), repeat=dimensions):
        if isagoodpoint(*coords):
            print(*coords)

rawDescription: How can I get rid of multiple nested for loops?

description: Get rid of multiple nested for loops


rawDescription: Django foreignkey query

description: Django foreignkey query


code:
1.  ### this is a comment
2.  # this call outputs an xml stream of the current parameter dictionary.
3.  # wow another comment

rawDescription: Python regular expression for a comment in a long string


code:
return render(request, 'my_form.html', {'param1': 'Parameter 1',
                                        'param2': 'Parameter 2'})

rawDescription: Redirect to external url with parameters in django


code:
z = intern(x)
id(z)

rawDescription: Why does the "is" keyword have a different behavior when there is a dot in the string?


code:
stack_df = df.set_index(['Names', 'Gender']).stack().to_frame().reset_index()
stack_df.columns = ['Names','Gender','Month', 'Value']

rawDescription: Groupby in Pandas yields Groupby Object rather than Dataframe


code:
counts = Counter()
for name in usernames:
    public_tweets = api.user_timeline(name, count=10)
    for tweet in public_tweets:
        urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', tweet.text)
        for url in urls:
            link = requests.head(url, allow_redirects=True).url  # follow redirects to the end
            domain = get_tld(link)
            counts[domain] += 1

rawDescription: Collections Counter not working

description: Collections Counter not working


code:
A = np.arange(12,dtype=float).reshape(3,4)
X = np.indices(A.shape).reshape(2,-1)
dt=np.dtype([('row',int), ('col',int), ('value',float)])
X1 = np.zeros(X.shape[1], dtype=dt)
X1['row']=X[0,:]
X1['col']=X[1,:]
X1['value']=A.flatten()
X1
X1[10]

rawDescription: Numpy: vector of indices and value

description: Numpy: vector of indices and value


code: {'WebAddress': [], 'Address': [], 'Surname': [], 'Name': [], 'Telephone': []}

rawDescription: Creating vertical dictionary from text file


code:
def draw(self, renderer):
    xs3d, ys3d, zs3d = self._verts3d
    xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
    self.set_data(xs, ys)
    lines.Line2D.draw(self, renderer)

rawDescription: Dynamic Point Manipulation in 3D Matplotlib


code: [item for ratio, item in inputlist]

rawDescription: Python values out of list

description: Python values out of list


rawDescription: Pygame How to use walking animations

description: Pygame How to use walking animations


rawDescription: How to follow on a button click in Django?

description: Follow on a button click in Django


code:
import csv

stats =  {
    "attackrange": 150,
    "mpperlevel": 45,
    "mp": 105.6,
    "attackdamage": 60.376,}

headers =['attackdamage','attackrange', 'mp', 'mpperlevel']

with open('output.csv', 'wb') as f:
    writer = csv.DictWriter(
        f, headers, delimiter=',', lineterminator='\n', )
    writer.writeheader()
    writer.writerow(stats)

rawDescription: Python Program to convert complicated json into csv for a complete beginner


code:
sql = "SELECT DATE_ADD(MAKEDATE(y, 1), INTERVAL w WEEK) as date, d FROM test.t"
df = pd.read_sql(sql, engine)
print(df)

rawDescription: pandas.read_sql and interpreting dates specified as weeks

description: Pandas.read_sql and interpreting dates specified as weeks


code:
def login_user(request):
    logout(request)
    username = password = ''
    if request.POST:
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)
        if user is not None and user.is_active:
            login(request, user)
            return HttpResponseRedirect(reverse('app:view'))
    return render_to_response('login.html', context_instance=RequestContext(request))

rawDescription: Specify `next` url passed to login view by Django login_required decorator


code:
def iter_data(data):
    for entry in data:
        for score in entry['scores']:
            yield entry['mood'], entry['id'], score

rawDescription: JSON to Stacked DataFrame

description: JSON to Stacked DataFrame


code:
from PyQt4 import QtGui, QtCore

class DockContents(QtGui.QWidget):
    _sizehint = None

    def setSizeHint(self, width, height):
        self._sizehint = QtCore.QSize(width, height)

    def sizeHint(self):
        print('sizeHint:', self._sizehint)
        if self._sizehint is not None:
            return self._sizehint
        return super(MyWidget, self).sizeHint()

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        self.setCentralWidget(QtGui.QTextEdit(self))

        self.dock = QtGui.QDockWidget('Tool Widget', self)
        self.addDockWidget(QtCore.Qt.LeftDockWidgetArea, self.dock)

        contents = DockContents(self)
        contents.setSizeHint(400, 100)
        layout = QtGui.QVBoxLayout(contents)
        layout.setContentsMargins(0, 0, 0, 0)
        self.toolwidget = QtGui.QListWidget(self)
        layout.addWidget(self.toolwidget)

        self.dock.setWidget(contents)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 600, 400)
    window.show()
    sys.exit(app.exec_())

rawDescription: pyqt : resize qdockwidget in maya

description: Pyqt : resize qdockwidget in maya


code:
from operator import itemgetter
[list(x) for x in zip(*sorted(zip(list1, list2), key=itemgetter(0)))]

rawDescription: python sorting two lists

description: Python sorting two lists


rawDescription: Summing over lists in python - is there a better way?


code:
from itertools import permutations, combinations
S={-4,-2,1,2,5,0}
[x for x in permutations(S,3) if sum(x) == 0]
[x for x in combinations(S,3) if sum(x) == 0]

rawDescription: Finding all combinations of length 3 from a set of numbers such that sum(combination) is 0


code:
def interpolate(l):
    last = None
    count = 0
    for num in l:
        if num is None:
            # count the number of gaps
            count += 1
            continue
        if count:
            # fill a gap based on the last seen value and the current
            step = (num - last) / float(count + 1)
            for i in xrange(count):
                yield last + int(round((1 + i) * step))
            count = 0
        last = num
        yield num

rawDescription: Python series algorithm

description: Python series algorithm


code:
def percent_change(x):
    if len(x):
        return (x[-1]-x[0])/x[0]

ser.resample('60T', base=30).apply(percent_change)

rawDescription: Python Pandas, Resampling data with pct_change function


rawDescription: Count all +1's in the file python

description: Count all +1's in the file python


code:
listo
headers, vals = zip(*listo)
headers
vals

rawDescription: Python - Write list of tuples horizontally to a text file


rawDescription: Converting String Date to Timestamp and back python


code:
temp = {}
for d in data:
    if d['id1'] not in temp:
        temp[d['id1']] = {}
    temp_d = temp[d['id1']]
    temp_d['price'] = temp_d.get('price', 0) + int(d['price'])
    temp_d.setdefault('colors', set()).add(d['color'])

temp

rawDescription: Merge values of same key, in list of dicts


code:
(X[:, 0] == 'rainy').ravel()
array([False, False, False,  True,  True,  True, False, False, False,
        True, False, False, False,  True], dtype=bool)

rawDescription: How to get a subset of rows from a NumPy Matrix based on a condition?

description: Get a subset of rows from a NumPy Matrix based on a condition


code:
master_matrix = pd.concat(list_of_dfs, axis=1)
master_matrix = master_matrix.values.reshape(master_matrix.shape, order='F')

rawDescription: Building a numpy array (matrix) from several dataframes


code:
from mrjob.compat import get_jobconf_value

class MRDataQuality(MRJob):

  def reducer(self, groupId, meterList):
    ...
    startDate = get_jobconf_value("my.job.settings.startdate")
    endDate = get_jobconf_value("my.job.settings.enddate")

    for meterId in meterList:
      sys.stderr.write("Querying: " + str(meterId) + "\n")
      df = extract_meter_data(table, meterId, startDate, endDate)

rawDescription: Passing parameters to reducer in MRjob

description: Passing parameters to reducer in MRjob


rawDescription: python pyfits, reading header information and using in caculation

description: Python pyfits, reading header information and using in caculation


code:
import binascii
bin(int(binascii.hexlify('hello'), 16))

rawDescription: Convert binary to ASCII and vice versa

description: Convert binary to ASCII and vice versa


code:
class Actor(models.Model):
    actorid = models.AutoField(primary_key=True)
    name = models.CharField(max_length=250)
    sex = models.CharField(max_length=1)

    @classmethod
    def director_list(cls):

        directors_available  = set (
            d.actorid
            for movie in Movie.objects.filter(director__is_null = False)
            for d in movie.director.all()
        )
        actors_directors     = Actor.objects.filter(actorid__in = list(directors_available))

        return actors_directors

rawDescription: Access many-to-many related to the same model


code:
import win32com.client
ac = win32com.client.Dispatch("Access.Application")
ac.Visible=True
ac.OpenCurrentDatabase("<mydirectory>\\testdb.accdb")
ac.DoCmd.RunMacro('MacroName')

ac.DoCmd.CloseDatabase
ac = None

rawDescription: Python code for running ms-Access Module Subroutine


code:
import socket

from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23
from ssl import SSLContext  # Modern SSL?
from ssl import HAS_SNI  # Has SNI?

from pprint import pprint

def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
                    ca_certs=None, server_hostname=None,
                    ssl_version=None):
    context = SSLContext(ssl_version)
    context.verify_mode = cert_reqs

    if ca_certs:
        try:
            context.load_verify_locations(ca_certs)
        # Py32 raises IOError
        # Py33 raises FileNotFoundError
        except Exception as e:  # Reraise as SSLError
            raise SSLError(e)

    if certfile:
        # FIXME: This block needs a test.
        context.load_cert_chain(certfile, keyfile)

    if HAS_SNI:  # Platform-specific: OpenSSL with enabled SNI
        return (context, context.wrap_socket(sock, server_hostname=server_hostname))

    return (context, context.wrap_socket(sock))

hostname = 'www.google.com'
print("Hostname: %s" % (hostname))

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((hostname, 443))

(context, ssl_socket) = ssl_wrap_socket(s,
                                       ssl_version=2,
                                       cert_reqs=2,
                                       ca_certs='/usr/local/lib/python3.3/dist-packages/requests/cacert.pem',
                                       server_hostname=hostname)

pprint(ssl_socket.getpeercertchain())

s.close()

rawDescription: Getting certificate chain with Python 3.3 SSL module


code:
from fabric.api import execute
from fabfile import restart_apache2

execute(restart_apache2, roles = ['eu-west-1'])
execute(restart_apache2, hosts = ['apache2'])

rawDescription: Python Fabric decorator

description: Python Fabric decorator


code: return Polynomial(poly[0], poly[1], poly[2], poly[3], poly[4])

rawDescription: creating class instances from a text file in python

description: Creating class instances from a text file in python


code:
tx = graph.cypher.begin()

statement = "CREATE (:City {Name: {name}})"
for city_name in city_neighborhood_map.keys():
    tx.append(statement, {"name": city_name})

statement = "CREATE (:Neighborhood {Name: {name}})"
for neighborhood_name in neighborhood_names: # get all neighborhood names for this
    tx.append(statement, {name: neighborhood_name})

tx.commit()

rawDescription: Optimizing py2neo's cypher insertion

description: Optimizing py2neo's cypher insertion


code:
# I'd prefer lxml, but you need to work on xml module...
import xml.etree.ElementTree as ET
tree = ET.fromstring(s)

# since the SubNetwork node you're interested is the parent of parent of ManagedElementId
node = tree.find('.//ManagedElementId[@string="rbs064841"]/../../../')

rawDescription: How to extract part of xml file

description: Extract part of xml file


code:
import shlex
shlex.split('-axh --delete --delete-excluded')

rawDescription: Python: split and format space separated values in a string to use in subprocess.check_call


rawDescription: Replace space between a letter and a number with a comma?


code:
#mp_guard.py
"""tracks invocation by creating an environment variable; if that
variable exists when next called a loop is in progress"""

import os

class Brick(Exception):
    def __init__(self):
        Exception.__init__(self, "Your machine just narrowly avoided becoming"
                                 " a brick!")

if 'MP_GUARD' in os.environ:
    raise Brick

os.environ['MP_GUARD'] = 'active'

rawDescription: Preventing multiprocessing "runaway bugs"


code: y1, y2, y3, y4 = (x & 0xFFFFFFFF).to_bytes(4, 'big')

rawDescription: Fast way to split an int into bytes

description: Fast way to split an int into bytes


code:
tests=np.in1d(a, [58, 107, 20]).reshape(a.shape)
tests[1,1]                 # is the element of 'a' in the list [58, 107, 20]?

rawDescription: Comparing a numpy array object to multiple conditions


rawDescription: Compute number of dates between two string dates and return an integer


code: int(input("enter pitch {}".format(i + 1)))

rawDescription: Check variables against a dictionary, and print the dictionary contents remaining


rawDescription: Change embedded image type in APIC ID3 tag via Mutagen


code:
def annotate_plot(frame, plot_col, label_col, **kwargs):
    """
    Annotate the plot of a given DataFrame using one of its columns

    Should be called right after a DataFrame or series plot method,
    before telling matplotlib to show the plot.

    Parameters
    ----------
    frame : pandas.DataFrame

    plot_col : str
        The string identifying the column of frame that was plotted

    label_col : str
        The string identifying the column of frame to be used as label

    kwargs:
        Other key-word args that should be passed to plt.annotate

    Returns
    -------
    None

    Notes
    -----
    After calling this function you should call plt.show() to get the
    results. This function only adds the annotations, it doesn't show
    them.
    """
    import matplotlib.pyplot as plt  # Make sure we have pyplot as plt

    for label, x, y in zip(frame[label_col], frame.index, frame[plot_col]):
        plt.annotate(label, xy=(x, y), **kwargs)

rawDescription: Include labels for each data point in pandas plotting


code:
matcher = re.compile(r'--%s\r?\n(.*)\r?\n--%s' % (boundary, boundary))
parts = [ mime(part) for part in matcher.findall(body) ]

rawDescription: How to extract line 1 to line 3 which are in the middle of the document?

description: Extract line 1 to line 3 which are in the middle of the document


code: ['Project 01:', '\t- Task 01\n\t\t- Subtask 01\n\t\t- Subtask 02\n\t\t- Subtask 03', '\t- Task 02', '\t- Task 03']

rawDescription: Supporting subtasks in Taskpaper script

description: Supporting subtasks in Taskpaper script


code:
from collections import OrderedDict

data = {'r': [4,3],'t': [4,5,6], 'n': [1,6]}
tuples = data.items()
tuples.sort(key=lambda pair: len(pair[1]), reverse=True)

ordered = OrderedDict(tuples)

rawDescription: Python merge two dictionnaries

description: Python merge two dictionnaries


code:
def foo(**kwargs):
    txt = {}
    for k, v in kwargs.items():
        if v:
            txt[k] = v
    return txt

rawDescription: Basic Python metaprogramming: populating dictionaries?


code:
from mechanize import Browser

br0 = Browser()
br1 = Browser()

br0.open('http://www.example.com/')
br1.open('http://www.example.com/')

rawDescription: Mechanize with multiple pages

description: Mechanize with multiple pages


rawDescription: Is it possible to run a while loop and check for tkinter input in python 3


rawDescription: Rank of a variable in a counter

description: Rank of a variable in a counter


code:
m = s.apply(lambda x: x.month)
m.hist()

rawDescription: How to generate a bar chart of occurrences per month from a pandas Series?

description: Generate a bar chart of occurrences per month from a pandas Series


code:
class StatusTab(QtGui.QTabWidget):
    def __init__(self, parent=None):
        QtGui.QTabWidget.__init__(self, parent)
        layout = QtGui.QVBoxLayout(self)
        tab = QtGui.QWidget(self)
        layout1 = QtGui.QVBoxLayout(tab)
        self.procbar = QtGui.QProgressBar(tab)
        self.procbar.setStyleSheet("")
        self.procbar.setRange(0, 0)
        self.procbar.setValue(0)
        layout1.addWidget(self.procbar)
        self.addTab(tab, 'Upload Status')
        layout.addWidget(tab)
        ...

rawDescription: Progress bar will not work correctly if add more than one window(pyside)


code:
df = pd.DataFrame({'col1': list('abcdefghij'), 'col2': range(0, 50, 5)})
df['new_index'] = range(30, 20, -1)
df.set_index('new_index')

rawDescription: Change dataframe index values while keeping other column data same


code:
def populateListbox():
    lst = [...] #gathered inside
    listbox.insert("end", *lst)

btn = tk.Button(..., command = populateListbox)

rawDescription: how to allow Tkinter to generate a listbox from list input

description: Allow Tkinter to generate a listbox from list input


code:
"DC_Volt","FUNC:VOLT DC"
"DC_Curr","FUNC:CURR DC"
"AC_Volt","FUNC:VOLT AC"

rawDescription: How do I dump text file contents into dictionary

description: Dump text file contents into dictionary


code:
import PIL.Image
import Image
import ImageTk
from Tkinter import *

class ExampleApp(Frame):
    def __init__(self,master):
        Frame.__init__(self,master=None)
        self.x = self.y = 0
        self.canvas = Canvas(self,  cursor="cross")

        self.sbarv=Scrollbar(self,orient=VERTICAL)
        self.sbarh=Scrollbar(self,orient=HORIZONTAL)
        self.sbarv.config(command=self.canvas.yview)
        self.sbarh.config(command=self.canvas.xview)

        self.canvas.config(yscrollcommand=self.sbarv.set)
        self.canvas.config(xscrollcommand=self.sbarh.set)

        self.canvas.grid(row=0,column=0,sticky=N+S+E+W)
        self.sbarv.grid(row=0,column=1,stick=N+S)
        self.sbarh.grid(row=1,column=0,sticky=E+W)

        self.canvas.bind("<ButtonPress-1>", self.on_button_press)
        self.canvas.bind("<B1-Motion>", self.on_move_press)
        self.canvas.bind("<ButtonRelease-1>", self.on_button_release)

        self.rect = None

        self.start_x = None
        self.start_y = None

        self.im = PIL.Image.open("logo.png")
        self.wazil,self.lard=self.im.size
        self.canvas.config(scrollregion=(0,0,self.wazil,self.lard))
        self.tk_im = ImageTk.PhotoImage(self.im)
        self.canvas.create_image(0,0,anchor="nw",image=self.tk_im)

    def on_button_press(self, event):
        # save mouse drag start position
        self.start_x = self.canvas.canvasx(event.x)
        self.start_y = self.canvas.canvasy(event.y)

        # create rectangle if not yet exist
        if not self.rect:
            self.rect = self.canvas.create_rectangle(self.x, self.y, 1, 1, outline='red')

    def on_move_press(self, event):
        curX = self.canvas.canvasx(event.x)
        curY = self.canvas.canvasy(event.y)

        w, h = self.canvas.winfo_width(), self.canvas.winfo_height()
        if event.x > 0.9*w:
            self.canvas.xview_scroll(1, 'units')
        elif event.x < 0.1*w:
            self.canvas.xview_scroll(-1, 'units')
        if event.y > 0.9*h:
            self.canvas.yview_scroll(1, 'units')
        elif event.y < 0.1*h:
            self.canvas.yview_scroll(-1, 'units')

        # expand rectangle as you drag the mouse
        self.canvas.coords(self.rect, self.start_x, self.start_y, curX, curY)

    def on_button_release(self, event):
        pass

if __name__ == "__main__":
    root=Tk()
    app = ExampleApp(root)
    app.pack()
    root.mainloop()

rawDescription: Tkinter: Draw rectangle using a mouse

description: Tkinter: Draw rectangle using a mouse


code:
@classmethod
def state_from_request(cls, request):
    state = {}
    next_url = get_next_redirect_url(request)
    if next_url:
        state['next'] = next_url
    state['process'] = request.REQUEST.get('process', 'login')
    return state

rawDescription: How to implement an invite flow using django allauth for signup/signin?

description: Implement an invite flow using django allauth for signup/signin


rawDescription: Python for loop overwriting

description: Python for loop overwriting


code:
class Organism(object):
    def reproduce(self):
        #use self here to customize the new organism ...
        return self.__class__()  # same as cls = type(self); return cls()

rawDescription: Create new class instance from class method


code: newkey, newvalue = zip(*[(k, ' '.join(d.pop(k))) for k in key if k in d])

rawDescription: Concatenate strings by groups python

description: Concatenate strings by groups python


code:
import struct

def readMatrix(f):
    rows, cols = struct.unpack('>ii',f.read(8))
    m = [ list(struct.unpack('>%df' % rows, f.read(4*rows)))
             for c in range(cols)
        ]
    # transpose result to return
    return zip(*m)

rawDescription: Python binary file reading problem

description: Python binary file reading problem


code: [re.sub('('+'|'.join(stop_words)+')','',wine) for wine in wines]

rawDescription: Using Python's replace() method to implement stopword functionality


code:
string ='"inlineParams":"json","title":"","lNameP":"MYNAME","key":"degree_result_person"},"firstName":"MYFIRSTNAME"'
import re
pattern = re.compile('\"lNameP"\:"(.*?)"')
match = pattern.search(string).group(1)
print (match)

rawDescription: Extract words from text files with python


code:
string='texttexttextblahblah",".'
string = string[:-3]
string

rawDescription: Python Remove Parts of string by index

description: Python Remove Parts of string by index


code: cond = " | ".join(["col{0} == 'blue'".format(i) for i in range(10)])

rawDescription: Set type in pytables

description: Set type in pytables


code: key = next((key for key, value in d.items() if value == 15), None)

rawDescription: Python 2 Selecting a key with a value

description: Python 2 Selecting a key with a value


code: df['uid'] = df[col_to_add].sum(axis=1)

rawDescription: Concatenate a list of series into a uid

description: Concatenate a list of series into a uid


code:
rng = pd.date_range('1/1/2011', periods=25, freq='1min')
yn = np.array(['NO', 'YES'])
ts = pd.Series(yn[(np.random.rand(len(rng)) > 0.85).astype(int)], index=rng)
ts

rawDescription: Downsize series containing boolean data with resample


code: x = np.random.random_integers(0, 1, (8, 8))

rawDescription: Choosing random one from each row of a binary numpy matrix?


code: df = pd.read_csv('file.txt', sep='\t', index_col='sample')

rawDescription: pandas create data frame, floats are objects, how to convert?

description: Pandas create data frame, floats are objects, how to convert


code:
from functools import partial
s.apply(partial(map, lambda x: x*2 ))

rawDescription: pandas row specific apply

description: Pandas row specific apply


code:
while True:
    text = raw_input()
    if not text:
        break
    #Do some processing here

rawDescription: Is it possible to get all lines with raw_input(), if you don't know the number of lines?


code:
a = MyClass()
b = MyClass()
MyClass.myclassattr

rawDescription: Methods to link common class attributes between objects? (not inheritance)


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

description: Read a file block-wise in python


code: audio = MP3("filename.mp3")

rawDescription: Change embedded image type in APIC ID3 tag via Mutagen


code:
numlist, alist, blist = [], [], []
for item in mixlist:
    if item == "a":
        alist.append(item)
    elif item == "b":
        blist.append(item)
    else:
        numlist.append(item)

rawDescription: Split a list in sublists by a logic criterion


code: aDict = { name: 42 for name in list1 }

rawDescription: Use list of strings elements as arrays

description: Use list of strings elements as arrays


code: variable = random.choice(wordlist)

rawDescription: how to assign a word from a text file to a variable in python

description: Assign a word from a text file to a variable in python


code: set(frozenset(e) for e in [np.array(range(10)), np.array(range(2))])

rawDescription: Python: Intersection of two lists of lists


code:
def hash_upload(instance, filename):
    instance.my_file.open() # make sure we're at the beginning of the file
    contents = instance.my_file.read() # get the contents
    fname, ext = os.path.splitext(filename)
    return "{0}_{1}{2}".format(fname, hash_function(contents), ext) # assemble the filename

rawDescription: Efficiently saving a file by hash in Django


code:
break_word = "q"
while True:
    text = raw_input()
    if text == break_word:
        break
    #Do some processing here

description: Is it possible to get all lines with raw_input(), if you don't know the number of lines


code:
from __future__ import print_function # Added in 2.6

map(print, range(10))

rawDescription: How to put statement before for-loop in python

description: Put statement before for-loop in python


rawDescription: Python - check if file/webpage exists

description: Python - check if file/webpage exists


code:
from dateutil.relativedelta import relativedelta
start = start + relativedelta(months = +1)

rawDescription: Iterating over date in python

description: Iterating over date in python


rawDescription: What is the Matlab equivalent to Python's `not in`?


rawDescription: python xmpp wokkel JID escaping

description: Python xmpp wokkel JID escaping