code: ROOT_URLCONF = 'try.urls'

rawDescription: django - ImportError

description: Django - ImportError


code:
@timeout(0.5, raise_exc=False)
def outer():
    return inner()

@timeout(2)
def inner():
    time.sleep(1)
    return "Shouldn't be printed"

print(outer())  # None

rawDescription: Nestable timeout decorator? (i.e. timeout decorated func calling timeout decorated func)


code: mylist = list(xrange(10))

rawDescription: Python: How to make a list of n numbers and randomly select any number?


code:
import collections
Row = collections.namedtuple('Row', 'lsn tid status type item AFIM BFIM')

for row in map(lambda row: Row(*row), l):
    if row.tid == 1 and row.type == 'Write':
        print(row)

# will print ...
# Row(lsn=2, tid=1, status='Active', type='Write', item='X', AFIM='2', BFIM='0')

rawDescription: searching an element in list of list

description: Searching an element in list of list


code:
def echo(self, start=0, stop=None, search=None):
    if stop is None:
        stop = len(self.codeSegment)

rawDescription: Python code, self not defined

description: Python code, self not defined


code:
df1['size'] = df1['Petal.Length'] * df1['Petal.Width']
print(df1)

rawDescription: Merging two data frames and doing calculation


code: s, loc, scale = stats.lognorm.fit(data, floc=0)

rawDescription: A lognormal distribution in python

description: A lognormal distribution in python


code:
matched_lines = list(line for line in f_in if "timeout of" in line)
f_out.writelines(matched_lines)

rawDescription: How do I search a file, count the number of hits and write the number to column B in a .csv?

description: Search a file, count the number of hits and write the number to column B in a .csv


code:
any(map(somefunction, sequence))
all(map(somefunction, sequence))

rawDescription: Does Python have andmap / ormap?

description: Does Python have andmap / ormap


code:
import datetime
values = ['2014', '08', '17', '18', '01', '05']
datetime.datetime(*map(int, values))

rawDescription: Python create datetime object from list of values


code:
import mymodule
mymodule.__all__
mymodule.b

rawDescription: can I regard __slots__ as the __all__ for classes?

description: Regard __slots__ as the __all__ for classes


code:
lis=[1,2,3,4,5,6,7,8,9,10,11,12]
w=3       #window size
[sum(lis[i-(w-1):i+1]) if i>(w-1) else sum(lis[:i+1])  for i in range(len(lis))]
w=4
[sum(lis[i-(w-1):i+1]) if i>(w-1) else sum(lis[:i+1])  for i in range(len(lis))]

rawDescription: Python Running cumulative sum with a given window


code:
# To fetch an empty answered question
qry = Calculation.All().filter('answer =', None)
ref = qry.get()

# The Json response
{ 'key': unicode(ref.key()),
  'question': ref.question}

rawDescription: using GAE datastore for job management

description: Using GAE datastore for job management


code:
def index_by_identity(lst, target):
    for i, obj in enumerate(lst):
        if obj is target:
            return i
    # no object matches
    raise IndexError(target)

rawDescription: Using .index() with duplicate values that have separate identifiers


code:
for x in get_first_list() or []:
    # process x
    break # process at most one item
for y in get_second_list() or []:
    # process y
    break

rawDescription: Python idiom to return first item or None


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

fp1 = fm.FontProperties(fname='/usr/share/fonts/truetype/ubuntu-font-family/Ubuntu-B.ttf')

data = np.random.randn(5000) #generate some random data
plt.plot(data)
plt.title(u"Τίτλος του γραφήματος", fontproperties=fp1)
plt.xlabel(u"Άξονας x", fontproperties=fp1)
plt.ylabel(u"Άξονας y", fontproperties=fp1)
plt.show()

rawDescription: Writing Greek in matplotlib labels, titles


code:
ar1 = np.array([1,2,3,8,20,23])
ar2 = np.array([1,2,3,5,7,21,35])
def closest(ar1, ar2, iter):
    x = np.abs(ar1[iter] - ar2)
    index = np.where(x==x.min())
    value = ar2[index]
    return value

def find(x):
    return closest(ar1, ar2, x)
c = np.array(map(find, range(ar1.shape[0])))

rawDescription: how to match two numpy array of unequal length?

description: Match two numpy array of unequal length


code:
fruits = [f for f in foods if f[0] == 'fruit']
fruit_count = len(fruits)

rawDescription: Using counter on array for one value while keeping index of other values


code:
def foo():
    print("in foo()")
    return "foo"

bar = foo()
opt = "initial"

rawDescription: how do imports work for a module used as a singleton?

description: How do imports work for a module used as a singleton


rawDescription: Transform filter function to Python code


code:
'Feeling hexey 0x{:X} and octally 0{:o} for decimal {}'.format(12, 12, 12)
"Lot's o decimals: {:0.30f}".format(.5)

rawDescription: python3.4.2 how to assign a string with texts and variables

description: Python3.4.2 how to assign a string with texts and variables


rawDescription: use variable to specify format in python

description: Use variable to specify format in python


code:
y = Xorg[:,weightind]
X = np.delete(X, weightind, 1)

rawDescription: How to create an SVM for my data?

description: Create an SVM for my data


rawDescription: Adjacency List and Adjacency Matrix in Python


code:
class C2(B, A2):
    def __init__(self, value):
        self.data = value

a = C2(10).m(2)
#Calling method m of class B
#Calling method m of class A2
#Calling method m of class A2

class C3(B, A3):
    def __init__(self, value):
        self.data = value

a = C3(10).m(1)
#Calling method m of class B
#Calling method m of class A3

rawDescription: Mixin to override inherited method

description: Mixin to override inherited method


code:
df["SUBMISSION_DATE"] = pd.to_datetime(df["SUBMISSION_DATE"],dayfirst=True)

gs = df.groupby(["USER_ID", "CONTRACT_REF"])["SUBMISSION_DATE"]
df["TIME_DIFF"] = gs.diff().fillna(0) / pd.datetools.timedelta(hours=1)

rawDescription: How to calculate difference on previous within set of grouped rows in a dataframe

description: Calculate difference on previous within set of grouped rows in a dataframe


code: print(c, end='')

rawDescription: Python: Print to one line with time delay between prints


code:
def replace(t, a, b):
    t = [elem for sub in t for elem in sub]

    inner_a_matches_removed = []
    for i, elem in enumerate(t):
        if not i % 2 or elem != a:
            inner_a_matches_removed.append(elem)
            continue
        if i < len(t) - 1 and t[i+1] == a:
            continue
        inner_a_matches_removed.append(elem)

    replaced = []
    for elem in inner_a_matches_removed:
        if elem == a:
            replaced.extend(b)
        else:
            replaced.append(elem)
    return [replaced[x:x+2] for x in range(len(replaced)-1)]

rawDescription: Digram list manipulation with Python

description: Digram list manipulation with Python


code:
def sparse_mov_avg(idx, val, win):
    avg_idx = np.arange(-win, win+1) + idx[:, None]
    avg_val = np.tile(val[:, None]/(2*win+1), (1, 2*win+1))
    unique_idx, _ = np.unique(avg_idx, return_inverse=True)
    mov_avg = np.bincount(_, weights=avg_val.ravel())
    return unique_idx, mov_avg

rawDescription: Efficiently take moving average of sparse data and filter above threshold in python


rawDescription: Accessing dictionary values within a dictionary


code: inlinkDict[docid] = adoc[1:] if adoc[1:] else 0

rawDescription: Creating a dictionary with list of lists in Python


code:
...
self.label = Label('/path/to/image.png')
...

rawDescription: Resizing QPixmap while maintaining aspect ratio


code:
def saveConfig():
    global config

    config.set('Default', 'Param1', e1.get())
    config.set('Default', 'Blah7', e2.get())
    config.set('Default', 'Param3', e3.get())
    config.write(open('config.ini','w'))

    root.quit()

Button(root, "QUIT", command=saveConfig)

rawDescription: tkinter and configparser : looking for a more beautiful solution

description: Tkinter and configparser : looking for a more beautiful solution


rawDescription: How to set a variable with pressing a button on an html file to the flask server route

description: Set a variable with pressing a button on an html file to the flask server route


code:
roads = RoadNetwork()
roads.types
roads.HighWay.max_speed
roads.HighWay.min_speed
roads.HighWay.road_type

rawDescription: Python Class with sub properties (Beginner)


code:
for i in xrange(x_len-1,0,-1):
    height_needed = shadow_map[i]

rawDescription: Speed up NumPy loop

description: Speed up NumPy loop


code:
if input is not None and not(
   var_a and var_a in input and
   var_b and var_b in input):
    pass

rawDescription: Python: more concise logic/syntax on empty strings


rawDescription: Python: Pulling data out of dictionary like a 2D array


code:
def galaxy_model2(q,c,Cb,rout,rin,Oout,a,M,N,Io,ro,n):
    gal_center=(0,0)
    x,y=meshgrid(arange(-M/2,M/2,1), arange(-N/2,N/2,1))
    r=(abs(x-gal_center[1])**(c+2.0)+((abs(y-gal_center[0]))/(q))**(c+2.0))**(1.0/(c+2.0))
    A=2*Cb/(abs(Oout)+Cb)-1.00001
    B=(2-np.arctanh(A))*((rout)/(rout-rin))
    T=0.5*(np.tanh(B*(r/rout-1)+2)+1)
    Or=Oout*T*(0.5*(r/rout+1))**a
    Or=30-np.log(1.0+r**2.0)+(2.0/p)*np.cos(n2*arctan2(x,y)+k*Or)
    I_exp=exponential_profile(Io,ro,r)
    I_ser=sersic_profile(Io,ro,r,n)
    #galaxy_model_2=0.5*Or
    return Or

rawDescription: Creating a spiral structure in Python, using hyperbolic tangent


code: [tup + (True,) if tup[0] in dol_values else tup for tup in lot]

rawDescription: complicated list and dictionary lookup in python

description: Complicated list and dictionary lookup in python


code: s[s.groupby(level=0).transform(lambda x: x == x.max()).astype(bool)]

rawDescription: Multiindex pandas groupby + aggregate, keep full index


rawDescription: How to reduce xticks label resolution when showing clock time

description: Reduce xticks label resolution when showing clock time


code:
import lxml.etree as ET

filename = '/tmp/test.xml'
with open(filename,'w') as f:
    f.write(ET.tostring(myobject))

rawDescription: saving an 'lxml.etree._ElementTree' object

description: Saving an 'lxml.etree._ElementTree' object


code: whos

rawDescription: Simple subtraction causes a broadcasting issue for different array shapes


code:
df1.apply(lambda x: np.sum(df2.values == x.values), axis=1).sum()

63

rawDescription: iterate through all dataframe columns

description: Iterate through all dataframe columns


code:
length = int(1 + (stop - 1 - start) / step)
for counter in range(length):
    i = start + counter * step
    temp = f(i) * step
    cuenta += temp

rawDescription: different answers when using different loop constructs

description: Different answers when using different loop constructs


code:
class foo: pass

a = foo()
a.bar = 1
getattr(a,'bar')
getattr(a,'baz',"Oops, foo doesn't have an attrbute baz")

rawDescription: Using a variable as part of a variable name


rawDescription: python capitalize first letter only

description: Python capitalize first letter only


code: abcd

rawDescription: Numpy: Creating an (x,y,2,2) array from 4 (x,y) arrays


code:
if __name__=="__main__":
    import logging
    logging.basicConfig(filename='bot.log', level=logging.INFO)

rawDescription: I can not use the import command

description: I can not use the import command


code:
rows = np.flatnonzero((~mask).sum(axis=1))
cols = np.flatnonzero((~mask).sum(axis=0))
im[rows.min():rows.max()+1, cols.min():cols.max()+1]

rawDescription: Remove empty 'rows' and 'columns' from 3D numpy pixel array


code:
from itertools import cycle
x_values = cycle((1, 'spam', 3.14))
next(x_values)
next(x_values)
next(x_values)
next(x_values)

rawDescription: if statement vs. expression

description: If statement vs. expression


code:
...
# keep rows with 16 columns and no empty strings
cols_iter = iter(cols)
data.append(list(zip(cols_iter, cols_iter)))

rawDescription: grabbing info from a table with loops (python)

description: Grabbing info from a table with loops (python)


code: for l in open("text"): print(l.strip())

rawDescription: Read large text file without read it into RAM at once


code:
sum, diff = foo(True)
sum = foo() #old calls still just get sum

rawDescription: Multiple return values in python

description: Multiple return values in python


rawDescription: dict.setdefault appends one extra (default?) item into the value list

description: Dict.setdefault appends one extra (default?) item into the value list


code:
def generate_numbers(digits, length):
    return [int(''.join(d)) for l in range(length) for d in product(digits, repeat=l + 1)]

generate_numbers('89', 3)
generate_numbers('123', 5)

rawDescription: How do I create a lambda function to print numbers containing x and y in Python?

description: Create a lambda function to print numbers containing x and y in Python


rawDescription: Convert a 3D array to 2D array based on dictionary


code:
mylist = ["name", "state", "name", "city", "name", "zip", "zip"]

from collections import Counter # Counter counts the number of occurrences of each item
counts = Counter(mylist) # so we have: {'name':3, 'state':1, 'city':1, 'zip':2}
for s,num in counts.items():
    if num > 1: # ignore strings that only appear once
        for suffix in range(1, num + 1): # suffix starts at 1 and increases by 1 each time
            mylist[mylist.index(s)] = s + str(suffix) # replace each appearance of s

rawDescription: Python: Rename duplicates in list with progressive numbers without sorting list


code:
import my.functions

def cleaner():
    print("Replacement fake cleaner!")

my.functions.cleaner = cleaner

def method_to_test():
    from my.functions import cleaner
    from my.functions import worker
    cleaner()
    worker()

if __name__ == "__main__":
    method_to_test()

rawDescription: How to load my fake module every time when `import a real module` in python?

description: Load my fake module every time when `import a real module` in python


rawDescription: Using xticks, ticks not aligned properly with figure


rawDescription: How to write this snippet in Python?

description: Write this snippet in Python


code: temp2.apply(lambda x: x[2])

rawDescription: Get last "column" after .str.split() operation on column in pandas DataFrame


code:
account_one = Account('John Smith', 500)
account_two = Account('Jane Smith', 100)

bank = Bank("The Bank O'Money")
bank.add_account(account_one)
bank.add_account(account_two)
bank.transfer(account_one, account_two, 10)
bank.accounts # <-- this will be a list of two objects

another_bank = Bank("The Bank of Even More Money")
another_bank.accounts # <-- this will be empty

rawDescription: Class Level Variables python

description: Class Level Variables python


code:
costs = [float(item["cost"]) for item in lst]
print(min(costs))

rawDescription: Get dictionary with lowest key value from a list of dictionaries


code:
from collections import namedtuple

Change = namedtuple("Change", ("old", "new", "action"))

class History(object):
    def __init__(self):
        self.history = []

    def save_change(self, old, new, action):
        change = Change(old, new, action)
        self.history.append(change)

    def get_history(self):
        return self.history

class ChangeableObject(object):
    def __init__(self, make_history=True):
        if make_history:
            self.history = History()
            self.history.save_change(None, self, "created")
        self.cloneable_attributes = ()

    @classmethod
    def get_clone(cls, obj):
        attrs = {attr: getattr(obj, attr) for attr in obj.cloneable_attributes}
        return cls(make_history=False, **attrs)

    def view_history(self):
        return self.history.get_history()

class Contact(ChangeableObject):
    def __init__(self, name, phone, email, make_history=True):
        super(Contact, self).__init__(make_history=make_history)
        self.name = name
        self.phone = phone
        self.email = email
        self.cloneable_attributes = ("name", "phone", "email")

    def update_phone(self, phone):
        clone = self.get_clone(self)
        self.phone = phone
        self.history.save_change(clone, self, "phone updated")

    def __repr__(self):
        return "{} {} {}".format(self.name, self.phone, self.email)

rawDescription: Python inheritance best practice for 'object histories'


rawDescription: How to replace a non-static substring case-insensitively

description: Replace a non-static substring case-insensitively


code:
import pytz # $ pip install pytz

dt = datetime.fromtimestamp(timestamp, pytz.timezone('US/Eastern'))
s = dt.strftime('%Y-%m-%d %H:%M:%S')
# -> '2015-03-19 08:37:15'

rawDescription: Convert Time Zone + format in Python from Twitter API


code: (df + ' ').sum(axis=1).str.strip()

rawDescription: Equivalent for str.join in pandas

description: Equivalent for str.join in pandas


rawDescription: TypeError: unsupported operand type(s) for -: 'list' and 'list'


code:
#!/usr/bin/python-exec-c
# vim:fileencoding=utf-8:ft=python
# (c) 2012 Michał Górny
# Released under the terms of the 2-clause BSD license.
#
# This is not the script you are looking for. This is just a wrapper.
# The actual scripts of this application were installed with -python*,
# -pypy* or -jython* suffixes. You are most likely looking for one
# of those.

from __future__ import with_statement
import os, os.path, sys

try:
    from epython import EPYTHON
except ImportError:
    EPYTHON = os.path.basename(sys.executable)
    if '' and EPYTHON.endswith(''):
        EPYTHON = EPYTHON[:-len('')]

# In the loop:
# sys.argv[0] keeps the 'bare' name
# __file__ keeps the 'full' name

while True:
    __file__ = sys.argv[0] + '-' + EPYTHON

    try:
        kwargs = {}
        if sys.version_info[0] >= 3:
            import tokenize

            # need to provide encoding
            with open(__file__, 'rb') as f:
                kwargs['encoding'] = tokenize.detect_encoding(f.readline)[0]

        with open(__file__, 'r', **kwargs) as f:
            data = f.read()
    except IOError:
        # follow symlinks (if supported)
        try:
            sys.argv[0] = os.path.join(os.path.dirname(sys.argv[0]),
                    os.readlink(sys.argv[0]))
        except (OSError, AttributeError):
            # no more symlinks? then it's time to fail.
            sys.stderr.write('This Python implementation (%s) is not supported by the script.\n'
                    % EPYTHON)
            sys.exit(127)
    else:
        break

sys.argv[0] = __file__
exec(data)

rawDescription: What is the function of this python script(python-exec tool)?


rawDescription: Converting PANDAS dataframe from monthly to daily


code: df = read_csv(StringIO(data),sep='|')

rawDescription: Aggregating over timestamps in pandas

description: Aggregating over timestamps in pandas


code:
def short(gen,X):
    n = next(gen)
    return n if n>X else short(gen,X)

rawDescription: Elegant way to calculate first generator result larger than X


code: common_parser.add_argument('--color', dest='color', required=False, default="BLUE", help='set the color')

rawDescription: How do I pass the argument correctly in Python

description: Pass the argument correctly in Python


code:
display = X11.XOpenDisplay(None)
key = XEvent(type=2).xkey #KeyPress
key.keycode = X11.XKeysymToKeycode(display, 0xffcc) #F15
key.window = key.root = X11.XDefaultRootWindow(display)
X11.XSendEvent(display, key.window, True, 1, ctypes.byref(key))
X11.XCloseDisplay(display)

rawDescription: How can I use python xlib to generate a single keypress?

description: Use python xlib to generate a single keypress


code:
return render_to_response('gallery/list_galleries.html',
                          {'galleries': zip(list_galleries,  g)})

rawDescription: Django adding two objects to view

description: Django adding two objects to view


rawDescription: Python strip() function - remove characters before/after string


code:
newtable = []
for i in table:
    newtable.append(i + ' |')
    newtable.append('-'*len(newtable[0]))

rawDescription: How can I recreate the following using list comprehensions?

description: Recreate the following using list comprehensions


code:
import random

def funcdec(func):
    state = random.random()
    def wrapper(*args, **kwargs):
        return func(state, *args, **kwargs)
    return wrapper

rawDescription: Python "Multi-Level Decorator" - how does this work?


code:
li = ['x, y, z', 'dogs, cats']
sum([elem.split(', ') for elem in li], [])

rawDescription: Python List of Strings created from a list of one string


rawDescription: Definition and difference between a shared array view and a copy of array data?


code:
from itertools import izip_longest
list_of_values = []
dict(izip_longest(('key1', 'key2', 'key3'), list_of_values[:3]))
list_of_values = ['foo']
dict(izip_longest(('key1', 'key2', 'key3'), list_of_values[:3]))
list_of_values = ['foo', 'bar']
dict(izip_longest(('key1', 'key2', 'key3'), list_of_values[:3]))
list_of_values = ['foo', 'bar', 'baz']
dict(izip_longest(('key1', 'key2', 'key3'), list_of_values[:3]))

rawDescription: Python - How to use try/except statement in dictionary


code:
from django.db import models

class model1(models.Model):
    name  = models.CharField(max_length=100)

rawDescription: How to move a model between two Django apps (Django 1.7)

description: Move a model between two Django apps (Django 1.7)


code:
"""
Usage:
    my_program [--comment=ARG]... FILE

Arguments:
    FILE       An argument for passing in a file.

Options:
    --comment  Zero or more comments
"""

rawDescription: How to specify one optional argument several times in docopt

description: Specify one optional argument several times in docopt


rawDescription: Transforming polynomial variable in Numpy


code: struct.unpack('f', file.read(4))

rawDescription: Reading 32 bit signed ieee 754 floating points from a binary file with python?


code:
import multiprocess as mp
# build a target function
def doit(x):
  return x**2 - 1

x = range(10)
# the for loop
y = []
for i in x:
  y.append(doit(i))

y

rawDescription: How to parallelize this piece of code?

description: Parallelize this piece of code


lkajdlkj oiuaoiuoi

kind: drive#permission

role: owner

type: user

rawDescription: Google Drive Permissions API – security settings


code: f = struct.unpack('>f', packed_v)[0]

rawDescription: convert unsigned integer to float in python

description: Convert unsigned integer to float in python


code:
# in models.py

graduation_choices = ([(x,str(x)) for x in range(1970,2015)])
graduation_choices.reverse()

class UserProfile(models.Model):
    # usually you want null=True if blank=True. blank allows empty forms in admin, but will
    # get a database error when trying to save the instance, because null is not allowed
    user = models.OneToOneField(User)       # OneToOneField is more explicit
    network = models.ForeignKey(Network)
    location = models.CharField(max_length=100, blank=True, null=True)
    graduation = models.CharField(max_length=100, blank=True, null=True, choices=graduation_choices)
    headline = models.CharField(max_length=100, blank=True, null=True)
    positions = models.ManyToManyField(Position, blank=True)
    avatar = models.ImageField(upload_to='images/%Y/%m/%d', blank=True, null=True)

    def get_avatar_path(self):
        if self.avatar is None:
            return 'images/default_profile_picture.jpg'
        return self.avatar.name

    def is_complete(self):
        """ Determine if getting started is complete without requiring a field. Change this method appropriately """
        if self.location is None and self.graduation is None and self.headline is None:
            return False
        return True

rawDescription: Improving Python/django view code

description: Improving Python/django view code


code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dates
from matplotlib.ticker import FuncFormatter, NullFormatter
import pylab

from StringIO import StringIO

table = table.replace("0:00", "")
sio = StringIO(table)
df = pd.read_table(sio, sep=r"\s+", parse_dates=['yrend'])
df = df.pivot_table(index=["yrend"], columns=["state","suburb"], values=["median_price"])

fig, ax = plt.subplots()

# plot the lines
for col in df.columns:
    ax.plot(df.index, df[col])

# tune the tickers
locator  = dates.MonthLocator(range(1, 13), bymonthday=1, interval=6)
ax.xaxis.set_minor_locator(locator)
def _monthFmt(x, pos):
    dt = pylab.num2date(x)
    return dt.strftime('%Y') if dt.month == 2 else dt.strftime("%b")
formatter = FuncFormatter(_monthFmt)
ax.xaxis.set_minor_formatter(formatter)
# quiet major formatter - default the years
ax.xaxis.set_major_formatter(NullFormatter())
ax.xaxis.grid(True, which="minor")

ax.yaxis.grid()

plt.show()

rawDescription: Plot no consecutive days with even intervals


code:
s = 'I am a superman, what are you'
n = s.index('what')
[i for (i, c) in enumerate(s) if c == 'a' and n <= i <= n+len('what')]

rawDescription: Finding index number for a character of a particular word in the string


code:
def pyramid(h,symbol="#"):
    return "\n".join((" " * (h-i - 1)) + (symbol * (2 * i + 1)) for i in range(h))

print(pyramid(5))

rawDescription: Writing a function that prints a pyramid - two parameters


code: currency, amount, multiplier = re.match(r'(\D+)(\d+(?:\.\d+)?)([mMkK])', '$1.5k').groups()

rawDescription: Extract the number and following letter from regex


code:
import requests
import json

response = requests.get("https://catalog.paytm.com/v1//g/electronics/mobile-accessories/mobiles/smart-phones?page_count=1&items_per_page=30&resolution=960x720&quality=high&sort_popular=1&cat_tree=1&callback=angular.callbacks._3&channel=web&version=2")
jsonResponse = ((response.text.split('angular.callbacks._3('))[1].split(');')[0])
data = json.loads(jsonResponse)
print(data["grid_layout"])
grid_data = data["grid_layout"]

for grid_item in grid_data:
    print("Brand:", grid_item["brand"])
    print("Product Name:", grid_item["name"])
    print("Current Price: Rs", grid_item["offer_price"])
    print("==================")

rawDescription: Scraping hidden elements using BeautifulSoup


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

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots()
line, = ax.plot(x, y, color='k')

def update(num, x, y, line):
    line.set_data(x[:num], y[:num])
    line.axes.axis([0, 10, 0, 1])
    return line,

ani = animation.FuncAnimation(fig, update, len(x), fargs=[x, y, line],
                              interval=25, blit=True)
ani.save('test.gif')
plt.show()

rawDescription: Animating "growing" line plot in Python/Matplotlib


code:
class BiDict(dict):
  """Bidirectional Dictionary - setting 'key' to 'value' also
     sets 'value' to 'key' (so don't use overlapping mappings)
  """

  def __init__(self, *args):
    super(BiDict, self).__init__(*args)

    # After regular dict initialization, loop over any items
    # and add their reverse.  Note that we can't use any of the
    # iter* methods here since we're adding items in the body
    # of the loop.
    for key in self.keys():
      super(BiDict, self).__setitem__(self[key], key);

  def __setitem__(self, key, val):
    # If the key has an old value, delete its reverse
    if key in self:
      super(BiDict, self).__delitem__(self[key])

    # Then add both forward and reverse for the new value
    super(BiDict, self).__setitem__(key, val);
    super(BiDict, self).__setitem__(val, key);

  def __delitem__(self, key):
    # delete both directions
    if key in self:
      super(BiDict, self).__delitem__(self[key]);
      super(BiDict, self).__delitem__(key);

rawDescription: Python dealing with reverse lookup

description: Python dealing with reverse lookup


code:
import ast
df = pd.read_clipboard(header=None, quotechar='"', sep=',',
                  converters={1:ast.literal_eval})
df

rawDescription: Reading csv containing a list in Pandas

description: Reading csv containing a list in Pandas


rawDescription: How do you merge the master branch into a feature branch with GitPython?

description: Merge the master branch into a feature branch with GitPython


code:
class AttrDict(dict):
    __slots__ = () # we don't need a __dict__

    def __getattr__(self, name): # wrapper around dict.__setitem__, with an exception fix
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name) from None # raise the right type of exception

    def __delattr__(self, name): # wrapper around dict.__delitem__
        try:
            del self[name]
        except KeyError:
            raise AttributeError(name) from None # change exception type here too

    __setattr__ = dict.__setitem__ # no special exception rewriting needed here

rawDescription: Passing a dict-like Object through multiprocessing.Queue Makes it Unable to be Modified by Attribute


rawDescription: Whence the 27 digits of extra precision in `decimal.Decimal(1.0/3.0)`?


code: re1_matches and re2_matches

rawDescription: Merge several regular expressions into one RE


code:
import pygame, sys, time, random
from pygame.locals import *

pygame.init()

fpsClock = pygame.time.Clock()

playSurface = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Happy Birthday Mum')
redColour = pygame.Color(255, 0, 0)
blackColour = pygame.Color(0, 0, 0)
whiteColour = pygame.Color(255, 255, 255)
greyColour = pygame.Color(150, 150, 150)

game_is_running = True
while game_is_running:
        snakePosition = [100,100]
        snakeSegments = [[100,100],[80,100],[60,100]]
        raspberryPosition = [300,300]
        raspberrySpawned = 1
        direction = 'right'
        changeDirection = direction
        diff = 30

        snake_is_alive = True
        while snake_is_alive:
            for event in pygame.event.get():
                if event.type == QUIT:
                    pygame.quit()
                elif event.type == KEYDOWN:
                    if event.key == K_RIGHT or event.key == ord('d'):
                        changeDirection = 'right'
                    if event.key == K_LEFT or event.key == ord('a'):
                        changeDirection = 'left'
                    if event.key == K_UP or event.key == ord('w'):
                        changeDirection = 'up'
                    if event.key == K_DOWN or event.key == ord('s'):
                        changeDirection = 'down'
                    if event.key == K_ESCAPE:
                        pygame.event.post(pygame.event.Event(QUIT))
                    if event.key == K_1:
                        diff = 10
                    if event.key == K_2:
                        diff = 20
                    if event.key == K_3:
                        diff = 30
                    if event.key == K_4:
                        diff = 40
                    if event.key == K_5:
                        diff = 50
                    if event.key == K_r:
                        snake_is_alive = False

            if changeDirection == 'right' and not direction == 'left':
                direction = changeDirection
            if changeDirection == 'left' and not direction == 'right':
                direction = changeDirection
            if changeDirection == 'up' and not direction == 'down':
                direction = changeDirection
            if changeDirection == 'down' and not direction == 'up':
                direction = changeDirection
            if direction == 'right':
                snakePosition[0] += 20
            if direction == 'left':
                snakePosition[0] -= 20
            if direction == 'up':
                snakePosition[1] -= 20
            if direction == 'down':
                snakePosition[1] += 20
            snakeSegments.insert(0,list(snakePosition))
            if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]:
                raspberrySpawned = 0
            else:
                snakeSegments.pop()
            if raspberrySpawned == 0:
                x = random.randrange(1,32)
                y = random.randrange(1,24)
                raspberryPosition = [int(x*20),int(y*20)]
            raspberrySpawned = 1
            playSurface.fill(blackColour)
            for position in snakeSegments:
                pygame.draw.rect(playSurface,whiteColour,Rect(position[0], position[1], 20, 20))
            pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1], 20, 20))
            pygame.display.flip()
            if snakePosition[0] > 620 or snakePosition[0] < 0:
                snake_is_alive = False
            if snakePosition[1] > 460 or snakePosition[1] < 0:
                snake_is_alive = False
            for snakeBody in snakeSegments[1:]:
                if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]:
                    snake_is_alive = False
            fpsClock.tick(diff)

        gameOverFont = pygame.font.Font('freesansbold.ttf', 72)
        gameOverSurf = gameOverFont.render('Game Over', True, greyColour)
        gameOverRect = gameOverSurf.get_rect()
        gameOverRect.midtop = (320, 10)
        playSurface.blit(gameOverSurf, gameOverRect)
        pygame.display.flip()
        time.sleep(5)

rawDescription: Pygame restart function

description: Pygame restart function


code: lv_temp4 = [i.id for i in LV.objects.all().order_by('id')]

rawDescription: Index, for loops and making things look cleaner


code:
with open('my100GBfile.txt') as corpus:
    for line in corpus:
        sequence = preprocess(line)
        extract_n_grams(sequence)

rawDescription: extracting n grams from huge text

description: Extracting n grams from huge text


code:
import pickle
with open("my_matrices.pkl", "wb") as f:
   pickle.dump(my_matrix_object, f)

rawDescription: Trying to write and read two matrices in text file


code:
for img in img_names:
    screen.blit(all_imgs[img], (desiredx, desiredy))

rawDescription: Moving Gif in Pygame?

description: Moving Gif in Pygame


code: [f(i) for i in iterator if conditional(i)]

rawDescription: What is a set? And what does "a for a in i" do?


code:
class Player(object):
    def __init__(self, name, running_speed, passing_acc, shooting_acc):
        self.name = name
        self.running_speed = running_speed
        self.passing_acc = passing_acc
        self.shooting_acc = shooting_acc

rawDescription: Menu Interface Player Records

description: Menu Interface Player Records


code:
if x <= 0 or x > 9:
    continue

rawDescription: How to use the count() method on a list excluding some items

description: Use the count() method on a list excluding some items


rawDescription: What is the most effective way to incremente a large number of values in Python?


rawDescription: How can I load a csv file and store its contents into an (numpy) array in python?

description: Load a csv file and store its contents into an (numpy) array in python


code:
from subprocess import Popen, PIPE
print("""What did you want to run? (pick a number)
        (1) Ping
        (2) Traceroute""")

runit = raw_input("> ")

print ("Enter a hostname to check")
host = raw_input("> ") #accept input for hostname

if runit == "1":
    p  = Popen("cmd /c ping " + host, shell=True, stdout=PIPE)
    with open("ping.txt","w") as f:
        for line in iter(p.stdout.readline,""):
            print(line)
            f.write(line)

elif runit == "2":
     p = Popen("cmd /c tracert " + host, shell=True, stdout=PIPE)
     with open("trace.txt", "w") as f:
         for line in iter(p.stdout.readline, ""):
             print(line)
             f.write(line)

rawDescription: How do I write a command from Command Prompt to a file using Python?

description: Write a command from Command Prompt to a file using Python


code: d = dict(d)

rawDescription: How to create a dictionary of lists from two columns in a dataframe

description: Create a dictionary of lists from two columns in a dataframe


code:
for inp in user_input:
    n = len(inp)
    ...
    print(inp, "goes to position", i)

rawDescription: Assigning the inputs, with respect to its len()


rawDescription: Byte Array in Python

description: Byte Array in Python


code:
class MinimumBalanceAccount(BankAccount):
    def __init__(self, minimum_balance):
        super().__init__()

rawDescription: Why dual __init__ in python?

description: Why dual __init__ in python


code:
from collections import OrderedDict

d = {
    'spam': 'tasty',
    'subtitle': 'A Subtitle',
    'title': 'Test Title',
    'foo': 'bar',
}

key_order = ('title', 'subtitle')
od = OrderedDict((k, d[k]) for k in key_order)
od.update(d)

rawDescription: Python OrderedDict: sort by tuple order?

description: Python OrderedDict: sort by tuple order


code:
a = np.array([1, 2, 3])
a
a.transpose()
a.dot(a.transpose())

rawDescription: Python: Differentiating between row and column vectors


code:
@app.route('/categories/<string:category_type>', methods=['GET'])
def categories(category_type):
    if category_type.lower() not in ('category', 'subcagory'):
        flask.abort(404)

    if request.method == 'GET':
        results = Categories.query.all()

        json_results = set()
        for result in results:
            d = {'Category': getattr(result, category_type.lower())}
            json_results.add(d)

        return jsonify(items=json_results)

rawDescription: Flask API with variable output defined by url


code:
a = [1, 2, 3]
def foo():
    a[:] = [5]  # modifies global 'a'

rawDescription: What does list[:] = process_list(list) does in python?


code:
tops = [925, 946, 966, 995, 996, 1015, 1035]
threshold = 2
reduce(lambda x, y: x + [y] if len(x) == 0 or y > x[-1] + threshold else x, sorted(tops), [])

rawDescription: How do I remove almost-duplicate integers from list?

description: Remove almost-duplicate integers from list


code: button1.config( height = WHATEVER, width = WHATEVER2 )

rawDescription: How do I change button size in Python?

description: Change button size in Python


code:
regex = re.compile(r'\+CMTI: "SM",(\d+)')
regex.match('+CMTI: "SM",0').group(1)

rawDescription: Parsing a message notification index in python using regular expressions


code:
fig, ax = plt.subplots()
im = ax.imshow(np.random.random((10,10)))
cb = fig.colorbar(im)
cb.formatter.set_powerlimits((0, 0))
cb.ax.yaxis.set_offset_position('left')
cb.update_ticks()
plt.show()

rawDescription: Matplotlib Colorbar scientific notation offset


code:
def analyse(expression):
    # Find all used symbols
    symbols = set(re.findall(r"\b[A-Z]\b", expression))
    # Find all combinations of symbols and values
    mappings = (dict(zip(symbols, values)) for values in itertools.product([False, True], repeat=len(symbols)))
    # Select combinations that make the whole expression true
    solutions = [sorted(name for name in mapping if mapping[name]) for mapping in mappings if eval(expression, None, mapping)]
    # Filter out redundant solutions
    return sorted(s1 for s1 in solutions if not any(set(s1) > set(s2) for s2 in solutions))

rawDescription: get elements in "AND" in logic string with Python

description: Get elements in "AND" in logic string with Python


code: notebook["worksheets"]["cells"]

rawDescription: How do I get more than one worksheet in an ipython notebook?

description: Get more than one worksheet in an ipython notebook


rawDescription: A function that would give the middle letters


code: y = list(set([e for e in x if e in range(1, 101)]))

rawDescription: Remove values from list leaving only unique values


code:
df.loc[df.b == True, 'a'] *= x
df.loc[df.b == False, 'a'] *= y

rawDescription: pandas: multiply column depending on other column

description: Pandas: multiply column depending on other column


code:
def rdpcap_and_close(filename, count=-1):
    """Read a pcap file, return a packet list and close the file
count: read only <count> packets"""
    pcap_reader = PcapReader(filename)
    packets = pcap_reader.read_all(count=count)
    pcap_reader.close()
    return packets

rawDescription: Close rdpcap function - Scapy

description: Close rdpcap function - Scapy


rawDescription: Pandas reindexing data frame issue

description: Pandas reindexing data frame issue


code:
#!/usr/bin/env python3
#http://stackoverflow.com/questions/26335059/converting-python-sparse-matrix-dict-to-scipy-sparse-matrix

from scipy.sparse import csr_matrix, coo_matrix

def convert(term_dict):
    ''' Convert a dictionary with elements of form ('d1', 't1'): 12 to a CSR type matrix.
    The element ('d1', 't1'): 12 becomes entry (0, 0) = 12.
    * Conversion from 1-indexed to 0-indexed.
    * d is row
    * t is column.
    '''
    # Create the appropriate format for the COO format.
    data = []
    row = []
    col = []
    for k, v in term_dict.items():
        r = int(k[0][1:])
        c = int(k[1][1:])
        data.append(v)
        row.append(r-1)
        col.append(c-1)
    # Create the COO-matrix
    coo = coo_matrix((data,(row,col)))
    # Let Scipy convert COO to CSR format and return
    return csr_matrix(coo)

if __name__=='__main__':
    doc_term_dict = { ('d1','t1'): 12,             \
                ('d2','t3'): 10,             \
                ('d3','t2'):  5              \
                }
    print(convert(doc_term_dict))

rawDescription: Converting python sparse matrix dict to scipy sparse matrix


code: states_dictionary.AK[0] //which is liza

rawDescription: are there dictionaries in javascript like python?

description: Are there dictionaries in javascript like python


code: bools[e[0]:e[1]+2] = False

rawDescription: Insert repeated value across list slices


rawDescription: How to tree-search an html file tag with no specific type

description: Tree-search an html file tag with no specific type


code:
import csv
import collections
from operator import itemgetter

...

if sort_int == 1:
    with open(path) as f:
        reader = csv.reader(f)
        for name, score in sorted(reader):
            print(name,score)

elif sort_int == 2:
    with open(path) as f:
        entries = sorted(csv.reader(f),
                         key=itemgetter(1),
                         reverse=True)
        for name,score in entries:
            print(name,score)

elif sort_int == 3:
    with open(path) as f:
        entries = collections.Counter()
        total_scores = collections.Counter()
        for name,score in csv.reader(f):
            score = int(score)
            total_scores[name] += score
            entries[name] += 1

        for name in sorted(entries):
            ave_score = total_scores[name] / entries[name]
            print(name,ave_score)

rawDescription: Sorting data from a csv alphabetically, highest to lowest and average


code:
def contains(a_polygon, a_point):
    return a_polygon.contains(a_point)
contains_vectorized = np.vectorize(contains)

rawDescription: Apply a pairwise shapely function on two numpy arrays of shapely objects


code:
numpy.random.seed(1)
m = numpy.random.randn(5.,5.)
m
m[~ ((m < 0.5) | (m > 0.8))].min()

rawDescription: numpy argmin elegant solution required.

description: Numpy argmin elegant solution required.


rawDescription: Python: Sorting a list by class objects

description: Python: Sorting a list by class objects


code:
def calculate(b, c, d):
    return 12 * b + 20 * c + 30 * d

rawDescription: Static lists in Python for arithmetic manipulations


code:
def age_arr():
    age_A = []
    for _i in range(100):
        age_A.append(42)

    for _i in range(100000):
        rand_ind_1 = randint(0,99)
        rand_ind_2 = randint(0,99)

        val_1 = age_A[rand_ind_1] #Subtract from
        val_2 = age_A[rand_ind_2] #Add to

        if val_1 == 23 or val_2 == 72:
            age_A[rand_ind_1] += 1
            age_A[rand_ind_2] -= 1

        age_A[rand_ind_1] -= 1
        age_A[rand_ind_2] += 1
    sum = 0
    for val in age_A:
        sum += val
    print(age_A)
    print('Average: ' + str(sum/100))

rawDescription: How to generate random int around specific mean?

description: Generate random int around specific mean


code: form = MyModelForm (instance=someinst)

rawDescription: How do I make a Django ModelForm menu item selected by default?

description: Make a Django ModelForm menu item selected by default


rawDescription: Python - finding next and previous values in list with different criteria


code:
import numpy as np
import pandas as pd
Timestamp = pd.Timestamp
nan = np.nan
NaT = pd.NaT
df1 = pd.DataFrame({
    'col1': list('ac'),
    'col2': ['b', nan],
    'date': (Timestamp('2014-08-14'), NaT)
    })

df1['col2'] = df1['col2'].fillna('')
df1['date'] = [d.strftime('%Y-%m-%d') if not pd.isnull(d) else '' for d in df1['date']]

print(df1)

rawDescription: Remove dtype datetime NaT

description: Remove dtype datetime NaT


code:
L = [0,1,2,3,4]
result = [L[i:j] for i in xrange(len(L)) for j in xrange(i + 1, len(L) + 1)]
pprint.pprint(result)

rawDescription: Get all combinations of neighbour elements in list


rawDescription: Python web app with background worker thread


code:
def sum_of_longest_branch(tree):
    """
    Parses a tree and returns a tuple containing (depth, sum) of deepest branch.
    """
    # stop conditions on leave nodes (can be single [node] or None)
    if 1 == len(tree):
        return 1, tree[0]
    elif None == tree:
        return 1, 0
    # splitting the branches
    else:
        # calling the function recursively on all branches branching from current node
        branches_sums = [sum_of_longest_branch(branch) for branch in tree[1:]]
        # extracting the currently deepest branch
        branch, sum = sorted(branches_sums, reverse=True)[0]
        # add own node value and one depth before returning
        return branch + 1, sum + tree[0]

rawDescription: Finding the maximum height of a tree and returning the sum of that path


code:
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
import inject

class EntityManager():

  session = None

  @inject.params(config=Configuration)
  def __init__(self, config):
    conf = config['persistence']
    uri = conf['driver'] + "://" + conf['username'] + ":@" + conf['host'] + "/" + conf['database']

    engine = create_engine(uri, echo=conf['debug'])

    Session = sessionmaker(bind=engine)
    self.session = Session()

  def query(self, entity_type):
    return self.session.query(entity_type)

  def add(self, entity):
    return self.session.add(entity)

  def flush(self):
    return self.session.flush()

  def commit(self):
    return self.session.commit()

class Configuration:
  def __init__(self, params):
    f = open(os.environ.get('PYTHONPATH') + '/conf/config.yml')
    self.configMap = yaml.safe_load(f)
    f.close()

  def __getitem__(self, key: str):
    return self.configMap[key]

class Result(Base):
  __tablename__ = 'result'

  id = Column(Integer, primary_key=True)
  job_id = Column(String(255))
  level = Column(Integer)
  result = Column(Integer)

  def __repr__(self):
    return "<Result (job='%s', level='%s', result='%s')>" % (self.job_id, str(self.level), str(self.result))

rawDescription: Celery: access all previous results in a chain


code:
from argparse import ArgumentParser
parser = ArgumentParser()
s = 'Fri May 15 11:22:54 EDT 2015'
parser.parse(s)

rawDescription: not getting date time from correctly formatted string

description: Not getting date time from correctly formatted string


code:
import subprocess
import shlex
cmd = 'foo -a -b --bar baz'
shlex.split(cmd)
subprocess.list2cmdline(['foo', '-a', '-b', '--bar', 'baz'])

rawDescription: output the command line called by subprocess?

description: Output the command line called by subprocess


code: np.extract(a != 1, a)

rawDescription: Remove specific values from dataframe

description: Remove specific values from dataframe


code:
def test():
    mock = Mock()
    mock_role_role = function_returning_mock_role_role(mock)
    assert mock_role_role == mock.role.role

rawDescription: How to write clean python mock code with nested property mock

description: Write clean python mock code with nested property mock


code:
@event.listens_for(class_.photo, 'set')
def set_photo(target, value, old_value, initiator):
    value.photoable_type = type

rawDescription: Polymorphic belongs-to relationships in SQLAlchemy?


code:
import sys
import csv

def read_csv(filepath):
    list = []
    with open(self.filepath, "r") as table:
        reader = csv.reader(table, delimiter="\t")
        for line in reader:
            list.append[line]

if __name__ == '__main__':
    read_csv(sys.argv[1])

rawDescription: Call Python class methods from the command line


code:
df['lastPeriod'] = g['value'].apply(lambda s: s.shift())
df

rawDescription: Pandas data frame: adding columns based on previous time periods


code:
a[rows,cols] = np.array([33,77])
a

rawDescription: how to modify a 2D numpy array at specific locations without a loop?

description: Modify a 2D numpy array at specific locations without a loop


code:
yield keys[i:i + size]                          # list of keys
yield [d[key] for key in keys[i:i + size]]      # list of values
yield {key: d[key] for key in keys[i:i + size]} # dictionary

rawDescription: Random groups of elements of a dictionary


code: df

rawDescription: groupby common values in two columns

description: Groupby common values in two columns


code:
distance = lambda i: len(word) / 2 - int(math.fabs((len(word) / 2) - i))
for i, character in enumerate(word):
    print(distance(i) * " ", character, sep='')

rawDescription: I cannot figure out how to manipulate strings in a couple different ways


code:
import csv
from operator import itemgetter

fileLineList = []
averageScoreDict = {} # Creating an empty dictionary here.

with open('Class1scores.csv', newline='') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        fileLineList.append(row)

for row in fileLineList:
    highest = 0
    lowest = 0
    total = 0
    average = 0
    for column in row:
        if column.isdigit():
            column = int(column)
            if column > highest:
                highest = column
            if column < lowest or lowest == 0:
                lowest = column
            total += column
    average = total / 3
    # Here is where we put the emtpy dictinary created earlier to good use.
    # We assign the key, in this case the contents of the first column of
    # the CSV, to the list of values.
    # For the first line of the file, the Key would be 'John'.
    # We are assigning a list to John which is 3 integers:
    #   highest, lowest and average (which is a float we round)
    averageScoreDict[row[0]] = [highest, lowest, round(average)]

averageScoreList = []

# Here we "unpack" the dictionary we have created and create a list of Keys.
# which are the names and single value we want, in this case the average.
for key, value in averageScoreDict.items():
    averageScoreList.append([key, value[2]])

# Sorting the list using the value instead of the name.
averageScoreList.sort(key=itemgetter(1), reverse=True)

print('\nStudents Average Scores From Highest to Lowest\n')
print(averageScoreList)

rawDescription: Formatting data in a CSV file (calculating average) in python


code:
from scipy.sparse import csr_matrix

def to_sparse_pivot(df, id, item, count):
    id_u = list(df[id].unique())
    item_u = list(np.sort(df[item].unique()))
    data = df[count].tolist()
    row = df[id].astype('category', categories=id_u).cat.codes
    col = df[item].astype('category', categories=item_u).cat.codes
    return csr_matrix((data, (row, col)), shape=(len(id_u), len(item_u)))

rawDescription: How to create dummy variable and then aggregate using scikit-learn?

description: Create dummy variable and then aggregate using scikit-learn


rawDescription: Convert AWK regex to Python script

description: Convert AWK regex to Python script


code:
from operator import itemgetter

unique_by_second_element = unique_by_key(a, key=itemgetter(1))

rawDescription: Making a sequence of tuples unique by a specific element


code:
fname = 'qdata.txt'
with open(fname) as f:
    words = set(f.read().split())
print(words, len(words))

rawDescription: open .txt file and place every word within a dictionary

description: Open .txt file and place every word within a dictionary


code:
numbers = ' '.join(subpieces[-2:])
numbers

rawDescription: strip text to create list and compare 2 similar lists

description: Strip text to create list and compare 2 similar lists


code:
result = []
for string in (text1, text2, text3):
    if not re.search(r'[/,@]{2,}', string):
        result.append(string)

rawDescription: Python regex: not more than one special symbol in a row


code:
class ValueErrorException (Exception):

    pass

class BankAccount:

    accounts = 0

    def __init__ (self, bal = 0.0):
        BankAccount.accounts += 1
        self.accountNumber = str(BankAccount.accounts)
        self.accountBalance = bal

    def withdraw(self, amount):
        if self.accountBalance - amount < 0:
            raise ValueErrorException("Illegal balance")
        else:
            self.accountBalance -= amount

    def deposit (self, amount):
        self.accountBalance += amount

    def balance(self):
        return self.accountBalance

rawDescription: Why does this class program not return the balance?


code:
def input_func(): #defines the input_function function
    ...
    return {
        'name': name,
        'people': people,
        'ingredients': ingredients,
        'quantity': quantity,
        'units': units,
        'num_ing': num_ing,
        }

rawDescription: Python Programming - input/output

description: Python Programming - input/output


code:
import matplotlib.pyplot as plt
from skimage.color import rgb2gray
from skimage import data
img = data.astronaut()
img_gray = rgb2gray(img)

plt.imshow(img_gray, cmap='gray')
plt.show()

rawDescription: rgb2gray not working, creating rainbow image

description: Rgb2gray not working, creating rainbow image


code:
# Plot circles
pylab.plot(x, y)
# Plot lines (first and last x and y of each theta)
pylab.plot(np.vstack((x[:,0], x[:, -1])),
           np.vstack((y[:,0], y[:, -1])))

rawDescription: Creating a 2d mesh in python

description: Creating a 2d mesh in python


code:
class Animal(object):
    def __new__(cls, *args, **kwargs):
        if not (args or kwargs) and not hasattr(cls, 'default'):
            cls.default = object.__new__(cls)
            return cls.default
        else:
            return object.__new__(cls)

rawDescription: Create current class default instance in its base class


rawDescription: How can I apply a namedtuple onto a function?

description: Apply a namedtuple onto a function


rawDescription: Convert data based on multiple dictionaries


code:
renderer.selection_glyph = Circle(fill_color='firebrick', line_color=None)
renderer.nonselection_glyph = Circle(fill_color='#1f77b4', fill_alpha=0.1, line_color=None)

rawDescription: How to set properties of selected/unselected glyphs in bokeh

description: Set properties of selected/unselected glyphs in bokeh


code: [heapq.nsmallest(x,2)[1] for x in list_of_lists]

rawDescription: Is it possible to have multiple statements in a python lambda expression?


code:
class Foo():
    r = randint(1, 7)
    def func(self):
        return  Foo.r

rawDescription: Using Random Once in a While loop

description: Using Random Once in a While loop


code: customer_codes = [customer['customer_code'] for customer in data['customers']]

rawDescription: Python and Vend JSON Queries

description: Python and Vend JSON Queries


code: pdf_contents = open(os.path.join(os.path.dirname(__file__), 'yourpdf.pdf')).read()

rawDescription: Attaching a PDF to an email in Appengine (Python)


rawDescription: How to evaluate an expression-tree in sympy?

description: Evaluate an expression-tree in sympy


rawDescription: Create multi-level index pandas dataframe from delimited string column


code:
from osgeo import osr, gdal

# get the existing coordinate system
ds = gdal.Open('path/to/file')
old_cs= osr.SpatialReference()
old_cs.ImportFromWkt(ds.GetProjectionRef())

# create the new coordinate system
wgs84_wkt = """
GEOGCS["WGS 84",
    DATUM["WGS_1984",
        SPHEROID["WGS 84",6378137,298.257223563,
            AUTHORITY["EPSG","7030"]],
        AUTHORITY["EPSG","6326"]],
    PRIMEM["Greenwich",0,
        AUTHORITY["EPSG","8901"]],
    UNIT["degree",0.01745329251994328,
        AUTHORITY["EPSG","9122"]],
    AUTHORITY["EPSG","4326"]]"""
new_cs = osr.SpatialReference()
new_cs .ImportFromWkt(wgs84_wkt)

# create a transform object to convert between coordinate systems
transform = osr.CoordinateTransformation(old_cs,new_cs)

#get the point to transform, pixel (0,0) in this case
width = ds.RasterXSize
height = ds.RasterYSize
gt = ds.GetGeoTransform()
minx = gt[0]
miny = gt[3] + width*gt[4] + height*gt[5]

#get the coordinates in lat long
latlong = transform.TransformPoint(x,y)

rawDescription: Obtain Latitude and Longitude from a GeoTIFF File


code:
d
map(sum, zip(*d.values()))

rawDescription: Sum of column elements of dictionary values made of lists in Python


code: print("TOGGLING OUTPUT PIN")

rawDescription: Execute script on Snort alert

description: Execute script on Snort alert


rawDescription: Fast way to transpose np.arrays and write them to file


code:
def separate(p, L):
    if L == []:
        return [], []

    l1, l2 = separate(p, L[1:])

    item = L[0]

    if p(item):
        l1.append(item)
    else:
        l2.append(item)
    return l1, l2

rawDescription: How does a recursive function returns a tuple of lists?


code:
from collections import Counter
tokens = [{"Value": "Blah", "SO": 0}, {"Value": "zoom", "SO": 5}, {"Value": "Blah", "SO": 2}, {"Value": "Blah", "SO": 3}]
Counter(tok['Value'] for tok in tokens)

rawDescription: Group/Count list of dictionaries based on value


code: parser.add_argument('-ipv4', '--ipv4', action='store_true', dest='ipv4')

rawDescription: Python parse options without any argument using optparse module


code: curr.executemany('UPDATE test SET myCol= ?', ((val,) for val in myList))

rawDescription: How to update entire column with values in list using Sqlite3

description: Update entire column with values in list using Sqlite3


code:
class Dog:
    def noise(self, x):
        print("bark! " + x)
    def sleep(self):
        print("sleeping on floor")

class Cat:
    def noise(self, x):
        print("meow! " + x)
    def sleep(self):
        print("sleeping on keyboard")

a = Dog()
a.noise("hungry")
a.sleep()

a = Cat()
a.noise("hungry")
a.sleep()

rawDescription: substitute of function pointers in python

description: Substitute of function pointers in python


code: wedges = [patch for patch in ax.patches if isinstance(patch, matplotlib.patches.Wedge)]

rawDescription: Changing line properties in matplotlib pie chart


code:
df = pd.read_csv('data', sep=';',
                 names=['time','flare','praia','spot','ruido'], header=1,
                 index_col=0)
df.index = pd.TimedeltaIndex(df.index)

rawDescription: Pandas: read_csv with only HH:MM:SS in the index


code: ismember = [row==searchKey for row in x.tolist()]

rawDescription: check if numpy array is subset of another array

description: Check if numpy array is subset of another array


code:
def viewport_set(x, y=None):
    if y is None:
        # assume x is a sequence of two coordinates instead
        x, y = x

rawDescription: Duck Typing and acceptance of tuples or integers in Python 3


code:
import csv

class PseudoFile(object):
    # http://stackoverflow.com/a/8712426/190597
    def write(self, string):
        return string
writer = csv.writer(PseudoFile())

rawDescription: Protect commas on consecutive string.join() and string.split()


code:
class MyClass():
   @staticmethod
   def my_func():
       return 'foobar'
   class_variable = my_func.__func__()

MyClass.class_variable
MyClass.my_func()

rawDescription: Assign Python class variable with a method of that class


code: allNA = frame[frame.T.isnull().all()]

rawDescription: pandas dataframe: index is DatetimeIndex and 4 columns. Some NaN

description: Pandas dataframe: index is DatetimeIndex and 4 columns. Some NaN


code:
action_group = gtk.ActionGroup("ExamplePyPluginActions")
action_group.add_action_with_accel(action, "<control>r")

rawDescription: How to add keyboard shortcuts / accelerator keys for a menu item created by a Gedit plugin

description: Add keyboard shortcuts / accelerator keys for a menu item created by a Gedit plugin


code:
# file: main.py
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord

def chunks(l, n):
    """Yield successive n-sized chunks from l."""
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

if __name__ == '__main__':
    handle = open('long.fasta', 'r')
    records = list(SeqIO.parse(handle, "fasta"))
    record = records[0]

    for pos, chunk in enumerate(chunks(record.seq.tostring(), 1000)):
        chunk_record = SeqRecord(Seq(
            chunk, record.seq.alphabet),
            id=record.id, name=record.name,
            description=record.description)
        outfile = "group_%d.fasta" % pos
        SeqIO.write(chunk_record, open(outfile, 'w'), "fasta")

rawDescription: Biopython Large Sequence splitting

description: Biopython Large Sequence splitting


script: doc['location'].distanceInMiles(lat, lon) < doc['distance'].value

rawDescription: ElasticSearch GeoDistance Query

description: ElasticSearch GeoDistance Query


code: idx = pd.date_range(df.date.min(), df.date.max() + dt.timedelta(days=1), freq='H')

rawDescription: reindex multiindex pandas dataframe

description: Reindex multiindex pandas dataframe


code:
Xs = radius * np.outer(np.cos(latitudes), np.sin(longitudes))
Ys = radius * np.outer(np.sin(latitudes), np.sin(longitudes))
Zs = radius * np.outer(np.ones(latitudes.size), np.cos(longitudes))

rawDescription: Matplotlib plot_surface spurious faces

description: Matplotlib plot_surface spurious faces


code:
class MyColors:
    def __init__(self):
        self._colors = {'yellow': 1, 'red': 2, 'blue': 3}
    def __getitem__(self, name):
        return self._colors.get(name, 100)

colors = MyColors()
colors['yellow']   # -> 1
colors['brown']    # -> 100

rawDescription: What are the differences amongst Python's "__get*__" and "_del*__" methods?


rawDescription: selecting edges based on source/target in igraph

description: Selecting edges based on source/target in igraph


code:
# test_real.py
import x

rawDescription: How can I replace a module without importing it?

description: Replace a module without importing it


code:
class NotPrintable(object):
    def __init__(self, text):
        """ Instanciation method """
        self.text = text

class Printable(object):
    def __init__(self, text):
        """ Instanciation method """
        self.text = text

    def __repr__(self):
        """ Text representation of the object called by print"""
        return "A printable object whose the value is : {0}".format(self.text)

if __name__ == "__main__":
    print( NotPrintable("StackOverFlowTest") )
    print( Printable("StackOverFlowTest") )

rawDescription: Python to find out, from coordinates of non- habitable areas to location/address


code:
W_EPOCH = datetime(1601, 1, 1)
(datetime.fromtimestamp(tstamp) - W_EPOCH).total_seconds()

rawDescription: Conversion of unix epoch time to windows epoch time in python


code:
def software_list(request):

    if request.method == 'GET':
        result = []
        if 'industry' in request.GET and 'industry' is not None:
            formattedq = request.GET
            #QueryDict instance is immutable so we need to make a copy
            formattedq = formattedq.copy()
            formattedq = formattedq.getlist('industry')
            softquery = Q(industries__id__in=[ind for ind in formattedq])
            #debugformattedq = formattedq
            result.append(softquery)

        if 'deployment_model' in request.GET:
            formattedq = request.GET
            #QueryDict instance is immutable so we need to make a copy
            formattedq = formattedq.copy()
            formattedq = formattedq.getlist('deployment_model')
            depquery = Q(deploymentmodels__id__in=[ind for ind in formattedq])
            #debugformattedq = formattedq
            result.append(depquery)

        result = Software.objects.filter(reduce(operator.and_, result))
    else:
        SoftwareSearchForm()
    return render_to_response('software_list.html',
        {
        #'software_list':results,
        'SoftwareSearchForm':SoftwareSearchForm,
        'formattedq':result,
        },
        context_instance = RequestContext(request)
        )

    return render_to_response('software_list.html', {'SoftwareSearchForm':SoftwareSearchForm})

rawDescription: Dynamically constructing a filter from request.GET


code:
class MySpecificTestCase(BaseTestCase):
    def test_something_specific(self):
        self.assertEqual(4, 2 + 2)

rawDescription: python unittest multiple mixins

description: Python unittest multiple mixins


code:
with open('comm.txt', 'r') as code, open('comm_edit.txt', 'w') as out:
    for line in code:
        if not line.startswith('#'):
            out.write(line + '\n')

rawDescription: Python - Delete comments in a Python code


code:
def csvupload(request):
    if request.method == "POST":
       f = request.FILES['csvfile']
       with open("/tmp/csvfile.csv", 'wb+') as destination:
                for chunk in f.chunks():
                    destination.write(chunk)
                destination.close()

rawDescription: django read file for importing details

description: Django read file for importing details


rawDescription: Python - XY array from 2 lists

description: Python - XY array from 2 lists


code:
mdf = pandas.merge(df1,df2,on='number')
mdf

rawDescription: Partial merge in Pandas

description: Partial merge in Pandas


code:
import time
import datetime
dt = datetime.datetime.strptime('2012-02-09', '%Y-%m-%d')
time.mktime(dt.timetuple())

rawDescription: Python timestamp from day, month, year

description: Python timestamp from day, month, year


code:
class A(object):
  def __init__(self):
    self.b = B(self)

class B(object):
  def __init__(self, a):
    self.a = a

a = A()
b = a.b

rawDescription: python classes dependant on eachother, how to init?

description: Python classes dependant on eachother, how to init


rawDescription: convert numpy array to string with delimiter and save to txt file

description: Convert numpy array to string with delimiter and save to txt file


code: c.execute("insert into medicoes values (?,?,?,?,?,?,?)", keys)

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


code:
class Image(models.Model):
    obj = models.ForeignKey(MyModel, related_name='images')
    name = models.CharField(max_length=50)
    image = models.ImageField(upload_to='images')
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created']
        get_latest_by = 'created'

rawDescription: Parent-child relationship efficiency

description: Parent-child relationship efficiency


rawDescription: Find all paths in graph from A to N

description: Find all paths in graph from A to N


code:
import sys

if sys.version_info[0] < 3:
    def py2_compat(cls):
        if hasattr(cls, '__str__'):
            cls.__unicode__ = cls.__str__
            del cls.__str__
            # or optionally supply an str that
            # encodes the output of cls.__unicode__
        return cls
else:
    def py2_compat(cls):
        return cls

@py2_compat
class MyPython3Class(object):
    def __str__(self):
        return u'Here I am!'

rawDescription: define different function for different versions of python

description: Define different function for different versions of python


rawDescription: How can lists in a list be overwritten by new lists in a new list in Python?


code: row = [int(x) for x in row]

rawDescription: Python: increasing array indexes

description: Python: increasing array indexes


code:
class SermonsView(SuperSpecialAwesomeView):
    paginate_by = 2
    queryset = Article.objects.order_by('-publish_date')

rawDescription: Refactoring Django class-based views, clean up 18 repetitive classes.


code:
regex = re.compile(r"""Objective:\s(.*?)Methodology:\s(.*?)
                       Results:\s(.*?)Conclusion:\s(.*)""", re.S|re.X)
obj, method, result, conclusion = regex.match(subject).groups()

rawDescription: Splitting paragraphs using python

description: Splitting paragraphs using python


code:
if f is not None:
    with open(f) as FILE:
        do_something(FILE)
else:
    do_something(f)

rawDescription: Is it possible to have an optional with/as statement in python?


rawDescription: Display Entire Dataset,Python

description: Display Entire Dataset,Python


code:
drops = []
for line in file:
    x, y, z, t = parseFromFile(line)
    drops.append(Droplet(x,y,z,t))

rawDescription: Dynamic object instantiation in Python

description: Dynamic object instantiation in Python


code:
def extendedEuclideanGF2(a, b): # extended euclidean. a,b are values 10110011... in         integer form
    inita, initb = a, b   # if a and b are given as base-10 ints
    x, prevx = 0, 1
    y, prevy = 1, 0
    while b != 0:
        q = a//b
        a, b = b, a%b
        x, prevx = prevx - q*x, x
        y, prevy = prevy - q*y, y
    print("Euclidean  %d * %d + %d * %d = %d" % (inita, prevx, initb, prevy, a))
    i2b = lambda n: int("{0:b}".format(n))  # convert decimal number to a binary value in a decimal number
    return i2b(a), i2b(prevx), i2b(prevy)  # returns gcd of (a,b), and factors s and t

rawDescription: Python multiplicative inverse in GF(2) finite field


code:
def replace_U(uij):
    i1, i2 = uij.indices
    return Derivative([u, v, w][i1], [x, y, z][i2])

rawDescription: Expand index notation equation using sympy


code:
subprocess.Popen([
    r'C:\Program Files (x86)\Notepad++\notepad++.exe',
    r'C:\Python27\Django_Templates\QC\postits.html'
])

rawDescription: Open Text File in Notepad++ using Subprocess.Popen


code:
# start with this
students = Student.objects.filter(sales=current_user)

value = form.cleaned_data.get('nickname', None)
if value is not None:
    students = students.filter(nickname=value)

# etc, etc ...

# end with that
students = students.order_by(register_order, remaining_order, level_order)

rawDescription: django filter when the some of the arguments are null

description: Django filter when the some of the arguments are null


code:
for row in table.find_all('tr'):
    rows.append([1 if val.img else 0 for val in row.find_all('td')])

rawDescription: Evaluate image in html table using Python


code:
import sklearn.feature_extraction.text
from nltk.tokenize import TreebankWordTokenizer

ngram_size = 4
string = ["I really like python, it's pretty awesome."]
vect = sklearn.feature_extraction.text.CountVectorizer(ngram_range=(ngram_size,ngram_size), \
                                                 tokenizer=TreebankWordTokenizer().tokenize)
print('{1}-grams: {0}'.format(vect.get_feature_names(), ngram_size))

rawDescription: How to use sklearn's CountVectorizerand() to get ngrams that include any punctuation as separate tokens?

description: Use sklearn's CountVectorizerand() to get ngrams that include any punctuation as separate tokens


code: func3 = lambda x: x+1

rawDescription: How does this Python Lambda recursion expression work?


code:
class C(A, B):
    def __init__(self):
        pass

rawDescription: How to invoke __repr__ of parent class?

description: Invoke __repr__ of parent class


code:
center_x = (x1 + x2) / 2
center_y = (y1 + y2) / 2

rawDescription: Rotate line around center point given two vertices


code: type(o) is str

rawDescription: What's the canonical way to check for type in python?


code:
Hindi
English

rawDescription: accessing values in subgroups in html code

description: Accessing values in subgroups in html code


code:
import math
def perfect_sq(n):
    return n == int(math.sqrt(n)) ** 2

rawDescription: Python Program on Perfect Squares

description: Python Program on Perfect Squares


code:
data = "data1~|~data2~|~data3~!~data1~|~data2~|~data3~!~data1~|~data2~|~data3~!~data1~|~data2~|~data3~!~"

## parse rows
rows = data.split("~!~")

## Parse Columns
final = [x.split("~|~") for x in rows]
print(final)

rawDescription: places to look for code to convert a data file to X12 format?

description: Places to look for code to convert a data file to X12 format


code: padding = random.choice("x|#_ ")

rawDescription: How to make sure the input is a multiple of 16, and if not add padding to it

description: Make sure the input is a multiple of 16, and if not add padding to it


code: queue.put(("QUIT", None, None))

rawDescription: end daemon processes with multiprocessing module

description: End daemon processes with multiprocessing module


code:
d = {}
d['dict1'] = {}
d['dict1']['innerkey'] = 'value'
d

rawDescription: How do you create nested dict in Python?

description: Create nested dict in Python


code:
from ftplib import FTP
import gzip
import StringIO

ftp = FTP('ftp.ncbi.nlm.nih.gov')
ftp.login() # Username: anonymous password: anonymous@

sio = StringIO.StringIO()
def handle_binary(more_data):
    sio.write(more_data)

resp = ftp.retrbinary("RETR pub/pmc/PMC-ids.csv.gz", callback=handle_binary)
sio.seek(0) # Go back to the start
zippy = gzip.GzipFile(fileobj=sio)

uncompressed = zippy.read()

rawDescription: Read a file in buffer from FTP python

description: Read a file in buffer from FTP python


rawDescription: Extracting a number with dot and comma using regex


code:
def pack_bigint(i):
    b = bytearray()
    while i:
        b.append(i & 0xFF)
        i >>= 8
    return b

rawDescription: How to encode a long in Base64 in Python?

description: Encode a long in Base64 in Python


rawDescription: Subsampling/averaging over a numpy array


rawDescription: How to clear empty keys in a dictionary with subdictionaries

description: Clear empty keys in a dictionary with subdictionaries


rawDescription: REGEX python find previous string

description: REGEX python find previous string


code:
for email in self.emailGenerator:
    self.toField.setText(email)

rawDescription: Python Generator Returns Last Item

description: Python Generator Returns Last Item


code:
def import_module(modname):
    if modname in sys.modules:
        module = sys.modules[modname]
    else:
        filename = find_file_for_module(modname)
        python_code = open(filename).read()
        module = create_module_from_code(python_code)
        sys.modules[modname] = module
    return module

rawDescription: How importing works. Why imported modules not inheriting other imported modules


code:
class Employees():
    def __init__(self):
        self.surname = ''
        self.salary = 0
        self.car_man = []  # if in case you want to add more than one car use a list type or just use string if you plan on keeping this a single value

rawDescription: How do I sort a complex dictionary by a key, which resides deep the dictionary?

description: Sort a complex dictionary by a key, which resides deep the dictionary


rawDescription: PyQT vs PyObjc / Cocoa-Python

description: PyQT vs PyObjc / Cocoa-Python


code:
a = np.array([1, 'x', np.nan])
a

rawDescription: Python numpy nan compare to true in arrays with strings


code: number = random.randint(10000, 99999)

rawDescription: Troubles with my MasterMind game code

description: Troubles with my MasterMind game code


rawDescription: Python: all possible combinations of "dynamic" list


code:
array3 = numpy.array(['cat3','dog3','bird3','cat3'])
my_list3 = ['cat3']

my_arrays = [array1, array2, array3]
my_lists = [my_list1, my_list2, my_list3]
res1 = main1[numpy.logical_and.reduce(tuple(np.in1d(array, lst) for
                                            array, lst in zip(my_arrays, my_lists)))]

rawDescription: Slice numpy array based on x number of other arrays


code: np.indices((4, 4)).reshape(2,-1).T

rawDescription: Creating the Powerset of a set of Vectors in Python?


code:
dest = bytearray(10) # all zero bytes
v = memoryview(dest)
ioObject.readinto(v[3:])
print(repr(dest))

rawDescription: Read into a bytearray at an offset?

description: Read into a bytearray at an offset


code:
with open('myfile.txt') as fin:
    lines = [line.split() for line in fin]

rawDescription: Python : Sort file by arbitrary column, where column contains time values


code:
while True:             # Loop continuously
    inp = raw_input()   # Get the input
    if inp == "":       # If it is a blank line...
        break           # ...break the loop

rawDescription: Python: How to keep repeating a program until a specific input is obtained?


rawDescription: Python Linux dmidecode, how to obtain HW info by Parsing?


code:
from operator import add as _add
# import operator as op  # now use op.add ...

rawDescription: How to make function calls obey lexical scope in Python?

description: Make function calls obey lexical scope in Python


code:
for i, j in enumerate(my_list[:-1]):
    if j[1] == my_list[i+1][1]:
        my_list[i]=["1st duplicate"]
        my_list[i+1 ]= ["2nd duplicate"]
    elif my_list[i] not in [["1st duplicate"],["2nd duplicate"]]:
        my_list[i] = [ "ok"]
[['ok'], ['1st duplicate'], ['2nd duplicate'], ['ok'], ['1st duplicate'], ['2nd duplicate']]

rawDescription: compare current and next item, skip next item if condition is met

description: Compare current and next item, skip next item if condition is met


code:
time_index = data.index.get_level_values(1)
selection = (time_index.day == 2) | (time_index.day == 4)
data[selection]

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

description: Slice a Multindex timeseries dataframe on Pandas


code:
counts['ResponseCount'] = counts.sum(1)
counts

rawDescription: How to take multiple rows and convert some of them into columns

description: Take multiple rows and convert some of them into columns


code:
def encode_basestring(s):
    """Return a JSON representation of a Python string

    """
    def replace(match):
        return ESCAPE_DCT[match.group(0)]
    return '"' + ESCAPE.sub(replace, s) + '"'

rawDescription: Real-world examples of nested functions

description: Real-world examples of nested functions


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('''\

ID:547

Class:foobar

Procedures:lorem ipsum.

dolor sit amet.

...

Description:curabitur at orci posuere.

massa nec fringilla.

''')
mapping = {}
key = None
for item in soup.find_all('p'):
    if item.strong:
        key = item.strong.get_text(strip=True).rstrip(':')
        value = item.strong.next_sibling.strip()
    else:
        value = mapping[key] + ' ' + item.get_text(strip=True)
    mapping[key] = value

from pprint import pprint
pprint(mapping)

rawDescription: Using a nested element's text as a selector in BeautifulSoup


code:
from jsonpath_rw import parse

obj = {
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

keys = ["glossary", "GlossDiv", "GlossList", "GlossEntry", "GlossDef", "para"]
jsonpath_expr = parse(".".join(keys))
print(jsonpath_expr.find(obj)[0].value)

rawDescription: Python function to read JSON file and retrieve the correct value


code:
from nltk.stem import SnowballStemmer

stemmer = SnowballStemmer('english')
cfd = nltk.ConditionalFreqDist(
       (fileid[:4], stemmer.stem(word))
           for fileid in inaugural.fileids()
           for word in inaugural.words(fileid))

A = ['2009', '2005']
B = [stemmer.stem(i) for i in ['freedom', 'war']]
cfd.tabulate(conditions=A, samples=B)

rawDescription: Counting the number of specified words

description: Counting the number of specified words


code:
def is_container_iterable(o):
    return hasattr(o, '__iter__') and not hasattr(o, '__next__')

is_container_iterable(())
is_container_iterable([])
is_container_iterable({})
is_container_iterable(range(5))
is_container_iterable(iter(range(5)))

rawDescription: how to check if an iterable allows more than one pass?

description: Check if an iterable allows more than one pass


code: outputDict = {k: v + (dict2[k][2],) for k, v in dict1.items() if k in dict2}

rawDescription: How to compare 2 dictionary of tuples to generate this list of dictionary?

description: Compare 2 dictionary of tuples to generate this list of dictionary


code:
def f(v):
    x, y = v
    return (x*x) + (x*y*y)

x = 3
y = 3
v = [x, y]
grad = estimate_gradient1(f, v, h=0.00001)
print(grad)

rawDescription: Interpreting Python code for partial derivatives of multi-variable function


code:
if len(get_port.fetchmany()):
    do_something_here()

rawDescription: Checking for empty queryset in Python/MySQLdb


code:
from mayavi import mlab

myfig  = mlab.figure()
myplot = mlab.plot3d([0,1,2],[0,1,2],[0,1,1])
myaxes = mlab.axes()
myaxes.axes.fly_mode = 'none'

mlab.show()

rawDescription: Preventing axis from updating on camera move - mayavi python


rawDescription: Can anybody explain me the numpy.indices()?


rawDescription: python numerically solving an equation with no sign change between the upper and lower bound

description: Python numerically solving an equation with no sign change between the upper and lower bound


code:
mylist = function_generates_a_list()
def newfunc():
   function_to_test(mylist)

rawDescription: How to pass a list as parameter function into a timeit call in Python 3.2.3?

description: Pass a list as parameter function into a timeit call in Python 3.2.3


code: Matrix_files = [ 'file{}.MAT'.format(num) for num in range(1,4) ]

rawDescription: Load many files into one array - Python

description: Load many files into one array - Python


rawDescription: Number divided by 4 by python regex

description: Number divided by 4 by python regex


code:
member_to_votes = defaultdict(dict)
for item in vote_data:
    member_to_votes[item['Name']][item['Voteid']] = item['Vote.Numeric']

rawDescription: Create edgelist from a python dictionary


code:
string = "ATGT"
results = [mutate(string) for _ in range(100)]
for result_string, mutations in results:
    if mutations: # skip writing out unmutated strings
        print(result_string, mutations)

rawDescription: Random DNA mutation Generator

description: Random DNA mutation Generator


code:
def fast_nearest_interp(xi, x, y):
    """Assumes that x is monotonically increasing!!."""
    # Shift x points to centers
    spacing = np.diff(x) / 2
    x = x + np.hstack([spacing, spacing[-1]])
    # Append the last point in y twice for ease of use
    y = np.hstack([y, y[-1]])
    return y[np.searchsorted(x, xi)]

rawDescription: Extraploation with 'nearest' method in Python


code:
from dateutil.parser import parse
parse("31/12/2009").strftime("%Y/%m/%d")

rawDescription: Convert DD/MM/YYYY HH:MM:SS into MySQL TIMESTAMP


code:
states = {}
for disease in seconddict['all_diseases']:
    state = disease.pop('status')
    states.setdefault(state, []).append(disease)

states
from pprint import pprint
output = {'output': [
    {'status': status, 'data': diseases}
    for status, diseases in states.iteritems()]}
pprint(output)

rawDescription: Merging 2 dicts with common elements in python


code:
import win32gui

toplist = []
winlist = []
def enum_callback(hwnd, results):
    winlist.append((hwnd, win32gui.GetWindowText(hwnd)))

win32gui.EnumWindows(enum_callback, toplist)
firefox = [(hwnd, title) for hwnd, title in winlist if 'firefox' in title.lower()]
# just grab the first window that matches
firefox = firefox[0]
# use the window handle to set focus
win32gui.SetForegroundWindow(firefox[0])

rawDescription: How do I take out the focus or minimize a window with Python?

description: Take out the focus or minimize a window with Python


rawDescription: Convert(decode) hex string to ASCII or any other understandable format


code: lst = [getCollection(gram) for gram in range(nGram)]

rawDescription: How to create list of collections.Counter?

description: Create list of collections.Counter


rawDescription: Issue with Decryption Algorithm

description: Issue with Decryption Algorithm


code:
b = io.BytesIO(b'\n\x00\x02\x90\x10\x00\n\x00\x02`\x10\x00\n\x00\x02\x80\x10\x00')
print(unpack(b, '>I'))
print(unpack(b, '>I'))
print(unpack(b, '>I'))
print(unpack(b, '>I'))
print(unpack(b, '>H'))

rawDescription: Idiomatic way to struct.unpack from BytesIO?


code:
a=vec
Matpreferences.append(a)

rawDescription: Having problems with python's random.shuffle


code:
hotpotato = ('%s'.join(param) % (random.choice(opers),
                                 random.choice(opers),
                                 random.choice(opers),
                                 random.choice(opers),
                                 random.choice(opers),
                                 random.choice(opers),
                                 random.choice(opers),
                                 random.choice(opers),
                                 )
         )

rawDescription: Checking for unique output in Python

description: Checking for unique output in Python


code: set(['car', 'statistics'])

rawDescription: Searching for Phrase Keywords in MySQL

description: Searching for Phrase Keywords in MySQL


code:
action = 'default'

if some_condition1:
    action = 'do_something'

if some_condition2:
    action = 'do_other_thing'

...

if action == 'default':
   one_reaction()
elif action == 'do_something':
   other_reaction()
...

rawDescription: Simulating Lisp's :keywords in Python

description: Simulating Lisp's :keywords in Python


rawDescription: How to retrieve elements that have the same foreign key from a list?

description: Retrieve elements that have the same foreign key from a list


code: line = re.sub(r'\W+', '.', line)

rawDescription: replace multiple occurrences of any special character by one in python

description: Replace multiple occurrences of any special character by one in python


rawDescription: Python : Extract HTML content

description: Python : Extract HTML content


rawDescription: is there something like coo_matrix but for sparse vectors?

description: Is there something like coo_matrix but for sparse vectors


rawDescription: Parameterised regular expression in Python


code:
import datetime
df.apply(lambda row: datetime.datetime(row['year'],row['month'],row['day']), axis=1)

rawDescription: Combining rows in DataFrame

description: Combining rows in DataFrame


code:
conditions = dict(word__startswith = 'A', length = 5)
Word.objects.filter(**conditions)

rawDescription: Django DB design to glob words quickly

description: Django DB design to glob words quickly


code:
# dummy example based on matplotlib.pyplot.clabel example:
import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

plt.figure()
CS = plt.contour(X, Y, Z)

for level in CS.collections:
    for kp,path in reversed(list(enumerate(level.get_paths()))):
        # go in reversed order due to deletions!

        # include test for "smallness" of your choice here:
        # I'm using a simple estimation for the diameter based on the
        #    x and y diameter...
        verts = path.vertices # (N,2)-shape array of contour line coordinates
        diameter = np.max(verts.max(axis=0) - verts.min(axis=0))

        if diameter<1: # threshold to be refined for your actual dimensions!
            del(level.get_paths()[kp])  # no remove() for Path objects:(

# this might be necessary on interactive sessions: redraw figure
plt.gcf().canvas.draw()

rawDescription: How to remove/omit smaller contour lines using matplotlib

description: Remove/omit smaller contour lines using matplotlib


code:
class Operation(object):
    def __init__(self, *operands):
        self.operands = operands

@flat
class F(Operation):
    pass

rawDescription: Python: Modifying passed arguments before class instance initialization


code:
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image

im = np.array(Image.open('Mean.png').convert('L'), dtype=float)

# Figure out how 'wide' each range is
leftSpan = inputMax - inputMin
rightSpan = outputMax - outputMin

# Convert the left range into a 0-1 range (float)
imNormalized = (im - inputMin) / leftSpan

# Convert the 0-1 range into a value in the right range.
imTranslated = outputMin + (imScaled * rightSpan)

rawDescription: Convert all array elements to a range in Python


code:
objectivetime = int(objectivetime) # I noticed you didn't do this in your code
delta = None

if timetype == 'Seconds':
    delta = datetime.timedelta(seconds = objectivetime)
else:
    delta = datetime.timedelta(minutes = objectivetime)

objtime = a + delta

rawDescription: How would I format inputted minutes/seconds into datetime.now() format?


rawDescription: Correct usage of \D in python?

description: Correct usage of \D in python


code:
import wx

class GUI(wx.Frame):
    def __init__(self, parent, id, title):
        screenWidth = 500
        screenHeight = 400
        screenSize = (screenWidth,screenHeight)
        wx.Frame.__init__(self, None, id, title, size=screenSize)
        myMenuBar = wx.MenuBar()
        file = wx.Menu()
        quit = wx.MenuItem(file, 101, '&Quit\tCtrl+Q', 'Quit the Application')
        # Adding an image to the quit menu item
        quit.SetBitmap(wx.Image('Exit-icon.png',wx.BITMAP_TYPE_PNG).ConvertToBitmap())
        file.AppendItem(quit)
        file.AppendSeparator()
        myMenuBar.Append(file, '&File')
        self.SetMenuBar(myMenuBar)

if __name__=='__main__':
    app = wx.App(False)
    frame = GUI(parent=None, id=-1, title="Problem Demo-PSS")
    frame.Show()
    app.MainLoop()

rawDescription: 'wxPython' ID icons not showing

description: 'wxPython' ID icons not showing


rawDescription: How to perform two inner joins in a queryset in Django

description: Perform two inner joins in a queryset in Django


code:
def firstMonthInQuarter(month):
    return (month - 1) // 3 * 3 + 1

rawDescription: First month of quarter given month in Python


code:
with open("dataFile.txt") as dataFile:
    items = {}
    for line in dataFile:
        line = map(int, line.split())  #convert the text data to integers
        key, value = line[0], line[1:]
        items[key] = value

rawDescription: Python: List of lists to dictionary

description: Python: List of lists to dictionary


rawDescription: How to read lines without iterating

description: Read lines without iterating


code:
some_number = int(input('input a number: '))
f = open('number.xml', 'r+')
f.write('<?xml version="1.0" ?>\n<number>{}</number>'.format(some_number))

rawDescription: How to save input from python to XML

description: Save input from python to XML


rawDescription: Is there an easy way to add handlers to the logger object?


code:
thread1 = Mythread(1, params)
thread1.start()
return open('redirectpage.html')

rawDescription: Flask: Execute time taking python script and direct the user to another page


code: np.array([A.astype(float) for A in fn(z)])

rawDescription: Can Numpy's frompyfunc() return an image?


code:
prev_weekday(date.today())
prev_weekday(date(2012, 8, 20))

rawDescription: Previous weekday in Python

description: Previous weekday in Python


code:
df = df.sort_index(axis=1)
nummask = slice(None), "Num"
letmask = slice(None), "Let"
df.loc[:, nummask] = df.loc[:, nummask].where((df.loc[:, letmask] != "B").values, 3)
df

rawDescription: Apply similar function to multilevel pandas dataframe


code:
class JSONLoader(bulkloader.Loader):
    def generate_records(self, filename):
        for item in json.load(open(filename)):
            yield item['fields']

rawDescription: GAE load data into datastore without using CSV


code:
def addsevenandaddeight(n):
    return (n+7, n+8)        # the parentheses aren't necessary, they are just for clarity

seven, eight = addsevenandaddeight(0)
print(seven)        # should be 7
print(eight)        # should be 8

rawDescription: What does return do? Nothing is ever returned


rawDescription: Python - Intra similarity

description: Python - Intra similarity


code:
def check_range(fn):
    def wrapper(self, other):
        value = fn(self, other)
        value = max(min(value, self._upperbound), self._lowerbound)
        return type(self)(value, self._lowerbound, self._upperbound)
    return wrapper

class ApplyDecoratorsType(type):
    def __init__(cls, name, bases, attrs):
        for decorator, names in attrs.get('_auto_decorate', ()):
            for name in names:
                fn = attrs.get(name, None)
                if fn is not None:
                    setattr(cls, name, decorator(fn))

class Range(object):
    __metaclass__ = ApplyDecoratorsType
    _auto_decorate = (
            (check_range,
             '__mul__ __div__ __truediv__ __add__ __sub__'.split()),
        )

    def __init__(self, value, lowerbound, upperbound):
        self._lowerbound = lowerbound
        self._upperbound = upperbound
        self.value = value

    def __repr__(self):
        return "<Range: %s>" % (self.value)

    def __mul__(self, other):
        return self.value * other

    def __div__(self, other):
        return self.value / float(other)

    def __truediv__(self, other):
        return self / other

    def __add__(self, other):
        return self.value + other

    def __sub__(self, other):
        return self.value - other

rawDescription: Decorating arithmetic operators | should I be using a metaclass?


code:
lists = get_my_lists() # whatever
itertools.product(*lists)

rawDescription: Algorithm to calculate total unique permutations of set of lists that contain some items


code: [w for w in words_list if sys.argv[1] in w]

rawDescription: Find out the words from a python list which contains permutation of another word


code:
cards_count = Card.query().filter(tags_value==q[0])\
  .filter(tags_value==q[1])\
  .filter(tags_value==q[2]).count()

rawDescription: How does it make query ndb.AND condition more smart


code: np.where(x == np.min(x))

rawDescription: Numpy: get the column and row index of the minimum value of a 2D array


code:
from collections import defaultdict
d = defaultdict(list) # create the dictionary, then populate it.
d.update({"TIM":[['xx', 'yy'], ['aa', 'bb']], "SAM":[['yy', 'cc']]})
d # see its what you wanted.
d["SAM"].append(['tt','uu']) # add more items to SAM
d["KIM"].append(['ii','pp']) # create and add to KIM
d # see its what you wanted.

rawDescription: Python Dictionary Update and Append

description: Python Dictionary Update and Append


code:
def split_list(a_list):
    half = len(a_list)/2
    return a_list[:half], a_list[half:]

A = [1,2,3,4,5,6]
B, C = split_list(A)

rawDescription: Split list into smaller lists

description: Split list into smaller lists


code:
def myFunction2(x):
    outcomes = [1, 2, 3, 4]
    probs = [0.5, 0.75, 0.9, 1.0]
    result = []
    for num in x:
        o = next(o for o, p in zip(outcomes, probs) if num <= p)
        result.append(o)
    return result

rawDescription: List Comprehension Control Flow

description: List Comprehension Control Flow


code:
strings = [ 'abc', 'def', 'xyz' ]
result = [ { 'type': type, 'extra_key1':0, 'extra_key2':'no' } for type in strings ]

rawDescription: Creating a list of dictionaries with default values


code: stories = data.get('stories', [])

rawDescription: Python json get specific story and image


code:
parent.py
import subprocess
import sys

s = "test"
p = subprocess.Popen([sys.executable, "child.py"],
                     stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE)
out, _ = p.communicate(s.encode())
print(out.decode())

rawDescription: Python3 subprocess communicate example

description: Python3 subprocess communicate example


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


code: data = file.readlines()

rawDescription: Modify csv files with Python

description: Modify csv files with Python


code:
def cartesian_exponent(li, e=1):
    return [[x] for x in li] if e == 1 else [[x] + y for x in li for y in cartesian_exponent(li, e=e-1)]

rawDescription: how to permute n elements from list recursively in python?

description: Permute n elements from list recursively in python


rawDescription: Messagebox not working

description: Messagebox not working


code:
import csv

weighed_items = [(item,float(weight)) for item,weight in csv.reader(open('file.csv'))]
picker = WeightedChoice(weighed_items)
print(picker.pick())

rawDescription: How to select an item from a list with known percentages in Python

description: Select an item from a list with known percentages in Python


code:
import package
x = package.ClassName()

rawDescription: Import a module in Python

description: Import a module in Python


code:
class EmailMultiAlternativesWithEncoding(EmailMultiAlternatives):
    def _create_attachment(self, filename, content, mimetype=None):
        """
        Converts the filename, content, mimetype triple into a MIME attachment
        object. Use self.encoding when handling text attachments.
        """
        if mimetype is None:
            mimetype, _ = mimetypes.guess_type(filename)
            if mimetype is None:
                mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
        basetype, subtype = mimetype.split('/', 1)
        if basetype == 'text':
            encoding = self.encoding or settings.DEFAULT_CHARSET
            attachment = SafeMIMEText(smart_str(content,
                settings.DEFAULT_CHARSET), subtype, encoding)
            # original text being replaced above (not last argument)
            # attachment = SafeMIMEText(smart_str(content,
            #     settings.DEFAULT_CHARSET), subtype, settings.DEFAULT_CHARSET)
        else:
            # Encode non-text attachments with base64.
            attachment = MIMEBase(basetype, subtype)
            attachment.set_payload(content)
            Encoders.encode_base64(attachment)
        if filename:
            attachment.add_header('Content-Disposition', 'attachment',
                                  filename=filename)
        return attachment

rawDescription: Django EmailMultiAlternatives and HTML e-mail display in Outlook 2003 on Win2003