code:
x = np.arange(6).reshape(3,2)
np.einsum.einsum('ij->j',x)
# array([6, 9])  # sums on the 1st dimension of `x`

rawDescription: Numpy: Multiple Outer Products

description: Numpy: Multiple Outer Products


code: foo(*i)

rawDescription: Is there a more pythonic way of exploding a list over a function's arguments?


code:
cur.execute('''SELECT {0}, {1}
                    FROM OsuOrgs
                    WHERE ORG_LEVEL= ? '''.format(on_level, parent_level),
                    x )

rawDescription: String parameters in pyodbc

description: String parameters in pyodbc


rawDescription: Python rounding of random floats to nearest points on a 2D uniform mesh grid


rawDescription: How to print a return value from a function inside a class

description: Print a return value from a function inside a class


code:
Data3 = 8
Data4 = 7
Data5 = 5
Data6 = 6
Data8 = 8

rawDescription: Compare two text files to find differences and output them to a new text file


code:
@login_required
def follow(request, username):
    myuser = request.user.id
    if request.method == 'POST':
        to_user = MyUser.objects.get(username=username)
        ...

rawDescription: NoReverseMatch found

description: NoReverseMatch found


code:
class COUNTRIES:  # pseudo-enum
    NEW_ZEALAND = 1
    UNITED_STATES = 2

rawDescription: Python style: lowercase class names for "namespaces"?


code: arrs = [ l.rstrip().split("\t") for l in open("your_file.tsv") ]

rawDescription: increment 1 in the sixth column after every twenty lines

description: Increment 1 in the sixth column after every twenty lines


code:
def seq_pow2(N):
    shp = 2*np.ones(np.log2(N),dtype=int)
    return np.arange(N).reshape(shp).transpose(np.arange(len(shp))[::-1]).ravel()

rawDescription: Iterate through a dynamic number of for loops (Python)


code:
from mock import patch
from PyQt4 import Qt

@patch.object(Qt.QMessageBox, 'aboutQt')
def testShowAboutQt(self, mock):
    self.win.actionAboutQt.trigger()
    self.assertTrue(mock.called)

rawDescription: Assert that a method was called in a Python unit test


code:
df = dd.read_csv(...)

from dask.multiprocessing import get
df.map_partitions(func, columns=...).compute(get=get)

rawDescription: python dask DataFrame, support for (trivially parallelizable) row apply?

description: Python dask DataFrame, support for (trivially parallelizable) row apply


rawDescription: How to create a pandas Timestamp object?

description: Create a pandas Timestamp object


code:
column = gtk.TreeViewColumn('Pixbuf and text')
cell1 = gtk.CellRenderText()
cell2 = gtk.CellRenderPixbuf()
column.pack_start(cell1, True)
column.pack_start(cell2, False)
column.set_attribute(cell1, 'text', 0) # the first column contains the text
column.set_attribute(cell2, 'pixbuf', 1) # the second column contains the pixbuf

rawDescription: How to render custom columns with a GenericTreeModel

description: Render custom columns with a GenericTreeModel


code:
pytest
coverage

rawDescription: python setup.py sdist and custom setup keywords don't play together

description: Python setup.py sdist and custom setup keywords don't play together


rawDescription: Adding a line to a matplotlib scatterplot based on a slope


code:
class Bar(Foo):
    aMethod = deco(Foo.aMethod)

rawDescription: Decorate subclass method

description: Decorate subclass method


code:
import xml.etree.ElementTree as ET

def recur(node):
    # if this node is a foobar, return a one-item list containing it
    if 'Name' in node.attrib:
        if "FooBar" in node.attrib['Name']:
            return [ node ]
    # otherwise return a list of the results on the children
    found = []
    for child in node:
        found += recur(child)
    return found

tree = ET.parse('test.xml')
root = tree.getroot()
print(recur(root))

rawDescription: How can I use ElementTree to find all top level matched nodes?

description: Use ElementTree to find all top level matched nodes


code:
from collections import defaultdict
def letterOccurrances(string):
    frequencies = defaultdict(lambda: 0)
    for character in string:
        frequencies[character.lower()] += 1
    return frequencies

rawDescription: How do I iterate through a string in Python?

description: Iterate through a string in Python


code:
def to_str(lst):
    if not lst:
        return ''
    return str(lst[0]) + to_str(lst[1:])

rawDescription: Covert a list to string

description: Covert a list to string


code: sorted(thelist, key=indices.get)

rawDescription: Python: sort list of strings in order that they appear in another string


code:
def sub():
    global name_of_array
    return name_of_array[0, 0]

def main():
    global name_of_array
    name_of_array = np.zeros((2, 2))
    sub()

rawDescription: Numpy array defined in main not recognized in function


code:
for result in pool.imap_unordered(func, args):
    counter -= 1

rawDescription: Increment/decrement global variable using python multiprocessing module


code:
#!/usr/bin/python

import matplotlib
matplotlib.use( 'Agg' )
import pylab

pylab.plot([1,2,3])
pylab.savefig('img.png')

rawDescription: Change permissions to allow PHP script in browser to execute matplotlib operations in a python script


code:
from scipy.misc import lena
from matplotlib import pyplot as plt

img = lena().astype(np.float32)
img -= img.min()
img /= img.max()
imgarray = np.sin(np.linspace(0, 2*np.pi, 25)[:, None, None] + img)

m = montage(imgarray)
plt.imshow(m, cmap=plt.cm.jet)

rawDescription: Algorithm to create a square matrix given any number of smaller square matrices


code:
def dates_split(data, dates1):
    lines = data.split("\n")
    dict_days = Counter(dt for line in lines
                        for dt in line.split() if dt in dates1)
    return dict_days.most_common(5)

def dates_comp_date1(data, dates1):
    lines = data.split("\n")
    r = re.compile("|".join(dates1))
    dict_days = Counter(dt for line in lines for dt in r.findall(line))
    return dict_days.most_common(5)

rawDescription: Performance - searching a string in a text file - Python


code:
import random
t = list(t)
random.shuffle(t)
l = []
entries = {}
queue = {}
for id, fid, title in t:
    entries[id] = entry = {'id': id, 'fid': fid, 'title': title}
    if id in queue:
        entry['sons'] = queue[id]
        del queue[id]
    if fid == -1:
        l.append(entry)
    elif fid in entries:
        parent = entries[fid]
        parent.setdefault('son', []).append(entry)
    else:
        queue.setdefault(fid, []).append(entry)

if queue:
    raise ValueError('No entries found for fid(s) {}'.format(queue.keys()))

pprint(l)

rawDescription: how to change a tuple into dictionary tree in python

description: Change a tuple into dictionary tree in python


rawDescription: Is is possible to run knnMatch for different images on different threads?


rawDescription: Django: How to filter patients from one department?


code:
s.values
'a' in s.values

rawDescription: How to determine whether a Pandas Column contains a particular value

description: Determine whether a Pandas Column contains a particular value


code:
def num_digits(n):
    if n == 0:
        return 1
    if n < 0:
        return num_digits(abs(n))

    count = 0
    while n:
        count = count + 1
        n = n / 10
    return count

rawDescription: How do I get my num_digit function to give me the correct output and how do I get it to return any integer value in python?

description: Get my num_digit function to give me the correct output and how do I get it to return any integer value in python


code:
cleaned = []
items = line.split()
for item in items:
    if item.startswith('(') and item.endswith(')'):
        cleaned.append(item.strip('()'))
        break
cleaned.append(items[-1])
cleaned = ' '.join(cleaned)

rawDescription: Python process text file with these criteria


code:
second_items = iter(l)
next(second_items, None) # Avoid exception on empty input
for thing1, thing2 in itertools.izip(l, second_items):
    whatever()

rawDescription: Does Python copy references to objects when slicing a list?


code:
import numpy as np

m, n = 5, 3
a = np.zeros((m, n))
b = np.ones((m, n))

boolvec = np.random.randint(0, 2, m).astype(bool)

rawDescription: Selecting columns in numpy based on a Boolean vector


code:
os.rename('myfile.csv', 'myfile.csv.bak')
with open('myfile.csv.bak', 'rU') as infile, open('myfile.csv', 'wU') as outfile:
    for line in infile:
        outfile.write(line.replace('\r'))
os.remove('myfile.csv.bak')

rawDescription: Removing newline from a csv file

description: Removing newline from a csv file


code:
df['D'] = 0
df.D = np.where( df.A < 1.5, df.B + df.C, df.D )
df.D = np.where( df.A > 2.5, df.B * df.C, df.D )

rawDescription: Handling assignment to empty selections from pandas.df.loc


code: whos

rawDescription: numpy squeeze along an axis wont work

description: Numpy squeeze along an axis wont work


code: sol = fsolve(lambda x, y: myfunc(x) - y, x0, args=(3,))

rawDescription: Python find root for non-zero level

description: Python find root for non-zero level


code: [dd[key] for key in sorted(dd.keys())]

rawDescription: Grouping elements of list by their membership order on another list


code:
# [START UserLogout]
class UserLogout(webapp2.RequestHandler):
    def get(self):
        url_logout = users.create_logout_url('/')
        self.response.out.write(url_logout)
# [END UserLogout]

rawDescription: google app engine python

description: Google app engine python


rawDescription: In python, how could I make this three line code into a one line code?


code: resultList = grouped_data["results"]

rawDescription: Loop through list in dictionary with dictionary values


code:
from langpy import lang
from langpy import port

rawDescription: def function returning wrong value (python 2.7)

description: Def function returning wrong value (python 2.7)


rawDescription: List of Dictionaries which contain lists


code: lock = threading.Lock()

rawDescription: How to share an integer between threads in python

description: Share an integer between threads in python


code:
def reset_to_0(the_array):
    for i, e in enumerate(the_array):
        if isinstance(e, list):
            reset_to_0(e)
        else:
            the_array[i] = 0

rawDescription: Python reset to 0 a Multidimensional Array


rawDescription: generating a full combination of values from multiple lists in python?

description: Generating a full combination of values from multiple lists in python


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


code:
class Prereq(models.Model):
    target_content_type = models.ForeignKey(ContentType, related_name='prereq_parent', limit_choices_to=conditions)
    target_object_id = models.PositiveIntegerField()
    target_object = GenericForeignKey("target_content_type", "target_object_id")

rawDescription: Django GenericForiegnKey, specify ContentTypes include/exclude for admin


code: query = '?' + url.query if url.query else ''

rawDescription: Python assignment with AND and OR

description: Python assignment with AND and OR


code:
def daterange(start_date, end_date, period):
    d = start_date
    while d < end_date:
        yield d
        d += period

rawDescription: How to match a list of dates to a pattern?

description: Match a list of dates to a pattern


code:
unique = 'bflmpsvz'

my_namespaces = {
                 'http://www.topografix.com/GPX/1/0' :    unique,
                 'http://www.groundspeak.com/cache/1/0' : 'groundspeak',
                }
xml.etree.ElementTree._namespace_map.update( my_namespaces )

rawDescription: lxml.etree and xml.etree.ElementTree adding namespaces without prefixes(ns0, ns1, etc.)

description: Lxml.etree and xml.etree.ElementTree adding namespaces without prefixes(ns0, ns1, etc.)


code:
from setuptools import setup, find_packages

setup(name='core',
      version='0.1',
      package_dir={'':'src'},
      packages=find_packages("src", exclude=["test"]), # <- test is excluded
      ####packages=find_packages("src"), # <- test is included
      author='J.R. Hacker',
      author_email='jr@example.com',
      url='http://stackoverflow.com/q/26545668/4279',
      package_data={'core': ['config/*.tmpl']},
)

rawDescription: setup.py sdist exclude packages in subdirectory

description: Setup.py sdist exclude packages in subdirectory


code: foods = { "Steak": "not-veg", "Spinach Pasta": "veg" }

rawDescription: How do I pick a string from a list and put it in a new list with the criteria

description: Pick a string from a list and put it in a new list with the criteria


code:
long_url = ('video' if self.video
            else urlparse(self.url).netloc if self.url
            else "be kind to one another")

rawDescription: how to add one more elsif into this function?

description: Add one more elsif into this function


code: import matplotlib.pyplot as plt

rawDescription: Get matplotlib color from style palette

description: Get matplotlib color from style palette


code:
from itertools import izip_longest
d = {1: [12, 13, 14, 15], 2: [16, 17, 18], 3: [19, 20, 21, 22]}
labels = d.keys()
rows = izip_longest(*d.values())

rawDescription: Dictionary of Lists to CSV in Python

description: Dictionary of Lists to CSV in Python


rawDescription: What is the easiest way to convert list with str into list with int?


code:
result = verify_session()
if not result:
   result = render_template("account")
return result

rawDescription: How do you break Python Flask controller flow when calling return inside a function?

description: Break Python Flask controller flow when calling return inside a function


code:
mx = maximum_filter(R, size=3)
mx

rawDescription: python: Faster local maximum in 2-d matrix

description: Python: Faster local maximum in 2-d matrix


code: self.results = Entry(display, textvariable=numbers, width=31, fg="snow", bg="snow", font="Verdana")

rawDescription: Binding number and operator buttons to calculator buttons


code:
# this step is optional; you don't have to configure a tag
# before adding it to a range of text
text.tag_configure("already_selected", background="yellow")
...
text.tag_add("already_selected", line_beginning, line_ending)

rawDescription: Avoid accessing the same location twice/clicking twice, TkInter Text widget


code:
import random
y = random.randint(1, 10)

rawDescription: Hotter/Colder Number Game in Python

description: Hotter/Colder Number Game in Python


code:
class LightDMUser(QObject):
    pass
LightDMUser = set_properties("display background")(LightDMUser)

rawDescription: Can anyone help condense this Python code?


code:
musics = data.execute("select * from audio")
lines = {row[1]: row[0] for row in musics}

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

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


code:
for avatar in avatars:
    user = avatar.user

rawDescription: chaining queries together in Django

description: Chaining queries together in Django


rawDescription: How can I add an additional row and column to an array?

description: Add an additional row and column to an array


code:
{ x : 2 if x == _variable else 3
  for x in [_id, _if, _while, _lbrace, _println, _variable] }

rawDescription: Pythonic way to write create dictionary from dict comprehension, + something else


rawDescription: Contradictory outputs in simple recursive function


code:
def italic(predecessor):
    x = predecessor
    x2 = x
    def successor():
        return "<italic/>" + x2() + "</italic>"
    return successor

rawDescription: A better way to write python closures?

description: A better way to write python closures


code:
import wx

class MyMenu(wx.Frame):

    def __init__(self, parent, id, title):
        super(MyMenu, self).__init__(parent, id, title)

        valid_targets = ["jpg", "gif", "pcx",
            "msp", "png", "ppm", "tiff"]

        # Cheap Image Converter v .1
        # File to convert: [            ] <Select File>
        # Convert to: [.jpg]v
        # [CONVERT]

        self.convert_target = None
        self.raw_file = []
        self.panel = wx.Panel(self, -1)

        # all elements will be declared in the order in which
        # they appear, top to bottom, left to right.
        self.intro_text = wx.StaticText(self.panel, -1, "Image Converter v 0.1")

        # Load files button and binding
        self.file_convert_text = wx.StaticText(self.panel, -1,
            "Select a file to convert.")
        self.file_text_box = wx.TextCtrl(self.panel, -1,
            "Select a file!", style=wx.TE_READONLY)
        self.load_file_button = wx.Button(self.panel, -1, "Load Files")
        #self.load_file_button.Bind(wx.EVT_BUTTON, self.SelectFileDialog)

        # Conversion type selection box and label
        self.choice_list_desc = wx.StaticText(self.panel, -1,
            "Select format to convert to: ")
        self.choice_list = wx.Choice(self.panel, -1,
            choices=valid_targets)
        #self.choice_list.Bind(wx.EVT_CHOICE,
            #self.SelectFromChoice)

        # Convert button!
        self.go_button = wx.Button(self.panel, -1, "Convert!")
        #self.go_button.Bind(wx.EVT_BUTTON, self.PerformConversion)

        # sizers!
        self.master_container = wx.GridBagSizer(4, 3)

        self.master_container.Add(self.intro_text, (0,0), (1,3), wx.EXPAND)

        self.master_container.Add(self.file_convert_text, (1,0), wx.DefaultSpan, wx.EXPAND | wx.ALIGN_RIGHT)
        self.master_container.Add(self.file_text_box, (1,1), wx.DefaultSpan, wx.EXPAND | wx.ALIGN_CENTER)
        self.master_container.Add(self.load_file_button, (1,2), wx.DefaultSpan, wx.EXPAND | wx.ALIGN_CENTER)

        self.master_container.Add(self.choice_list_desc, (2,0), wx.DefaultSpan, wx.EXPAND)
        self.master_container.Add(self.choice_list, (2,1), wx.DefaultSpan, wx.EXPAND)

        self.master_container.Add(self.go_button, (3,0), wx.DefaultSpan, wx.EXPAND)

        self.panel.Layout()
        self.panel.SetSizer(self.master_container)
        self.master_container.Fit(self)

        self.Centre()

# callbacks removed for brevity.
class MyApp(wx.App):
    def OnInit(self):
        frame = MyMenu(None, -1, 'Python Bulk Image Converter')
        frame.Show(True)
        return True

if __name__ == "__main__":
    app = MyApp(0)
    app.MainLoop()

rawDescription: Stretching a panel to fill the whole window as opposed to just a corner


code:
import pandas as pd

url = ("https://www.quandl.com/api/v3/datasets.csv?"
       "database_code=TSE&per_page=100&sort_by=id&page={0}")
[pd.read_csv(url.format(page_number)) for page_number in range(1, 5)]

rawDescription: python requests.text to pandas dataframe

description: Python requests.text to pandas dataframe


code: return next(islice(permutations(range(10)), 999999, 1000000))

rawDescription: Elegant way to skip elements in an iterable


code:
import numpy as np
import pandas as pd
N = 100
df1 = pd.DataFrame({'a': np.random.randn(10*N),
                   'b': [1, 2] * 5*N,
                   'c': np.random.randn(10*N)},
                   index=pd.date_range('1/1/2000', periods=10*N))
df2 = pd.DataFrame({'a': np.random.randn(N),
                'b': [2, 1] * (N//2),
                'c': np.random.randn(N)},
               index=pd.date_range('1/1/2000', periods=N))

def orig(df1, df2):
    df1 = df1.reset_index() # 312 µs per loop
    df1['embarrassingHackInd'] = 0 # 75.2 µs per loop
    df1.set_index('embarrassingHackInd', inplace=True) # 526 µs per loop
    df1.rename(columns={'index':'origIndex'}, inplace=True) # 209 µs per loop
    df1['df1Date'] = df1.origIndex.astype(np.int64) // 10**9 # 23.1 µs per loop
    df1['df2Date'] = 0

    df2 = df2.reset_index()
    df2['embarrassingHackInd'] = 0
    df2.set_index('embarrassingHackInd', inplace=True)
    df2.rename(columns={'index':'origIndex'}, inplace=True)
    df2['df2Date'] = df2.origIndex.astype(np.int64) // 10**9
    df2['df1Date'] = 0
    df3 = abs(df1-df2) # 88.7 ms per loop  <-- this is the bottleneck
    return df3

def using_numpy(df1, df2):
    df1.index.name = 'origIndex'
    df2.index.name = 'origIndex'
    df1.reset_index(inplace=True)
    df2.reset_index(inplace=True)
    df1_date = df1['origIndex']
    df2_date = df2['origIndex']
    df1['origIndex'] = df1_date.astype(np.int64)
    df2['origIndex'] = df2_date.astype(np.int64)

    arr1 = df1.values
    arr2 = df2.values
    arr3 = np.abs(arr1[:,np.newaxis,:]-arr2) # 3.32 ms per loop vs 88.7 ms
    arr3 = arr3.reshape(-1, 4)
    index = pd.MultiIndex.from_product(
        [df1_date, df2_date], names=['df1Date', 'df2Date'])
    result = pd.DataFrame(arr3, index=index, columns=df1.columns)
    # You could stop here, but the rest makes the result more similar to orig
    result.reset_index(inplace=True, drop=False)
    result['df1Date'] = result['df1Date'].astype(np.int64) // 10**9
    result['df2Date'] = result['df2Date'].astype(np.int64) // 10**9
    return result

def is_equal(expected, result):
    expected.reset_index(inplace=True, drop=True)
    result.reset_index(inplace=True, drop=True)

    # expected has dtypes 'O', while result has some float and int dtypes.
    # Make all the dtypes float for a quick and dirty comparison check
    expected = expected.astype('float')
    result = result.astype('float')
    columns = ['a','b','c','origIndex','df1Date','df2Date']
    return expected[columns].equals(result[columns])

expected = orig(df1.copy(), df2.copy())
result = using_numpy(df1.copy(), df2.copy())
assert is_equal(expected, result)

rawDescription: Difference between every row and column in two DataFrames (Python / Pandas)


rawDescription: How do i get the average of three pos_coordinates values?

description: Get the average of three pos_coordinates values


code:
df = pd.DataFrame({"stuff": ["44_title_iphone6_32GB", "44_title_iphone5_32gb_white"]})
df
df["stuff"].str.split("_", 2)

rawDescription: Pandas Split DataFrame

description: Pandas Split DataFrame


code:
def is_osx_realpath (path):
    return path == osx_realpath(path)

rawDescription: Python: Check if a directory is an alias


code: max(alkaline_earth_values, key=lambda x: x[1])

rawDescription: Sorting or Finding Max Value by the second element in a nested list. Python


code:
import gmpy2

def prime_numbers(limit=1000000):
    '''Prime number generator. Yields the series
    2, 3, 5, 7, 11, 13, 17, 19, 23, 29 ...
    using Sieve of Eratosthenes.
    '''
    yield 2
    sub_limit = int(limit**0.5)
    # Actual number is 2*bit_position + 1.
    oddnums = gmpy2.xmpz(1)
    f_set = oddnums.bit_set
    f_scan0 = oddnums.bit_scan0
    current = 0
    while True:
        current += 1
        current = f_scan0(current)
        prime = 2 * current + 1
        if prime > limit:
            break
        yield prime
        # Exclude further multiples of the current prime number
        if prime <= sub_limit:
            list(map(f_set,range(2*current*(current+1), limit>>1, prime)))

rawDescription: Speed up bitstring/bit operations in Python?


code: [[(j,i) for j in range(i,max+1)] for i in range(max+1)]

rawDescription: Accessing array elements by internal data index and order


code:
A = Start
B = End
C = Inactive
D = Active

rawDescription: url design in django-cms

description: Url design in django-cms


code:
df1 = df.xs('2015-01-31', level=1)

columns = df1.loc['key1'].nlargest(2).index.tolist()
columns.append(df1.loc['key2'][df.columns.difference(columns)].idxmax())
df1.loc['rtr', columns]

rawDescription: Sequential sorting in multi-indexed Pandas DataFrame


code:
SerialData = [ b'468095384\r\n', b'0.01\r\n'] * 10

radarData = []
timeData = []

for i in range(0,len(SerialData)):
    if(i % 2 == 0):
        radarData.append(float(str(SerialData[i], 'utf-8')))
    else:
        timeData.append(float(str(SerialData[i], 'utf-8')))

print(radarData)
print(timeData)

rawDescription: Python doesn't parse Serial data to an array


rawDescription: Rounding in Python NumPy when adding nodes in Networkx


code:
mapper = class_mapper(ORMClass)
pkname = str(mapper.primary_key[0].name)

rawDescription: Get the relationship metadata from sqlalchemy


code:
obj = MyClass(
    API_KEY,
    API_SECRET,
    OAUTH_TOKEN,
    OAUTH_TOKEN_SECRET,
    data=DATA
)

rawDescription: best way to pass kwargs arguments to overriden method

description: Pass kwargs arguments to overriden method


code: table = [0 for _ in range(n+1)]

rawDescription: Dynamic Programming - Fibonacci

description: Dynamic Programming - Fibonacci


code:
import re
datetime.datetime.strptime(re.sub('\..*', '', s), "%Y-%m-%d %H:%M:%S")

rawDescription: Python reading logfile with timestamp including microseconds


rawDescription: How can I replace LaTeX $...$ and $$...$$ notations by something like <div>$...$</div>?

description: Replace LaTeX $...$ and $$...$$ notations by something like <div>$...$</div>


code:
class X(object):
    def get_y(self):
        return self.y

rawDescription: How to call the property method in a dynamic Django model?

description: Call the property method in a dynamic Django model


rawDescription: time.strptime got TypeError: function takes at most 8 arguments (9 given)

description: Time.strptime got TypeError: function takes at most 8 arguments (9 given)


code:
def f(x):
    y = np.dot(A, x) - b
    return np.dot(y, y)

rawDescription: Solving system using linalg with constraints


code:
value1 = value2 = value3 = 0
value4 = 100
value1, value2, value3 = inc(value4, value1, value2, value3)

rawDescription: Multiple increment operators on the same line Python


code:
import csv

def make_billing_dict(csv_dict_reader):
    bdict = {}
    for entry in csv_dict_reader:
        key = entry['BillingNumber']
        bdict[key] = entry
    return bdict

with open('old.csv') as csv_file:
    old = csv.DictReader(csv_file)
    old_bills = make_billing_dict(old)

rawDescription: Compare 2 .csv files with Python then output results


code: bet.append(mon) # add to end

rawDescription: How to change a list in a for loop? Labouchere in Python

description: Change a list in a for loop? Labouchere in Python


code:
import re
import timeit
def test2(charsInString):
    regex = re.compile('((ab{3,5}c+){5000,6000}d)+e*f')
    string = 'abbbbcc'*charsInString;
    for i in range(1, 100000):
        regex.match(string)
print(timeit.timeit("test2(1)", setup="from __main__ import test2", number=1))
print(timeit.timeit("test2(3571)", setup="from __main__ import test2", number=1))
print(timeit.timeit("test2(3572)", setup="from __main__ import test2", number=1))

rawDescription: Minimum lenght of string that match a regex


rawDescription: Need to take average of long, strangely formatted set of data in Python


code:
def parse_club(self, response):
    # loop through each of the rows
    for sel in response.css('td.club'):
        item = rankingItem()
        item['name'] = sel.xpath('.//div[@itemprop="itemListElement"]/text()').extract_first()

        # get more club information
        club_href = sel.xpath('.//a/@href').extract_first()
        club_url = response.urljoin(club_href)
        request = scrapy.Request(club_url, callback=self.parse_club_page_2)

        request.meta['item'] = item
        yield request

rawDescription: Multi-page scrapy yielding my items too quickly to finish - functions not chaining and waiting for completion


code:
rest = x>>1
cf = get_carry_flag()

rawDescription: Carry bit of python bitwise shift

description: Carry bit of python bitwise shift


code:
def split_list(l, sep):
    nl = [[]]
    for el in l:
        if el == sep:
            nl.append([])
        else:
            # Append to last list
            nl[-1].append(el)
    return nl

rawDescription: Splitting a list with a separator

description: Splitting a list with a separator


code:
from scrapy.spider import Spider
from scrapy.selector import Selector
from .items import myItems

class mainSpider(Spider):
    name = "crazyCrawler"
    allowed_domains = ['http://ign.com', 'http://de.ign.com/']
    handle_httpstatus_list = [200, 302, 404] # any other if you want

    start_urls = [
        "http://ign.com"
    ]

    def parse(self, response):
        # spider
        sel = Selector(response)

        items = []
        item = myItems()

        item['redirect_count'] = 0

        if response.status == 302:
            item['redirect_count'] += 1

rawDescription: Count number of redirects in Scrapy

description: Count number of redirects in Scrapy


code: val = map(lambda y: x[y*4:y*4+4], range(len(x)//4))

rawDescription: python for loop using lambda syntax

description: Python for loop using lambda syntax


code:
var1, var2, var3, var4 = map(float, findall("-?\d+\.\d+", mystr))
var1
var4

rawDescription: Collecting the numbers from a string in python


code:
class MyClass:
    def __getitem__(self,index):
        return index * 2
myobj = MyClass()
myobj[3]

rawDescription: How to override [] operator

description: Override [] operator


rawDescription: Python code to access sub-List by index of first element of that sub-List


rawDescription: Scrapy multiple spiders

description: Scrapy multiple spiders


code: [x + y for x in xrange(limit + 1) for y in xrange(x + 1)]

rawDescription: Python - Sum of numbers

description: Python - Sum of numbers


rawDescription: Using Python to Decode Steganography Images (example images at Wikipedia)


code:
from collections import defaultdict, Mapping

class default_attribute_dict(defaultdict):
    def __init__(self, *args, **kwargs):
        super(default_attribute_dict, self).__init__(*args, **kwargs)
        self.__dict__ = self

    def __getattr__(self, name):
        # trigger default
        return self[name]

    @classmethod
    def from_dictionaries(cls, d, default=lambda: None):
        cdic = cls(default)
        for key, value in d.iteritems():
            if isinstance(value, Mapping):
               value = cls.from_dictionaries(value, default=default)
            cdic[key] = value
        return cdic

rawDescription: Python 2.7 how to define a super powerful class-style dict object?


code:
models.py
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    phone_number = models.CharField(max_length=100, validators=[
    RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'")
    ], blank=True, null=True)
    created_timestamp = models.DateTimeField(auto_now_add=True, null=True)
    updated_timestamp = models.DateTimeField(auto_now=True, null=True)

rawDescription: How to implement nested serializer in django rest framework?

description: Implement nested serializer in django rest framework


code: max(cols[1] for cols in reader)

rawDescription: For loop position in csv reader_Python

description: For loop position in csv reader_Python


code:
game.update()

kname = pygame.key.get_pressed()
if kname[pygame.K_LEFT]:
    if x > 0: x = x - 5
elif kname[pygame.K_RIGHT]:
    if x < 700: x = x + 5
elif kname[pygame.K_UP]:
    if y > 0: y = y - 5
elif kname[pygame.K_DOWN]:
    if y < 460: y = y + 5

pygame.display.update()

rawDescription: The method for the use of about pygame.sprite.groupcollide


code:
import numpy as np

arr = np.empty([5,5])
arr[:] = np.nan
arr[1:4,1:4] = np.arange(100,109).reshape(3,3)

rawDescription: Calculate conditional means in Pandas

description: Calculate conditional means in Pandas


code:
final = [['K'], ['E'], ['Y']]
message = ['F', 'F', 'F', ...]
while message:
    for lst in final:
        for _ in range(2):
            lst.append(message.pop(0))

rawDescription: Assigning N number of elements from a flat list, itterativly to each member of a matrix


code:
def groupby_app(A,WSZ): # @lambo477's solution
    groups = itertools.groupby(A)
    result = []
    for group in groups:
        group_items = [item for item in group[1]]
        group_length = len(group_items)
        if group_length >= WSZ:
            result.extend([item for item in group_items])
        else:
            result.extend([0]*group_length)
    return result

def stride_tricks_app(arr, window): # @ajcr's solution
    x = pd.rolling_min(arr, window)
    x[:window-1] = 0
    y = np.lib.stride_tricks.as_strided(x, (len(x)-window+1, window), (8, 8))
    y[y[:, -1] == 1] = 1
    return x.astype(int)

rawDescription: Filtering pandas or numpy arrays for continuous series with minimum window length


code:
class SubscriberActivityView(View):
  def get(self, request):
    user_profile = UserProfile.objects.get(user=request.user)
    date_verbose_name = user_profile.timezone
    events = user_profile.event_set.all()
    context = {
      'event_table': EventTable(list(events), date_verbose_name=date_verbose_name)
    }

rawDescription: django-tables2 column header with value from database

description: Django-tables2 column header with value from database


code:
import pandas as pd
ts = pd.TimeSeries(range(86400), index=pd.DatetimeIndex(start='2013-05-14 00:00:00', freq='1S', periods=86400))

rawDescription: timeseries database to use with python

description: Timeseries database to use with python


code: np.delete(a, list(range(0, a.shape[1], 8)), axis=1)

rawDescription: delete every nth row or column in a matrix using Python

description: Delete every nth row or column in a matrix using Python


code:
from copy import deepcopy
new_list = deepcopy([[1], [1, 2], [1, 2, 3]])

rawDescription: How to copy a list which will not be changed in function call in Python

description: Copy a list which will not be changed in function call in Python


code:
p = re.compile(r'\w+\s*(?P<semicolon>;)\s*\w+')
for m in p.finditer(s):
    print(m.start('semicolon'), s[m.start('semicolon')])

rawDescription: Finding punctuation marks in noisy text

description: Finding punctuation marks in noisy text


code:
from sqlalchemy import inspect
inspector = inspect(engine)

for table_name in inspector.get_table_names():
   for column in inspector.get_columns(table_name):
       print("Column: %s" % column['name'])

rawDescription: List database tables with SQLAlchemy

description: List database tables with SQLAlchemy


code:
import numpy as np
cluster = np.random.randint(10, size = (5,2))
cluster
new_spin = np.array([[1,2]])
new_spin == cluster

rawDescription: Detect ordered pair in numpy array

description: Detect ordered pair in numpy array


code:
def write_file(filename, toWrite):
  file = open(filename, 'w')
  file.write(toWrite)
  file.close()

rawDescription: Edit text in file in python

description: Edit text in file in python


code: t = s.map(pd.Series(l))

rawDescription: Pandas: Use a series to do list look up

description: Pandas: Use a series to do list look up


code:
from bisect import bisect_left as bs
import datetime
import time
import numpy as np

def foo():
    from re import findall

class Foo():
    def test(self):
        from re import compile as cp, finditer as ft

rawDescription: How to textually find an imported name in a module

description: Textually find an imported name in a module


code:
class SimpleObject:
    def __init__(self, property, propertyChangeObserver = None):
        self.property = property
        self.propertyChangeObserver = propertyChangeObserver

    def registerPropertyChangeObserver(self, propertyChangeObserver):
        self.propertyChangeObserver = propertyChangeObserver

    def update_property(self, value):
        self.property = value
        if self.propertyChangeObserver:
            self.propertyChangeObserver.simpleObjectPropertyChanged(self)

rawDescription: Is it possible to monitor a list (or mutable sequence) for when a member of the list is modified?


code:
mask = df2.iloc[0:2]
frames = [df2, mask]
result = pd.concat(frames)
result.index = range(len(result))
df3 = df1.add(result)
df3['Max'] = df1['Max']
df3

rawDescription: Pandas :Add certain row of a dataframe to a certain row of the other dataframe


code:
vals.index = pd.MultiIndex.from_tuples(vals.index)
vals.head()

rawDescription: Pandas groupby year object plotting it year over year


code:
from scipy.io import loadmat
x = loadmat('c.fig')
x
x['hgS_070000'][0,0].__dict__

rawDescription: Data from a MATLAB .fig file using Python?


code:
import jinja2

def list_replace(a_list,search,replace):
    new_list=[]
    for item in a_list:
        new_list.append(item.replace(search,replace))
    return new_list

templateLoader = jinja2.FileSystemLoader( searchpath="/" )
templateEnv = jinja2.Environment( loader=templateLoader )
templateEnv.filters['list_replace'] = list_replace

rawDescription: jinja2 escape joined character in joinee

description: Jinja2 escape joined character in joinee


code:
#!/usr/bin/env python

# This is a demo/example of how you might do MVC (Passive View) in wxpython.
import sys

import wx

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

from enum import Enum

import logging

import bank_view
import bank_view_separate_frames

#####
#   The control events that the Controller can process
#   Usually this would be in a module imported by each of M, V and C
#   These are the possible values for the "event" parameter of an APP_EVENT message

class AppEvents(Enum):
    APP_EXIT = 0
    APP_ADD_WORKPLACE = 1
    APP_ADD_CUSTOMER = 2
    CUSTOMER_DEPOSIT = 3
    CUSTOMER_WITHDRAWAL = 4
    CUSTOMER_EARN = 5
    PERSON_WORK = 6
    EARN_REVENUE = 7

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

class Controller:
    def __init__(self, view_separate_frames):
        self._log = logging.getLogger("MVC Logger")
        self._log.info("MVC Main Controller: starting...")

        pub.subscribe(self.OnAppEvent, "APP_EVENT")

        if view_separate_frames:
            self._view = bank_view_separate_frames.MainWindow("Demo MVC - Bank Simulator")
        else:
            self._view = bank_view.MainWindow("Demo MVC - Bank Simulator")

        # Note that this controller can conceptually handle many customers and workplaces,
        # even though the current view implementations can't...

        self._customers = []
        self._workplaces = []

        # Here is the place in the controller where we restore the app state from storage,
        # or (as in this case) create from scratch

        self._customers.append(CustomerModel("Fred Nerks"))

        self._bank = BankModel()
        self._bank.CreateAccountFor(self._customers[0])

        self._view.AddBank(self._bank)
        self._view.AddCustomer(self._customers[0])

    def OnAppEvent(self, event, value=None):
        if event == AppEvents.APP_EXIT:
            self._log.info("MVC Controller: exit requested.")
            # do any necessary state saving...
            # ... then:
            sys.exit()
        elif event == AppEvents.APP_ADD_WORKPLACE:
            self._log.info("Main Controller: Add workplace requested...")
            self._workplaces.append(WorkplaceModel("Workplace %d" % (len(self._workplaces)+1) ))
            # Note: here the controller is implementing application business logic driving interactions between models
            new_workplace = self._workplaces[-1]
            for customer in self._customers:
                if customer.AcceptEmployment(new_workplace):
                    new_workplace.AddEmployee(customer)
            self._view.AddWorkplace(new_workplace)

        elif event == AppEvents.CUSTOMER_DEPOSIT:
            (the_customer, the_amount) = value
            self._log.info("customer deposit funds requested(%s)..." % the_customer.name)
            the_customer.DepositFunds(the_amount)
        elif event == AppEvents.CUSTOMER_WITHDRAWAL:
            (the_customer, the_amount) = value
            self._log.info("customer withdraw funds requested(%s)..." % the_customer.name)
            the_customer.WithdrawFunds(the_amount)
        elif event == AppEvents.CUSTOMER_EARN:
            the_customer = value
            self._log.info("customer earn requested(%s)..." % the_customer.name)
            the_customer.Work()

        elif event == AppEvents.PERSON_WORK:
            the_person = value
            self._log.info("request for customer %s to work ..." % customer.name)
            the_person.Work()
        elif event == AppEvents.EARN_REVENUE:
            self._log.info("request for sales revenue payment ...")
            the_workplace = value
            the_workplace.EarnFromSales()
        else:
            raise Exception("Unknown APP_EVENT: %s" % event)

#################
#
#  Models
#

class AccountModel:
    def __init__(self, owner, bank):
        self._balance = 0
        self._owner = owner
        self._bank = bank

    def AddMoney(self, amount):
        self._balance += amount
        self._bank.ReceiveMoney(amount)

    def RemoveMoney(self, amount):
        withdrawal_amount = min(amount, self._balance)  # they can't take out more than their account balance
        pay_amount = self._bank.PayMoney(withdrawal_amount)
        self._balance -= pay_amount
        return pay_amount

class CustomerModel:
    def __init__(self, name):
        self._log = logging.getLogger("MVC Logger")
        self._log.info("Customer %s logging started" % name)
        self.name = name

        self._cash = 0
        self._account = None
        self._employer = None

    def GetAccount(self, account):
        self._account = account

    def CashInHand(self):
        return self._cash

    def AcceptEmployment(self, workplace):
        self._employer = workplace
        self._log.info("%s accepted employment at %s" % (self.name, workplace.name))
        return True

    def Work(self):
        if self._employer:
            self._cash += self._employer.RequestPay(self)
            pub.sendMessage("CUSTOMER_BALANCE_EVENT", value = self)
        else:
            self._log.info("%s cant work, not employed" % self.name)

    def DepositFunds(self, amount):
        deposit_amount = min(amount, self._cash) # can't deposit more than we have
        self._cash -= deposit_amount
        self._account.AddMoney(deposit_amount)
        pub.sendMessage("CUSTOMER_BALANCE_EVENT", value = self)

    def WithdrawFunds(self, amount):
        amount_received = self._account.RemoveMoney(amount)
        self._cash += amount_received
        pub.sendMessage("CUSTOMER_BALANCE_EVENT", value = self)

class BankModel:
    def __init__(self):
        self._funds = 0
        self._accounts = {}

    def Funds(self):
        return self._funds

    def CreateAccountFor(self, owner):
        new_account = AccountModel(owner, self)
        self._accounts[owner.name] = new_account
        owner.GetAccount(new_account)

    def PayMoney(self, amount):
        paid = min(self._funds, amount)
        self._funds -= paid
        pub.sendMessage("BANK_BALANCE_EVENT")
        return paid

    def ReceiveMoney(self, amount):
        self._funds += amount
        pub.sendMessage("BANK_BALANCE_EVENT")

class WorkplaceModel:
    def __init__(self, name):
        self.name = name

        self._employees = []
        self._standardWage = 10

        self._funds = 0
        self._salesRevenue = 20

    def AddEmployee(self, employee):
        self._employees.append(employee)

    def EarnFromSales(self):
        self._funds += self._salesRevenue
        pub.sendMessage("WORKPLACE_BALANCE_EVENT")

    def Funds(self):
        return self._funds

    def RequestPay(self, employee):
        # (should check if employee is legit)
        paid = min(self._funds, self._standardWage)
        self._funds -= paid
        pub.sendMessage("WORKPLACE_BALANCE_EVENT")
        return paid

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

logging.basicConfig(level=logging.INFO)

view_separate_frames = False

if len(sys.argv) > 1:
    if sys.argv[1] == "view-separate-frames":
        view_separate_frames = True

app = wx.App()
controller = Controller(view_separate_frames)
app.MainLoop()

rawDescription: How to keep the controller alive

description: Keep the controller alive


code: a(False) or (b(True),a(False))[0] or (c(True),b(True),a(False))[0]

rawDescription: Pythonic way to "run X before Y if Y fails"?


code: d[sid] += mark

rawDescription: Python CSV - Need to sum up values in a column grouped by value in another column


code: dict(foo={})

rawDescription: Defining a nested dictionary in python

description: Defining a nested dictionary in python


rawDescription: Conditional replacement of multiple columns based on column values in pandas DataFrame


code: print("this is a prime number" if is_prime(2) else "this is not a prime number")

rawDescription: python shorthand method for a if-else based on the function's return

description: Python shorthand method for a if-else based on the function's return


code:
class RSA:
  def __init__(self):
    print("foo")

obj = RSA
obj() is obj()

rawDescription: python calling methods of class using different ways

description: Python calling methods of class using different ways


code:
import sys
writer = csv.writer(sys.stdout)
keys = sorted(all_custom_vals)
for row in results:
    items = [row['ID'], row['STUFF']]
    for key in keys:
        items.append(key)
        items.append(row.get(key, '<no value>'))
    writer.writerow(items)

rawDescription: Convert values in CSV column to individual columns


code:
FatherInlineFormSet = inlineformset_factory(Father,
    Son,
    form=SonInline,
    extra=1,
    can_delete=False,
    can_order=False
)

rawDescription: Multiple Forms and Formsets in CreateView


code:
from yourmodule import MyAPI, filter_timetable

api = MyAPI

filtered_timetable = filter_timetable(api.time_table, something)

rawDescription: Optionally use decorators on class methods


code:
"""
Module `Database` (found in Database.py)
"""
data = []

def connect(self, location=None):
    global data
    path = '.\\resources\\database\\'
    with open(path + 'info.csv', 'rU') as f:
        csv_data = csv.reader(f, delimiter=',')
        for row in csv_data:
            data.append(Entry(*row))
        data = data[1:]

rawDescription: Confusion over how to share and modify class level data between instances.


rawDescription: Counting the Frequency a Value appears in a given "set" within a DF


code:
for _ in range(1,10000):
    with open('/path/to/image.png', 'r') as f:
        Bullet2(YourImage(f.read()))

rawDescription: Python class attributes usage and initialization


code:
L = []
y = list(range(11))
for x in list(range(11)):
    if x % 2 == 0:
        L.append(x)
    else:
        L.append(0)
print(L)

rawDescription: Turning Printed Answers into a List

description: Turning Printed Answers into a List


code:
import pickle
dict = {...}
tcp_send(pickle.dumps(dict))

rawDescription: Python sending dictionary throught TCP

description: Python sending dictionary throught TCP


code:
authentication = AuthPolicy(secret='@#^&*$!DSYUIDSA8321789DS',
                        hashalg='sha512', check=authcheck, debug=True)
authorization = ACLAuthorizationPolicy()

config = Configurator(settings=settings, root_factory=RootFactory,
                  authentication_policy=authentication,
                  authorization_policy=authorization)

rawDescription: Multiple Authhentication Policies in Pyramid


code:
import statsmodels.api as sm
import pandas as pd
import numpy as np

df = pd.DataFrame({
  'y': np.random.randn(20),
  'x1': np.random.randn(20),
  'x2': np.random.randn(20),
  'grp': ['a', 'b'] * 10})

def ols_res(x, y):
    return pd.Series(sm.OLS(y, x).fit().predict())

df.groupby('grp').apply(lambda x : x[['x1', 'x2']].apply(ols_res, y=x['y']))

rawDescription: Python pandas: how to run multiple univariate regression by group


code:
x=int(raw_input()) #Terminal will stall to allow user to input the first number
y=int(raw_input()) #This will wait for the second number to be inputted

rawDescription: Read in text from STDIN Python

description: Read in text from STDIN Python


code: return sys.stdin.readline()       # This is a comment

rawDescription: How do I add text describing the code into a Python source file?

description: Add text describing the code into a Python source file


code:
item_dict = {}
for big_lst in item:
    for lst in big_lst:
        try:
            item_dict[lst[0]] += [lst[1:],] # Append to existing value
        except KeyError:
            item_dict[lst[0]] = [lst[1:],] # Initialize value

rawDescription: Managing big point lists, best approach?

description: Managing big point lists, best approach


code:
from multiprocessing import Pool
from hashlib import sha256
from time import time

def find_solution(args):
    salt, nBytes, nonce_range = args
    target = '0' * nBytes

    for nonce in xrange(nonce_range[0], nonce_range[1]):
        result = sha256(salt + str(nonce)).hexdigest()

        #print('%s %s vs %s' % (result, result[:nBytes], target)); sleep(0.1)

        if result[:nBytes] == target:
            return (nonce, result)

    return None

def proof_of_work(salt, nBytes):
    n_processes = 8
    batch_size = int(2.5e5)
    pool = Pool(n_processes)

    nonce = 0

    while True:
        nonce_ranges = [
            (nonce + i * batch_size, nonce + (i+1) * batch_size)
            for i in range(n_processes)
        ]

        params = [
            (salt, nBytes, nonce_range) for nonce_range in nonce_ranges
        ]

        # Single-process search:
        #solutions = map(find_solution, params)

        # Multi-process search:
        solutions = pool.map(find_solution, params)

        print('Searched %d to %d' % (nonce_ranges[0][0], nonce_ranges[-1][1]-1))

        # Find non-None results
        solutions = filter(None, solutions)

        if solutions:
            return solutions

        nonce += n_processes * batch_size

if __name__ == '__main__':
    start = time()
    solutions = proof_of_work('abc', 6)
    print('\n'.join('%d => %s' % s for s in solutions))
    print('Solution found in %.3f seconds' % (time() - start))

rawDescription: Python stop multiple process when one returns a result?


code:
import sys
import itertools

CHUNK_LENGTH = 200

lines_chunk = itertools.islice(sys.stdin, CHUNK_LENGTH)

rawDescription: How to read fixed chunk of lines (say 100) from stdin in python?

description: Read fixed chunk of lines (say 100) from stdin in python


code: B[X] = A

rawDescription: Efficient way of getting a subarray of an array that the indices are mapped


code: b = np.vstack((a for i in range(3)))

rawDescription: Generating a list of unique numpy arrays


code:
def login(name, password, id):
    # do stuff with name password and id passed into method
    ...

for row in L1:
    login(row)

rawDescription: Help with Excel, Python and XLRD

description: Help with Excel, Python and XLRD


code:
z = np.array([[complex(c.m_x, c.m_y) for c in cells]]) # notice the [[ ... ]]
out = abs(z.T-z)

rawDescription: Efficiently Calculating a Euclidean Distance Matrix Using Numpy


rawDescription: define aggfunc for each values column in pandas pivot table

description: Define aggfunc for each values column in pandas pivot table


code:
import operator
a = range(10)
reduce(operator.add,a) #45
reduce(operator.sub,a) #-45
reduce(operator.mul,a) #0 -- first element is 0.
reduce(operator.div,a) #0 -- first element is 0.

rawDescription: how to "add" things together python

description: "add" things together python


code:
for element in tagall:
    for item in element:
        print(item) #but this doesn't need a comma because they are on separate lines

rawDescription: How to split pyodbc.row into a list of its values

description: Split pyodbc.row into a list of its values


rawDescription: Python 3: Why are my while loops exiting?


code:
import math
x1,y1 = obj.pos
x2,y2 = obj.lastpos

x = x2 - x1
y = y2 - y1

angle = math.degrees(math.atan2(y,x))
if angle < 0:  angle += 360
print(angle)
#now you have the angle from it was heading

rawDescription: Directional collisions in PyGame?

description: Directional collisions in PyGame


code:
MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'sessions.middleware.HandleSessionExpiryMiddleware',
    ...
)

rawDescription: How to track the length of a user session in Django

description: Track the length of a user session in Django


rawDescription: Solving a task in cosmology using Python 2.7.5


code:
def get_df(path):
    allfiles = glob.glob(path + "/*.csv")
    result = list(itertools.product(allfiles,allfiles))
    #
    dataframe=[]
    for files in result:
        x=(pd.read_csv(files[0], names = ['Percent', 'Value']))
        z=x.Percent
        y=(pd.read_csv(files[1], names = ['Percent', 'Value']))
        d=y.Percent
        stats2=sp.stats.ks_2samp(z,d)
        g=files, stats2
        df=pd.DataFrame(data=list(sum(g, ())), index=['File1', 'File2', 'D', 'p_value']).transpose()
        dataframe.append(df)
    return pd.concat(dataframe)

rawDescription: Function which changes strings of filenames based on a list


code:
import inspect
import datetime

inspect.getmodule(datetime).__name__

rawDescription: How to get a dot notation of a python module?

description: Get a dot notation of a python module


code:
@property
def prop(self):
    return self._prop
@prop.setter
def prop(self, value):
    self._prop = value

rawDescription: Future Development in Python 2.4

description: Future Development in Python 2.4


code:
data = [
    'Option A',
    'Option B',
    'Blabla',
    'Some text'
]
idata = list(enumerate(data))  # add indexes to uniquely identify items
sdata = sorted(idata, key=lambda x: x[1])  # sort the items by label
flt_neworder = [sdata.index(x) for x in idata]  # find the position to move to

rawDescription: Order mapping - more efficient Python solution for sorting?


code:
x = var('x')
y = var('y')
c = var('c')
ysol = (ln(x)+c)/x
show(ysol)
p1 = plot_slope_field( -y/x+1/(x*x), (x,0,5), (y,-5,5))

for i in range(-5,5):
    p1 = p1 + plot(ysol(c=i),x,0,5, ymin=-5, ymax=5)
p1

rawDescription: Sage plot slope field and differential equation


code:
from functools import partial
import tkinter
import tkinter.messagebox

class LatConvGUI(tkinter.Tk):

    def __init__(self):
        super().__init__()

        self.top_frame = tkinter.Frame(self)
        self.bottom_frame = tkinter.Frame(self)

        self.prompt_label = tkinter.Label(self.top_frame,
                                          text='English Translation is:')
        self.prompt_label.pack(side='left')

        self.label1 = tkinter.Label(self.top_frame, text='')
        self.label1.pack(side='top')

        self.label2 = tkinter.Label(self.bottom_frame,
                                    text='Latin word is:')
        self.label2.pack(side='left')

        self.sin_button = tkinter.Button(self.bottom_frame,
                                         text='sinister',
                                         command=partial(self.label1.config,
                                                         text='left'))
        self.sin_button.pack(side='left')

        self.top_frame.pack()
        self.bottom_frame.pack()

eng_conv = LatConvGUI()
eng_conv.mainloop()

rawDescription: Python 3 Latin to English simple gui button translator


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

x = np.random.uniform(-100, 100, 1000)
plt.hist(x, bins=30)
plt.xlim(-500, 500)
plt.show()

rawDescription: matplotlib hist() autocropping range

description: Matplotlib hist() autocropping range


code:
START = time.time()
def remaining_time(a, b):
    if START:
        y = (time.time() - START)
        z = ((a * y) / b) - y
        d = time.strftime('%H:%M:%S', time.gmtime(z))
        e = round(b / y)
        progress("{0}/{1} | Tiempo restante {2} ({3}p/s)".format(b, a, d, e), b, a)

def progress(p, c, t):
    pc = (c * 100) / t
    sys.stdout.write("%s [%-20s] %d%%\r" % (p, '█' * (pc / 5), pc))
    sys.stdout.flush()

def dowork(args):
    p, i, pcount  = args
    remaining_time(pcount, i)

def main():
    queue = multiprocessing.Queue()

    procs = [multiprocessing.Process(target=dowork, args=(queue,)) for _ in range(CONFIG_POOL_SIZE)]
    pool = multiprocessing.Pool(CONFIG_POOL_SIZE)
    mongo_query = {}
    products = MONGO.mydb.items.find(mongo_query, no_cursor_timeout=True)
    pcount = products.count()
    pool.map(dowork, ((p, idx, pcount) for idx,p in enumerate(products)))
    pool.close()
    pool.join()

rawDescription: Python MongoDB (PyMongo) Mutliprocessing cursor


code: save_single_frame(fig, ims, 5)  # this should save the animation for you

rawDescription: Matplotlib save individual "ims" (animation parts) as image


code:
class Monster(object):
    monsters = []

@registered_monster
class Lochness(Monster):
    pass

@registered_monster
class Yeti(Monster):
    pass

Monster.monsters

rawDescription: Executing code after construction of class object


code:
import os
# this will remove the dir path in the filename
# so that `../../../etc/passwd` will become `passwd`
filename = os.path.basename(filename)

rawDescription: How to grab the output from python subprocess

description: Grab the output from python subprocess


code:
df = df.resample('MS').fillna(0)
df

rawDescription: Appending missing values in list of dictionaries


rawDescription: Combined diacritics do not normalize with unicodedata.normalize (PYTHON)


code:
txt = b" 39, State-gov, 77516, Bachelors, 13, Never-married, Adm-clerical, Not-in-family, White, Male, 2174, 0, 40, United-States, <=50K"
txt = [txt for _ in range(5)]
txt

rawDescription: 2D Numpy Array of Strings WITH column access


code:
def double(lst):
    for i, x in enumerate(lst):
        x *= 2
        print("x = %s" % x)
        print("lst[%d] = %s" % (i, lst[i]))

rawDescription: How to double all the values in a list

description: Double all the values in a list


code:
def find_intersect_vec(x_down, y_down, x_up, y_up):
    p = np.column_stack((x_down, y_down))
    q = np.column_stack((x_up, y_up))
    p0, p1, q0, q1 = p[:-1], p[1:], q[:-1], q[1:]
    rhs = q0 - p0[:, np.newaxis, :]
    mat = np.empty((len(p0), len(q0), 2, 2))
    mat[..., 0] = (p1 - p0)[:, np.newaxis]
    mat[..., 1] = q0 - q1
    mat_inv = -mat.copy()
    mat_inv[..., 0, 0] = mat[..., 1, 1]
    mat_inv[..., 1, 1] = mat[..., 0, 0]
    det = mat[..., 0, 0] * mat[..., 1, 1] - mat[..., 0, 1] * mat[..., 1, 0]
    mat_inv /= det[..., np.newaxis, np.newaxis]
    import numpy.core.umath_tests as ut
    params = ut.matrix_multiply(mat_inv, rhs[..., np.newaxis])
    intersection = np.all((params >= 0) & (params <= 1), axis=(-1, -2))
    p0_s = params[intersection, 0, :] * mat[intersection, :, 0]
    return p0_s + p0[np.where(intersection)[0]]

rawDescription: FInd all intersections of xy data point graph with numpy?


code:
import gc
from types import FunctionType
def a(): pass

code = a.__code__
[obj for  obj in  gc.get_referrers(code) if isinstance(obj, FunctionType)  ][0]

rawDescription: Getting the Python function for a code object


code:
def rename_code_object(func, new_name):
    code_object = func.__code__
    function, code = type(func), type(code_object)
    return function(
        code(
            code_object.co_argcount, code_object.co_nlocals,
            code_object.co_stacksize, code_object.co_flags,
            code_object.co_code, code_object.co_consts,
            code_object.co_names, code_object.co_varnames,
            code_object.co_filename, new_name,
            code_object.co_firstlineno, code_object.co_lnotab,
            code_object.co_freevars, code_object.co_cellvars),
        func.__globals__, new_name, func.__defaults__, func.__closure__)

rawDescription: Changing the __name__ of a generator

description: Changing the __name__ of a generator


code:
class Base(object):
    # This is an abstract class

    # This is the method child classes need to implement
    def implement_me(self):
        raise NotImplementedError("told you so!")

rawDescription: What is the difference between Abstract classes and Mixins in Python django


code:
class foo():
    pass
x = foo()
# Define a function and attach it
def bar(self, a):
    print(a)
foo.bar = bar
x.bar('a')

rawDescription: How can I extend a class instance?

description: Extend a class instance


code:
from flask.ext.admin.contrib.sqla import ModelView
from flask.ext.admin.form.upload import FileUploadField
from wtforms.validators import ValidationError
from flask.ext.admin import Admin
from flask.ext.sqlalchemy import SQLAlchemy
from flask import Flask
import imghdr

app = Flask(__name__)
db = SQLAlchemy(app)

class UserAdminView(ModelView):

   def picture_validation(form, field):
      if field.data:
         filename = field.data.filename
         if filename[-4:] != '.jpg':
            raise ValidationError('file must be .jpg')
         if imghdr.what(field.data) != 'jpeg':
            raise ValidationError('file must be a valid jpeg image.')
      field.data = field.data.stream.read()
      return True

   form_columns = ['id','url_pic', 'pic']
   column_labels = dict(id='ID', url_pic="Picture's URL", pic='Picture')

   def pic_formatter(view, context, model, name):
       return 'NULL' if len(getattr(model, name)) == 0 else 'a picture'

   column_formatters =  dict(pic=pic_formatter)
   form_overrides = dict(pic= FileUploadField)
   form_args = dict(pic=dict(validators=[picture_validation]))

admin = Admin(app)
admin.add_view(UserAdminView(User, db.session, category='Database Administration'))
...

rawDescription: Flask-Admin upload and insert in database automatically


code:
def get(d, keys):
    return reduce(lambda d, key: d[key], keys, d)

rawDescription: How to dynamically move inside a nested dict in Python

description: Dynamically move inside a nested dict in Python


rawDescription: Python 3.x Shifting Ranges

description: Python 3.x Shifting Ranges


code:
idx = grp['Payment_Date'].searchsorted(grp['Order_Date'])
result = grp['Payment_Date'].iloc[idx-1]

rawDescription: Finding the closest date given a date in a groupby dataframe (Python)


code: wl = sorted(random.sample(alphabet, 20))

rawDescription: Why is my implementation of binary search very inefficient?


code:
with open('filename.txt', 'r') as handle:
    parsed = json.load(handle)

rawDescription: How to Python prettyprint a JSON file

description: Python prettyprint a JSON file


rawDescription: Ndb default order does not preserve insertion order


code:
import re
re.findall('Name:\s+([^,]*)', s)

rawDescription: Regex extract element after string

description: Regex extract element after string


rawDescription: find the set of integers for which two linear equalities holds true

description: Find the set of integers for which two linear equalities holds true


code:
from datetime import datetime
date_string = 'Fri, 31 Oct 2014 01:51:22 +0000'
format_string = '%a, %d %b %Y %I:%M:%S %z'
date_object = datetime.strptime(date_string, format_string)
date_object
date_object.strftime("%d-%m-%Y")

rawDescription: Converting string containing complex date value to a date, with Python


code:
def argmax(**kw):
    wk = {v:k for k,v in kw.items()}
    return wk[max(wk)]

argmax(foo=3, bar=5, frotz=1, kaka=-3)

rawDescription: Create function in python to find the highest of all function arguments, and return the "tag" of the value


rawDescription: How to create rolling percentage for groupby DataFrame

description: Create rolling percentage for groupby DataFrame


code:
from collections import defaultdict
by_column = defaultdict(list)

for row in rows:
   for k,v in row.iteritems():
       by_column[k].append(v)

rawDescription: Storing each column in a separate dictionary using python


code:
menu = wx.Menu()
item_id = 1

# Ctrl+T is bound to the keybinding
accelerator_table = wx.AcceleratorTable([(wx.ACCEL_CTRL, ord('T'), item_id)])
self.setAcceleratorTable(accelerator_table)

# Ctrl+T is not included, but the menu item can be accessed via Alt key
item_name = '&My menu item'

help_text = 'Clicking this does something interesting.'
item = menu.Append(item_id, item_name, help_text)

rawDescription: wxPython menu text alignment

description: WxPython menu text alignment


code: dictionary = set(dictionary.values())

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


rawDescription: Annotating dimensions in matplotlib

description: Annotating dimensions in matplotlib


code:
import pandas as pd

df = pd.DataFrame({'A':[1,2,3],
                   'B1':[4,5,6],
                   'B2':[7,8,9],
                   'B3':[1,3,5],
                   'C':[5,3,6],
                   'D':[7,4,3]})

print (df)
df = pd.concat([df]*10000).reset_index(drop=True)
df1 = df.copy()

def a(df):
    cols = df.columns[df.columns.str.contains('B')]
    df[cols] = df[cols].mul(df.A, axis = 0)
    return (df)

def b(df):
    df.loc[:, df.filter(regex=r'^B').columns] = df.loc[:, df.filter(regex=r'^B').columns].mul(df.A, axis=0)
    return (df)

print (a(df))
print (b(df1))

rawDescription: Replace certain column with `filter(like = "")` in Pandas


rawDescription: reshaping a data frame in pandas

description: Reshaping a data frame in pandas


code:
def get_cnt(expr):
    ops = '+-*/'
    res = [expr]
    for op in ops:
        tmp = []
        for x in expr:
            tmp.extend(x.split(op))
        res = tmp[:]
    return len(res), sum(expr.count(op) for op in ops)

rawDescription: How to find the operand and the operation in a string

description: Find the operand and the operation in a string


rawDescription: python variable length values in dictionary

description: Python variable length values in dictionary


code:
def Collection_is_cheap(C, price):
    result = []
    for rest in C:
        for dish in rest.menu:
            if dish.price <= price:
                result.append(rest)
                break  # stop the rest.menu loop, go to the next
    return result

rawDescription: Iterating over list of namedtuples, selecting restaurants


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

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


code:
from .module1 import Class11, Class12
from .module2 import Class21, function21

rawDescription: Python - Can I import specific classes when importing all from a package


rawDescription: How can I return the last element that fits under the criteria for driver.find_element_by_partial_link_text?

description: Return the last element that fits under the criteria for driver.find_element_by_partial_link_text


code:
re.sub("(this)(.*)(string)",
       r'<markup>\1</markup>\2<markup>\3</markup>',
       text)

rawDescription: replacing all regex matches in single line

description: Replacing all regex matches in single line


rawDescription: Selecting One String from data list in Python


code:
from collections import defaultdict
def default():
    return []

appointments = defaultdict(default)

rawDescription: Need to add appointments into empty dictionary


code:
def xyz_there(s):
    return s.count('xyz') - s.count('.xyz') > 0

rawDescription: Find if char precedes substring

description: Find if char precedes substring


code:
s = row[1].upper()
if s in name_to_abbr:
    row[2] = name_to_abbr[s]

rawDescription: Translating State Names in Python

description: Translating State Names in Python


code: product = remove_keys(product, set(['_event', 'length']))

rawDescription: How to recursively remove certain keys from a multi-dimensional(depth not known) python dictionary?

description: Recursively remove certain keys from a multi-dimensional(depth not known) python dictionary


code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np

X = np.linspace(-np.pi, np.pi, 200, endpoint=True)
Y = np.linspace(-np.pi, np.pi, 200, endpoint=True)
XX, YY = np.meshgrid(X,Y)
Z = np.cos(XX)*np.cos(YY)

fig = plt.figure()
ax1 = plt.subplot2grid((1,2), (0,0), projection='3d')
ax2 = plt.subplot2grid((1,2), (0,1), projection='3d')
surf = ax1.plot_surface(XX, YY, Z,
                        cmap=plt.cm.Set2)
surf2 = ax2.plot_surface(XX, YY, Z, shade=False,
                         facecolors=plt.cm.Set2((XX-XX.min())/(XX.max()-XX.min()))
                         )

rawDescription: Applying colormaps to custom axis in Matplotlib 3D surface


code:
import numpy as np
from PIL import Image

def bradley_roth_numpy(image, s=None, t=None):

    # Convert image to numpy array
    img = np.array(image).astype(np.float)

    # Default window size is round(cols/8)
    if s is None:
        s = np.round(img.shape[1]/8)

    # Default threshold is 15% of the total
    # area in the window
    if t is None:
        t = 15.0

    # Compute integral image
    intImage = np.cumsum(np.cumsum(img, axis=1), axis=0)

    # Define grid of points
    (rows,cols) = img.shape[:2]
    (X,Y) = np.meshgrid(np.arange(cols), np.arange(rows))

    # Make into 1D grid of coordinates for easier access
    X = X.ravel()
    Y = Y.ravel()

    # Ensure s is even so that we are able to index into the image
    # properly
    s = s + np.mod(s,2)

    # Access the four corners of each neighbourhood
    x1 = X - s/2
    x2 = X + s/2
    y1 = Y - s/2
    y2 = Y + s/2

    # Ensure no coordinates are out of bounds
    x1[x1 < 0] = 0
    x2[x2 >= cols] = cols-1
    y1[y1 < 0] = 0
    y2[y2 >= rows] = rows-1

    # Count how many pixels are in each neighbourhood
    count = (x2 - x1) * (y2 - y1)

    # Compute the row and column coordinates to access
    # each corner of the neighbourhood for the integral image
    f1_x = x2
    f1_y = y2
    f2_x = x2
    f2_y = y1 - 1
    f2_y[f2_y < 0] = 0
    f3_x = x1-1
    f3_x[f3_x < 0] = 0
    f3_y = y2
    f4_x = f3_x
    f4_y = f2_y

    # Compute areas of each window
    sums = intImage[f1_y, f1_x] - intImage[f2_y, f2_x] - intImage[f3_y, f3_x] + intImage[f4_y, f4_x]

    # Compute thresholded image and reshape into a 2D grid
    out = np.ones(rows*cols, dtype=np.bool)
    out[img.ravel()*count <= sums*(100.0 - t)/100.0] = False

    # Also convert back to uint8
    out = 255*np.reshape(out, (rows, cols)).astype(np.uint8)

    # Return PIL image back to user
    return Image.fromarray(out)

if __name__ == '__main__':
    img = Image.open('test.jpg').convert('L')
    out = bradley_roth_numpy(img)
    out.show()
    out.save('output.jpg')

rawDescription: Bradley-Roth Adaptive Thresholding Algorithm - How do I get better performance?


code:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.dir", '/path/to/downloads/')
fp.set_preference("browser.download.downloadDir", '/path/to/downloads/')
fp.set_preference("browser.download.defaultFolder", '/path/to/downloads/')
fp.set_preference("browser.helperApps.neverAsk.openFile", "CONTENT-TYPE")
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","CONTENT-TYPE")

rawDescription: Working with dialog box to download file from a site in python


rawDescription: Pandas describe() behaviour for numeric dtypes


rawDescription: How to evaluate line of data in python

description: Evaluate line of data in python


code: pattern = re.compile(re.escape(motif))

rawDescription: Convert user input strings to raw string literal to construct regular expression


code: dir(obj)

rawDescription: Iterate over object attributes in python


code:
import fileinput
for line in fileinput.input(["in.txt","amended.txt"]): # list of file names  as strings
    print (line)

rawDescription: argument type of fileinput.input() in python

description: Argument type of fileinput.input() in python


code:
import lxml.etree as etree

xml = etree.Element('presentation')
format_xml = etree.SubElement(xml, 'format')
content_xml = etree.SubElement(xml, 'slides')
new = """<slide1>
    <title>My Presentation</title>
    <subtitle>A sample presentation</subtitle>
    <phrase>Some sample text
        <subphrase>Some more text</subphrase>
    </phrase>
</slide1>"""

content_xml.append(etree.fromstring(new))

print(etree.tostring(xml,pretty_print=1))

rawDescription: Using lxml to add a string as a sub element


rawDescription: Python Pandas - Remove values from first dataframe if not in second dataframe


code:
source = Phonon.MediaSource("test.ogg")
output = Phonon.AudioOutput(Phonon.MusicCategory)
media = Phonon.MediaObject()
media.setCurrentSource(source)
Phonon.createPath(media, output)
media.play()

rawDescription: PyQt Phonon Audio Player

description: PyQt Phonon Audio Player


code:
from itertools import izip

def pairwise(t):
    it = iter(t)
    return izip(it,it)

# for "pairs" of any length
def chunkwise(t, size=2):
    it = iter(t)
    return izip(*[it]*size)

rawDescription: Pairs from single list

description: Pairs from single list


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import os.path

def rm(filename):
    if os.path.isfile(filename):
        os.remove(filename)

rawDescription: Stubbing vs Mocking in Python

description: Stubbing vs Mocking in Python


code:
@window.event
def on_draw():
        window.clear()
        label.draw()
        window.flip()

rawDescription: Pyglet hello world example doesn't show label until a key is pressed


rawDescription: Assertion error failing - can't find a reason - Norvig Sudoku


rawDescription: sorting a list of two columns based on one column python

description: Sorting a list of two columns based on one column python


code:
it = ((x, x**2) for x in range(20))
import itertools
y = np.fromiter(itertools.chain.from_iterable(it), dtype=float)
y
y, y2 = y[::2], y[1::2]
y
y2

rawDescription: Numpy create two arrays using fromiter simultaneously


rawDescription: Intersection of variable number of lists


rawDescription: Method to convert object from class to subclass in Python


rawDescription: Python 2.7 Tkinter classes

description: Python 2.7 Tkinter classes


rawDescription: How to make a Structured Array from multiple simple array

description: Make a Structured Array from multiple simple array


code:
import sys
sys.getsizeof({'number_of_legs': 4, 'favourite_food': ['Lasagna', 'Fish']})
from collections import namedtuple
Animal = namedtuple('Animal', 'number_of_legs favourite_food')
sys.getsizeof(Animal(4, ['Lasagna', 'Fish']))

rawDescription: Grouping constants in python

description: Grouping constants in python


code:
grade_titles = ['pre-k', 'k', '1', '2', '3', '4', '5', '6', '7', '8']
gallery_list = []
for grade_title in grade_titles:
    grade = GradeLevel.objects.prefetch_related().get(title=grade_title)
    grade_categories = grade_pk.grade_cats.filter(active=True,featured=True)
    grade_galleries = grade_pk.grade_curriculum.filter(active=True,featured=True)
    gallery_list.extend(grade_categories)
    gallery_list.extend(grade_galleries)
gallery_list = list(sorted(frozenset(gallery_list), key=attrgetter('display_order')))

rawDescription: Django Query Optimization - Using Itertools


code: sum((node.sons.values() for node in current_nodes), [])

rawDescription: How to propagate tree nodes in Python

description: Propagate tree nodes in Python


code:
class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        try:
            while True:
                self._fetch_data()
                time.sleep(10)
        except KeyboardInterrupt:
            pass

    def _fetch_data(self):
        data = ... # fetch data here
        MyModel.objects.create(foo=data.foo, bar=data.bar) # insert into db

rawDescription: long runner to regularly update Django DB with web harvested data -?

description: Long runner to regularly update Django DB with web harvested data -


code: z

rawDescription: How to do operations with two vectors of different format in python

description: Do operations with two vectors of different format in python


code:
'Hello world!  This\tis\t         awesome!'.split()
len('Hello world!  This\tis\t         awesome!'.split())

rawDescription: Count the number of words in a string

description: Count the number of words in a string


code:
import wx
import os
#import pandas as pd
#import numpy as np
#import matplotlib.pyplot as ply
#from scipy.stats import linregress

class MyFileDropTarget(wx.FileDropTarget):

    #----------------------------------------------------------------------
    def __init__(self, obj):
        wx.FileDropTarget.__init__(self)
        self.obj = obj

    #----------------------------------------------------------------------
    def OnDropFiles(self, x, y, filenames):
        #self.obj.SetInsertionPointEnd(y)
        #self.obj.WriteText("\n%d file(s) dropped at %d,%d:\n" %
        #                   (len(filenames), x, y))
        for filepath in filenames:
            self.obj.WriteText(filepath + '\n')

class MyPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        #Create some sizers
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        grid = wx.GridBagSizer(hgap=5, vgap=5)
        hSizer = wx.BoxSizer(wx.HORIZONTAL)

        #Create a button
        self.button = wx.Button(self, label="Test")
        #self.Bind(wx.EVT_BUTTON, self.OnClick,self.button)

        # Radio Boxes
        sysList = ['QEXL','QEX10','QEX7']
        wlList = ['1100', '1400', '1800']
        sys = wx.RadioBox(self, label="What system are you calibrating ?",
                        pos=(20, 40), choices=sysList,  majorDimension=3,
                        style=wx.RA_SPECIFY_COLS)
        grid.Add(sys, pos=(1,0), span=(1,3))

        WL = wx.RadioBox(self, label="Maximum WL you currently Calibrating ?",
                        pos=(20, 100), choices=wlList,  majorDimension=0,
                        style=wx.RA_SPECIFY_COLS)
        grid.Add(WL, pos=(2,0), span=(1,3))

        x = 3
        for widget in range(1, 4):
            lbl = wx.StaticText(self, label="Cal File {} :".format(widget))
            grid.Add(lbl, pos=(x,0))
            txt = wx.TextCtrl(self, name="Cal_{}".format(widget),
                                     value="", size=(240,-1))
            dt = MyFileDropTarget(txt)
            txt.SetDropTarget(dt)
            grid.Add(txt, pos=(x,1))
            x += 1

        hSizer.Add(grid, 0, wx.ALL, 5)

        mainSizer.Add(hSizer, 0, wx.ALL, 5)
        mainSizer.Add(self.button, 0, wx.CENTER)
        self.SetSizer(mainSizer)

class MainWindow(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title, size=(400,400))
        panel = MyPanel(self)

        self.CreateStatusBar() # A Statusbar in the bottom of the window

        # Creating the menubar.
        menubar = wx.MenuBar()
        fileMenu = wx.Menu()
        helpMenu = wx.Menu()

        menubar.Append(fileMenu, '&File')
        menuOpen = fileMenu.Append(wx.ID_OPEN, "&Open"," Open a file to edit")
        #self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
        fileMenu.AppendSeparator()
        menuExit = fileMenu.Append(wx.ID_EXIT,"E&xit"," Terminate the program")
        self.Bind(wx.EVT_MENU, self.OnExit, menuExit)

        menubar.Append(helpMenu, '&Help')
        menuAbout= helpMenu.Append(wx.ID_ABOUT, "&About",
                                " Information about this program")
        self.Bind(wx.EVT_MENU, self.OnAbout, menuAbout)

        self.SetMenuBar(menubar)

        self.Show(True)

    def OnAbout(self,e):
        # A message dialog box with an OK button. wx.OK is a standard ID in wxWidgets.
        dlg = wx.MessageDialog( self, "A quick test to see if your scans pass repeatability", "DOMA-64 Tester", wx.OK)
        dlg.ShowModal() # Show it
        dlg.Destroy() # finally destroy it when finished.

    def OnExit(self,e):
        # Close the frame.
        #del self.fdt
        self.Close(True)

app = wx.App(False)
frame = MainWindow(None, "Sample editor")
app.MainLoop()

rawDescription: unable to quit wxpython

description: Unable to quit wxpython


code:
[
    {
        'name': 'Folder 1',
        'id': 'OY00',
        'type': 'folder',
        'children': [
            {
                'name': 'Folder 2',
                'id': 'zRDg',
                'parent': 'OY00',
                'type': 'folder'
            },
            {
                'name': 'DX00025.jpg',
                'id': '9Xdd',
                'parent': 'OY00',
                'type': 'jpeg'
            }
        ]
    },
    {
        'name': 'Folder 3',
        'id': 'ZDE1',
        'type': 'folder'
    }
 ]

rawDescription: Sorting JSON object(s) into a Hierarchy

description: Sorting JSON object(s) into a Hierarchy


code: new_list = [[i for i in l if i not in list_A] for l in list_of_list]

rawDescription: Delete all occurrences of specific values from list of lists python


code: [h, f] = freqz(b, a, n, fs)

rawDescription: Matlab freqz function in Python

description: Matlab freqz function in Python


code:
import itertools
def matches(d, target):
    # First try single items, then couples, then triplets etc.
    for num in range(1,len(d)+1):
        # Iterate over all possible combinations of length num
        for com in itertools.combinations(d.items(), num):
            # Does the sum of all second items per key/value pair match the target?
            if sum(item[1] for item in com) == target:
                # Yield one item at a time, so the caller can decide when to stop
                yield com

rawDescription: How to sort through keys in a dictionary, adding the values and returning a list of keys if combined values equal a certain number

description: Sort through keys in a dictionary, adding the values and returning a list of keys if combined values equal a certain number


code: df["signal"] == "S"

rawDescription: List Comprehension Loop

description: List Comprehension Loop


code:
from itertools import cycle
list1 = ['a','b','c']
list2 = ['1','2','3','4','5']
zip(list2, cycle(list1))

rawDescription: Cyclic combination of two list of different length


code:
import __builtin__
dir(__builtin__)

rawDescription: Is the list of Python reserved words and builtins available in a library?


rawDescription: How to stack arrays and scalars in numpy?

description: Stack arrays and scalars in numpy


rawDescription: Python: How to import 2.7 module into 3.4 program?


rawDescription: inequality comparison of numpy array with nan to a scalar

description: Inequality comparison of numpy array with nan to a scalar


code:
d = {"foo":0, "spam":0}
test = "This is a string with many words, including foo and bar"
any(word in d for word in test.split())

rawDescription: Python regex for something *not* in a dictionary?


code: goblin["health"] -= player["attack"]()

rawDescription: I want to turn the string "random.randint(2,4), into an integer


code:
First: 'First'
Middle: 'Middle'
Last: 'Last'
First: 'M First'
Middle: 'Middle'
Last: 'Last'
First: 'First'
Middle: 'Shk Middle'
Last: 'Last'
First: 'BS First'
Middle: 'M Middle'
Last: 'Last'

rawDescription: Separate first, middle and last names (Python)


rawDescription: how to read numpy 2D array from string?

description: Read numpy 2D array from string


code:
import re
s = "MARKDOWN: [This link](http://example.net/)"
m = re.sub(r'\[([^]]*)\]\((.*?)\/\)', r'[link=\2]\1[/link]', s)
m

rawDescription: Transform part of string in Python

description: Transform part of string in Python


code:
#!/usr/bin/env python3
# coding: utf-8

from bs4 import BeautifulSoup

html = '
text1 foo bar text2 foobar baz
'
soup = BeautifulSoup(html, 'html.parser')

result = soup.getText().replace(soup.em.getText(), '').lstrip()

print(result)

rawDescription: How to grab item outside of tag using python+beautifulsoup

description: Grab item outside of tag using python+beautifulsoup


code: df['max_a'] - df['min_b']

rawDescription: Calculating averages of 15 records ahead of the current record as a new column


code:
import re
pattern = re.compile(r'\s*%s\s*' % 'USB 2 ports')
result = soup.find(text=pattern)

rawDescription: How to find a string in a HTML document, ignoring whitespace?

description: Find a string in a HTML document, ignoring whitespace


code: starts = np.where(y == 'B')[0]

rawDescription: Longest prefix of array equal to a value


code:
from string import punctuation
a="what is. your. name? It's good"
a.translate(None, punctuation)

rawDescription: replace punctuation with nothing

description: Replace punctuation with nothing


code: reader = CategorizedPlaintextCorpusReader('~/MainFolder/', r'.*\.txt', cat_pattern=r'[0-100]_(\w+)\.txt')

rawDescription: Creating a custom categorized corpus in NLTK and Python


code:
import pandas as pd
import matplotlib.pyplot as plt
url = "https://www.revisor.mn.gov/laws/?year=2014&type=0&doctype=Chapter&id=294"

#read second table in url
df = pd.read_html(url)[1]
#replace texts to empty string
df = df.replace('new text begin','', regex=True).replace('new text end','', regex=True)
#set new columns names
df.columns = ['Source','b','Amount']
#remove first row
df = df[1:]
#remove second column b
df = df.drop('b', axis=1)
#strip whitespaces
df.Source = df.Source.str.strip()
#strip whitespaces and remove (),
df.Amount = df.Amount.str.strip().str.replace(r'[(),]','')
#convert column Amount to numeric
df.Amount = pd.to_numeric(df.Amount)
#reset index
df = df.reset_index(drop=True)

rawDescription: Python 3.x - Create dataframe and specify column names


code:
from .models import SomeAwesomeModel
from django import forms

class SomeAwesomeModelForm(ModelForm):
    class Meta:
        model=SomeAawesomeModel
        fields=['myfield']

rawDescription: Multiselect dropdown/list in django admin panel only


code:
#custom.middleware.py
try:
    from threading import local
except ImportError:
    from django.utils._threading_local import local

_thread_locals = local()

def get_current_request():
    return getattr(_thread_locals, 'request', None)

class RequestMiddleware():
    def process_request(self, request):
        _thread_locals.request = request

rawDescription: Dynamically serve static content based on server name in Django


code:
import sys
import string
from PyQt5 import QtWidgets, QtCore

class Window(QtWidgets.QDialog):
    def __init__(self):
        super().__init__()
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        self.letters = list(string.ascii_lowercase)

        self.lay = QtWidgets.QVBoxLayout(self)
        self.group = QtWidgets.QButtonGroup()

        # Create all the buttons
        for letter in self.letters:
            btn = QtWidgets.QRadioButton(letter, self)
            # In case you want to find it back later using findChild
            btn.setObjectName("btn_"+letter)
            self.group.addButton(btn)
            self.lay.addWidget(btn)

        self.group.buttonClicked.connect(self.btnCliked)

    def btnCliked(self, btn):
        # Do something with the button
        print(btn.text())

def main():
    qApp = QtWidgets.QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(qApp.exec_())

if __name__ == '__main__':
    main()

rawDescription: how do I create check box or radio button in python?

description: Create check box or radio button in python


code:
import yaml

yaml_str = """\
!!python/object:try.Settings
annual_volatility_target: 0.25
"""

class Settings:
    def __init__(self, annual_volatility_target):
        self.__setstate__({annual_volatility_target: annual_volatility_target})

    def __setstate__(self, kw):
        self.annual_volatility_target = kw.get('annual_volatility_target')
        self.daily = self.annual_volatility_target/np.sqrt(252)

    def __repr__(self):
        return "Setting({}, {})".format(self.annual_volatility_target, self.daily)

settings = yaml.load(yaml_str)

print(settings)

rawDescription: YAML parsing to Objects (PyYAML Python3)


code:
import unittest

data = [
    (2, True),
    (3, False),
    (4, True),
    (5, False)]

# this should be imported from a separate module.
def isEven(number):
    return True # quite buggy implementation

def create_test_func(num, expected):
    def _test_func(self):
        self.assertEqual(expected, isEven(num))
    return _test_func

class TestIsEven(unittest.TestCase):

    pass

# pyunit isn't pythonic enought use py.test instead
# till then we rely on such hackery
import new
for i, (num, expected) in enumerate(data):
    setattr(TestIsEven, 'test_data_%d'%i, create_test_func(num, expected))

if __name__ == "__main__":
    unittest.main()

rawDescription: Providing test data in python

description: Providing test data in python


rawDescription: Applying custom function while grouping returns NaN


code: ['MAIN', 'SUB1', 'SUBSUB1', 'NAME1', 'NAME2', 'SUBSUB2', 'SUBSUB3']

rawDescription: Extract the object names from different nesting levels in JSON


code:
menu = wx.Menu()
ID_PRG_NFO = wx.NewId()
m_about = menu.Append(ID_PRG_NFO, "Program &Info\tAlt-I", "Information about this     program")

rawDescription: Using wxPython Menus, ID: What does it mean and Which should I use for X?


code: __all__ = ['irange', 'ixrange']

rawDescription: Is it OK to re-use the names of Python's built-in functions?


code:
plural_forms = {'wolf': 'wolves', 'dog': 'dogs', 'cat': 'cats', 'cow': 'cows', 'pig': 'pigs'}
pluralize = plural_forms.get
input_list = ["wolf","dog","cat","cow","pig"]
[word for data in input_list for word in (pluralize(data), data)]

rawDescription: Python - List comprehension how to insert 2 elements at a time?


code:
loop = asyncio.get_event_loop()
with timeit(loop=loop):
    coro = asyncio.sleep(1, result=3)
    result = loop.run_until_complete(coro)
    print("Result: {}".format(result))

rawDescription: How to measure Python's asyncio code performance?

description: Measure Python's asyncio code performance


code:
from access import countries

def whichcolour(country, countries):
    print('{} has the color {}'.format(country, countries[country][0]))

for country in countries:
    whichcolour(country, countries)

rawDescription: How to return a list of items from a different py file

description: Return a list of items from a different py file


code: from __builtin__ import len

rawDescription: Using function names as variables in python


code:
class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        ...
        self._pixmap = QtGui.QPixmap(self.label.pixmap())
        self.label.installEventFilter(self)

    def eventFilter(self, widget, event):
        if (event.type() == QtCore.QEvent.Resize and
            widget is self.label):
            self.label.setPixmap(self._pixmap.scaled(
                self.label.width(), self.label.height(),
                QtCore.Qt.KeepAspectRatio))
            return True
        return QtGui.QMainWindow.eventFilter(self, widget, event)

rawDescription: How to Autoresize QLabel pixmap keeping ratio without using classes?


rawDescription: HMAC-SHA1 URL encryption in VBA produces incorrect output


code: ground = pygame.Rect(0, 750, 0, 0) # (x, y, width, heigh)

rawDescription: Pygame - AttributeError: 'int' object has no attribute 'y'


rawDescription: Matching values in nested dictionaries

description: Matching values in nested dictionaries


code: ax.set_xticklabels = ax.set_yticklabels = headers[1:]

rawDescription: adding text ticklabels to pcolor heatmap

description: Adding text ticklabels to pcolor heatmap


rawDescription: Remove odd elements from list in Python

description: Remove odd elements from list in Python


code: from a import x,y,z

rawDescription: Reasoning behind `from ... import ...` syntax in Python


code:
class MyData:
    def __init__(self):
        self.r = range(10)
        self.r2 = range(10, 20)

    def f(self):
        self.r.extend(self.r2)
        return self.r

rawDescription: how to pass self to function inside python dictionary

description: Pass self to function inside python dictionary


code:
from scipy.interpolate import interp1d
f = interp1d(x, y) ## for linear interpolation
f2 = interp1d(x, y, kind='cubic') ## for cubic interpolation
xnew = np.linspace(x.min(), x.max(), num=41, endpoint=False)
ynew = f(xnew) ## or f2(xnew) for cubic interpolation

rawDescription: Split numpy array into similar array based on its content


code: f = lambda t,y: interp(y, yvalues, fvalues)

rawDescription: ODE integration with discretized values

description: ODE integration with discretized values


code:
['Ben Schwartz', 'Soko', 'Jacob Escobedo (R 2/28/14)']
['Wil Wheaton', 'the Birds of Satan', 'Courtney Kemp Agboh']

rawDescription: Regular Expressions: Find Names in String using Python


code:
strings = ["1asdf", "25etrth", "2234342 awefiasd"]
[numeric_prefix(s) for s in strings]

rawDescription: removing non-numeric characters from a string

description: Removing non-numeric characters from a string


code:
trips = [zip(B, p) for p in product(A, repeat=len(B))]
trips[:5]

rawDescription: Possible alignments of two lists using Python


code:
arr = np.array([[0, 2], [1, 3], [2, 5], [3, 2], [4, 5]])
value = np.array([4,0])
np.linalg.norm(arr-value, axis=1)
np.linalg.norm(arr-value, axis=1).argmin()
arr[np.linalg.norm(arr-value, axis=1).argmin()]

rawDescription: Search for closest value in list of lists in python


code:
M=sparse.lil_matrix(X)
M
m=sparse.coo_matrix(y)
m
I,J=np.nonzero(m)
I
J
M[I+3,J+2]=m[I,J]

rawDescription: Scipy sparse matrix assignment using only stored elements


code: sentencesWithHighlights = ['Chickens crushes a popular vet next to the eater.', 'Coffee funds chickens.']

rawDescription: Finding the surrounding sentence of a char/word in a string


code: result = [MyClass() for i in xrange(n_objects)]

rawDescription: Creating a list of objects in Python constructor


rawDescription: Filling a polygon with with multiple holes with pyCairo


code:
import datetime
import gzip
ts = datetime.datetime(2010, 11, 12, 13, 14).timestamp()
zf = gzip.GzipFile('test.gz', mode='wb', mtime=ts)
zf.write(b'test')
zf.flush()
zf.close()

rawDescription: Compresse file with preserve modified time stamp


code: entry = models.ForeignKey(Entry, related_name='files')

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


rawDescription: Django custom order_by

description: Django custom order_by


code:
def compute_neighborhoods(data, alphabet):
    keyset = set(data.keys())
    for key in data:
        possible_neighbors = set(generate_neighbors(key, alphabet))
        neighbors = possible_neighbors & keyset

        identifier = data[key][0]

        for neighbor in neighbors:
            data[neighbor][1].append(identifier)

rawDescription: Faster alternative to for loop in for loop


code:
result = df.groupby('labels').median()
result

rawDescription: getting median of particular rows of array based on index

description: Getting median of particular rows of array based on index


code:
if tdelta.days < 0:
    tdelta = timedelta(days=0,
                seconds=tdelta.seconds, microseconds=tdelta.microseconds)

rawDescription: Difference between two time intervals in Python


code:
with open("MyTEXT.txt", "r") as myfile:
    wordlist = [line.rstrip('\n').split() for line in myfile]

titlelist = [i[0] for i in wordlist if len(i) == 1 and i[0] != "unwanted"]

rawDescription: Searching for one-word string occupying a line of a text with Python 2.7


code:
data = [
    ('Abe', 'Bob', 3),
    ('Abe', 'Frank', 5),
    ('Abe', 'George', 4),
    ('Carl', 'Bob', 1),
    ('Dan', 'Carl', 2),
]

WEIGHT = 0
NODES = slice(1, None)

def get_path_and_weight(data, start, end):

    paths = [[0, start]]
    added = True

    while added:
        added = False

        for first, second, weight in data:
            for path in paths:
                candidate = None

                if (first in path[NODES]) and (second not in path[NODES]):
                    candidate = second
                elif (first not in path[NODES]) and (second in path[NODES]):
                    candidate = first

                if candidate:
                    new_path = list(path)
                    new_path.append(candidate)
                    new_path[WEIGHT] += weight

                    if new_path not in paths:
                        paths.append(new_path)
                        added = True

    for path in sorted(paths):
        if end in path[NODES]:
            return path

    return None

rawDescription: Find path from a list of tuples in Python


rawDescription: Previous and next item of list python

description: Previous and next item of list python


rawDescription: Basic Numpy array value assignment

description: Basic Numpy array value assignment


code: gen = (x for x in lists if x[0] > 10000)

rawDescription: minimum of list of lists

description: Minimum of list of lists


rawDescription: change 2 byte in a string

description: Change 2 byte in a string


code:
predefined_list = ['id','name','age','height','weight',]
ordering = {word: i for i, word in enumerate(predefined_list)}
sorted(['height','id'], key=ordering.get)
sorted(['name','weight','height'], key=ordering.get)

rawDescription: python sort list based on key sorted list

description: Python sort list based on key sorted list


code: from tkinter import messagebox as tkMessageBox

rawDescription: Installing tkMessageBox on Python2.7

description: Installing tkMessageBox on Python2.7


rawDescription: Can scraping be applied to this page which is actively recalculating?


code:
df = pd.read_csv('raw_df.csv') # raw dataframe
dfp = pd.read_csv('processed_df.csv') # processed dataframe
dfr = df.drop('Tr_id', axis=1)

x = pd.DataFrame()
for col_raw in dfr.columns:
    for col_p in dfp.columns:
        if (dfr.tail(9).astype(int)[col_raw] == dfp[col_p]).all():
            series = dfr[col_raw].head(7).tolist()
            series.append(col_raw)
            x[col_p] = series

x = pd.concat([df['Tr_id'].head(7), x], axis=1)

rawDescription: Pandas compare 2 dataframes by specific rows in all columns


code:
rand_max = (screen_width * screen_height) - (rect_width * rect_height)
def rand_point():
    rand_raw = random.randint(0, rand_max-1)
    x = rand_raw % screen_width
    y = rand_raw // screen_width
    if rect_y <= y < rect_y+rect_height and rect_x <= x < rect_x+rect_width:
        rand_raw = rand_max + (y-rect_y) * rect_width + (x-rect_x)
        x = rand_raw % screen_width
        y = rand_raw // screen_width
    return (x, y)

rawDescription: Generate random number outside of range in python