code:
def print_slot(slot):
    for row in slot:
        print(" ".join('{: >2}'.format(element) for element in row))

rawDescription: ultimate fixed width Python board array

description: Ultimate fixed width Python board array


code:
group = QtGui.QGroupBox()
group.setTitle("FOO")

rawDescription: How to build a QGroupBox with a button in the title?

description: Build a QGroupBox with a button in the title


code:
with open("wordlist-eng.txt") as word_file:
    english_words = set(word.strip().lower() for word in word_file)

fList = open("frequencyList.txt","r")
lines = fList.readlines()
fList.close()

eWords = open("eng_words_only.txt", "a")

for w in lines:
    if w.strip().lower() in english_words:
        eWords.write(w)
    else: pass
eWords.close()

rawDescription: how to remove all non english characters and words using NLTK >

description: Remove all non english characters and words using NLTK >


rawDescription: Finding string in a file

description: Finding string in a file


code:
connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
                                    username varchar(50),
                                    password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('test','test'))
print(cursor.lastrowid)
# 1

rawDescription: How to retrieve inserted id after inserting row in SQLite using Python?

description: Retrieve inserted id after inserting row in SQLite using Python


code:
sm = StateMachine()
sm.state = 'test'
sm.dispatcher()
sm.state = 'working'
sm.dispatcher()
sm.state = None
sm.dispatcher()

rawDescription: Singledispatch based on value instead of type


rawDescription: Find the number of divisors of (N!)^2

description: Find the number of divisors of (N!)^2


code: ['Hello', 'World', 'To', 'You']

rawDescription: Python regular expression, matching the last word


code:
for key, value in sorted(mydict.items()):
    pass  # now it is sorted in ascending order of key

rawDescription: How to rearrange a dict keys in increasing order (ex: date in a year as key)? python 3

description: Rearrange a dict keys in increasing order (ex: date in a year as key)? python 3


rawDescription: Splitting on last delimiter in Python string?


code:
c = []
for x in a:
    if x < b:
        c.append(x)
c

rawDescription: Extract values from a list based on a condition


code: subjectList = [row[0] for row in cur.fetchall()]

rawDescription: Remove unicode in Python from databse?

description: Remove unicode in Python from databse


code:
def sortable_version(version):
    return '.'.join(bit.zfill(5) for bit in version.split('.'))

sortable_version('1.1')
sortable_version('2')
sortable_version('2.1.10')
sortable_version('10.1')
sortable_version('2') > sortable_version('1.3.4')
sortable_version('10') > sortable_version('2')
sortable_version('2.3.4') > sortable_version('2')

rawDescription: How do I store version number strings in a django database so they are correctly comparable/sortable

description: Store version number strings in a django database so they are correctly comparable/sortable


code:
def f():
    a = ['a','b','c']
    b = ['d','e','f']
    d = ['g','h','i']
    c = ['j','k','l']
    w = next(n for n,v in filter(lambda t: isinstance(t[1],list), locals().items()) if value in v)
    print(w)

f()

rawDescription: Find if value exists in multiple lists

description: Find if value exists in multiple lists


Sid: PublicReadImages

Effect: Allow

rawDescription: Using Boto3 and Python How Make a Folder Public


code: dialog.setStyleSheet("QPushButton { min-height: 0px; min-width: 0px }");

rawDescription: Ignore minimum size when resizing QWidget


code:
def changeCell(worksheet, row, col, text):
    """ Changes a worksheet cell text while preserving formatting """
    # Adapted from http://stackoverflow.com/a/7686555/1545769
    previousCell = worksheet._Worksheet__rows.get(row)._Row__cells.get(col)
    worksheet.write(row, col, text)
    newCell = worksheet._Worksheet__rows.get(row)._Row__cells.get(col)
    newCell.xf_idx = previousCell.xf_idx

# ...

changeCell(worksheet_instance, 155, 2, "New Value")

rawDescription: Conditionally formatting text strings from Excel using python


code:
resource['contents'][media_type] = [row[i].toPython() for i in (0, 2)
                                    if row[i] is not None]

rawDescription: Is this a valid use of a conditional expression?


code:
from cStringIO import StringIO

# initialize a string stream with XML data
stream = StringIO( myXmlString )
# create an XML handler
handler = wx.richtext.RichTextXMLHandler()
# load the stream into the control's buffer
handler.LoadStream( myRichTextCtrl.GetBuffer(), stream )
# refresh the control
myRichTextCtrl.Refresh()

rawDescription: WxRichTextCtrl python retrieving entries from file


code:
S1 = Series(predict_results)
S2 = Series(first_list)
RES = S1==S2
RES[0]   # check   predict_results[0]==first_list[0]
RES[1]   # check   predict_results[1]==first_list[1]

rawDescription: How do you compare integer values in two separate lists?

description: Compare integer values in two separate lists


code: np.subtract.outer(a, b)

rawDescription: How to efficiently apply an operator to the cartesian product of two arrays?

description: Efficiently apply an operator to the cartesian product of two arrays


code:
url='http://gigs.gigatools.com/user/Danny/archive'
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)

events=soup.find('div', attrs={'class':'events'})
month = ""
day = ""
number = ""
for div in events.findAll('div'):
    try:
        if(div.get("class")[0] == "monthLeft"):
            month = div.text.strip()
        if(div.get("class")[0] == "day"):
            day = div.text.strip()
        if(div.get("class")[0] == "number"):
            number = div.text.strip()
            print (month + " " + day + " " + number)
    except:
        day = ""

rawDescription: How to scrape http://gigs.gigatools.com/user/Danny/archive

description: Scrape http://gigs.gigatools.com/user/Danny/archive


code:
import ast
def is_valid_python(code):
   try:
       ast.parse(code)
   except SyntaxError:
       return False
   return True

rawDescription: How to tell if a string contains valid Python code

description: Tell if a string contains valid Python code


code:
#!python3
#coding: utf8
symbols = ' {}&+()"=!.?.:../|»©:><#«,123456789_-+;[]%'
D = str.maketrans('','',symbols)
with open('All12.txt','a',encoding='utf8') as t, open('All11.txt','r',encoding='utf8') as n:
    for line in n:
        t.write(line.translate(D))

rawDescription: Removing symbols from a large unicode text file


code:
a = None
def foo():
    global a
    a = 5  # rebinds global 'a'

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


code:
df
df -= df.min()  # equivalent to df = df - df.min()
df /= df.max()  # equivalent to df = df / df.max()
df

rawDescription: scaling numbers column by column with pandas [python]

description: Scaling numbers column by column with pandas [python]


code:
import logging
from functools import wraps

class CustomFormatter(logging.Formatter):
    """Custom formatter, overrides funcName with value of name_override if it exists"""
    def format(self, record):
        if hasattr(record, 'name_override'):
            record.funcName = record.name_override
        return super(CustomFormatter, self).format(record)

# setup logger and handler
logger = logging.getLogger(__file__)
handler = logging.StreamHandler()
logger.setLevel(logging.DEBUG)
handler.setLevel(logging.DEBUG)
handler.setFormatter(CustomFormatter('%(funcName)20s - %(message)s'))
logger.addHandler(handler)

def log_and_call(statement):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            # set name_override to func.__name__
            logger.info(statement, extra={'name_override': func.__name__})
            return func(*args, **kwargs)
        return wrapper
    return decorator

@log_and_call("This should be logged by 'decorated_function'")
def decorated_function():
    logger.info('I ran')

decorated_function()

rawDescription: Using functools.wraps with a logging decorator


rawDescription: comparing excel data from two separate sheets with python/xlrd

description: Comparing excel data from two separate sheets with python/xlrd


code:
res = Server.objects.prefetch_related("serverinfo_set", "serverdnsrecord_set", ...).first()
res.serverinfo_set # Won't need another query
res.serverdnsrecord_set # Won't need another query

rawDescription: Django select all models with foreign key


code: isinstance(g(), types.CoroutineType)

rawDescription: Why isn't a function declared as async of type types.CoroutineType?


code:
import re

strings = ("rmv clusters phase 2 block 1 , flat no 209 dev."
           "sky line apartments block 2 chandra layout"
           "foo bar 99 block baz") # tests rule 1.

rawDescription: Conditioning on Regex

description: Conditioning on Regex


code:
def composite_value(n, min_p = 0):
    for p in primesiter(n):
        # avoid double solutions such as (6, [2,3]), and (6, [3,2])
        if p < min_p: continue
        yield (p, [p])
        for t, r in composite_value(n//p, min_p = p): # uses integer division
            yield (t*p, [p] + r)

rawDescription: Efficiently generate all composite numbers less than N (with their factorizations)


code:
class MySprite(pygame.sprite.Sprite):
    def __init__(self, name):
        # <your other sprite code>
        self.name = name

rawDescription: Pygame get name of colided sprite

description: Pygame get name of colided sprite


code: for x in c[0]: x = 0

rawDescription: Updating elements in nested list using 'for' won't work in python list


code:
from calendar import monthrange
from datetime import date, datetime

begin = date(year, month, 1)
end = date(year, month, monthrange(year, month)[1])

rawDescription: check date range with only month and year in Python

description: Check date range with only month and year in Python


code:
os.sys.path.remove("")
os.sys.path
import redis

rawDescription: importing from venv folder with same file name

description: Importing from venv folder with same file name


rawDescription: Flask - How to use CSS when i'm using Response(stream_template) with generator


code:
-bikes
-cars
-autobus
-truck

rawDescription: OpenCV Combining SURF with Neural Network


code:
pts_dot = pts.dot(transform_matrix.T)
np.allclose(pts_brute, pts_dot)

rawDescription: Use numpy to multiply a matrix across an array of points?


code:
f = open(filepath, 'r')
tags = ["#intensities"]
answer = {}
for line in f:
    if line.strip() in tags: # we've encountered a new tag
        curr = line.strip()[1:]
        answer[curr] = []
    else:
        answer[curr].append(line.strip().split('\t'))

f.close()

rawDescription: loading tab separated text files with multipled data into arrays in python

description: Loading tab separated text files with multipled data into arrays in python


code:
def foo(astr):
    if 'i' in astr:
        return '%10i'
    elif 'f' in astr:
        return '%10f'
[foo(x[1]) for x in data.dtype.descr]
# ['%10i', '%10f', '%10f', '%10f', '%10f', '%10f']

rawDescription: Numpy: use dtype from genfromtxt() when exporting with savetxt()


code:
for step_id in FUNNEL_STEP_ARRAY:
    y = db.external_funnel.find({
        "step_id": step_id,
        "client_timestamp": {"$regex": "2013-10-25T"},
        "application_id":"6083502215600857441"
    }).distinct("user_id")
    print(len(y))

rawDescription: For Loop returning blank values for query values


rawDescription: Split when character changes in Python

description: Split when character changes in Python


code:
from django.db import models

class CMSImageField(models.ImageField):
    def pre_save(self, model_instance, add):

        file = super(models.FileField, self).pre_save(model_instance, add)

        if file and not file._committed:
            # Commit the file to storage prior to saving the model
            file.save('%s.png' % model_instance.pk, file, save=False)
        return file

rawDescription: Python Django: How to upload a file with a filename based on instance pk


code: chain('spain', nations)

rawDescription: Longest chain of elements from list in Python


rawDescription: How to store lists over criteria in Python?

description: Store lists over criteria in Python


code:
for i, key_id in enumerate(df["id"]):
    # create empty dict
    d[key_id.strip()] = {}
    # a less python more C-like syntax
    # go through cols, skip the first and step is 2
    for j in range(1, len(df.columns), 2):
        # if there is some entry
        if not pd.isnull(df.ix[i,j]):
            d[key_id.strip()][df.ix[i, j]] = df.ix[i, j+1]

rawDescription: Read CSV for same headers and separate in dict


code: select(u for u in User).recent(days=3).name_starts_with('A')[:10]

rawDescription: Writing select functions for customized Pony


code:
import xml.etree.ElementTree as ET
tree = ET.parse('your.xml')
root = tree.getroot()

for item in root.findall('field'):
   name = item.find('value').text

rawDescription: get values from each itme in xml code with python

description: Get values from each itme in xml code with python


code:
from bs4 import BeautifulSoup

data = """your HTML"""
soup = BeautifulSoup(data, 'lxml')

print(soup.br.next_sibling)  # prints "The Text I want to get"

rawDescription: Extracting text between <br> with beautifulsoup, but without next tag


code:
import numpy as np
rotated_v = np.einsum('lij, lkj->lki', R, v)

rawDescription: Rotation of an array of vectors by an array of rotation matrices


code: entries = [{'entry': k, 'count': v} for k, v in myDict.iteritems()]

rawDescription: Converting a python dictionary to a JSON - like object


code: values = [ data[mask==l] for l in range(1, mask.max()+1)]

rawDescription: Slicing array in regions - Python

description: Slicing array in regions - Python


code:
new_df = pd.concat([summ, class_info], axis=1)
new_df

rawDescription: Pandas summing up different data types using counts and conditions


code:
import math
def round_up_to_even(f):
    return math.ceil(f / 2.) * 2

round_up_to_even(1.25)
round_up_to_even(3)
round_up_to_even(2.25)

rawDescription: python 2.7: round a float up to next even number

description: Python 2.7: round a float up to next even number


rawDescription: Python: Concatenate (or clone) a numpy array N times


code:
import operator

ranges = {
    '4'  : 'a',
    '70' : 'b',
    '700': 'c',
    '701': 'd',
    '85' : 'e',
    '87' : 'a',
}

def id_for_value(value):
    possible = '*'
    for idvalue, id in sorted(ranges.iteritems()):
        if value.startswith(idvalue):
            possible = id
        elif idvalue > value:
            break
    return possible

rawDescription: Building a "complete" number range w/out overlaps


code:
if any(letter in word for word in a_list):
    print('yes', letter)
else:
    print('no', letter)

rawDescription: Checking charcters in a string and outputing a Single message


code:
for string in soup.stripped_strings:
    print(repr(string))

rawDescription: How to find all kinds of website tags by python and beautifulsoup?

description: Find all kinds of website tags by python and beautifulsoup


code:
- Google
"""
Args:
  param1(int): Description of parameter `param1`.
  param2(str, optional): Description of a parameter. Defaults to None.

Returns:
  bool: True or False depending on the result.
"""

rawDescription: Python: Standard way to denote return and parameter types


code:
from PySide import QtGui, QtCore
import sys

class Data(object):

    def __init__(self):
        self.items = [['Pet', 'Dog'],['Pet', 'Cat'],['Bird','Eagle'],['Bird','Jay'],['Bird','Falcon']]
        self.selectors = list({ k[0] for k in self.items})

    def currentItems(self,select_on):
        return [k[1] for k in self.items if k[0] == select_on]

class TableModel(QtCore.QAbstractTableModel):
    def __init__(self, data, parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self.data_obj = data
        self.currentSelection = None
    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.data_obj.currentItems(self.currentSelection))
    def columnCount(self, parent=QtCore.QModelIndex()):
        return 1
    def data(self, index, role):
        if not index.isValid() or role != QtCore.Qt.DisplayRole: return
        row=index.row()
        return self.data_obj.currentItems(self.currentSelection)[row]
    def setSelection(self,combo_row):
        self.currentSelection = self.data_obj.selectors[combo_row]
        self.layoutChanged.emit()

class ComboModel(QtCore.QAbstractListModel):
    def __init__(self, data, parent=None):
        QtCore.QAbstractListModel.__init__(self, parent)
        self.data_obj = data
    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.data_obj.selectors)
    def data(self, index, role):
        if not index.isValid() or role != QtCore.Qt.DisplayRole: return
        row=index.row()
        return self.data_obj.selectors[row]

class MyWindow(QtGui.QWidget):
    def __init__(self, *args):
        QtGui.QWidget.__init__(self, *args)
        vLayout=QtGui.QVBoxLayout(self)
        self.setLayout(vLayout)

        self.data=Data()
        self.tableModel = TableModel(self.data)
        self.comboModel = ComboModel(self.data)

        self.combo=QtGui.QComboBox()
        self.combo.setModel(self.comboModel)
        self.combo.activated.connect(self.tableModel.setSelection)
        vLayout.addWidget(self.combo)

        self.ViewA=QtGui.QTableView(self)
        self.ViewA.setModel(self.tableModel)
        self.ViewA.clicked.connect(self.viewClicked)
        vLayout.addWidget(self.ViewA)

        self.tableModel.setSelection(0)

    def viewClicked(self, indexClicked):
        print('indexClicked() row: %s  column: %s'%(indexClicked.row(), indexClicked.column() ))

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

rawDescription: How to share same model with QTableView and QComboBox

description: Share same model with QTableView and QComboBox


code:
idx = pd.date_range ('2007-1-1','2014-12-31',freq='W')
df = pd.DataFrame(np.random.randint(100, size=len(idx)), index=idx, columns=['value'])
df.head()
df.tail()

rawDescription: Issue with merging time series variables to create new DataFrame with arbitrary index


code:
def fixList(inputList, splitChar='X'):
    outputList = inputList[:]
    x = None
    for i in xrange(len(outputList)):
        if outputList[i] == splitChar:
            outputList[i] = x = 0
        elif x is None:
            continue
        else:
            outputList[i] = x
            x += 1
    return outputList

rawDescription: In Python how can I change the values in a list to meet certain criteria


rawDescription: Python: Cumulative insertion of values in a sparse matrix (lil_matrix) due to repeated indices


code:
vals = set([v for tup in my_edge_list for v in tup])
assert all([v in vals for v in original_values])

rawDescription: How to generate a list with couples of random integers?

description: Generate a list with couples of random integers


code:
import ast

def dict_from_row(row):
    """Convert a list of strings in the form 'name=value' into a dict."""
    res = []
    for entry in row:
        name, value = entry.split('=')
        res.append('"{name}": {value}'.format(name=name, value=value))
    dict_string = '{{{}}}'.format(', '.join(res))
    return ast.literal_eval(dict_string)

rawDescription: Converting CNC drillings from old to new system (using Python)


code:
['First National Bank also operating as The National Bank of El Paso', 'Edinburg', 'TX', '14318', '13-Sep-13', '18-Sep-13']
["The Community's Bank", 'Bridgeport', 'CT', '57041', '13-Sep-13', '17-Sep-13']
['Sunrise Bank of Arizona', 'Phoenix', 'AZ', '34707', '23-Aug-13', '11-Sep-13']
['Community South Bank', 'Parsons', 'TN', '19849', '23-Aug-13', '5-Sep-13']
['Bank of Wausau', 'Wausau', 'WI', '35016', '9-Aug-13', '4-Sep-13']
['First Community Bank of Southwest Florida (also operating as Community Bank of Cape Coral)', 'Fort Myers', 'FL', '34943', '2-Aug-13', '26-Aug-13']
# etc.

rawDescription: Python - CSV read as one big line

description: Python - CSV read as one big line


code:
class Lesson(models.Model):
    contents = models.TextField()
    visit_count = models.IntegerField(default=0)

class StatLesson(models.Model):
    lesson = models.ForeignKey(Lesson)
    datetime = models.DateTimeField(default=datetime.datetime.now())

    def save(self, *args, **kwargs):
        if self.pk is None:
            self.lesson.visit_count += 1
            self.lesson.save()
        super(StatLesson, self).save(*args, **kwargs)

rawDescription: How to sort on number of visits in Django app?

description: Sort on number of visits in Django app


code: ['count', 'device', 'fstype', 'index', 'mountpoint', 'opts']

rawDescription: Python output format

description: Python output format


rawDescription: Python pandas: get elements (index,col) below diagonal in dataframe


code:
list1 = map(list,csv.reader(open("text1")))
list2 = map(list,csv.reader(open("text2")))

with open("combined.txt","wb") as f:
    csv.writer(f).write_rows(zip(*(zip(*list1)+zip(*list2))))

rawDescription: Properly combining 2 different files

description: Properly combining 2 different files


code:
class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    email = Column(String, nullable=False)
    tags = relationship('UserTag', collection_class=set,
                        cascade="all, delete, delete-orphan")
    tagset = association_proxy(
        'tags', 'tag_name',
        creator=lambda tag_name: UserTag(tag_name=tag_name),
    )

class UserTag(Base):
    __tablename__ = 'user_tags'
    user_id = Column(Integer, ForeignKey('users.id'), primary_key=True)
    tag_name = Column(String, primary_key=True)

rawDescription: Creating a set-like mapped attribute in SQLAlchemy


rawDescription: How do I select and store columns greater than a number in pandas?

description: Select and store columns greater than a number in pandas


code:
def chunked_topsort(relations):
    # `relations` is an iterable producing relations.
    # A relation is a sequence, interpreted to mean
    # relation[0] < relation[1] < relation[2] < ...
    # The result is a list such that
    # result[i] is the set of elements assigned to i.
    from collections import defaultdict
    succs = defaultdict(set)    # new empty set is default
    npreds = defaultdict(int)   # 0 is default
    allelts = set()
    nopreds = set()

    def add_elt(u):
        allelts.add(u)
        if npreds[u] == 0:
            nopreds.add(u)

    for r in relations:
        u = r[0]
        add_elt(u)
        for i in range(1, len(r)):
            v = r[i]
            add_elt(v)
            if v not in succs[u]:
                succs[u].add(v)
                npreds[v] += 1
                nopreds.discard(v)
            u = v
    result = []
    while nopreds:
        result.append(nopreds)
        allelts -= nopreds
        next_nopreds = set()
        for u in nopreds:
            for v in succs[u]:
                npreds[v] -= 1
                assert npreds[v] >= 0
                if npreds[v] == 0:
                    next_nopreds.add(v)
        nopreds = next_nopreds
    if allelts:
        raise ValueError("elements in cycles %s" % allelts)
    return result

rawDescription: More efficient algorithm to compute an integer mapping for a set of relations


code:
import itertools
["".join(perm) for perm in itertools.permutations("abc")]

rawDescription: producing all the anagrams from a string python

description: Producing all the anagrams from a string python


code:
import os.path
path = 'C:\\Docs\\Bob\\blah\\blah\\blah'
base = 'C:\\Docs'
os.path.relpath(path, base)

rawDescription: calling the indexed position of a string

description: Calling the indexed position of a string


code:
number
format(number, 'f')
format(number, '.0f')

rawDescription: Preventing auto scientific form for numbers in python3


code:
Rsaturn = 0.018
rs0 = np.array([[np.cos(phi), np.sin(phi), 0.] for phi in np.linspace(0., 2*np.pi, 100)])
plt.fill(Rsaturn*rs0[:,0], Rsaturn*rs0[:,1],'yellow')
plt.axis('equal')

rawDescription: How to fill between two rings with matplotlib

description: Fill between two rings with matplotlib


code:
import os

while True:
    userInput = ""
    if os.getpgrp() == os.tcgetpgrp(sys.stdout.fileno()):
        userInput = raw_input("")
    time.sleep(1)

rawDescription: Python script hanging when running in the background


code:
class Photo(admin.ModelAdmin):
    class Media:
        js = ('jquery.js', 'inlines.js',)

rawDescription: Uploading multiple images in Django admin


code:
# "application/file" is not a valid mime type!
content_subtype = ext if ext in ['jpg','pdf'] else 'octet-stream'

# This replaces non-ascii characters with '?'
# (This assumes f.name is a unicode string)
content_disposition_filename = f.name.encode('ascii', 'replace')

response = Response(content_type="application/%s" % content_subtype,
                    content_disposition='attachment; filename="%s"'
                      % content_disposition_filename.replace('"','\\"')
           )

rawDescription: How can I rename a file in a Python Pyramid Response object?

description: Rename a file in a Python Pyramid Response object


rawDescription: Getting HTML with Pycurl

description: Getting HTML with Pycurl


code:
line4 = [
    'http://www.example.org/lexicon#' + synset_offset,
    'http://www.monnetproject.eu/lemon#gloss',
    gloss
]

rawDescription: How to split a line but keep a variable in the line unsplit in python

description: Split a line but keep a variable in the line unsplit in python


code:
import subprocess

farm_path="/home/me/..."
database_name="test"
subprocess.call("monetdbd create "+farm_path,shell=True,executable="/bin/bash")
subprocess.call("monetdbd start "+farm_path,shell=True,executable="/bin/bash")
subprocess.call("monetdb create "+database_name,shell=True,executable="/bin/bash")
subprocess.call("monetdb release "+database_name,shell=True,executable="/bin/bash")

rawDescription: How to setup a (new) monetdb db from scratch in python?

description: Setup a (new) monetdb db from scratch in python


rawDescription: Create arg string from ArgumentParser parsed args in Python


code: text = ''.join(re.search(r'(rescued.*?)\r(Finished.*)', text, re.DOTALL).groups())

rawDescription: How do I remove all non-standard characters from a file?

description: Remove all non-standard characters from a file


code:
df = DataFrame([1, 2, 3])
df2 = DataFrame()

def get_row(row):
    global df2
    df2 = df2.append(row)

df.apply(get_row)
print(df2)

rawDescription: Why is it not possible to access other variables from inside the apply function in Python?


code:
def ShowChoice(root):
    world = v.get()
    if world == 0:
       root.destroy()

rawDescription: Python - Tkinter RadioButton If Statement


code:
with open('urllist.txt', 'r') as f: #text file containing the URLS
     for url in f:
         page = requests.get(url.strip())

rawDescription: Python URLs in file Requests

description: Python URLs in file Requests


code:
import time

t0 = time.time()
code_block
t1 = time.time()

total = t1-t0

rawDescription: Python: Start and stop timer

description: Python: Start and stop timer


code:
import re
re.sub(r'(?i)[aeiou]', '', 'Abracadabra')

rawDescription: str.replace issue

description: Str.replace issue


code:
from bs4 import BeautifulSoup
import requests

url = 'https://google.com'
name = requests.get(url)

with open("/tmp/A.html", "w") as f:
  f.write(name.content)

# read it back in
with open("/tmp/A.html") as f:
  soup = BeautifulSoup(f)
  # do something with soup

rawDescription: Python - save requests or BeautifulSoup object locally


code:
ie1.setTextBox("q","my text goes here")
ie1.clickButton("btnK")

rawDescription: How to open a New window in Python PAMIE

description: Open a New window in Python PAMIE


code:
import re

# see <http://stackoverflow.com/a/312464/1535629>
def chunks(l, n):
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

text = '''1
<src> he is a [man]</src>
<tgt>lui è un [uomo]</tgt>
2
<src> she is a [woman]</src>
<tgt>lei è una donna</tgt>
3
<src> he works well</src>
<tgt> lui lavora [bene]</tgt>'''
lines = text.split('\n')
linepairs = [chunk[1:] for chunk in chunks(lines, 3)]

regex = re.compile(r'\[\w*\]')
for src, tgt in linepairs:
    src_match = re.search(regex, src)
    tgt_match = re.search(regex, tgt)
    if src_match and tgt_match:
        print(src_match.group(), tgt_match.group())

rawDescription: Detect what is in brackets in two lines

description: Detect what is in brackets in two lines


code:
xx = np.matrix([[1.2,3.4],[5.4,6.7],[9.8, 5.2]])
zz = np.matrix([[str(ele) for ele in a] for a in np.array(xx)])

rawDescription: Typecasting a numpy matrix into a string in python


code:
dataDictionary = {}
for datum in data:
    x0, t, r = datum.split()
    dataDictionary[x0] = t, r

rawDescription: Splitting two lists and assigning data from one list to values in the other


code:
df['expected_week'] = df.groupby(['Country', 'Product']).Week.transform(lambda s: range(s.min(), s.min() + s.size))
df[df.Week == df.expected_week]

rawDescription: Python Pandas: Eliminate a row from a dataframe if a value in a any preceding row in a groupby meets a certain criteria


code:
import pkgutil
for importer, modname, ispkg in pkgutil.walk_packages(path=None, onerror=lambda x: None):
    print(modname)

rawDescription: Python Finding all packages inside a package, even when in an egg


rawDescription: List of numbers

description: List of numbers


code:
def OnSelect(self, name_selected):
    self.lc2.Destroy()
    self.lc2 = PanelA(self.splitter, name_selected.data)

rawDescription: How to rebuild panels in wxpython in function of a variable?

description: Rebuild panels in wxpython in function of a variable


rawDescription: Tensorflow how to check if a tensor row is only zeroes?


code: datetime.datetime(2015, 9, 30, 18, 59, 39, tzinfo=datetime.timezone.utc)

rawDescription: Parse date from string and insert with Sqlalchemy tosqlite


code:
import sys

if sys.version_info[0] < 3:
   print('before Python 3 (Python 2)')
else: # Python 3
   print('Python 3 or newer')

rawDescription: check python version(s) from within a python script and if/else based on that

description: Check python version(s) from within a python script and if/else based on that


code: df.to_csv('Result.csv', index=False, sep=' ')

rawDescription: Preserving Column Order - Python Pandas and Column Concat


rawDescription: Add bits in all possible places

description: Add bits in all possible places


code:
for r in logsplit(range(50)):
    print(list(r))

rawDescription: Split a Python list logarithmically

description: Split a Python list logarithmically


code: root.bind('<Control-Q>', _quit)

rawDescription: Tkinter bind problem

description: Tkinter bind problem


rawDescription: Convert Delphi BufferToHex function to Python


code: time_between = dt_next_7am.astimezone(tz=UTC) - dt.astimezone(tz=UTC)

rawDescription: How do I find the next 7am in a timezone

description: Find the next 7am in a timezone


code: Request(url, method="HEAD")

rawDescription: Scrapy crawl http header data only

description: Scrapy crawl http header data only


code:
class Spider(Spider):
    name = "test"

    def __init__(self):
        self.myPipeline = None

    def parse(self, response):
        self.myPipeline.get_date()

rawDescription: How to get the pipeline object in Scrapy spider

description: Get the pipeline object in Scrapy spider


code:
sys.path = ['.'] + sys.path
import oauth2

rawDescription: How to import 3rd party module to python if its name is taken?

description: Import 3rd party module to python if its name is taken


code: Directory = '.'.join(str(x) for x in (Release, Build, ServicePack, Hotfix))

rawDescription: Assigning multiple variable values to a single variable in Python


code:
class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ['category','title' ]
        widgets = {
            'category': ReadOnlySelect(),
        }

rawDescription: Django Model form with read only properties


code:
class Message(models.Model):
    # some code...

    @property
    def sender_name(self):
        return self.sender.name # username or whatever

rawDescription: How to include in queryset details fields of a foreign key (django and rest_api)

description: Include in queryset details fields of a foreign key (django and rest_api)


code:
import difflib
difflib.SequenceMatcher(None,'CCCCCC', 'CCCCCT').ratio()

rawDescription: Use levenshtein distance for keys in defaultdict in python


code:
content = [7, 14, 23, 49, 191,]
ticks = [0,1,0,1,0]

fmt = '{:>5}'

for tic in ticks:
    print(fmt.format('|' if tic else""), end="")
print()
for num in content:
    print(fmt.format(num) ,end="")
print()

rawDescription: Python format print to evenly print numbers


code:
import itertools

def lines_of_interest(filename):
    with open(filename, 'r') as inf:
        for line in itertools.islice(inf, 11):  # yield the first 11 lines
            yield line
        while True:
            # out of next 11 lines, skip 9 and keep last 2
            lines = list(itertools.islice(inf, 9, 11))
            for line in lines:
                yield line
            if not lines:  # end-of-file?
                break

rawDescription: python read file and skip n lines and read again and skip

description: Python read file and skip n lines and read again and skip


code:
sub[first] = 1
sub[second] = 1

rawDescription: Very simple Python script, puzzling behaviour


code:
#!/usr/bin/python3

import os

keepers = ['safe', 'also_safe.txt']
os.chdir('/tmp/r')

for filename in os.listdir('.'):
    if filename not in keepers:
        print('Removing %s' % (filename,))
        os.remove(filename)

rawDescription: Why does shopt fail when called from python?


code:
import timeit
import shlex

def foo():
    total = 0
    for i in range(10000):
        total += i**3
    return total

timeit.main(args=shlex.split("""-s'from __main__ import foo' 'foo()'"""))

rawDescription: Use Python's `timeit` from a program but functioning the same way as the command line?


code:
m = create_matrix(file)
i = some_y_location
j = some_x_location
neighbors = find_neighbors(m, i, j)

rawDescription: python find all neighbours of a given node in a list of lists

description: Python find all neighbours of a given node in a list of lists


code:
rdiff = resource.struct_rusage(f1-f0 for f0, f1 in zip(r0, r))
sys.stderr.write('{}: utime {} maxrss {} nsignals {} etc.\n'.format(
    datetime.timedelta(seconds=rdiff.r_utime),
    rdiff.ru_maxrss,
    rdiff.ru_nsignals))

rawDescription: How to use the resource module to measure the running time of a function?

description: Use the resource module to measure the running time of a function


rawDescription: Efficient way to subset a huge delimited file


code:
plt.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)
# or
plt.setp([a.get_xticklabels() for a in ax_arr[:-1]], visible=False)

rawDescription: How can I remove xtics from an axis in matplotlib?

description: Remove xtics from an axis in matplotlib


rawDescription: Selecting a new dataframe via a multi-indexed frame in Pandas using index names


code: myobj.__dict__[foo] = bar

rawDescription: Is it possible to overload a call to vars(object) in Python?


code:
F = ['mary', 'zari', 'ali', 'fari','Thaghi', 'zagi', 'shad', 'sila', 'bita']
A = [item for i, item in enumerate(F) if i % 3 == 0]
B = [item for i, item in enumerate(F) if i % 3 == 1]
C = [item for i, item in enumerate(F) if i % 3 == 2]

rawDescription: Extracting items in a list that are not in order


code:
handles, labels = pyplot.gca().get_legend_handles_labels()
newLabels, newHandles = [], []
for handle, label in zip(handles, labels):
  if label not in newLabels:
    newLabels.append(label)
    newHandles.append(handle)
pyplot.legend(newHandles, newLabels)

rawDescription: pyplot combine multiple line labels in legend

description: Pyplot combine multiple line labels in legend


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

rawDescription: Django recognizes static address but not media


code: exec("print " + x)

rawDescription: Python convert a string to a logic operator


code:
gln = a[a['AA2'] == 'GLN']
gln['mean'].mean()

rawDescription: Nicer way to compute means of a set with numpy


rawDescription: How do I limit the number of digits in a list?

description: Limit the number of digits in a list


code:
WIDTH=600
HEIGHT=480
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))

rawDescription: pygame: pygame.KEYDOWN not working

description: Pygame: pygame.KEYDOWN not working


code:
def datetime_factory(format,s):
    from datetime import datetime
    return datetime.strptime(s,format)

from functools import partial

dType= [str, partial(datetime_factory,'%d-%m-%Y'), str, int, float, float, str]

[t(x) for t,x in zip(dType,foo)]
Out[29]: ['plot001', datetime.datetime(2013, 1, 1, 0, 0), 'XX', 10, 12.5, 0.65, 'A']

rawDescription: Convert list items to defined data type

description: Convert list items to defined data type


code:
lst = [[3, 4.6575, 7.3725],
       [3, 3.91, 5.694],
       [2, 3.986666666666667, 6.6433333333333335],
       [1, 3.9542857142857137, 5.674285714285714]]

# group the values in a dictionary
import collections
d = collections.defaultdict(list)
for item in lst:
    d[item[0]].append(item)
# find sum of values
for key, value in d.items():
    print [key] + map(sum, zip(*value)[1:])

rawDescription: Get all elements in a list where the value is equal to certain value


code:
xfile = requests.get(candidate_link)
file_name = candidate_link.split('/')[-1]
if xfile:
    with open(file_name, "wb") as f:
        f.write(xfile.content)

rawDescription: Python: Save Excel File As-Is To Folder

description: Python: Save Excel File As-Is To Folder


code:
arr = np.asarray(col)
tot = arr.sum(-1)  # sum over color (last) axis
mn  = arr.mean(-1) # or a mean, to keep the same normalization (0-1)

rawDescription: Sum of colorvalues of an image

description: Sum of colorvalues of an image


code: self.check = Checkbutton(self, ..., command=self.switch)

rawDescription: Python: Tkinter active and deactive entry space with checkutton


code:
class CharsLeftInput(forms.TextInput):
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            final_attrs['value'] = force_unicode(self._format_value(value))
        maxlength = final_attrs.get('maxlength',False)
        if not maxlength:
            return mark_safe(u'<input%s />'%flatatt(final_attrs))
        current = force_unicode(int(maxlength) - len(value))
        html = u"""

            <input %(attrs)s />
            %(current)s characters remaining
            %(maxlength)s

        """ % {
            'attrs':flatatt(final_attrs),
            'current':current,
            'maxlength':int(maxlength),
        }
        return mark_safe(html)

    class Media:
        css = {'screen':('charsleft-widget/css/charsleft.css',),}
        js = ('charsleft-widget/js/charsleft.js',)

rawDescription: django admin - count characters and show remaining space in text fields which are limited

description: Django admin - count characters and show remaining space in text fields which are limited


code:
import collections

Score = collections.namedtuple("Score", ["name","score"]) # just to make things easy
new_score = Score("Joe Schmoe",12000)

with open("highscores.pkl","rb") as in_:
    high_scores = pickle.load(in_)
if new_scores.name not in high_scores:
    high_scores[new_scores.name] = new_scores.score
with open("highscores.pkl","wb") as out:
    pickle.dump(high_scores, out)

rawDescription: Keeping high scores in a text file

description: Keeping high scores in a text file


rawDescription: Counting occurrences based on criterion

description: Counting occurrences based on criterion


code: [u'The First Artist', u'The Second Artist']

rawDescription: abstracting the conversion between id3 tags, m4a tags, flac tags

description: Abstracting the conversion between id3 tags, m4a tags, flac tags


code:
#!/usr/bin/python

import time
import sys
import curses

def alarmloop(stdscr):
    stdscr.addstr("How many seconds (alarm1)? ")
    curses.echo()
    alarm1 = int(stdscr.getstr())
    while (1):
        time.sleep(alarm1)
        curses.flushinp()
        stdscr.clear()
        stdscr.addstr("Alarm1\n")
        stdscr.addstr("Continue (Y/N)?[Y]:")
        doit = stdscr.getch()
        stdscr.addstr("\n")
        stdscr.addstr("Input "+chr(doit)+"\n")
        stdscr.refresh()
        if doit == ord('N') or doit == ord('n'):
            stdscr.addstr("Exiting.....\n")
            break

curses.wrapper(alarmloop)

rawDescription: How to flush the input stream in python?

description: Flush the input stream in python


code: filtered_list = [padded_name for padded_name in padded_names if any(padded_name.find(name) >= 0 for name in names)]

rawDescription: Creating a list by searching for substrings in python


code:
_memodict = {}
def memoized_function(input):
    try:
        return _memodict[input]
    except KeyError:
        # do what you would have normally done
        _memodict[input] = output
        return output

rawDescription: Need help understanding how to implement memoization


rawDescription: Calling PARI/GP from Python

description: Calling PARI/GP from Python


code:
set_o = set(o)
min(f, key=lambda k: f[k] if k in set_o else float('inf'))

rawDescription: Most efficient way to find the key of the smallest value in a dictionary from a subset of the dictionary


code: orders_list = [row[0] for row in reader2]

rawDescription: Getting urls with csv reader and putting them into a list


code: print([item for lang in languages_list for item in [lang.code] + list(lang.alt)])

rawDescription: Returning a list in each iteration using list comprehension


code:
def get_cropped(style):
    rex = re.compile(r'.*/%s(?:\b|_)' % style)
    cropped_images = filter(rex.match, cropped)
    return cropped_images

rawDescription: python group file names by exact string

description: Python group file names by exact string


code: from matplotlib.ticker import LinearLocator

rawDescription: align grid lines on two plots

description: Align grid lines on two plots


code: func("arg", "arg2", *(("some value",) if condition == True else ()))

rawDescription: Conditionally passing arbitrary number of default named arguments to a function


code: curdate = time.strftime("%d/%m/%Y")    #returns 17/04/2015.

rawDescription: I want to find the date in the description of AMI image


rawDescription: Applying cell wise function in a dataframe


code:
with app.test_client() as c:
    response = c.get('/some/path/that/doesnt/exist')
    self.assertEquals(response.status_code, 404)

rawDescription: Testing Flask routes do and don't exist

description: Testing Flask routes do and don't exist


rawDescription: Scrapy crawling stackoverflow questions matching multiple tags


code: diffs = data - data.mean(1,keepdims=True)

rawDescription: Quickly compute eigenvectors for each element of an array in python


code:
count = 0
data = response[:]
while True:
    start = data.find(ultrias)
    if start < 0:
        break
    data = data[start + 1:]
    count += 1
print(count)

rawDescription: Python count everytime a string is found in another string


code:
import os
import checkIP
os.path.abspath(checkIP.__file__)
checkIP.__file__

rawDescription: Python: Find the absolute path of an imported module


code:
class Foo(object):
    __metaclass__ = FooMeta
    FOO = 123
    def a(self):
        pass

rawDescription: Python metaclasses: Why isn't __setattr__ called for attributes set during class definition?


code:
import argparse
import sys

def main(args):
    """Does all of the work."""
    ...

def parse_args(args):
    """Parses the arguments."""
    ...
    return parsed_args

if __name__ == "__main__":
    main(parse_args(sys.argv))

rawDescription: How to "hijack" and modify command line parameters


rawDescription: Sum over rows in scipy.sparse.csr_matrix


rawDescription: merging tuples in heap module in python

description: Merging tuples in heap module in python


code:
from django.utils.timezone import utc

def get_time_diff(self):
    if self.time_posted:
        now = datetime.datetime.utcnow().replace(tzinfo=utc)
        timediff = now - self.time_posted
        return timediff.total_seconds()

rawDescription: Django: How to get a time difference from the time post?


rawDescription: Python: finding files with matching extensions or extensions with matching names in a list


code: xticks(xticks()[0], [str(t*4) for t in xticks()[0]])

rawDescription: How do I change the scale of imshow in matplotlib without stretching the image?

description: Change the scale of imshow in matplotlib without stretching the image


code:
import datetime as DT

def time_between(a, b):
    minutes, seconds = divmod((b-a).total_seconds(), 60)
    hours, minutes = divmod(minutes, 60)
    return hours, minutes, seconds

# current time
tct = DT.datetime.now()
# job datetime (just for example)
we_dt = tct + DT.timedelta(hours=3, minutes=30)

work_alarm = DT.timedelta(hours=2, minutes=30)

# time till work
work_hours, work_minutes, work_seconds = time_between(tct, we_dt)

# time till get up
up_time = we_dt - work_alarm
up_hours, up_minutes, up_seconds = time_between(tct, up_time)
print("""\
Scheduled Work Time: {wt}
You have {we} in {h} + hours and {m} minutes.""".format(
          wt=we_dt.strftime('%H:%M'),
          we='something to do',
          h=work_hours,
          m=work_minutes))

if up_time > tct:
    print('You need to be up in {uh}  hours and {um} minutes.'.format(
        uh=up_hours,
        um=up_minutes))

rawDescription: How to see when a point in time has passed in Python

description: See when a point in time has passed in Python


rawDescription: Divide part of a dataframe by another while keeping columns that are not being divided


code:
import oauth2 as oauth
import oauth2.clients.smtp as smtplib

consumer = oauth.Consumer('anonymous', 'anonymous')
token = oauth.Token('1/MI6B2DqJP4FEkDRLUKrD5l46sQ0758-2ucEKBY-DeB0', 'NysqNqVTulFsdHpSRrPP56sF')

url = "https://mail.google.com/mail/b/testing.oauth.1@gmail.com/smtp/"

conn = smtplib.SMTP('smtp.googlemail.com', 587)
conn.set_debuglevel(True)
conn.ehlo('test')
conn.starttls()
conn.ehlo()
conn.authenticate(url, consumer, token)
header = 'To:testing.oauth.1@gmail.com\n' + 'From: testing.oauth.1@gmail.com\n' + 'Subject:testing \n'
msg = header + '\n this is test msg from me \n\n'
conn.sendmail('testing.oauth.1@gmail.com', 'testing.oauth.1@gmail.com', msg)

rawDescription: python & smtplib: Is sending mail via gmail using oauth2 possible?

description: Python & smtplib: Is sending mail via gmail using oauth2 possible


rawDescription: convert list elements to dictionary python

description: Convert list elements to dictionary python


rawDescription: Python list comprehension, with unique items


code:
id('new-string') # 48441808
id('new-string') # 48435352
# These change
id('newstring') # 48441728
id('newstring') # 48441728
# These don't, and I don't know why.

rawDescription: compare two python strings with hypen/dash

description: Compare two python strings with hypen/dash


code: import math, random, sys, time, bisect, string

rawDescription: update fct in python constructors

description: Update fct in python constructors


code:
def jack_chan_in_employee():
    query = Employee.all()
    count = query.filter('name =', 'Jacky Chan').count()
    return count

rawDescription: How can I check if a particular value exists in a particular column in google app engine datastore?(python)

description: Check if a particular value exists in a particular column in google app engine datastore?(python)


code:
def build_structure(data, d=[]):
    if 'children' in data:
        for c in data['children']:
            d.append({'title': c.get('title', 'No title'),
                                     'uri': c.get('uri', None)})
            build_structure(c, d)
    return d
pprint.pprint(build_structure(jdata))

rawDescription: Parsing json and searching through it

description: Parsing json and searching through it


code:
width = 100
height = 100

code = """<?php

  include('/path/to/file.php');
  echo start(""" + width + """, """ + height + """);

?>
"""
res = php(code)

rawDescription: call php function from python

description: Call php function from python


code:
def file_open_button(filename):
    b = Button(donut, text = 'open {0}'.format(filename), command = lambda: openfile(filename))
    return b

rawDescription: Create numerous unique events

description: Create numerous unique events


code:
def mapper(_, v, writer):
    for i, x in enumerate(v.split()):
        writer.emit(i, x)

def reducer(k, values, writer):
    writer.emit(k, sum(map(int, values)))

rawDescription: Read tab-separated file in Hadoop using Python


rawDescription: Pivoting duplicate columns into rows

description: Pivoting duplicate columns into rows


code: f = [[0 for _ in range(21)] for _ in range(21)]

rawDescription: How do 2 dimentional lists work in Python


code:
factory = PBClientFactory(...)
d = factory.getRootObject()
...

clientEndpoint.connect(factory)

rawDescription: Can Perspective Broker be used over stdio instead of TCP?


code: Board = list(range(1, 10)) # python 3

rawDescription: (Python) adding a list to another without the brackets


rawDescription: Pandas- Removing duplicate rows based on the columns


code:
exp = sympify('w1*X1'); right_exp = w1*X1

type(exp), type(right_exp)
Out[47]: (sympy.core.mul.Mul, sympy.matrices.expressions.matmul.MatMul)

rawDescription: Matrix Expression from String

description: Matrix Expression from String


code:
import numpy as np
import Image

def alpha_composite(src, dst):
    '''
    Return the alpha composite of src and dst.

    Parameters:
    src -- PIL RGBA Image object
    dst -- PIL RGBA Image object

    The algorithm comes from http://en.wikipedia.org/wiki/Alpha_compositing
    '''
    # http://stackoverflow.com/a/3375291/190597
    # http://stackoverflow.com/a/9166671/190597
    src = np.asarray(src)
    dst = np.asarray(dst)
    out = np.empty(src.shape, dtype = 'float')
    alpha = np.index_exp[:, :, 3:]
    rgb = np.index_exp[:, :, :3]
    src_a = src[alpha]/255.0
    dst_a = dst[alpha]/255.0
    out[alpha] = src_a+dst_a*(1-src_a)
    old_setting = np.seterr(invalid = 'ignore')
    out[rgb] = (src[rgb]*src_a + dst[rgb]*dst_a*(1-src_a))/out[alpha]
    np.seterr(**old_setting)
    out[alpha] *= 255
    np.clip(out,0,255)
    # astype('uint8') maps np.nan (and np.inf) to 0
    out = out.astype('uint8')
    out = Image.fromarray(out, 'RGBA')
    return out

rawDescription: With the Python Imaging Library (PIL), how does one compose an image with an alpha channel over another image?


code:
from flask import Flask, render_template

app = Flask('testapp')

@app.route('/')
def index():
    return render_template('index.html', variable='12345')

if __name__ == '__main__':
    app.run()

rawDescription: How to display a variable in HTML

description: Display a variable in HTML


code: reversed(lines)

rawDescription: Python : Reverse Order Of List

description: Python : Reverse Order Of List


code:
data = [(random.randint(1,20),random.randint(1,20)) for _ in range(10)]
data
foo(data,3,7)

rawDescription: Given a float, find if in list or closest number to it


rawDescription: Delete all characters in a multline string up to a given pattern


code: elements2 = elements0 + elements1

rawDescription: Py ReportLab append platypus

description: Py ReportLab append platypus


code: resultmatrix <- endvalues + startvalues

rawDescription: Code for determining number of 15 minute periods


code:
import pandas as pd

df = pd.DataFrame([([u'Avocado', u' Havarti', u' Turkey'], 'Barry Z', 8.98),
                   ([u'Bacon', u' Swiss', u'Turkey'], 'Barry B', 8.98)],
                  columns=['ingredients', 'name', 'price'])

print(df)
#                     ingredients     name  price
# 0  [Avocado,  Havarti,  Turkey]  Barry Z   8.98
# 1      [Bacon,  Swiss,  Turkey]  Barry B   8.98

rawDescription: How to normalize text in a list that is itself in a column of Pandas dataframe?

description: Normalize text in a list that is itself in a column of Pandas dataframe


rawDescription: How should I go about subsampling from a scipy.sparse.csr.csr_matrix and a list


code:
def class_id(self):
    "%s.%s.%s" % (self.__class__._meta.app_label,
                    self.__class__.__name__, self.id)

rawDescription: How to test django caching?

description: Test django caching


code:
class Handle:
    def __init__(self, pid=-1):
        self.pid = pid

    # A separate constructor, with a different name,
    # because "explicit is better than implicit" and
    # "sparse is better than dense" (cit. The Zen of
    # Python).
    # In my opinion, this is the most Pythonic solution.
    @classmethod
    def from_process_name(cls, procname):
        pid = get_pid(procname)
        return cls(pid)

rawDescription: Python overload __init__

description: Python overload __init__


code:
if randomNumber == One or randomNumber == Uno:
    randomNumber = 1
else:
    randomNumber = 2

rawDescription: If statement for multiple values

description: If statement for multiple values


code:
fname = 'qdata.txt'
words = set()
with open(fname) as f:
    for line in f:
        words.update(line.split())

print(words, len(words))

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

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


code: dict((k,sorted(v)) for k, v in d.items())

rawDescription: Sorting dictionary list values

description: Sorting dictionary list values


code:
class FileReader:
    def __init__(self, fp):
        self.fp = fp
    def read_callback(self, size):
        return self.fp.read(size)

rawDescription: POSTing a file and passing a parameter using pycurl


code:
Result
[('>link is the first', 'OIGFHFHAGIUUIIUFG'),
 ('>ganon is the fourth', 'ADGGHHHHHH'),
 ('>volvagia is the last', 'AFGDAAFGDAADFGAFDADFDFFDDFGAHUUERR')]

rawDescription: Search for word (from list of words) in line (from list of lines) and append values to new list. Python


code: dddcccba

rawDescription: Packing 4 Integers as ONE BYTE?

description: Packing 4 Integers as ONE BYTE


code: python -msplash.server

rawDescription: Python/Scrapy: Scraping Nasdaq's data?

description: Python/Scrapy: Scraping Nasdaq's data


code:
object = MyOtherFactory()
thing = MyFactory(object=object, related__param=object)

rawDescription: Passing an object created with SubFactory and LazyAttribute to a RelatedFactory in factory_boy


rawDescription: Python save arbitrarily nested list to CSV


code:
import copy

def recur_subs(last_eqn, frame):
    for item in last_eqn:
        if type(item[0]) == int and item[0] in frame:
            substitute = copy.deepcopy(frame[item[0]])
            item[0] = recur_subs(substitute, frame)

    return last_eqn

rawDescription: Search & Substitute numbers for list from a dictionary lookup


rawDescription: how to calculate a 2D array with numpy mask

description: Calculate a 2D array with numpy mask


rawDescription: Trying to figure out the run time of my function


code: surface.set_at((x, y), color)

rawDescription: Pygame: Draw single pixel

description: Pygame: Draw single pixel


code:
for record in data:
    fasta_out.write_record(record)

rawDescription: Using Bio.SeqIO to write single-line FASTA


rawDescription: How can I get pyyaml.safe_load() to handle python/unicode tag?

description: Get pyyaml.safe_load() to handle python/unicode tag


code:
STEP_BYTES = 1024

def main():
    infile = open("module3.txt","r")
    uppercasecount = 0
    lowercasecount = 0
    digitcount = 0
    spacecount = 0
    data = infile.read(STEP_BYTES)
    while data:
        for character in data:
            if character.isupper() == True:
                uppercasecount += 1
            if character.islower() == True:
                lowercasecount += 1
            if character.isdigit() == True:
                digitcount += 1
            if character.isspace() == True:
                spacecount += 1
        data = infile.read(STEP_BYTES)

    print ("Total count is %d Upper case, %d Lower case, %d Digit(s) and %d spaces." %(uppercasecount, lowercasecount, digitcount, spacecount))

main()

rawDescription: Reading multiple lines from an external text file in Python


rawDescription: Executing python code from script and getting interpreter-style output


code:
s = "Yes! These are words."
for w in s.split(' '):
   print(w, w.isalpha())

rawDescription: Finding letters in a string

description: Finding letters in a string


code:
import datetime
origin_time = '2014-02-21 00:00:00'
d = datetime.datetime.strptime(origin_time, '%Y-%m-%d %H:%M:%S')
d + datetime.timedelta(weeks=1)  # + 1 week
d + datetime.timedelta(hours=3)  # + 3 hours

rawDescription: time function in Python for add an interval to a datetime object

description: Time function in Python for add an interval to a datetime object


code: [reduce(lambda x, y: x.replace(y[0], y[1]), replacements, s) for s in mylist]

rawDescription: itertools or functools for find-replace list in python

description: Itertools or functools for find-replace list in python


code: yield (sequence[0],) + item, tuple(all_but_first.difference(item))

rawDescription: N choose N/2 sublists of a list

description: N choose N/2 sublists of a list


code:
import numpy as np
import pandas as pd

df = pd.DataFrame([['02/18/2016', '23:00:00', '00:00:00']],
                  columns = ["Date", "Start_Time", "End_Time"])

df['Diff'] = pd.to_timedelta((df['End_Time'] == '00:00:00').astype(int), unit='d')
for col in ['Start_Time', 'End_Time']:
    df[col] = pd.to_datetime(df['Date'] + ' ' + df[col])
df['End_Time'] += df['Diff']
df['Diff'] = df['End_Time'] - df['Start_Time']
print(df)

rawDescription: How to convert the time from 00:00 to 24:00 in python

description: Convert the time from 00:00 to 24:00 in python


code:
current_trace = [[3,5,1,5,7,9,4]]
sliding_tristep(current_trace)
current_trace

rawDescription: Why does Python modify the list which is out of the loop?


rawDescription: Exclude one or more items from pandas Series


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

rawDescription: Numpy: How to get rid of the minima along axis=1, given the indices - in an efficient way?


code:
from circle import Circle

c1 = Circle(0, 0, 5)
c2 = Circle(0, 0, 5)
print(c1)
print(c2)
print("Collision: {collision}".format(collision = Circle.is_collision(c1, c2)))

c1.move(16, 16)
c2.move(16, 136)
print(c1)
print(c2)
print("Collision: {}".format(Circle.is_collision(c1, c2)))

rawDescription: Python Circle Shape Collison Class

description: Python Circle Shape Collison Class


rawDescription: How do I pass a string into subprocess.Popen in Python 2?

description: Pass a string into subprocess.Popen in Python 2


code:
from collections import defaultdict

l = [
['a', 1],
['b',2],
['c',1],
['a', 2],
['c', 5]
]

d = defaultdict(int)
for key, value in l:
    d[key] += value

print(d.items())

rawDescription: List of list increment if exists otherwise extend


code:
class Scraper:
    def __init__(self,url):
        self.start_page = url
        self.run()
        # etc...

rawDescription: How to present a class as a function?

description: Present a class as a function


rawDescription: How to generate this custom alpha-numeric sequence?

description: Generate this custom alpha-numeric sequence


code:
def grid_objects(alist, blist):
    for i in range(len(alist)):
        for j in range(len(alist[i])):
            yield(alist[i][j], blist[i][j])

rawDescription: How can I, in python, iterate over multiple 2d lists at once, cleanly?


code:
for chunk in chunked(big_dict.iteritems(), batch_size):
    func(chunk)

rawDescription: How to iterate over a dictionary - n key-value pairs at a time

description: Iterate over a dictionary - n key-value pairs at a time


code:
return map(lambda a: a[0],               # extract the first element
        filter(lambda a: not a[1] == 1,  # take iff second element != 1
           reduce(f1, a, {}).items()     # reduce a using f1, then take items()
         )
    )

rawDescription: What is happening in this Python function?


code: nhatx, nhaty, nhatz = get_coords() # unpack tuple

rawDescription: create python list of exactly three elements

description: Create python list of exactly three elements


code:
def lookup(entry):
    entries = chain(*[index.get(entry, []) for index in indexes])
    return [yourstructure[i] for i in entries]

rawDescription: How to assign a collection of 3 pieces of data

description: Assign a collection of 3 pieces of data


code: divmod(5, 2)

rawDescription: Partitioning a file for parallel download


code:
import re

new_html = re.sub(r'<nav id="mainNav">.*?</nav>', replacement_text, original_text)

rawDescription: Parse HTML files then edit them in python


code:
def lookup_escape(name):
    from mako import filters
    return eval(filters.DEFAULT_ESCAPES[name])

rawDescription: Lookup escape filter method

description: Lookup escape filter method


code: p1, p2 = tDict['Example']['points']

rawDescription: Splitting one dictionary item into 2 variables


code:
import random
from easygui import *

ans = boolbox("Would you like to play Craps?")
while ans == True:
    looping = True
    firstRoll = random.randrange(1,7) + random.randrange(1,7)
    if firstRoll in (7,11):
        result = 1 # initial winning condition
        looping = False
    if firstRoll in (2,3,12):
        result = 0 #initial losing condition
        looping = False

    while looping:
        newRoll = random.randrange(1,7) + random.randrange(1,7)
        if newRoll == firstRoll:
            result = 1 #secondary winning condition
            looping = False
        if newRoll == 7:
            result = 0 #secondary losing condition
            looping = False

    string = ""
    if( result == 1 ):
        string += ("WIN!")
    else:
        string += ("LOSS!")
    msgbox(string)
    ans = boolbox("Would you like to play Craps?")

rawDescription: Craps simulator on python

description: Craps simulator on python


rawDescription: Can't seem to find success with datetime python2.7


code:
# admin.py
class CustomAdmin(admin.ModelAdmin):
    def render_change_form(self, request, context, *args, **kwargs):
        # here we define a custom template
        self.change_form_template = 'admin/myapp/change_form_help_text.html'
        extra = {
            'help_text': "This is a help message. Good luck filling out the form."
        }

        context.update(extra)
        return super(CustomAdmin, self).render_change_form(request,
            context, *args, **kwargs)

rawDescription: Adding model-wide help text to a django model's admin form


code:
[i for i,j in zip(a,b) if j == 1]
[i for i,j in zip(a,b) if j == 2]
[i for i,j in zip(b,b) if j == 2]

rawDescription: How to filter a list based on another list's values

description: Filter a list based on another list's values


code:
matrix[0][0] = 1
matrix

rawDescription: standard python library to construct matrix

description: Standard python library to construct matrix


code: a >= x and b >= y and c >= z

rawDescription: merging tuples in heap module in python

description: Merging tuples in heap module in python


code:
class CB(B):
    cls_definitions = {'C' : 444}

rawDescription: Inherit dictionary for multiple levels of ancestry


code:
import ast
import time
import argparse

from selenium import webdriver

EXECUTORS = {
    'desktop': 'http://127.0.0.1:4444/wd/hub',
    'ios': 'http://127.0.0.1:4723/wd/hub',
    'android': 'http://127.0.0.1:9515'
}

parser = argparse.ArgumentParser(description='My program.')
parser.add_argument('-c', '--capabilities', type=ast.literal_eval)
parser.add_argument('-e', '--executor', type=str, choices=EXECUTORS)

args = parser.parse_args()

driver = webdriver.Remote(command_executor=EXECUTORS[args.executor], desired_capabilities=args.capabilities)
driver.get("http://google.com")
time.sleep(5)
driver.quit()

rawDescription: Python: command line argument not passing the same way as hard coded lines


code:
top2_by_date.index =  top2_by_date.index.droplevel(0)
top2_by_date

rawDescription: Trying to create a stacked bar chart of the top 10 issues per month


code:
unique_key_dict = {}
for date in file_dict:
  for key in file_dict[date]:
    if date not in unique_key_dict: unique_key_dict[date] = []
    unique_key_dict[date].append(file_dict[date][key])

rawDescription: How to change dictionary from one format into another?

description: Change dictionary from one format into another


rawDescription: Difference of consecutive float numbers in a column


code:
d = dict.fromkeys(["Jon","Jane","Bob","Jim","Janice"],"blue")
d["Jim"] = "Brown"
d["Jane"] = "Brown"
d["Bob"] = "Brown"
[ (x,y) for (x,y) in itertools.combinations(d,2) if d[x]=="Brown" and d[y]=="Brown" ]

rawDescription: Compare a dictionary to itself in Python


rawDescription: In place difference between elements of a Numpy array


rawDescription: Finding minimum value element-wise in three 2d submatrices


code:
soup = BeautifulSoup(s)
soup.find('p').text
soup.find('p').text.replace('\n', ' ').strip()

rawDescription: Python: parsing only text from HTML using bs4 and RegEx


code:
from timeit import timeit
def crude(): "'a','b'".replace("'", "").split(",")
def regex(): re.findall(r"\w", "'a','b'")
def _eval(): list(ast.literal_eval("'a','b'"))
def csvio(): next(csv.reader(io.StringIO(u"'a','b'"), quotechar="'"))
timeit(crude)
timeit(regex)
timeit(_eval)
timeit(csvio)

rawDescription: Coverting a string to an array in python


code:
from itertools import product
from string import ascii_lowercase
keywords = [''.join(i) for i in product(ascii_lowercase, repeat = 3)]

rawDescription: What is the best way to generate all possible three letter strings?


code:
def compare(word):
    res = 0
    for letter in word:
        res += score.get(letter, 0)
        # dict.get(key, defaultvalue)
    return res

rawDescription: python - how to compare a key of the dictionary with a string character

description: Python - how to compare a key of the dictionary with a string character


code:
thelec = lecturers.get(lec_id)
if thelec is None:
    thelec = lecturers[lec_id] = Lecturer(lec_id, lec_name)
thelec.offered_proj.add(proj_id)

rawDescription: How do I create a list or set object in a class in Python?

description: Create a list or set object in a class in Python


code:
class TemplateX(Template):
    def getvalues(self,Str):
        """ Reads a string matching the template to find the original values.

            >>> temp = TemplateX("Blah: $xx;$y;")
            >>> newsting = temp.substitute(xx="1",y="2")
            >>> temp.getvalues(newstring)
            ('1', '2')

        """
        regex = re.sub(self.pattern, "(.*)", self.template)
        m = re.match(regex, Str)
        return m.groups()

rawDescription: In python extending the string.Template class for easy regular expressions


code:
import pygame

# you'll be able to shoot every 450ms
RELOAD_SPEED = 450

# the foes move every 1000ms sideways and every 3500ms down
MOVE_SIDE = 1000
MOVE_DOWN = 3500

screen = pygame.display.set_mode((300, 200))
clock = pygame.time.Clock()

pygame.display.set_caption("Micro Invader")

# create a bunch of events
move_side_event = pygame.USEREVENT + 1
move_down_event = pygame.USEREVENT + 2
reloaded_event  = pygame.USEREVENT + 3

move_left, reloaded = True, True

invaders, colors, shots = [], [] ,[]
for x in range(15, 300, 15):
    for y in range(10, 100, 15):
        invaders.append(pygame.Rect(x, y, 7, 7))
        colors.append(((x * 0.7) % 256, (y * 2.4) % 256))

# set timer for the movement events
pygame.time.set_timer(move_side_event, MOVE_SIDE)
pygame.time.set_timer(move_down_event, MOVE_DOWN)

player = pygame.Rect(150, 180, 10, 7)

while True:
    clock.tick(40)
    if pygame.event.get(pygame.QUIT): break
    for e in pygame.event.get():
        if e.type == move_side_event:
            for invader in invaders:
                invader.move_ip((-10 if move_left else 10, 0))
            move_left = not move_left
        elif e.type == move_down_event:
            for invader in invaders:
                invader.move_ip(0, 10)
        elif e.type == reloaded_event:
            # when the reload timer runs out, reset it
            reloaded = True
            pygame.time.set_timer(reloaded_event, 0)

    for shot in shots[:]:
        shot.move_ip((0, -4))
        if not screen.get_rect().contains(shot):
            shots.remove(shot)
        else:
            hit = False
            for invader in invaders[:]:
                if invader.colliderect(shot):
                    hit = True
                    i = invaders.index(invader)
                    del colors[i]
                    del invaders[i]
            if hit:
                shots.remove(shot)

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_LEFT]: player.move_ip((-4, 0))
    if pressed[pygame.K_RIGHT]: player.move_ip((4, 0))

    if pressed[pygame.K_SPACE]:
        if reloaded:
            shots.append(player.copy())
            reloaded = False
            # when shooting, create a timeout of RELOAD_SPEED
            pygame.time.set_timer(reloaded_event, RELOAD_SPEED)

    player.clamp_ip(screen.get_rect())

    screen.fill((0, 0, 0))

    for invader, (a, b) in zip(invaders, colors):
        pygame.draw.rect(screen, (150, a, b), invader)

    for shot in shots:
        pygame.draw.rect(screen, (255, 180, 0), shot)

    pygame.draw.rect(screen, (180, 180, 180), player)
    pygame.display.flip()

rawDescription: PyGame Custom Event

description: PyGame Custom Event


code:
pd.datetools.MONTHS
target.columns = ['is'+x.capitalize() for x in pd.datetools.MONTHS]

rawDescription: Pandas Dataframe - How To Convert Date to Boolean Columns?


code:
['DEFAULT_CHUNK_SIZE', 'chunks', 'close', 'closed', 'delete', 'encoding', 'field', 'file',
'fileno', 'flush', 'instance', 'isatty', 'multiple_chunks', 'name', 'newlines', 'open', 'path',
'read', 'readinto', 'readline', 'readlines', 'save', 'seek', 'size', 'softspace', 'storage', 'tell',
'truncate', 'url', 'write', 'writelines', 'xreadlines']

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:
class UUID(types.TypeDecorator):
    impl = Binary # this one!

...
...
id_column_name = "id"

def id_column():
    import uuid
    return Column(id_column_name,UUID(),primary_key=True,default=uuid.uuid4)

#usage:
app_uuid = Column(u'app_uuid', UUID(), primary_key=True)

rawDescription: Storing UUIDs in sqlite using Pylons and SQLalchemy


rawDescription: how to get only some of the strings in a list while using random,shuffle? in python

description: Get only some of the strings in a list while using random,shuffle? in python


code: mylist = [0 if x != x else x for x in mylist]

rawDescription: replace the NaN value zero after an operation with arrays

description: Replace the NaN value zero after an operation with arrays


code:
def restore(self, serialized_object):
    original = pickle.loads(serialized_object)
    self.__dict__.update(original.__dict__)

rawDescription: Storing serialized object in database then restoring object state from key


code:
def f():
    for i in range (0,numLights):
        master.after(100, renderGUI(a))
        w.update_idletasks()
        for n in range(0,numLights):
            if a[n]>1:
                a[n] = a[n]-1
            elif a[n] == 1:
                    #then its about to become nought, right?
                    a[n-1] = speed[n]
                    speed[n-1] = speed[n]
                    a[n] = a[n]-1
                    continue
            continue

btn = Button(master, text='Stop', width=20, command=master.destroy)
btn.pack()
master.after(1, f)
master.mainloop()

rawDescription: Tkinter need to update canvas mid process. It only updates when finished


rawDescription: Sort list by given order of indices -Python


code:
from django.db import models
from django.db.models.query import QuerySet

class MemberQuerySet(QuerySet):

    def in_group(self, group):
        return self.filter(group_set__pk=group.pk)

    def not_in_group(self, group):
        return self.exclude(groups_set__pk=group.pk)

class MemberManager(models.Manager):

    def get_queryset(self):
        return MemberQuerySet(self.model, using=self._db)

    def in_group(self, group):
        return self.get_queryset().in_group(group)

    def not_in_group(self, group):
        return self.get_queryset().not_in_group(group)

class Member(models.Model):

    # ...

    objects = MemberManager()

rawDescription: Django: Give custom filtering methods to `QuerySet` objects of a specific model


code:
import numpy as np
import Image

data = np.random.randint(0, 255, (10,10)).astype(np.uint8)
im = Image.fromarray(data)
im.save('test.tif')

rawDescription: Save raw data as tif

description: Save raw data as tif


rawDescription: Binary representation of float in Python (bits not hex)


code:
self.test = StringVar()
eBox = Entry(self, textvariable=self.test)

rawDescription: Store data from Entry widget tkinter

description: Store data from Entry widget tkinter


code:
# Define inclined plane.
angle = pi * 0.5  # <-- This is the variable
X2, Y2 = np.meshgrid([-dim, dim], [0, dim])
Z2 = Y2 * np.tan(angle)
X3, Y3 = np.meshgrid([-dim, dim], [-dim, 0])
Z3 = Y3 * np.tan(angle)

rawDescription: Angle between intersecting planes drawn with matplotlib


code:
sample = expon.rvs(loc=0, scale=scale, size=8)
sample

rawDescription: Generating random numbers given required distribution and empirical sampling


code:
import concurrent.futures as CF

with CF.ThreadPoolExecutor() as executor:
    future = executor.map(worker, args)
    result = list(future)

rawDescription: Distinguishing the return values from threads when a queue is used


code:
@pytest.fixture()
def test_package(request):
    def make_test_package(version='1.0'):
        ...
        request.addfinalizer(fin)
        ...
        return test_package

    return make_test_package

rawDescription: py.test: Pass a parameter to a fixture function

description: Py.test: Pass a parameter to a fixture function


code:
mylist = []
while 1:
    mylist.append(raw_input(': '))
    if raw_input('Add another? (Y/n): ')[0].lower() == 'n':
        break

rawDescription: PYTHON - Add on to list

description: PYTHON - Add on to list


code: [(a, b) for a in A for b in B if a in b]

rawDescription: Efficient strings containing each other

description: Efficient strings containing each other


rawDescription: How can I convert a SHA256 hash from integer to string and back?

description: Convert a SHA256 hash from integer to string and back


rawDescription: Python Pygame Camera Movement

description: Python Pygame Camera Movement


code:
from __future__ import division # in case you are on Python 2.x
dispute_percentage = {date: dispute_count.get(date, 0) / invoices
                      for date, invoices in invoice_count.items()}

rawDescription: After counting occurrences, how to make entries for each day in list


code: heads = [o.head for o in objs]

rawDescription: Why doesn't python have a attrsetter (and what would it take to make one)?


code: result = sorted(second_list_unordered, key=lambda d: indices.get(d['id']))

rawDescription: Sort list of dictionaries by appearance of key in a second ordered list


code:
import Queue
q=Queue.Queue()
q.put(1)
q.empty()
q.get()
q.empty()
q.empty()!=True

rawDescription: Correct usage of multithreading and Queue module in data collection application written in Python


code: scipy.stats.kstest(data, 'norm', args=(5, 10))

rawDescription: Using Scipy's stats.kstest module for goodness-of-fit testing


code:
STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join (BASE_DIR, "static"),
]

rawDescription: display a site admin template django

description: Display a site admin template django


code: self.caseful_id = value

rawDescription: Making id case-insensitive but case-preserving in endpoints-proto-datastore


rawDescription: Permute a list using Python

description: Permute a list using Python


code: x = input("What do you want to do? ").lower()

rawDescription: Python - function setting external variable to user input as side effect


code:
from mrjob.job import MRJob

class MRWordFrequencyCount(MRJob):

    def mapper(self, key, line):
        yield "chars", len(line)
        yield "words", len(line.split())
        yield "lines", 1
        yield "Constant",self.constant

    def reducer(self, key, values):
        yield key, sum(values)

    def __init__(self,*args,**kwargs):
        super(MRWordFrequencyCount, self).__init__(*args, **kwargs)
        self.constant = 10

if __name__ == '__main__':
    MRWordFrequencyCount.run()

rawDescription: Declare mrjob mapper without ignoring key


code:
from PySide.QtCore import *
from PySide.QtGui import *
from PySide import QtCore
import sys

class WorkThread(QtCore.QThread):
    ranThread = QtCore.Signal()
    # for PyQt, use QtCore.pyqtSignal() instead

    def __init__(self):
        QtCore.QThread.__init__(self)

    def run(self):
        print("From thread")
        self.ranThread.emit()

class Foo(QObject):
    def handle_trigger(self):
        print ("trigger signal received")
        self.get_thread.quit()
        self.get_thread.wait()
        QApplication.quit()

    def new_thread(self):
        self.get_thread = WorkThread()
        self.get_thread.ranThread.connect(self.handle_trigger)
        self.get_thread.start()

a = Foo()
a.new_thread()

app = QApplication(sys.argv)
app.exec_()

rawDescription: Custom signals and multithreading

description: Custom signals and multithreading


code:
from itertools import takewhile

def indexed_date_groups(it):
    indexed = enumerate(it)
    for i, elem in indexed:
        if elem is not None:
           yield (
             i, [elem] + [v for i, v in takewhile(
                 lambda v: v[1] is not None, indexed)])

rawDescription: Split list on None and record index

description: Split list on None and record index


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class A(Base):
    __tablename__ = "a"
    id = Column(Integer, primary_key=True)
    bs = relationship("B")

class B(Base):
    __tablename__ = "b"
    id = Column(Integer, primary_key=True)
    a_id = Column(Integer, ForeignKey('a.id'))

rawDescription: Python+SQLAlchemy: Getting mapper class from InstrumentedList?


code:
from bottle import Bottle, request, response
from datetime import datetime
from functools import wraps
import logging

logger = logging.getLogger('myapp')

# set up the logger
logger.setLevel(logging.INFO)
file_handler = logging.FileHandler('myapp.log')
formatter = logging.Formatter('%(msg)s')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

def log_to_logger(fn):
    '''
    Wrap a Bottle request so that a log line is emitted after it's handled.
    (This decorator can be extended to take the desired logger as a param.)
    '''
    @wraps(fn)
    def _log_to_logger(*args, **kwargs):
        request_time = datetime.now()
        actual_response = fn(*args, **kwargs)
        # modify this to log exactly what you need:
        logger.info('%s %s %s %s %s' % (request.remote_addr,
                                        request_time,
                                        request.method,
                                        request.url,
                                        response.status))
        return actual_response
    return _log_to_logger

app = Bottle()
app.install(log_to_logger)

@app.route('/')
def home():
    return ['hello, world']

app.run(host='0.0.0.0', port='8080', quiet=True)

rawDescription: python bottle always logs to console, no logging to file

description: Python bottle always logs to console, no logging to file


code:
if parts[-1] in MATCH_OPERATORS:
    op = parts.pop()

negate = False
if parts[-1] == 'not':
    parts.pop()
    negate = True

rawDescription: Mongoengine - using icontains with all

description: Mongoengine - using icontains with all


code:
from sqlalchemy import *

"""
INSERT INTO example_table
    (id, name)
SELECT 1, 'John'
WHERE
    NOT EXISTS (
        SELECT id FROM example_table WHERE id = 1
    );
"""

m = MetaData()

example_table = Table("example_table", m,
                        Column('id', Integer),
                        Column('name', String)
                    )

sel = select([literal("1"), literal("John")]).where(
           ~exists([example_table.c.id]).where(example_table.c.id == 1)
      )

ins = example_table.insert().from_select(["id", "name"], sel)
print(ins)

rawDescription: Postgresql - Insert into where not exists using sqlalchemy's INSERT from SELECT


rawDescription: How to operate with values in the same column in .csv files

description: Operate with values in the same column in .csv files


code:
df = DataFrame(np.random.randn(10,3),columns=list('abc'))
df.to_hdf('test.h5','df',format='table')
df.to_hdf('test.h5','df',format='table')
pd.read_hdf('test.h5','df')

rawDescription: Is it possible to directly rename pandas dataframe's columns stored in hdf5 file?


code:
def clean_string2(input_string):
    return "".join([char for char in input_string if char in string.letters])

rawDescription: String with non-letters

description: String with non-letters


code:
x = [1,2,3,4]
y = [1,4,7,8]
x += [ item for item in y if item not in x]
x

rawDescription: Appending new values to a python list

description: Appending new values to a python list


code:
def view_incrementer(view_func):
    """A decorator which increments board views"""

    def _wrapped(*args, **kwargs):
        # here you can increment Board.views
        # kwargs will contain URL parameters
        pk = kwargs.get('pk')
        Board.objects.filter(pk=pk).update(views=F('views')+1)
        return view_func(*args, **kwargs)

    return _wrapped

rawDescription: Counting "page views" or "hits" when using cache


code: lst = [ [int(val) for val in line.replace('.','0')] for line in f]

rawDescription: Building a List from a text file in python


code:
import csv
with open('statistics.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    results = map( lambda x: (x[0],x[1:]), reader)

rawDescription: Loading data from a csv file and display in list of tuples


code:
def choice_without_repetition(lst):
    i = 0
    while True:
        i = (i + random.randrange(1, len(lst))) % len(lst)
        yield lst[i]

rawDescription: how to pick random items from a list while avoiding picking the same item in a row

description: Pick random items from a list while avoiding picking the same item in a row


rawDescription: Calculate Euclidian Distance in two numpy arrays


code: dict(x.groups() for x in re.finditer(r'([a-zA-Z]+)(\d+)',"english100spanish24"))

rawDescription: how to split numbers and characters in python

description: Split numbers and characters in python


rawDescription: How to get all combinations of list groupings of at least a certain size?

description: Get all combinations of list groupings of at least a certain size


code:
from scipy.spatial.distance import cdist

p0 = cdist(pairs[:,0,:],positions)
p1 = cdist(pairs[:,1,:],positions)
out = pairs[((p0==0) | (p1==0)).sum(1)!=2]

rawDescription: Efficient Python implementation of numpy array comparisons


code:
for el in vector:
    if el in elements:
        elements[el] += 1
    elif random.choice(range(0, 10)) == 0:
        elements[el] = 1

rawDescription: Implementing the Alon-Matias-Szegedy Algorithm For The Second Moment Stream Approximation


rawDescription: In python how can I set multiple values of a list to zero simultaneously?


rawDescription: How to check if a string is a valid python identifier? including keyword check?

description: Check if a string is a valid python identifier? including keyword check


code:
import time
ion()
x = linspace(-1,1,51)
plot(sin(x))
for i in range(10):
    plot([sin(i+j) for j in x])
    # make it appear immediately
    draw()
    time.sleep(1)

rawDescription: matplotlib.pyplot/pylab not updating figure while isinteractive(), using ipython -pylab

description: Matplotlib.pyplot/pylab not updating figure while isinteractive(), using ipython -pylab


code:
def adapt(selobj):

    # Rotating / panning / zooming 3D view is handled here.
    # Creates a matrix.
    if selobj.rotation_mode == "AXIS_ANGLE":
        # object rotation_quaternionmode axisangle
        ang, x, y, z =  selobj.rotation_axis_angle
        matrix = Matrix.Rotation(-ang, 4, Vector((x, y, z)))
    elif selobj.rotation_mode == "QUATERNION":
        # object rotation_quaternionmode euler
        w, x, y, z = selobj.rotation_quaternion
        x = -x
        y = -y
        z = -z
        quat = Quaternion([w, x, y, z])
        matrix = quat.to_matrix()
        matrix.resize_4x4()
    else:
        # object rotation_quaternionmode euler
        ax, ay, az = selobj.rotation_euler
        mat_rotX = Matrix.Rotation(-ax, 4, 'X')
        mat_rotY = Matrix.Rotation(-ay, 4, 'Y')
        mat_rotZ = Matrix.Rotation(-az, 4, 'Z')
        if selobj.rotation_mode == "XYZ":
            matrix = mat_rotX * mat_rotY * mat_rotZ
        elif selobj.rotation_mode == "XZY":
            matrix = mat_rotX * mat_rotZ * mat_rotY
        elif selobj.rotation_mode == "YXZ":
            matrix = mat_rotY * mat_rotX * mat_rotZ
        elif selobj.rotation_mode == "YZX":
            matrix = mat_rotY * mat_rotZ * mat_rotX
        elif selobj.rotation_mode == "ZXY":
            matrix = mat_rotZ * mat_rotX * mat_rotY
        elif selobj.rotation_mode == "ZYX":
            matrix = mat_rotZ * mat_rotY * mat_rotX
    # handle object scaling
    sx, sy, sz = selobj.scale
    mat_scX = Matrix.Scale(sx, 4, Vector([1, 0, 0]))
    mat_scY = Matrix.Scale(sy, 4, Vector([0, 1, 0]))
    mat_scZ = Matrix.Scale(sz, 4, Vector([0, 0, 1]))
    matrix = mat_scX * mat_scY * mat_scZ * matrix

    return matrix

rawDescription: cannot get ray_cast in blender to work

description: Cannot get ray_cast in blender to work


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

angles = np.random.rand(100)
# Define coords for arrow tails (the origin)
x0, y0 = np.zeros(100), np.zeros(100)
# Define coords for arrow tips (cos/sin)
x, y = np.cos(angles), np.sin(angles)

# in case you want colored arrows
colors = 'bgrcmyk'
colors *= colors * (len(x0) / len(colors) + 1)
plt.quiver(x0, y0, x, y, color=colors[:len(x0)], scale=1) #scale sets the length
plt.show()

rawDescription: Plot stack of unit vectors in cylindrical coordinates - matplotlib


code: subprocess.POpen(r'python -c "open(\"foo.txt\", \"r\")', stdout=subprocess.PIPE)

rawDescription: Why does cat works and file open object doesn't?


code: max_col_in_row_i = np.argmax(F[i,:])

rawDescription: Numpy.argmax() on certain axis in 2D matrix


code:
y = ["- memphis , tn! ", "~~~memphis,tn", ":) memphis , tn (:", ". - memphis,tn - .", "memphis tn?", ". - memphis,tn - .", "- . memphis,tn . -"]

for x in y:
    print(','.join(y for y in re.split("[- ,!~?:;)(.]", x) if y))

rawDescription: Cleaning away symbols/whitespace efficiently


rawDescription: How to check if all items in a list are there in another list?

description: Check if all items in a list are there in another list


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

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

description: Permute n elements from list recursively in python


code:
for thing in itertools.chain(list1, list2, list3):
    do_stuff(thing)

rawDescription: how do I concatenate 3 lists using a list comprehension?

description: Concatenate 3 lists using a list comprehension


rawDescription: series containing cartesian product into table

description: Series containing cartesian product into table


code: p = pstats.Stats('profile.dat', stream = s)

rawDescription: Error when attempting to write cProfile information to file


rawDescription: Pandas dataframe: how to group by values in a column and create new columns out of grouped values


code:
import example
import inspect
x = 42
x
example.update_locals(inspect.currentframe(), (x, '3.14'))
x

rawDescription: Boost.python automatically convert parameter


code:
[Database]
host: '192.168.0.1'
user: 'user'
passwd: 'passwd'
port: 3306
db: 'data'

rawDescription: how to set up config file to access mysql database parameter

description: Set up config file to access mysql database parameter


code:
print(df.groupby([d.strftime('%Y-%m') for d in df['Start']]).sum())
#            A  B
# 2004-01    0  0
# 2004-02  123  0

# [2 rows x 2 columns]

rawDescription: Pandas Python: Merging every two rows in one dataframe


code: dataD = dict([i,data[i]] for i in xrange(len(data)))

rawDescription: What is recommended way to store dictionaries and json file type in python


code:
q = testClass()
q.setValue('red')

rawDescription: Using an Enum as a flag in a class, Python


code:
import ystockquote

def run():
    return ystockquote.get_all('GOOG')

rawDescription: How can I run Python code in Ruby?

description: Run Python code in Ruby


code:
for line in iterate:
    s = subprocess.Popen(['sampleprog.exe'], stdin = subprocess.PIPE, stdout = saveFile)
    s.communicate(line)

rawDescription: Reading Multiple lines in stdin using subprocess


code:
class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'user'
        excludes = ['email', 'password', 'is_active', 'is_staff', 'is_superuser']
        authentication = SessionAuthentication()

    def get_object_list(self, request):
        return super(UserResource, self).get_object_list(request).filter(username=request.user)

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/login%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('login_user'), name="api_login"),
            url(r'^(?P<resource_name>%s)/logout%s$' %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('logout_user'), name='api_logout'),
        ]

    def login_user(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        data = self.deserialize(request, request.body)
        user = authenticate(username=data.get('username'), password=data.get('password'))
        if user:
            login(request, user)
            return self.create_response(request, {'success': True})
        return self.create_response(request, {'success': False})

    def logout_user(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        logout(request)
        return self.create_response(request, {'success': True})

rawDescription: limiting data using tasty pie authorization

description: Limiting data using tasty pie authorization


code:
photo = PhotoImage(file="AI.gif")
x.configure(image=photo)

rawDescription: How do I save an image in python 3 using PIL?

description: Save an image in python 3 using PIL


rawDescription: Assistance with numpy savetext function

description: Assistance with numpy savetext function


code:
with transaction.atomic(): # or commit_on_success/commit_manually in django < 1.6
    new_entries = prepare_entries()
    new_entries.select_for_update() # lock to update only in current transaction
    for new_entry in new_entries:
        #change new_entry somehow
        new_entry.save()

rawDescription: General Ledger Concurrency (django atomic operations)


code:
import numpy as np
x = 1e9 * np.random.random(5)
x
x = ['{:f}'.format(item) for item in x]
x

rawDescription: convert elements of an array from scientific notation to decimal notation in python

description: Convert elements of an array from scientific notation to decimal notation in python


code: my_dict = dict((k,v.strip('"')) for k,v in pat.findall(txt) if k.startswith('MMM00'))

rawDescription: How to parse this web page (and convert into a dictionary) in Python

description: Parse this web page (and convert into a dictionary) in Python


code:
line = 'a: b :c:d:e  :f:gh   '
','.join(x.strip() for x in line.split(':'))

rawDescription: Python: Split, strip, and join in one line


rawDescription: Converting dates in Python

description: Converting dates in Python


code:
class number(int):
    @property
    def double(self):
        return type(self)(self * 2)

print(number(42).double) # 84
print(number(42).double.double) # 168

rawDescription: Python - How use properties without creating an object


code:
def f(x, *args):
    if not hasattr(f, 'all_intermediates'):
        f.all_intermediates = {}
    if x not in f.all_intermediates:
        f.all_intermediates[x] = computationally_expensive_fct(x)
    intermediate = f.all_intermediates[x]
    return do_stuff(intermediate,*args)

rawDescription: Alternative for non existing global dictionary


code:
for denom in [500, 200, 100, 50, 20, 10]:
    num_bills = 0
    while amount >= denom:
        amount -= denom
        num_bills += 1
    print(denom, "USD x", num_bills)

rawDescription: All cash change is only for one bill

description: All cash change is only for one bill


code:
gb = df.groupby(('Name','Value2'))
result = gb['Value'].unique()
result.reset_index(inplace=True) #lastly, reset the index
#  Name Value2       Value
#0    A      x  [8.8, 6.6]
#1    B      y       [6.6]

rawDescription: Pandas DataFrame - Combining one column's values with same index into list


code:
results = []
for r in range(2):

    # do the calcs from above to generate say df1 and df2
    results.append(df1)
    results.append(df2)

# concatenate the rows!
final_result = pd.concat(results)

rawDescription: Pandas: rare data form disrupts normal statistical analysis


code:
L = [('a01', '01-24-2011', 's1'), ('a03', '01-24-2011', 's2')]
for animal, date, station in L:
    month, day, year = date.split('-')
    print("animal ID {} in month {} at station {}".format(animal, month, station))

rawDescription: How to iterate into a list into a tuple

description: Iterate into a list into a tuple


code:
import os
import ctypes

if os.name == 'nt':
    from ctypes import wintypes

    kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

    def check_bool(result, func, args):
        if not result:
            raise ctypes.WinError(ctypes.get_last_error())
        return args

    kernel32.LoadLibraryExW.errcheck = check_bool
    kernel32.LoadLibraryExW.restype = wintypes.HMODULE
    kernel32.LoadLibraryExW.argtypes = (wintypes.LPCWSTR,
                                        wintypes.HANDLE,
                                        wintypes.DWORD)

class CDLLEx(ctypes.CDLL):
    def __init__(self, name, mode=0, handle=None,
                 use_errno=True, use_last_error=False):
        if os.name == 'nt' and handle is None:
            handle = kernel32.LoadLibraryExW(name, None, mode)
        super(CDLLEx, self).__init__(name, mode, handle,
                                     use_errno, use_last_error)

class WinDLLEx(ctypes.WinDLL):
    def __init__(self, name, mode=0, handle=None,
                 use_errno=False, use_last_error=True):
        if os.name == 'nt' and handle is None:
            handle = kernel32.LoadLibraryExW(name, None, mode)
        super(WinDLLEx, self).__init__(name, mode, handle,
                                       use_errno, use_last_error)

rawDescription: Python | accessing dll using ctypes

description: Python | accessing dll using ctypes


code: fracs = {str(Fraction(x, y)) for x in ilist1 for y in ilist2}

rawDescription: How to make a character in a list appear only once?

description: Make a character in a list appear only once


code:
try:
    from cPickle import dumps, loads
except ImportError:
    from pickle import dumps, loads

def s_dump(iterable_to_pickle, file_obj):
    """ dump contents of an iterable iterable_to_pickle to file_obj, a file
    opened in write mode """
    for elt in iterable_to_pickle:
        s_dump_elt(elt, file_obj)

def s_dump_elt(elt_to_pickle, file_obj):
    """ dumps one element to file_obj, a file opened in write mode """
    pickled_elt_str = dumps(elt_to_pickle)
    file_obj.write(pickled_elt_str)
    # record separator is a blank line
    # (since pickled_elt_str might contain its own newlines)
    file_obj.write('\n\n')

def s_load(file_obj):
    """ load contents from file_obj, returning a generator that yields one
        element at a time """
    cur_elt = []
    for line in file_obj:
        cur_elt.append(line)

        if line == '\n':
            pickled_elt_str = ''.join(cur_elt)
            elt = loads(pickled_elt_str)
            cur_elt = []
            yield elt

rawDescription: create working data structure in file

description: Create working data structure in file


rawDescription: Preferred arguments for redirect function


code: "|{:22}|".format("Niki Lauda")

rawDescription: Tabbing in Python?

description: Tabbing in Python


code:
def fetch_one(n):
    lst = [[1,2,3], [4,5,6], [7,8,9]][n]
    for x in lst:
        if x == 6:
            yield 'StopAll'
            return
        yield x

def work():
    n = 0
    in_progress = True
    while in_progress:
        numbers_iterator = fetch_one(n)
        for x in numbers_iterator:
            if x == 'StopAll':
                in_progress = False
                break
            print('x =', x)
        n += 1

work()

rawDescription: What do you call an iterator with two different "done" states?


code:
for i in product(zip(*(reel[j:]+reel[:j] for j in range(3))), repeat=3):
    print(i)

rawDescription: Python algorithm to sequentially generate all possible outcomes of slot machine


rawDescription: Python regex get text between last forward slash and then before first hyphen