code: return lambda x: np.dot(A, x) - b

rawDescription: Dynamically build a lambda function in python


code:
def punc(x):
    predicate = lambda y:y not in ''.join(c for c in string.punctuation if c not in './')
    prepositions = ['a', 'in']  #define by yourself
    if any(p in x.split() for p in prepositions):
        return filter(predicate,x)
    return x

rawDescription: Remove selected punctuation from list of sentences


code:
if OldVersion:
    from my.package.location.A import A
else:
    from new.package.location.A import A

rawDescription: Python, doing conditional imports the right way


code:
board = [
    [1,0,1,0,1],
    [1,0,1,0,1],
    [1,0,1,0,1],
    [1,0,1,0,1],
    [1,0,1,0,1]
]

def clamp(minV,maxV,x):
    if x < minV:
        return minV
    elif x > maxV:
        return maxV
    else:
        return x

def getNeighbour(grid,startx,starty,radius):
    width = len(grid[starty])
    height = len(grid)
    neighbourhood = []
    for y in range(clamp(0,height,starty-radius),clamp(0,height,starty+radius)+1):
        row = []
        for x in range(clamp(0,width,startx-radius),clamp(0,width,startx+radius)+1):
            if x != startx or (x==startx and  y != starty):
                row.append(grid[y][x])
        neighbourhood.append(row)
    return neighbourhood

rawDescription: Iterator for each item in a 2D Python list and its immediate m by n neighbourhood


code: import inspect

rawDescription: How to find all Python built-in private variables such as __file__, __name__

description: Find all Python built-in private variables such as __file__, __name__


code:
self.old_port_dict = collections.defaultdict(set)
for s in self.prev_report.hosts:
    for x in s.get_open_ports():
        self.old_port_dict[s.address].add(x)

self.new_port_dict = collections.defaultdict(set)
for s in self.report.hosts:
    for x in s.get_open_ports():
        self.new_port_dict[s.address].add(x)

rawDescription: How to use collections.defaultdict, to ensure a straightforward comparison of values in Python

description: Use collections.defaultdict, to ensure a straightforward comparison of values in Python


code:
import re
re.split(r'(\d+)', 'A123E')

rawDescription: Split a string using an integer as a delimeter


rawDescription: Numpy indexing multidimensional arrays with array and slice


code:
import numpy as np
x = np.array([164, 202, 164, 164, 164, 166], dtype=np.uint16)

rawDescription: Numpy way to determine the value(s) in an array which is causing a high variance


rawDescription: Split string in Python into chunks with constant length, but right-aligned


code:
def key_values_view(request, path):

    bits = path.split('/')
    it = iter(bits)
    data = dict(zip(it, it))

    key1 = data.get('key1')
    key2 = data.get('key2')
    key3 = data.get('key3')

    ...

rawDescription: Multiple URL key-value pair parameters that are optional in Django


code:
def my_view(request):
    ...
    return redirect('http://example.com/')

rawDescription: Django - template not loading, perpetual 302 message


rawDescription: Get the values of multiple checkboxes in django


code:
from model_mommy import mommy
from your_app.models import ShippingContainer

dummy_shipping_container = mommy.make('ShippingContainer')

rawDescription: Factoryboy Django model with default fuzzyfields


code:
import numpy, scipy.sparse
n = 100000
x = (numpy.random.rand(n) * 2).astype(int).astype(float) # 50% sparse vector
x_csr = scipy.sparse.csr_matrix(x)
x_dok = scipy.sparse.dok_matrix(x.reshape(x_csr.shape))

rawDescription: Scipy sparse... arrays?

description: Scipy sparse... arrays


code:
import cProfile
import re
cProfile.run('re.compile("foo|bar")')

rawDescription: Is there any simple way to benchmark python script?


code:
import os
path = os.path.dirname(amodule.__file__)

rawDescription: Retrieving python module path

description: Retrieving python module path


rawDescription: Matplotlib: Getting subplot position values (hspace, wspace, ..)


code:
import numpy as np
np.array(list_).sum(0).prod()

rawDescription: Working with nested lists in Python

description: Working with nested lists in Python


rawDescription: How to delete a set of meshgrid points inside a circle?

description: Delete a set of meshgrid points inside a circle


code:
import datetime
datetime.datetime.now()

rawDescription: How to get current time in Python

description: Get current time in Python


code: hours[2, 'Sunday']

rawDescription: Python: nested loops not behaving how I want them to


rawDescription: How to select only complete in a panda data.frame

description: Select only complete in a panda data.frame


code:
class Player(object):
    def __init__(self, nm, am, wp, ht, tp, ide):
        self.name = nm
        self.ammo = am
        self.weapon = wp
        self.health = ht
        self.type = tp
        self.id = ide

    def __str__(self):
        values1 = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "I am a: " + self.type + "\n" + "ID #: " + str(self.id)
        return values1

class Enemy(object):
    def __init__(self, nm, am, wp, ht, tp, ide):
        self.name = nm
        self.ammo = am
        self.weapon = wp
        self.health = ht
        self.type = tp
        self.id = ide

    def __str__(self):
        values = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "I am a: " + self.type + "\n" + "ID #: " + str(self.id)
        return values

rawDescription: Creating methods with the same attributes


code:
import  csv

with open("train.csv", "r") as f:
    r = csv.reader(f)
    # pull first row i.e A,B,C,D... to use ad the keys
    keys = next(r)
    # iterate ober the rows mapping to float and transpose
    # with zip(*... so rows become columns, one per key
    summed_dict = dict(zip(keys, map(sum, zip(*(map(float, row) for row in r)))))

rawDescription: how to get sums in CSV file python

description: Get sums in CSV file python


rawDescription: Combining two sorted lists in Python

description: Combining two sorted lists in Python


code: {key: value for key, value in ((x, func(y)) for x, y in l) if isinstance(value, int)}

rawDescription: Is comprehension possible here?

description: Is comprehension possible here


rawDescription: python library for evaluating random walks?

description: Python library for evaluating random walks


rawDescription: Split Python Flask app into multiple files


code:
from datetime import datetime
td = datetime.now() - datetime(1850, 1, 1)
print (86400*td.days)+td.seconds  # seconds since then till now

rawDescription: How to get a timestamp older than 1901

description: Get a timestamp older than 1901


rawDescription: unpacking function argument

description: Unpacking function argument


code:
try:
    sched.start()
except (KeyboardInterrupt):
    logger.debug('Got SIGTERM! Terminating...')

rawDescription: APscheduler will not stop

description: APscheduler will not stop


code:
import random

def shift_char(ch,shift):
    if not ch.isalpha():
        return ch   # return non-alphabetic characters as is
    if ch.isupper():
        base_a = 'A'
    else:
        base_a = 'a'
    return chr(ord(base_a) + (ord(ch)-ord(base_a)+shift)%26)

def encode_string(s,shift):
    return ''.join(shift_char(i,shift) for i in s)

def decode_string(s,shift):
    return ''.join(shift_char(i,-shift) for i in s)

# usage
s = 'Hello, StackOverflow!'
shift = random.randint(1,25)
enc_s = encode_string(s,shift)
dec_s = decode_string(enc_s,shift)

rawDescription: How to change random letter using number in Python

description: Change random letter using number in Python


code:
melted = pd.melt(results, id_vars=['Item 1','Item 2'], var_name='Position')
# we only care about rows where Contractor or President value was 1. So use .loc to select those rows.
melted = melted.loc[melted['value']==1]
#     Item 1  Item 2    Position  value
# 0      1.0       1  Contractor      1
# 1      1.0       0  Contractor      1
# 5      NaN       1  Contractor      1
# 6      1.0       1   President      1
# 10     1.0       0   President      1
# 11     NaN       1   President      1

rawDescription: Pandas Pivot Table with Fancy Stacking

description: Pandas Pivot Table with Fancy Stacking


code:
groupings = defaultdict(list)
for dt, t1, t2, t3 in data:
    groupings[coarse(dt, 15)].append([t1, t2, t3])

rawDescription: Averaging along DataFrame columns with some missing rows


rawDescription: Python converting latin1 to UTF8

description: Python converting latin1 to UTF8


code:
df.dropna(subset=['comments'])
df = df.dropna(subset=['comments'])

rawDescription: Cant get NaN elements dropped in pandas dataFrame


code: s

rawDescription: Reindex time-stamped data with date_range


code:
def find_value(needle, container):
    # Already found the object. Return.
    if needle == container:
        return True

    values = None
    if isinstance(container, dict):
        values = container.values()
    elif hasattr(container, '__iter__'):
        values = container.__iter__()

    if values is None:
        return False

    # Check deeper in the container, if needed.
    for val in values:
        if find_value(needle, val):
            return True

    # No match found.
    return False

rawDescription: search for any string value in an ordered dictionary

description: Search for any string value in an ordered dictionary


code:
def calc_x(x, n):
    i = 0
    while (i < n):
        x = 4 * x * (1 - x)
        i += 1
    return x

rawDescription: Avoid loops in the computation of logistic equation?


code:
lyrl2004_tokens_train.dat,
lyrl2004_tokens_test_pt0.dat,
lyrl2004_tokens_test_pt1.dat,
lyrl2004_tokens_test_pt2.dat,
lyrl2004_tokens_test_pt3.dat,

rawDescription: Twitter/ general categorisation training corpus


code:
import numpy as np
import pylab as pl

pl.ioff()

rand_field = np.random.rand(10,10)

fig = pl.figure()
cm = pl.pcolormesh(rand_field, vmin=0, vmax=1)
pl.colorbar()

def onclick(event):
    indexx = int(event.xdata)
    indexy = int(event.ydata)
    print("Index ({0},{1}) will be set to zero".format(indexx, indexy))
    rand_field[indexy, indexx] = 0.
    cm.set_array(rand_field.ravel())
    event.canvas.draw()

cid = fig.canvas.mpl_connect('button_press_event', onclick)

pl.show()

rawDescription: Interaction with python's matplotlib figure: assign value to selected features


code:
import re

for tag in soup.find_all('a', href=re.compile('^http://t\.co/')):
    link = tag['href']
    webbrowser.open_new_tab(link)

rawDescription: Why doesn't my code loading links in a browser tab work?


code:
from collections import defaultdict

def find_minimal_phrases(phrases):
    # Make the phrases hashable
    phrases = map(frozenset, phrases)

    # Create a map to find all phrases containing a word
    phrases_containing = defaultdict(set)
    for phrase in phrases:
        for word in phrase:
            phrases_containing[word].add(phrase)

    minimal_phrases = []
    found_superphrases = set()
    # in sorted by length order to find minimal sets first thanks to the
    # fact that a.superset(b) implies len(a) > len(b)
    for phrase in sorted(phrases, key=len):
        if phrase not in found_superphrases:
            connected_phrases = [phrases_containing[word] for word in phrase]
            connected_phrases.sort(key=len)
            superphrases = reduce(set.intersection, connected_phrases)
            found_superphrases.update(superphrases)
            minimal_phrases.append(phrase)
    return minimal_phrases

rawDescription: Algorithm to filter a set of all phrases containing in other phrase


code:
data = web.urlopen(message)
str_data = data.read()

rawDescription: How to convert an urlopen into a string in python

description: Convert an urlopen into a string in python


code:
from collections import defaultdict
import pprint

data = {
 'Bob' : {'item1':3, 'item2':8, 'item3':6},
 'Jim' : {'item1':6, 'item4':7},
 'Amy' : {'item1':6,'item2':5,'item3':9,'item4':2}
}

flipped = defaultdict(dict)
for key, val in data.items():
    for subkey, subval in val.items():
        flipped[subkey][key] = subval

pprint.pprint(dict(flipped))

rawDescription: Pythonic Way to reverse nested dictionaries


code:
def obsfucate_letters(letters):
    for i in range(len(letters)):
        try:
            letters[i] = obfuscate_function()
        except ValueError:
            # don't replace a letter when the random value was out of range
            pass

    return letters

rawDescription: Return original value, python

description: Return original value, python


code:
from collections import deque
from itertools import islice

def skip_last_n(iterator, n=1):
    it = iter(iterator)
    prev = deque(islice(it, n), n)
    for item in it:
        yield prev.popleft()
        prev.append(item)

rawDescription: Skip the last row of CSV file when iterating in Python


rawDescription: reduce time precision of time series to milliseconds

description: Reduce time precision of time series to milliseconds


rawDescription: In python curly braces with numbers from range() inside


code:
from numpy import *
import matplotlib.pyplot as plt

symbols = [u'\u2B21', u'\u263A', u'\u29C6', u'\u2B14', u'\u2B1A', u'\u25A6', u'\u229E', u'\u22A0', u'\u22A1', u'\u20DF']

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

plt.figure()
for i, symbol in enumerate(symbols):
    y2 = y + 4*i
    plt.plot(x, y2, 'g')
    for x0, y0 in zip(x, y2):
        plt.text(x0, y0, symbol, fontname='STIXGeneral', size=30, va='center', ha='center', clip_on=True)

plt.show()

rawDescription: matplotlib custom markers

description: Matplotlib custom markers


code:
fullstr = "my|name|is|will"
fullstr.split('|')[1]
fullstr.rsplit('|')[1]

rawDescription: Getting Substring in Python

description: Getting Substring in Python


code: idx = mask[xarr, yarr].astype(bool)

rawDescription: removing entries from a numpy array

description: Removing entries from a numpy array


code: mock_poll = Mock(side_effect=chain(['first'], cycle(['others'])))

rawDescription: python mock side_effect or return_value dependent on call_count

description: Python mock side_effect or return_value dependent on call_count


code:
from lxml import etree
et = etree.XML("""<root xmlns="foo" xmlns:stuff="bar"><bar><stuff:baz /></bar></root>""")
etree.tostring(et, encoding=str) # encoding=str only needed in Python 3, to avoid getting bytes
et.xpath("f:bar", namespaces={"b":"bar", "f": "foo"})

rawDescription: Good python XML parser to work with namespace heavy documents


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Button

import serial
import binascii
import struct
from time import sleep

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
ax.axis([0, 10, 0, 255])

ser = serial.Serial('COM5', 1000000, timeout=0)
ser.write("0".encode())
sleep(0.1)
if ser.read()== b'\xf1':
    print ("Interface is responding")
else:
    print ("Interface is NOT responding")
    ser.flush()
    ser.close()
    exit(1)

t = np.linspace(0, 10, 2048)
line1, line2 = plt.plot(t,0*t, t,0*t, lw=2)

def ShowChannel(Channel):
    if Channel==1:
        ser.write("11".encode())
    elif Channel==2:
        ser.write("12".encode())
    sleep(0.05)
    Header = ser.read().decode("utf-8")
    # print(Header)
    if Header == "1":
        data = ser.read(2048)
        y = struct.unpack('2048B', data)
        # print(y)
        if Channel==1:
            line1.set_ydata(y)
        elif Channel==2:
            line2.set_ydata(y)
        fig.canvas.draw()

def one(event):
    global channel1_on

    if channel1_on == 0:
        channel1_on = 1
        timer1.start()
    else:
        channel1_on = 0
        timer1.stop()
        line1.set_ydata(None)

def two(event):
    global channel2_on

    if channel2_on == 0:
        channel2_on = 1
        timer2.start()
    else:
        channel2_on = 0
        timer2.stop()
        line2.set_ydata(None)

channel1_on = 0
channel2_on = 0
timer1 = fig.canvas.new_timer(interval = 50)
timer1.add_callback(ShowChannel, 1)
timer2 = fig.canvas.new_timer(interval = 50)
timer2.add_callback(ShowChannel, 2)

axone = plt.axes([0.1, 0.05, 0.1, 0.075])
axtwo = plt.axes([0.21, 0.05, 0.1, 0.075])
axstart = plt.axes([0.40, 0.05, 0.1, 0.075])
axstop = plt.axes([0.51, 0.05, 0.1, 0.075])

bone = Button(axone, '1')
bone.on_clicked(one)
btwo = Button(axtwo, '2')
btwo.on_clicked(two)

plt.show()

rawDescription: Python Matplotlib Buttons

description: Python Matplotlib Buttons


code:
# we need to keep track of the current string,
# the power of two, and the total (decimal)
def placeToInt (str, pow, total):
    # if the length of the string is one,
    # we won't call the function anymore
    if (len(str) == 1):
        # return the number, 0 or 1, in the string
        # times 2 raised to the current power,
        # plus the already accumulated total
        return int(str) * (2 ** pow) + total
    else:
        # grab the last digit, a 0 or 1
        num = int(str[-1:])
        # the representation in binary is 2 raised to the given power,
        # times the number (0 or 1)
        # add this to the total
        total += (num * (2 ** pow))
        # return, since the string has more digits
        return placeToInt(str[:-1], pow + 1, total)

# test case
# appropriately returns 21
print(placeToInt("10101", 0, 0))

rawDescription: binary to decimal using recursion,python

description: Binary to decimal using recursion,python


code:
df = pd.read_csv('SIT Req.tx', sep='\t')    # note use of sep

for a, b, c in df.values:
    ...
# or
for i, a, b, c in df.itertuples():
    ...
# or
for i, row in df.iterrows():
    a, b, c = row
    ...

rawDescription: Python - iterate text file and create dictionary of dictionary


code:
sp_mat.getnnz(axis=1)
# array([4, 2], dtype=int32)

rawDescription: Check Density of a Scipy Sparse Matrix

description: Check Density of a Scipy Sparse Matrix


code: build_insert_statement('foo', ['bar'], ['1'], 'baz')

rawDescription: string_builder decorator in python 2.7 - how to do it and should I?

description: String_builder decorator in python 2.7 - how to do it and should I


code: parent = relationship(Parent, primaryjoin=parent_metadata_id == Parent.metadata_id)

rawDescription: Specify join condition in SQLalchemy ORM without foreign key


code: URL = [i.split('/')[0] for i in URL]

rawDescription: Is there a way to extract the section before the first `/` from a list?


code: img_urls = form_soup.findAll('a', title=u'\u67e5\u770b\u5927\u56fe')

rawDescription: how to get tags when attribute is chinese in beautifulsoup

description: Get tags when attribute is chinese in beautifulsoup


code: if not path: path = '.'

rawDescription: most efficient way to substring path and file out of a string

description: Most efficient way to substring path and file out of a string


code:
def get_text_column_row(table_css, header, row):
    table = driver.find_element_by_css_selector(table_css)
    table_headers = table.find_elements_by_css_selector('tbody > tr:nth-child(1) > th')
    table_rows = table.find_elements_by_css_selector("tbody > tr > td:nth-child(1)")

    index_of_column = None
    index_of_row = None

    for i in range(len(table_headers)):
        if table_headers[i].text == header:
            index_of_column = i + 1

    for i in range(len(table_rows)):
        if table_rows[i].text == row:
            index_of_row = i + 1

    xpath = '//tr[position() = %d]//td[position() = %d]' %(index_of_row, index_of_column)

    return driver.find_element_by_xpath(xpath).text

rawDescription: How do I return a web page's table cell value without ID, using column and row names (not index)

description: Return a web page's table cell value without ID, using column and row names (not index)


code: output == ['item2', 'item1', 'item4', 'item3']

rawDescription: Sorting a list based on associated scores


code:
from itertools import islice, imap
import csv
from collections import defaultdict
with open("in.txt") as f,open("numbers.txt") as nums:
    # make a set of all winning nums
    nums = set(imap(str.rstrip, nums))
    r = csv.reader(f)
    results = defaultdict(list)
    # iterate over each row and sum how many matches we get
    for row in r:
        results[sum(n in nums for n in islice(row, 1, None))].append(row[0])

rawDescription: Comparing two CSV files in Python when rows have multiple values


code:
def filtered(f, x):
    if f:
        status, result = f(x)
        return result if status else x
    else:
        return x

rawDescription: Better / More pythonic way to process the results of a function with multiple return values


code:
d = {}
with open("in.txt") as f:
    f_csv = csv.reader(f, delimiter='\t')
    headers = next(f_csv)
    tuple_attr = tuple(headers)
    data = tuple(tuple(x.split()) for x in f_csv)
    for tup in data:
        d.setdefault(tup[-1],[])
        d[tup[-1]].append(tup[:-1])

rawDescription: Creating python dictionary with a particular column value as key and removing that column from value


code:
name_max = subprocess.check_output("getconf NAME_MAX /", shell=True)
path_max = subprocess.check_output("getconf PATH_MAX /", shell=True)

rawDescription: How do I get in python the maximum filesystem path length in unix?

description: Get in python the maximum filesystem path length in unix


code:
lstname1 = np.arange(3)
lstname2 = 22*np.arange(3)
np.vstack((lstname1,lstname2)).T
# returns
array([[ 0,  0],
       [ 1, 22],
       [ 2, 44]])
#or
np.hstack((lstname1[:,np.newaxis],lstname2[:,np.newaxis]))
array([[ 0,  0],
       [ 1, 22],
       [ 2, 44]])

rawDescription: clearing elements of numpy array

description: Clearing elements of numpy array


code: print('Your triangle is %s.' % id_triangle(t1, t2, t3))

rawDescription: I'm making a triangle class finder and I'm stuck


code:
@nb.jit(nopython=True)
def nb_sum(A):
    s=0
    n = A.shape[0]
    for i in range(n):
        s += A[i]
    return s

@nb.jit(nopython=True)
def nb_sum2(i):
    s=0
    for x in range(i):
        s+=x
    return s

rawDescription: why is numba so much faster on this simple summation?

description: Why is numba so much faster on this simple summation


rawDescription: Adding a data frame column with len() of another column's values


code:
@pluralize
def unixtime(dt):
    return int(dt.strftime('%s'))

unixtime.on_seq([datetime.now(), datetime(2010, 12, 3)])
unixtime.on_dict({'start': datetime.now(), 'end': datetime(2010, 12, 3)})

rawDescription: How Awful is My Decorator?

description: How Awful is My Decorator


code:
p = np.array([3, 2, 0, 1])
np.argsort(p)
p[np.argsort(p)]

rawDescription: How to invert a permutation array in numpy

description: Invert a permutation array in numpy


code:
lastname = ['smith','jones','cook']
companies = ['company a','company b']
names = {'smith':'matt smith','jones':'tom jones','cook':'karen cook'}
affiliations = {'matt smith':'company a','tom jones':'company b','karen cook':'company c'}

rawDescription: In python: How to find match of string in same row, compare part of (fuzzy) matched string to list?


code: row

rawDescription: Why doesn't this function "take" after I iterrows over a pandas DataFrame?


code:
# File database
db.define_table("file",
    Field("job", "reference job"),
    Field("name", "string", length=30, required=True),   # stores the filename (without path)
    Field("isimage", "boolean", default=False))

rawDescription: Web2py: downloading files / displaying images


code: df2 = pd.DataFrame(df.ix[:,['col1', 'col2', 'col3']].div(df.col4, axis=0))

rawDescription: Broadcasting Error Pandas

description: Broadcasting Error Pandas


rawDescription: Sort a list of candidates according to a metric - Python?


rawDescription: count of last n days per group

description: Count of last n days per group


code: list(triangle(100, 0.5))

rawDescription: Triangle wave shaped array in Python

description: Triangle wave shaped array in Python


code:
vals = [[1]]
for _ in xrange(n):
    vals.append(f(vals[-1]))

rawDescription: Python applying dynamic list comprehension (list append)


code:
from django.shortcuts import redirect

def show_amt_page(request, SSL):
    if 'ref_source' not in request.GET:
        return redirect('amt/?ref_source=AMT&ref_id=PC')
    # rest of view goes here
    ...

rawDescription: Django: redirect to the same url with an appended querystring


code:
from lxml import html
import requests
from pprint import pprint

url = 'http://www.amazon.co.uk/dp/B009CX5VN2'
page = requests.get(url)
tree = html.fromstring(page.text)
feature_bullets = tree.xpath('//div[@id="technicalProductFeaturesATF"]/ul/li/text()')

pprint(feature_bullets)

rawDescription: Scraping web content using xpath won't work


code: sorted([3,4,7,2,1], reverse=True)

rawDescription: Discuss the "sorted" function in Python

description: Discuss the "sorted" function in Python


rawDescription: Repeat a List Within a List X Number of Times


code: my_form = TestForm(field1_qs=MyQS)

rawDescription: Can we give dynamic queryset for ModelChoiceField in django forms?


code:
print (today - past).days
print (now.date() - past).days

rawDescription: Trouble with datetime in python2.7/django1.5.1


code: population = list(itertools.chain(fhd, fhet, fhr))

rawDescription: Populate list with tuples

description: Populate list with tuples


code:
df = pd.DataFrame({'ts':pd.date_range('2016-01-01', freq='1min', periods=10000), 'col': np.random.randint(0,100, len(times))})
df.head(10)
df.groupby([df.ts.dt.date, df.ts.dt.hour, df.ts.dt.minute//15]).sum().head(20)

rawDescription: Pandas: Group Timeseries into parts of a day


code: g.data_version = my_dict['dataVersion'] if my_dict else g.data_version

rawDescription: Python: Inline if statement else do nothing


code:
from functools import partial
from operator import add
from itertools import imap

addone = partial(add, 1)

test = list(imap(addone, test))  # don't really use imap if you want a list

rawDescription: Increase each list element in all possible ways


rawDescription: Python : efficient bytearray incrementation


code:
chained = itertools.chain.from_iterable(sixbit)
[''.join(bits) for bits in itertools.izip(*[chained]*8)]

rawDescription: iterating over list of string and combining string values Python

description: Iterating over list of string and combining string values Python


code:
def filter_by_beginning_and_len(phone):
    return str(phone).startswith('+1') and len(str(phone)) == 13

df = df[df['Phone'].apply(filter_by_beginning_and_len)]

rawDescription: Delete rows not containing a value in pandas


code:
def plus(a, b): return a + b

methods = {
    '+': plus,
    # ...
}

rawDescription: Is there any idiomatic way to add methods to object in Python?


rawDescription: How to get the value of msExchMailboxGuid of an Actvie Directory user by python script

description: Get the value of msExchMailboxGuid of an Actvie Directory user by python script


code:
def count(word):
    d = {}
    for c in word:
        d[c] = d.get(c, 0) + 1
    return d

rawDescription: program takes long time to calculate........recursion(python)

description: Program takes long time to calculate........recursion(python)


code:
def disableWidget(currentIndex):
     widget = widgets[currentIndex]
     widget.setEnabled(False)
     # or anything else you want to do on the widget

rawDescription: How to toggle enabled state of widgets based on QcomboBox index

description: Toggle enabled state of widgets based on QcomboBox index


code:
import numpy as np
data = np.asarray(l)
mat, row, col = data.shape
data = data.swapaxes(0, 1)
data
data.resize((row, mat*col))
data

rawDescription: Python eliminate Tuples after zipping list of list of lists


code:
import  csv
with open(source) as f:
    data = [map(float,row) for row in csv.reader(f,delimiter=" ")]
    print(data)

rawDescription: coordinates (str) to list

description: Coordinates (str) to list


code: any('a' in lst for lst in dictA.itervalues())

rawDescription: List Comprehension of Lists Nested in Dictionaries


rawDescription: Creating a variable inside of a for loop


code:
@app.before_request
def before_request():
    g.user = None
    if 'user_id' in session:
        g.user = User.query.get(session['user_id'])

rawDescription: Change "Sign In through Steam" logo after authentication


rawDescription: Python CSV DictReader ignore columns?

description: Python CSV DictReader ignore columns


code:
A[:,0:1] # not so clear
A[:,:1]  # black magic
A[:,[0]] # clearest syntax imho

rawDescription: Best way to iterate through a numpy array returning the columns as 2d arrays

description: Iterate through a numpy array returning the columns as 2d arrays


code: df['c'] = df.apply(lambda x: max(len(x['a']), len(x['b'])), axis=1)

rawDescription: Creating a new column in Panda by using lambda function on two existing columns


rawDescription: split command question

description: Split command question


code:
plt = pg.plot()
def update():
    data = getNewData()
    if data is not None:
        plt.plot(data, clear=True)
timer = QTimer()
timer.timeout.connect(update)
timer.start(10)

rawDescription: Integrating two event handling programs in Python


code:
...
requests.post('http://site.com/', data=data, files=image)
f.seek(0)
requests.post('http://othersite.com/', data=data, files=image)

rawDescription: Always empty multipart-encoded files in second POST


code:
for key, c in sorted(count.items(), key=lambda i: a.index(i[0])):
    print("{}: {}".format(key, c))

rawDescription: Display 'Counter' results on seperate line (Python)


code:
columns = []
for n in range(8):
    columns.append([item for item in itertools.islice(e, n, None, 8)])

rawDescription: Use Python zip to save data in separate columns from a binary file


code:
remspace('a b c')
remspace('a b c ')
remspace('a b c\n')
remspace('a b c \n')
remspace('')
remspace('\n')
remspace(' \n')
remspace(' ')
remspace('I')

rawDescription: Remove Space at end of String but keep new line symbol


code:
def bitstring_to_bytes(s):
    v = int(s, 2)
    b = bytearray()
    while v:
        b.append(v & 0xff)
        v >>= 8
    return bytes(b[::-1])

s = "0110100001101001"
print(bitstring_to_bytes(s))

rawDescription: Convert binary string to bytearray in Python 3


rawDescription: Filter list of tuples to removes lists with all odd number or sum less than 80


code:
from fractions import Fraction
Fraction(10)
Fraction(10)**50
Fraction(10)**50-1
(Fraction(10)**50-1)/23
((Fraction(10)**50-1)/23) % 1
float(((Fraction(10)**50-1)/23) % 1)

rawDescription: Python: Decimal part of a large float

description: Python: Decimal part of a large float


code:
set_cycles = set(cycles(a))
b in set_cycles

description: Clean way to accomplish -- if x in [(0, 1, 2), (2, 0, 1), (1, 2, 0)]:


code:
df2 = df2.drop("n",axis=1).reset_index(drop=True)
df2

rawDescription: Replicating rows in a pandas data frame by a column value


code:
import reloadme
x = reloadme.MyClass()
y = reloadme.MyClass()
reload(reloadme)
z = reloadme.MyClass()
x == y
x == z

rawDescription: Python Multiprocessing: Reloading module in child effecting parent


code:
key = createMagicalKey()

foo = key.encryptor()
ciphertext = foo.encrypt(data)

bar = key.decryptor()
data = bar.decrypt(ciphertext)

rawDescription: Pythonic solution to cryptographic agility that avoids violating Liskov's substitution principle


rawDescription: Python pandas multiindex getting info from series


code:
def set_from_dict(d):
    return frozenset(
        (k, set_from_dict(v) if isinstance(v, dict) else v)
        for k, v in d.iteritems())

rawDescription: How make unique a list of nested dictionaries in python


code: w = apply(Entry, [optionFrame], {"textvariable": var})

rawDescription: Labelling "Entry" in Tkinter

description: Labelling "Entry" in Tkinter


code: parser.add_argument('-w', action='store_true', help='word help')

rawDescription: How to implement command line switches to my script?

description: Implement command line switches to my script


code: sorted(numbers_array, key=abs)

rawDescription: Sorting by absolute value without changing to absolute value


code:
def unique_file(input_filename, output_filename):

    input_file = open(input_filename,'r')
    content = input_file.read()
    input_file.close()
    word_list = content.split()
    output_file = open(output_filename,'w')

    word_list = list(set(word_list))

    for word in word_list:
        output_file.write(words + '\n')
    output_file.close

rawDescription: Only Wanting Unique Words in my output file


code:
RolUp = RolUp.reindex_like(delta, method='ffill')
RolDown = RolDown.reindex_like(delta, method='ffill')

rawDescription: Relative Strength Index in python pandas


code:
from tkinter import *
import random

class Cell:
    def __init__(self, word, hidden=True):
        self.word = word
        self.hidden = hidden

    def show_word(self):
        """ Shows the word behind the cell """
        self.hidden = not self.hidden
        self.button["text"] = str(self)

        if mem.choice1 is None:
            mem.choice1 = self
        elif mem.choice2 is None:
            mem.choice2 = self
        else:
            choice1, choice2 = mem.choice1, mem.choice2
            mem.choice1, mem.choice2 = self, None
            self.check(choice1, choice2)

    def check(self, choice1, choice2):
        """ Checks if the chosen words are a pair """
        if choice1.word != choice2.word:
            for cell in (choice1, choice2):
                cell.hidden = True
                cell.button['text'] = str(cell)

    def __str__(self):
        """ Displays or hides the word """
        if self.hidden == True:
            return "---"
        else:
            return self.word

class Memory(Frame):
    """ GUI application that creates a Memory game """
    def __init__(self, master):
        super(Memory, self).__init__(master)
        self.grid()
        self.create_widgets()
        self.tries = 0
        self.choice1 = None
        self.choice2 = None

    def readShuffle(self):
        """ Creates and organizes (shuffles) the pairs in a list """
        # reads a list of words from the file
        with open('memo.txt', 'r') as infile:
            words = [line.strip() for line in infile]

        # creates 18 pairs of words in a new list
        the_pairs = list()
        for i in range(18):
            the_pairs.extend([Cell(words[i]), Cell(words[i])])

        # shuffles the words in the new list
        random.shuffle(the_pairs)

        return the_pairs

    def create_widgets(self):
        """ Create widgets to display the Memory game """
        # instruction text
        Label(self,
              text = "- The Memory Game -",
              font = ("Helvetica", 12, "bold"),
              ).grid(row = 0, column = 0, columnspan = 7)

        # buttons to show the words
        column = 0
        row = 1
        the_pairs = self.readShuffle()
        for index in range(36):
            temp = Button(self,
                   text = the_pairs[index],
                   width = "7",
                   height = "2",
                   relief = GROOVE,
                   command = the_pairs[index].show_word
                   )
            temp.grid(row = row, column = column, padx = 1, pady = 1)
            column += 1
            the_pairs[index].button = temp
            if column == 6:
                column = 0
                row += 1

        # total tries
        self.label = Label(self)
        Label(self,
              text = "Total tries: 0",
              font = ("Helvetica", 11, "italic")
              ).grid(row = 7, columnspan = 7, pady = 5)

        # a quit button
        Button(self,
               text = "Quit",
               font = ("Helvetica", 10, "bold"),
               width = "25",
               height = "1",
               command = self.quit
               ).grid(row = 8, column = 0, columnspan = 7, pady = 5)

    def quit(self):
        """ Ends the memory game """
        global root
        root.destroy()

# main
root = Tk()
root.title("Memory")
root.geometry("365x355")
mem = Memory(root)
root.mainloop()

rawDescription: Something wrong without any error - Includes Tkinter


code:
if col in relevanCols:
    event.GetEventObject().SetToolTipString("Hai")
else:
    self.grid.SetToolTip(None)

rawDescription: How to remove a tooltip in wxpython?

description: Remove a tooltip in wxpython


code: all(isinstance(x, (int, long)) for x in lst)

rawDescription: Python check if all elements of a list are the same type


code: age += 1

rawDescription: How to add on python

description: Add on python


rawDescription: Finding largest indices of non-zero elements along each axis


rawDescription: comparing ndarray with values in 1D array to get a mask

description: Comparing ndarray with values in 1D array to get a mask


code:
class AttrMap(object):
    def __init__(self, name):
        self.name = name
    def __get__(self, obj, typ):
        # Read access to obj's attribute.
        if obj is None:
            # access to class -> return descriptor object.
            return self
        return getattr(obj, self.name)
    def __set__(self, obj, value):
        return setattr(obj, self.name, value)
    def __delete__(self, obj):
        return delattr(obj, self.name)

rawDescription: child class attribute different name

description: Child class attribute different name


code:
my_instance = MyClass()
my_second_instance = my_instance # what's the "name" of that instance now? there's two handles for it, now.

rawDescription: How to write a class method in Python that captures the name of the instance and apply some action on it

description: Write a class method in Python that captures the name of the instance and apply some action on it


code: re.compile("[^\w']|_").sub(" ","doesn't this _technically_ means it works? naïve I am ...")

rawDescription: Python Regex - Remove special characters but preserve apostraphes


code:
my_model = MyModel(name="Bob")
my_model.save(using='my_non_default_database')

rawDescription: Using Django ORM get_or_create with multiple databases


code: print([{'CustName': key, 'parts': value} for key, value in d.items()])

rawDescription: rebuild python array based on common elements

description: Rebuild python array based on common elements


code: thread.daemon = True

rawDescription: How to end a program properly with threads?

description: End a program properly with threads


code:
def app():
    x=5
    d = {'x': x}
    exec("x+=1", d)
    x = d['x']
    print(x)

app()

rawDescription: using exec() with python 3.2

description: Using exec() with python 3.2


code:
import matplotlib
from pylab import *

data = np.arange(-50, 50).reshape(10, 10)
data = np.abs(data)
colors = [(0,0,0)] + [(cm.YlOrRd(i)) for i in xrange(1,256)]
new_map = matplotlib.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)
pcolor(data, cmap=new_map)
savefig('map.png')
show()

rawDescription: Setting arbitrary color in pseudocolor plot with matplotlib


code:
['SE', 'The Spiderwick Chronicles', '"SPIDERWICK CHRONICLES  THE"', 'movie']
['GB', 'Fast Friends', 'Burn Notice  S:4  E:2', 'episode']

rawDescription: Ambiguity in parsing csv file

description: Ambiguity in parsing csv file


rawDescription: Efficient Numpy computation of pairwise squared differences


rawDescription: Python returning variables from various functions


code:
import numpy as np

img_array = np.load('filename.npy')

rawDescription: Viewing .npy images

description: Viewing .npy images


code: print(gs.translate('carpe diem', 'en', 'la'))

rawDescription: How can I easily machine translate something with python?

description: Easily machine translate something with python


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

driver = webdriver.PhantomJS()
driver.get("https://www.bestodds.com.au/odds/cricket/ICC-World-Twenty20/Sri-Lanka-v-Afghanistan_71992/")

# waiting for the page to load
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".odds-comparison")))

for comparison in driver.find_elements_by_css_selector(".odds-comparison"):
    description = comparison.find_element_by_css_selector(".description").text
    print(description)

driver.close()

rawDescription: All elements from html not being extracted by Requests and BeautifulSoup in Python


code: strs.split(', ')

rawDescription: How to convert this list in a given format?

description: Convert this list in a given format


code:
A.foo is A.foo
a.foo is a.foo

rawDescription: Using same function as instance and classmethod in python


code:
from collections import deque

limit = 100
prev_items = deque(maxlen=limit)

# Open file and iterate over lines.
with open('names.txt') as f:
    for line in f:
        # Add the line to the deque.
        prev_items.append(line)

        # If the current line is 'Alpha', we don't need to read any more.
        if line == 'Alpha':
           break

# Append prev_items to the results file.
with open('results.txt', 'a') as f:
    f.write('\n'.join(prev_items))

rawDescription: python search a string in a text file and copy a block

description: Python search a string in a text file and copy a block


code:
import os
import subprocess
import itertools

def line_to_filename(line):
    # This assumes that filenames have no spaces, which is a false assumption
    # Ex: /etc/NetworkManager/system-connections/Wired connection 1
    idx = line.rfind('->')
    if idx > -1:
        return line[:idx].split()[-1]
    else:
        return line.split()[-1]

rawDescription: Different results achieved using Python's os.walk function and ls command


code:
colnum = 2
for (rownum, words) in enumerate(row_list):
    w_sheet.write(rownum, colnum, ' '.join(words))

rawDescription: Python script not putting entire line in excel spreadsheet


rawDescription: python counting frequency of elements

description: Python counting frequency of elements


code:
def bind_method(object, methods):
    for method in methods:
        setattr(object, method.__name__, method)

rawDescription: Bind method to object runtime late binding


code: [('viewAllLimiter =', '9924')]

rawDescription: Search string with re module in html page


code:
class BlahTestCase(SessionTestCase):

    def test_blah_with_session(self):
        session = self.session
        session['operator'] = 'Jimmy'
        session.save()

rawDescription: How do I modify the session in the Django test framework

description: Modify the session in the Django test framework


code:
from matplotlib.patches import Rectangle

def zoomingBox(ax1, roi, ax2, color='red', linewidth=2, roiKwargs={}, arrowKwargs={}):
    '''
    **Notes (for reasons unknown to me)**
    1. Sometimes the zorder of the axes need to be adjusted manually...
    2. The figure fraction is accurate only with qt backend but not inline...
    '''
    roiKwargs = dict([('fill',False), ('linestyle','dashed'), ('color',color), ('linewidth',linewidth)] + roiKwargs.items())
    ax1.add_patch(Rectangle([roi[0],roi[2]], roi[1]-roi[0], roi[3]-roi[2], **roiKwargs))
    arrowKwargs = dict([('arrowstyle','-'), ('color',color), ('linewidth',linewidth)] + arrowKwargs.items())
    srcCorners = [[roi[0],roi[2]], [roi[0],roi[3]], [roi[1],roi[2]], [roi[1],roi[3]]]
    dstCorners = ax2.get_position().corners()
    srcBB = ax1.get_position()
    dstBB = ax2.get_position()
    if (dstBB.min[0]>srcBB.max[0] and dstBB.max[1]<srcBB.min[1]) or (dstBB.max[0]<srcBB.min[0] and dstBB.min[1]>srcBB.max[1]):
        src = [0, 3]; dst = [0, 3]
    elif (dstBB.max[0]<srcBB.min[0] and dstBB.max[1]<srcBB.min[1]) or (dstBB.min[0]>srcBB.max[0] and dstBB.min[1]>srcBB.max[1]):
        src = [1, 2]; dst = [1, 2]
    elif dstBB.max[1] < srcBB.min[1]:
        src = [0, 2]; dst = [1, 3]
    elif dstBB.min[1] > srcBB.max[1]:
        src = [1, 3]; dst = [0, 2]
    elif dstBB.max[0] < srcBB.min[0]:
        src = [0, 1]; dst = [2, 3]
    elif dstBB.min[0] > srcBB.max[0]:
        src = [2, 3]; dst = [0, 1]
    for k in range(2):
        ax1.annotate('', xy=dstCorners[dst[k]], xytext=srcCorners[src[k]], xycoords='figure fraction', textcoords='data', arrowprops=arrowKwargs)

rawDescription: Use subplots to zoom into timeseries or how I can draw lines outside of axis borders


rawDescription: Getting NLTK tree leaf values as a string


code:
dictionary = {'one': 1, 'two': 2, 'three': 3}
number = 2
dictionary2 = {}

for i in dictionary:
    dictionary2[i] = dictionary[i]*number

print(dictionary2)

rawDescription: Changing all the values of a dictionary

description: Changing all the values of a dictionary


code: t = sorted(a.items(), key=lambda x: x[1])

rawDescription: Create a hierarchy from a dictionary of lists


code:
www.google.com
www.hp.com
www.ibm.com

rawDescription: Running exactly x number of commands

description: Running exactly x number of commands


code:
import pandas as pd
import numpy as np

df = pd.DataFrame(range(50), columns  = ['filtercol'])
w = 0
x = 5
y = 17
z = 33
filter_values = [w, x, y, z]
out = pd.cut(df.filtercol, bins = filter_values)
counts = pd.value_counts(out)
# counts is a Series
print(counts)

rawDescription: Better binning in pandas

description: Better binning in pandas


code:
from bs4 import BeautifulSoup
import sys

for fi in sys.argv[1:]:
    with open(fi) as markup:
        soup = BeautifulSoup(markup.read())

    with open("strip_" + fi, "w") as f:
        f.write(soup.get_text().encode('utf-8'))

rawDescription: Python - beautifulsoup, apply in every text file in folder and produce new text file


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

import pandas as pd
from statsmodels.graphics import tsaplots

def label(ax, string):
    ax.annotate(string, (1, 1), xytext=(-8, -8), ha='right', va='top',
                size=14, xycoords='axes fraction', textcoords='offset points')

np.random.seed(1977)
data = np.random.normal(0, 1, 100).cumsum()

fig, axes = plt.subplots(nrows=4, figsize=(8, 12))
fig.tight_layout()

axes[0].plot(data)
label(axes[0], 'Raw Data')

axes[1].acorr(data, maxlags=data.size-1)
label(axes[1], 'Matplotlib Autocorrelation')

tsaplots.plot_acf(data, axes[2])
label(axes[2], 'Statsmodels Autocorrelation')

pd.tools.plotting.autocorrelation_plot(data, ax=axes[3])
label(axes[3], 'Pandas Autocorrelation')

# Remove some of the titles and labels that were automatically added
for ax in axes.flat:
    ax.set(title='', xlabel='')
plt.show()

rawDescription: bug of autocorrelation plot in matplotlib‘s plt.acorr?

description: Bug of autocorrelation plot in matplotlib‘s plt.acorr


code:
def get_string(s):
    for it in ast.walk(ast.parse(s)):
        if isinstance(it, ast.Str):
            yield it.s

rawDescription: Python find python strings in string

description: Python find python strings in string


code:
data = webURL.read()
print(data)
encoding = webURL.info().get_content_charset('utf-8')
JSON_object = json.loads(data.decode(encoding))

rawDescription: Loading JSON object in Python using urllib.request and json modules


code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import scipy.interpolate as interpolate

samples = { 0.0: 0.0, 0.4: 0.5, 0.5: 0.9, 0.6: 0.7, 0.8:0.3, 1.0: 1.0 }
x, y = zip(*sorted(samples.items()))

fig, ax = plt.subplots(nrows=3, sharex=True)
df1 = pd.DataFrame(index=np.linspace(0, 1, 31), columns=['raw', 'itp'], dtype=float)
df1.loc[x] = np.array(y)[:, None]

df2 = df1.copy()
df3 = df1.copy()

df1['itp'].interpolate('spline', order=3, inplace=True)
df2['itp'] = interpolate.UnivariateSpline(x, y, k=3)(df2.index)
df3['itp'].interpolate('spline', order=3, s=0, inplace=True)
for i, df in enumerate((df1, df2, df3)):
    df.plot(style={'itp': 'b-', 'raw': 'rs'}, figsize=(8, 6), ax=ax[i])
plt.show()

rawDescription: How to use `Series.interpolate` in pandas with the old values modified

description: Use `Series.interpolate` in pandas with the old values modified


code:
xml = '''<?xml version="1.0" encoding="utf-8"?>
<Test>
  <MyElement1>sdfsdfdsfd</MyElement1>
</Test>'''
from lxml import objectify
root = objectify.fromstring(xml)
root.find('.//MyElement1')
root.find('.//MyElement17')
root.find('.//MyElement17') is None

rawDescription: Test the existence of an Element with lxml.objectify


code:
import shlex, re

def foo(query):
    pieces = shlex.split(query)
    include, exclude = [], []
    for piece in pieces:
        if piece.startswith('-'):
            exclude.append(re.compile(piece[1:]))
        else:
            include.append(re.compile(piece))
    def validator(s):
        return (all(r.search(s) for r in include) and
                not any(r.search(s) for r in exclude))
    return validator

rawDescription: Python advanced string searching with operators and boolean


code: filter(lambda x: fdist[x] > 4, fdist)

rawDescription: nltk word pair count using fdist

description: Nltk word pair count using fdist


rawDescription: zip two values from the dictionary in Python

description: Zip two values from the dictionary in Python


code:
from StringIO import StringIO

data = StringIO('\n'.join(line.strip() for line in open('/etc/samba/smb.conf')))

parser = SafeConfigParser()
parser.readfp(data)
...

rawDescription: How can I remove the white characters from configuration file?

description: Remove the white characters from configuration file


code:
df2 = df2.set_index('item') # could just drop this column
df2.loc[res]  # reorder, may not be required

rawDescription: Python Pandas merge two data frames based on multiple values field


code:
import requests # pip install requests

r = requests.get(url)
unicode_str = r.text # may use `chardet` to auto-detect encoding

rawDescription: A good way to get the charset/encoding of an HTTP response in Python


code:
def digit_or_slash(s):
    return all(c.isdigit() or c == '/' for c in s)

rawDescription: How to I check that a string contains only digits and / in python?


code:
from statistics import mean
from operator import itemgetter
l = [['Hussain', 7, 8, 0], ['Max', 3, 4, 3], ['Alexandra', 10, 9, 8]]

print(sorted(([ele[0],mean(ele[1:])] for ele in l),key=itemgetter(1),reverse=True))

[['Alexandra', 9.0], ['Hussain', 5.0], ['Max', 3.3333333333333335]]

rawDescription: Sort tuple by averages

description: Sort tuple by averages


code:
# ASSUMING PYTHON3

user_input = input("Enter a list of numbers, comma-separated\n>> ")
user_input_as_list = user_input.split(",")
user_input_as_numbers_in_list = map(float, user_input_as_list) # maybe int?
# This will fail if the user entered any input that ISN'T a number

def sum(lst):
    accumulator = 0
    for element in lst:
        accumulator += element
    return accumulator

rawDescription: Writing a custom sum function that sums a list of numbers


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

# a simple plot function we can reuse (taken from the seaborn tutorial)
def sinplot(flip=1):
    x = np.linspace(0, 14, 100)
    for i in range(1, 7):
        plt.plot(x, np.sin(x + i * .5) * (7 - i) * flip)

sinplot()

# this will have the matplotlib defaults
plt.savefig('seaborn-off.png')
plt.clf()

# now import seaborn
import seaborn as sns

sinplot()

# this will have the seaborn style
plt.savefig('seaborn-on.png')
plt.clf()

# reset rc params to defaults
sns.reset_orig()

sinplot()

# this should look the same as the first plot (seaborn-off.png)
plt.savefig('seaborn-offagain.png')

rawDescription: Seaborn configuration hides default matplotlib


code:
import pandas as pd

# make 1000 random times throughout the year
N = 1000
times = pd.date_range('2014', '2015', freq='min')
ind = np.random.permutation(np.arange(len(times)))[:N]

data = pd.DataFrame({'TIMESTAMP': times[ind],
                     'TYPE': np.random.randint(0, 10, N)})
data.head()

rawDescription: Average of daily count of records per month in a Pandas DataFrame


code:
r = {
    'coh':   lambda: (my_coherence(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean), my_coherence(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean), freqs, freqs_surro),
    'imcoh': lambda: (my_imcoh(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean), my_imcoh(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean), freqs, freqs_surro),
    'cohy':  lambda: (my_cohy(n_freqs, Rxy_mean, Rxx_mean, Ryy_mean), my_cohy(n_freqs, Rxy_s_mean, Rxx_s_mean, Ryy_s_mean), freqs, freqs_surro),
    'plv':   lambda: (my_plv(n_freqs, Rxy, Rxy_mean), my_plv(n_freqs, Rxy_s, Rxy_s_mean), freqs, freqs_surro),
    'pli':   lambda: (my_pli(n_freqs, Rxy, Rxy_mean), my_pli(n_freqs, Rxy_s, Rxy_s_mean), freqs, freqs_surro),
    'wpli':  lambda: (my_wpli(n_freqs, Rxy, Rxy_mean), my_wpli(n_freqs, Rxy_s, Rxy_s_mean), freqs, freqs_surro),
    }
return r[con_name]()

rawDescription: Compromising Python if statement

description: Compromising Python if statement


rawDescription: How to make a label with the background color as a color chosen by the user?

description: Make a label with the background color as a color chosen by the user


code:
from suds.client import Client
url = 'http://localhost:7080/webservices/WebServiceTestBean?wsdl'
client = Client(url)

rawDescription: Backend for SOAP in Python

description: Backend for SOAP in Python


code:
hints = ["a", "b", "c"]
generators = list(map(gen_fun, hints))
for x in zip(*generators):
    for txt in x:
        print(txt)

rawDescription: Transpose nested generators

description: Transpose nested generators


code:
result = ""
for key in self.cases.keys():
    a = key, self.cases[key].color, self.cases[key].thetype
    b = str(a) + "\n"
    result = result + b
return result

rawDescription: how to return the iterations over keys as a string?

description: Return the iterations over keys as a string


code: sum([n for n in xrange(1,24) if 24 % n == 0])

rawDescription: sum of factors of a given number

description: Sum of factors of a given number


code:
import argparse
parser = argparse.ArgumentParser(description='details',
        usage='use "%(prog)s --help" for more information',
        formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('--argument', default=None,
        help='''
             First line
             Second line

             More lines
             ''')
parser.print_help()

rawDescription: Multiple lines in python argparse help display


code:
with open("mylist.txt","w") as f: #in write mode
    f.write("{}".format(mylist))

rawDescription: Python Storing Data

description: Python Storing Data


code: hours, minutes = int(input[0:2]), int(input[2:4])

rawDescription: 24-Hour Time Conversion to 12-Hour Clock (ProblemSetQuestion) on Python


code:
sums = {}
for element in data:
    sums[element] = data.count(element) * element

# sums[4] = sum of 4s

rawDescription: calculate the sum of repeated numbers in a tuple

description: Calculate the sum of repeated numbers in a tuple


code:
from datetime import *
from dateutil.relativedelta import *

days_to_substract = 64
my_date   = (date.today()-timedelta(days=days_to_substract))
next=my_date+relativedelta(weekday=MO)
previous=my_date+relativedelta(weekday=MO(-1))
print ('mydate is %s' %my_date)
print ('next monday is %s' %next)
print ('previous monday is %s' %previous)

diff1=my_date-previous
diff2=next-my_date
if diff2<diff1:
    print ('Closest monday is %s' %next)
else:
    print ('Closest monday is %s' %previous)

rawDescription: Rounding dates in Python

description: Rounding dates in Python


code:
import functools
class reprwrapper(object):
    def __init__(self, repr, func):
        self._repr = repr
        self._func = func
        functools.update_wrapper(self, func)
    def __call__(self, *args, **kw):
        return self._func(*args, **kw)
    def __repr__(self):
        return self._repr(self._func)

rawDescription: Possible to change a function's repr in python?


code:
class RwBunch(object):
  def __init__(self, adict):
    self.__dict__ = adict

rawDescription: Accesing dictionary with class attribute


code:
import os
def isLink(a, b):
    return os.path.islink(a) and os.path.realpath(a) == os.path.realpath(b)

rawDescription: If path is symlink to another path

description: If path is symlink to another path


code:
# make sure value is not "[]" or "[[]]"
{k: v for k, v in complete_list.iteritems() if v and v[0]}

rawDescription: Removing empty dictionary elements in Python


code:
import subprocess
p1 = subprocess.Popen(["cat", "file.log"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["tail", "-1"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output,err = p2.communicate()

rawDescription: Call a shell command containing a 'pipe' from Python and capture STDOUT


code:
qs = PlayerStats.objects.select_related().all().extra(Sum('goals'))
qs.group_by = ('player', 'match')
for player in qs:
    qs.player.name # player's name
    qs.goals__sum # goals per match

rawDescription: Django collect elements from database

description: Django collect elements from database


code:
binary = 'binaryfile.png'
data2d = np.fromfile('binaryfile.png', count=10, dtype=('int16', 10)).astype('double')

rawDescription: Reading binary file in two dimension

description: Reading binary file in two dimension


code:
config = generate_initial_configuration()
for i in range(max_rounds):
    new_config = next_configuration(config)
    if new_config == config:
        break
    config = new_config

rawDescription: Simple solitaire

description: Simple solitaire


code:
namelist = [d for d in data]
namelist.sort(key=lambda x: x[0])
namelist

rawDescription: Doubly Linked list in Python

description: Doubly Linked list in Python


code:
#!/usr/bin/env python
import io
import shlex
from functools import partial
from subprocess import Popen, PIPE
from threading import Thread
from Queue import Queue

def count_lines(pipe, queue, chunksize=io.DEFAULT_BUFFER_SIZE):
    #NOTE: you could write intermediate results here (just drop `sum()`)
    queue.put(sum(chunk.count(b'\n')
                  for chunk in iter(partial(pipe.read, chunksize), b'')))
    pipe.close()

p = Popen(shlex.split('unrar.exe x -y myfile.rar'), stdout=PIPE, bufsize=-1)
result = Queue()
Thread(target=count_lines, args=[p.stdout, result]).start()
p.wait() # you can omit it if you want to do something else and call it later
number_of_lines = result.get() # this blocks (you could pass `timeout`)

rawDescription: Work with the stdout of some other process (created with Popen)


rawDescription: Python’s argh library: preserve docstring formatting in help message


code:
el.attrib.clear()
el.tag = '|||'
text = lxml.html.tostring(el)
assert text.startswith('<'+el.tag+'>') and text.endswith('</'+el.tag+'>')
text = text[len('<'+el.tag+'>'):-len('</'+el.tag+'>')]

rawDescription: Python, lxml and removing outer tag from using lxml.html.tostring(el)


code:
Counter({'Item': 2, 'Timestamp': 1})
2

rawDescription: How to detect number of xml nodes?

description: Detect number of xml nodes


code:
this_row=0
this_column=0
for nextWidget in range(len(titles)):
    ...
    this_column += 1
    if this_column > 1:
        this_row += 1
        this_column = 0

rawDescription: Iteration to place widgets in Tkinter and Pmw


code: {{ wtf.quick_form(form, action="/fancy_url") }}

rawDescription: Flask WTF – Forms always redirect to root


code:
class sampleClass:
    def __init__(self, tup):
            self.tup = tup
    def __str__(self): #To print it
            return str(tuple([item if item <= 10 else 10 for item in self.tup])) #List comprehension to replace x > 10 with 10, then convert to a tuple, then surround with quotes so __str__ accepts it
    def __getitem__(self, ind): #To access by index e.g. x[1], x[-1] etc.
            return self.tup[ind]

rawDescription: How to access tuple's elements in a class that inherits it

description: Access tuple's elements in a class that inherits it


code: df['newcol'] = (df['A'] == df['B']).astype('int')

rawDescription: Python Compare rows in two columns and write a result conditionally


code:
items = '15674 24000 Manager Gregory the 1st John\n'
number, salary, position, rest = items.split(None, 3)
oname, first = rest.rsplit(None, 1)
first, oname, number, position, salary

rawDescription: Tuple rearrangment Python

description: Tuple rearrangment Python


code:
import pickle

WordList = ["cat", "hat", "jump", "house", "orange", "brick", "horse", "word"]

# do your thing here, like
Wordlist.append("monty");

#open a pickle file
newfile = 'mypickle.pk'

with open(newfile, 'wb') as fi:
  # dump your data into the file
  pickle.dump(Wordlist, fi)

rawDescription: Keeping the data of a variable between runs of code


code:
from setuptools import setup

setup(
    name='confectionary',
    version='2.0.0',
    py_modules=['confectionary'],
    entry_points='''
        [console_scripts]
        praline=confectionary.confections:praline
        lime_coconut=confectionary.confections:lime_coconut
    ''',
)

rawDescription: Can I get pip to delete scripts that I installed but no longer want?

description: Get pip to delete scripts that I installed but no longer want


code:
def numPens(n):
  pen_sizes = [5, 8, 24]
  results = [True]
  for i in range(1, n+1):
    results.append(any(i >= size and results[i - size] for size in pen_sizes))
  return results[n]

rawDescription: Find if a number is a possible sum of two or more numbers in a given set - python


rawDescription: .gz file to pandas DataFrame with hive delimiter


rawDescription: Python: easiest way to flatten a tupple containing another tupple from a function


code:
import datetime
start_time = datetime.datetime(2011,3,10,15,45,48)
end_time = datetime.datetime(2011,3,10,18,4,0)

rawDescription: Converting date into hours

description: Converting date into hours


code:
def language_values(line):
    for entry in line.split(';'):
        lang, nums = entry.split(':', 1)
        yield lang.strip(), [n.strip() for n in nums.split(',')]

{k: dict(language_values(v)) for k, v in tuplist}

rawDescription: How to convert this tuple list to this dict in a Pythonic way?

description: Convert this tuple list to this dict in a Pythonic way


code:
bgColor='#1F1F1F'
appStyle="""
QToolButton {{border: 0px solid #0F0F0F; background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #7A7A7A, stop: 1 #0F0F0F); color: #EBEBEB}}
QMenu QAbstractItemView  {{ border: 0px solid black; background-color: #7A7A7A; color: #EBEBEB; border-radius: 0; }}
QMenu {{  font-size:10pt; selection-background-color: #ffaa00; selection-color: black; background-color: #7A7A7A; border-style: solid; border: 0px solid #EBEBEB; border-radius: 0; color: #EBEBEB; padding: 0px 0px 0px 0px; }}
QMenu:on  {{padding-top: 0px; padding-left: 0px; background-color: #7A7A7A; selection-background-color: #ffaa00; color: #EBEBEB; border-radius: 0;}}
QMenu:hover {{ border: 0px solid #ffa02f; }}
QMenu::drop-down  {{ border-radius: 0px; background-color: #7A7A7A; color: #EBEBEB; }}""".format(bgColor)

class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        button=QToolButton(self)
        button.setText('Click Here')

        menu=QMenu(self)
        menu.addAction("Action01")
        menu.addAction("Action02")
        menu.addAction("Action03")

        separator=menu.addAction("")
        separator.setSeparator(True)

        subMenu=menu.addMenu('SubMenu')
        subMenu.addAction("SubAction01")
        subMenu.addAction("SubAction02")
        subMenu.addAction("SubAction03")

        button.setMenu(menu)
        button.setPopupMode(QToolButton.InstantPopup)

app=QApplication(sys.argv)
view=Window()
view.setStyleSheet(appStyle)
view.show()
sys.exit(app.exec_())

rawDescription: How to apply CSS Style to QMenu via an entire MainWIndow

description: Apply CSS Style to QMenu via an entire MainWIndow


code:
class Direction(object):
    x, y, z = None, None, None

class Coefficients(object):
    x, y, z = None, None, None

class Ray(object):
    direction = Direction()
    coefficients = Coefficients()

def create_ray(point1, direction):
    ray = Ray()
    ray.direction.x = direction.x;
    ray.coefficients.x = point1.x;
    ray.direction.y = direction.y;
    ray.coefficients.y = point1.y;
    ray.direction.z = direction.z;
    ray.coefficients.z = point1.z;
    return ray

rawDescription: MATLAB Function declaration

description: MATLAB Function declaration


code:
for series in doc.xpath('/series_ts/Data_Set/Series'):
    print(series.attrib)
    # {'calc_kind': 'Weighted',
    #  'name_ser': 'Number Of Companies That Answered',
    #  'get_time': '2011-06-21',
    #  'name_topic': "Business Tendency Survey - Distributions Of Businesses By Industry, Kind Of Questions And Answers  - Manufacturing - Company'S Experience Over The Past Three Months - Orders For Export",
    #  'time_unit': 'Month',
    #  'code_series': '22978',
    #  'data_kind': '5-10 Employed Persons',
    #  'decimals': '0',
    #  'unit_kind': 'Number'}

    for elt in series.xpath('obs'):
        print(elt.attrib)
        # {'time_period': ' 2010-12', 'value': '40'}
        # {'time_period': ' 2011-01', 'value': '38'}
        # {'time_period': ' 2011-02', 'value': '40'}
        # {'time_period': ' 2011-03', 'value': '36'}
        # {'time_period': ' 2011-04', 'value': '30'}
        # {'time_period': ' 2011-05', 'value': '33'}

rawDescription: How can I scrape data from the Israeli Bureau of Statistics web query tool?

description: Scrape data from the Israeli Bureau of Statistics web query tool


code:
for (vv,hh) in zip(VV1,HH1):
    comp+= numpy.min((vv-precomp[...,0])**2+(hh-precomp[...,1])**2, axis=2)

rawDescription: How to avoid using for-loops with numpy?

description: Avoid using for-loops with numpy


code:
import itertools as IT
zero_to_nine = range(10)
even_digits = [2, 4, 6, 8]
odd_digits = [1, 3, 5, 7, 9]
flipflops = 0
for ndigits in range(2, 10):
    for digits in IT.product(*(
            [odd_digits] + [zero_to_nine]*(ndigits-2) + [even_digits])):
        reversed_digits = digits[::-1]
        carry = 0
        # print('testing {!r}'.format(digits))
        for a, z in zip(digits, reversed_digits):
            total = a+z+carry
            # print('total: {}'.format(total))
            if total % 2 == 0:
                break
            else:
                carry = total//10
        else:
            # print('{!r} + {!r}'.format(digits, reversed_digits))
            flipflops += 1
print(flipflops)

rawDescription: How many inverse numbers equal only odd numbers under 1 billion


code: my_tuple = 1    # my_tuple is the integer 1, not a one-element tuple!

rawDescription: Python string formatting

description: Python string formatting


rawDescription: Fill 24 hours of data into five years of hourly dataframe


code:
def is_implemented_in_c(obj):
    if isinstance(obj, (types.FunctionType, types.LambdaType)):
        return False
    elif isinstance(obj, type):
        if '__dict__' in dir(obj): return False
        return not hasattr(obj, '__slots__')
    # We accept also instances of classes.
    # Return True for instances of C classes, False for python classes.
    return not isinstance(obj, types.InstanceType)

rawDescription: Determine whether a Python function is already implemented in C extension


code: treeFunction = lambda x,y: mult(2, add(x, y))

rawDescription: Dynamically generating a function tree in Python.


code: met_dir, out_dir = [...]

rawDescription: Update elements of a list

description: Update elements of a list


rawDescription: Not able to view all columns in Pandas Data frame


code:
num = 0
for tags in csvData:
    num += 1

rawDescription: Python Conditional XML Writing

description: Python Conditional XML Writing


rawDescription: Getting the Max Value from a Dictionary

description: Getting the Max Value from a Dictionary


code:
from lxml import etree
parser = etree.XMLParser(remove_blank_text=True)
xmlData = etree.parse('test.xml', parser )

rawDescription: XML file edit with Python script

description: XML file edit with Python script


code:
output_file = open("/path/to/output.txt", "w")
CSVJSON(args, output_file).main()
output_file.close()

rawDescription: csvkit & django a.k.a. using csvkit as modules instead of from command line

description: Csvkit & django a.k.a. using csvkit as modules instead of from command line


rawDescription: How can I have my program read updates that it has just made to a text file?

description: Have my program read updates that it has just made to a text file


code:
u = (evec/evec.sum()).real
u
np.dot(u.T, M).T

rawDescription: find Markov steady state with left eigenvalues (using numpy or scipy)

description: Find Markov steady state with left eigenvalues (using numpy or scipy)


code:
from pysnmp.smi import view, builder

mibViewController = view.MibViewController(builder.MibBuilder())
varName = mibvar.MibVariable('1.3.6.1.6.3.10.2.1.1.0').loadMibs('SNMP-FRAMEWORK-MIB').resolveWithMib(mibViewController)
print(varName.getMibNode().getSyntax().clone('12341234'))

rawDescription: Translate OID value pairs from MIB textual convention using pysnmp


code:
class ProgressBarObserver(object):
  def __init__(self, progbar):
    self.progbar = progbar
  def progress_total(self, n):
    self.progbar.setRange(0, n)
  def progress(self, i):
    self.progbar.setValue(i)

rawDescription: Sending progress from thread to gui

description: Sending progress from thread to gui


code:
somestring = 'abcd'

with open("test.bin", "wb") as file:
    file.write(somestring)

rawDescription: Writing an ASCII string as binary in python


code:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext

setup(
    cmdclass = {'build_ext': build_ext},
    ext_modules = [
    Extension("elps",
              sources=["elps.pyx", "src/ITestClass.cpp"],
              libraries=["elp"],
              language="c++",
              )
    ]
)

rawDescription: Can I override a C++ virtual function within Python with Cython?

description: Override a C++ virtual function within Python with Cython


code:
def calculateProportions(strategies,proportions):
    import copy
    import itertools
    combinations = []
    columns = list(itertools.product(strategies, repeat=3))
    for i in range(0, len(columns)):
        columns[i] = list(columns[i])
    for n in range(0, len(strategies)):
        combinations.append(copy.deepcopy(columns))

rawDescription: Cloned list seems to be functioning as an alias, even though explicitly declared as a a clone


code: expected = '<ComponentMain><Component /></ComponentMain>'

rawDescription: Filtering XML in Python

description: Filtering XML in Python


code: exec('python /path/to/file.py');

rawDescription: run python script with html button

description: Run python script with html button


code:
df = DataFrame(np.random.randint(0,10,size=100).reshape(10,10))
df
Series(df.values.ravel()).unique()

rawDescription: unique values in a pandas dataframe

description: Unique values in a pandas dataframe


code:
import weakref

class ClassA:
    def __init__(self):
        self._callbacks = []

    def registerCallback(self, callback):
        try:
            # methods
            callback_ref = weakref.ref(callback.__func__), weakref.ref(callback.__self__)
        except AttributeError:
            callback_ref = weakref.ref(callback), None
        self._callbacks.append(callback_ref)

    def __del__(self):
        for callback_ref in self._callbacks:
            callback, arg = callback_ref[0](), callback_ref[1]
            if arg is not None:
                # method
                arg = arg()
                if arg is None:
                    # instance is gone
                    continue
                callback(arg, self)
                continue
            else:
                if callback is None:
                    # callback has been deleted already
                    continue
                callback(self)

rawDescription: using python WeakSet to enable a callback functionality

description: Using python WeakSet to enable a callback functionality


code:
land = (points[tri.simplices][...,2] > 0).any(axis=1)
triangles = tri.simplices[land]
len(triangles)

rawDescription: Algorithm for finding approximate area of the ground via elevation grid?


code: admin.site.register(Site) # Notice that no ModelAdmin is passed

rawDescription: Validation to site.domain fieald

description: Validation to site.domain fieald


code:
from mininet.topo import Topo

class MyTopo( Topo ):

    def __init__( self ):

        Topo.__init__( self )

        # Add hosts and switches
        left_host = self.addHost( 'h1' )
        right_host = self.addHost( 'h2' )
        left_switch = self.addSwitch( 's0' )
        right_switch = self.addSwitch( 's2' )

        # Add links
        self.addLink( leftHost, left_switch, bw=10, delay='10ms', loss=0, max_queue_size=1000 )
        self.addLink( left_switch, right_switch, bw=10, delay='10ms', loss=0, max_queue_size=1000 )
        self.addLink( right_switch, rightHost, bw=10, delay='10ms', loss=0, max_queue_size=1000 )

topos = { 'mytopo': ( lambda: MyTopo() ) }

rawDescription: Save my own topology:Mininet

description: Save my own topology:Mininet


code:
class FlashableLabel(tk.Label):
    def flash(self,count):
        bg = self.cget('background')
        fg = self.cget('foreground')
        self.configure(background=fg,foreground=bg)
        count +=1
        if (count < 31):
             self.after(1000,self.flash, count)

rawDescription: How to flash tkinter label limited number of times, and only if conditions are met

description: Flash tkinter label limited number of times, and only if conditions are met


code:
session = mapi.MAPILogonEx(0, MAPIProfile, None, mapi.MAPI_EXTENDED |
                           mapi.MAPI_USE_DEFAULT)

rawDescription: Python - Sending Outlook email from different address using pywin32


code:
def addTab(self, widget, name):
    self.stacked.addWidget(widget)
    self.tabBar.addTab(name)

rawDescription: remove padding/margin from QTabBar in QLayout

description: Remove padding/margin from QTabBar in QLayout


code: names = [name.strip() for name in authors.split(r'\and')]  # assuming a raw \ here, not the escape code \a.

rawDescription: Join author names with python: first ones by comma and last one by and


code:
unique = set(zip(StringA, StringB))
unique

rawDescription: Finding unique combinations of two strings in python


rawDescription: How to set some xlim and ylim in Seaborn lmplot facetgrid

description: Set some xlim and ylim in Seaborn lmplot facetgrid


code:
tk.SEL_FIRST + '-6c', tk.SEL_FIRST  # for \term{
tk.SEL_LAST, tk.SEL_LAST + '+1c'    # for }

rawDescription: Adding coloured text to selected text - Tkinter


rawDescription: How can i overwrite the dictionary key names in python

description: Overwrite the dictionary key names in python


code: slider = Slider(parent, from_=0, to=100000, command=callback)

rawDescription: tkinter: slider ("scale") with discrete steps?

description: Tkinter: slider ("scale") with discrete steps


rawDescription: How to set QTextDocument margins and other properties (setHTML, print to pdf)?

description: Set QTextDocument margins and other properties (setHTML, print to pdf)


code: import re

rawDescription: Python regex - split string at back to back line breaks with [possibly] spaces in between


code: list(powerset("abcd"))

rawDescription: what's a good way to combinate through a set?

description: What's a good way to combinate through a set


code:
from timeit import timeit
setup = """
import re
a = 'a[b]cdef[g ]hi[ j]klmno[ p ]'
d = {'b':2,'g':7,'j':10,'p':16}
"""
timeit(r"re.sub(r'\[\s?(.*?)\s?\]',r'{\1}',a).format(**d)", setup)
timeit(r"re.sub(r'\[\s?(.*?)\s?\]', lambda m: str(d[m.group(1)]), a)", setup)

rawDescription: Python regex substitution using a dictionary


rawDescription: Numpy: placing values into an 1-of-n array based on indices in another array


rawDescription: Django, redirected url is not proper

description: Django, redirected url is not proper


code:
L = []
for i in lst:
    if i == y:
        L.append(i)

rawDescription: Writing the filter() function using for/while loops


code:
QUERY = 'www.foo.com' + '/bar?' \
        + '&title=%(title)s' \
        + '&start=%(start)i' \
        + '&num=%(num)s'

rawDescription: Modify a python script with bash and execute it with the changes


code:
import re
query = "SELECT * FROM `users` WHERE user='$user' AND password='$pass';";
re.findall(r"='(\$\w+)'", query)

rawDescription: Regex capturing inserted variables in PHP SQL string statements


rawDescription: How do i find out how many individual letters there are in a word in python?

description: Find out how many individual letters there are in a word in python


code:
df = []
for f in ['c:\\file1.xls', 'c:\\ file2.xls']:
    data = pd.read_excel(f, 'Sheet1').iloc[:-2]
    data.index = [os.path.basename(f)] * len(data)
    df.append(data)

df = pd.concat(df)

rawDescription: Using pandas Combining/merging 2 different Excel files/sheets


rawDescription: Numpy.loadtxt imports data as array of arrays rather than a multidimension array


code:
import signal

X = False

def handle_alarm(signum, frame):
    global X
    X = False

signal.signal(signal.SIGALRM, handle_alarm)

def set_X_true_then_false_later(secs=3600):
    global X
    X = True
    signal.alarm(secs)

rawDescription: killing a thread in python before its done

description: Killing a thread in python before its done


code: [u"Mykolaiv, Mykolaivs'ka oblast, Ukraine, 54000", u'54000 Nancy, France', u'54000, Thailand', u'Kampung Datuk Keramat, 54000 Kuala Lumpur, Federal Territory of Kuala Lumpur, Malaysia', u'Tlalnepantla Centro, 54000 Tlalnepantla, M\xe9x., Mexico', u'54000, Broken Bow, OK 74728, USA', u'54000, Oklahoma, USA']

rawDescription: geopy does not show correct output

description: Geopy does not show correct output


code: text = plt.text(x, y, "Some text")

rawDescription: Change matplotlib.pyplot text() object properties


code:
line  = ['aaaa, 1111, BOB, 7777','aaaa, 1111, BOB, 8888','aaaa, 1111, larry, 7777','aaaa, 1111, Steve, 8888','BBBB, 2222, BOB, 7777']
from pprint import pprint
pprint(sorted(line, key=lambda l: l.lower().split(', ')[2:0:-1]))

rawDescription: Python Line Sorting -

description: Python Line Sorting -


code:
for entry in entries:
    print(entry.get())

rawDescription: Loading a list into seperate Entry widgets


code:
## @package another
#
#  Another module

import func

## This function calls func.foo()
def another():
     foo()

rawDescription: Doxygen python linking to functions

description: Doxygen python linking to functions


rawDescription: elegant unpacking variable-length tuples

description: Elegant unpacking variable-length tuples


code:
from nltk import word_tokenize
from nltk.util import ngrams
text = """hi ya. see you tomorrow. it is fine, thank you. my name is blah blah blah. attention to the words..."""
list(ngrams(word_tokenize(text), 2))
bigrams = list(ngrams(word_tokenize(text), 2))
trigrams = list(ngrams(word_tokenize(text), 3))
fourgrams = list(ngrams(word_tokenize(text), 4))
[i for i in trigrams if i[:-1] not in bigrams]
[i for i in fourgrams if i[:-1] not in trigrams]
[i for i in fourgrams if i[:-2] not in bigrams]
len([i for i in trigrams if i[:-1] in bigrams]) == len(trigrams)

rawDescription: Python Nltk: ngrams filtration

description: Python Nltk: ngrams filtration


code: [(d["Name"], d["Address"]) for item in (v if type(v) is list else [v] for v in D.values())]

rawDescription: What is the Pythonic way to iterate over a dict of dicts and lists?


code: self.text.mark_set("insert", "%s+1c" % ...)

rawDescription: tkinter text widget: Setting the insertion curser

description: Tkinter text widget: Setting the insertion curser


code:
"""All grouping functionality is collected here."""
from collections import namedtuple
from numpy import r_, arange, argsort, array, ones, pi, where
from numpy import logical_and as land
from radial_support import from_polar

__all__= ['tree', 'pre_order', 'post_order']

Node= namedtuple('Node', 'ndx lnk')

# ToDo: enhance documentation
def _groub_by(p, tol, r):
    g, gm, gp= [], [], p- p[0]
    while True:
        if gp[-1]< 0: break
        ndx= where(land(0.<= gp, gp< tol))[0]
        if 0< len(ndx):
            g.append(ndx)
            gm.append(p[ndx].mean())
        gp-= tol
    return g, array([gm, [r]* len(gm)])

def _leafs(p):
    return argsort(p[0])

def _create_leaf_nodes(ndx):
    nodes= []
    for k in xrange(len(ndx)):
        nodes.append(Node(ndx[k], []))
    return nodes

def _link_and_create_nodes(_n, n_, cn, groups):
    nodes, n0= [], 0
    for k in xrange(len(groups)):
        nodes.append(Node(n_+ n0, [cn[m] for m in groups[k]]))
        n0+= 1
    return n_, n_+ n0, nodes

def _process_level(nodes, polar, p, tol, scale, _n, n_):
    groups, p= _groub_by(p, tol, scale* polar[1, _n])
    _n, n_, nodes= _link_and_create_nodes(_n, n_, nodes, groups)
    polar[:, _n: n_]= p
    return nodes, polar, _n, n_

def _create_tree(p, r0, scale, tols):
    if None is tols:
        tols= .3* pi/ 2** arange(5)[::-1]
    _n, n_= 0, p.shape[1]
    polar= ones((2, (len(tols)+ 2)* n_))
    polar[0, :n_], polar[1, :n_]= p[0], r0
    # leafs
    nodes= _create_leaf_nodes(_leafs(p))
    nodes, polar, _n, n_= _process_level(
    nodes, polar, polar[0, _leafs(p)], tols[0], scale, _n, n_)
    # links
    for tol in tols[1:]:
        nodes, polar, _n, n_= _process_level(
        nodes, polar, polar[0, _n: n_], tol, scale, _n, n_)
    # root
    polar[:, n_]= [0., 0.]
    return Node(n_, nodes), polar[:, :n_+ 1]

def _simplify(self):
    # ToDo: combine single linkages
    return self._root

def _call(self, node0, node1, f, level):
    f(self, [node0.ndx, node1.ndx], level)

def pre_order(self, node0, f, level= 0):
    for node1 in node0.lnk:
        _call(self, node0, node1, f, level)
        pre_order(self, node1, f, level+ 1)

def post_order(self, node0, f, level= 0):
    for node1 in node0.lnk:
        post_order(self, node1, f, level+ 1)
        _call(self, node0, node1, f, level)

class tree(object):
    def __init__(self, p, r0= pi, scale= .9, tols= None):
        self._n= p.shape[1]
        self._root, self._p= _create_tree(p, r0, scale, tols)

    def traverse(self, f, order= pre_order, cs= 'Cartesian'):
        self.points= self._p
        if cs is 'Cartesian':
            self.points= from_polar(self._p)
        order(self, self._root, f, 0)
        return self

    def simplify(self):
        self._root= _simplify(self)
        return self

    def is_root(self, ndx):
        return ndx== self._p.shape[1]- 1

    def is_leaf(self, ndx):
        return ndx< self._n

if __name__ == '__main__':
    # ToDO: add tests
    from numpy import r_, round
    from numpy.random import rand
    from pylab import plot, show

    def _l(t, n, l):
        # print round(a, 3), n, l, t.is_root(n[0]), t.is_leaf(n[1])
        plot(t.points[0, n], t.points[1, n])
        if 0== l:
            plot(t.points[0, n[0]], t.points[1, n[0]], 's')
        if t.is_leaf(n[1]):
            plot(t.points[0, n[1]], t.points[1, n[1]], 'o')

    n= 123
    p= r_[2* pi* rand(1, n)- pi, ones((1, n))]
    t= tree(p).simplify().traverse(_l)
    # t= tree(p).traverse(_l, cs= 'Polar')
    show()
    # print
    # t.traverse(_l, post_order, cs= 'Polar')

rawDescription: How do I create a radial cluster like the following code-example in Python?

description: Create a radial cluster like the following code-example in Python


code:
a = numpy.matrix(a)
b = numpy.matrix(b)
c = a+b
d = a*b

rawDescription: Adding 2 matrix and Multiplying 2 matrix in python by using scipy/numpy


rawDescription: Pythonic way to convert two adjacent list elements to a tuple and preserve rest of list


code:
db((db.t_proyecto.id==db.t_informe.f_proyecto) &
   (db.t_informe.id==db.t_gasto.f_informe)).select(db.t_gasto.f_monto.sum(), db.t_proyecto.f_nombre, groupby=db.t_proyecto.f_nombre)

rawDescription: web2py DAL complex query

description: Web2py DAL complex query


code:
"""
Download zip file
""".format(movedZip)

rawDescription: Variable web link in python

description: Variable web link in python


code:
class Test(object):
    def __init__(self):
       for i in dir(self):
           result = getattr(self, i)
           if i.startswith('fetch') and hasattr(result, '__call__'):
               result()

rawDescription: call all method of class that start with something

description: Call all method of class that start with something


code:
class IPAddressSerializer(serializers.ModelSerializer):

     class Meta:
         model = IPAddress
         fields: ('address',)

class RuleSerializer(serializers.ModelSerializer):

    ips = IPAddressSerializer(many=True)

    class Meta:
         model = Rule
         fields: ('name', 'ips')

rawDescription: ManyToMany relation custom serializer

description: ManyToMany relation custom serializer


code:
from subprocess import call

def valid_password(password):
    rc = call(true_crypt_command(password), close_fds=True)
    return rc == 0, password

rawDescription: Python multiprocessing with subprocess stops working


rawDescription: Determining all sub-vector combinations of a binary vector for a certain hamming weight


code:
from array import array
output_file = open('file', 'wb')
float_array = array('d', [3.14, 2.7, 0.0, -1.0, 1.1])
float_array.tofile(output_file)
output_file.close()

rawDescription: How to output list of floats to a binary file in Python

description: Output list of floats to a binary file in Python


rawDescription: Sort numeric lines with thousand separators


code:
hellocan
hellobe
helloof
hellodifferent
hellosizes
hello111
hello111can
hello111be
hello111of
hello111different
hello111sizes
hello450
hello450can
hello450be
hello450of
hello450different
hello450sizes
hellonice
hellonicecan
hellonicebe
helloniceof
hellonicedifferent
hellonicesizes
goodbyecan
goodbyebe
goodbyeof
goodbyedifferent
goodbyesizes
goodbye111
goodbye111can
goodbye111be
goodbye111of
goodbye111different
goodbye111sizes
goodbye450
goodbye450can
goodbye450be
goodbye450of
goodbye450different
goodbye450sizes
goodbyenice
goodbyenicecan
goodbyenicebe
goodbyeniceof
goodbyenicedifferent
goodbyenicesizes
foocan
foobe
fooof
foodifferent
foosizes
foo111
foo111can
foo111be
foo111of
foo111different
foo111sizes
foo450
foo450can
foo450be
foo450of
foo450different
foo450sizes
foonice
foonicecan
foonicebe
fooniceof
foonicedifferent
foonicesizes

rawDescription: want to combine every element of a list with every element of n lists

description: Want to combine every element of a list with every element of n lists


code:
with open('output.csv', 'wb') as f:
    w = csv.writer(f, delimiter='\t')
    for key in keys:
        w.writerow([key], [dct[item].get(key, '') for item in lst])

rawDescription: In Python, how do I write the contents of nested dictionaries to a file in a certain format?


code:
if ((search(x+1, y, mazeList))
        or (search(x, y-1, mazeList))
        or (search(x-1, y, mazeList))
        or (search(x, y+1, mazeList))):
        mazeList[x][y] = 'o'
        return True

rawDescription: Python Maze solving program: how to mark correct path


code:
pi = 3.141
x = list(str(pi))
x.remove('.')
map(int,x)

rawDescription: Separate float into digits

description: Separate float into digits


rawDescription: A more optimized code in recursion exercise


code: filter(bool, my_str.split(';'))

rawDescription: python split function -avoids last empy space

description: Python split function -avoids last empy space


rawDescription: How do I select from a many-to-many intermediate model in django?

description: Select from a many-to-many intermediate model in django


rawDescription: os.chdir() is not working in mac

description: Os.chdir() is not working in mac


code:
del m.keys
m.__iter__.return_value = [("a","A"),("b","B"),("c","C")]
dict(m)
#Little bit generic
m.__iter__.return_value = d.items()
dict(m)

rawDescription: calling python builtin dict on a mock

description: Calling python builtin dict on a mock


code: df['Date'] = pd.to_datetime(df['Date'])

rawDescription: How to filter out values by values in Pandas.DataFrame

description: Filter out values by values in Pandas.DataFrame


code:
newList=zip(*List)
column=newList[j]

rawDescription: Fast way of slicing columns from tuples

description: Fast way of slicing columns from tuples


code:
tup = return_args()
call(*tup)

rawDescription: Using variables from a returned function as arguments in another function


code:
import s
s.get_string_function("Coord")
_(1, 4)

rawDescription: Creating a boost::python::object from a std::function


code: dir()

rawDescription: python: retrieve names of all builtins

description: Python: retrieve names of all builtins


code:
a = 1
b = 2
print(a%b) # 1/2 = 0 2's + 1 remainder
print(b%a) # 2/1 = 2 1's + 0 remainder

rawDescription: Why the below command prints nothing

description: Why the below command prints nothing


code:
values=[]
for ind in sub_list:
    values.append(d[x, y])

rawDescription: Retrieve properties of a class instance stored in a dictonary


code:
def evaluate(node):
    # evaluate parameters of the call
    params = []
    for child in node:
        params.append(evaluate(child))

    # now make the call to whatever function this node represents,
    # passing the parameters
    return node.function.call(*params)

rawDescription: Translating a declarative DSL into nested function calls


code: [list(x) for x in zip(*a)]

rawDescription: Transpose nested list in python

description: Transpose nested list in python


code:
df = pd.read_excel('stack.xlsx', 'tabelle1')
names = pd.concat((df.plA, df.plB)).unique()
for name in names:
    nA = df.plA==name
    nB = df.plB==name
    df['mean'+name] = np.cumsum(df.ptsA*nA + df.ptsB*nB)/np.maximum(1.,
                                     np.cumsum(1.*np.logical_or(nA, nB)))

rawDescription: Calculating expanding mean on 2 columns simultaneously


code:
space = np.meshgrid(*[np.linspace(low_bound, up_bound, m)]*dim, sparse=True)
space_old = np.asarray(np.meshgrid(*[np.linspace(low_bound, up_bound, m)]*dim))

rawDescription: Creating variables in loop for dynamicly creating griddata()


code:
a = BuildInfo() #uses default value of an empty list for object/sourceFiles
b = BuildInfo(["hello.dat", "world.dat"], ["foo.txt", "bar.txt"])
a.append(b) #a now has the same info as b
a.append(b) #a now has ["hello.dat", "world.dat", "hello.dat", "world.dat"], ["foo.txt", "bar.txt", "foo.txt", "bar.txt"]

rawDescription: python/scons help: maintaining lists of source files + object files

description: Python/scons help: maintaining lists of source files + object files


code:
from pyparsing import OneOrMore, Optional, oneOf, alphas, Word, Group, Forward, Suppress, Dict

# define the grammar
nodes = Forward()
nodeName = oneOf(list(alphas))
nodeChildren = Suppress('(') + Group(nodes) + Suppress( ')')
node = Group(nodeName + Optional(nodeChildren))
nodes <<= OneOrMore(node)

print(nodes.parseString('abc(abc(defg)d)de(f)gh'))

rawDescription: Optimizing string parsing with Python

description: Optimizing string parsing with Python


rawDescription: How to make equivalency in Python?

description: Make equivalency in Python


code: math.floor(math.log(n, 2)) + 3

rawDescription: Python character length of a binary value


code: [filter(lambda e: e not in punctuation, sub) for sub in a]

rawDescription: How do I remove common elements from two lists?

description: Remove common elements from two lists


code:
def read_instance(filename):
    instance = RS()
    instance.importer(filename)
    return instance

rawDescription: How to programmatically add instances in Python?

description: Programmatically add instances in Python


code: [name for name, method in Class.__dict__.iteritems() if callable(method)]

rawDescription: How can I list methods directly defined in a class (not inherited)?

description: List methods directly defined in a class (not inherited)


code:
df.max(1)
df.min(1)

rawDescription: Get min and max elements for 2 corresponding series in pandas


code: [x.name().split(".")[0] for x in wn.all_synsets('n')]

rawDescription: Extract word from a list of synsets in NLTK for Python


rawDescription: In SQLAlchemy, how to access a referenced property in a query when having multiple relationships?


rawDescription: Layout not adding correctly, seems that its not erasing previous widgets


code: list = x.split()

rawDescription: Convert string (without any separator) to list


code:
def implicit(a):
    n = a.shape[0]
    m = np.zeros_like(a)
    m = - n*a.T + n*np.diag(a)[:,newaxis]
    for k in range(n):
        for i in range(n):
            m[k,i] += (a[i,:] - a[k,:]).sum()
    return m

rawDescription: Numpy matrix operations

description: Numpy matrix operations


rawDescription: Multiple hash assignments in perl - translated to python? Why equal 1 always?


code:
from VideoCapture import Device
import pygame
import time
In=1
pygame.init()
w = 640
h = 480
size=(w,h)
screen = pygame.display.set_mode(size)
c = pygame.time.Clock() # create a clock object for timing

while True:
    cam = Device()
    filename = str(In)+".jpg" # ensure filename is correct
    cam.saveSnapshot(filename)
    img=pygame.image.load(filename)
    screen.blit(img,(0,0))
    pygame.display.flip() # update the display
    c.tick(3) # only three images per second
    In += 1

rawDescription: How to display Image in pygame?

description: Display Image in pygame


code:
my_shelf = shelve.open(filename)
for key in my_shelf:
    globals()[key]=my_shelf[key]
my_shelf.close()

print(T)
# Hiya
print(val)
# [1, 2, 3]

rawDescription: How can I save all the variables in the current python session?

description: Save all the variables in the current python session


rawDescription: Creating a numpy array of 3D coordinates from three 1D arrays


code:
from inspect import stack

def chain(it1, it2):
    for collection in [it1, it2]:
        try:
            for el in collection:
                yield el

        except StopIteration:
            pass

rawDescription: Chaining of Python generators to traverse a nested data structure; best practices


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter
from matplotlib import scale as mscale
from matplotlib import transforms as mtransforms

class CustomScale(mscale.ScaleBase):
    name = 'custom'

    def __init__(self, axis, **kwargs):
        mscale.ScaleBase.__init__(self)
        self.thresh = None #thresh

    def get_transform(self):
        return self.CustomTransform(self.thresh)

    def set_default_locators_and_formatters(self, axis):
        pass

    class CustomTransform(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def __init__(self, thresh):
            mtransforms.Transform.__init__(self)
            self.thresh = thresh

        def transform_non_affine(self, a):
            return a**(R/cp)

        def inverted(self):
            return CustomScale.InvertedCustomTransform(self.thresh)

    class InvertedCustomTransform(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def __init__(self, thresh):
            mtransforms.Transform.__init__(self)
            self.thresh = thresh

        def transform_non_affine(self, a):
            return a**(cp/R)

        def inverted(self):
            return CustomScale.CustomTransform(self.thresh)

# Now that the Scale class has been defined, it must be registered so
# that ``matplotlib`` can find it.
mscale.register_scale(CustomScale)

rawDescription: How can I scale my y axis into y**constant

description: Scale my y axis into y**constant


code: dir = find('image.gif', "%s\%s" %(os.path.expanduser("~"), "MyProject\Images"))

rawDescription: Python - File Directory Issue

description: Python - File Directory Issue


rawDescription: Python list manipulation: Add an item to a string element to make it a 2 item list


code:
with open("file.enc", "rb") as f:
    iv = f.read(16)
    salt = f.read(16)
    key = f.read(32)

rawDescription: Writing and retrieving bytes to/from a file in Python


code: local4.sub(temp1, arg3[temp2])

rawDescription: What is the Ruby String sub function?

description: What is the Ruby String sub function


code:
import subprocess
subprocess.call(['sudo', '-i', 'echo "hi"'])

rawDescription: Script stops after entering root mode in ubuntu


code:
d = {'': '', 'username': 'johndoe', 'email': 'johndoe@gmail.com'}

for k, v in d.items():
    if not any([k, v]):
        del d[k]

print(d)
{'username': 'johndoe', 'email': 'johndoe@gmail.com'}

rawDescription: How to remove dict keys if value is empty

description: Remove dict keys if value is empty


code:
class A: pass
class B: pass
class C: pass

classes = [A(), B(), C()]
master_list = [B, A]

def sorter(instance):
    # get the type of the object
    c = instance.__class__
    # if it is in the master_list, use its index, otherwise put it at the end
    return master_list.index(c) if c in master_list else len(master_list)

final_list = sorted(classes, key=sorter)

rawDescription: sort list of class instances according to master list

description: Sort list of class instances according to master list


code: dt_next_7am = next_7am(dt)

rawDescription: How do I find the next 7am in a timezone

description: Find the next 7am in a timezone


code:
from Tkinter import *

def update_listbox():
    longest = 20  # initial value acts as minimum width
    for key,value in dic.iteritems():
        entry = '{}: {}'.format(key, (', '.join(value)))
        longest = max(longest, len(entry))
        listbox.insert(END, entry)
    listbox.config(width=longest)  # width in "standard" or average characters

dic = {
    'Foods': ['apple','grape','pizza'],
    'Drinks': ['milk','soda','juice'],
}

root=Tk()
root.title('Listbox')
listbox = Listbox(root)
button = Button(root, text='push', command=update_listbox)
button.pack()
listbox.pack()

root.mainloop()

rawDescription: Python Tkinter:When string with space inserted into Listbox, brackets appear


rawDescription: How can i use the value of one variable to call another in python?

description: Use the value of one variable to call another in python


code:
def defaultdict_factory_factory(default_factory):
    def defaultdict_factory(*args, **kwargs):
        return defaultdict(default_factory, *args, **kwargs)
    return defaultdict_factory

rawDescription: Populating a defaultdict at init time

description: Populating a defaultdict at init time


rawDescription: How can I order a list of connections

description: Order a list of connections


code:
for plugin in Plugin.plugins:
    plugin.other_plugin_stuff()

rawDescription: Plugin architecture - Plugin Manager vs inspecting from plugins import *


rawDescription: Concatenate Items within nested list python