code:
for row in bar_csv_reader:
    fips_code = row[...] # Row storing FIPS code.
    if fips_code in master:
        inner_data = master[fips_code]
        inner_data['bar'] = ... # Data from bar CSV.

rawDescription: Using Nested Dictionaries in Python -- combining two datasets with a common 'key' and different other variables


code:
import os, sys
from subprocess import Popen, PIPE
import nltk

BP = os.path.dirname(os.path.abspath(__file__))
CP = "%(BP)s/opennlp-tools-1.4.3.jar:%(BP)s/opennlp-tools-1.4.3/lib/maxent-2.5.2.jar:%(BP)s/opennlp-tools-1.4.3/lib/jwnl-1.3.3.jar:%(BP)s/opennlp-tools-1.4.3/lib/trove.jar" % dict(BP=BP)
cmd = "java -cp %(CP)s -Xmx1024m opennlp.tools.lang.english.TreebankParser -k 1 -d %(BP)s/opennlp.models/english/parser" % dict(CP=CP, BP=BP)
p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
stdin, stdout, stderr = (p.stdin, p.stdout, p.stderr)
text = "This is my sample sentence."
stdin.write('%s\n' % text)
ret = stdout.readline()
ret = ret.split(' ')
prob = float(ret[1])
tree = nltk.Tree.parse(' '.join(ret[2:]))

rawDescription: Break/Decompose complex and compound sentences in nltk


code:
df3 = pd.merge(df1, df2, on='item', how='outer')
for col in ['item', 'user']:
    df3[col] = pd.factorize(df3[col])[0] + 1
print(df3)

rawDescription: How to factorize two data frame meanwhile with python-pandas?

description: Factorize two data frame meanwhile with python-pandas


code:
import numpy as np
import pandas as pd

try:
    # Python3
    from io import StringIO
except ImportError:
    # Python2
    from StringIO import StringIO

scrabble_table = u'''\
,×1 ,×2 ,×3 ,×4 ,×6 ,×8 ,×9 ,×12
0, ,(Blank)
1,,,,L S U ,N R T ,O ,A I ,E
2 ,,,G ,D
3 ,,B C M P,,,,
4 ,,F H V W Y
5 ,K
8 ,J X
10 ,Q Z'''
scrabble_table = scrabble_table.replace(' ', '')
df = pd.read_table(StringIO(scrabble_table), delimiter=',', index_col=0)
df = df.stack().reset_index()
df = df.replace('(Blank)', '_')
df.columns=['points', 'freq', 'letters']
df = pd.DataFrame([(row['points'], row['freq'], letter)
                   for index, row in df.iterrows()
                   for letter in row[-1]], columns=['points', 'freq', 'letter'])
print(df)

rawDescription: Pandas: transform a DataFrame by splitting each value into multiple values


code:
id_to_dict = {d['id']: d for d in res_result}
[id_to_dict[id] for id in req_ids]

rawDescription: How can I order a list of dictionaries based on another list which has the key?

description: Order a list of dictionaries based on another list which has the key


code:
def save(self):
    print_all_fields_starting_with(self, "foo_")
    super(MyModel, self).save()

rawDescription: In model save() how to get all field starting with 'foo'


code:
classa = ClassA(class_a_init_args)
classb = ClassC(class_b_init_args)
classc = ClassC(class_c_init_args)

otherclass_obj = OtherClass(classa_obj, classb_obj, classc_obj)

rawDescription: python memory consumption and performance related to classes

description: Python memory consumption and performance related to classes


code:
totals = [0] * 12
for widget in widgets:
    totals[widget.datetime.month - 1] += 1

rawDescription: Building a list of monthly totals

description: Building a list of monthly totals


code:
@for_all_methods_in_float(mydecorator,'__new__')
class Datum(float):
    def __new__(klass, value, dtype="dtype", source="source", index1="index1", index2="index2"):
        return super(Datum,klass).__new__(klass,value)
    def __init__(self, value, dtype="dtype", source="source", index1="index1", index2="index2"):
        self.value = value
        self.dtype = dtype
        self.source = source
        self.index1 = index1
        self.index2 = index2
        super(Datum,self).__init__()

rawDescription: How to set up a class with all the methods of and functions like a built in such as float, but holds onto extra data?

description: Set up a class with all the methods of and functions like a built in such as float, but holds onto extra data


code: pd.melt(df, id_vars=['Date'], value_vars=['ELEM1', 'ELEM2']).sort(columns='Date')

rawDescription: Python Pandas, transform dataframe

description: Python Pandas, transform dataframe


rawDescription: Timestamp YYYY-MM-DDThh:mm:ss.sssTZD in Python


code:
page = urllib.request.urlopen(base_url)
soup = BeautifulSoup(page)
# ...
# do something with soup
# ...
# do something with soup

rawDescription: Python - Passing urls vs. an HTTPResponse object


code:
from itertools import permutations

result = [
    a * 10000 + b * 1000 + c * 100 + d * 10 + e
    for a, b, c, d, e in permutations(range(10), 5)
    if a != 0
]

rawDescription: What is the quickest way to get a number with unique digits in python?


code:
class SomeClass:
    def __init__(self):
        self.value = None
        ...
        someTextView = build_textview("some text")
        ...
        tree_selection = someTreeView.get_child().get_selection()
        tree_selection.connect("changed", self.selection_changed)
        ...

    def selection_changed(self, widget, data=None):
        (model, pathlist) = widget.get_selected_rows()
        for path in pathlist :
            tree_iter = model.get_iter(path)
            value = model.get_value(tree_iter,0)
            this.value = value
            return

rawDescription: Save variable returned by signal handler?


code:
if letter in find:
    a = find.index(str(letter))
    l[int(a)] = letter

rawDescription: How to code so the program finds multiple instances - Python

description: Code so the program finds multiple instances - Python


code:
#!python3
#coding:utf8

import sys

try:
    '┌┬┐╔╦╗╒╤╕╓╥╖│║─═├┼┤╠╬╣╞╪╡╟╫╢└┴┘╚╩╝╘╧╛╙╨╜'.encode(sys.stdout.encoding)
    test = True
except UnicodeEncodeError:
    test = False

if not test:
    print('Unsupported characters in',sys.stdout.encoding)

rawDescription: Testing if the terminal supports pseudographics


rawDescription: Order of traversal in dictionary

description: Order of traversal in dictionary


code:
def write_frame(frame, name=None, con=None, flavor='sqlite'):
    """
    Write records stored in a DataFrame to SQLite. The index will currently be
    dropped
    """
    if flavor == 'sqlite':
        schema = get_sqlite_schema(frame, name)
    else:
        raise NotImplementedError

rawDescription: Can I export a Python Pandas dataframe to MS SQL?

description: Export a Python Pandas dataframe to MS SQL


rawDescription: Python - Finding elements in a list efficiently


code:
price = 99.99
while price > 7.74:
    price += 1
    time.sleep(5)

rawDescription: time.sleep() function in Python 3.3?

description: Time.sleep() function in Python 3.3


code: myOutput=subprocess.Popen("C:\\usr\\local\\bin\\att\\compare.exe -metric AE -fuzz 100 1.png 2.png mask.png", stderr=subprocess.PIPE)

rawDescription: Problem getting terminal output from ImageMagick's compare.exe ( Either by pipe or Python )


rawDescription: Missing data, insert rows in Pandas and fill with NAN


rawDescription: Pattern match in file

description: Pattern match in file


code:
from collections import Counter

summed = sum((Counter({elem['title']: elem['views']}) for elem in a + b), Counter())
c = [{'title': title, 'views': counts} for title, counts in summed.items()]

rawDescription: Combine two lists of dicts, adding the values together


rawDescription: Spark dataframe transform multiple rows to column


rawDescription: Finding strings that are each separated by the same string


code:
data = TimeClock.objects.order_by('card','rec_date','rec_time').all()
for start, end in make_pairs( data ):
    WorkIntervals.objects.create( start.card, start.rec_date, start.rec_time, end.rec_time, ... )

rawDescription: Analyse data using time and date objects


code:
class YourModel(models.Model):
    parent = models.ForeignKey('YourModel', related_name='children')

    def siblings(self):
        return self.objects.filter(parent=self.parent_id).exclude(pk=self.pk)

rawDescription: Making portable Nodes in Django and using them to make Trees


code:
type() # <- missing argument
type(()) # returns <type 'tuple'>

rawDescription: How to pass tuple as argument in Python?

description: Pass tuple as argument in Python


code: [[(k, v) for v in values] for k, values in d.items()]

rawDescription: Turning list of pairs into list of pairs of pairs that share last item with first or vice versa


code: [path for path in files if filterex(path, 'txt')]

rawDescription: Python: Passing functions with arguments to a built-in function?


code:
opener = poster.streaminghttp.register_openers()
params = {'file': open("test.txt", "rb"), 'name': 'upload test'}
datagen, headers = poster.encode.multipart_encode(params)
request = urllib2.Request(upload_url, datagen, headers)
auth = base64.encodestring('%s:%s' % ('username', 'password'))[:-1] # This is just standard un/pw encoding
request.add_header('Authorization', 'Basic %s' % auth ) # Add Auth header to request
result = urllib2.urlopen(request)

rawDescription: How to post a file via HTTP with cookies using python poster lib

description: Post a file via HTTP with cookies using python poster lib


rawDescription: Recursive list comprehension for permutation. Python


code: matches = [(name, dict(values)[name]) for name in set(names) if name in dict(values)]

rawDescription: Find co-occurrences of two lists in python


code: l[:] = first_found(l)

rawDescription: Keep firstly found duplicate items in a list


code:
from cnv_csharp_date_fmt import cnv_csharp_date_fmt as cv
cv("yyyy-MM-dd hh:mm:ss")
cv("3pcts %%% yyyy-MM-dd hh:mm:ss")
cv("'3pcts' %%% yyyy-MM-dd hh:mm:ss")
cv(r"3pc\t\s %%% yyyy-MM-dd hh:mm:ss")

rawDescription: Python datetime format like C# String.Format


code:
for idx, item in enumerate(li):
    li[idx] = 'foo'

rawDescription: Can't modify list elements in a loop Python


rawDescription: Python - How to join elements in a list that are separated by a certain value


code:
from customvalidator import IS_NOT_EMPTY_IF_OTHER

db.define_table("foo",
    Field('a', 'integer'),
    Field('b', 'boolean'),
    Field('c', 'integer')
)

# apply the validator
db.foo.c.requires = IS_NOT_EMPTY_IF_OTHER(request.vars.b)

rawDescription: Web2py Custom Validators

description: Web2py Custom Validators


rawDescription: How do I suppress scientific notation in Python?

description: Suppress scientific notation in Python


code: env['CSC']          = env.Detect('mcs') or 'csc'

rawDescription: Adding C# support to SCons on Mac

description: Adding C# support to SCons on Mac


code: min(positions, key=posfunc)

rawDescription: Python finding minimum values of functions of list items, but returning the list item


rawDescription: Create a matrix from dynamic dictionary

description: Create a matrix from dynamic dictionary


rawDescription: pyparsing recursion of values list (ibm rhapsody)

description: Pyparsing recursion of values list (ibm rhapsody)


code:
import re
import itertools

pattern = "^\d+(?!\.tar\.gz)$"
file_list = ['20150301',
 '20150301100.tar.gz',
 '20150302',
 '20150302100.tar.gz',
 '20150303',
 '20150303100.tar.gz']
matchOB = filter(None, [ re.findall(pattern, x) for x in file_list ])
chain = itertools.chain(*matchOB)
print(list(chain))

rawDescription: Using re and extract some patterns from list Python2.7


rawDescription: Python: Split NumPy array based on values in the array


rawDescription: How to use Channel instead of Group when using django channels?

description: Use Channel instead of Group when using django channels


rawDescription: Remove one column for a numpy array

description: Remove one column for a numpy array


code: daily = df.resample('D').apply(sum)

rawDescription: Summing sections of a 2d array python

description: Summing sections of a 2d array python


code:
import csv
try:
    with open(r'input.tsv', 'r', newline='\n') as in_f, \
         open(r'output.csv', 'w', newline='\n') as out_f:
        reader = csv.reader(in_f, delimiter='\t')
        writer = csv.writer(out_f, delimiter=',', quoting=csv.QUOTE_ALL)  # Quoting added per comment from @Rob.
        for li in reader:
            try:
                writer.writerow([li[0], li[1], li[2], li[7], li[8], li[9],])
            except IndexError:  # Prevent errors on blank lines.
                pass
except IOError as err:
    print(err)

rawDescription: Python - Convert tab delimited file into csv in a specific manner


code:
group = [['steve', 'adam', 'avery'], ['avery', 'sarah', 'henry'], ['adam', 'harry', 'jane'], ['john', 'helene', 'bill'], ['andrew', 'helene', 'bill'], ['david', 'bill', 'helene']]
parents = {n: [p1, p2] for n, p1, p2 in group}
[[n, p1, p2] + parents.get(p1, [0, 0]) + parents.get(p2, [0, 0])
 for n, p1, p2 in group]

rawDescription: interating through a list of lists to create a new list

description: Interating through a list of lists to create a new list


code:
def dictfilter(pred, d=None):
    """dictfilter(d) -- returns a dict with all non-empty values from d
    dictfilter(pred, d) -- returns a dict with all values from d where pred(v)"""
    if d is None:
        return {k: v for k, v in pred.items() if v}
    else:
        return {k: v for k, v in d.items() if pred(v)}

rawDescription: Appending python dictionaries, without replacing if the value is empty


code:
root = self.treeWidget.invisibleRootItem()
child_count = root.childCount()
for i in range(child_count):
    item = root.child(i)
    url = item.text(0) # text at first (0) column
    item.setText(1, 'result from %s' % url) # update result column (1)

rawDescription: PyQT QTreeWidget iterating

description: PyQT QTreeWidget iterating


code: result = reduce(function, iterable, start)

rawDescription: Python alternative to reduce()

description: Python alternative to reduce()


code:
import sys, tty
tty.setraw(sys.stdin.fileno())
one_character= sys.stdin.read(1)

rawDescription: How can I determine when a user is in the process of entering something as an input in Python?

description: Determine when a user is in the process of entering something as an input in Python


code:
from pyspark.sql.types import ArrayType, StringType

keywords = sc.broadcast(set(
    keywords_df.map(lambda row: row[0]).collect()))

bd_contains = udf(
    lambda s: list(set(s.split()) & keywords.value),
    ArrayType(StringType()))

like_with_bd = (documents_df.select(
    col("document_id"),
    explode(bd_contains(col("document_text"))).alias("keyword")))

like_with_bd.show()

## +-----------+-------+
## |document_id|keyword|
## +-----------+-------+
## |          1|  spark|
## |          2| erlang|
## |          3|haskell|
## +-----------+-------+

rawDescription: How can we JOIN two Spark SQL dataframes using a SQL-esque "LIKE" criterion?


code:
def choice_without_repetition(lst):
    prev = None
    while True:
        i = random.randrange(len(lst))
        if i != prev:
            yield lst[i]
            prev = i

rawDescription: how to pick random items from a list while avoiding picking the same item in a row

description: Pick random items from a list while avoiding picking the same item in a row


code:
class UserHyperLinkedRelatedField(serializers.HyperLinkedRelatedField):

    def display_value(self, instance):
        return instance.get_full_name()

rawDescription: How do I customize the text of the select options in the api browser?

description: Customize the text of the select options in the api browser


code:
import sys                # if you want a system return code
MY_CONSTANT = "whatever"  # a symbolic constant

def a_function( args):    # replace with your useful stuff
    pass

# def b_function( args):   # as many more defs as are useful
    # can refer to / use both a_function (above) and c_function (below)

# def c_function()
    # etc

def main():
    print( "Script starting ...")
    # parse arguments, if any parsing needed
    # do stuff using the functions defined above
    # print output, if needed
    print( "End of script")
    sys.exit(0)    # 0 is Linux success, or other value for $? on exit

# "magic" that executes script_main only if invoked as a script

if __name__ == "__main__": # are we being invoked directly from command line?
    main()                 # if so, run this file as a script.

rawDescription: Convert Python 3 script to function

description: Convert Python 3 script to function


rawDescription: How do I get a formatted list of methods from a given object?

description: Get a formatted list of methods from a given object


code:
grades = {}
grades['k'] = 'x'
grades['newinput'] = 'newval'
grades

rawDescription: Iterating on a dictionary, adding keys and values


code:
from wx.lib.pubsub import setupkwargs
from wx.lib.pubsub import pub

rawDescription: pyinstaller exe with pubsub

description: Pyinstaller exe with pubsub


code:
timeit.timeit('x in l', '''
class Foo: pass
x = Foo(); l = [Foo()] * 100000''', number=10)
timeit.timeit('any(x is y for y in l)', '''
class Foo: pass
x = Foo(); l = [Foo()] * 100000''', number=10)

rawDescription: Python - "in" statement seach slow for list of objects


rawDescription: sort an array by row in pyhton

description: Sort an array by row in pyhton


code:
import numpy as np
x = np.random.rand(1000, 500, 3)
normed = x / np.sqrt((x**2).sum(axis=-1))[:,:,None]

rawDescription: how to calculate the norm of a vector in a large mxnx3 array?

description: Calculate the norm of a vector in a large mxnx3 array


code:
from itertools import chain
list(chain.from_iterable(zip(a,b)))

rawDescription: Pythonically inserting multiple values to a list


code:
import ast
tree = ast.parse('lambda S,b : (g(S[1:],b),S)[len(S)==b]')
ast.dump(tree)

rawDescription: Recursion with ternary operator 'hack' in Python


code:
import glob

glob.glob('*.html') #return all html files in curr dir
glob.glob('*')     # lists all files in the current directory python is running in
glob.glob('*.jpg')   # returns all jpeg images
glob.glob('[a-z]????.*')    # lists all files starting with a letter, followed by 4 characters (numbers, letters) and any ending.

rawDescription: How to extract filenames from cmd input in python

description: Extract filenames from cmd input in python


rawDescription: 4 dimensional array of zeros in python

description: 4 dimensional array of zeros in python


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

def make_colormap(seq):
    """Return a LinearSegmentedColormap
    seq: a sequence of floats and RGB-tuples. The floats should be increasing
    and in the interval (0,1).
    """
    seq = [(None,) * 3, 0.0] + list(seq) + [1.0, (None,) * 3]
    cdict = {'red': [], 'green': [], 'blue': []}
    for i, item in enumerate(seq):
        if isinstance(item, float):
            r1, g1, b1 = seq[i - 1]
            r2, g2, b2 = seq[i + 1]
            cdict['red'].append([item, r1, r2])
            cdict['green'].append([item, g1, g2])
            cdict['blue'].append([item, b1, b2])
    return mcolors.LinearSegmentedColormap('CustomMap', cdict)

c = mcolors.ColorConverter().to_rgb
rvb = make_colormap(
    [c('red'), c('violet'), 0.33, c('violet'), c('blue'), 0.66, c('blue')])
N = 1000
array_dg = np.random.uniform(0, 10, size=(N, 2))
colors = np.random.uniform(-2, 2, size=(N,))
plt.scatter(array_dg[:, 0], array_dg[:, 1], c=colors, cmap=rvb)
plt.colorbar()
plt.show()

rawDescription: Create own colormap using matplotlib and plot color scale


code:
self.street
self.ltype
self.use
self.length

# .a and .b can be instances of NodeConnection
self.a.setback
self.a.bearing

self.b.setback
self.b.bearing
self.b.node

# .ab and .ba can be a separate class, "UniDirectionalLink
self.ab.lanes
self.ab.left
self.ab.right
self.ab.speed
self.ab.fspd
self.ab.capacity

self.ba.lanes
self.ba.left
self.ba.right
self.ba.speed
self.ba.fspd
self.ba.capacity

rawDescription: Initializing instance variable: Idiomatic way


code:
def func(X,W):
    Func=np.einsum('ij,kj->',X,W)
    return lambda : Func

rawDescription: Double sum in Python

description: Double sum in Python


code:
# original list
lst = ['        0.200000\n', '        0.000000\n', '        0.000000\n', '       -0.200000\n', '  3400000.100000\n', '  5867999.900000\n']
# removes leading whitespaces from each string of the list
lst = [ s.lstrip() for s in lst ]
# removes the first character of the 4th string of the list
lst[4] = lst[4][1:]
# prints the modified list
print(lst)

rawDescription: Removing specific characters from multiple lines in a list by indexing


code:
# Convert, sort and group.  Print generated groups.
A = ['1', '1.01', '1.1', '2', '3', '3.2', '4', '5']
a1 = sorted(float(f) for f in A)
g1 = grouper(a1)

print("Grouped A:", g1)
# Grouped A: [[1.0, 1.01, 1.1], [2.0], [3.0, 3.2], [4.0], [5.0]]

# Generate new list as average of each group.
g2 = (mean(g) for g in grouper(a1))
a2 = list(g2)

print("Averaged grouped A:", a2)
# Averaged grouped A: [1.0366666666666668, 2.0, 3.1, 4.0, 5.0]

print("Averaged grouped A:", average_similar(A, width=0.5))
# Averaged grouped A: [1.0366666666666668, 2.0, 3.1, 4.0, 5.0]

# Generate new list as rounded averages of each group.
g3 = (round(mean(g), 2) for g in grouper(a1))
a3 = list(g3)

print("Averaged grouped and rounded A:", a3)
# Averaged grouped and rounded A: [1.04, 2.0, 3.1, 4.0, 5.0]

print("Averaged grouped and rounded A:", average_similar(A, 0.5, 2))
# Averaged grouped and rounded A: [1.04, 2.0, 3.1, 4.0, 5.0]

# A more compact example given a list of numbers.
C = [1.1, 1.2, 1.3, 1.5, 1.6, 1.4]
# In-place sort.
C.sort()
lc = list(round(mean(g), 2) for g in grouper(C))
print("Average C", lc)
# Average C [1.3, 1.6]
print("Average C", average_similar(C, precision=2))
# Average C [1.3, 1.6]

# Another examples as a one-liner.
D = ['1', '1.01', '1.1', '2', '3', '3.2', '4', '5', '5.1', '6', '2.5']
ld = list(round(mean(g), 2)
          for g in grouper(
                  sorted(float(f) for f in D)))
print("Average D", ld)
# Average D [1.04, 2.0, 2.5, 3.1, 4.0, 5.05, 6.0]
print("Average D", average_similar(D, width=0.5, precision=2))
# Average D [1.04, 2.0, 2.5, 3.1, 4.0, 5.05, 6.0]

rawDescription: Python - Average similar values in list and create new list with averaged values


code:
import random

def funcdec(func):
    if not hasattr(funcdec, 'state'):
        # an attribute on a global function is also 'global':
        funcdec.state = random.random()
    def wrapper(*args, **kwargs):
        return func(funcdec.state, *args, **kwargs)
    return wrapper

rawDescription: Python "Multi-Level Decorator" - how does this work?


code: y = x.strip()

rawDescription: How to copy what Python last printed and put it to a string

description: Copy what Python last printed and put it to a string


code:
encoded = "&".join( "%s=%s" % (key, quote(parameters[key], safe="+"))
    for key in ordered(parameters.keys()))

rawDescription: Build query string using urlencode python


code:
numbers = [1, 2, -3, 3, -7, 5, 4, -1, 4, 5]
sum(1 for number in numbers if number < 0)

rawDescription: Python - Identify a negative number in a list


code: window(open('C:/working_file.txt', mode='r', encoding='utf8'), 4)

rawDescription: Python nested loop - get next N lines

description: Python nested loop - get next N lines


code:
if line1 in f2data:
    linecount += 1

rawDescription: Using Python to Compare Two Text Files Line by Line


code:
HELLO
HELLO

rawDescription: Lambda expression replacement

description: Lambda expression replacement


code: self.new_thread = thread_worker(self)

rawDescription: Python/PySide: How can i destroy a terminated thread object?


code:
a = [] # all
p = [] # pos
n = [] # neg

print("Enter positive, negative or zero to determine the average: ")
values = []
for i in iter(lambda: int(input("Enter a number (-9999 to end): ")), -9999):
    if i >= 0: # if positive append to p
        p.append(i)
    else: # else must be negative so append to n
        n.append(i)
    a.append(i) # always add to a to get all nums

def allNumAvg(values):
    return sum(values) / len(values)

def posNumAvg(values):
    return sum(values) /len(values)

def nonPosAvg(values):
    return sum(values) / len(values)

print("The list of all numbers entered is:")

# pass correct list to each function
dictionary = {
    "AvgPositive": posNumAvg(n),
    "AvgNonPos": nonPosAvg(p),
    "AvgAllNum": allNumAvg(a)
}

rawDescription: Implementing a dictionary function to calculate the average of a list


code: t = [l[0] for l in t]

rawDescription: Unexpected output in for loop - Python

description: Unexpected output in for loop - Python


code:
str1 = "abc.com/oms/shipment/show/"
str3 = "?legacy=1"
n=400
link_strings = [str1 + '-'.join([str(num) for num in id_list[i:i+n]]) + str3 for i in xrange(0, len(id_list), n)]

rawDescription: python Split list dynamically

description: Python Split list dynamically


code:
if __name__ == "__main__":
    myroom = Room("Ground Zero", "First empty room")
    ...

rawDescription: Python Class Shenanigans

description: Python Class Shenanigans


rawDescription: Python: merging lists like this

description: Python: merging lists like this


code: group = df.groupby("Country")

rawDescription: Python Pandas sort by column, but keep index same


code: string = string[:-1]

rawDescription: PyGame User Input

description: PyGame User Input


code:
a = MetaArray([1,2,3], comment='/Documents/Data/foobar.txt')
a.metadata

rawDescription: Add metadata comment to Numpy ndarray

description: Add metadata comment to Numpy ndarray


code:
average = tuple(sum(x[i] for x in set_of_tuples) / len(set_of_tuples)
                for i in range(len(set_of_tuples[0])))

rawDescription: Python: How would I get an average of a set of tuples?


rawDescription: Making a Python script Object-Oriented

description: Making a Python script Object-Oriented


rawDescription: How get average value fro each columns from pivot pandas python?


code:
import re

data = '''
ID  " Literal\t : "
'''

for line in data.split('\n'):
    if line:
        liter = re.search(r'"(.*)"', line).groups()[0]
        print(liter)
        print(repr(liter))

rawDescription: Read verbatim string from file

description: Read verbatim string from file


code:
sample = """
... given sample text ...
 """
from pyparsing import *

# punctuation
LPAR,RPAR,LBRACE,RBRACE,LBRACK,RBRACK,COMMA,EQ = map(Suppress,"(){}[],=")

identifier = Word(alphas,alphanums+"_")

# define some types that can get converted to Python types
# (parse actions will do conversion at parse time)
NONE = Keyword("None").setParseAction(replaceWith(None))
integer = Word(nums).setParseAction(lambda t:int(t[0]))
quotedString.setParseAction(removeQuotes)

# define a placeholder for a nested object definition (since objDefn
# will be referenced within its own definition)
objDefn = Forward()

objType = Combine(LPAR + identifier + RPAR)

objval = quotedString | NONE | integer | Group(objDefn)
objattr = Group(identifier + EQ + objval)

arrayattr = Group(identifier + LBRACK + RBRACK + EQ + Group(OneOrMore(Group(objDefn)+COMMA)) )

# use '<<' operator to assign content to previously declared Forward
objDefn << objType + LBRACE + ZeroOrMore((arrayattr | objattr) + Optional(COMMA)) + RBRACE
# parse sample text
result = objDefn.parseString(sample)

# use pprint to list out indented parsed data
import pprint
pprint.pprint(result.asList())

rawDescription: Possible Parser for Unknown String Format(soup?) from SUDS.client


code:
import tkinter as tk

class SubWindow(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        x = tk.Text(self)
        x.pack()

class MainWindow(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self)
        self.win1 = SubWindow(self)
        self.win1.pack(side="left")
        self.win2 = SubWindow(self)
        self.win2.pack(side="right")

if __name__ == "__main__":
    main = MainWindow()
    main.mainloop()

rawDescription: Can you combine two tkinter tk widgets?

description: Combine two tkinter tk widgets


rawDescription: "x Days ago' template filter in Django?

description: "x Days ago' template filter in Django


code: res[pos] += ord(char)

rawDescription: How to sum value of integers based on position?

description: Sum value of integers based on position


rawDescription: How to extract points from a graph?

description: Extract points from a graph


code:
from netifaces import interfaces, ifaddresses, AF_INET

def ip4_addresses():
    ip_list = []
    for interface in interfaces():
        for link in ifaddresses(interface)[AF_INET]:
            ip_list.append(link['addr'])
    return ip_list

rawDescription: How do I determine all of my IP addresses when I have multiple NICs?

description: Determine all of my IP addresses when I have multiple NICs


code: import threading

rawDescription: threading programming in python

description: Threading programming in python


rawDescription: Concise way to get NumPy to return array of proper shape after logical indexing, without doing a reshape?


code: db = SQLAlchemy(session_options={'query_cls': MyQuery})

rawDescription: SQLAlchemy - can you add custom methods to the query object?


code:
stu = []
inp = input('Students: ')
inp.split(' ')
stu += inp.split(' ')
print('Class Roll')
for i in stu:
  print(i)

rawDescription: Printing on new line - python

description: Printing on new line - python


code:
class Data:
    __slots__ = ["key1", "key2"]

    def __init__(self, k1, k2):
        self.key1, self.key2 = k1, k2

    def __getitem__(self, key):
        if key not in self.__slots__:
            raise KeyError("%r not found" % key)
        return getattr(self, key)

rawDescription: Best way to store fixed-keys key:value datasets that are accessed by keys in python?

description: Store fixed-keys key:value datasets that are accessed by keys in python


code:
from __future__ import (absolute_import, division, print_function,)
#                        unicode_literals)

import collections
import json

mycollection = [1, 2, 3, 4]

def build_dict(_id):
    d = dict()
    d['my_' + str(_id)] = _id
    return d

class SeqProxy(collections.Sequence):
    def __init__(self, func, coll, *args, **kwargs):
        super(SeqProxy, *args, **kwargs)

        self.func = func
        self.coll = coll

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

    def __getitem__(self, key):
        return self.func(self.coll[key])

class JsonEncoderProxy(json.JSONEncoder):
    def default(self, o):
        try:
            iterable = iter(o)
        except TypeError:
            pass
        else:
            return list(iterable)
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, o)

jsonencoder = JsonEncoderProxy()
collproxy = SeqProxy(build_dict, mycollection)

for chunk in jsonencoder.iterencode(collproxy):
    print(chunk)

rawDescription: Python, write json / dictionary objects to a file iteratively (one at a time)


code:
from django.conf.urls.defaults import *
from haystack.forms import ModelSearchForm
from haystack.query import SearchQuerySet
from haystack.views import SearchView
from forms import AutocompleteSearchForm

sqs = SearchQuerySet()

# Without threading...
urlpatterns = patterns('haystack.views',
  url(r'^$', SearchView(searchqueryset=sqs, form_class=AutocompleteSearchForm), name='haystack_search'),
)

rawDescription: django haystack module search with whoosh

description: Django haystack module search with whoosh


code:
with open("data.txt") as infile:
    text = infile.read()

rawDescription: Regex to find search term and place result in another data file?


code:
u = User.objects.get(username='someuser')
u.tasks.all()  # Because of `related_name` in Task.assignee

rawDescription: have multiple users as one model field in many to one format django models

description: Have multiple users as one model field in many to one format django models


code:
for num, heading in enumerate(headings):
    neatomatic9000(heading)
    for j in info:
        neatomatic9000(j[num])
    print('\n')

rawDescription: Constructing a 'table' by combining lists


rawDescription: Extract Information From a File

description: Extract Information From a File


code: lines = l

rawDescription: With return get only the one line

description: With return get only the one line


code:
...
SECURITY_MIDDLEWARE = ('django.middleware.security.SecurityMiddleware',)
MIDDLEWARE_CLASSES = SECURITY_MIDDLEWARE + MIDDLEWARE_CLASSES

SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True
X_FRAME_OPTIONS = 'SAMEORIGIN'
SECURE_HSTS_SECONDS = 60
SECURE_BROWSER_XSS_FILTER = True
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_CONTENT_TYPE_NOSNIFF = True

SECURE_SSL_REDIRECT = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')

rawDescription: django: application crash with SECURE_SSL_REDIRECT using NGINX

description: Django: application crash with SECURE_SSL_REDIRECT using NGINX


code:
#!/usr/bin/env python3
from io import StringIO
from subprocess import Popen, PIPE

with Popen('/path/to/script', stdout=PIPE, bufsize=1,
           universal_newlines=True) as p, StringIO() as buf:
    for line in p.stdout:
        print(line, end='')
        buf.write(line)
    output = buf.getvalue()
rc = p.returncode

rawDescription: Displaying subprocess output to stdout and redirecting it


code:
another_scenario = {
        "scenario_name":
        (
            (
                "command1",
                (
                    os.path,
                    os.path.exists
                ),
                None
            ),  # <- Note this comma
        )
}

rawDescription: Python flattening my tuple structure

description: Python flattening my tuple structure


code:
# blueprint.py
def print_howdy(): pass
def print_seeya(): pass

MYSIGNAL_LISTENERS = (print_howdy, print_seeya)

# __init__.py
from blueprint import MYSIGNAL_LISTENERS
for listener in MYSIGNAL_LISTENERS:
    mysignal.connect_via(app)(listener)

rawDescription: Catch signals in Flask Blueprint

description: Catch signals in Flask Blueprint


code:
import datetime

def parse_date(string):
    # Split the string into year/month/date, time, and seconds
    split_string = string.split()
    # get year month and date
    year = split_string[0].split('-')[0]
    month = split_string[0].split('-')[1]
    date = split_string[0].split('-')[2]

    # get hour minute second
    hour = split_string[1].split(':')[0]
    min = split_string[1].split(':')[1]
    second = split_string[1].split(':')[2]

    return datetime.datetime(year, month, date, hour=hour, minute=min, second=second)

rawDescription: Datetime header when reading in a file with pandas


code: result = [ord(ch) for ch in unhexlify(s)]

rawDescription: Encode string as hex bytes

description: Encode string as hex bytes


code:
class RegistrationView(flow_views.StartViewMixin, generic.CreateView):
    form_class = RegistrationForm

    def activation_done(self, form):
        self.activation.process.user = self.object
        self.activation.done()

rawDescription: viewflow.io: How can I present a custom form for gathering input for a specific task?

description: Viewflow.io: How can I present a custom form for gathering input for a specific task


rawDescription: Set an array equal to the first half of it's entries in python


code:
from tkinter import *
root = Tk()
canv = Canvas(root,height=17)
canv.grid_propagate(0)
lbl1 = Label(canv,text="First line\nSecond Line")
lbl1.grid(column=0,row=0)
canv.grid(column=0,row=0)
root.mainloop()

rawDescription: Tkinter, enclosing_frame.grid_propogate(0) to prevent resizing also prevents updating label text


code:
def process_line(line_parts):
    out = line_parts[:1]
    for part in line_parts[1:]:
        if part == "-":
            out.extend('00')
        else:
            out.extend(part)
    return out

rawDescription: replace elements to reformat the dataset

description: Replace elements to reformat the dataset


code:
from collections import defaultdict
raw = ['opst tops', 'opst opts', 'opst pots', 'eip pie', 'eip epi']
words = defaultdict(list)
for entry in raw:
    key, word = entry.split()
    words[key].append(word)

[' '.join(v) for v in words.values()]

rawDescription: Merge some part of the list together using python


code: '\n'.join([' '.join(line.split()) for line in ex_str.splitlines() if line.strip()])

rawDescription: Removing odd \n, \t, \r and space combinations from a given string in Python


code:
def play_turn():
    total = roll_die() + roll_die()

    if total == 12:
        return 1.5
    elif total == 11:
        return 1.0
    elif total == 10:
        return 0.5
    elif total <= 6:
        return -0.5
    else:  # total is 7, 8, or 9
        return 0

rawDescription: Probability Dice Game in Python with two dices


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
angles = np.random.rand(100)

length = 1.
heights = np.arange(len(angles))
vectors_3d = np.vstack((length * np.cos(angles),
                        length * np.sin(angles),
                        heights)).T

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
for x, y, z in vectors_3d:
    ax.plot([0, x], [0, y], zs=[z, z])
plt.show()

rawDescription: Plot stack of unit vectors in cylindrical coordinates - matplotlib


rawDescription: How do I call write a python function without opening the file beforehand?

description: Call write a python function without opening the file beforehand


code: csvdata_old = csvdata.copy()

rawDescription: Comparing two pandas dataframes for differences


code:
#~ line 8 "superior_science.c"
_("Facial hair has been shown to improve intelligence by a factor of 5.")

rawDescription: Python line numbers with xgettext

description: Python line numbers with xgettext


code:
import os

newtime = createnewtime()
command = "python setHeater.py | at " + newtime
os.system(command)

rawDescription: How can i execute this command from Python

description: Execute this command from Python


rawDescription: Compare (assert equality of) two complex data structures containing numpy arrays in unittest


code:
cmd = [
    "/usr/atria/bin/cleartool",
    "setview",
    "-exec",
    # single quotes in the argument no longer required, as we're not going through the shell
    "/usr/bin/python /home/testUser/Development/Scripts/setDoneFlag_Count_Lines.py",
    "testUser__project_5_0_myProject_001"
]
p = subprocess.Popen(cmd)

rawDescription: run os.system command as subprocess python

description: Run os.system command as subprocess python


code:
Location1 = motion_plan(alternator(0, 1), increasor(0, 1))
Location2 = motion_plan(increasor(0, -1), alternator(0, -1))
Location3 = motion_plan(alternator(0, -1), increasor(0, 1))
Location4 = motion_plan(increasor(0, -1), alternator(0, 1))

rawDescription: Robot Motion in Python

description: Robot Motion in Python


code:
a = "5, 7"
b = "6,5"
bool(set(map(int, a.split(','))).intersection(map(int, b.split(','))))

rawDescription: comparing numbers in 2 string A and B

description: Comparing numbers in 2 string A and B


code:
DEVLINKS='/dev/serial/by-id/usb-FTDI_USB__-__Serial-if00-port0 /dev/serial/by-path/platform-bcm2708_usb-usb-0:1.2:1.0-port0'
DEVNAME='/dev/ttyUSB0'
DEVPATH='/devices/platform/bcm2708_usb/usb1/1-1/1-1.2/1-1.2:1.0/ttyUSB0/tty/ttyUSB0'
ID_BUS='usb'
ID_MODEL='USB__-__Serial'
ID_MODEL_ENC='USB\x20\x3c-\x3e\x20Serial'
ID_MODEL_FROM_DATABASE='FT232 USB-Serial (UART) IC'
ID_MODEL_ID='6001'
ID_PATH='platform-bcm2708_usb-usb-0:1.2:1.0'
ID_PATH_TAG='platform-bcm2708_usb-usb-0_1_2_1_0'
ID_REVISION='0400'
ID_SERIAL='FTDI_USB__-__Serial'
ID_TYPE='generic'
ID_USB_DRIVER='ftdi_sio'
ID_USB_INTERFACES=':ffffff:'
ID_USB_INTERFACE_NUM='00'
ID_VENDOR='FTDI'
ID_VENDOR_ENC='FTDI'
ID_VENDOR_FROM_DATABASE='Future Technology Devices International, Ltd'
ID_VENDOR_ID='0403'
MAJOR='188'
MINOR='0'
SUBSYSTEM='tty'
UDEV_LOG='3'
USEC_INITIALIZED='2247071814106'

rawDescription: Python USB Serial ports connection

description: Python USB Serial ports connection


code:
from bs4 import BeautifulSoup

data = """

    11:15
    12:15
    13:15

    18:15
    19:15
    20:15

12:00 13:00

14:00 15:00 16:00

12:00

"""

soup = BeautifulSoup(data, "html.parser")

result = [row.text.split() for row in soup.table.find_all("tr")]
print(result)

rawDescription: python re.findall pattern for different number of matches

description: Python re.findall pattern for different number of matches


code:
def get_min_coin_configuration(total_sum, coins, cache=None):  # shadowing python built-ins is frowned upon.
    # assert(all(c > 0 for c in coins)) Assuming all coins are > 0
    if cache is None:  # initialize cache.
        cache = {}
    if total_sum in cache:  # check cache, for previously discovered solution.
        return cache[total_sum]
    elif total_sum in coins:  # check if total_sum is one of the coins.
        cache[total_sum] = [total_sum]
        return [total_sum]
    elif min(coins) > total_sum:  # check feasibility, if min(coins) > total_sum
        cache[total_sum] = []     # no combination of coins will yield solution as per our assumption (all +).
        return []
    else:
        min_configuration = []  # default solution if none found.
        for coin in coins:  # iterate over all coins, check which one will yield the smallest combination.
            results = get_min_coin_configuration(total_sum - coin, coins, cache=cache)  # recursively search.
            if results and (not min_configuration or (1 + len(results)) < len(min_configuration)):  # check if better.
                min_configuration = [coin] + results
        cache[total_sum] = min_configuration  # save this solution, for future calculations.
    return cache[total_sum]

assert all([ get_min_coin_configuration(**test[0]) == test[1] for test in
             [({'total_sum':25,  'coins':[1, 5, 10]}, [5, 10, 10]),
              ({'total_sum':153, 'coins':[1, 5, 10, 50]}, [1, 1, 1, 50, 50, 50]),
              ({'total_sum':100, 'coins':[1, 5, 10, 25]}, [25, 25, 25, 25]),
              ({'total_sum':123, 'coins':[5, 10, 25]}, []),
              ({'total_sum':100, 'coins':[1,5,25,100]}, [100])] ])

rawDescription: recursively implementing 'minimum number of coins' in python

description: Recursively implementing 'minimum number of coins' in python


rawDescription: Find colour based on brightness in python


code:
def getCurrentShow(hour=None, day=None):
    hour = hour or localtime().tm_hour
    day = day or datetime.datetime.now().strftime('%A')
    return Schedule.objects.get(hour=hour, day=day).show

rawDescription: python/django function returning identical value every time

description: Python/django function returning identical value every time


code:
if request.method == "POST":
    form = CSSForm(request.POST)
    if form.is_valid():
        t = TemplateResponse(request, 'base.css', {"cssform": form})
        t.render()
        css_string = t.content
        #now do something with your css_string

rawDescription: Contextual alternative to giant heredoc in python/django


code:
import seaborn as sns
sns.set(rc={'image.cmap': 'cubehelix'})

rawDescription: What was the default color palette for images in seaborn version 0.2?


code:
level_sort(('B', 1, None))
level_sort(('C', 1, None))

rawDescription: Python advanced list ordering

description: Python advanced list ordering


code: form = UserForm(request.user, ...)

rawDescription: Pass parameters to Django class meta

description: Pass parameters to Django class meta


code:
def func(s, method, cond):
    if cond:
        return method()
    else:
        return s

s = 'hello world'

print(func(s, s.upper, 'hello' in s))
print(func(s, s.upper, 'goodbye' in s))

rawDescription: Python: Higher Order Functions with Methods


code:
import asyncio
import time

class Protocol(asyncio.Protocol):

    def __init__(self):
        print('Protocol initialised')

    def pipe_data_received(self, fd, data):
        print('Data received %s' % data)
        if fd == 1:

            with open('rand_file.txt', 'a') as out:
                out.write(bytes(data).decode('ascii'))
        elif fd == 2:
            print('Received error data!')
            print(data)

    def pipe_connection_lost(self, fd, exc):
        print('Pipe connection lost')
        if exc is not None:
            print(exc)
            raise exc

    def process_exited(self):
        print('Subprocess exited')

@asyncio.coroutine
def mycoro():
    loop = asyncio.get_event_loop()
    print('creating process...')
    subprocess = loop.subprocess_exec(lambda: Protocol(),
                                      'python3.5', 'get_rand.py',
                                      stdin=None, stderr=None)
    asyncio.ensure_future(subprocess)
    asyncio.ensure_future(dummy_work())
    print('Mycoro finished, tasks are scheduled')

@asyncio.coroutine
def dummy_work():
    while True:
        yield from asyncio.sleep(1)
        print('dummy work')

def main():
    loop = asyncio.get_event_loop()
    asyncio.ensure_future(mycoro())
    loop.run_forever()
    loop.close()

main()

def main():
    loop = asyncio.get_event_loop()
    asyncio.ensure_future(mycoro())
    loop.run_forever()
    loop.close()

main()

rawDescription: Python asyncio timely event handling

description: Python asyncio timely event handling


code:
class Struct1(object):
    fields = ('a','b','c')
    ...

class Struct2(object):
    fields = ('foo', 'bar', 'baz')
    ...

rawDescription: Structures packing/unpacking class design


code: b = '\n'.join('\t'.join('%0.3f' %x for x in y) for y in a)

rawDescription: convert 2d numpy array to string

description: Convert 2d numpy array to string


code:
view = MyView()
view.pre_save()

rawDescription: Python mixin with a method that cannot be overridden (by default)?


code:
for line in extract_data(browser):
    f.write(line.encode('utf-8') + '\n')

rawDescription: get python UnicodeEncodeError when i was using selenium to crawl a website

description: Get python UnicodeEncodeError when i was using selenium to crawl a website


code:
from cStringIO import StringIO
s = StringIO()
s.write('foo')
s.getvalue()
s.truncate(0)
s.getvalue()
s.write('bar')
s.getvalue()

rawDescription: how do I clear a stringio object?

description: Clear a stringio object


code:
True
False

rawDescription: How to find out the nested class hierarchy?

description: Find out the nested class hierarchy


rawDescription: It is possible to round up integers using format?


rawDescription: Set derivatives of a function to 0 in Python


code:
number = 5896
ascending = "".join(sorted(str(number)))
descending = "".join(sorted(str(number), reverse=True))
ascending
descending

rawDescription: How to sort digits in a number?

description: Sort digits in a number


code:
txt = "foo\nbar\nbaz"

m_1 = []
io = StringIO.StringIO(txt)
for line in io:
    m_1.append(line)

rawDescription: creating stream to iterate over from string in Python

description: Creating stream to iterate over from string in Python


code:
import os
os.system('cls')   #Windows
os.system('clear') #Linux

rawDescription: Clearing previous terminal output in python


code:
# The directory to use for notebooks.
c.FileNotebookManager.notebook_dir = u'/path/to/your/notebooks'

rawDescription: IPython Notebook save location

description: IPython Notebook save location


code:
import codecs
import os
with codecs.open("tupper.txt", "w", "utf-8") as f:
    values = [[tuppers_formula(x, y) for x in range(106)] for y in range(17)]
    for row in values:
        for value in row[::-1]: # x = 0 starts at the left so reverse the whole row
            if value:
                f.write("\u2588") # Write a block
            else:
                f.write(" ")
        f.write(os.linesep)

rawDescription: Imprecise floats in Tupper's self-referential formula


code:
class ToppingSerializer(serializers. ModelSerializer):
    class Meta:
        model = Topping
        fields = ('name',)

class PizzaSerializer(serializers. ModelSerializer):
    class Meta:
        model = Pizza
        fields = ('name', 'toppings')

rawDescription: Correct way to use Django's ORM and Django Rest Framework to serialize a queryset of nested relationships?


code:
import dis
dis.dis(outer)
inner = outer(lambda a, b: None)
dis.dis(inner)

rawDescription: Variable scope for nested functions in python


code: fd = os.open("x", os.O_WRONLY | os.O_CREAT | os.O_EXCL)

rawDescription: How do I create a file in python without overwriting an existing file

description: Create a file in python without overwriting an existing file


code:
a = [[]]*3
# The ids are the same
id(a[0])
id(a[1])
id(a[2])

rawDescription: interesting thing about python list initializing

description: Interesting thing about python list initializing


code:
import numpy as np
import scipy as sp
import scipy.ndimage

import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

def animate(input_filename):
    """Detects paws and animates the position and raw data of each frame
    in the input file"""
    # With matplotlib, it's much, much faster to just update the properties
    # of a display object than it is to create a new one, so we'll just update
    # the data and position of the same objects throughout this animation...

    infile = paw_file(input_filename)

    # Since we're making an animation with matplotlib, we need
    # ion() instead of show()...
    plt.ion()
    fig = plt.figure()
    ax = fig.add_subplot(111)
    fig.suptitle(input_filename)

    # Make an image based on the first frame that we'll update later
    # (The first frame is never actually displayed)
    im = ax.imshow(infile.next()[1])

    # Make 4 rectangles that we can later move to the position of each paw
    rects = [Rectangle((0,0), 1,1, fc='none', ec='red') for i in range(4)]
    [ax.add_patch(rect) for rect in rects]

    title = ax.set_title('Time 0.0 ms')

    # Process and display each frame
    for time, frame in infile:
        paw_slices = find_paws(frame)

        # Hide any rectangles that might be visible
        [rect.set_visible(False) for rect in rects]

        # Set the position and size of a rectangle for each paw and display it
        for slice, rect in zip(paw_slices, rects):
            dy, dx = slice
            rect.set_xy((dx.start, dy.start))
            rect.set_width(dx.stop - dx.start + 1)
            rect.set_height(dy.stop - dy.start + 1)
            rect.set_visible(True)

        # Update the image data and title of the plot
        title.set_text('Time %0.2f ms' % time)
        im.set_data(frame)
        im.set_clim([frame.min(), frame.max()])
        fig.canvas.draw()

def find_paws(data, smooth_radius=5, threshold=0.0001):
    """Detects and isolates contiguous regions in the input array"""
    # Blur the input data a bit so the paws have a continous footprint
    data = sp.ndimage.uniform_filter(data, smooth_radius)
    # Threshold the blurred data (this needs to be a bit > 0 due to the blur)
    thresh = data > threshold
    # Fill any interior holes in the paws to get cleaner regions...
    filled = sp.ndimage.morphology.binary_fill_holes(thresh)
    # Label each contiguous paw
    coded_paws, num_paws = sp.ndimage.label(filled)
    # Isolate the extent of each paw
    data_slices = sp.ndimage.find_objects(coded_paws)
    return data_slices

def paw_file(filename):
    """Returns a iterator that yields the time and data in each frame
    The infile is an ascii file of timesteps formatted similar to this:

    Frame 0 (0.00 ms)
    0.0 0.0 0.0
    0.0 0.0 0.0

    Frame 1 (0.53 ms)
    0.0 0.0 0.0
    0.0 0.0 0.0
    ...
    """
    with open(filename) as infile:
        while True:
            try:
                time, data = read_frame(infile)
                yield time, data
            except StopIteration:
                break

def read_frame(infile):
    """Reads a frame from the infile."""
    frame_header = infile.next().strip().split()
    time = float(frame_header[-2][1:])
    data = []
    while True:
        line = infile.next().strip().split()
        if line == []:
            break
        data.append(line)
    return time, np.array(data, dtype=np.float)

if __name__ == '__main__':
    animate('Overlapping paws.bin')
    animate('Grouped up paws.bin')
    animate('Normal measurement.bin')

rawDescription: How can I improve my paw detection?

description: Improve my paw detection


code:
def comparisons(seq):
    return [abs(a-b) for a, b in zip(seq, seq[1:])]

rawDescription: Comparison between adjacent elements in sequences


code:
def find_all_paths(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return [path]
    paths = []
    for node in set(graph.neighbors(start)) - set(path):
        paths.extend(find_all_paths(graph, node, end, path))
    return paths

rawDescription: Path between two nodes

description: Path between two nodes


code:
s = "asdf23rlkasdfidsiwanttocutthisoutsadlkljasdfhvaildufhblkajsdhf"
s[s.index("iwant")+len("iwant"):s.index("thisout")]

rawDescription: Find and cut out a python substring

description: Find and cut out a python substring


code:
import re

def get_find_and_replace(f):
    """f --> a file that is open with r+ mode"""
    data = f.read()
    def find_and_replace(old, new):
        for m in re.finditer(old, data):
            f.seek(m.start())
            f.write(new)
    return find_and_replace

with open("test","r+") as f:
  find_and_replace = get_find_and_replace(f)
  find_and_replace("apples_","lettuce")
  #find_and_replace(...,...)
  #find_and_replace(...,...)

rawDescription: Using 'r+' mode to overwrite a line in a file with another line of the same length


code: list(paths(tree))

rawDescription: Generate all leaf-to-root paths in a dictionary tree in Python


code: df

rawDescription: Pandas: transforming the DataFrameGroupBy object to desired format


code:
def func(a):
  return a

class MyClass(object): # note: you should inherit from object in py2.X!
  def class_func(self, thing):
    return func(thing)

myinstance = MyClass()
foo = myinstance.class_func(1)

def func(a):
  return str(a)

bar = myinstance.class_func(1)

rawDescription: Methods defined outside class which itself is subsequently imported


rawDescription: How can I find all the combinations of elements in a set of arrays?

description: Find all the combinations of elements in a set of arrays


rawDescription: jsonpath_rw for Python: How to navigate relatively?

description: Jsonpath_rw for Python: How to navigate relatively


rawDescription: transpose part of a table with Python

description: Transpose part of a table with Python


rawDescription: Python ctypes and function pointers

description: Python ctypes and function pointers


code:
from app.users.views import users
from app.posts.views import posts

def init_app(app):
    app.register_blueprint(users, prefix='/users')
    app.register_blueprint(posts, prefix='/posts')

rawDescription: Can I keep all Flask blueprints in one file?

description: Keep all Flask blueprints in one file


code:
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)
engine.execute("select * from table where bit_count(column & bitmask) > 5").scalar()

rawDescription: BIT_COUNT in SQLAlchemy

description: BIT_COUNT in SQLAlchemy


code:
data = {'company': [], 'gender': [], 'investor': [], 'name': [], 'title': []}
for k, v in my_dict.items():
    for entry in v:
        data['company'].append(k)
    if not v:
        data['company'].append(k)
    for name in ['gender', 'investor', 'name', 'title']:
        has_entry = False
        for entry in v:
            has_entry = True
            data[name].append(entry.get(name))
        if not has_entry:
            data[name].append(None)
df = pd.DataFrame(data)
print(df)

rawDescription: Pandas DataFrame from dictionary with nested lists of dictionaries


code:
def splitNumber (num):
    lst = []
    while num > 0:
        lst.append(num & 0xFF)
        num >>= 8
    return lst[::-1]

bytes(splitNumber(12345678901234567890))
# b'\xabT\xa9\x8c\xeb\x1f\n\xd2'

rawDescription: Python writing binary

description: Python writing binary


code:
import binascii
import crc16

def crccitt(hex_string):
    byte_seq = binascii.unhexlify(hex_string)
    crc = crc16.crc16xmodem(byte_seq, 0xffff)
    return '{:04X}'.format(crc & 0xffff)

rawDescription: Calculate CRC-CCITT (0xFFFF) for HEX string


code:
last = df.irow(0)
for i in range(1, df.shape[0]):
    print(last)
    print(df.irow(i))
    last = df.irow(i)

rawDescription: iterrows pandas get next rows value

description: Iterrows pandas get next rows value


code:
with open("o.tex", "w") as o:
    o.write(">>>\t|\i|\t<<<\n")

rawDescription: why does python add another backslash to \i

description: Why does python add another backslash to \i


code:
bb = B([A(i) for i in range(10)])
bb.b = 5
print(list(bb.a))
print(bb.b)

rawDescription: Get attribute of all items in container python


code:
#!/usr/bin/env python3
import io
import sys
from subprocess import Popen, PIPE

char = ord('✌')
filename = 'U+{char:04x}.txt'.format(**vars())
with Popen(["powershell", "-C", '''
    $old = [Console]::OutputEncoding
    [Console]::OutputEncoding = [Text.Encoding]::UTF8
    echo $([char]0x{char:04x}) | fl
    echo $([char]0x{char:04x}) | tee {filename}
    [Console]::OutputEncoding = $old'''.format(**vars())],
           stdout=PIPE) as process:
    print(sys.stdout.encoding)
    for line in io.TextIOWrapper(process.stdout, encoding='utf-8-sig'):
        print(ascii(line))
print(ascii(open(filename, encoding='utf-16').read()))

rawDescription: Decode poweshell output possibly containing non-ascii unicode characters into a python string


rawDescription: Change encoding of stdin / stdout at runtime in Python 3


code:
def call(coefficients, x):
    return sum(x ** (len(coefficients) - i - 1) * c for i, c in enumerate(coefficients))

rawDescription: Horner's method to return P(x) and its derivative


code:
import itertools
it = itertools.count(1)  # yield 1, 2, 3, ... infinitely.
next(it)
next(it)

rawDescription: Using lambda to create new list by altering/modifying old list


code: Series(np.random.randn(3)).apply(lambda x: '%.3f' % x)

rawDescription: Format / Suppress Scientific Notation from Python Pandas Aggregation Results


code:
from lxml import etree
tree = etree.XML('<c/><d><e><f/></e></d>')
node_b = tree.xpath('/a/b')[0]
node_d = tree.xpath('/a/d')[0]
node_d.append(node_b)
etree.tostring(tree) # complete 'b'-branch is now under 'd', after 'e'
node_f = tree.xpath('/a/d/e/f')[0] # Nothing stops us from moving it again
node_f.append(node_a) # Now 'a' is deep under 'f'
etree.tostring(tree)

rawDescription: Move an entire element in with lxml.etree


code:
@app.route('/getpythondata')
def get_python_data():
    return json.dumps(pythondata)

rawDescription: How do I send data from JS to Python with Flask?

description: Send data from JS to Python with Flask


rawDescription: ASCII Art With Letters

description: ASCII Art With Letters


rawDescription: Use readline() from python to read specific line


code:
"""
    from:  http://code.activestate.com/recipes/194364-the-markov-chain-algorithm/?in=lang-python
"""

import random;
import sys;

stopword = "\n" # Since we split on whitespace, this can never be a word
stopsentence = (".", "!", "?",) # Cause a "new sentence" if found at the end of a word
sentencesep  = "\n" #String used to seperate sentences

# GENERATE TABLE
w1 = stopword
w2 = stopword
table = {}

for line in sys.stdin:
    for word in line.split():
        if word[-1] in stopsentence:
            table.setdefault( (w1, w2), [] ).append(word[0:-1])
            w1, w2 = w2, word[0:-1]
            word = word[-1]
        table.setdefault( (w1, w2), [] ).append(word)
        w1, w2 = w2, word
# Mark the end of the file
table.setdefault( (w1, w2), [] ).append(stopword)

# GENERATE SENTENCE OUTPUT
maxsentences  = 20

w1 = stopword
w2 = stopword
sentencecount = 0
sentence = []
paragraphsep == "\n\n"
count = random.randrange(1,5)

while sentencecount < maxsentences:
    newword = random.choice(table[(w1, w2)])
    if newword == stopword: sys.exit()
    if newword in stopsentence:
        print ("%s%s" % (" ".join(sentence), newword), end=" ")
        sentence = []
        sentencecount += 1
        count -= 1
        if count == 0:
            count = random.randrange(1,5)
            print (paragraphsep)
    else:
        sentence.append(newword)
    w1, w2 = w2, newword

rawDescription: How to create paragraphs from markov chain output?

description: Create paragraphs from markov chain output


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

for line in iter(sys.stdin.readline, ''): # get line as soon as it is available
    print(int(line)**2) # find square
    sys.stdout.flush()  # make the answer available immediately
    time.sleep(.5) # a delay to show that the answer is available immediately

rawDescription: How to Achieve Continuous Interactive Dialog with a Subprocess in Python?


code:
result = df.groupby(np.arange(len(df))//2).sum()
result.index = df.loc[1::2, 'Start']
print(result)
#               A  B
# Start
# 2004-01-11    0  0
# 2004-01-25    0  0
# 2004-02-08  123  0

# [3 rows x 2 columns]

rawDescription: Pandas Python: Merging every two rows in one dataframe


rawDescription: return constantly changing variable python

description: Return constantly changing variable python


code:
sentinel = object()
def recur_method(self, key=sentinel, val=sentinel):
    if key is sentinel and val is sentinel:
       raise exception("You fail it")

rawDescription: Generic arguments in recursive functions: terrible habit?


rawDescription: how to change form variable values from view

description: Change form variable values from view


code:
import heapq
import contextlib

files = [open(fn) for fn in inFiles]
with contextlib.nested(*files):
    with open('output', 'w') as f:
        f.writelines(heapq.merge(*files))

rawDescription: how to join multiple sorted files in Python alphabetically?

description: Join multiple sorted files in Python alphabetically


code:
from itertools import product
values = [1, 2, 3]
[[num * mul for num, mul in zip(values, combo)] for combo in product([1, -1], repeat=len(values))]

rawDescription: create list with negative value permutation

description: Create list with negative value permutation


code:
final_sum = float(sum(final_dict.values()))
[(elem, num, str(num/final_sum)+'%') for elem, num in final_dict.items()]

rawDescription: Grouping and totaling a pipe separated list


code: srt = sorted(twitter_users.values(), key=lambda v: v.mentioned)

rawDescription: Why is my list not sorted as expected?

description: Why is my list not sorted as expected


rawDescription: OpenCV-Python: What is correct shape of points for finding epipolar lines?


code:
from oauth2client.file import Storage
from oauth2client.client import AccessTokenRefreshError
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
import httplib2

FLOW = OAuth2WebServerFlow(
    client_id=CLIENT_ID,
    client_secret=CLIENT_SECRET,
    scope='https://www.googleapis.com/auth/analytics.readonly')
storage = Storage('file_name.dat')
credentials = storage.get()
if credentials is None or credentials.invalid:
    credentials = run(FLOW, storage)
http = credentials.authorize(httplib2.Http())

rawDescription: Google Analytics Core Reporting API Python library


code:
driver.find_element_by_css_selector(".step__footer__continue-btn.btn").click() # for class with css_selector you need '.' in the beginning
driver.find_element_by_class_name("step__footer__continue-btn").click() # by_class_name gets only one class
driver.find_element_by_xpath("//button[@type='submit'][@name='button']").click() # type='submit' and name='button' are <button> tag attributes, not div

rawDescription: Selenium python click button

description: Selenium python click button


rawDescription: How to convert any numeric string value in int?

description: Convert any numeric string value in int


rawDescription: iterating over a list by a certain number

description: Iterating over a list by a certain number


code: date_b = date_a - datetime.timedelta(minutes=30)

rawDescription: How to subtract datetime with multiple choice values

description: Subtract datetime with multiple choice values


code:
c = Counter(l[0] for l in data)
c

rawDescription: numpy - how do I count the occurrence of items in nested lists by index?

description: Numpy - how do I count the occurrence of items in nested lists by index


code:
while True:
    rows = input('Enter the number of rows:  ')

    if 3 <= rows <= 33:
        break
    else:
        continue

padding = ' '*rows
while rows > 0:
    print(padding[rows:] + '*'*rows)
    rows = rows - 1

rawDescription: Draw inverted triangle of asterisk by using nested loops in Python


rawDescription: Euclidean Distance Between All Points in an 2 Vectors


code:
string = 'WWF'
num = 0.0
print ("{0}:{1}".format(string[-1],num))

rawDescription: How to form a string from 2 values

description: Form a string from 2 values


code:
from operator import itemgetter
def header_parse(line,order_dict):
    header_info = line.split(',')
    indices = [None] * len(header_info)
    for i,col_name in enumerate(header_info):
        indices[order_dict[col_name]] = i
    return indices

def fix(fname,foutname):
    with open(fname) as f,open(foutname,'w') as fout:
        #Assume first line is a "header" and gives the order to use for the
        #rest of the file
        line = f.readline()
        order_dict = dict((name,i) for i,name in enumerate(line.strip().split(',')))
        reorder_magic = itemgetter(*header_parse(line.strip(),order_dict))
        for line in f:
            if line.startswith('Column'):  #somehow determine if this is a "header"
                reorder_magic = itemgetter(*header_parse(line.strip(),order_dict))
            else:
                fout.write(','.join(reorder_magic(line.strip().split(','))) + '\n')

if __name__ == '__main__':
    import sys
    fix(sys.argv[1],sys.argv[2])

rawDescription: Best way to parse a file with columns that randomly change order before importing it into SQL Server 2008?

description: Parse a file with columns that randomly change order before importing it into SQL Server 2008


code:
def giveMeSomeRows(group):
    return pandas.DataFrame(random.uniform(low=group.low, high=group.high, size=N))

rawDescription: How do I convert a row from a pandas DataFrame from a Series back to a DataFrame?

description: Convert a row from a pandas DataFrame from a Series back to a DataFrame


rawDescription: What is the best way to fetch/render one-to-many relationships?


code:
m = multiletters(ascii_uppercase)
next(m)
next(m)
next(m)

rawDescription: Python: Pair alphabets after loop is completed


code: self.btn = QtGui.QPushButton()

rawDescription: PyQt4 - Dragging and dropping files into QPushButton


code:
config.add_route('show_table', '/table')
config.add_route('show_chart', '/chart')

rawDescription: Create a webpage with charts or tables from csv data using the pyramid framework


code:
foo_objects = Foo.objects.extra(tables=('bar',),
                                where=('foo.bar_id=bar.id',),
                                select={'is_ok':'IF(bar.is_ok,"Yes","No")'}).values()

rawDescription: Django related_table() with extra()

description: Django related_table() with extra()


code: suggested_usernames = [name for name in get_similar_usernames(username)]

rawDescription: similar usernames generation in django rest framework

description: Similar usernames generation in django rest framework


code:
@register.assignment_tag
def exclude_files_by_type(SiteFiles, types):
    type_list = [type.strip() for type in types.split(',')]
    return SiteFiles.exclude(file_type__type__in=type_list)

rawDescription: django - Mulitple excludes in template filter

description: Django - Mulitple excludes in template filter


code:
from lxml import etree
doc = etree.parse('test.xml')
ids = doc.xpath(".//*[local-name()='KeyId']/text()")
print(ids)
...

rawDescription: XML parsing in Python using Python 2 or 3


code:
a, b, c, d = output[1:]
block = (first_element[0], a, b, c, d)

rawDescription: Create a Tuple from text file

description: Create a Tuple from text file


code:
def handleSelectionChanged(self, selected, deselected):
    indexes = selected.indexes()
    if indexes:
        print('row: %d' % indexes[0].row())

rawDescription: How to react to keyboard selection on QtTreeView?

description: React to keyboard selection on QtTreeView


code:
import re
line = '(<layerThickness> 0.58 </layerThickness>)'
L = re.search(r"([-+]?[0-9]*\.?[0-9]+)", line).group(0)
print(L)

rawDescription: Regex returning <_s instead of decimal value


rawDescription: How to rename a node with Python LXML?

description: Rename a node with Python LXML


code: print(list(data))

rawDescription: how to get key of dictionary in python

description: Get key of dictionary in python


code:
import pandas as pd

df1 = pd.DataFrame({'alpha': ['1', '2', '3'],
               'beta': ['JRLeparoux', 'BJHernandez,Jr.','SXBridgmohan'],})

df2 = pd.DataFrame({'alpha': ['1', '2', '3'],
               'gamma': ['Leparoux R', 'Hernandez,B, Jr.','Bridgmohan S X'],
               'zeta': ['17', '23','116'],})

df1['lower'] = df1['beta'].str.extract(r'([a-z]+)')
df2['lower'] = df2['gamma'].str.extract(r'([a-z]+)')
final = pd.merge(df1, df2)
print(final)

rawDescription: pandas join data frames on similar but not identical string using lower case only

description: Pandas join data frames on similar but not identical string using lower case only


code:
def date_hour(timestamp):
   return datetime.datetime.fromtimestamp(timestamp).strftime("%w %H")

rawDescription: Django group by hour

description: Django group by hour


code:
for i in [1, 2, 3]:
    num = i
print(num)

rawDescription: How to Print the information using selenium

description: Print the information using selenium


code:
ndb_ctx = ndb.get_context()
ndb_ctx.set_memcache_policy(lambda key: True)
...
yield operation.db.Put(product)

rawDescription: ndb Models are not saved in memcache when using MapReduce

description: Ndb Models are not saved in memcache when using MapReduce


code: import mybundle.JSONEncoder

rawDescription: Packaging python with circular imports

description: Packaging python with circular imports


code:
import email

# create a simple message
msg = email.mime.text.MIMEText('''This is a simple message.
And a very simple one.''')
msg['Subject'] = 'Simple message'
msg['From'] = 'sender@sending.domain'
msg['To'] = 'rcpt@receiver.domain'

# open a file and save mail to it
with open('filename.elm', 'w') as out:
    gen = email.generator.Generator(out)
    gen.flatten(msg)

rawDescription: Saving to .msg file in Python, or alternatively, sending mail to the file system


code:
func(a = "  foo  bar", b = "baz  boz", c = "biz buz  ")
func("  foo  bar", "baz  boz", "biz buz  ")
func(a = "  foo  bar", b = "baz  boz", c = "biz buz  ", d = " ha ha")

rawDescription: What is the proper way to loop through the required keyword arguments of a function and perform the same action on each of their values?


code:
grouped = df.groupby("student_id")
grouped.filter(lambda x: x["student_id"].count()==1)

rawDescription: Pandas Filter function returned a Series, but expected a scalar bool


code:
from bottle import route, run, install, JSONPlugin
from bson import json_util

class JSONDefaultPlugin(JSONPlugin):
    def __init__(self):
        super(JSONDefaultPlugin, self).__init__()
        self.plain_dump = self.json_dumps
        self.json_dumps = lambda body: self.plain_dump(body, default=json_util.default)

rawDescription: Bottle framework: how to return datetime in JSON response


rawDescription: Numpy extract arbitrary subarray along one axis


code:
def examplebdc():
    wordv = 'asdfsdfm'

    if any("m" in s for s in wordv):
        print("new post")
        threading.Timer(60*60, examplebdc).start()
    else:
        threading.Timer(50, examplebdc).start()

examplebdc()

rawDescription: pause threading.Timer for 1hr

description: Pause threading.Timer for 1hr


rawDescription: Arithmetic in Python slicing, end behaviour


code:
basedir = os.path.dirname(path)
if not os.path.exists(basedir):
    os.makedirs(basedir)

rawDescription: Create empty file using python

description: Create empty file using python


rawDescription: Python: look back n days rolling standard deviation


code: (self.list[L][0] == operand.list[R][0]) and (op == '*' or op == '**' or op == '+' or op == '-' or (op == '/' and operand.list[R][1] != 0))

rawDescription: How to do this conditional statement?

description: Do this conditional statement


code: df

rawDescription: grouping or merging? dataframes pandas python

description: Grouping or merging? dataframes pandas python


code:
def sub_group_hash(x):
    # x is a dataframe with the 'user id' field given above
    # return the last 2 characters of the input
    # if these are number like, then you will be sub-grouping into 100 sub-groups
    return x['user id'].str[-2:]

rawDescription: Trouble with grouby on millions of keys on a chunked file in python pandas


code:
sys.path.append('d')
sys.path

rawDescription: python module paths that I set have gone when I restart python

description: Python module paths that I set have gone when I restart python


code: i = np.where(k > mlm)[0][0]

rawDescription: Is there a fast way to compare one element in a numpy array to the rest of the elements in that array?


code:
from random import randint

def random_element(s):
    rand_index = randint(0, len(s)-1)
    return s[rand_index]

rawDescription: using randint to return random letter from string

description: Using randint to return random letter from string


rawDescription: Converting some CSV elements to float Python


code: weights = np.loadtxt(model_name, skiprows=6)

rawDescription: convert list of strings to numpy list of lists

description: Convert list of strings to numpy list of lists


code:
import itertools

xs = 'a', 'b'
for n in range(1, len(xs)+1):
    for ys in itertools.permutations(xs, n):
        print(ys)

rawDescription: Any possible combination in a list?

description: Any possible combination in a list


code:
def assert_inside_atomic_block(self, using=None):
    """
    Returns a function that will assert we are inside an atomic transaction block. The purpose of this is to allow
    us to inject this assertion inside methods where we want to verify that a transaction is active.

    Does not work with django.db.TransactionTestCase because it automatically wraps each test in a transaction.
    """

    if issubclass(self.__class__, TransactionTestCase):
        raise AssertionError('Cannot determine if code is run inside a transaction with a TransactionTestCase')

    def _assert_inside_atomic_block(*args, **kwargs):
        if not get_connection(using=using).in_atomic_block:
            raise AssertionError('Not inside an atomic transaction block')

    return _assert_inside_atomic_block

rawDescription: Django Unit Test Assert Database Transaction is Active


code:
"CAN'T".title()
"CAN'T".capitalize()

rawDescription: Keeping existing capital letters in string


code:
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder

Builder.load_string("""
<Example>:
    center_button: _center_button
    center_widget: _center_widget
    grid:_grid
    GridLayout:
        id: _grid
        cols: 3
        size_hint: .7, .3
        pos_hint: {'center_x': .5}
        x: 0
        Widget:
            Button:
                pos: self.parent.pos
                size: self.parent.size
                on_press: _grid.y = 0
                text: "Down"
        Widget:
            id: _center_widget
            Button:
                id: _center_button
                pos: self.parent.pos
                size: self.parent.size
                on_press: root.centerize(*args)
                text: "Out of the Grid"
        Widget:
            Button:
                pos: self.parent.pos
                size: self.parent.size
                on_press: _grid.top = root.height
                text: "Up"
""")

class Example(FloatLayout):
    def centerize(self, instance):
        if self.center_button.parent == self.center_widget:
            _size = self.center_button.size
            self.center_widget.remove_widget(self.center_button)
            self.center_button.size_hint = (None, None)
            self.add_widget(self.center_button)
            self.center_button.pos_hint = {'center_x': .5, 'center_y':.5}
        else:
            self.remove_widget(self.center_button)
            self.center_button.size_hint = (1, 1)
            self.center_widget.add_widget(self.center_button)
            self.center_button.size = self.center_widget.size
            self.center_button.pos = self.center_widget.pos

class ExampleApp(App):
    def build(self):
        return Example()

if __name__ == "__main__":
    ExampleApp().run()

rawDescription: How to unbind a property automatically binded in Kivy language?

description: Unbind a property automatically binded in Kivy language


code: [dis.jaccrd(string1, string2) for string1, string2 in product(list_1, list_2)]

rawDescription: Problems computing the score of a pairwise list in an iterative way?


code:
def listImportablesFromAST(ast_):
    from ast import (Assign, ClassDef, FunctionDef, Import, ImportFrom, Name,
                     For, Tuple, TryExcept, TryFinally, With)

    if isinstance(ast_, (ClassDef, FunctionDef)):
        return [ast_.name]
    elif isinstance(ast_, (Import, ImportFrom)):
        return [name.asname if name.asname else name.name for name in ast_.names]

    ret = []

    if isinstance(ast_, Assign):
        for target in ast_.targets:
            if isinstance(target, Tuple):
                ret.extend([elt.id for elt in target.elts])
            elif isinstance(target, Name):
                ret.append(target.id)
        return ret

    # These two attributes cover everything of interest from If, Module,
    # and While. They also cover parts of For, TryExcept, TryFinally, and With.
    if hasattr(ast_, 'body') and isinstance(ast_.body, list):
        for innerAST in ast_.body:
            ret.extend(listImportablesFromAST(innerAST))
    if hasattr(ast_, 'orelse'):
        for innerAST in ast_.orelse:
            ret.extend(listImportablesFromAST(innerAST))

    if isinstance(ast_, For):
        target = ast_.target
        if isinstance(target, Tuple):
            ret.extend([elt.id for elt in target.elts])
        else:
            ret.append(target.id)
    elif isinstance(ast_, TryExcept):
        for innerAST in ast_.handlers:
            ret.extend(listImportablesFromAST(innerAST))
    elif isinstance(ast_, TryFinally):
        for innerAST in ast_.finalbody:
            ret.extend(listImportablesFromAST(innerAST))
    elif isinstance(ast_, With):
        if ast_.optional_vars:
            ret.append(ast_.optional_vars.id)
    return ret

def listImportablesFromSource(source, filename = '<Unknown>'):
    from ast import parse
    return listImportablesFromAST(parse(source, filename))

def listImportablesFromSourceFile(filename):
    with open(filename) as f:
        source = f.read()
    return listImportablesFromSource(source, filename)

rawDescription: Check Contents of Python Package without Running it?


code:
# Modified from itertools.combinations_with_replace example
# from the python doc.
import itertools
import pprint
def odometer(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in itertools.product(range(n), repeat=r):
        yield tuple(pool[i] for i in indices)

pprint.pprint (list(odometer([1,2,3], 4)))

rawDescription: List all combinations

description: List all combinations


code:
from collections import defaultdict
count_dict = defaultdict(int)
for item in my_list:
    count_dict[item] += 1

rawDescription: Without using Counter(), how to find most common element in a list?


code:
from datetime import date

def year_boundaries(start, end):
    while start.year != end.year:
        yield start, date(start.year, 12, 31)
        start = date(start.year + 1, 1, 1)
    yield (start, end)

rawDescription: Python date seperating a multiple year date span to single year spans


code:
temp = a.__getitem__(slice(0, 1))
temp.__setitem__(0, 1)

rawDescription: slice in python, is a copy or just a pointer

description: Slice in python, is a copy or just a pointer


code:
def meshgrid2(*arrs):
    arrs = tuple(reversed(arrs))  #edit
    lens = map(len, arrs)
    dim = len(arrs)

    sz = 1
    for s in lens:
        sz*=s

    ans = []
    for i, arr in enumerate(arrs):
        slc = [1]*dim
        slc[i] = lens[i]
        arr2 = asarray(arr).reshape(slc)
        for j, sz in enumerate(lens):
            if j!=i:
                arr2 = arr2.repeat(sz, axis=j)
        ans.append(arr2)

    return tuple(ans)

rawDescription: Numpy meshgrid in 3D

description: Numpy meshgrid in 3D


code:
figure()
for r in range(myarray.shape[0]):
    plot(X[0], myarray[r] + 0.2*r, 'k')

rawDescription: Python plot values at nodes in meshgrid

description: Python plot values at nodes in meshgrid


rawDescription: Trim Pandas DataFrame based on values in list


code:
def __getattr__(self, tag):
    if len(tag) > 3 and tag.endswith('Tag'):
        # BS3: soup.aTag -> "soup.find("a")
        tag_name = tag[:-3]
        warnings.warn(
            '.%sTag is deprecated, use .find("%s") instead.' % (
                tag_name, tag_name))
        return self.find(tag_name)
    # We special case contents to avoid recursion.
    elif not tag.startswith("__") and not tag=="contents":
        return self.find(tag)
    raise AttributeError(
        "'%s' object has no attribute '%s'" % (self.__class__, tag))

rawDescription: extracting contents from a tag "extract" from Beautifulsoup

description: Extracting contents from a tag "extract" from Beautifulsoup


rawDescription: Return the different multiplicative combinations of a list of numbers in Python


code:
import csv
from collections import defaultdict

d = defaultdict( list )

input_file = 'a.csv'
output_file = 'b.csv'

with open( input_file, 'rb' ) as infile:
    reader = csv.reader(infile, delimiter='\t')
    next(reader, None)  # skip the header
    for row in reader:
        d[ row[0] ].append( int(row[1]) )

with open( output_file, 'wb' ) as outfile:
    writer = csv.writer(outfile, delimiter='\t')
    for key, value in d.items():
        writer.writerow( [key, max(value) - min(value)] )

rawDescription: Iterating through list of names and using min/max values to create new list


code:
df = df.set_index(['B'])
print(df.loc['one'])

rawDescription: Select rows from a DataFrame based on values in a column in pandas


code: acc = np.array((result, trainAcc, crossAcc, testAcc)).T

rawDescription: Simpler way to concatenate 3 or more lists in Numpy


code:
import re

table={}
with open('synonyms','r') as syn:
    for line in syn:
        match=re.match(r'(\w+)\s+=\s+(.+)',line)
        if match:
            primary,synonyms=match.groups()
            synonyms=[synonym.lower() for synonym in synonyms.split()]
            for synonym in synonyms:
                table[synonym]=primary.lower()

print(table)

rawDescription: Python: normalizing a text file

description: Python: normalizing a text file


code:
class RootClass(object):
    pass

class ChildClass(RootClass):
    pass

rawDescription: How to automatically Import all subclasses of a root class in Python?

description: Automatically Import all subclasses of a root class in Python


code:
f = {}
for item in a:
    ak1,ak2 = item.split('_')
    f[ak1] = {ak2:{}}
for item in b:
    bk1,bk2 = item.split('_')
    next(f[akey][bk1]
            for akey in f
                if bk1 in f[akey])[bk2] = {}
for item in c:
    ck1,ck2 = item.split('_')
    next(f[akey][bkey][ck1]
            for akey in f
                for bkey in f[akey]
                    if ck1 in f[akey][bkey])[ck2] = []
for item in d:
    dk1,dk2 = item.split('_')
    next(f[akey][bkey][ckey][dk1]
            for akey in f
                for bkey in f[akey]
                    for ckey in f[akey][bkey]
                        if dk1 in f[akey][bkey][ckey]).append(dk2)

import pprint
pprint.pprint(f)

rawDescription: how to create dict inside one more dict, without overwriting old data

description: Create dict inside one more dict, without overwriting old data


rawDescription: Searching a Pandas series using a string produces a KeyError


code:
mask = np.zeros((image.shape[0], image.shape[1]), dtype=np.bool)
mask[100:200, 100:500] = True

image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
image[mask, 0] = 80
image[mask, 1] = 255
image = cv2.cvtColor(image, cv2.COLOR_HSV2BGR)

rawDescription: OpenCV & Python: quickly superimpose mask over image without overflow


code:
def fn_connect(host, port, timeout):
    try:
        s = socket.create_connection((host, port), timeout=timeout)
    except socket.timeout:
        return None
    else:
        return s

rawDescription: Python's 2.7 socket.timeout behavior

description: Python's 2.7 socket.timeout behavior


code:
from nltk.stem import PorterStemmer
from nltk import word_tokenize, pos_tag
sent = "This is a messed up sentence from the president's Orama and it's going to be sooo good, you're gonna laugh."

rawDescription: Confused about priority between stemmer and pos tagger


code:
import decimal
import flask.json

class MyJSONEncoder(flask.json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, decimal.Decimal):
            # Convert decimal instances to strings.
            return str(obj)
        return super(MyJSONEncoder, self).default(obj)

rawDescription: How to convert all Decimals in a Python data structure to string?

description: Convert all Decimals in a Python data structure to string


code:
def distance(list1, list2):
    s = len(list1)
    t = sum(map(lambda x,y: 1 if x == y else 0, list1, list2))

    # note: float() is important here, or you would nearly always get zero!
    return float(s-t)/s

rawDescription: calculate the distance of data on specific column using python language

description: Calculate the distance of data on specific column using python language


rawDescription: Pandas: Get value of mutliple sorting/grouping query


code: {'Spec 3 Included': 'FALSE', 'Spec 2 Included': 'TRUE', 'Spec 3 Label': '4-1-Bead1-HS3', 'Spec 2 Label': '19-Flat2-HS3'}

rawDescription: Editing the XML texts from a XML file using Python


code: x=Ether()/IP()/TCP(sport=sp, dport=dp, options=[('WScale', 100)])

rawDescription: how to add the option scaling to the tcp packet with scapy

description: Add the option scaling to the tcp packet with scapy


code:
from plotfile import Plotter

app = Plotter(xval=range(0,10), yval=range(0,10))
plot = app.plotthing()
plot.show()
raw_input()

rawDescription: Passing plots out of a class

description: Passing plots out of a class


code: 'Pulp Fiction'.split()

rawDescription: Use of a deprecated module 'string'

description: Use of a deprecated module 'string'


rawDescription: Determine if entry is visible by startdate and enddate


code:
numbers = []
struct_4096 = struct.Struct("d" * 4096 / 8)
with open("sth.bin", "rb") as f:
    while True:
        chunk = f.read(4096)
        try:
            numbers.extend(struct_4096.unpack(chunk))
        except struct.error:
            numbers.extend(struct.unpack("d" * len(chunk) / 8))

rawDescription: Python read binary: how to unpack a large number of numbers?


code:
alphabeticalWord = lambda w: ''.join(sorted(word))

' '.join([alphabeticalWord(word) for word in sentence.split()])

rawDescription: Python lambda to print formatted nested list


rawDescription: Accessing / modifying submatrix of sparse scipy matrix


code:
import sys
sys.path.insert(0, '.path/to/folder/with/scripts')

rawDescription: how to place ".py" file into the search path of your python installation

description: Place ".py" file into the search path of your python installation


code:
from string import ascii_lowercase     # ascii_lowercase =='abcdefghijklmnopqrstuvwxyz'
with open(file) as f:
    text = f.read().strip()
    dic = {}
    for x in ascii_lowercase:
        dic[x] = text.count(x)

rawDescription: Count frequency of letters in a text file


code:
import lxml.html

root = lxml.html.fromstring(html)
matched = root.cssselect('#__VIEWSTATE')
if matched:
    value = matched[0].get('value')

rawDescription: Python find value of view state given source


rawDescription: Converting html to text with Python

description: Converting html to text with Python


code:
# second way
grouped = df.groupby('type').agg({'value': max}).reset_index()
grouped = grouped.set_index(['type','value'])

second = grouped.join(df.set_index(['type', 'value']))

rawDescription: Pandas, how to filter a df to get unique entries?


code:
class Note:
    def __init__(self, name, value): self.name, self._size = name, value
    size = property(lambda x: x._size+1)

class Notebook(object):
    def __new__(cls, *notes):
        notebook = object.__new__(cls)
        notebook._notes = {note.name: note.size for note in notes}
        for note in notes: setattr(notebook, note.name, note.size)
        return notebook

memo1, report1 = Note("memo", 5), Note("report", 20)
notebook1 = Notebook(memo1, report1)

print(notebook1.memo, notebook1.report) # 6 21

memo2, report2 = Note("memo", 35), Note("report", 40)
notebook2 = Notebook(memo2,report2)

print(notebook2.memo, notebook2.report) # 36 41
print(notebook1.memo, notebook1.report) # 6 21
notebook1.memo += 5
print(notebook1.memo) # 11
print(memo1.size) # 6
memo1.size += 5 # AttributeError: can't set attribute

rawDescription: Adding properties dynamically using functions created dynamically


code:
key_qs = QuotedString('"').setName("key_qs")
value_qs = QuotedString('"', escChar='\\', multiline=True).setName("value_qs")

rawDescription: Parsing a CS:GO language file with encoding in Python


rawDescription: How to automatically get port no. of a hardware in python serial communcation?

description: Automatically get port no. of a hardware in python serial communcation


code:
from collections import Counter

c = list((Counter(a) & Counter(b)).elements())

rawDescription: Intersection of two lists including duplicates?


code:
f = d * e[:,np.newaxis,np.newaxis]

d.shape
(3, 2, 2)
e.shape
(3,)
e[:,np.newaxis,np.newaxis].shape
(3, 1, 1)

rawDescription: multiply array of matrices by a vector

description: Multiply array of matrices by a vector


rawDescription: How to extract background-url from css definition with scrapy

description: Extract background-url from css definition with scrapy


code:
class MyFloat(object):
#...
  def __mul__(self, other):
    return type(self)(self.a * other.a)
#...

rawDescription: Override __mul__ from a child class using parent implementation: leads to problems


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

# simulate some artificial data
# ==========================================
np.random.seed(0)
df = pd.DataFrame(np.random.rand(10,2), columns=['original', 'new'] )
df['by column'] = pd.Series([0,0,0,0,1,1,1,1,1,1])

# your original plot
ax = df.boxplot(['original', 'new'], by='by column', figsize=(12,6))

rawDescription: pandas boxplot: swap box placement for comparison

description: Pandas boxplot: swap box placement for comparison


rawDescription: Python array manipulation

description: Python array manipulation


rawDescription: Python 2.7 modules don't exists

description: Python 2.7 modules don't exists


code: mins,secs,ms = divmod(divmod(delta_ms,1000)[0],60) + (divmod(delta_ms,1000)[1],)

rawDescription: An elegant one-line solution to extract data from Nested Tuples from divmod


code: get_selected_block_entries(infile, '')

rawDescription: Read and Write the specific content

description: Read and Write the specific content


code:
A
min_idx = np.argmin(A,axis=1)
A[np.arange(A.shape[0]),min_idx] # Using min_idx & indexing
np.amin(A,axis=1)                # Using np.amin to verify

rawDescription: Efficiently getting numpy.argmin and numpy.amin at the same time


code:
text = 'Hello, this is an example of text shown in the scrolling display. Bla, bla, bla!'
from textwrap import wrap
wrap(text, 16)

rawDescription: Python - split sentence after words but with maximum of n characters in result


rawDescription: Getting argument list in a Boost:Python function


code:
# file handler for **ansi_escape**
class MyFileHandler(logging.handlers.RotatingFileHandler):
    import re
    ansi_escape = re.compile(r'\x1b[^m]*m')
    def emit(self, record):
        record.msg = self.ansi_escape.sub('', record.msg)
        logging.handlers.RotatingFileHandler.emit(self, record)

rawDescription: How to decorate console logger messages in Python?

description: Decorate console logger messages in Python


rawDescription: How to know if a data contains non-ascii character?

description: Know if a data contains non-ascii character


code:
def partition(alist, indices):
    return [alist[i:j] for i, j in zip([0]+indices, indices+[None])]

rawDescription: Split a list into parts based on a set of indexes in Python


code:
class Timer(object):

    def timestamp(self):
        return time.strftime("%H:%M:%S")

rawDescription: Importing class from another file - where to put 'import' statements that the class requires


code:
class ArticleLike(models.Model):
    article = models.ForeignKey(Article, related_name='likes')
    like = models.ForeignKey(User, related_name='articles_like')

Article.objects.get(...).likes.all()

User.objects.get(...).articles_like.all()

rawDescription: django add relationships to user model

description: Django add relationships to user model


rawDescription: How do I take a column of pandas data based on a scalar condition AND a column comparison?

description: Take a column of pandas data based on a scalar condition AND a column comparison


code:
shrink(a, 2,2)
shrink(a, 2,1)

rawDescription: Reduce resolution of array through summation


code:
class MyClass(object):
    # This doesn't work
    query = text(str(select(...).where(...).order_by('distance').limit(1)))
    ...

    @classmethod
    def issue_query(cls, **params):
        cls.engine.execute(cls.query, params)

rawDescription: Is there a way to make SQLAlchemy pre-compile a query?


code:
def orig(a):
    cd = []
    (x, y) = np.shape(a)
    for row in a:
        trim = np.trim_zeros(row)
        to_add = y - np.size(trim)
        a = to_add / 2
        b = to_add - a
        cd.append(np.pad(trim, (a, b), 'constant', constant_values=(0, 0)).tolist())
    result = np.array(cd)
    return result

rawDescription: Centralising data in numpy

description: Centralising data in numpy


code: set(mylist)

rawDescription: efficient way to count the element in a dictionary in Python using a loop

description: Efficient way to count the element in a dictionary in Python using a loop


code:
def estimate_pi(terms):
    result = 0.0
    for n in range(terms):
        result += (-1.0)**n/(2.0*n+1.0)
    return 4*result

rawDescription: Leibniz formula for π - Is this any good? (Python)


code:
for item in potential_names:
    print(item)
    item = item[:-3]
    print(item)

rawDescription: file.write() not permanently writing to file python

description: File.write() not permanently writing to file python


code:
from random import randrange, sample

def random_insert(lst, item):
    lst.insert(randrange(len(lst)+1), item)

rawDescription: Python | How to append elements to a list randomly


code: popt, pcov = curve_fit(sigmoid, xdata, ydata, p0 = (1,1))

rawDescription: how to find 50% point after curve fitting using numpy

description: Find 50% point after curve fitting using numpy


code:
windows = {"bartlett": numpy.bartlett,
           "blackman": numpy.blackman,
           "hamming": numpy.hamming,
           "hanning": numpy.hanning,
           "kaiser": numpy.kaiser}

rawDescription: accessing module-level functions in Python if their name is stored in a variable

description: Accessing module-level functions in Python if their name is stored in a variable


code:
class Breakfast(object):
    def __init__(self, eggs=0, spam=5):
        self.spam, self.eggs = spam, eggs

rawDescription: Multiple constructors in python, using inheritance


code:
def __iter__(self):
    current = self.head

    while current:
        yield current
        current = current.next

rawDescription: How would a linked list be faster in iteration? with __iter__ and __next__ or with __getitem__?


code:
def OnInit(self):

   image=wx.Image('your_image.jpg',wx.BITMAP_TYPE_JPEG)
   self.frame=bucky(image)

rawDescription: wxPython - Creating a button that produces a bitmap image within my TextCtrl panel

description: WxPython - Creating a button that produces a bitmap image within my TextCtrl panel


code: df[(df['Vehicle Class'] == 2) & (df['Vehicle Class'].shift() == 3)]

rawDescription: How to plot selective data from a text file?

description: Plot selective data from a text file


code: r"([aeiou]+[bcdfghjklmnpqrstvwxz]+)+"

rawDescription: Regex in Python to find words that follow pattern: vowel, consonant, vowel, consonant


code:
class Person(object):
    def __init__(self, name, phone):
        self.name = name
        self.phone = phone
class Teenager(Person):
    def __init__(self, name, phone, website):
        Person.__init__(self, name, phone)
        self.website=website

rawDescription: Inheritance of attributes in python using _init_


rawDescription: add string to first item in list of list of strings in python

description: Add string to first item in list of list of strings in python


code:
john = Author.objects.create(name="John")
paul = Author.objects.create(name="Paul")
george = Author.objects.create(name="George")
ringo = Author.objects.create(name="Ringo")
entry.authors.add(john, paul, george, ringo)

rawDescription: Django: Saving multiple ManyToMany fields within a transaction


code: UserSizer.Add( upperSizer, 0, wx.EXPAND, 5 )

rawDescription: How to remove blank area between sizers in wxPython

description: Remove blank area between sizers in wxPython


code:
def stringify(x):
  if x // 10 % 10 == 1:
    return str(x) + 'th'
  else:
    return str(x) + { 1:'st', 2:'nd', 3:'rd' }.get(x % 10, 'th')

rawDescription: Any pretty python string formatting for a counter?


code:
x = int
y = x('2') # y is now 2

rawDescription: What does it mean when you assign int to a variable in Python?


code:
import B

tv = pygame.display.set_mode((256, 256))
B.blitSpecial(tv)

rawDescription: Python and Pygame: Avoiding creating display surface twice


code:
if request.path == "/sort/":
    sortid = request.POST.get('sortid')
    locs = Location.objects.order_by(sortid)
    if request.is_ajax():
        import json
        return HttpResponse(json.dumps(locs), mimetype="application/json")

rawDescription: How to return json dictionary in django ajax update

description: Return json dictionary in django ajax update


code: getregion(thesecoordinates, thesevalues, gt2 )

rawDescription: Pass conditional expression as function argument