code:
from Tkinter import *
from tkFileDialog import askopenfile, asksaveasfile

class App(object):

    def __init__(self, root):
        self.lbl1 = Label(root, text="Type")
        self.lbl1.pack(side=LEFT)

        self.txt1 = Text(root, borderwidth=3, relief="sunken", height=4, width=55)
        self.txt1.config(font=("consolas", 12), undo=True, wrap='word')
        self.txt1.pack(side=LEFT, expand=1, fill=BOTH)

        scrollb1 = Scrollbar(root, command=self.txt1.yview)
        scrollb1.pack(side=LEFT, fill=BOTH)
        self.txt1['yscrollcommand'] = scrollb1.set

    def open_file(self):
        f = askopenfile(defaultextension=".txt", filetypes=[("All Types", ".*")])
        if not f:
            return
        self.txt1.delete(1.0, END)
        self.txt1.insert(END, f.read())
        f.close()

    def file_save(self):
        f = asksaveasfile(mode='w', defaultextension=".txt")
        if not f:
            return
        f.write(self.txt1.get(1.0, END))
        f.close()

rawDescription: Tkinter not open and save text file

description: Tkinter not open and save text file


code:
row_type = namedtuple('row', [col.name for col in cursor.description])
for row in map(row_type._make, a):
    print(row.ID)

rawDescription: split database record into variables

description: Split database record into variables


code:
import random
import sys
color = [color for color in range(91, 97)]
with open(sys.argv[1], 'r') as f:
    for i in f:
        for w in i.rstrip().split(' '):
            if w.strip():
                print('\033[{0}m{1}\033[{0};m'
                      .format(random.choice(color), w), end='')
            print(' ', end='')
        print()

rawDescription: `.split()` how to save space more than one?


code:
from PyInstaller.building.build_main import Analysis, PYZ, EXE, COLLECT, BUNDLE, TOC

def collect_pkg_data(package, include_py_files=False, subdir=None):
    import os
    from PyInstaller.utils.hooks import get_package_paths, remove_prefix, PY_IGNORE_EXTENSIONS

    # Accept only strings as packages.
    if type(package) is not str:
        raise ValueError

    pkg_base, pkg_dir = get_package_paths(package)
    if subdir:
        pkg_dir = os.path.join(pkg_dir, subdir)
    # Walk through all file in the given package, looking for data files.
    data_toc = TOC()
    for dir_path, dir_names, files in os.walk(pkg_dir):
        for f in files:
            extension = os.path.splitext(f)[1]
            if include_py_files or (extension not in PY_IGNORE_EXTENSIONS):
                source_file = os.path.join(dir_path, f)
                dest_folder = remove_prefix(dir_path, os.path.dirname(pkg_base) + os.sep)
                dest_file = os.path.join(dest_folder, f)
                data_toc.append((dest_file, source_file, 'DATA'))

    return data_toc

pkg_data = collect_pkg_data('<YOUR LIB HERE>')

rawDescription: Pyinstaller Jinja2 TemplateNotFound

description: Pyinstaller Jinja2 TemplateNotFound


code:
def get_family_tree(person):
    """ return a family tree for a Person object """

    children = person.children.all()

    if not children:
        # this person has no children, recursion ends here
        return {'name': person.name, 'children': []}

    # this person has children, get every child's family tree
    return {
        'name': person.name,
        'children': [get_family_tree(child) for child in children],
    }

rawDescription: Recursively Collect Children in Python/Django


code:
listOfSets = [set([1, 4]), set([2, 4]), set([2, 3]), set([1, 3])]

def selfJoin(l) :
    ret = []
    for i, outer in enumerate(listOfSets):
        for inner in listOfSets[i + 1:]:
            inter = inner.intersection(outer)
            if len(inter) > 0 :
                ret.append(outer.union(inner))
    return ret

print(selfJoin(listOfSets))

rawDescription: Does Python have a relational join operator?


code:
from abc import ABCMeta, abstractmethod

class A(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def do_some_cool_stuff():
        ''' To override '''
        pass

    def do_some_boring_stuff():
        return 2 + 2

rawDescription: Is it possible in Python to declare that method must be overriden?


code:
for top_items in survival_gear:
    for individual_items in guessed_inventory_list:
        if individual_items == top_items:
            #finally the print statements below advise the user if they guessed an item and  which position it's in.
            print ("You have chosen wisely", top_items)
            print ("It's in position", t, "on the survival list")
    t = t + 1

rawDescription: comparing a list to a tuple, python 3.x - having problems getting the correct position to print

description: Comparing a list to a tuple, python 3.x - having problems getting the correct position to print


code: x, y = d.get('level0', None) or d.get('level1', None) or d.get('level2', None)

rawDescription: How do I get the first value from a list of keys in a concrete way in Python?

description: Get the first value from a list of keys in a concrete way in Python


code:
cur.execute("INSERT INTO Firstdb(First, Second) VALUES(%s, %s)", [
    self.t1.text, self.t2.text
])

rawDescription: Insert textbox value into python mysql databse


code: range(start, stop, jump)

rawDescription: python for loop

description: Python for loop


rawDescription: python json dumps

description: Python json dumps


code: numpy.rollaxis(t.reshape(3, 3, 3, 3), 2, 1)

rawDescription: Creating a 4D view on 2D array to divide it into cells of fixed size


code: sys.stderr = sys.stdout = logFile = open( tmpLogFileName, 'a' )

rawDescription: Ouput file redirection in Python

description: Ouput file redirection in Python


code: pd.Series(df.values[:, :-1].ravel())

rawDescription: How to select all data from Data Frame?

description: Select all data from Data Frame


rawDescription: How to extract parameters from a list and pass them to a function call

description: Extract parameters from a list and pass them to a function call


code: self.crumb = self._breadcrumb(self)

rawDescription: How can I handle dynamic calculated attributes in a model in Django?

description: Handle dynamic calculated attributes in a model in Django


code:
def f(): return f.x

f.x = 7
f()
g = f
g()
del f
g()

rawDescription: "self" inside plain function?

description: "self" inside plain function


code:
def class_factory(classname):
    base_class = getattr(tk, classname)

    class CustomClass(base_class):
        def __init__(self, parent, **kwargs):
            objparams, packparams = dispatch_parameters(self, **kwargs)
            base_class.__init__(self, parent, objparams)
            self.pack(packparams)

    CustomClass.__name__ = classname
    return CustomClass

rawDescription: Building class names from a list of strings


code:
test.unstack().reset_index(-1).groupby(0).apply(lambda x: x.level_1.tolist())

a    [0, 1]
b    [1, 0]
c    [2, 4]
d       [3]
e       [4]
k       [2]
n       [3]

rawDescription: groupby multiple value columns

description: Groupby multiple value columns


code:
[u"".join(li.xpath('.//text()').extract())
 for li in sel.xpath('//*[@id="tab_description"]/ul/li')]

rawDescription: Scrapy, receive just the text from an unordered list, including text between other html tags


code:
my_list = ['BLA1', 'BLA2', 'BLA3', 'ELE1', 'ELE2', 'ELE3', 'PRI1', 'PRI2', 'NEA1', 'NEA2', 'MAU1', 'MAU2', 'MAU3']
[list(group) for key, group in itertools.groupby(my_list, key=lambda v: v[:3])]

rawDescription: Python: New list grouping repeated elements from existing list


code:
@jit(nopython=True)
def loopMultJit_dot(Arr):
    ArrMult = np.empty(shape=Arr.shape[1:], dtype=Arr.dtype)
    for i in range(0, Arr.shape[1]):
        ArrMult[i] = Arr[0, i]
        for j in range(1, Arr.shape[0]):
            ArrMult[i] = dot(ArrMult[i], Arr[j, i])
    return ArrMult

@jit(nopython=True)
def loopMultJit_dotInternal(Arr):
    ArrMult = np.empty(shape=Arr.shape[1:], dtype=Arr.dtype)
    for i in range(0, Arr.shape[1]):
        ArrMult[i] = Arr[0, i]
        for j in range(1, Arr.shape[0]):
            s = 0.0
            for r1 in range(ArrMult.shape[1]):
                for c2 in range(Arr.shape[3]):
                    s = 0.0
                    for r2 in range(Arr.shape[2]):
                        s += ArrMult[i,r1,r2] * Arr[j,i,r2,c2]
                    ArrMult[i,r1,c2] = s
    return ArrMult

rawDescription: optimal numba implementations for matrix multiplication depends significantly on matrix size

description: Optimal numba implementations for matrix multiplication depends significantly on matrix size


code:
from collections import defaultdict
dd = defaultdict(list)
for key, value in ll:
    dd[key].append(value)

dd.items()

rawDescription: Join list of tuples using first element as key


code:
import ctypes

ctypes.windll.WINMM.mciSendStringW(u"set cdaudio door open", None, 0, None)

rawDescription: How to eject CD using WMI and Python?

description: Eject CD using WMI and Python


rawDescription: How can I find why is my pickled data so large?

description: Find why is my pickled data so large


rawDescription: Django REST Framework Specify Some Fields Before calling serializer.isValid()


code:
from django.contrib.gis.geos import MultiPolygon

list_poly = [reg.poly for reg in Region.objects.filter(criteria=criteria)]
multipolygon = MultiPolygon(list_poly)
list_examples = Example.objects.filter(point__within=multipolygon)

rawDescription: Finding models inside a set of Polygons in GeoDjango


rawDescription: Creating a slice object in python

description: Creating a slice object in python


code: data[labels == row]

rawDescription: Boolean indexing of 2D ndarray based on row comparison


code:
def new_pow(a,b):
    _a = Uncertain(a)
    _b = Uncertain(b)
    return _a ** _b

math.pow = new_pow

rawDescription: Difference between the built-in pow() and math.pow() for floats, in Python?


code:
handle = Entrez.efetch(db="gene",
                       id="10555",
                       retmode="xml")

rawDescription: Biopython Retrieving protein transcripts for a protein coding gene


code:
import binascii
import functools
import numpy as np

def hexint(b):
    return int(binascii.hexlify(b), 16)

def loop1(b):
    def f(x, y): return (x<<8)|y
    return functools.reduce(f, b, 0)

def loop2(b):
    x = 0
    for c in b:
        x <<= 8
        x |= c
    return x

def numpily(b):
    n = np.array(list(b))
    p = 1 << np.arange(len(b)-1, -1, -1, dtype=object)
    return np.sum(n * p)

rawDescription: Convert variable-sized byte array to a integer/long


code:
str = 'players 0 2 count:2 playerindex:0 playerid:a5:41:d2:cd:cd:05 ip:127.0.0.1:60488 name:127.0.0.1 model:softsqueeze displaytype:graphic-280x16 connected:1 playerindex:1 playerid:00:04:20:02:00:c8 ip:192.168.1.22:3483 name:Movy model:slimp3 displaytype:noritake-katakana connected:1'
regex = re.compile(r'([^:]+):(\S+)\s')
regex.findall(str)

rawDescription: Python reading tags in string, json?

description: Python reading tags in string, json


code:
from settings import *
ROOT_URLCONF='public_urls.py'

rawDescription: Django - per-domain URLConf?

description: Django - per-domain URLConf


code:
import trac.admin.console
import trac.config
import os

def _get_project_options(envdir):
    confpath = os.path.join(envdir, 'conf/trac.ini')
    config = trac.config.Configuration(confpath)
    return dict([x for x in config.options(u'project')])

def _get_project_name(envdir):
    admin = trac.admin.console.TracAdmin(envdir)
    if admin.env_check():
        options = _get_project_options(envdir)
        return options[u'name']
    else:
        return None

def iter_trac_projects_from_dir(dirname):
    for which in os.listdir(dirname):
        if not which in ('.', '..') and os.path.isdir(dirname):
            envdirname = os.path.join(dirname, which)
            project_name = _get_project_name(envdirname)
            if project_name:
                yield (project_name, envdirname)

def get_trac_projects_from_dir(dirname):
    return [pr for pr in iter_trac_projects_from_dir(dirname)]

rawDescription: Getting a listing of Trac projects in Python


code: ['mtdp', 'mtdq', 'mtdr', 'mtds', 'mtep', 'mteq', 'mter', 'mtes', 'mtfp', 'mtfq', 'mtfr', 'mtfs', 'mudp', 'mudq', 'mudr', 'muds', 'muep', 'mueq', 'muer', 'mues', 'mufp', 'mufq', 'mufr', 'mufs', 'mvdp', 'mvdq', 'mvdr', 'mvds', 'mvep', 'mveq', 'mver', 'mves', 'mvfp', 'mvfq', 'mvfr', 'mvfs', 'ntdp', 'ntdq', 'ntdr', 'ntds', 'ntep', 'nteq', 'nter', 'ntes', 'ntfp', 'ntfq', 'ntfr', 'ntfs', 'nudp', 'nudq', 'nudr', 'nuds', 'nuep', 'nueq', 'nuer', 'nues', 'nufp', 'nufq', 'nufr', 'nufs', 'nvdp', 'nvdq', 'nvdr', 'nvds', 'nvep', 'nveq', 'nver', 'nves', 'nvfp', 'nvfq', 'nvfr', 'nvfs', 'otdp', 'otdq', 'otdr', 'otds', 'otep', 'oteq', 'oter', 'otes', 'otfp', 'otfq', 'otfr', 'otfs', 'oudp', 'oudq', 'oudr', 'ouds', 'ouep', 'oueq', 'ouer', 'oues', 'oufp', 'oufq', 'oufr', 'oufs', 'ovdp', 'ovdq', 'ovdr', 'ovds', 'ovep', 'oveq', 'over', 'oves', 'ovfp', 'ovfq', 'ovfr', 'ovfs']

rawDescription: combination of words based on a list of list of characters

description: Combination of words based on a list of list of characters


code:
def make_ppend(n, lis):  # add lis as a parameter to be explicit, but you could rely on scope instead of adding this extra parameter
    if n.rest is not None:
        lis.append(n.first)
        make_ppend(n.rest, lis)

def ppend(n):
    lis = []  # now in the local scope
    make_ppend(n, lis)
    return lis

rawDescription: appending LinkedLists items to list using Recursion

description: Appending LinkedLists items to list using Recursion


code:
import tkinter
import tempfile

ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00'
    b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00'
    b'\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    b'\x00\x01\x00\x00\x00\x01') + b'\x00'*1282 + b'\xff'*64

_, ICON_PATH = tempfile.mkstemp()
with open(ICON_PATH, 'wb') as icon_file:
    icon_file.write(ICON)
tk = tkinter.Tk()
tk.title("rename")
tk.iconbitmap(default=ICON_PATH)
label = tkinter.Label(tk, text="Window with transparent icon.")
label.pack()
tk.mainloop()

rawDescription: Removing TK from Window Title Python tkinter


code: [ [x[0]] + [ y[1]*y[2] for y in x[1:] ] for x in orders ]

rawDescription: How can I rewrite this map() example using list comprehension?

description: Rewrite this map() example using list comprehension


rawDescription: Accessing individual elements of an encrypted list in python


code: yield from funB()

rawDescription: Python - is there any way to organize a group of yields in sub function to yield outside the main function?


code: numpy.where(mask, 1, numpy.where(numpy_array == 0, 0, 2))

rawDescription: Check if values in a set are in a numpy array in python


code:
# initialising primes
minPrime = 0
maxPrime = 1000
cached_primes = [i for i in range(minPrime,maxPrime) if isPrime(i)]

#elsewhere in the code
import random
n = random.choice([i for i in cached_primes if p<i<q])

rawDescription: Random prime Number in python

description: Random prime Number in python


code: df['since_last'] = df.groupby('id')['date'].apply( lambda x: x - x.shift() )

rawDescription: Python (Pandas) updating previous x rows within specified condition


rawDescription: deleting semicolons in a column of csv in python

description: Deleting semicolons in a column of csv in python


code:
for x in whatever():
    anobj.amethod(x)

rawDescription: Python performance characteristics

description: Python performance characteristics


code:
for pupil in dict1:
    highest = max(pupil["one"], pupil["two"], pupil["three"])
    print("StudentName", pupil["Name"], highest)

rawDescription: How to order a dictionary within a list by alphabetical order and highest number

description: Order a dictionary within a list by alphabetical order and highest number


code:
class A(object):
    def __init__(self, data=None):
        self.data = data

    def f(self, data):
        return self.__class__(data)

class B(A):
    pass

rawDescription: Inheritance and Slicing, making it the child type


code:
Matrix = [[ [0] for x in range(3)] for x in range(2)]
Matrix[0][1]+=[4,5]
Matrix

rawDescription: Append Numpy Array post Creation

description: Append Numpy Array post Creation


code:
def menu():
    ans = input("Please enter the number: ")
    if ans == '1':
        start(Ktest)
    else:
        start(Etest)

def start(choosen_func):
    number = input("Please choose. 1, 2 or 3: ")
    choosen_func(str(number))

def Ktest(arg):
    print("Ktest " + arg)

def Etest(arg):
    print("Etest " + arg)

menu()

rawDescription: Multiple arguments in parameter in def_name() and function's name as variable


code: unique=set(i for  i in permutations('AAAAAA'+'LL'))

rawDescription: Permutations of a string with two distinct characters (60 of one value and 20 of another)


code:
def generateTemplate(func, templateFile, name=None):
    template = open(templateFile, 'r')
    if name:
        code = func(template.read(), name)
    else:
        code = func(template.read())
    template.close()
    return code

rawDescription: function with another function as parameter

description: Function with another function as parameter


code:
class StreamingXMLParser(Protocol):
    def __init__(self):
        self.done = Deferred()

    def connectionMade(self):
        self._parser = make_parser()

    def dataReceived(self, bytes):
        self._parser.feed(bytes)

    def connectionLost(self, reason):
        self._parser.feed('', True)
        self.done.callback(None)

from twisted.web.client import Agent
from twisted.internet import reactor

agent = Agent(reactor)
d = agent.request('GET', url, headers, None)
def cbRequest(response):
    # You can look at the response headers here if you like.
    protocol = StreamingXMLParser()
    response.deliverBody(protocol)
    return protocol.done
d.addCallback(cbRequest) # d fires when the response is fully received and parsed

rawDescription: How do I fetch an XML document and parse it with Python twisted?

description: Fetch an XML document and parse it with Python twisted


code:
import sys
import os
import unittest
sys.path.append(os.path.dirname(__file__))

rawDescription: Python - organising code and test suite

description: Python - organising code and test suite


code:
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

weekly = map(sum, grouper(7, visitors, 0))

rawDescription: Find the sum of subsets of a list in python


code:
for idx, row in df.iterrows():
    for c in check:
        if c in row['A']:
            df.ix[idx, 'B'] = c

rawDescription: pandas: find partial string and use it in new columns

description: Pandas: find partial string and use it in new columns


code:
def modify_Person_to_be_friendly():
    # so that we're modifying the global identifier 'Person'
    global Person

    # now just redefine the class using type(), specifying that the new
    # class should inherit from Friendly and have all attributes from
    # our old Person class
    Person = type('Person', (Friendly,), dict(Person.__dict__))

def main():
    modify_Person_to_be_friendly()
    p = Person()
    p.hello()  # works!

rawDescription: How to dynamically change base class of instances at runtime?

description: Dynamically change base class of instances at runtime


code:
from collections import namedtuple
Lang = namedtuple("Lang", ("code", "name"))
langs = []
langs.append(Lang("xx", "unknown"))
langs[0]
langs[0].code
langs[0].name

rawDescription: Python: Add row to list with two columns?


code: return long("".join(l))

rawDescription: convert array of tuples to 2 dimensional array

description: Convert array of tuples to 2 dimensional array


code: e/e.sum(axis=1, keepdims=True)

rawDescription: numpy divide row by row sum

description: Numpy divide row by row sum


code:
import ast

def parse_params(s):
    root = ast.parse(s)
    expr = root.body[0]
    return process_node(expr.value)

def process_node(node):
    if isinstance(node, ast.Tuple):
        return tuple(map(process_node, node.elts))
    elif isinstance(node, ast.Name):
        return node.id
    else:
        raise ValueError("unsupported node type %r" % node)

rawDescription: Python convert String to Tuple for REST API


code: sorted(tuples, key=lambda t: t[-1])

rawDescription: Sorting Tuples in a descending order based on the last item given in the tuple


code:
import re
data = """Name: Machine_1 Status: On IP:10.0.0.1
Name: Machine_2 Status: On IP:10.0.0.2
Network_name: Private Router_name: router1 Router_ID=3568
Subnet: Tenant A"""
for line in data.split('\n'):
    ip = re.match('.*IP:(\d+.\d+.\d+.\d+)', line)
    rname = re.match('.*Router_name: (\w+)', line)
    if ip and ip.lastindex > 0:
        print(ip.group(1))
    if rname and rname.lastindex > 0:
        print(rname.group(1))

rawDescription: Extract data from a field in a text file in Python


code:
form_widget_args = {
    'description': {
        'rows': 100,
        'style': 'font-family:Consolas,Monaco,Lucida Console,Liberation Mono,DejaVu Sans Mono,Bitstream Vera Sans Mono,Courier New, monospace;'
    }
}

rawDescription: Flask Admin: TextArea with monospace font


rawDescription: How To apply a filter to a signal in python


code:
a = override()
override.context("value")
override.description()

rawDescription: How to return a value computed by overriding method from a subclass to it's base class method in python

description: Return a value computed by overriding method from a subclass to it's base class method in python


code:
def buildDTree(sofar, todo, sigma=None):
    if sigma is None:
        sigma = [[]]
    sal = []
    if not todo:
        return sigma, binaryTree(sofar)
    else:
        _, withelt = buildDTree(sofar + [todo[0]], todo[1:], sigma)
        _, withoutelt = buildDTree(sofar, todo[1:], sigma)
        here = binaryTree(sofar)
        here.setLeftBranch(withelt)
        here.setRightBranch(withoutelt)
        sal += here.getLeftBranch().getValue()
        sigma += [sal]
        return sigma, here

sigma, _ = buildDTree([], [1,2,3])

rawDescription: Python: Substituting for global variables


code: x = int(x) if x is not None else None

rawDescription: Semantic way to check if variable is None


code:
import tkinter

def run():
    root = tkinter.Tk()
    root.title("Window1")
    s_var = tkinter.StringVar()
    tkinter.Label(root, textvariable = s_var).pack()
    tkinter.Button(root, text = "Button", command = lambda: makewindow(root)).pack()
    s_var.set("Window #1")

def makewindow(root):
    top = tkinter.Toplevel(root)
    top.title("Window2")
    s_var = tkinter.StringVar()
    tkinter.Label(top, textvariable = s_var).pack()
    tkinter.Button(top, text = "Button", command = lambda: makewindow(root)).pack()
    s_var.set("Window #2")

if __name__ == "__main__":
    run()

rawDescription: window label is not printing : Python

description: Window label is not printing : Python


rawDescription: Sorting names containing numbers

description: Sorting names containing numbers


code:
def is_corner(lst, i, j):
    return i >= 0 and j > 0 and lst[i-1][j] == "bar" and lst[i][j-1] == "bar"

new_nested_list = [["bar" if is_corner(nested_list, i, j) else nested_list[i][j]
                    for j in range(WIDTH)]
                   for i in range(HEIGHT)]

rawDescription: How to correctly access elements of a nested list in python

description: Correctly access elements of a nested list in python


code:
from PyQt4 import QtGui
import sys
app = QtGui.QApplication(sys.argv)
QtGui.QImageReader.supportedImageFormats()

rawDescription: PyQt4 jpeg/jpg unsupported image format

description: PyQt4 jpeg/jpg unsupported image format


code:
import numpy as np
from pprint import pprint
from main_module import arrayholder

def calc(arrayholder):
    arrayholder['test_array'] = np.append(arrayholder['test_array'], [4])
    pprint(arrayholder['test_array'])

calc(arrayholder)
pprint(arrayholder['test_array'])

rawDescription: Can't append global NumPy array from other module


code:
from pylab import imshow, show, get_cmap
from numpy import random

Z = random.random((50,50))   # Test data

imshow(Z, cmap=get_cmap("Spectral"), interpolation='nearest')
show()

rawDescription: How can I use a pre-made color map for my heat map in matplotlib?

description: Use a pre-made color map for my heat map in matplotlib


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

answers = []
p = Popen([sys.executable or 'python', 'square.py'], stdin=PIPE, stdout=PIPE,
          bufsize=1)
for c in [b'2', b'7', b'1']:
    p.stdin.write(c + b'\n')
    p.stdin.flush()
    answers.append(int(p.stdout.readline()))
    print(answers)
p.communicate() # close pipes, wait for child to finish
print(answers)

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


code:
e = list(enumerate(l))
e
list(e)
list(e)

rawDescription: Enumerate function

description: Enumerate function


code:
import numpy.ma.mrecords as mrecords

X = np.rec.fromarrays([Ynan, (Ynan+100).astype(np.int)], names='g,h')
Z = np.ma.array(X, mask=np.isnan(Ynan))
Z2 = Z.view(mrecords.mrecarray)

Z2

Z2['h']

rawDescription: reassigning expanded recarray field

description: Reassigning expanded recarray field


code:
def test(phrase, filename):
    phrase = phrase.strip()
    with open(filename, 'r') as f:
        text = f.read()
    if phrase in text:
        return 'Y'
    else:
        return 'N'

rawDescription: Python3: Finding a phrase (string) in a file


rawDescription: Converting list of tuples in functional way


code:
outer = lambda *outer: lambda *inner: tuple(a + b for a, b in zip(outer, inner))
inner = func(1, 2, 3)
inner(2, 3, 4)
inner = outer(1, 2, 3, 4)
inner(4, 5, 6, 7)

rawDescription: How can I supply two arbitrary number of arguments to a lambda expression in python?

description: Supply two arbitrary number of arguments to a lambda expression in python


code:
import ctypes
lib = ctypes.CDLL("libfoo.so.1.0")
names = (ctypes.c_char_p*4)()
names[0] = "NAME0"
names[1] = "NAME1"
names[2] = "NAME2"
names[3] = 0
lib.foo("whatever", names)

rawDescription: Problem in printing array of char pointer passing from Python


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


code:
lst = [
  {u'self': u'https://jr.com/Option/134', u'id': u'134', u'value': u'AI'},
  {u'self': u'https://jr.com/Option/135', u'id': u'135', u'value': u'E'}
]
values = ','.join(item['value'] for item in lst)
values

rawDescription: Python: comma-delimited list from a list of sets


code:
"""Replaces template placeholder with values.

:param timestamp: formatted date to display
:type timestamp: str or unicode
:param priority: priority number
:type priority: str or unicode
:param priority_name: priority name
:type priority_name: str or unicode
:param message: message to display
:type message: str or unicode
:returns: formatted string
:rtype: str or unicode
"""

rawDescription: Using javadoc for Python documentation

description: Using javadoc for Python documentation


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

#-- Set axis spines at 0
for spine in ['left', 'bottom']:
    ax.spines[spine].set_position('zero')

# Hide the other spines...
for spine in ['right', 'top']:
    ax.spines[spine].set_color('none')

#-- Decorate the spins
arrow_length = 20 # In points

# X-axis arrow
ax.annotate('', xy=(1, 0), xycoords=('axes fraction', 'data'),
            xytext=(arrow_length, 0), textcoords='offset points',
            arrowprops=dict(arrowstyle='<|-', fc='black'))

# Y-axis arrow
ax.annotate('', xy=(0, 1), xycoords=('data', 'axes fraction'),
            xytext=(0, arrow_length), textcoords='offset points',
            arrowprops=dict(arrowstyle='<|-', fc='black'))

#-- Plot
ax.axis([-4, 10, -4, 10])
ax.grid()

plt.show()

rawDescription: how to move axes labels to near the arrows in matplotlib

description: Move axes labels to near the arrows in matplotlib


code:
ind=(slice(2,None),slice(None,2))
Mat[ind]
Mat[ind] += sub   # duplicate the sub values
Mat

rawDescription: numpy ndarray indexing - retrieving indexes from tuple

description: Numpy ndarray indexing - retrieving indexes from tuple


code:
actor = ActorFactory()
actor.save()

rawDescription: Django REST Framework: how to properly use the HyperlinkedModelSerializer url field in unit tests


code:
for i in range (0, 4):
      localdevice = cmd("some command create name ARRAY_456_%d" % i)

rawDescription: Would I be able to run a cmd python command with a name that is generated by a list?


code:
import csv
RESULT = ['apple','cherry','orange','pineapple','strawberry']
resultFile = open("output.csv",'wb')
wr = csv.writer(resultFile, dialect='excel')
wr.writerow(RESULT)

rawDescription: Writing List of Strings to Excel CSV File in Python


code:
class youModelAdminClass(admin.ModelAdmin):

     list_filter = [ExpiryDateFilter]
     list_display = ['CustomerValidity']

rawDescription: django SimpleListFilter

description: Django SimpleListFilter


code:
members = ['Alice', 'Bob']
cursor.execute('CREATE TEMP TABLE tmp_members (member CHAR(255)) ON COMMIT DROP;')
cursor.executemany('INSERT INTO tmp_members VALUES (%s);',
    [(name,) for name in members])

rawDescription: How do I create a one-column SQL table from an input list/array?

description: Create a one-column SQL table from an input list/array


rawDescription: Dynamic Python Array Slicing

description: Dynamic Python Array Slicing


code:
@app.route('/uploads/<new_folder_name>/<filename>')
def uploaded_file(filename, new_folder_name):
    if '/' in filename or '\\' in filename:
        abort(404)
    return send_from_directory(
        os.join(app.config['UPLOAD_FOLDER'], new_folder_name), filename)

rawDescription: Flask - fetching files from a subdirectory of main upload folder


rawDescription: change string during pyparsing

description: Change string during pyparsing


code:
with open('foo.txt', 'r') as f, open('bar.txt', 'r') as f2:
    pass    # do stuff here

rawDescription: Can I use with statements in python with a list?

description: Use with statements in python with a list


code:
class A (object):
    def __init__ (self):
        super().__init__()
        print('A')

class B (A):
    def __init__ (self):
        super().__init__()
        print('B')

class C (A):
    def __init__ (self):
        super().__init__()
        print('C')

class D (C, B):
    def __init__ (self):
        super().__init__()
        print('D')

rawDescription: Difference between super() and calling directly


code:
from key_value import KeyValue

rdd = sc.parallelize(
    [KeyValue("foo", 1), KeyValue("foo", 2), KeyValue("bar", 0)])

rdd.reduceByKey(add).collect()
## [('bar', 0), ('foo', 3)]

rawDescription: How to determine if object is a valid key-value pair in PySpark

description: Determine if object is a valid key-value pair in PySpark


rawDescription: Python list to nested keys

description: Python list to nested keys


code:
def add_element(root, path, data):
    reduce(lambda x, y: x[y], path[:-1], root)[path[-1]] = data

rawDescription: How do I build a tree dynamically in Python

description: Build a tree dynamically in Python


rawDescription: How to not display script name when looping on command line argument?

description: Not display script name when looping on command line argument


code:
import csv
with open('bytewrite.csv', 'w', encoding='iso-8859-1', newline='') as csvfile:
    a = b'\x8b'
    b = a.decode("iso-8859-1")
    w = csv.writer(csvfile)
    w.writerow([b])

rawDescription: Write bytes literal with undefined character to CSV file (Python 3)


code:
import pandas as pd
import numpy as np
np.random.seed(2016)
columns = pd.MultiIndex.from_product([['A', 'B'], ['a', 'b', 'c'], ['x', 'y', 'z']])
df = pd.DataFrame(np.random.randint(10, size=(7, 18)), columns=columns)

idx = pd.IndexSlice
x = df.loc[:,idx[:,:,'x']]
y = df.loc[:,idx[:,:,'y']]
z = df.loc[:,idx[:,:,'z']].values
result = pd.concat([x-z, y-z], axis=1)
result = result.rename(columns={'x':'x-z', 'y':'y-z'})

rawDescription: Subtract same column multi index for each level


code: print(my_dict['v3']) # outputs d

rawDescription: Save for loop result in variable

description: Save for loop result in variable


code:
r <= x <= cols-1-r
r <= y <= rows-1-r # Assuming 0-indexing

rawDescription: OpenCV Python HoughCircles: Circles detected outside of image boundary


code:
def tupleToDict(listOfList):
    yield getItems(listofList)
    for nestedList in listOfList:
        for el in getAllNestedItems(nestedList):
            yield el

rawDescription: How can I return values in a recursive function without stopping the recursion?

description: Return values in a recursive function without stopping the recursion


code:
import cgi
cgi.escape("""<hello "spam" & 'egg'>'""")

rawDescription: xml excape form a python dictionary

description: Xml excape form a python dictionary


rawDescription: how to create a transparent rectangle responding to click event in Tkinter

description: Create a transparent rectangle responding to click event in Tkinter


code:
def my_fn(a, b, c):
    return (a | b) ^ c

print(my_fn(a, b, c))     # => {1, 2, 5, 6}

rawDescription: Possible to pass set operators (operation) as a string argument to a function?


code: {keys: 0 for keys in itertools.combinations(items, 2)}

rawDescription: Dictionary whose key is independent on the order of elements it contains


code:
# MERGING DATA FRAMES
merge_df = pd.merge(predict_df, seasonal_component[['Month', 'SeasonalComponent']],
                    on=['Month'], how='outer')

# ADDING COLUMNS
merge_df['Prediction'] = merge_df['Prediction'] + merge_df['SeasonalComponent']

rawDescription: Python/Pandas - Sum dataframe items if indexes have the same month


code:
from functools import total_ordering
@total_ordering
class ReversedOrder:
    def __init__(self, value):
        self.value = value
    def __eq__(self, other):
        return other.value == self.value
    def __lt__(self, other):
        return other.value < self.value

rawDescription: How to write Python sort key functions for descending values

description: Write Python sort key functions for descending values


code:
def initUI(self):
    ...
    self.timer.start(next_qt_hour)
    ...

def Time(self):
    if int(strftime("%M")) % 15 == 0:
        self.timer.setInterval(900000)
    self.lcd.display(strftime("%M"))

rawDescription: Update QWidget every minutes

description: Update QWidget every minutes


code:
import uuid
u = uuid.uuid4()
u

rawDescription: How to generate random numbers that are unique forever in python

description: Generate random numbers that are unique forever in python


rawDescription: How do you perform basic joins of two RDD tables in Spark using Python?

description: Perform basic joins of two RDD tables in Spark using Python


code: df1 = df1.merge(df2, on='Country_Name', how='left')

rawDescription: Add a category column to a pandas dataframe from an existing list of categories


code: thisHeader = getHeader('csvfile.csv')

rawDescription: Python - Using encapsulation/functions to modify a variable and pass it to the current namespace


code:
unset_op = dict(izip_longest(set(document.keys()).difference(fields), [''], fill_value=''))
collection.update_one({'_id': document['_id']}, {'$unset': unset_op})

rawDescription: How to unset all fields except some known fields?

description: Unset all fields except some known fields


code:
soup('div', text='John')
import re
soup('div', text=re.compile('Jo'))

rawDescription: Equivelant of contains() selector in BeautifulSoup/Python


code:
import libxml2
doc = libxml2.parseFile('input.html')

rawDescription: python libXML2 remove Item

description: Python libXML2 remove Item


code:
d = {"Name": "foo","Pay_date" : 50,"Hours": 40}

import csv
with open('Emp schedule.csv','a') as schedule:
   writer= csv.DictWriter(schedule,d,delimiter ="|")
   writer.writeheader() # write header
   writer.writerow(d) # write values
#

rawDescription: How to write text to an output file in a structured, organize manner

description: Write text to an output file in a structured, organize manner


rawDescription: Insert tree kind of data taken from a database into a python dictionary


code: value = re.findall(r"mxy\s*(.*?)\s*jpg", output)

rawDescription: python parse output and return certain value

description: Python parse output and return certain value


rawDescription: logarithmically spaced integers

description: Logarithmically spaced integers


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

check_call("perl script.pl /path/to/file1/ < input > output", shell=True)

rawDescription: Process a perl script within a python script


code: ' '.join('< {} {} >'.format(*items) for items in A_board)

rawDescription: manipulate python lists into string type i want

description: Manipulate python lists into string type i want


rawDescription: Convert single backslash to double backslash


code:
from collections import defaultdict

masterdict = defaultdict(lambda: defaultdict(int))

# or

from collections import Counter, defaultdict

masterdict = defaultdict(Counter)

rawDescription: Sub-dictionary erroneously repeated throughout dictionary?


code: form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data

rawDescription: Editing the Form in Django creates new instance


code: lstNew = [int(i) for i in lstNew]

rawDescription: List of numbers

description: List of numbers


rawDescription: What is the formal way to load numpy package?


code:
import somemodule

def NewFunction(param):

    a = ...
    b = ...

    return somemodule.MyCustomType(a, b)

rawDescription: namedTuples definition across multiple chained functions

description: NamedTuples definition across multiple chained functions


code:
def qname(prefix, element, map={'xml':'http://www.w3.org/XML/1998/namespace'}):
    return "{{{}}}{}".format(map[prefix], element)

rawDescription: How do I find an xml node that does not have an attribute

description: Find an xml node that does not have an attribute


rawDescription: Nested list sort python 3

description: Nested list sort python 3


code:
def result():
    return '<pre>{}</pre>'.format(json.dumps(data,
            indent=4, default=json_util.default))

rawDescription: jsonify/pretty-print JSON for Bottle

description: Jsonify/pretty-print JSON for Bottle


code:
string = "sdfsdfsdfsdfsdf" \
         "sdfsdfsdfsdfs"

rawDescription: Is there a clean way to write multi-lines strings in Python?


code:
result = []
for bar in baz:
    result.append(foo)

rawDescription: Understanding Python List Comprehension equivalent


code: return word.upper()

rawDescription: python functions for beginners

description: Python functions for beginners


code: print("download: " + ", ".join(down_url))

rawDescription: python string formatting from list with arbitrary item

description: Python string formatting from list with arbitrary item


code:
def inquisition(weapon1, weapon2, weapon3):
    print("Our weapons are {}, {} and {}".format(weapon1, weapon2, weapon3))

repeat(10, inquisition, "surprise", "fear", "ruthless efficiency")

rawDescription: Python, how to pass an argument to a function pointer parameter?


code:
m = (mat - mat.T) + np.diag(np.diag(mat))
m

rawDescription: Subtract transpose from a matrix but keep the original diagonal


code: common_keys = [k for k in dict1 if k in dict2]

rawDescription: Dictionaries in Python

description: Dictionaries in Python


code:
from pyramid.paster import get_app

app = get_app('testing.ini#main')
test_app = TestApp(app)

rawDescription: Writing doctests for pyramid web app which depend on settings in ini file


code:
from nose.tools import *

_globals = {'foo': None}

def setup():
    _globals['foo'] = 10

def teardown():
    _globals['foo'] = None

@with_setup(setup, teardown)
def test_foo_value():
    foo = _globals['foo']
    assert_equal(foo, 10)

rawDescription: How can I access variables set in the python nosetests setup function

description: Access variables set in the python nosetests setup function


code:
text = 'apples pairs bannanas'
matches = ['a', 'n', 'p']
#gives:
{'a': 3, 'p': 2, 'n': 1}

rawDescription: How to find occurrences of list of letters efficiently with NLTK in Python?

description: Find occurrences of list of letters efficiently with NLTK in Python


code:
from numpy import zeros

NUMBER_PARTICLES = 1000
BOX_LENGTH = 100
CUT_OFF_ENERGY = 1
CUT_OFF_RADIUS_SQUARED = 100

def computeForceVector(currentPositions):
    potentialEnergy = 0
    force = zeros((NUMBER_PARTICLES, 3))
    for iParticle in range(0, NUMBER_PARTICLES - 1):
        positionsJ =  currentPositions[iParticle + 1:, :]
        distance = currentPositions[iParticle, :] - positionsJ
        distance = distance - BOX_LENGTH * (distance / BOX_LENGTH).round()
        distanceSquared = (distance**2).sum(axis=1)
        ind = distanceSquared < CUT_OFF_RADIUS_SQUARED

        if ind.any():
            r2i = 1. / distanceSquared[ind]
            r6i = r2i * r2i * r2i
            lennardJones = 48. * r2i * r6i * (r6i - 0.5)
            ljdist = lennardJones[:, None] * distance[ind, :]
            force[iParticle, :] += (ljdist).sum(axis=0)
            force[iParticle+1:, :][ind, :] -= ljdist
            potentialEnergy += (4.* r6i * (r6i - 1.) - CUT_OFF_ENERGY).sum()
    return (force, potentialEnergy)

rawDescription: improve nested loop performance

description: Improve nested loop performance


code:
#Create RR dataframep
rr = Nos/Responses
#Reset dataframe index
rr = rr.reset_index()
Responses = Responses.reset_index()
Nos = Nos.reset_index()

rawDescription: How to bin groupeby counts in pandas?

description: Bin groupeby counts in pandas


code:
cList1 = []
for line in f:
    cList1.append(line.rstrip('\n'))

rawDescription: readlines not reading the last line of the file in python

description: Readlines not reading the last line of the file in python


code: result = inputstring.split("'", 5)[-1].rsplit("'", 8)[0]

rawDescription: Get substring by parsing from both directions


code:
sql = '''
    SELECT buy, AVG(sell)
    FROM {t}
    WHERE (datetime > ? AND datetime < ?)
    GROUP BY strftime('%s', date)/(15*60)
    '''.format(t = currency)

rawDescription: Regroup time list in python from sql query


code: b = a[numpy.ix_(*s)]

rawDescription: Passing a list to numpy.ix_, or how to slice a multidimensional array, when number of dimensions and selection criteria are not known beforehand?


code:
while threads:
    try:
        for t in threads[:]: # enumerate threads
            t.join(.1) # timeout 0.1 seconds
            if not t.is_alive():
               threads.remove(t)
    except KeyboardInterrupt:
        break

rawDescription: Persistence of urllib.request connections to a HTTP server


code:
import pprint
import textwrap
import re

data=['DIR1/',['fileA','fileB','DIR3/',['fileE','fileF']],'DIR2/',['fileC','fileD']]
print(textwrap.dedent(re.sub(r"[\]\[',]", r' ',
                             pprint.pformat(data,indent=4,width=1))))

rawDescription: Python: output for recursively printing out files and folders


code: result = [w for w in vocab if len(w) >= 8]

rawDescription: Regular expression matching anything greater than eight letters in length, in Python


code:
#-*- encoding: utf8 -*-
from collections import defaultdict

INPUT = """you have requested a debate on this subject in the course of the next few days , during this part-session . {##} sus señorías han solicitado un debate sobre el tema para los próximos días , en el curso de este período de sesiones . {##} 0-0 0-1 1-2 2-3 3-4 4-5 5-6 6-7 7-8 8-9 12-10 13-11 14-11 15-12 16-13 17-14 9-15 10-16 11-17 18-18 17-19 19-21 20-22"""

if __name__ == "__main__":
    english, spanish, trans = INPUT.split(" {##} ")
    eng_words = english.split(' ')
    spa_words = spanish.split(' ')
    transtable = defaultdict(list)
    for e, s in [i.split('-') for i in trans.split(' ')]:
        transtable[eng_words[int(e)]].append(spa_words[int(s)])

    print(transtable['course'])
    print(transtable['you'])
    print(" ".join(transtable['course']))
    print(" ".join(transtable['you']))

rawDescription: How to extract matching strings into a defaultdict(set)? Python

description: Extract matching strings into a defaultdict(set)? Python


code:
class Group(db.Model):
    # ...
    toys = relationship('Toy',
        secondary="join(Group, Parent, Group.id == Parent.group_id).join(Child, Parent.id == Child.parent_id)",
        primaryjoin="and_(Group.id == Parent.group_id, Parent.id == Child.parent_id)",
        secondaryjoin="Child.id == Toy.child_id",
        viewonly=True,
    )

rawDescription: SQLAlchemy chaining association proxy for great grandchildren?


code: results += list(currentResults)

rawDescription: Add a list of lists to a list of lists with a list comprehension


code:
children = relationship("TreeNode", # NOTE: now each TreeNode has "children"
                    # ...
                    backref=backref("parent", remote_side=id), # this line allows children to link to "parent"
                    # ...
                )

rawDescription: How do you add a child node to a parent in an adjacency list in sqlalchemy?

description: Add a child node to a parent in an adjacency list in sqlalchemy


code:
import numpy as np

num_points = 500
U = np.random.random(num_points)
V = np.random.random(num_points)

import math as m

def spherical_to_cartesian(vec):
    '''
    Convert spherical polar coordinates to cartesian coordinates:

    See the definition of spherical_cartesian_to_polar.

    @param vec: A vector of the 3 polar coordinates (r, u, v)
    @return: (x, y, z)
    '''
    (r, u, v) = vec

    x = r * m.sin(u) * m.cos(v)
    y = r * m.sin(u) * m.sin(v)
    z = r * m.cos(u)

    return [x, y, z]

radius = 1.
points = np.array([spherical_to_cartesian([radius, 2 * np.pi * u, np.arccos(2*v - 1)]) for u,v in zip(U,V)])

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax = Axes3D(fig)

ax.plot(points[:,0], points[:,1], points[:,2], 'o')

rawDescription: how to generate new points as offset with gaussian distribution for some points in spherical coordinates in python

description: Generate new points as offset with gaussian distribution for some points in spherical coordinates in python


code:
for char in reversed(sequence):
    if char == end:
        endCount += 1
        if ( char != end): # always False because char == end
            break

rawDescription: Function does not work properly in for loop - Python


code:
import json  # simple json is better bit I didn't want to force an install
from collections import namedtuple
Point = namedtuple("Point", "x y", verbose = False)
p = Point(3,4)
json.dumps(p._asdict())
s = json.dumps(p._asdict())
json.loads(s)  # not there yet cause thisis a dict
Point(**json.loads(s))

rawDescription: String of namedtuples to list

description: String of namedtuples to list


rawDescription: PYTHON (Jython) how to get DATE TIME value in string - all before specific string?


code:
x = Devices()
x.devices = Devices({"name":"thom"})
x.devices.name

rawDescription: Python override dictionary access methods


code:
def make_dimnames(names):
    return [{n:i for i,n in enumerate(name)} for name in names]
def foo(d, *args):
    return [d[x] for x in args]

A = np.arange(9).reshape(3,3)
dimnames = [('x','y','z'),('a','b','c')]
Adims = make_dimnames(dimnames)
A[foo(Adims[0],'x','z'),foo(Adims[1],'b')]  # A[[0,2],[1]]
A[foo(Adims[0],'x','z'),slice(*foo(Adims[1],'b','c'))]  # A[[0,2],slice(1,2)]

rawDescription: python tensors with named field access

description: Python tensors with named field access


rawDescription: Why is list+set method of making a list unique faster than dictionary keys method?


code:
import unittest
import difflib

class MyTestCase(unittest.TestCase):
    def test_a(self):
        a = """hi
there
ok"""
        b = """bye
there
ok
whatever"""
        self.assertMultiLineEqual(a,b)

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

rawDescription: assertEqual only shows differences

description: AssertEqual only shows differences


code: "HERES THE DETAILED ERROR"

rawDescription: Get CDATA using xml.etree.ElementTree

description: Get CDATA using xml.etree.ElementTree


code:
from datetime import datetime
date_objects = [datetime.strptime(x,'%Y-%m-%d').date() for x in dates_filtered]

rawDescription: How do I perform math operations on dates and sort them in Python?

description: Perform math operations on dates and sort them in Python


code:
def statistics(it):
    """Returns number of elements, sum, max, min"""

    it = iter(it)

    x0 = next(it)
    maximum = minimum = total = x0
    n = 1

    for x in it:
        maximum = max(maximum, x)
        minimum = min(minimum, x)
        total += x
        n += 1

    return n, total, maximum, minimum

rawDescription: Computing stats on generators in single pass. Python


code:
results = [os.path.join(root, f)
               for root, dirs, files in os.walk(search_folder)
                   for f in files]

rawDescription: python sort on extension / Name of the file

description: Python sort on extension / Name of the file


rawDescription: Python: PyQt QTreeview example - selection


code:
from operator import attrgetter

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def get_attribute_value(obj, attr):
    return attrgetter(attr)(obj)

add.takes_args = True
add.number_of_args = 2
add.type_of_args = [int, int]
add.uses_black_magic = False

subtract.takes_args = True
subtract.number_of_args = 2
subtract.type_of_args = [int, int]
subtract.uses_black_magic = False

get_attribute_value.takes_args = True
get_attribute_value.number_of_args = 2
get_attribute_value.type_of_args = [object, str]
get_attribute_value.uses_black_magic = True

rawDescription: What method attributes are used in Django?


code:
sizeInKb = float(size) * 1024
est = float(sizeInKb) / float(speed)

rawDescription: Data and time conversion - PyMathematics


rawDescription: numpy, named columns

description: Numpy, named columns


code:
a = None
b = None

rawDescription: Unpack assignment vs chained assignment

description: Unpack assignment vs chained assignment


code:
cols = maximas[1][np.unique(maximas[0], return_index=True)[1]]
np.choose(cols, y.T)

rawDescription: Extracting required indices from the array of tuples


code:
section_bis[:] = 0
s

rawDescription: Slice numpy matrix using vectors as indices


code:
import string

exclude = string.punctuation
from tempfile import NamedTemporaryFile
from shutil import move

with open("test1") as tsvfile, NamedTemporaryFile(dir=".",delete=False) as t:
    tsvreader = csv.reader(tsvfile, delimiter="\t")
    temp = csv.writer(t,delimiter="\t")
    for row in tsvreader:
        row[4] = row[4].strip(exclude)
        temp.writerow(row)

move(t.name,"test1")

rawDescription: python how to read a tsv file, clean it and save as new file?

description: Python how to read a tsv file, clean it and save as new file


code:
#   dmg_max = round(
#                    ((STR + dmg_STR_add) * dmg_STR_mult)
#                  + ((AGI + dmg_AGI_add) * dmg_AGI_mult)
#                  + ((INT + dmg_INT_add) * dmg_INT_mult)
#                  ) * dmg_overall_mult
#             + dmg_overall_add

rawDescription: Safely parsing user defined equations in Python 3 without eval


code:
item ["country"] = loc_Con.select('text()').extract()
item ["region"] = loc_Reg.select('text()').extract()
item ["location"] = loc_Loc.select('text()').extract()

item ["country"] = item ["country"][0] if item ["country"] else ""
item ["region"] = item ["region"][0] if item ["region"] else ""
item ["location"] = item ["location"][0] if item ["location"] else ""

rawDescription: concatenating scraped data in scrapy

description: Concatenating scraped data in scrapy


code:
import re
from bs4 import BeautifulSoup

html = '''

'''

soup = BeautifulSoup(html)

for div in soup.find_all('div', {'data-text': re.compile(r'^bitcoin:')}):
    address, amount = div.get('data-text').replace('bitcoin:', '').split('?amount=')

rawDescription: Parsing bitcoin address in html

description: Parsing bitcoin address in html


code:
class MyFileDropTarget(wx.FileDropTarget):
    """"""
    def __init__(self, window):
        wx.FileDropTarget.__init__(self)
        self.window = window

    def OnDropFiles(self, x, y, filenames):
        self.window.notify(filenames)
#

rawDescription: Wxpython browse for or drag and drop folder


rawDescription: Pandas HDFStore of MultiIndex DataFrames: how to efficiently get all indexes


code:
class Player(object):
    # ... init code
    def __eq__(self, other):
        if isinstance(other, Player):
            # other object is a Player instance with the same identifier
            return self.identifier == other.identifier
        return False

rawDescription: Adding an object of one class to an object of another class and checking for duplicates in Python


rawDescription: Python: print unicode string stored as a variable


code:
from array import array

data = array('d')
CHUNKSIZE = 8192
rowcount = CHUNKSIZE / data.itemsize  # number of doubles we find in CHUNKSIZE bytes

with open('eigenvalues.bin', 'rb') as eg:
    data.fromfile(eg, rowcount)

rawDescription: Interpreting binary files as ASCII

description: Interpreting binary files as ASCII


code:
e = [['x'], [0, 1], [0, 1, 2]]
product(e)   # won't work
product(e[0], e[1], e[2])   # ok when e's length is exactly 3
product(*e)   # works for any e -> equivalent to product(e[0], e[1], ....)

rawDescription: Python specific format output with itertools.product


code: unique = df.drop_duplicates('field')

rawDescription: python pandas dataframe unique values appending 'L' to data values

description: Python pandas dataframe unique values appending 'L' to data values


code:
import re
[s for s in mylist if re.search(r'\b{}\b'.format(pattern),s)]

rawDescription: Python - Search a list item that contains a string (match case)


rawDescription: Define variables with the same list data but different objects using python


rawDescription: what is the equivalent of Matlab's typecast function in R / Python / Julia

description: What is the equivalent of Matlab's typecast function in R / Python / Julia


rawDescription: Dropping a single (sub-) column from a MultiIndex


rawDescription: Two-Digit dates in Python

description: Two-Digit dates in Python


code:
data = [{'id': id, 'usr': usr, 'pwd': pwd} for id,usr,pwd in
        zip(id_data_generator, usr_data_generator, pwd_data_generator)]

rawDescription: python post request json

description: Python post request json


code:
from django.contrib.auth.models import User

def unique_rand():
    while True:
        code = password = User.objects.make_random_password(length=8)
        if not Person.objects.filter(code=code).exists():
            return code

class Person(models.Model):
    code = models.CharField(max_length=8, unique=True, default=unique_rand)

rawDescription: Django unique random as a default value

description: Django unique random as a default value


code:
time = pd.date_range('9:00', '10:00', freq='1s')
data = np.cumsum(np.random.randn(time.size))

df = pd.DataFrame({'time' : time,
                   'data' : data})

rawDescription: Linear regression with panda time series


code:
import subprocess

def setAutomount(value):
    """
    @type value: boolean
    """
    cmd = ['gconftool-2', '--type', 'bool', '--set',
            '/apps/nautilus/preferences/media_automount']
    cmd.append(str(value).lower())
    subprocess.check_call(cmd)

setAutomount(False)

rawDescription: Disable GNOME's automount with Python

description: Disable GNOME's automount with Python


code: words=[x.rstrip() for x in line.split("\t")]

rawDescription: manipulating list items python

description: Manipulating list items python


code:
d={}
for node in macro:
    ...
    d[id_data]=cl_data

rawDescription: Python: Put values of variables into a new dictionary


code:
arg_list = [(user_in1, val1, flag1), ...]
result = {user_in: prev_def_func(val, flag) for user_in, val, flag in arg_list}

rawDescription: Unpack a list so the first element is assigned the result of a function operated on the following elements


code:
import re

def mergedgroupdict(pattern, thestring):
  there = re.compile(pattern)
  result = {}
  for mo in there.finditer(thestring):
    d = mo.groupdict()
    for k in d:
      if k not in result and d[k] is not None:
        result[k] = d[k]
  return result

rawDescription: Possible to retrieve an arbitrary unordered set of named groups in one swoop with Python's re module?


code:
tags = ['Good', 'Enjoy']
tags_dict = {}
for tag in tags:
    tags_dict['summary.tags.'+tag] = 1
db = pymongo.MongoClient().collection.summary
db.update_one({'_id': 1}, {'$inc': tags_dict })

rawDescription: update mongodb on fly

description: Update mongodb on fly


code:
import random
def rand_sequence(n_max):
    while True:
        next_random = random.randint(0, n_max)
        print(next_random)
        yield next_random

all(isPrime(x) for x in rand_sequence(20))

rawDescription: "exists" keyword in Python?

description: "exists" keyword in Python


code:
import datetime
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateFormatter, AutoDateLocator, date2num

x = [datetime.datetime.now() + datetime.timedelta(days=30*i) for i in range(20)]
y = np.random.random((20))

xtick_locator = AutoDateLocator()
xtick_formatter = AutoDateFormatter(xtick_locator)

for i in range(4):
    ax = plt.subplot(2,2,i+1)
    ax.xaxis.set_major_locator(xtick_locator)
    ax.xaxis.set_major_formatter(xtick_formatter)
    ax.plot(date2num(x),y)

plt.show()

rawDescription: Add date tickers to a matplotlib/python chart


code:
from itertools import chain
lst = ['a', 'pnp', 'a|pnp', 'lab2|pnp']
list(chain.from_iterable(x.partition('|') if '|' in x else [x] for x in lst))
list(chain.from_iterable(filter(None, x.partition('|'))  for x in lst))

rawDescription: How to split a character in list and must still exist in python?

description: Split a character in list and must still exist in python


code:
def equivalent(s1, s2):
    e1 = word_equivs.get(s1)
    e2 = word_equivs.get(s2)
    if e1 and e2:
        return e1 == e2
    else:
        return s1 == s2

rawDescription: a slightly different string equivalence function in python

description: A slightly different string equivalence function in python


code:
def application(environ, start_response):
    start_response('200 OK', [('content-type', 'text/html')])
    return ['Hello world!']

rawDescription: Beginner Python question about making a web app


code:
if __name__ == "__main__":
     ATM = Savingaccount()
     ATM.menu()

rawDescription: Banking ATM program

description: Banking ATM program


code:
arb = 4
dicts = {"dict_{}".format(i): {} for i in range(arb)}
print(dicts)

rawDescription: How to create an arbitrary number of dictionaries/lists (with different names) in python?

description: Create an arbitrary number of dictionaries/lists (with different names) in python


rawDescription: Converting a Pandas GroupBy object to DataFrame


code:
import time
interval = 0.2  # nr of seconds
while True:
    stop_looping = myAlertCheck()
    if stop_looping:
        break
    time.sleep(interval)

rawDescription: Python - Do (something) when event is near


rawDescription: Register Event callbacks with pywin32

description: Register Event callbacks with pywin32


code:
type(file)
type(open)

rawDescription: Why is open() preferable over file() in Python?


code:
def pick(*attrs):
    return {attr: getattr(x, attr) for attr in attrs}

subsets = [pick("a", "d") for x in someObjects]

rawDescription: How Can I Get a Subset of an Object's Properties as a Python Dictionary?


code: somevalue

rawDescription: Freezing Function Arguments

description: Freezing Function Arguments


code:
def per(l):
    if len(l) == 1:
        return [l]
    return [[l[i]] + p for i in range(len(l))for p in per(l[:i] + l [i+1:])]
per([2])
per([0,1,2])
per([0,1,2, 3])
len(per([0,1,2, 3]))

rawDescription: Permutations in python without libraries


code:
from sqlalchemy import MetaData, Table, Integer, Column, create_engine
engine = create_engine('sqlite://')
metadata = MetaData(bind=engine)
table = Table("Bookings", metadata,
    Column('id', Integer(), primary_key=True,),
    Column('value', Integer(),),
)
field = 'value'
table.c.get(field)
table.c[field]

rawDescription: SqlAlchemy Dynamic Where

description: SqlAlchemy Dynamic Where


code:
gzopen64
gz_open

rawDescription: Python C extension link with a custom shared library


code: df.groupby('case')['change'].apply(lambda x: x.shift(1) - x)

rawDescription: get previous row's value and calculate new column pandas python

description: Get previous row's value and calculate new column pandas python


code:
content = """Sep  1 09:27:46 hostname kernel: IPTables-Dropped: IN=eth0 OUT= MAC=00000 SRC=255.255.255.1 DST=10.0.0.1 LEN=56 TOS=0x00 PREC=0x00 TTL=10 ID=36829 DF PROTO=TCP SPT=490000 DPT=80 WINDOW=15500 RES=0x00 SYN URGP=0 MARK=0x32
Sep  1 09:27:47 hostname kernel: IPTables-Dropped: IN=eth0 OUT= MAC=00000 SRC=255.255.255.1 DST=10.0.0.1 LEN=56 TOS=0x00 PREC=0x00 TTL=10 ID=36830 DF PROTO=TCP SPT=490000 DPT=80 WINDOW=15500 RES=0x00 SYN URGP=0 MARK=0x32
Sep  1 09:27:47 hostname kernel: IPTables-Dropped: IN=eth0 OUT= MAC=00000 SRC=255.255.255.1 DST=10.0.0.1 LEN=56 TOS=0x00 PREC=0x00 TTL=10 ID=36830 DF PROTO=TCP SPT=490000 DPT=80 WINDOW=15500 RES=0x00 SYN URGP=0 MARK=0x32
Sep  1 09:27:47 hostname kernel: IPTables-Dropped: IN=eth0 OUT= MAC=00000 SRC=255.255.255.2 DST=10.0.0.1 LEN=56 TOS=0x00 PREC=0x00 TTL=10 ID=36830 DF PROTO=TCP SPT=490000 DPT=80 WINDOW=15500 RES=0x00 SYN URGP=0 MARK=0x32""".splitlines()
lstset = {l.split()[9].replace('SRC=','') for l in content}
print('\n'.join(lstset))

rawDescription: How to get the nth parameter of a list with delimiter space in python

description: Get the nth parameter of a list with delimiter space in python


code:
if last_key:
    sys.stdout.write("%s\t%s\n" % (last_key, tot_cnt))

rawDescription: How to get the Reducer to emit only duplicates

description: Get the Reducer to emit only duplicates


code:
#include <stdio.h>
setvbuf(stdout, NULL, _IOLBF, 0);

rawDescription: Getting another program's output as input on the fly


code:
def match(s, pat):
    try: return fnmatch.fnmatch(s, pat)
    except TypeError: return False

def sel(ds, pat):
    return [d[k] for d in ds for k in d if match(k, pat)]

def set(ds, k, v):
    for d in ds: d[k] = v

rawDescription: How to glob for iterable element

description: Glob for iterable element


code: foo(123, 456, name='Mike', is_valid=True)

rawDescription: How does CPython match variables to values?


code:
func_2 #0.5 seconds elapsed
func_2 #1.0 seconds elapsed
func_1 #1.5 seconds elapsed finally func_1 :)
func_2 #1.5 threading is not mutithreading! ;)
func_2 #2.0 seconds elapsed
func_2 #2.5 seconds elapsed and since variable i is 5 func_2 is no more :(
func_1 #3.0 seconds elapsed
func_1 #4.5 seconds elapsed
func_1 #6.0 seconds elapsed
func_1 #7.5 seconds elapsed

rawDescription: Two while loops at one?

description: Two while loops at one


code:
from fractions import Fraction
Fraction('nan')
Fraction(float('nan'))

rawDescription: Assigning a variable NaN in python without numpy


code:
urlpatterns += patterns('netadmin.plugins.ajax_view',
    url(r'^ajax/(?P<object_id>\d+)/$', 'ajax_render_data', name='ajax_render_data'),
)

rawDescription: How to use Django views and template tag simultanosly?

description: Use Django views and template tag simultanosly


code:
from matplotlib.dates import drange, num2date
date_dict = dict((d, len(list(g))) for d,g in itertools.groupby(list_of_dates, lambda k: k.date()))
dates = num2date(drange(min(list_of_dates).date(), max(list_of_dates).date() + timedelta(1), timedelta(1)))
counts = asarray([date_dict.get(d.date(), 0) for d in dates]).cumsum()
step(dates, counts)

rawDescription: Plotting a cumulative graph of python datetimes


code: d = pd.pivot_table(df,index=df.index, columns='Name', values='Activity').fillna(0)

rawDescription: Using pandas to plot data

description: Using pandas to plot data


code: iconPathName = os.path.abspath(os.path.join( sys.path[0], 'balloontip.ico' ))

rawDescription: Multiple WindowsBaloonTip / TrayTip Notifications?


code:
def search_by_entity_name(entity_name, entity_search_type='B'):
    return query({
        'ctl00$MainContent$CorpSearch':'rdoByEntityName',
        'ctl00$MainContent$txtEntityName': entity_name,
        'ctl00$MainContent$ddBeginsWithEntityName': entity_search_type,
    })

rawDescription: How to start a query from a static website?

description: Start a query from a static website


code:
from itertools import chain
from collections import Counter

data = [['a', 'b', 'c'], ['a'], ['a', 'b']]

d = Counter(chain.from_iterable(data))
print([i for i, c in d.most_common()])

rawDescription: Python: given a list of lists, create a list ordered by the number of occurrences in inner list


code:
for line in feed:
    lines = line.split('\n')

rawDescription: Counting lines, words, and characters within a text file using Python


code:
import itertools
lists = ["ABC","AC","CCCC","BC"]
position = map(''.join,itertools.izip_longest(*lists, fillvalue=''))

rawDescription: How to iterate through a list of strings with different lengths?

description: Iterate through a list of strings with different lengths


code:
from PyQt4.QtCore import QObject, pyqtSignal

class Foo(QObject):

    # This defines a signal called 'closed' that takes no arguments.
    closed = pyqtSignal()

    # This defines a signal called 'rangeChanged' that takes two
    # integer arguments.
    range_changed = pyqtSignal(int, int, name='rangeChanged')

    # This defines a signal called 'valueChanged' that has two overloads,
    # one that takes an integer argument and one that takes a QString
    # argument.  Note that because we use a string to specify the type of
    # the QString argument then this code will run under Python v2 and v3.
    valueChanged = pyqtSignal([int], ['QString'])

rawDescription: python qt4 - passing arguments in QtCore.QObject.connect

description: Python qt4 - passing arguments in QtCore.QObject.connect


rawDescription: Converting Sage symbolic Expression to string


code:
import os

os.system('{0}\\System32\\control.exe Inetcpl.cpl'.format(os.environ['WINDIR']))

# or

os.system('control.exe Inetcpl.cpl')

rawDescription: How to open Control Panel in python using win32 extension

description: Open Control Panel in python using win32 extension


code:
import pandas as pd
rng = pd.date_range('1/1/2011', periods=10000, freq='10S')
ts = pd.Series(np.random.randint(0, 5, len(rng)), index=rng)
ts

rawDescription: Count number of events per hour given in datetime/numpy


code:
dfQ1 = df[df.quarter == 1]
dfQ2 = df[df.quarter == 2]
dfQ3 = df[df.quarter == 3]
dfQ4 = df[df.quarter == 4]

rawDescription: How can I subset a data frame based on dates, when my dates column is not the index in Python?

description: Subset a data frame based on dates, when my dates column is not the index in Python


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

kets = ["|00>","|01>","|10>","|11>"] #my axis labels

fig = plt.figure()
ax1  = fig.add_subplot(111,projection = '3d')

xpos = [0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3]
xpos = [i+0.25 for i in xpos]
ypos = [0,1,2,3,0,1,2,3,0,1,2,3,0,1,2,3]
ypos = [i+0.25 for i in ypos]
zpos = [0]*16

dx    = 0.5*np.ones(16)
dy    = 0.5*np.ones(16)
dz    = [1,0,0,0,0,1,0,0,0,0,0,1,0,0,1,0]
dz2   = [0.2*i for i in dz] # to superimpose dz

ticksx = np.arange(0.5,4,1)
ticksy = np.arange(0.6,4,1)

# only change here:
# new loop, changed alphas and a color
for k in range(len(xpos)):
    ax1.bar3d(xpos[k], ypos[k], zpos[k], dx[k] , dy[k] ,dz[k],  color = '#ff0080', alpha = 0.3)
    ax1.bar3d(xpos[k], ypos[k], zpos[k], dx[k] , dy[k] ,dz2[k],  color = '#008080', alpha = 1)

ax1.w_xaxis.set_ticklabels(kets)
ax1.w_yaxis.set_ticklabels(kets)
ax1.set_zlabel('Coefficient')

plt.xticks(ticksx,kets)
plt.yticks(ticksy,kets)

plt.show()

rawDescription: Is it possible to superimpose 3-d bar charts in matplotlib?


code: for _ in range(10) : print (select())

rawDescription: How to randomly pick numbers from ranked groups in python, to create a list of specific length

description: Randomly pick numbers from ranked groups in python, to create a list of specific length


code:
def letter_to_index(letter):
    """Converts a column letter, e.g. "A", "B", "AA", "BC" etc. to a zero based
    column index.

    A becomes 0, B becomes 1, Z becomes 25, AA becomes 26 etc.

    Args:
        letter (str): The column index letter.
    Returns:
        The column index as an integer.
    """
    letter = letter.upper()
    result = 0

    for index, char in enumerate(reversed(letter)):
        # Get the ASCII number of the letter and subtract 64 so that A
        # corresponds to 1.
        num = ord(char) - 64

        # Multiply the number with 26 to the power of `index` to get the correct
        # value of the letter based on it's index in the string.
        final_num = (26 ** index) * num

        result += final_num

    # Subtract 1 from the result to make it zero-based before returning.
    return result - 1

rawDescription: Is it possible to get an Excel document's row count without loading the entire document into memory?


code:
# submit form
session.post(login_url, data={
    "_token": token,
    "pnr": PNR
})

rawDescription: Trouble with requests/Beautiful soup

description: Trouble with requests/Beautiful soup


code: T2 = [map(int, x) for x in T1]

rawDescription: How to convert strings into integers in python?

description: Convert strings into integers in python


code:
import re
regexp = re.compile('{(.*?)}')
keys = regexp.findall(expression)
keys
table_get = lambda *x: np.random.randint(5)
values = {k: table_get(k) for k in keys}
expression.format(**values)

rawDescription: Python compiled eval?

description: Python compiled eval


code: "/newdirectory/date/2011/2009-01-11 This is a file's path/file.MOV"

rawDescription: Fastest way to replace elements of a file's path and extension?


code:
#!/usr/bin/env python

from pprint import pprint

nList = [
    [[0, 0, 0], [3, 2, 1]],
    [[]],
    [[1, 1, 12]],
    [[0, 0, 0], [30000, 40, 3010], [32000, 40500, 7520], [0, 0, 10520]],
    [[15340, 0, 0], [104300, 0, 3630], [434000, 4434000, 63460]]
]

def calculate_length(x1, y1, x2, y2):
    return ((x1-x2)**2 + (y1 - y2)**2) ** 0.5

def calculate_time (t1,t2):
    return abs(t1-t2)

def lengths(trace):
    previous_x, previous_y = 0, 0
    for index, point in enumerate(trace):
        if point:
            x, y, t = point
            if index > 0:
                yield calculate_length(x, y, previous_x, previous_y)
            previous_x, previous_y = x, y

all_lengths_list = [list(lengths(trace)) for trace in nList]

pprint(all_lengths_list, indent=4)

rawDescription: How to store 'yield' generator result in a list in Python 2.7?

description: Store 'yield' generator result in a list in Python 2.7


code:
def record_click(click_type=None):
    """
    Save each click seen in a list
    """
    try:
        cache = record_click.cache
    except AttributeError:
        record_click.cache = []
    if click_type is not None:
        cache.append(click_type)
    return cache

def handle_click(channel, click_type, was_queued, time_diff):
    """
    Report each click, then record it for later
    """
    print(click_type)
    record_click(click_type)

cc.on_button_single_or_double_click_or_hold = handle_click

rawDescription: Get Value from a lambda

description: Get Value from a lambda


code:
variables = {}
for name, colour, shape in Applist:
    variables[name + "_n"] = name
    variables[name + "_c"] = colour
    variables[name + "_s"] = shape

rawDescription: Python List as variable name

description: Python List as variable name


rawDescription: Filtering through a list of Words (Python)


rawDescription: How to Print An Odd Number of Backslashes in Python


code:
for i in range(0, len(some_list)-1):
    elem = some_list[i]
    ...

rawDescription: How does this for loop know which list to sort through?


rawDescription: Create a Pandas dataframe with counts of items spanning a date range


code: fruit = re.compile(r'\b(?:%s)\b' % '|'.join(fruit_list))

rawDescription: how to do re.compile() with a list in python

description: Do re.compile() with a list in python


code:
((name, position, emp_id, tasks)
for name, position, emp_id in ListA
for position2, tasks in ListB
if position == position2)

rawDescription: Combine two lists based on a column

description: Combine two lists based on a column


code:
class Your_form(forms.ModelForm):
  field_integer = forms.IntegerField()
  field_boolean = forms.BooleanField()

  def __init__(self, *args, **kwargs):
    option = kwargs["option"]
    if option == "integer":
      field_boolean.widget = field_boolean.hidden_widget()
    else:
      field_integer.widget = field_integer.hidden_widget()
    super(Your_form, self).__init__(*args, **kwargs)

rawDescription: How to initialize django-form data type field from a given choices?

description: Initialize django-form data type field from a given choices


code: ARTICLE_ORDER_BY = 'filename'

rawDescription: How to sort articles by filename in pelican?

description: Sort articles by filename in pelican


code:
class TestMaker(type):
    def __new__(cls, clsname, bases, dct):
        # Add a method to the class' __dict__ for every key in
        # the petersen_prop dict.
        for prop in petersen_prop:
            dct['test_{}'.format(prop)] = cls.make_test(prop)

        return super(TestMaker, cls).__new__(cls, clsname, bases, dct)

    @staticmethod
    def make_test(prop):
        # test_wrap is the method body that will be used for each
        # test
        def test_wrap(self):
            func = getattr(myfuncs, prop)
            self.assertTrue(func(self.adj, **self.args) ==
                    petersen_prop[prop])
        return test_wrap

class PetersenGraph(unittest.TestCase):
   __metaclass__ = TestMaker

rawDescription: Unittest from a dictionary of functions and values


$regex: one|two|three

rawDescription: MongoDB: Transform PHP code to Python code


code:
text = "section,year,key,value\n"
for sectionName in myData:
    yearData = myData[sectionName]
    for year in yearData:
        keyValueDict = yearData[year]
        for key in keyValueDict:
            value = keyValueDict[key]
            text += sectionName + "," + year + "," + key + "," + str(value) + "\n"

rawDescription: How to save Multi-layered dictionary to csv

description: Save Multi-layered dictionary to csv


rawDescription: Custom Sorting Python Dictionary

description: Custom Sorting Python Dictionary


code:
text = "The quick brown fox jumps over the lazy dog. fox. Redfox."
links = {'fox': [], 'dog': []}
yield_words(text,links)

rawDescription: Positions of substrings in string

description: Positions of substrings in string


code:
s = "STRING 1 160 Some descriptor information. /Uselessstuff.; STRING 161 274 Some other descriptor information. /Moreuselessstuff.; STRING 275 1070 Last descriptor info. /Lastuselesspart."
m = re.findall(r'(\d+)\s(\d+)\s([^\.]*)', s)
m

rawDescription: Getting everything before a period using regex?


code:
from operator import setitem
[setitem(items_dict, x, to_string_and_select(x)) for x in we_need_this]

rawDescription: list comprehension with some equal action python

description: List comprehension with some equal action python


rawDescription: Selenium Webdriver is finding hidden values too


code:
import sqlite3
import csv
import sys
from itertools import islice
conn = sqlite3.connect('/tmp/ipaddresses.db')
conn.execute('CREATE TABLE IF NOT EXISTS ipaddress (domain, ip)')
conn.execute('''\
    CREATE UNIQUE INDEX IF NOT EXISTS domain_ip_idx
    ON ipaddress(domain, ip)''')
reader = csv.reader('''\
yahoo.com|89.45.3.5
bbc.com|45.67.33.2
yahoo.com|89.45.3.5
myname.com|45.67.33.2
'''.splitlines(), delimiter='|')
cursor = conn.cursor()
while True:
    with conn:
        batch = list(islice(reader, 10000))
        if not batch:
            break
        cursor.executemany(
            'INSERT OR IGNORE INTO ipaddress VALUES(?, ?)',
            batch)

conn.execute('CREATE INDEX IF NOT EXISTS ip_idx ON ipaddress(ip)')
writer = csv.writer(sys.stdout, delimiter='|')
cursor = conn.cursor()
cursor.execute('SELECT ip, domain from ipaddress order by ip')
writer.writerows(cursor)

rawDescription: How to parse files larger than 100GB in Python?

description: Parse files larger than 100GB in Python


rawDescription: Python iterating through pandas more efficiently without for loop


code: zeros = [ [0]*M for _ in xrange(N) ]

rawDescription: 2d array of zeros

description: 2d array of zeros


code: df['new_field'] = df['field2'].where(df['field1'] >0, 0)

rawDescription: Python pandas: banal apply statements incredibly slow


rawDescription: Why does using multiplication operator on list create list of pointers?


code: newBuf[i] ^= xorPad[(i + baseByteTableIndex) & 2047]

rawDescription: Can't reproduce working C bitwise encoding function in Python


code:
# first initialize dataframe
data_frame = pd.DataFrame(columns=['type', 'hash', 't0', 't1'], index=np.arange(10))

# this is now what would have to be inside the queue loop
data_dict = {'type': name, 'hash':md5hash,
             't0': times[0], 't1': times[1]}
name = "hlog"

data_series = pd.Series(data_dict)

data_frame.loc[0] = data_series
data_series[['t0', 't1']] += 0.5 # now I just quickly "fake" an additional loop to create more data
data_frame.loc[1] = data_series

rawDescription: Calculated column in pandas dataframe

description: Calculated column in pandas dataframe


code:
data_n=(data-data.min())/(data.max()-data.min())
img_array = plt.get_cmap('cubehelix')(data_n)

rawDescription: Issue creating map shading in Matplotlib imshow by setting opacity to data gradient


rawDescription: Formatting a table output to a file :: numpy python


code:
import numpy as np
import time

x_dim = 5000
y_dim = 5000
channels = 3

# base data
a = np.random.randint(1, 1000, (x_dim, y_dim, channels))
b = np.random.randint(0, channels, (x_dim, y_dim))

# meshgrid method (from here http://stackoverflow.com/a/27281566/377366 )
start_time = time.time()
i1, i0 = np.meshgrid(xrange(x_dim), xrange(y_dim), sparse=True)
c_by_meshgrid = a[i0, i1, b]
print('Meshgrid time: {}'.format(time.time() - start_time))

# indices method (this is the vectorized method that does what you want)
start_time = time.time()
b_indices = np.indices(b.shape)
c_by_indices = a[b_indices[0], b_indices[1], b[b_indices[0], b_indices[1]]]
print('Indices time: {}'.format(time.time() - start_time))

# loops method
start_time = time.time()
c_by_loops = np.zeros((x_dim, y_dim), np.intp)
for i in xrange(x_dim):
    for j in xrange(y_dim):
        c_by_loops[i, j] = a[i, j, b[i, j]]
print('Loops time: {}'.format(time.time() - start_time))

# confirm correctness
print('Meshgrid method matches loops: {}'.format(np.all(c_by_meshgrid == c_by_loops)))
print('Loop method matches loops: {}'.format(np.all(c_by_indices == c_by_loops)))

rawDescription: python, dimension subset of ndimage using indices stored in another image

description: Python, dimension subset of ndimage using indices stored in another image


code:
import itertools

def python2sort(x):
    it = iter(x)
    groups = [[next(it)]]
    for item in it:
        for group in groups:
            try:
                item < group[0]  # exception if not comparable
                group.append(item)
                break
            except TypeError:
                continue
        else:  # did not break, make new group
            groups.append([item])
    print(groups)  # for debugging
    return itertools.chain.from_iterable(sorted(group) for group in groups)

rawDescription: How can I get 2.x-like sorting behaviour in Python 3.x?

description: Get 2.x-like sorting behaviour in Python 3.x


code:
from random import choice

results = {}
for movie in movies:
    results[movie] = choice(directors)

rawDescription: Joining two lists with unequal number of elements into a dictionary


code:
regular_heights = np.arange(120, 213, 5)       # Regular heights every 5m
plot(height, temp, 'o', regular_heights, f(regular_heights), 'x')

rawDescription: Interval average of 1D data

description: Interval average of 1D data


code:
import csv
with open('mydata.csv') as in_file:
    with open('outfile.csv', 'wb') as out_file:
        csv_reader = csv.reader(in_file, delimiter=' ', skipinitialspace=True)
        csv_writer = csv.writer(out_file, delimiter = '\t')

        # Iterate over all rows in the file
        for i, header in enumerate(csv_reader):
            # Get the header data
            num = header[0]
            csv_writer.writerow([num])

            # Write frame number, starting with 1 (hence the +1 part)
            csv_writer.writerow([i+1])

            # Iterate over all data rows
            for _ in xrange(326):

                # Call next(csv_reader) to get the next row
                # Put inside a try ... except to avoid StopIteration exception
                # if end of file is found before reaching 326 lines
                try:
                    row = next(csv_reader)
                except StopIteration:
                    break
                # Use list comprehension to extract number of zeros
                zeros = sum([1 for x in row[2:12] if x.strip() == '0'])
                not_zeros = 10 - zeros
                # Write the data to output file
                out = [row[0].strip(), row[1].strip(),not_zeros, zeros, row[12].strip()]
                csv_writer.writerow(out)
            # If the
            else:
                # Skip the last two lines of the file
                next(csv_reader)
                next(csv_reader)

rawDescription: Python: Read and write the file of complex and reapeating format


code:
a = a.loc[a.reset_index().groupby('A')['index'].max()]
a

rawDescription: How to select group's rows having the greatest index

description: Select group's rows having the greatest index


code: tarfile

rawDescription: Get Python without (selected) batteries

description: Get Python without (selected) batteries


code:
data = """\
endDate,val
2016-05-06 15:01:01 -0400,11
2016-05-06 20:20:20 -0100,12
"""

df = pd.read_csv(io.StringIO(data), index_col='endDate', parse_dates=['endDate'],
                 date_parser=lambda x: pd.to_datetime(x.rsplit(' ', 1)[0]))

rawDescription: Ignore timezone offset portion of date time stamp pandas parse_dates


code:
[head]
var: self.post.id

rawDescription: Inplace substitution from ConfigParser

description: Inplace substitution from ConfigParser


code:
import numpy as np
np.random.seed(1)
list_of_np_1D = np.random.randint(0, 5, size=(500, 6))
np_2D = np.random.randint(0, 5, size=(20, 6))

rawDescription: Possible to add numpy arrays to python sets?


code:
import os

def split(filehandler, delimiter=',', row_limit=1000,
          output_name_template='output_%s.csv', output_path='.', keep_headers=True):
    import csv
    reader = csv.reader(filehandler, delimiter=delimiter)
    current_piece = 1
    current_out_path = os.path.join(
        output_path,
        output_name_template % current_piece
    )
    current_out_writer = csv.writer(open(current_out_path, 'w'), delimiter=delimiter)
    current_limit = row_limit
    if keep_headers:
        headers = reader.next()
        current_out_writer.writerow(headers)
    for i, row in enumerate(reader):
        if i + 1 > current_limit:
            current_piece += 1
            current_limit = row_limit * current_piece
            current_out_path = os.path.join(
                output_path,
                output_name_template % current_piece
            )
            current_out_writer = csv.writer(open(current_out_path, 'w'), delimiter=delimiter)
            if keep_headers:
                current_out_writer.writerow(headers)
        current_out_writer.writerow(row)

rawDescription: splitting one csv into multiple files in python

description: Splitting one csv into multiple files in python


rawDescription: Python nonogram uniqueness

description: Python nonogram uniqueness


code:
def drem(x, y):
    n = round(x / y)
    return x - n * y

rawDescription: How can I simulate GNU C Library drem / remainder function in Google App Engine Python 2.7 runtime?

description: Simulate GNU C Library drem / remainder function in Google App Engine Python 2.7 runtime


code:
def application(environ, start_response):

    status = '200 OK'
    output = 'This is my Website!'

    response_headers = [('Content-type', 'text/plain'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)

    return [output]

rawDescription: Blank page when trying to set up Apache and Django together


code:
class Foo (Base):
    def get_message (self):
        return "Hello World";

rawDescription: How can I wrap an empty function to be implemented by a child class in a try-except block?

description: Wrap an empty function to be implemented by a child class in a try-except block


code:
long_string_value = (
    "This is the first chuck of a longer string, it fits within the "
    'limits of a "style guide" that sets a shorter line limit while '
    r'at the same time letting you use \n as literal text instead of '
    "escape sequences.\n")

rawDescription: Why does Python's print function act this way?


rawDescription: Python data wrangling issues

description: Python data wrangling issues


code:
ra = compose(rangeset_001, algo_001)
ra(lsrc)

rawDescription: python, functions combination via names and chain them to invoke in-a-go?

description: Python, functions combination via names and chain them to invoke in-a-go


code:
for idx, val in enumerate(set_of_pk_values):
    for idx_2, val_2 in enumerate(set_of_pk_values):
        if (val['someKey'] == val_2['someKey'] and idx != idx_2):
            do_stuff()

rawDescription: Python Nested For Loop Array Comparison - Possibility of Optimization?


code:
import win32com.client              #import the whole module first
Dispatch = win32com.client.Dispatch #assign the required attributes to global variables
del win32com                        #remove the reference to module object

rawDescription: Why does it take longer to import a function from a module than the entire module itself?


code:
self.Bind(wx.EVT_CLOSE, self.on_Close)

def on_Close(self, event):
    self.MakeModal(False)
    frame_1.Show() #frame_1 becomes active again
    event.Skip() #after we have executed our custom set of instructions it is a good idea to skip the event so that python can de-allocate memory and perform other routine tasks

rawDescription: WXPYTHON: How to check If a frame is already visible?


code:
def getPermutations(string):
    if len(string) == 1: # Base Case
        return [string]
    else:                # Not base case
        result = []
        for i in range(len(string)):
            candidate = string[i]
            remaining = string[0:i] + string[i+1:]
            babies = getPermutations(remaining)  # Faith!
            for word in babies:
                result.append(candidate + word)
        return result

rawDescription: how to print sorted permutation of a string with recursion in python

description: Print sorted permutation of a string with recursion in python


rawDescription: IPython notebook read string from raw text cell


code:
import fractions
ai = fractions.Fraction(2)
bi = 1
n = 5
for i in range(n):
    ai = 2 + bi / ai
    F = ai - 1
    print(F)

rawDescription: The fractions are incomplete

description: The fractions are incomplete


code:
import re
import lxml
from lxml.html.clean import Cleaner
new_pattern = '\s*(?:javascript:|jscript:|livescript:|vbscript:|data:[^(?:image/.+;base64)]+|about:|mocha:)'

print(new_pattern)

lxml.html.clean._javascript_scheme_re = re.compile(new_pattern, re.I)

cleaner = Cleaner()
dochtml = """

"""
r = cleaner.clean_html(dochtml)
print(r)

rawDescription: lxml cleaner to ignore base64 image

description: Lxml cleaner to ignore base64 image


code:
def getLongestSequenceSize(search_str, polymer_str):
    matches = re.findall(r'(?:\b%s\b\s?)+' % search_str, polymer_str)
    longest_match = max(matches)
    return longest_match.count(search_str)

rawDescription: Python: re..find longest sequence

description: Python: re..find longest sequence


code:
def get_stackoverflow(query):
    import urllib, urllib2, re, urlparse
    params = urllib.urlencode({'q': query, 'sort': 'relevance'})
    html = urllib2.urlopen("http://stackoverflow.com/search?%s" % params).read()
    links = re.findall(r'
([^<]*)
', html)
    links = [(urlparse.urljoin('http://stackoverflow.com/', url), title) for url,title in links]

    return links

rawDescription: How can I search through Stack Overflow questions from a script?

description: Search through Stack Overflow questions from a script


code: matrix = getMatrix()

rawDescription: Python 3- matrix input

description: Python 3- matrix input


code:
region = regions[6]
conn = region.connect()

rawDescription: Difficulty in finding the Region names in AWS rds


code:
def get_links(url, times=None):
    '''Returns all <a> tags from `url` and every 3rd link, up to `times` deep

    get_links("protocol://hostname.tld", times=2) -> list
    if times is None, recurse until there are fewer than 3 links to be found
    '''

    def _get_links(url, TTL):
        soup = BeautifulSoup(urllib.urlopen(url).read())
        links = soup('a')
        if (times is not None and TTL >= times) or \
           len(links) < 3:
            # base case
            return links
        else:
            return links + _get_links(links[2]['href'], TTL+1)
    return _get_links(url, 0)

rawDescription: My loop isn't running

description: My loop isn't running


code:
from os.path import isfile as isFileExsist
import sys

filePath = input("What is the name of your file?: ")

while isFileExsist(filePath) == False:
    pos = ['y', 'Y', 'yes', 'Yes']
    neg = ['n', 'N', 'no', 'No']
    answer = input("File not found! Do you want to start again? (y-yes/n-no)")
    if answer in neg:
        exit("Bye!")
    elif answer in pos:
        filePath = input("What is the name of your file?: ")
        continue
    else:
        print("Not sure what is the answer. Try again!")
        continue

file = open(filePath, 'r')
data = file.readlines()

print("{0:15s}{1:15s}{2:10s}{3:15s}{4:20s}{5:15s}".format("First Name",   "Last Name", "Hours", "Payrate", "Overtime Hours", "Gross Pay"))
print("==============================================================================================================")

overHoursAll = 0
grossPayAll = 0
count = 0

for line in data:
    words = line.split()

    lastName = words[0]
    firstName = words[1]
    initialHours=(int(words[2]))
    payRate =(int(words[3]))

    if initialHours > 40:
        regHours = 40
        overHours = initialHours - 40

        regPay = payRate * regHours
        otPay = overHours * (payRate * 1.5)
        grossPay = regPay + otPay
    else:
        regHours = initialHours
        overHours = 0

        grossPay = initialHours * payRate

    grossPayAll += grossPay
    overHoursAll += overHours

    # heading3
    print("{0:15s}{1:15s}{2:2d}{3:10d}{4:14d}{5:24.2f}".format(firstName, lastName, regHours, payRate, overHours, grossPay))
    # space heading
    print("               ")

# overall stats
print("{0:15s}{1:21.2f}".format("Total Gross Pay", grossPayAll))
print("{0:15s}{1:19.2f}".format("Average Gross Pay", grossPayAll / len(data)))
print("{0:15s}{1:16d}".format("Total Overtime Hours", overHoursAll))

rawDescription: Looping over a text file list with python


code: img[mask] = 0

rawDescription: Python how to loop through an array in numpy at C speed and store some positions


code:
import pandas as pd
import numpy as np

df = pd.DataFrame({'id': [1,1,2,2,1,2,1,1], 'x':[10,20,100,200,np.nan,np.nan,300,np.nan]})
df['x'] = df.groupby(['id'])['x'].transform(lambda grp: grp.fillna(method='ffill'))
print(df)

rawDescription: Fill in missing pandas data with previous non-missing value, grouped by key


code:
from django.db.models import Count

School.objects.annotate(post_count=Count('userprofile__post'))

rawDescription: Annotate via second-degree model relation


code: x[y.nonzero()] = y[y.nonzero()]

rawDescription: Python numpy array replacing

description: Python numpy array replacing


code:
import numpy
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

# Define locations of my vectors
lat = numpy.array([50.1,46.2,51.6,52.2,54.4])
lon = numpy.array([-3.3,-1.0,-5.2,-1.2,0.2])

# Define some east-west vectors to illustrate the problem
u = numpy.array([5,5,5,5,5])
v = numpy.array([0,0,0,0,0])

# Set up map projection
m = Basemap(llcrnrlon=-15.,llcrnrlat=46.,urcrnrlon=15.,urcrnrlat=59.,
            projection='lcc',lat_1=40.,lat_2=50.,lon_0=-50.,
            resolution ='l')

# Calculate positions of vectors on map projection
x,y = m(lon,lat)

# Calculate the orientation of the vectors
x1, y1 = m(lon+u, lat+v)
u_map, v_map = x1-x, y1-y

# Rescale the magnitudes of the vectors...
mag_scale = np.hypot(u_map, v_map) / np.hypot(u, v)
u_map /= mag_scale
v_map /= mag_scale

# Draw barbs
m.barbs(x,y,u_map,v_map, length=7, color='red')

# Draw some grid lines for reference
parallels = numpy.arange(-80.,90,20.)
meridians = numpy.arange(0.,360.,20.)
m.drawparallels(parallels)
m.drawmeridians(meridians)
m.drawcoastlines(linewidth=0.5)

plt.show()

rawDescription: How can I rotate vectors onto a Basemap map projection?

description: Rotate vectors onto a Basemap map projection


rawDescription: Is there a dedicated milli-sec precision timestamp data structure in python pandas?


code:
my_list = [1,2,25,1,67,8,9,1,99]
for i in range(len(my_list)): # len() returns length of an array
    if my_list[i] == 1: # here you check if 'i' element of my_list is equal to 1
        try:
            print(my_list[i+1]) # here you are printing 'i+1' element of my_list
        except IndexError:
            pass

rawDescription: How to access an element based on the element appears before it in python list

description: Access an element based on the element appears before it in python list


code:
from django.conf.urls import patterns, url, include

extra_patterns = patterns('',
    url(r'^reports/(?P<id>\d+)/$', 'credit.views.report', name='credit-reports'),
    url(r'^charge/$', 'credit.views.charge', name='credit-charge'),
)

urlpatterns = patterns('',
    url(r'^$', 'apps.main.views.homepage', name='site-homepage'),
    (r'^help/', include('apps.help.urls')),
    (r'^credit/', include(extra_patterns)),
)

rawDescription: Grouping URL patterns that are similar

description: Grouping URL patterns that are similar


code:
import xml.dom.minidom as minidom
dom = minidom.parse('test.xml')
data={}
for dct in dom.getElementsByTagName('dict'):
    keys=dct.getElementsByTagName('key')
    # key.nextSibling can be an integer or string or date element, or Text node
    # key.nextSibling.firstChild is a Text node or None
    vals=[key.nextSibling.firstChild for key in keys]
    # drill down to the text inside the keys and vals
    keys=[key.firstChild.data for key in keys]
    vals=[val.data if val else None for val in vals]
    data=dict(zip(keys,vals))
    if data['Track ID']=='1208':
        print(data['Location'])
        break

rawDescription: XML parsing python

description: XML parsing python


code: pairs = [v for v in index.itervalues() if len(v) == 2]

rawDescription: Find duplicates in a list of lists with tuples


code:
y(0) == 4      # paint 0;3
y(1) == 2.(6)  # paint 1;2
y(2) == 1.(3)  # paint 2;1

x(0) == 3      # paint 2;-1 (-1 is not a valid pixel coordinate,
               # so we may just throw away this, as there are no pixels below y=0)
x(1) == 2.25   # paint 2;0
x(2) == 1.5    # paint 1;1
x(3) == 0.75   # paint 0;2

rawDescription: Drawing an almost straight line

description: Drawing an almost straight line


rawDescription: How to convert PlayJSON list to Scala Map (complex)?

description: Convert PlayJSON list to Scala Map (complex)


rawDescription: Print a dict sorted by values

description: Print a dict sorted by values


code:
import subprocess

def write_to_clipboard(string):
    p = subprocess.Popen(['python', __file__], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    p.communicate(input=string)

if __name__ == "__main__":
    import sys
    from Tkinter import Tk

    r = Tk()
    r.withdraw()
    r.clipboard_clear()
    r.clipboard_append(sys.stdin.read())
    r.update()
    r.destroy()

rawDescription: How do I use Tkinter and allow my application to keep the focus?

description: Use Tkinter and allow my application to keep the focus


code:
import pandas as pd
import random
df = pd.DataFrame({'id':[100*random.randint(10, 50) for _ in range(100)], 'question': [str(random.randint(0,3)) for _ in range(100)], 'response': [str(random.randint(100,120)) for _ in range(100)]})
df.head()
df.info()
df.pivot_table(index='id', columns='question', values='response', aggfunc=lambda x: ' '.join(x)).head()

rawDescription: Pivoting a Pandas Dataframe containing strings - 'No numeric types to aggregate' error


code:
def test_conditions(obj, a=5, **kwargs):
    if obj.a <= a:
        return False
    for k, v in kwargs.items():
        if getattr(obj, k) <= v:
            return False
    return True

rawDescription: Python - adding conditions in if only they are specified (domain)?


code:
from rest_framework import routers

router = routers.SimpleRouter()
router.register(r'num', NumViewSet)
urlpatterns = router.urls

rawDescription: Django Rest Framework adding 2 numbers

description: Django Rest Framework adding 2 numbers


code: {k:v for k,v in zip(dct_keys, city_list)}

rawDescription: How to create unique key(keys defined in some list) for dictionary and assign value to it in for loop in python 2.7?

description: Create unique key(keys defined in some list) for dictionary and assign value to it in for loop in python 2.7


code:
for artist in tree_data.keys():
    print(artist)
    for album, titles in tree_data[artist].iteritems():
        print("\t" + album)
        for title in titles:
            print ("\t\t" + title)

rawDescription: How can I put data into a tree view?

description: Put data into a tree view


code:
for td, val in zip(*[tds]*2):
    print(td,val)

rawDescription: Simple example regarding how to parse data from html output using lxml