code:
icol = range(ncols)
for irow, row in enumerate(data):
    if irow>0:
         result = np.vstack((result, f(row, irow, icol)))
    else:
         result = f(row, irow, icol)

rawDescription: Get Index of 2D array in Python

description: Get Index of 2D array in Python


test

source_type: sql

source_type: csv

rawDescription: Using an xml "map" to import data to MySQL via python?


code:
from django.contrib.auth import login
from django.views.generic.edit import FormView
from key_auth.forms import KeyAuthenticationForm

class KeyAuthLoginView(FormView):
    form_class = KeyAuthenticationForm
    template_name = 'key_auth_form.html'

    def form_valid(self, form):
        login(self.request, form.user)
        return super(KeyAuthLoginView, self).form_valid(form)

    def get_success_url(self):
        return self.request.REQUEST.get('next', '/')

login_view = KeyAuthLoginView.as_view()

rawDescription: Security issues with a middleware screener page


code: return_value = eval(v, None, in_dict)

rawDescription: Infinite loop while iterating dictionary Python


code: np.all(a == a[0], axis=0)

rawDescription: Check for invariant columns in a numpy array


code:
[x if re.match(r,x) else d for x,r,d in zip(list_ex2,reg_ex_check,default_fill)]
Out[14]: ['pear', '0', '45', '2000-01-01', '565.11']

rawDescription: Python: Checking a list with regex, filling in blanks


code:
import re
s = '''LaunchPad   Infrastructure
CyclingLeague   SportsLeague
Territory   PopulatedPlace
CurlingLeague   SportsLeague
GatedCommunity  PopulatedPlace'''
subbed = re.sub('([A-Z][a-z]+)([A-Z])', r'\1_\2', s)
print(subbed)

rawDescription: How do I change strings based on some rules?

description: Change strings based on some rules


code: w = numpy.array(data)

rawDescription: Convert fixed-width, non-delimited float strings to comma separated values


rawDescription: How do I slice a Multindex timeseries dataframe on Pandas?

description: Slice a Multindex timeseries dataframe on Pandas


code:
class C(P):
    def __init__(self, c, *args):
        super(C, self).__init__(*args)
        self.c = c

obj = C(3, 1, 2)
print(obj.a, obj.b, obj.c) # 1 2 3

rawDescription: Passing arguments to superclass constructor without repeating them in childclass constructor


code:
def _coefs_to_long(coefs, window):
    """Given a sequence of coefficients *coefs* and the *window* size return a
    long-integer representation of these coefficients.
    """

    length = len(coefs)
    if length < 100:
        res = 0
        adder = 0
        for k in coefs:
            res += k << adder
            adder += window
        return res
    else:
        half_index = length // 2
        big_window = window * half_index
        low = _coefs_to_long(coefs[:half_index], window)
        high = _coefs_to_long(coefs[half_index:], window)
        return low + (high << big_window)

def _long_to_coefs(long_repr, window, n):
    """Given a long-integer representing coefficients of size *window*, return
    the list of coefficients modulo *n*.
    """

    win_length = long_repr.bit_length() // window
    if win_length < 256:
        mask = 2**window - 1
        coefs = [0] * (long_repr.bit_length() // window + 1)
        for i in xrange(len(coefs)):
            coefs[i] = (long_repr & mask) % n
            long_repr >>= window

        # assure that the returned list is never empty, and hasn't got an extra 0.
        if not coefs:
            coefs.append(0)
        elif not coefs[-1] and len(coefs) > 1:
            coefs.pop()

        return coefs
    else:
        half_len = win_length // 2
        low = long_repr & (((2**window) ** half_len) - 1)
        high = long_repr >> (window * half_len)
        return _long_to_coefs(low, window, n) + _long_to_coefs(high, window, n)

rawDescription: Optimize conversion between list of integer coefficients and its long integer representation


code:
if __name__=="__main__":
    args = my_parse_args()
    do_something(args['arg1'])

rawDescription: How to access argparse parse_args from another function

description: Access argparse parse_args from another function


rawDescription: Permutation of values on numpy array/matrix


code:
def OnButtonClick(self):
    top = Toplevel()
    top.title("title")
    top.geometry("300x150+30+30")

    top.transient(self)

    topButton = Button(top, text="CLOSE", command = self.destroy)
    topButton.pack()

rawDescription: Python GUI code to click a button to open another window breaks


rawDescription: in python, how do I check to see if keys in a dictionary all have the same value x?

description: In python, how do I check to see if keys in a dictionary all have the same value x


code:
def add_tests(args, name_builder):
   def decorator(cls):
      for a in args:
          def tb(a):
              return lambda self: self.test_body(*a)
          setattr(cls, name_builder(a), tb(a))
      return cls

rawDescription: Dynamically adding tests to my Test Cases


code:
def solution_sets(l):
    return functools.reduce(operator.and_, l)

rawDescription: Python bitwise AND on multiple numbers, faster way than iterative bitwise operator?


code:
for line1 in lines1:
    p = line1.split()
    if float(p[2]) < 2:     # changed here
        x1a.append(float(p[1]))
        y1a.append(float(p[3]))
    elif 1 < float(p[2]) < 4:  # There seems to be a problem with this if
        x1b.append(float(p[1]))
        y1b.append(float(p[3]))
    elif float(p[2]) > 3:     # changed here
        x1c.append(float(p[1]))
        y1c.append(float(p[3]))

rawDescription: Plot specific lines for specific values with Pyplot


rawDescription: How to merge only the unique lines from file_a to file_b?

description: Merge only the unique lines from file_a to file_b


code:
import collections
class LazySequence(collections.Sequence):
    def __init__(self, f, n):
        """Construct a lazy sequence representing map(f, range(n))"""
        self.f = f
        self.n = n
    def __len__(self):
        return self.n
    def __getitem__(self, i):
        if not (0 <= i < self.n):
            raise IndexError
        return self.f(i)

rawDescription: How to use bisect to search in a compute-when-need array

description: Use bisect to search in a compute-when-need array


code:
from random import sample
xs = sample(range(100000), 50000)
ys = sample(range(100000), 50000)
print(primesum(xs, ys))

rawDescription: Python 2 lists of positive integers finding prime number


rawDescription: python regex speed

description: Python regex speed


code:
class ListPQ():
    def __init__(self):
        self.h = []

    def put(self, item):
        heapq.heappush(self.h, item)

    def get(self):
        return heapq.heappop(self.h)

rawDescription: python queue using embedded list

description: Python queue using embedded list


code:
#!/usr/bin/env python
import os
import time
from subprocess import check_call, STDOUT

DEVNULL = open(os.devnull, 'wb', 0)

start = time.time()
check_call(['sleep', '1'], stdout=DEVNULL, stderr=STDOUT)
print("{:.3f} seconds".format(time.time() - start))

rawDescription: Python subprocess with /usr/bin/time: how to capture timing info but ignore all other output?


code: return tuple([value, None][i > 0] for i in xrange(tuple_length))

rawDescription: Is there a more lightweight way to get a tuple of variable length?


code:
import sys

from PyQt5 import Qt
from PyQt5 import uic

a = Qt.QApplication(sys.argv)

from untitled import Ui_Form

# Override like this:

class override_graphicsScene (Qt.QGraphicsScene):
    def __init__(self,parent = None):
        super(override_graphicsScene,self).__init__(parent)

    def mousePressEvent(self, event):
        super(override_graphicsScene, self).mousePressEvent(event)
        print(event.pos())

class Image_Process(Qt.QWidget):
    def __init__(self):
        super(Image_Process, self).__init__()
        self.path = r"d:\test\winxp.jpg"  #image path

        self.new = Ui_Form()
        self.new.setupUi(self)

        self.pixmap = Qt.QPixmap()
        self.pixmap.load(self.path)
        self.pixmap = self.pixmap.scaled(self.size(), Qt.Qt.KeepAspectRatio)

        self.graphicsPixmapItem = Qt.QGraphicsPixmapItem(self.pixmap)

        self.graphicsScene = override_graphicsScene(self)
        self.graphicsScene.addItem(self.graphicsPixmapItem)

        self.new.graphicsView.setScene(self.graphicsScene)

my_Qt_Program = Image_Process()

my_Qt_Program.show()
sys.exit(a.exec_())

rawDescription: In PyQt, image won't show after override mousePressEvent of QGraphicsView


code:
strs = "['foo','abarc']"
'bar' in strs            #substring search
lis = ['foo','abarc']    #item search
'bar' in lis

rawDescription: Find list of keywords in string

description: Find list of keywords in string


rawDescription: Turning binary string into an image with PIL


code:
def sumPair2(theList, n):
    for ind, e in enumerate(theList):
        try:
            theList.index(n - e, ind + 1)
            return e, n - e
        except ValueError:
            pass

rawDescription: One loop? python

description: One loop? python


code:
@register.filter
def customFilter(value):
    return value / 60.0 * 0.16

rawDescription: Math on Django Templates

description: Math on Django Templates


code:
#!/bin/env/python
# -*- coding: ascii -*-
import os
import sys
import imp
import tarfile
import tempfile

RUN_MODULE = "__run__"
SENTINEL = 'RzlBTXhya3ljIzl6PFFkQiRKLntEdHF+c2hvWid0IX5NVlxWd' \
           'FxcJ0NWQ2xKVUI0TVEuNl0rWUtnKiRr'.decode('base64')

class FileOffset(object):
    def __init__(self, fileobj, offset=0):
        self._fileobj = fileobj
        self._offset = offset
        self._fileobj.seek(offset)

    def tell(self):
        return self._fileobj.tell() - self._offset

    def seek(self, position, whence=os.SEEK_SET):
        if whence == os.SEEK_SET:
            if position < 0: raise IOErrror("Negative seek")
            self._fileobj.seek(position + self._offset)
        else:
            oldposition = self._fileobj.tell()
            self._fileobj.seek(position, whence)
            if self._fileobj.tell() < self._offset:
                self._fileobj.seek(oldposition, os.SEEK_SET)
                raise IOError("Negative seek")

    def __getattr__(self, attrname):
        return getattr(self._fileobj, attrname)

    def __enter__(self, *args):
        return self._fileobj.__enter__(*args)

    def __exit__(self, *args):
        return self._fileobj.__exit__(*args)

class TarImport(object):
    def __init__(self, tarobj, tarname=None):
        if tarname is None:
            tarname = '<tarfile>'
        self._tarname = tarname
        self._tarobj = tarobj

    def find_module(self, name, path=None):
        module_path = os.path.join(*name.split('.'))
        package_path = os.path.join(module_path, '__init__')

        for path in [module_path, package_path]:
            for suffix, mode, module_type in imp.get_suffixes():
                if module_type != imp.PY_SOURCE:
                    continue
                member = os.path.join(path) + suffix
                try:
                    modulefileobj = self._tarobj.extractfile(member)
                except KeyError:
                    pass
                else:
                    return Loader(name, modulefileobj,
                                  "%s/%s" % (self._tarname, member),
                                  (suffix, mode, module_type))

class Loader(object):
    def __init__(self, name, fileobj, filename, description):
        self._name = name
        self._fileobj = fileobj
        self._filename = filename
        self._description = description

    def load_module(self, name):
        imp.acquire_lock()
        try:
            module = sys.modules.get(name)
            if module is None:
                module = imp.new_module(name)

            module_script = self._fileobj.read()
            module.__file__ = self._filename
            module.__path__ = []
            sys.modules[name] = module
            exec(module_script, module.__dict__, module.__dict__)
        finally:
            imp.release_lock()

        return module

def find_offset(fileobj, sentinel):
    read_bytes = 0
    for line in fileobj:
        try:
            offset = line.index(sentinel)
        except ValueError:
            read_bytes += len(line)
        else:
            return read_bytes + offset + len(sentinel)
    raise ValueError("sentinel not found in %r" % (fileobj, ))

if __name__ == "__main__":
    sys.argv[:] = sys.argv[1:]
    archive_path = os.path.abspath(sys.argv[0])
    archive_offset = find_offset(open(archive_path), SENTINEL)

    archive = FileOffset(open(archive_path), archive_offset)

    tarobj = tarfile.TarFile(fileobj=archive)
    importer = TarImport(tarobj, archive_path)

    sys.meta_path.insert(0, importer)

    importer.find_module(RUN_MODULE).load_module(RUN_MODULE)

rawDescription: Packing Python files into a single .py script


code: data2['buy'] = pd.rolling_sum( data2.AboveUpper, window=X ) >= X

rawDescription: More Efficient way to check values of neighboring rows in pandas dataframe for stock backtesting


rawDescription: Find unique elements of floating point array in numpy (with comparison using a delta value)


code:
a
b
np.vstack((a + b[:,None,:]))

rawDescription: Combine array along axis

description: Combine array along axis


code:
dbus.Struct((dbus.Boolean(a_boolean),
             dbus.Struct((dbus.ObjectPath(s1),
                          dbus.String(s2),
                          dbus.String(s3)))),
            signature="(b(oss))")

rawDescription: How to represent dbus type b(oss) in python?

description: Represent dbus type b(oss) in python


code:
string = 'ABC123'
string[0]   | 'A'
string[-1]  | '3'
string[0:3] | 'ABC'

rawDescription: Trying to make this work with two characters and not just one


code:
from time import sleep
...
sleep(5) # specify pause in seconds

rawDescription: Selenium + Python: StaleElementReferenceException (selecting by class)


rawDescription: How to create sub list with fixed length from given number of inputs or list in Python?

description: Create sub list with fixed length from given number of inputs or list in Python


rawDescription: How to create a list of sublists where the sublists are split strings?

description: Create a list of sublists where the sublists are split strings


rawDescription: Assigning values to two dimensional array from two one dimensional ones


rawDescription: How can I add two functions together in Python 3?

description: Add two functions together in Python 3


code:
# in main.py
from package1.module1 import *
from package1.module2 import *

# in package1.module1
import module2
from package2.module1 import *

# in package2.module1 import *
import module2
from package1.module1 import *

rawDescription: Import paths - the right way?

description: Import paths - the right way


rawDescription: Python 3 one-liner for 2 lists string format?


code:
scene = MyScene()
...
my_proxy = MyProxy()
my_proxy.setWidget(button2)
my_proxy.setAcceptDrops(True)
scene.addItem(my_proxy)
...

rawDescription: Drag n Drop inside QgraphicsView doesn't work (PyQt)


rawDescription: Is there a way to get processes information of local machine with python?


code:
blocks[0][0]
blocks[1][0]

rawDescription: Indexes of fixed size sub-matrices of numpy array


code:
session.query(Event).filter(or_(
    and_(
        Event.regular == True,
        ~Event.exceptions.any(and_(
            EventException.year == current_year,
            EventException.occurs == False,
        )),
    ),
    and_(
        Event.regular == False,
        Event.exceptions.any(and_(
            EventException.year == current_year,
            EventException.occurs == True,
        )),
    ),
))

rawDescription: In sqlalchemy, how do I get a query that matches all rows in a table such that no row in another table links to it?


code:
class MetaEnum(type):
    def __new__(cls, class_name, parents, attrs):
        def __init__(self, name=None):
            if name is not None: self.name = name
        attrs['__init__'] = __init__
        Klass = type.__new__(cls, class_name, parents, attrs)
        if 'instances' in attrs:
            for name in attrs['instances']:
                setattr(Klass, name.capitalize(), Klass(name))
            del Klass.instances # clean up
        return Klass

class Fruit(object):
    __metaclass__ = MetaEnum
    instances = ('apple', 'banana', 'cranberry')

for attr_name in dir(Fruit):
    if not attr_name.startswith('_'):
        attr = getattr(Fruit, attr_name)
        if type(attr) is Fruit:
            print('Fruit.{}, is a Fruit named {}'.format(attr_name, getattr(attr, 'name')))
        else:
            print('Fruit.{}, is a {}'.format(attr, type(attr)))

rawDescription: Python 2.x - creating static instance of class in same class


code: sorted(zip(a, b, c))

rawDescription: How to turn 3 lists into an ordered dictionary

description: Turn 3 lists into an ordered dictionary


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

nrows, ncols = 1000, 1000
z = 500 * np.random.random(nrows * ncols).reshape((nrows, ncols))

plt.imshow(z, interpolation='nearest')
plt.colorbar()
plt.show()

rawDescription: Large matplotlib pixel figure best approach


code:
x = np.multiply.accumulate( np.ones( 10 )*2)
x[0] = 0

rawDescription: Creating numpy array with different steps


code:
def callback(*args):
    def decorate(f):
        try:
            f._marks.add(args)
        except AttributeError:
            f._marks = {args}
        return f
    return decorate

rawDescription: How to get a reference to an instance method from a decorator

description: Get a reference to an instance method from a decorator


code:
auxdict = {}
L = len(hugelist) - 1
for i, d in enumerate(reversed(hugelist)):
  auxdict.update(dict.fromkeys(d['ids'], L-i))

rawDescription: Python: find index of item containing X in list


code: list1 = list(str1)

rawDescription: Algorithm to check the order of substrings in combined string


rawDescription: sorting list based on other array contents

description: Sorting list based on other array contents


code:
class TestFoo(unittest.TestCase):

    def setUp(self):
        if not SLOW_TESTS:
            self.skipTest("slow test")
        # some expensive setup

rawDescription: Disable automatic test execution for some tests unless those are explicitly requested


code:
def make_square_matrix(size):
    return [[0]*size for b in range(size)]

def inverse(A):
    n = len(A)
    B = make_square_matrix(n)
    L = make_square_matrix(n)
    U = make_square_matrix(n)
    LU.crout(A,L,U)
    return B

rawDescription: python function making unrequested changes

description: Python function making unrequested changes


code:
#gtk file inclusion
import gtk
# The runtime dir is in the same directory as the module:
GTK_RUNTIME_DIR = os.path.join(
    os.path.split(os.path.dirname(gtk.__file__))[0], "runtime")

assert os.path.exists(GTK_RUNTIME_DIR), "Cannot find GTK runtime data"

rawDescription: Bundling GTK resources with py2exe

description: Bundling GTK resources with py2exe


rawDescription: NumPy dtype issues in genfromtxt(), reads string in as bytestring


code:
variable1 = 3
variable2 = 'stuff'

def spam(arg1):
    return 'spam' + arg1

def eggs(arg1,arg2):
    return 'eggs' + arg1 + arg2

rawDescription: Need help properly using variables, python


code:
arg = input('Enter a phrase :')
splitted = func(arg)

print(*splitted)  # or in Python 2: print ' '.join(splitted)

rawDescription: Reverse an input using tuples Python

description: Reverse an input using tuples Python


code:
# an image widget to contain the pixmap
image = gtk.Image()
image.set_from_pixmap(pixmap, mask)
image.show()

# a button to contain the image widget
button = gtk.Button()
button.add(image)
window.add(button)
button.show()

button.connect("clicked", self.button_clicked)

rawDescription: How do I include an image in a window with pygtk?

description: Include an image in a window with pygtk


code:
h = ''.join(map(str, range(0,21)))
h
struct.pack('>IIIIIIII', *struct.unpack('>IIIIIIII', h)[::-1])[::-1]

rawDescription: What does this piece of python indexing code do


code:
import os
import sys

if __name__ == '__main__':
    with open(os.path.abspath('test.png'), 'rb') as f:
        print("Content-Type: image/png\n")
        sys.stdout.flush() # <---
        sys.stdout.buffer.write(f.read())

rawDescription: Output binary data from CGI in Python 3

description: Output binary data from CGI in Python 3


code:
tsdays = df.index.values.astype('<M8[D]')
bdays = pd.bdate_range(tsdays[0], tsdays[-1]).values.astype('<M8[D]')
df = df[np.in1d(tsdays, bdays)]

rawDescription: rolling_sum on business day and return new dataframe with date as index

description: Rolling_sum on business day and return new dataframe with date as index


code:
" ".join(s.upper() if s.lower() in ["and", "or", "not"] else s
         for s in term.split())

rawDescription: Multiple re.sub() statements

description: Multiple re.sub() statements


code:
def yieldContext(l, func):
    l = [''] + l + ['']
    for i, s in enumerate(l):
        if func(s):
            yield ' '.join(l[i-1:i+2]).strip()

rawDescription: Joining the previous and next sentence using python


code: FindDuplicates(lst)

rawDescription: return duplicates in a list

description: Return duplicates in a list


code:
with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

rawDescription: How to split a line of code into multiple lines?

description: Split a line of code into multiple lines


code:
features = ['Camera', 'Touchscreen', 'Keyboard']
items = Item.objects.all()

for feature in features:
  items = items.filter(feature__name=feature)

rawDescription: Django: filter queryset by intersection result


rawDescription: Sorting variable number of columns/rows

description: Sorting variable number of columns/rows


code:
def get_page_list(url):
    page = get_page(url)
    text = get_text(page)
    cleantext = cleanup(text)
    return make_list(cleantext)

rawDescription: cleaning up nested function calls

description: Cleaning up nested function calls


rawDescription: Dynamic Self Referencing Dictionary in Python


code: df.selectExpr('date_sub(date_col, day_col) as subtracted_dates')

rawDescription: How to subtract a column of days from a column of dates in Pyspark?

description: Subtract a column of days from a column of dates in Pyspark


code:
with open(file_save_path, 'wb') as save_file:
    save_file.write(file_contents)

rawDescription: Pylons Uploading Distorted Images on Windows


code:
end = 78
start = -1 * end
step_size = 16
range(start-(start%step_size), end+step_size, step_size)

rawDescription: generic algorithm to force range to go through zero

description: Generic algorithm to force range to go through zero


code:
def is_subset(a, b):
  b = np.unique1d(b)
  c = np.intersect1d(a,b)
  return c.size == b.size

rawDescription: How to check efficiently if numpy array a contains b

description: Check efficiently if numpy array a contains b


rawDescription: Python While Not recordset.EOF that wont .MoveNext


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

X = np.linspace(0, 1, 10)
Y = np.linspace(0, 1, 10)

x,y = np.meshgrid(X,Y)

f1 = np.cos(x*y)
f2 = x-y

plt.contour(x,y,f2,colors='red')
plt.contour(x,y,f1,colors='blue')
plt.show()

rawDescription: several contour plots in the same figures

description: Several contour plots in the same figures


code:
for a in ax:
    plt.setp(a.get_yticklabels()[0], visible=False)
    plt.setp(a.get_yticklabels()[-1], visible=False)

rawDescription: Remove first and last ticks label of each y-axis subplot


code:
# File: forms.py
from django import forms
from django.forms.formsets import BaseFormSet

# What you've called 'GetMachine'
class MachineForm(forms.Form):
    no_of_lines = forms.IntegerField(max_value=4)

# What you've called 'GetLine'
class LineForm(forms.Form):
    beamline_name = forms.CharField(max_length=15, label='Name of Beamline')

# Create a custom formset and override __init__
class BaseLineFormSet(BaseFormSet):
    def __init__(self, *args, **kwargs):
        super(BaseLineFormSet, self).__init__(*args, **kwargs)
        no_of_forms = len(self)
        for i in range(0, no_of_forms):
            self[i].fields['beamline_name'].label += "-%d" % (i + 1)

rawDescription: Django: how to change label using formset extra?


code:
mask = idx != 0
df.loc[mask, 'id'] += '.' + idx[mask].astype('str')
df

rawDescription: How to generate the unique id from a list of ids containing duplicates

description: Generate the unique id from a list of ids containing duplicates


rawDescription: Quick way to sum the ith item of a list of lists in python


rawDescription: Feeding a Python array into a Perl script


code:
import client
import httpretty
import requests
from mock import Mock, patch
...
def testGetQueryToAPI(self):
  """
  Tests the client can send a 'GET' query to the API, asserting we receive
  an HTTP status code reflecting successful operation.
  """
  # Arrange: patch the request in client.Client._queryAPI().
  with patch.object(requests, 'get') as mock_get:
    mock_get.return_value = mock_response = Mock()
    mock_response.status_code = 200

    # Act:
    c = client.Client()
    response = c._queryAPI("path", 'GET', {}, None, {})

    # Assert:
    self.assertEqual(response.status_code, 200)

# Repeat the same test for 'POST' queries.

rawDescription: Python unittest mock an API key

description: Python unittest mock an API key


code:
password = input('Enter your password: ')
password
import getpass
password = getpass.getpass('Enter your password: ')
password

rawDescription: How to change or overwrite input password

description: Change or overwrite input password


code:
def step_impl(context):
    if some_condition:
        take_the_shot(context.scenario.name + " " + context.step.name)

rawDescription: How to get the current behave step with Python?

description: Get the current behave step with Python


code: (listbox.get(i) for i in listbox.curselection())

rawDescription: Attach data element to tkinter Listbox element


code:
class CallableHierarchyWrapper(object):

    def __init__(self, wrapped_object):
        self.wrapped_object = wrapped_object

    def __getattribute__(self, name):
        attr = self.wrapped_object.__getattribute__(name)
        if callable(attr):
            return hierarchywrapper(attr)
        else:
            return attr

rawDescription: Define function stubs enmasse

description: Define function stubs enmasse


code:
# Op 1
z1 = tf.add(rand_var_1, rand_var_2)

# Op 2
z2 = tf.add(rand_var_1, rand_var_2)

init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)        # Random numbers generated here and cached.
    z1_op = sess.run(z1)  # Reuses cached values for rand_var_1, rand_var_2.
    z2_op = sess.run(z2)  # Reuses cached values for rand_var_1, rand_var_2.
    print(z1_op, z2_op)   # Will print two identical vectors.

rawDescription: How do I generate a random vector in TensorFlow and maintain it for further use?

description: Generate a random vector in TensorFlow and maintain it for further use


code: b = ''.join(str(int(x) + 1) if x.isdigit() else x for x in a)

rawDescription: Python, context sensitive string substitution


rawDescription: Interpolation with Delaunay Triangulation (n-dim)


code:
dict1 = {'AAA': 'id5', 'BBB': 'id3', 'CCC': 'id8', 'DDD': 'id3'}
dict2 = {'AAA': 'value8', 'BBB': 'value24', 'CCC': 'value13', 'DDD': 'value2'}
output = {}
for key in dict1.keys() & dict2.keys():
    output.setdefault(dict1[key], []).append(dict2[key])

output

rawDescription: Match two dictionaries by key and return array of values


rawDescription: Python-Getting contents between current and next occurrence of pattern in a string


rawDescription: How to get row, column indices of items in Pandas dataframe

description: Get row, column indices of items in Pandas dataframe


code: my_other_func('hello', 'world', 'what a', state='fine', what='day')

rawDescription: Python newbie: What does this code do?

description: Python newbie: What does this code do


code:
import numpy as np
import pandas as pd

d = {'one' : np.random.rand(10),
     'two' : np.random.rand(10)}

df = pd.DataFrame(d)

df.plot(style=['o','rx'])

rawDescription: How to plot two columns of a pandas data frame using points?

description: Plot two columns of a pandas data frame using points


code:
idx = np.argsort(data[..., -1].flatten())
print(data[idx[-3:]])

rawDescription: Sorting an array of arrays in Python

description: Sorting an array of arrays in Python


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup("")
soup
new_tag = BeautifulSoup('<link rel="stylesheet" href="css/bootstrap.min.css"/>')
new_tag
soup.head.insert(0,new_tag)
soup
new_tag = BeautifulSoup('<link rel="stylesheet" href="css/custom1.css"/>')
new_tag
soup.head.insert(0,new_tag)
soup

rawDescription: How can I create a stylesheet external link using BeautifulSoup?

description: Create a stylesheet external link using BeautifulSoup


code:
class Fruit:

    def __init__(self, name, sugar_content):
        self.name = name
        self.sugar_content = sugar_content

rawDescription: Pythonic way of inheriting many classes?

description: Pythonic way of inheriting many classes


code:
d = defaultdict(dict)
d['A']['X'] = 'V1'

rawDescription: Dictionary with named values?

description: Dictionary with named values


code:
func()
func()
func()

rawDescription: How to make a few lines of function execute only once in python? preferably using lambda?

description: Make a few lines of function execute only once in python? preferably using lambda


rawDescription: python split string from file

description: Python split string from file


code: vectors[i] = A[:]

rawDescription: Trying to find all combinations of a 2-state vector (in python)


rawDescription: Conditional maths operation on 2D numpy array checking on one dimension and doing different operations on diff dimensions


code:
import multiprocessing as mp
import Queue

def foo(queue):
    pass

pool=mp.Pool()
q=Queue.Queue()

pool.map(foo,(q,))

rawDescription: multiprocessing.Pool - PicklingError: Can't pickle <type 'thread.lock'>: attribute lookup thread.lock failed

description: Multiprocessing.Pool - PicklingError: Can't pickle <type 'thread.lock'>: attribute lookup thread.lock failed


rawDescription: Referencing a variable inside another module/.py file


code:
[general]
jid=jid@host.org
resource=presence_watcher
password=yourpwd

rawDescription: How do I monitor the change of my gtalk status message?

description: Monitor the change of my gtalk status message


rawDescription: Convert numpy unit8 raw array directly to float32


code:
from __future__ import division
import multiprocessing as mp
import time

def foo(x):
    time.sleep(0.1)
    return x

def make_log_result(results, len_data):
    def log_result(retval):
        results.append(retval)
        if len(results) % (len_data//10) == 0:
            print('{:.0%} done'.format(len(results)/len_data))
    return log_result

if __name__ == '__main__':
    pool = mp.Pool()
    results = []
    data = range(200)
    for item in data:
        pool.apply_async(foo, args=[item], callback=make_log_result(results, len(data)))
    pool.close()
    pool.join()
    print(results)

rawDescription: How to keep track of status with multiprocessing and pool.map?

description: Keep track of status with multiprocessing and pool.map


code:
class FancySeeker(object):
    def __init__(self, *a, **k):
        self.l = list(*a, **k)
        self.d = {}

    def _find_in_list(self, predicate):
        for i, n in enumerate(self.l):
            if predicate(n):
                return i
        return -1

    def find(self, predicate):
        where = self.d.get(predicate)
        if where is None:
            where = self._find_in_list(predicate)
            self.d[predicate] = where
        return where

rawDescription: Efficient list manipulation in python

description: Efficient list manipulation in python


rawDescription: Use Numpy Multidimensional Array Slicing Without Using the [slice,slice] Syntax?


rawDescription: edit entry on special position in a grid

description: Edit entry on special position in a grid


code:
seen = set()
with open(infile, 'rt') as f:
    reader = csv.reader(f,delimiter=",")
    for row in reader:
        if row[0] in seen:
            continue
        if all(x in {"0", "1"} for x in row[2:]):
            print(row)
        seen.add(row[0])

rawDescription: How do I remove a dictionary from a list depending on a value being present in a list in Python?

description: Remove a dictionary from a list depending on a value being present in a list in Python


code:
import re
regex = '^(https?|ftp)://'
site = re.sub(regex, '', site)

rawDescription: Using replace() function to replace multiple texts(strings) at once in Python


code:
import multiprocessing.pool
from time import sleep

def timeout(seconds, function, *args, **kwargs):
    pool = multiprocessing.pool.ThreadPool(processes=1)
    result = pool.apply_async(function, args, kwargs)
    try:
        result.get(timeout=seconds)
    except multiprocessing.TimeoutError:
        print("Process timed out")
    pool.terminate()
#    pool.join()  # Don't need this, all worker threads have been stopped.
    print("Pool terminated")

def worker():
    for n in range(5):
        sleep(1)
        print(n+1)
    print("Process succeeded")

timeout(2.5, worker)

rawDescription: multiprocessing threadpool not terminating as expected

description: Multiprocessing threadpool not terminating as expected


rawDescription: How to append columns based on other column values to pandas dataframe

description: Append columns based on other column values to pandas dataframe


code:
doc=xee.fromstring(data)
for parent in doc.getiterator():
    for child in parent.findall('node2'):
        if child.attrib['a1']=='x2':
            parent.remove(child)

rawDescription: xml filtering with python

description: Xml filtering with python


code:
import argparse
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='Functions')
parser_1 = subparsers.add_parser('cmd1', help='...')
parser_1.add_argument('cmd1_option1', type=str, help='...')
parser_1.set_defaults(parser1=True)

parser_2 = subparsers.add_parser('cmd2', help='...')
parser_2.set_defaults(parser2=True)

parser_3 = subparsers.add_parser('cmd3', help='...')
parser_3.add_argument('cmd3_options', type=int, help='...')
parser_3.set_defaults(parser_3=True)

args = parser.parse_args()
print(args)

rawDescription: How to handle CLI subcommands with argparse

description: Handle CLI subcommands with argparse


rawDescription: How to create mask with multiple alternative values (Pandas DataFrame)

description: Create mask with multiple alternative values (Pandas DataFrame)


code:
from sklearn.feature_extraction import DictVectorizer

pipeline = Pipeline([('dvect', DictVectorizer()),
                     ('tfidf', TfidfTransformer()),
                     ('clf', MultinomialNB())])
model = pipeline.fit(x, y)

rawDescription: Given a dictionary of word and frequency pairs, how to proceed with text mining in scikit


code:
class MainWindow(QtGui.QMainWindow,Ui_MainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        from module_c import class_c
        global b
        b=class_c(self) #NOTICE THE CHANGE HERE
        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), b.close_call )

    def close_ok(self):
        self.close()

rawDescription: The Code does not work successfully when the function is called


code: [int(i) for i in grades.split()]

rawDescription: How do I convert strings of digits into lists of digits with proper spacing?

description: Convert strings of digits into lists of digits with proper spacing


rawDescription: Manipulating numpy arrays

description: Manipulating numpy arrays


code:
axes = plt.gca()  # Get current axes
axes.lines.remove(ax2[0])  # Removes the (first and only) line created in ax2
plt.draw()  # Updates the graph (in interactive mode)

rawDescription: matplotlib plt.show() only selected objects

description: Matplotlib plt.show() only selected objects


rawDescription: Removing extra spaces in Chinese HTML files using lxml


code:
teacher.student.add(student) # associate the 'teacher' object with the  'student' object

student.parents.add(parent) # associate the 'student' object with the 'parent' object

rawDescription: How do I fill in nested ManyToMany fields in Django with Shell?

description: Fill in nested ManyToMany fields in Django with Shell


rawDescription: How to decode 'xmlcharrefreplace' ascii to UTF-8 in python3?

description: Decode 'xmlcharrefreplace' ascii to UTF-8 in python3


code:
from django.db import models

# A decorator to implement the behavior you want for the
# __init__ method
def new_init(func):
   def __init__(self, *args,  **kw):
       self.documentation = kw.pop("documentation", None)
       return func(self, *args, **kw)

for name, obj in models.__dict__.items():
    #check if obj is a class:
    if not isinstance(obj, type):
        continue

    # creates a new_init, retrieving the original one -
    # taking care for not to pick it as an unbound method -
    # check: http://pastebin.com/t1SAusPS
    new_init_method = new_init(obj.__dict__.get("__init__", lambda s:None))

    # dynamically creates a new sublass of obj, overriding just the __init__ method:
    new_class = type(name, (obj,), {"__init__": new_init_method})

    # binds the new class to this module's scope:
    globals().__setitem__(name, new_class)

rawDescription: Override __init__ for all classes in module


code: dic = {x:i for i, x in enumerate(al, 1)}

rawDescription: How to create a dict with letters as keys in a concise way?

description: Create a dict with letters as keys in a concise way


code: a_dict  = {v[0].strip():float(v[1].strip()) for v in map(lambda v: v.split('|'), a_string.splitlines())}

rawDescription: How do I parse a multiline string into a python dict?

description: Parse a multiline string into a python dict


code:
def solve(x, y, mazeList=None):
    if mazeList is None:
        mazeList = loadMaze("sample.maze")

    if mazeList[y][x] == "E":
        return "YOU'VE SOLVED THE MAZE!"
    elif mazeList[y][x+1] == " ":  #right
        mazeList[y][x+1] = ">"
        return solve(x+1,y,mazeList)
    elif mazeList[y+1][x] == " ":  #down
        mazeList[y+1][x] = "v"
        return solve(x,y+1,mazeList)
    elif mazeList[y][x-1] == " ":  #left
        mazeList[y][x-1] = "<"
        return solve(x-1,y,mazeList)
    elif mazeList[y-1][x] == " ":  #up
        mazeList[y-1][x] = "^"
        return solve(x,y-1,mazeList)

rawDescription: Runtime Error in python: "Maximum recursion depth exceeded"


code:
from itertools import islice
with open("test.txt") as fin:
    try:
        while True:
            data =  islice(fin, 0, 8)

            firstname = next(data)
            lastname = next(data)
            email = next(data)
            #.....
    except StopIteration:
        pass

rawDescription: Read a File 8 Lines at a Time Python

description: Read a File 8 Lines at a Time Python


code:
columns_non_unique = indices[1]
unique_columns = sorted(set(columns_non_unique))
X.tocsc()[:,unique_columns]

rawDescription: How to efficiently remove columns from a sparse matrix that only contain zeros?

description: Efficiently remove columns from a sparse matrix that only contain zeros


code:
def check_col(self, rect):
    for row in self.cLayer:
        for column in row:
            grid_position = (row*element_size, column*element_width)
            collide_x = False
            collide_y = False

            # check x axis for collision
            if self.rect.x + self.rect.w > grid_position[0]:
                collide_x = True
            elif self.rect.x < grid_position[0] + element_width:
                collide_x = True

            # check y axis for collision
            if self.rect.y < grid_position[1] + element_height:
                collide_y = True
            elif self.rect.y + self.rect.h > grid_position[1]:
                collide_y = True

            # act on a collision on both axis
            if collide_x and collide_y:
                # act on the collision
                return True
            else:
                # act on no collision
                return False

rawDescription: Abstract Collision Detection

description: Abstract Collision Detection


code:
import csv

for file in files:
    with open(file, "rb") as currentfile, open(file[:-4]+"_RGB_moved.pts", "wb") as out:
        reader = csv.reader(currentfile, delimiter=' ', quoting=csv.QUOTE_NONE)
        writer = csv.writer(out, delimiter=' ', quoting=csv.QUOTE_NONE)

        out.writerow(next(reader)[0])

        for row in reader:
            newrow = [str(float(row[0])+offsetx), str(float(row[1])+offsety), row[2], str((int(row[3]) + 2050) / 2)]
            out.writerow(newrow)

rawDescription: How can I speed up this really basic python script for offsetting lines of numbers

description: Speed up this really basic python script for offsetting lines of numbers


code:
channel.queue_bind(exchange='amq.direct',
                   queue='hello')

rawDescription: How to create a delayed queue in RabbitMQ?

description: Create a delayed queue in RabbitMQ


rawDescription: Pandas Split DataFrame

description: Pandas Split DataFrame


code: return self.index <= other.index

rawDescription: Simpler way to do python operator overloading?


code:
source = browser.page_source
soup = BeautifulSoup(source)

rawDescription: Use urllib2 cookie in Selenium

description: Use urllib2 cookie in Selenium


rawDescription: randrange inside for loop in python 3.5

description: Randrange inside for loop in python 3.5


code:
df = pd.DataFrame((np.random.randn(6*6)).reshape(6,6))
df
df.groupby(df.columns//2, axis=1).mean()

rawDescription: Grouping a dataframe by X columns

description: Grouping a dataframe by X columns


rawDescription: Python - print tab delimited two-word set


code:
def reverse_dict(d):
    res = {}
    for key, val in d.items():
        res.setdefault(val, []).append(key)
    return res

rawDescription: how to get all item with specific value from dict?

description: Get all item with specific value from dict


code: s[s.apply(lambda x: isinstance(x, (int, float)))].rank(pct=True).max()

rawDescription: why aren't pandas "rank" percentiles bounded between 0 and 1?

description: Why aren't pandas "rank" percentiles bounded between 0 and 1


code:
def a():
    return [], []

rawDescription: How do I use django @lazy decorator?

description: Use django @lazy decorator


code:
with open('path/to/file.txt') as inf:
    text = inf.read()

chars = [ch for ch in text if ch.isspace() or ch.isdigit()]
# [' ', ' ', '9', '5', ' ', ' ', ' ', ' ', '9', '0']
# every space and every digit

chars = ''.join(chars)
# "  95    90"
# join every element with the empty string

numbers = chars.strip().split()
# ['95', '90']
# strip off leading and trailing whitespace, then split on groups of whitespace

for number in numbers:
    print(number)  # as before

rawDescription: Python program that is given a line read from a text file and displays the one number found


code:
df
df[['A', 'B', 'C', 'D']] = df[['A', 'B', 'C', 'D']].fillna(axis=1, method='backfill')
df

rawDescription: Row-by-row fillna with respect to a specific column?


code:
import json
self.response.out.write(json.dumps([m.to_dict() for m in matches]))

rawDescription: send tidy json data of a database model from server(python) to client

description: Send tidy json data of a database model from server(python) to client


code:
for listing in listings_data:
    listings['Address: %s' % listing.find("li", "address").string]

rawDescription: Iterating through an object returned by Beautiful Soup


code:
import pandas as pd
from numpy import arange
#mytup = [(111, [1,2,3,4,5], 0), (222, [33,44,55,66], 2), (333, [0,11,22,33], -1)]
mytup = [(111, [1,2,3,4,5], 0),
         (222, [33,44,55,66], 2),
         (444, [1,2,3,4,5], 0),
         (333, [0,11,22,33], -1),
         ('a', [5,6,7], -2)]

def SfromTuple(row):
    name, data, shift = row
    return pd.Series(data, index = arange(shift, len(data) + shift))

reindexed = pd.concat([SfromTuple(row) for row in mytup], axis=1)
reindexed.columns = [x[0] for x in mytup]
print(reindexed)

rawDescription: Creating dataframe by adjusting the index taken from list of tuples


code: s = df['addr']

rawDescription: Pandas: Efficient way to get first row with element that is smaller than a given value


rawDescription: how can i return the nodes in pre-order from encoded tuple

description: Return the nodes in pre-order from encoded tuple


code:
def loo(x):
    return [[el for el in x if el!=x[i]] for i in range(len(x))]

rawDescription: Leaving one item out in a python list and print paths


code:
# assuming unordered_dict is a dict that contains your data
ordered_dict = OrderedDict()
for key, value in sorted(unordered_dict.iteritems(), key=lambda t: t[0]):
    ordered_dict[key] = value

rawDescription: Python OrderedDict ordered by date

description: Python OrderedDict ordered by date


code:
import functools
import time

def interval_assured(interval):
    """Ensure consecutive calls are separated by a minimal interval."""
    def wrapper(f):
        @functools.wraps(f)
        def func(*args, **kwargs):
            if (time.time() - func.last_time) < interval:
                time.sleep(interval)
            result = f(*args, **kwargs)
            func.last_time = time.time()
            return result
        func.last_time = time.time()
        return func
    return wrapper

rawDescription: Assure minimal wait between calls with decorators


code: match = min(d_origins, key=lambda p: dist(p, origin['point']))

rawDescription: Finding closest pair of coordinates from a list


code:
l
f

rawDescription: Python dynamic function attribute

description: Python dynamic function attribute


rawDescription: Converting strings to integers then ordering them in an list with strings


rawDescription: how to convert xml into list

description: Convert xml into list


code:
from abc import ABCMeta, abstractmethod

class SomeAbstractClass(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def this_method_must_be_overridden(self):
        return "But it can have an implementation (callable via super)."

class ConcreteSubclass(SomeAbstractClass):
    def this_method_must_be_overridden(self):
        s = super(ConcreteSubclass, self).this_method_must_be_overridden()
        return s.replace("can", "does").replace(" (callable via super)", "")

rawDescription: Python abstract classes - how to discourage instantiation?


rawDescription: Setting the order of output for a table

description: Setting the order of output for a table


rawDescription: Trying to manipulate data, assign a list to the first item in a higher list, second item will be information about that list


code: random_id_list = random.sample(read_id_list, num_reads)

rawDescription: Python very slow random sampling over big list


rawDescription: Accept everything until "more than 1 white space", using pyparsing


code: {u'key1': u'value1', u'key2': u'value2'}

rawDescription: Loading key value pairs from a file to mongodb in Python


rawDescription: How to iterate over time periods in pandas

description: Iterate over time periods in pandas


rawDescription: Single dash for argparse long options

description: Single dash for argparse long options


code:
from itertools import islice
l = ["1", "2", "3", "4", "5"]
c, b, a =  map("something{}".format ,  islice(reversed(l), 3))
a,b,c

rawDescription: Python, assign the last three elements of a list to individual variables


code: sum(v[1] for d in myList for v in d.itervalues())

rawDescription: Python List of Dictionaries[int : tuple] Sum


code:
class TodoSerializer(serializers.ModelSerializer):
    category = PrimaryKeyRelatedByUser(required=False, allow_null=True, queryset=Category.objects.all())
    tags = PrimaryKeyRelatedByUser(required=False, many=True, queryset=Tag.objects.all())

class Meta:
    model = Todo
    fields = ('id', 'category', 'tags', ...)

rawDescription: Limit choices and validate django's foreign key to related objects (also in REST)


code:
class Struct(object):
    pass

rawDescription: mustache/pystache: Rendering complex objects

description: Mustache/pystache: Rendering complex objects


rawDescription: Modify pandas dataframe values with numpy array


rawDescription: Locating files conditional on file names in python


code:
row = df.ix[2:3]  # this one's a view
row['Day'] = 3

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


code:
def parse(self, response):
    questions = response.xpath('//h2[span = "Classifica"]/following-sibling::center/table//tr')[1:]

    for question in questions:
        item = StackItem()
        item['position'] = question.xpath('td[2]/text()').extract()[0]
        item['team'] = question.xpath('td[3]/a/text()').extract()[0]
        item['point'] = question.xpath('td[4]/b/text()').extract()[0]
        yield item

rawDescription: Scrapy crawled 0 pages

description: Scrapy crawled 0 pages


rawDescription: Extracting Unique String Combinations from List of List in Python


code:
import subprocess
import csv

process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
stdout, stderr = process.communicate()

reader = csv.DictReader(stdout.decode('ascii').splitlines(),
                        delimiter=' ', skipinitialspace=True,
                        fieldnames=['permissions', 'links',
                                    'owner', 'group', 'size',
                                    'date', 'time', 'name'])

for row in reader:
    print(row)

rawDescription: python subprocess output to list or file

description: Python subprocess output to list or file


rawDescription: How can I map 0 to 1 and 1 to -1?

description: Map 0 to 1 and 1 to -1


rawDescription: Pythonic way to write a for loop that doesn't use the loop index


rawDescription: Using beautifulsoup to parse tag with some text


code:
class IterableToFileAdapter(object):
    def __init__(self, iterable):
        self.iterator = iter(iterable)
        self.length = len(iterable)

    def read(self, size=-1): # TBD: add buffer for `len(data) > size` case
        return next(self.iterator, b'')

    def __len__(self):
        return self.length

rawDescription: Progress of Python requests post

description: Progress of Python requests post


rawDescription: generate polynomial in python

description: Generate polynomial in python


code:
a = sqrt(d)
b = sqrt(e)
c = arctan(g/f)

rawDescription: Solving non-linear equations in python

description: Solving non-linear equations in python


code: cutUpText = " ".join(nodups(srcList))

rawDescription: Stripping duplicate words from generated text in python script


code:
# Note that I changed the variable name here so you can see how
# its related to what's passed into url_for
@app.route('/topic/<topic_name>')
def questions(topic_name):
    question = request.args['question']
    return render_template('page.html')

rawDescription: Issues sending and receiving a GET request using Flask


code:
def value_to_time(val):
    if val == 'now':
        return -11
    if val.endswith('min'):
        return -11 + int(val[:-3])
    hours, minutes = map(int, val.split(':'))
    return hours * 60 + minutes

rawDescription: Python - sorting a tuple, characters over numbers


rawDescription: Regular Expression for a pattern of 45 hex numbers OR 48 hex numbers - Python


code:
def compose(*funcs):
    def f(x):
        ret = x
        for func in funcs[::-1]:
            ret = func(ret)
        return ret
    return f

rawDescription: Can't figure this function composition code


code:
from collections import OrderedDict
l = [(7, 36), (8, 36), (9, 36), (12, 36), (13, 37), (15, 37), (23, 37), (65, 78)]

seen = OrderedDict()
for first, second in l:
    if first > seen.get(second, None):
        seen[second] = first

[(x, y) for y, x in seen.items()]

rawDescription: Deleting all tuples except ones with the smallest gap between integers, in the list of tuples


code:
len(''.join(s.split('AB'))) == 0
len(''.join(s.split('ABA'))) == 0
len(''.join(s.split('ABAB'))) == 0

rawDescription: Boolean expression with strings

description: Boolean expression with strings


code:
class userProfile(models.Model):
    user = models.OneToOneField(User, related_name='profile')
    USER_RATING_CHOICES = (("1 star", "1 Star(s)"), ("2 star", "2 Star(s)"), ("3 star", "3 Star(s)"), ("4 star", "4 Star(s)"), ("5 star", "5 Star(s)"))
    userRating = models.CharField("User rating", max_length=6, choices=USER_RATING_CHOICES, default="1 star")

rawDescription: How to access a field from an extended user in Django?

description: Access a field from an extended user in Django


rawDescription: pexpect: Retrieve log from command run over ssh tunnel

description: Pexpect: Retrieve log from command run over ssh tunnel


code:
#first is the value to signal to go to next group
data_sorter = iter([(week_ago,None), #None placeholder to not keep data from before week_ago
                    (day_ago,data_Week),
                    (None,data_24)]) #no split for last one, just take the rest of data until end of reader
split_time,current_data = next(data_sorter)
for row in f_reader:
    stringRowDate = row[0]
    Date = datetime.datetime.strptime(stringRowDate,"%Y-%m-%d %H:%M")
    if split_time is not None and (Date > split_time):
        split_time,current_data = next(data_sorter)
    if current_data is not None: #make sure there is no placeholder
        current_data[row[0]] = row[1:]

rawDescription: Iterate over . csv file --> write into two dictionaries


code:
class SkillRecord(models.Model):
    player          = models.ForeignKey(Player, related_name='skills')
    date            = models.DateTimeField(default=datetime.datetime.now)

rawDescription: Django Query including a table where no relation can be followed


code:
def __init__(self):
    print(self.__class__.b) # __class__ works for a new-style class, too
    print(type(self).b)

rawDescription: Python: Reference to a class generically in an instance method?


code:
from subprocess import check_call

check_call(["python", "2ndpythonscript.py" ,"input_variable" ,"output_variable"])

rawDescription: Calling a python script which has input Fields


code:
if window_width == 100:
    width = 4.5
elif window_width == 300:
    width = 13.5

rawDescription: tkinter wrap text if larger than column width

description: Tkinter wrap text if larger than column width


code: call('tool.exe changes="%s"' % var, shell=True)

rawDescription: how do I pass a var including the quotes("")

description: Pass a var including the quotes("")


code:
import ctypes

# Load DLL into memory.

hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll")

# Set up prototype and parameters for the desired function call.
# HLLAPI

hllApiProto = ctypes.WINFUNCTYPE (
    ctypes.c_int,      # Return type.
    ctypes.c_void_p,   # Parameters 1 ...
    ctypes.c_void_p,
    ctypes.c_void_p,
    ctypes.c_void_p)   # ... thru 4.
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0),

# Actually map the call ("HLLAPI(...)") to a Python name.

hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)

# This is how you can actually call the DLL function.
# Set up the variables and call the Python name with them.

p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p (sessionVar)
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))

rawDescription: How can I use a DLL file from Python?

description: Use a DLL file from Python


code: dm = pdist(X, lambda u, v: np.sqrt(((u-v)**2).sum()))

rawDescription: Clustering in python(scipy) with space and time variables


rawDescription: python: id() of mutable object - explanation interesting pattern?

description: Python: id() of mutable object - explanation interesting pattern


code:
{ "_id" : "1234gbrghr", "Device" : "samsung", "UserId" : "12654", "Month" : "july" }
{ "_id" : "1278gbrghr", "Device" : "nokia", "UserId" : "87654", "Month" : "july" }
{ "_id" : "1239gbrghr", "Device" : "samsung", "UserId" : "12654", "Month" : "july" }
{ "_id" : "1238gbrghr", "Device" : "samsung", "UserId" : "12653", "Month" : "july" }

rawDescription: How to use distinct with pipeline in mongodb using python

description: Use distinct with pipeline in mongodb using python


code:
class A:
    def __init__(self):
        self._init_var()

    def _init_var(self):
        self.var = 11

class B(A):
    def __init__(self):
        A.__init__(self)

    def _init_var(self):
        self.var = 10

rawDescription: Why doesn't this superclass run methods in a subclass during initialization?


code:
''.join('%{0:X}'.format(ord(c)) for c in u"杭州".encode('gbk'))
''.join('%{0:X}'.format(ord(c)) for c in u"大连".encode('gbk'))

rawDescription: Python Unicode Conversions

description: Python Unicode Conversions


code:
def fileswithcmonth(dirname, whatmonth):
    results = []
    for f in os.listdir(dirname):
        fullname = os.path.join(dirname, f)
        if whatmonth == cmonth(fullname):
            results.append(fullname)
    return results

rawDescription: Python dealing with dates and times

description: Python dealing with dates and times


code:
class Toy(object):
    def __new__(cls, *args, **kwargs):
        x = np.random.uniform() <= 0.5
        if x:
            return super(Toy, cls).__new__(cls, *args, **kwargs)
        logger.info('Returning None')

rawDescription: Parallel and conditional: NoneType object has no attribute '__dict__'


code:
from random import randint

number = randint(0, 9)
print("Write will create", number, "random numbers")

rawDescription: How do i make it say: "Write will create (random number goes here) random numbers

description: Make it say: "Write will create (random number goes here) random numbers


code: u = odeint(deriv, u0, t)

rawDescription: plotting orbital trajectories in python

description: Plotting orbital trajectories in python


rawDescription: Can a constructor for a super class return instances of a sub class instead?


code:
with open(filename, 'w') as f:
    for key, value in d.items():
        f.write('{}  {}\n'.format(key, value))

rawDescription: How to read from file, turn into a dictionary and write to the same file

description: Read from file, turn into a dictionary and write to the same file


code: isinstance(C(1), C)

rawDescription: Changing the bases of an object based on arguments to __init__


rawDescription: How can I get the proper capitalization for a path?

description: Get the proper capitalization for a path


code:
TROGA_TONTA
TROGA_SONTA
TROGA_JONTA
TROGA_BONTA

rawDescription: Replace part of a matched string in python


code:
class FirstTenDict(dict):
    def __init__(self, pairs):
        super(FirstTenDict, self).__init__(pairs[:10])

data = json.loads(json_string, object_pairs_hook=FirstTenDict)

rawDescription: Load part of a json in python

description: Load part of a json in python


code: keys, inv = np.unique(data, return_inverse=True)

rawDescription: Numpy: Convert values in a 1-D array based upon dictionary


code:
import timeit
timeit.timeit("''.join(x)", "x=('a', 'b')", number=int(1e6))

rawDescription: Can my use of paste0() in R be corrected so that this function runs as fast as the original Python example?


code:
def combinations(list1, list2):
    return ([opt1, opt2, opt3]
            for opt1 in list1
            for opt2 in list1
            for opt3 in list2 if opt1 != opt2)

rawDescription: Testing all combinations in Python

description: Testing all combinations in Python


code:
class Player(object):
    def __init__(self):
        self.Items = set()

class Item(object):
    def __init__(self):
        self.Equipped = 0

class Leather_Pants(Item):
    def __init__(self):
        pass # there is nothing to do here
    def Pick_Up(self, owner):
        self.owner.Items.add(self)
    def Equip(self):
        self.Equipped = 1

rawDescription: Creating dynamic variables for a class from within the class


code:
a = np.arange(5)
a.flags

rawDescription: How can I verify when a copy is made in Python?

description: Verify when a copy is made in Python


rawDescription: Use regex to parse parameter line with whitespace in parameters but without quotes


code:
from tkinter import *

root = Tk()
frame=Frame(root)
Grid.rowconfigure(root, 0, weight=1)
Grid.columnconfigure(root, 0, weight=1)
frame.grid(row=0, column=0, sticky=N+S+E+W)
grid=Frame(frame)
grid.grid(sticky=N+S+E+W, column=0, row=7, columnspan=2)
Grid.rowconfigure(frame, 7, weight=1)
Grid.columnconfigure(frame, 0, weight=1)

#example values
for x in range(10):
    for y in range(5):
        btn = Button(frame)
        btn.grid(column=x, row=y, sticky=N+S+E+W)

for x in range(10):
  Grid.columnconfigure(frame, x, weight=1)

for y in range(5):
  Grid.rowconfigure(frame, y, weight=1)

root.mainloop()

rawDescription: How to create a self resizing grid of buttons in tkinter?

description: Create a self resizing grid of buttons in tkinter


code: r'WHATEVER AND (%s) (%s)' % (r1.pattern, 'hello')

rawDescription: Nested Regular Expression in Python for

description: Nested Regular Expression in Python for


code:
element = ('h', 'e', 'l', 'l', 'o')
for character in element:
    print(character)

rawDescription: List conversion/transformation

description: List conversion/transformation


code:
xx.shape
xx

rawDescription: "stacking" arrays in a new dimension?

description: "stacking" arrays in a new dimension


code:
import datetime
datetime.datetime.strptime('16234', '%y%j').date()

rawDescription: Python3 convert Julian date to standard date


rawDescription: Fetching a IP from text file using python


code:
class LevelMap():
    ...
    def get_tile(self, x, y):
        return self.level_array[y][x]

map = LevelMap()
tile = map.get_tile(0, 1)
# or
location = (0, 1)
tile = map.get_tile(*location)

rawDescription: Assigning unique names to each square in a game map


code:
from astropy.cosmology import WMAP9 as cosmo
H0 = cosmo.H(0)
H0.value, H0.unit

rawDescription: loading issue of subpackages in astropy 0.3 in ubuntu 14.04

description: Loading issue of subpackages in astropy 0.3 in ubuntu 14.04


code: [a[0:3] for a in matrix]

rawDescription: Extract variable number of columns for a matrix


code:
'''
Created on Apr 23, 2015

@author: chris
'''
import Queue

class JobManagement:
    incoming_queue = Queue.Queue(maxsize=10)
    incoming_jobs = []
    current_job = None
    finished_jobs = []

rawDescription: Python: Blocking issues with a queue and threads


code:
columnsToReplace = ['var1001', 'var1002', ...]
df.ix[df.type==8, columnsToReplace] = 0

rawDescription: Python/pandas idiom for if/then/else

description: Python/pandas idiom for if/then/else


code:
from operator import itemgetter
# min of all elements
mn = min(nl, key=itemgetter(1))[1]

# remove elements equal to min
filtered = [x for x in nl if x[1] != mn]

# get min of remaining
mn_fil = min(filtered,key=itemgetter(1))[1]

# filter remaining
out = [x for x in filtered if x[1] == mn_fil]
print(out)

[['Harsh', 20], ['Beria', 20]]

rawDescription: How to find the second lowest lists into a nested list by their second value?

description: Find the second lowest lists into a nested list by their second value


code:
import curses
stdscr = curses.initscr()

for i in range(10):
    stdscr.addch(i, 10-i, '/')
    stdscr.addch(i, 11 + i, '\\')

for i in range(2, 20):
    stdscr.addch(9, i, '_')

stdscr.getch()

rawDescription: How could I design none square symbol in ncurses?


rawDescription: Python Pandas overlapping data with TimeGrouper


code:
search_string = ';              Q8CCS6 '
no_space_in_string = sum(c.isprintable() for c in search_string)
no_space_in_string
search_string[:no_space_in_string]
' '.isprintable()

rawDescription: python - pandas dataframe string search - problems with ";" ?

description: Python - pandas dataframe string search - problems with ";"


code: matches = filter(fulfills_some_condition, lst)

rawDescription: Python: Find in list

description: Python: Find in list


code:
from sqlalchemy import *
import sqlalchemy.ext.declarative

Base = sqlalchemy.ext.declarative.declarative_base()

class TableA(Base):
    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)
    a_code = Column(String)

class TableB(Base):
    __tablename__ = 'b'
    id = Column(Integer, primary_key=True)
    b_code = Column(String)

rawDescription: Mapping a 'fake' object in SQLAlchemy

description: Mapping a 'fake' object in SQLAlchemy


code:
class Character:
    def scan(self, monster):
        print("{} is {} and has {} HP.".format(
            monster.__name__, monster.color, monster.HP))

rawDescription: How to call or refer to an instance attribute from another's class method

description: Call or refer to an instance attribute from another's class method


code:
[u'Logged-in users', u'True', u'True', u'True', u'True']
[u'User 1', u'Confirm', u'Confirm', u'Site', u'Confirm']
[u'User 2', u'Confirm', u'Confirm', u'Confirm', u'Confirm']
[u'User 3', u'Confirm', u'Confirm', u'Confirm', u'Confirm']
[u'User 4', u'Confirm', u'Site', u'Site', u'Confirm']

rawDescription: Beautiful soup, html table parsing

description: Beautiful soup, html table parsing


code:
# dbcli.py
import plac
from sqlalchemy.ext.sqlsoup import SqlSoup

@plac.annotations(
    db=plac.Annotation("Connection string", type=SqlSoup),
    header=plac.Annotation("Header", 'flag', 'H'),
    sqlcmd=plac.Annotation("SQL command", 'option', 'c', str, metavar="SQL"),
    delimiter=plac.Annotation("Column separator", 'option', 'd'),
    scripts=plac.Annotation("SQL scripts"),
    )
def main(db, header, sqlcmd, delimiter="|", *scripts):
    "A script to run queries and SQL scripts on a database"
    yield 'Working on %s' % db.bind.url

    if sqlcmd:
        result = db.bind.execute(sqlcmd)
        if header: # print the header
            yield delimiter.join(result.keys())
        for row in result: # print the rows
            yield delimiter.join(map(str, row))

    for script in scripts:
        db.bind.execute(open(script).read())
        yield 'executed %s' % script

if __name__ == '__main__':
    for output in plac.call(main):
        print(output)

rawDescription: (semi-) automatic generation of argparsers for functions


rawDescription: Filter non-existing GenericForeignKey objects in Django queryset


rawDescription: filter items by value in dict

description: Filter items by value in dict


code: moveParticles(pos, lastpos, velocity, 1)

rawDescription: Writing calculation results back into its array?


code:
rddCalculated = (
    rddData
        .repartition(200)
        .map(
            lambda l, dInputData=dInputData: TheThing(dInputData, l).does_the_thing()
        )
)

rawDescription: Dataproc Pyspark job only running on one node


code: scroll_area = pyglet.text.layout.ScrollableTextLayout(my_text, width, height, multiline=True)

rawDescription: Render and scroll through multiline paragraphs using pyglet and ScrollableTextLayout


code:
import sys

if sys.version_info >= (3, 3, 0):
    from inspect import getclosurevars

def is_recursive(func):
    if sys.version_info >= (3, 3, 0):
        return getclosurevars(func).globals.get(func.__name__) is func
    else:
        # We can implement part of it if it's not in our standard library
        def global_vars_in_closure(func):
            vars = {x: func.__globals__.get(x) for x in func.__code__.co_names}
            return vars

        return global_vars_in_closure(func).get(func.__name__) is func

rawDescription: Search for recursive functions in a Python project


code:
# get groups by key
print('specific group only:')
print(groups.get_group('54321'))

rawDescription: Read hierarchical (tree-like) XML into a pandas dataframe, preserving hierarchy


code:
fig, ax = plt.subplots()
w = sum(end)/len(end)/10 #change the width of the bar
for i in range(len(ids)):
    ax.bar(start[i], ids[i], width=end[i])

plt.show()

rawDescription: Plot large data in the specified format using python


code: re.match(r'\d.*{}.*\d'.format(re.escape(p)), '1 foo+*bar 2')

rawDescription: How to escape special regex characters in a string?

description: Escape special regex characters in a string


code:
import lxml.etree

text = """
<root>
  <pgBreak pgId="1"/>

    some text to fill out a para
    <pgBreak pgId="2"/>
    some more text
    <quote> A quoted block </quote>
    remainder of para
    <pgBreak pgId="3"/>

       blurb

</root>
"""

root = lxml.etree.fromstring(text)
for pgbreak in root.xpath('//pgBreak'):
    inner = pgbreak.getparent()
    if inner == root:
        continue
    outer = inner.getparent()
    pgbreak_index = inner.index(pgbreak)
    inner_index = outer.index(inner) + 1
    siblings = inner[pgbreak_index+1:]
    inner.remove(pgbreak)
    outer.insert(inner_index,pgbreak)
    if siblings[0].tag != 'p':
        p = lxml.etree.Element('p')
        p.text = pgbreak.tail
        pgbreak.tail = None
        for node in siblings:
            p.append(node)
        outer.insert(inner_index+1,p)
    else:
        for node in siblings:
            inner_index += 1
            outer.insert(inner_index,node)

rawDescription: xpath to select from child element to end of parent

description: Xpath to select from child element to end of parent


code:
with my_queue.mutex:
    if x not in my_queue:
        my_queue.put(x)

rawDescription: Check if element is already in a Queue

description: Check if element is already in a Queue


code:
def generate_TimeSERIE_preLAGs( aTimeSERIE, pre_lag_window_depth ):
    #
    # COURTESY & THANKS TO:
    #                     Nicolas P. Rougier, INRIA
    #             Author: Joe Kington / Erik Rigtorp
    #
    shape   = ( aTimeSERIE.size - pre_lag_window_depth + 1,
                pre_lag_window_depth
                )
    strides = ( aTimeSERIE.itemsize,
                aTimeSERIE.itemsize
                )
    return np.lib.stride_tricks.as_strided( aTimeSERIE,
                                            shape,
                                            strides = strides
                                            )
xVECTOR = np.arange( 10 )
pre_laggz_on_xVECTOR = generate_TimeSERIE_preLAGs( xVECTOR, 4 )
pre_laggz_on_xVECTOR

rawDescription: How to auto-discover a lagging of time-series data in scikit-learn and classify using time-series data

description: Auto-discover a lagging of time-series data in scikit-learn and classify using time-series data


code:
f = open('file1', 'r')
name = f.readline()

rawDescription: Take all lines from one txt file and copy them to a new text file with some extras


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

# define a dict with sample data
d = {'fruit': 13}

# print keys and values of sample dict
for key, val in d.items():
    print(key, val)

rawDescription: How to print varible name in python

description: Print varible name in python


code: pd.Series(*zip(*((b,a) for a,b in data)))

rawDescription: python key value list to panda series

description: Python key value list to panda series


code:
def foo():
    return sys._getframe(0).f_code.co_name

foo()
bar = foo
bar()

rawDescription: Scope of function inside the function (understanding recursion)


code: titles = soup.find_all('h1 class="title multiline"')

rawDescription: find_all() not finding any results when using Beautiful Soup + Requests

description: Find_all() not finding any results when using Beautiful Soup + Requests


code:
from csv import DictReader
from io import StringIO

stringios = []

with open('file.csv', 'r') as f:
    stringio = None
    for line in f:
        if line.startswith('ClientAccountID'):
            if stringio is not None:
                stringio.seek(0)
                stringios.append(stringio)
            stringio = StringIO()
        stringio.write(line)
        stringio.write("\n")
    stringio.seek(0)
    stringios.append(stringio)

rawDescription: Splitting Rows in csv on several header rows


code:
# ...
for p in gener:
    print(p)
    for v in p: counts[v] += 1

rawDescription: Python: how to optimize the count of all possible shortest paths?


code: (pastpresent[:,1][:,np.newaxis] + 1 > np.arange(nlayers+2)).astype(int)

rawDescription: Slicing different rows of a numpy array differently


code:
import os, time, tkinter, urllib
from tkinter import *
from urllib.request import *
from urllib.error import *

class App:
    def __init__(self, master):
        start_time = time.time()
        self.master = master
        self.frame = Frame(master)
        self.frame.pack()
        self.label = Label(self.frame, text="")
        self.label.pack()
        self.start_time = time.time()

    def internet_on(self):
        try:
            response=urllib.request.urlopen('http://www.google.com.br',timeout=1)
            self.label.config(text="Internet is online")
        except urllib.error.URLError as err:
            self.label.config(text="Internet is offline!  Downtime: " + str(time.time() - self.start_time))
        self.master.after(5000,self.internet_on)
top = tkinter.Tk()
app = App(top)
top.after(5000,app.internet_on)
top.mainloop()

rawDescription: Tkinter set new value for labels

description: Tkinter set new value for labels


code:
# from [0.0, 1.0], but upper boundary not guaranteed
x = random.uniform(0, 1)

rawDescription: How do I generate random numbers from [0,1]?

description: Generate random numbers from [0,1]


code:
from collections import defaultdict, Counter
import xlrd

workbook = xlrd.open_workbook('filter_data.xlsx')
worksheet = workbook.sheet_by_name('filter_data')

first_col = 0
scnd_col = 1
third_col = 2

celldict = defaultdict(Counter)
for curr_row in range(1, worksheet.nrows): # start at 1 skips header row

    cell0_val = int(worksheet.cell_value(curr_row, first_col))
    cell1_val = worksheet.cell_value(curr_row, scnd_col)
    cell2_val = worksheet.cell_value(curr_row, third_col)

    if cell2_val == 'toSkip' and cell1_val[:3] in ('BL1', 'OUT'):
        continue

    celldict[cell0_val][cell1_val] += 1

rawDescription: skip excel lines with python

description: Skip excel lines with python


code:
from collections import defaultdict

results = defaultdict(list)

with open('somefile.txt') as f:
   for line in f:
      if line.strip():
         value, key = line.split(',')
         if '_' in key:
             key = key.split('_')[0] # returns var1 from var1_val1
         results[key].append(value)

for k,v in results.iteritems():
    print('{} {}'.format(k, ' '.join(v)))

rawDescription: Iterating through file multiple times (Python)


code: uni_name = soup.title.string

rawDescription: To use BeautifulSoup to extract parts of texts in webpage title


code:
questions = {'What is 5 + 4?' : 9,
             'What is 3 - 1?' : 2}

rawDescription: How could I loop a code involving a list


code: pivoted.cumsum() + (pivoted == -1)

rawDescription: Create new pandas timeseries dataframe from other dataframe


code:
class MediaItem(models.Model):
    objects = MediaItemManager()
    all_objects = models.Manager()

rawDescription: In Django, how do I gracefully add a queryset filter to a large group or all members of an object?


code: print(' '.join(str(key)+":"+str(value) for key,value in dicMyDictionary.iteritems()))

rawDescription: Dictionary all for one

description: Dictionary all for one


code:
def calc_histo(slice):
    # process the slice asyncronously
    return np.histogram(slice, bins=BINS,
        range=(DMIN, DMAX))[0].astype(np.int32)

def calc_sync(start,stop):

    histo = None

    # grab a chunk of data, you likely don't need to lock this
    histo = raw_data[start:stop]

    # acutal calculation is async
    result = calc_histo(histo)

    with histo_shared.get_lock():
         histo_shared += result

rawDescription: Using numpy array in shared memory slow when synchronizing access


rawDescription: What is the purpose of the `//` operator in python?


code: os.write(tup[0], "foo\n")

rawDescription: Python - How do I convert "an OS-level handle to an open file" to a file object?


code: test = [sum(elem) for elem in izip(test, repeat(1))]

rawDescription: Increase each list element in all possible ways


rawDescription: Python: How to remove whitespace from number in a string


code: norm = [float(i)/max(raw) for i in raw]

rawDescription: Normalizing a list of numbers in Python

description: Normalizing a list of numbers in Python


code:
import types

instance = getattr(types, typename)(arguments)

rawDescription: Create a set of objects when their type is set by ini file (Python)


code:
series = pd.Series([1,2,3,4,5])
between(1,3)(series)

rawDescription: Customizing rolling_apply function in Python pandas


code:
op       = lambda: x.get('eggs', x.get('spam'))
aaron    = lambda: x.get('eggs') or x.get('spam')
ndpu     = lambda: filter(None, map(x.get, ['eggs', 'spam']))[0]
mhlester = lambda: x['eggs'] if 'eggs' in x else x.get('spam')
timeit(op, number=100000)
timeit(aaron, number=100000)
timeit(ndpu, number=100000)
timeit(mhlester, number=100000)

rawDescription: Is there something better than dict.get(<thing>, dict.get(<other>))?


code:
I, J = D[:,0], np.zeros(D.shape[0],int)
M1=sparse.coo_matrix((D[:,1],(I, J)), shape=(7000,1))
M2=sparse.coo_matrix((D[:,2],(I, J)), shape=(7000,1))
print(sparse.bmat([[M1,M2]]))

rawDescription: How do I create a scipy sparse matrix from a pandas dataframe?

description: Create a scipy sparse matrix from a pandas dataframe


rawDescription: PyQt4 : How can i toggle the "Stay On Top" behavior?


code: storage = [set() for i in range(35)]

rawDescription: List of sets, set.add() is adding to all sets in the list


code:
app = App()
app.add_buttons()
window.mainloop()

rawDescription: Button excecutes command once (Tkinter)

description: Button excecutes command once (Tkinter)


code:
def factorial( *args ):
    def fact( n ):
        if n == 0: return 1
        return n*fact(n-1)
    return [ fact(a) for a in args ]

rawDescription: Single implementation to cover both single and multiple values in Python?


code:
import collections

d = collections.defaultdict(lambda: collections.deque(maxlen=4))
# defaultdict accepts as an argument a function that returns the default
#   state of the value of undefined keys. In this case we make an anonymous
#   function that returns a `collections.deque` with maxlen of 4.

# we could also do
# # import functools, collections
# # d = collections.defaultdict(functools.partial(collections.deque,
# #                                               maxlen=4))

with open('path/to/file.txt', 'r') as infile:
    for line in infile:
        player,score = line.strip().split(":")
        d[player].append(int(score))

rawDescription: Making each key store a maximum of 5 values in Python Dictionary


code:
Test.ponk = "blork"
a = Test()
a.ponk is Test.ponk
a.modify_state()
a.ponk is Test.ponk

rawDescription: Trying to understand instance variables in python


code:
fig, ax = plt.subplots(1, 1)
df = DataFrame(rand(5, 3), columns=['a', 'b', 'c'])
ax.get_xaxis().set_visible(False)   # Hide Ticks
df.plot(table=True, ax=ax)

rawDescription: Adding datalabels - matplotlib barchart

description: Adding datalabels - matplotlib barchart


code:
class AttrDict(dict):
    def __init__(self, *args, **kw):
        super(AttrDict, self).__init__(*args, **kw)
        self.__dict__ = self

rawDescription: Using Python to create a dictionary with setters and getters


code:
re.findall(r'\d+', u'The answer is \u0664\u0662')         # No flag
re.findall(r'(?u)\d+', u'The answer is \u0664\u0662')     # With unicode flag

rawDescription: What does (?ui) mean in a Python regex?

description: What does (?ui) mean in a Python regex


code:
bitext = []
for i, pair in enumerate(zip(open(c_data), open(e_data))):
    if i < opts.num_sents:
        sentence_pair = []
        for sentence in pair:
            if len(sentence) < 100:
                sentence_pair.append(sentence.strip().split())
        if len(sentence_pair) > 1:  # ie both sentences are < 100
            bitext.append(sentence_pair)

rawDescription: Python if-statement within list comprehension


code:
next_string('11A')
next_string('11A')
next_string('11Z')
next_string('119')
next_string('1')
next_string('ZZ')
next_string('ZZ1')
next_string('ZZ9')
next_string('ZZH')

rawDescription: Python: Alphanumeric Serial Number with some rules


code:
my_values = Range('Sheet1','A1:A6', atleast_2d=True).value
Range('Sheet2','A1:A6').value = my_values

rawDescription: python xlwings - copy and paste ranges

description: Python xlwings - copy and paste ranges


code:
# There is nothing restricting their type.
CONST_A = "<something>"
CONST_B = ["other value", "type is irrelevent"]

parser = MappedParser() #constructor is same

parser.def_mapping(foo={"A":CONST_A, "B":CONST_B})

parser.add_argument("--foo") # and this is unchanged

# the following is now true:
print(parser.parse_args("--foo A".split()).foo is CONST_A)
print(parser.parse_args("--foo B".split()).foo is CONST_B)
#note that 'is' operator works so it is even the same reference

#this gives decent error message
parser.parse_args("--foo INVALID".split())

print("when parser.error() is called the program ends so this never is printed")

rawDescription: argparse: map user input to defined constant

description: Argparse: map user input to defined constant


code: scipy.optimize.minimize(fun, x0, args=(), method=None, jac=None, hess=None, hessp=None, bounds=None, constraints=(), tol=None, callback=None, options=None)

rawDescription: How to use scipy to optimize the position of n points?

description: Use scipy to optimize the position of n points


code:
def startbars(query_name, commodity_name):

    assert query_name in INNOVOTABLE_FIELD_NAMES

    ## TODO: Replace with proper SQL query
    query = """ SELECT wbcode, Year, """+query_name+"""
             FROM innovotable WHERE commodity='"""+commodity_name+"""' and

             """+query_name+""" != 'NULL' """
    rows = cursor.execute(query)

    data = []
    maxField = None

    for row in rows:
        an_year = int(row[1])
        if an_year < 1961 or an_year > 2031:
            continue

        wbCode = str(row[0])
        if wbCode not in result:
            continue

        n = float(row[2])

        data.append((wbCode+str(an_year),n))
        if maxField is None or n > maxField:
            maxField = n

    constant = 8.0 / maxField

    global h_list
    h_list = {}

    for (skey,n) in data:
        h_list[skey] = constant * n

rawDescription: Optimize two simple nested loops

description: Optimize two simple nested loops


rawDescription: Python for loop with a tuple in it

description: Python for loop with a tuple in it


code:
from random import shuffle
from time import time
seq = range(1000000)
shuffle(seq)
def time_it(func, *args, **kwargs):
    t0 = time()
    func(*args, **kwargs)
    return time() - t0
#here I define the above function, two_largest().
from heapq import nlargest
time_it(nlargest, 2, seq)
time_it(two_largest, seq)

rawDescription: More pythonic way to find first two greatest value in a list in python


code:
from pandas import *
import matplotlib
from numpy.random import rand
import matplotlib.pyplot as plt
df = DataFrame(rand(10,2), columns=['Col1', 'Col2'] )
df['X'] = Series(['A','A','A','A','A','B','B','B','B','B'])
bp = df.boxplot(by='X')
cl=bp[0].get_children()
cl=[item for item in cl if isinstance(item, matplotlib.lines.Line2D)]

rawDescription: Styling of Pandas groupby boxplots

description: Styling of Pandas groupby boxplots


code:
import numpy as np
A = np.ones((5,5), dtype=int)
B = [1, 3, 7, 23]
A
A_ = A.ravel()
A_[B] = 0
A_.reshape(A.shape)

rawDescription: Python: multidimensional array masking

description: Python: multidimensional array masking


code:
# testutils.py
class LogCheckerMixin(object):
    """ this class adds log checking abilities to a TestCase.
    """
    def check_logs(self, logs, **kw):
       self.assertWhatever(something)

# myserver/tests.py
import unittest
from testutils import LogCheckerMixin

class MyServerTest(unittest.TestCase, LogCheckerMixin):
    def test_log1(self):
        logs = extract_the_logs()
        self.check_logs(logs, log_1=1, log2='foo')

rawDescription: Python unittest: having an external function for repetitive code in different modules


code:
fig, ax = plt.subplots()
[vals[['col2','col3']].plot.scatter(x='col2', y='col3', ax=ax, label=grp)
 for grp, vals in df.groupby('col4')]

rawDescription: Multiple inputs multivariate data visualisation


code: ", ".join([repr(y) for y in x])

rawDescription: String of strings for arbitrary amount, python


code:
def rolling_prod1(xs, n):
    return np.exp(pd.rolling_sum(np.log(xs), n))

rawDescription: Fast numpy rolling_product

description: Fast numpy rolling_product


code: product_list = ndb.gql("SELECT * FROM Post")

rawDescription: templating in python with GAE using GQL

description: Templating in python with GAE using GQL


code:
import urllib
from xml.etree import ElementTree

class News():

    base_url = 'http://finance.yahoo.com/rss/headline?s='
    query = 'goog'

    url = base_url + query
    response = urllib.urlopen(url)
    data = response.read()

    dom = ElementTree.fromstring(data)
    items = dom.findall('channel/item')

    for item in items:
        print(item.find('title').text)

rawDescription: cannot extract item element from xml

description: Cannot extract item element from xml


rawDescription: Assigning the same value to different positions in a list in python


code:
# initialize example data
import numpy as np
B = 1
dt = 1
position =  np.array([4, 4.34, 4.69, 5.02, 5.3, 5.7])

# do calculation
A = np.zeros(len(position) + 1)
A[1:] = np.cumsum((B/position**2)*dt)

rawDescription: How to make numpy.cumsum start after the first value [Python]

description: Make numpy.cumsum start after the first value [Python]


code:
from itertools import islice

def chunks(data, SIZE=10000):
    it = iter(data)
    for i in xrange(0, len(data), SIZE):
        yield {k:data[k] for k in islice(it, SIZE)}

rawDescription: How to split dictionary into multiple dictionaries fast

description: Split dictionary into multiple dictionaries fast


code: (num >> offset*8) & 0xff

rawDescription: Pushing Radix Sort (and python) to its limits


code:
if B[0] == A[0] and B[1] == A[1] and B[2] == A[2]:
    return True
else: return False

rawDescription: Compare List with different number of items


code: image /= image.max()/255.0    # Uses 1+image.size divisions

rawDescription: How to normalize a NumPy array to within a certain range?

description: Normalize a NumPy array to within a certain range


code:
def create_toy(self, fun_0_3, fun_3_4, fun_4_7, fun_7_9, fun_9_plus):
    def toy(self):
        self.happiness_num = float(self.happiness)
        if float(self.age) <= 3.0:
            self.happiness_num = self.happiness_num + fun_0_3
        elif float(self.age) > 3.0 and float(self.age) < 4.0:
            self.happiness_num = self.happiness_num + fun_3_4
        elif float(self.age) > 4.0 and float(self.age) < 7.0:
            self.happiness_num = self.happiness_num + fun_4_7
        elif float(self.age) > 7.0 and float(self.age) < 9.0:
            self.happiness_num = self.happiness_num + fun_7_9
        elif float(self.age) > 9.0:
            self.happiness_num = self.happiness_num + fun_9_plus
            gui.msgbox(
                msg = 'This toy is Only providing minimal fun to your potato head. Either get a new one or play with another!',
                title = 'WARNING!',
                ok_button = 'Understood')
        self.happiness = str(self.happiness_num)
    return toy

#somewhere else
play_Softball = create_toy(0.3, 0.7, 1.0, 0.5, 0.02)

rawDescription: Using a function to create a function in Python


code:
try:
    from settings_prod import *
except ImportError:
    try:
        from settings_test import *
    except ImportError:
        from settings_dev import *

rawDescription: How do I make Django use a different database besides the 'default'?

description: Make Django use a different database besides the 'default'


code:
m = Message.objects.create(*args)
recipients = []
for email in ModelWithEmails.active.values_list('email', flat=True):
    recipients.append(Recipient(message=m, email=email))

Recipient.objects.bulk_create(recipients)

rawDescription: Creating many related objects like INSERT ... SELECT in SQL


code: from mod2 import *

rawDescription: Limit which classes in a .py file are importable from elsewhere


code:
from math import sqrt
from itertools import takewhile

def primes(upper):
    n = 2; foundPrimes = []
    while n < upper:
        sqrtN = int(sqrt(n))
        # If a number n is not divisble through all preceding primes up to sqrt(n), it's prime
        if all(n % div != 0 for div in takewhile(lambda div: div <= sqrtN, foundPrimes)):
            yield n
            foundPrimes.append(n)
        n += 1

rawDescription: Can this be made more pythonic?

description: Can this be made more pythonic


rawDescription: Python - finding same elements in three lists (ignoring empty list)


code:
new_val = []
for x, y in d[key]:
   #In each iteraion x is assigned to VALs and `y` is assigned to (Flag1, Flag2)
   #now append a new value, a tuple containg x and y[0](first item from that tuple)
   new_val.append((x, y[0]))
d[key] = new_val  #reassign the new list to d[key]

rawDescription: How to change a tuple within a value of a dictionary?

description: Change a tuple within a value of a dictionary


rawDescription: Regex works fine on Pythex, but not in Python


code: q1 = Question("How many roads must a man walk down?", ["Think Douglas Adams.", "It's more than 40 and less than 50"], "42")

rawDescription: How to fix this iterative python code and reduce repetition?

description: Fix this iterative python code and reduce repetition


code:
import re

with open('yourfile.txt') as f:
    exampleText = f.read()

new = ''

for line in exampleText.split('\n'):
    if line == '':
        new += '\n\n'
    elif re.search('[a-zA-Z]', line):  # check if there is text
        new += line + ' '
    else:
        new += line + '\n'

rawDescription: Python to combine lines in a txt file

description: Python to combine lines in a txt file


code:
from ticket.views import project_choices

urlpatterns = patterns(
    (r'^product_change/', project_choices),
)

rawDescription: How to set dynamic mapping between two models in django

description: Set dynamic mapping between two models in django


code:
from django.http import HttpResponse

def getclub(request, club_name):
    teaminfo = ModelName.objects.get(name=club_name) # something like that
    return HttpResponse(teaminfo)

rawDescription: JSON/Django http request

description: JSON/Django http request


code: somezip = lambda *p: list(takewhile(lambda e: not e[0] is None,izip_longest(*p)))

rawDescription: Is there a middle ground between `zip` and `zip_longest`


code:
from django.conf.urls import url

# Import ``HomepageView`` here.

urlpatterns = [
    url(r'^$', HomepageView.as_view(), name='homepage'),
    # Other patterns here.
]

rawDescription: Django dynamic homepage

description: Django dynamic homepage


code:
r = re.compile(r'|'.join(separators))
r.split(s)

rawDescription: Using Python: to split long string, by given ‘separators’


rawDescription: pyparsing: Nested countedArray?

description: Pyparsing: Nested countedArray


code:
from scipy.signal import lfilter
num = np.array([1.0])
alpha = 2.0
den = np.array([1.0, -alpha])
a = np.zeros((4,4))
a[0,:] = [1,2,3,4]
lfilter(num, den, a, axis=0)

rawDescription: Trying to vectorize iterative calculation with numpy


code:
def dot_aligned(seq):
    snums = [str(n) for n in seq]
    dots = [s.find('.') for s in snums]
    m = max(dots)
    return [' '*(m - d) + s for s, d in zip(snums, dots)]

nums = [4.8, 49.723, 456.781, -72.18]

for s in dot_aligned(nums):
    print(s)

rawDescription: Formatting Numbers So They Allign On Decimal Point


code:
# your_app/views.py
def rock_and_feat(request):
    feats = Feat.objects.order_by('-num')[:1]
    rocks = Rockinfo.objects.order_by('-rank')[:50]
    context = RequestContext(request, {
        'feats': feats, 'rocks': rocks
    })
    return render_to_response('template.html', context)

rawDescription: django 1.8 using one view in another

description: Django 1.8 using one view in another


code:
class MySerializer(serializers.ModelSerializer):
    thumbnail_url = serializers.SerializerMethodField('get_thumbnail_url')

    def get_thumbnail_url(self, obj):
        return self.context['request'].build_absolute_uri(self.thumbnail_url)

rawDescription: Django REST Framework and FileField absolute url


code:
from django import template

register = template.Library()

@register.inclusion_tag('car.html')
def show_car(car):
    history = get_history_for_car(car)
    return {'name': car.name, 'history': history}

rawDescription: Include tag in Django template language -- what can I pass in to it?


rawDescription: Sorting List of Lists

description: Sorting List of Lists


rawDescription: coordinates (str) to list

description: Coordinates (str) to list


code:
l = [['F', 'G', 'C'], ['S', 3, 7], ['C', 3, 'D']]
[[item for item in sublist if not isinstance(item, int)] for sublist in l]

rawDescription: Python, remove all numbers from sublist

description: Python, remove all numbers from sublist


code:
text_output = ""
for i in range(len(file_2)):
    for j in range(len(file_1)):
        for k in range(len(file_3)):
            text_output += file_2[i] + " " + file_1[j] + " " + file_3 [k] + "\n"

rawDescription: Merge 3 Textfiles with python

description: Merge 3 Textfiles with python


rawDescription: Python set Union and set Intersection operate differently?


code:
def create_grid(grid):
    table = ''

    for y in range(0, LENGTH * WIDTH, WIDTH):
        table += '|'.join(grid[y:y+WIDTH]) + '\n'

    return table

rawDescription: Python: Using two while loops to create grid. No for loops


code:
from itertools import izip_longest
[(x == y == 1) for x, y in izip_longest(Actual, Predicted, fillvalue=0)]

rawDescription: How to compare two arrays in python based on a value

description: Compare two arrays in python based on a value


code:
id(mc)
id(mc.a)
id(mc2)
id(mc2.a)
id(mc3)
id(mc3.a)
id(mc4)      #mc4 is a different object than mc
id(mc4.a)    #and mc4.a is a different object than mc.a

rawDescription: Interesting list behaviour in python

description: Interesting list behaviour in python


code:
# create blueprint in feed/__init__.py
from flask import Blueprint

feed = Blueprint('feed', __name__)
import views

# create blueprint in chat/__init__.py
from flask import Blueprint

chat = Blueprint('chat', __name__)
import views

# add views (endpoints) in feed/views.py
from . import feed

@feed.route('/feed')
def feed():
    return 'feed'

# add views (endpoints) in chat/views.py
from . import chat

@chat.route('/chat')
def chat():
    return 'chat'

# register blueprint and start flask app
from flask import Flask
from expense import expense
from budget import budget

app = Flask(__name__)
app.register_blueprint(feed)
app.register_blueprint(chat)
app.run(debug=True)

rawDescription: flask : how to architect the project with multiple apps?

description: Flask : how to architect the project with multiple apps


code:
stanza = """Old MacDonald had a farm, E-I-E-I-O,
          And on his farm he had a {0}, E-I-E-I-O
          With a {1}-{1} here -
          And a {1}-{1} there -
          Here a {1} there a {1}
          Everywhere a {1}-{1}
          Old MacDonald had a farm, E-I-E-I-O""".format(animal, animalSound)

rawDescription: Beginner python: Formatting Lines

description: Beginner python: Formatting Lines


code:
import io
import csv

file_in = io.StringIO('''
aþbþ'hello
world'
''')

log=csv.reader(file_in, delimiter='\xfe', quotechar="'")
for row in log:
    print(row)

rawDescription: Python csv new line character in field

description: Python csv new line character in field


code: return "sep".join(itertools.chain(dct[u"items"] for dct in myList if dct[u"version"] == version))

rawDescription: Search data object and concatenate items in array of strings


rawDescription: numpys argsort, sorting column based on another one

description: Numpys argsort, sorting column based on another one


rawDescription: String Comparison with a Format - Python


code:
def Sort():
    scores = []
    with open("results.txt") as x:
        # x is open only inside this block!
        for linia in x:
            name, score=linia.split(' ')
            score = int(score)
            scores.append((name, score))
        scores.sort(key=lambda sc: sc[1])

    with open("results.txt", "w") as x:
        # open it a second time, this time with `w`
        for name, score in scores:
            x.write(name + ' ' + str(score))

Sort()

rawDescription: Python file read and write

description: Python file read and write


code: re.split("a(?=b)", "ababba")

rawDescription: retrieving substrings which are not matched by re.findall

description: Retrieving substrings which are not matched by re.findall


code:
def ct_dynamic(r, alpha):
    """alpha: the n-2 values between [0,\pi) and last one between [0,2\pi)
    """
    x = np.zeros(len(alpha) + 1)
    s = 1
    for e, a in enumerate(alpha):
        x[e] = s*np.cos(a)
        s *= np.sin(a)
    x[len(alpha)] = s
    return x*r

rawDescription: n-sphere coordinate system to Cartesian coordinate system

description: N-sphere coordinate system to Cartesian coordinate system


code: a = b if b else {}

rawDescription: What is the official name of this construct?


rawDescription: Returning the index of a string that is not within brackets


code: url = line

rawDescription: Python Read URLs from File and print to file


code:
s.groupby(level=[0,1]).transform("mean")
s >= s.groupby(level=[0,1]).transform("mean")

rawDescription: Drop values below group means with Pandas DataFrame


code:
def remap_args(func, mapping):
    @functools.wraps(func)
    def newfunc(*args, **kwargs):
        newargs = [args[m] for m in mapping]
        return func(*newargs, **kwargs)
    return newfunc

rawDescription: Python counterpart to partial for ignoring an argument


code:
import re
re.findall(r'(?<=@)\w+', 'This is @lame')
re.findall(r'(?<=@)\w+', 'This is lame')
re.findall(r'(?<=@)\w+', 'This is @lame but that is @not')

rawDescription: extracting multiple instances regex python

description: Extracting multiple instances regex python


code:
Parent.counter = 3.14159
class C3(Parent): pass

C3().counter

rawDescription: Parent changing child's attribute

description: Parent changing child's attribute