code:
import datetime
TimeStart = datetime.datetime(2014, 6, 30, 13, 23, 46)
TimeEnd = datetime.datetime.now()
TimeEnd
def getTimeDifferenceFromNow(TimeStart, TimeEnd):
    timeDiff = TimeEnd - TimeStart
    return timeDiff.total_seconds() / 60

getTimeDifferenceFromNow(TimeStart, TimeEnd)

rawDescription: How to get the time difference in minutes in python for time expressed in this format?

description: Get the time difference in minutes in python for time expressed in this format


code:
my_ip_ports = [IpPort.load(dumped_ipport)
               for dumped_ipport in json.loads(dumped_stuff)]

rawDescription: how to convert a list of object to json format in python

description: Convert a list of object to json format in python


code:
s = StringIO()
df.to_csv(s, quoting=2)  # or output to file instead
s.getvalue()

rawDescription: Pandas, to_csv () to a specific format

description: Pandas, to_csv () to a specific format


code:
def initializeVariables(self):
    varnames = ['a', 'b', 'c', 'd']
    self.frames = {}
    self.entries = {}
    for var in varnames:
        self.frames[var] = ttk.Frame(...)
        self.entries[var] = ttk.Entry(...)

rawDescription: Avoid exec in instance variable definition


code: bprev.label="A new Label!" #actually this doesnt work...

rawDescription: Python: Change the label of a matplotlib button on click


code:
def merge_dicts(*dicts):
    d = {}
    for dict in dicts:
        for key in dict:
            try:
                d[key].append(dict[key])
            except KeyError:
                d[key] = [dict[key]]
    return d

rawDescription: Merge dictionaries retaining values for duplicate keys


code:
start = datetime.date(year, 1, 1)
end = datetime.date(year, 12, 31)
query(Foo).filter(Foo.date.between(start, end))

rawDescription: SA: can I have a 'year' column_property for a Date column?


code:
def scale_ratio(ratios: list) -> list:
    sum_ = sum(ratios)
    return [x/sum_ for x in ratios]

def ratio_breakdown_recursive(x: int, ratios: list) -> list:
    top_ratio = ratios[0]
    part = round(x*top_ratio)
    if x <= part:
        return [x]
    x -= part
    return [part] + ratio_breakdown_recursive(x, scale_ratio(ratios[1:]))

def ratio_breakdown(x: int, ratios: list) -> list:
    sorted_ratio = sorted(ratios, reverse=True)
    assert(round(sum(ratios)) == 1)
    sorted_result = ratio_breakdown_recursive(x, sorted_ratio)
    assert(sum(sorted_result) == x)
    # Now, we have to reverse the sorting and add missing zeros
    sorted_result += [0]*(len(ratios)-len(sorted_result))
    numbered_ratios = [(r, i) for i, r in enumerate(ratios)]
    sorted_numbered_ratios = sorted(numbered_ratios, reverse=True)
    combined = zip(sorted_numbered_ratios, sorted_result)
    combined_unsorted = sorted(combined, key=lambda x: x[0][1])
    unsorted_results = [x[1] for x in combined_unsorted]
    return unsorted_results

rawDescription: Subdivide integers using a given ratio without producing floats


code:
import matplotlib.pyplot as plt

#Choose the correct dimensions for your first screen
FMwidth = 1280
FMheight = 1024

#Choose the correct dimensions for your second screen
SMwidth = 1280
SMheight = 1024

fm = plt.get_current_fig_manager()
#Works with QT on linux
fm.window.setGeometry(FMwidth,0,SMwidth,SMheight)

rawDescription: Python on windows, open plot windows next to each other


code: "".join([c for c in filename if c.isalpha() or c.isdigit() or c==' ']).rstrip()

rawDescription: Create (sane/safe) filename from any (unsafe) string


rawDescription: How to change colours of nodes and edges of bipartite graph in networkX?

description: Change colours of nodes and edges of bipartite graph in networkX


code:
cities = ('Boston', 'New York', 'Chicago')
cities_users = dict(map(lambda city: (city, ifilter(lambda u: users[u]['Location'] == city, users)), cities))

rawDescription: Small Tables in Python?

description: Small Tables in Python


code:
import getopt
args = ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
opts, args = getopt.getopt(args, "abc:d")
print ("opts=" + str(opts))
print ("args=" + str(args))
optdic = dict(opts) # convert options to dictionary
print ("optdic['-c'] = " + str(optdic['-c']))

rawDescription: What is the data type returned by getopt in Python


code:
q
np.array(q)
print(repr(np.array(q)))
len(q)
q[1]
q[0]
q[0].value

rawDescription: How to prevent Numpy from splitting up an array-like object

description: Prevent Numpy from splitting up an array-like object


rawDescription: Python multiprocessing.Pool: when to use apply, apply_async or map?


code: min(basket.values(), key=lambda x: x['price']) # {'group': 4, 'name': 'Brisket Beef 400G', 'price': 3.5, 'amount': 3, 'promotion': 'get4pay3', 'unit': 'pieces'}

rawDescription: For a dictionary inside another dictionary how do you sort it by the value and compare different items within the dictionary


rawDescription: Removing length 1 dimensions in arrays

description: Removing length 1 dimensions in arrays


code:
list(tables)
for k,v in tables.items():
    print("table:", k)
    print(v)
    print()

rawDescription: Python Pandas - Read csv file containing multiple tables


code: bar

rawDescription: How to get an attribute of an Element that is namespaced

description: Get an attribute of an Element that is namespaced


code:
pairs = [x.split() for x in s.split('\n') ]
pairs

rawDescription: How to use python to format strings with delimiter into columns

description: Use python to format strings with delimiter into columns


rawDescription: How can I match multiple elements enclosed in corner brackets with python regex?

description: Match multiple elements enclosed in corner brackets with python regex


code:
import array
a = array.array('I', xrange(10**8))  # a.itemsize indicates 4 bytes per element => about 0.5 GB
import random
random.shuffle(a)

rawDescription: Generate big random sequence of unique numbers


code: username = user_email[:30]

rawDescription: django-allauth set username the same as email

description: Django-allauth set username the same as email


code:
import copy
b = copy.deepcopy(a)

rawDescription: Two lists are printing the same thing when I expected them to print differently


code:
query(User).join(User.search_table).\
           filter(Match([UserSearch.x, UserSearch.y], "some value"))

rawDescription: Proper use of MySQL full text search with SQLAlchemy


code:
import pylab

x = [1, 2, 3, 4, 5, 6, 7]
y = [2, 3, 4, 5, 6, 7, 8]

pylab.plot(x, y)
pylab.axhline(0, color="black")
pylab.axvline(0, color="black")

# Here we go:
pylab.xlim(-5, 3)
pylab.ylim(-5, 3)

pylab.show()

rawDescription: Show specific range in graphic

description: Show specific range in graphic


code:
my_prices = [float(price.text.translate(trans_table))
                for price in data.find_all("example", {"class":"example"})]

rawDescription: How to change text to digits and save into array in Python

description: Change text to digits and save into array in Python


rawDescription: Which python re module to pick for translating a perl regular expression


code:
count = collections.Counter()
for line in f:
    count[line] += 1

rawDescription: Summarizing log file to unique entries only


code:
import multiprocessing as mp

logger = mp.get_logger()

def main():
    logger.info('Script is running...')

rawDescription: How to print log messages from external modules to the main Python module's terminal window?

description: Print log messages from external modules to the main Python module's terminal window


code:
a = MyClass(7)
a + 3

rawDescription: Add to custom class in Python

description: Add to custom class in Python


code: zm = z * mask

rawDescription: Using Numpy to Count Numbers in a range

description: Using Numpy to Count Numbers in a range


code: l

rawDescription: Populating a sparse list with random 1's


code:
def update(self):
    self.Odometer = self.Odometer + self.Speed*0.17
    self.Speed = randint(1,121)

rawDescription: Assignment: Python 3.3: add keys and values from dictionary to class


code:
import wx
class oranges(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id, 'TEST',size=(500,500))
        self.frame=wx.Panel(self)

rawDescription: How to call a wxFrame from a different file in wxPython?

description: Call a wxFrame from a different file in wxPython


code:
for w in fromcin():
  dosomething(w)

rawDescription: How to simply read in input from stdin delimited by space or spaces

description: Simply read in input from stdin delimited by space or spaces


code: widget.entryconfig(0, state="disabled")

rawDescription: How to update the state of tkiner menu cascade or command?

description: Update the state of tkiner menu cascade or command


code:
import csv
from collections import namedtuple
try:
    from itertools import imap
except ImportError:  # Python 3
    imap = map

with open("data_file.txt", mode="rb") as infile:
    reader = csv.reader(infile)
    Data = namedtuple("Data", next(reader))  # get names from column headers
    for data in imap(Data._make, reader):
        print(data.foo)
        # ...further processing of a line...

rawDescription: What is the pythonic way to read CSV file data as rows of namedtuples?


code:
import csv

with open('file.txt', 'r') as f:
    next(f) # skip header
    r = csv.reader(f, delimiter=" ")
    d = dict((int(row[0]), map(int,row[1:])) for row in r)
    print(d)

{1: [5, 6, 7], 2: [8, 9, 10]}

rawDescription: Populating dictionary from text file PYTHON


code: Bit_Offset += bits

rawDescription: Understanding bit-manipulation function in Python


code:
p = re.compile(r'[^\w-]+', re.U)
for line in s.split('\n'):
    print(p.split(line+' ')[-2])

rawDescription: Unicode Regex with regex not working in Python


rawDescription: numpy type conversions for arrays vs. scalars

description: Numpy type conversions for arrays vs. scalars


code:
from itertools import combinations

word = "rum"
for x in range(len(word)+1):
    for c in combinations(word,x):
        print ("".join(c))

rawDescription: Reads a word and prints all substrings, sorted by length in Python


code:
lst = []

class AwesomeMeta(type):
    def __new__(metacls, cls, bases, classdict):
        if cls != 'Awesome':
            lst.append(cls)
        return super().__new__(metacls, cls, bases, classdict)

class Awesome(metaclass=AwesomeMeta):
  """This is my magical super class."""

class Stack(Awesome):
  """Awesome does awesome stuff with Inherits."""

class Overflow(Awesome):
    """More awesomely stuff!"""

print(lst)

rawDescription: Do something automatically after class definition?


code:
@route('/hello')
def hello():
    return "Hello World!"

rawDescription: How to use decorators (bottle.py)

description: Use decorators (bottle.py)


code:
@app.route('/<path:url>')
def feature_or_catch(url):
    slug  = url
    if '/' not in slug and slug_in_database(slug):
        return "feature: " + slug
    return "catch: " + url

rawDescription: Skip/pass over view function so the next can execute in Flask


code:
# read data into a data frame
column_names = ['first_column', 'second_column', 'third_column', 'fourth_column']
df = pd.read_csv(data, names=column_names)

# extract values using regular expression which is much more robust
# than string spliting
tmp = df.first_column.str.extract('CODE(\d{2})(\d{2})([A-L]{1})(\d+)')
tmp.columns = ['year', 'day', 'month', 'value']
tmp['month'] = tmp['month'].apply(lambda m: str(ord(m) - 64))

rawDescription: How to split a dataframe column into multiple columns with a Pandas converter

description: Split a dataframe column into multiple columns with a Pandas converter


code:
def fibR(n):
    if n == 1 or n ==2:
        return 1
    return fibR(n-1) + fibR(n-2)

for i in range(1,6):
    print(fibR(i))

rawDescription: Fibonacci series in python 3 displays only final number


code:
#!/usr/bin/env python3

import random
import string

import cherrypy

class Api:

  def __init__(self):
    self.string = String()
    # ...

class String:

  exposed = True

  def GET(self):
    return cherrypy.session.get('mystring', '')

  def POST(self, length=8):
    result = ''.join(random.sample(string.hexdigits, int(length)))
    cherrypy.session['mystring'] = result
    return result

  def PUT(self, new):
    cherrypy.session['mystring'] = new

  def DELETE(self):
    cherrypy.session.pop('mystring', None)

class Token:

  @cherrypy.expose
  def csrf(self):
    crsf = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in range(32))
    cherrypy.session['csrf'] = crsf
    return {'crsf': crsf}

if __name__ == '__main__':
  # global server config
  cherrypy.config.update({
    'server.socket_host' : '0.0.0.0',
    'server.socket_port' : 8080,
  })

  # applicaton config is provided
  cherrypy.tree.mount(Api(), '/api', {
    '/' : {
      'tools.sessions.on' : True,
      'request.dispatch'  : cherrypy.dispatch.MethodDispatcher(),
    },
    '/string' : {
      'tools.response_headers.on'      : True,
      'tools.response_headers.headers' : [('Content-Type', 'text/plain')]
    }
  })

  # applicaton config is provided
  cherrypy.tree.mount(Token(), '/token', {'/' : {
    'tools.sessions.on' : True,
    'tools.json_out.on' : True,
  }})

  cherrypy.engine.signals.subscribe()
  cherrypy.engine.start()
  cherrypy.engine.block()

rawDescription: cherrypy - 'module' object has no attribute session when run with uWSGI

description: Cherrypy - 'module' object has no attribute session when run with uWSGI


rawDescription: lxml iterparse mising child nodes

description: Lxml iterparse mising child nodes


rawDescription: lxml xpath not finding anchor text

description: Lxml xpath not finding anchor text


code:
import gmpy
gmpy.is_square(x**7)
gmpy.is_square(x**7 + 1)

rawDescription: How could I check if a number is a perfect square?


code:
l = []
while True:
    head, tail = os.path.split(filename)
    l.insert(0, tail)
    if head == "/":
        l.insert(0, "")
        break
    filename = head
"/".join(l[:7])

rawDescription: Python: cut equivalent in Python?

description: Python: cut equivalent in Python


code:
db.Tuser.find({'_id':obj_id},
                {'$set':{'state': 2}})

rawDescription: update not working with pymongo

description: Update not working with pymongo


code: plt.hexbin(x, y)

rawDescription: Python - Randomly subsamble a range of points to plot


code:
x
y
thing.x
thing.z

rawDescription: A member tuple (as opposed to member variable) of a class?


code:
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=INSERT IP NUMBER;DATABASE=INSERT DATABASE NAME;UID=INSERT USER NAME;PWD=INSERT PASSWORD')

cursor = cnxn.cursor()

cursor.executemany("insert into tester (car_brands) values (?)",variable_cars)

rawDescription: pyodbc - where to insert data?

description: Pyodbc - where to insert data


code:
from peewee import *

db = SqliteDatabase("newsalmost.db",threadlocals = True)

class Story(Model):
    title = CharField()
    story = TextField()
    date = DateField()
    class Meta:
        database = db

rawDescription: flask peewee not working on web server

description: Flask peewee not working on web server


code:
# Compute parallactic angle using PyEphem.
city = ephem.city( ... )
moon = ephem.moon( city )
parallacticAngle = moon.parallactic_angle()

rawDescription: .parallactic_angle() method in PyEphem

description: .parallactic_angle() method in PyEphem


code:
import itertools
def get_structure_for_node(structure, find_node=1):
    return next(itertools.islice(flat_list(structure), find_node, find_node+1))[1]

rawDescription: How can I find the index for a list of nested lists which I am recursing over?

description: Find the index for a list of nested lists which I am recursing over


code: r = {reduce(lambda x, y : '{0};{1}'.format(x,y), l[j][:3]):{t[0]: t[1] for t in zip(k, l[j])} for j in range(1, len(l))}

rawDescription: Translating a 2D Array to nested dictonary


rawDescription: Merging rows when counting - Django/SQL

description: Merging rows when counting - Django/SQL


code:
df2.loc[:, to_shift] = df2.loc[:, to_shift].shift(1)
df2

rawDescription: For any rows with a NaN in a Pandas DataFrame, shift by 1


code:
import numpy as np
a = np.arange(1, 10)
a.prod()
a = np.arange(1, 10).reshape(3,3)
a.prod(axis=1)

rawDescription: Python equivalent of MATLAB command prod


code: df

rawDescription: pandas dataframe aggregate - why does it return column names?

description: Pandas dataframe aggregate - why does it return column names


code: print({k:[v] for k, v in database.items()})

rawDescription: changing values of a dictionary to a list

description: Changing values of a dictionary to a list


code:
[x for x in lst if isinstance(x, (float, int))]
import numbers
[x for x in lst if isinstance(x, numbers.Number)]

rawDescription: Remove empty element but keep zeros as values


code:
unichr(97)
unichr(1234)

rawDescription: ASCII value of a character in Python

description: ASCII value of a character in Python


rawDescription: Euler's pentagonal number function in python


code: a= myapplication.Application(basedir= '/opt/myapp', site= 'www.example.com', debug= False)

rawDescription: Organizing a large Python project that must share an internal state?


code:
def __init__(self,real=0,imag=0):
    ...

rawDescription: python create a class with complex numbers

description: Python create a class with complex numbers


rawDescription: How can I build a regular expression which has options part

description: Build a regular expression which has options part


rawDescription: Return a list containing the number with most repeats from a list of numbers


code:
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE t (a integer, b integer, c integer)')
col_names = ['a', 'b', 'c']
values = [0, 1, 2]
conn.execute('INSERT INTO t (%s, %s, %s) values(?,?,?)'%tuple(col_names), values)

rawDescription: Python Sqlite3 insert operation with a list of column names


code:
def autodiscover_tasks(self, packages, related_name='tasks', force=False):
    ...

rawDescription: Celery tasks immediately autodiscover

description: Celery tasks immediately autodiscover


rawDescription: set() not removing duplicates

description: Set() not removing duplicates


code: model = LogisticRegression(C=100000, fit_intercept=False)

rawDescription: python logistic regression (beginner)

description: Python logistic regression (beginner)


code: ("".join(x) for x in itertools.permutations("0123456789"))

rawDescription: How to turn the result (in python) of itertools.permutations("0123456789") into list of strings

description: Turn the result (in python) of itertools.permutations("0123456789") into list of strings


code:
from passlib.hash import sha512_crypt

orig = "password"
h = sha512_crypt.encrypt(orig)
print("hash", h)
# h for eg. is $6$rounds=100000$5YnTXatKh4b1pLjp$3QQjVIfjrbiTakj.wkaw1woAcFiPRAjJP2U/b3BiGW4m8OvI8x0tgw1bb63dNQWMUl1uYNDBcTO3tWgrJ6eHh1

okay = sha512_crypt.verify(orig, h)
print("verified", okay)

rawDescription: How can I verify a cryptographic hash created by Python's Passlib using Node.js?

description: Verify a cryptographic hash created by Python's Passlib using Node.js


code:
import base

class Index(base.BaseHandler):
    """ Set the language cookie (if locale is valid), then redirect back to referrer
    """
    def get(self, locale):
        if locale in self.available_locales:
            self.response.set_cookie('locale', locale, max_age = 15724800)  # 26 weeks' worth of seconds

        # redirect to referrer or root
        url = self.request.headers.get('Referer', '/')
        self.redirect(url)

rawDescription: How to decide the language from cookies/headers/session in webapp2?

description: Decide the language from cookies/headers/session in webapp2


code:
words = ['foo', '123', 'foo123']
[word for word in words if not word.isdigit()]

rawDescription: Python list-comprehension for words that do not consist solely of digits


code: x[:, np.newaxis, :] - x

rawDescription: How do I calculate all pairs of vector differences in numpy?

description: Calculate all pairs of vector differences in numpy


code:
import datetime as dt

x = [dt.datetime.strptime(d,'%Y-%m-%d %H:%M:%S') for d in dates]

rawDescription: Datetime down to seconds Python

description: Datetime down to seconds Python


code:
import difflib
difflib.get_close_matches('anlmal', ['car', 'animal', 'house', 'animation'])

rawDescription: How to find the most similar word in a list in python

description: Find the most similar word in a list in python


rawDescription: How can I extract this obvious event from this image?

description: Extract this obvious event from this image


code:
import re
s = "I went out on 1 sep 2012 and it was better than 15 jan 2012"
r = re.compile('(^.*)(1 sep 2012 )(.*$)')
r.sub(r'\2\1\3',s)

rawDescription: Reorder string using regular expressions


code: r = s.send(p)

rawDescription: Create url without request execution

description: Create url without request execution


rawDescription: Get only last part of xpath

description: Get only last part of xpath


code: function_call = fn + lpar + expr + rpar

rawDescription: How to get pyparser to work in a particular form

description: Get pyparser to work in a particular form


code:
from PyQt4.QtCore import *

app = QCoreApplication([])

class Signals(QObject):
    signal = pyqtSignal()
    def __init__(self):
        QObject.__init__(self)

class Test():
    def __init__(self, s):
        s.connect(self.done)

    def done(self):
        print("Done")

s = Signals()
t = Test(s.signal)
print("first")
s.signal.emit()
app.processEvents()

t = None
print("second")
s.signal.emit()
app.processEvents()

rawDescription: Does PyQT4 signal.connect keep objects live?


code:
# make namespace explicit
from matplotlib import pyplot as PLT

cbar = fig.colorbar(result)

rawDescription: How do I set a matplotlib colorbar extents?

description: Set a matplotlib colorbar extents


code:
lst1 = MyList(collections.MutableSequence)
lst2 = MyList(numbers.Integral)

rawDescription: How to make an iterable class in Python in which only a specific type is allowed to be the element?

description: Make an iterable class in Python in which only a specific type is allowed to be the element


code:
import re
textline = "AZERTY:qwerty"
if re.search('^([A-Z0-9]+:)(.*)', textline):
    print("match !")

rawDescription: Perl - regex How to write this in python?


code:
chan = np.array( [0,1,2,3,4,5,6,7,8,9] )
counts = np.array( [0.,0.,5.,2.,0.,0.,1.,1.,1.,0.] )
groups = np.array( [1,-1,-1,-1,-1,1,-1,-1,-1,-1] )

indx = np.where( groups==1 )
# indx is a tuple with one entry for each dimension of the array groups
# in the next statement I just grab the first (and only) element of the tuple
indx = indx[0]

# next we split the array based on those indices
counts = np.split( counts, indx )
# counts is now a list of arrays
# [array([], dtype=float64), array([ 0.,  0.,  5.,  0.,  0.]),array([ 0.,  1.,  1.,  1.,  0.])]
# I use the if statement in the list comprehension to get rid of the first empty array

totals = np.array( [sum(c) for c in counts if len(c)>0] )
tchnls = np.split( chan, indx )[1:]

rawDescription: grouping table elements according to grouping column values

description: Grouping table elements according to grouping column values


code:
A  # Input: A numpy array
np.lib.pad(A, ((0,1),(0,2)), 'constant', constant_values=(0))

rawDescription: python - increase array size and initialize new elements to zero

description: Python - increase array size and initialize new elements to zero


rawDescription: counting the number of key value pairs in a dictionary

description: Counting the number of key value pairs in a dictionary


rawDescription: Convert numpy array from values to indices


code: "bla".replace("a", "b")

rawDescription: Python 2.7: replace method of string object deprecated


code:
class MyModel(Base):
    data = Column(MutableDict.as_mutable(PickleType))

rawDescription: How to implement mutable PickleTypes that automatically update on change

description: Implement mutable PickleTypes that automatically update on change


code:
def factor_scatter_matrix(df, factor, palette=None):
    '''Create a scatter matrix of the variables in df, with differently colored
    points depending on the value of df[factor].
    inputs:
        df: pandas.DataFrame containing the columns to be plotted, as well
            as factor.
        factor: string or pandas.Series. The column indicating which group
            each row belongs to.
        palette: A list of hex codes, at least as long as the number of groups.
            If omitted, a predefined palette will be used, but it only includes
            9 groups.
    '''
    import matplotlib.colors
    import numpy as np
    from pandas.tools.plotting import scatter_matrix
    from scipy.stats import gaussian_kde

    if isinstance(factor, basestring):
        factor_name = factor #save off the name
        factor = df[factor] #extract column
        df = df.drop(factor_name,axis=1) # remove from df, so it
        # doesn't get a row and col in the plot.

    classes = list(set(factor))

    if palette is None:
        palette = ['#e41a1c', '#377eb8', '#4eae4b',
                   '#994fa1', '#ff8101', '#fdfc33',
                   '#a8572c', '#f482be', '#999999']

    color_map = dict(zip(classes,palette))

    if len(classes) > len(palette):
        raise ValueError('''Too many groups for the number of colors provided.
We only have {} colors in the palette, but you have {}
groups.'''.format(len(palette), len(classes)))

    colors = factor.apply(lambda group: color_map[group])
    axarr = scatter_matrix(df,figsize=(10,10),marker='o',c=colors,diagonal=None)

    for rc in xrange(len(df.columns)):
        for group in classes:
            y = df[factor == group].icol(rc).values
            gkde = gaussian_kde(y)
            ind = np.linspace(y.min(), y.max(), 1000)
            axarr[rc][rc].plot(ind, gkde.evaluate(ind),c=color_map[group])

    return axarr, color_map

rawDescription: class labels in Pandas scattermatrix

description: Class labels in Pandas scattermatrix


code: listy = [ [x for x in ilist if len(x) > 0] for ilist in indexdf]

rawDescription: filter lists of lists by taking out items less than a certain length - more pythonic way?

description: Filter lists of lists by taking out items less than a certain length - more pythonic way


code: df.query(' and '.join(['{0}=={1}'.format(x[0], x[1]) for x in parameter]))

rawDescription: Filter data iteratively in Python data frame


code: {0: {'comment': 'outstanding', 'field 2': 'first', 'field 1': 'dog'}, 1: {'comment': 'some comment about the cat', 'field 2': '', 'field 1': 'cat'}}

rawDescription: Parsing string sections

description: Parsing string sections


code:
class HashableProxy(object):
    def __init__(self, wrapped):
        self._wrapped = wrapped

    def __eq__(self, other):
        return self._wrapped == other

    def __hash__(self):
        return hash(self._wrapped)

class Required(HashableProxy):
    pass

class Optional(HashableProxy):
    pass

rawDescription: Thin proxy class for hashables

description: Thin proxy class for hashables


code:
from django.core.urlresolvers import reverse

class UserRedirectView(RedirectView):

    permanent = False

    def get_redirect_url(self, pk):
        # it would be better to use reverse here
        return '/myapp/%s/' % self.request.user.username

rawDescription: Django 1.5 url redirect with regex?

description: Django 1.5 url redirect with regex


code:
@property
def current_user(self):
    if not hasattr(self, '_current_user'):
        self._current_user = None
        cookie = get_user_from_cookie(self.request.cookies,
                facebookconf.FACEBOOK_APP_ID,
                facebookconf.FACEBOOK_APP_SECRET)
        if cookie:

            # Store a local instance of the user data so we don't need
            # a round-trip to Facebook on every request
            user = FBUser.get_by_key_name(cookie['uid'])
            if not user:
                graph = GraphAPI(cookie['access_token'])
                profile = graph.get_object('me')
                user = FBUser(key_name=str(profile['id']),
                              id=str(profile['id']),
                              name=profile['name'],
                              profile_url=profile['link'],
                              access_token=cookie['access_token'])
                user.put()
            elif user.access_token != cookie['access_token']:
                user.access_token = cookie['access_token']
                user.put()
            self._current_user = user
    return self._current_user

rawDescription: Understanding "runwithfriends" facebook-app sample code


code:
def search(string, dict_search):
    # If those 2 lines are too expensive, calculate them and pass as arguments
    max_key = max(len(x) for x in dict_search)
    min_key = min(len(x) for x in dict_search)

    return set(
        string[x:x+i]
        for i in range(min_key, max_key+1)
        for x in range(len(string)-i+1)
        if string[x:x+i] in dict_search
    )

rawDescription: Fastest way to match substring from large dict


code: rdd.mapPartitionsWithIndex(lambda i, iter: [(i,  sum(1 for _ in iter))]).collect()

rawDescription: RDD transformation map, Python

description: RDD transformation map, Python


code: split_row + [''] * (template_tuple_len - len(split_row))

rawDescription: Template Python list with default element values


code:
from django.db.models import Q

obj_list = Application.objects.filter(reduce(lambda x, y: x | y, [Q(name__contains=word) for word in titleVars]))

rawDescription: Django models queryset with array

description: Django models queryset with array


code: cats = [categories_mapping[key] for key in set(labels).intersection(categories_mapping)]

rawDescription: Pythonic way to check if element in a list contains in key dictionary


rawDescription: Summing elements in a list

description: Summing elements in a list


code:
@cherrypy.expose
def products(self):
    c = self.dbConnect()
    products = list()

    # Get every products
    c.execute('Select * from T_products')
    result = c.fetchall()
    for row in result:
        versions = list()
        # Conversion ID to string
        id = self.b10to26(int(str(row).split(",")[0][1:]))
        if len(id)==1:
            id = "AA" + id
        elif len(id)==2:
            id = "A" + id

        # Parse db informations
        name = str(row).split("'")[1]
        created = str(row).split(",")[2].split("'")[1]

        # Product in dict line
        product = {"name" : name, "id" : id, "created" : created}

        # Get every product versions
        cmd = ('Select * from T_products_Versions where id_product="{}"').format(str(row).split(",")[0][1:])
        c.execute(cmd)
        cmd_versions = c.fetchall()
        for row_version in cmd_versions:

            # Get ID + Name
            id_version = self.b10to26(int(str(row_version).split(",")[1]))
            if len(id_version)==1:
                id_version = "A" + id_version
            name = str(row_version).split("'")[1]
            created = str(row_version).split(",")[4].split("'")[1]

            # Product version dict line
            version = {"name" : name, "id" : id_version, "created" : created}

            #Put in a list
            versions.append (version)
        products.append({"product" : product, "versions" : versions})

    cherrypy.response.headers["Content-Type"] = "application/json"
    return json.dumps(products)

rawDescription: Deserialize JSON list of dictionaries in javascript


rawDescription: In Python, how to sum nested lists: [[1,0], [1,1], [1,0]] → [3,1]


code: list(compress(star_list, '**'))

rawDescription: Remove certain consecutive duplicates in list


code:
a, b, c = np.zeros((3,2), dtype=np.object)
a.flags.owndata
a, b, c = [np.zeros((2,), dtype=np.object) for _ in xrange(3)]
a.flags.owndata

rawDescription: assigning an object to multiple variables - python

description: Assigning an object to multiple variables - python


code: B = np.roll(A,1,axis=0) * np.sqrt(np.roll(np.roll(A,-1,axis=1),-1,axis=2))

rawDescription: Parallel array manipulations in numpy

description: Parallel array manipulations in numpy


rawDescription: Python Code to read File and Extract data


code:
import socket
import fcntl
import struct

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

get_ip_address('eth0')  # '192.168.0.110'

rawDescription: How can I get the IP address of eth0 in Python?

description: Get the IP address of eth0 in Python


code: removeRow(myDictBefore, 'a', 2)

rawDescription: Python 2.7.9 dictionary find and delete

description: Python 2.7.9 dictionary find and delete


rawDescription: Regex to match years within 1980 and 2050


code:
if mc.ls ('L_Shoulder_JNT', sl=1):
    if mc.objExists ('L_ShoulderOrient_NODE.jointOrient'): mc.deleteAttr ('L_ShoulderOrient_NODE.jointOrient')
    mc.addAttr ('L_ShoulderOrient_NODE', ln='jointOrient', at='enum', en=WOB3 + WOB4, k=1)

rawDescription: How can I query a joints sao (secondary axis world orientation)? Maya Python

description: Query a joints sao (secondary axis world orientation)? Maya Python


code:
def mycopy(d):
    return {k: copy.copy(v) for k, v in d.items()}

rawDescription: large number of changing dictionaries for tree nodes in python

description: Large number of changing dictionaries for tree nodes in python


code:
# same first three lines as above
instances = [i for r in reservations for i in r.instances]

rawDescription: How to get instance ID from reservation ID in boto

description: Get instance ID from reservation ID in boto


code: files_are_equal = filecmp.cmp(filename1, filename2)

rawDescription: How to detect that two Python iterators yield the same items?

description: Detect that two Python iterators yield the same items


code: a, b = np.split(arr, arr.shape[1]/2, axis=1)

rawDescription: Instantiate two 2D numpy arrays from a list of strings


code: self.labels = [Label(self, text=val) for val in my_list_of_texts]

rawDescription: Iterating over a list to make widgets

description: Iterating over a list to make widgets


code:
import subprocess

def command(cmd):
    try:
        p = subprocess.Popen(cmd, shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.STDOUT, close_fds = True)
        stdout = p.communicate()
        return stdout[0]
    except Exception as ex:
        raise Exception(ex)

df = command("df -h")

print(df)

rawDescription: How remember the whole function result?

description: How remember the whole function result


code:
"""This is your target object.
It's part of the problem domain; it rarely changes.
"""
class MyTargetObject( object ):
    def __init__( self ):
        self.someAttr= ""
        self.anotherAttr= ""
        self.this= 0
        self.that= 3.14159
    def aMethod( self ):
        """etc."""
        pass

rawDescription: Which language is easiest and fastest to work with XML content?


code:
first = df['tweet'].str.contains('first')
this = df['tweet'].str.contains('this')
fin = df['tweet'].str.contains('finally')

rawDescription: How to access a specific row in a DataFrame

description: Access a specific row in a DataFrame


rawDescription: how to divide integer and take some part

description: Divide integer and take some part


code: re.compile(r".*", re.IGNORECASE)

rawDescription: MongoAlchemy regex return nothing

description: MongoAlchemy regex return nothing


code: [str(item).zfill(6) for item in data]

rawDescription: add leading zeros to a list of numbers in Python

description: Add leading zeros to a list of numbers in Python


code: numpy.broadcast_arrays(a, [1, 2, 3])[1]

rawDescription: Is there a better way to broadcast arrays?


code:
import multiprocessing as mp
import itertools
import time
import csv

def worker(chunk):
    # `chunk` will be a list of CSV rows all with the same name column
    # replace this with your real computation
    # print(chunk)
    return len(chunk)

def keyfunc(row):
    # `row` is one row of the CSV file.
    # replace this with the name column.
    return row[0]

def main():
    pool = mp.Pool()
    largefile = 'test.dat'
    num_chunks = 10
    results = []
    with open(largefile) as f:
        reader = csv.reader(f)
        chunks = itertools.groupby(reader, keyfunc)
        while True:
            # make a list of num_chunks chunks
            groups = [list(chunk) for key, chunk in
                      itertools.islice(chunks, num_chunks)]
            if groups:
                result = pool.map(worker, groups)
                results.extend(result)
            else:
                break
    pool.close()
    pool.join()
    print(results)

if __name__ == '__main__':
    main()

rawDescription: Chunking data from a large file for multiprocessing?


code:
from subprocess import Popen,PIPE
p1 = Popen(["cat","text.txt"], stdout=PIPE)
p2 = Popen(["grep", variable], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()
out,err = p2.communicate()
p1.wait()
print(out)

rawDescription: Variable in subprocess

description: Variable in subprocess


rawDescription: Getting totals from list of lists and apply it to a dictionary


rawDescription: getting desired value from dictionary based on another value

description: Getting desired value from dictionary based on another value


code: [c['type'] for c in query.column_descriptions]

rawDescription: how to know the type of sql query result before it is executed in sqlalchemy

description: Know the type of sql query result before it is executed in sqlalchemy


code:
from sklearn.feature_extraction.text import CountVectorizer as CV
count_vect=CV()
docs_new = ['Modern Warfare 2', 'Modern Warfare 3', 'Modern Warfare 1', 'Modern Warfare 4', 'Modern Warfare A', 'Modern Warfare 44', 'Modern Warfare AA', 'Modern Warfare', 'Mahjong Kakutou Club', 'Mass Effect 2']
new_counts = count_vect.fit_transform(docs_new)
count_vect.inverse_transform(new_counts)

rawDescription: Scikit-learn Naive Bayes inexplicable results with sparse string classification


code: resultant_dict = {rev[k]:v for k,v in dict2.iteritems()}

rawDescription: Comparing multiple dictionaries and generating another dictionary using python


code:
with open('newxml.xml','w') as of:
    of.write(ET.tostring(xml.getroot()).decode())

rawDescription: Insert XML Value/Element with Python

description: Insert XML Value/Element with Python


rawDescription: When to split sub-apps into new apps

description: When to split sub-apps into new apps


code:
a = Vector(4,5,0)
direction = Vector(10, 1, 0).unitVector()
a + direction

rawDescription: Calculate a point along a line segment one unit from a end of the seg


code:
class review_opinion(osv.osv_memory):
    _name='review.opinion'

    _columns = {
        'opinion_emission': fields.text('Opinion emission'),
        'notes': fields.text('Additional notes'),
    }

    #defaults calls a function that will browse your main object and fill the field with the existing information
    _defaults={
        'opinion_emission': lambda self, cr, uid, context: self._get_opinion(cr, uid, context),
        'notes': lambda self, cr, uid, context: self._get_notes(cr, uid, context), # populates requestor field with actual user id

    }
    def save_info(self, cr, uid, ids, context=None):
        if 'active_id' in context:
            info = self.browse(cr,uid,ids)
            self.pool.get('opinion').write(cr,uid,context['active_id'],{'opinion_emission': info[0].opinion_emission,'notes': info[0].notes})

        return {
            'type': 'ir.actions.act_window_close',
         }

    #functions that get the info stored in db
    def _get_opinion(self, cr, uid, context=None):
        if 'active_id' in context:
            return self.pool.get('opinion').browse(cr, uid, context['active_id'], context).opinion_emission

    def _get_notes(self, cr, uid, context=None):
        if 'active_id' in context:
            return self.pool.get('opinion').browse(cr, uid, context['active_id'], context).notes

review_opinion()

rawDescription: OpenERP wizard syntax

description: OpenERP wizard syntax


code:
tag = 'a'
attr = 'href'
xpq = '//{}/@{}'.format(tag, attr)
a = 'helloNo href hereblah'
import lxml.html
lxml.html.fromstring(a).xpath(xpq)

rawDescription: dynamically extracting data from HTML page

description: Dynamically extracting data from HTML page


code:
def __getstate__(self):
    return self.rows

def __setstate__(self, rows):
    self.rows = rows

rawDescription: Saving a deep copy of an object, then modifying it and saving another copy?


rawDescription: how to set autocommit = 1 in a sqlalchemy.engine.Connection

description: Set autocommit = 1 in a sqlalchemy.engine.Connection


code:
from selenium import webdriver

a = 4
b = 5
url = "http://example.com/form"
# formactionurl = "http://example.com/formaction/url" # this is not relevant in Selenium

# Start up Firefox
browser = webdriver.Firefox()

# Assume, you get somehow authenticated now
# You might succeed with Basic Authentication by using url = "http://appuser:apppass@example.com/form

# Navigate to your url
browser.get(url)

# find the element that's id is param_a and fill it in
inputElement = browser.find_element_by_id("param_a")
inputElement.send_keys(str(a))
# repeat for "b"
inputElement = browser.find_element_by_id("param_b")
inputElement.send_keys(str(b))

# submit the form (if having problems, try to set inputElement to the Submit button)
inputElement.submit()

time.sleep(10) # wait 10 seconds (better methods can be used)

page_text = browser.page_source
# now you have what you asked for
browser.quit()

rawDescription: Login, Navigate and Retrieve data behind a proxy with Python


code: letters = [c.casefold() for c in my_str if c.isalpha()]

rawDescription: Can I make a code in python that ignores special characters such as commas, spaces, exclamation points, etc?

description: Make a code in python that ignores special characters such as commas, spaces, exclamation points, etc


code:
import time

# Assuming the Popen objects are in the dictionary values
PROCESS_DICT = { ... }

def my_thread_main():
    while 1:
        dead_keys = []
        for k, v in PROCESS_DICT.iteritems():
            v.poll()
            if v.returncode is not None:
                dead_keys.append(k)
        if not dead_keys:
            time.sleep(1)  # Adjust sleep time to taste
            continue
        for k in dead_keys:
            del PROCESS_DICT[k]

rawDescription: How to Clean Up subprocess.Popen Instances Upon Process Termination


code: board.index([4, 5, 6])

rawDescription: Determine number of row in matrix

description: Determine number of row in matrix


code:
def _loadTileTable(arg1, arg2):
    pass # blah blah
tile_table = _loadTileTable('image path', other_var)

rawDescription: calling class/static method from class variable in python

description: Calling class/static method from class variable in python


code:
def func(alist):
    it = iter(alist)
    old = next(it, None)
    for new in it:
        yield old, new
        old = new

rawDescription: Get Pairs of List Python

description: Get Pairs of List Python


code: a, b = b, a

rawDescription: How can I switch contents of lists?

description: Switch contents of lists


code:
def strParse(str):
    a = 't'
    b = 'br'
    c = 'ht'
    if a in str and b in str and c in str:
        print('Ok!')

rawDescription: Python if this and this and this

description: Python if this and this and this


code:
for line in input:
    key, val = line.split(':')
    if key == 'particular':
       val = '111222333'

rawDescription: Replace part of string using python regular expression


code:
class parserSAXHandler(handler.ContentHandler):

    def __init__(self):
        self.parentflag = False
        self.childlist  = []

    def startElement(self, name, attrs):
        if name == "parent":
           self.parentflag = True
        elif self.parentflag:
           self.childlist.append(name)

    def endElement(self,name):
        if name == "parent":
            self.parentflag = False

rawDescription: python sax xml names of the children tags

description: Python sax xml names of the children tags


code:
mytype = type(a)
arr = np.append(a, b)
result = mytype(arr)

rawDescription: Extend numpy array in a way compatible with builtin arrays


code:
import re
from bs4 import BeautifulSoup

matches = {}
_catalog_link = re.compile(r'^http://www\.bricklink\.com/catalogItem\.asp\?P=')

soup = BeautifulSoup(htmlpage)

for match in soup.find_all(text=re.compile(r'Match #\d+')):
    match_number = match.string.split('#', 1)[-1]
    matches[match_number] = matched_links = []
    # Find the parent table row
    row = next(p for p in match.parents if p.name == 'tr')
    # next rows hold the links
    for sibling in row.next_siblings:
        if sibling.name != 'tr':
            continue
        links = sibling.find_all('a', href=_catalog_link)
        if not links:
            break
        matched_links.extend(l.string for l in links)

rawDescription: Parsing a file without BeautifulSoup

description: Parsing a file without BeautifulSoup


code: file = open('result.dat')

rawDescription: Read specific column from .dat-file in Python


code:
class A(object):
  def __dir__(self):
    return ['a', 'b', 'c']

print(dir(A()), dir(A))

rawDescription: How to find hidden attributes of Python objects? (attributes that don't appear in the dir(obj) list)

description: Find hidden attributes of Python objects? (attributes that don't appear in the dir(obj) list)


rawDescription: Python filter() function

description: Python filter() function


rawDescription: Redirect print to string list?

description: Redirect print to string list


rawDescription: How do I force Python to keep an integer out of scientific notation

description: Force Python to keep an integer out of scientific notation


code:
import ast, json
x = "[26, 25]"
ast.literal_eval(x)
json.loads(x)

rawDescription: Convert Python string to list

description: Convert Python string to list


code:
df.pivot_table(rows=("report", "action"),
               cols="label",
               values="label",
               aggfunc="count").fillna(0)

rawDescription: Transforming stacked records into a columns in pandas


code:
spec.args
spec.defaults

rawDescription: Where is the default parameter in Python function


rawDescription: How to add an item at the last nested list of an outer list in python?

description: Add an item at the last nested list of an outer list in python


code:
d["red","blue","green"] = {
    # {rule_set} : {result: probability}
    frozenset(["red", "green"]): {"ballon": 0.8},
    frozenset(["blue"]): {"toy": 0.15},
    frozenset([]): {"car": 0.05}
}

rawDescription: Multikey Multivalue Non Deterministic python dictionary


code:
# makepath.py
import sys
sys.path.append('/whatever/dir/you/want')

# script.py
import makepath

rawDescription: Using .pth files

description: Using .pth files


code:
import itertools as IT
import numpy as np
import pandas as pd

df = pd.DataFrame({
    'item': ['item1', 'item2', 'item3', 'item1', 'item4', 'item1', 'item2', 'item4'],
    'user': ['user1', 'user1', 'user1', 'user2', 'user2', 'user3', 'user3', 'user3']})
edges = df.groupby(['user'], group_keys=False).apply(
    lambda x: pd.DataFrame(list(IT.combinations(x['item'], 2)),
                           columns=['first', 'second'])).reset_index(drop=True)
print(edges)

rawDescription: Pandas combine rows that share an association


code:
import numpy as np
from matplotlib import pyplot as plt
X = np.linspace(0, 100, 50)
Y = 23.24 + 2.2*X + 0.24*(X**2) + 10*np.random.randn(50) #added some noise
coefs = np.polyfit(X, Y, 2)
print(coefs)
p = np.poly1d(coefs)
plt.plot(X, Y, "bo", markersize= 2)
plt.plot(X, p(X), "r-") #p(X) evaluates the polynomial at X
plt.show()

rawDescription: Which is the simplest way to make a polynomial regression with sklearn?


code:
from math import log10, floor
def round_to_1(x):
  return round(x, -int(floor(log10(abs(x)))))

round_to_1(0.0232)
round_to_1(1234243)
round_to_1(13)
round_to_1(4)
round_to_1(19)

rawDescription: How to round a number to significant figures in Python

description: Round a number to significant figures in Python


code:
@login_required
def submission_set_rank(request):
    keys = {'rank1': 5, 'rank2': 4, 'rank3': 3, 'rank4': 2, 'rank5': 1}
    ranks = [{'score': request.GET.get(key,''), 'id': key} for key in keys]

    cursor = connection.cursor()
    cursor.executemany("""
        UPDATE
            ballot_stats
        SET
            score = score + %(score)s
        WHERE
            object_id = %(id)s
    """, ranks)

    return HttpResponseRedirect('/submissions/results/film/')

rawDescription: How can I write this with less redundancy/copy-paste?

description: Write this with less redundancy/copy-paste


rawDescription: _func() , any functional use of underscore? (Python)


code:
pairs = np.array(list(pairs))
pairs = np.vstack((pairs, pairs[:, ::-1]))
pairs = pairs[np.argsort(pairs[:, 0])]
is_z_smaller = points[pairs[:, 0], 2] < points[pairs[:, 1], 2]
bins, = np.nonzero(pairs[:-1, 0] != pairs[1:, 0])
has_neighbors = pairs[np.concatenate(([True], bins)), 0]
bins = np.concatenate(([0], bins+1))
is_maximum = np.ones((len(points),), bool)
is_maximum[has_neighbors] &= np.logical_and.reduceat(is_z_smaller, bins)
localCoordinateMaxima, = np.nonzero(is_maximum)

rawDescription: Efficient double iteration over array

description: Efficient double iteration over array


rawDescription: Python sum, why not strings?

description: Python sum, why not strings


code:
A.tocoo().row
A.tocoo().col

rawDescription: Read sparse matrix in python

description: Read sparse matrix in python


code: return np.random.randint(0, 100, (rows, cols)).astype('uint8')

rawDescription: python.exe crushed while creating numpy array

description: Python.exe crushed while creating numpy array


code:
activities = [None] * 5
index = 0

# some code in-between

activities[index] = activity

if index == 4:
    index = 0
else:
    index = index + 1

rawDescription: Most efficient way to add an item and at the same time remove one from a list with a fixed length


code: [d for d in L1 if (d['file'], d['ext']) in pairs]

rawDescription: Get dictionaries in a list where the key:value pairs are in another list of dictionaries


code: map(int, re.findall('\d+', s))

rawDescription: extract digits in a simple way from a python string

description: Extract digits in a simple way from a python string


code:
{u'ROLE_NAME': {u'BAR': {u'download_url': u'http: //something.staging/12345/fizz.zip'},
                u'FOO': {u'download_url': u'http: //something.staging/12345/buzz.zip'},
                u'db_name': u'somedb',
                u'db_server': u'dbserver.staging.dmz',
                u'download_url': u'http: //something.staging/12345/fizzbuzz.zip',
                u'plugin': {u'server_url': u'http: //lab.staging.corp/server/'}}}
{u'ROLE_NAME': {u'BAR': {u'download_url': 'XXX'},
                u'FOO': {u'download_url': 'XXX'},
                u'db_name': u'somedb',
                u'db_server': u'dbserver.staging.dmz',
                u'download_url': 'XXX',
                u'plugin': {u'server_url': u'http: //lab.staging.corp/server/'}}}

rawDescription: Replace value in JSON file for key which can be nested by n levels


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

x = np.array([1,2,3,4,5])
y = np.array([2,1,3,6,7])

cluster = np.array([1,1,1,2,2])

fig, ax = plt.subplots()

ax.scatter(x[cluster==1],y[cluster==1], marker='^')
ax.scatter(x[cluster==2],y[cluster==2], marker='s')

plt.show()

rawDescription: How to use different marker for different point in scatter plot pylab

description: Use different marker for different point in scatter plot pylab


code: pat = pat % re.escape(string.punctuation)

rawDescription: Gruber’s URL Regular Expression in Python


code:
import os
import unittest

# Generate a test class for an individual file.
def make_test(filename):
    class TestClass(unittest.TestCase):
        def test_file(self):
            # Do the actual testing here.
            # parsed = do_my_parsing(filename)
            # golden = load_golden(filename)
            # self.assertEquals(parsed, golden, 'Parsing failed.')

            # Randomly fail some tests.
            import random
            if not random.randint(0, 10):
                self.assertEquals(0, 1, 'Parsing failed.')

        # Set the docstring so we get nice test messages.
        test_file.__doc__ = 'Test parsing of %s' % filename

    return TestClass

# Create a single file test.
Test1 = make_test('file1.html')

# Create several tests from a list.
for i in range(2, 5):
    globals()['Test%d' % i] = make_test('file%d.html' % i)

# Create them from a directory listing.
for dirname, subdirs, filenames in os.walk('tests'):
    for f in filenames:
        globals()['Test%s' % f] = make_test('%s/%s' % (dirname, f))

# If this file is being run, run all the tests.
if __name__ == '__main__':
    unittest.main()

rawDescription: Proper way to organize testcases that involve a data file for each testcase?


code:
import tkinter
r=Tkinter.Tk()
b=Tkinter.Button(r,text='aaa')
b.pack()
b['text']='bbb'

rawDescription: Window is losing keyboard focus after recreation


code: df = pd.read_csv(filename, index_col = 0).drop_duplicates()

rawDescription: how to ignore multiple entries with same index while reading data from CSV using pandas

description: Ignore multiple entries with same index while reading data from CSV using pandas


code:
import urllib2
import bs4 as bs
url = 'http://mattilintulahti.net/mediablogi/2013/02/11/19-asiaa-joita-et-tieda-mediayhtiosta-nimeltaan-red-bull/'
html = urllib2.urlopen(url).read()
doc = bs.BeautifulSoup(html, 'lxml')
for meta in doc.html.head.findAll('meta', attrs={'property': 'og:title'}):
    print(meta.attrs['content'])

rawDescription: Encoding issue with BeatifulSoup

description: Encoding issue with BeatifulSoup


code:
Atom.pos = parsepos.get_pos()
print(Atom.pos)

rawDescription: assign list to python object

description: Assign list to python object


code:
months = "|".join(calendar.month_name)[1:]
matches = re.findall("{0}\s\d+\s\-\s{0}\s\d+".format(months), text)

rawDescription: regex to find a specific pattern in python

description: Regex to find a specific pattern in python


rawDescription: python pyparsing word excludeChars

description: Python pyparsing word excludeChars


code:
Code
def split_string_by_position(a_string, lengths):
    result = []
    position = 0
    for length in lengths:
        result.append(a_string[position:position+length])
        position = position+length
    return result

line = '66TP        1003    54.437269600149717.012388003107655.5139691177756'
lengths = [2, 2, 16, 16, 16, 16, 16, 16, 1, 1, 16, 16]

print(split_string_by_position(line, lengths))

rawDescription: ascii file parsing based on position and length in line using python

description: Ascii file parsing based on position and length in line using python


code:
import numpy as np
np.clip(data32, 0, 255, out=data32)
data_u8 = data32.astype('uint8')

rawDescription: numpy uint8 pixel wrapping solution

description: Numpy uint8 pixel wrapping solution


code:
from itertools import dropwhile, takewhile

with open("test.txt") as f:
    dp = dropwhile(lambda x: not x.startswith("-"), f)
    next(dp)  # skip ----
    names = next(dp).split()  # get headers names
    next(f)  # skip -----
    out = []
    for line in takewhile(lambda x: not x.startswith("-"), f):
        a, b = line.rsplit(" ", 1)
        out.append(dict(zip(names,  a.rstrip().split(None, 7) + [b.rstrip()])))

rawDescription: Python convert table to dictionary

description: Python convert table to dictionary


code:
loc = ticker.MultipleLocator(4./12)
ax.yaxis.set_major_locator(loc)

rawDescription: Python Matplotlib: plotting feet and inches


code:
def mod(match,value) :
    for n in doc.xpath(".//*[preceding-sibling::*/text()='%s']" % match):
        n.text = value

mod('customer', 'new customer value')
mod('admin', 'new admin value')

rawDescription: Edit XSL file using Python

description: Edit XSL file using Python


code:
from datetime import datetime
import pytz
tz = pytz.timezone('America/New_York')
tz.localize(datetime(2015,11,1,1,30), is_dst=None)
tz.localize(datetime(2015,11,1,1,30), is_dst=True).astimezone(pytz.utc)
tz.localize(datetime(2015,11,1,1,30), is_dst=False).astimezone(pytz.utc)

rawDescription: Compare times with python

description: Compare times with python


code:
import sys
import numpy
import cv2

im = cv2.imread(sys.argv[1])
im_ycrcb = cv2.cvtColor(im, cv2.COLOR_BGR2YCR_CB)

skin_ycrcb_mint = numpy.array((0, 133, 77))
skin_ycrcb_maxt = numpy.array((255, 173, 127))
skin_ycrcb = cv2.inRange(im_ycrcb, skin_ycrcb_mint, skin_ycrcb_maxt)
cv2.imwrite(sys.argv[2], skin_ycrcb) # Second image

contours, _ = cv2.findContours(skin_ycrcb, cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE)
for i, c in enumerate(contours):
    area = cv2.contourArea(c)
    if area > 1000:
        cv2.drawContours(im, contours, i, (255, 0, 0), 3)
cv2.imwrite(sys.argv[3], im)         # Final image

rawDescription: Computer Vision: Masking a human hand

description: Computer Vision: Masking a human hand


code:
s = '23.456'
d = decimal.Decimal(s)
d - decimal.Decimal('1')
d - decimal.Decimal('1.0')

rawDescription: How do I convert a string into a decimal number for arithmetic manipulation in Python?

description: Convert a string into a decimal number for arithmetic manipulation in Python


code:
import itertools

def permutation_with_repeats(seq, key):
    """
    generator that produces all permutations of length key
    of the elements in  seq.
    seq = list('abc'); key = 4
    >>> aaaa aaab aaac aaba aabb aabc aaca aacb...
    seq = list('abcdefghijklmnopqrstuvwzyz'); key = 2
    >>> aa ab ac ad ae af ag ah ai aj ak al...
    """
    for _ in  itertools.product(seq, repeat=key):
        yield ''.join(_)

seq = list('abcdefghijklmnopqrstuvwzyz')
key = 2
a = permutation_with_repeats(seq, key)  # seq and key of arbitrary size > 0

while True:
    try:
        print(next(a), end=' ')
    except StopIteration:
        break

rawDescription: Python: print possible letter combination of key size


code:
q = (select([fruit.c.type, func.min(fruit.c.price).label("min_price")]).
    group_by(fruit.c.type)).alias("subq")

s = select([fruit],
            and_(fruit.c.type == q.c.type,
                 fruit.c.price == q.c.min_price)
    )
res = session.execute(s)

rawDescription: How do I express this query in sqlalchemy?

description: Express this query in sqlalchemy


code:
opts = {"ln":"AttrNameTextField","k":True}
if typenum == 1:
   opts["at"] = "enum"
   opts["en"] = "Off:On"
else:
   opts["at"] = "float"
   opts["min"] = 0
   opts["max"] = 1
cmds.addAttr(selectedObject, **opts)

rawDescription: Python (Maya) pass flags as variables

description: Python (Maya) pass flags as variables


code:
counterA
counterB
counterA - counterB
counterB - counterA

rawDescription: Compute the similarity between two lists


code:
df["sum4"] = df.groupby("Type")["Value"].apply(lambda x: pd.rolling_sum(x,4))
df

rawDescription: Limit cumsum to only the previous 4 rows


code:
print(np.bincount([1, 1, 3, 3, 3, 4]))
# [0, 2, 0, 3, 1]
# i.e. [count for 0, count for 1, count for 2, count for 3, count for 4]

rawDescription: numpy: ravel_multi_index increment different results from iterating over indices loop

description: Numpy: ravel_multi_index increment different results from iterating over indices loop


code: self.book_values_list.append([bookNode.get(i) for i in book_attribute])

rawDescription: Python - How can I return a list for each xml node I am iterating through using xml.etree.ElementTree?


code: i = e.GetString()

rawDescription: WxPython Combobox string not returning correctly


code:
import httplib2
http = credentials.authorize(httplib2.Http())

rawDescription: How to make 'access_type=offline' / server-only OAuth2 operations on GAE/Python?

description: Make 'access_type=offline' / server-only OAuth2 operations on GAE/Python


code: np.kron(img, np.ones((2,2)))

rawDescription: Python function to expand image

description: Python function to expand image


code:
from parameterizedtestcase import ParameterizedTestCase

class MyTests(ParameterizedTestCase):
    @ParameterizedTestCase.parameterize(
        ("value", "expected"),
        [
            (True, True),
            (False, False),
        ]
    )
    def test_identical(self, value, expected):
        self.assertTrue(value is expected)

rawDescription: A pythonic way to code self writing test methods


code:
def flatten_cmd(schema, cmd):
    ret = cmd['type']
    for x in schema:
        k = x[0]
        ret = ret + ' ' + str(cmd[k])
    return ret+'\r\n'

rawDescription: twisted client transport.write not sending data, even after close

description: Twisted client transport.write not sending data, even after close


code:
class DepartmentPeople(models.Model):
    person = models.ForeignKey(
        Person,
        verbose_name    = _(u'Person'),
        help_text           = _(u'Person is a member of this deparment.'),
    )
    department = models.ForeignKey(
        Department,
        verbose_name    = _(u'Department'),
        help_text           = _(u'Pseron is a member of this department.'),
    )
    order = models.IntegerField(
        verbose_name    = _(u'Order'),
        help_text           = _(u'What order to display this person within the department.'),
        max_length      = 255
    )

    class Meta:
        verbose_name = _(u"Department Person")
        verbose_name_plural = _(u"Department People")
        ordering = ['order',]

    def __unicode__(self):
        return self.person.first_name + " " + self.person.last_name + " is a member of " + self.department.name + (" in position %d" % self.order)

rawDescription: Define an order for ManyToManyField with django


code:
def fizz_count(x):
    return x.count("fizz")

rawDescription: for statement does not work as intended

description: For statement does not work as intended


rawDescription: How to read contents of an Table in MS-Word file Using Python?

description: Read contents of an Table in MS-Word file Using Python


code:
def call_an_sp(self, var):
    cursor = connection.cursor()
    cursor.callproc("fn_sp_name", (var,))
    return self.fn_generic(cursor)

def fn_generic(self, cursor):
    msg = cursor.fetchone()[0]
    cursor.execute('FETCH ALL IN "%s"' % msg)
    thing = create_dict_from_cursor(cursor)
    cursor.close()
    return thing

def create_dict_from_cursor(cursor):
    rows = cursor.fetchall()
    # DEBUG settings (used to) affect what gets returned.
    if DEBUG:
        desc = [item[0] for item in cursor.cursor.description]
    else:
        desc = [item[0] for item in cursor.description]
    return [dict(zip(desc, item)) for item in rows]

rawDescription: What is the best way to access stored procedures in Django's ORM


code: exec(c, {"public": public})

rawDescription: Creating a simple scripting language in Python


code:
from a import *
from b import *
from c import *
# etc

example()
# Where did this come from? From module a, b, or c? What if both a and b define a
# function named 'example'?

rawDescription: Importing Turtle graphics modules

description: Importing Turtle graphics modules


code:
for d in A:
    d['status'] = mid_status.get(d['mid'], [])

rawDescription: comparison between two values in two tables and Append

description: Comparison between two values in two tables and Append


code:
last_names = names[::2]
first_names = names[1::2]

rawDescription: Python: extract unique id from file name


code:
query = df.index.get_level_values(2) >= pd.Timestamp('2013-01-17')
df[query]

rawDescription: Pandas multi-index best way to slice for ranges of subordinate levels


code:
import re
s = 'adsgasdlkgasYasdgjaUUalsdkjgaZsdalkjgalsdkjTlaksdjfgasdkgj'
re.match(r'(?:.*?[A-Z]){3}.*?([A-Z].*)', s).group(1)

rawDescription: Parse 4th capital letter of line in Python?


code: py = min(py + movespeed, 5)

rawDescription: Python - How to add then limit a number in python


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import Slider

class ChangingPlot(object):
    def __init__(self):
        self.inc = 0.5

        self.fig, self.ax = plt.subplots()
        self.sliderax = self.fig.add_axes([0.2, 0.02, 0.6, 0.03],
                                          axisbg='yellow')

        self.slider = Slider(self.sliderax, 'Value', 0, 10, valinit=self.inc)
        self.slider.on_changed(self.update)
        self.slider.drawon = False

        x = np.arange(0, 10.5, self.inc)
        self.ax.plot(x, x, 'ro')
        self.dot, = self.ax.plot(self.inc, self.inc, 'bo', markersize=18)

    def update(self, value):
        value = int(value / self.inc) * self.inc
        self.dot.set_data([[value],[value]])
        self.slider.valtext.set_text('{}'.format(value))
        self.fig.canvas.draw()

    def show(self):
        plt.show()

p = ChangingPlot()
p.show()

rawDescription: Can I make matplotlib sliders more discrete?

description: Make matplotlib sliders more discrete


code:
def parse_data():
    data=shelve.open(html_filename)
    with open(out_file,'w') as out_handle:
        line = '\t'
        for item in header_list:
            line=line+item+'\t'
        out_handle.write(line)
        for url in data:
            line=""
            for item in header_list:
                line=line+data[item]+'\t'
                out_handle.write(line)
    print("Done writing data")
    data.close()

rawDescription: How to extract search results on a website into local file

description: Extract search results on a website into local file


code:
struct = {'TotalCount': 1, 'PageSize': 1, 'FoundCategories': [], 'Page': 1, 'List': [{'AsAt': '/Date(1457733660023)/', 'Model': 'Continental', 'Suburb': 'Palmerston North', 'NoteDate': '/Date(0)/', 'PriceDisplay': '$100.00', 'EndDate': '/Date(1457930919847)/', 'RegistrationExpires': '/Date(0)/', 'StartPrice': 100.0, 'Owners': 0, 'ListingLength': None, 'CategoryPath': '/Trade-Me-Motors/Cars/Bentley', 'ListingId': 4550689, 'Subtitle': 'sdf', 'Category': '0001-0268-7081-', 'StartDate': '/Date(1457326119847)/', 'Year': 1999, 'WofExpires': '/Date(0)/', 'ExteriorColour': None, 'Vin': None, 'EngineSize': 0, 'Doors': 0, 'BodyStyle': 'Coupe', 'Title': 'Bentley Continental 1999', 'IsDealer': False, 'Make': 'Bentley', 'Transmission': 'Manual', 'Fuel': None, 'ImportHistory': None, 'Odometer': 2000, 'StereoDescription': None, 'Region': 'Manawatu', 'BestContactTime': None, 'Cylinders': 0, 'NumberPlate': None}]}

car_info = struct.get('List')
with open('car_info.csv', 'w') as csvfile:
    writer = csv.DictWriter(csvfile, fieldnames=car_info[0].keys())

    writer.writeheader()
    for row in car_info:
        writer.writerow(row)

rawDescription: Save Json data to csv file

description: Save Json data to csv file


code:
class GeneratorWrap(object):

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

      def __iter__(self):
          return self

      def next(self):
          for o in self.generator:
              return o
          raise StopIteration # If you don't care about the iterator protocol, remove this line and the __iter__ method.

rawDescription: is there an alternative way of calling next on python generators?

description: Is there an alternative way of calling next on python generators


code:
grouped = df.groupby('minute').sum().sort('values', ascending=False)
grouped.index[:2]

rawDescription: Python - Get group names from aggregated results in pandas


code:
import csv
import re
keyvalue = re.compile(r'([^"= ]+)="([^"]+)"')
sample = '''\
"Harry Potter", "book", "12 Mar 2014 note=""good"" language=""English"""
"Forrest Gump", "movie", "14 March 2015 note=""good"" language=""Aztec"""
'''
reader = csv.reader(sample.splitlines(True), skipinitialspace=True)
[dict(keyvalue.findall(row[2])) for row in reader]

rawDescription: parsing space delimited, named fields

description: Parsing space delimited, named fields


code:
class Apartment(models.Model):
    rooms = models.IntegerField()
    price = models.IntegerField() # Can use Decimal,
                                  # but who quotes real estate prices with decimals?

rawDescription: Filter based on user provided values with ajax and django


code:
from email.utils import getaddresses
for realname, emailaddr in getaddresses(returnpaths):
    print(realname, emailaddr)

rawDescription: Parsing "Return-Path:" in Python

description: Parsing "Return-Path:" in Python


code:
try:
    from accel import _get_ptr
    def get_ptr(x):
        return C.cast(_get_ptr(x), p_t)
except ImportError:
    get_ptr = get_ptr_array

rawDescription: Portable/fast way to obtain a pointer to Numpy/Numpypy data


code:
def calc_soma(num):
    ns = str(num)
    soma = 0
    indic = 0
    while indic < len(ns):
        soma += int(ns[indic])
        indic = indic + 1
    return soma
calc_soma(123)
calc_soma(1048)

rawDescription: Sum of digits of a number using While

description: Sum of digits of a number using While


code:
re.findall("\s?(" + "[A-Za-z]*[AEIOUaeiou]"*2 + "[b-df-hj-np-tv-z]*)", "bool sjalkdj tehere")
re.findall("\s?(" + "[A-Za-z]*[AEIOUaeiou]"*3 + "[b-df-hj-np-tv-z]*)", "bool sjalkdj tehere")

rawDescription: Regular expressions Python. Matching words in a text file with 1 or more vowels depending on input?


code:
def vectorized(flow_direction, sediment_transport):
    elevation_change = np.zeros_like(sediment_transport)
    nrows, ncols = flow_direction.shape
    lookup = {32: (-1, -1),
              16:  (0, -1),
              8:   (1, -1),
              4:   (1,  0),
              64: (-1,  0),
              128:(-1,  1),
              1:   (0,  1),
              2:   (1,  1)}

    # Initialize an array for the "shifted" mask
    shifted = np.zeros((nrows+2, ncols+2), dtype=bool)

    # Pad "sediment_transport" with zeros
    # Again, `np.pad` would be better and more flexible here, as it would
    # easily allow lots of different boundary conditions...
    tmp = np.zeros((nrows+2, ncols+2), sediment_transport.dtype)
    tmp[1:-1, 1:-1] = sediment_transport
    sediment_transport = tmp

    for value, (row, col) in lookup.iteritems():
        mask = flow_direction == value

        # Reset the "shifted" mask
        shifted.fill(False)
        shifted[1:-1, 1:-1] = mask

        # Shift the mask by the right amount for the given value
        shifted = np.roll(shifted, row, 0)
        shifted = np.roll(shifted, col, 1)

        # Set the values in elevation change to the offset value in sed_trans
        elevation_change[mask] = sediment_transport[shifted]

    return elevation_change

rawDescription: Iterating through a numpy array and then indexing a value in another array


code:
i.create_dataset("array", data=l)
arr = i["array"]

rawDescription: how to write data to a h5py dataset

description: Write data to a h5py dataset


code:
def inside3d(input):
    # Get idx in 3D
    idx3d = np.floor(input).astype(np.int)

    # Create a similar mask as witrh 2D case, but in 3D now
    mask3d = grid[idx3d[:,:,0], idx3d[:,:,1]]==1

    # Count of mask matches for each index in 0th dim
    counts = np.sum(mask3d,axis=1)

    # Index into input to get masked matches across all elements in 0th dim
    out_cat_array = input.reshape(-1,2)[mask3d.ravel()]

    # Split the rows based on the counts, as the final output
    return np.split(out_cat_array,counts.cumsum()[:-1])

rawDescription: Using array indexing to apply 2D array function on 3D array


code:
temp = df.Value.cummax()
df['Altered'] = df.Value < temp
df['Value'] = temp

rawDescription: How to set current row item to previous if smaller, in Pandas?

description: Set current row item to previous if smaller, in Pandas


code:
itemA = random(1, 2, 3)
itemB = random.from_file('file.txt')

rawDescription: How do I replace variables in python class?

description: Replace variables in python class


rawDescription: how to extend model User?

description: Extend model User


code:
class Author(db.Model):
  owner = db.UserProperty()

class Post(db.Model):
  author = db.ReferenceProperty(Author,
    collection_name='posts')
  tags = db.StringListProperty()

class Tag(db.Model):
  post_count = db.IntegerProperty()

rawDescription: parent->child relationships in appengine python (bigtable)

description: Parent->child relationships in appengine python (bigtable)


code:
from collections import defaultdict
result = defaultdict(int)
for key, value in mydict.items():
    result[value] += mytb[key]

rawDescription: Python do a lookup between 2 dictionaries


code:
# this will be the index value of codes not in the list "A"
end_index = len(A)+1

def key(job):
    code = job[0]
    if code in A:
        return A.index(code)
    return end_index

jobs = OrderedDict(sorted(jobs.items(), key=key))

rawDescription: How to do sorting inside a python dictionary from a predefined list

description: Do sorting inside a python dictionary from a predefined list


code:
from django.db.models.signals import pre_delete
from django.dispatch import receiver

@receiver(pre_delete, sender=Question, dispatch_uid='question_delete_signal')
def log_deleted_question(sender, instance, using, **kwargs):
    d = Deleted()
    d.question = instance.id
    d.dt = datetime.datetime.now()
    d.save()

rawDescription: Using Pre_delete Signal in django

description: Using Pre_delete Signal in django


rawDescription: How to find all elements in a numpy 2-dimensional array that match a certain list?

description: Find all elements in a numpy 2-dimensional array that match a certain list


code:
import ast
ast.literal_eval("__import__('os').system('rm -R *')")

rawDescription: What is the best Pythonic way to parse this data?


rawDescription: Accessing non-consecutive elements of a list or string in python


code:
sorted_listobj = sorted(listobj)
reversed_iterator = reversed(listobj)

rawDescription: Python naming convention: indicating if function alters arguments


code:
htmltest = lxml.html._looks_like_full_html_bytes if isinstance(inputtext, str) else lxml.html._looks_like_full_html_unicode
if htmltest(inputtext):
    tree = lxml.html.fromstring(inputtext)
else:
    tree = lxml.html.document_fromstring(inputtext)[0]

rawDescription: parse html body fragment in lxml

description: Parse html body fragment in lxml


rawDescription: Pattern matching and compiling

description: Pattern matching and compiling


code:
from itertools import islice, izip

def predicate(line):
    ''' you can add other general checks in here '''
    if line.startswith('Date'):
        return False # ignore it
    return True

with open('File1.txt') as f1, open('File2.txt') as f2:
    f1 = ifilter(predicate, f1)
    f2 = ifilter(predicate, f2)
    print(all(x == y for x, y in izip(f1, f2)))

rawDescription: Ignoring lines while comparing files using Python


rawDescription: How to initialize NumPy structured array with different default value for each column?

description: Initialize NumPy structured array with different default value for each column


code:
freq_list = count.values()
freq_list
max_cnt = max(freq_list)
total = freq_list.count(max_cnt)
most_common = count.most_common(total)
[elem[0] for elem in most_common]

rawDescription: Python: value that occurs the most in a list


code:
my_value_as_series = x.loc[bar==foo]['variable_im_interested_in']

# Assumes the index to get is number 0, but from your example, it might
# be 24 instead.
plain_value = my_value_as_series[0]

# Likewise, this needs the actual index value, not necessarily 0.
also_plain_value = my_value_as_series.ix[0]

# This one works with zero, since `values` is a new ndarray.
plain_value_too = my_value_as_series.values[0]

rawDescription: Extracting just a string element from a pandas dataframe


code:
def string_splosion(string):
    return ''.join(string[:i] for i in range(1, len(string) + 1))

rawDescription: python3 string "abcd" print: aababcabcd?

description: Python3 string "abcd" print: aababcabcd


code:
if settings.DEBUG:
    patterns += patterns('',
        url(r'^fs02/(?P<path>.*)$', 'django.views.static.serve',
            {'document_root': '/fs02'}))

description: SuspiciousOperation using sorl-thumbnail


code: sorted_A = sorted(A, key=make_datetime)

rawDescription: How to sort array with unique elements by datetime (Python)

description: Sort array with unique elements by datetime (Python)


code:
d = dict(list(df.groupby("Category")))
d["Thing01"]

rawDescription: Group by category in pandas DataFrame object output to dictionary object


code:
def fun(X, y, alpha):
    #some stuff
    return J, gradient

rawDescription: How to minimize one argument of a function using Scipy?

description: Minimize one argument of a function using Scipy


code: return request.args['bloburi'] + '?' + sas_token

rawDescription: Fine-Uploader in depth information on the use of Azure Blob Storage through python flask


code: env.user = 'bryan'

rawDescription: paramiko, isn't talking to ssh-agent. same behavior in fabric

description: Paramiko, isn't talking to ssh-agent. same behavior in fabric


code:
import matplotlib.pyplot as plt

plt.figure(1)
a = plt.subplot(211)
r = 2**16/2
a.set_ylim([-r, r])
a.set_xlabel('time [s]')
a.set_ylabel('sample value [-]')
x = np.arange(44100)/44100
plt.plot(x, left)
b = plt.subplot(212)
b.set_xscale('log')
b.set_xlabel('frequency [Hz]')
b.set_ylabel('|amplitude|')
plt.plot(lf)
plt.savefig('sample-graph.png')

rawDescription: Python amplitude spectrum plot

description: Python amplitude spectrum plot


rawDescription: Creating editable CrawlSpider rules in Scrapy


rawDescription: float to integer in python

description: Float to integer in python


code:
def merge(xs):
    it = iter(xs)
    ret = next(it, (None, None))
    for x in it:
        if ret[1] is None or x[0]['alt'] != ret[1]['alt']:
            yield ret
            ret = x
        else:
            ret = ret[0], x[1]
    if ret[0] is not None:
        yield ret

rawDescription: Looking for algorithm to merge tuples containing duplicate fields, within list of tuples


code:
def decontext(cm_factory):
    def factory(*cm_args, **cm_kwargs):
        cm = cm_factory(*cm_args, **cm_kwargs)
        def decorator(func):
            def wrapper(*args, **kwargs):
                with cm:
                    return func(*args, **kwargs)
            return wrapper
        return decorator
    return factory

rawDescription: Passing arguments to decontext decorator


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://tip.iatext.ulpgc.es/silabas/Default.aspx")
elem = driver.find_element_by_id("MainContent_TextBox1")
elem.send_keys("Competencia")
elem.send_keys(Keys.RETURN)
print(driver.find_element_by_css_selector("table#MainContent_Table1 > tbody > tr > td:nth-of-type(2)").text)

rawDescription: Sending and Receive data from a web page - Selenium


code:
import sympy
sympy.sympify("t**5 - t + 3")
sympy.sympify("t**5 - t + 3").subs({"t": 10})

rawDescription: Python: How to evaluate a function which is string?


code: A = [[a, b] for a, b in A if len(b) == 2]

rawDescription: How to remove a list within list based on len in python?

description: Remove a list within list based on len in python


code:
idx = tuple(slice(pp - 1, pp + 2) for pp in p)
print(x[idx])
# [[1 1]
#  [1 2]
#  [1 1]]

rawDescription: How to Find the Neighbors of a Cell in an ndarray?


code:
import random

x = random.randrange(1,1000)
counter = 0

while True:
    guess = int(input("I have a number between 1 and 1000. Can you guess my number?\nPlease type your first guess."))
    if guess == x:
        print ("Excellent! You guessed the number in", counter,"tries.")
        break
    else:
        if guess > x:
            print("high")
        else:
            print("low")
        counter += 1

rawDescription: Python: Looping issue or indentation

description: Python: Looping issue or indentation


code:
ctype = ContentType.objects.get(model='user')
related_to_user = Room.objects.filter(content_type=ctype)

rawDescription: Django - Get ContentType model by model name (Generic Relations)


code:
word0 | 10
word1 | 5
word2 | 2

rawDescription: Counter in python not showing all words

description: Counter in python not showing all words


code:
m = np.ma.masked_invalid(flux)
time2 = time[~m.mask]
time2
flux2
flux2 = flux[~m.mask]

rawDescription: Removing Corresponding Entries from Two Numpy Arrays


code:
def foreach(self, f):
    for d in self._data:
        f(d)

rawDescription: Python, lambda, find minimum

description: Python, lambda, find minimum


code: is_fetched(person, 'address')

rawDescription: Is there a way to check whether a related object is already fetched?


code:
if not (event == None):
    if(event.type == pygame.KEYDOWN):
        if (event.key == pygame.K_UP or event.key == pygame.K_SPACE):
            jump_pressed = True
    elif (event.type == pygame.KEYUP):
        if (event.key == pygame.K_UP or event.key == pygame.K_SPACE):
            jump_pressed = False

rawDescription: Pygame sprite jump with pressed key

description: Pygame sprite jump with pressed key


code:
sig_f = inspect.signature(f)
sig_g = inspect.signature(g)
sig_f.parameters
sig_f.parameters['x'].annotation
sig_g.parameters['b'].annotation
sig_f.return_annotation == sig_g.return_annotation

rawDescription: Given the name of a positional parameter to a function, can the parameter's position be determined?


code:
class Canvas_On:
    def __init__(self, master):
        # ... your original code here ...
        self.c.bind('<Button-1>', self.click)
        self.c.bind('<B1-Motion>', self.drag)

    def click(self, event):
        self.c.scan_mark(event.x, event.y)

    def drag(self, event):
        self.c.scan_dragto(event.x, event.y)

rawDescription: Moving Around A Python Canvas Without Using Scrollbars


rawDescription: Removing Negative Elements in a List - Python


code:
mask = b > a[..., -1:]
wrong = np.all(~mask, axis=-1)
index = np.argmax(mask, axis=-1)
index[wrong] = -1

rawDescription: Python/Scipy: Find "bounded" min/max of a matrix


code:
import program1
app = program1.Class(None)
app.mainloop()

rawDescription: Importing classes in python

description: Importing classes in python


code:
@inheritdocstring
class SubClassWithoutDocstring(ParentWithDocstring):
    pass

SubClassWithoutDocstring.__doc__

rawDescription: Inherit a parent class docstring as __doc__ attribute


code:
from datetime import datetime
userdateString = '2013-2-1'
datetime.strptime(userdateString, '%Y-%m-%d')

rawDescription: How to allow users to pick dates using Python

description: Allow users to pick dates using Python


code:
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
response = opener.open(image_url)
img_file = cStringIO.StringIO(response.read())
image = Image.open(img_file)

rawDescription: Python PIL: IOError: cannot identify image file


code:
import datetime

def today():
    return datetime.date.today()

rawDescription: Django unit testing with date/time-based objects


code: pd.concat( t4, t3['Population Age 0 - 14'], axis=1)

rawDescription: Do I want to join/merge, concat, or append these two Pandas DataFrames?


code: x = struct.pack('2q', random.randint(0, MAX_NUM), random.randint(0, MAX_NUM))

rawDescription: How to unpack a struct in Python?

description: Unpack a struct in Python


code:
data = pd.read_csv('meansr.txt', delim_whitespace=True)
numcols, numrows = 30, 30
xi = np.linspace(data.Lon.min(), data.Lon.max(), numrows)
yi = np.linspace(data.Lat.min(), data.Lat.max(), numcols)
xi, yi = np.meshgrid(xi, yi)
x, y, z = data.Lon, data.Lat, data.Z

# NOTE: from here on it changes
points = np.vstack((x,y)).T
values = z
wanted = (xi, yi)
zi = griddata(points, values, wanted) # for more info on griddata: http://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html

# from here its the same code again as you had
plt.figure()
plt.contourf(xi, yi, zi)
plt.scatter(data.Lon, data.Lat, c=data.Z, s=100, vmin=zi.min(), vmax=zi.max())
plt.colorbar()
plt.show()

rawDescription: converting map coordinates to lat/long

description: Converting map coordinates to lat/long


code:
from PIL import Image, ImageEnhance
image = Image.open('downloads/jcfeb2011.jpg')
contrast = ImageEnhance.Contrast(image)
image.show()

rawDescription: Using Python's PIL, how do I enhance the contrast/saturation of an image?


rawDescription: Extract document-topic matrix from Pyspark LDA Model


code:
a = numpy.array([[ 1, 2.0, "three"],
                 [ 4, 5.0, "six"  ]], dtype=object)
funcs = [lambda x: x + 10, lambda x: x / 2, lambda x: x + '!']
apply_vectorized = numpy.vectorize(lambda f, x: f(x), otypes=[object])
apply_vectorized(funcs, a)

rawDescription: Numpy: Apply an array of functions to a same length 2d-array of value as if multiplying elementwise? (using a python function as an operator?)


code:
import os
import sys

if getattr(sys,'frozen',False):
    # if trap for frozen script wrapping
    sys.path.append(os.path.join(os.path.dirname(sys.executable),'bin'))
    sys.path.append(os.path.join(os.path.dirname(sys.executable),'bin\\library.zip'))
    os.environ['TCL_LIBRARY'] = os.path.join(os.path.dirname(sys.executable),'bin\\tcl')
    os.environ['TK_LIBRARY'] = os.path.join(os.path.dirname(sys.executable),'bin\\tk')
    os.environ['MATPLOTLIBDATA'] = os.path.join(os.path.dirname(sys.executable),'bin\\mpl-data')

rawDescription: cx_freeze & bundling files

description: Cx_freeze & bundling files


rawDescription: Numpy genfromtxt Column Names

description: Numpy genfromtxt Column Names


rawDescription: Partitioning a string in Python by a regular expression


rawDescription: Why does argparse give me a list-in-a-list?


code:
from StringIO import StringIO
s = StringIO("foobar")
s.tell()
s.seek(0, 2)
s.tell()

rawDescription: How to get bytes of image in StringIO container

description: Get bytes of image in StringIO container


code:
import MySQLdb
conn = MySQLdb.connect(db="my_db", user="root", host="localhost")
curs = conn.cursor()
curs.execute("""SELECT SUBDATE(%s, INTERVAL -1 DAY)""", [date])
results = curs.fetchall()

rawDescription: How to Include a Variable as part of Subprocess Call in Python


code: plot = p.plot(x, y, pen = "y")

rawDescription: How to clear a plot in a `while` loop when using PyQtGraph?

description: Clear a plot in a `while` loop when using PyQtGraph


code:
def checkOccurence(string, checkfor):
    for i in range(len(string)):
            if  string[i:]+string[:i] == checkfor:
                    return True
    return False

rawDescription: check a string for a substring where the end of the string loops around to the start

description: Check a string for a substring where the end of the string loops around to the start


code:
lst = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']
sorted(lst)

rawDescription: Python data structure sort list alphabetically


code:
import timeit
from operator import itemgetter
import random

list_= [('a', i) for i in range(10)]
random.shuffle(list_)

def a():
    return [i[1] for i in list_].index(1)

def b():
    return zip(*list_)[1].index(1)

def c():
    return map(itemgetter(1), list_).index(1)

def d():
     for index, value in enumerate(list_):
         if 1 == value[1]:
             return index

rawDescription: Fastest way to index an element by the first element of a tuple in a list of tuples in python


code:
import re
values = re.split("\s*\|\s*", line)[1:-1]

rawDescription: constructing regexp expression to check for particular text-database format

description: Constructing regexp expression to check for particular text-database format


code:
class Desc(object):
    default_value = 10
    def __init__(self, name):
        self.name = name

    def __get__(self,obj,objtype):
        return obj.__dict__.get(self.name, self.default_value)
        # alternatively the following; but won't work with shadowing:
        #return getattr(obj, self.name, self.default_value)

    def __set__(self,obj,val):
        obj.__dict__[self.name] = val
        # alternatively the following; but won't work with shadowing:
        #setattr(obj, self.name, val)

    def __delete__(self,obj):
        pass

class MyClass(object):
    desc = Desc('varx')

rawDescription: python descriptors sharing values across classes

description: Python descriptors sharing values across classes


code:
b=foo()
b()

rawDescription: What exactly is contained within a obj.__closure__?


code:
s = "C BOS  - Traded from Royal Disappointments  -  foobar"
re.split(r'\s*-\s*', s, 1)

rawDescription: Python Regular Expressions re.findall -- split a string into two


code:
class Class1():
    def __init__(self):
        self.prop1=11

# This object is accessed by both sets of routes
obj1 = Class1()

rawDescription: How can Blueprint Flask routes in different files access shared objects


code:
orders = Order.objects.filter(exhibition=data)
formset = CourierFormSet(queryset=orders)

rawDescription: Multiple text fields with id's in django


code:
d = {1:[1,6,16],2:[1],7:[6]}
for lst in d.values(): lst[:] = [x for x in lst if x >= 16]

d
for k in list(d):
    if not d[k]:
        del d[k]

d

rawDescription: Delete numbers from dictionary of lists

description: Delete numbers from dictionary of lists


rawDescription: Combine many similar regex in one in Python


code:
example8.py
def main(command: ("SQL query", 'option', 'q'), dsn):
    if command:
        print('executing %s on %s' % (command, dsn))
        # ...

if __name__ == '__main__':
    import plac; plac.call(main)

rawDescription: How to make sys.argv arguments optional? (Python)

description: Make sys.argv arguments optional? (Python)


rawDescription: Python Ctypes: Convert returned C array to python list, WITHOUT numpy


code:
for match in reg.findall('"this is", "my test"'):
    print(match)

rawDescription: Python regex to find only second quotes of paired quotes


rawDescription: Remove occuring elements from multiple lists (shorten multiple lists) by value


rawDescription: How can fractional number expressions be parsed using pyparsing?


rawDescription: How to parse a number from line

description: Parse a number from line


code:
class FunkyCmpFoo( foo ):
    def __cmp__( self, other ):
        return -1

rawDescription: How can i change the __cmp__ function of an instance (not in class)?

description: Change the __cmp__ function of an instance (not in class)


code: my_list[ (my_list.index(400) + 1) % len(my_list) ]

rawDescription: Previous and next item of list python

description: Previous and next item of list python


code:
soup = BeautifulSoup(r.content)
soup.find_all(lambda tag: "agricultural" in tag.string if tag.string else False)

rawDescription: Python scraping with BeautifulSoup, Only scrape paragraphs with certain word in it


rawDescription: How to ignore quotes while splitting strings python

description: Ignore quotes while splitting strings python


rawDescription: Removing intersection between data frame based on multiple columns


rawDescription: Matplotlib: Gridspec and aspect='auto' not compatible?


rawDescription: Python: Remove top 'n' keys from a dictionary


code:
import os
os.environ['PAGER'] = 'cat'
help(os)

rawDescription: How to disable Python shell spawning less with "help"

description: Disable Python shell spawning less with "help"


code:
df.shape
(11, 1)

sdf.shape
(11, 1)

rawDescription: sparse versions of Pandas DataFrame

description: Sparse versions of Pandas DataFrame


code: the_function(a,b,c,d, *args, **kwargs)

rawDescription: multiprocess.apply_async How do I wrap *args and **kwargs?

description: Multiprocess.apply_async How do I wrap *args and **kwargs


code:
try:
    cart = request.user.cart
except Cart.DoesNotExist:
    cart = Cart.objects.create(user=request.user)
    cart_details = cart.cart_details.all().order_by('-date_added')

rawDescription: Python/Django: RelatedObjectDoesNotExist: Cart has no user


code:
import redis
r = redis.StrictRedis(host='localhost', port=6379, db=0)
for e in yourlist:
    r.rpush('yourlist', e)

rawDescription: Store SQL query result into Redis using Python?


code:
def cut_out_emphasis(str1):
    list1 = ["b", "i", "ul"]
    str2 = ""
    for x in list1:
        str2 = r'%s|%s|\/%s' % (str2, x, x)
    str2 = r'<(%s)[^>]*>' % (str2, )
    str1 = re.sub(str2, ', ', str1, flags=re.I)
    return str1

rawDescription: python regex sub compile with flags

description: Python regex sub compile with flags


code:
class EvenNumbers(object):

    # Add other container methods as needed

    def __contains__(self, value):
        return value % 2 == 0

even_numbers = EvenNumbers()

rawDescription: Translating a callable test into a collection membership test


code:
conditions = (check_size, check_color, check_tone, check_flavor)
checks = (condition() for condition in conditions)
return next((check for check in checks if check), None)

rawDescription: Pythonic way to avoid "if x: return x" statements


code:
def __sum_of_cards(self):
    return self.card1.value + self.card2.value

rawDescription: Python - __str__ returning elements of a list


code:
import numpy as np

P = np.array([1, 2, 3, 4, 5])
T = np.array([0, 0, 1, 1, 1])

U,inverse = np.unique(T,return_inverse=True)
Q = np.bincount(inverse,weights=P)
print (Q, U)
# (array([  3.,  12.]), array([0, 1]))

rawDescription: Numpy vectorization algorithms to sum up numbers with the same time stamps


rawDescription: Python simple naked objects

description: Python simple naked objects


code:
from binascii import hexlify
hexlify(struct.pack('!Bhh', 1, 1, 10))

rawDescription: Python struct.pack dropping a byte.

description: Python struct.pack dropping a byte.


code:
if __name__ == "__main__":
    a = Example()
    loop = gobject.MainLoop()
    loop.run()

rawDescription: Register a "Hello World" DBus service, object and method using Python


rawDescription: Trying to create an array of x and y values after reading file in Python


code:
import numpy as np

N, M = 10, 20
a = np.random.random((N,M))
b = np.random.random((N,M))
x = a + b*1j

def orig(x):
    X = np.empty((x.shape[0], x.shape[0]), dtype='complex128')
    for i in range(x.shape[0]):
        for j in range(x.shape[0]):
            X[i, j] = np.vdot(x[i], x[j])
    return X

def alt(x):
    return np.einsum('ik,jk->ij', np.conj(x), x)

assert np.allclose(orig(x), alt(x))

rawDescription: Pairwise vdot using Numpy

description: Pairwise vdot using Numpy


code: df.drop(random.sample(df.columns, 1), axis = 1) * z

rawDescription: python: multiplication of array to pandas dataframe

description: Python: multiplication of array to pandas dataframe


code:
n = int(input("Enter the start number: "))

if -6 < n < 2:
    for x in range(n, 38 - (n < -4), 6):
        for j in range(x,  x + 6):
            print("{:>2}".format(j), end=" ")
        print()

rawDescription: How to generate rows and columns in Python 3

description: Generate rows and columns in Python 3


code:
found = False
for c in list1[i]:
    if c == char:
        found = True
        break

rawDescription: Print only the list items that contain a certain character


code:
rcParamsDefault = RcParams([ (key, default) for key, (default, converter) in \
                    defaultParams.iteritems() ])

rawDescription: .matplotlibrc and default options

description: .matplotlibrc and default options


code:
def get_variables(self, variable_names=None):
    while not self.end_of_stream():
        ...
        if variable_names:
            variable_names.remove(name)
            if len(variable_names) == 0:
                break

rawDescription: Why is scipy.io.loadmat failing to filter out variables on all but the first iteration of this generator function?


code: ', '.join(map(str, (t[0] for t in new_li)))

rawDescription: Mapping modified string indices to original string indices in Python


code:
import rules

# compile regex
compiled = dict([(re.compile(regex), action_name) for (regex, action_name) in rules.mappings])

def incoming(msg):
    for regex, action_name in compiled:
        if regex.search(msg):
            # if search is successfull, execute action
            action_function = getattr(rules, action_name)
            action(msg)

rawDescription: Python: Loading data from a file into an IRC bot


code:
import os
with open('input.txt', 'r') as f, open("new_file",'w') as f1:
   for line in f:
       if 'string' in line:
          f1.write("somedate\n")  # Move f1.write(line) above, to write above instead
       f1.write(line)
os.remove('input.txt')  # For windows only
os.rename("newfile", 'input.txt')  # Rename the new file

rawDescription: How do I write a string to a specific line number?

description: Write a string to a specific line number


code:
assert os.path.isfile("D:\\Work\\Python Workspace\\Android_API_Parser\\test.txt")
assert os.path.isfile(r"D:\Work\Python Workspace\Android_API_Parser\test.txt")
assert os.path.isfile("D:/Work/Python Workspace/Android_API_Parser/test.txt")
assert os.path.isfile(os.path.join("D:", "Work", "Python Workspace",
                                   "Android_API_Parser", "test.txt"))

rawDescription: Python os.isfile assert failing

description: Python os.isfile assert failing


code:
X, Y = np.meshgrid(x, y, copy=False)
Z = function(X, Y) # I don't know how you are getting the z values from...

import matplotlib.pyplot as plt
plt.contour(X, Y, Z) # non-filled contour

rawDescription: Smooth contour plot in matplotlib from 3 lists of different size


code: [s for s in [''.join(j for j in i if j not in forbiddenList) for i in tempList] if s]

rawDescription: how to remove characters from items in a list, using another list as reference

description: Remove characters from items in a list, using another list as reference


code:
myfunc = str2func(myStruct.myFunction);
myfunc(5)

rawDescription: save matlab function to disk using scipy

description: Save matlab function to disk using scipy


rawDescription: Python - Why doesn't this instance method need parentheses when called inside another instance method?


code:
import arrow

def get_week(dt):
    mydate = arrow.get(dt)
    start = mydate.floor('week')
    end = mydate.ceil('week')
    return arrow.Arrow.range('day', start, end)

rawDescription: How to get a list of dates from a week number in python

description: Get a list of dates from a week number in python