code:
import pandas as pd
import pandas.io.data as pdd

x = pdd.DataReader('VBK', data_source='yahoo', start='2004/1/30')
y = pdd.DataReader('IWM', data_source='yahoo', start='2000/5/26')
z = {'x': x, 'y': y}

conversion = {
    'Open': 'first',
    'High': 'max',
    'Low': 'min',
    'Close': 'last',
    'Volume': 'sum',
    'Adj Close': 'last'
}

for key, df in z.items():
    z[key] = df.resample('BQ', how=conversion)

rawDescription: How to resample a dictionary of dataframes (Yahoo Data) in Pandas?

description: Resample a dictionary of dataframes (Yahoo Data) in Pandas


code:
min_date = max(df.first_valid_index() for df in [o, g])
max_date = min(df.last_valid_index() for df in [o, g])

o = o[(o.index >= min_date) & (o.index <= max_date)]
g = g[(g.index >= min_date) & (g.index <= max_date)]

rawDescription: How to make sure two pandas dataframes cover same dates only

description: Make sure two pandas dataframes cover same dates only


code:
class A(object):
    a = ""

    def some_func(self):
        analyze()

def analyze():
    frm = inspect.stack()[1]
    setattr(frm[0].f_globals.get('A'), 'stuff', 'boo')

a = A()
a.some_func()
# will output boo
print(a.stuff)

rawDescription: Access instance object attributes from instance.stack()


code:
class Spheroid(object):

    def __init__(self, shortt, longg):
        self.shortax = shortt
        self.longax = longg
        self.alpha = self.longax / self.shortax

    @property
    def vol(self):
        return Spheroid.volume(self.shortax, self.longax)

    @staticmethod
    def volume(shortax, longax):
        return (4 * np.pi / 3) * shortax * shortax * longax

# outside the instance call it like this
Spheroid.volume(X, Y)

rawDescription: Using a Class method/property outside of an instance variable


code:
c = a + b*(np.arange(1, len(y)+1))
y/c

rawDescription: Iterating over a numpy array with enumerate like function


code:
import requests

url = "http://mlb.mlb.com/lookup/json/named.player_info.bam?sport_code=%27mlb%27&player_id=150378"

response = requests.get(url)
data = response.json()
data['player_info']['queryResults']['row']['status']

rawDescription: Can't find the contents of a 'div' using BeautifulSoup


rawDescription: Parsing JSON data with Python

description: Parsing JSON data with Python


code:
def inputnumber():
    numbers = input('Enter number(s): ').split(',')
    return [int(i) for i in numbers]

x = inputnumber()
y = set(x)
print(y)

rawDescription: unique values in list from another list

description: Unique values in list from another list


code: utc_offset = fromtimestamp(ts) - utcfromtimestamp(ts)

rawDescription: Get timezone used by datetime.datetime.fromtimestamp()


code:
class Event(object):
    pass

class Observable(object):
    def __init__(self):
        self.callbacks = []
    def subscribe(self, callback):
        self.callbacks.append(callback)
    def fire(self, **attrs):
        e = Event()
        e.source = self
        for k, v in attrs.iteritems():
            setattr(e, k, v)
        for fn in self.callbacks:
            fn(e)

rawDescription: Python Observer Pattern: Examples, Tips?

description: Python Observer Pattern: Examples, Tips


code:
client = erppeek.Client(SERVER, DATABASE, USERNAME, PASSWORD)
invoices=client.search('account.invoice',[('type','ilike',"out_invoice")])
for i in range(len(invoices)):
    client.copy('account.invoice',invoices[i-1])

rawDescription: Mass invoices duplicate Odoo8

description: Mass invoices duplicate Odoo8


code:
vg = np.vectorize(g)
vg(e)
vg = np.vectorize(g, otypes=[np.float64])
vg(e)

rawDescription: Numpy vectorize wrongly converts the output to be integer


code:
from itertools import groupby
def remove_duplicates(data):
    ''' Remove duplicates from the data (normally a list).
        The data must be sortable and have an equality operator
    '''
    data = sorted(data)
    return [k for k, v in groupby(data)]

rawDescription: Fastest way to remove duplicates from a list of comparable, unhashable items


code:
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy.random as nr
quilt = nr.random((4,4))

plt.imshow(quilt, interpolation='none', aspect='equal', cmap=cm.jet)
plt.scatter([1,2,3],[3,0,1])
plt.plot([0,1,1.4, 2.3, 3.5],[0,1,2,3,2])
plt.show()

rawDescription: How do you get the marker squares to be exact squares with matplotlib?

description: Get the marker squares to be exact squares with matplotlib


code:
[pytest]
python_files=*py

rawDescription: How do I run pytest on all-modules?

description: Run pytest on all-modules


code:
import plotly.plotly as py
from plotly.graph_objs import *
# Fill in with your personal username and API key
# or, use this public demo account
py.sign_in('Python-Demo-Account', 'gwt101uhh0')

trace1 = Scatter(
    x=[0, 1, 2],
    y=[1, 2, 3],
    name='First Trace',
    showlegend=False
)
trace2 = Scatter(
    x=[0, 1, 2, 3],
    y=[8, 4, 2, 0],
    name='Second Trace',
    showlegend=True
)
data = Data([trace1, trace2])
plot_url = py.plot(data, filename='show-legend')

rawDescription: How to avoid duplicate legend labels in plotly or pass custom legend labels

description: Avoid duplicate legend labels in plotly or pass custom legend labels


code:
from itertools import groupby
def block_generator(filename):
    with open(filename) as lines:
        for pred,block in groupby(lines, "\t\n".__ne__):
            if pred:
                yield block

rawDescription: Why does takewhile() skip the first line?


code:
Python
with open('input.txt') as f:
    indent = 8
    prev_depth = -1
    closes = []
    for line in f:
        line = line.strip()
        if not line: continue

        depth = line.count('|')
        while prev_depth >= depth:
            prev_depth -= 1
            print(closes.pop())
        pad = ' ' * (depth*indent)
        print(pad + 'If ({})'.format(line.lstrip('| ').split(':', 1)[0]))
        print(pad + '{')
        closes.append(pad + '}')
        if ':' in line:
            pad2 = ' ' * ((depth+1)*indent)
            print(pad2 + 'Return {}'.format(line[line.find(':')+1:].strip()))
        prev_depth = depth
    while closes:
        print(closes.pop())

rawDescription: Parsing Tree Structure to If statements

description: Parsing Tree Structure to If statements


code:
from django.contrib.auth.views import login
from django.http import HttpResponseRedirect

def mylogin(request, **kwargs):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    else:
        return login(request, **kwargs)

rawDescription: django-registration, fix for a glitch

description: Django-registration, fix for a glitch


code:
from django.db.models.signals import post_save

instance = MyModel(field='qwerty')
post_save.send(MyModel, instance=instance, created=True)

rawDescription: Can I manually trigger signals in Django?

description: Manually trigger signals in Django


code:
import subprocess
import sys

# Create subprocess with pipes for stdin and stdout
progA = subprocess.Popen("a", stdin=subprocess.PIPE, stdout=subprocess.PIPE)

# Reassign the pipes to our stdin and stdout
sys.stdin = progA.stdout
sys.stdout = progA.stdin

rawDescription: How can I get those two processes (programs) talk to each other directly using pipes?

description: Get those two processes (programs) talk to each other directly using pipes


code:
col = pymongo.Connection().db.collection
cur = col.find({})

obj = next(cur, None)
if obj:
    age = obj['age']
    gender = obj['gender']

rawDescription: PyMongo Cursor Iteration

description: PyMongo Cursor Iteration


code:
import pickle
numlist = {'Person': ['2342342', '15:05']}
outfile = open("log.txt", "wb")
pickle.dump(numlist, outfile)
outfile.close()
infile = open("log.txt", "rb")
pickle.load(infile)

rawDescription: Pickle and Unpickle dict w/list as value


code: y = map(testfunction, x)

rawDescription: How to iterate over two dataframes?

description: Iterate over two dataframes


code:
for row in reader:
    row_result = {}
    for key, value in row.iteritems():
        if '.' in key:
            tableau, name = key.split('.')
            row_result.setdefault(tableau, []).append({'value': value, 'name': name})
        else:
            row_result[key] = value
    csv_rows.append(row_result)

rawDescription: CSV to JSON with Python

description: CSV to JSON with Python


code:
class GameOfThrones(object):

    def __init__(self, kingdom):
        self.kingdom = kingdom
        self.population = {}

    def create_character(self, *args, **kwargs):
        c = Character(*args, **kwargs)
        self.population[c.name] = c

    def kill_character(self, killer, victim):
        self.population[killer].kill(self.population[victim])
        del self.population[victim]

class Character(object):

    def __init__(self, name, house, castle):
        self.name = name
        self.house = house
        self.castle = castle
        self.victims = []
        self.alive = True

    @property
    def kills(self):
        return len(self.victims)

    def kill(self, other):
        other.dies()
        self.victims.append(other)
        print("{} killed {}".format(self.name, other.name))

    def dies(self):
        self.alive = False

game = GameOfThrones()

game.create_character("Joffrey", "Baratheon", "King's Landing")
game.create_character("Eddard", "Stark", "Winterfell")

game.kill_character("Eddard", "Joffrey")

rawDescription: How to write a class method to simulate object being eliminated by another in Python?

description: Write a class method to simulate object being eliminated by another in Python


code:
alist = [1,4,1,2,1]
blist = [6,7,8,9,5]
d = {}
for a,b in zip(alist, blist):
    d[a] = d.get(a, 0) + b

[d[x] for x in sorted(d)]

rawDescription: Python, how do we concatenate two lists with a specific format then sum like elements?


code:
s = 'first_item second\ item "third item"'

import shlex

shlex.split(s)
Out[3]: ['first_item', 'second item', 'third item']

rawDescription: "Unquote"/parse bash argument string in python


code:
class Product(models.Model):
    ...
    def save(self, *args, **kwargs):
        for field_name in ['title', 'price', ... ]:
            val = getattr(self, field_name, False)
            if val:
                setattr(self, field_name, val.capitalize())
        super(Product, self).save(*args, **kwargs)

rawDescription: How to automatically capitalize field on form submission in Django?

description: Automatically capitalize field on form submission in Django


code:
def recursive_division (a, b):
    if b == 0:
        return ("(Cannot divide by zero)","(Cannot divide by zero)")
    elif a < b:
        return (0, a)
    else:
        (x, y) = recursive_division (a - b, b)
        return (x+1, y)

rawDescription: Recursive division using only subtraction and addition


code:
import logging
import pexpect
import re

# this is the method called by the pexpect object to log
def _write(*args, **kwargs):
    content = args[0]
    # Ignore other params, pexpect only use one arg
    if content in [' ', '', '\n', '\r', '\r\n']:
        return # don't log empty lines
    for eol in ['\r\n', '\r', '\n']:
        # remove ending EOL, the logger will add it anyway
        content = re.sub('\%s$' % eol, '', content)
    return logger.info(content) # call the logger info method with the reworked content

# our flush method
def _doNothing():
    pass

logger = logging.getLogger('foo')
hdlr = logging.FileHandler('/bar.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)

# give the logger the methods required by pexpect
logger.write = _write
logger.flush = _doNothing

p = pexpect.spawn('echo "hello world !"', logfile=logger)

rawDescription: How do I get timestamps in logfile of pexpect

description: Get timestamps in logfile of pexpect


code:
from sqlalchemy import func, NUMERIC
db_objects = session.query(DatabasePolygon)\
    .order_by(func.cast(func.replace(DatabasePolygon.tag, 'shape', ''),
                        NUMERIC).desc()).all()

rawDescription: Order sqlalchemy query objects in descending order by a fields digit portion


code:
import sys
from PyQt4 import QtGui

class MyWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.table = QtGui.QTableWidget(5,5)
        self.table.setHorizontalHeaderLabels(['1', '2', '3', '4', '5'])
        self.table.setVerticalHeaderLabels(['1', '2', '3', '4', '5'])
        self.table.horizontalHeader().sectionDoubleClicked.connect(self.changeHorizontalHeader)

        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.table)
        self.setLayout(layout)

    def changeHorizontalHeader(self, index):
        oldHeader = self.table.horizontalHeaderItem(index).text()
        newHeader, ok = QtGui.QInputDialog.getText(self,
                                                      'Change header label for column %d' % index,
                                                      'Header:',
                                                       QtGui.QLineEdit.Normal,
                                                       oldHeader)
        if ok:
            self.table.horizontalHeaderItem(index).setText(newHeader)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())

rawDescription: Set pyqt qtablewidget horizontal header lable editable


code:
import types

def strategyA(possible_self):
    pass

instance = OrigObject()

instance.strategy = types.MethodType(strategyA, instance)

instance.strategy()

rawDescription: Overwriting class methods without inheritance (python)


code:
(flights
    .keyBy(lambda x: x[5])
    .groupByKey()
    .mapValues(lambda vs: sorted(vs, key=lambda x: x[1:5])))

rawDescription: What is the most efficient way to do a sorted reduce in PySpark?


code:
import random

numbers = [n for n in listP if n is not None]
result = [n if n is not None else random.choice(numbers) for n in listP]

rawDescription: Python replacing numbers in a list

description: Python replacing numbers in a list


code:
#!/usr/bin/env python

import Image

im1 = Image.open("hil0.png")
im2 = Image.open("hil0.png")
w, h = im1.size

draw1 = im1.load()
draw2 = im2.load()

for x in range(w):
    for y in range(h):
        if draw1[x,y] == (255,0,0):
            for dx in [-1,0,1]:
                for dy in [-1,0,1]:
                    nx = x+dx
                    ny = y+dy
                    # print nx, ny
                    if nx>=0 and ny>=0 and nx<w and ny<h:
                        draw2[ nx, ny ] = (255,0,0)

# im2.show()
im2.save("hil1.png")

rawDescription: How can I increase the pixel size in PNG file in Python?

description: Increase the pixel size in PNG file in Python


code:
CoolDog(True)
CoolDog(True, old=False)
CoolDog(bite=True, old=True)
CoolDog(old=True, bite=False)

rawDescription: Most "pythonic" way of organising class attributes, constructor arguments and subclass constructor defaults?


code:
from distutils import log
from distutils.core import setup
from distutils.command.sdist import sdist

class CustomSdist(sdist):

    user_options = [
        ('packaging=', None, "Some option to indicate what should be packaged")
    ] + sdist.user_options

    def __init__(self, *args, **kwargs):
        sdist.__init__(self, *args, **kwargs)

        self.packaging = "default value for this option"

    def get_file_list(self):

        log.info("Chosen packaging option: {self.packaging}".format(self=self))

        # Change the data_files list here based on the packaging option
        self.distribution.data_files = list(
          ('folder', ['file1', 'file2'])
        )
        sdist.get_file_list(self)

if __name__ == "__main__":

    setup(
        name = "name",
        version = "version",
        author = "author",
        author_email = "author_email",
        url = "url",
        py_modules = [
            # ...
        ],
        packages = [
            # ...
        ],
#        data_files = default data files for commands other than sdist if you wish
        cmdclass={
            'sdist': CustomSdist
        }
    )

rawDescription: Create different distribution types with setup.py


code:
def recurse_tree(node):
    tree = {}
    for element in node:
        name = element.get('name')
        tree[name] = recurse_tree(element)
    if tree:
        return tree
    else:
        return 'No children.'

rawDescription: Read dynamic xml using element tree

description: Read dynamic xml using element tree


code:
import csv
with open('1.txt', 'rt') as f:
  reader = csv.reader(f, delimiter=' ', skipinitialspace=True)

  lineData = list()

  cols = next(reader)
  print(cols)

  for col in cols:
    # Create a list in lineData for each column of data.
    lineData.append(list())

  for line in reader:
    for i in xrange(0, len(lineData)):
      # Copy the data from the line into the correct columns.
      lineData[i].append(line[i])

  data = dict()

  for i in xrange(0, len(cols)):
    # Create each key in the dict with the data in its column.
    data[cols[i]] = lineData[i]

print(data)

rawDescription: Importing data and variable names from a text file in Python


code:
class MyCustomType(object):
    def __str__(self):
        return "My string is really costly to produce"

rawDescription: lazily providing the value of a string

description: Lazily providing the value of a string


code:
from django.contrib.auth.models import User as DjangoUser
from django.db import models

class ClientDetails(models.Model):
   user = models.OneToOneField(DjangoUser)
   address = models.ForeignKey(Address, blank=True, null=True)

rawDescription: Django Model object creation

description: Django Model object creation


code:
import matplotlib.pyplot as plt
from scipy.interpolate import griddata
import numpy as np
import vtk
from vtk.util.numpy_support import vtk_to_numpy

# load a vtk file as input
reader = vtk.vtkXMLUnstructuredGridReader()
reader.SetFileName("my_input_data.vtk")
reader.Update()

# Get the coordinates of nodes in the mesh
nodes_vtk_array= reader.GetOutput().GetPoints().GetData()

#The "Temperature" field is the third scalar in my vtk file
temperature_vtk_array = reader.GetOutput().GetPointData().GetArray(3)

#Get the coordinates of the nodes and their temperatures
nodes_nummpy_array = vtk_to_numpy(nodes_vtk_array)
x,y,z= nodes_nummpy_array[:,0] , nodes_nummpy_array[:,1] , nodes_nummpy_array[:,2]

temperature_numpy_array = vtk_to_numpy(temperature_vtk_array)
T = temperature_numpy_array

#Draw contours
npts = 100
xmin, xmax = min(x), max(x)
ymin, ymax = min(y), max(y)

# define grid
xi = np.linspace(xmin, xmax, npts)
yi = np.linspace(ymin, ymax, npts)
# grid the data
Ti = griddata((x, y), T, (xi[None,:], yi[:,None]), method='cubic')

## CONTOUR: draws the boundaries of the isosurfaces
CS = plt.contour(xi,yi,Ti,10,linewidths=3,cmap=cm.jet)

## CONTOUR ANNOTATION: puts a value label
plt.clabel(CS, inline=1,inline_spacing= 3, fontsize=12, colors='k', use_clabeltext=1)

plt.colorbar()
plt.show()

rawDescription: VTK to Maplotlib using Numpy

description: VTK to Maplotlib using Numpy


code:
from sklearn import preprocessing

x = df.values #returns a numpy array
min_max_scaler = preprocessing.MinMaxScaler()
x_scaled = min_max_scaler.fit_transform(x)
df = pandas.DataFrame(x_scaled)

rawDescription: Normalize rows of pandas data frame

description: Normalize rows of pandas data frame


code:
def as_dict(self):

    props = {k: getattr(self, k) for (k, v) in vars(self.__class__).items()
             if type(v) is property}

    columns = {c.name: getattr(self, c.name) for c in self.__table__.columns}
    columns.update(**props)

    return columns

rawDescription: Flask-SQLALchemy add property value to dictionary of columns names


code:
import os
print('What game do you want to play?')
print('1.  Hangman')
print('2.  Dragon Realm')
print('3.  Crafting Challenge')

gamechoice = input()
print('Ok, sending you there...')

if gamechoice == 1:
    os.startfile('hangman.py')
elif gamechoice == 2:
    os.startfile('Dragon Realm.py')
elif gamechoice == 3:
    os.startfile('crafting challenge.py')

rawDescription: How do i make a game director in python?

description: Make a game director in python


rawDescription: Pandas un-list while applying values to rows


code:
import pandas as pd

df1 = pd.DataFrame({'Data': [10, 20, 30, 40]})
df2 = pd.DataFrame({'Data': [13, 24, 35, 46]})

writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')

df1.to_excel(writer, sheet_name='Sheet1')
df2.to_excel(writer, sheet_name='Sheet1', startrow=6)

rawDescription: XlsxWriter python to write a dataframe in a specific cell


code:
import time
t = time.strptime("2010-02-02 7:31", "%Y-%m-%d %H:%M")
t
import datetime
datetime.datetime(*t[:6])

rawDescription: datetime command line argument in python 2.4

description: Datetime command line argument in python 2.4


rawDescription: How can i get exactly 2 decimal position in python

description: Get exactly 2 decimal position in python


rawDescription: How to avoid some xticks are auto-hidden in pandas?

description: Avoid some xticks are auto-hidden in pandas


code:
desired_width = 320
pd.set_option('display.width', desired_width)

rawDescription: Getting wider output in PyCharm's built-in console


code:
def end_other(s1, s2):
    s1 = s1.lower()
    s2 = s2.lower()
    return s1.endswith(s2) or s2.endswith(s1)

rawDescription: Python String function

description: Python String function


code:
html = """

test

test

blah
"""
soup = BeautifulSoup(html)
[div.extract() for div in soup("div",id="top-card")]
soup

rawDescription: Remove portion of html (tag) keeping style - python


code:
import pygtk
pygtk.require('2.0')
import gtk

def clicked(selection):

    global selection_signal

    liststores, listpaths = selection.get_selected_rows()
    for selected_row in xrange(len(listpaths)):
        #The 1 looks for the 'B' row
        if listpaths[selected_row][0] == 1:
            #Blocking the handler so that the reverting doesn't invoke a callback
            selection.handler_block(selection_signal)
            selection.unselect_path(listpaths[selected_row])
            selection.handler_unblock(selection_signal)

w = gtk.Window()
treemodel = gtk.ListStore(str)
for r in ('A', 'B', 'C'):
    treemodel.append([r])

treeview = gtk.TreeView(treemodel)
w.add(treeview)
tv_cell = gtk.CellRendererText()
tv_column = gtk.TreeViewColumn("Header", tv_cell, text=0)
treeview.append_column(tv_column)
selection = treeview.get_selection()
selection_signal = selection.connect("changed", clicked)
selection.set_mode(gtk.SELECTION_MULTIPLE)
w.show_all()

rawDescription: Making rows in a GTK TreeView unselectable


code:
from Tkinter import *
import ttk
import heapq

# Program GUI
class App(object):
    def __init__(self):
        self.root = Tk()
        self.graph = {
            'a': {'w': 16, 'x': 9, 'y': 11},
            'b': {'w': 11, 'z': 8},
            'w': {'a': 16, 'b': 11, 'y': 4},
            'x': {'a': 9, 'y': 12, 'z': 17},
            'y': {'a': 11, 'w': 4, 'x': 12, 'z': 13},
            'z': {'b': 8, 'x': 17, 'y': 13},
        }
        self.termini = {}  # storage for node ids of each terminus
        self.create_gui_widgets()
        self.root.mainloop()

    def create_gui_widgets(self):
        values = tuple(self.graph.keys())  # valid node ids
        self.combo1 = self.create_combobox('start', values, 5, 75, 5, 20)
        self.combo2 = self.create_combobox('end', values, 5, 100, 5, 20)

    def create_combobox(self, terminus, values, x, y, height, width):
        " Utility to create ComboBox of node ids for a terminus of route. "
        combobox = ttk.Combobox(self.root, height=height, width=width)
        combobox['values'] = values
        combobox.terminus = terminus
        combobox.current(0)
        self.termini[combobox.terminus] = combobox.get()  # set to current value
        combobox.place(x=x, y=y)
        combobox.bind("<<ComboboxSelected>>", self.combobox_event_handler)
        return combobox

    def combobox_event_handler(self, event):
        " Event handler for both ComboBoxes. "
        combobox = event.widget  # ComboBox triggering event
        self.termini[combobox.terminus] = combobox.get()  # set selected node id

        # if both a start and end terminus are defined and different, then
        # find and display shortest path between them
        start, end = self.termini.get('start'), self.termini.get('end')
        if start and end and start != end:
            cost, path = self.shortest_path(start, end)
            print('cost: {}, path: {}'.format(cost, path))

    # Dijkstra's search algorithm
    def shortest_path(self, start, end):
        graph = self.graph  # copy to local var for faster access
        queue, seen = [(0, start, [])], set()
        while True:
            cost, v, path = heapq.heappop(queue)
            if v not in seen:
                path = path + [v]
                seen.add(v)
                if v == end:
                    return cost, path
                for next, c in graph[v].iteritems():
                     heapq.heappush(queue, (cost + c, next, path))

App()

rawDescription: Binding two comboboxes to one function

description: Binding two comboboxes to one function


code:
class DerivedMetaClass(BaseMetaClass):
    def __new__(cls, name, bases, dct):
        # Do your custom memory allocation here, if any

        # Now let base metaclass do its memory allocation stuff
        return BaseMetaClass.__new__(cls, name, bases, dct)

    def __init__(cls, name, bases, dct):
        # Do your custom initialization here, if any
        # This, I assume, is where your catalog creation stuff takes place

        # Now let base metaclass do its initialization stuff
        super(DerivedMetaClass, cls).__init__(name, bases, dct)

rawDescription: Python: Metaclasses all the way down

description: Python: Metaclasses all the way down


code:
sudoPassword = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'
p = os.system('echo %s|sudo -S %s' % (sudoPassword, command))

rawDescription: Using sudo with Python script

description: Using sudo with Python script


code:
import re
def as_link(match):
    link = match.group(1)
    return '{}'.format(link.replace(' ', '_'), link)
text = 'This is a random text. This should be a [[link somewhere]]. And some more text at the end.'
re.sub(r'\[\[(.*?)\]\]', as_link, text)

rawDescription: Python Regular Expression: Replace Withing a group


code:
def post(self):
    product = Product()
    product.ref_category = db.get(self.request.get('ref_category'))
    product.put()

rawDescription: Inserting Data in Datastore - App Engine - One to Many


code:
it = iter(list1)
while True:
    try:
        item = next(it)
    except StopIteration:
        break
    if item == thingToCheck:
        return True
return False

rawDescription: Formal interpretation of `in` in Python's `for` loops


code:
def clickButton2(self):
    self.setCentralWidget(MyWidget2())

rawDescription: PyQt4: disable deleting widget after setCentralWidget


code:
def open_spider(self, spider):
    self.file = codecs.open('%s_outputchiness.json' % spider.name, 'w', encoding='utf-8')

def process_item(self, item, spider):
    line = json.dumps(dict(item)) + "\n"
    self.file.write(line.encode('utf-8').decode("unicode_escape"))

def spider_closed(self, spider):
    self.file.close()

rawDescription: scrapy:custom pipeline save file with spider name

description: Scrapy:custom pipeline save file with spider name


code:
import docker
import dockerpty

client = docker.Client()
container = client.create_container(
    image='busybox:latest',
    stdin_open=True,
    tty=True,
    command='/bin/sh',
)
client.start(container)

dockerpty.PseudoTerminal(client, container).start()

rawDescription: How to use docker-py (official docker client) to start a bash shell?

description: Use docker-py (official docker client) to start a bash shell


code:
from itertools import cycle, islice
df['xyz'] = list(islice(cycle([0, 1]), len(df)))

rawDescription: How can I fill a DataFrame column with a list of e.g. 2 values in Pandas Python?

description: Fill a DataFrame column with a list of e.g. 2 values in Pandas Python


code:
import re
print(re.match(r'[^\\]+\\[^\\]+', r'C:\my_dir\repo\branch').group())
re.findall(r'[^\\]+\\[^\\]+|.+', r'C:\my_dir\repo\branch')

rawDescription: Split path in Python

description: Split path in Python


code: a2 = [[item] for item in a]

rawDescription: Split single list into multiple list in python


code:
import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as plt

# By indexing at 0 along first dimension, we eliminate the time
# dimension, which only had size 0 anyway.
lons = b.variables['XLONG'][0]
lats = b.variables['XLAT'][0]
temp = a.variables['T2'][0]

lat_bnds, lon_bnds = [49,53], [-125,-115]

# Just AND together all of them and make a big mask
subset = ((lats > lat_bnds[0]) & (lats < lat_bnds[1]) &
          (lons > lon_bnds[0]) & (lons < lon_bnds[1]))

# Apply mask--should apply to trailing dimensions...I think
T_subset = temp[subset]

rawDescription: WRF netcdf file - subset smaller array out of dataset based on coordinate boundaries in python


code:
group = df.groupby([lambda x: x.year, lambda x: x.month])
dataframes = []
for n in range(23):
    frame = group.nth(n).describe().T
    frame.index = [(inner, n, outer) for outer, inner in frame.index]
    dataframes.append(frame)
final_df = pd.concat(dataframes)

rawDescription: "Flattening" output of group.nth in Pandas


code:
current_year = now.year
current_month = now.month
current_day = now.day

rawDescription: Being able to print before declaring. PYTHON


code:
# pylint: disable=wildcard-import, method-hidden
# pylint: enable=too-many-lines

rawDescription: What pylint options can be specified in inline comments?


code:
import glob, csv, xlwt, os
wb = xlwt.Workbook()
for filename in glob.glob("c:/xxx/*.csv"):
    (f_path, f_name) = os.path.split(filename)
    (f_short_name, f_extension) = os.path.splitext(f_name)
    ws = wb.add_sheet(f_short_name)
    spamReader = csv.reader(open(filename, 'rb'))
    for rowx, row in enumerate(spamReader):
        for colx, value in enumerate(row):
            ws.write(rowx, colx, value)
wb.save("c:/xxx/compiled.xls")

rawDescription: python: creating excel workbook and dumping csv files as worksheets

description: Python: creating excel workbook and dumping csv files as worksheets


code:
import math

def distance(row_a, row_b, weights):
    diffs = [math.fabs(a-b) for a,b in zip(row_a, row_b)]
    return sum([v*w for v,w in zip(diffs, weights)])

def get_nearest_neighbour(data, criteria, weights):
    def sort_func(row):
        return distance(row, criteria, weights)
    return min(data, key=sort_func)

rawDescription: Python: nearest neighbour (or closest match) filtering on data records (list of tuples)


code:
from oauth2client.client import flow_from_clientsecrets

flow = flow_from_clientsecrets(
  "/path/to/client_secrets.json",
  scope=["https://www.google.com/m8/feeds"],
  redirect_url="http://example.com/auth_return"
)

# 1. To have user authorize, redirect them:
send_redirect(flow.step1_get_authorize_url())

# 2. In handler for "/auth_return":
credentials = flow.step2_exchange(request.get("code"))

# 3. Use them:

import gdata.contacts.client
import httplib2

# Helper class to add headers to gdata
class TokenFromOAuth2Creds:
  def __init__(self, creds):
    self.creds = creds
  def modify_request(self, req):
    if self.creds.access_token_expired or not self.creds.access_token:
      self.creds.refresh(httplib2.Http())
    self.creds.apply(req.headers)

# Create a gdata client
gd_client = gdata.contacts.client.ContactsClient(source='<var>YOUR_APPLICATION_NAME</var>')

# And tell it to use the same credentials
gd_client.auth_token = TokenFromOAuth2Creds(credentials)

rawDescription: Google Contacts API: Storing the auth code and exchanging for token


code:
data = ['1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35']
type(data) # It is a list
len(data)  # It has one item
type(data[0]) # That item is a string
data[0]
data[0].split(' ') # Like all strings, it has a `split` method

rawDescription: Is this a list or string in Python?

description: Is this a list or string in Python


code:
class C(object):
    def __init__(self, cond):
        if cond ==True:
           self.__class__ = A
        else:
           self.__class__ = B
        self.__class__.__init__(self)

rawDescription: Understanding Python Class Initialization


rawDescription: Wrong value from TAN(X) in Python and Excel


code:
df
df.rename_axis(lambda x: x.split()[0]+ " " +x.split()[2])
df.rename_axis({'garbled #### one': 'one', 'garbled #### two': 'two'})

rawDescription: apply changes to the column names of a dataframe

description: Apply changes to the column names of a dataframe


code:
class Hello:                   #line 1
         def printHello(self): #line 2
             print ("hello")   #line 3
                               #line 4
x = Hello()                    #line 5
x.printHello()                 #line 6

rawDescription: I can't get Classes to work right in any shape or form


code:
zeros = arr == 0.0
without_zeros = arr[~zeros]
np.allclose(without_zeros, 1, ...)

rawDescription: Check if all elements in numpy array match a number


code:
def walkThroughPath(self , sBasePath, blFolders = True, blFiles = True, blFollowSymlinks = True  ):
    aPaths = []
    for sRootDir, aSubFolders, aFiles in os.walk( sBasePath, blFollowSymlinks ):
        for sFolder in aSubFolders:
            if blFolders == True:
                try:
                    aPaths.index( sRootDir )
                    blPathExists = True
                except:
                    blPathExists = False
                    pass

                if blPathExists == False:
                    aPaths.append( sRootDir )
                    self.logDebug("Append: " + sRootDir )
                    self.logDebug("Current content of aPaths: \n" + pprint.pformat(aPaths) )

        for sFileName in aFiles:
            self.logDebug("Current root dir: " + sRootDir )
            if blFiles == True:
                try:
                    aPaths.index( sRootDir + "/" + sFileName )
                    blPathExists = True
                except:
                    blPathExists = False
                    pass

                if  blPathExists == False:
                    aPaths.append( sRootDir + "/" + sFileName )
            if blFolders == True:
                try:
                    aPaths.index( sRootDir )
                    blPathExists = True
                except:
                    blPathExists = False
                    pass

                if blPathExists == False:
                    aPaths.append( sRootDir )
                    self.logDebug("Append: " + sRootDir )
                    self.logDebug("Current content of aPaths: \n" + pprint.pformat(aPaths) )

    self.logDebug("Folders: " + str(blFolders) )
    self.logDebug("Files  : " + str(blFiles) )
    self.logDebug("Paths found in " + sBasePath + " : \n" + pprint.pformat(aPaths) )
    return aPaths

rawDescription: Python: why is my method using os.walk does not return all available pathes?


code:
foo = defaultdict(lambda: ([], []))
foo['key1'][0].append('value')

rawDescription: defaultdict tuple of lists

description: Defaultdict tuple of lists


code: from baz import bar

rawDescription: How to run a Python file not in directory from another Python file?

description: Run a Python file not in directory from another Python file


code:
def num(entry):
    number = Decimal(0.00) if not entry else Decimal(entry)
    return number

rawDescription: How do I set a invisible default value in entry widgets?

description: Set a invisible default value in entry widgets


code:
class foo(object):
    bar = "bar"
    @property
    def baz(self):
        return "baz"

rawDescription: Accessing function as attribute in a Python class


code:
foo
bar

rawDescription: Reading lines from text file in python (windows)


code:
import sys
sys.path.append('/home/francis/docs/folder1/')
sys.path.append('/home/francis/docs/folder2/')
import Prog1
import Prog2

rawDescription: Import program in other folders with Python


code:
def incoming_ping():
    pass

regexes = {"^PING: (.+)": incoming_ping,
           "more regex": "more meanings"}

rawDescription: The right way to do a Python IRC bot?

description: The right way to do a Python IRC bot


code:
DEC2FLOAT = psycopg2.extensions.new_type(
    psycopg2.extensions.DECIMAL.values,
    'DEC2FLOAT',
    lambda value, curs: float(value) if value is not None else None)
psycopg2.extensions.register_type(DEC2FLOAT)

rawDescription: psycopg2 returns numbers as string

description: Psycopg2 returns numbers as string


code:
def test_get_or_create_indexed_node_with_int_property(self):
    graph_db = neo4j.GraphDatabaseService()
    fred = graph_db.get_or_create_indexed_node(index="person", key="name", value="Fred", properties={"level" : 1})
    assert isinstance(fred, neo4j.Node)
    assert fred["level"] == 1
    graph_db.delete(fred)

rawDescription: Are all data types strings in Neo4j accessed by py2neo through the REST API?


code:
#!/usr/bin/env python3

from imaplib import IMAP4_SSL
from netrc import netrc
from email import message_from_bytes
from argparse import ArgumentParser

parser = ArgumentParser(description='Check email')
parser.add_argument('-n', '--count', dest='count', action='store',
                   default=1, type=int,
                   help='How many messages to show')

args = parser.parse_args()

conn = IMAP4_SSL('imap.gmail.com')
auth = netrc().hosts['imap.gmail.com']

conn.login(auth[0], auth[2])
conn.select()

typ, data = conn.search(None, 'ALL')
i = 0
for num in reversed(data[0].split()):
    i += 1
    typ, data = conn.fetch(num, '(BODY.PEEK[])')
    email = message_from_bytes(data[0][1])
    print("%i: %s" % (int(num), email.get('subject')))
    if i == args.count:
        break

conn.close()
conn.logout()

rawDescription: How do I fetch emails leaving them read/unread in Python?

description: Fetch emails leaving them read/unread in Python


code:
class Match(models.Model):
    tournament = models.ForeignKey(Tournament)
    players = models.ManyToManyField(Player, through='Participate')
    score = models.CharField(max_length=16)

class Participate(models.Model):
    player = models.ForeignKey(Player)
    match = models.ForeignKey(Match)
    visitor = models.BooleanField()

rawDescription: How to query multiple tables at a time?

description: Query multiple tables at a time


code:
r = re.compile(r'headers="Y\d+ i\d+">(\d+)<\\/td>')
r.findall(s)

rawDescription: python re, multiple matching groups

description: Python re, multiple matching groups


code:
soup = BeautifulSoup(html, "html.parser")
for i in soup.find_all('img'):
    print(i.get('src'))

[i.get('src') for i in soup.find_all('img')]

rawDescription: How to find all image uris in a text using python?

description: Find all image uris in a text using python


code:
matches = re.findall(r'"([^"]*)".=."([^"]*)"', line)
matches

rawDescription: Matching "..." = "..." in Python via Regex


rawDescription: numpy array memory allocation

description: Numpy array memory allocation


code:
with open("filename.pkl", "wb") as f:
    pickle.dump(dictname, f)
...
with open("filename.pkl", "rb") as f:
    dictname = pickle.load(f)

rawDescription: How to close the file after pickle.load() in python

description: Close the file after pickle.load() in python


code: output_file.write('{:-50} {:-6} {:-3} {:-25} {:-4}\n'.format(country, category, third, fourth, year))

rawDescription: how to format output file in python?

description: Format output file in python


code:
class Event(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self._aab = fancyFunction(a, b)
    def retrieve_state(self):
        return self.a, self.b, self._aab
    def restore_state(self, state):
        self.a, self.b, self._aab = state
    def copy_from(self, event):
        self.restore_state(event.retrieve_state())
    def copy(self):
        e = object.__new__(self.__class__)
        e.restore_state(self.retrieve_state())
        return e

class MouseEvent(Event):
    def __init__(self, a, b, c, d):
        Event.__init__(self, a, b)
        self.c = c
        self.d = d
    def retrieve_state(self):
        event_state = super(MouseEvent, self).retrieve_state()
        return event_state, self.c, self.d
    def restore_state(self, state):
        event_state, self.c, self.d = state
        super(MouseEvent, self).restore_state(event_state)

rawDescription: Create a copy of a subclass, recursively?


code:
import matplotlib.pyplot as plt
from numpy.random import rand

with open('DataSample2.txt', 'r') as f:
    next(f)
    xmin = ymin = 999999999
    xmax = ymax = -999999999
    for line in f:
        x, y, r = map(float, line.split())
        circle = plt.Circle((x, y), r, color=rand(3))
        fig = plt.gcf()
        fig.gca().add_artist(circle)
        xmin = min(x-r, xmin)
        xmax = max(x+r, xmax)
        ymin = min(y-r, ymin)
        ymax = max(y+r, ymax)
        #break # if you want draw only one circle, break here.
    plt.xlim(xmin, xmax)
    plt.ylim(ymin, ymax)
    plt.show()

rawDescription: Plot circles with matplotlib from text file


code:
px=37  # center of arrow
py=37  # center of arrow
while True:
    screen.fill((0,0,255))
    mouseX, mouseY=pygame.mouse.get_pos()  # unpack to avoid confustion
    angle_to_pointer = degrees(atan2(mouseY - py, mouseX - px))  # calculate off center of image
    for e in pygame.event.get():
        if e.type == QUIT:
            exit()
    spr=pygame.transform.rotate(arrow, -angle_to_pointer) # clockwise rotation
    # adjust draw top left based on center and rotated image size
    blit_pos = (px - spr.get_width()//2, py - spr.get_height//2)
    screen.blit(spr, blit_pos)
    pygame.display.flip()

rawDescription: Pygame: Problems with pointing image to mouse


rawDescription: Automatically process numbers in e (scientific) notation in python


code:
a
a == a.max(axis=1, keepdims=True)
(a == a.max(axis=1, keepdims=True)).astype(int)

rawDescription: How to convert 2d numpy array into binary indicator matrix for max value

description: Convert 2d numpy array into binary indicator matrix for max value


code:
class MainApp(App):

    link_buttons = 0

    def build(self):
        layout = GridLayout(cols=1, padding=1, spacing=10,
                    size_hint=(None, None), width=10)
        layout.bind(minimum_height=layout.setter('height'))
        sv = ScrollView(size_hint=(None, None), size=(200, 400),
             pos_hint={'center_x': .5, 'center_y': .5}, do_scroll_x=False)
        sv.add_widget(layout)
        self.layout = layout
        root = RootWidget()
        c = CustomLayout()
        s = Scrollbox()
        root.add_widget(c)
        root.add_widget(s)
        s.add_widget(sv)

        get_buttons = Button(
            text='Get links',
            size_hint=(1, 0),
            pos=(20, 20))
        s.add_widget(get_buttons)

        get_buttons.bind(on_press=self.buttons)
        return root

    def buttons(self, btn):

        layout = self.layout
        self.link_buttons += 1

        for buttn in range(20):
            btn = Button(text='test', size=(200, 50),
                     size_hint=(None, None))

            self.layout.add_widget(btn)

rawDescription: How can I change an attribute of a parents class instance

description: Change an attribute of a parents class instance


code:
parameters = {field_name: value for field_name, value in request.GET.items()
              if value and field_name in model._meta.get_all_field_names()}
model.objects.filter(**parameters)

rawDescription: Django building objects filter with GET params


rawDescription: What is my current desktop environment?

description: What is my current desktop environment


code:
import pexpect

child = pexpect.spawn('ssh myname@host.example.com')
child.expect('Password:')
child.sendline(mypassword)
child.interact()

rawDescription: ssh using python without RSA keys

description: Ssh using python without RSA keys


code:
# Red!
gc.set_rgb_fg_color(gtk.gdk.Color(0xff, 0x0, 0x0))

rawDescription: pygtk: Draw lines onto a gtk.gdk.Pixbuf

description: Pygtk: Draw lines onto a gtk.gdk.Pixbuf


code:
import time
import datetime
s = "01/12/2011"
time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())

rawDescription: Convert string date to timestamp in Python


code:
print("Hello %s hello %s" % (str1, str2))

print("Hello {} hello {}".format(str1, str2))

rawDescription: What is the Python 3 equivalent of %s in strings?


code:
"asdf".isalpha()
"as df".isalpha()
"as. df:".isalpha()

rawDescription: Assert string only contains letters

description: Assert string only contains letters


code: df['NewCol'] = df.apply(lambda x: segmentMatch(x['TimeCol'], x['ResponseCol']), axis=1)

rawDescription: python pandas- apply function with two arguments to columns

description: Python pandas- apply function with two arguments to columns


code:
def onEvent(msg):
   print("got event: {}".format(msg))

@app.register('com.example.triggersubscribe')
def triggerSubscribe():
   yield app.session.subscribe(onEvent, 'com.example.topic1')

rawDescription: Can autobahn.twisted.wamp.Application do pub/sub?


code:
import pandas as pd
import numpy as np

##### EXCEL LOAD
filepath= 'H:\\CCGT GE startup.xlsx'

df = pd.read_excel(filepath,sheet_name='Sheet1',header=0,skiprows=0,parse_cols='A:CO',index_col=0)
df = df.sort_index() # set increasing time index, source data is time decreasing

tg1 = pd.DataFrame(index=df.index.copy(),columns=['counter','flag','gas','p','raw_p','tv_p','lhv','fs'])
k = 0
for i,row in df.iterrows():
        if 'A' == str(row['FLAG STARTUP TG1']):
          tg1.ix[i,'flag']=row['FLAG STARTUP TG1']
          tg1.ix[i,'gas']=row['Portata gas naturale']
          tg1.ix[i,'counter']=k
          tg1.ix[i,'fs']=row['1FIRED START COUNT  -  N°']
          tg1.ix[i,'p']=row['POTENZA ATTIVA  MONTANTE 1 SU 400 KV  -  MW']
          tg1.ix[i,'raw_p']=row['POTENZA ATTIVA  MONTANTE 1 SU 15 KV  -  MW']
          tg1.ix[i,'tv_p']=row['POTENZA ATTIVA  MONTANTE TV  -  MW']
          tg1.ix[i,'lhv']=row['LHV -  MJ/Sm3']

        elif 'F' == str(row['FLAG STARTUP TG1']):
          tg1.ix[i,'flag']=row['FLAG STARTUP TG1']
          tg1.ix[i,'gas']=row['Portata gas naturale']
          tg1.ix[i,'counter']=k
          tg1.ix[i,'fs']=row['1FIRED START COUNT  -  N°']
          tg1.ix[i,'p']=row['POTENZA ATTIVA  MONTANTE 1 SU 400 KV  -  MW']
          tg1.ix[i,'raw_p']=row['POTENZA ATTIVA  MONTANTE 1 SU 15 KV  -  MW']
          tg1.ix[i,'tv_p']=row['POTENZA ATTIVA  MONTANTE TV  -  MW']
          tg1.ix[i,'lhv']=row['LHV -  MJ/Sm3']
          k+=1

tg1 = tg1.dropna(axis=0)
tg1 = tg1[tg1['gas'] != 0] #data where gas flow measurement is missing is dropped
tg1 = tg1.convert_objects(convert_numeric=True)

#timestamp count for each startup for duration calculation
counts = pd.DataFrame(tg1['counter'].value_counts(),columns=['duration'])
counts['start']=counts.index
counts = counts.set_index(np.arange(len(tg1['counter'].value_counts())))

tg1 = tg1.merge(counts,how='inner',left_on='counter',right_on='start')
 # filter out non pertinent startups (too long or too short)

tg1 = tg1[tg1['duration'].isin([6,7])]

#calculate thermal input per start (process)
table = tg1.groupby(['counter']).mean()
table['t_in']=table.apply((lambda row: row['gas']*row['duration']*0.25*row['lhv']/3600),axis=1)

rawDescription: Detection of variable length pattern in pandas dataframe column


code:
small_list_set = set(small_list)
for line in big_list:
    for item in line:
        if item in small_list_set:
            bucket.append(line)

rawDescription: Fastest algorithm for finding overlap between two very large lists?


code:
def my_callback(sender, **kwargs):
    if kwargs['created']:
        print('Instance is new')

rawDescription: Django signals for new entry only

description: Django signals for new entry only


rawDescription: Passing parameters from Python to a makefile


rawDescription: Python - return constructor arguments names without instantiating


code:
from collections import defaultdict

a = [1,2,3,4,5]
b = [2,2,5,5,3]
c = [5,2,8,1,1]
d = [1,1,1,1,1]
e = [5,1,2,3,4]
f = [1,1,5,5,5]

all_lists = [a,b,c,d,e,f]

dictionary = defaultdict(list)
for l in all_lists:
    dictionary[l[1]].append(l)

sorted_dict = {key:sorted(l, key=lambda x:x[2], reverse=True)[0] for key,l in dictionary.items()}

rawDescription: Compare elements in different lists in python


code: result = [s.strip() for s in string1.split('  ') if s.strip()]

rawDescription: using regular expression to split string with multiple spaces.

description: Using regular expression to split string with multiple spaces.


code:
max_word = max(words, key=len)
print('The longest word in the list is "{}" at {} characters.'.format(max_word, len(max_word)))

rawDescription: Print the word (from user input) with the max amount of characters python


code:
class MyClass(object):
    def __init__(self):
        self.__x = 3
    @property
    def x(self):
        return self.__x
    @x.setter
    def x(self, value):
        if value != 3:
            print('Nice try')
        else:
            self.__x = value

foo = MyClass()
foo._MyClass__x = 4
foo.x

rawDescription: Monkey patching Python Property setters (and getters?)


code:
from gevent import monkey; monkey.patch_all()

from time import sleep
from bottle import route, run

@route('/stream')
def stream():
    yield 'START'
    sleep(3)
    yield 'MIDDLE'
    sleep(5)
    yield 'END'

run(host='0.0.0.0', port=8080, server='gevent')

rawDescription: Print to HTML without "return"

description: Print to HTML without "return"


code:
article = Article.objects.all()[:3]  # first three articles

article = Article.objects.all()[3:6]  # second three articles

rawDescription: Django query to get three objects at a time


rawDescription: Using array to generate random text

description: Using array to generate random text


code:
import urllib.request as u
zipcode = 47401
url = 'http://watchdog.net/us/?zip={}'.format(zipcode)
con = u.urlopen(url)
page = con.read().decode('utf-8')
page[page.find("<title>") + 7:page.find("</title>") - 15]

rawDescription: Why won't Python display this text correctly? (UTF-8 Decoding Issue)


code:
from PIL import Image
image = Image.open("pepper.png")
bg = image.getpixel((0,0))
width, height = image.size
bg_count = next(n for n,c in image.getcolors(width*height) if c==bg)
img_count = width*height - bg_count
img_percent = img_count*100.0/width/height

rawDescription: How to detect an 'image area' percentage inside an image?

description: Detect an 'image area' percentage inside an image


rawDescription: Convert Python date to Unix timestamp

description: Convert Python date to Unix timestamp


code:
if filecmp.cmp(local, config_file):
    shutil.copyfile(remote, config_file)
else:
    shutil.copyfile(local, config_file)

rawDescription: Python style

description: Python style


rawDescription: Regular expression to match repeated occurrence of a pattern


code:
if __name__ == '__main__':
    # Be careful, this appends all job args, if you have lots it could be a problem
    sys.argv.extend(["--jobconf", "mapred.job.name=%s" % " ".join(sys.argv)])
    MRYourJobClass.run()

rawDescription: Is there a way to specify the title of a job from mrjob in the Hadoop Administration web interface?


code: df[df.Job == 'Lawyers'].sort('Salary', ascending=False).City

rawDescription: how to do multiple sort in csv using pandas and filter particular value?

description: Do multiple sort in csv using pandas and filter particular value


code:
while mazesol.removeDeadEnds(win, board) != 0:
    pass

rawDescription: I need to call a function until it returns 0 in python


code:
def autoAddScript(function):
    """
        Returns a decorator function that will automatically add it's result to the element's script container.
    """
    def autoAdd(self, *args, **kwargs):
        result = function(self, *args, **kwargs)
        if isinstance(result, ClientSide.Script):
            self(result)
            return result
        else:
            return ClientSide.Script(ClientSide.var(result))
    return autoAdd

rawDescription: What does the Python function keyword do?


code:
def replace(lst):
    global scount, mcount, lcount
    #rest of function

rawDescription: How do i count a number of occurrences in a string?

description: Count a number of occurrences in a string


rawDescription: Scrolling in QScrollArea pyqt

description: Scrolling in QScrollArea pyqt


rawDescription: store each word from a text file into a list

description: Store each word from a text file into a list


code:
def parallelize(methods, args):
    results = []
    if CPUS > 1:
        pool = Pool(CPUS)
        for method, arg in zip(methods, args):
            results.append(pool.apply_async(method, args=arg))
        pool.close()
        pool.join()
        out = map(lambda x: x.get(), results)
    else:
        for i in xrange(len(methods)):
            results.append(methods[i](*args[i]))
    return results

rawDescription: Parallelizing bulk of functions on multiple cpu environment


code:
import pydot
g = pydot.Dot(graph_type="digraph")
g.add_node(pydot.Node(name="A"))
g.add_node(pydot.Node(name="B"))
g.add_node(pydot.Node(name="C"))
g.add_node(pydot.Node(name="D"))
g.add_edge(pydot.Edge("A","B"))
g.add_edge(pydot.Edge("A","C"))
g.add_edge(pydot.Edge("C","D"))
g.get_nodes()
leafs = {n.get_name():True for n in g.get_nodes()}
for e in g.get_edge_list():
    leafs[e.get_source()] = False

leafs

rawDescription: get all leaf nodes of a directed graph in pydot

description: Get all leaf nodes of a directed graph in pydot


code:
import re
from collections import Counter
x='1234328732'
c=Counter(re.findall(r'\d',x))
[x for x in c if c[x]>1]
x='1231231234'
c=Counter(re.findall(r'\d',x))
[x for x in c if c[x]>1]

rawDescription: Python Regular Expression find repeating digits


code:
import networkx as nx
G=nx.Graph()
G.add_node("I like Python because : it's fast and readable")
G.nodes()

rawDescription: Having a colon in a networkx node

description: Having a colon in a networkx node


code:
import smtplib

username = "account@gmail.com"
password = "password"

vtext = "1112223333@vtext.com"
message = "this is the message to be sent"

msg = """From: %s
To: %s
Subject: text-message
%s""" % (username, vtext, message)

server = smtplib.SMTP('smtp.gmail.com',587)
server.starttls()
server.login(username,password)
server.sendmail(username, vtext, msg)
server.quit()

rawDescription: Sending Verizon SMS message via Python and smtplib


rawDescription: Python: Grabbing the width and height of image from url


code:
import operator
sorted(A, key=operator.itemgetter(2, 0, 1))

rawDescription: sort list of tuples by reordering tuples

description: Sort list of tuples by reordering tuples


rawDescription: Return X number of objects from Cursa.objects.filter


code:
class CustomHelpFormatter(argparse.HelpFormatter):
    def _iter_indented_subactions(self, action):
        try:
            get_subactions = action._get_subactions
        except AttributeError:
            pass
        else:
            self._indent()
            if isinstance(action, argparse._SubParsersAction):
                for subaction in sorted(get_subactions(), key=lambda x: x.dest):
                    yield subaction
            else:
                for subaction in get_subactions():
                    yield subaction
            self._dedent()

rawDescription: Argparse subcommand order in help output


code:
from lxml import html

doc = html.fromstring(data)
for br in doc.findall('.//br'):
    if br.tail is None: # no text immediately after
 tag
        for dup in br.itersiblings():
            if dup.tag != 'br': # don't merge if there is another tag inbetween
                break
            dup.drop_tag()
            if dup.tail is not None: # don't merge if there is a text inbetween
               break

print(html.tostring(doc))
# ->

foo
bar.

foo
bar

rawDescription: Merge multiple <br /> tags to a single one with python lxml


code:
def build(self):

    parent = BoxLayout() #the only line changed
    self.painter = CanvasWidget()
    parent.add_widget(self.painter)
    return parent

rawDescription: How do you get Kivy to refresh the size of a widget when the window resizes?

description: Get Kivy to refresh the size of a widget when the window resizes


code: pd.DataFrame(series_list,index = ['i', 'ii'])

rawDescription: Pandas dataframe from series of series

description: Pandas dataframe from series of series


rawDescription: Compare tuple value to integer in Python


rawDescription: Django select database objects based on previous query


code:
FO1=open("output1.txt","wt")
FO2=open("output2.txt","wt")
one=file1.readlines()
two=file2.readlines()
for line1 in one:
    if line1 in two:
        FO1.write(line1)
        two.remove(line1)
    else:
        FO2.write(line1)
for line2 in two:
   FO2.write(line2)

rawDescription: How to read two files and write a file with the content which matches two files and writes anothe file which doesnot match?

description: Read two files and write a file with the content which matches two files and writes anothe file which doesnot match


code:
def intersection(first, *others):
    return set(first).intersection(*others)

rawDescription: taking intersection of N-many lists in python

description: Taking intersection of N-many lists in python


code:
def collatz(n, seq=None):
    seq = [] if seq is None else seq
    seq.append(n)
    if n == 1:
        return seq
    if n%2 == 0:
        return collatz(n/2, seq)
    else:
        return collatz((3*n)+1, seq)

rawDescription: Recursive function return value keeps the results from previous runs


rawDescription: What's the Pythonian way to append to a bytearray a list?


rawDescription: Python, Hex and common file signatures

description: Python, Hex and common file signatures


rawDescription: Python: how to simultaneously add two lists to a list?


code:
def do_debug(self, arg):
    interactive_startup = ("import os;"
        "os.path.exists(os.environ.get('PYTHONSTARTUP', '')) "
        "and execfile(os.environ['PYTHONSTARTUP']); del os;"
        'import Zope2; app=Zope2.app()')
    cmdline = self.get_startup_cmd(self.options.python,
                                   interactive_startup,
                                   pyflags = '-i', )

rawDescription: How do I get Plone to read my pythonrc?

description: Get Plone to read my pythonrc


code: ast.literal_eval(raw_input('Foo: '))

rawDescription: Is it possible to format text input so Python recognises it as a list?


rawDescription: python zipfile directory gets copied too

description: Python zipfile directory gets copied too


code:
def setdefaultattr(obj, name, value):
    if not hasattr(obj, name):
        setattr(obj, name, value)
    return getattr(obj, name)

rawDescription: In python, is there a setdefault() equivalent for getting object attributes?


code:
#Django
from django.contrib.auth.models import User
from django.conf.urls import url

#Tasty
from tastypie.resources import ModelResource

class UserResource(ModelResource):
    class Meta:
        queryset = User.objects.all()
        resource_name = 'users'

        #Disallow list operations
        list_allowed_methods = []
        detail_allowed_methods = ['get', 'put', 'patch']

        #Exclude some fields
        excludes = ('first_name', 'is_active', 'is_staff', 'is_superuser', 'last_name', 'password',)

    #Apply filter for the requesting user
    def apply_authorization_limits(self, request, object_list):
        return object_list.filter(pk=request.user.pk)

    #Override urls such that GET:users/ is actually the user detail endpoint
    def override_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
        ]

rawDescription: Django Tastypie - Resource with object details only


code:
import bisect
a_values = [0, 0.2, 0.5, 1.0, 2.0]
b_values = [30, 25, 20, 15, 10]
b = b_values[bisect.bisect_left(a_values, a)-1]

rawDescription: Elegant way of assigning value to variable according to the value of another variable


code:
class MyUpdateView(UpdateView):
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object = form.save() # oops, we redefined self.object, user won't be saved
        return HttpResponseRedirect(self.get_success_url())

rawDescription: Is my recommendation of using super() incorrect?


code:
from other_module import Foo, FooTypeA, FooTypeB

bases = [Foo, FooTypeA, FooTypeB]

class MyMixin(object):
    pass

def factory(bases, mixins, name='MyClass'):
    return type(name, bases + mixins, {})

new_classes = [factory((c,), (MyMixin,)) for c in bases]

rawDescription: What's the pythonic way to add behavior to objects returned by an external module?


code:
from queue import Queue
from threading import Thread

# A thread that produces data
def producer(out_q):
    while True:
        # Produce some data
        ...
        out_q.put(data)

# A thread that consumes data
def consumer(in_q):
    while True:
        # Get some data
        data = in_q.get()
        # Process the data
        ...

# Create the shared queue and launch both threads
q = Queue()
t1 = Thread(target=consumer, args=(q,))
t2 = Thread(target=producer, args=(q,))
t1.start()
t2.start()

rawDescription: QThreads Python - Communicating

description: QThreads Python - Communicating


code:
lst = []
lst.extend([1, 2, 3])
lst
lst.append([1, 2, 3])
lst

rawDescription: Combining elements in list: seems like python treats the same item in two different ways and I don't know why


code:
values = range(10)
random.shuffle(values)

def get_value():
    return values.pop()

rawDescription: In python, how to generate a random integer in a range, excluding some numbers in a list?


code:
class RoomList(object):
    def __init__(self):
        super(RoomList, self).__init__()
        self.rooms = []
        self.subvisit_clinicians = []

    def add_room(self, room):
        self.rooms.append(room)

    def add_subvisit_clinician(self, subvisit_clinician):
        self.subvisit_clinicians.append(subvisit_clinician)

class RoomListSerializer(serializers.Serializer):
    rooms = RoomSerializer(many=True)
    subvisit_clinicians = SubvisitClinicianSerializer(many=True)

rawDescription: Django REST Framework - Custom JSON

description: Django REST Framework - Custom JSON


code:
def Login(self):
    global user_barcode
    self.login_attempts = 1
    self.lineEditScanBarcode.returnPressed.connect(LoginAttempt)

def LoginAttempt(self):
    user_barcode = self.lineEditScanBarcode.text()
    # all the stuff that validates the barcode
    if valid:
        self.LoggedIn()
        return
    print("Unauthorised access request.")
    self.login_attempts += 1
    self.lineEditScanBarcode.clear()
    self.LCDLoginAttempt.display(self.login_attempts-1)
    if self.login_attempts == 4:
        print("Sorry, you are not an authorised user of this system. Please contact the system administrator for further clarification, or if you feel this is an error.")
        # probably want to do something here... disconnect the signal? quit?

rawDescription: PySide signals/slots with iterative loops


code:
from tvtk.api import tvtk
fig = mlab.gcf()
fig.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain()

rawDescription: Constrain Mayavi mouse drag to rotating Earth around its axis


code:
import subprocess

def textToWav(text,file_name):
   subprocess.call(["espeak", "-w"+file_name+".wav", text])

textToWav('hello world','hello')

rawDescription: Recording synthesized text-to-speech to a file in Python


code: dfz.loc[:, 'A':'D'].replace(1, pd.Series(dfz.columns, dfz.columns))

rawDescription: How to replace a value in a pandas dataframe with column name based on a condition?

description: Replace a value in a pandas dataframe with column name based on a condition


rawDescription: Removing all non-numeric characters from string in Python


code: page, resources = ghost.evaluate("agree()", expect_loading=True)

rawDescription: Use ghost.py to click a link linking to a javascript


code:
class Spider(BaseSpider):

    name = "domain_spider"

    def start_requests(self):

        last_domain_id = 0
        chunk_size = 10
        cursor = settings.db.cursor()

        while True:
            cursor.execute("""
                    SELECT domain_id, domain_url
                    FROM domains
                    WHERE domain_id > %s AND scraping_started IS NULL
                    LIMIT %s
                """, (last_domain_id, chunk_size))
            self.log('Requesting %s domains after %s' % (chunk_size, last_domain_id))
            rows = cursor.fetchall()
            if not rows:
                self.log('No more domains to scrape.')
                break

            for domain_id, domain_url in rows:
                last_domain_id = domain_id
                request = self.make_requests_from_url(domain_url)
                item = items.Item()
                item['start_url'] = domain_url
                item['domain_id'] = domain_id
                item['domain'] = urlparse.urlparse(domain_url).hostname
                request.meta['item'] = item

                cursor.execute("""
                        UPDATE domains
                        SET scraping_started = %s
                        WHERE domain_id = %s
                    """, (datetime.now(), domain_id))

                yield request

    ...

rawDescription: scrapy transport start_url to subsequent requests

description: Scrapy transport start_url to subsequent requests


code:
while True:
    num_sticks = 10
    while num_sticks!=0:
        ...

rawDescription: How to troubleshoot an infinite loop

description: Troubleshoot an infinite loop


code:
# coding=utf8
import sublime_plugin, sublime, re, html

def clipboard():
    return sublime.get_clipboard()

def copy(data):
    sublime.set_clipboard(data)

# to transfer data to sublime text
def clean_paste(data):
    # clean word
    data = str(data)
    data = data.replace(u'”', '"').replace(u'“', '"').replace(u'’', "'")
    data = data.replace('________________________________________', '\n')
    # clean htmlentities
    data = re.sub('&([^;]+);', lambda m: unichr(html.entities.name2codepoint[m.group(1)]), data)
    return data;

# to transfer data from sublime text
def clean_copy(data):
    # clean html
    data = str(data)
    data = re.sub(r'<br ?/?>', '\n', data, re.I);
    data = re.sub(r'<[^>]*>', '', data);
    # clean htmlentities
    data = re.sub('&([^;]+);', lambda m: unichr(html.entities.name2codepoint[m.group(1)]), data)
    return data;

rawDescription: Sublime Text 3 - Clean Paste

description: Sublime Text 3 - Clean Paste


rawDescription: Integer to Hexadecimal Conversion in Python


rawDescription: pre allocation of memory in Ruby and Python for hashes, akin to Perl's keys %hash = num

description: Pre allocation of memory in Ruby and Python for hashes, akin to Perl's keys %hash = num


code:
from random import shuffle
from PySide import QtCore, QtGui

class ClickableLabel(QtGui.QLabel):
    clicked = QtCore.Signal(str)

    def __init__(self, width, height, color):
        super(ClickableLabel, self).__init__()
        pixmap = QtGui.QPixmap(width, height)
        pixmap.fill(QtGui.QColor(color))
        self.setPixmap(pixmap)
        self.setObjectName(color)

    def mousePressEvent(self, event):
        self.clicked.emit(self.objectName())

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QGridLayout(self)
        colors = 'red green blue orange purple yellow'.split()
        for row in range(len(colors)):
            shuffle(colors)
            for column, color in enumerate(colors):
                label = ClickableLabel(25, 25, color)
                label.clicked.connect(self.handleLabelClicked)
                layout.addWidget(label, row, column)

    def handleLabelClicked(self, name):
        print('"%s" clicked' % name)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 200, 200)
    window.show()
    sys.exit(app.exec_())

rawDescription: Is possible to put an image instead of a button, and make it clickable?


code:
obj.headers['Access-Control-Allow-Origin'] = '*'
obj.sync_metadata()

rawDescription: Setting Access-Control-Allow-Origin (CORS) in the Rackspace Cloud Files Python API


rawDescription: Catch print output in python

description: Catch print output in python


code:
import csv
import json

csvfile = open('spreadsheet.csv', 'r')
jsonfile = open('fileTo.json', 'w')

fieldnames = ("Id","name","TypeId","Type", "listHere")
fieldfixers = {
    'Id': int,
    'Type': int,
}
reader = csv.DictReader( csvfile, fieldnames)

for row in reader:
    for key,value in row.iteritems():
        ffunc = fieldfixers.get(key)
        if ffunc:
            row[key] = ffunc(value)
    json.dump(row, jsonfile, sort_keys=True, indent=4, separators=(',', ':'))
    jsonfile.write(',')
    jsonfile.write('\n')

rawDescription: formatting .csv to json in python for individual key:value pairs

description: Formatting .csv to json in python for individual key:value pairs


code:
node = self.head
while node.next and node.next.priority > priority:
    node = node.next

if node.next is None:
    node.next = qNode(value=value, next=None, priority=priority)
    self.foot = node.next
else:
    new_node = qNode(value=value, next=node.next, priority=priority)
    node.next = new_node

rawDescription: How can I implement Priority Queue without using any built-in functions?

description: Implement Priority Queue without using any built-in functions


code:
students = Students.objects.all()
students.model
students.model.__name__
students.model.__module__
students.model._meta.app_label

rawDescription: get class name for empty queryset in django

description: Get class name for empty queryset in django


code:
a
a[np.tril_indices(3, k=-1)] = 0
a

rawDescription: check on indices of matrix/array and then check for some condition

description: Check on indices of matrix/array and then check for some condition


code:
from scipy import stats
import numpy as np
np.random.seed(2015)

x = [ stats.t.rvs(9) for i in range(250)]
stats.t.fit(x)

rawDescription: Is there a way to automatically estimate the best degree of freedoms for a t-distribution using Scipy?


code:
import random
import json

line = open('projects.txt').read().replace("'", '"')  # Format JSON
projNames = json.loads(line) # Load list
print(random.choice(projNames))

rawDescription: Python load list from file and print random selection


rawDescription: In python, how do I preserve decimal places in numbers?


code:
@staticmethod
def parseDERPublicKey(bytes):
    a = ASN1Parser(bytes)
    b = a.getChild(1)
    padding = b.value[1]
    # TODO: I am assuming padding is 0, this is wrong.
    #       Skip the padding as well.
    c = b.value[1:] # get the mod/exp portion after the padding
    d = ASN1Parser(c)

    modulus = bytesToNumber(d.getChild(0).value)
    exponent = bytesToNumber(d.getChild(1).value)

rawDescription: How to use Python gdata.tlslite.utils.ASN1Parser to get exponent and modulus?

description: Use Python gdata.tlslite.utils.ASN1Parser to get exponent and modulus


code:
from twisted.web.client import HTTPClientFactory
HTTPClientFactory.noisy = False

rawDescription: How to disable noisy debug?

description: Disable noisy debug


code:
from werkzeug.exceptions import NotAcceptable

class CustomApi(Api):
    FORMAT_MIMETYPE_MAP = {
        "csv": "text/csv",
        "json": "application/json"
        # Add other mimetypes as desired here
    }

    def mediatypes(self):
        """Allow all resources to have their representation
        overriden by the `format` URL argument"""

        preferred_response_type = []
        format = request.args.get("format")
        if format:
            mimetype = FORMAT_MIMETYPE_MAP.get(format)
            preferred_response_type.append(mimetype)
            if not mimetype:
                raise NotAcceptable()
        return preferred_response_type + super(CustomApi, self).mediatypes()

rawDescription: Flask Restful: change representation based on URL parameter


code:
import os, random
random.choice(os.listdir("C:\\")) #change dir name to whatever

rawDescription: Best way to choose a random file from a directory

description: Choose a random file from a directory


code:
import tkinter

frame = tkinter.Tk()

frame.config(height=370, width=670, bg="#C2C2D6")
entry = tkinter.Entry(frame, exportselection=0)
entry.pack(padx=100, pady=100, expand=1, fill='x')

frame.mainloop()

rawDescription: How to center this Entry widget?

description: Center this Entry widget


code:
def skip(seconds):
    samples = int(seconds * RATE)
    count = 0
    while count < samples:
        stream.read(chunk)
        count += chunk
        time.sleep(0.01)

rawDescription: PyAudio behavior during time.sleep()

description: PyAudio behavior during time.sleep()


code:
def direction_function(direction=None):
    direction = direction or raw_input()
    # Do something with the input

rawDescription: python bypassing raw_input by passing in other raw_input

description: Python bypassing raw_input by passing in other raw_input


code:
from subprocess import *
from time import sleep

for i in range(2, 4):
    x = Popen('python' + str(i) + ' --version', shell=True, stdout=PIPE, stdin=PIPE, stderr=STDOUT)
    while x.poll() == None:
        sleep(0.025)
    print('Exit code of ' + str(i) + ' is:',x.poll())
    x.stdout.close()
    x.stdin.close()

rawDescription: How to list all Python versions installed in the system?

description: List all Python versions installed in the system


code:
class A():
    def __init__(self):
        self.var1 = 12
        self.var2 = C()

    def start(self):
        self.var1=11
        B(self)             # pass this instance into the initialisation of B

class B():
    def __init__(self, a):
        self.a = a          # save reference to the A() instance

    def doSomething(self):
        varXX = self.a.var2

rawDescription: getting variable

description: Getting variable


code:
def deriv(Y,t): # return derivatives of the array Y
    a = -2.0
    b = -0.1
    return array([ Y[1], a*Y[0]+b*Y[1] ])

rawDescription: Solving system of coupled differential equations using scipy odeint


code:
numbers = input("How many numbers you want to calculate? ")
grade_list = []

def evaluate():
    for i in range (numbers):
        grades = float(input("Please enter a number between 1-1000: "))
        while grades < 0 or grades > 1000:
            print ("The number " + str(grades) + " is out of range")
            grades = float(input("Please enter a number between 1-1000: "))
        grade_list.append(grades)
    average = sum(grade_list)/numbers
    if (average >= 500):
        print("Good,", str(average))
    if (average <= 500):
        print("Bad,", str(average))

try:
    numbers = int(numbers)
    evaluate()
except:
    while True:
        try:
            numbers = int(numbers)
            evaluate()
            break
        except:
            print("You should not enter " + str(numbers) + " because it is not an integer.")
            numbers = input("How many numbers you want to calculate? ")

rawDescription: How to write a python program to calculate average number?

description: Write a python program to calculate average number


code:
from PyQt4.QtGui import QApplication, QWorkspace, QTableView
from PyQt4.QtCore import Qt

def main():
    app = QApplication([])
    workspace = QWorkspace()
    view = QTableView()
    workspace.addWindow(view, Qt.FramelessWindowHint)
    workspace.show()
    app.exec_()

if __name__ == '__main__':
    main()

rawDescription: In PyQT4, how can I hide the window title of a child widget?


code:
items = [
    (self.PNew, self.New, 0),
    (self.POpen, self.Open, 0),
    (self.PSave, self.Save, 0),
    (self.POrigin, self.SetOrigin, 20),
    (self.PFiducial, self.SetFiducial, 0),
    (self.PLine, self.AddLine, 20),
    (self.PPoint, self.AddPoint, 0),
    (self.PMove, self.AddMove, 0),
    (self.PCircle, self.AddCircle, 0),
    (self.PCall, self.AddCall, 0)
]
for pic, fn, xoff in items:
    Button(ButtonRow, image=pic, command=fn).pack(side=LEFT, padx=(xoff, 0))

rawDescription: Python line is too long, how can i make it more readable?


code:
layout = QVBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)  # <---
layout.addWidget(view)

rawDescription: Why does a WebKit in fullscreen leaves a border?


code: random.choice([i for i, e in enumerate(board) if e == " "])

rawDescription: Python Random Number Generator for Tic-Tac-Toe


code:
import wx
from numpy import arange, sin, pi
import matplotlib
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FCW
from matplotlib.figure import Figure

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY,
                          "Pyramid App",size=(800,600),
                           pos=((wx.DisplaySize()[0]-800)/2,(wx.DisplaySize()[1]-600)/2),
                           style=wx.SYSTEM_MENU | wx.CAPTION | wx.MINIMIZE_BOX | wx.CLOSE_BOX)

        self.PageThree = pageThree(self)

class pageThree(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent,size=(800,525))
        self.myparent=parent
        self.pageThree=wx.Panel(self, size=(500,525))
        self.drawPyFigure()
        self.draw()

    def drawPyFigure(self):
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FCW(self, -1, self.figure)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.pageThree, 0)
        sizer.Add(self.canvas, 1, wx.EXPAND)
        self.SetSizer(sizer)
        self.Fit()

    def draw(self):
        t = arange(0.0, 3.0, 0.01)
        s = sin(2 * pi * t)
        self.axes.plot(t, s)

if __name__ == "__main__":
    app = wx.App()
    MainFrame().Show()
    app.MainLoop()

rawDescription: embedding matplotlib figure and change its size

description: Embedding matplotlib figure and change its size


code:
# normal_call
result = "abc".startswith("a")

# creating a bound method
method = "abc".startswith
result = method("a")

# using the raw function
function = str.startswith
string = "abc"
result = function(string, "a")

rawDescription: Pass object along with object method to function


code:
drinks = ['cola_with_ice', 'icetea', 'lemonade', 'coffee']
any('cola' in drink for drink in drinks)
any('apple' in drink for drink in drinks)

rawDescription: Match string anywhere in the string without using regular exp module


code: f = lambda x: x.val if isinstance(x.val, int) else (int(x.val) if isinstance(x.val, basestring) and x.isdigit() else None)

rawDescription: Filter values in a Python object array generically with a lambda function as a string


code:
def repl_func(matched_obj):
    my_dict = {'NAME':'rep1', '\n':'rep2'}
    try:
        match = matched_obj.group(0)
    except AttributeError:
        matched = ''
        # Or raise an exception
    else:
        return my_dict.get(match, '')

re.sub(regex, repl_func, content)

rawDescription: Function to dictate the replacements in re.sub method (Python)


code:
import glob
files = glob.glob('*.txt')
my_classes = ['xxx', 'yyy', 'zzz']

for cls in my_classes:
    files = glob.glob('*{}*.txt'.format(cls))
    if files:
        with open(cls, 'w') as fout:
            for file_name in files:
                with open(file_name, 'r') as fin:
                    fout.write(fin.read())

rawDescription: Combining multiple text files belonging to different groups using Python


code:
regex = re.compile(r'IN\s+NS\s')
for line in output:
    if regex.search(line):
        print(line)

rawDescription: python regex doesn't match dig output

description: Python regex doesn't match dig output


code:
import os
if os.path.exists("__LOCK__"):
    raise RuntimeError("Already running.") # or whatever
try:
    open("__LOCK__", "w").write("Put some info here if you want.")
finally:
    if os.path.exists("__LOCK__"):
        os.unlink("__LOCK__")

rawDescription: RW-locking a Windows file in Python, so that at most one test instance runs per night


code:
if dictionary is None:
    self.dict = {}
else:
    self.dict = dictionary

rawDescription: Python only has one instance of object's dictonary when run concurrently


code: subprocess.Popen("cmd.exe /c callee.py arg1 arg2")

rawDescription: Executing a cmd.exe command from a python script


code:
import cProfile

def print_multiples0(n, high):         #This is the e-book version
    for i in range(1, high+1):
        print(n * i, end='   ')
    print()

def print_mult_table0(high):
    for i in range(1, high+1):
        print_multiples0(i, i+1)       #They changed high+1 to i+1 to halve output

def print_multiples1(n):        #n is the number of columns that will be made
    '''Prints a line of multiples of factor 'n'.'''
    for x in range(1, n+1):     #prints n  2n  3n ... until x = n+1
        print(n * x, end='\t')  #(since x starts counting at 0,
    print()                     #n*n will be the final entry)

def print_mult_table1(n):            #n is the final factor
    '''Makes a table from a factor 'n' via print_multiples().
    '''
    for i in range(1, n+1):          #call function to print rows with i
        print_multiples1(i)          #as the multiplier.

def test( ) :
     print_mult_table0( 10)
     print_mult_table1( 10)

cProfile.run( 'test()')

rawDescription: Python multiplication table syntax differences


code:
product = Product.objects.get(id=12)
try:
    mattress = product.mattress
    is_mattress = True
except Mattress.DoesNotExist:
    is_mattress = False

rawDescription: How to create django database model that "knows" what kind of category it is?

description: Create django database model that "knows" what kind of category it is


code:
try:
    from tkinter import *
    from tkinter import ttk
except ImportError:
    # Python 2, probably
    from Tkinter import *
    import ttk

class stuff (object):
    def __init__(self, master):
        self._master = master
        master.title("Grid Master")
        master.frame_1 = ttk.Frame(master)
        master.frame_1.pack()
        master.configure(background = "#FFFFFF")

        self.button = ttk.Button(master, text = 'Press')
        self.button.bind("<Button-1>", self.button_pressed)
        self.button.bind("<ButtonRelease-1>", self.button_released)
        self.button.pack()

        self.hello_world_frequency = 1    # milliseconds

    def hello_world(self):
        print ("Hello world")
        self._job = self._master.after(self.hello_world_frequency, self.hello_world)

    def button_pressed(self, event):
        print ("Button down")
        self.hello_world()

    def button_released(self, event):
        print ("Button released")
        self._master.after_cancel(self._job)

def main():
    root = Tk()
    loop = stuff(root)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Execute Button Method

description: Execute Button Method


code:
def some_magic():
    import a
    for i in dir(a):
        item = getattr(a,i)
        if callable(item):
            item()

if __name__ == '__main__':
    some_magic()

rawDescription: Is there a way in python to execute all functions in a file without explicitly calling them?


code:
for i in range(10):
    x = np.append(x, i)
    y = np.append(y, i**2)
    plt.gca().cla()
    plt.plot(x,y,label='test')
    plt.legend()
    display.clear_output(wait=True)
    display.display(plt.gcf())
    time.sleep(0.5)

rawDescription: Dynamically update plot in iPython notebook


code:
getattr(x, 'foobar')
x.foobar

rawDescription: Python: access structure field through its name in a string


code:
import pygame
pygame.init()
screen = pygame.display.set_mode((490, 160))
font = pygame.font.SysFont('Arial', 150)
pattern = pygame.image.load('t.bmp').convert()
text = font.render('FooBar', True, (255, 255, 255), (0, 0, 0))

pattern.blit(text, (0, 0), special_flags = pygame.BLEND_MULT)

screen.blit(pattern, (0, 0))
pygame.display.flip();
while True:
    if pygame.event.get(pygame.QUIT):
        break

rawDescription: Fill pygame font with custom pattern

description: Fill pygame font with custom pattern


rawDescription: How to specify the number of X ticks and their labels in Matplotlib?

description: Specify the number of X ticks and their labels in Matplotlib


code:
def has_achieved(self, obj):

    return obj.has_achieved(self.context['request'].user)

rawDescription: Django Rest Framework SerializerMethodField Pass Extra Argument


code:
import numpy as np

class NumpyFloatHandler(jsonpickle.handlers.BaseHandler):
    """
    Automatic conversion of numpy float  to python floats
    Required for jsonpickle to work correctly
    """
    def flatten(self, obj, data):
        """
        Converts and rounds a Numpy.float* to Python float
        """
        return round(obj,6)

jsonpickle.handlers.registry.register(np.float, NumpyFloatHandler)
jsonpickle.handlers.registry.register(np.float32, NumpyFloatHandler)
jsonpickle.handlers.registry.register(np.float64, NumpyFloatHandler)

rawDescription: Jsonpickle Encoding Floats with Many Decimals as Null


code:
def get_closest_quarter(target):
    # candidate list, nicely enough none of these
    # are in February, so the month lengths are fixed
    candidates = [
        datetime.date(target.year - 1, 12, 31),
        datetime.date(target.year, 3, 31),
        datetime.date(target.year, 6, 30),
        datetime.date(target.year, 9, 30),
        datetime.date(target.year, 12, 31),
    ]
    # take the minimum according to the absolute distance to
    # the target date.
    return min(candidates, key=lambda d: abs(target - d))

rawDescription: Find the closest quarter-end for a date?

description: Find the closest quarter-end for a date


code:
__tablename__ = 'courses'

id = Column(INTEGER, primary_key=True)
course = Column(String, unique=True, nullable=False)
start_date = Column(Date, nullable=True)
end_date = Column(Date, nullable=True)
hours_per_day = Column(Integer, nullable=True)

def __init__(self, course, start_date=None, end_date=None, hours_per_day=None):
    self.course = course
    if start_date:
        self.start_date = start_date
    if end_date:
        self.end_date = end_date
    if hours_per_day:
        self.hours_per_day = hours_per_day

def __repr__(self):
    return "Course(%r)" % (self.course)

rawDescription: Storing to database in sqlalchemy with no values


code:
from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://www.example.com')
element = browser.find_element_by_tag_name('h1')
assert element.text == 'Example Domains'
browser.quit()

rawDescription: Assert/VerifyElementPresent with Python and WebDriver?


code:
list1 = [('horse',2),('doll',34)]
list2 = [('horse',1),('monster',23),('salamander',12),('doll',17)]
d = dict(list1)  # => {'horse': 2, 'doll': 34}
v2 = [value for name, value in list2]
v1 = [d.get(name, 0) for name, value in list2]
# d.get(name, 0) will return `0` for non-existing key (name).
v1
v2
sum(x * y for x, y in zip(v1, v2))

rawDescription: Python, DotProduct between two vectors issue


code:
def make_obstacles(self, num, length, dx):
    for i in range(num):
        while True:
            x = random.randrange(700, length)
            y = random.randrange(10, games.screen.height - 10)
            size = random.choice([Obstacle.obstacle_1,Obstacle.obstacle_3])
            if is_empty(x, y, size):
                break
        new_obstacle = Obstacle(game = self, x = x, y = y, size = size, dx = dx)
        games.screen.add(new_obstacle)

rawDescription: Trying to create sprites with no overlap


code:
A = scipy.delete(A, 1, 0)  # delete second row of A
B = scipy.delete(B, 2, 0)  # delete third row of B
C = scipy.delete(C, 1, 1)  # delete second column of C

rawDescription: How to delete columns in numpy.array

description: Delete columns in numpy.array


code:
# for example
a = np.random.random_integers(0, 500, size=(200,1000))
N = 200

result = np.zeros((200,1000))
ia = np.arange(result.size)
tw = float(np.sum(a.ravel()))
result.ravel()[np.random.choice(ia, p=a.ravel()/tw,
                                size=N, replace=False)]=1

rawDescription: How to randomly sample a matrix in python?

description: Randomly sample a matrix in python


code:
import yaml

with open('path/to/config.yml', 'rb') as f:
    conf = yaml.loads(f.read())    # load the config file

def process(**params):    # pass in variable numbers of
    for key, value in params.items():
        print('%s: %s' % (key, value))

process(**conf)    # pass in your keyword args

rawDescription: Input YAML config values into keyword arguments for Python


code:
from pylab import *
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.cbook import get_sample_data
from matplotlib._png import read_png
fn = get_sample_data("lena.png", asfileobj=False)
img = read_png(fn)
x, y = ogrid[0:img.shape[0], 0:img.shape[1]]
ax = gca(projection='3d')
ax.plot_surface(x, y, 10, rstride=5, cstride=5, facecolors=img)
show()

rawDescription: Image overlay in 3d plot using python

description: Image overlay in 3d plot using python


code:
from tagging.fields import TagField

class BlogPost(models.Model):
    # ...
    tags = TagField()

rawDescription: Added tagging to existing model, now how does its admin work?


code:
pq = [ ]
heappush(pq, (10, task1))
heappush(pq, (5, task2))
heappush(pq, (15, task3))
priority, task = heappop(pq)

rawDescription: In Python, heapq.heapify doesn't take cmp or key functions as arguments like sorted does


code:
import sys
sys.stdout.write("hi")

rawDescription: Forward-compatible print statement in python 2.5


code: df['obs_num'] = df.groupby(["Index", "Date"]).cumcount() + 1

rawDescription: Pandas cumsum using large amounts of memory


code:
def startWork(self):
    worker = Worker()
    worker.moveToThread(self.thread)
    worker.finished.connect(self.thread.quit)
    self.thread.started.connect(worker.process)
    def cleanup():
        self.thread.started.disconnect(worker.process)
        self.thread.finished.disconnect(cleanup)
        worker.deleteLater()
    self.thread.finished.connect(cleanup)
    self.thread.start()

rawDescription: Do QThreads control destruction of stack-created QObjects pushed to it?


code:
file = open( "file","r")
for line in file.readlines():
    if "NSF" in line:
        values= line.split(":")
    elif "Fld" in line:
        values1 = line.split(":")

rawDescription: extracting part of text from file in python

description: Extracting part of text from file in python


code:
from twisted.internet import reactor, task
def fun():
    print("I don't know why CPU usage increases in the beginning")
lc = task.LoopingCall(fun)
raw_input("Hit Enter To Start The Reactor:")
lc.start(10)
reactor.run()

rawDescription: CPU usage at the time of starting twisted reactor


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

# Fake data
x = np.arange(10)
y = 10*np.random.rand(10) + 95
names = string.lowercase[:10] # first 10 lowercase letters

# Plot data
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x,y)

# Annonate points with y values greater than 100
for xi, yi, iname in zip(x,y,names): # Loop over x and y values
    if yi > 100: # Check if y is greater than 100
        ax.annotate(iname, (xi, yi),size = 30) # Add an annoatation.

plt.show()

rawDescription: If function for annotating from pandas

description: If function for annotating from pandas


code:
import logging
import socket

# The next line allows 'socket' in the logging package's namespace to pick up
# the stdlib socket module
logging.socket = socket
...
# when the config file is processed, it should work as expected
logging.config.fileConfig(...)
# remove the mapping from the logging package, as not needed any more
# (optional)
del logging.socket

rawDescription: How to refer to a standard library in a logging configuration file?

description: Refer to a standard library in a logging configuration file


code:
spacer = self.itemVBox.AddSpacer((0, 5))
self.itemVBox.remove(spacer)

rawDescription: wxPython: How do I remove spacers from a sizer?

description: WxPython: How do I remove spacers from a sizer


code:
class QuestionForm(forms.ModelForm):
    answers = forms.ModelMultipleChoiceField(queryset=Question.answer_set.all(), widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Question

rawDescription: Django form for model referenced by foreign keys


code:
class D(object):
    def __metaclass__(name, bases, dct):
        for attr in meta_attrs:
            dct[attr] = attr.upper()
        return type(name, bases, dct)

rawDescription: Dynamic Class Variables - locals() vs __metaclass__


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

# Example pixel array
pixels = np.random.rand(100,100,3)
reds = pixels[:,:,1:] = 0.          # Remove B and G

plt.imshow(reds, interpolation='nearest')

rawDescription: set bin colors in 2d histogram (polyochromatic plots)

description: Set bin colors in 2d histogram (polyochromatic plots)


rawDescription: Mongokit add objects to collection

description: Mongokit add objects to collection


code:
import re
s = r'http://www.google.com/search=ooo-jjjj'
re.findall(r'((\w)\2{2,})', s)
[match[0] for match in re.findall(r'((\w)\2{2,})', s)]

rawDescription: [python]: use re to find consecutively repeated chars


rawDescription: Adding numbers 01-15 to the end of a set of numbers


code:
import distutils.sysconfig

setup(
    # [...]
    data_files = [(distutils.sysconfig.get_python_lib(), ["/path/to/the/DLL"])],
)

rawDescription: Python copy a DLL to site-packages on Windows


rawDescription: Given a list of values remove first occurrence


code:
files_to_check = glob.glob(os.path.join(path, '*.tar.gz'))
most_recent_file = max(files_to_check, key=os.path.getmtime)

rawDescription: Python get latest directory and unzip

description: Python get latest directory and unzip


code:
'foo' in 'foobar' # Basic match
re.search(r'\bfoo\b', 'foobar') # Whole word only
re.search(r'\bfoo\b', 'foo bar')

rawDescription: Using Python to match an exact word

description: Using Python to match an exact word


code: list_of_image_fields = [x.name for x in instance._meta.fields if x.get_internal_type() == 'ImageFieldFile']

rawDescription: Django filter list of field to get field of a certain type only


code:
import re
reValidIPv4 = re.compile(r"""
    # Match a valid IPv4 in the wild.
    (?:                                         # Group two start-of-IP assertions.
      ^                                         # Either the start of a line,
    | (?<=\s)                                   # or preceeded by whitespace.
    )                                           # Group two start-of-IP assertions.
    (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)    # First number in range 0-255
    (?:                                         # Exactly 3 additional numbers.
      \.                                        # Numbers separated by dot.
      (?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)  # Number in range 0-255 .
    ){3}                                        # Exactly 3 additional numbers.
    (?=$|\s)                                    # End IP on whitespace or EOL.
    """, re.VERBOSE | re.MULTILINE)

text = "10.0.0.1.1 but 127.0.0.256 1.1.1.1"
l = reValidIPv4.findall(text)
print(l)

rawDescription: Finding valid IP addresses with regex

description: Finding valid IP addresses with regex


rawDescription: Pandas modify column values in place based on boolean array


code: battery = ''.join(c for c in battery if not c.isdigit() and not c.isspace())

rawDescription: How to strip string of all integers and spaces

description: Strip string of all integers and spaces


code:
import math

def ceil(x, s):
    return s * math.ceil(float(x)/s)

rawDescription: Excel-like ceiling function in python?

description: Excel-like ceiling function in python


code:
data = """34% passed 23% failed 46% deferred"""
for m in re.finditer('(?P<percentage>\w+)%\s(?P<word>\w+)', data):
    print( m.group('percentage'), m.group('word') )

rawDescription: Capturing named groups in regex with re.findall


code:
import numpy as np
r, d = 1000, 100000
a = np.random.rand(d).round()
A = a * np.ones((r, 1))
A.shape
a
A

rawDescription: How to efficiently generate this matrix in python

description: Efficiently generate this matrix in python


code:
for each in x:
    for match in regex.finditer(each):
        print (match.group(1), '--', match.group(2))

rawDescription: Using python regex, find, and accessing groups


code:
class RelatedFriendSerializer(serializers.ModelSerializer):
    class Meta:
        model = FriendModle
        fields = ('id', '...')

class UserSerializer(serializers.ModelSerializer):
    relatedfriendserializer = RelatedFriendSerializer(read_only=False)
    class Meta:
        model = User
        fields = ('id', 'relatedfriendserializer',)

rawDescription: How to do model bulk interpolate in Django REST Framework 3?

description: Do model bulk interpolate in Django REST Framework 3


rawDescription: How to set HTTP_REFERER header in a Django view?

description: Set HTTP_REFERER header in a Django view


code:
import errno
import os

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:  # Python >2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

rawDescription: mkdir -p functionality in Python

description: Mkdir -p functionality in Python


code:
string = "Batman Superman"
tokenized = string.split(" ")
list(nltk.bigrams(tokenized))

rawDescription: How can I get string as input to Bigrams in nltk

description: Get string as input to Bigrams in nltk


code:
det(pilot-2, A-1)
nsubj(flies-3, pilot-2)
root(ROOT-0, flies-3)
det(airplane-5, an-4)
dobj(flies-3, airplane-5)

rawDescription: Natural Language to Binary Fact

description: Natural Language to Binary Fact


code:
avro_rdd = sc.newAPIHadoopFile(
    path,
    "org.apache.avro.mapreduce.AvroKeyInputFormat",
    "org.apache.avro.mapred.AvroKey",
    "org.apache.hadoop.io.NullWritable",
    keyConverter="org.apache.spark.examples.pythonconverters.AvroWrapperToJavaConverter",
    conf=conf)

rawDescription: How to read pyspark avro file and extract the values?

description: Read pyspark avro file and extract the values


rawDescription: Is there any way to keep a PeriodIndex as a series of Periods with a reset_index()?