code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('file.html')
prettified = soup.prettify(encoding="utf8")

rawDescription: Shortening HTML files

description: Shortening HTML files


rawDescription: Python 2.7 Multiprocessing

description: Python 2.7 Multiprocessing


code:
indices = x[:,:,3] > 50000
x = x[numpy.where(indices)[0]]

rawDescription: Numpy: choose, where, partition or something else?


rawDescription: Plotting pandas timedelta

description: Plotting pandas timedelta


code:
line1
line2
line3
line4
line5
line6
line7

rawDescription: How to trigger something on the close of a loop?

description: Trigger something on the close of a loop


code: l.check(('root', 'INFO', 'a message'))

rawDescription: Writing a unit test for Python logger formatted output


code:
logging.config.dictConfig(MY_DICTIONARY)
vmrunalllogger = logging.getLogger('VMRunAll_Python_Logger')

rawDescription: Which module should contain logging.config.dictConfig(my_dictionary)? What about my_dictionary?


rawDescription: prevent unexpected stdin reads and lock in subprocess

description: Prevent unexpected stdin reads and lock in subprocess


code: os.path.join(settings.DATA_PATH, str(user.pk // partition_size), str(user.pk))

rawDescription: django max folders number per user

description: Django max folders number per user


code:
class Router(models.Model):
    specifications = models.FileField(upload_to='router_specifications')

rawDescription: Uploading files using Django Admin

description: Uploading files using Django Admin


code:
import numpy as np

x = np.random.randn(100, 3)
y = np.array([int(i % 5 == 0) for i in range(100)])

rawDescription: random subsampling of the majority class

description: Random subsampling of the majority class


code:
class MyFrame( wx.Frame ):
    def __init__( self, parent, ID, title ):
        wx.Frame.__init__( self, parent, ID, title, wx.DefaultPosition, wx.Size( 400, 300 ) )

        self.InitUI()
        self.Center()
        self.Show()

    def InitUI(self):

        MPanel = MyPanel(self)
        GridBag = wx.GridBagSizer(2, 2)

        CO = ["RED", "BLUE"]

        for i in range(10):
            X = wx.StaticText(MPanel, size=(50,50), style=wx.ALIGN_CENTER, label="")
            X.SetBackgroundColour(CO[i%2])
            GridBag.Add(X, pos=(i+1, 1), flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=1)

        GridBag.AddGrowableCol(1)
        MPanel.SetSizerAndFit(GridBag)

class MyApp( wx.App ):
    def OnInit( self ):
        self.fr = MyFrame( None, -1, "K" )
        self.fr.Show( True )
        self.SetTopWindow( self.fr )
        return True

app = MyApp( 0 )
app.MainLoop()

rawDescription: How to scroll Panel with GridBagSizer in wxPython

description: Scroll Panel with GridBagSizer in wxPython


code:
df
df.T.dot(df)

rawDescription: finding similarities in rows for a pandas dataframe

description: Finding similarities in rows for a pandas dataframe


rawDescription: I have a list with item in lists and I want to give them a name for each list python


code:
newlist = []
newlist.append(random.choice(c3))

rawDescription: Putting items of a list into another list in Python?


code:
#!/usr/bin/env python
from bs4 import BeautifulSoup # $ pip install beautifulsoup4

with open('input.xml', 'rb') as file:
    soup = BeautifulSoup(file)

elements = soup.find_all("div", class_="header name quantity".split())
print("\n".join("{} {}".format(el['class'], el.get_text()) for el in elements))

rawDescription: Iterate through elements in html tree using BeautifulSoup, and produce an output that maintains the relative position of each element? in Python


code:
# retrieve caller globals
import sys
caller_globals = sys._getframe(1).f_globals

rawDescription: How to create cross-module, on-thy-fly variable name in python?

description: Create cross-module, on-thy-fly variable name in python


code:
import subprocess
command = 'php /path/to/script.php "{1}"'.format(soap_string)
process = subprocess.Popen(command, shell = True, stderr = subprocess.PIPE, stdout = subprocess.PIPE)
process.wait()
output = process.communicate()[0]
(error, result, order_id) = output.split(',')

rawDescription: Parsing a SOAP response in Python

description: Parsing a SOAP response in Python


code:
import requests
from bs4 import BeautifulSoup
html = requests.get('http://steamcommunity.com/market/search/render/?query=appid:730&start=0&count=3&currency=3&l=english&cc=pt').json()['results_html']
BeautifulSoup(html, 'lxml').find('span', class_='normal_price').span

rawDescription: BS4 get info from class with weird name

description: BS4 get info from class with weird name


code:
def iter_flattened(data):
    '''returns a generator that allows iteration over key,value pairs, even if the dictionaries are nested in lists'''
    if isinstance(data, dict):
        yield from data.items()
    elif isinstance(data, list):
        for item in data:
            yield from iter_flattened(item)

def _find(data, keys):
    '''This function searches the given (sub-)tree for the given keys'''
    if len(keys) == 0:
        return data

    for key, value in iter_flattened(data):
        if key == keys[0]:
            result = _find(value, keys[1:])
        else:
            result = _find(value, keys)
        if result is not None:
            return result
    return None

def find(data, path):
    '''Interface function, that accepts the keys as a string seperated with dots.'''
    keys = path.split('.')
    return _find(data, keys)

rawDescription: how to extend a python dictionary while there are list inside

description: Extend a python dictionary while there are list inside


code:
def flatten(source):
    target = {}
    def helper(src, path ='.', last_key = None):
        if last_key:
            target[last_key] = {}
            target[last_key]['location'] = path
        for key, value in src.items():
            if isinstance(value, dict):
                helper(value, os.path.join(path, key), key)

            else:
                target[last_key][key] = value

    helper(source)
    return target

rawDescription: Flatten nested dictionaries while checking content


code:
levels = np.arange(-1.0,1.5,0.25)
CS = plt.contour(X, Y, Z, levels=levels)

rawDescription: Adding extra contour lines using matplotlib 2D contour plotting


code:
import scipy
from scipy import ndimage
import matplotlib.pyplot as plt
import matplotlib
from random import random

colors = [(1,1,1)] + [(random(),random(),random()) for i in xrange(255)]
new_map = matplotlib.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)

im = scipy.misc.imread('blobs.jpg',flatten=1)
blobs, number_of_blobs = ndimage.label(im)

plt.imshow(blobs, cmap=new_map)
plt.imsave('jj2.png',blobs, cmap=new_map)
plt.show()

rawDescription: How to display objects in different random colors on a white background in matplotlib python?

description: Display objects in different random colors on a white background in matplotlib python


rawDescription: Equivalent to Lambda Expressions in Python


code:
class AMockSpec(A):
    def __subclasses__(self): pass
m = create_autospec(AMockSpec)
m.__subclasses__ = Mock()
m.__subclasses__.return_value = ['SomeMockValue']
m.__subclasses__()

rawDescription: Unable to mock __subclasses__ in python

description: Unable to mock __subclasses__ in python


rawDescription: How to urlencode multi valued keys in python?

description: Urlencode multi valued keys in python


code: twos_complement(61703, 16)

rawDescription: How to make python look hex numbers as two's complemented?

description: Make python look hex numbers as two's complemented


rawDescription: Convert a list to a dictionary in Python


code: int_values = [int(cell.internal_values[i]) for i in xrange(1, len(cell.internal_values), 2)]

rawDescription: Strip and convert values/numbers out of a list


code:
foo = "This is not " \
    "recommended"

rawDescription: String Concatenation: Putting large chuck of text in Python code


code: distinct_dates = list(session.query(cast(Test_Table.test_time, DATE)).distinct())

rawDescription: convert selected datetime to date in sqlalchemy

description: Convert selected datetime to date in sqlalchemy


code:
x.ix[(x.groupby(pd.Grouper(key='Timestamp', freq='5T'))['Volume'].transform('sum') > 65000)
     &
     (x.Timestamp.dt.hour==9)
     &
     (x.Timestamp.dt.minute>=30) & (x.Timestamp.dt.minute<=34)]

rawDescription: Select certain dates from Pandas dataframe


code:
import sys
import os
sys.executable

rawDescription: A system independent way using python to get the root directory/drive on which python is installed


code:
import pandas as pd
import matplotlib.pyplot as plt

rawDescription: Plotting bar charts by each two rows

description: Plotting bar charts by each two rows


rawDescription: Decode bracket-encoded dictionary in query string


code:
def avg(sources):
    return float(sum(sources)) / len(sources)

def total(sources):
    return sources[-1] - sources[0]

for i in range(len(eventVqts)-2, 0, -1):
    filtered = map(attrgetter('Variant.Double'), sources.filter(eventQvts, i))
    the_sum = sum(filtered)
    the_avg = avg(filtered)
    the_total = total(filtered)
    # etc....

rawDescription: Pythonic conditional sum on member

description: Pythonic conditional sum on member


code:
from pyparsing import makeHTMLTags,withAttribute,Suppress,Regex,Group

""" looking for this recurring pattern:
          00-03
          .50
          .50

    and want a dict with keys 0, 1, 2, and 3 all with values (.50,.50)
"""

td,tdend = makeHTMLTags("td")
keytd = td.copy().setParseAction(withAttribute(bgcolor="#FFFFCC"))
td,tdend,keytd = map(Suppress,(td,tdend,keytd))

realnum = Regex(r'1?\.\d+').setParseAction(lambda t:float(t[0]))
integer = Regex(r'\d{1,3}').setParseAction(lambda t:int(t[0]))
DASH = Suppress('-')

# build up an expression matching the HTML bits above
entryExpr = (keytd + integer("start") + DASH + integer("end") + tdend +
                    Group(2*(td + realnum + tdend))("vals"))

rawDescription: Parse HTML Table with Python BeautifulSoup


code:
import numpy as np
from matplotlib.path import Path
from scipy.misc import lena

img = lena()

# vertices of the cropping polygon
xc = np.array([219.5, 284.8, 340.8, 363.5, 342.2, 308.8, 236.8, 214.2])
yc = np.array([284.8, 220.8, 203.5, 252.8, 328.8, 386.2, 382.2, 328.8])
xycrop = np.vstack((xc, yc)).T

# xy coordinates for each pixel in the image
nr, nc = img.shape
ygrid, xgrid = np.mgrid[:nr, :nc]
xypix = np.vstack((xgrid.ravel(), ygrid.ravel())).T

# construct a Path from the vertices
pth = Path(xycrop, closed=False)

# test which pixels fall within the path
mask = pth.contains_points(xypix)

# reshape to the same size as the image
mask = mask.reshape(img.shape)

# create a masked array
masked = np.ma.masked_array(img, ~mask)

# if you want to get rid of the blank space above and below the cropped
# region, use the min and max x, y values of the cropping polygon:

xmin, xmax = int(xc.min()), int(np.ceil(xc.max()))
ymin, ymax = int(yc.min()), int(np.ceil(yc.max()))
trimmed = masked[ymin:ymax, xmin:xmax]

rawDescription: Crop out partial image using NumPy (or SciPy)


rawDescription: Python numpy bool masks for absoluting values


code:
self.process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE, bufsize=0, shell=True)
out = self.process.stdout.readline()
self.jobid = out.split()[10]

rawDescription: Best Approach to Threading/Spawning Multiple OS Commands and Getting Output at Various Points


rawDescription: How can I sort 2 lists of lists by column?

description: Sort 2 lists of lists by column


code:
low = re.search(r"[a-z]", password)
up = re.search(r"[A-Z]", password)
num = re.search(r"[0-9]", password)
has_all = all((low, up, num))

rawDescription: python regular expression re.search(r"([a-z]+[A-Z]+[0-9]+)", password)

description: Python regular expression re.search(r"([a-z]+[A-Z]+[0-9]+)", password)


code:
def setones_between_triggers(A,T1,T2):

    # Get start and stop indices corresponding to rising and falling triggers
    start = np.where(A==T1)[0]
    stop = np.where(A==T2)[0]

    # Take care of boundary conditions for np.searchsorted to work
    if (stop[-1] < start[-1]) & (start[-1] != A.size-1):
        stop = np.append(stop,A.size-1)

    # This is where the magic happens.
    # Validate (filter out) the triggers based on the set conditions :
    # 1. See if there are more than one stop indices between two start indices.
    # If so, use the first one and rejecting all others in that in-between space.
    # 2. Repeat the same check for start, but use the validated start indices.

    # First off, take care of out-of-bound cases for proper indexing
    stop_valid_idx = np.unique(np.searchsorted(stop,start,'right'))
    stop_valid_idx = stop_valid_idx[stop_valid_idx < stop.size]

    stop_valid = stop[stop_valid_idx]
    _,idx = np.unique(np.searchsorted(stop_valid,start,'left'),return_index=True)
    start_valid = start[idx]

    # Create shifts array (array filled with zeros, unless triggered by T1 and T2
    # for which we have +1 and -1 as triggers).
    shifts = np.zeros(A.size,dtype=int)
    shifts[start_valid] = 1
    shifts[stop_valid] = -1

    # Perform cumm. summation that would almost give us the desired output
    out = shifts.cumsum()

    # For a worst case when we have two groups of (T1,T2) adjacent to each other,
    # set the negative trigger position as 1 as well
    out[stop_valid] = 1
    return out

rawDescription: numpy array set ones between two values, fast

description: Numpy array set ones between two values, fast


code:
plans = Plan.objects.filter(region__name='Region 1') # all plans for that region
for plan in plans:
   region_weather = plan.region.weather_set.all()
   district_weather = plan.district.weather_set.all()

rawDescription: How to join the results of two tables in django python

description: Join the results of two tables in django python


code: bin_str = ''.join(bin(0x100 + ord(b))[-8:] for b in byte_str)

rawDescription: Workin with binary in python

description: Workin with binary in python


code:
df = pd.read_csv('energy.csv')
x = df.drop('year',1)
percent = pd.concat([df.year,x.div(x.sum(1),'index')*100],1)

rawDescription: Calculate percent value across a row in a dataframe


code:
def smallest_value_greater_than_0(numbers):
    return min(num for num in numbers if num > 0)

rawDescription: How can I write a function that returns the smallest value greater than 0 from a list?

description: Write a function that returns the smallest value greater than 0 from a list


code:
{
  'username': {'max_length': 30},
  'first_name': {'max_length': 30},
  'last_name': {'max_length': 30},
  'is_active': {'max_length': None},
  'email': {'max_length': 75},
  'is_superuser': {'max_length': None},
  'is_staff': {'max_length': None},
  'last_login': {'max_length': None},
  'password': {'max_length': 128},
  u'id': {'max_length': None},
  'date_joined': {'max_length': None}
}

rawDescription: How can i extract metdata from django models

description: Extract metdata from django models


rawDescription: Automated alignment of "tabular" Python code


code:
x = "define('DB_NAME', 'database_name');"
re.search(r"define\('DB_NAME',\s*'([^']*)'\);", x).group(1)

rawDescription: Python: Extract substring that matches regular expression in a string


code: {{ order.pa_tranlength * order.pa_width * order.pa_costprice }}

rawDescription: Jinja2 convert float to decimal mid calculation


code:
# somestring is a string, but could be any object
somestring = "valentyn"

# somestring.upper happens to be a method
method = getattr(somestring, "upper")

# ...which can be called in the usual manner
print(method())

rawDescription: Call a function using getattr in Python

description: Call a function using getattr in Python


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

values = (1, 2)

s = sum(*values)

rawDescription: What does the Star operator mean in Python?


code:
dict1={"letter":[]}
dict1["letter"].extend([a for a in list1])
dict
{"letter":["a","b","c"]}

rawDescription: How to iteratively append key-value pairs to a dictionary in Python?

description: Iteratively append key-value pairs to a dictionary in Python


rawDescription: Django: Count users used in model's ManyToMany


code:
#First .py module
class ftp_server:
   def __init__(self):
       self.authorizer = DummyAuthorizer()
       self.authorizer.add_user('admin', 'password', '.', perm='elradfmwM')

   def run(self):
       self.handler = FTPHandler
       self.handler.authorizer = self.authorizer
       self.address = ('localhost', 21)
       self.server = FTPServer(self.address, self.handler)
       logging.basicConfig(filename='pyftpd.log', level=logging.INFO)
       self.server.serve_forever()

   def add_user(self,user,passwd,loc,privi):
       self.authorizer.add_user(str(user), str(passwd), str(loc), perm=str(privi))

rawDescription: PyFtpdLib How to add a user while still running server


code: {{ movie.title }}

rawDescription: Returning Data from Python Function for use with Jinja2 Template (Flask)


code:
numbers = [1, 8, 9, 6, 2, 3, 1, 4, 5]
output = []

while numbers:
    smallest = min(numbers)
    index = numbers.index(smallest)
    output.append(numbers.pop(index))

print(output)

rawDescription: How to manually sort a list of numbers in Python?

description: Manually sort a list of numbers in Python


code: from collections import Counter

rawDescription: How to count occurrences of specific element for arrays in a list?

description: Count occurrences of specific element for arrays in a list


code:
fig = plt.figure()

line_1 = Line2D([0,1], [0,4], linewidth=1, linestyle = "-", color="green")
line_2 = Line2D([0,4.5], [0,3], linewidth=1, linestyle = "-", color="red")

ax = fig.add_subplot(1,1,1)

ax.add_line(line_1)
ax.add_line(line_2)

angle_plot = get_angle_plot(line_1, line_2, 1)
angle_text = get_angle_text(angle_plot)
# Gets the arguments to be passed to ax.text as a list to display the angle value besides the arc

ax.add_patch(angle_plot) # To display the angle arc
ax.text(*angle_text) # To display the angle value

ax.set_xlim(0,7)
ax.set_ylim(0,5)

rawDescription: Best way to plot an angle between two lines in Matplotlib

description: Plot an angle between two lines in Matplotlib


code:
new_catalogue = orig_catalogue[orig_catalogue['interesting'] > 100]
new_catalogue.write('new_filename.fits')

rawDescription: build new table from rows in astropy

description: Build new table from rows in astropy


code: return sorted(ob.items()[:default],key=lambda x: x[1])

rawDescription: Sorting function works differently when imported rather then called in script


rawDescription: Mask an array with conditions on multiple columns


code:
for ax in axs.flat[axs.size - 1:len(subsl) - 1:-1]:
    ax.set_visible(False)

rawDescription: Create subplots in Matplotlib in a loop?

description: Create subplots in Matplotlib in a loop


rawDescription: Python regex: Search and replace a character except when outside braces


code:
ips.append('{}.{}.{}.{}'.format(i, j, k, p)) # OR
ips.append('.'.join(map(str, (i, j, k, p))))

rawDescription: Python parse ip regex

description: Python parse ip regex


rawDescription: Replacing consecutive symbol with number digit in python using regex


code: your_count = graph.cypher.execute("MATCH (p:Person) RETURN count(*)")[0][0]

rawDescription: How to convert neo4j return types to python types

description: Convert neo4j return types to python types


code:
for num in range(ind_max):
    ro.r("source('" + codeLoc + "/filename" + str(num) + ".R')")

rawDescription: assigning then attaching a filepath name in python using rpy2

description: Assigning then attaching a filepath name in python using rpy2


rawDescription: How does python do list slices and modification on the LHS?


rawDescription: Using numpy fromfile on binary file returns 1 dimension ndarray


code: df['subindex'] = df.groupby('ID').cumcount() + 1

rawDescription: Pivot table from a pandas dataframe without an apply function


code: users = User.query.filter({"name": re.compile(r".*", re.IGNORECASE)}).all()

rawDescription: MongoAlchemy regex return nothing

description: MongoAlchemy regex return nothing


code:
weak_obj = weakref.ref(meth.im_self)
weak_func = weakref.ref(meth.im_func)

rawDescription: Can I weak reference methods?

description: Weak reference methods


code:
r = re.compile('^((?P<fixed>\d+)|(?P<begin>\d+)?-(?P<end>\d+)?)$')
r.match('123').groupdict()
r.match('123-').groupdict()
r.match('-456').groupdict()
r.match('-').groupdict()
r.match('123-456').groupdict()

rawDescription: Python regular expressions: match a range of numbers with a separator


code:
sage: cc = C()
sage: cc.scale(4)
8

rawDescription: Changing dynamically one method of a class


code:
sorted(index)
sorted(index['connected'])
for key in sorted(index):
    print('{:<20}{}'.format(key, ', '.join(str(i) for i in sorted(index[key]))))

rawDescription: Python sort in a dictionary and a set

description: Python sort in a dictionary and a set


code:
from matplotlib import pyplot,colors
import matplotlib as mpl

fig = pyplot.figure(figsize=(8,1))
ax2 = fig.add_axes([0.05, 0.25, 0.9, 0.5])

cmap = colors.ListedColormap(['r', 'g', 'b', 'k','y'])

bounds =  [0, 1, 2, 4, 7, 8, 13]
yVals  =  [  1, 2, 1, 3, 4, 5]

cBounds = [i+0.5 for i in range(6)]

norm = mpl.colors.BoundaryNorm(cBounds, cmap.N)
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap=cmap,
                                 norm=norm,
                                 values=yVals,
                                 boundaries=bounds,
                                 ticks=bounds[1:-1], # optional
                                 spacing='proportional',
                                 orientation='horizontal')

rawDescription: Custom Colorbar-like plot with matplotlib


rawDescription: Creating a list from another list - Python


code:
def fallBack(submission):
    if not submission:
        return "fixed!"
    else:
        return submission

rawDescription: Python function to give default value for blank entry not working


order: chronological

rawDescription: How to get share count from Facebook Graph API?

description: Get share count from Facebook Graph API


code:
import ConfigParser
import logging

class ConfigLogger(object):
    def __init__(self, log):
        self.__log = log
    def __call__(self, config):
        self.__log.info("Config:")
        config.write(self)
    def write(self, data):
        # stripping the data makes the output nicer and avoids empty lines
        line = data.strip()
        self.__log.info(line)

config = ConfigParser.ConfigParser()
config.add_section("test")
config.set("test", "a", 1)
# create the logger and pass it to write
logging.basicConfig(filename="test.log", level=logging.INFO)
config_logger = ConfigLogger(logging)
config_logger(config)

rawDescription: How can I print the contents of a ConfigParser to my log?

description: Print the contents of a ConfigParser to my log


code:
import re

r = re.compile(r'.*({}).*'.format('|'.join(w.values)), re.IGNORECASE)

masked = map(bool, map(r.match, df['Tweet']))

rawDescription: pandas find strings in common among Series

description: Pandas find strings in common among Series


code:
session.bulk_update_mappings(
                Salary,
                [{employeeId:1,Salary:10000},
                 {employeeId:2,Salary:15000}]
            )

rawDescription: SQL Alchemy: How to bulk update values from a list of dicts


rawDescription: Python lxml: How to traverse back up a tree


code: command = lambda idx=i: self.removeButton(idx)

rawDescription: Making Buttons that Locate Themselves in a List


code:
deleted_edges = [('a', 'b'), ('c', 'd'), ('e', 'f'), ('g', 'h')]
l = list(new_edge_sets(deleted_edges))
len(l)
for new_edges in l:
    print(new_edges)

rawDescription: How to enumerate possible reconstructions of a Hamiltonian cycle without DFS/BFS?

description: Enumerate possible reconstructions of a Hamiltonian cycle without DFS/BFS


code:
company_a = Company.objects.get(pk=1)

company_a.owned_items.all()
company_a.held_items.all()

items_owned_and_held_by_a=Items.objects.filter(owner=company_a, holder=company_a)

items_on_loan_by_a=Items.objects.filter(owner=company_a).exclude(holder=company_a)
#or
items_on_loan_by_a=company_a.owned_items.exclude(holder=company_a)

items_a_is_borrowing=Items.objects.exclude(owner=company_a).filter(holder=company_a)
#or
items_a_is_borrowing=company_a.held_items.exclude(owner=company_a)

company_b = Company.objects.get(pk=2)

items_owned_by_a_held_by_b=Items.objects.filter(owner=company_a, holder=company_b)
#or
items_owned_by_a_held_by_b=company_a.owned_items.filter(holder=company_b)
#or
items_owned_by_a_held_by_b=company_b.held_items.filter(owner=company_a)

rawDescription: How to model lending items between a group of companies

description: Model lending items between a group of companies


rawDescription: How would I determine zodiac / astrological star sign from a birthday in Python?


code:
from functools import partial

cube = partial(power, pow=3)

rawDescription: Python, assign function to variable, change optional argument's value


code: a = Class()

rawDescription: Is there any way besides __init__ to receive values when constructing a class?


code:
# First create a new series, which is true whenever the value changes from a zero value to a non-zero value (which will be at the start of each group)
nonzero = (df['Value1'] > 0) & (df['Value1'].shift(1) == 0)
# Take a cumulative sum. This means each group will have it's own number.
df['group'] = df['nonzero'].cumsum()
# Group by the group column
gb = df[df['Value1'] > 0].groupby('group')

rawDescription: Aggregation on Pandas data frame for selected rows


code:
import numpy
ra = numpy.recarray((10,), 'int,int,int')

rawDescription: numpy recarray minimum diffrences

description: Numpy recarray minimum diffrences


rawDescription: Python rounding of random floats to nearest points on a 2D uniform mesh grid


code:
i = arange(255)
j = arange(255)
x = simple_func1(i)
y = simple_func2(j)
y = y.reshape(-1,1)

A = alpha * x * y + beta * x**2 + gamma * y**2 # broadcasting is your friend here

rawDescription: Fast math operations on an array in python


rawDescription: Numpy equivalent of dot(A,B,3)

description: Numpy equivalent of dot(A,B,3)


code: results = [item for item in iterator]

rawDescription: What are the advantages of "yield item" vs return iter(items)?


code: fhandle.write('RGB = {}'.format( tuple(int(h[i:i+2], 16) for i in (0, 2 ,4)) ))

rawDescription: Converting Hex to RGB value in Python

description: Converting Hex to RGB value in Python


code:
[('Goalkeepers', 'Cech', 'Chelsea', '30', '£6.4'),
 ('Goalkeepers', 'Hart', 'Man City', '28', '£6.4'),
 ('Goalkeepers', 'Krul', 'Newcastle', '21', '£5.0'),
 ('Goalkeepers', 'Ruddy', 'Norwich', '25', '£5.0'),
 ('Goalkeepers', 'Vorm', 'Swansea', '19', '£5.0'),
 ('Goalkeepers', 'Stekelenburg', 'Fulham', '6', '£4.9'),
 ('Goalkeepers', 'Pantilimon', 'Man City', '0', '£4.9'),
 ('Goalkeepers', 'Lindegaard', 'Man Utd', '0', '£4.9'),
 ('Goalkeepers', 'Butland', 'Stoke City', '0', '£4.9'),
 ('Goalkeepers', 'Foster', 'West Brom', '13', '£4.9'),
 ('Goalkeepers', 'Viviano', 'Arsenal', '0', '£4.8'),
 ('Goalkeepers', 'Schwarzer', 'Chelsea', '0', '£4.7'),
 ('Goalkeepers', 'Boruc', 'Southampton', '42', '£4.7'),
 ('Goalkeepers', 'Myhill', 'West Brom', '15', '£4.5'),
 ('Goalkeepers', 'Fabianski', 'Arsenal', '0', '£4.4'),
 ('Goalkeepers', 'Gomes', 'Tottenham', '0', '£4.4'),
 ('Goalkeepers', 'Friedel', 'Tottenham', '0', '£4.4'),
 ('Goalkeepers', 'Henderson', 'West Ham', '0', '£4.0'),
 ('Defenders', 'Baines', 'Everton', '43', '£7.7'),
 ('Defenders', 'Vertonghen', 'Tottenham', '34', '£7.0'),
 ('Defenders', 'Taylor', 'Cardiff City', '14', '£4.5'),
 ('Defenders', 'Zverotic', 'Fulham', '0', '£4.5'),
 ('Defenders', 'Davies', 'Hull City', '28', '£4.5'),
 ('Defenders', 'Flanagan', 'Liverpool', '0', '£4.5'),
 ('Defenders', 'Dawson', 'West Brom', '0', '£3.9'),
 ('Defenders', 'Potts', 'West Ham', '0', '£3.9'),
 ('Defenders', 'Spence', 'West Ham', '0', '£3.9'),
 ('Midfielders', 'Özil', 'Arsenal', '24', '£10.6'),
 ('Midfielders', 'Redmond', 'Norwich', '20', '£5.0'),
 ('Midfielders', 'Mavrias', 'Sunderland', '5', '£5.0'),
 ('Midfielders', 'Gera', 'West Brom', '0', '£5.0'),
 ('Midfielders', 'Essien', 'Chelsea', '0', '£4.9'),
 ('Midfielders', 'Brown', 'West Brom', '0', '£4.3'),
 ('Forwards', 'van Persie', 'Man Utd', '24', '£13.9'),
 ('Forwards', 'Cornelius', 'Cardiff City', '1', '£5.4'),
 ('Forwards', 'Elmander', 'Norwich', '7', '£5.4'),
 ('Forwards', 'Murray', 'Crystal Palace', '0', '£5.3'),
 ('Forwards', 'Vydra', 'West Brom', '2', '£5.3'),
 ('Forwards', 'Proschwitz', 'Hull City', '0', '£4.3')]

rawDescription: HTML file parsing in Python

description: HTML file parsing in Python


rawDescription: Placing a numpy record array inside another record array python


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

data = np.random.random((4, 4))

fig, ax = plt.subplots()
# Using matshow here just because it sets the ticks up nicely. imshow is faster.
ax.matshow(data, cmap='seismic')

for (i, j), z in np.ndenumerate(data):
    ax.text(j, i, '{:0.1f}'.format(z), ha='center', va='center',
            bbox=dict(boxstyle='round', facecolor='white', edgecolor='0.3'))

plt.show()

rawDescription: Show the values in the grid using matplotlib


rawDescription: How to find median using Spark

description: Find median using Spark


code:
config = {'webapp2_extras.jinja2': {'template_path': 'templates',
          'filters': {
          'timesince': filters.timesince,
          'datetimeformat': filters.datetimeformat},
          'environment_args': {'extensions': ['jinja2.ext.i18n']}},
          'webapp2_extras.sessions': {'secret_key': 'my-secret-key'}}

rawDescription: Organizing my config variable for webapp2


code:
def get(self, section, option):
    opt = self.optionxform(option)
    if section not in self._sections:
        if section != DEFAULTSECT:
            raise NoSectionError(section)
        if opt in self._defaults:
            return self._defaults[opt]
        else:
            raise NoOptionError(option, section)
    elif opt in self._sections[section]:
        return self._sections[section][opt]
    elif opt in self._defaults:
        return self._defaults[opt]
    else:
        raise NoOptionError(option, section)

rawDescription: Why does ConfigParser items() give raw strings while get() returns bool/float/etc?


rawDescription: Pandas Dataframe CSV export, how to prevent additional double-quote characters


code:
class Bread(Food):
    def __eq__(self, other):
        return isinstance(other, Bread)

rawDescription: One class with flags or many number of different classes


rawDescription: How to convert numbers into characters?

description: Convert numbers into characters


rawDescription: OrderedDict Merge and Append 0 if not

description: OrderedDict Merge and Append 0 if not


code:
import dis
dis.dis(Test.calc_x)

rawDescription: Python introspection: how to detect what fields are accessed from a method


code:
def gen_point_dist_from_lst(lst, p2):
    return (sqrt((p1.x-p2.x)**2 + (p1.y-p2.y)**2) for p1 in lst)

rawDescription: Python Effecient Wrappers

description: Python Effecient Wrappers


code: differences = [float(row[3]) - float(row[4]) for row in table]

rawDescription: Arithmetic Operations with Nested Lists in Python


code:
import pprint

def show(obj):
    pprint(obj)

rawDescription: organising classes and modules in python

description: Organising classes and modules in python


code:
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))
df

rawDescription: Pandas: How to create a data frame of random integers?


code:
from django.utils.decorators import method_decorator
from haystack.backends.elasticsearch_backend import ElasticsearchSearchBackend, ElasticsearchSearchEngine
from haystack.backends import BaseEngine
from haystack.backends import log_query
from urllib3.exceptions import ProtocolError, ConnectionError

class RobustElasticSearchBackend(ElasticsearchSearchBackend):
    """A robust backend that doesn't crash when no connection is available"""

    def mute_error(f):

        def error_wrapper(self, *args, **kwargs):
            try:
                return f(self, *args, **kwargs)
            except TransportError:
                self.log.warn('Connection Error: elasticsearch communication error')
        return error_wrapper

    def __init__(self, connectionalias, **options):
        super(RobustElasticSearchBackend, self).__init__(connectionalias, **options)

    @mute_error
    def update(self, indexer, iterable, commit=True):
        super(RobustElasticSearchBackend, self).update(indexer, iterable, commit)

    @mute_error
    def remove(self, obj, commit=True):
        super(RobustElasticSearchBackend, self).remove(obj, commit)

    @mute_error
    def clear(self, models=[], commit=True):
        super(RobustElasticSearchBackend, self).clear(models, commit)

class RobustElasticSearchEngine(ElasticsearchSearchEngine):
    backend = RobustElasticSearchBackend

rawDescription: Catch ConnectionError with Django-Haystack and ElasticSearch


code:
s = (
    r"foo\tbar\n"
    r"baz\tqux\n")

rawDescription: How can I create a single raw string from multiple literals in Python?

description: Create a single raw string from multiple literals in Python


code:
df
inbnd = pd.DataFrame({'event': 1}, index=df.date_in)
outbnd = pd.DataFrame({'event': -1}, index=df.date_out)
real_stream = pd.concat([inbnd, outbnd]).sort()
real_stream

rawDescription: pandas window functions: accessing to intermediate results

description: Pandas window functions: accessing to intermediate results


code:
from django.core.urlresolvers import resolve
from settings import DEBUG

def debug_settings(request):
    return {'DEBUG': DEBUG}

rawDescription: Django Templates Development vs. Production


code: GPIO.add_event_detect(17, GPIO.BOTH, callback=callback_func, bouncetime=200)

rawDescription: Controlling a relay with a momentary button in Python


rawDescription: Python irregular loop

description: Python irregular loop


code:
sys.stdout.write('hello')
sys.stdout.flush()
for _ in range(5):
    time.sleep(1)
    sys.stdout.write('\033[D \033[D')
    sys.stdout.flush()

rawDescription: In Python, how to change text after it's printed?


code:
from datetime import date
today = date.today()
this_month_qs = Sample.objects.filter(
    date__month=today.month,
    date_year=today.year,
)

rawDescription: Sorting queryset with date

description: Sorting queryset with date


code:
class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'

    def disable(self):
        self.HEADER = ''
        self.OKBLUE = ''
        self.OKGREEN = ''
        self.WARNING = ''
        self.FAIL = ''
        self.ENDC = ''

print(bcolors.WARNING + "Warning" + bcolors.ENDC)

rawDescription: Printing colors in python terminal

description: Printing colors in python terminal


code:
class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        DATA = { 0 : ("3", "3", "1"), 1 : ("2", "1", "2"), 2 : ("1", "2", "3") }
        self.list = MyList(self, DATA)
        self.Show()

rawDescription: How to allow UltimateListCtrl to rearrange itself, wxpython

description: Allow UltimateListCtrl to rearrange itself, wxpython


code:
from collections import Counter

create_combiner = Counter

def merge_value(cnt, doc):
    cnt.update(Counter(doc))
    return cnt

def merge_combiners(cnt1, cnt2):
    cnt1.update(cnt2)
    return cnt1

topics = (mapped_value
    .combineByKey(create_combiner, merge_value, merge_combiners)
    .mapValues(lambda cnt: cnt.most_common(2)))

topics
## [(1, [('b', 4), ('a', 3)]), (2, [('a', 3), ('c', 3)])]

rawDescription: Finding top words per kmeans cluster

description: Finding top words per kmeans cluster


code:
class Foo(object):
    calls=0            # <--- call is a class member
    def baz(self):
        Foo.calls+=1

foo=Foo()
bar=Foo()
for i in range(100):
    foo.baz()
    bar.baz()
print('Foo.baz was called {n} times'.format(n=foo.calls))
# Foo.baz was called 200 times

rawDescription: Static member of a function in Python ?

description: Static member of a function in Python


code:
import subprocess

subprocess.call(['python', 'child.py'])

rawDescription: Python3x - Write a python script to run other python scripts?


code:
class couple ( bidict ) :

    self._flags = {}

    def add ( self, key, val, flag ) :
        try :
            del self._flags[ self._inv[ val ] ]
        except KeyError :
            pass
        self._put(key, val, overwrite_key=True, overwrite_val=True)
        self._flags[ key ] = flag

    def flag ( self, key, val ) :
        if ( self._fwd.get( key ) == val ) :
            return self._flags[ key ]
        else :
            raise KeyError( key, val )

rawDescription: Efficient both ways mapping in Python with flag values


code:
class JSONPlugin(object):
    name = 'json'
    api  = 2

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

    def apply(self, callback, route):
        dumps = self.json_dumps
        if not dumps: return callback
        def wrapper(*a, **ka):
            ...

            if isinstance(rv, dict):
                ...
            elif isinstance(rv, HTTPResponse) and isinstance(rv.body, dict):
                rv.body = dumps(rv.body)
                rv.content_type = 'application/json'
            return rv

        return wrapper

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


code:
A = GenericA # Just re-export the generic A class

class B(GenericB):
    def __init__(self):
        super(B,self).__init__()

#I really want to inherit from C and change it's behavior
class C(GenericC):
    def __init__(self):
        super(C,self).__init__()
    def changeHello(self):
        self.hello = "Hello! I am Mr.C modified in t_Custom"

rawDescription: pythonic way to customize classes

description: Pythonic way to customize classes


code:
def rhs(c, t, f):
    ...

rawDescription: Solve a ODE for arrays of parameters (Python)


code:
# create the first image as a template
l = plt.plot(x, list[0])
for sublist in list:
    l.set_ydata(sublist)
    plt.title(names[g])
    g = g + 1
    plt.savefig(genes[g-1])

rawDescription: Matplotlib: want different plot for each line


code:
import lib
lib.lib7

rawDescription: Python : Import modules once then share with several files


code: peakthree = float(peaktwo) - float(peakone)

rawDescription: Subtracting numbers from inputted array

description: Subtracting numbers from inputted array


rawDescription: Avoiding TypeError when using timedelta to compare times


rawDescription: Sum float values at each index point in nested lists


code:
class Meta:
    unique_together = ('field1', 'field2',)

rawDescription: Create Django Objects outside of Admin

description: Create Django Objects outside of Admin


rawDescription: List of values for duplicate keys in dictionary Python


code:
with open("identifiers.txt") as ids, open("target.txt") as target:
    idents = {line.split()[1] for line in ids}
    matches = [line.split() for line in target if line.split()[0] in idents]

rawDescription: Finding lines by first value in text file in python


rawDescription: remove duplicate elements from two numpy arrays

description: Remove duplicate elements from two numpy arrays


code:
filled_1 = False
filled_2 = True
filled_3 = True
filled_4 = False

rawDescription: pygame circle not changing

description: Pygame circle not changing


rawDescription: More Digits in Irrational Numbers

description: More Digits in Irrational Numbers


code:
# a_module.py
b1 = 1
a0 = 1
a1 = 2

rawDescription: Get ordered list of attributes of a Python module


rawDescription: How do I remove from the beginning to the 2nd specific character of a string?

description: Remove from the beginning to the 2nd specific character of a string


rawDescription: Plot only x-axis minor gridlines in x-y graph in Python


rawDescription: django how to use AUTH_PROFILE_MODULE with multiple profiles?

description: Django how to use AUTH_PROFILE_MODULE with multiple profiles


rawDescription: Timeout function using threading in python does not work


code: coerce = lambda x: x == 'True'

rawDescription: Django form-wizard typechoicefield returning string instead of boolean


code:
this_iteration = 0
letters_positions = list(letters_positions)

for [x, y, dx, dy, r], letter in letters_positions:
    last_iteration = this_iteration
    this_iteration += 1
this_iteration = 0

for [x, y, dx, dy, r], letter in letters_positions:
    if this_iteration == last_iteration:
        continue
    this_iteration += 1

rawDescription: Unpacking in a for loop twice

description: Unpacking in a for loop twice


code: texture = glGenTextures(1)

rawDescription: Image format for glGenTextures

description: Image format for glGenTextures


code: from django.db.models.base import Model

rawDescription: Django Models: Where is Model class?

description: Django Models: Where is Model class


code: quicksort( inputList, numElems-last-1, last+1 )

rawDescription: Python 'pointer arithmetic' - Quicksort

description: Python 'pointer arithmetic' - Quicksort


rawDescription: urllib2 file name

description: Urllib2 file name


code:
Aobj = A()
aBoundMeth = getattr(Aobj, 'a')
aBoundMeth.__name__

rawDescription: Get name of the bound method from instance of the bound method object in Python


rawDescription: Need help Regex for python

description: Need help Regex for python


code:
from __future__ import print_function

import os

les={'Unix':chr(10), 'MacOS':chr(13), 'Windows': ''.join([chr(13), chr(10)])}

n=10000
for osn, le in les.items():
   fn='{} {} lines.txt'.format(osn, n)
   print(fn)
   with open(fn, 'wb') as f:
       for x in range(n):
           f.write('line {}{}'.format(x, le))

   for mode in ('r', 'rb', 'rU'):
       with open(fn, mode) as f:
           print("{:10d} lines with {}".format(sum(1 for _ in f), mode))

   os.remove(fn)

rawDescription: Reading really large text files in python does iterate correctly


code:
from threading import Thread

def threaded_process_range(nthreads, id_range):
    """process the id range in a specified number of threads"""
    store = {}
    threads = []
    # create the threads
    for i in range(nthreads):
        ids = id_range[i::nthreads]
        t = Thread(target=process_range, args=(ids,store))
        threads.append(t)

    # start the threads
    [ t.start() for t in threads ]
    # wait for the threads to finish
    [ t.join() for t in threads ]
    return store

rawDescription: Making multiple API calls in parallel using Python (IPython)


rawDescription: Attributes of Python module `this`

description: Attributes of Python module `this`


rawDescription: Pymongo and Aggregation framework query

description: Pymongo and Aggregation framework query


rawDescription: Dot product of every element with every other element of an array


code:
all( comb_df == df7 )
True

rawDescription: Combining pandas data frames with overlapping columns / rows


rawDescription: Is a Regular Expression Faster than using .replace()


code: html = '''<acronym class="non-experimental-qualifier" title="Indicates that the information given is not based on experimental findings." onclick="dialog('non_experimental_qualifiers'); Event.stop(event || window.event); return false" onmousedown="Event.stop(event || window.event);">By similarity</acronym>. <a class="attribution" href="http://hamap.expasy.org/unirule/'''

rawDescription: How can I read this string if it has " and ' ? Python

description: Read this string if it has " and ' ? Python


code: mydbcursor.executemany(sql, (k + v for k, v in mydict.iteritems()))

rawDescription: How to write a Python compound key, value dictionary to a database?

description: Write a Python compound key, value dictionary to a database


code:
number_of_line_Edit = 70
txt = [getattr(self.ui,'lineEdit{0}'.format(i)) for i in range(1,number_of_line_Edit+1)] #This will collect all lineEdit(s) reference so we can call there methods in return_text method
mySlot = lambda :instance_b.return_text(txt)
QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"),  mySlot)

rawDescription: I can not add many values in one function


code:
def key_finder(d,val):
   for key in d :
      value=finance[key]
      if value==val:
         yield key
      elif isinstance(value,list) and val in value:
         yield key

rawDescription: How can i get keys in a dictionaty in Python when a value is given?

description: Get keys in a dictionaty in Python when a value is given


rawDescription: background music not playing in pygame

description: Background music not playing in pygame


code:
ss = s.to_frame().set_index(np.array([0,0]))
ss[df.columns] = df
ss

rawDescription: Adding a Pandas Dataframe-column to a new dataframe


code:
def isLast(itr):
  old = itr.next()
  for new in itr:
    yield False, old
    old = new
  yield True, old

rawDescription: Have csv.reader tell when it is on the last line


rawDescription: items.py and nested xml tags with scrapy

description: Items.py and nested xml tags with scrapy


code:
for i in var:
    if i:
       form1(name=i1,qualification=i2,keyskills=i).save()

rawDescription: Django database shouldn't accept a null value


code:
y = abs(y)
y = (y >> 32) ^ (y & 0xffffffff)  # collapse to 32 bits

rawDescription: implementing custom hashing method

description: Implementing custom hashing method


code: driver.execute_script("document.getElementsByName('redirect')[0].value = '" + s + "';")

rawDescription: Python SELENIUM issue

description: Python SELENIUM issue


code:
client.drop_database(db) # drop our demo database
fs.put('img.jpg', encoding='utf-8', filename='img.jpg')
fs.list()
pprint.pprint(db['fs.files'].find_one())

rawDescription: The gridfs "list" method returns empty list with non empty collection


code:
def test_request_object(self):
    self.user = User.objects.create_user(
    username='abc', email='abc@gmail.com', password='1234')
    request = HttpRequest()
    #create a session which will hold the user profile that will be used in by our custom decorator
    request.session = {} #Session middleware is not available in UnitTest hence create a blank dictionary for testing purpose
    request.session['user_profile'] = self.user.is_staff #assuming its django user.

    # User send a request to access repositories
    response = staff_users(request)

    #Check the response type for appropriate action
    self.assertIsNone(response)

rawDescription: How to test that a view is only accessed by staff users in Django

description: Test that a view is only accessed by staff users in Django


code:
[login]
username = user01
password = 123456

rawDescription: How to pass values to a Python executable from a config file

description: Pass values to a Python executable from a config file


code:
...
CONNECTION = MySQLdb.connect(host=..., port=...,
                             user=..., passwd=..., db=...,
                             cursorclass=MySQLdb.cursors.DictCursor,
                             charset = "utf8")
cursor = CONNECTION.cursor()
cursor.execute("SELECT ... FROM ... WHERE ... AND some_field=%s", ("first", "amazing", "topic"))
first_result = cursor.fetchall()

cursor.execute("SELECT ... FROM ... WHERE ... AND some_field=%s", (("first", "amazing", "topic")))
second_result = cursor.fetchall()

cursor.close()
...

rawDescription: Executing different queries using mysql-python


code:
from itertools import count
from collections import defaultdict
a=[['a1', 'b1'], ['a1', 'b2'], ['a2', 'b1'], ['a2', 'b4']]
counts = defaultdict(lambda c=count(): next(c))
zip(*((counts[cell] for cell in col) for col in zip(*a)))

rawDescription: How to map a unique id (counting from 0) to items in sublists

description: Map a unique id (counting from 0) to items in sublists


code:
from copy import deepcopy

for ind, st_nodes in enumerate(starting_nodes):
    for node in object_list:
        if st_nodes[0].id == node.pred:
            starting_nodes[ind].append(deepcopy(node))
print(starting_nodes)

rawDescription: How to compare two unequal lists and append matching elements value back to the first List

description: Compare two unequal lists and append matching elements value back to the first List


code:
class MyView(FormView):
    def get_form(self, form_class):
        return form_class(self.request, self.get_form_kwargs())

rawDescription: forms.ModelForm Restrict to User Who Created the Model

description: Forms.ModelForm Restrict to User Who Created the Model


code: ax5 = fig.add_axes(ax4.get_position() , frameon=True, zorder = -10.0)

rawDescription: What is subplot_adjust() doing to pyplot axes?


code:
for handle in handles:
    handle.close()

rawDescription: Iterate over multiple generators (file handles)


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

fig = plt.figure()
ax = Axes3D(fig) #Or: ax = fig.add_subplot(111, projection='3d')

ax.scatter( range(0,10), range(0,10), c=range(0,10) )

rawDescription: Convert a list into 2-D array in python

description: Convert a list into 2-D array in python


rawDescription: Pandas plotting lines from different columns ignoring values


code:
root = Tk()

# derived width and height
width = 400
height = 40

# add a font
font = tkFont.Font(size=-height)

# blank photo image
image = PhotoImage()

Label(root, image=image, compound='center', text='Hello World',
      width=width, height=height, bg='white', font=font).pack()

mainloop()

rawDescription: How to derive the font size from a height constraint?

description: Derive the font size from a height constraint


code:
import django_tables2 as tables

class SimpleTable(tables.Table):
    class Meta:
        model = Simple

rawDescription: how to render a Queryset into a table template-django

description: Render a Queryset into a table template-django


code:
from threading import Thread
from time import sleep

def change_state(obj):
    sleep(5)
    obj.commandState = obj.COMMAND_COMPLETE

def test_1():
  obj = MyClass()

  # Launch a thread that within 5 seconds will change the state of `obj`
  Thread(target=change_state, args=[obj]).start()

  # Call the main loop, which will recognize that the state changed within 5 secs
  obj.run_loop()

rawDescription: Mocking a variable in python

description: Mocking a variable in python


code:
def resp1_start():
    pass
def resp1_stop():
    pass
responses = {
    "resp1": {
        "start": resp1_start,
        "stop": resp1_stop,
    },
}
responses["resp1"]["start"]()

rawDescription: Restrictons of Python compared to Ruby: lambda's


code:
def wrapper(row1, row2):
    # might have to fiddle a bit here, but i think this retrieves the indices.
    i1, i2 = row1[0], row2[0]
    return D[i1, i2]

rawDescription: Does KNeighborsClassifier compare lists with different sizes?


code:
import logging
import datetime as dt

class MyFormatter(logging.Formatter):
    converter=dt.datetime.fromtimestamp
    def formatTime(self, record, datefmt=None):
        ct = self.converter(record.created)
        if datefmt:
            s = ct.strftime(datefmt)
        else:
            t = ct.strftime("%Y-%m-%d %H:%M:%S")
            s = "%s,%03d" % (t, record.msecs)
        return s

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)

console = logging.StreamHandler()
logger.addHandler(console)

formatter = MyFormatter(fmt='%(asctime)s %(message)s',datefmt='%Y-%m-%d,%H:%M:%S.%f')
console.setFormatter(formatter)

logger.debug('Jackdaws love my big sphinx of quartz.')
# 2011-06-09,07:12:36.553554 Jackdaws love my big sphinx of quartz.

rawDescription: Python logging: use milliseconds in time format


code: max(c+f for (a,b,c),(d,e,f) in your_list)

rawDescription: Return min/max of multidimensional in Python?


code:
import collections, itertools
q = collections.deque(xrange(10, 20))
q
list(itertools.islice(q, 3, 7))

rawDescription: Use slice notation with collections.deque


code:
from collections import defaultdict
payperday = defaultdict(lambda: 10, {'Sunday': 20})
print(sum(payperday[day] * hours[day] for day in daysofweek))

rawDescription: Python: nested loops not behaving how I want them to


code: data

rawDescription: Defining a list of values for a dictionary key using an external file


code:
parts = (t[0:4], t[4:8], t[8:12], t[12:16])

# or as a function
def grouper2(n, lst):
    return [t[i:i+n] for i in range(0, len(t), n)]

rawDescription: Spliting a long tuple into smaller tuples


code:
known_tags = (
    (1, 'Choice 1'), (2, 'Choice 2'), (3, 'Choice 3'),
    (4, 'Choice 4'), (5, 'Choice 5'))

class MyForm(django.forms.Form):
    tags = django.forms.MultipleChoiceField(choices=known_tags, required=True)

rawDescription: Django array value in a form

description: Django array value in a form


code: s = s.sortlevel([0,1])

rawDescription: Filter by rank of one index level in Pandas?


code:
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']
['this is a foo', 'this is a bar']

rawDescription: Python multiprocessing in objects

description: Python multiprocessing in objects


code:
class MyClass:
    def set_child(self,child = None):
        # I prefer to make child optional for ease of use.
        child = MyClass() if child is None else child
        self.child=child

mc=MyClass()
mc.set_child()

rawDescription: create instance of a class in the same class's definition in python

description: Create instance of a class in the same class's definition in python


code: plt.bar(bin_edges[:-1], total, width=1)

rawDescription: How to build (or precompute) a histogram from a file too large for memory?

description: Build (or precompute) a histogram from a file too large for memory


code:
from numpy import isnan
result = ~isnan(arr_a) * ~isnan(arr_b)

rawDescription: create mask of non-nan matrix intersections

description: Create mask of non-nan matrix intersections


code:
content ="'Yoda' :"
if not content.endswith(':'):
    content=''
else:
    pass

rawDescription: python regex not ending with some characters

description: Python regex not ending with some characters


code:
cherrypy.config.update(
    {'server.socket_host': '10.149.4.240' } ) # Pub IP
cherrypy.quickstart()

rawDescription: Python (CherryPy) web app deployed locally, but not visible over intranet


code:
window.phones
window.rates
window.discounts
window.goodies
window.promotions

rawDescription: Issue with extracting data from a javascript structure on a website using beautiful soup in Python


code: b

rawDescription: Doubling the matrix in numpy

description: Doubling the matrix in numpy


code: n_grams = CountVectorizer(min_n=1, max_n=5)

rawDescription: Python List of Ngrams with frequencies

description: Python List of Ngrams with frequencies


code: df = pd.read_excel('Workbook1.xlsx', header=None)

rawDescription: pandas.read_excel, first row values

description: Pandas.read_excel, first row values


rawDescription: Add values to one column of a pandas dataframe based on the values in another


code: elems = list(allnext(comment))

rawDescription: Split html document in pieces parsing html comments with BeautifulSoup


code:
mystring = "Hello world, how how are you doing today"
words = mystring.split()
mydict = {}
for word in words:
    if word in mydict:
        mydict[word] += 1
    else:
        mydict[word] = 1

print(mydict['how'])

rawDescription: I am relatively new to Python, I was wondering how to see if two words in a string are the same like this:


rawDescription: Find last occurrence of any item of one list in another list in python


code:
class BeforeAfterLoader(unittest.TestLoader):
    def loadTestsFromTestCase(self, testCaseClass):
        self.suiteClass = BeforeAfterSuite
        suite = unittest.TestLoader.loadTestsFromTestCase(self, testCaseClass)
        self.suiteClass = unittest.TestLoader.suiteClass
        return suite

rawDescription: How can I create a class-scoped test fixture in pyUnit?

description: Create a class-scoped test fixture in pyUnit


rawDescription: Is there a way to write a Python script that creates and executes code?


code: type(f)

rawDescription: Is a Python function stored as an object?


code:
r = parent.delay()
r.state

rawDescription: What is the life cycle of celery's parent tasks?


code:
from test import *

a = make_example()

print(a)
a.wibble = 1234567
a.baz()

dump_example(a)

a.baz()

print(bool(a))
print(bool(FooUniquePtr(None)))

b=a.release()
print(b)

rawDescription: How to handle unique_ptr's with SWIG

description: Handle unique_ptr's with SWIG


code:
from binary16 import binary16
binary16(0.006534)
binary16(-.1232)

rawDescription: Floating point to 16 bit Twos Complement Binary, Python


code:
def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

rawDescription: Set products in Python

description: Set products in Python


rawDescription: Python: convert date from string to number


rawDescription: PyQt5 QTextEdit auto completion

description: PyQt5 QTextEdit auto completion


code: np.all(res1[np.lexsort(res1.T), :] == res3)

rawDescription: Possible to add numpy arrays to python sets?


code:
func = lambda x: h(g(f(x)))
func(4)

rawDescription: Chaining operations in Python

description: Chaining operations in Python


code:
np.argwhere((image > threshold).any(-1))
image[0,1]
image[1,1]
image[1,2]

rawDescription: Thresholded pixel indices of a NumPy array


code: a = [int(x) for x in input().split()]

rawDescription: Get a list of numbers as input from the user


code:
np.float is float
np.complex is complex

rawDescription: Why numpy.double applies to a nested list and numpy.complex doesn't?


code:
[('param x', '<field_body><paragraph>some parameter</paragraph></field_body>'),
 ('type x', "<field_body><paragraph>and it's type</paragraph></field_body>"),
 ('return', '<field_body><paragraph>Some text</paragraph></field_body>'),
 ('rtype', '<field_body><paragraph>Return type</paragraph></field_body>')]

rawDescription: Parse sphinx like documentation

description: Parse sphinx like documentation


code:
pd.set_option('display.expand_frame_repr', False)
pd.set_option('display.max_columns', 99)
pd.set_option('display.float_format', '%.12f')

rawDescription: Python Pandas to_csv method formatting

description: Python Pandas to_csv method formatting


code:
# contents of test_Foo.py
def test_Foo(param):
    foo = Foo(param)
    # test foo

rawDescription: Py.Test with configuration files

description: Py.Test with configuration files


code:
import pandas as pd
import numpy as np

df= pd.DataFrame.from_csv('sample.csv')

resamp = df.groupby(['event','user']).resample('W', how='sum')

rawDescription: extracting downsampled timeseries from a normalised csv using pandas

description: Extracting downsampled timeseries from a normalised csv using pandas


code: os.path.relpath(Fullpath, TempPath)

rawDescription: Easiest way to get a specific section of a file path


code:
from collections import defaultdict
import django_tables2 as tables

def merge_table_dicts(labels, tables, key_column):
    merged_tables = []
    for table, label in zip(tables, labels):
        new_table = []
        for row in table:
            new_row = {}
            for key, value in row.iteritems():
                if key == key_column:
                    new_row[key] = value
                else:
                    new_row[old_key + '_' + label] = value
            new_table.append(new_row)
        merged_tables.append(new_table)
    d = defaultdict(dict)
    for l in merged_tables:
        for elem in l:
            d[elem[key_column]].update(elem)
    merged_table_dicts = d.values()
    return merged_table_dicts

def get_merged_table(labels, tables_dicts, key_column_name, merged_columns_order):
    attrs = {}
    # General options
    class Meta:
        order_by = (key_column_name,)
        template = '_merged_table.html'
        empty_text = 'No data presented'
    attrs['Meta'] = Meta
    attrs[key_column_name] = tables.Column()
    for column in merged_columns_order:
        for label in labels:
            attrs[get_merged_key(column, label)] = tables.Column(verbose_name=label)
    merged_table = type('MergedTable', (tables.Table,), attrs)
    merged_columns = []
    for merged_column_name in merged_columns_order:
        column = tables.Column(verbose_name=merged_column_name,
                               attrs={"th": {"rowspan": len(labels)}})
        merged_columns.append(column)
    merged_table.merged_columns = merged_columns

    # Merge data for table
    data = merge_table_dicts(labels, tables_dicts, key_column_name)
    return merged_table(data)

rawDescription: Django-tables2 render merged tables

description: Django-tables2 render merged tables


code:
RE = re.compile(u'[⺀-⺙⺛-⻳⼀-⿕々〇〡-〩〸-〺〻㐀-䶵一-鿃豈-鶴侮-頻並-龎]', re.UNICODE)
nochinese = RE.sub('', mystring)

rawDescription: Find all Chinese text in a string using Python and Regex


code: df['Y'] = df['index'].where(df['X'] == 'A').ffill()

rawDescription: find previous max index in data frame with conditional statement

description: Find previous max index in data frame with conditional statement


code:
bg_subtractor = cv2.BackgroundSubtractorMOG()
default_bg = cv2.imread(IMAGE_FILENAME_FORMAT % 119)
bg_subtractor.apply(default_bg, None, 1.0)

rawDescription: Counting Cars OpenCV + Python Issue

description: Counting Cars OpenCV + Python Issue


code:
def ngrams(input, n):
  input = input.split(' ')
  output = {}
  for i in range(len(input)-n+1):
    g = ' '.join(input[i:i+n])
    output.setdefault(g, 0)
    output[g] += 1
  return output

ngrams('a a a a', 2) # {'a a': 3}

rawDescription: Computing N Grams using Python

description: Computing N Grams using Python


code:
from django import template
register = template.Library()

@register.filter
def get_field_value(obj, field_name):
    return getattr(obj, field_name, None)

@register.filter
def get_verbose_name(obj, field_name):
    return obj._meta.get_field(field_name).verbose_name

register.tag('get_verbose_name', get_verbose_name)
register.tag('get_field_value', get_field_value)

rawDescription: django: looping or iterating over fields, name and verbose_name

description: Django: looping or iterating over fields, name and verbose_name


code:
data = np.genfromtxt(
    fname,
    names = True, #  If `names` is True, the field names are read from the first valid line
    comments = '#', # Skip characters after #
    delimiter = '\t', # tab separated values
    dtype = None)  # guess the dtype of each column

rawDescription: Numpy genfromtxt - column names

description: Numpy genfromtxt - column names


code:
find_letter("apple")
(['a'], 'pple')

rawDescription: Append/pop specific element of a string to the list when iterating over it


code:
test = {'a': (1, 2, None), 'b':(2, 3, '')}
all(elem[2] in ('', None) for elem in test.values())
test['c'] = (1, 2, 3)
all(elem[2] in ('', None) for elem in test.values())

rawDescription: evaluating values of a dictionary

description: Evaluating values of a dictionary


rawDescription: Regex : match a string containing only one alphabet


code:
df
df['e'].iloc[-1]

rawDescription: obtaining last value of dataframe column without index

description: Obtaining last value of dataframe column without index


rawDescription: How can i use multiple lists as arguments in a function and receive them differently?

description: Use multiple lists as arguments in a function and receive them differently


code:
frame = {}
for idx, df in enumerate(dflist):
    n = idx+1  # Since lists are 0-indexed
    name = "df{0:d}.Close".format(n)
    close = df["Close"]
    frame[name] = close

rawDescription: Merging multiple, unaligned data-frames into single pandas data-frame


code:
#app/models.py
from django.contrib.postgres.fields import JSONField
class Something(models.Model):
    name = models.CharField(max_length=32)
    data = JSONField(db_index=True)

rawDescription: Django dynamic model fields

description: Django dynamic model fields


code: 0 if lett == ' ' else ord(lett) - 96

rawDescription: Replacing spaces by 0's in an array (Python)


rawDescription: Gathering multiple multiple lists together


rawDescription: Forms not getting submitted with MECHANIZE in PYTHON!


code:
c = 1
#do my stuff
while c < 20:
    if c == 1:
        logging.debug(line.split(PID_ANDROID)[c])
        c = + 2
    else:
        logging.debug('Moving on to a refresh')
    # You do not incremennt c
    # c += 2 should go here to increment every time

rawDescription: while loop calling array outside

description: While loop calling array outside


code:
def rotT(T, g):
    gg = np.outer(g, g)
    gggg = np.outer(gg, gg).reshape(4 * g.shape)
    axes = ((0, 2, 4, 6), (0, 1, 2, 3))
    return np.tensordot(gggg, T, axes)

rawDescription: Fast tensor rotation with NumPy

description: Fast tensor rotation with NumPy


code:
in_fh  = open('input', 'r')
out_fh = open('output', 'w')
subprocess.check_call("script.pl", stdin=in_fh, stdout=out_fh)

rawDescription: Running a perl script in python and storing the output in a file


code:
for y in range(height):
    for x in range(width):
        greypix[x,y] = min(255, max(255 + impix[x,y][0] - whitepix[x,y][0], 255 + impix[x,y][7] - whitepix[x,y][8], 255 + impix[x,y][9] - whitepix[x,y][10]))

rawDescription: What processing steps should I use to clean photos of line drawings?


code:
mask = (df['action'] == 'sell') & (df['action'].shift(-1) != 'sell')
# In [229]: mask
# Out[229]:
# 0    False
# 1    False
# 2    False
# 3     True
# 4    False
# 5     True
# Name: action, dtype: bool

rawDescription: Insert rows according to value of columns in pandas dataframes


code:
df2 = df.reset_index().groupby(['Name', 'Purchase']).count().unstack('Purchase').fillna(0)
df2.columns = df2.columns.droplevel(0)
totals = df2.sum(axis=1)
totals.name = 'tot-purchases'
df3 = df2.divide(df2.sum(axis=1), axis=0)
df2.columns = ['num-'+x for x in df2.columns]
df3.columns = ['percent-'+x for x in df3.columns]
dff = pd.concat([totals, df2, df3], axis=1)
print(dff)
print(dff.loc[:,('tot-purchases', 'num-apple', 'percent-apple')])

rawDescription: Generating Count Table in Python pandas

description: Generating Count Table in Python pandas


code:
def update(self, dt):
    self.ser.read()  # Not sure if you're deliberately or accidentally reading twice
    data = self.ser.read()
    self.add_widget(Label(text=str(data)))

rawDescription: Using while loop in Pycharm and Kivy

description: Using while loop in Pycharm and Kivy


code:
def longest_words(targets):
    targets = targets.split()
    max_len = max(len(item) for item in targets)
    return set(item for item in targets if len(item) == max_len)

rawDescription: Longest word in sentence, potential equality of lengths


code:
import maya.standalone
maya.standalone.initialize("Python")

import maya.cmds as cmds
cmds.loadPlugin("Mayatomr") # Load all plugins you might need

rawDescription: use external python script to open maya and run another script inside maya

description: Use external python script to open maya and run another script inside maya


code:
df3 = pd.DataFrame(np.arange(6).reshape(3,2))
df3.query('columns >= 1')

rawDescription: What's the meaning of keyword 'columns' in pandas query method?


code:
from ctypes import c_longlong as ll
ll(2 ** 63 - 1)
ll(2 ** 63)
ll(2 ** 63).value

rawDescription: Python type long vs C 'long long'

description: Python type long vs C 'long long'


code:
from lxml import html

def itertext(root, handlers=dict(ul=lambda el: (list(el.itertext()),
                                                el.tail))):
    if root.text:
        yield root.text
    for el in root:
        yield from handlers.get(el.tag, itertext)(el)
    if root.tail:
        yield root.tail

print(list(itertext(html.fromstring(
                "text0text1

item1
"
                "
item2

text2sib"))))

rawDescription: Python, lxml - access text

description: Python, lxml - access text


rawDescription: character responding to key on keyboard, and being moved accross the map and other functions?

description: Character responding to key on keyboard, and being moved accross the map and other functions


code:
def get(self):
    if not self.session['username']:
        return redirect('/login')

rawDescription: Creating restricted pages in google app engine


rawDescription: Sorting/Combining a list of lists

description: Sorting/Combining a list of lists


code: grpdA.get_group('a1').B.tolist()  # leave off `.tolist()` to get a series

rawDescription: Output pandas grouped dataframe without aggregation


code: [i.strip() for i in re.split(r'[+-]',s2)]

rawDescription: re.split('[+ -]',f) or better stepping to partial derivatives

description: Re.split('[+ -]',f) or better stepping to partial derivatives


rawDescription: Binary storage of floating point values (between 0 and 1) using less than 4 bytes?


code:
from datetime import datetime, timedelta

class CPUMonitor(FigureCanvas):
    """Matplotlib Figure widget to display CPU utilization"""
    def __init__(self):
        ...
        self.timeStamp=[]
        ...

rawDescription: matplotlib axes formatting

description: Matplotlib axes formatting


code:
from scipy import special as sp
sphj = sp.specfun.sphj

import ctypes
addr = ctypes.pythonapi.PyCObject_AsVoidPtr(ctypes.py_object(sphj._cpointer))

rawDescription: Vectorized spherical bessel functions in python?


code:
# This prevents Nose from seeing them as tests after the loop is over.
passer = None
failer = None

rawDescription: Run specific Django tests (with django-nose?)


code:
from shapely.geometry import Polygon
from shapely.affinity import affine_transform

poly = Polygon(pts)

# rearrange the coefficients in the order expected by affine_transform
matrix = (a, b, d, e, xoff, yoff)

polyp = affine_transform(poly, matrix)
print(polyp.wkt)

rawDescription: affine_transform xy coords from gda94

description: Affine_transform xy coords from gda94


code:
variable = [None]*2
x = 0
variable[x] = 4
x = 1
variable[x] = 7
print(variable[0])
print(variable[1])

rawDescription: How to create continuously changing variables in Python

description: Create continuously changing variables in Python


rawDescription: Using .pth files

description: Using .pth files


code:
keyorder = {k:v for v,k in enumerate(['ZT21', '10', 'WX21', 'UM', '5', '2'])}
OrderedDict(sorted(d.items(), key=lambda i:keyorder.get(i[0])))

rawDescription: Custom Sorting Python Dictionary

description: Custom Sorting Python Dictionary


code:
class Matrix(object):
    def __init__(self):
        self.m = [[row + col/10. for col in range(4)] for row in range(4)]
    def __getitem__(self, idx):
        if isinstance(idx, (numbers.Integral, slice)):
            idx = (idx, slice(None, None, None))
        elif len(idx) == 1:
            idx = (idx[0], slice(None, None, None))
        rowidx, colidx = idx
        rowslice, colslice = True, True
        if isinstance(rowidx, numbers.Integral):
            rowidx, rowslice = slice(rowidx, rowidx+1), False
        if isinstance(colidx, numbers.Integral):
            colidx, colslice = slice(colidx, colidx+1), False
        ret = self.m[rowidx][colidx]
        if not colslice:
            ret = [row[0] for row in ret]
        if not rowslice:
            ret = ret[0]
        return ret

rawDescription: Implementing 2D slicing in Python

description: Implementing 2D slicing in Python


code: {{ model_class.objects.count }}

rawDescription: Django dynamic name values in model overview on admin site


code: new_y_val = skew(x_values, p[0], p[1], p[2])

rawDescription: Plotting resulting fitted curve with scipy


code:
a=["file1","file2","file3","file1","file2","file1","file5"]
seen=set()
for file in a:               #you can iterate over a list itself
    if file not in seen:     #if file is not in the set then write
       file_name= '%s.txt' %(file)
       file_write= open('%s'%(file_name),'w')
       seen.add(file)  #add file to seen

rawDescription: Writing files only once

description: Writing files only once


rawDescription: Saving output of a for-loop to file

description: Saving output of a for-loop to file


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

# Evaluate an existing colormap from 0.5 (midpoint) to 1 (upper end)
cmap = plt.get_cmap('gist_earth')
colors = cmap(np.linspace(0.5, 1, cmap.N // 2))

# Create a new colormap from those colors
cmap2 = LinearSegmentedColormap.from_list('Upper Half', colors)

y, x = np.mgrid[-200:1900, -300:2000]
z = np.cos(np.hypot(x, y) / 100) + 1

fig, axes = plt.subplots(ncols=2)
for ax, cmap in zip(axes.flat, [cmap, cmap2]):
    cax = ax.imshow(z, cmap=cmap, origin='lower',
                    extent=[x.min(), x.max(), y.min(), y.max()])
    cbar = fig.colorbar(cax, ax=ax, orientation='horizontal')
    cbar.set_label(cmap.name)

plt.show()

rawDescription: Matplotlib Half color axis

description: Matplotlib Half color axis


code:
def upperalpha(s):
  return s.isupper() and s.isalpha()
upperalpha('ABC')
upperalpha('ABc')
upperalpha('ABC1')
upperalpha('ABC DEF')
upperalpha('ABCDEF')
upperalpha('ABCDEF!')

rawDescription: How to only allow capital letters to be input to a variable

description: Only allow capital letters to be input to a variable


rawDescription: Suppressing scientific notation when applying operators to very long decimal numbers using the standard library Decimal


rawDescription: Looking for a Python shorthand way of parsing a url encoded string into tuples


code:
streetno = {}
streetno["1"] = "Sachine Tendulkar"

rawDescription: Hash Map in Python

description: Hash Map in Python


code:
for item in listWidget.selectedItems():
    item.setBackground(QBrush(Qt.yellow, Qt.SolidPattern))

rawDescription: Is it possible to highlight (not select) multiple rows in QListWidget?? (Python/PyQt)


code: Root.option_add("*Entry.Width", 5) #10 is default

rawDescription: set Tkinter label widget below entry widget

description: Set Tkinter label widget below entry widget


code:
myspin = [os.path.join(root, file)
          for root, dirs, files in os.walk(mainpath + newspin01)
          for file in files]

rawDescription: Python Tkinter Spinbox dependencies

description: Python Tkinter Spinbox dependencies


rawDescription: storing chr(3) to variable in python output showing junk values

description: Storing chr(3) to variable in python output showing junk values


rawDescription: Get session info and place into a django form


code:
shape = (20,50)
data.shape = shape # where shape is the new shape

rawDescription: represent an index inside a list as x,y in python

description: Represent an index inside a list as x,y in python


code:
for documentNumber in docdictionary:
    for word1location in docdictionary[documentNumber][0]:
        for word2location in docdictionary[documentNumber][1]:
            if abs(word1location - word2location) == 1:
                return documentNumber

rawDescription: comparing python dictionary values

description: Comparing python dictionary values


good: buono

afternoon: pomeriggo

thanks: grazie

rawDescription: converting a list of strings into a tuple

description: Converting a list of strings into a tuple


code:
sample_input = "Process 1234567-89.1234.12431242.12.1234 -  text title and long text description with no assured pattern Process 2234567-89.1234.12431242.12.1234 : chars and more text Process 3234567-89.1234.12431242.12.1234 - more text process 3234567-89.1234.12431242.12.1234 (...)"
m = re.match(r"(Process \d{7}\-\d{2}\.\d{4}\.\d+\.\d{2}\.\d{4}.*?)(?=Process)|(Process \d{7}\-\d{2}\.\d{4}\.\d+\.\d{2}\.\d{4}.*)", sample_input)
m.group(1)       # The first parenthesized subgroup.
m.groups()       # Return a tuple containing all the subgroups of the match, from 1 up to however many groups are in the pattern

rawDescription: Python: How to get string between matches?


rawDescription: Seasonal Adjustment in R or Python

description: Seasonal Adjustment in R or Python


code:
import re, sys, io

def contains_meta(regex):
    stdout = sys.stdout            # remember stdout
    sys.stdout = io.StringIO()     # redirect stdout to string
    re.compile(regex, re.DEBUG)    # compile the regex for the debug tree side effect
    output = sys.stdout.getvalue() # get that debug tree
    sys.stdout = stdout            # restore stdout
    return not all(line.startswith("LITERAL ") for line in output.strip().split("\n"))

rawDescription: How to find if a regex contains non-escaped metacharacters?

description: Find if a regex contains non-escaped metacharacters


code:
myinteger = 212345
number_string = str(myinteger)

rawDescription: Split an integer into digits to compute an ISBN checksum


code:
def quickSort(mylist, start, end):
    if start < end:
        pivotpos = partition(mylist, start, end)
        #print("pos", pivotpos)
        quickSort(mylist, start, pivotpos - 1)
        #print(quickSort(mylist, start, pivotpos - 1))
        quickSort(mylist, pivotpos + 1, end)
        #print(quickSort(mylist, pivotpos + 1, end))

def partition(mylist, left, right):
    pivot = mylist[left]
    pivotpos = left
    currentlow, currenthigh = left + 1, right
    while currentlow <= currenthigh:
        if mylist[currentlow] < pivot:
            mylist[currentlow], mylist[pivotpos] = mylist[pivotpos], mylist[currentlow]
            pivotpos = currentlow
        elif mylist[currentlow] > pivot:
            mylist[currentlow], mylist[currenthigh] = mylist[currenthigh], mylist[currentlow]
            currenthigh = currenthigh - 1
        currentlow = currentlow + 1
    return pivotpos

rawDescription: How to finish off these python functions for a 'quick Sort'?

description: Finish off these python functions for a 'quick Sort'


code:
@app.route('/<path:path>')
@app.route('/')
def admin(path=None):
    return render_template('angular_interface.html')

rawDescription: how to develop a web app with angularjs at client-side and flask at backend?

description: Develop a web app with angularjs at client-side and flask at backend


code:
from config import MEDIA_FOLDER

@app.route('/uploads/<path:filename>')
def download_file(filename):
    return send_from_directory(MEDIA_FOLDER, filename, as_attachment=True)

rawDescription: How do i link to images not in Static folder in flask

description: Link to images not in Static folder in flask


code:
class NumericInput(TextInput):

    def insert_text(self, substring, from_undo=False):
        if not from_undo:
            try:
                int(substring)
            except ValueError:
                return
        super(NumericInput, self).insert_text(substring, from_undo)

rawDescription: Kivy: Is there a "BoundedString" property available for TextInputs?


code:
x = 32
y = 48

for i in range(0,6):

    # Characters
    print('chr:', end='')
    for i in range(x, y):
        print('  ', chr(i), end='')
    print('')  # newline

    # Numbers
    print('asc: ', end='')
    for j in range(x, y):
        print('{:^4}'.format(j), end='')
    print('')  # newline

    # Advance to next row
    x = x + 16
    y = y + 16

rawDescription: How can I fix the spacing of this ASCII table?

description: Fix the spacing of this ASCII table


code:
import numpy as np

ss = np.cumsum(s)  # array with cumulative sum
k = ss.searchsorted(retained_variance*s_sum) # exploit that ss is monotonically increasing

rawDescription: Is there are more pythonic way to write a while loop that only updates a variable?


code:
import scipy.stats as ss
np.random.seed(123)
alpha = 5
loc = 100.5
beta = 22
data = ss.gamma.rvs(alpha, loc=loc, scale=beta, size=10000)
data
fit_alpha, fit_loc, fit_beta = ss.gamma.fit(data)
fit_alpha, fit_loc, fit_beta

rawDescription: How to get log likelihood for exponential and gamma distributions

description: Get log likelihood for exponential and gamma distributions


code:
def _tag_find_or_create(tag_name):
    tag = Tag.query.filter_by(tag_name=tag_name).first()
    return tag or Tag(tag_name=tag_name)

class Book(Base):
    __tablename__ = 'book'
    id = Column(Integer, primary_key=True)
    book_name = Column(String)

    # relationship
    _tags = relationship('Tag', secondary='book_tag')
    tags = association_proxy('_tags', 'tag_name', creator=_tag_find_or_create)

rawDescription: Correct pattern for inserting row in SQLAlchemy


code: data['weighted'] = 0.0

rawDescription: Updating DataFrame Value

description: Updating DataFrame Value


rawDescription: getting the opposite diagonal of a numpy array

description: Getting the opposite diagonal of a numpy array


code:
print(find_base_nbytes(x))
# 8000

print(find_base_nbytes(y))
# 8000

print(find_base_nbytes(z))
# 8000

rawDescription: Size of numpy strided array/broadcast array in memory?


code: song, name = line.strip().split(",")

rawDescription: Can't read file after split line?

description: Can't read file after split line


code:
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (
    "Your User Agent String here . . .")

rawDescription: How to assign to workers a proxy that requires user name - password and a custom user agent?

description: Assign to workers a proxy that requires user name - password and a custom user agent


code:
threshold = .1 # arbitrary: 10%
to_consider = np.logical_and(results[:,6] < threshold, results[:,11] < threshold)
table = results[to_consider][:, [0,1,2,3,4,5,7,8,9,10]]

rawDescription: How can I assign scores to a list of datapoints and then output values > 2 standard deviations from the mean in python?

description: Assign scores to a list of datapoints and then output values > 2 standard deviations from the mean in python


code:
groups = re_fn.match(fileName).groupdict()
# do stuff with groups['T'], groups['M'], groups['Dt'], groups['H']

rawDescription: Python: iterating by match to regex

description: Python: iterating by match to regex


code: x, y = service(x, y, z)

rawDescription: trying to call a string that is assigned within a function

description: Trying to call a string that is assigned within a function


code:
import asyncio

loop = asyncio.get_event_loop()
loop.run_until_complete(foo())
loop.close()

rawDescription: How to use async/await in Python 3.5?

description: Use async/await in Python 3.5


code:
def _run_finalizers(minpriority=None):
    '''
    Run all finalizers whose exit priority is not None and at least minpriority

    Finalizers with highest priority are called first; finalizers with
    the same priority will be called in reverse order of creation.
    '''

rawDescription: Context managers and multiprocessing pools


code:
import requests
from bs4 import BeautifulSoup as BS
for page in range(1, 7):
    r = requests.post('http://money.rediff.com/indices/bse/bsesmallcap',
                      data={'currentPageNo': page, 'RowPerPage': 100})
    soup = BS(r.text)
    table = soup.find(class_='dataTable')
    # Add table information to whatever output you plan to use

rawDescription: How to webscrape this website

description: Webscrape this website


code:
for i in reflist:
    subprocess.call('open ' + '%s' % i, shell = True)

rawDescription: Python: Adding Variable paths into os.system("open"+filename)


code:
from collections import Iterable
_typetest = lambda t: isinstance(t, Iterable) and not isinstance(t, basestring)
def flattenlen(a):
    return sum(flattenlen(i) if _typetest(i) else 1 for i in a)

flattenlen([[[[1, 2], [3, 4]], 5], [6, 7]])
flattenlen([([[1, 2], [3, 4]], 5), {6, 7, 'foobar'}])

rawDescription: Retrieving the length of a list after flattening


code:
def home(request):
    data = []
    if request.POST:
        username = request.POST.getlist('username')
        email = request.POST.getlist('email')
        data = [{'username': u, 'email': e} for u, e in zip(username, email)]
        return render_to_response('data.html', locals(),
            context_instance=RequestContext(request))
    return render_to_response('index.html', locals(),
            context_instance=RequestContext(request))

rawDescription: Global Variable Django

description: Global Variable Django


code:
myWidgets = [button1, label1, ... ] # List of widgets to change colour
for wid in myWidgets:
    wid.configure(bg = newColour)

rawDescription: How to change the colour of everything in a tkinter GUI at once

description: Change the colour of everything in a tkinter GUI at once


rawDescription: scipy sparse matrices as an input for petsc4py

description: Scipy sparse matrices as an input for petsc4py


code:
from datetime import timedelta, datetime

month, year = 2, 2008

day = timedelta(days=1)
date1 = datetime(year, month, 1)
d = date1
dates = []
while d.month == month:
    dates.append(d.strftime('%Y-%m-%d'))
    d += day

rawDescription: Generate dates for a particular month?

description: Generate dates for a particular month


code:
def __str__(self):
    s  = "Name:    %s\n" % self.namn
    s += "Price:   %s\n" % self.pris
    s += "Quantity:%s\n" % self.antal
    s += "Code:    %s\n" % self.kod

rawDescription: function and classes, usage of __str__

description: Function and classes, usage of __str__


code:
import dateutil.parser as DP
observationTime = DP.parse('Sat, 13 Dec 2014 13:52:00 -0500')
# datetime.datetime(2014, 12, 13, 13, 52, tzinfo=tzoffset(None, -18000))

rawDescription: Date parsing and formating in Python 2.7


code:
import dbus, sys

bus = dbus.SystemBus()
m_proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager")
manager = dbus.Interface(m_proxy, "org.freedesktop.NetworkManager")
mgr_props = dbus.Interface(m_proxy, "org.freedesktop.DBus.Properties")

s_proxy = bus.get_object("org.freedesktop.NetworkManager", "/org/freedesktop/NetworkManager/Settings")
settings = dbus.Interface(s_proxy, "org.freedesktop.NetworkManager.Settings")

active = mgr_props.Get("org.freedesktop.NetworkManager", "ActiveConnections")
for a in active:
    a_proxy = bus.get_object("org.freedesktop.NetworkManager", a)
    a_props = dbus.Interface(a_proxy, "org.freedesktop.DBus.Properties")
    name = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Id")
    vpn = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Vpn")
    print('Name: %s; vpn?: %s' % (name, vpn))

    # to get even more data
    #connection_path = a_props.Get("org.freedesktop.NetworkManager.Connection.Active", "Connection")
    #c_proxy = bus.get_object("org.freedesktop.NetworkManager", connection_path)
    #connection = dbus.Interface(c_proxy, "org.freedesktop.NetworkManager.Settings.Connection")
    #settings = connection.GetSettings()
    #print("%s (%s)" % (name, settings['connection']))

rawDescription: Getting Connected VPN Name in Python

description: Getting Connected VPN Name in Python


rawDescription: mixing 3 dimenional and 2 dimensional data in a pandas dataframe

description: Mixing 3 dimenional and 2 dimensional data in a pandas dataframe


code:
class Bill:
    def __init__(self, check, tax, tip):
        self.check = check
        self.tax = tax
        self.tip = tip

    def percent(self):
        self.tax = self.tax/100
        self.tip = self.tip/100

    def calculate(self):
        self.percent()
        self.result_1 = self.check + (self.check * self.tax)
        self.result_final = self.result_1 + (self.result_1 * self.tip)
        self.difference = self.result_final - self.result_1
        self.advice = (self.result_1, "is your check with tax added.",
                       self.difference, "is how much tip you need to pay.",
                       self.result_final, "is your total.")
        return self.advice

bills = []
while True:
    choice = input("Do you want to calculate for another person?")
    if choice.lower().startswith("y"):
        break
    bill = Bill(float(input("Check: ")), float(input("Tax: ")),
                float(input("Tip: ")))
    bill.calculate()
    print(*bill.advice)
    bills.append(bill)

rawDescription: How would I make a loop that creates instances in python 3?


code:
# 2D-arrays from DataFrame
x1 = np.linspace(df['x'].min(), df['x'].max(), len(df['x'].unique()))
y1 = np.linspace(df['y'].min(), df['y'].max(), len(df['y'].unique()))

"""
x, y via meshgrid for vectorized evaluation of
2 scalar/vector fields over 2-D grids, given
one-dimensional coordinate arrays x1, x2,..., xn.
"""

x2, y2 = np.meshgrid(x1, y1)

# Interpolate unstructured D-dimensional data.
z2 = griddata((df['x'], df['y']), df['z'], (x2, y2), method='cubic')

# Ready to plot
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(x2, y2, z2, rstride=1, cstride=1, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Meshgrid Created from 3 1D Arrays')

plt.show()

rawDescription: How to surface plot/3d plot from dataframe?

description: Surface plot/3d plot from dataframe


code: import this

rawDescription: Getting the row index for a 2D numPy array when multiple column values are known


code:
import subprocess as sp

svn_url = "svn://repo-path.com/project"
revisions = [12345, 12346]
revision_clargs = ["-r%i" % revision for revision in revisions]
popen = sp.Popen(["svn", "log", "-v"] + revision_clargs + [svn_url],stdout=sp.PIPE,stderr=sp.PIPE)
out,err = popen.communicate()

rawDescription: Finding the modules where changes were checked with svn


code:
import random

my_list = [1, 2, 3, 4, 5]
n = len(my_list)

for _ in xrange(30):
  start = random.randint(1, n-2)
  a = my_list[start:]

rawDescription: renaming a variable in loop using Jython

description: Renaming a variable in loop using Jython


code: d = dict( self.arguments.values_list('key', 'value') )

rawDescription: Why is Django reverse() failing with unicode?


code:
from matplotlib.mathtext import math_to_image
math_to_image("$\\alpha$", "alpha.png", dpi=1000, format='png')

rawDescription: How can I use matplotlib's mathtext rendering outside of matplotlib in another tk widget?

description: Use matplotlib's mathtext rendering outside of matplotlib in another tk widget


code:
[
  "/hostedservices/services/tenant/(?P<id>[a-zA-Z0-9_]+)/?$",
  "<class 'sysinfo.hostedservices.ServicesTenantHandler'>"
],
[
  "/hostedservices/services/(?P<id>[a-zA-Z0-9_]+)/?$",
  "<class 'sysinfo.hostedservices.ServicesIdHandler'>"
]

rawDescription: Tornado python REST api with multiple handlers but same parameter types


rawDescription: Exponential Fit Between 2 Lists

description: Exponential Fit Between 2 Lists


rawDescription: Indexing and printing tuples

description: Indexing and printing tuples


rawDescription: python dictionary parsing using format and get new data

description: Python dictionary parsing using format and get new data


code: ret_dict = {}

rawDescription: Python - Convert JSON object data into a List


code:
_mapping = {}

def register(f):
    _mapping[f.__name__] = f
    return f

@register
def _and(*args):
    return lambda context: reduce(operator.and_,
                                  [arg(context) for arg in args], True)

@register
def _tautology(*_):
    return lambda *_: True

rawDescription: function_exists in PHP for python3

description: Function_exists in PHP for python3


code:
myconditions  = [
    (lambda i: i > 0.5, "greater than 0.5"),
    (lambda i: i == 5, "it is equal to 5"),
    (lambda i: i > 5 and i < 6, "somewhere between 5 and 6"),
]

rawDescription: How to map a series of conditions as keys in a dictionary?

description: Map a series of conditions as keys in a dictionary


code:
import dis

def foo():
  a = 2

dis.dis(foo)

rawDescription: Python Id call on an uninstantiated object


code:
first.__getitem__(('monkey', 1))
first.__getitem__(('cat', 3))

rawDescription: Dictionary value sorting

description: Dictionary value sorting


code:
vname = 'chr3'
list_I_want = globals()['LIST_'+vname]

rawDescription: Choose list according to list name which is variable in python


rawDescription: How to group by a range of values in pandas?

description: Group by a range of values in pandas


code:
class structtype():
    pass

rawDescription: Complex matlab-like data structure in python (numpy/scipy)


rawDescription: Implementation of numpy in1d for 2D arrays?


rawDescription: python 3 print generator

description: Python 3 print generator


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

plt.scatter([1, 2, 3], [1, 2, np.nan])
plt.show()

rawDescription: Draw / Create Scatterplots of datasets with NaN


rawDescription: Basic celery task function call from inside a django function


code:
A = ['A', 'B', 'C']
B = [24]
import itertools
list(zip(itertools.cycle(B), A))

rawDescription: Merge lists with different size. Fill with smallest


code:
from Tkinter import *
from tkB import Right # bring in the class Right from secondary script

class Left(Frame):
    '''just a frame widget with a white background'''
    def __init__(self, parent):
        Frame.__init__(self, parent, width=200, height=200)
        self.config(bg='white')

if __name__ == "__main__":
    # if this script is run, make an instance of the left frame from here
    # and right right frame from tkB
    root = Tk()
    Left(root).pack(side=LEFT) # instance of Left from this script
    Right(root).pack(side=RIGHT) # instance of Right from secondary script
    root.mainloop()

rawDescription: How to Open Multiple Tkinter windows in one window


code: re.split('\^A', line)

rawDescription: re.split not working on ^A

description: Re.split not working on ^A


code:
server_list, bad_email = ["gmail.com", "yahoo.com"], []
if any(emailaddress.endswith(server) for server in server_list):
    bad_email.append(emailaddress)

rawDescription: Python: check if string is in any items in a list?


code:
for row in result['rows']:
    job, count = (col['v'] for col in row['f'])
    print_two_cols(job, count)

rawDescription: parse through JSON

description: Parse through JSON


code:
@FuncOperations
def f(x):
    return x + 1

@FuncOperations
def g(x):
    return x + 2

rawDescription: product of two functions

description: Product of two functions


code:
np.random.seed(2015)
A = np.random.random((10,2))
A
np.std(A - A.mean(axis=0))

rawDescription: calculating 2D rms in python

description: Calculating 2D rms in python


rawDescription: Efficiently re-shaping a numpy ndarray from 2-D to 3-D based on elements from 2-D


code: self.files = set(self.options.get('--files', "").split(",")) ^ set(['']) or None

rawDescription: In Python, what is a minimal way of assigning a value to a variable depending on whether a dictionary contains a key?


rawDescription: Get MM-DD-YYYY from pandas Timestamp

description: Get MM-DD-YYYY from pandas Timestamp


rawDescription: How to make my code calculate q2-LOO faster?

description: Make my code calculate q2-LOO faster


code:
func_to_run = getattr(other_module, ran_test_opt)
func_to_run()

rawDescription: Convert string into a function call

description: Convert string into a function call


code:
import string
alphaDict = dict.fromkeys(string.ascii_lowercase,0)
alphaDict

rawDescription: Convert every character in a String to a Dictionary Key


code:
# Testing code
if __name__ == '__main__':

    circle = Circle(x=3, y=4, r=5)
    print('circumference', circle.circumference)

    print('try setting circumference')
    circle.circumference = 12.5

rawDescription: Using descriptor class to raise RuntimeError when user tries to change object's value


code: lm = sns.lmplot("length", "speed", data=subdf, fit_reg=True)

rawDescription: y-axis scaling in seaborn vs pandas

description: Y-axis scaling in seaborn vs pandas


code:
def move():
    app.hello_b.place(x=100, y=100)
root.after(1000, move)

rawDescription: Background image using Tkinter - Python 2.7


code:
from random import randint

myList = ['a', 'b', 'c']
myOtherList = [1, 2, 3]

index = randint(0, len(myList)-1)

del myList[index]
del myOtherList[index]

rawDescription: Removing an element from a list and a corresponding value


code: firstline = "Log Created: {}/nLog deleted and recreated.".format(grab_date)

rawDescription: Writing variables with .write() Python 3


code: a[np.arange(3)[:,None], inds]

rawDescription: Index 2D numpy array by a 2D array of indices without loops


code: newList = sorted(alist, key=lambda x: (int(x[1]), int(x[2])))

rawDescription: Python3 - Change the type of specific list elements


code:
def _contents(items, laplace=False):
    # count occurrences of values
    counts = {}
    for item in items:
        counts[item] = counts.get(item,0) + 1.0
    # normalize
    for k in counts:
        if laplace:
            counts[k] += 1.0
            counts[k] /= (len(items)+len(counts))
        else:
            counts[k] /= len(items)
    return counts

rawDescription: Laplacian smoothing to Biopython

description: Laplacian smoothing to Biopython