code:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def wait_for_element(self, elm, by = 'id', timeout=10):
    wait = WebDriverWait(self.driver, timeout)
    wait.until(EC.presence_of_element_located((By.CLASS_NAME, elm)))
    return self.driver.find_element_by_class_name(elm)

wait_for_element(self, "highlight", "class").click()

rawDescription: Django - Selecting Autocomplete-Light choices with Selenium


code:
import random
rand = random.Random()       # change to random.Random(1234) for repeatable results

chosen = set()
s0 = rand.sample(u, 500)
chosen.update(s0)
s1 = rand.sample([x for x in v if x not in chosen], 500)
chosen.update(s1)
s2 = rand.sample([x for x in w if x not in chosen], 500)
chosen.update(s2)

rawDescription: python file manipulations (bash script porting)

description: Python file manipulations (bash script porting)


code:
import sys
path = sys.argv[1]
sys.path.append(path)
import urllib
import httplib

rawDescription: Importing Python Librarys over C#?

description: Importing Python Librarys over C#


code:
import scipy.interpolate as spint
import scipy.spatial.qhull as qhull
import itertools

def interp_weights(xyz, uvw):
    tri = qhull.Delaunay(xyz)
    simplex = tri.find_simplex(uvw)
    vertices = np.take(tri.simplices, simplex, axis=0)
    temp = np.take(tri.transform, simplex, axis=0)
    delta = uvw - temp[:, d]
    bary = np.einsum('njk,nk->nj', temp[:, :d, :], delta)
    return vertices, np.hstack((bary, 1 - bary.sum(axis=1, keepdims=True)))

def interpolate(values, vtx, wts):
    return np.einsum('nj,nj->n', np.take(values, vtx), wts)

rawDescription: Speedup scipy griddata for multiple interpolations between two irregular grids


code:
with open('datafile.csv') as f:
    d = {}
    next(f)    # skip first header line
    next(f)    # skip second header line
    for line in f:
        id_, value, amount = line.split()
        d[id_] = d.get(id_, []) + [(int(value), int(amount))]

# sum and average of column Value by ID
for id_ in d:
    total = sum(t[0] for t in d[id_])
    average = total / float(len(d[id_]))
    print('{}: sum = {}, avg = {:.2f}'.format(id_, total, average))

rawDescription: get value of one column by another column in csv file python

description: Get value of one column by another column in csv file python


code:
x = np.random.randint(10000, size=100000000)
y = x * 0.10
np.column_stack((x,y))

rawDescription: How do I create matrix in numpy to be called like this?

description: Create matrix in numpy to be called like this


code:
def outOfFocus(self, widget):
    focusInFrame = False
    for child in widget.get_parent():
        if child.has_focus():
            focusInFrame = True
    if focusInFrame == False:
        theFrame.hide()

rawDescription: Detecting focus-out event on a frame

description: Detecting focus-out event on a frame


code:
def num_years(begin, end=None):
    if end is None:
        end = datetime.now()
    num_years = int((end - begin).days / 365.25)
    if begin > yearsago(num_years, end):
        return num_years - 1
    else:
        return num_years

rawDescription: Python timedelta in years

description: Python timedelta in years


code:
a
(np.arange(a.max()) == a[:,:,None]-1).astype(int)

rawDescription: Convert a 2d matrix to a 3d one hot matrix numpy


rawDescription: Operations on 'N' dimensional numpy arrays


rawDescription: Create constrained random numbers?

description: Create constrained random numbers


code:
#include "cursorshapearea.h"
qmlRegisterType<QsltCursorShapeArea>("Cursor", 1, 0, "CursorShapeArea");

rawDescription: Cursor shape in QML

description: Cursor shape in QML


code:
st = set("""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~""")
with open("text.txt") as f:
    out = []
    for line in f:
        temp = ""
        for ch in line:
            if ch not in st:
                temp += ch
            else:
                temp += " {} ".format(ch)
        out.extend(temp.split())

rawDescription: Splitting strings at multiple delimiters in python


code:
import logging

def expensive_func(*args):
    print('Expensive func called: %s' % (args,))
    return sum(args)

class DeferredMessage(object):
    def __init__(self, func, *args):
        self.func = func
        self.args = args

    def __str__(self):
        return 'Message {0}'.format(self.func(*self.args))

if __name__ == '__main__':
    logging.basicConfig()
    logging.info(DeferredMessage(expensive_func, 1, 2))
    logging.warning(DeferredMessage(expensive_func, 3, 4))
    logging.error(DeferredMessage(expensive_func, 5, 6))

rawDescription: Python: how to do lazy debug logging

description: Python: how to do lazy debug logging


code:
image_median = np.median(image_stacks, axis=0).astype(np.uint8)
image = Image.fromarray(image_median)

rawDescription: Stack multiple images in python pillow

description: Stack multiple images in python pillow


rawDescription: Scipy label erosion

description: Scipy label erosion


rawDescription: Python regular syntax remove @ string until space


code:
test = StringIO(u'This is a test containing Unicode data: \ua000'.encode('utf8'))
readUTF8(test, 41)

rawDescription: Reading UTF-8 strings from a binary file


code:
class VideoContent(models.Model):
    ...
    def save(self, *args, **kwargs):
        self.size = self.file.size
        super(VideoContent, self).save(*args, **kwargs)
        self.size = self.file.size

rawDescription: IntegerField automatically set to size of FileField


code:
eventsdb_subset = self.eventsdb_subset
self.eventsdb_subset = sqldf('SELECT * from eventsdb_subset WHERE %s' % filterstring,locals())
self.db_info_string.set('Number of events: ' +str(len(self.eventsdb_subset)))

rawDescription: Updating Tkinter label from a StringVar happens on a delay


code:
amino_acid_counts = dict.fromkeys(aaDict.values(), 0)
for c in codons:
    amino_acid_counts[aaDict[c]] += 1

rawDescription: Python counting all instances of a value which has more than one key


code:
df = pd.DataFrame({'RZS': ['1.087,29', '1.087.087,28', '1.087.087.087,28']})

def fix(x):
    return x.replace('.', '').replace(',', '.')

df['RZS'] = df['RZS'].apply(fix).astype(float)

# The column RZS now should be of dtype float, and pivot_table should work.

rawDescription: Python - get a dataframe with time as index and several dates as columns


code:
whitespace = "\r\n\t"
my_string.strip(whitespace)

rawDescription: strip whitespace except spaces

description: Strip whitespace except spaces


code:
# List of users and passwords
USERS = {
    'rod': 'password1',
    'jane': 'password2',
    'freddy': 'password3'
}
# Initial name->initial session with cookies
sessions = {name:requests.session().get(URL) for name in USERS}
# Login users
sessions.update(
    (name, session.post(URL, data={'Command': 'LOGIN', 'username': name, 'password': USERS[name]}))
    for name, session in sessions.items()
)
# Now do something with users
r1 = sessions['rod'].get('http://something.com')
r2 = sessions['freddy'].get('http://something.com', params={'foo': 'bar'})
# etc...

rawDescription: Why I can't fill this form using Python "requests" library?


rawDescription: Python AST: How to get the children of a node


code: ''.join([t[1] for t in new_li])

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


code:
rng = np.arange(4).reshape(4, 1, 1)
cmyk = lut[rgb[0], rgb[1], rgb[2], rng]

rawDescription: Fancier Fancy Indexing in NumPy?

description: Fancier Fancy Indexing in NumPy


code:
from sympy import Interval

coverage = Interval(0,20) + Interval(15,20) + Interval(30,50)
target = Interval(0, 50)

return coverage.subset(target)

rawDescription: How to check if a number is present in a group of ranges?

description: Check if a number is present in a group of ranges


code: data = np.genfromtxt(fobj, dtype=desc)

rawDescription: importing an array from a .dat file in python

description: Importing an array from a .dat file in python


code:
form_cls = make_order_edit_form(fields)
order_form = form_cls(request.POST, instance=order)

rawDescription: How to dynamically create a ModelForm based on James Bennett's article "So you want a dynamic form"?

description: Dynamically create a ModelForm based on James Bennett's article "So you want a dynamic form"


code: self.tc = wx.TextCtrl(self, wx.TE_MULTILINE|wx.TE_PROCESS_ENTER, size=(200,100))

rawDescription: Enter key in wx.TextCtrl on Mac has no effect


code:
def f(n):
    return '<' + str(num) + '>'

class C(object):

    v = f(9)
    w = f(42)

rawDescription: The best way to invoke methods in Python class declarations?

description: Invoke methods in Python class declarations


code: hero = Hero(**my_hero)

rawDescription: Mixing class and instance variables together


rawDescription: Retrieving an item from a 2D list

description: Retrieving an item from a 2D list


code:
def divisible_by_five_A():
    for n in range(100):
        if n and not n % 5:
            return n, 1

divisible_by_five_A()
# O: 5, 1

rawDescription: Depth first search: return values

description: Depth first search: return values


rawDescription: Converting file data to nested list

description: Converting file data to nested list


code:
from fuzzywuzzy.fuzz import partial_ratio
Df['Description'].apply(lambda x: max(topics, key=lambda t: partial_ratio(x, t)))

rawDescription: How to replace all words in a series with a few specified words in Pandas,Python?

description: Replace all words in a series with a few specified words in Pandas,Python


code:
s = '$x^2+2\\cdot x + 2 = 0$'

print(s.replace('$', '\$'))   # Technically works, but not as clear
# \$x^2+2\cdot x + 2 = 0\$

print(s.replace('$', '\\$'))  # Escaping the backslash
# \$x^2+2\cdot x + 2 = 0\$

print(s.replace('$', r'\$'))  # Using a raw string
# \$x^2+2\cdot x + 2 = 0\$

rawDescription: Replacing a string by a string with backslashes


code:
def with_step(step):
    def simple(value, target):
        if value < target:
            value = min(value + step, target)
        else:
            value = max(value - step, target)
        return value
    return simple

gen = RampUp()
gen.target = 20
# you could move this line into the class
# reaches the target value in 12 steps
gen.calc = with_step((gen.target - gen.value)/12.)

rawDescription: Ramping Joystick values over time

description: Ramping Joystick values over time


code: subprocess.call(['inkscape', '-D', '-A', outfn, inpfn])

rawDescription: Inkscape extension in Python

description: Inkscape extension in Python


code:
import web

urls = (
    '/', 'Index',
    '/search/text=(.*)', 'Search',
)

render = web.template.render('templates/')

search_form = web.form.Form(
        web.form.Textbox(
            'text',
            web.form.regexp(r"\S+", "It mustn't be empty"),
            size=30,
            description='Text'),
        web.form.Button('Apply'),
    )

class Index:

    def GET(self):
        form = search_form()
        text = 'Hello'
        return render.index(form, text)

    def POST(self):
        form = search_form()
        if not form.validates():
           text = 'Bad Text'
           return render.index(form, text)
        else:
           url = '/search/text=%s' % form.d.text
           web.seeother(url)

class Search:

    def GET(self, text):
        form = search_form()
        return render.search(form, str(text))

    def POST(self, text):
        form = search_form()
        if not form.validates():
           text = 'Bad Text'
           return render.index(form, str(text))
        else:
           url = '/search/text=%s' % form.d.text
           web.seeother(url)

class MyApplication(web.application):
    def run(self, port=8080, *middleware):
        func = self.wsgifunc(*middleware)
        return web.httpserver.runsimple(func, ('127.0.0.1', port))

if __name__ == "__main__":
    app = MyApplication(urls, globals())
    app.run(port=8102)

rawDescription: Webpy doesn't validates form

description: Webpy doesn't validates form


rawDescription: Check if sympy expression contains function


code:
def func(y):
   return y**2

rawDescription: How to bring variables into functions - Python

description: Bring variables into functions - Python


code:
currencies = {}
trs = soup.find_all('tr') # find rows
for tr in trs[1:-3]: # skip first and last 3 (or whatever)
    text = list(tr.strings) # content of all text stuff in tr (works in this case)
    # [u'U.S Dollar', u'USDGHS', u'1.8673', u'1.8994']
    currencies[text[1]] = [float(text[2]), float(text[3])]

rawDescription: python scraping exchange rate data

description: Python scraping exchange rate data


code:
import tornado.web
from tornado.ioloop import IOLoop

class AboutPageHandler(tornado.web.RequestHandler):
    def get(self, lang=None):
        self.write("HI {}\n".format(str(lang)))

if __name__ == "__main__":
    app = tornado.web.Application([
       #(r'/([A-Za-z]{2})/about/?', AboutPageHandler)       # Old, busted regex
        (r'/(?:([A-Za-z]{2})/)?about/?', AboutPageHandler)  # New, hot regex
        ])
    app.listen(8888)
    IOLoop.instance().start()

rawDescription: How do I direct different URL's with optional capture groups to the same Handler?

description: Direct different URL's with optional capture groups to the same Handler


code:
array([[False, False, False,  True, False, False, False, False],
       [False,  True,  True,  True,  True,  True, False, False],
       [False,  True,  True,  True,  True,  True, False, False],
       [ True,  True,  True,  True,  True,  True,  True, False],
       [False,  True,  True,  True,  True,  True, False, False],
       [False,  True,  True,  True,  True,  True, False, False],
       [False, False, False,  True, False, False, False, False],
       [False, False, False, False, False, False, False, False]], dtype=bool)

rawDescription: Applying circular mask with periodic boundary conditions in python


code:
df['count'] = df.reset_index().merge(df.shift(1).reset_index().rename(columns={'coulmnis':'newcol'})) \
                .set_index('timestmp').apply((lambda x: len(x['coulmnis'] & x['newcol']) if pd.notnull(x['newcol']) else 0),axis=1)

rawDescription: Pandas dataframe column containing list, Get intersection of two consecutive rows


code:
output = "\n".join(i[0] for i in matches)
g.write(output)

rawDescription: Writing items to file on separate lines without blank line at the end


code: (line.split() for line in f)

rawDescription: how to parse column data to arrays?

description: Parse column data to arrays


code:
def unpickle_iter(file):
    try:
        while True:
             yield cPickle.load(file)
    except EOFError:
        raise StopIteration

rawDescription: Can I stream a Python pickle list, tuple, or other iterable data type?

description: Stream a Python pickle list, tuple, or other iterable data type


code:
import pyodbc

MDB = 'c:/path/to/my.mdb'
DRV = '{Microsoft Access Driver (*.mdb)}'
PWD = 'my_password'

conn = pyodbc.connect('DRIVER=%s;DBQ=%s;PWD=%s' % (DRV,MDB,PWD))
c = conn.cursor()
c.execute("ALTER TABLE my_table ADD COLUMN my_column INTEGER;")
conn.commit()
c.close()
conn.close()

rawDescription: Add new field to access table using python


code: c = a + b

rawDescription: Union of two lists in Python

description: Union of two lists in Python


code: output[:] = input

rawDescription: Python: Output list = x largest numbers of input list


rawDescription: Conditionally and interatively calculate column based on value of three columns


code:
def create_post(request, post_id):
    post = Post.objects.get(pk=post_id)
    PostImageInlineFormSet = inlineformset_factory(Post, PostImage, fields=('image',))
    if request.method == "POST":
        formset = PostImageFormSet(request.POST, request.FILES, instance=post)
        if formset.is_valid():
            formset.save()
            return redirect('index')
    else:
        formset = PostImageFormSet(instance=post)
    return render(request, 'manage_books.html', {'formset': formset})

rawDescription: What is the right way to attach multiple images to a post? [Django]


code:
doc = {
                'record_hash': hash,
                'level': record.level,
                'channel': record.channel or u'',
                'location': u'%s:%d' % (record.filename, record.lineno),
                "message": record.msg,
                'module': record.module or u'<unknown>',
                'occurrence_count': 0,
                'solved': False,
                'app_id': app_id,
                'sql': sql,
            }

rawDescription: customize django runserver output

description: Customize django runserver output


code:
result = pd.concat([ chunk.apply(Series.value_counts) for chunk in pd.read_csv('test.csv',index_col=0,chunksize=10000) ] )
result

rawDescription: value counts of a Database chunk by chunk using pandas

description: Value counts of a Database chunk by chunk using pandas


rawDescription: How to create a very large 2 dimensional matrix in python?

description: Create a very large 2 dimensional matrix in python


code:
import gzip
import pickle
with gzip.open('mnist.pkl.gz', 'rb') as f:
    train_set, valid_set, test_set = pickle.load(f)

rawDescription: how to unpack pkl file

description: Unpack pkl file


code:
from datetime import datetime
from monthdelta import monthdelta

dte = 'Wed 12 Nov'

start = datetime.strptime('Wed 12 Nov', "%a %d %b")
greatest = None

while start <= datetime.now():
    start += monthdelta(1)
    if start.strftime("%a %d %b") == dte:
        greatest = start

print(greatest)

rawDescription: string to date in python with the greatest possible year when dow is given

description: String to date in python with the greatest possible year when dow is given


code:
def bin(i):
    s = []
    prefix = '0b' if i >= 0 else '-0b'
    if i < 0: i = -i
    while i:
        s.append('1' if i & 1 else '0')
        i = i >> 1
    return prefix + (''.join(reversed(s)) if s else '0')

rawDescription: Python Hex File Write

description: Python Hex File Write


code:
class Member(Model):
    inviter = models.ForeignKey(
        'self',
        related_name="invited_set"
    )

rawDescription: what is the use of recursive relationship and a relationship to an undefined model in Django?

description: What is the use of recursive relationship and a relationship to an undefined model in Django


code:
class MyModel(models.Model):
    name = models.CharField(max_length=100)
    text = models.FileField(max_length=100, upload_to='.')

def display_text_file(self):
    with open(self.text.path) as fp:
        return fp.read().replace('\n', '<br>')

rawDescription: django - How to insert the content of uploaded file in template?

description: Django - How to insert the content of uploaded file in template


code: [ ''.join(p) for p in permutations('217') ]

rawDescription: 'leet' program - getting all permutations


code: fix_json("'This string has - I'm sure -  single quotes delimiters.'")

rawDescription: Proper way to deal with string which looks like json object but it is wrapped with single quote


code:
from flask import render_template

@app.route('/form/')
def hello(name=None):
    return render_template('hello.html', buttons=['A', 'B', 'C'], active_btns=['A', 'C'])

rawDescription: Using Twitter Bootstrap radio buttons with Flask


code: OperationalError: (1305, 'SAVEPOINT {{name}} does not exist')

rawDescription: Django + MySQL: savepoint does not exist?


rawDescription: Program consisting of multiple classes

description: Program consisting of multiple classes


code:
import example
spam = example.Spam()
spam.action()
spam.times_two(5)
example.action()
example.times_two()

rawDescription: Boost.Python: Wrap functions to release the GIL


code:
data = """\
0  JP2015121
1    US14822
2    US14358
3  JP2015539
4  JP2015156
"""
df = pd.read_csv(io.StringIO(data), delim_whitespace=True, index_col=0,
                 header=None, names=['Name'])

rawDescription: Pandas: read_csv (read multiple tables in a single file)


code:
from collections import defaultdict

# Keep a dictionary of our rd and pc values, with the value as a list of the line numbers each occurs on
# e.g. {'10': [1, 45, 79]}
pc_elements = defaultdict(list)
rd_elements = defaultdict(list)

with open(file, 'rb') as f:
    line_number = 0
    csvin = csv.reader(f, delimiter='\t')
    for row in csvin:
        try:
            pc_elements[int(row[0])].append(line_number)
            rd_elements[int(row[1])].append(line_number)
            line_number += 1
        except ValueError:
            print("Not a number")
            print(row)
            line_number += 1
            continue

for pc, indexes in pc_elements.iteritems():
    print("pc  {0} appears {1} times. First on row {2}, last on row {3}".format(
        pc,
        len(indexes),
        indexes[0],
        indexes[-1]
    ))

rawDescription: Time complexity of a huge list in python 2.7


rawDescription: remove rows and columns from numpy array

description: Remove rows and columns from numpy array


code:
idx = df.tag == 1
pv1 = df[ idx ].pivot_table( cols='name',
                             rows='date',
                             values='tag',
                             aggfunc=len ).shift( 1 ).fillna( 0 ).cumsum( )

rawDescription: Calculating previous chance figure for use in chi square test


code:
date_series = pd.date_range('2015-01-05', '2015-01-15', freq='1D')
date_df = pd.DataFrame(dict(date=date_series, dummy=1))

final = (
    date_df
    .merge(df, on='dummy')
    .ply_where(X.start <= X.date, X.date <= X.end)
    .groupby('date')
    .ply_select(val_count=X.size(), val_sum=X.value.sum(), median=X.value.median())
    .reindex(date_series)
    .ply_select('*', val_count=X.val_count.fillna(0), val_sum=X.val_sum.fillna(0))
    .reset_index()
)

rawDescription: Aggregate events with start and end times with Pandas


code:
words = "range(1,6) goes from  one to five".split()
correct = sorted(words)
num_sort = sorted(words,key=number_word)
backward = sorted(words,key=number_word, reverse=True)

print(correct)
print(num_sort)
print(backward[::-1])

rawDescription: Why can't Python understand integers in word form?


code:
def total_enrollment(a):
    total_students = 0
    all_in_all = 0
    for e in a:
        total_students = total_students + e[1]
        all_in_all += (e[1] * e[2])
    return (total_students, all_in_all)

rawDescription: Why does the code return wrong multiplication?


rawDescription: pandas - unstack with most frequent values in MultiIndex DataFrame

description: Pandas - unstack with most frequent values in MultiIndex DataFrame


code: email_reg.findall('Text text foo@foo.com, text text, baz@baz.com!')

rawDescription: Python split by regular expression?

description: Python split by regular expression


code:
class WrappedThingy(object):
    def __init__(self, thingy):
        self.thingy = thingy
    def __eq__(self, other):
        return self.thingy.notkey == other.thingy.notkey
    def __hash__(self):
        return hash(self.thingy.notkey)

rawDescription: Custom comparison functions for built-in types in Python


code:
import numpy as np
df['Winner'] = np.nan
for i,row in df.iterrows():
   if row.Event == gamedic[row.GameID][0]:
      df['Winner'].ix[i] = 'First'
   if row.Event == gamedic[row.GameID][1]:
      df['Winner'].ix[i] = 'Second'

rawDescription: How to calculate a rolling count of a categorical variable in pandas

description: Calculate a rolling count of a categorical variable in pandas


code:
#!/usr/bin/env python

import os

rpipe, wpipe = os.pipe()

def reader():
    import gzip
    FILE = "million_lines.txt.gz"
    os.close(rpipe)
    with gzip.open(FILE) as inf, os.fdopen(wpipe, 'wb') as outf:
        buf = bytearray(16384)  # Reusable buffer to minimize allocator overhead
        while 1:
            cnt = inf.readinto(buf)
            if not cnt: break
            outf.write(buf[:cnt] if cnt != 16384 else buf)

pid = os.fork()
if not pid:
    try:
        reader()
    finally:
        os._exit()

try:
    os.close(wpipe)
    with os.fdopen(rpipe, 'rb') as f:
        for line in f:
            if line == b'1000000\n':
                print("This is the millionth line: Python")
                break
finally:
    os.kill(pid, 9)

rawDescription: Python vs Perl: performance reading a gzipped file


rawDescription: python comprehension from two list or zip

description: Python comprehension from two list or zip


code:
class C(str):
    def __new__(cls, value, meta):
        obj = str.__new__(cls, value)
        obj.meta = meta
        return obj

c = C("hello world", "meta")
c
c.meta

rawDescription: inheritance from str or int

description: Inheritance from str or int


code: ordered = OrderedDict((k, mydict[k]) for k in myorder)

rawDescription: How to reorder a python ordered dict based on array?

description: Reorder a python ordered dict based on array


code:
a = 7   # Create "7", make "a" refer to it.
b = a   # make "b" refer to  the "7" as well.
a = 42  # Create "42", make "a" refer to it, b still refers to the "7".

rawDescription: Understanding python's name binding

description: Understanding python's name binding


rawDescription: Sort value in dictionary by value in Python


code:
NewType=type('nt',(object,),{'x':'hello'})
n=NewType()
n.x
NewType.__dict__
type(n).__dict__
vars(NewType)
vars(type(n))

rawDescription: Return dict of attribute name and value of type


code:
# -*- coding: utf-8 -*-

def run():
    code_task = get_active_task()
    code_task.new_file(factory_id='canopy.editor.code_editor', editor_type='Python')
    code_editor = code_task.active_editor
    cursor = code_editor.cursor
    cursor.write(u'# Hello world')
    code_editor.autoindent_newline()

rawDescription: Creating template files for Enthought Canopy


code:
import os, sys
def splitall(path):
    allparts = []
    while 1:
        parts = os.path.split(path)
        if parts[0] == path: # sentinel for absolute paths
            allparts.insert(0, parts[0])
            break
        elif parts[1] == path: # sentinel for relative paths
            allparts.insert(0, parts[1])
            break
        else:
            path = parts[0]
            allparts.insert(0, parts[1])
            return allparts

rawDescription: Python: change part (single directory name) of path


rawDescription: Creating an exhaustive list of `n` substrings


code:
out = [] # store lists of lists
for self.div in self.soup.findAll('li',{'class':'has-sub'}):
     out.append([x["href"] for x in self.div.find_all('a',href=True)])
     print([x["href"] for x in self.div.find_all('a',href=True)])

['#', '#', '/onepiece_book', '/onepiece', '#', '/naruto_book', '/naruto', '#', '/bleach_book', '/bleach', '/kingdom', '/tera', '/torico', '/titan', '/seven', '/fairytail', '/soma', '/amsal', '/berserk', '/ghoul', '/kaizi', '/piando']
['#', '/onepiece_book', '/onepiece']
['#', '/naruto_book', '/naruto']
['#', '/bleach_book', '/bleach']
['#', '/conan', '/silver', '/hai', '/nise', '/hunterbyhunter', '/baku', '/unhon', '/souleater', '/liargame', '/kenichi', '/dglayman', '/magi', '/suicide', '/pedal']
['#', '/dobaku', '/gisei', '/dragonball', '/hagaren', '/gantz', '/doctor', '/dunk', '/susi', '/reborn', '/airgear', '/island', '/crows', '/beelzebub', '/zzang', '/akira', '/tennis', '/kuroco', '/claymore', '/deathnote']

rawDescription: how to select specific words and put them into tuple - list?

description: Select specific words and put them into tuple - list


rawDescription: Pattern for multiplicity in python

description: Pattern for multiplicity in python


code:
match = None
if match:
    # The interpreter will never get here because `match` is None, which
    # evaluates to False when in an `if`
    print >> take, match.group(1)
elif match:
    # This `elif` is still testing against `match`, which is still None,
    # therefore, evaluated to false.
    print >> take, match2.group(1)
elif match:
    # Same drill here...
    print >> take, match3.group(1)

rawDescription: How to include "Elif" in "if match" command - Python

description: Include "Elif" in "if match" command - Python


code:
def commonElements(t1,t2):
    temp = []  # store  common elements
    st2  = set(t2)
    for ele in t1: # loop over each element in t1
        if ele in st2: # if it is in t2 add it to or temp list, set lookups are O(1)
            temp.append(ele)
    return tuple(sorted(temp)) # sort temp and convert to a tuple

In [4]: commonElements((1, 2, 3), (2, 5, 1))
Out[4]: (1, 2)

In [5]: commonElements((1, 2, 3, 'p', 'n'), (2, 5 ,1, 'p'))
Out[5]: (1, 2, 'p')

In [6]: commonElements((1, 3, 'p', 'n'), ('a', 2 , 5, 1, 'p'))
Out[6]: (1, 'p')

rawDescription: how to compare between two Tuples?

description: Compare between two Tuples


code:
def default(obj):
    if isinstance(obj, (Car, Person)):  # so if this is one of *your* objects
        return obj.__dict__             # turn it into a python dict

    raise TypeError                     # Sorry, don't know how to handle this

rawDescription: Retrieve the object from dict to that it can easily be dumped via json.dumps()


code: my_list = (int(k) for k in input().split())

rawDescription: Python - replay values in list

description: Python - replay values in list


code:
Input
[a]
b = 1
c = 2
[d]
e = 3

rawDescription: Automatically read configuration values in Python


code:
if not any(myList):
    print('all empty or evaluating to False')

rawDescription: Most concise way to check whether a list is empty or contains only None?


code:
def register_action( name ):
    def register_decorator( fcn ):
        fcn._action_name = name
        return fcn
    return register_decorator

rawDescription: differentiate between python function and class function

description: Differentiate between python function and class function


code: list(set(a) - set(b))

rawDescription: Python list difference

description: Python list difference


code:
def getAttributes(clazz):
    return {name: attr for name, attr in clazz.__dict__.items()
            if not name.startswith("__")
            and not callable(attr)
            and not type(attr) is staticmethod}

rawDescription: Get class and object attributes of class without methods and builtins


rawDescription: Sorting column entries in Pandas by name and week


code:
import subprocess
import sys
new_process = subprocess.Popen([sys.executable]+sys.argv)

rawDescription: Running Python Script Again

description: Running Python Script Again


code: plt.plot(times, np.diff(values))

rawDescription: matplotlib pylplot: plotting series of cumulative data as differences

description: Matplotlib pylplot: plotting series of cumulative data as differences


rawDescription: how to change the shape of a contour in matplotlib

description: Change the shape of a contour in matplotlib


code:
# file mainprogram.py

def read_messages_from_file(filename):
    module_dict = {}
    execfile(filename, module_dict)
    return module_dict['messages']

if __name__ == "__main__":
    from pprint import pprint
    import sys

    for arg in sys.argv[1:]:
        messages = read_messages_from_file(arg)
        pprint(messages)

rawDescription: Parsing a datafile in python (2.5.2)

description: Parsing a datafile in python (2.5.2)


code:
current_line = input()
# if length is even, we don't care about the letter in the middle
# abcde <-- just need to look for first and last 2 values
# 5 // 2 == 2
half_length = len(current_line) // 2
changes = 0
for i in range(index):
    changes += abs(
        ord(current_line[i]) - ord(current_line[-(i+1)])
    )
print (changes)

rawDescription: Python - variable not updating in loop

description: Python - variable not updating in loop


code:
ldict = locals()
for k in models.__dict__:
    if not k.startswith('__') or not k.endswith('__'):
        ldict[k] = models.__dict__[k]

rawDescription: Dynamic Loading of Modules then using "from x import *" on loaded module


rawDescription: Pandas multiIndex DataFrame sort

description: Pandas multiIndex DataFrame sort


code:
combine_events = CombineEvents.objects.filter(team__id=team_id)
for event in combine_events:
    result = event.combineresults_set.order_by('-result')[0]

rawDescription: Filter queryset to return only the best result for each user


code:
def join_punctuation(seq, characters='.,;?!'):
    characters = set(characters)
    seq = iter(seq)
    current = next(seq)

    for nxt in seq:
        if nxt in characters:
            current += nxt
        else:
            yield current
            current = nxt

    yield current

c = ' '.join(join_punctuation(b))

rawDescription: Join split words and punctuation with punctuation in the right place


rawDescription: nltk frequency combining singular and plural, verb and adverb when tokenizing

description: Nltk frequency combining singular and plural, verb and adverb when tokenizing


code:
x2 = xaxis[:,None,None]
y2 = yaxis[None,:,None]
z2 = zaxis[None,None,:]

rawDescription: numpy - evaluate function on a grid of points

description: Numpy - evaluate function on a grid of points


rawDescription: C-style escaping in python

description: C-style escaping in python


code:
def find4(S, m, d):
    combs = set()
    while len(combs) < d:
        combs.add(tuple(sorted(random.sample(S, m))))
    return combs

rawDescription: Python- exact number of subsets

description: Python- exact number of subsets


rawDescription: delete empty rows from a python list

description: Delete empty rows from a python list


rawDescription: How to convert a string into a constant tuple in Python

description: Convert a string into a constant tuple in Python


code:
def convert_postcodes(postcode_path, file_path, output_path):
    postcodes = dict()
    with open(postcode_path, 'rb') as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            code, lng, lat = row[1:4]
            postcodes[code] = [lng, lat]
    with open(file_path, 'rb') as fin, open(output_path, 'wb') as fout:
        reader = csv.reader(fin, delimiter=',')
        writer = csv.writer(fout, delimiter=',')
        for row in reader:
            code = row[3]
            row.extend(postcodes[code])
            writer.writerow(row)

rawDescription: Python struggling with data?

description: Python struggling with data


rawDescription: Django if value is in list

description: Django if value is in list


code:
def set_way():
    my_set = set()
    my_set_add = my_set.add   # remember the method
    for ele in x:
        if ele not in my_set:
            my_set_add(ele)   # call the method directly

rawDescription: What is the fastest method for checking for duplicates in python?


rawDescription: Is there a way to generate a list of indices using numpy


code: ' '.join([a[i:i+3] for i in range(0, len(a), 3)])

rawDescription: Python - How to add space on each 3 characters?


code:
import urllib
import urllib2
from bs4 import BeautifulSoup

uni_id = "P22216"
url = "http://www.rcsb.org/pdb/search/smart.do?smartComparator=and&smartSearchSubtype_0=UpAccessionIdQuery&target=Current&accessionIdList_0=%s" % uni_id
text = urllib2.urlopen(url).read()
soup = BeautifulSoup(text)
table = soup.find( "table", {"class":"queryBlue"} )
link = table.find("a", {"class":"tooltip"}).get("href")
urllib.urlretrieve("http://www.rcsb.org/" + str(link), str(link.split("=")[-1]) + ".pdb")

rawDescription: download file using python beautifulsoup and selenium

description: Download file using python beautifulsoup and selenium


code:
c2.a
c2.group.d
c2.a = 6
c2.group.d

rawDescription: Python: Idiomatic properties for structured data?


code: print('<table>')

rawDescription: Python formatting of strings with line breaks


code:
df3['Year'] = year
df3['Month'] = month

rawDescription: Excel Table into Organized Pandas Dataframe


code:
class MyListener(object):
    msg_list = []

    def __init__(self):
        self.message = []

    def on_error(self, headers, message):
        self.msg_list.append('(ERROR) ' + message)

    def on_message(self, headers, message):
        self.msg_list.append(message)

rawDescription: Stomp.py how to return message from listener


code: [e for sub in a for e in sub]

rawDescription: How to replace the nth element of multi dimension lists in Python?

description: Replace the nth element of multi dimension lists in Python


code:
import datetime
import collections
import threading

class ExpireCounter:
    """Tracks how many events were added in the preceding time period
    """

    def __init__(self, timeout=1):
        self.lock=threading.Lock()
        self.timeout = timeout
        self.events = collections.deque()

    def add(self,item):
        """Add event time
        """
        with self.lock:
            self.events.append(item)
            threading.Timer(self.timeout,self.expire).start()

    def __len__(self):
        """Return number of active events
        """
        with self.lock:
            return len(self.events)

    def expire(self):
        """Remove any expired events
        """
        with self.lock:
            self.events.popleft()

    def __str__(self):
        with self.lock:
            return str(self.events)

rawDescription: container where values expire in python

description: Container where values expire in python


code:
a, b = np.loadtxt("/home/xi_{}<zphot{:.03f}<{}_.dat".format(zcos1, sig0, zcos2),
                  unpack=True)

rawDescription: Python string formatting, include the 0 at the end


code:
from functools import total_ordering

@total_ordering
class Contact(object):
    # ...

    def __eq__(self, other):
        if self.lastName != other.lastName:
            return False
        return self.firstName == other.firstName

    def __lt__(self, other):
        if not self.lastName:
            if not other.lastName:
                return self.firstName < other.firstName
            return self.firstName < other.lastName
        return (self.lastName, self.firstName) < (other.lastName, other.firstName)

rawDescription: Python - sort method parameter takes same precedence


code: lambda item: (item[0].rsplit(None, 1)[0], item[1])

rawDescription: Python: sorting items in a dictionary by a part of a key?


code:
df = DataFrame({'one':[1,1,2,2,3], 'two':list('xyyzz'), 'three':list('eecba')}, index=list('abcde'), columns=['one','two','three'])
df
df.groupby('one').agg(lambda x: "|".join(x.order().unique().tolist()))

rawDescription: python pandas custom agg function

description: Python pandas custom agg function


code:
type(my_tree)  is Node
isinstance(my_tree, Node)

rawDescription: How to model datatypes in Python (namedtuple almost there?)

description: Model datatypes in Python (namedtuple almost there?)


code:
from werkzeug.serving import run_simple

def app(environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/plain')])
    yield str(dir(environ['wsgi.input']))

run_simple('localhost', 5000, app)

rawDescription: Changing request method using hidden field _method in Flask


code:
with open('testresult.txt', 'w') as f:
  for root, dirs, files in os.walk(path):
    found = names.intersection(files)
    for name in found:
      f.write(os.path.join(root, name) + '\n')

rawDescription: Checking if multiple specific files exist on a given drive


code: np.random.randn(5) * 10

rawDescription: Formatting floats in a numpy array

description: Formatting floats in a numpy array


code:
import numpy as np
import scipy.ndimage.filters as filters

def using_filters(data):
    return np.where(np.logical_and.reduce(
        [data == f(data, footprint=np.ones((3,3)), mode='constant', cval=np.inf)
         for f in (filters.maximum_filter, filters.minimum_filter)]))

using_filters(data)
# (array([2, 3]), array([5, 9]))

rawDescription: Retrieve position of elements with setting some criteria in numpy


code:
import requests, lxml.html

page  = requests.get('site_.com')
doc   = lxml.html.document_fromstring(page.text)
phone = doc.cssselect('.bsi-c2 .bsi-lbl')[0].text_content()

rawDescription: Python Scrapy - dynamic HTML, div and span content needed


rawDescription: appending dictionaries to a list

description: Appending dictionaries to a list


code:
class zeropad:

    def __init__(self, block_size):
        assert block_size > 0 and block_size < 256
        self.block_size = block_size

    def pad(self, pt):
        ptlen = len(pt)
        padsize = self.block_size - ((ptlen + self.block_size - 1) % self.block_size + 1)
        return pt + "\0" * padsize

    def unpad(self, ppt):
        assert len(ppt) % self.block_size == 0
        offset = len(ppt)
        if (offset == 0):
            return ''
        end = offset - self.block_size + 1
        while (offset > end):
            offset -= 1;
            if (ppt[offset] != "\0"):
                return ppt[:offset + 1]
        assert false

class cbc:

    def __init__(self, padding, cipher, iv):
        assert padding.block_size == cipher.block_size;
        assert len(iv) == cipher.block_size;
        self.padding = padding
        self.cipher = cipher
        self.iv = iv

    def encrypt(self, pt):
        ppt = self.padding.pad(pt)
        offset = 0
        ct = ''
        v = self.iv
        while (offset < len(ppt)):
            block = ppt[offset:offset + self.cipher.block_size]
            block = self.xorblock(block, v)
            block = self.cipher.encrypt(block)
            ct += block
            offset += self.cipher.block_size
            v = block
        return ct;

    def decrypt(self, ct):
        assert len(ct) % self.cipher.block_size == 0
        ppt = ''
        offset = 0
        v = self.iv
        while (offset < len(ct)):
            block = ct[offset:offset + self.cipher.block_size]
            decrypted = self.cipher.decrypt(block)
            ppt += self.xorblock(decrypted, v)
            offset += self.cipher.block_size
            v = block
        pt = self.padding.unpad(ppt)
        return pt;

    def xorblock(self, b1, b2):
        # sorry, not very Pythonesk
        i = 0
        r = '';
        while (i < self.cipher.block_size):
             r += chr(ord(b1[i]) ^ ord(b2[i]))
             i += 1
        return r

rawDescription: Python equivalent of PHP's MCRYPT_RIJNDAEL_256 CBC


code:
class UserInputStoring(UserInput):
    users = [] # this is only here, not at the parent.
    def __init__(self, *a, **k):
        super(UserInputStoring, self).__init__(*a, **k) # pass everything up as it was used
        self.users.append(self)

rawDescription: Applying the @staticmethod, python3

description: Applying the @staticmethod, python3


code:
class MyList(list):

    def __init__(self, data):
        self.condition1 = True
        self.condition2 = True
        for content in data:
            self.append(MyClass(content))

    def __iter__(self):
        return (self[i] for i in range(len(self))
                if ((self.condition1 or self[i].attr1) and
                    (self.condition2 or self[i].attr2)))

rawDescription: How to filter the return value of a class that extends the list object

description: Filter the return value of a class that extends the list object


rawDescription: How to call a "wizard view" with {% url %} statement in Django?

description: Call a "wizard view" with {% url %} statement in Django


code: return [ y[i/2] if i%2 else x for i in range(len(y)*2)]

rawDescription: list comprehension question

description: List comprehension question


code:
class TaskManager(models.Manager):
    def get_queryset(self):
        return super(self.__class__, self).get_queryset().filter(is_deleted=False)

class Task(models.Model):
    # ...
    objects = TaskManager()

rawDescription: How to expose a filtered reverse relationship in Django REST API framework?

description: Expose a filtered reverse relationship in Django REST API framework


code:
def to_json(obj):
    cls = type(obj)
    d = dict((c, getattr(obj, c)) for c in vars(cls) if isinstance(getattr(cls, c), property))
    return json.dumps(d)

rawDescription: Easier way to create a JSON object from an SQLObject


rawDescription: Pandas dataframe with column of timestamps and timezones


rawDescription: Delete columns of a matrix that are mostly zero


code: ret = pycb()

rawDescription: Calling Python functions from C++

description: Calling Python functions from C++


code: re.findall(pattern, rr[::-1])

rawDescription: Python regex - faster search

description: Python regex - faster search


rawDescription: What is the inverse function of zip in python?


code:
#!/usr/bin/env python3
import os
import string
from tempfile import NamedTemporaryFile

caesar_shift = 3
filename = 'file'

def caesar_bytes(plaintext, shift, alphabet=string.ascii_lowercase.encode()):
    shifted_alphabet = alphabet[shift:] + alphabet[:shift]
    return plaintext.translate(plaintext.maketrans(alphabet, shifted_alphabet))

dest_dir = os.path.dirname(filename)
chunksize = 1 << 15
with open(filename, 'rb') as file, \
     NamedTemporaryFile('wb', dir=dest_dir, delete=False) as tmp_file:
    while True: # encrypt
        chunk = file.read(chunksize)
        if not chunk: # EOF
            break
        tmp_file.write(caesar_bytes(chunk, caesar_shift))
os.replace(tmp_file.name, filename)

rawDescription: Python - How can I change bytes in a file


rawDescription: Recursive functions

description: Recursive functions


code:
def numbertoletter(number):
    if number >= 0 and number <= 26:
        return chr(65 + number)
    else:
        raise ValueError('Number out of range')

rawDescription: How to search nested list grid and give lettered coordinates in Python?

description: Search nested list grid and give lettered coordinates in Python


code:
def justify(n):
    return float(n) / (1<<int(log(n,2)))

rawDescription: Bitwise operations to produce power of two in Python


rawDescription: Reordering rows of a 3D array

description: Reordering rows of a 3D array


code:
f1
f2
f3
s1

rawDescription: Python: Save data with floats and strings with np.savetxt


code:
def deep_map(lst, f=int):  # the parameter `f` is the function
    for i in lst:
        if isinstance(i, collections.Iterable) and not isinstance(i, str):
            yield list(deep_map(i, f))
        else:
            yield f(i)

rawDescription: Performing operations on each item in a multilevel list


code:
import gtk

# Don't use globals in a real application,
# better to encapsulate everything in a class
handlerId = 0

def main():
    button = gtk.Button("Hello")
    scroll_win = gtk.ScrolledWindow()
    scroll_win.add(button)
    win = gtk.Window(gtk.WINDOW_TOPLEVEL)
    win.add(scroll_win)

    # Connect to expose signal to allow time
    # for the window to be drawn
    global handlerId
    handlerId = win.connect_after('expose-event', drawWindow)

    win.show_all()

def drawWindow(win, e):
    width, height = win.get_size()
    pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)

    # Retrieve the pixel data from the gdk.window attribute (win.window)
    # of the gtk.window object
    screenshot = pixbuf.get_from_drawable(win.window, win.get_colormap(),
                                          0, 0, 0, 0, width, height)
    screenshot.save('screenshot.png', 'png')

    # Disconnect this handler so that it isn't
    # repeated when the screen needs to be redrawn again
    global handlerId
    win.disconnect(handlerId)

if __name__ == '__main__':
    main()
    gtk.main()

rawDescription: Creating a screenshot of a gtk.Window

description: Creating a screenshot of a gtk.Window


code:
class StaticVarsMeta(type):

    statics = {}

    def __new__(meta, name, bases, dct):
        cls = super().__new__(meta, name, bases, dct)
        meta.statics[cls] = {}
        for key, val in dct.items():
            if hasattr(val, '__get__') and hasattr(val, '__set__'):
                meta.statics[cls][key] = {'__get__'}
                try:
                    val.__set__(None, None)
                except AttributeError as err:
                    if "can't set attribute" in err.args:
                        continue
                meta.statics[cls][key].add('__set__')
        return cls

rawDescription: Determine if class attribute is a read-only data descriptor


code: max((self.getTotalDeflection(x), x) for x in x_vals)

rawDescription: Finding the maximum return value of a function and the corresponding input for a given number of inputs


rawDescription: Python: Use Regular expression to remove something


code:
from django.http import HttpResponse
import datetime
import pprint

def prettyprint(fun):
    return lambda request:HttpResponse(
            pprint.pformat(fun(request)), mimetype="text/plain")

@prettyprint
def current_datetime(request):
    return datetime.datetime.now()

rawDescription: django generic templates

description: Django generic templates


code:
if cond1 == 'val1' and \
   cond2 == 'val2' and \
   cond3 == 'val3' and \
   cond4 == 'val4':
    do_something

rawDescription: Python style: multiple-line conditions in IFs


code: afc = {'Baltimore Ravens': {'wins':10,'losses': 3}, 'Pb Steelers': {'wins': 3,'losses': 4}}

rawDescription: Can a value in a Python Dictionary have two values?


code:
class Member:
    def __init__(self, name, dayoff):
        self.name = name
        self.dayoff = dayoff

peplist = ['A', 'B', 'C']
dolist = ['monday', 'tuesday', 'thursday']

members = [Member(name, dayoff) for name, dayoff in zip(peplist, dolist)]

rawDescription: Create object from several lists

description: Create object from several lists


rawDescription: Python Compare rows in two columns and write a result conditionally


code: np.cross(d2, d3, axisa=1, axisb=1, axisc=1)

rawDescription: Np.cross produces wrong results, search for a working alternative


code:
import a
import b
import a

rawDescription: Would multiple circular imports degrade performance?


code:
# server.py

import os
import time

pipe_name = 'pipe_test'

if not os.path.exists(pipe_name):
    os.mkfifo(pipe_name)

with open(pipe_name, 'r') as pipe:
    print("Listening for actions...")
    while True:
        action = pipe.readline()[:-1]
        if action == '':
            print("No clients. Sleeping...")
            time.sleep(1)
        else:
            print("Action received:", repr(action))

rawDescription: Interprogram communication in python on Linux


code:
import datetime
new_object = TheModel(date=datetime.date(2014, 12, 15))

rawDescription: Compare saved date field with new unsaved object


code: from mydict import mydict

rawDescription: How to get my global variables to be available during imports of other modules?

description: Get my global variables to be available during imports of other modules


code:
CLASSES = ['Google Android', 'Microsoft Windows', 'Apple Mac OS X Lion']

def classify_query(query_string):
    """
    Computes the most "likely" class for the given query string.

    First normalises the query to lower case, then computes the number of
    overlapping tokens for each of the possible classes.

    The class(es) with the highest overlap are returned as a list.

    """
    query_tokens = query_string.lower().split()
    class_tokens = [[x.lower() for x in c.split()] for c in CLASSES]

    overlap = [0] * len(CLASSES)
    for token in query_tokens:
        for index in range(len(CLASSES)):
            if token in class_tokens[index]:
                overlap[index] += 1

    sorted_overlap = [(count, index) for index, count in enumerate(overlap)]
    sorted_overlap.sort()
    sorted_overlap.reverse()

    best_count = sorted_overlap[0][0]

    best_classes = []
    for count, index in sorted_overlap:
        if count == best_count:
            best_classes.append(CLASSES[index])
        else:
            break

    return best_classes

rawDescription: Python natural language processing for named entities


code:
def example(somefunc):
  somefunc()

example(someFunction)
example(lambda x: x ** 2)

rawDescription: How to design mathematical program which calculate the derivative of a function using python?

description: Design mathematical program which calculate the derivative of a function using python


code: import pickle

rawDescription: Remember variables after code execution

description: Remember variables after code execution


code:
foo = 1000
bar = 1000
foo is bar # same value but different objects so identity test is False
foo == bar # equality test is True
id(foo) # both have different id's
id(bar)
foo = bar # now make foo point to the object bar
foo is bar # now foo is bar so identity check is True
id(bar) # matching id's
id(foo)

rawDescription: Why do the objects __name__ and __main__ have different identities in Python?


code:
rows, cols = np.where(np.all(a == b[None, None, 2], axis=-1))
assert np.all(rows * W + cols == sorted(res[2]))

rawDescription: fastest way to get lookup table indices with numpy

description: Fastest way to get lookup table indices with numpy


code: rating_data_raw = sc.textFile("/<path_to_csv_file>.csv", minPartitions=128)

rawDescription: Is there a way to control the number of partitions when reading a text file in PySpark


rawDescription: How to Parse an orderedDict?

description: Parse an orderedDict


rawDescription: What is the difference between "range(0,2)" and "list(range(0,2))"?


code:
def get_topic(topic_id):
    # magic
    return topic_with_that_id

rawDescription: Django .id usage in url function

description: Django .id usage in url function


code:
global x,y
def foo():
    x = y = 1
    global y
    x = y = 2
    # only global y is 2

def bar():
    #here x and y are not global
    x = y = 3

foo()
bar()
print(x,y) # runtime error. x undefined

rawDescription: How to parse python code to identify global variable uses?

description: Parse python code to identify global variable uses


rawDescription: Automocking for Python?

description: Automocking for Python


code: filled = interpolate_gaps(x, limit=2)

rawDescription: Working with NaN values in matplotlib

description: Working with NaN values in matplotlib


code: [df.iat[i, j] for i, j in enumerate(1 * (np.random.rand(len(df)) < .5))]

rawDescription: Random selection in pandas dataframe

description: Random selection in pandas dataframe


rawDescription: File of lists, import as individual lists in python 2.7


code:
class PerArgsBorgMeta(type):
    def __new__(mcls, name, bases, attrs):
        cls = super(PerArgsBorgMeta, mcls).__new__(mcls, name, bases, attrs)
        setattr(cls, '_{}__shared_state'.format(name), {})
        return cls

    def __call__(cls, *args, **kwargs):
        instance = super(PerArgsBorgMeta, cls).__call__(*args, **kwargs)
        context_key = hash('{0}{1}'.format(cPickle.dumps(args),cPickle.dumps(kwargs)))
        state = getattr(cls, '_{}__shared_state'.format(cls.__name__))
        instance.__dict__ = state.setdefault(context_key, {})
        return instance

rawDescription: Singleton/Borg pattern based on different parameters passed while creating the object


code: urls = [myurls[x,y] for x in range(1, 15) for y in range(1, 87)]

rawDescription: How to globally declare this Python list

description: Globally declare this Python list


code:
l = ['John Fine', 'Doug Biro', 'Jo Ann Alfred']

sorted(l, key=lambda x: x.rsplit(None,1)[-1])

rawDescription: Sort by last name

description: Sort by last name


code: result = [fdist.get(l, 0) for l in string.ascii_lowercase]

rawDescription: Sorting letter occurrences in a text alphabetically


code:
import itertools as IT
import operator

ls = ['N', 'N', 'N', 'C', 'C', 'C', 'C', 'N', 'C', 'C']

[list(zip(*g))[::-1]
 for k, g in IT.groupby(enumerate(ls), operator.itemgetter(1))
 if k == 'C']

rawDescription: Split the list by consecutive common element


rawDescription: Converting some columns of a matrix from float to int


code:
p = pd.DataFrame(a.items(), columns=['item', 'score'])
p['perc'] = p['score']/10
p

rawDescription: How to calculate percentage with Pandas' DataFrame

description: Calculate percentage with Pandas' DataFrame


rawDescription: Difference between numpy.array shape (R, 1) and (R,)


rawDescription: Merge 2 arrays vertical to tuple Numpy

description: Merge 2 arrays vertical to tuple Numpy


rawDescription: python change str to hex, NOT CONVERTING

description: Python change str to hex, NOT CONVERTING


rawDescription: Searching for a line in a jpg file Python


code: plt.subplots_adjust(left=0.1, right=0.9, bottom=0.1, top=0.9)

rawDescription: Adjusting space around figure with subplots


rawDescription: Easiest way to replace a string using a dictionary of replacements?


rawDescription: How do I turn a list of tuples into a dictionary while keeping redundant values?

description: Turn a list of tuples into a dictionary while keeping redundant values


code: x += y+z

rawDescription: Possible to append multiple lists at once? (Python)


code:
try_quiet_nan = struct.unpack(">d", "\x7f\xf8\x00\x00\x00\x00\x00\x00")[0]
struct.pack(">d", try_quiet_nan).encode("hex_codec")

rawDescription: How to distinguish different types of NaN float in Python

description: Distinguish different types of NaN float in Python


rawDescription: forced conversion of non-numeric numpy arrays with NAN replacement

description: Forced conversion of non-numeric numpy arrays with NAN replacement


code:
class AttributeDict(dict):
    __getattr__ = dict.__getitem__

class Foo (object):
    def __init__(self,d):
        self.d=d

    @property
    def return_d(self):
        return AttributeDict(self.d)

rawDescription: Python Classes: adding dynamic attributes to methods


code:
a = {
    'breakfast': {
        'time': "8AM",
        'items': ['banana', 'yogurt']
    },
    'lunch': {
        'time': '2PM',
        'items': ['fish', 'tartar sauce']
    },
    'dinner': {
        'time': '8PM',
        'items': ['soup', 'salad']
    }
}

rawDescription: Dictionaries store pairs. Who stores triples?


rawDescription: How does one get an Enum's members into the global namespace?

description: Get an Enum's members into the global namespace


code:
def multiply():                                                                                #starts sub program when 'multiply()' is called
    num1 = random.randint(1,12)                                                                     #randomly generates a number between 1 and 12
    num2 = random.randint(1,12)
    while loop == True:                                                                             #creates loop, and uses previously defined 'loop'
        try:
            ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? "))          #asks question and requires a user input
            correct = (ans == num1 * num2)
            if correct:
                print("You are correct! ")
                break                                                                                #if the answer is correct, it prints 'You are correct!' and breaks to avoid the loop
            else:
                print("Wrong, please try again. ")
            loop == False
        except ValueError:
            print("That is not an option")

rawDescription: Letters inside "int(input(())"

description: Letters inside "int(input(())"


code: 'MATERIAL 4 {clad-den} {clad-temp} 2'.format(**data)

rawDescription: python - replace string entry with a dictionary entry

description: Python - replace string entry with a dictionary entry


code:
#!/usr/bin/python
import sys

ret = sys.stdout.write("Greetings, human!\n")
print("return value: <{}>".format(ret))

rawDescription: Strange output when writing to stdout in console


code:
from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def get_by_name(context, name):
    return context[name]

rawDescription: django templates - how to dynamically access variable?

description: Django templates - how to dynamically access variable


code: get_key = get_key_(start)

rawDescription: Using Apache-Spark to analyze time series


code: process_Festival = subprocess.Popen(["festival", "--tts", "/var/log/dmesg"])

rawDescription: how to kill a process group using Python subprocess

description: Kill a process group using Python subprocess


code: {i:(''.join(str(x) for x in j[0]) if j else '') for i,j in d.items()}

rawDescription: Stripping whitespace and joining multiple values stored in a single key in a dictionary


code: grp = df.groupby('A')

rawDescription: Pandas sort by group aggregate and column


rawDescription: Heapsort not working in Python for list of strings using heapq module


code:
TC = C + MktFrac*P + PayFrac*P
TP = P - TC
PM = TP / P

rawDescription: Calculate product price based on multiple percentage factors


code: df

rawDescription: Pandas - Convert Unbalanced Panel Data to Cross Section


code:
def rand_str():
    return str.join("", (chr(random.randrange(97, 123))
                         for i in range(random.randrange(3, 16))))

class A(object):
    def __init__(self):
        self.x = rand_str()
        self.y = rand_str()
    def __hash__(self):
        return hash(self.x)
    def __eq__(self, other):
        return self.x == other.x

rawDescription: Python: Retrieve items from a set

description: Python: Retrieve items from a set


code: array[xs, :]

rawDescription: Manipulation with arrays in numpy

description: Manipulation with arrays in numpy


rawDescription: Remove words of length less than 4 from string


code:
###########
# Imports #
###########
import pandas
import datetime
import numpy as np
from dateutil import relativedelta
from pandas.io import data as pdata

############################################
# Functions to retrieve Yahoo finance data #
############################################

# Utility to get generic stock symbol data from Yahoo finance.
# Starts two days prior to present (or most recent business day)
# and goes back a specified number of days.
def getStockSymbolData(sym_list, end_date=datetime.date.today()+relativedelta.relativedelta(days=-1), num_dates = 30):

    dReader = pdata.DataReader
    start_date = end_date + relativedelta.relativedelta(days=-num_dates)
    return dict( (sym, dReader(sym, "yahoo", start=start_date, end=end_date)) for sym in sym_list )
###

# Utility function to get some AAPL data when needed
# for testing.
def getAAPL(end_date=datetime.date.today()+relativedelta.relativedelta(days=-1), num_dates = 30):

    dReader = pdata.DataReader
    return getStockSymbolData(['AAPL'], end_date=end_date, num_dates=num_dates)
###

rawDescription: How to take out the column index name in dataframe

description: Take out the column index name in dataframe


code:
example_list = ['turtle','cow','goat','pig','swag']
number_of_ones = 1
for item in example_list:
    globals()['a'+('1'*number_of_ones)] = item
    number_of_ones += 1

print(a11111) # prints 'swag'

rawDescription: Looping Function to Define variables

description: Looping Function to Define variables


rawDescription: Python: calling another python script

description: Python: calling another python script


code:
import timeit, partial, re
ascii_only = partial(re.compile(r'[^a-zA-Z]').sub, '')
timeit.timeit('f(t)', 'from __main__ import ascii_only as f, inputtext as t')
timeit.timeit('t.translate(None, m)', 'from __main__ import inputtext as t, non_letters as m')

rawDescription: how to Ignore characters other than [a-z][A-Z]

description: Ignore characters other than [a-z][A-Z]


code:
sentence = 'The cat sat on the mat.'
sentence.count('a')

rawDescription: How can i change a string that counts how many letters in a sentence into counting the occurence of one letter?

description: Change a string that counts how many letters in a sentence into counting the occurence of one letter


rawDescription: How do I display tuples in columns? [Python]

description: Display tuples in columns? [Python]


rawDescription: taking input to the .c file using pyqt

description: Taking input to the .c file using pyqt


rawDescription: Searching for content between non-tag strings


code:
milestone["only_date"] = [d.date() for d in milestone["datetime"]]
milestone["only_time"] = [d.time() for d in milestone["datetime"]]

rawDescription: How do you extract only the date from a python datetime?

description: Extract only the date from a python datetime


code:
class RandomPerson(Person):
    def __new__(cls):
        new = super().__new__(cls)
        new.__dict__.update(random.choice((Kyle,John)).__dict__)
        return new

rawDescription: python class factory inherit random parent

description: Python class factory inherit random parent


rawDescription: How to build an undo storage with limit?

description: Build an undo storage with limit


code:
if event.key in (pygame.K_ESCAPE, pygame.K_q):
    pygame.quit()

rawDescription: Easier way of getting keyboard input in Pygame?


code:
from nltk import sent_tokenize, word_tokenize, pos_tag
sent = "John write His name as Ishmael"
[pos_tag(word_tokenize(i)) for i in sent_tokenize(sent)]
tagged_sent = [pos_tag(word_tokenize(i)) for i in sent_tokenize(sent)]
[[(word,"CAPITALIZED" if word[0].isupper() else None, "noun" if word[1][0] == "N" else "non-noun") for word,pos in sentence] for sentence in tagged_sent]

rawDescription: How to find elements of an array in Python and add more information to it

description: Find elements of an array in Python and add more information to it


code: [m.group(0) for m in re.finditer("(ABC)+\d+", s)]

rawDescription: Regular Expression: Include Text After (...) Group


code:
import numpy
lst = []
with open('path/to/input') as infile:
    copy = False
    for line in infile:
        if line.strip() in ["Biography"]:
            copy = True
            lst.append([line.strip()])
        elif line.strip() in ["Place of Birth"]:
            copy = False
        elif copy:
            lst[-1].append(line.strip())

lst = list(zip(*lst))
n = numpy.array(lst)
numpy.savetext("foo.csv", n, delimiter=",")

rawDescription: Extracting text between two strings/title


code:
new_dict = {}

for entry in dictionary:
    new_dict['/' + entry + '/'] = dictionary[entry]

return new_dict

rawDescription: Cannot get dictionary keys to look like i want them to


code:
for i in k:
    if i not in '#&@$!*^{}_()*+[]%\n':
        stat=stat+i

rawDescription: Something wrong in interpreting my solution to python challenge?


code:
output = []
for row in reader:
    output.append(dict(k, v) for k, v in row if k in ('id', 'col2', 'col3'))
output.sort(key=lambda x: x['col3'])
return output[:10]

rawDescription: Parsing through CSV using DictReader in Python


code:
word = 'hello'
for chars in itertools.product(*zip(word, word.upper())):
    print(''.join(chars))

rawDescription: How to get all capitalizations of a word?

description: Get all capitalizations of a word


code: df['end_of_week'] = df['date'].map(lambda x: next_weekday(x, 3) if  x.weekday() < 3 else x)

rawDescription: Get end of week based on date column

description: Get end of week based on date column


rawDescription: Do Python regular expressions have an equivalent to Ruby's atomic grouping?


code:
dat.dropna(how='any')    #to drop if any value in the row has a nan
dat.dropna(how='all')    #to drop if all values in the row are nan

rawDescription: better way to drop nan rows in pandas

description: Better way to drop nan rows in pandas


rawDescription: I am using a numpy array of randomly generated ordered pairs, I need to determin if the ordered pairs are different types of triangles


code:
def __init__(self, master):

    # ...

    self.lista1=Listbox(self,yscrollcommand=self.yscroll1,exportselection=0)
    self.lista1.bind('<<ListboxSelect>>', self.on_select1)
    self.lista1.grid(row=3,column=1)

    self.lista2=Listbox(self, yscrollcommand=self.yscroll2,exportselection=0)
    self.lista2.bind('<<ListboxSelect>>', self.on_select2)
    self.lista2.grid(row=3, column=2)

    self.lista3=Listbox(self, yscrollcommand=self.yscroll3,exportselection=0)
    self.lista3.bind('<<ListboxSelect>>', self.on_select3)
    self.lista3.grid(row=3, column=3)

     # ...

rawDescription: Selecting values simultaneously from different Tkinter Listbox widgets in Python 3.5


code:
cmd = "date"
subprocess.call(cmd, shell=True)

rawDescription: how to integrate "at" command in python

description: Integrate "at" command in python


code:
def submit_edit_selected_row(context):
  opts = context['opts']
  change = context['change']
  is_popup = context['is_popup']
  save_as = context['save_as']
  if opts.object_name.lower() != 'foo':
    has_delete = (not is_popup and context['has_delete_permission']
                  and (change or context['show_delete']))
    has_save_as_new = not is_popup and change and save_as
    has_save_and_add_another = (context['has_add_permission'] and
                                not is_popup and (not save_as or context['add']))
    has_save_and_continue = (context['has_add_permission'] and
                             not is_popup and (not save_as or context['add']))
    has_save = True
  else:
    has_delete = auth_utils.has_delete_pop_permission()
    has_save_as_new = auth_utils.has_add_pop_permission()
    has_save_and_add_another = auth_utils.has_add_pop_permission()
    has_save_and_continue = (auth_utils.can_edit() or
                             auth_utils.can_edit_selectively())
    has_save = auth_utils.can_edit() or auth_utils.can_edit_selectively()
  return {
    'onclick_attrib': (opts.get_ordered_objects() and change
                          and 'onclick="submitOrderForm();"' or ''),
    'show_delete_link': has_delete,
    'show_save_as_as_new': has_save_as_new,
    'show_save_and_add_another': has_save_and_add_another,
    'show_save_and_continue': has_save_and_continue,
    'is_popup': is_popup,
    'show_save': has_save
   }
register.inclusion_tag('admin/submit_line.html', takes_context=True) (submit_edit_selected_row)

rawDescription: How do I set up add, delete, update and view permissions for a particular model instance?

description: Set up add, delete, update and view permissions for a particular model instance


rawDescription: Unique HTML element IDs for each model with Django


code:
def f(x,poslist):
  v = 0
  for pos in poslist:
    v += 1/((x-pos)*(x-pos))
  return v

rawDescription: Function Design

description: Function Design


code:
def function(x, y):
    a = 3
    b = 4
    return a*1j*x+b*y

rawDescription: Complex number in python

description: Complex number in python


code:
#!/usr/bin/env python
# -*- encoding: utf8 -*-

rawDescription: How to get Python bs4 to work properly on XML?

description: Get Python bs4 to work properly on XML


code:
for (y, x), v in polys:
    rr, cc = draw.polygon(y, x, (H, W))
    count_buf[rr, cc] += 1
    sum_buf[rr, cc] += v

mean_buf = np.zeros_like(sum_buf)
mask = count_buf > 0
mean_buf[mask] = sum_buf[mask] / count_buf[mask]

rawDescription: Overlapping polygons in Python PIL

description: Overlapping polygons in Python PIL


code:
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument(
    "-option1", type=int, nargs='?', default=1, const=1,
    choices=xrange(1, 10), help="option 1 message")
parser.parse_args(['-option1', '4'])  # option with argument
parser.parse_args(['-option1'])       # option with *no* argument
parser.parse_args([])                 # option not specified
parser = ArgumentParser()
parser.add_argument(
    "-option1", type=int, default=1,
    choices=xrange(1, 10), help="option 1 message")
parser.parse_args(['-option1', '4'])  # option with argument
parser.parse_args([])                 # option not specified
parser.parse_args(['-option1'])       # option with *no* argument

rawDescription: Reading default arguments with argparse

description: Reading default arguments with argparse


code:
mu = np.hstack((mu1,mu2))
distances = np.sqrt(np.einsum('ij,ij,ik,ik->ij',mu,mu,rays,rays))

rawDescription: Avoiding numpy loops while calculating intersections


code:
for word, value in words_dict.items():
    if len(word) == word_len and value == frequency:
        max_word_list += [word]

rawDescription: Dictionary Issue Python

description: Dictionary Issue Python


code:
mask = (result['count'] == 0) & pd.isnull(result).any(axis=1)
result = result.loc[~mask]

rawDescription: Pandas join/merge 2 dataframes using date as index


code:
def extract_info_games(page_id):
    # Create session
    session = requests.session()

    # Get initial html
    html = session.get("http://store.steampowered.com/app/%s/" % page_id).text

    # Checking if I'm in the check age page (just checking if the check age form is in the html code)
    if ('<form action="http://store.steampowered.com/agecheck/app/%s/"' % page_id) in html:
            # I'm being redirected to check age page
            # let's confirm my age with a POST:
            post_data = {
                     'snr':'1_agecheck_agecheck__age-gate',
                     'ageDay':1,
                     'ageMonth':'January',
                     'ageYear':'1960'
            }
            html = session.post('http://store.steampowered.com/agecheck/app/%s/' % page_id, post_data).text

    # Extracting javscript object (a json like object)
    start_tag = 'InitAppTagModal( %s,' % page_id
    end_tag = '],'
    startIndex = html.find(start_tag) + len(start_tag)
    endIndex = html.find(end_tag, startIndex) + len(end_tag) - 1
    raw_data = html[startIndex:endIndex]

    # Load raw data as python json object
    data = json.loads(raw_data)
    return data

rawDescription: Missing source page information using urllib2


rawDescription: Grab portions of txt after headings

description: Grab portions of txt after headings


code:
max_xticks = 10
xloc = plt.MaxNLocator(max_xticks)
ax.xaxis.set_major_locator(xloc)

rawDescription: Date labels intersecting

description: Date labels intersecting


code:
import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
urllib.request.urlopen('http://www.example.com/login.html')

rawDescription: Adding authentication header in python 3


code:
df = pd.DataFrame(list_yearly).merge(pd.DataFrame(list_monthly))

def func(group):
    result = []
    for idx, row in group.iterrows():
        result.append({'month':row['month'],'total_month':row['total_month']})
    return result

result = df.groupby(['name','total_year']).apply(func).reset_index()
result.columns = ['name','total_year','trend']
result_dict = result.to_dict(orient='records')

rawDescription: Using Pandas to merge 2 list of dicts with common elements


rawDescription: Python: How to convert array of 4 digits to a larger number, bitwise?


code:
class MyBase():
  def __init__(self):
    pass

class prog(MyBase, ArgParseMixin):
  def __init__(self):
    import argparse
    import textwrap

    # call constructor of the main interitance tree
    MyBase.__init__(self)

    # Call the constructor of the ArgParseMixin
    ArgParseMixin.__init__(self,
      description = textwrap.dedent('''\
        This is the Admin Service Tool.
        '''),
      formatter_class = argparse.RawDescriptionHelpFormatter,
      add_help=False)

    self.MainParser.add_argument('-v', '--verbose',  dest="verbose",  help='print out detailed messages',  action='store_const', const=True, default=False)
    self.MainParser.add_argument('-d', '--debug',    dest="debug",    help='enable debug mode',            action='store_const', const=True, default=False)

  def Run(self):
    ArgParseMixin.Run(self)

  @DefaultAttribute()
  def HandleDefault(self, args):
    print("DefaultHandler: verbose={0}  debug={1}".format(str(args.verbose), str(args.debug)))

  @CommandAttribute("create-user", help="my new command")
  @ArgumentAttribute(metavar='<Username>', dest="Users", type=str, help='todo help')
  def HandleCreateUser(self, args):
    print("HandleCreateUser: {0}".format(str(args.Users)))

  @CommandAttribute("remove-user", help="my new command")
  @ArgumentAttribute(metavar='<UserID>', dest="UserIDs", type=str, help='todo help')
  def HandleRemoveUser(self, args):
    print("HandleRemoveUser: {0}".format(str(args.UserIDs)))

p = prog()
p.Run()

rawDescription: Is it possible to implement .NET-like attributes in Python?


code:
td_heads_content = soup.find_all(text="Total Cash (mrq):")
for elem in td_heads_content:
    td_head = elem.parent

rawDescription: parsing with expression including a newline in python

description: Parsing with expression including a newline in python


code:
myuser

mypass

...

rawDescription: Python Login: Error reading Text file

description: Python Login: Error reading Text file


code:
class Pair(tuple):
    def _cmp(self, other):
        center = self[0] - other[0]
        dev = self[1] + other[1]
        r = center / dev if dev != 0 else center
        if r < 0:
            return -1
        if r >  0:
            return 1
        return 0

    def __lt__(self, other):
        return self._cmp(other) < 0

    def __lte__(self, other):
        return self._cmp(other) <= 0

    def __eq__(self, other):
        return self._cmp(other) == 0

    def __ge__(self, other):
        return self._cmp(other) >= 0

    def __gt__(self, other):
        return self._cmp(other) > 0

rawDescription: spark custom sort in python

description: Spark custom sort in python


code:
@classmethod
def from_xml(cls, xml_file):
    x, y, z  = XMLDataHelper.import_something_from_xml(xml_file)
    return cls(x,y,z)

rawDescription: split up classmethods in python

description: Split up classmethods in python


code:
import Tkinter as tk
import matplotlib
matplotlib.use('TkAgg')

from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

class App():
    def __init__(self, parent):

        self.__drawplotFrame = tk.Frame(parent, width=500, height=500)
        self.__drawplotFrame.pack()

        self.__fig = Figure(figsize=(16,11))
        self.__p = self.__fig.add_subplot(1,1,1)
        self.__p.plot(range(10), range(10))

        self.__drawplotCanvas = FigureCanvasTkAgg(self.__fig, master=self.__drawplotFrame)
        self.__drawplotCanvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

root = tk.Tk()
App(root)
root.mainloop()

rawDescription: Declaration of FigureCanvasTkAgg causes memory leak


rawDescription: Any way to use rrule going backwards

description: Any way to use rrule going backwards


rawDescription: add a number to all odd or even indexed elements in numpy array without loops

description: Add a number to all odd or even indexed elements in numpy array without loops


code:
my_obj[0]
my_obj[1]

rawDescription: String-based indices in tuple Python

description: String-based indices in tuple Python


code:
def memory_usage():
    """Memory usage of the current process in kilobytes."""
    status = None
    result = {'peak': 0, 'rss': 0}
    try:
        # This will only work on systems with a /proc file system
        # (like Linux).
        status = open('/proc/self/status')
        for line in status:
            parts = line.split()
            key = parts[0][2:-1].lower()
            if key in result:
                result[key] = int(parts[1])
    finally:
        if status is not None:
            status.close()
    return result

rawDescription: Python equivalent of PHP's memory_get_usage()?


code:
SHOWALL
data
data
data
data
data
data
data

rawDescription: Trying to read certain text from a file that has strange characters. (Python)


code:
from haystack import connections
from haystack.constants import DEFAULT_ALIAS

import my_app.search_indexes as search_index

for my_class in some_list_of_models:

    search_index_class_name = "%s_%sSearchIndex"%(concept_class._meta.app_label,concept_class.__name__)

    # Create a new subclass of search index (see below)
    # And monkey-patch it in.
    setattr(search_index, class_name, create(concept_class))

# Since we've added a new class, kill the index so it is rebuilt next time we access the index.
connections[DEFAULT_ALIAS]._index = None

rawDescription: Programmatically create haystack index

description: Programmatically create haystack index


code:
from subprocess import STDOUT, check_output as qx

output = qx([r"c:\Python27\python.exe", r"c:\path\to\script.py"], stderr=STDOUT)

rawDescription: LookupError: unknown encoding: idna - only from subprocess.call


code:
{'Role Name': ['Administrator'],
 'Approval': ['N', 'N', 'N', 'N', 'N'],
 'Functions': ['Admin Action', 'Create Users', 'Transfer Amount', 'User Deletion', 'Withdraw Amount'],
 'Approve': ['N', 'N', 'N', 'N', 'Y'],
 'Action': ['Y', 'Y', 'N', 'Y', 'Y']}

rawDescription: Python: Sorting list in dictionary by key name


code:
a = np.arange(9).reshape(3, 3)
a
corners = a[tuple(slice(None, None, j-1) for j in a.shape)]
corners
corners += 1
a

rawDescription: Get corner values in Python numpy ndarray


code: yChannel = 4*[[]]

rawDescription: Python populating all the elements of a 2D list (or array) when I change only one


code: linenos = 'table' if self.linenos else False

rawDescription: Weird variable setting in python

description: Weird variable setting in python


rawDescription: python class namespace and init function

description: Python class namespace and init function


code:
from os import path
with open(path.expanduser("~/.bash_history")) as f:
    for line in f:
        pass
    last = line
    print(last)

rawDescription: Run shell builtin command in Python

description: Run shell builtin command in Python


rawDescription: Apply permutation matrix to pandas DataFrame


rawDescription: How to evaluate N largest elements in a multidimensional array?

description: Evaluate N largest elements in a multidimensional array


rawDescription: Copy all files with certain extension, while maintaining directory tree


code: result = [np.average(f_i['mz'], weights=f_i['I']) for f_i in fsplit]

rawDescription: Numpy: Efficient access to sub-arrays generated by numpy.split


code:
edges = vtk.vtkExtractEdges()
edges.SetInput(trianglePolyData)
edge_mapper = vtk.vtkPolyDataMapper()
edge_mapper.SetInput(edges.GetOutput())

edge_actor = vtk.vtkActor()
edge_actor.SetMapper(edge_mapper)
edge_actor.GetProperty().SetColor(1,0,0)

ren.AddActor(edge_actor)

vtk.vtkPolyDataMapper().SetResolveCoincidentTopologyToPolygonOffset()

rawDescription: How to display only triangle boundaries on textured surface in vtk?

description: Display only triangle boundaries on textured surface in vtk


code:
import cgi

response = urllib2.urlopen(URL)
_, params = cgi.parse_header(response.headers.get('Content-Disposition', ''))
filename = params['filename']

rawDescription: python httplib/urllib get filename

description: Python httplib/urllib get filename


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

import os
import types

import cherrypy
import jinja2

path   = os.path.abspath(os.path.dirname(__file__))
config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 4
  }
}

class TemplateTool(cherrypy.Tool):

  _engine = None
  '''Jinja environment instance'''

  def __init__(self):
    viewLoader   = jinja2.FileSystemLoader(os.path.join(path, 'view'))
    self._engine = jinja2.Environment(loader = viewLoader)

    cherrypy.Tool.__init__(self, 'before_handler', self.render)

  def __call__(self, *args, **kwargs):
    if args and isinstance(args[0], (types.FunctionType, types.MethodType)):
      # @template
      args[0].exposed = True
      return cherrypy.Tool.__call__(self, **kwargs)(args[0])
    else:
      # @template()
      def wrap(f):
        f.exposed = True
        return cherrypy.Tool.__call__(self, *args, **kwargs)(f)
      return wrap

  def render(self, name = None):
    cherrypy.request.config['template'] = name

    handler = cherrypy.serving.request.handler
    def wrap(*args, **kwargs):
      return self._render(handler, *args, **kwargs)
    cherrypy.serving.request.handler = wrap

  def _render(self, handler, *args, **kwargs):
    template = cherrypy.request.config['template']
    if not template:
      parts = []
      if hasattr(handler.callable, '__self__'):
        parts.append(handler.callable.__self__.__class__.__name__.lower())
      if hasattr(handler.callable, '__name__'):
        parts.append(handler.callable.__name__.lower())
      template = u'/'.join(parts)

    data     = handler(*args, **kwargs) or {}
    renderer = self._engine.get_template(u'{0}.html'.format(template))

    return renderer.render(**data)

cherrypy.tools.template = TemplateTool()

class App:

  @cherrypy.expose
  def index(self):
    '''No renderer applied, CherryPy outputs dict keys'''
    return {'user': 123}

  @cherrypy.tools.template
  def auto(self):
    return {'user': 123}

  @cherrypy.tools.template(name = 'app/auto')
  def manual(self):
    return {'user': 234}

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: CherryPy with Cheetah as plugin + tool - blank pages


code:
seta = set(A)
[x for x in B if not x in seta]

rawDescription: Efficient Compare of two LIST of Lists in Python


code:
a = np.array([1,2,3,4]) # gives you a numpy array of 4 elements [1,2,3,4]
b = a - 1 # this operation on a numpy array will subtract 1 from every element resulting in the array [0,1,2,3]

rawDescription: numpy.ndarray sent as argument doesn't need loop for iteration?

description: Numpy.ndarray sent as argument doesn't need loop for iteration


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


code:
lookup = [(w.startswith("@"), w) for w in doh.split()]
lookup

rawDescription: hmm, lists, tuples, arrays, sets or dicts for this data structure?

description: Hmm, lists, tuples, arrays, sets or dicts for this data structure


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

numpoints = 30
theta = np.linspace(0, 2*np.pi, numpoints)
r1 = np.random.random(numpoints)
r2 = 5 * np.random.random(numpoints)

params = dict(projection='polar', theta_direction=-1, theta_offset=np.pi/2)
fig, ax = plt.subplots(subplot_kw=params)

ax.fill_between(theta, r2, color='blue', alpha=0.5)
ax.fill_between(theta, r1, color='green', alpha=0.5)

plt.show()

rawDescription: Add second axis to polar plot

description: Add second axis to polar plot


rawDescription: Commutative combination of elements of two lists


code:
ar
result

rawDescription: Selecting values in ndarray occuring after a NaN


code:
class ListWithReCalc(list):
    def position_recalc(self):
        ...

class Control:
    def __init__(self, instances):
        self.machine_instances = instances
        ...

    def get(self, elem = 0, end = None, step = 1):
        return ListWithReCalc(machine_instances[elem : end : step])

rawDescription: Chain over iterable

description: Chain over iterable


code:
line_3 = Line2D([0,7], [0,1], linewidth=1, linestyle = "-", color="brown")
ax.add_line(line_3)
angle_plot = get_angle_plot(line_1, line_3, 2, color="red") # Second angle arc will be red in color
angle_text = get_angle_text(angle_plot)

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

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

description: Plot an angle between two lines in Matplotlib


code:
@register.assignment_tag
def hs_get_section_answer(questionnaire, app, model, field, comp_value):

  model = get_model(app, model)
  modal_instance = model.objects.get(questionnaire=questionnaire)

  if getattr(modal_instance, field) == comp_value:
    return True
  else:
    return False

rawDescription: Use of "if" in template with custom template tag with multiple arguments


code: patt = re.compile(r'(.*?)(\.suffix|)$')

rawDescription: Python Regex: How to match filenames with optional suffix? Why '(.*?)(\.suffix)?' doesn't work?


code:
import csv

with open('so.csv') as f:
    bl = [[],[],[],[],[]]
    reader = csv.reader(f)
    for row in reader:
        for col in range(5):
            bl[col].append(row[col])

rawDescription: Converting columns in a file into separate lists using python


code: 'Three first values are: %f, %f and %f' % (3.14, 2.71, 1)

rawDescription: String formatting options: pros and cons


code:
pythonapi.PyObject_GC_UnTrack.restype = None # which means "void"
a = [1,2,3,4,5]
pythonapi.PyObject_GC_UnTrack(py_object(a))

rawDescription: What does pythonapi.PyObject_GC_UnTrack return?


rawDescription: Python: Using a multidimensional multiprocessing.manager.list()


code: table = doc.Tables(1)

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:
import re
r = re.compile(r'[^\W\d_]', re.U)
r.match('x')
r.match(u'é')

rawDescription: Match any unicode letter?

description: Match any unicode letter


rawDescription: Click event is sent immediately after I start application (PySide and Python)


code: len('jabberwocky')

rawDescription: Letter guessing game in python

description: Letter guessing game in python


code:
# in-place removal of column in matrix

matrixK = [[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]

for row in matrixK:
    for i in reversed(range(len(row))):
        if i % 2 == 0:
           del row[i:i+1]

print('matrixK after: {}'.format(matrixK))

rawDescription: Delete columns from matrix according to its index


code:
mrows = matrix.shape[0]
comp_mean = np.zeros(pattern.shape[0])
for i in range(pattern.shape[0]):
    comp_mean[i] = (pattern[i,:] == matrix).sum()
comp_mean = comp_mean/mrows

rawDescription: Numpy matrix row comparison

description: Numpy matrix row comparison


code:
def sgn_pbc(x, y, Lbox):
    d = abs(x-y)
    w = sgn(Lbox/2., d)
    return  w * sgn(x, y)

rawDescription: efficient sign function in python for case of periodic boundary conditions

description: Efficient sign function in python for case of periodic boundary conditions


code:
from myapp.models import DBSession
from myapp.models import Foo

rawDescription: How do I split models.py into different files for different models in Pyramid?

description: Split models.py into different files for different models in Pyramid


code:
['Intrus.*Detect.*', 'Approv.*rewrit.*', 'Firewal.*']

['intrusion detection devices in production today.']
['approved a rewrite of the system']
['approve a complete rewrite of the system']
['approved a rewriting']
['Firewalls']

rawDescription: Best way to match a large list against strings in python

description: Match a large list against strings in python


code:
def alphastartgen(n=27):
    resul = ""
    for i in alphagen(n):
        resul += i
        yield resul

rawDescription: Is there a way to subclass a generator in Python 3?


code:
class A():
    def __init__(self):
        assert(not hasattr(B, '_parent')) # make sure there is only one A
        B._parent = self
        ...

rawDescription: Is this the correct way to save a pointer to an upper layer object in Python?


code:
regex = re.compile(r'"\\u(\d|[a-f])+\[(\w|\d)+\\u(\d|[a-f])+\[(\d|\w)+\\r\\n(?P<content>[^"]+)')
output = "\"\\u001b[H\\u001b[2J\\r\\nPROCESS1       : process not running\\r\\n \\r\\nPROCESS2       : process running\\r\\nT\""
regex.match(output).group('content')

rawDescription: Unicode - Just print the string

description: Unicode - Just print the string


code:
import numpy

def find_coeffs(pa, pb):
    matrix = []
    for p1, p2 in zip(pa, pb):
        matrix.append([p1[0], p1[1], 1, 0, 0, 0, -p2[0]*p1[0], -p2[0]*p1[1]])
        matrix.append([0, 0, 0, p1[0], p1[1], 1, -p2[1]*p1[0], -p2[1]*p1[1]])

    A = numpy.matrix(matrix, dtype=numpy.float)
    B = numpy.array(pb).reshape(8)

    res = numpy.dot(numpy.linalg.inv(A.T * A) * A.T, B)
    return numpy.array(res).reshape(8)

rawDescription: How does perspective transformation work in PIL?


code:
import pandas as pd
df = pd.DataFrame([['txt1','txt2'], [12, 22]], columns=['c1', 'c2'])
df

rawDescription: How can we change data type of a dataframe row in pandas?


code:
class main2(Toplevel):
    def __init__(self):
        Toplevel.__init__(self)
        self.frame= Frame(self, width=80, height=50)
        self.label = Label(self.frame, text='this is another frame')
        self.frame.grid()
        self.label.grid()

rawDescription: Python GUI - Linking one GUI in a class to another class


code:
def setValue(derived, Input):
    derived.value = sum(x.value for x in Input)
    return derived

rawDescription: Assigning classes as variables

description: Assigning classes as variables


code:
import linecache
linecache.getline('/tmp/lines.txt', 2)

rawDescription: numpy - Python - Selectively import parts of the .txt file

description: Numpy - Python - Selectively import parts of the .txt file


code:
#item = collections.defaultdict(lambda : '"<unknown>"', **item)
item = my_defaultdict(**item)

rawDescription: Python "switch statement" and string formatting


code: product(*[ range(0, 1), range(1, 5), range(2, 6) ])

rawDescription: Python, all possible combinations of numbers betweens 2 lists


code:
if not any(not v[0]["Times"] for v in d["Showtimes"].itervalues()):
    print(d)

rawDescription: check if the value in a dict is not empty?

description: Check if the value in a dict is not empty


code:
import bs4
import re

soup = bs4.BeautifulSoup('Telefon: +421 902 808 344')
for span in soup.find_all('span', {'class':"date"}):
    if span.find(text=re.compile('Telefon:')):
        for text in span.stripped_strings:
            print(text)
# Telefon:
# +421 902 808 344

rawDescription: Beautifulsoup can't find tag by text

description: Beautifulsoup can't find tag by text


rawDescription: Strip everything but URL from a string in python


code:
value = d[i, j]
d[i, j].append(3)

rawDescription: Python: How to efficiently implement large symmetric array with many empty entries


code: np.stack([x, np.log(x)], axis=x.ndim)

rawDescription: efficient numpy array creation

description: Efficient numpy array creation


code:
class MyForm(ModelForm):
    class Meta:
        model = MyModel
        fields = ('description',)

rawDescription: Paginate Django formset

description: Paginate Django formset


code:
item1 = Item(product_id = 4, price = 13) # use the field name!
item2 = Item(name = "hammer", description = "used to belong to Thor")

rawDescription: Python: flexible way to declare constructors


code:
import itertools
import timeit

def makestuff(count):
    for i in range(count):
        yield (i, i)

def f_extend(mystuff):
    mylist = []
    for x, y in mystuff:
        mylist.extend([int(x), int(y)])
    return mylist

def f_append(mystuff):
    mylist = []
    for x, y in mystuff:
        mylist.append(int(x))
        mylist.append(int(y))
    return mylist

def f_chainmap(mystuff):
    return list(map(int, itertools.chain(*mystuff)))

def f_chaincomp(mystuff):
    return [int(x) for x in itertools.chain(*mystuff)]

def f_chainfrommap(mystuff):
    return list(map(int, itertools.chain.from_iterable(mystuff)))

def f_chainfromcomp(mystuff):
    return [int(x) for x in itertools.chain.from_iterable(mystuff)]

def f_reducecompcomp(mystuff):
    return [int(x) for x in reduce(operator.iadd, (list(y) for y in mystuff), [])]

def f_reducecompmap(mystuff):
    return [int(x) for x in reduce(operator.iadd, map(list, mystuff), [])]

try:
    import numpy
    def f_numpy(mystuff):
        return numpy.array(mystuff).flatten().tolist()
    def f_numpy2(mystuff):
        return numpy.array(list(mystuff)).flatten().tolist()
except:
    pass

if __name__ == '__main__':
  import sys
  main = sys.modules['__main__']
  count = int(sys.argv[1]) if len(sys.argv) > 1 else 10000
  for f in dir(main):
    if f.startswith('f_'):
      func = getattr(main, f)
      mystuff = makestuff(count)
      testfunc = lambda: func(mystuff)
      print('{}: {}'.format(f, timeit.timeit(testfunc, number=count)))

rawDescription: building up lists as efficiently as possible in Python

description: Building up lists as efficiently as possible in Python


rawDescription: Calculating the analogous color with python


code:
import dis
def inplace_add():
    a = 0
    a += 1

def add_and_assign():
    a = 0
    a = a + 1

dis.dis(inplace_add)
dis.dis(add_and_assign)

rawDescription: Will a+=1 be faster than a = a+1 in Python?


code:
s = [(3, 4), (1, 2)]
[i for sub in s for i in sub]

rawDescription: Opposite of zip(*[iter(s)]*n)

description: Opposite of zip(*[iter(s)]*n)


code:
import android
droid = android.Android()
#call your commands with droid.bluetoothcommand
droid.bluetoothDiscoveryStart()
#or
droid.toggleBluetoothState(True)

rawDescription: Using SL4A (Python) and bluetooth

description: Using SL4A (Python) and bluetooth


code: M = numpy.dot(R,[k,m0])

rawDescription: Inverse of numpy.dot

description: Inverse of numpy.dot


code:
'''
  >>> foo
  23
'''

foo = 23

if __name__ == '__main__':
    import doctest
    doctest.testmod()

rawDescription: Python using doctest on the mainline

description: Python using doctest on the mainline


code:
K = np.array(K)
K.argsort()[-5:]
K[K.argsort()[-5:]]

rawDescription: How to find the index of n largest elements in a list or np.array, Python

description: Find the index of n largest elements in a list or np.array, Python


code:
from itertools import chain
list(chain(a,b,c))

rawDescription: Join many lists using list comprehension


code:
from bisect import bisect    # fast binary search
from random import random

class RandomItemGenerator:
    def __init__(self, items=None, probs=None):
        # start with no items
        self.items       = []
        self.total       = 0.
        self.breakpoints = []
        # add any initial items
        if items is not None:
            for item, prob in zip(items, probs):
                self.add_item(item, prob)

    def add_item(self, item, prob):
        self.items.append(item)
        self.total += prob
        self.breakpoints.append(self.total)

    def __call__(self):
        if self.items:
            value = random() * self.total
            index = bisect(self.breakpoints, value)
            return self.items[index]
        else:
            raise ValueError("you haven't got any items yet")

rawDescription: Pythonic way of percentagechance

description: Pythonic way of percentagechance


code: self.list_customers = cnx.fetchall()

rawDescription: Pul MySql Database values to liststore - Python3 and Mysql.connector


rawDescription: Filter rows of a DataFrame based on the value of an attribute of a column value


code:
from ast import literal_eval as make_tuple
make_tuple("(1,2,3,4,5)")

rawDescription: Parse a tuple from a string?

description: Parse a tuple from a string


code: yourDict['b']['d']['b'] = "test"

rawDescription: Python change an array's value from array index