code:
d1 = {"name":"Joe", "Pets":[{"name":"spot", "species":"dog"}]}
d2 = {"name":"Joe", "Pets":[{"name":"spot", "species":"cat"}]}
dd(d1, d2, "base")

rawDescription: Recursive diff of two python dictionaries (keys and values)


code:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...

rawDescription: python: Open file from zip without temporary extracting it

description: Python: Open file from zip without temporary extracting it


code:
import json
import sqlite3

traffic = json.load(open('xxx.json'))
db = sqlite3.connect("fluxos.sqlite")

query = "insert into medicoes values (?,?,?,?,?,?,?)"
columns = ['local', 'coord', 'sentido', 'veiculos', 'modalidade', 'pistas']
for timestamp, data in traffic.iteritems():
    keys = (timestamp,) + tuple(data[c] for c in columns)
    c = db.cursor()
    c.execute(query, keys)
    c.close()

rawDescription: Convert JSON to SQLite in Python - How to map json keys to database columns properly?


code:
def sequence(*functions):
    def func(*args, **kwargs):
        return_value = None
        for function in functions:
            return_value = function(*args, **kwargs)
        return return_value
    return func

rawDescription: tkinter call two functions

description: Tkinter call two functions


rawDescription: How to pull all the unique combinations from a list of lists

description: Pull all the unique combinations from a list of lists


code: d = dict([(e['name'],e['value']) for e in items])    # transpose

rawDescription: Get Value of a key from List of dictionary


code:
class MyScene(QGraphicsScene):
    def dragEnterEvent(self, e):
        e.acceptProposedAction()

    def dropEvent(self, e):
        # find item at these coordinates
        item = self.itemAt(e.scenePos())
        if item.setAcceptDrops == True:
            # pass on event to item at the coordinates
            try:
               item.dropEvent(e)
            except RuntimeError:
                pass #This will supress a Runtime Error generated when dropping into a widget with no MyProxy

    def dragMoveEvent(self, e):
        e.acceptProposedAction()

class MyProxy(QGraphicsProxyWidget):
    def dragEnterEvent(self, e):
        e.acceptProposedAction()

    def dropEvent(self, e):
        # pass drop event to child widget
        return self.widget().dropEvent(e)

    def dragMoveEvent(self, e):
        e.acceptProposedAction()

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


code:
from bs4 import BeautifulSoup

data = """

"""
soup = BeautifulSoup(data)
img = soup.img

img.parent.name

rawDescription: Get immediate parent tag with BeautifulSoup in Python


code:
import datetime as dt
now = dt.datetime.now()
event_date = dt.date(2012,10,22)
event_date = dt.datetime(event_date.year, event_date.month, event_date.day)
event_time = dt.timedelta(seconds = 28800)
event = event_date + event_time
elapsed = now - event
elapsed.total_seconds()
elapsed.total_seconds() // 60

rawDescription: Wrestling with Python MySQLdb timedelta

description: Wrestling with Python MySQLdb timedelta


rawDescription: How to combine different data sets in Pandas (python 3)?

description: Combine different data sets in Pandas (python 3)


code:
from . import conftest

def test_foo():
    assert isinstance(conftest.someobj, SomeObj)

rawDescription: How to share object from fixture to all tests using pytest?

description: Share object from fixture to all tests using pytest


code:
for x in doc.findAll('span'):
    s = x["attrib"]
    t = x.find('font')
    t.string = t.text.strip() + '_' + s
    x.replaceWithChildren()

rawDescription: How to replace a span with its children and do a regex over the inner text in BeautifulSoup

description: Replace a span with its children and do a regex over the inner text in BeautifulSoup


code: scale = [notes[(y+root_i)%len(notes)] for y in [0,2,4,5,7,9,11]]

rawDescription: python looping index

description: Python looping index


code: example.py:8 - aargh

rawDescription: Python debugging: get filename and line number from which a function is called?


code:
def f():
    "some documentation .."
    pass

f.__str__

rawDescription: custom print statement for python function objects

description: Custom print statement for python function objects


code:
m = Monster()
m.decreaseHealth()

rawDescription: Class method: 'self' not being read

description: Class method: 'self' not being read


code:
from collections import OrderedDict
import sys

od = OrderedDict()
od.update(sys.modules)
sys.modules = od

rawDescription: How to determine if one module has been loaded before or after another

description: Determine if one module has been loaded before or after another


rawDescription: python - how can I select a class and get the number of another class with whitespace between them using selenium

description: Python - how can I select a class and get the number of another class with whitespace between them using selenium


code:
sm = ScreenManager()

sc1 = Screen(name='firstscreen')
sc1.add_widget(ScreenButton(screenmanager=sm))

sc2 = Screen(name='whatever')
sc2.add_widget(Label(text='another screen'))

sm.add_widget(sc1)
sm.add_widget(sc2)

rawDescription: Kivy: Changing screens in screen manager with an on_press event


code:
inputlist = [('a', 'b'), ('b', 'a'), ('c','d')]
set(tuple(sorted(t)) for t in inputlist)

rawDescription: Set of string tuples in python

description: Set of string tuples in python


rawDescription: dfs to implement a graph, python

description: Dfs to implement a graph, python


rawDescription: Calculating the number of remaining items in a list from a given index


rawDescription: Advanced array/dataframe slicing (numpy/pandas)


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

for elem in xmlTree.iter():
  # skipping root element
  if elem.tag == xmlTree.getroot().tag:
    continue
  # this is supposed to be my temporary list
  for child in elem:
      d[elem.tag].append(child.tag)
print(tableWColumns)

rawDescription: Generating dictionary of lists in a loop (3.2.3)


rawDescription: Replacing certain values in a pandas dataseries?


code:
import os
from docx import getdocumenttext
from lxml import etree

# get `xml_content` from word doc...

tree = etree.fromstring(xml_content)
paragraphs = getdocumenttext(tree)
print(os.linesep.join(paragraphs))
# Result:
# 0 things and stuff
# 1 things and stuff

rawDescription: Preserve newlines when pulling text from xml


code:
def confirmSub(replacement):
    def confirmer(match):
        print("Going to replace", match.string[match.start()-5:match.end()+5])
        x = raw_input("OK?")
        if x.lower().startswith("y"):
            return re.sub(match.re.pattern, replacement, match.group())
        return match.group()
    return confirmer

rawDescription: Interactive substitution - re.sub() with pos?


code: os.environ["PATH"] = ':'.join(os.environ["PATH"].split(":") + ["/var/bin"])

rawDescription: PATH variable in Python

description: PATH variable in Python


code: dfd.applymap(lambda x: L.distance(x[0], x[1]))

rawDescription: ipython Pandas : How can I compare different rows of one column with Levenshtein distance metric?

description: Ipython Pandas : How can I compare different rows of one column with Levenshtein distance metric


code:
import lxml.etree as etree
root = etree.Element('root')
heads = ["foo", "foobar", "fooboo"]
for head in heads:
    etree.SubElement(root, head)

rawDescription: Creating XML-child's from a list

description: Creating XML-child's from a list


code:
data = {}
lists = [
   [{'id': 1, 'name': 'test'}, {'id': 2, 'name': 'test1'},],
   [{'id': 1, 'age': 10}, {'id': 2, 'age': 20},]
]

for each_list in lists:
   for each_dict in each_list:
       data.setdefault(each_dict['id'], {}).update(each_dict)

rawDescription: Is there better way to merge dictionaries contained in two lists in Python?


code:
import pyperclip
y = '\n'.join('- ' + str(x) for x in range(1, 158))
pyperclip.copy(y)

rawDescription: Python - How do you assign a variable to a table displayed on seperate lines


code:
with open('file') as f:
    for line in f:
        word = line[:max(line.find(' '), 0) or None]
        if condition(word):
            do_something(word)

rawDescription: Python: read one word per line of a text file


code:
RPT_tmp = RPT.reset_index()
RPT_tmp['year'] = RPT_tmp['RPT_Date'].apply(year)
grouped = RPT_tmp.groupby(['STK_ID', 'year'])

rawDescription: How to do a 'groupby' by multilevel index in Pandas

description: Do a 'groupby' by multilevel index in Pandas


code:
dis.dis(lambda: [])
dis.dis(lambda: list())

rawDescription: How can I add the outcome of a function to a list in python?

description: Add the outcome of a function to a list in python


rawDescription: What’s the most Pythonic way of handling different, mutually-exclusive function inputs?


code:
import numpy as np
from numpy import *
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.patches import FancyArrowPatch
from mpl_toolkits.mplot3d import proj3d

class Arrow3D(FancyArrowPatch):
    def __init__(self, xs, ys, zs, *args, **kwargs):
        FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)
        self._verts3d = xs, ys, zs

    def draw(self, renderer):
        xs3d, ys3d, zs3d = self._verts3d
        xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)
        self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))
        FancyArrowPatch.draw(self, renderer)

####################################################
# This part is just for reference if
# you are interested where the data is
# coming from
# The plot is at the bottom
#####################################################

# Generate some example data
mu_vec1 = np.array([0,0,0])
cov_mat1 = np.array([[1,0,0],[0,1,0],[0,0,1]])
class1_sample = np.random.multivariate_normal(mu_vec1, cov_mat1, 20)

mu_vec2 = np.array([1,1,1])
cov_mat2 = np.array([[1,0,0],[0,1,0],[0,0,1]])
class2_sample = np.random.multivariate_normal(mu_vec2, cov_mat2, 20)

rawDescription: Putting arrowheads on vectors in matplotlib's 3d plot


code: c = list(set(a).difference(b))

rawDescription: Find items not in common between lists in Python


code:
import sys

x = load_some_data()
function = eval("".join(sys.argv[1:]))
print(function(x))

rawDescription: How do I pass function definition to python script as string

description: Pass function definition to python script as string


code:
while i < (len(foo_list)):
    if foo_list[i] < bar: # if condition is True increment by 4
        i += 4
    else:
        i += 1 # else just increment 1 by one and check next `foo_list[i]`

rawDescription: Incrementing a for loop, inside the loop


code:
import dask.dataframe as dd
import pandas as pd
df = dd.from_pandas(pd.DataFrame({'a': [1,2]}), npartitions=1)
numbers = [df['a'].mean() for _ in range(2)]
dd.compute(*numbers)  # note the *

rawDescription: How do I actually get dask to compute a list of delayed or dask-container-based results?

description: Actually get dask to compute a list of delayed or dask-container-based results


code:
from ctypes import *
from ctypes.wintypes import *
from enum import IntEnum

ntdll = WinDLL('ntdll')

PVOID = c_void_p
PWSTR = c_wchar_p
ULONG_PTR = WPARAM

class UNICODE_STRING(Structure):
    _fields_ = (('Length', USHORT),
                ('MaximumLength', USHORT),
                ('Buffer', PWSTR))

PUNICODE_STRING = POINTER(UNICODE_STRING)

NTSTATUS = c_long
STATUS_BUFFER_OVERFLOW = NTSTATUS(0x80000005).value
STATUS_NO_MORE_FILES = NTSTATUS(0x80000006).value
STATUS_INFO_LENGTH_MISMATCH = NTSTATUS(0xC0000004).value

def NTError(status):
    err = ntdll.RtlNtStatusToDosError(status)
    return WinError(err)

class IO_STATUS_BLOCK(Structure):
    class _STATUS(Union):
        _fields_ = (('Status', NTSTATUS),
                    ('Pointer', PVOID))
    _anonymous_ = '_Status',
    _fields_ = (('_Status', _STATUS),
                ('Information', ULONG_PTR))

PIO_STATUS_BLOCK = POINTER(IO_STATUS_BLOCK)

# WINFUNCTYPE(None, PVOID, PIO_STATUS_BLOCK, ULONG)
# but just make it void *:
PIO_APC_ROUTINE = PVOID

class c_enum(IntEnum):
    @classmethod
    def from_param(cls, arg):
        return cls(arg)

FILE_INFORMATION_CLASS = c_enum('FILE_INFORMATION_CLASS',
  '''
  FileDirectoryInformation,
  FileFullDirectoryInformation,
  FileBothDirectoryInformation,
  FileBasicInformation,
  FileStandardInformation,
  FileInternalInformation,
  FileEaInformation,
  FileAccessInformation,
  FileNameInformation,
  FileRenameInformation,
  FileLinkInformation,
  FileNamesInformation,
  FileDispositionInformation,
  FilePositionInformation,
  FileFullEaInformation,
  FileModeInformation,
  FileAlignmentInformation,
  FileAllInformation,
  FileAllocationInformation,
  FileEndOfFileInformation,
  FileAlternateNameInformation,
  FileStreamInformation,
  FilePipeInformation,
  FilePipeLocalInformation,
  FilePipeRemoteInformation,
  FileMailslotQueryInformation,
  FileMailslotSetInformation,
  FileCompressionInformation,
  FileObjectIdInformation,
  FileCompletionInformation,
  FileMoveClusterInformation,
  FileQuotaInformation,
  FileReparsePointInformation,
  FileNetworkOpenInformation,
  FileAttributeTagInformation,
  FileTrackingInformation,
  FileIdBothDirectoryInformation,
  FileIdFullDirectoryInformation,
  FileValidDataLengthInformation,
  FileShortNameInformation,
  FileIoCompletionNotificationInformation,
  FileIoStatusBlockRangeInformation,
  FileIoPriorityHintInformation,
  FileSfioReserveInformation,
  FileSfioVolumeInformation,
  FileHardLinkInformation,
  FileProcessIdsUsingFileInformation,
  FileNormalizedNameInformation,
  FileNetworkPhysicalNameInformation,
  FileIdGlobalTxDirectoryInformation,
  FileIsRemoteDeviceInformation,
  FileAttributeCacheInformation,
  FileNumaNodeInformation,
  FileStandardLinkInformation,
  FileRemoteProtocolInformation,
  FileReplaceCompletionInformation,
  FileMaximumInformation,
  ''')
globals().update(FILE_INFORMATION_CLASS._member_map_)

class FILE_DIRECTORY_INFORMATION(Structure):
    _fields_ = (('Next', ULONG),
                ('FileIndex', ULONG),
                ('CreationTime', LARGE_INTEGER),
                ('LastAccessTime', LARGE_INTEGER),
                ('LastWriteTime', LARGE_INTEGER),
                ('ChangeTime', LARGE_INTEGER),
                ('EndOfFile', LARGE_INTEGER),
                ('AllocationSize', LARGE_INTEGER),
                ('FileAttributes', ULONG),
                ('FileNameLength', ULONG),
                ('_FileName', WCHAR * 1))

    @property
    def FileName(self):
        addr = addressof(self) + type(self)._FileName.offset
        arrt = WCHAR * (self.FileNameLength // sizeof(WCHAR))
        return arrt.from_address(addr).value

    @classmethod
    def listbuf(cls, buf):
        fdilist = []
        offset = 0
        while True:
            fdi = cls.from_buffer(buf, offset)
            if fdi.FileNameLength:
                cfdi = cls()
                size = sizeof(cls) - sizeof(WCHAR) + fdi.FileNameLength
                resize(cfdi, size)
                memmove(addressof(cfdi), addressof(fdi), size)
                fdilist.append(cfdi)
            if fdi.Next:
                offset += fdi.Next
            else:
                break
        return fdilist

NtQueryDirectoryFile = ntdll.NtQueryDirectoryFile
NtQueryDirectoryFile.restype = NTSTATUS
NtQueryDirectoryFile.argtypes = (
    HANDLE,                  # FileHandle           In
    HANDLE,                  # Event                In_opt
    PIO_APC_ROUTINE,         # ApcRoutine           In_opt
    PVOID,                   # ApcContext           In_opt
    PIO_STATUS_BLOCK,        # IoStatusBlock        Out
    PVOID,                   # FileInformation      Out
    ULONG,                   # Length               In
    FILE_INFORMATION_CLASS,  # FileInformationClass In
    BOOLEAN,                 # ReturnSingleEntry    In
    PUNICODE_STRING,         # FileName             In_opt
    BOOLEAN,                 # RestartScan          In
)

rawDescription: Python NtQueryDirectoryFile (File information structure)


rawDescription: How to Join two separate text data files and align data over varying time intervals and avg


code: zip(*sorted(zip(*rows), key=lambda c: len(set(c))))

rawDescription: Python sorting list of tuples by frequency


code:
link = line.split('.')
if len(link) > 3 and link[-1].isalpha():
    plink = link[-3:]

rawDescription: Split and take n words from the end

description: Split and take n words from the end


code:
from sklearn.tree import DecisionTreeClassifier
dt = DecisionTreeClassifier()
dt.fit([[0,0],
        [0,1],
        [1,1]], [0,1,0])
get_value(dt)

rawDescription: How to get pos/neg instance counts for all nodes of a scikit-learn decision tree?

description: Get pos/neg instance counts for all nodes of a scikit-learn decision tree


code:
def __init__(self):
    items = sorted(self._registry.items() + [(self._num, self)]) #collect items
    self._registry.clear() #clean the dict
    self._registry.update(items) #now update it

rawDescription: OrderedDict won't sort within a class

description: OrderedDict won't sort within a class


code:
items_to_pick = [2, 618]
[color for idx, color in list_of_tuples if idx in items_to_pick]

rawDescription: Python, to pick specific elements from a list of tuples


code:
data = []
with open('file1') as in_file:
    for line in in_file:
        data.append(line.strip().split())
data = [a[1] for a in data if a[1]]

rawDescription: Convert text file into csv format

description: Convert text file into csv format


code: input('Press the enter key to exit')

rawDescription: defining variables and exectuing a variable python

description: Defining variables and exectuing a variable python


code:
from itertools import combinations

for i, j in combinations(self.objects, 2):
    if pygame.sprite.collide_rect(i, j):
        grid.collisions.append(Collision(i, j))

rawDescription: Python: Iterating through a set so we don't compare the same objects multiple times?


code:
import pymysql

def MySQLCheck(*args, **kwargs):
    try:
        conn = pymysql.connect(*args, **kwargs)
        cursor = conn.cursor()
        cursor.execute("show databases;")
        r = cursor.fetchall()
        conn.close()
        return r
    except Exception as e: return e

rawDescription: How to check a given MySQL server connects through Python?

description: Check a given MySQL server connects through Python


code: (matrix_a >= matrix_b).all()

rawDescription: Elegant way to check empty result of numpy.nonzero


code: list(map(fib, range(5)))

rawDescription: how to I get the total number of stack frames used in recursion in Python?


code:
import numpy as np

def normalize_column(A, col):
    A[:,col] = (A[:,col] - np.min(A[:,col])) / (np.max(A[:,col]) - np.min(A[:,col]))

if __name__ == '__main__':
    A = np.matrix([[1,2,3], [4,5,6], [7,8,9]], dtype=float)
    normalize_column(A, 1)
    print (A)

rawDescription: column-wise normalization (scaling) of arrays

description: Column-wise normalization (scaling) of arrays


code: new_leetcode_file("testfile", "test", ("arr1", "arr2"))

rawDescription: Function arguments in creating function file dynamically


code: all_list_something = all(map(is_valid, list_something))

rawDescription: Python - How to check Booleans inside a for loop?


code:
points = np.array((a1, a2)).T
values = np.array((models))

ip = interpolate.LinearNDInterpolator(points, values)
p = [A1_new, A2_new]
new_model = ip([point])[0]

rawDescription: Python interpolare a function or array in a 2D (or nD) grid of parameters


code: variable = something if condition else something_else

rawDescription: python ? (conditional/ternary) operator for assignments

description: Python ? (conditional/ternary) operator for assignments


rawDescription: file.readlines() leaving blank lines

description: File.readlines() leaving blank lines


code:
class KeyValueField(serializers.Field):
    """ A field that takes a field's value as the key and returns
    the associated value for serialization """

    labels = {}
    inverted_labels = {}

    def __init__(self, labels, *args, **kwargs):
        self.labels = labels
        # Check to make sure the labels dict is reversible, otherwise
        # deserialization may produce unpredictable results
        inverted = {}
        for k, v in labels.iteritems():
            if v in inverted:
                raise ValueError(
                    'The field is not deserializable with the given labels.'
                    ' Please ensure that labels map 1:1 with values'
                )
            inverted[v] = k
        self.inverted_labels = inverted
        return super(KeyValueField, self).__init__(*args, **kwargs)

    def to_representation(self, obj):
        if type(obj) is list:
            return [self.labels.get(o, None) for o in obj]
        else:
            return self.labels.get(obj, None)

    def to_internal_value(self, data):
        if type(data) is list:
            return [self.inverted_labels.get(o, None) for o in data]
        else:
            return self.inverted_labels.get(data, None)

rawDescription: Serialize and De-serialize a Django Enum field to accept Numerical and Text representation


code:
import lxml.etree
import lxml.html
xmlstring = '''\
<?xml version='1.0' encoding='ASCII'?>
<root>link1link2</root>
'''
root = lxml.etree.fromstring(xmlstring)
root.cssselect('a.here')

rawDescription: lxml: Converting XML to HTML through XSLT and get HtmlElements

description: Lxml: Converting XML to HTML through XSLT and get HtmlElements


code:
from collections import defaultdict

d = defaultdict(list)

words = ['ABC', 'ACE', 'BED', 'BRT', 'CCD', ...]

for word in words:
    d[word[0]].append(word)

rawDescription: python get list element according to alphabet

description: Python get list element according to alphabet


rawDescription: Rendering unicode in pygame

description: Rendering unicode in pygame


code:
def readData():
    bank= []
    with open("example.txt", "r") as file:
        for line in file:
            line = line.split()
            sub_bank = []
            for i in line:
                if i.isdigit() is True:
                    sub_bank.append(int(i))
                else:
                    sub_bank.append(i)
            bank.append(sub_bank)
    return bank

rawDescription: Inputting a file of mixed data types and converting numbers into ints using Python


rawDescription: Merging some elements inside a list

description: Merging some elements inside a list


code:
import unicodedata
NUMERALS_TRANSLATION_TABLE = {
    i: unicode(unicodedata.digit(unichr(i)))
    for i in range(2 ** 16) if unichr(i).isdigit()}
NUMERALS_TRANSLATION_TABLE.update(
    (i, u'.') for i in range(2 ** 16)
    if 'DECIMAL SEPARATOR' in unicodedata.name(unichr(i), ''))
input = u'\u0663\u0669\u0668\u066b\u0664\u0667'
input.translate(NUMERALS_TRANSLATION_TABLE)

rawDescription: Convert unicode representation of number to ascii string


code:
print("Guesses", "Clues", sep='\t')
for guess, clue in zip(Guesses, Clues):
    print(' '.join(guess), ' '.join(clue), sep='\t')

rawDescription: Python formatting lists of lists

description: Python formatting lists of lists


code:
def nearest_interp(xi, x, y):
    idx = np.abs(x - xi[:,None])
    return y[idx.argmin(axis=1)]

rawDescription: Extraploation with 'nearest' method in Python


code:
import ConfigParser

countryName = raw_input("What will your country be called? ")

config = ConfigParser.RawConfigParser()

config.add_section('Countries')
config.set('Countries', 'MyCountry', countryName)

with open('save.txt', 'wb') as saveFile:
    config.write(saveFile)

rawDescription: How can I save data to/load data from a text file as variables in Python?

description: Save data to/load data from a text file as variables in Python


code:
def awesome_parse(path_or_file):
    if isinstance(path_or_file, basestring):
        f = file_to_close = open(path_or_file, 'rb')
    else:
        f = path_or_file
        file_to_close = None
    try:
        return do_stuff(f)
    finally:
        if file_to_close:
            file_to_close.close()

rawDescription: Python function that accepts file object or path


rawDescription: Function being called even though Matplotlib button hasn't been clicked


code:
import numpy as np
from scipy.optimize import minimize

#Define problem
A = np.array([[60., 90., 120.],
              [30., 120., 90.]])

b = np.array([6700.5, 699.,])

#-----------------------------
# I tried rescaling the data by adding this two lines,
# so that they're in same scale.
# but why the solution is different?
#    x: array([ 1.,  0.,  0.])
# What's the correct way to go?
#-----------------------------
# A = A/np.linalg.norm(A,axis=0)
# b = b/np.linalg.norm(b)

def f(x):
    return np.linalg.norm(A.dot(x) - b)

cons ={'type': 'eq',
       'fun': lambda x: sum(x) - 1}

x0 = [1, 0, 0]  # initial guess
minimize(f, x0, method='SLSQP', bounds=((0, np.inf),)*3, constraints=cons)

rawDescription: Best way to scale the matrix variables in SCIPY linear programming scheme

description: Scale the matrix variables in SCIPY linear programming scheme


code:
username = forms.EmailField(label="Preferred Username",
                            widget=UsernameInput(),
                            error_messages={'invalid': "Please enter a valid email address"})

rawDescription: How can I add custom properties to a field class for output in template?

description: Add custom properties to a field class for output in template


code:
def isSpaceFree(bin, row, column, block):
    #return False if the block would go out of bounds
    if row + block > len(bin):
        return False
    if column + block > len(bin):
        return False

    #possible todo:
    #return False if row or column is negative

    #return False if the square would overlap an existing element
    for r in range(row, row+block):
        for c in range(column, column+block):
            if bin[r][c] != 0: #oops, overlap will occur
                return False

    #square is in bounds, and doesn't overlap anything. Good to go!
    return True

rawDescription: 2D binary list python

description: 2D binary list python


rawDescription: Python: get list indexes using regular expression?


code:
from pyspark.sql.functions import when, lit, col

colors = df.select("color").distinct().map(lambda x: x[0]).collect()
cols = (
    when(col("color") == lit(color), 1).otherwise(0).alias(color)
    for color in colors
)

df.select(*cols)

rawDescription: Spark - Single column to columns of X classes


code:
jsonnet.evaluate_snippet()
import json, _jsonnet

# from
js_obj = '{x:1, y:2, z:3}'

# to
py_obj = json.loads(_jsonnet.evaluate_snippet('snippet', js_obj))

rawDescription: How to convert raw javascript object to python dictionary?

description: Convert raw javascript object to python dictionary


code:
X = df.Xi.reshape((len(df), 1))
X

rawDescription: I want to take data from CSV file and to put into Two different arrays variables


code:
provider = request.POST.get('provider')
kwargs = {}
if provider is not None:
    kwargs['provider'] = provider

order_items = OrderItem.objects.filter(**kwargs)

rawDescription: Django wildcard query

description: Django wildcard query


code: origin.py | process1.py | process2.py | process3.py

rawDescription: Sharing data between processes in Python


code: sum(d[k])/float(len(d[k]))

rawDescription: converting list to dict and averaging the values of duplicates in python

description: Converting list to dict and averaging the values of duplicates in python


code:
class SuperClass(object):
    def print(self):
        print('my sub classes are:', ', '.join([
            cls.__name__ for cls in type(self).__subclasses__()]))

class Sub1(SuperClass):
    def print(self):
        print('My direct parents are:', ', '.join([
            cls.__name__ for cls in type(self).__bases__]))
        all_parents = type(self).__mro__
        all_parents = all_parents[all_parents.index(Sub1) + 1:]
        print('All my parents are:', ', '.join([
            cls.__name__ for cls in all_parents]))

rawDescription: print all SubClass in a SuperClass and all SuperClass in a SubClass

description: Print all SubClass in a SuperClass and all SuperClass in a SubClass


code:
for i in data:
    print(''.join(i))      #prints string

rawDescription: Mutation algorithm python

description: Mutation algorithm python


rawDescription: Getting text from br tags in BeautifulSoup


rawDescription: Checking for unique output in Python

description: Checking for unique output in Python


code: cities['_find'] = find_city

rawDescription: python underscores: learn python the hard way exercise 40

description: Python underscores: learn python the hard way exercise 40


code:
import argparse
import collections

class ValidateCredits(argparse.Action):
    def __call__(self, parser, args, values, option_string=None):
        # print '{n} {v} {o}'.format(n=args, v=values, o=option_string)
        valid_subjects = ('foo', 'bar')
        subject, credits = values
        if subject not in valid_subjects:
            raise ValueError('invalid subject {s!r}'.format(s=subject))
        credits = float(credits)
        Credits = collections.namedtuple('Credits', 'subject required')
        setattr(args, self.dest, Credits(subject, credits))

parser = argparse.ArgumentParser()
parser.add_argument('-c', '--credits', nargs=2, action=ValidateCredits,
                    help='subject followed by number of credits required',
                    metavar=('SUBJECT', 'CREDITS')
                    )
args = parser.parse_args()
print(args)
print(args.credits.subject)
print(args.credits.required)

rawDescription: Python argparse type and choice restrictions with nargs > 1


code:
fstrip = filmstrip.make_film_strip(filmstrip.fnames, (120, 120), (0,0,0,0), 0)
fstrip.save('/path/to/file.format')

rawDescription: How to generate a filmstrip image in python from a folder of images?

description: Generate a filmstrip image in python from a folder of images


code:
class Cell(Rectangle):
    def __init__(self, canvas, row, column):
        # make a 50x50 rectangle in the given row, column
        x0 = column * 50
        y0 = row * 50
        x1 = x0 + 50
        y1 = y0 + 50
        self.state = None
        super(Cell, self).__init__(canvas, (x0, y0, x1, y1), "gray")

    def set_state(self, state):
        self.state = state
        color = "green" if state == "alive" else "red"
        self.canvas.itemconfigure(self.canvas_id, fill=color, outline=color)

rawDescription: Can rectangle be used as a parent class (tkinter)?


code:
relation3 = {'Jerry': ['George', 'Elaine'], 'Elaine':['Kramer']}
dict2pairs(relation3)

rawDescription: Python dictionary to pairs and check for antisymmetry using dictionary


rawDescription: declare multiple variables to same value

description: Declare multiple variables to same value


rawDescription: Python append dictionary to dictionary

description: Python append dictionary to dictionary


code:
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
list(enumerate(seasons))
list(enumerate(seasons, start=1))

rawDescription: Python: Changing values in a String with a for loop


code: c = Counter((x.rstrip(punctuation).lower() for y in text for x in y.split() if x in relevant_items))

rawDescription: Python: Getting specific list elements

description: Python: Getting specific list elements


code:
post_db = Post(desc='Hello World')
post_db.put()

comment_db = Comment(parent=post_db, desc='Nice post')
comment_db.put()

rawDescription: GAE datastore cache keys vs filter

description: GAE datastore cache keys vs filter


code:
while not entry:
  entry = self.upload_chunk(start_byte, self.file_handle)
  start_byte += self.chunk_size

rawDescription: Using Google App Engine how to upload document in google docs (python)


code:
from re import finditer

def findSubstringMatch(target, key):
    return tuple(m.start() for m in finditer(key, target))

rawDescription: I need this Substring counting program to return a Tuple


code:
@foo(default_value="test param2")
def test_decorator():
    pass

rawDescription: How can i set a default value for a function parameter with a decorator?

description: Set a default value for a function parameter with a decorator


rawDescription: Python look for pattern in string

description: Python look for pattern in string


code:
def game_over():
    message_display("Você morreu de morte morrida")
    # game_loop() # removed

rawDescription: Pygame - why my game repeats instead of closing?


code: persons_by_id = {p.id: p for p in persons}

rawDescription: How to directly access class instances through class dictionary in Python

description: Directly access class instances through class dictionary in Python


code:
def add(a,b):
    return a + b

rawDescription: How to check if a function is pure in Python?

description: Check if a function is pure in Python


code: sniff(iface="<My Interface>", prn = lambda x: x.show(), filter="tcp", store=0)

rawDescription: Scapy packet sniffer triggering an action up on each sniffed packet


code:
A.GetMembers()
B.GetMembers()

rawDescription: Access child's __dict__ from parent in Python?


code:
x=0
y=radius
d=3-2*radius
while (x<=y):
    for hor in range(0,x + 1): #This loop is my unfortunate attempt to fill the circle with 1s
##        for ver in range(0,y):
        empty_lattice[xc+hor][yc+y]=1 #1st octant
        empty_lattice[xc-hor][yc+y]=1 #2nd octant
        empty_lattice[xc+hor][yc-y]=1 #3rd octant
        empty_lattice[xc-hor][yc-y]=1 #4th octant
        empty_lattice[xc+x][yc+hor]=1 #1st octant
        empty_lattice[xc-x][yc+hor]=1 #2nd octant
        empty_lattice[xc+x][yc-hor]=1 #3rd octant
        empty_lattice[xc-x][yc-hor]=1 #4th octant
        empty_lattice[xc+hor][yc+x]=1 #5th octant
        empty_lattice[xc-hor][yc+x]=1 #6th octant
        empty_lattice[xc+hor][yc-x]=1 #7th octant
        empty_lattice[xc-hor][yc-x]=1 #8th octant
        empty_lattice[xc+y][yc+hor]=1 #5th octant
        empty_lattice[xc-y][yc+hor]=1 #6th octant
        empty_lattice[xc+y][yc-hor]=1 #7th octant
        empty_lattice[xc-y][yc-hor]=1 #8th octant
    if (d<0):
        d=d+4*x+6
    else:
        d=d+4*(x-y)+10
        y=y-1
    x=x+1

rawDescription: How to "translate" the Midpoint Circle Algorithm into matplotlib?


code:
while self.x_p1_laser <= 900:
   self.canvas.move(self.laser_p1,5,0)
   self.x_p1_laser += 5
   self.canvas.update()
   time.sleep(.009)

rawDescription: Stack overflow in python game

description: Stack overflow in python game


code:
df = df.sort_index(axis=1)
idx = pd.IndexSlice
df.loc[:,idx[:,"Num"]] = df.loc[:,idx[:,"Num"]].where((df.loc[:,idx[:,"Let"]] != "B").values, 3)
df

rawDescription: Apply similar function to multilevel pandas dataframe


code:
a = object()
b = object()
a == b
pickle.dumps(b) == pickle.dumps(a)

rawDescription: Is the pickling process deterministic?

description: Is the pickling process deterministic


code:
# read variables from the cache, a user's custom.py file or command line
# arguments
var = Variables(['variables.cache', 'custom.py'], ARGUMENTS)
# add a path variable
var.AddVariables(PathVariable('LIBFOO',
        'where the foo library is installed',
        r'C:\default\libfoo', PathVariable.PathIsDir))

env = Environment(variables=var)
env.Program('test', 'main.c', LIBPATH='$LIBFOO')

# save variables to a file
var.Save('variables.cache', env)

rawDescription: SCons configuration file and default values


rawDescription: How to get the intermediate dates given the start date and end date?

description: Get the intermediate dates given the start date and end date


code:
import numpy as np
N = len(vertnormals)
for j in range(vertnormals.shape[-1]):
    vertnormals[:, j] += np.bincount(trivertidx[:, 0], trinormals[:, j], minlength=N)
    vertnormals[:, j] += np.bincount(trivertidx[:, 1], trinormals[:, j], minlength=N)
    vertnormals[:, j] += np.bincount(trivertidx[:, 2], trinormals[:, j], minlength=N)

rawDescription: Numpy loop using an index

description: Numpy loop using an index


rawDescription: How do I combine these regular expressions to match the variations in this text?

description: Combine these regular expressions to match the variations in this text


rawDescription: what would be the python code to add time to a specific timestamp?

description: What would be the python code to add time to a specific timestamp


code:
class DeclarativeFieldsMetaclassFromMultipleClasses(type):
  def __new__(cls, name, bases, attrs):
    for clazz in attrs['includes']:
      attrs['base_fields'] += get_declared_fields(bases, clazz.attrs)
    new_class = super(DeclarativeFieldsMetaclassFromMultipleClasses,cls).__new__(cls, name, bases, attrs)
    if 'media' not in attrs:
      new_class.media = media_property(new_class)
    return new_class

rawDescription: Django multiple form factory

description: Django multiple form factory


rawDescription: How to calculate length of string in pixels for specific font and size?

description: Calculate length of string in pixels for specific font and size


code:
d = {'Four': []}
for i in range(100):
    if not i % 4:
        d['Four'].append(i)

rawDescription: Is it possible to alter the values in a dictionary, keeping the key value constant?


code: assert 'Edit your profile admin' in rv.data, rv.data

rawDescription: Is there a way to configure Python logging to log content or context of assert failures?


rawDescription: pandas Subtract Dataframe with a row from another dataframe

description: Pandas Subtract Dataframe with a row from another dataframe


code:
def bd_from_ac(a, c):
    return a*neighbor_min(a), neighbor_min(c)

rawDescription: Numpy: fast calculations considering items' neighbors and their position inside the array


rawDescription: How to get all html elements with id equal to `constant_text-something_changed`?

description: Get all html elements with id equal to `constant_text-something_changed`


code:
import codecs
import json
import os
import sys

try:
    import unicodecsv as csv
except ImportError:
    import csv

OUTPUT_FILE = 'output.csv'

def process_file(infile, writer):
    print('Processing file: %s' % infile)
    with codecs.open(infile, encoding='utf-8') as infile:
        data = json.load(infile)
        for item in data:
            _id = item['id']
            description = item['description']
            for gov in item['source']:
                gov_id = gov['name']
                for source in item['secondarySource']:
                    source_id = source['sourceId']
                    name = source['name']
                    party = source['party']
                    writer.writerow([_id, description, gov_id, source_id, name, party])

def process_files_in_directory(directory, outfile):
    with codecs.open(outfile, 'w') as outfile:
        writer = csv.writer(outfile)
        writer.writerow(["id", "description", "branch", "sourceID", "name", "party"])
        for f in os.listdir(directory):
            if f.endswith('.json'):
                process_file(os.path.join(directory, f), writer)

USAGE = """
Usage:

            python json_parser.py <source_directory> [<output_file>]

            Where source_directory is path to directory with input JSON files.
            output_file is optional -- defaults to %s
            File names must end with .json
            """ % OUTPUT_FILE

if __name__ == '__main__':
    try:
        directory = sys.argv[1]
    except IndexError:
        print(USAGE)
        sys.exit(0)
    if len(sys.argv) > 2:
        outfile = sys.argv[2]
    else:
        outfile = OUTPUT_FILE
    process_files_in_directory(directory, outfile)

rawDescription: Not receiving output from json-parser in python


code:
def get_sumdf(area_tab):  # perhaps you can name better?
    actdf,aname = get_data(area_tab)
    lastq,fcast_yr,projections,yrahead,aname,actdf,merged2,mergederrs,montdist,ols_test,mergedfcst=do_projections(actdf)
    sumdf=merged2[-2:]
    sumdf['name']= aname #<<< I'll be doing a few more calculations here as well
    return sumdf

[get_sumdf(area_tab) for area_tab in areas_tabs]

rawDescription: Create a summary Pandas DataFrame using concat/append via a for loop


code:
def blah_method(request):
    form = GroceryForm(request.POST or None)
    if form.is_valid():
        grocery_type = form.cleaned_data['grocery_type']
        if grocery_type == 'dairy':
            result = Groceries.objects.create(dairy=form.cleaned_data['name'])
        elif grocery_type == 'produce':
            result = Groceries.objects.create(produce=form.cleaned_data['name'])
        elif grocery_type == 'deli':
            result = Groceries.objects.create(deli=form.cleaned_data['name'])

rawDescription: In Python Django, how do I assign a charfield to a column in SQL based on the user's selection from a combobox?


code:
scaled = copy.deepcopy(original)
for i in range(len(scaled[0])):
    scaled[0][i]=scaled[0][i]*scaleFactor
    scaled[1][i]=scaled[1][i]*scaleFactor

rawDescription: Rotation, scale and translate function for python


code:
interm = re.sub(r'\[(.*?)\]', '', text)
re.findall(r'<(.+?)>', interm)

rawDescription: Python RegEx for exact matches of brackets


code:
df = pd.DataFrame(datetimes, columns=['date'])
df

rawDescription: Find Unique Dates in Numpy Datetime Array


code:
for line in data:
    file.write(line.replace(",",";"))

rawDescription: Modify csv files with Python

description: Modify csv files with Python


code:
def ec_inv(P):
    """
    Inverse of the point P on the elliptic curve y^2 = x^3 + ax + b.
    """
    if P == O:
        return P
    return Point(P.x, (-P.y)%p)

def ec_add(P, Q):
    """
    Sum of the points P and Q on the elliptic curve y^2 = x^3 + ax + b.
    """
    if not (valid(P) and valid(Q)):
        raise ValueError("Invalid inputs")

    # Deal with the special cases where either P, Q, or P + Q is
    # the origin.
    if P == O:
        result = Q
    elif Q == O:
        result = P
    elif Q == ec_inv(P):
        result = O
    else:
        # Cases not involving the origin.
        if P == Q:
            dydx = (3 * P.x**2 + a) * inv_mod_p(2 * P.y)
        else:
            dydx = (Q.y - P.y) * inv_mod_p(Q.x - P.x)
        x = (dydx**2 - P.x - Q.x) % p
        y = (dydx * (P.x - x) - P.y) % p
        result = Point(x, y)

    # The above computations *should* have given us another point
    # on the curve.
    assert valid(result)
    return result

rawDescription: Elliptic curve point addition over a finite field in Python


code:
def goat_door(guess, correct):
    return [random.choice(list({1,2,3} - {g,c}))
            for g,c in zip(guess, correct)]

rawDescription: List comprehension to generate and then sample from array that in turn depends on values in another array (index dependent)


code:
import os
path = os.path.join(os.path.expanduser('~'), 'Documents', 'ArcGIS', 'file1.gdb')

rawDescription: Save a file depending on the user Python


code:
def get_intersection_by_model(self, queryset_or_model, tags):
    """
    Create a ``QuerySet`` containing instances of the specified
    model associated with *all* of the given list of tags.
    """
    tags = get_tag_list(tags)
    tag_count = len(tags)
    queryset, model = get_queryset_and_model(queryset_or_model)

    if not tag_count:
        return model._default_manager.none()

    model_table = qn(model._meta.db_table)
    # This query selects the ids of all objects which have all the
    # given tags.
    query = """
    SELECT %(model_pk)s
    FROM %(model)s, %(tagged_item)s
    WHERE %(tagged_item)s.content_type_id = %(content_type_id)s
      AND %(tagged_item)s.tag_id IN (%(tag_id_placeholders)s)
      AND %(model_pk)s = %(tagged_item)s.object_id
    GROUP BY %(model_pk)s
    HAVING COUNT(%(model_pk)s) = %(tag_count)s""" % {
        'model_pk': '%s.%s' % (model_table, qn(model._meta.pk.column)),
        'model': model_table,
        'tagged_item': qn(self.model._meta.db_table),
        'content_type_id': ContentType.objects.get_for_model(model).pk,
        'tag_id_placeholders': ','.join(['%s'] * tag_count),
        'tag_count': tag_count,
    }

    cursor = connection.cursor()
    cursor.execute(query, [tag.pk for tag in tags])
    object_ids = [row[0] for row in cursor.fetchall()]
    if len(object_ids) > 0:
        return queryset.filter(pk__in=object_ids)
    else:
        return model._default_manager.none()

rawDescription: Union and Intersect in Django

description: Union and Intersect in Django


code:
arrays = np.arange(0, 2), np.arange(4, 6), np.arange(8, 10)
grid = np.meshgrid(*arrays, sparse=True)
[tuple(g[i] for g in grid) for i in np.ndindex(grid[0].shape)]

rawDescription: Dimensionality agnostic (generic) cartesian product


code:
data = [{
    'product_id': product.id,
    'title': product.title,
    'price': product.price,
    'variants': [{'product_variant_id': products[product.id].id,
                    'colour': products[product.id].colour}]
} for product in products]

rawDescription: Python speed up list of dict iteration

description: Python speed up list of dict iteration


code:
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
TEMPLATE_CONTEXT_PROCESSORS = (
       "django.core.context_processors.request",
       "django.core.context_processors.media",
       "django.contrib.messages.context_processors.messages"
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'h^@hi8e&q4e#h!j4v$x+@y2ngs&3&*o%!u8pi(vp3h8n&0$*a)'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
#     'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (

   'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

rawDescription: Django Message framework is not showing message in template


code:
y = ['Alligator', 'pple', 'banana']
map(lambda x: x if x[0] == 'A' else "A" + x, y)
[x if x[0] == 'A' else "A" + x for x in y]

rawDescription: How to minimize string-appending to one line in Python?

description: Minimize string-appending to one line in Python


code:
class AClass(object):
      def __init__(self):
           self.aprop = "avalue"
AClass.aprop

rawDescription: Initialize object properties as class properties first in Python


code:
sys.modules['packageA.moduleA'] = moduleA
# etc.

rawDescription: Unpickling python objects with a changed module path


rawDescription: Indices of resampled array in scipy

description: Indices of resampled array in scipy


code: results = map(func, obj)

rawDescription: Map Function to Dictionary of Objects

description: Map Function to Dictionary of Objects


code:
angle = (math.pi*2)/shots
for i in xrange(shots):
    angle += angle

rawDescription: Python - Pygame - Handling angles and speeds of animations


code: d1[numpy.searchsorted(t1, t2, side="right") - 1]

rawDescription: "as of" in numpy

description: "as of" in numpy


code:
from bs4 import BeautifulSoup
l = [
    """My website is WEBSITE1""",
    """The link is LINK1"""
]
for item in l:
    soup = BeautifulSoup(item, "html.parser")
    for a in soup("a"):
       a.replace_with(a.text)
    print(str(soup))

rawDescription: regex substitute html href and u tags in list (python)

description: Regex substitute html href and u tags in list (python)


code:
x = arr[7].max()   # Maximum in row 7
y = arr[29].sum()  # Sum of the values in row 29

rawDescription: Sum one row of a NumPy array

description: Sum one row of a NumPy array


code:
data
data.dtype
data.dtype.names

rawDescription: Getting header row from numpy.genfromtxt


code:
class Container(dict):
    def put_in(self, something):
        self[something] = Thing(self, something)

class Thing:
    def __init__(self, container, name):
        self.container = container
        self.name = name

    def what_is_it(self):
        assert self.container[self.name] is self, "Thing stored under wrong name"
        print("I am a thing called {}".format(self.name))

    def __getattr__(self, name):
        # By the time __getattr__ is called, normal attribute access on Thing has
        # already failed. So, no need to check again. Go straight to checking the
        # container
        try:
            return getattr(self.container, name)
        except AttributeError:
            # raise a fresh attribute error to make it clearer that the
            # attribute was initially accessed on a Thing object
            raise AttributeError("'Thing' object has no attribute {!r}".format(name)) from e

rawDescription: Does circular reference between two objects requires the use of weakref?


code:
class Thing():
     timeTo = 0
     timeFrom = 0
     name = ""

     def __lt__(self, other):
         return self.timeFrom < other.timeTo

lesser, bigger = sorted(myList)

rawDescription: What is the best way to sort items on one of the items values


code: conn = oursql_conn()

rawDescription: SQLAlchemy memory hog on select statement


code:
#!/usr/bin/env python

from matplotlib import pyplot as plt

def mk_groups(data):
    try:
        newdata = data.items()
    except:
        return

    thisgroup = []
    groups = []
    for key, value in newdata:
        newgroups = mk_groups(value)
        if newgroups is None:
            thisgroup.append((key, value))
        else:
            thisgroup.append((key, len(newgroups[-1])))
            if groups:
                groups = [g + n for n, g in zip(newgroups, groups)]
            else:
                groups = newgroups
    return [thisgroup] + groups

def add_line(ax, xpos, ypos):
    line = plt.Line2D([xpos, xpos], [ypos + .1, ypos],
                      transform=ax.transAxes, color='black')
    line.set_clip_on(False)
    ax.add_line(line)

def label_group_bar(ax, data):
    groups = mk_groups(data)
    xy = groups.pop()
    x, y = zip(*xy)
    ly = len(y)
    xticks = range(1, ly + 1)

    ax.bar(xticks, y, align='center')
    ax.set_xticks(xticks)
    ax.set_xticklabels(x)
    ax.set_xlim(.5, ly + .5)
    ax.yaxis.grid(True)

    scale = 1. / ly
    for pos in xrange(ly + 1):
        add_line(ax, pos * scale, -.1)
    ypos = -.2
    while groups:
        group = groups.pop()
        pos = 0
        for label, rpos in group:
            lxpos = (pos + .5 * rpos) * scale
            ax.text(lxpos, ypos, label, ha='center', transform=ax.transAxes)
            add_line(ax, pos * scale, ypos)
            pos += rpos
        add_line(ax, pos * scale, ypos)
        ypos -= .1

if __name__ == '__main__':
    data = {'Room A':
               {'Shelf 1':
                   {'Milk': 10,
                    'Water': 20},
                'Shelf 2':
                   {'Sugar': 5,
                    'Honey': 6}
               },
            'Room B':
               {'Shelf 1':
                   {'Wheat': 4,
                    'Corn': 7},
                'Shelf 2':
                   {'Chicken': 2,
                    'Cow': 1}
               }
           }
    fig = plt.figure()
    ax = fig.add_subplot(1,1,1)
    label_group_bar(ax, data)
    fig.subplots_adjust(bottom=0.3)
    fig.savefig('label_group_bar_example.png')

rawDescription: How to add group labels for bar charts in matplotlib?

description: Add group labels for bar charts in matplotlib


rawDescription: Python: how best to combine two regex's into one pattern match?


code:
from bottle import route, run, request

@route('/hello/:name')
def index(name='World'):
    return '<b>Hello %s! You are at %s</b>' % (name, request.path)

run(host='localhost', port=8080)

rawDescription: Get current, requested URL in Python without a framework


rawDescription: Python argmin/argmax: Finding the index of the value which is the min or max


code:
s = 'abcdefg'
items_123 = slice(1, 4)
s[items_123]
s[1:4]

rawDescription: Writing python chunking loops with reference to another txt


code:
from __future__ import print_function

def f(x, print=print):
    print(x*x)

f(5)
L=[]
f(6, print=L.append)
print(L)

rawDescription: Self Modifying Python? How can I redirect all print statements within a function without touching sys.stdout?


code: self.connect(self.ILCheck, SIGNAL("valueChanged(bool)"), ILCheckbox, SLOT("setChecked(bool)"))

rawDescription: Python2 PyQt4 Connect a bool Variable to a QCheckBox item


code:
temp = y + 1
y = temp

rawDescription: In Python, why doesn't 'y = x; y += 1' also increment x?


code:
def customeradd(request):
    form = CustomerAddForm(request.POST or None)
    customer_types = CustomerType.objects.all()

    if form.is_valid():
        save_it = form.save(commit=False)
        save_it.save()
        messages.success(request, 'Customer added succesfully')
        return HttpResponseRedirect('/customeroverview/')

    return render_to_response("customer-add.html",
                              {'customer_types': customer_types},
                              context_instance=RequestContext(request))

rawDescription: Django Dropdown with Foreign key in Bootstrap Form


code:
'X'.isidentifier()
'X123'.isidentifier()
'2'.isidentifier()
'while'.isidentifier()

rawDescription: Pythoncially check if a variable name is valid


code:
def removeChars(txt, chars):
    return ''.join(char for char in txt if char.upper() not in chars)

rawDescription: How to remove parameter from string?

description: Remove parameter from string


code:
import pandas as pd

df = pd.DataFrame(["foo bar" , "foo", "bar barf"],columns=["name"])
from operator import itemgetter

df['first_name'], df['last_name'] = zip(*map(itemgetter(0, 2), df['name'].str.partition(" ").values))
print(df)

rawDescription: ValueError: need more than 1 value to unpack, how can I make my code more robust?


rawDescription: 3x1 Matrix Multiplication with lists[UPDATED]


rawDescription: How to calculate CRC32 with Python to match online results?

description: Calculate CRC32 with Python to match online results


rawDescription: Item Loaders not working properly in scrapy


code:
import Image
img = Image.open("Chess_Board.bmp")

rawDescription: convert image to value matrix

description: Convert image to value matrix


code:
class AdjustPWMForm(Form):
    dutyCycle = IntegerField('dutycycle', default=55)

rawDescription: Prepopulate Flask-WTForm IntegerField

description: Prepopulate Flask-WTForm IntegerField


code:
def binarySearch(l, value, low = 0, high = -1):
    binarySearch.counter += 1

rawDescription: How could I use a for loop to count the number of searches being performed in binary search?


code:
if obj.image.storage.exists(obj.image.name):
    ...

rawDescription: django templates upload file - how to handle a non-existant physical file

description: Django templates upload file - how to handle a non-existant physical file


rawDescription: Replace a blank space followed by text with a blank space using string replace


code:
# create the lines
line_objects = plot_multi_y(x, y)

#update the lines
update_multi_y(line_objects, x, y)

rawDescription: Drawing dynamically n plots

description: Drawing dynamically n plots


code:
"{subdomain}{dot}{fullDomain}".format(subdomain=subdomain,
                                      dot='.' if subdomain else '',
                                      fullDomain=fullDomain)

rawDescription: Conditionally parsing a string

description: Conditionally parsing a string


code:
class Character:
    def __init__ (self, name, xp = 0, level = 1, hp = 4, speed = 3, atk = 1, def_ = 2):
        self.name = name
        self.xp = xp
        self.level = level
        self.hp = self.curHp = hp
        self.speed = speed
        self.atk = atk
        self.def_ = def_
        self.inventory = []

rawDescription: Python - Compare two lists and find matching values and their positions in the list


code: description = re.sub(pattern, "\1", description)

rawDescription: Python regex multiline replacement

description: Python regex multiline replacement


code: ScoreList = [[key] + value.values() for key, value in ScoreDict.iteritems()]

rawDescription: (Python) Converting a dictionary to a list?


code: a = ['Hello'+b for b in a]

rawDescription: python add string to the start of each element in array

description: Python add string to the start of each element in array


code: codecs.decode(string, 'unicode_escape')

rawDescription: How to convert a python string

description: Convert a python string


code:
bigstr.index(smallstr)
len(bigstr) - bigstr.index(smallstr) -len(smallstr)

rawDescription: Distance from str to the end (python)

description: Distance from str to the end (python)


code:
import re
p = re.compile("(?<=on ).+")
filename = "*test file on part-of-filename-of-interest.csv"
new_filename = p.search(filename).group(0)

rawDescription: Reading a filename and applying part of that name to a variable


code:
def logsumexp_csr_row(x):
    data = x.data
    mx = max(np.max(data), 0)
    tmp = data - mx
    r = np.exp(tmp, out=tmp).sum()
    k = X.shape[1] - len(data)
    return mx + np.log(r + k * np.exp(-mx))

rawDescription: Log-sum-exp trick on a sparse matrix in scipy


code:
Module(body=[Import(names=[alias(name='ast',
                                 asname=None)]),
             Import(names=[alias(name='sys',
                                 asname=None)]),
             With(context_expr=Call(func=Name(id='open',
                                              ctx=Load()),
                                    args=[Subscript(value=Attribute(value=Name(id='sys',
                                                                               ctx=Load()),
                                                                    attr='argv',
                                                                    ctx=Load()),
                                                    slice=Index(value=Num(n=0)),
                                                    ctx=Load()),
                                          Str(s='r')],
                                    keywords=[],
                                    starargs=None,
                                    kwargs=None),
                  optional_vars=Name(id='my_source',
                                     ctx=Store()),
                  body=[Assign(targets=[Name(id='my_ast',
                                             ctx=Store())],
                               value=Call(func=Attribute(value=Name(id='ast',
                                                                    ctx=Load()),
                                                         attr='parse',
                                                         ctx=Load()),
                                          args=[Call(func=Attribute(value=Name(id='my_source',
                                                                               ctx=Load()),
                                                                    attr='read',
                                                                    ctx=Load()),
                                                     args=[],
                                                     keywords=[],
                                                     starargs=None,
                                                     kwargs=None)],
                                          keywords=[],
                                          starargs=None,
                                          kwargs=None))]),
             Print(dest=None,
                   values=[Call(func=Attribute(value=Name(id='ast',
                                                          ctx=Load()),
                                               attr='dump',
                                               ctx=Load()),
                                args=[Name(id='my_ast',
                                           ctx=Load())],
                                keywords=[],
                                starargs=None,
                                kwargs=None)],
                   nl=True)])

rawDescription: Recommended Compiler Parse Tree Data Structure


code:
def my_range(*args, **kwargs):
    d = {'start':0, 'stop':None, 'step':1}
    for arg, v in zip(('start', 'stop', 'step'), args):
         d[arg] = v
    d.update(kwargs)
    start, stop, step = (d[arg] for arg in ('start', 'stop', 'step'))
    if stop == None:
        start, stop = 0, start
    while start < stop:
        yield start
        start += step

rawDescription: How do Python methods handle arbitrary parameters?


code:
import os

files_path = os.path.join(path, "files.py")

exec(compile(open(files_path).read(), "script", "exec"), {"igor": igor, "IgorPlugin": IgorPlugin})

rawDescription: How to use a variable in a module from the script that called the module

description: Use a variable in a module from the script that called the module


code:
apples
carrots
process
processes
tennis

rawDescription: Regex to get rid of the last term with conditions


code:
example = ['a', 'b', 'c']
', '.join([repr(x) for x in example])

rawDescription: Need to join the elements of a list but keep the '' around element after joining


display: Mark

pass: Smith

rawDescription: How to add to a json file in python

description: Add to a json file in python


code:
from Tkinter import *
import Image, ImageTk,tkFileDialog

class LoadImage:
    def __init__(self,root):
        frame = Frame(root)
        self.canvas = Canvas(frame,width=900,height=900)
        self.canvas.pack()
        frame.pack()
        self.zoomcycle = 0
        self.zimg_id = None
        root.bind("<MouseWheel>", self.zoomer)
        self.canvas.bind("<Motion>", self.crop)

    def abrir(self):
        File = "nlx019PQVT1sidekro1_540.jpg"
        options={}
        options['defaultextension']='.gif'
        options['filetypes']=[('GIF','.gif'),('JPEG','.jpg'),('TIFF','.tif')]
        options['title']='Select image file'
        File=tkFileDialog.askopenfilename()
        self.orig_img = Image.open(File)
        self.img = ImageTk.PhotoImage(self.orig_img)
        self.canvas.create_image(0,0,image=self.img, anchor="nw")

    def zoomer(self,event):
        if (event.delta > 0):
            if self.zoomcycle != 4: self.zoomcycle += 1
        elif (event.delta < 0):
            if self.zoomcycle != 0: self.zoomcycle -= 1
        self.crop(event)

    def crop(self, event):
        if self.zimg_id: self.canvas.delete(self.zimg_id)
        if (self.zoomcycle) != 0:
            x,y = event.x, event.y
            if self.zoomcycle == 1:
                tmp = self.orig_img.crop((x-45,y-30,x+45,y+30))
            elif self.zoomcycle == 2:
                tmp = self.orig_img.crop((x-30,y-20,x+30,y+20))
            elif self.zoomcycle == 3:
                tmp = self.orig_img.crop((x-15,y-10,x+15,y+10))
            elif self.zoomcycle == 4:
                tmp = self.orig_img.crop((x-6,y-4,x+6,y+4))
            size = 300,200
            self.zimg = ImageTk.PhotoImage(tmp.resize(size))
            self.zimg_id = self.canvas.create_image(event.x,event.y,image=self.zimg)

root = Tk()
root.title("Crop Test")
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)

li = LoadImage(root)
filemenu.add_command(label = "Abrir", command = li.abrir)
menubar.add_cascade(label = "Archivo", menu = filemenu)
root.config(menu = menubar)
root.mainloop()

rawDescription: Problems with zoom and menu (Tkinter)

description: Problems with zoom and menu (Tkinter)


code:
class TestReader(BufferedReader):
    def __del__(self):
        self.detach()
        # self.raw will not be closed,
        # rather left in the state it was in at detachment

rawDescription: prevent BufferedReader from closing the file for a list of files

description: Prevent BufferedReader from closing the file for a list of files


rawDescription: oneliner scramble program

description: Oneliner scramble program


code:
import time
while True: range(10000) and None; time.sleep(0.2)      # 1% CPU
while True: range(10000) and None; time.sleep(0.02)     # 15% CPU
while True: range(10000) and None; time.sleep(0.002)    # 60% CPU
while True: range(10000) and None; time.sleep(0.0002)   # 86% CPU

rawDescription: Efficient and fast Python While loop while using sleep()


code:
with open(csvfile) as f:
    headers = next(csv.reader(f, delimiter='|', skipinitialspace=True))
    headers = [header.strip() for header in headers]
    for row in csv.DictReader(f, fieldnames=headers,
                              delimiter='|', skipinitialspace=True):
        do_something_with(row[colname].strip())

rawDescription: Extract a column from a .csv file by name


code:
def set_bytes_from_string(self, data):
    "Sets the value of the packet buffer from the string 'data'"
    self.__bytes = array.array('B', data)

def get_buffer_as_string(self):
    "Returns the packet buffer as a string object"
    return self.__bytes.tostring()

def get_bytes(self):
    "Returns the packet buffer as an array"
    return self.__bytes

def set_bytes(self, bytes):
    "Set the packet buffer from an array"
    # Make a copy to be safe
    self.__bytes = array.array('B', bytes.tolist())

def set_byte(self, index, value):
    "Set byte at 'index' to 'value'"
    index = self.__validate_index(index, 1)
    self.__bytes[index] = value

def get_byte(self, index):
    "Return byte at 'index'"
    index = self.__validate_index(index, 1)
    return self.__bytes[index]

def set_word(self, index, value, order = '!'):
    "Set 2-byte word at 'index' to 'value'. See struct module's documentation to understand the meaning of 'order'."
    index = self.__validate_index(index, 2)
    ary = array.array("B", struct.pack(order + 'H', value))
    if -2 == index:
        self.__bytes[index:] = ary
    else:
        self.__bytes[index:index+2] = ary

def get_word(self, index, order = '!'):
    "Return 2-byte word at 'index'. See struct module's documentation to understand the meaning of 'order'."
    index = self.__validate_index(index, 2)
    if -2 == index:
        bytes = self.__bytes[index:]
    else:
        bytes = self.__bytes[index:index+2]
    (value,) = struct.unpack(order + 'H', bytes.tostring())
    return value

def set_long(self, index, value, order = '!'):
    "Set 4-byte 'value' at 'index'. See struct module's documentation to understand the meaning of 'order'."
    index = self.__validate_index(index, 4)
    ary = array.array("B", struct.pack(order + 'L', value))
    if -4 == index:
        self.__bytes[index:] = ary
    else:
        self.__bytes[index:index+4] = ary

def get_long(self, index, order = '!'):
    "Return 4-byte value at 'index'. See struct module's documentation to understand the meaning of 'order'."
    index = self.__validate_index(index, 4)
    if -4 == index:
        bytes = self.__bytes[index:]
    else:
        bytes = self.__bytes[index:index+4]
    (value,) = struct.unpack(order + 'L', bytes.tostring())
    return value

def set_long_long(self, index, value, order = '!'):
    "Set 8-byte 'value' at 'index'. See struct module's documentation to understand the meaning of 'order'."
    index = self.__validate_index(index, 8)
    ary = array.array("B", struct.pack(order + 'Q', value))
    if -8 == index:
        self.__bytes[index:] = ary
    else:
        self.__bytes[index:index+8] = ary

def get_long_long(self, index, order = '!'):
    "Return 8-byte value at 'index'. See struct module's documentation to understand the meaning of 'order'."
    index = self.__validate_index(index, 8)
    if -8 == index:
        bytes = self.__bytes[index:]
    else:
        bytes = self.__bytes[index:index+8]
    (value,) = struct.unpack(order + 'Q', bytes.tostring())
    return value

def get_ip_address(self, index):
    "Return 4-byte value at 'index' as an IP string"
    index = self.__validate_index(index, 4)
    if -4 == index:
        bytes = self.__bytes[index:]
    else:
        bytes = self.__bytes[index:index+4]
    return socket.inet_ntoa(bytes.tostring())

def set_ip_address(self, index, ip_string):
    "Set 4-byte value at 'index' from 'ip_string'"
    index = self.__validate_index(index, 4)
    raw = socket.inet_aton(ip_string)
    (b1,b2,b3,b4) = struct.unpack("BBBB", raw)
    self.set_byte(index, b1)
    self.set_byte(index + 1, b2)
    self.set_byte(index + 2, b3)
    self.set_byte(index + 3, b4)

rawDescription: Packet sniffer in python using pcapy impacket


code:
from scipy.optimize import fmin_slsqp

# equality constraints as h(x) = 0
def h(x):
    return x[0] + x[1] - 50

# inequality constraints as g(x) >= 0
def g(x):
    return [
        x[0] - 5,
        -x[0] + 65,
        x[1] - 10,
        -x[1] + 40,
    ]

# target functions
f1 = lambda x: x[0] + x[1]
f2 = lambda x: x[0] + x[1] + sum(x**2)

rawDescription: Weight Middle Range for use of scipy.optimize.linprog (Simplex algorithm)


code:
def _standoff(path, leaves, slices, offset, tree):
    width = 0
    for i, child in enumerate(tree):
        if isinstance(child, tuple):
            tok, tag = child
            leaves.append(tok)
            width += 1
        else:
            path.append(i)
            width += _standoff(path, leaves, slices, offset + width, child)
            path.pop()
    slices.append((tuple(path), tree.label(), offset, offset + width))
    return width

def standoff(tree):
    leaves = []
    slices = []
    _standoff([], leaves, slices, 0, tree)
    return leaves, slices

rawDescription: Converting NLTK phrase structure trees to BRAT .ann standoff


code:
data= ['asdf123', 'asdf1234', 'asdf111', 'asdf124']
data.sort( key=key )
data

rawDescription: python sort strings with digits at the end

description: Python sort strings with digits at the end


code: print(*alist, sep='\n')

rawDescription: How to make the output shows tabs instead of showing \t?

description: Make the output shows tabs instead of showing \t


rawDescription: Replace single quotes with double quotes in python, for use with insert into database


code:
for indx, item in enumerate(a):
    c.append(item + [b[indx]])

rawDescription: Unpack items and add a new one

description: Unpack items and add a new one


code:
import datetime
from datetime import date

result = collection.aggregate([
    # Matchn the documents possible
    { "$match": { "date": { "$gte": startdate } } },

    # Group the documents and "count" via $sum on the values
    # use "epoch" "1970-01-01" as a base to convert to integer
    { "$group": {
        "_id": {
            "scan_status": "$scan_status",
            "date": {
                "$subtract": [
                    { "$subtract": [ "$date", date.fromtimestamp(0) ] },
                    { "$mod": [
                        { "$subtract": [ "$date", date.fromtimestamp(0) ] },
                        1000 * 60 * 60 * 24
                    ]}
                ]
            }
        },
        "count": { "$sum": 1 }
    }}
])

rawDescription: PyMongo group by multiple keys

description: PyMongo group by multiple keys


rawDescription: Sequential image presentation in Pygame

description: Sequential image presentation in Pygame


code:
def traverseTree(tree):
  if not isinstance(tree, nltk.Tree): return []
  h = []
  for subtree in tree:
      #no need to check here as well as right inside the call
      h.extend(traverseTree(subtree))
  if tree.label() == 'NP' and len(h) == 0:
      h.append(tree)
  return h

rawDescription: Retrieve Graph Lowest Height Node with Filter


code:
def list_n(n):
    if n < 2:
       return False
    return [random.randrange(1,5) for x in range(n)]

rawDescription: Generate Random and Print List on 1 Line


code:
import csv

company_data = {}  # empty dictionary

with open('data.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    next(reader) # skips the header
    for row in reader:
        company_states = company_data.setdefault(row[0], {})
        state_data = company_states.setdefault(row[1], [])
        state_data.append(row[2])
        company_data[row[0]][row[1]] = state_data

rawDescription: issue in processing data from a csv file and a dictionary in python

description: Issue in processing data from a csv file and a dictionary in python


code:
import re
from datetime import datetime

sz = '2013-07-19T13:02:53.8241899Z'
if '.' in sz:
   sz = re.sub(r'(\.\d{,6})\d*Z?$', r'\1Z', sz) # truncate to 6 digits +Z
else: # no fractions
   sz = sz.rstrip('Z') + '.0Z'

utc_dt = datetime.strptime(sz, '%Y-%m-%dT%H:%M:%S.%fZ')

rawDescription: python strptime from UTC string to datetime regex re.sub

description: Python strptime from UTC string to datetime regex re.sub


code:
['blpcfgokakmgnkcojhhkbfbldkacnbeo', '695108']
['pjkljhegncpnkpknbcohdijeoejaedia', '678425']
['apdfllckaahabafndbhieahigkjlhalf', '651374']
...

rawDescription: python - identify characters from numbers in csv file

description: Python - identify characters from numbers in csv file


code:
from requests_futures import FuturesSession

session = FuturesSession()
# request is run in the background
future = session.get('http://httpbin.org/get')
# ... do other stuff ...
# wait for the request to complete, if it hasn't already
response = future.result()
print('response status: {0}'.format(response.status_code))
print(response.content)

rawDescription: Python: wait for requests_futures.sessions to finish before continuing with the code flow


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file1')
parser.add_argument('file2')
parser.add_argument('vars', type=int, nargs=3)
parser.add_argument('file3',nargs='?')
print(parser.parse_args())

rawDescription: file as an optional parameter

description: File as an optional parameter


code: d = {'timmy': 'red', 'barry': 'green', 'guido': 'blue'}

rawDescription: How is the return value of __hash__ used?


code: matrix_div = pd.DataFrame(R.values/A.T.values, index=R.index, columns=A.index)

rawDescription: Pandas dataframe.dot division method

description: Pandas dataframe.dot division method


code:
data =  ["thematic-scope-112013:Demo.Airport_Traffic", "thematic-scope-112013:Demo.Alcohol_Consumption", "thematic-scope-112013:Demo.Flight_paths", "thematic-scope-112013:Demo.GDP_Country_Wise", "thematic-scope-112013:Demo.like_data", "thematic-scope-112013:Demo.medicare_cost"]
[i.split('.')[-1] for i in data]

rawDescription: Method in python to obtain the following pattern string


rawDescription: Sort table by a column and set other column to sequential value to persist ordering


code:
def main():
    name = input("What is your first name?: ")
    name2 = input("What is your last name?: ")
    mass = float(input("What is your weight in kilograms?: "))
    height = float(input("What is your height in meters?: "))
    #mass = float(kg) #not needed
    #height = float(meters) #not needed
    result = health(mass, height)
    #printing based on the return value. result[0] is bmi, and so on.

    print("%s, %s (BMI: %d, Ponderal Index: %d, Rohrer's Index: %d"%(name2,name,health[0],health[1],health[2]))

def bmi (mass, height):
    result = mass / (height ** 2)
    return result

def ponderal (mass, height):
    result = mass / height ** 3
    return result

def rohrer(mass, height):
    result = (mass * 10000) / ((height * 100) ** 3)
    return result

def health (mass, height):
    #calling the functions
    bmi = bmi(mass, height)  #store the returned value to a variable
    ponderal = ponderal(mass, height)
    rohrer = rohrer(mass, height)
    return [bmi,ponderal,rohrer] #return it as a list.

rawDescription: Why wont my code work?

description: Why wont my code work


code:
[ { 'city_id': x, 'city_name': y, 'city_capital': z }
  for x, y, z in zip(city_id, city_name, city_capital) ]

rawDescription: How to create JSON formatted string from multiple lists in python?

description: Create JSON formatted string from multiple lists in python


code:
def everythird(l):
    i = 0
    ret = []
    while i < len(l):
        ret.append(l[i])
        i += 3
    return ret

rawDescription: Python: How to return a list without modifying the original list using a while loop only?


code:
from itertools import islice, cycle, repeat

def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

# Now, the real recipe starts
obj = {'a1':3,'a2':5,'a3':1}
objiter = [repeat(x,y) for x,y in obj.items()]
objlist = list(roundrobin(*objiter))
objlist
['a1', 'a3', 'a2', 'a1', 'a2', 'a1', 'a2', 'a2', 'a2']

rawDescription: printing dict keys 'value' times and alternatively like round robin scheduling

description: Printing dict keys 'value' times and alternatively like round robin scheduling


code:
def make_pa(prefix):
    def pa(tokens):
        return ParseResults([prefix] + [tokens])
    return pa

optional_expr = (LBRACK + expr + RBRACK).setParseAction(make_pa("OPT:"))
reqd_expr = (LBRACE + expr + RBRACE).setParseAction(make_pa("REQD:"))
user_expr = (LANGLE + OneOrMore(ident) + RANGLE).setParseAction(make_pa("USER:"))

term = ident | optional_expr | reqd_expr | user_expr
term = Group(term * (2,None)) | term
alternation = Group(term + OneOrMore(VERT_BAR + term))
alternation.setParseAction(make_pa("OR:"))

rawDescription: Parsing data between multiple brackets and different kind of brackets


code:
[user(name='root', terminal='pts/0', host='your-local-host-from-isp.net',
started=1358152704.0)]

rawDescription: Find out who is logged in on linux using python


code:
data = [10, 20, 30]
lists = [ [x] for x in data ]

rawDescription: Python: Appending items to lists by iterating through list of lists


code:
def mp(SNR2, *events):
    ...
    return np.asarray([np.array([I for event in events[i]]) for i in range(len(events))]).reshape(events.shape)

rawDescription: Syntax Error in function definition

description: Syntax Error in function definition


code:
def makeValue(highbyte, lowbyte):
    return int(highbyte, 16)*256 + int(lowbyte, 16)

rawDescription: Python BCD splitting nibbles and concatenation 2 ints


code:
def sum_max(L, accum=0, max_value=0):
    if not L:
        return max_value
    accum += L[0]
    return sum_max(L[1:], accum, max(max_value, accum))

def find_max(L):
    ...
    left_half = sum_max(L[mid_index-1::-1])
    right_half = sum_max(L[mid_index:])
    ...

rawDescription: Generative recursion to find the sublist with the maximum sum


code:
import requests

# create a Session object
s= requests.Session()

# first visit the main page
s.get("http://www.pollnet.it/default_it.asp")

# then we can visit the weekly report pages
r = s.get("http://www.pollnet.it/WeeklyReport_it.aspx?ID=69")

print(r.text)

# another page
r = s.get("http://www.pollnet.it/WeeklyReport_it.aspx?ID=89")
print(r.text)

rawDescription: Python library requests open the wrong page


code:
class Composable(object):
    def __init__(self, function):
        self.function = function
    def __call__(self, *args, **kwargs):
        return self.function(*args, **kwargs)
    def __mul__(self, other):
        @Composable
        def composed(*args, **kwargs):
            return self.function(other(*args, **kwargs))
        return composed
    def __rmul__(self, other):
        @Composable
        def composed(*args, **kwargs):
            return other(self.function(*args, **kwargs))
        return composed

rawDescription: How to multiply functions in python?

description: Multiply functions in python


rawDescription: Python float to string, only "dotted notation"?


code:
@api.model
def create(self, vals):
    user_env = self.env['res.users']
    user_vals = {
        'name': self.name,
        'login': self.email,
    }
    user_id = user_env.create(user_vals) # will create user with name and login field
    self.user_id = user_id
    super(TestModel,self).create(vals)

@api.multi
def unlink(self):
    for rec in self:
        if rec.user_id:
            rec.user_id.unlink()
    return super(TestModel, self).unlink()

rawDescription: Automatic user creation in odoo8 when custom record created using inheritance by delegation


code:
df = df.pivot(index='name',columns='time')
#df = df.fillna(0) #to replace NaN with 0 as in your output example

rawDescription: Python pandas: creating condensed dataframe


code:
cnt = np.bincount(np.ravel_multi_index(np.vstack((a, b)), (3, 3)))
np.resize(cnt, (3, 3))

rawDescription: Increment given indices in a matrix

description: Increment given indices in a matrix


code:
df.loc[~df["S"].isin(allowed_vals), "S"] = "None"
df

rawDescription: How to replace all values in a Pandas Dataframe not in a list?

description: Replace all values in a Pandas Dataframe not in a list


code:
def make_mask(s):
    if s.unique().shape[0] == 2: # If binary, return all-false mask
        return np.zeros(s.shape[0], dtype=bool)
    else: # Otherwise, identify outliers
        return s >= np.percentile(s, 99)

rawDescription: Pandas DataFrame apply function doubling size of DataFrame


code:
for item in ObjList:
    self.myCboBox.append(item.label, item)

rawDescription: How can I store objects other than strings in a wxPython ComboBox?

description: Store objects other than strings in a wxPython ComboBox


rawDescription: Defining the name of a ManyToOne relationship in Django


code:
from django.conf import settings

user = settings.DATABASES['default']['USER']
password = settings.DATABASES['default']['PASSWORD']
database_name = settings.DATABASES['default']['NAME']
# host = settings.DATABASES['default']['HOST']
# port = settings.DATABASES['default']['PORT']

database_url = 'postgresql://{user}:{password}@localhost:5432/{database_name}'.format(
    user=user,
    password=password,
    database_name=database_name,
)

engine = create_engine(database_url, echo=False)

rawDescription: How to write a Pandas Dataframe to Django model

description: Write a Pandas Dataframe to Django model


code:
import shiboken
from PySide import QtGui
app = QtGui.QApplication([])
w = QtGui.QWidget()
repr(w)
w.setStyleSheet('{')
print(shiboken.dump(w))
hex(shiboken.getCppPointer(w)[0])
0x12e2fc0

rawDescription: Warning seems to point to a different object address


code:
import usb.backend.libusb1 as libusb1
import usb.backend.libusb0 as libusb0
import usb.backend.openusb as openusb

rawDescription: How do I switch backends in libusb for python?

description: Switch backends in libusb for python


code:
for url in urls:
    line = url

rawDescription: Is it possible to open multiple URLs from a .txt and scrape all the webpages at once?


rawDescription: Trying to implement recursive Tower of Hanoi algorithm with arrays


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

x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]

colors = cm.rainbow(np.linspace(0, 1, len(ys)))
for y, c in zip(ys, colors):
    plt.scatter(x, y, color=c)

rawDescription: Setting different color for each series in scatter plot on matplotlib


code: Product.name = classmethod(lambda cls: "stubbed_name")

rawDescription: Mocking out methods on any instance of a python class


code:
import timeit
timeit.timeit('divmod(n, d)', 'n, d = 42, 7')
timeit.timeit('n // d, n % d', 'n, d = 42, 7')

rawDescription: Is divmod() faster than using the % and // operators?


code:
import pprint
n = 3
distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)]
pprint.pprint(distance)
distance[0][1]
distance[0][1][2]

rawDescription: Create 3D array using Python

description: Create 3D array using Python


code: ipfirewall

rawDescription: Matching IP addresses to a list of subnets and then returning the firewall


code: d = min(date.day, calendar.monthrange(y, m)[1])

rawDescription: What's the simplest way to subtract a month from a date in Python?


code:
for item in ({child.get('value') for child in xml_data} &
             {item[4] for item in main_list}):
    print(item)

rawDescription: Compare two lists in python and print the output


code:
# First, get the tests from the second log.
tests = {}
for line in log2:
    test = line[3] # test number
    if test not in tests:
        tests[test] = {'times': []}

    tests[test]['times'].append(line[5]) # test time

rawDescription: Parse data from 2 log files in Python

description: Parse data from 2 log files in Python


rawDescription: merge two lists to make list of lists

description: Merge two lists to make list of lists


rawDescription: How to merge 2 numpy arrays and concatenate their values?

description: Merge 2 numpy arrays and concatenate their values


code: C

rawDescription: Translate reshape from Matlab to Python

description: Translate reshape from Matlab to Python


code:
dx = x[1]-x[0]
deriv = np.diff(wei.cdf(x))/dx

rawDescription: Calculating the derivative of cumulative density function in Python


code: testvar = "MyVariable"

rawDescription: Django: Pass variable to logging in settings file


code:
d1 = pandas.DataFrame(numpy.array([1, 4]), index=['a', 'b'], dtype="int32")
d2 = pandas.DataFrame(numpy.array([2, 2]), index=['a', 'c'], dtype="int32")

d1.add(d2, fill_value=0)

rawDescription: More efficient solution? Dictionary as sparse vector


code:
class Solution(object):
    def summaryRanges(self, nums):
        """
        :type nums: List[int]
        :rtype: List[str]
        """

rawDescription: leetcode No 228, runtime error

description: Leetcode No 228, runtime error


code: df = pd.read_hdf('/path/to/my_storage.h5', 'my_data', where="A == 'Y'")

rawDescription: Python Pandas memory - subsetting and releasing main data frame


rawDescription: merge to dictionaries preserving different values

description: Merge to dictionaries preserving different values


rawDescription: numpy matrix rank incorrect result

description: Numpy matrix rank incorrect result


code: line_start = self.OutWidget.index("@%s,%s linestart" % (event.x, event.y))

rawDescription: Highlighting a clicked line in an unfocused Tkinter text widget


code:
class Revision (db.Model):
  name = db.StringProperty(required=True)
  created = db.DateTimeProperty(required=True)
  modified = db.DateTimeProperty(auto_now_add=True)
  content = db.TextProperty(required=True)
  user = db.UserProperty()

rawDescription: Storing wiki revisions on Google App Engine/Django - Modifying This Existing Code


code:
states
{0: [u'Miami', u'Orlando'], 1: [u'Los Angeles', u'San Diego']}

rawDescription: Python regex by grouping elements belonging to same category


code: temp = copy.copy(z)

rawDescription: How can I assign by value in python

description: Assign by value in python


code: df2 = df2.drop('None')

rawDescription: percentage of sum in dataframe pandas

description: Percentage of sum in dataframe pandas


code:
p = psutil.Process(1245)  # The pid of desired process
print(p.name()) # If the name is "python.exe" is called by python
print(p.cmdline()) # Is the command line this process has been called with

rawDescription: Checking if program is running

description: Checking if program is running


code:
sdata = sorted(data1 + data2, key=lambda x:x['id'])
res = []
for _,v in itertools.groupby(sdata, key=lambda x:x['id']):
    v = list(v)
    if len(v) > 1:    # happened that the same id was in both datas
        # append the one with higher version
        res.append(v[0] if v[0]['version'] > v[1]['version'] else v[1])
    else:             # the id was in one of the two data
        res.append(v[0])

rawDescription: Merging arrays of versioned dictionaries


code:
from sklearn.naive_bayes import GaussianNB, MultinomialNB, BernoulliNB
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.ensemble import GradientBoostingClassifier
from scipy.sparse import csr_matrix
from sklearn.datasets import load_digits
digits = load_digits()
X, y = digits.data, digits.target

for CLF in [GaussianNB, MultinomialNB, BernoulliNB, LogisticRegression, LinearSVC, GradientBoostingClassifier]:
    print(CLF.__name__, end='')
    try:
        CLF().fit(csr_matrix(X), y == 0)
        print(' PASS')
    except TypeError:
        print(' FAIL')

rawDescription: How to train/upscale a very large dataset using scikit-learn?

description: Train/upscale a very large dataset using scikit-learn


code:
f = open (file,'r')
with open (output,'wt') as m:
    for line in f:
        line = line.strip('\n')
        domain = line.split(';')
        try:
            w = pythonwhois.get_whois(domain)
            c_date = (w['creation_date'])
            print (domain,c_date[0].strftime('%Y/%m/%d'))

        except:
            pass

rawDescription: How to convert a list of datetime.datetime objects to date in Python?

description: Convert a list of datetime.datetime objects to date in Python


code:
logging.config.fileConfig(
    '{0}/logging.cfg'.format(os.path.dirname(os.path.realpath(__file__))),
    disable_existing_loggers=False
)

rawDescription: Python root logger messages not being logged via handler configured with fileConfig


rawDescription: Python Pandas: Get index of rows which column matches certain value


code:
from operator import neg

result = sum(map(neg, L[1:]), L[0])

rawDescription: How to subtract from a user-inputed list

description: Subtract from a user-inputed list


code:
with open('filename') as inputfile:
    rows = [line.split() for line in inputfile]

columns = zip(*rows)

rawDescription: reading files as both vertical lists and horizental lists(python 3.2)

description: Reading files as both vertical lists and horizental lists(python 3.2)


code:
from subprocess import check_output,CalledProcessError
def apt_cache(app):
    try:
        return check_output(["apt-cache", "policy",app])
    except CalledProcessError as e:
        return e.output

print(apt_cache("python"))

rawDescription: How to lookup debian package info with Python

description: Lookup debian package info with Python


rawDescription: Parsing text file and storing it in a list


code:
class AuthorSpider(BaseSpider):
    ...

    def __init__(self, articles):
        self.start_urls = []

        for line in articles:
            article = json.loads(line)
            self.start_urls.append(data['author_url'])

rawDescription: Writing to multiple files with Scrapy

description: Writing to multiple files with Scrapy


rawDescription: Why is python returning a numbers from a string?


code: ' '.join(word for word in line.split() if word.isalpha() and word.lower() in list)

rawDescription: remove characters from a python string

description: Remove characters from a python string


code:
class FooForm(forms.ModelForm):
    name = forms.CharField()

    class Meta:
        model = People
        widgets = {
            'name': forms.Textarea(attrs={'placeholder': u'Bla bla'}),
        }

rawDescription: Specifying widget for model form extra field (Django)


rawDescription: How to access first and last timestamp in dataframe

description: Access first and last timestamp in dataframe


code:
from collections import defaultdict
dd = defaultdict(int)

with open('D:/project/report.txt','r') as fob:
    for line in fob:
        for word in line.split():
            dd[word] += 1

rawDescription: Storing the count of each word occurring in a text file


code:
import itertools

def get_distance(w1, w2):
    if w1 in words and w2 in words:
        w1_indexes = [index for index, value in enumerate(words) if value == w1]
        w2_indexes = [index for index, value in enumerate(words) if value == w2]
        distances = [abs(item[0] - item[1]) for item in itertools.product(w1_indexes, w2_indexes)]
        return {'min': min(distances), 'avg': sum(distances)/float(len(distances))}

rawDescription: Determining proximity between 2 words in a sentence in Python


code:
def isNum(s):
    try:
            float(s)
            return True
    except ValueError:
            return False
lst = ['hello', '2U:', '-224.3', '45.1', 'SA 2']
lst = list(filter(isNum, lst))

rawDescription: How to remove strings that contain letters from a list?

description: Remove strings that contain letters from a list


code:
result = dict(curs.fetchall())
result = [(result.get(d,None), d) for d in date]

rawDescription: Query Sqlite for multiple arguments at once and handling missing values


code:
res = DF.set_index(["a", "d"])["e"]
res

rawDescription: How to use Pandas to create Dictionary from column entries in DataFrame or np.array

description: Use Pandas to create Dictionary from column entries in DataFrame or np.array


code: [r for r in (f(char) for char in string) if r is not None]

rawDescription: Ignore an element while building list in python


code:
print(s)
def parse_message_to_tree(message):
    buf = StringIO(message)
    return parse_message_to_tree_helper(buf, 0, None)[0]
def parse_message_to_tree_helper(buf, prev, prevline):
    ret = {}
    index = -1
    for line in buf:
        line = line.rstrip()
        index = len(line) - len(line.lstrip())
        print (line + " => " + str(index))
        if index > prev:
            ret[prevline.strip()],prevline,index = parse_message_to_tree_helper(buf, index, line)
            if index < prev:
                return ret,prevline,index
            continue
        elif not prevline:
            ret[line.strip()] = {}
        else:
            ret[prevline.strip()] = {}
        if index < prev:
            return ret,line,index
        prevline = line
    if index == -1:
        ret[prevline.strip()] = {}
        return ret,None,index
    if prev == index:
        ret[prevline.strip()] = {}
    return ret,None,0
pprint.pprint(parse_message_to_tree(s))
s = """line a
line b
  line ba
  line bb
    line bba
  line bc
line c
  line ca
    line caa
line d"""
pprint.pprint(parse_message_to_tree(s))

rawDescription: converting a string to a tree structure in python

description: Converting a string to a tree structure in python


rawDescription: python match regular expression

description: Python match regular expression


code:
True
True
True
True

rawDescription: Why can `__subclasshook__` be monkeypatched onto the metaclass but `__instancecheck__` cannot?


code:
for i, col in enumerate(df.columns):
    df.iloc[:, i] = df.iloc[:, i].str.replace('"', '')

rawDescription: Remove all quotes within values in Pandas


rawDescription: gotchas where Numpy differs from straight python?

description: Gotchas where Numpy differs from straight python


code:
(df.join(pd.concat({'sum': df.groupby(level=1, axis=1).sum()}, axis=1))
   .sortlevel(level=1, axis=1))

rawDescription: Using groupby and apply to add column to each group


code: day_indexes = dict((name, i) for i, name in enumerate(calendar.day_name))

rawDescription: Python: Converting ('Monday', 'Tuesday', 'Wednesday') to 'Monday to Wednesday'


code:
def filter(self, *args, **kwargs):
    args, kwargs = self.__translate(*args, **kwargs)
    super(QuerySet, self).filter(args, kwargs)

rawDescription: Django : how could I overload Q in django.db.models.query QuerySet to use for a special purpose in my Manager


code:
import pandas as pd
import numpy as np

rawDescription: make 1 dimensional array of strings with elements seperated by commas from 2 d array in numpy

description: Make 1 dimensional array of strings with elements seperated by commas from 2 d array in numpy


rawDescription: Iterating w/ Pandas DataFrame and Changing Values


code:
username = "xy"
password = "abcd"

rawDescription: Storing the secrets (passwords) in a separate file


code:
yaj = function(x1, *pars)
plt.figure(1, figsize=(8.5, 11))
plt.plot(x1, y1, 'g-', x1, yaj, 'r-')
plt.xlim(min(x1), max(x1))
plt.ylim(min(y1), max(y1))
plt.show()

rawDescription: Getting completely wrong fit from python scipy.optimize.curve_fit


code:
pages = [{"letter": i, "contacts": contact_list.filter(first_name__istartswith=i) }
           for i in "ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
return render(request, 'contact/contact.html', {'pages': pages})   # why pass contact_list?

rawDescription: Paginating based on the alphabet (A-Z)

description: Paginating based on the alphabet (A-Z)


rawDescription: How to remove commas, brackets in python using regular expression?

description: Remove commas, brackets in python using regular expression


code:
trailingcomma = re.compile(r',(\s*})')
result = trailingcomma.sub(r'\1', result)

rawDescription: How to parse Apple's IAP receipt mal-formatted JSON?

description: Parse Apple's IAP receipt mal-formatted JSON


code: date, time, ok = DateDialog.getDateTime()

rawDescription: How can I show a PyQt modal dialog and get data out of its controls once its closed?

description: Show a PyQt modal dialog and get data out of its controls once its closed


code:
def View(request):
   result = test_function()
   return render_to_response('template', {'test_valiable' : result })

rawDescription: django - calling functions form one file to another

description: Django - calling functions form one file to another


code:
Example
total = Counter()
for _ in range(1000):
    sample = weighted_sample("abc", [1,10,2], 5)
    total.update(sample)
print(sample)
print("Frequences %s" % (dict(Counter(sample)),))

# Check that values are sane
print("Total " + ', '.join("%s: %.0f" % (val, count * 1.0 / min(total.values()))
                           for val, count in total.most_common()))

rawDescription: Weighted random sample in python

description: Weighted random sample in python


code: syscalls = set(ln.split('(', 1)[0] for ln in strace_output)

rawDescription: Extracting unique syscall names from strace output (via regex?)


code:
from nltk import FreqDist
fd = FreqDist(list('aaabbbbbcccccdddddddd'))
last_two = FreqDist(dict(fd.most_common()[-2:]))
last_two.plot()

rawDescription: plot the 50 least frequent words with nltk

description: Plot the 50 least frequent words with nltk


code:
@all_chainable
class Foo(object):
    def show(self):
        self.visibility = True

rawDescription: DRYout a class-based chainable API

description: DRYout a class-based chainable API