code:
import time
import sys

toolbar_width = 40

# setup toolbar
sys.stdout.write("[%s]" % (" " * toolbar_width))
sys.stdout.flush()
sys.stdout.write("\b" * (toolbar_width+1)) # return to start of line, after '['

for i in xrange(toolbar_width):
    time.sleep(0.1) # do real work here
    # update the bar
    sys.stdout.write("-")
    sys.stdout.flush()

sys.stdout.write("\n")

rawDescription: Python Progress Bar

description: Python Progress Bar


code:
def userJoined(self, user, channel):
    log.msg('%s has joined %s' % (user, channel))

def userLeft(self, user, channel):
    log.msg('%s has left %s' % (user, channel))

def userQuit(self, user, quitMessage):
    log.msg('%s has quit. Reason: %s' % (user, quitMessage))

rawDescription: Python/Twisted IRC bot logging problem

description: Python/Twisted IRC bot logging problem


rawDescription: Why does the "down" key behavior change in a Tkinter listbox after issuing selection_set and selection_clear commands?


code:
## Explore the data (line 27)
data = pd.read_table('u.data', header=None)  # header=None avoid getting the columns automatically
data.columns = ['userID', 'itemID',
                'rating', 'timestamp']       # Manually set the columns.
data = data.drop('timestamp', axis=1)        # Continue with regular work.

...

## Load user information (line 75)
users_info = pd.read_table('u.user', sep='|', header=None)
users_info.columns = ['useID', 'age', 'gender',
                      'occupation' 'zipcode']
users_info = users_info.set_index('userID')

...

## Load movie information (line 88)
movies_info = pd.read_table('u.item', sep='|', header=None)
movies_info.columns = ['movieID', 'movie title', 'release date',
                       'video release date', 'IMDb URL', 'unknown',
                       'Action', 'Adventure', 'Animation', "Children's",
                       'Comedy', 'Crime', 'Documentary', 'Drama',
                       'Fantasy', 'Film-Noir', 'Horror', 'Musical',
                       'Mystery', 'Romance', 'Sci-Fi',' Thriller',
                       'War', 'Western']
movies_info = movies_info.set_index('movieID')#.drop(low_count_movies)

rawDescription: ValueError: labels ['timestamp'] not contained in axis


rawDescription: QNetworkProxy: unset proxy

description: QNetworkProxy: unset proxy


code:
def crop(doc, start, end):
    return doc[doc.find(start):doc.rfind(end)+len(end)]

rawDescription: How to crop a text?

description: Crop a text


code:
class SampleClass:
    foo = staticmethod(foobar)
    def printfunc(self):
        self.foo() # Prints 'FOOBAR!'

rawDescription: Call Python object's variable as a function without passing the calling object


code:
# Code that defines the prior: p(a,b)∝(a+b)^(−5/2)
@pm.stochastic
def ab(power=-2.5, value=[1,1]):
    if np.any(value <= 0):
        return -np.Inf
    return power * np.log(value[0]+value[1])

a = ab[0]
b = ab[1]

rawDescription: Custom priors in PyMC

description: Custom priors in PyMC


code:
b = soup.b
results = []
result = str()
while b != None:
    try:
        if b.name == 'b':
            results.append(result)
            result = b.text
    except AttributeError:
        result = result + b
    b = b.nextSibling
results.append(result)

rawDescription: Scraping a pretty typical block of text

description: Scraping a pretty typical block of text


code:
import datetime
s = "Apr 18 17:19:42"
t = datetime.datetime.strptime(s, "%b %d %H:%M:%S")
t
t = t.replace(year = 2012)
n = datetime.datetime.now()
n
d = n-t
d.total_seconds()

rawDescription: Convert string to datetime in python and compare to current time


code:
from pylab import *

figure()
gca().set_position((.1, .3, .8, .6)) # to make a bit of room for extra text
plot([1,2], [3,4])
figtext(.95, .9, "This is text on the side of the figure", rotation='vertical')
figtext(.02, .02, "This is text on the bottom of the figure.\nHere I've made extra room for adding more text.\n" + ("blah "*16+"\n")*3)
xlabel("an interesting axis label")
show()

rawDescription: Add graph description under graph in pylab


code:
keys = redis.keys('*')
for key in keys:
    type = redis.type(key)
    if type == KV:
        val = redis.get(key)
    if type == HASH:
        vals = redis.hgetall(key)
    if type == ZSET:
        vals = redis.zrange(key, 0, -1)

rawDescription: Redis: Return all values stored in a database


code:
import sys
import time

def spinning_cursor():
    while True:
        for cursor in '|/-\\':
            yield cursor

spinner = spinning_cursor()
for _ in range(50):
    sys.stdout.write(spinner.next())
    sys.stdout.flush()
    time.sleep(0.1)
    sys.stdout.write('\b')

rawDescription: How to create a spinning command line cursor using python?

description: Create a spinning command line cursor using python


code:
import sys
from PyQt4 import QtCore, QtGui, QtDeclarative
from PyQt4.QtCore import pyqtProperty, pyqtSignal, QObject

class TweetModel(QtCore.QAbstractListModel):
    def __init__(self, prototype, parent=None):
        QtCore.QAbstractListModel.__init__(self, parent)
        self.setRoleNames(prototype.roles)
        self.tweets = []

    def appendRow(self, item):
        self.tweets.append(item)

    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.tweets)

    def data(self, index, role):
        return self.tweets[index.row()].data(role)

class TweetItem(QObject):
    roles = {
        QtCore.Qt.UserRole + 1: 'id',
        QtCore.Qt.UserRole + 6: 'original',
    }

    id_changed = pyqtSignal()

    def __init__(self, id=None, original=None, parent=None):
        QObject.__init__(self, parent=parent)

        self._data = {'original': original}
        self.id = id

    def data(self, key):
        return self._data[self.roles[key]]

    @pyqtProperty(str, notify=id_changed)
    def id(self):
        return self._data['id']

    @id.setter
    def id(self, value):
        if self._data.get('id') != value:
            self._data['id'] = value
            self.id_changed.emit()

if __name__ == "__main__":
    model = TweetModel(TweetItem)
    item = TweetItem("0001", None, model)
    model.appendRow(TweetItem("0002", item, model))

    App = QtGui.QApplication(sys.argv)
    view = QtDeclarative.QDeclarativeView()
    view.rootContext().setContextProperty("mymodel", model)
    view.setSource(QtCore.QUrl.fromLocalFile("main.qml"))
    view.show()
    App.exec_()

rawDescription: Return an object in a role in Python and get a reference of another object in QML


code:
def next_string(s):
    strip_zs = s.rstrip('z')
    if strip_zs:
        return strip_zs[:-1] + chr(ord(strip_zs[-1]) + 1) + 'a' * (len(s) - len(strip_zs))
    else:
        return 'a' * (len(s) + 1)

rawDescription: How can I get the next string, in alphanumeric ordering, in Python?

description: Get the next string, in alphanumeric ordering, in Python


code: response = urllib2.urlopen(req, json.dumps([p["firstname"] for p in Profiles]))

rawDescription: How to extract single property from Python object when it is in a list?

description: Extract single property from Python object when it is in a list


rawDescription: How to get a list of those columns that contain any NA field?

description: Get a list of those columns that contain any NA field


code:
df
df.set_index(['Form', 'nr Element', 'Type', 'Test'])

rawDescription: Pandas hierarchical dataframe

description: Pandas hierarchical dataframe


code:
obj = Foo.objects.get(pk="foo")
obj.pk = "bar"
obj.save()

rawDescription: How do I clone a Django model instance object and save it to the database?

description: Clone a Django model instance object and save it to the database


code:
my_path = "some/path/blah"
os.path.insert(0,my_path)
import my_custom_module

rawDescription: import a python module from a user-specified dir?

description: Import a python module from a user-specified dir


code:
from socket import *

def createServer():
    serversocket = socket(AF_INET, SOCK_STREAM)
    serversocket.bind(('localhost',9000))
    serversocket.listen(5)
    while(1):
        (clientsocket, address) = serversocket.accept()
        clientsocket.send("It works")

createServer()

rawDescription: How can I implement a simple web server using Python without using any libraries?

description: Implement a simple web server using Python without using any libraries


code:
import numpy as np
np.genfromtxt('filename', dtype= None)
# array([(1, 2.0, 'buckle_my_shoe'), (3, 4.0, 'margery_door')],
#       dtype=[('f0', '<i4'), ('f1', '<f8'), ('f2', '|S14')])

rawDescription: How do I import data with different types from file into a Python Numpy array?

description: Import data with different types from file into a Python Numpy array


code:
import os
all_txt = []
root = r'C:\Users\EDV\Desktop\Peter\Models\Texte'
for d in os.listdir(root):
    abs_d = os.path.join(root, d)
    if os.path.isdir(abs_d):
        txt = os.path.join(abs_d, '002.txt')
        if os.path.isfile(txt):
            all_txt.append(txt)

rawDescription: glob function in python with one wildcard

description: Glob function in python with one wildcard


rawDescription: Is there a way for on-the-fly pre-processing (splitting) of elements with get_dummies()?


code:
data = dict() # or another cache structure
def edit(request):
    data[request.user] = your_data
    ...
def save(request):
    your_data = data.get(request.user)
    ...

rawDescription: Flask&Pandas: upload a csv as a pandas Dataframe and pass it through views


rawDescription: Python: Difference between != and "is not"


code:
def __delattr__(self, key):
    del self._meta[key]

rawDescription: Implement _del_ method for a class with __getattribute__ overriden


code:
import subprocess
import os
import threading

class LogThread(threading.Thread):
    """Thread which will read from `pipefd` and write all contents to
    `fileobj` until `pipefd` is closed.  Used as a context manager, this thread
    will be automatically started, and joined on exit, usually when the
    child process exits.
    """
    def __init__(self, pipefd, fileobj):
        self.pipefd = pipefd
        self.fileobj = fileobj
        super(LogThread, self).__init__()
        self.setDaemon(1)
        self.start()

    def run(self):
        while True:
            line = self.pipefd.readline()
            if not line:
                break
            self.fileobj.write(line)
            self.fileobj.flush()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.join()

# Here's how to use the LogThread.
p = subprocess.Popen ("script", shell = False, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
with open('logfile.txt', 'wt') as logfile:
    with LogThread(p.stdout, logfile):
        p.stdin.write("\n".join(in_lines))
        p.stdin.close()

rawDescription: logged subprocess.communicate()?

description: Logged subprocess.communicate()


code:
import matplotlib.pyplot as plt
import numpy as np
from scipy import optimize

data=[np.arange(0,20.0,1),np.array([-52.368, 32.221, 40.102, 48.088, 73.106, 50.807, 52.235, 76.933, 65.737, 34.772, 94.376, 123.366, 92.71, 72.25, 165.051, 91.501, 118.92, 100.936, 56.747, 159.034])]

def line(m,b):
   return np.arange(0, 20, 1)*m + b

guess = np.ones(2)

errfunc= lambda p,y: (y-line(p[0],p[1]))
parameter, sucess = optimize.leastsq(errfunc, guess, args=(data[1]))

print(parameter)
plt.plot(data[0],data[1],'o')
plt.plot(data[0],line(parameter[0],parameter[1]))
plt.show()

rawDescription: Optimising two arrays simultaneously with scipy optimize


code:
def merge3( row1, row2 ):
    i1= 0
    i2= 0
    result= []
    while i1 != len(row1) or i2 != len(row2):
        if i1 == len(row1):
            result.append( ' '.join(row1[i1].contents) )
            i2 += 1
        elif i2 == len(row2):
            result.append( ' '.join(row2[i2].contents) )
            i1 += 1
        else:
            if row1[i1]['colspan'] < row2[i2]['colspan']:
                # Fill extra cols from row1
                c1= row1[i1]['colspan']
                while c1 != row2[i2]['colspan']:
                    result.append( ' '.join(row2[i2].contents) )
                    c1 += 1
            elif row1[i1]['colspan'] > row2[i2]['colspan']:
                # Fill extra cols from row2
                c2= row2[i2]['colspan']
                while row1[i1]['colspan'] != c2:
                    result.append( ' '.join(row1[i1].contents) )
                    c2 += 1
            else:
                assert row1[i1]['colspan'] == row2[i2]['colspan']
                pass
            txt1= ' '.join(row1[i1].contents)
            txt2= ' '.join(row2[i2].contents)
            result.append( txt1 + " " + txt2 )
            i1 += 1
            i2 += 1
    return result

rawDescription: Is there a more Pythonic way to merge two HTML header rows with colspans?


code:
widgets = {}
form = QFormLayout()
for key, value in your_dict.iteritems():
    widgets[key] = widget = {}
    widget['spinbox'] = spinbox = QSpinBox()
    spinbox.setValue(value)
    form.addRow(key, spinbox)

rawDescription: Generic value editor GUI for dictionaries in PyQt


code:
sprites = pygame.sprite.LayeredDirty((sprite1, sprite2, sprite3))
sprites.add(sprite4)
...
sprites.draw(pygame_screen)

rawDescription: Loading and blitting images per frame?

description: Loading and blitting images per frame


code:
import json
import requests

# name and path to files with the secret key and certificate
KEYFILE = '/path/to/private.key'
CERTFILE = '/path/to/cert.crt'

# address for sending JSON requests
url = 'https://api.direct.yandex.ru/json-api/v4/'

# input data structure (dictionary)
data = {
   'method': 'GetClientInfo',
   'param': ['agrom'],
   'locale': 'en'
}

# convert the dictionary to JSON format and change encoding to UTF-8
jdata = json.dumps(data, ensure_ascii=False).encode('utf-8')

response = requests.post(url, data=jdata, cert=(CERTFILE, KEYFILE))

print(response.content)

rawDescription: Yandex.Direct - API in Python

description: Yandex.Direct - API in Python


code:
import Tkinter as tk

class Mainwindows:
    def __init__ (self, master):
        self.master=master
        self.mainframe=tk.LabelFrame(self.master, text="INPUT")
        self.outputframe=tk.LabelFrame(self.master, text="OUTPUT")
        self.sinputbutton=tk.Button(self.mainframe, text="Soil INPUT", command=self.opensoilinput)
        self.sinputbutton.pack()
        #self.beamimage=tk.PhotoImage(file="Inputfond.pgm")
        #self.binputbutton=tk.Button(self.mainframe, text="Beam INPUT",image=self.beamimage, compound="top", command=self.openbeaminput)

        self.binputbutton=tk.Button(self.mainframe, text="Beam INPUT", compound="top", command=self.openbeaminput)

        self.binputbutton.pack()
        self.actinputbutton= tk.Button(self.mainframe, text= "Actions INPUT", command= self.openactioninput)
        self.actinputbutton.pack()
        self.glabel=tk.Label(self.mainframe, text= "Beam leinght [m]")
        self.glabel.pack()
        self.glinpute=tk.Entry(self.mainframe, textvariable=tk.DoubleVar)
        self.glinpute.pack()
        self.g2label=tk.Label(self.mainframe, text= "Strip leinght [m]")
        self.g2label.pack()
        self.gl2inpute=tk.Entry(self.mainframe, textvariable= tk.DoubleVar)
        self.gl2inpute.pack()
        self.runbutton=tk.Button(self.outputframe, text="RUN", command=self.runkoenig)
        self.runbutton.pack(side="bottom")
        self.plotbutton=tk.Button(self.outputframe, text="Plot", command= self.plotaction)
        self.plotbutton.pack()
        self.canvplot= tk.Canvas (self.outputframe, width=800, height=600, bg="#60B7FF")
        self.canvplot.pack()
        self.mainframe.pack()
        self.outputframe.pack()

        self.soilwindow= tk.Toplevel(self.master)
        self.soilwindow.title("Soil INPUT")
        self.soil = Soilinput(self.soilwindow)
        self.soilwindow.withdraw()
        self.beamwindow= tk.Toplevel(self.master)
        self.beamwindow.title("Beam INPUT")
        self.beam = Beaminput(self.beamwindow)
        self.beamwindow.withdraw()
        self.actionwindow= tk.Toplevel(self.master)
        self.actionwindow.title("Actions INPUT")
        self.action = Actioninput(self.actionwindow)
        self.actionwindow.withdraw()

    def opensoilinput(self):
        self.soilwindow.deiconify()
    def openbeaminput(self):
        self.beamwindow.deiconify()
    def openactioninput(self):
        self.actionwindow.deiconify()
    def runkoenig(self):
        self.run = Runkoenig(self)

    def plotaction(self):
        plt.plot(self.Runkoenig.x, self.Runkoenig.pfin)

class Soilinput:      #1st input window with some widgets
    def __init__ (self, master):
        self.master=master
        self.soilframe=tk.Frame(self.master)
        self.soilstiffness= tk.Label(self.soilframe, text="Soil stiffness [kPa]")
        self.soilstiffness.pack()
        self.soilstiffnessinpute= tk.Entry(self.soilframe, textvariable=tk.DoubleVar)
        self.soilstiffnessinpute.pack()
        self.deflayer= tk.Label(self.soilframe, text="Deformable layer [m]")
        self.deflayer.pack()
        self.deflayerinpute= tk.Entry(self.soilframe, textvariable=tk.DoubleVar)
        self.deflayerinpute.pack()
        self.poissonratio=tk.Label(self.soilframe, text="Poisson ratio v")
        self.poissonratio.pack()
        self.poissonratioinpute=tk.Entry(self.soilframe, textvariable=tk.DoubleVar)
        self.poissonratioinpute.pack()
        self.soilbutton=tk.Button(self.soilframe, text="Ok", command=self.soilinputquit)
        self.soilbutton.pack(side="right", padx=5, pady=10)
        self.soilframe.pack()
    def soilinputquit(self):
        self.master.withdraw()

class Beaminput:   #2nd input window with other stuff widget
    def __init__ (self, master):
        self.master=master
        self.beamframe=tk.Frame(self.master)
        self.beamstiffness= tk.Label(self.beamframe, text="Beam stiffness [kPa]")
        self.beamstiffness.pack()
        self.beamstiffnessinpute= tk.Entry(self.beamframe, textvariable=tk.DoubleVar)
        self.beamstiffnessinpute.pack()
        self.beaminertia=tk.Label(self.beamframe, text="Beam inertia [kPa]")
        self.beaminertia.pack()
        self.beaminertiainpute= tk.Entry(self.beamframe,textvariable=tk.DoubleVar)
        self.beaminertiainpute.pack()
        self.beambase=tk.Label(self.beamframe, text="Beam base [m]")
        self.beambase.pack()
        self.beambaseinpute=tk.Entry(self.beamframe,textvariable=tk.DoubleVar)
        self.beambaseinpute.pack()
        self.beamexitbutton=tk.Button(self.beamframe, text="Ok", command=self.beamexit)
        self.beamexitbutton.pack(side="right", padx=5, pady=10)
        self.beamframe.pack()
    def beamexit(self):
        self.master.withdraw()

class Actioninput: #3rd and last one of the input windows
    def __init__ (self, master):
        self.master=master
        self.actionframe=tk.Frame(self.master)
        self.actionforce=tk.Label(self.actionframe, text="Nodal Force [kN]")
        self.actionforce.pack()
        self.actionforceinpute= tk.Entry(self.actionframe, textvariable=tk.DoubleVar)
        self.actionforceinpute.pack()
        self.actionforcedistance=tk.Label(self.actionframe, text="Node distance [m]")
        self.actionforcedistance.pack()
        self.actionforcedistanceinpute= tk.Entry(self.actionframe, textvariable=tk.DoubleVar)
        self.actionforcedistanceinpute.pack()
        self.linearload= tk.Label(self.actionframe, text="Linear Load [kN/m]")
        self.linearload.pack()
        self.linearloadinpute= tk.Entry(self.actionframe, textvariable=tk.DoubleVar)
        self.linearloadinpute.pack()
        self.actionexitbutton= tk.Button(self.actionframe, text="Ok", command= self.actionexit)
        self.actionexitbutton.pack(side="right", padx=5, pady=10)
        self.actionframe.pack()
    def actionexit(self):
        self.master.withdraw()

class Runkoenig:      #in here i put all the mathematical operations
    def __init__ (self, mainwin):
        self.f=mainwin.action.actionforceinpute.get()
        self.df= mainwin.action.actionforcedistanceinpute.get()
        self.E= mainwin.beam.beamstiffnessinpute.get()
        self.J= mainwin.beam.beaminertiainpute.get()
        self.B= mainwin.beam.beambaseinpute.get()
        self.Et= mainwin.soil.soilstiffnessinpute.get()
        self.Hdef= mainwin.soil.deflayerinpute.get()
        self.v= mainwin.soil.poissonratioinpute.get()
        self.L= mainwin.glinpute.get()
        self.l= mainwin.gl2inpute.get()
        print("ok!")

        #self.x=(0.5*self.l*(2*self.NaSTR-self.Nuno));

        #math stuff stuff stuff and then the final passages:

        #self.p=np.linalg.solve(self.A,self.N)
        #self.pfin=np.resize(self.p,np.size(self.x))

def main():
     root=tk.Tk()
     root.title("$$$$$")
     app= Mainwindows(root)
     root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Python/Tkinter- Problems with calling variables from another class and plot graph


code:
import numpy as np
from scipy.optimize import minimize
from sympy.utilities.lambdify import lambdify
import sympy as sy

sy.init_printing()  # LaTeX like pretty printing for IPython

x1, x2, x3, x4 = sy.symbols('x1 x2 x3 x4')
xx = (x1, x2, x3, x4)
f = -2*x1**2*x3+6*x1**2*x4+13*x1**2-3*x1*x2**2+x1*x2+3*x1*x3**2-3*x4+103
f_n = lambdify(xx, f, modules='numpy')

# Build Jacobian:
jac_f = [f.diff(x) for x in xx]
jac_fn = [lambdify(xx, jf, modules='numpy') for jf in jac_f]

def f_v(zz):
    """ Helper for receiving vector parameters """
    return f_n(zz[0], zz[1], zz[2], zz[3])

def jac_v(zz):
    """ Jacobian Helper for receiving vector parameters """
    return np.array([jfn(zz[0], zz[1], zz[2], zz[3]) for jfn in jac_fn])

bnds = ((-1, 1), (-1, 1), (-1, 1), (-1, 1))
zz0 = np.array([1, 1, 1, 1])

rslts = minimize(f_v, zz0, method='SLSQP', jac=jac_v, bounds=bnds)
print(rslts)

rawDescription: Want to do multi-variation minimize with sympy


code:
from sqlalchemy import MetaData
from sqlalchemy.orm import scoped_session, sessionmaker
__all__ = ['Session', 'engine', 'metadata']
engine = None
Session = scoped_session(sessionmaker())
metadata = MetaData()

rawDescription: Sqlalchemy layout with WSGI application

description: Sqlalchemy layout with WSGI application


code:
import re
from datetime import datetime as dt

def changedate(birthdate):
    weekday = dt.strptime(birthdate, '%m-%d-%Y %H:%M:%S%p').strftime('%A')
    return birthdate + ',' + weekday

str = open(filename).read()
str = re.sub(r'Name,Birthdate,Age,Address','Name,Birthdate,Weekday,Age,Address', str)
str = re.sub(r'(\d+-\d+-\d+\s\d+:\d+:\d+\w{2})',lambda m: changedate(m.group()), str)

with open(filename, 'w') as f:
    f.write(str)

rawDescription: Python: How to add values obtained from an operation in a new column of given CSV?


code:
@total_ordering
class Student:
    def __eq__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) ==
                (other.lastname.lower(), other.firstname.lower()))
    def __lt__(self, other):
        return ((self.lastname.lower(), self.firstname.lower()) <
                (other.lastname.lower(), other.firstname.lower()))

rawDescription: Is it safe to just implement __lt__ for a class that will be sorted?


code:
import numpy as np
from scipy import interpolate
from matplotlib import pyplot as plt

x = np.array([23, 24, 24, 25, 25])
y = np.array([13, 12, 13, 12, 13])

# append the starting x,y coordinates
x = np.r_[x, x[0]]
y = np.r_[y, y[0]]

# fit splines to x=f(u) and y=g(u), treating both as periodic. also note that s=0
# is needed in order to force the spline fit to pass through all the input points.
tck, u = interpolate.splprep([x, y], s=0, per=True)

# evaluate the spline fits for 1000 evenly spaced distance values
xi, yi = interpolate.splev(np.linspace(0, 1, 1000), tck)

# plot the result
fig, ax = plt.subplots(1, 1)
ax.plot(x, y, 'or')
ax.plot(xi, yi, '-b')

rawDescription: Interpolating a closed curve using scipy


code:
Component.objects.extra(
    select={'fieldsum':'material_cost + labor_cost'},
    order_by=('fieldsum',)
)

rawDescription: Django order_by sum of fields

description: Django order_by sum of fields


code:
...
self.tree = ttk.Treeview(...)
self.tree.bind("<1>", self.on_click)
...
def on_click(self, event):
    selection = self.tree.selection()
    item = self.tree.select_row(event.y)
    if item in selection:
        self.tree.selection_remove(item)
        return "break"

rawDescription: TreeView option to select and de-select by clicking?


code: Vector = List[float]

rawDescription: How do you alias a type in python?

description: Alias a type in python


code:
import time
def myscript():
    print("What do you want to buy? You have currently")
    print ("You have a choice between the following and may only buy one:")
    time.sleep(1)
    pistol = 20
    print("A pistol for 20 coins")
    time.sleep(1)
    costfuel = 10
    print("15 fuel for 10 coins")
    time.sleep(1)
    shotgun = 40
    print("A shotgun for 40 coins")
    time.sleep(1)
    costoxygen = 10
    print("10 oxygen for 10 coins")
    time.sleep(1)
    costlife = 50
    print("or 5 life for 50 coins")
    time.sleep(1)
    choose = input("You may now choose which of the following you want - please type it in e.g pistol. ")
    if choose == "pistol":
        while Coins < pistol:
             print ("You cannot buy this as you do not have enough money.")
             time.sleep(4)
             myscript()
        else:
             print ("Thank you for purchasing the pistol! You have",Coins,"coins remaining")
    elif choose == "costfuel":
        while Coins < costfuel:
             print ("You cannot buy this as you do not have enough money.")
             time.sleep(4)
             myscript()
        else:
            print ("Thank you for purchasing the fuel! You have",Fuel,"fuel remaining and",Coins,"coins remaining.")
    else:
        while Coins < shotgun:
            print ("You cannot buy this as you do not have enough money.")
            time.sleep(4)
            myscript()
        else:
            print ("Thank you for purchasing the shotgun! You have",Coins,"coins remaining")
myscript()

rawDescription: Nothing comes up when I type this in python


code:
from itertools import product

def foo(point):
    for combo in product(*(range(i + 1) for i in point)):
        yield combo

rawDescription: How to make function foo generate all the points?

description: Make function foo generate all the points


code: cmd = ["glpsol", "-m", os.path.join(os.path.dirname(__file__), "workingLP.txt")]

rawDescription: python subprocess, No such file or directory

description: Python subprocess, No such file or directory


code:
import collections
def load(fname):
    d = collections.OrderedDict()
    for i in (line.rstrip('\n') for line in open(fname) if line[:-1]):
        d.update({i[1:-1]:[], '_':i[1:-1]}) \
        if i.startswith('[') else d[d['_']].append(i)
    return d

def join(first, dic):
    f = dic[first]
    for i,j in ((i,j[2:]) for i,j in enumerate(f) if j.startswith('<')):
        f[i:i+1] = join(j, dic)
    return f

d = load('file.txt')
join(next(iter(d)), d)

rawDescription: replace names with lists from file

description: Replace names with lists from file


rawDescription: python/numpy: how to get 2D array column length?

description: Python/numpy: how to get 2D array column length


code:
def dataReceived(self, data):
    username = self._parseAndExtractUsername(data)
    if username is not None:
        self.factory.users[username] = self

rawDescription: Twisted - Matching current connection in factory.clients with unique ID


code:
...
def get_movietimes(self, obj):
    movietimes = {}
    for i in obj.theater.all():
        if i.mvtype not in movietimes:
            movietimes[i.mvtype] = []
        movietimes[i.mvtype].append(i.movietime)
    return movietimes
...

rawDescription: django restframework display format

description: Django restframework display format


code:
first, second = [], []
for lst in (first, second):
    lst.append(msg)

rawDescription: Adding same text to two different lists

description: Adding same text to two different lists


rawDescription: hexToBinary dictionary

description: HexToBinary dictionary


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

URL = "http://www.quora.com"
EMAIL = 'your email here'
PASSWORD = 'your password here'

driver = webdriver.Chrome()  # can be webdriver.Firefox() in your case
driver.get(URL)
wait = WebDriverWait(driver, 10)

# login
form = driver.find_element_by_class_name('regular_login')
username = form.find_element_by_name('email')
username.send_keys(EMAIL)

password = form.find_element_by_name('password')
password.send_keys(PASSWORD)

login_button = form.find_element_by_xpath('//input[@type="submit" and @value="Login"]')
login_button.click()

# search
search = wait.until(EC.presence_of_element_located((By.XPATH, "//form[@name='search_form']//input[@name='search_input']")))
search.send_keys('Kevin Rose')
search.send_keys(Keys.ENTER)

# follow the link
link = wait.until(EC.presence_of_element_located((By.LINK_TEXT, "Kevin Rose")))
link.click()

rawDescription: Unable to click link using selenium webdriver in python


code:
class MetaTagsSerializer(serializers.ModelSerializer):
    class Meta:
        model = MetaTags

    def to_native(self, obj):
        """
        Serialize objects -> primitives.
        """
        ret = self._dict_class()
        ret.fields = self._dict_class()

        for field_name, field in self.fields.items():
            if field.read_only and obj is None:
                continue
            field.initialize(parent=self, field_name=field_name)
            key = self.get_field_key(field_name)
            value = field.field_to_native(obj, field_name)

            # Continue if value is None so that it does not get serialized.
            if value is None:
                continue

            method = getattr(self, 'transform_%s' % field_name, None)
            if callable(method):
                value = method(obj, value)
            if not getattr(field, 'write_only', False):
                ret[key] = value
            ret.fields[key] = self.augment_field(field, field_name, key, value)

        return ret

rawDescription: Remove null fields from Django Rest Framework response


rawDescription: Import an image as a background in Tkinter


code:
import matplotlib.pyplot as plt
import matplotlib.dates as md
import dateutil

datestrings = ['2012-02-21 11:28:17.980000', '2012-02-21 12:15:32.453000', '2012-02-21 23:26:23.734000', '2012-02-26 17:42:15.804000']
dates = [dateutil.parser.parse(s) for s in datestrings]

plt_data = range(5,9)
plt.subplots_adjust(bottom=0.2)
plt.xticks( rotation=25 )

ax=plt.gca()
ax.set_xticks(dates)

xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)
plt.plot(dates,plt_data, "o-")
plt.show()

rawDescription: Plotting timestamps (hour/minute/seconds) with Matplotlib


code:
from scipy.interpolate import RectBivariateSpline

# sample data
data = np.random.rand(8, 4)
width, height = data.shape
xs = np.arange(width)
ys = np.arange(height)

# target size and interpolation locations
new_width, new_height = width*2, height*2
new_xs = np.linspace(0, width-1, new_width)
new_ys = np.linspace(0, height-1, new_height)

# create the spline object, and use it to interpolate
spline = RectBivariateSpline(xs, ys, data) #, kx=1, ky=1) for linear interpolation
spline(new_xs, new_ys)

rawDescription: Scale square matrix in geometrical sense using python


code:
import numpy as np
import pylab as plt
from math import *
plt.figure()
th=np.linspace(0,np.pi,num=200)
y=range(10)
for i in range(10):
    alph=np.exp(i/2)
    y[i]=((np.cos(alph*np.cos(th)) - np.cos(alph))/np.sin(th))**2
    plt.plot(th/pi,y[i],  label = 'Line %d' %i)
plt.legend(loc =2)
plt.show()

rawDescription: Matplotlib more than 3 lines on same axes


code:
map(max, a, b)
[max(x, y) for x, y in zip(a, b)]

rawDescription: Simpler/preferred way to iterate over two equal-length lists and append the max of each pair to a new list?


code:
class MyModule(object):
    def __init__(self, namespace):
        self.__dict__.update(namespace)
    def __getitem__(name):
        return self.__dict__[name]

import other
import sys
sys.modules[other.__name__] = MyModule(other.__dict__)

rawDescription: Add __getitem__ to module

description: Add __getitem__ to module


code:
import arcpy, os

original_path = r'F:\Sheyenne\Atmospherically Corrected Landsat\hank_masked\Band 1'
#pathway where there are only 80 .tif files, one for each landsat scene
arcpy.env.workspace=original_path
#list of rasters in above pathway
list1 = arcpy.ListRasters("*.tif")
#output save pathway
main_path=r'F:\Sheyenne\Atmospherically Corrected Landsat\Individual Scenes\Main'

#create folder for each landsatscene containing first 21 characters
for raster in list1:

    source_path = os.path.join(original_path, raster)
    dir_name=split("_")[0]
    destination_path=os.path.join(main_path, dir_name)

    if not os.path.isdir(destination_path):
        os.makedirs(destination_path)

    destination_path = os.path.join(destination_path, raster)

    if not os.path.exists(destination_path):
        os.rename(source_path, destination_path)

rawDescription: Saving files based on filename to individual folders


code:
try:
    # Python 3.x
    from urllib.request import urlopen, urlretrieve, quote
    from urllib.parse import urljoin
except ImportError:
    # Python 2.x
    from urllib import urlopen, urlretrieve, quote
    from urlparse import urljoin

from bs4 import BeautifulSoup

url = 'http://oilandgas.ky.gov/Pages/ProductionReports.aspx'
u = urlopen(url)
try:
    html = u.read().decode('utf-8')
finally:
    u.close()

soup = BeautifulSoup(html)
for link in soup.select('div[webpartid] a'):
    href = link.get('href')
    if href.startswith('javascript:'):
        continue
    filename = href.rsplit('/', 1)[-1]
    href = urljoin(url, quote(href))
    try:
        urlretrieve(href, filename)
    except:
        print('failed to download')

rawDescription: scraping: download files from url

description: Scraping: download files from url


code:
import sys
sys.path.append(path)

rawDescription: Implementing Home Grown Plugins for a Python Service


code:
import shelve

d = shelve.open(filename) # open -- file may get suffix added by low-level
                          # library

d[key] = data   # store data at key (overwrites old data if
                # using an existing key)
data = d[key]   # retrieve a COPY of data at key (raise KeyError if no
                # such key)
del d[key]      # delete data stored at key (raises KeyError
                # if no such key)
flag = d.has_key(key)   # true if the key exists
klist = d.keys() # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = range(4)  # this works as expected, but...
d['xx'].append(5)   # *this doesn't!* -- d['xx'] is STILL range(4)!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']      # extracts the copy
temp.append(5)      # mutates the copy
d['xx'] = temp      # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.

d.close()       # close it

rawDescription: Using pickle to log user's input without overwriting the file


code:
import win32com.client as client

xl = client.Dispatch("Excel.Application")
xl.Visible = True
wb = xl.Workbooks.Open("c:/1temp/badacres.xls")
ws = wb.Sheets(1)

tb = ws.Shapes.AddTextbox(1, 570, 45, 171, 80)
tb.TextFrame2.TextRange.Characters.Text = 'This is a great big test.'

rawDescription: Adding an Excel Textbox with win32com

description: Adding an Excel Textbox with win32com


code:
import numpy
from datetime import datetime
from matplotlib import pyplot as plt
from matplotlib.dates import DateFormatter, MonthLocator

t = numpy.array([datetime(2014, 3, 3),
                 datetime(2014, 2, 19),
                 datetime(2014, 7, 13),
                 datetime(2014, 5, 11),
                 datetime(2014, 6, 13),
                 datetime(2014, 1, 20)])

values = numpy.array([1, 5, 8, 9, 4, 6])

fig, ax = plt.subplots()
ax.plot_date(t, values, 'ro')
plt.xticks(rotation=45)
plt.xlabel('Date', fontsize=12)
plt.ylabel('Quantity', fontsize=12)

months = MonthLocator()
monthsFmt = DateFormatter("%b '%y")
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(monthsFmt)
plt.show()

rawDescription: When dates are on the x axis, how do i set the x axis intervals to months?


code:
numbers = np.array(words[:words.index('***END')]).astype('int')
columns = ['AA', 'BB', 'CC', 'DD']
dd = DataFrame(numbers.reshape(-1, 4), columns=columns)
dd

rawDescription: Pandas Dataframe Append or Set_Value

description: Pandas Dataframe Append or Set_Value


code:
import time
from threading import Thread,Semaphore

class Barrier:
    def __init__(self, n):
        self.n = n
        self.count = 0
        self.mutex = Semaphore(1)
        self.barrier = Semaphore(0)

    def wait(self):
        self.mutex.acquire()
        self.count = self.count + 1
        self.mutex.release()
        if self.count == self.n: self.barrier.release()
        self.barrier.acquire()
        self.barrier.release()

b = Barrier(2)

def func1():
    time.sleep(3)
    #
    b.wait()
    #
    print('Working from func1')
    return

def func2():
    time.sleep(5)
    #
    b.wait()
    #
    print('Working from func2')
    return

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()

rawDescription: Implementing Barrier in Python2.7

description: Implementing Barrier in Python2.7


code:
if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

rawDescription: Python 2.x - Write binary output to stdout?


code: mylist[:4] = szResult.split()

rawDescription: Python String List additions

description: Python String List additions


code:
import pytz
import datetime

fecha_actual_Madrid = pytz.timezone('Europe/Madrid')
logging.info('time is %s', datetime.datetime.now(fecha_actual_Madrid ))

rawDescription: Datetime in Google Cloud SQL [GAE + Python]


rawDescription: Set the color of the ticker powerlimits using matplotlib


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

def startDivide(filename):
    data = np.genfromtxt(filename, dtype=None, usecols=[1])
    data = np.abs(data)
    data.sort()
    np.savetxt("{}_1_out.csv".format(filename), data)
    plt.plot(data)
    plt.plot([0,len(data)-1], [data[0], data[-1]])
    plt.savefig("{}_1_.png".format(filename))
    area = np.trapz([data[0], data[-1]], dx=len(data)-1) - np.trapz(data)
    print(area)

if __name__ == "__main__":
    startDivide(sys.argv[1])

rawDescription: Plotting in Python via matplotlib.pyplot (calculate the area)


rawDescription: Using LooseVersion to sort a list of objects that have a version string


code:
poly1 = wkt.loads("POLYGON((1 1,2 1,2 2,1 2,1 1))")
poly2 = wkt.loads("POLYGON((1.5 2,2.5 2,2.5 3,1.5 3,1.5 2))")

shared_line = poly1.intersection(poly2)
poly1 = poly1.union(shared_line)
poly2 = poly2.union(shared_line)

rawDescription: How can I add points to Polygons which share an edge in shapely?

description: Add points to Polygons which share an edge in shapely


code:
#z = np.tile(z, (len(x), len(x)))
xm = np.tile(x,11)
xm = np.reshape(xm,(11,10)).T
zm = np.tile(z,10).T

with PdfPages('./on_tau.pdf') as p_tau:
    _p_vs_tau_ = plt.figure(figsize=(5, 5))
    _p_vs_tau_.clf()
    p_vs_tau = plt.subplot(111)
    #x, y = np.meshgrid(x, y)
    surf = plt.contourf(y, xm, zm, 30, rstride=1, cstride=1, cmap=cm.gist_heat,
                       linewidth=0, antialiased=False, alpha = 1.0)
    surf1 = plt.contour(y, xm, zm, 30, colors = '#000000',
                       linewidths=0.5, antialiased=False, alpha = 1.0)
    plt.clabel(surf1, inline=1, fontsize=6)
    p_tau.savefig(bbox_inches='tight')
    plt.close()

rawDescription: How to create contours correctly with matplotlib?

description: Create contours correctly with matplotlib


code:
# step 1
club_types = ClubTypes.objects.distinct()

# step 2 & #3
club_sets = []
for current_club_type in club_types:
    cset = Clubs.objects.filter(club_type__id=current_club_type.pk).order_by('name')
    club_sets.append((current_club_type, cset))

rawDescription: How to query a many to many relationship in Django

description: Query a many to many relationship in Django


code:
mm=cv.Moments(img)
mat=cv.GetMat(img)
mm=cv.Moments(mat)
mm.m00

rawDescription: Using Python OpenCV Moments Function With An Image


code:
import re
function_list = [f for f in dir(re) if 'find' in f] # faster than using list.append
function_list.sort() # faster than using sorted. This can actually be excluded, since `dir` returns a sorted list

rawDescription: More efficient way of solving this example?


code:
import sys
from PyQt4 import QtCore, QtGui

class SearchDialog(QtGui.QDialog):

    def __init__(self, parent = None):
        QtGui.QDialog.__init__(self, parent)
        self.setWindowTitle('Search')
        self.searchEdit = QtGui.QLineEdit()
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.searchEdit)
        self.setLayout(layout)

class MainWindow(QtGui.QDialog):

    def __init__(self):
        QtGui.QDialog.__init__(self, None)
        self.resize(QtCore.QSize(320, 240))
        self.setWindowTitle('Main window')
        self.logText = QtGui.QPlainTextEdit()
        searchButton = QtGui.QPushButton('Search')
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.logText)
        layout.addWidget(searchButton)
        self.setLayout(layout)
        searchButton.clicked.connect(self.showSearchDialog)

    def showSearchDialog(self):
        searchDialog = SearchDialog(self)
        searchDialog.show()
        searchDialog.searchEdit.returnPressed.connect(self.onSearch)

    def onSearch(self):
        self.logText.appendPlainText(self.sender().text())

def main():
    app = QtGui.QApplication(sys.argv)
    mainWindow = MainWindow()
    mainWindow.show()
    app.exec_()

if __name__ == "__main__":
    main()

rawDescription: PyQt: Accesing Main Window's Data from a dialog?


rawDescription: how to convert from ascii code to normal code in python?

description: Convert from ascii code to normal code in python


code:
def ind(the_string, the_char):
   i = 0
   for a_char in the_string:
       if a_char == the_char: return i
       i += 1
   return -1

rawDescription: Python: How to get the Index of a string


rawDescription: Set QButton height

description: Set QButton height


code:
@cached_property
def translations(self):
    return list(ClientTranslation.objects.filter(base=self))

rawDescription: How to retrieve properties only once from database in django

description: Retrieve properties only once from database in django


code:
soupByEmail = soup.find(title="Email")
if soupByEmail:
    profile['email'] = soupByEmail.a.string

rawDescription: Optimize python if statement

description: Optimize python if statement


code:
class Test(unittest.TestCase):
    Site_Home = None
    Profile_Home = None

    def redirectToFalconHostUI(self):
        #Start GOOGLE CHROME Browser
        self.browser = webdriver.Chrome(executable_path='E:\\chromedriver.exe')

        #Navigate to Website URL
        Test.Site_Home = Home(self.browser)
        Test.Site_Home.navigate()

    def testloginToWebsite(self):
        #Get Logged in the Falcon Web UI
        loginPage = Test.Site_Home.getLoginForm()
        loginPage.enter_email(SINGLE_LOGIN_USERNAME)
        loginPage.enter_password(SINGLE_LOGIN_PASSWORD)
        Test.Profile_Home = loginPage.get_logged_into_Site()

    def testProfilePageSection(self):
        Test.Profile_home.go_to_Section1()

rawDescription: How to make values accessible across all test methods?

description: Make values accessible across all test methods


code:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')

ax2 = fig.add_subplot(2,1,2, sharex=ax1)
ax2.plot(range(10), 'r-')

plt.setp(ax1.get_xticklabels(), visible=False)

plt.show()

rawDescription: matplotlib share x axis but don't show x axis tick labels for both, just one

description: Matplotlib share x axis but don't show x axis tick labels for both, just one


code:
from django.contrib.auth.views import logout_then_login

url(r'^accounts/logout/$', lambda request: logout_then_login(request, "/"), name='logout'),

rawDescription: django redirect to home page after logging out

description: Django redirect to home page after logging out


code:
inLayer6Block = False
for line in file:
    # strip trailing whitespace, since every line ends with the line break
    line = line.rstrip()

    # if we see the `LAYER 6` line, we start our block
    if line == 'LAYER 6':
        inLayer6Block = True

    # if we see the `ENDEL` line, we are no longer in the block
    elif line == 'ENDEL':
        inLayer6Block = False

rawDescription: python read lines of an entire file, and efficiently storing the ones I want in lists

description: Python read lines of an entire file, and efficiently storing the ones I want in lists


code:
def kill_process(process):
    if process.poll() is None: # don't send the signal unless it seems it is necessary
        try:
            process.kill()
        except OSError: # ignore
            pass

# shutdown process in `timeout` seconds
t = Timer(timeout, kill_process, [proc])
t.start()
proc.communicate(cmd)
t.cancel()

rawDescription: Close Python subprocess.PIPE after process is terminated


code:
fd = urllib.urlretrieve("http://images.intellicast.com/WxImages/Radar/den.gif", "den.gif")
im1 = Image.open("den.gif")
im_small = im1.resize((200, 200), Image.ANTIALIAS)

im = ImageTk.PhotoImage(im_small)
image = Label(root, image = im, bd =2)
image.grid(row = 8, column = 0, columnspan = 2, padx = 20, pady = 30)

rawDescription: Resize url image using urllib and pil

description: Resize url image using urllib and pil


rawDescription: Extract date from Pandas DataFrame

description: Extract date from Pandas DataFrame


rawDescription: Pick four cards and check if they sum to 24 - Python


code:
def __dir__(self):
    base = dir(self.data)
    base.extend(('_try_attr', 'data'))
    return base

rawDescription: can any recursive looping happen from overwriting __dir__ in python

description: Can any recursive looping happen from overwriting __dir__ in python


code:
import subprocess as sub

process = sub.Popen("ls --colors=always /", stdout=sub.PIPE, stderr=sub.PIPE)
output, errors = process.communicate()

rawDescription: Python pty module usage example

description: Python pty module usage example


code:
from itertools import chain, izip
value_list = [[['NaN'], ['sponge'], ['Palau']], [['skin'], ['fish'], ['Cuba']], [['claw'], ['crab'], ['Japan: Aomori, Natsudomari peninsula']]]
key_tuple = ('AB479448', 'AB479449', 'AB602436')
{k: list(chain.from_iterable(v)) for k, v in izip(key_tuple, value_list)}

rawDescription: Python: Making a dict from tuple keys with multiple values from a nested list


code:
class Item():

    def __init__(self, _prices):
        self.newPrice = 0
        self.price = _prices

rawDescription: Updating a list in a class, in a list

description: Updating a list in a class, in a list


code:
matrix = [[1,2,3,4],[9,8,7,6],[4,8,2,6]]
dict(enumerate(zip(*matrix)))
matrix = []
dict(enumerate(zip(*matrix)))

rawDescription: python - from matrix to dictionary in single line

description: Python - from matrix to dictionary in single line


code:
def leibniz_series():
    """Generator producing the Leibniz series (1, -1/3, 1/5, -1/7, ...)."""
    numerator = denominator = 1.0
    while True:
        yield (numerator / denominator)
        numerator *= -1
        denominator += 2

def pi_steps(steps=100):
    """Calculates pi from the Leibniz series with a defined number of steps."""
    values = leibniz_series()
    output = 0
    for _ in range(steps):
        value = 4 * next(values)
        output += value
    return output

def pi_tolerance(tolerance=0.0001):
    """Calculates pi from the Leibniz series with a defined output tolerance."""
    values = leibniz_series()
    output = 0
    value = 4 * next(values)
    while abs(value) > tolerance:
        output += value
        value = 4 * next(values)
    return output

rawDescription: Python basic math

description: Python basic math


code:
json_data = {u'friends': {u'paging': {u'next': u'https://graph.facebook.com/556702392/friends?access_token=-MYACCESSTOKEN-&limit=5000&offset=5000&__after_id=100005821213415'}, u'data': [{u'name': u'Ian Fung', u'id': u'419972'}, {u'name': u'Jason Turer', u'id': u'420694'}]}}
[x['id'] for x in json_data['friends']['data']]

rawDescription: Parse a JSON String from Facebook Graph API using Python


code:
import Image, ImageDraw

def add_corners(im, rad):
    circle = Image.new('L', (rad * 2, rad * 2), 0)
    draw = ImageDraw.Draw(circle)
    draw.ellipse((0, 0, rad * 2, rad * 2), fill=255)
    alpha = Image.new('L', im.size, 255)
    w, h = im.size
    alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0))
    alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h - rad))
    alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w - rad, 0))
    alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w - rad, h - rad))
    im.putalpha(alpha)
    return im

im = Image.open('tiger.jpg')
im = add_corners(im, 100)
im.save('tiger.png')

rawDescription: how to round_corner a logo without white background(transparent?) on it using pil?

description: Round_corner a logo without white background(transparent?) on it using pil


code:
from PyQt4 import QtGui, QtCore
import sys

class FetchData(QtCore.QObject):
    fetchFinished = QtCore.pyqtSignal(str)
    def __init__(self, *args):
        super(FetchData, self).__init__(*args)

    @QtCore.pyqtSlot()
    def run(self, searchStr):
        rtString = "Some data from no where : %s" % searchStr
        self.fetchFinished.emit(str(rtString))

class BASEGUICLS(QtGui.QDialog):
    def __init__(self,parent=None):
        super(BASEGUICLS, self).__init__(parent)
        self.verticalLayout = QtGui.QVBoxLayout()
        self.searchString = QtGui.QLineEdit()
        self.resultsText = QtGui.QPlainTextEdit()
        self.fetchButton = QtGui.QPushButton("Fetch")
        self.stopButton = QtGui.QPushButton("Stop")
        self.verticalLayout.addWidget(self.searchString)
        self.verticalLayout.addWidget(self.resultsText)
        self.verticalLayout.addWidget(self.fetchButton)
        self.verticalLayout.addWidget(self.stopButton)
        self.setLayout(self.verticalLayout)
        self.fetchData = FetchData()
        self.fetchData.fetchFinished.connect(self.updateResult)
        self.fetchButton.clicked.connect(self.getData)
        self.stopButton.clicked.connect(self.stopFetch)
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.refreshResult)

    def getData(self):
        self.timer.start(500)

    def refreshResult(self):
        searchStr = str(self.searchString.text())
        if not searchStr:
            self.stopFetch()
            raise RuntimeError("Missing Search String")
        self.fetchData.run(searchStr)

    def stopFetch(self):
        self.timer.stop()

    def updateResult(self, value):
        self.resultsText.appendPlainText(value)

def main():
    app = QtGui.QApplication(sys.argv)
    ex = BASEGUICLS(None)
    ex.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

rawDescription: PyQT Read and Update TextEdit from .txt file


code:
def _send_request(self, request, token=None):
    request.sign_request(OAuthSignatureMethod_HMAC_SHA1(), self.consumer, token)
    conn = self._get_conn() # connection was requested here
    if request.http_method == 'POST':
        conn.request('POST', request.http_url, body=request.to_postdata())
    else:
        conn.request('GET', request.http_url, headers=request.to_header())
    return conn.getresponse()  # Error occurs here

def _get_conn(self):
    return httplib.HTTPConnection("%s:%d" % (self.host, self.port)) # no timeout!

rawDescription: What part of python.socket could conceivably freeze my script for ever even though timeout is set?


code:
import requests
payload = 'v=1&t=event&tid=UA-XXXXXY&cid=555&ec=video&ea=play&el=holiday&ev=300'
r = requests.post('http://www.google-analytics.com/collect', data=payload)

rawDescription: REST service Google Analytics integration


code:
for item in (x.attr for x in some_list):
    do_something_with(item)

rawDescription: Creating a generator expression from a list in python


rawDescription: Remove all zero decimal places except the decimal mark


code: fields = [ix[0] for ix in cursor.description]

rawDescription: Get column name from a table's dataset in python


rawDescription: Create dummies from column with multiple values in pandas


rawDescription: function to print current module's name, also when called from another module

description: Function to print current module's name, also when called from another module


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

import sys
import os
import requests
from hashlib import sha1

recent_hash_filename = ".recent_hash"

def test(url):
    print("looking up %s" % url)
    if not os.path.exists(recent_hash_filename):
        open(recent_hash_filename, 'a').close()

    hash_fetched = sha1()
    hash_read    = ""
    r = requests.get(url)
    hash_fetched.update(r.text.encode("utf8"))

    with open(recent_hash_filename) as f:
        hash_read = f.read()

    print(hash_fetched.hexdigest())
    print(hash_read)

    if hash_fetched.hexdigest() == hash_read:
        print("same")
    else:
        print("different")

    with open(recent_hash_filename, "w") as f:
        f.write(hash_fetched.hexdigest())

if __name__ == '__main__':
    if len(sys.argv) > 1:
        url = sys.argv[1]
    else:
        url = "https://www.heise.de"

    test(url)

    print("done")

rawDescription: How to detect change on webpage without reload

description: Detect change on webpage without reload


code:
dates = pd.date_range('2013-02', '2013-03', freq='D')
# create random index
rindex =  np.array(sample(xrange(len(dates)), 10))
# get 10 random dates
dates = dates[rindex]

df = pd.DataFrame({'category': ['foo','foo','foo','foo','foo',
                            'bar','bar','bar','bar','bar']
                   })
df['date'] = dates
df = df.set_index(['category', 'date'], drop=False)
df = df.sortlevel()
df['dateseq'] = df.groupby('category').date.rank().astype(int) - 1
df
# Increment each rank number by one to get the rank number of the next date
# in the group. Final-day records will get numbers that don't join, which is
# what we want.
prevdates = df['dateseq']
prevdates = prevdates + 1

# convert the index back into columns
prevdates = prevdates.reset_index()
prevdates['prev_date'] = prevdates['date']
prevdates = prevdates.drop('date',1)
prevdates
# Use merge to join the two tables, with the category and sequence number for keys.
df = pd.merge(df, prevdates, how='left', left_on=['category','dateseq'], right_on=['category','dateseq'],
      left_index=False, right_index=False, sort=True,
       copy=True)

rawDescription: Calculate a new column in pandas with transform based on a subset of the group


code:
import networkx as nx
G=nx.Graph()
G.add_node(1,color='red',size=75)
G.add_node(2,color='blue',size=33)
import json
json.dumps(G.nodes(data=True))  # all nodes
json.dumps((1,G.node[1])) # (node, data) tuple

rawDescription: How to serialize networkx (python) node to json format?

description: Serialize networkx (python) node to json format


code:
import pandas as pd
import numpy as np

df = pd.io.parsers.read_csv('temp.txt', sep = '\t')

df_agg = df.groupby('session').agg({
    'x2' : np.mean,
    'x3' : np.sum,
    'x4' : np.min,
    })

# you can apply more than one function to a column like so:

df_agg_multifunc = df.groupby('session').agg({
    'x2' : [np.mean, np.std],
    'x3' : [np.sum, np.std],
    'x4' : [np.min, np.std],
    })

rawDescription: calculate average and maximum value for subset of rows in pandas dataframe

description: Calculate average and maximum value for subset of rows in pandas dataframe


rawDescription: Change binding of listbox after defining one


code:
from bs4 import BeautifulSoup
import requests

URL = 'url here'

def download_file(url, filename, headers):
    r = requests.get(url, stream=True, headers=headers)
    with open(filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
                f.flush()

# get link and file name
response = requests.get(URL)
soup = BeautifulSoup(response.content)
a = soup.find('td', text='Download:').next_sibling.a
link = a.get('href')
filename = a.text + '.pdf'

# download file
headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36',
    'Host': 'filepi.com',  # host could be extracted from the link
    'Referer': URL
}
download_file(link, filename, headers)

rawDescription: Selenium not fully downloading files

description: Selenium not fully downloading files


code:
a = np.array([2, 0, 3, -4, -2, 7, 9])
np.maximum.accumulate(a)

rawDescription: numpy max vs amax vs maximum

description: Numpy max vs amax vs maximum


rawDescription: python statement of short if else

description: Python statement of short if else


code:
import random

def gen_random_data(inputfile):
    with open(inputfile, "r") as f:
        column_a, column_b = zip(*(line.strip().split() for line in f))

    for a, b in zip(column_a, column_b):
        r = random.sample(column_b, 2)
        while b in r: # resample if we hit a duplicate of the original pair
            r = random.sample(column_b, 2)

        yield a, r[0]
        yield a, r[1]

rawDescription: random generation of unique combination from two column

description: Random generation of unique combination from two column


code:
import StringIO
import sys

# Store App Engine's modified stdout so we can restore it later
gae_stdout = sys.stdout

# Redirect stdout to a StringIO object
new_stdout = StringIO.StringIO()
sys.stdout = new_stdout

# Run your code here, however you're doing that

# Get whatever was printed to stdout using the `print` statement (if necessary)
printed = new_stdout.getvalue()

# Restore App Engine's original stdout
sys.stdout = gae_stdout

rawDescription: In Python in Google App Engine, how do you capture output produced by the print statement?


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

def _profile(ax, x, y):
    ln, = ax.plot(x, y)
    # return the Artist created
    return ln

def profile_matrix(n, m):
    fig, ax_array = plt.subplots(n, m, sharex=True, sharey=True)
    for ax in np.ravel(ax_array):
        _profile(ax, np.arange(50), np.random.rand(50))

profile_matrix(3, 3)

rawDescription: How should I pass a matplotlib object through a function; as Axis, Axes or Figure?


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label
from kivy.uix.behaviors import ToggleButtonBehavior
from kivy.properties import BooleanProperty
from kivy.lang import Builder

Builder.load_string('''
<MyWidget>:
    SelectButton:
        state: 'down'
        text: 'on'
    SelectButton
        state: 'normal'
        text: 'off'
    SelectButton
        state: 'normal'
        text: 'off'
''')

class SelectButton(ToggleButtonBehavior, Label):
    active = BooleanProperty(False)

    def __init__(self, **kwargs):
        super(SelectButton, self).__init__(**kwargs)

        self.allow_no_selection = False

        self.group = "mygroup"
        self.color=[1,0,1,1]

        self.bind(state=self.toggle)

    def toggle(self, instance, value):
        if self.state == 'down':
            self.text = 'on'
        else:
            self.text = 'off'

class MyWidget(BoxLayout):
    pass

class MyApp(App):
    def build(self):
        return MyWidget()

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

rawDescription: Kivy ToggleButtonBehavior

description: Kivy ToggleButtonBehavior


code: 100 * ( len([x for x in l if property(x)]) / len(l) )

rawDescription: Get percentage of a list that meets criteria


code:
import csv
import sqlite3

with open('data', 'r', newline='') as infh:
    rows = list(csv.reader(infh))
    columns = zip(*rows)
    next(columns, None)  # skip the first column

    with sqlite3.connect('test.sqlite') as conn:
        cursor = conn.cursor()
        cursor.executemany('insert into test values (?, ?, ?)', columns)

rawDescription: how to insert the data from csv file into sqlite db?

description: Insert the data from csv file into sqlite db


code:
from dateutil.parser import parse
date = 'Thu, 14 Mar 2013 13:33:07 -0400'
parse(date).strftime("%Y-%m-%d %H:%M:%S")

rawDescription: Convert String In Python to insert into MySQL DB date column date


code:
db.create_collection('test',
                     storageEngine={'wiredTiger':{'configString':'block_compressor=zlib'}})

rawDescription: How to add wiredTiger in pymongo at collection level?

description: Add wiredTiger in pymongo at collection level


rawDescription: Python regular expression (regex) match comma separated number - why does this not work?


code:
def htmlentities(string):
  def char_htmlentities(c):
    return '&#%d;' % ord(c) if c in html_symbols else c

  html_symbols =  set(',\'".<>?;:')
  return ''.join(map(char_htmlentities, string))

rawDescription: How to replace punctuation with HTML entities

description: Replace punctuation with HTML entities


code:
import os
from IPython.display import Image, display
from IPython.html.widgets import interact
path = '/home/yves/to/some/images'
imgs = filter(lambda fn:fn.lower().endswith('.jpg'), os.listdir(path))
def loadimg(k):
    display(Image(open(os.path.join(path,imgs[k]),'rb').read()))
interact(loadimg ,k=(0,len(imgs)-1))

rawDescription: Is there an off the shelf IPython notebook widget for browsing images?


code:
from itertools import izip
ff = {'colors': ['yellow', 'pink', 'green'], 'names': ['banana', 'grapefruit', 'apple'], 'blah': ['a','b','c']}
[dict(izip(ff.iterkeys(), v)) for v in izip(*ff.itervalues())]

rawDescription: re-combining a list/dictionary in python

description: Re-combining a list/dictionary in python


code: frame.author[0].index('Deshpande, R.')

rawDescription: Search element in Series with Pandas

description: Search element in Series with Pandas


rawDescription: Converting a set to a list with Pandas grouopby agg function causes 'ValueError: Function does not reduce'


code:
from PyQt4 import QtCore, QtGui
import sys

class Foo(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)

        items = ['foo', 'bar', 'yib','nuz', 'pip', 'rof']
        cb = QtGui.QComboBox(self)
        for i in items:
            cb.addItem(i)

        disable = [1,4]
        for i in disable:
            j = cb.model().index(i,0)
            cb.model().setData(j, QtCore.QVariant(0), QtCore.Qt.UserRole-1)

if __name__ == "__main__":
    app = QtGui.QApplication([])
    foobar = Foo()
    foobar.show()
    sys.exit(app.exec_())

rawDescription: PyQt set enabled property of a row of QComboBox


code:
import pygame

pygame.init()
screen = pygame.display.set_mode((200, 50))

image = pygame.image.load("1.png")
shadow = pygame.image.load("2.png")

merged = image.copy()
merged.blit(shadow, (0, 0))

while True:
    screen.fill(pygame.color.Color('white'))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise

    screen.blit(image, (0,  0))
    screen.blit(shadow, (50, 0))
    screen.blit(image, (100, 0))
    screen.blit(shadow, (100, 0))
    screen.blit(merged, (150, 0))
    pygame.display.flip()

rawDescription: Merging two images in to one in pygame

description: Merging two images in to one in pygame


code:
def __init__(self, *args, **kwargs):
    super(ProfInfo, self).__init__(*args, **kwargs)
    if self.instance.pk:
        del self.field['email']

rawDescription: Showing a field in ModelForm when it is being created but hiding it when it is being updated


code: writer = csv.writer(f, lineterminator="\n")

rawDescription: python csv library always uses dos end-of-line character?

description: Python csv library always uses dos end-of-line character


code:
import os
import base64

def secure_rand(len=8):
    token=os.urandom(len)
    return base64.b64encode(token)

print(secure_rand())

rawDescription: generating promotion code using python

description: Generating promotion code using python


rawDescription: Django queryset on related field with multiple constraints


rawDescription: join two lists by interleaving

description: Join two lists by interleaving


code:
def strPolynomialFromArray(coeffs):
    return("".join([str(k)+"*x**"+str(n)+"+" for n,k in enumerate(coeffs)])[0:-1])

from numpy import *
from matplotlib.pyplot import *
x = linespace(-15,45,300) # your smooth line will be made of 300 smooth pieces
y = exec(strPolynomialFromArray(numpy.polynomial.polynomial.polyfit(xs,ys,degree)))
plt.plot(x , y)

rawDescription: Plotting confidence and prediction intervals with repeated entries


code:
import lxml.etree as ET
class HaltingTarget(object):
    def __init__(self, limit=None):
        self.done=False
        self.limit=limit
        self.counter=0
        self.result=[]
    def start(self, tag, attrib):
        if self.limit and self.counter>self.limit:
            self.done=True
            return
        if attrib:
            self.result.append(attrib)
        self.counter+=1
    def end(self, tag):
        pass
    def data(self, data):
        pass
    def comment(self, text):
        pass
    def close(self):
        return
def halt_parser():
    content='''\
        <node1>
          <Title a1="x1"> My Title </Title>
          <node2 a1="x2"> ... </node2>
          <node2 a1="x1"> ... </node2>
        </node1>
        '''
    target=HaltingTarget()
    parser=ET.XMLParser(target=target)
    for line in content.splitlines():
        parser.feed(line.strip())
        if target.done: break
    # We can't call parser.close() since the XML we've fed it is probably
    # incomplete. We don't plan to use `parser` anymore, so delete it.
    del parser
    print(target.result)
    # [{'a1': u'x1'}, {'a1': u'x2'}, {'a1': u'x1'}]

rawDescription: Is it possible to interrupt parsing large xml file in the middle with lxml target parsing interface?


code: tokens = nltk.word_tokenize(sentence)

rawDescription: How to split a sentence in Python?

description: Split a sentence in Python


rawDescription: unique values in django template

description: Unique values in django template


code:
my_task_runner = Monitor(cherrypy.engine, my_task, frequency=3)
my_task_runner.subscribe()

rawDescription: python web server and periodic tasks

description: Python web server and periodic tasks


rawDescription: Matplotlib x-axis troubles

description: Matplotlib x-axis troubles


code:
class DetRecForm(forms.ModelForm):
    fecha_recepcion = forms.DateField(widget=DateInput())

    def __init__(self, *args, **kwargs):
        super(DetRecForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.layout = Layout(
            Field('id_proveedor',
                  'anio',
                  'mes',
                  'usuario',
                  readonly=True
            ),
            Fieldset('',
                     'fecha_recepcion',
                     'num_archivos',
                     Submit('save', 'Grabar'),
                     HTML('Cancelar')
            )
        )

    def clean(self):
        cleaned_data = super(DetRecForm, self).clean()

        id_proveedor = self.cleaned_data['id_proveedor']
        num_archivos = self.cleaned_data['num_archivos']

        qs = self.Meta.model.objects.filter(id_proveedor=id_proveedor, num_archivos=num_archivos)
        if self.instance:
            qs = qs.exclude(pk=self.instance.id)
        if qs.count() > 0:
            raise forms.ValidationError(u'Such object exists!')

        return cleaned_data

    class Meta:
        model = DetalleRecepcion

rawDescription: Django form insert record instead of update record


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

grid = np.random.random((10,10))

fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, figsize=(6,10))

ax1.imshow(grid, extent=[0,100,0,1])
ax1.set_title('Default')

ax2.imshow(grid, extent=[0,100,0,1], aspect='auto')
ax2.set_title('Auto-scaled Aspect')

ax3.imshow(grid, extent=[0,100,0,1], aspect=100)
ax3.set_title('Manually Set Aspect')

plt.tight_layout()
plt.show()

rawDescription: Imshow: extent and aspect

description: Imshow: extent and aspect


code:
from fuzzywuzzy import fuzz
fuzz.partial_ratio("Harley Davidson","Hardley Davidson")
93

rawDescription: Partial String Matching with Python

description: Partial String Matching with Python


code:
import re

def cased_replacer(s):
    def replacer(m):
        if m.group(0)[0].isupper():
            return s.capitalize()
        else:
            return s
    return replacer

re.sub(r'\bfoo\b', cased_replacer('bar'), 'this is foo', flags=re.I)
# => 'this is bar'
re.sub(r'\bfoo\b', cased_replacer('bar'), 'this is Foo', flags=re.I)
# => 'this is Bar'

rawDescription: How to do a regex replace with matching case?

description: Do a regex replace with matching case


code:
import matplotlib.pyplot as plt
fig1 = plt.figure()
fig1.set_size_inches(5.5,4)
fig1.set_dpi(300)
ax = fig1.add_subplot(111)
ax.grid(True,which='both')
ax.hist(driveDistance,100)
xlabel = ax.set_xlabel('Driven Distance in km')
ax.set_ylabel('Frequency')
fig1.savefig('figure1_distance.png', bbox_extra_artists=[xlabel], bbox_inches='tight')

rawDescription: matplotlib: if I set fig height, x legend is cut off

description: Matplotlib: if I set fig height, x legend is cut off


code:
import Example
name = getattr(Example, 'new_example1').name

rawDescription: How can i use a variable name for a class path / use a variable in a reference statement? Python

description: Use a variable name for a class path / use a variable in a reference statement? Python


code:
def getCourseID(s):
    cur.execute('SELECT id FROM students WHERE name = ? ', (s, ))
    results = list(cur)
    if results:
        return results[0][0]
    return None # nothing was found...

rawDescription: Create function to retrieve ID from table


code: chr(ord('c') & ord('a'))

rawDescription: Int to boolean array python

description: Int to boolean array python


code: my_dict = {x: {y: get_dict(x, y) for y in range(b)} for x in range(a)}

rawDescription: How to form a 2D dict from a 2D list?

description: Form a 2D dict from a 2D list


code:
list1 = [('Donut', '320', '4.00'), ('Apple Pie', '200', '3.20')]

def search_info(name, list1):
    for c in list1:
        if name in c:
            return True
    return False

rawDescription: Searching inside with a group of tuples inside a list


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

x, y = np.random.random((2, 10))

fig, ax = plt.subplots()
scat = ax.scatter(x, y, s=150)

# Show the figure, then remove one point every second.
fig.show()
for _ in range(10):
    time.sleep(1)
    xy = np.delete(scat.get_offsets(), 0, axis=0)
    scat.set_offsets(xy)
    plt.draw()

rawDescription: Removing a plotted point in scatter plot - matplotlib


code:
import os,sys
folder = 'E:/.../1936342-G/test'
for filename in os.listdir(folder):
       infilename = os.path.join(folder,filename)
       if not os.path.isfile(infilename): continue
       oldbase = os.path.splitext(filename)
       newname = infilename.replace('.grf', '.las')
       output = os.rename(infilename, newname)

rawDescription: Change the file extension for files in a folder in Python


code:
import matplotlib.pyplot as plt

r = plt.Rectangle((0,0), 1, 1, edgecolor='red', facecolor='none', zorder=100)

ax = plt.gca()
ax.add_patch(r)
ax.axis([0, 1, 0, 1])

ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)

[spine.set_visible(False) for spine in ax.spines.values()]

r.set_clip_on(False)

plt.show()

rawDescription: Improper rendering at axes border in Matplotlib


code:
from collections import defaultdict

results = defaultdict(list)

with open("in_file.csv") as f:
    header = f.readline()
    for line in f:
        cols = line.split(",")
        key = ",".join(cols[0:4])
        results[key].append(cols[4])

with open("out_file.csv", "w") as f:
    f.write(header)
    for k, v in results.iteritems():
        line = '{},"{}",\n'.format(k, ", ".join(v))
        f.write(line)

rawDescription: Sort excel worksheet using python

description: Sort excel worksheet using python


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        layout = QtGui.QVBoxLayout(self)
        self.combo = QtGui.QComboBox()
        self.combo.setEditable(True)
        self.combo.addItems('One Two Three Four Five'.split())
        self.buttonOne = QtGui.QPushButton('Change (Default)', self)
        self.buttonOne.clicked.connect(self.handleButtonOne)
        self.buttonTwo = QtGui.QPushButton('Change (Blocked)', self)
        self.buttonTwo.clicked.connect(self.handleButtonTwo)
        layout.addWidget(self.combo)
        layout.addWidget(self.buttonOne)
        layout.addWidget(self.buttonTwo)
        self.changeIndex()
        self.combo.activated['QString'].connect(self.handleActivated)
        self.combo.currentIndexChanged['QString'].connect(self.handleChanged)
        self.changeIndex()

    def handleButtonOne(self):
        self.changeIndex()

    def handleButtonTwo(self):
        self.combo.blockSignals(True)
        self.changeIndex()
        self.combo.blockSignals(False)

    def changeIndex(self):
        index = self.combo.currentIndex()
        if index < self.combo.count() - 1:
            self.combo.setCurrentIndex(index + 1)
        else:
            self.combo.setCurrentIndex(0)

    def handleActivated(self, text):
        print('handleActivated: %s' % text)

    def handleChanged(self, text):
        print('handleChanged: %s' % text)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: Separate user interaction from programmical change: PyQt, QComboBox


code:
from scrapy import signals
from couchbase.exceptions import CouchbaseError
from couchbase import Couchbase

class CouchbaseStore(object):

    @classmethod
    def from_crawler(cls, crawler):
        o = cls(crawler.settings)
        crawler.signals.connect(o.spider_opened, signal=signals.spider_opened)
        crawler.signals.connect(o.spider_opened, signal=signals.spider_opened)
        return o

    def __init__(self, settings):
        self._server = settings.get('COUCHBASE_SERVER')
        self._port = settings.get('COUCHBASE_PORT', 8091)
        self._bucket = settings.get('COUCHBASE_BUCKET')
        self._password = settings.get('COUCHBASE_PASSWORD')

    def process_item(self, item, spider):
        data = {}
        for key in item.keys():
            if isinstance(item[key], datetime):
                data[key] = item[key].isoformat()
            else:
                data[key] = item[key]
        ## I assume item have a unique time field
        key = "{0}".format(item['time'].isoformat())
        self.couchbase.set(key, data)
        log.msg("Item with key % s stored in bucket %s/ node %s" %
                    (key, self._bucket, self._server),
                level=log.INFO, spider=spider)
        return item

    def spider_opened(self, spider):
        try:
            self.couchbase = Couchbase.connect(bucket=self._bucket,
                                               host=self._server,
                                               post=self._port,
                                               password=self._password)
        except CouchbaseError:
            log.msg('Connection problem to bucket %s'% self._bucket,
                     log.ERROR)
        log.msg("CouchbaseStore.spider_opened called", level=log.DEBUG)

    def spider_closed(self, spider):
        self.couchbase._close()
        log.msg("CouchbaseStore.spider_closed called", level=log.DEBUG)

rawDescription: scrapy +couchebase: middleware or pipline? how to store and retrieve data

description: Scrapy +couchebase: middleware or pipline? how to store and retrieve data


code:
z = [(i,j) for i in range(10) for j in range(10)]
z
np.array(z).reshape((10,10, 2))

rawDescription: Convert one dimensional point list in two dimensional np array


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

from __future__ import print_function  # I'm using Python 2.7 so need this

import random

class Card(object):
    '''A card object with a suit and face'''

    def __init__(self, value):
        '''Stores both the card's value and face'''
        self._value = value
        self._face = False

    # Getters and setters are not Pythonic
    # Consider using property
    def getValue(self):
        '''Get the value of the card'''
        return self._value

    def getFace(self):
        '''Get the face of the card'''
        return self._face

    def setFace(self):
        self._face = True

    def __str__(self):
        '''Override str to return printable result. Useful for debugging.'''
        return ", ".join(("Value: ", str(self._value), "Face: ", str(self._face)))

class Deck(object):

    def __init__(self, pairs):
        self._pairs = pairs
        self._cards = []
        for cards in range(self._pairs):
            c1 = Card(cards)
            self._cards.append(c1)
            c2 = Card(cards)
            self._cards.append(c2)

    def deal(self):
        if len(self) == 0:
           return None
        else:
           return self._cards.pop(0)

    def shuffle(self):
        '''Shuffles the cards.'''
        random.shuffle(self._cards)

    def __len__(self):
        '''Returns the number of cards in the deck'''
        return len(self._cards)

class Game(object):

    def __init__(self, rows, columns):
        self._deck = Deck((rows * columns)//2)
        self._rows = rows
        self._columns = columns
        self._board = []
        for row in range(self._rows):
            self._board.append([0] * self._columns)

        self.populateBoard()
        # self.revealBoard()  # For debugging

    def populateBoard(self):
        self._deck.shuffle()
        # For debugging
        # print("Deck: {}".format(map(str, self._deck._cards)))
        # self._board = [[self._deck.deal() for _ in range(self._columns)]
        #                for _ in range(self._rows)]

        # Consider renaming variables as col and row. Similar for others
        # elsewhere
        for columns in range(self._columns):
            for rows in range(self._rows):
                self._board[rows][columns] = self._deck.deal()

    def revealBoard(self):
        """For debugging. Reveal the cards for the board"""
        for rows in range(self._rows):
            for columns in range(self._columns):
                print(str(self._board[rows][columns].getValue()) + " ", end="")

            print("")

    def displayBoard(self):
        for rows in range(self._rows):
            for columns in range(self._columns):
                if self._board[rows][columns].getFace() == False:
                    print('* ', end="")
                else:
                    # print(self._board[rows][columns._getValue()])
                    print(str(self._board[rows][columns].getValue()) + " ", end="")

            print("")  # Print newline after each row

    def play(self):
        while not self.isGameOver():
            self.displayBoard()
            coord1 = raw_input('Enter coordinates for the first card: ')
            coord2 = raw_input('Enter coordinates for the second card: ')
            newCoord1 = map(int, coord1.strip().split())
            newCard1 = self._board[newCoord1[0]][newCoord1[1]].getValue()
            newCoord2 = map(int, coord2.strip().split())
            newCard2 = self._board[newCoord2[0]][newCoord2[1]].getValue()

            # Need to check that user has entered valid data here

            # newCoord1 = coord1.split(" ")
            # newCard1 = self._board[int(newCoord1[0])][int(newCoord1[1])].getValue()
            # newCoord2 = coord2.split(" ")
            # newCard2 = self._board[int(newCoord2[0])][int(newCoord2[1])].getValue()
            if newCard1 != newCard2:
                print("Not an identical pair. Found", newCard1, "at", newCoord1, "and", newCard2, "at", newCoord2)
            else:
                self._board[newCoord1[0]][newCoord1[1]].setFace()
                self._board[newCoord2[0]][newCoord2[1]].setFace()
                # self._board[int(newCoord1[0])][int(newCoord1[1])].setFace()
                # self._board[int(newCoord2[0])][int(newCoord2[1])].setFace()

        print("Game Over")
        self.displayBoard()

    def isGameOver(self):
        for rows in range(self._rows):
            if not all(card.getFace() for card in self._board[rows]):
                return False
            # for columns in range(self._columns):
            #     # If there is still one card facing down then
            #     # game is not over yet
            #     if self._board[rows][columns].getFace() == False:
            #         return False
        return True

def getUserInput(input_type):
    while True:
        try:
            val = int(raw_input("Enter number of {}: ".format(input_type)))
            if 1 <= val <= 9:
                return val
            else:
                raise ValueError
        except ValueError:
            print ("    ***Number of {} must be between 1 and 9! Try again.***".format(input_type))

def main():

    while True:
        # Force user to enter valid value for number of rows and columns
        rows = getUserInput("rows")
        columns = getUserInput("cols")

        if rows * columns % 2 == 0:
            break
        else:
            print ("    ***The value of rows X columns must be even. Try again.***")

    game = Game(rows, columns)
    game.play()

if __name__ == "__main__":
    main()

rawDescription: How to fix the int error in a matching game using python?

description: Fix the int error in a matching game using python


code:
wave_match = 9500  # wavelength for matching
index1 = np.searchsorted(wave1, wave_match)
index2 = np.searchsorted(wave2, wave_match)
match1 = filter1[index1]
match2 = filter2[index2]
scale = match1 / match2

wave12 = np.concatenate([wave1[:index1], wave2[index2:]])
filter12 = np.concatenate([filter1[:index1], scale * filter2[index2:]])

rawDescription: finding the extrapolation from the structure of one data and apply it to the other

description: Finding the extrapolation from the structure of one data and apply it to the other


code:
import os
import sys
import re

for fn in sys.argv[1:]:
    os.rename(fn, fn + '.orig')
    with open(fn + '.orig', 'rb') as fin, open(fn, 'wb') as fout:
        data = fin.read()
        data = re.sub(r'<VirtualHost.*?>.*?</VirtualHost>', '', data,
                      flags=re.DOTALL)
        fout.write(data)

rawDescription: remove a block of text in a file with python

description: Remove a block of text in a file with python


rawDescription: Why does Python have an __ne__ operator method instead of just __eq__?


code:
def save(self, *args, **kwargs):
        #this line below give to the instance slug field a slug name
        self.slug = slugify(self.name)
        #this line below save every fields of the model instance
        super(Category, self).save(*args, **kwargs)

rawDescription: SlugField in Django and overriding save

description: SlugField in Django and overriding save


code:
SCHEMA_NAMESPACE = "http://www.w3.org/2001/XMLSchema"

def add_element(schema):
    nsmap = schema.nsmap
    nsrmap = dict([(uri, prefix) for prefix, uri in nsmap.items()])
    prefix = nsrmap[SCHEMA_NAMESPACE]
    xs = lambda name: "%s:%s" % (prefix, name)
    element = schema.makeelement(xs("element"), nsmap=nsmap,
                                 attrib={'name': 'age', 'type': xs('string')})
    schema.append(element)
    return etree.tostring(schema, pretty_print=True)

rawDescription: how to set a namespace prefix in an attribute value using the lxml?

description: Set a namespace prefix in an attribute value using the lxml


code:
import numpy
from matplotlib import pyplot

x_arr = numpy.random.random(10)-0.5; y_arr = numpy.arange(10)

pyplot.hlines(y_arr, 0, x_arr, color='red')  # Stems
pyplot.plot(x_arr, y_arr, 'D')  # Stem ends
pyplot.plot([0, 0], [y_arr.min(), y_arr.max()], '--')  # Middle bar

rawDescription: Draw horizontal lines from x=0 to data points in matplotlib scatterplot (horizontal stem plot)


code:
#!/usr/bin/env python
import numpy as np
from datetime import date
x=np.array([(date(2000,1,1),0,1),
              (date(2000,1,1),1,1),
              (date(2000,1,1),1,0),
              (date(2000,1,1),0,0),
              ])

y=np.rec.fromrecords( x )

z=np.empty((len(y),len(y.dtype)),dtype='object')
for idx,field in enumerate(y.dtype.names):
   z[:,idx]=y[field]
assert (x==z).all()

rawDescription: Is there any possibilty to convert recarray to ndarray and change ndim?


code:
myFile=open('example.txt', 'wt')
myFile.write('I have written to a file.')
25
myFile.close()
myFile = open('example.txt','r')
print(myFile.read())

rawDescription: python 3 how to write to file

description: Python 3 how to write to file


code:
import cPickle
class A(object):
    def __init__(self):
        self.value=1
    def __getstate__(self):
        return self.value
    def __setstate__(self, state):
        self.value = state

class B(A):
    def __init__(self):
        super(B,self).__init__()
        self.anothervalue=2
    def __getstate__(self):
        return (super(B,self).__getstate__(), self.anothervalue)
    def __setstate__(self, state):
        superstate, self.anothervalue = state
        super(B,self).__setstate__(superstate)

b=B()
with open('a','w') as f:
    cPickle.dump(b,f)

with open('a','r') as f:
    c=cPickle.load(f)
print(b.value)
print(b.anothervalue)

rawDescription: How to best pickle/unpickle in class hierarchies if parent and child class instances are pickled

description: Best pickle/unpickle in class hierarchies if parent and child class instances are pickled


code:
amount = 0 # Used to increment your inv value
for eachKey in stock:
# Iterate through your stock, pulling values for each item you have
    try:
        amount += stock[eachKey]*prices[eachKey]
        # Try to add your total inventory price for the current iteration
        # to your total, but if that item in your stock has no price set...
    except KeyError as e:
        print("Your item {} has no price!".format(eachKey))
        # Let you know that there's no price for this item
print("Your total inventory has value ${:.2f}".format(amount))
# Print out your total inventory value

rawDescription: How do I find the total (Python)

description: Find the total (Python)


rawDescription: Python file - Want to change it to a function or a class


code:
def queens_sum(N):
    return solve(N, [0]*N, 0, N)

def solve(N, table, column, end):
    if column == end:
        return 1

    sum = 0
    for n in range(N):
        # if no other queen can attack here, place a queen in this row
        if is_available(n, table, column, N):
            table[column] = n
            # Omit the current column at the start
            sum += solve(N, table, column+1, end)
        #else: we can't place queen here, we should abort this direction
            # do nothing

    return sum

rawDescription: 8 queens puzzle - recursion using python


code:
from functools import wraps
from django.contrib.auth.models import User

from faker import Faker

def create_admin_user_and_login(func):
    @wraps(func)
    def wrapper(self):
        faker = Faker()
        username = faker.pronounceable_unique_id(length=30)
        password = faker.password()
        user = User.objects.create_user(
            username=username,
            first_name=faker.word().title(),
            last_name=faker.word().title(),
            email=faker.email(),
            password=password)
        user.is_staff = True
        user.is_superuser = True
        user.save()
        self.client.login(username=username, password=password)
        return func(self)
    return wrapper

rawDescription: Login user by User object in django

description: Login user by User object in django


code:
import subprocess

maxm = subprocess.check_output('curl -u  "Username : Password " %s' % url)

rawDescription: Store os.system( 'curl -u "username:password" "https://<url>") in a python variable to stream data in another framework?


code:
from collections import OrderedDict
from xml.etree import ElementTree as ET

tree = ET.parse("data.xml")
root = tree.getroot()

result = OrderedDict()
for folder in root.iter('Folder'):
    for placemark in folder.findall('Placemark'):
        if placemark.find('styleUrl').text == '#flightline':
            result[folder.find('name').text.strip()] = placemark.find('LineString/coordinates').text.strip()

print(result)

rawDescription: Python in XML: Getting text from grandchildren


John

password: eek hope this is secure

Title: Rule 1

Title: Rule 2

rawDescription: Interrelated requests MySQL, analogue in MongoDB


code:
import mlpy
mlpy.dtw_std([1,2,3], [4,5,6], squared=False) # Euclidean distance
mlpy.dtw_std([1,2,3], [4,5,6], squared=True) # Squared Euclidean distance

rawDescription: Two Issues about mlpy.dtw package in Python?


code:
class B(A):
    def __init__(self, some, args):
        A.__init__(self, some, args)

    @classmethod
    def fromA(cls, theA, extra=some_default):
        newB = cls(theA.some, theA.args)
        newB.extra = extra
        return newB

rawDescription: python classes/subclasses with mutually exclusive optional arguments using a instance of the superclass as a possible constructor

description: Python classes/subclasses with mutually exclusive optional arguments using a instance of the superclass as a possible constructor


code:
with open('old.csv') as oldcsv, open('new.csv', 'w') as newcsv:
    r, w = csv.reader(oldcsv), csv.writer(newcsv)
    header = next(r)
    w.writerow(['Name', 'Date', 'Reading'])
    for row in r:
        for colname, colval in zip(header[1:], row[1:]):
            w.writerow([row[0], colname, colval])

rawDescription: Reorganize a CSV so Dates are not column Headers


code:
httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)

rawDescription: Django - Template not complete rendered

description: Django - Template not complete rendered


code:
mylist = [Q(question__contains='dinner'), Q(question__contains='meal')]
Poll.objects.filter(reduce(operator.and_, mylist))
Poll.objects.filter(*mylist)

rawDescription: Dynamically build complex queries with Q() in Django


code:
import itertools
truth_values = itertools.product((True, False), repeat = 4)
people = (person_a, person_b, person_c, person_d)
all_people_and_states = [[person(truth) for person, truth in zip(people, combination)] for combination in truth_values]

rawDescription: Obtaining all possible states of an object for a NP-Complete(?) problem in Python


code:
import StringIO

# in GET(self):
web.header('Content-type', 'image/png')
buf = StringIO.StringIO()
img.save(buf, "PNG")
contents = buf.getvalue()
return contents

rawDescription: Correct way to serve a dynamic image in Python/Web.Py using PIL


rawDescription: Get the indices of the least often occuring values in numpy


code:
def sel():
   selection = "You selected the option " + str(var.get())
   label.config(text = selection)

root = Tk()
frame = Frame(root)
frame.pack()

labelframe = LabelFrame(frame, text="This is a LabelFrame")
labelframe.pack(fill="both", expand="yes")

var = IntVar()
R1 = Radiobutton(labelframe, text="Option 1", variable=var, value=1,
                  command=sel)
R1.pack( anchor = W )

R2 = Radiobutton(labelframe, text="Option 2", variable=var, value=2,
                  command=sel)
R2.pack( anchor = W )

R3 = Radiobutton(labelframe, text="Option 3", variable=var, value=3,
                  command=sel)
R3.pack( anchor = W)

label = Label(labelframe)
label.pack()

rawDescription: Radiobuttons are modifying wrong values tkinter


code:
class Test(webapp.RequestHandler):
    def get(self, upload_type):
        self.response.headers['Content-Type'] = 'text/csv'
        self.response.out.write(','.join(['a', 'cool', 'test']))

rawDescription: google app engine python download file

description: Google app engine python download file


code:
connection = DBClient()

def query():
    connection.select(...)

rawDescription: reuse class object across module

description: Reuse class object across module


code:
class MyDefaultDict(dict):
    def __init__(self, word_iterable, translate):
        self.word_set = frozenset(word_iterable)
        self.translate = translate
    def __missing__(self, key):
        if key in self.word_set:
            translated = translate(key)
            self[key] = translated
            return translated
        raise KeyError(key)

rawDescription: Fastest way to pass function on all items in list


code:
if args.prox and args.lport is None and args.rport is None:
    parser.error("--prox requires --lport and --rport.")

rawDescription: Argparse: Required argument 'y' if 'x' is present


code:
from matplotlib import units, dates
from matplotlib import pyplot as plt
from numpy import datetime64, timedelta64, arange, ndarray, dtype
from numpy.random import rand
import datetime

resolution_scale = {
    dtype('datetime64[ns]'): 1e-9,
    dtype('datetime64[us]'): 1e-6,
    dtype('datetime64[ms]'): 1e-3,
    dtype('datetime64[s]'): 1,
    dtype('datetime64[m]'): 60,
    dtype('datetime64[h]'): 60 * 60,
    dtype('datetime64[D]'): 24 * 60 * 60,
}

class Datetime64Converter(dates.DateConverter):
    @staticmethod
    def convert(values, unit, axis):
        if isinstance(values, ndarray) and issubclass(values.dtype.type, datetime64):
            return dates.epoch2num(values.view('i8') * resolution_scale[values.dtype])
        elif isinstance(values, datetime.date):
            return dates.date2num(values)
        else:
            return values

units.registry[datetime64] = Datetime64Converter

a = arange('2014-01-01', '2014-01-07', timedelta64(1, 'D'), dtype='datetime64[D]')
b = rand(len(a))
for i, r in enumerate(('ns', 'us', 'ms', 's', 'm', 'h', 'D')):
    plt.plot(a.astype('datetime64[{0}]'.format(r)), b + i, label=r)
plt.legend()
plt.show()

rawDescription: why doesn't matplotlib support datetime64

description: Why doesn't matplotlib support datetime64


code:
import collections
itemlist = [('ItemA', '0', 'Type1'), ('ItemA', '0', 'Type2'),('ItemA', '0', 'Type1'), ('ItemB', '0', 'Type2'), ('ItemA', '1', 'Type2'), ('ItemB', '2', 'Type1'), ('ItemB', '1', 'Type3'), ('ItemB', '1', 'Type1'), ('ItemC', '1', 'Type4'), ('ItemD', '1', 'Type4')]
data_dict = collections.defaultdict(int)
for attribute1, attribute2, attribute3 in itemlist:
    data_dict[(attribute1, attribute2, attribute3)] += 1
for key, value in sorted(data_dict.items()):
    attribute1, attribute2, attribute3 = key
    print("{attribute1} {attribute2}: {attribute3} = {value}".format(**locals()))

rawDescription: How to group and filter elements in list using groupby?

description: Group and filter elements in list using groupby


code:
words = [ "in", "india", "indian", "indian", "flag", "bull", "bully", "bullshit"]

Result = sorted([ (sum([ w.startswith(prefix) for w in words ]) , prefix )  for prefix in words])[::-1]

rawDescription: How to find and rank all prefixes in a list of strings?

description: Find and rank all prefixes in a list of strings


code:
from scrapy.http import HtmlResponse
from scrapy.selector import Selector

body = """

      text1
 text2

         text3

 """
response = HtmlResponse(url='http://example.com/', body=body)
sel = Selector(response)
[u''.join(paragraph.css('::text').extract()).strip() for paragraph in sel.css('div.a > p')]

rawDescription: What is the right xpath/css to use to get each paragraph text in a single string?


code: proc = subprocess.call(["C:\\absolute\\path\\some.exe ", fetched_data])

rawDescription: Subprocess in script doesn't work, when started manually it does [SOLVED]


code:
from itertools import groupby

def contains_data(ln):
    # just an example; there are smarter ways to do this
    return ln[0] not in "#\n"

with open("example") as f:
    datasets = [[ln.split() for ln in group]
                for has_data, group in groupby(f, contains_data)
                if has_data]

rawDescription: How can I split a text file based on comment blocks in Python?

description: Split a text file based on comment blocks in Python


code:
l=[None ,3]
min(i for i in l if i is not None)

rawDescription: Python: min(None, x)

description: Python: min(None, x)