code:
list = ['a', 'b', 'c', 'd']
params = ','.join('?' for _ in list)
c.execute("""SELECT colour,
                    COUNT(*)
             FROM MyTable
             WHERE colour IN (SELECT colour
                              FROM MyTable
                              WHERE letter IN (""" + params + """))
             GROUP BY colour""",
          list)

rawDescription: How to return the total count of a database entity when one of its rows matches a condition

description: Return the total count of a database entity when one of its rows matches a condition


code:
t = Tree()
dic = {'foo': t, 'foobar': t.branch()}

rawDescription: defining values in dictionary based on other values there

description: Defining values in dictionary based on other values there


code:
from __future__ import print_function
import string

def complement(dna):
    transtable = string.maketrans('acgtnACGTN', 'tgcanTGCAN')
    return dna.translate(transtable)

print(complement('TGA'))

rawDescription: AttributeError: 'str' object has no attribute 'maketrans'


code:
x.py
from ctypes import *
x = CDLL('x')
x.read.argtypes = [POINTER(POINTER(c_int16))]
x.read.restype = None
x.release.argtypes = [POINTER(c_int16)]
x.release.restype = None
p = POINTER(c_int16)()
x.read(p,5)
for i in range(5):
    print(p[i])
x.release(p)

rawDescription: passing arrays with ctypes

description: Passing arrays with ctypes


code:
foo = settings.default_settings['foo']
bar = settings.current_settings['bar']
settings.current_settings['bar'] = True

rawDescription: how to override default values needed by function in module?

description: Override default values needed by function in module


code:
from bs4 import BeautifulSoup

html = """

  Monday Some info here...
 and then some

  Tuesday Some info here...

  Wednesday Some info here...

  ...

"""
soup = BeautifulSoup(html)
result = soup.find('strong', text='Tuesday').findNextSibling(text=True)
print(result.decode('utf-8'))

rawDescription: BeautifulSoup parse unstructured html

description: BeautifulSoup parse unstructured html


code: new_list = [a for a in range(1111,10000) if all(int(b) % 2 == 1 for b in str(a))]

rawDescription: How to check if all the digits of a number are odd in python?

description: Check if all the digits of a number are odd in python


code:
t1 = ('A', 'B', 'C')
t2 = ('d', 'e')
from itertools import product

list(product(t1,t2))

rawDescription: Remove particular combinations from itertools.combinations


code:
ReadDirectoryChangesW = ctypes.windll.kernel32.ReadDirectoryChangesW

ReadDirectoryChangesW.restype = ctypes.wintypes.BOOL
ReadDirectoryChangesW.errcheck = _errcheck_bool
ReadDirectoryChangesW.argtypes = (
    ctypes.wintypes.HANDLE,  # hDirectory
    LPVOID,  # lpBuffer
    ctypes.wintypes.DWORD,  # nBufferLength
    ctypes.wintypes.BOOL,  # bWatchSubtree
    ctypes.wintypes.DWORD,  # dwNotifyFilter
    ctypes.POINTER(ctypes.wintypes.DWORD),  # lpBytesReturned
    ctypes.POINTER(OVERLAPPED),  # lpOverlapped
    RDCW_CALLBACK_F  # FileIOCompletionRoutine # lpCompletionRoutine
)

rawDescription: Watchdog compatibility: A workaround for "CancelIoEx"


code:
display.HTML('
'+df.to_html()+'
')

rawDescription: IPython Notebook & Pandas: How does pandas produce html table?


code:
#!/usr/bin/env python
import os
from subprocess import Popen

fifo = "fifo"
os.mkfifo(fifo)
p = Popen(["gnome-terminal", "-x", "python", "handler.py", fifo])
with open(fifo, 'wb') as file:
    file.write("Text sent to handler for display")
os.remove(fifo)
p.wait()

rawDescription: Communication between two gnome-terminal sessions


code:
from collections import defaultdict

country_nodes = defaultdict(int)
for n in Nodes.query():
    country_nodes[n.country] += 1

rawDescription: Ran out of "Datastore Small Operations" quota unexpectedly


code:
words = list()
num = list()
with open("words.txt", "r") as f:
    for line in f:
        words += line.split()

with open("positions.txt", "r") as f:
    for line in f:
        num += [int(i) for i in line.split()]

recreated = ' '.join(words[pos] for pos in num)

with open("recreated.txt", "wt") as f:
    f.write(recreated)

rawDescription: Recreating a sentence using two text files (Python)


code:
courses_list=[]

for item in g_data2:
   try:
      name=item.contents[1].find_all("div",{"class":"views-field-title"})[0].text
   except:
       name=''
   try:
      address1=item.contents[1].find_all("div",{"class":"views-field-address"})[0].text
   except:
      address1=''
   try:
      address2=item.contents[1].find_all("div",{"class":"views-field-city-state-zip"})[0].text
   except:
      address2=''

   course=[name,address1,address2]
   courses_list.append(course)

rawDescription: writing and saving CSV file from scraping data using python and Beautifulsoup4

description: Writing and saving CSV file from scraping data using python and Beautifulsoup4


code: coords = pd.read_csv('IDQQCoords.csv')

rawDescription: How to move data in numpy array from column/row to another based on value in third column

description: Move data in numpy array from column/row to another based on value in third column


code:
all_lists = [l1, l2, l3, l4, l5]
from itertools import chain
from collections import Counter
all_counts = Counter(chain.from_iterable(all_lists))
for k, v in all_counts.items():
    print('element', k, 'appears in', v, 'lists')

rawDescription: Counting appearance of an element in many lists


code:
replace("banana", "na", "so")
replace("notabene", "na", "so")

rawDescription: Replacing a character in a stringin Python


rawDescription: Group consecutive integers and tolerate gaps of 1


code: block_process(a, blocksize, filter1, (filtsize,))

rawDescription: Calling filter functions from within a block-by-block processing function


code: val_dict = dict(zip(RANKS, zip(VALUES, range(len(VALUES)))))

rawDescription: Sort Python list by dict key,value

description: Sort Python list by dict key,value


rawDescription: Python storing Arabic in an Array?

description: Python storing Arabic in an Array


code:
def factorial(X):
    x = 1
    for position in range(1, X + 1):
        x = factorial_recurrence(x, position)
    return x

rawDescription: Issues with Recursion using Python 3

description: Issues with Recursion using Python 3


code:
from timeit import timeit
from operator import itemgetter
import heapq
def original(a):
    ran = len(a.values()[0])
    max = [0.0 for i in range(0,ran)]
    for vals in a.values():
        max = [max[x] if max[x] > vals[x] else vals[x] for x in range(0,ran)]
    a = {k : [v[x]/max[x] for x in range(0,ran)] for k,v in a.items()}
    best = heapq.nlargest(1, (v for v in a.values()), key=lambda v: sum(v))

def zip_and_max(a):
    best = (0, [])
    maxes = [max(c) for c in zip(*a.values())]
    for k, v in a.iteritems():
        v = a[k] = [c/m for c, m in zip(v, maxes)]
        best = max([best, (sum(v), v)], key=itemgetter(0))

timeit('f(a.copy())', 'from __main__ import a, original as f', number=100000)
timeit('f(a.copy())', 'from __main__ import a, zip_and_max as f', number=100000)

rawDescription: normalise list data in range (0.0, 1.0)

description: Normalise list data in range (0.0, 1.0)


code: list_of_funcs = [lambda a, b, x=i: a*b*x for i in range(10)]

rawDescription: How to create an array of functions which partly depend on outside parameters? (Python)

description: Create an array of functions which partly depend on outside parameters? (Python)


code: x = foo.pixsolve(A.T, b.T).T

rawDescription: Solve large number of small equation systems in numpy


code:
if (e.type is KEYDOWN and e.key == K_f):
    if screen.get_flags() & FULLSCREEN:
        pygame.display.set_mode(size)
    else:
        pygame.display.set_mode(size, FULLSCREEN)

rawDescription: How can I exit Fullscreen mode in Pygame?

description: Exit Fullscreen mode in Pygame


rawDescription: Optimize Double loop in python

description: Optimize Double loop in python


code:
walk_object = os.walk(path)
def func():
    global walk_object
    try:
        dirpath, dirnames, filenames = next(walk_object)
        print(dirpath, dirnames, filenames)
        func()    # or w.after(0,func) or w.after_idle(func)
    except StopIteration:
        return
func()

rawDescription: Using os.walk inside a Tkinter mainloop

description: Using os.walk inside a Tkinter mainloop


code: [u'Some text', u'Some other text', u'Some text', u'Some text2', u'Some text', u'Some other text']

rawDescription: Parse HTML using BeautifulSoup depending on previous tag


code: np.tensordot(t,I, axes=([0],[0]))

rawDescription: Efficient product of 1D array and 3D array along one dimension - NumPy


code:
CONDITIONS = [(lambda i: i % 4 == 0, "four"), (lambda i: i % 6 == 0, "six"),
              (lambda i: i % 7 == 0, "seven")]

def apply_conditions(i):
    for condition, replacement in CONDITIONS:
        if condition(i):
            return replacement
    return i

ar = map(apply_conditions, range(0, n))

rawDescription: Multiple IF conditions in a python list comprehension


code:
for i in range(0,1+m-n):
    result.append(b[i:i+n]-a)

rawDescription: Python: Cell arrays comparison using minus function


rawDescription: python 3.4, timer count down not working

description: Python 3.4, timer count down not working


code:
with open('soundTransit1_remote_rawMeasurements_15m.txt', 'r') as infile,\
        open('soundTransit1.txt','w') as outfile:
    inr = csv.reader(infile, delimiter='\t')
    for row in inr:
        d = datetime.datetime.strptime(row[0], '%Y-%m-%d %H:%M:%S')
        p = int(int(row[5]) * 0.2)
        nr = '01{:%Y%m%d%H%M}{:04}\n'.format(d, p)
        outfile.write(nr)

rawDescription: Print strings with line break Python

description: Print strings with line break Python


code:
data = csv.DictReader(open(f), delimiter="\t", fieldnames=fieldnames)
sorted_data = sorted(data, key=operator.itemgetter(col_name))
for name, entries in itertools.groupby(data, key=operator.itemgetter(col_name)):
    pass # whatever

rawDescription: Disturbing odd behavior/bug in Python itertools groupby?


code:
class ModelX(models.Model):
    ...
    ...
    row_number = models.IntegerField("Row number when ordering by date desc")

    class Meta:
        db_table = 'x_with_reverse_date_index'

rawDescription: Limit queryset results based on model field, are there better ways?


code:
import pandas as pd
import numpy as np

np.random.seed(1)
df = pd.DataFrame({'ID': ('STRSUB BOTDWG'.split())*4,
                   'Days Late': [60, 60, 50, 50, 20, 20, 10, 10],
                   'quantity': [56, 20, 60, 67, 74, 87, 40, 34]})
print(df)

#    Days Late      ID  quantity
# 0         60  STRSUB        56
# 1         60  BOTDWG        20
# 2         50  STRSUB        60
# 3         50  BOTDWG        67
# 4         20  STRSUB        74
# 5         20  BOTDWG        87
# 6         10  STRSUB        40
# 7         10  BOTDWG        34

rawDescription: Grouping data by value ranges

description: Grouping data by value ranges


code:
import numpy as np
import numpy.ma as ma

z = np.random.random((10,10))
sorted = np.sort(z,axis=None)
mask = ma.masked_inside(z,sorted[10],sorted[-10])

rawDescription: Maximun and mininum values numpy Array

description: Maximun and mininum values numpy Array


rawDescription: How to make a function that detects a character in a string and returns it's position in the string? Python 3.2

description: Make a function that detects a character in a string and returns it's position in the string? Python 3.2


rawDescription: Unpack BinaryString sent from JavaScript FileReader API to Python


rawDescription: How to find cluster sizes in 2D numpy array?

description: Find cluster sizes in 2D numpy array


code:
import os, os.path
os.path.expanduser('~')

rawDescription: Is there a Python idiom for creating dot folders in home directory?


rawDescription: how can draw a line in python by x,y?

description: How can draw a line in python by x,y


code:
from PyQt4.QtSql import QSqlQueryModel,QSqlDatabase,QSqlQuery
from PyQt4.QtGui import QTableView,QApplication
import sys

app = QApplication(sys.argv)

db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("sqlitedb.rdb")
db.open()

projectModel = QSqlQueryModel()
projectModel.setQuery("select name,age from info",db)

projectView = QTableView()
projectView.setModel(projectModel)

projectView.show()
app.exec_()

rawDescription: Getting data from selected item in QListView


code:
x,y,z = a.shape
b = a.T #Transpose - get the indices grouped along the other axis
b = b.reshape(y, x, z) #Interchange the axes.

rawDescription: Reshape/resize(pivot?) N-dimensional numpy array column-wise


code:
def generate(n, filename):
    """Write a number of random sentences to a file and standard output.

    Arguments:
    n -- the number of random sentences to write.
    filename -- the name of the file to write the sentences to.
    """
    with open(filename, 'w+') as outf:
        for generate in range(n):
            s = sentence()
            print(generate + 1, s)
            outf.write(s + '\n')

rawDescription: Trying to output to file as well as printing to screen inside a for loop


rawDescription: Can some one explain me what does np.log do?


code:
Before
import locale
setlocale(LC_ALL, 'de')
x = locale.format('%.2f', 123)
setlocale(LC_ALL, '')

rawDescription: Python: Access Posix' locale database without setlocale()


code: np.where((ibound == 1) & (abs(h - nodata) <= eps), L1TopOld, h)

rawDescription: Efficient way to do conditional checks on Numpy Arrays


code:
d, e = zip(*c)
d
e

rawDescription: Slicing a python string with intervals?

description: Slicing a python string with intervals


code: return [str(value[1]) for value in foundFiles]

rawDescription: Getting rid of empty strings in a tuple

description: Getting rid of empty strings in a tuple


code:
print(b)
print(c)

rawDescription: split list into 2 lists corresponding to every other element

description: Split list into 2 lists corresponding to every other element


code:
from scipy import sparse
a = sparse.lil_matrix((2,3),)
a[0] = [1, 2, 3]
a[1, 2] = 5

a = a.tocsr()
a.indices = -a.indices + a.shape[1] - 1
print(a)

rawDescription: flip rows of sparse array in python

description: Flip rows of sparse array in python


code:
index_col_name = cols[0]
dtypes = dict(zip(cols[1:], [float]* len(cols[1:])))
dtypes[index_col_name] = str

rawDescription: How to read index data as string with Python pandas?

description: Read index data as string with Python pandas


rawDescription: Using matlab's find like operation in python


code:
def groupby(a, key_columns):
    from collections import defaultdict
    groups = defaultdict(list)
    for i, row in enumerate(a):
        groups[tuple(row[c] for c in key_columns)].append(i)
    return groups.values()

rawDescription: How do I get the indexes of unique row for a specified column in a two dimensional array

description: Get the indexes of unique row for a specified column in a two dimensional array


code: s = weather.loc[selector2, 'Dry_bulb_temperature']

rawDescription: How to get a combined look at two different DataFrames

description: Get a combined look at two different DataFrames


code:
from collections import defaultdict

result = defaultdict(lambda: 0)

# Summarize quantities for each name
for item in a.values():
    result[item['name']] += int(item['qty'])

# Convert to your funny format
b = {str(i+1): v for i, v in enumerate({'name': key, 'qty': str(val)} for key, val in result.items())}

# b contains:
# {'1': {'name': 'Blue', 'qty': '3'}, '2': {'name': 'Green', 'qty': '1'}}

rawDescription: From a dictionary with repeated values, how to create a new one excluding the repeats and incrementing a couter inside the dictionary?


code:
assigned_layers = correspondinglayerbuff = 0
tuple_of_tuples = moduleconfigcopy = ((0, 1), (0, 0, 1), (0, 1))
dimension = moduledimension
MOD_BUFFER = modulebuffer = 'buffer'
c_buff = moduleconbuff = 0

rawDescription: Matching Binary operators in Tuples to Dictionary Items


code:
(u'SaturdaySep. 5', u'Arizona State Sun Devils')
(u'SaturdaySep. 12', u'Ball State Cardinals')
(u'SaturdaySep. 19', u'Nevada Wolf Pack')
(u'SaturdaySep. 26', u'at Arkansas Razorbacks')
(u'SaturdayOct. 3', u'Mississippi State Bulldogs')
(u'SaturdayOct. 10', u'Open Date')
(u'SaturdayOct. 17', u'Alabama Crimson Tide')
(u'SaturdayOct. 24', u'at Ole Miss Rebels')
(u'SaturdayOct. 31', u'South Carolina Gamecocks')
(u'SaturdayNov. 7', u'Auburn Tigers')
(u'SaturdayNov. 14', u'Western Carolina Catamounts')
(u'SaturdayNov. 21', u'at Vanderbilt Commodores')
(u'Saturday\r\n    Nov. 28', u'at LSU Tigers')
(u'SaturdayDec. 5', u'SEC Championship Game')

rawDescription: Iterate and remove HTML from list elements in python


rawDescription: Fastest way to draw a ton of squares?

description: Fastest way to draw a ton of squares


code:
class PageForm(forms.ModelForm):
    class Meta:
        model = Page

    def normal_fields(self):
        return [field for field in self if not field.is_hidden
               and field.name in ('field1', 'field2')]

    def collapsible_fields(self):
        return [field for field in self if not field.is_hidden
               and field.name in ('field4', 'field5', 'field3')]

rawDescription: django modelForm regrouping fields

description: Django modelForm regrouping fields


code:
class ResultView(TemplateView):
    template_name = "result.html"

class MainView(FormView):
    template_name = 'index.html'
    form_class = UserInputForm
    success_url = 'result/'

    def form_valid(self, form):
        self.request.session['temp_data'] = form.cleaned_data
        return super(MainView, self).form_valid(form)

rawDescription: Send form data from views to template

description: Send form data from views to template


rawDescription: Beginning with two separate tuples, how to make one non-nested tuple?


code:
def convertsmall(text):
    return ' '.join(smallnr(int(word)) if word.isdigit() else word for word in text.split())

rawDescription: changing a word in a string?

description: Changing a word in a string


code:
result = dfs[0]
for df in dfs[1:]:
    result = merge(result, df)

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


code: os.system('setterm -cursor off')

rawDescription: Display Number of Iterations in Output Window


code:
serv.stop()
serv.join()

rawDescription: python stop multithreaded echo server

description: Python stop multithreaded echo server


code:
from pprint import pprint
for result in db.test.find({'EXPERIMENT':1}, {'DATA.TIMESTAMP':1, '_id':0}): pprint(result)

rawDescription: Pymongo iterate through list of docs

description: Pymongo iterate through list of docs


code:
import urllib2, urllib
values = {"query": "['=', 'certname', 'myserver']"}
data = urllib.urlencode(values)
print(data)

rawDescription: HOW TO translate CURL command to Python

description: HOW TO translate CURL command to Python


code:
d = {n: df2.ix[rows]
     for n, rows in enumerate(df2.groupby('group_no').groups)}

rawDescription: Splitting a dataframe based on column values


rawDescription: Removing items from a list in python

description: Removing items from a list in python


code:
import datetime
def now_string():
    return datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

rawDescription: Shorter version of now()

description: Shorter version of now()


code: reader = csv.reader(open(path, "rb"), delimiter=',', quoting=csv.QUOTE_NONE, escapechar="\\")

rawDescription: Reading from csv file Python

description: Reading from csv file Python


code:
import imp
foo = imp.load_source('filename', 'File\Directory\filename.py')

rawDescription: how to import module from other directory in python?

description: Import module from other directory in python


code:
union_set = set()
union_set.update(*l)

rawDescription: Taking the union of sets

description: Taking the union of sets


code: dict(zip(i,map(list,zip(*j))))

rawDescription: How to add two lists into dictionary?

description: Add two lists into dictionary


rawDescription: SVD - Matrix transformation Python

description: SVD - Matrix transformation Python


code:
dist = stats.rv_discrete(values=(np.arange(counts.shape[0]),
                                 counts/counts.sum()))
fill_idxs = dist.rvs(size=df.shape[0] - df.category.count())
df.loc[df.category.isnull(), "category"] = counts.iloc[fill_idxs].index.values

rawDescription: Fill multiple nulls for categorical data


code:
import zipfile
import io

zf = zipfile.ZipFile('data/test_zip.zip')
for filename in zf.namelist():
    with zf.open(filename, 'r') as f:
        words = io.TextIOWrapper(f, newline=None)
        for line in words:
            print(repr(line))

rawDescription: python zipfile module with TextIOWrapper

description: Python zipfile module with TextIOWrapper


code: from mom.codec import base85

rawDescription: Store arbitrary binary data on a system accepting only valid UTF8


code: stop_words = set(stop_words)

rawDescription: Why is pos_tag() so painfully slow and can this be avoided?


rawDescription: Remove all lists of multiple sets where the specific index is same


code:
# Get offsets for row and column
R_offset,C_offset = np.meshgrid(np.arange(-1,2),np.arange(-1,2))

# Get row and column indices for places where elements are 1s
R_match,C_match = np.nonzero(A==1)

# Store number of matches as it would be frequently used
N = R_match.size

# Get offsetted row, col indices for all matches
R_idx = (R_match[:,None,None] + R_offset).reshape(N,-1)
C_idx = (C_match[:,None,None] + C_offset).reshape(N,-1)

# Based on boundary conditions set invalid ones to zeros
valid_mask = (R_idx>=0) & (C_idx>=0) & (R_idx<A.shape[0]) & (C_idx<A.shape[1])
valid_mask[:,4] = 0 # Set the pivot(self/center) ones to invalid

# Using valid mask, "cut off" elements from each group of 9 elems
cut_idx = valid_mask.sum(1).cumsum()

# Finally form groups
grps_R = np.split(R_idx[valid_mask],cut_idx)[:-1]
grps_C = np.split(C_idx[valid_mask],cut_idx)[:-1]

rawDescription: Find a nodes 8 neighbors on a 2D grid

description: Find a nodes 8 neighbors on a 2D grid


code:
indices = {key: index for index, key in enumerate(List1)}
indices

rawDescription: Replacing elements in a list with the indices of a list containing all unique elements


code:
from tkinter import *

class SampleApp:
    def __init__(self, parent):

        self.textfield = None

        self.myParent = parent
        self.Container = Frame(parent)
        self.Container.pack()

        self.textfield = Entry(self.Container, bg="red")
        self.textfield.pack()

        self.button = Button(self.Container, text="Get", command=self.on_button)
        self.button.pack()

    def on_button(self):
        print(self.textfield.get())

root = Tk()
myapp = SampleApp(root)
root.mainloop()

rawDescription: Python 3.4.4 settin argument in Tkinter?

description: Python 3.4.4 settin argument in Tkinter


code:
import json
import pandas as pd

content = '''{
    "uselessInfo": "blabla",
    "headers": [
        { "type": "DIMENSION", "name": "DATE" },
        { "type": "DIMENSION", "name": "COUNTRY" },
        { "type": "METRIC", "name": "REVENUE" }
    ],
    "rows": [ [ "2014-09-29", "Germany", 435 ],
        [ "2014-09-28", "USA", 657 ],
        [ "2014-09-13", "Spain", 321 ]
    ],
    "average": [ "some unwanted info" ],
    "total": [ "some unwanted info" ]
}'''
data = json.loads(content)

columns = [dct['name'] for dct in data['headers']]
df = pd.DataFrame(data['rows'], columns=columns)
print(df)

rawDescription: Create pandas df from JSON where Column Headers and Rows are in separate arrays


code:
import json
from bson import json_util

install(JSONPlugin(json_dumps=lambda body: json.dumps(body, default=json_util.default)))

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


code:
def setName(self, *names):
    for name in names:
        self.names.append(name)

rawDescription: Best way to apply function to element or to list of elements in python

description: Apply function to element or to list of elements in python


code:
class Student(object):
    name = ""
    age = 0
    major = ""

    # The class "constructor" - It's actually an initializer
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

def make_student(name, age, major):
    student = Student(name, age, major)
    return student

rawDescription: Python, creating objects

description: Python, creating objects


rawDescription: Can someone explain how to use the repr function to format the output?


code: event.set() # event occurred

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


code:
from itertools import groupby
from operator import itemgetter

def aggregate(data):
    result = []
    data = sorted(data, key=itemgetter(3))
    for k, g in groupby(data, itemgetter(3)):
        g = list(g)
        n = len(g)  # Cast to float if you want average to be float in python 2
        x1 = g[0][0]
        x2 = sum(x[1] for x in g)
        x3 = sum(x[2] for x in g)
        d = {k: [x1, x2/n, x3/n]}  # This is what you want for each group
        result.append(d)

    return result

def main():
    data = [[[-50,98], 1, 2, 'San Antonio,TX'],
            [[-52,99], 3, 4, 'San Antonio,TX']]
    result = aggregate(data)
    print(result)

if __name__ == '__main__':
    main()

rawDescription: Group by place names in python

description: Group by place names in python


code: objects = MyModel.objects.filter(start_time__lt=time(7, 30))

rawDescription: Django filter datetime field by time, irrespective of date


code:
def getregion( coordinates, values, testfun ):
    ...
    if testfun(x):
        ...

rawDescription: Pass conditional expression as function argument


code:
fsm = Fysom(TABLE)

@transition(fsm, "onload")
def myfunction():
    pass

rawDescription: python FSM Fysom callbacks on the other way

description: Python FSM Fysom callbacks on the other way


code:
#If you trust parse and you have no other way to test parse instead check its calls you need to patch it
@patch(__name__ + ".parse")
class MyTestCase(unittest.TestCase):
    def setUp(self):
        #Our 'feed'
        self.mock_feed = MagicMock()
        #readline mock
        self.mock_readline = self.mock_feed.readline

    def test_my_reader_empty(self, mock_parse):
        #setting up an empty stream
        self.mock_readline.return_value = ""
        my_reader(self.mock_feed)
        #Our test is that parse was never called
        self.assertFalse(mock_parse.called)

    def test_my_reader_some_lines(self, mock_parse):
        #setting up lines sequence and EOF
        self.mock_readline.side_effect = ["hi,\n", "I'm your standard input\n", "cheers", ""]
        my_reader(self.mock_feed)
        #Call parse with every lines
        mock_parse.assert_has_calls([call("hi,\n"), call("I'm your standard input\n"), call("cheers")])

rawDescription: How to mock a buffered file handle for unit testing

description: Mock a buffered file handle for unit testing


code:
import os
import sys
import time

if __name__ == '__main__':
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)

    for i in range(5):
        time.sleep(1)
        sys.stdout.write("Hello how are you " + str(i))
        sys.stdout.flush()

rawDescription: How do I send stdout in real time from nodejs to angularjs?

description: Send stdout in real time from nodejs to angularjs


rawDescription: Diagonals at different points of a 2D list in Python


code:
import re
pattern = re.sub('noun', lambda match: getRandomLine('noun.txt'), pattern)

rawDescription: How can I replace substrings without replacing all at the same time? Python

description: Replace substrings without replacing all at the same time? Python


rawDescription: Pandas sorting by group aggregate

description: Pandas sorting by group aggregate


code:
for row in cur:
    print(row['column_name'])

rawDescription: DictCursor doesn't seem to work under psycopg2


code:
sentence = 'Hello, This is string.'
sentence = ''.join(sentence.split('i', 1))
sentence = ''.join(sentence.rsplit('i', 1))
sentence.swapcase()

rawDescription: Actions with strings, python

description: Actions with strings, python


code:
letters = []
for x in ascii_lowercase:
    letters.append((x,(dic[x]/n)*100))
return letters

rawDescription: Determing relative letter frequency

description: Determing relative letter frequency


code:
import process_manager
...

def callback(ch, method, properties, body):
    job_info = json.loads(body)
    logging.info('Start Time: ' + time.strftime("%H:%M:%S"))
    split_jobs = split_job(job_info)
    manager.runProcesses(split_jobs)
    ch.basic_ack(delivery_tag=method.delivery_tag)

if __name__ == "__main__":
    manager = process_manager.get_manager()
    connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
    channel = connection.channel()

    channel.queue_declare(queue="JobReader", durable=True)
    logging.info('Waiting for messages..')

rawDescription: Python - Asynch Multiprocessing from RabbitMQ Consumer


rawDescription: Change IPython 3 for Python 3 kernel to python2 for the cluster too


code:
def dupli(the_list):
    return [(item, the_list.count(item)) for item in sorted(set(the_list))]

rawDescription: how to optimally count elements in a python list

description: Optimally count elements in a python list


rawDescription: Averaging multiple masked numpy arrays in python


rawDescription: decompress name

description: Decompress name


code: struct.pack('IBB', bar, t, x)

rawDescription: Python - struct / ctypes

description: Python - struct / ctypes


code:
OrderHeader = form.save()
OrderLines  = formset.save()

rawDescription: Django calculate field based on two other fields in formset


code:
from app.forms import DynamicForm

def create_form(request):
    if request.method == 'POST':
        dynamic_form = DynamicForm(request.POST)
        ...
        ...
    else:
        dynamic_form = DynamicForm()
    return render(request, 'form.html', {
        'dynamic_form': dynamic_form
        })

rawDescription: Django forms - checkbox group with dropdowns


rawDescription: Adding elements of RGB array in Python

description: Adding elements of RGB array in Python


rawDescription: Print to same line

description: Print to same line


rawDescription: How to use ax with Pandas and Matplotlib

description: Use ax with Pandas and Matplotlib


code: "This module is automatically imported during initialization."

rawDescription: Making Python run a few lines before my script


code:
def add_these_numbers(number_1, number_2):
    return number_1 + number_2

rawDescription: What is a self-written decorator (like @login_required) actually doing?


rawDescription: Check multiple bool values with tuples in python


code:
def Something(somedict):
    return '.'.join(['%s and %s' % (key, value) for key, value in somedict.iteritems()])

rawDescription: Iteritems return formatted strings

description: Iteritems return formatted strings


code:
import random
phrase = "I am feeling sad that he left, but that's okay because I'm happy he will be back soon"
thesaurus = { "happy":["glad",  "blissful", "ecstatic", "at ease"],
              "sad"  :["bleak", "blue", "depressed"]
            }
print (" ".join(random.choice(thesaurus[x]) if x in thesaurus else x for x in phrase.split()))

rawDescription: Print one word from a list within a dictionary (python)


code:
g = (line.split('\t') for line in open(fname))
[els[i:i+2] for els in g for i in range(0, 4, 2)]

rawDescription: python - appending different columns from a file to different lists?

description: Python - appending different columns from a file to different lists


code: {{ listing.listing|upper }}

rawDescription: How to write Python Code in Django

description: Write Python Code in Django


code:
#instead of this
numpy.mean(tsvar[12,25,35])
# try
numpy.ma.mean(tsvar[12,25,35])

rawDescription: Unmask netcdf Python

description: Unmask netcdf Python


code:
import operator

ops = {
    'conjunction': operator.and_,
    'disjunction': operator.or_,
    'exclusive': operator.xor,
    'equivalence': operator.eq,
}

rawDescription: Python operations

description: Python operations


code:
from numpy import meshgrid, sin, cos, pi, linspace
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
dx = 100; dy =  50; dz = 25
nx = 200; ny = 100; nz = 100
xs = linspace(0,dx,nx)
ys = linspace(0,dy,ny)
zs = linspace(0,dz,nz)
X,Y,Z = meshgrid( xs, ys, zs, dtype=float)
my_array = sin(0.3*pi+0.4*pi*X/dx)*sin(0.3*pi+0.4*pi*Y/dy)*(Z/dz)

fig = plt.figure()
ax = fig.gca(projection='3d')

z = calc_iso_surface( my_array, my_value=0.1, zs=zs, interp_order=6 )
ax.plot_surface(X[:,:,0], Y[:,:,0], z, cstride=4, rstride=4, color='g')

z = calc_iso_surface( my_array, my_value=0.2, zs=zs, interp_order=6 )
ax.plot_surface(X[:,:,0], Y[:,:,0], z, cstride=4, rstride=4, color='y')

z = calc_iso_surface( my_array, my_value=0.3, zs=zs, interp_order=6 )
ax.plot_surface(X[:,:,0], Y[:,:,0], z, cstride=4, rstride=4, color='b')

plt.ion()
plt.show()

rawDescription: Using numpy/scipy to calculate iso-surface from 3D array


code:
def split_into_five_character_segments(s):
    ret = []
    while len(s) > 5:
        ret.append(s[:5])
        s = s[5:]
    ret.append(s)
    return ret

rawDescription: how can I generate a fragment library from a protein sequence file?

description: Generate a fragment library from a protein sequence file


rawDescription: Count occurrences of certain words in pandas dataframe


rawDescription: Django store regular expression in DB which then gets evaluated on page


code: a[ range(i,j) + range(k,p)   , ]

rawDescription: Python: what's an elegant way to select specific rows of an 2-d array into a new array?


code: col_2 = np.vstack([queen, queen])

rawDescription: How to best create a new image out of existing images in openCV

description: Best create a new image out of existing images in openCV


code:
from itertools import chain
import csv

l = [['Route', 'Vehicles', 'Vehicle Class', 'Driver_ID', 'Date', 'Start', 'Arrive'],
     ['ABC', 'ZYG098, AB0134, GF0158', 'A1, B2, C3', 'John Doe, Jane Doe, Abraham Lincoln', '20150301', 'A', 'B'],
     ['AC', 'ZGA123', 'C3', 'George Washington', '20150301', 'A', 'C'],
     ['ABC', 'XAZ012, AB0134, YZ089', 'C1, B2, A2 ', 'John Adams, Jane Doe, Thomas Jefferson', '20150302', 'A', 'B']]
it = map(list,zip(*l))

# transpose original list, row-columns, columns-rows
it =  zip(*l)

# get each column separately, using iter so we can pop first element
# off to get headers efficiently
route, veh, veh_c, d_id, date, start, arrive = iter(iter(next(it))), iter(next(it)), iter(next(it)), iter(next(it)), iter(next(it)), iter(next(it)), iter(next(it))

# get all headers to write later
headers = next(route), next(veh), next(veh_c), next(d_id), next(date), next(start), next(arrive)

srt_veh = []
key_inds = []

# sort vehicle elements and keep a record of old indexes
# so subelements in Vehicle_class and driver_id can be rearranged to match
for x in veh:
    srt = sorted(x.split(","))
    key_inds.append([x.split(",").index(w) for w in srt])
    srt_veh.append(",".join(srt).strip())

srt_veh_cls = []

# sort vehicle class based on old index of elements in vehicles
# and rejoin split elements
for ind, ele in enumerate(veh_c):
    spl = ele.split(",")
    srt_veh_cls.append(",".join([spl[i].strip() for i in key_inds[ind]]))

srt_dr_id = []

# sort driver_ids  based on old index of elements in vehicle
# and join subelements again after splitting and sorting
for ind, ele in enumerate(d_id):
    spl = ele.split(",")
    srt_dr_id.append(",".join([spl[i].strip() for i in key_inds[ind]]))

 # transpose again for writing
zipped = zip(*(route, srt_veh, srt_veh_cls,
           srt_dr_id, date, start, arrive))

rawDescription: Turn Python list from CSV with multi-value fields into a Python nested list, sort nested list values and export to CSV


code:
X_train_pca = pca.transform(Xtrain)

X_train_pca2 = (Xtrain - pca.mean_).dot(pca.components_.T)

assert_array_almost_equal(X_train_pca, X_train_pca2)

rawDescription: PCA projecting and reconstruction in Scikit


code: finalDict = dict([(k['id'], k['sigla']) for k in myDictList])

rawDescription: From List of Dictionary To Dictionary

description: From List of Dictionary To Dictionary


code:
def seno(x,n):
    result = 0.0
    fact = 1.0   # start with '1!'
    exp = x      # start with 'x¹'
    xx = x*x     # xx = x²
    for i in range(1, n+1, 2):
        result += exp / fact
        exp *= -xx  # update exponential term to 'xⁱ', and swap sign
        fact *= (i+1) * (i+2) # update factorial term to '(i+2)!'
    return result

rawDescription: Programming a math function in python

description: Programming a math function in python


code:
from System.Collections import *
# create an instance of Hashtable
h = Hashtable()

from System.Collections.Generic import *
# create an instance of List<string>
l = List[str]()

rawDescription: How do I reference classes using IronPython?

description: Reference classes using IronPython


code:
payload = {
    'query':'neutrogena',

}

r = requests.get('http://www.pharmacy295.gr/products',data = payload ,headers = headers)

soup = BeautifulSoup(r.text,'lxml')
products = soup.findAll('span', {'class':'name'})
print(products)

rawDescription: Using Python to use a website's search function


code: default_data.update({'item3': 3})

rawDescription: Python add new item to dictionary

description: Python add new item to dictionary


code:
byte = 0xFC
list_size = 8
[(byte >> i) & 1 for i in range(list_size)][::-1] # reverse this array, since left-most bits are evaluated first.

rawDescription: Searching a more elegant way for converting a byte to a list of bits


code:
AdminEmailMessage(
    sender = "your@adminaccount.com",
    subject = "Hello Admin",
    body = "A test admin email"
).send()

rawDescription: Who is treated as administrator of GAE application?


code: type(A)

rawDescription: pls help - error message "no attribute 'renderContents'"

description: Pls help - error message "no attribute 'renderContents'"


code:
someList = [1,2,3,4,5,7]
someString = "hello this is a string"

def some_function(a, b):
    return a+b

rawDescription: which python IDE is close to R for running a line code after the whole file

description: Which python IDE is close to R for running a line code after the whole file


code: self.Panes = []

rawDescription: Why aren't my old boxes disappearing?

description: Why aren't my old boxes disappearing


code: items = [li.extract() for li in ul.find_all("li")]

rawDescription: How do I sort an unordered list using BeautifulSoup 4 by a child element

description: Sort an unordered list using BeautifulSoup 4 by a child element


rawDescription: convert indices into corresponding pandas dataframe values

description: Convert indices into corresponding pandas dataframe values


code: pd.melt(df, id_vars="y").head()

rawDescription: What is the effective way to have a pivot-table having pandas dataset columns as its rows?


rawDescription: Find and Replace Percent Signs - Python

description: Find and Replace Percent Signs - Python


code:
from pyparsing import *

LBRACE,RBRACE,EQ,SEMI = map(Suppress, "{}=;")
name = Word(printables, excludeChars="{}=;")
expr = Word(printables, excludeChars="{}=;") | quotedString

leaf = Group(name + EQ + expr + SEMI)
group = Group(LBRACE + ZeroOrMore(leaf) + RBRACE) | leaf
tree = OneOrMore(group)

rawDescription: Convert BNF grammar to pyparsing

description: Convert BNF grammar to pyparsing


code:
def orig(A, MIN_OBS):
    temp_dict = collections.defaultdict(int)
    for k, v in A.iteritems():
        temp_list = v.split(',')
        for item in temp_list:
            temp_dict[item] += 1
    cols_to_make = []
    for k, v in temp_dict.iteritems():
        if v > MIN_OBS:
            cols_to_make.append('A_' + k)

    result_df = pd.DataFrame(0, index=A.index, columns=cols_to_make)
    for k, v in A.iteritems():
        temp_list = v.split(',')
        for item in temp_list:
            if ('A_' + item) in cols_to_make:
                result_df['A_' + item][k] = 1
    return result_df

rawDescription: Transform pandas Series with variable length comma separated values to Dataframe


code:
url = 'http://httpbin.org/get'
url1 = urlopen(Request(url,  headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}))
print(url1.read().decode('utf8'))

rawDescription: Testing for user agent spoofing in python


rawDescription: Make every numeric value in a pandas DataFrame negative


code:
class Bat(Mammal):
    ...

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

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


rawDescription: Can two distributions deliver the same package?


rawDescription: Using a Django custom model method property in order_by()


code: tables_df = pd.read_sql('SELECT table_name FROM database_name', conn)

rawDescription: Importing multiple SQL tables using pandas


code:
from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas, numpy as np  # I find np.random.randint to be better

# Make the data
x = [{i:np.random.randint(1,5)} for i in range(10)]
df = pandas.DataFrame(x)

# Make a list by cycling through the colors you care about
# to match the length of your data.
my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))

# Specify this list of colors as the `color` option to `plot`.
df.plot(kind='bar', stacked=True, color=my_colors)

rawDescription: How to give a pandas/matplotlib bar graph custom colors

description: Give a pandas/matplotlib bar graph custom colors


code:
def bits(iterable):
    bit = 1
    res = 0
    for elem in iterable:
        if elem:
            res |= bit
        bit <<= 1
    return res

def mask(dim, i, j):
    res = 0
    for idx in range(dim * i, dim * (i + 1)):
        res |= 1 << idx
    for idx in range(j, dim * dim, dim):
        res |= 1 << idx
    return res

def masks(dim):
    return [mask(dim, i, j) for i in range(dim) for j in range(dim)]

class Puzzle(object):
    def __init__(self, matrix):
        if isinstance(matrix, Puzzle):
            self.matrix = matrix.matrix
            self.dim = matrix.dim
            self.masks = matrix.masks
        else:
            self.matrix = bits(sum(matrix, []))
            self.dim = len(matrix)
            self.masks = masks(len(matrix))

    def __repr__(self):
        return str(self.matrix)

    def solved(self):
        return self.matrix == 0

    def next(self):
        for mask in self.masks:
            puzzle = Puzzle(self)
            puzzle.matrix ^= mask
            yield puzzle

    def solve(self):
        v = set()

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

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

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

rawDescription: Avoid a deepcopy when doing a BFS

description: Avoid a deepcopy when doing a BFS


rawDescription: Python Tuple & List Manipulation (As an input to the SVM model in scikit-learn)


code:
# one line, not especially readable
def is_full(self):
    return not any(cell == ' ' for row in d for cell in row)

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


code: myDict = {key:val for key, val in myDict.items() if val != 42}

rawDescription: What is the best way to remove a dictionary item by value in python?


code:
from pprint import pprint
from parcon import (Forward, SignificantLiteral, Word, alphanum_chars, Exact,
                    ZeroOrMore, CharNotIn, concat, OneOrMore)

block = Forward()
hyphen = SignificantLiteral('"')
word = Word(alphanum_chars + '/_.)')
value = word | Exact(hyphen + ZeroOrMore(CharNotIn('"')) + hyphen)[concat]
pair = word + '=' + value
flag = word
attribute = pair | flag | block
head = word
body = ZeroOrMore(attribute)
block << '{' + head + body  + '}'
blocks = OneOrMore(block)

with open('<your file name>.txt') as infile:
    pprint(blocks.parse_string(infile.read()))

rawDescription: Parsing structured text file in python

description: Parsing structured text file in python


code:
all_allowable = df3['Bid'].isin(['E', 'A', 'N'])
df3[all_allowable].groupby('Location')['Bid'].value_counts(normalize=True)

rawDescription: Pandas calcuating percentage in data summary


code:
' '.join(random.sample(nameLines, random.randint(1, 2)))
' '.join(random.sample(nameLines, random.randint(1, 2)))

rawDescription: Python - Print random number of lines from file


code:
from itertools import product
lhs_values, rhs_values = ['a', 'b'], [1, 2]
for i, (lhs, rhs) in enumerate(product(lhs_values, rhs_values)):
    df.loc[(df.l == lhs) & (df.n == rhs), 'v'] = 'val%s' % (i + 1)

rawDescription: How to rename elements of a column based on conditional statements?

description: Rename elements of a column based on conditional statements


code:
[{'debug': 'on', 'locale': 'de_DE'},
 {'debug': 'on', 'locale': 'en_US'},
 {'debug': 'on', 'locale': 'fr_FR'},
 {'debug': 'off', 'locale': 'de_DE'},
 {'debug': 'off', 'locale': 'en_US'},
 {'debug': 'off', 'locale': 'fr_FR'}]

rawDescription: Combinations from dictionary with list values using Python


code:
orders = []
orders.append((code, number))

rawDescription: python multiplication {how to do it with a dic ?}

description: Python multiplication {how to do it with a dic ?}


rawDescription: asyncio: Wait for event from other thread

description: Asyncio: Wait for event from other thread


rawDescription: Python parent in QTreeWidget

description: Python parent in QTreeWidget


code: df.apply(lambda x: re.search(r'\b' + x.bar + r'\b', x.foo) is not None, axis=1)

rawDescription: Pandas DataFrame - check if string in column A contains full word string in column B


code:
lis=[range(3),list('abc')]
id(lis)
lis1=lis[:]
id(lis1)
[id(x) for x in lis1]==[id(y) for y in lis]
lis2=copy.deepcopy(lis)
[id(x) for x in lis2]==[id(y) for y in lis]

rawDescription: Pass list to function by value

description: Pass list to function by value


rawDescription: numpy random usage validity

description: Numpy random usage validity


rawDescription: how to rename django image as id.jpg

description: Rename django image as id.jpg


code: countries = [country.alpha2 for country in pycountry.countries]

rawDescription: List of language codes (ISO639-1) in Python?


rawDescription: finding a record with a max value in python

description: Finding a record with a max value in python


code:
indexedValues = {}
for entry in documents_query:
    if entry[0] not in indexedValues:
        indexedValues[entry[0]] = {}
    indexedValues[entry[0]][entry[1]] = entry[2]

rawDescription: How to extract data from two different lists

description: Extract data from two different lists


code: pprint(streetno)

rawDescription: Retrieving Key and Values from Dictionary


code:
import numpy as np
a = np.array([[1,2],[3,4]])
b = np.diag(a.ravel())
b

rawDescription: Transfer matrix elements to another matrix's diagonal


code:
def f(row):
    if row['A'] == row['B']:
        val = 0
    elif row['A'] > row['B']:
        val = 1
    else:
        val = -1
    return val

rawDescription: Creating a new column based on if-elif-else condition


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

description: Generate all possible combinations from all permutations


code: sis = 'nohup ~/mycodes/code > {}/out{}.dat'.format(j, i)

rawDescription: python multiprocessing sleep between executions

description: Python multiprocessing sleep between executions


rawDescription: Pandas: join with outer product

description: Pandas: join with outer product


code:
def TaggingDecorator(method):
  "Decorate the method with an attribute to let the metaclass know it's there."
  method.my_attr = 'FOO BAR'
  return method # No need for a wrapper, we haven't changed
                # what method actually does; your mileage may vary

class TaggingMetaclass(type):
  "Metaclass to check for tags from TaggingDecorator and add them to the class."
  def __new__(cls, name, bases, dct):
    # Check for tagged members
    has_tag = False
    for member in dct.itervalues():
      if hasattr(member, 'my_attr'):
        has_tag = True
        break
    if has_tag:
      # Set the class attribute
      dct['my_attr'] = 'FOO BAR'
    # Now let 'type' actually allocate the class object and go on with life
    return type.__new__(cls, name, bases, dct)

rawDescription: Python - decorator - trying to access the parent class of a method


code:
def search_slow():
    prod_nums = ['V475', 'F987', 'Q143', 'R688']
    return_value = False
    for item in prod_nums:
        if item == 'R688':
            return_value = True
    return return_value

rawDescription: Don't understand how Timeit works. Need an explanation


code:
aggregated_counts = (data
    .map(lambda kv: (kv, 1))
    .reduceByKey(add)
    .map(lambda kv: (kv[0][0], (kv[0][1], kv[1])))
    .groupByKey()
    .mapValues(lambda xs: (list(xs), sum(x[1] for x in xs))))

aggregated_counts.collect()
## [('a', ([('v', 1), ('u', 1)], 2)), ('b', ([('w', 1), ('x', 2)], 3))]

rawDescription: Apache Spark CombineByKey with list of elements in Python


code:
import os

ip = get_ipython()

favfile = "readline_favorites"

def load_readline_favorites():
    """load profile_dir/readline_favorites into the readline history"""
    path = os.path.join(ip.profile_dir.location, favfile)
    if not os.path.exists(path):
        return

    with open(path) as f:
        for line in f:
            ip.readline.add_history(line.rstrip('\n'))

if ip.has_readline:
    load_readline_favorites()

rawDescription: How to log IPython history to text file?

description: Log IPython history to text file


code:
import testApp
import wx

########################################################################
class ReloaderPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.testFrame = None

        showAppBtn = wx.Button(self, label="Show App")
        showAppBtn.Bind(wx.EVT_BUTTON, self.onShowApp)

        reloadBtn = wx.Button(self, label="Reload")
        reloadBtn.Bind(wx.EVT_BUTTON, self.onReload)

        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer.Add(showAppBtn, 0, wx.ALL|wx.CENTER, 5)
        mainSizer.Add(reloadBtn, 0, wx.ALL|wx.CENTER, 5)
        self.SetSizer(mainSizer)

    #----------------------------------------------------------------------
    def onReload(self, event):
        """
        Reload the code!
        """
        if self.testFrame:
            self.testFrame.Close()
            reload(testApp)
            self.showApp()
        else:
            self.testFrame = None

    #----------------------------------------------------------------------
    def onShowApp(self, event):
        """
        Show the app
        """
        self.showApp()

    #----------------------------------------------------------------------
    def showApp(self):
        """
        """
        self.testFrame = testApp.TestFrame()

########################################################################
class ReloaderFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Reloader")
        panel = ReloaderPanel(self)
        self.Show()

if __name__ == "__main__":
    app = wx.App(False)
    frame = ReloaderFrame()
    app.MainLoop()

rawDescription: How can I modify my wxPython code live to avoid closing/reopening them?

description: Modify my wxPython code live to avoid closing/reopening them


code:
def per_section(it):
    section = []
    for line in it:
        if line.strip():
            section.append(line)
        else:
            yield ''.join(section)
            section = []
    # yield any remaining lines as a section too
    if section:
       yield ''.join(section)

rawDescription: How to read a textfile by x number of lines, but x is unknown?

description: Read a textfile by x number of lines, but x is unknown


rawDescription: Build regular expressions using previously compiled regular expressions


rawDescription: How should I check more than 10 columns for nan values and select those rows having nan values, ie keepna() instead of dropna()


code:
import fnmatch
import os

for file in os.listdir("/Users/x/y"):
    if fnmatch.fnmatch(file, '*.txt'):
        print(file)
        my_var = file
        # do your stuff

rawDescription: how can I save the output of a search for files matching *.txt to a variable?

description: Save the output of a search for files matching *.txt to a variable


code:
url(r'^v1/ (?P<type>(statistics|analytics))/stats_bar$', views.stats_bar, name='stats_bar')

reverse('status_bar', kwargs={'type': 'statistics'}) # usage

rawDescription: Django NoReverseMatch Exception for regular expression matching 2 routes


code:
def to_pygame(coords, height, obj_height):
    """Convert an object's coords into pygame coordinates (lower-left of object => top left in pygame coords)."""
    return (coords[0], height - coords[1] - obj_height)

rawDescription: Change the position of the origin in PyGame coordinate system


rawDescription: Constructing 3D array from base 2D array - Numpy


code:
from datetime import datetime
while True:
    inp = input("Enter date in format yyyy/mm/dd hh:mm:ss")
    try:
        then = datetime.strptime(inp, "%Y/%m/%d %H:%M:%S")
        break
    except ValueError:
        print("Invalid input")
diff = then - datetime.now()
print(diff, "until", inp)
print(diff.total_seconds(),"seconds")

rawDescription: Can you do sums with a datetime in Python?

description: Do sums with a datetime in Python


code: #!/usr/bin/python

rawDescription: Should I put the shebang line in every python file?


code:
for ol_man, kid in paternal_pairs.items():
    if temp_son == kid:
        print("\nThe grandfather of", son, "is", ol_man)
        break
else:
    print("\nNo grandfather listed for", son)

rawDescription: Python Programming for Absolute Beginner Chapter 5 Challenge 4


code:
def dict_insert_or_append(adict,key,val):
    """Insert a value in dict at key if one does not exist
    Otherwise, convert value to list and append
    """
    if key in adict:
        if type(adict[key]) != list:
            adict[key] = [adict[key]]
        adict[key].append(val)
    else:
        adict[key] = val

rawDescription: Creating a tree/deeply nested dict from an indented text file in python


code:
def letter_grade(score):
    if 90 <= score <= 100:
        return "A"
    elif 80 <= score <= 89:
        return "B"
    elif 70 <= score <= 79:
        return  "C"
    elif 60 <= score <= 69:
        return "D"
    elif score < 60:
        return "F"
    else:
        #This is returned if all other conditions aren't satisfied
        return "Invalid Marks"

rawDescription: Python Script returns unintended "None" after execution of a function


rawDescription: Python. BigData. Need to extract Web-Browser and OS users' preferences from cells. Best-performance method?


code:
logger.warn(...)
logger.log(...)

rawDescription: Adding magic global methods to modules

description: Adding magic global methods to modules


code: [statistics.median(xs) for xs in zip(list_1, list_2, list_3)]

rawDescription: Python: Iterating through multiple lists to get median of each item of same index


code:
for colname in df.columns:
    if 'dxpoa' in colname:
        colid = colname.split('dxpoa')[1]
        df = df.apply(subfunc,axis=1,col_reference=colname,col_target='dx'+colid)

rawDescription: Replacing item values in a data frame on certain condition in other columns


rawDescription: Indentation of pformat() output

description: Indentation of pformat() output


code:
table_dict = {}
for i in range(4):   # Create
  table_name = "mytable" + str(i)
  table_dict[table_name] = MyTable(table_name)

for i in range(4):   # Query
  session.query(table_dict["mytable" + str(i)])

rawDescription: dynamically creating a set of SQLAlchemy tables

description: Dynamically creating a set of SQLAlchemy tables


code:
def dict_cursor(cursor):
    description = [x[0] for x in cursor.description]
    for row in cursor:
        yield dict(zip(description, row))

rawDescription: Django Backend-neutral DictCursor

description: Django Backend-neutral DictCursor


code:
class Worker(threading.Thread):
    results = []
    ...

    def run(self):
        results = self.calculate_results()
        Worker.results.extend(results) # extending a list is thread safe

rawDescription: parallel writing to list in python

description: Parallel writing to list in python


code:
def __init__(self):
    self.foo = 5

rawDescription: How to call a data member of the base class if it is being overwritten as a property in the derived class?

description: Call a data member of the base class if it is being overwritten as a property in the derived class


code: leafIDs_custom = [dictRows[v] for v in rowHeaders_custom]

rawDescription: Sorting tuples based on another list

description: Sorting tuples based on another list


code:
with open('/path/to/my/file') as myFile:
    d = dict(line.strip().split(None, 1) for line in myFile)

print(d['a'])
# Cheif manager

rawDescription: How do I read data from a file using Python?

description: Read data from a file using Python


code:
parens('a d f gsds ( adsd ) adsdaa')
parens('adadsa ( sadad adsads ( adsda ) dsadsa ) ( dsadsad )')
parens('a ana anan anan ( adad ( sad ) sdada asdad ) ( sadad ( adasd ) asda ) sdafds ( afdasf )')

rawDescription: Python - Return all substrings in the first group of nested parentheses


code:
my_composition = compose(remove_tables, clean_text_passage, replace,
                         count_words, risk_count)
with open('filing2.txt') as input:
    riskcount = my_composition(input.read())

rawDescription: How can I automatically run all the functions in the module?

description: Automatically run all the functions in the module


code:
from itertools import chain
pipe((repeat(i, i + 1) for i in  range(4)), chain.from_iterable, list)
[0, 1, 1, 2, 2, 2, 3, 3, 3, 3]

rawDescription: Extracting a dictionary from an RDD in Pyspark


code:
#Insert count row into all groups and recombine
RRData = grouped.apply(addcount)

rawDescription: How to bin groupeby counts in pandas?

description: Bin groupeby counts in pandas


code:
output = "path/to/parentfile"
cmd = "sort -k2 {}".format(output)
with open(new_file,"w") as f:
    sorting = Popen(cmd.split(),stdout=f)

rawDescription: How to store output from linux call in Python

description: Store output from linux call in Python


code: { k:v for k, v in hand.items() if v }

rawDescription: Removing entries from a dictionary based on values


code:
from matplotlib import pylab
pylab.ion()  # Force interactive
pylab.plot(range(10), range(10))
pylab.show() # This does not block
pylab.pause(2**31-1)

rawDescription: Keep a figure "on hold" after running a script


rawDescription: Python: return unique only cartesian product of a list containing lists?


code:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

outer_grid = gridspec.GridSpec(1,2) # gridspec with two adjacent horizontal cells
left_cell = outer_grid[0,1] # the left SubplotSpec within outer_grid

inner_grid = gridspec.GridSpecFromSubplotSpec(2,1, left_cell)

# From here we can plot usinginner_grid's SubplotSpecs
ax1 = plt.subplot(inner_grid[0,0])
ax2 = plt.subplot(inner_grid[1,0])

ax1.plot(data)
ax2.plot(other_data)

plt.show()

rawDescription: Embedding multiple gridspec layouts on a single matplotlib figure?


code:
def window(inputlist, index):
    return inputlist[max(0, index - 2):index + 3]

window(['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'], 1)
window(['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'], 2)
window(['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'], 4)
window(['foo', 'bar', 'baz', 'spam', 'ham', 'eggs'], 5)

rawDescription: Elegant way to access last two and next two elements in a list?


rawDescription: Pandas Multi-Colum Boolean Indexing/Selection with Dict Generator


rawDescription: What are the possible numpy value format strings?


code:
item_list = []

for row in rows:
    info = {} # <---- here
    itemId = row[0]
    itemDesc = row[10]

rawDescription: Python Append List Repeats Last Element?

description: Python Append List Repeats Last Element


code: yuv_image = np.einsum('kl,ijl->ijk', transformation_matrix, rgb_image)

rawDescription: Numpy 3d array map operation

description: Numpy 3d array map operation


rawDescription: How to unpack list into two variables in python2.x

description: Unpack list into two variables in python2.x


code:
import urllib, urllib2
page = urllib2.urlopen(URL + urllib.urlencode(params))

rawDescription: Python-Replace HTTP parameters one at a time


code:
import os

with open(os.path.expanduser('~/matches.txt'), 'w') as f:
    for dirpath, dirnames, filenames in os.walk(os.path.expanduser('~/x/y')):
        for x in dirnames + filenames:
            f.write('{}\n'.format(os.path.join(dirpath, x)))

rawDescription: equivalent to the find coreutil command in python 3 for recursively returning all files and folders in a directory structure?

description: Equivalent to the find coreutil command in python 3 for recursively returning all files and folders in a directory structure


code:
def is_iterable(object):
    '''
    Returns True if the object is iterable, False if it is not.
    '''
    try:
        i = iter(object)
    except TypeError:
        return False
    else:
        return True

def validate_type(object, type_or_prototype):
    '''
    Returns True if the object is of the type passed in.

    The type can be a straightforward type, such as int, list, or
    a class type. If so, we check that the object is an instance of
    the type.

    Alternatively the 'type' can be a prototype instance of a more
    complex type. For example:
    [int]                   a list of ints
    [(str, int)]            a list of (str, int) tuples
    {str: [(float, float)]} a dictionary of strings to lists of (float, float) tuples

    In these cases we recursively check the sub-items to see if they match
    the prototype.
    '''
    # If the type_or_prototype is a type, we can check directly against it...
    type_of_type = type(type_or_prototype)
    if type_of_type == type:
        return isinstance(object, type_or_prototype)

    # We have a prototype.

    # We check that the object is of the right type...
    if not isinstance(object, type_of_type):
        return False

    # We check each sub-item in object to see if it is of the right sub-type...
    if(isinstance(object, dict)):
        # The object is a dictionary, so we check that its items match
        # the prototype...
        prototype = type_or_prototype.popitem()
        for sub_item in object.items():
            if not validate_type(sub_item, prototype):
                return False

    elif(isinstance(object, tuple)):
        # For tuples, we check that each element of the tuple is
        # of the same type as each element the prototype...
        if len(object) != len(type_or_prototype):
            return False
        for i in range(len(object)):
            if not validate_type(object[i], type_or_prototype[i]):
                return False

    elif is_iterable(object):
        # The object is a non-dictionary collection such as a list or set.
        # For these, we check that all items in the object match the
        prototype = iter(type_or_prototype).__next__()
        for sub_item in object:
            if not validate_type(sub_item, prototype):
                return False

    else:
        # We don't know how to check this object...
        raise Exception("Can not validate this object")

    return True

rawDescription: Python: type checking of complex returned values


code:
coolmod = __import__('coolm')
coolm.someproperty

rawDescription: Dynamic Module Python

description: Dynamic Module Python


code:
class GFF3OutStream(GenomeStream):
    def __init__(self, genome_stream):
        self.gs = c_void_p(gtlib.gt_gff3_out_stream_new(genome_stream, None))
        self._as_parameter_ = self.gs

rawDescription: Issues with Python ctypes '_as_parameter_' and 'from_param' on OS X


code:
def hamming2(s1, s2):
    """Calculate the Hamming distance between two bit strings"""
    assert len(s1) == len(s2)
    return sum(c1 != c2 for c1, c2 in zip(s1, s2))

rawDescription: Hamming distance between two binary strings not working


code:
df['hour'] = df['hour'].apply(lambda x: int(x.lstrip('h'))-1)
df

rawDescription: How to rearrange a python pandas dataframe?

description: Rearrange a python pandas dataframe


code: xyz.objects.raw("SELECT * FROM xyz WHERE col3 != CONCAT(col1, col2)")

rawDescription: using sql concat() in django for concatenating two columns

description: Using sql concat() in django for concatenating two columns


rawDescription: Extra index in list

description: Extra index in list


code:
df = pd.read_csv("test.csv")
df['Date'] = pd.to_datetime(df['Date'])
delta = df['Date'].iat[-1] - df['Date'].iat[0]
delta
delta / np.timedelta64(1, 's')

rawDescription: Subtract last and first elements in a column using Python Pandas


code:
import StringIO
import csv
import requests

r = requests.get('http://www.twilio.com/resources/rates/international-sms-rates.csv')
reader = csv.DictReader(StringIO.StringIO(r.text))
row = next(reader) # get the next row
print(row)

rawDescription: Why does the parsing of csv file not break things into their 'logical' order?


rawDescription: Include template form to django admin

description: Include template form to django admin


code:
from win32com.client import GetObject

WMI = GetObject('winmgmts:')
for battery in WMI.InstancesOf('Win32_Battery'):
    print(battery.EstimatedChargeRemaining)

rawDescription: Get battery status using wmi in python?

description: Get battery status using wmi in python


code: sorted([-max(x) for x in ords], reverse=True) # now "y" comes first

rawDescription: Sorting dictionary by value and key length


code:
class GroupMembers(models.Model):
    class Meta:
        ordering = ['order']

    group = models.ForeignKey(Group)
    person = models.ForeignKey(Person)
    order = models.PositiveIntegerField(default=0)

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


code:
# want to track x, y, z
trk = Trk(x, y, z)
trk.fn() # returns up-to-date value

trk.x = new_value
trk.fn() #detects that trk.x changed and computes new trk.value

rawDescription: In Python, can I bind a variable to a function/expression so that it automatically updates?


code:
import string
inoutdict = {ord(p):unicode(" "+p+" ") for p in string.punctuation}
unicode("foo,,,bar!!1").translate(inoutdict)

rawDescription: How to convert an iterative str.replace() with str.translate()? - python

description: Convert an iterative str.replace() with str.translate()? - python


code:
from mybot.spider import MyParametrizedSpider

class MySpiderManager(object):
    loaded = True

    def fromdomain(self, name):
        start_urls, extra_domain_names, regexes = self._get_spider_info(name)
        return MyParametrizedSpider(name, start_urls, extra_domain_names, regexes)

    def close_spider(self, spider):
        # Put here code you want to run before spiders is closed
        pass

    def _get_spider_info(self, name):
        # query your backend (maybe a sqldb) using `name` as primary key,
        # and return start_urls, extra_domains and regexes
        ...
        return (start_urls, extra_domains, regexes)

rawDescription: Using one Scrapy spider for several websites


code:
@app.task()
def add(x, y):
    return x + y

rawDescription: What is the right way to invoke celery.task.chunks?


code:
for menu in ["Admin", "Groups", "Network", "Subnets", "Entries"]:
    try:
        doWork(my_dataset[menu])
        del my_dataset[menu]
    except KeyError:
        # The user might not have any entries for that menu, so don't worry about it
        pass
for menu in my_dataset.keys():
    doWork(my_dataset[menu])

rawDescription: Custom sort on a dictionary in Python?

description: Custom sort on a dictionary in Python


rawDescription: How should I remove one string from the start of another given that I know the longer string matches case-insensitively?


code:
import pyexcel as pe

...
pe.save_as(file_name="test.csv", dest_session=session, dest_table=Sample)

rawDescription: Bulk import/load csv to sqlite using Python


code:
prediction_list.append(regr.predict(test_set_feature_list))
np.set_printoptions(formatter={'float_kind':'{:f}'.format})
for items in prediction_list:
    final_prediction.append(items)

rawDescription: issue in executing scikit-learn linear regression model

description: Issue in executing scikit-learn linear regression model


code: name="\" or UserType=\"Admin"

rawDescription: Secure MySQL login data in a Python client program


code:
import os
import sys
sys.path.append(os.path.join(os.dirname(__file__), '../'))

rawDescription: Python paths/import in standalone programs


code:
for child in root.findall("item"):
  # if there are children, get their text content as well.
  if len(child):
    for subchild in child:
      subchild.text
  # else just get the current child text.
  else:
    child.text

rawDescription: Check if Element has children or not

description: Check if Element has children or not


code:
xindex = darr[43]['xindex']
pindex = darr[43]['pindex']
x = xarr[xindex]
p = parr[pindex]

rawDescription: find value of forloop at which event occurred Python

description: Find value of forloop at which event occurred Python


rawDescription: Get Day name from Weekday int

description: Get Day name from Weekday int


code:
# Two 1D color arrays
tmp1 = np.array(['red', 'red', 'red', 'green'])
tmp2 = np.array(['white', 'black', 'blue', 'blue'])

# Multiplicity arrays
color1_occupations = [1, 0, 1, 2]
color2_occupations = [0, 2, 0, 1]

# Stack those two color arrays and two multiplicity arrays separately
tmp12 = np.column_stack((tmp1,tmp2))
color_occupations = np.column_stack((color1_occupations,color2_occupations))

# Use np.repeat to get stacked multiplicities for stacked color arrays
out = np.repeat(tmp12,color_occupations.ravel())

rawDescription: using numpy repeat simultaneously on arrays with distinct multiplicities but same dimension

description: Using numpy repeat simultaneously on arrays with distinct multiplicities but same dimension


code:
app = Flask(__name__)

# ...

from .utils import DictionaryConverter
app.url_map.converters['dict'] = DictionaryConverter

from .main import main as main_blueprint
app.register_blueprint(main_blueprint)

rawDescription: redirect data to the next view in Flask

description: Redirect data to the next view in Flask


code:
with open('my_data.csv', 'wb') as ofile:
    writer = csv.writer(ofile, delimiter='\t')
    writer.writerow(['ID', 'dict1', 'dict2', 'dict3', 'dict4'])
    keys = set(d.keys() for d in dicts)
    for key in keys:
        writer.writerow([key] + [d.get(key, None) for d in dicts])

rawDescription: Writing multiple Python dictionaries to csv file


rawDescription: Remove rows of zeros from a Pandas series


code:
SERVER = "your.mail.server"
FROM = "yourEmail@yourAddress.com"
TO = ["listOfEmails"] # must be a list

SUBJECT = "Subject"
TEXT = "Your Text"

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.sendmail(FROM, TO, message)
server.quit()

rawDescription: Send Outlook Email Via Python?

description: Send Outlook Email Via Python


code:
len(q.levels) - q.labels
quintile(df, "A")
np.array(df["A"])

rawDescription: Convert data to the quantile bin

description: Convert data to the quantile bin


code:
for name, group in grouped:
    print("Option name: {}".format(name))
    # Count of entries for this OPTION
    print("Count: {}".format(len(group.index)))
    # Accessing specific columns, say SELL
    print("SELL for this option\n")
    print(group["SELL"])
    # Summary for SELL for this option
    print("Summary\n")
    print(group["SELL"].describe())

rawDescription: Accessing data from a count method in Pandas


code:
import cProfile
cProfile.run('foo()')

rawDescription: How can you profile a Python script?

description: Profile a Python script


rawDescription: How to run specific test in Nose2

description: Run specific test in Nose2


code:
x = 'google'
y = 'google'
id(x), id(y)

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


code:
A = np.arange(12).reshape(3,4)
X=np.vstack([np.indices(A.shape),A[None,...]]).reshape(3,-1)
X.shape
X

rawDescription: Numpy: vector of indices and value

description: Numpy: vector of indices and value


code:
import sys
import threading
import time

class waiter(object):
    __slots__ = \
    [
        "action",
        "delay",
        "undelayed",
        "delay_timeout",
    ]
    def __init__(self, action, delay = 0.5, *args, **kwargs):
        self.action        = action
        self.delay         = delay
        self.undelayed     = False
        self.delay_timeout = threading.Thread(target = self.action_enable)
        self.delay_timeout.start()

    def action_prevent(self):
        self.undelayed = False

    def action_enable(self):
        while True:
            time.sleep(self.delay)
            if self.undelayed:
                self.action()
                break
            else:
                self.undelayed = True

def thanks():
    print("Person 2: Thank you ...")

polite = waiter(thanks, 1)
for _ in range(0, 1000000):
    polite.action_prevent()

print("First batch of events done.")
time.sleep(2)

rawDescription: Most efficient way to perform a deferred action in Python


rawDescription: Improving code design of DNA alignment degapping


code:
import two
a=1
b=2
c=3
my_dictionary={'ONE':a,'TWO':b,'THREE':c}
two.f(my_dictionary)

rawDescription: How to pass on variable to function in different script file

description: Pass on variable to function in different script file


code:
items = line.split()
items[2]

rawDescription: How to match this kind of string in Python use re?

description: Match this kind of string in Python use re


code:
class LoginNextMiddleware(object):
    redirect_url = '/app/view/'

    def process_request(self, request):
        next_url = request.GET.get('next', None)
        if next_url is not None and next_url != self.redirect_url:
            params = dict(request.GET.copy())
            del params['next']
            params['next'] = self.redirect_url
            return redirect(request.path + '?' + urlencode(params))

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


rawDescription: How to subtract datetimes / timestamps in python

description: Subtract datetimes / timestamps in python


code:
def foo(l,func):
    return  map(func,l) # list(map(...) python 3

print(foo(l,str.isalpha))

rawDescription: Passing method to a function in Python

description: Passing method to a function in Python


code:
import numpy as np
import pandas as pd
np.random.seed(2016)

N = 100
index = ((pd.date_range('2009-01-01', periods=N//2, freq='2T'))
         .union(pd.date_range('2009-01-01 4:00', periods=N//2, freq='2T')))
Data = pd.DataFrame(np.random.random((N,5)),
                    columns='spyo spyc spyv vxxo vxxc'.split(),
                    index=index)
Data['vxxv'] = np.random.randint(10, size=(N,))

def percent_change(x):
    if len(x):
        return (x[-1]-x[0])/x[0]
print(Data.resample('60T', base=30).apply(percent_change))

rawDescription: Python Pandas, Resampling data with pct_change function


code:
x = 5
def something(d):
    d['x'] = 10
something(locals())
print(x)   # now prints 10

rawDescription: Sharing data among instances of a mapping function in Python


rawDescription: Why does 'append' mutates all elements in a list?


code: dupemask = ~df.duplicated(subset = ['id'])

rawDescription: Using Pandas how do I deduplicate a file being read in chunks?


code: v.inverse_transform(X[i][None, :])

rawDescription: Extracting a feature by feature name in scikit dict vectorizer


rawDescription: Converting String Date to Timestamp and back python


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

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


code:
def bjorn4(s):
    # we start out with s[0] being the longest sorted substring (LSS)
    longest = (0, 1)    # the slice-indices of the longest sorted substring
    longlen = 1         # the length of longest
    cur_start = 0       # the slice-indices of the *current* LSS
    cur_stop = 1

    for ch in s[1:]:       # skip the first ch since we handled it above
        end = cur_stop-1   # cur_stop is a slice index, subtract one to get the last ch in the LSS
        if ch >= s[end]:   # if ch >= then we're still in sorted order..
            cur_stop += 1  # just extend the current LSS by one
        else:
            # we found a ch that is not in sorted order
            if longlen < (cur_stop-cur_start):
                # if the current LSS is longer than longest, then..
                longest = (cur_start, cur_stop)    # store current in longest
                longlen = longest[1] - longest[0]  # precompute longlen

            # since we can't add ch to the current LSS we must create a new current around ch
            cur_start, cur_stop = cur_stop, cur_stop+1

    # if the LSS is at the end, then we'll not enter the else part above, so
    # check for it after the for loop
    if longlen < (cur_stop - cur_start):
        longest = (cur_start, cur_stop)

    return s[longest[0]:longest[1]]

rawDescription: Why won't my for loop work? (Python)

description: Why won't my for loop work? (Python)


code: Student('Crow', 1, ['pecking', 'cawing', 'scavenging', 'advanced film theory'])

rawDescription: represent a class in the order that was shown in init, without hardcoding

description: Represent a class in the order that was shown in init, without hardcoding


code:
d3_dict = defaultdict(lambda: defaultdict(dict))
d3_dict['dried_food']['food']['jerky'] = 'chewy'
d3_dict

rawDescription: 2d dictionary with multiple keys per value


code:
import time
from multiprocessing.dummy import Pool
from multiprocessing.pool import TERMINATE

def get_api_response(apikey, result, subscription_id):
    url  = ("https://api.example.com/" + str(subscription_id))
    time.sleep(2)
    result.append(url)
    return result

def pass_args(args):
    foo = get_api_response(*args)
    if foo:
        return foo

def check_response_amount(result):
    if result and len(result) >= 5:
        print("DONE %s" % result)
        pool.terminate()

def get_db_entries():
    return [{'subscription_id' : i} for i in range(100)]

# One entry looks like that: {"id": 1, "name": "smith", "subscription_id": 123}
db_entries = get_db_entries()
apikey = 'abcd1234'
result = []
request_tuples = [(apikey, result, entry['subscription_id']) for entry in db_entries]
pool = Pool(2)
results = []
for item in request_tuples:
    results.append(pool.apply_async(get_api_response, item, callback=check_response_amount))
pool.close()
pool.join()
print("done")

rawDescription: Python 3: Multiprocessing API calls with exit condition


code:
Annot1
NAME: name
TEXT: text

Annot2
NAME: name
TEXT: text

Annot3
NAME: name
TEXT: text

Annot4
NAME: name
TEXT: text

rawDescription: List of dictionaries: print readable output in python 2.7


code:
X = scipy.randn(100, 2)
centroids, labels = kmeans2(X, 3)
labels

rawDescription: k-means in python: Determine which data are associated with each centroid

description: K-means in python: Determine which data are associated with each centroid


rawDescription: split a list into three lists with a stepsize and a starting point

description: Split a list into three lists with a stepsize and a starting point


code:
import pandas as pd
import numpy as np

df = pd.DataFrame({'Type':list('ABBC'), 'Set':list('ZZXY')})
df['color'] = np.where(df['Set']=='Z', 'green', 'red')
print(df)

rawDescription: Pandas conditional creation of a series/dataframe column


code:
with open('out.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile)

    for a_chunk in chunks(data[0], 6):
        csvwriter.writerow(a_chunk)

rawDescription: Save data to csv file using Python

description: Save data to csv file using Python


code: sticky = W+E or "we" or WE

rawDescription: Creating GUI using Tkinter

description: Creating GUI using Tkinter


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

num = 1000
x = np.linspace(0, 10, num)
y = np.exp(x)

# Add some non-stationary noise that's hard to see without de-trending
noise = 100 * np.exp(0.2 * x) * np.random.normal(0, 1, num)
y += noise

# Detrend with a 2d order polynomial
model = np.polyfit(x, y, 2)
predicted = np.polyval(model, x)

fig, axes = plt.subplots(nrows=2, sharex=True)
axes[0].plot(x, y, 'ro')
axes[0].plot(x, predicted, 'k-')
axes[0].set(title='Original Data and 2nd Order Polynomial Trend')

axes[1].plot(x, y - predicted, 'ro')
axes[1].set(title='Detrended Residual')

plt.show()

rawDescription: Detrend Flux Time Series with Non-Linear Trend


code:
# List of all .proto files
proto_src = ['file1.proto', 'path/to/file2.proto']

class build_py(_build_py):
  def run(self):
    for f in proto_src:
        generate_proto(f)
    _build_py.run(self)

class clean(_clean):
  def run(self):
    # Delete generated files in the code tree.
    for (dirpath, dirnames, filenames) in os.walk("."):
      for filename in filenames:
        filepath = os.path.join(dirpath, filename)
        if filepath.endswith("_pb2.py"):
          os.remove(filepath)
    # _clean is an old-style class, so super() doesn't work.
    _clean.run(self)

rawDescription: Python project using protocol buffers, Deployment issues


code:
def myfunc():
    d = {'Retry': ['30', '12', '12'],
         'Station MAC': ['aabbccddeea', 'ffgghhiijj', 'kkllmmnnoo'],
         'Download': ['70.', '99', '90']}
    colnames = ['Retry', 'Station MAC', 'Download']
    rows = zip(*[d[c] for c in colnames])
    return dict(rows=rows, colnames=colnames)

rawDescription: Generate HTML Table from Python Dictionary


code:
l = [list(permutations('1397', y)) for y in range(3)]
l

rawDescription: Multi-variable List Comprehension

description: Multi-variable List Comprehension


code: max_order = max_order + diff

rawDescription: Dynamically increment/decrement the value of a variable?


code:
from __future__ import division
from itertools import product

class Cube:
    """Representation of a cube."""

    # directions to all eight corners of a cube
    DIR = [Point3D(*s) for s in product([-1, +1], repeat=3)]

    def __init__(self, center, size, depth=0):
        if not isinstance(center, Point3D):
            center = Point3D(*center)
        self.center = center
        self.size = size
        self.depth = depth

    def __repr__(self):
        return 'Cube(center={c.center}, size={c.size}, depth={c.depth})'.format(c=self)

    def _divide(self):
        """Divide into eight cubes of half the size and one level deeper."""
        c = self.center
        a = self.size/2
        d = self.depth - 1
        return [Cube(c + a/2*e, a, d) for e in Cube.DIR]

    def divide(self, target_depth=0):
        """Recursively divide down to the given depth and return a list of
        all 8^d cubes, where d is the difference between the depth of the
        cube and the target depth, or 0 if the depth of the cube is already
        equal to or less than the target depth.

        >>> c = Cube(center=(0, 0, 0), size=2, depth=1)
        >>> len(c.divide(0))
        8
        >>> len(c.divide(-1))
        64
        >>> c.divide(5)[0] is c
        True
        >>> c.divide(-1)[0].size
        0.5
        """
        if self.depth <= target_depth:
            return [self]
        smaller_cubes = self._divide()
        return [c for s in smaller_cubes for c in s.divide(target_depth)]

rawDescription: Break down cubes into 8 smaller cubes recursively (when the cubes are defined by a mid point and size)


code: dict((item, item) for item in a.split(','))

rawDescription: How to convert a list into a required dictionary format

description: Convert a list into a required dictionary format


code:
from re import findall
def keyfun(p):
    v1, v2 = findall(p.name, '\d+')
    tot = int(v1) + int(v2) % 2
    return tot

rawDescription: Group related objects in Django

description: Group related objects in Django


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', action='append')
parser.parse_args('--foo 1 --foo 2'.split())

rawDescription: Why does argparse give me a list-in-a-list?


code: [ p for p in database if p.distFrom( 1, 2, 3 ) <= 3.0 ]

rawDescription: Storing information on points in a 3d space


rawDescription: Equating python datetimes

description: Equating python datetimes


code: ['dns.exe', 'lsass.exe', 'svchost.exe', 'lsass.exe', 'System']

rawDescription: extracting specific data from a text file in python

description: Extracting specific data from a text file in python


code:
dict_names = {'d1' : {'name':'bob', 'place':'lawn', 'animal':'man'},
              'd2' : {'name':'spot', 'place':'bed', 'animal':'dog'}}

rawDescription: Creating 2D dictionary in Python

description: Creating 2D dictionary in Python


code:
import Image
import numpy as np

value = "0110100001100101011011000110110001101111"

carr = np.array([(255,255,255), (0,0,0)], dtype='uint8')
data = carr[np.array(map(int, list(value)))].reshape(-1, 8, 3)
img = Image.fromarray(data, 'RGB')
img.save('/tmp/out.png', 'PNG')

rawDescription: Turning binary string into an image with PIL


rawDescription: How can I access the default value for a keyword argument in Python?

description: Access the default value for a keyword argument in Python


code:
rooms = {
    "room1": Room1,
    "room2": Room2
}

def get_room(id):
   return rooms[id]

rawDescription: How do I define a function in python to choose a list.

description: Define a function in python to choose a list.


rawDescription: how to transfer an numpy array into another array

description: Transfer an numpy array into another array


code:
def calculate_pnl( records, node_prices ):
    for record in records:
        record.setPnl( node_prices )

rawDescription: Best practices for manipulating database result sets in Python?


rawDescription: Convert u'\xe0' to '\u00E0' in Python 2.x?


code:
from __future__ import print_function

class transposer(object):
    def _skip_preamble(self):
        for line in self.fin:
            if line.strip().startswith('"No."'):
                self.keys = line.strip().split(',')[2:]
                return
        raise Exception('Initial line not found')
    def _do_loop(self):
        for line in self.fin:
            elts = line.strip().split(',')
            dat = elts[1]
            ix = 0
            for val in elts[2:]:
                print(dat, self.keys[ix], val, sep=',', file = self.out)
                ix += 1

    def transpose(self, ficin, ficout):
        with open(ficin) as fin:
            with open(ficout, 'w') as fout:
                self.do_transpose(fin, fout)
    def do_transpose(self, fin, fout):
        self.fin = fin
        self.out = fout
        self._skip_preamble()
        self._do_loop()

rawDescription: Python - CSV time oriented Transposing large number of columns to rows


code:
f(arg1=var1, arg2=var2, arg3=var3)
f(arg1=var4, arg2=var5, arg3=var6)

rawDescription: How can you output a varying argument in Python?

description: Output a varying argument in Python


code: names = db.select('todo', what='name')

rawDescription: Web.py SQL queries giving odd data

description: Web.py SQL queries giving odd data


code: [int("4"*i + "0"*(n-i)) for n in range(0,31) for i in range(1,n+1)]

rawDescription: How to generate numbers based on a pattern in python

description: Generate numbers based on a pattern in python


code:
while running == 2:
    pygame.display.flip()
    for event in pygame.event.get():
        ...
    for frame in tmpcache:
        screen.blit(test, (0,0))
        screen.blit(frame, (currentchar.posx, currentchar.posy))
        pygame.display.flip()
        clock.tick(charfps)

rawDescription: Pygame keyboard input event lag

description: Pygame keyboard input event lag


code: df_total_data[df_total_data.apply(lambda x: 'secure' not in  x['BBBlink'],1 ).values]

rawDescription: Selection of rows by condition

description: Selection of rows by condition


rawDescription: Expanding mean over multiple series in pandas


code:
sorted(lst, reverse=True)
sorted(lst, key=str.lower, reverse=True)

rawDescription: Python data structure sort list alphabetically


code:
import re
with open('weather.txt') as weather_file:
    data = re.findall(r'Heat Index.*?(\d+).*?(\d+).*?', weather_file.read())
data = [map(int, row) for row in data]

rawDescription: Parsing simple weather data

description: Parsing simple weather data


code:
import math
import collections

string = "AABC"

chars = collections.Counter(string)
denominator = reduce(lambda x,y: x * math.factorial(y), chars.values(), 1)
count = math.factorial(len(string)) / denominator
print(count)

rawDescription: Calculate the number of unique strings that can be made from a string


code:
a = df.values
a.sort(axis=1)  # no ascending argument
a = a[:, ::-1]  # so reverse
a
pd.DataFrame(a, df.index, df.columns)

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


code: [x for x in (x for x in range(5) if x != 2) if x != 3]

rawDescription: Python LIST functions not returning new lists


code: pd.concat([ df.reindex(index=df.index-df2.index-df3.index), df2, df3]).reindex_like(df)

rawDescription: Fastest way to copy columns from one DataFrame to another using pandas?


code:
def find_char(string, char):
    start_index = 0
    while True:
        yield string.lower().find(char, start_index)  # checks for the char in the string
        start_index += 1  # increments the index to find further in the word,
        # eg:
        # Bob constructed[index 0]
        # ob constructed[index 1]
        # b constructed[index 2]

def find_it(friends, message):
    friends = friends.split()
    for friend in friends:
        sequence_check = []
        for char in friend.lower():
            gen = find_char(message, char)  # creates the find_char generator
            for _ in message:  # limits the search to the length of the word
                char_index = next(gen) # try to find the index
                if char_index not in sequence_check: # if not in the sequence
                    sequence_check.append(char_index) # add it to it
                    break
        if -1 in sequence_check: # this check if every character of the name is in the word
            continue
        if sorted(sequence_check) == sequence_check: # this part check if it's in a sequence.
            print (friend + ' could have written ' + message)

find_it('James Nicky Jake', "join and make enough cash today!")
find_it('Fred Bill Sue Simone', "Should you make tea?")
find_it("Bob", "Bob constructed Balloon Town")

rawDescription: Python - Check if letter appears in consecutive words


code:
#!python3

import re
import xml.etree.ElementTree as ET

rex = re.compile(r'''(?P<title>Longitude
                       |Latitude
                       |date&time
                       |gsm\s+cell\s+id
                       |Neighboring\s+List-\s+Lac\s+:\s+Cid\s+:\s+RSSI
                     )
                     \s*:?\s*
                     (?P<value>.*)
                     ''', re.VERBOSE)

root = ET.Element('root')
root.text = '\n'    # newline before the celldata element

with open('cell.txt') as f:
    celldata = ET.SubElement(root, 'celldata')
    celldata.text = '\n'    # newline before the collected element
    celldata.tail = '\n\n'  # empty line after the celldata element
    for line in f:
        # Empty line starts new celldata element (hack style, uggly)
        if line.isspace():
            celldata = ET.SubElement(root, 'celldata')
            celldata.text = '\n'
            celldata.tail = '\n\n'
        else:
            # If the line contains the wanted data, process it.
            m = rex.search(line)
            if m:
                # Fix some problems with the title as it will be used
                # as the tag name.
                title = m.group('title')
                title = title.replace('&', '')
                title = title.replace(' ', '')

                if line.startswith('Neighboring'):
                    neighbours = ET.SubElement(celldata, 'neighbours')
                    neighbours.text = '\n'
                    neighbours.tail = '\n'
                else:
                    e = ET.SubElement(celldata, title.lower())
                    e.text = m.group('value')
                    e.tail = '\n'
            else:
                # This is the neighbour item. Split it by colon,
                # and set the attributes of the item element.
                item = ET.SubElement(neighbours, 'item')
                item.tail = '\n'

                lac, cid, rssi = (a.strip() for a in line.split(':'))
                item.attrib['lac'] = lac
                item.attrib['cid'] = cid
                item.attrib['rssi'] = rssi.split()[0] # dBm removed

# Include the root element to the tree and write the tree
# to the file.
tree = ET.ElementTree(root)
tree.write('cell.xml', encoding='utf-8', xml_declaration=True)

rawDescription: How to convert .txt file into xml file using python?

description: Convert .txt file into xml file using python


code:
def some_view(request):
    if request.method == 'POST':
        some_id = 1

        form = SomeForm(data=request.POST, some_id=some_id)

rawDescription: How to access id in modelform validation?

description: Access id in modelform validation


code:
test = a[0].split()
result = [test[0], " ".join(test[1:-1]), test[-1]]

rawDescription: How to separate the first and last part of a string in a list

description: Separate the first and last part of a string in a list


code:
with open('bigfile_1') as bf1:
    with open('bigfile_2') as bf2:
        for line1, line2 in zip(bf1, bf2):
            process(line1, line2)

rawDescription: Iterate over the lines of two files simultaneously


code:
m = mmap.mmap(f.fileno(), access=mmap.ACCESS_WRITE)
m[start:end-deleted_line_size] = m[start+deleted_line_size:end]
m.close()
f.seek(end-deleted_line_size)
f.truncate()

rawDescription: How to make a buffered writer?

description: Make a buffered writer


code:
import multiprocessing
import time

# Code that you want to execute then later execute

time.sleep(2)
t=multiprocessing.Process(target=send_p)
t.start()
time.sleep(100) # "Some interval of time"
if t.is_alive():
    t.terminate() # Kill it with fire! or SIGTERM on linux

rawDescription: How to stop a timer thread

description: Stop a timer thread


code:
def makeMap(d):
    return dict([[x, [y for y in d.keys() if x in d[y]]]
                 for x in set([x for x in chain.from_iterable(d.values())])
                 ])

rawDescription: Acess the dictionary being created inside dictionary comprehension


code:
remove_n_smallest(lst, 2)
lst
sum(lst) / len(lst)

rawDescription: Removing the lowest numbers from a list

description: Removing the lowest numbers from a list


code:
#!/usr/bin/env python

from ncclient import manager
from ncclient.xml_ import *

brcd_new_ele = lambda tag, ns, attrs={}, **extra: ET.Element(qualify(tag, ns), attrs, **extra)
brcd_sub_ele = lambda parent, tag, ns, attrs={}, **extra: ET.SubElement(parent, qualify(tag, ns), attrs, **extra)

BROCADE_1_0 = "http://brocade.com/ns/netconf/config/netiron-config/"
register_namespace('brcd', BROCADE_1_0)

@staticmethod
def brcd_build(capabilities):
    hello = brcd_new_ele("hello", None, {'xmlns':"urn:ietf:params:xml:ns:netconf:base:1.0"})
    caps = brcd_sub_ele(hello, "capabilities", None)
    def fun(uri): brcd_sub_ele(caps, "capability", None).text = uri
    map(fun, capabilities)
    return to_xml(hello)

def brcd_build_filter(spec, capcheck=None):
    type = None
    if isinstance(spec, tuple):
        type, criteria = spec
        # brocades want the netconf prefix on subtree filter attribute
        rep = new_ele("filter", {'nc:type':type})
        if type == "xpath":
            rep.attrib["select"] = criteria
        elif type == "subtree":
            rep.append(to_ele(criteria))
        else:
            raise OperationError("Invalid filter type")
    else:
        rep = validated_element(spec, ("filter", qualify("filter")),
                                attrs=("type",))
    if type == "xpath" and capcheck is not None:
        capcheck(":xpath")
    return rep

manager.transport.session.HelloHandler.build = brcd_build
manager.operations.util.build_filter = brcd_build_filter

rawDescription: How to override stuff in a package at runtime?

description: Override stuff in a package at runtime


code: combinations = itertools.product(nucleotides, repeat=i)

rawDescription: Generate all combinations of nucleotide k-mers between range(i, j)


code:
tree, id_map = ET.XMLID('''<class id="1" name="good/bad">
    <verb>
        <token>like</token>
        <token>feel</token>
    </verb>
    <mess>This is <sugg>not</sugg> text</mess>
    <id type="incorrect">I'm glad to <marker>unsee you</marker>.</id>
    <id type="correct">I'm glad to see you.</id>
</class>''')
elems = id_map['1'].find('verb')
verbs = [verb.text for verb in elems]

rawDescription: How to extract text from tags using ElementTree

description: Extract text from tags using ElementTree


code:
seen=set()
[e for e in A+B if e not in seen and (seen.add(e) or True)]

rawDescription: Python: Intersection of two lists of lists


code:
class C:
    foo = 42

i = C()
print(i.foo)  # 42

rawDescription: How are Python Class attributes different from PHP static class properties?


rawDescription: Scale the real part of complex numpy array


code: np.argmax((a == 1).sum(axis=0))

rawDescription: How can i do this numpy array operation in an efficient manner?

description: Do this numpy array operation in an efficient manner


code:
import os
if not os.environ.has_key('SILENT_MODE'):
    import Tkinter
    import tkMessageBox

    warningWindow = Tkinter.Tk()
    warningWindow.withdraw()
    tkMessageBox.showwarning("WARNING", "blah, blah, blah")

    warningWindow.destroy()

rawDescription: How to disable Tkinter dialogs while running in batch mode

description: Disable Tkinter dialogs while running in batch mode