rawDescription: Checkbox input using python mechanize

description: Checkbox input using python mechanize


code:
def bin_convert(x, count=8):
    return "".join(map(lambda y:str((x>>y)&1), range(count-1, -1, -1)))

rawDescription: Why does this Python 3.3 code not work? digc not defined


code:
from ast import literal_eval
stringOfLists1 = '[["Social","Food and Dining","Restaurants","American"], ["Social","Food and Dining","Restaurants","Pizza"]]'
lst = literal_eval(stringOfLists1)
lst
type(lst)
type(lst[0])
type(lst[0][3])

rawDescription: Convert a string with list syntax into list(s)


rawDescription: Python: Remove Duplicate Tuples from List if They are Exactly the Same Including Order Of Items


rawDescription: Remove non-letter characters from beginning and end of a word


code:
def mutations(word, hamming_distance, charset='ATCG'):
    for indices in itertools.combinations(range(len(word)), hamming_distance):
        for replacements in itertools.product(charset, repeat=hamming_distance):
            mutation = list(word)
            for index, replacement in zip(indices, replacements):
                mutation[index] = replacement
            yield "".join(mutation)

rawDescription: Inverse of Hamming Distance

description: Inverse of Hamming Distance


code:
newlines = {}
i = 0
while i < n:
   newlines.setdefault(numbersbytwo, [])
   newlines.setdefault(numbersbyfive, [])
   newlines['numbersbytwo'].append(i*2)
   newlines['numbersbyfive'].append(i*5)
   i += 1

rawDescription: Declaring and appending a list within a dictionary in one line


code:
def newton(f, fprime, firstguess, epsilon):
    x = firstguess
    while abs(f(x)) > epsilon:
        x = x - (f(x) / fprime(x))
    return x

rawDescription: Fastest way to solve long polynomial with lots of different powers


code: res = service.data().ga().get(ids='ga:' + profile_id, start_date='2014-01-01', end_date=t, metrics='ga:sessions', dimensions='ga:browser',sort='-ga:sessions' , max_results='5' ).execute()

rawDescription: How do I get dimension data from Analytics reporting api

description: Get dimension data from Analytics reporting api


code:
def createWSSecurityHeader(username,password):
    # Namespaces
    wsse = ('wsse', 'http://schemas.xmlsoap.org/ws/2002/07/secext')

    # Create Security Element
    security = Element('Security', ns=wsse)

    # Create UsernameToken, Username/Pass Element
    usernametoken = Element('UsernameToken', ns=wsse)
    uname = Element('Username', ns=wsse).setText(username)
    passwd = Element('Password', ns=wsse).setText(password)

    # Add Username and Password elements to UsernameToken element
    usernametoken.insert(uname)
    usernametoken.insert(passwd)

    security.insert(usernametoken)
    return security

rawDescription: Add Namespace to the default WSSE Security Object in Suds


code: a = [b + 4 if b < 0 else b for b in a]

rawDescription: modify list element with list comprehension in python

description: Modify list element with list comprehension in python


code:
import numpy as np
a = np.array([ np.nan,   2.5,   3.,  np.nan,   4.,   5.])
print(np.nanargmin(a))
# 1

rawDescription: Is there a better way of making numpy.argmin() ignore NaN values


code:
class BrokerClient(object):
    clients = []

    @staticmethod
    def instance():
        if not hasattr(BrokerClient, '_instance'):
            BrokerClient._instance = BrokerClient()
        return BrokerClient._instance

    def __init__(self):
        self.connection = BrokerConnection(settings.BROKER_URL)
        self.consumer = Consumer(self.connection.channel(), [queue, ], callbacks=[self.process_task])
        self.consumer.consume()
        io_loop = tornado.ioloop.IOLoop.instance()
        for sock, handler in self.connection.eventmap.items():
            def drain_nowait(fd, events):
                handler()
            io_loop.add_handler(sock.fileno(), drain_nowait, l.READ | l.ERROR)

    def process_task(self, body, message):
        #something
        message.ack()

    def add_client(self, client):
        self.clients.append(client)

    def remove_client(self, client):
        self.clients.remove(client)

rawDescription: Kombu in non-blocking way

description: Kombu in non-blocking way


rawDescription: How to copy data in Python

description: Copy data in Python


code:
from unidecode import unidecode
unidecode('ẚ')

rawDescription: Python, Convert non-ascii to ascii based on look-up dictionary


code:
def add(root, path, value):
    for part in path[:-1]:
        root = root.setdefault(part, {})
    root[path[-1]] = value

def parse(s):
    videos = {}
    for key, value in parse_qsl(s):
        parts = filter(None, re.split('[\[\]]', key))
        insert(videos, parts[1:], value)
    return videos

rawDescription: Python parsing query string to list

description: Python parsing query string to list


code:
global bookStartLine
global bookEndLine

def grabLine(currentUrl):
    ### blah blah defines what lines is
    currentBookStartLine,currentBookEndLine = False,False #needed to define these before use below
    for index,line in enumerate(lines,start=1): #start = 1 so index gets 1 on first iteration
        if "*** START OF THE PROJECT" in line:
            currentBookStartLine = index
        if "*** END OF THE PROJECT" in line:
            currentBookEndLine = index

    bookStartLine = currentBookStartLine
    bookEndLine   = currentBookEndLine

grabLine('http://www.gutenberg.org/cache/epub/768/pg768.txt') #grabLine not grabline

print(bookStartLine)
print(bookEndLine)

rawDescription: What wrong with this code?

description: What wrong with this code


code: lexer = lexers.get_lexer_by_name("python", stripnl=False)

rawDescription: Preserving whitespace with Pygments

description: Preserving whitespace with Pygments


code:
with open('the.csv') as f:
    next(f)
    list_of_rows = list(csv.reader(f))

listA = [row[0] for row in list_of_rows]
listB = [int(row[1]) for row in list_of_rows]

rawDescription: Taking each column as its own list

description: Taking each column as its own list


code:
import csv
import collections

data = csv.reader(open('player.csv', 'rb'), delimiter=';')
next(data)  # Skip the header

sizes = []
players_count = collections.Counter()
for name, size in data:
    players_count.update([name])
    sizes.append(float(size))

total = sum(sizes)
average = total / len(sizes)

with open('result.txt', 'wb') as f:
    f.write('Total size = {}\n'.format(total))
    f.write('Average = {}\n'.format(average))

    # Output count of players, sorted by count in decending order
    f.write('\nCount Player\n')
    for player, count in players_count.most_common():
        f.write('{:5} {}\n'.format(count, player))

rawDescription: Make calculation on one column in CSV file and add it into the file using python


code:
from collections import defaultdict, deque

with open('second_csv.csv') as f:
    next(f) #skip header
    dic = defaultdict(deque)
    for num1,alpha1,num2 in csv.reader(f, delimiter=','):
        dic[num1, alpha1].append(num2)

with open('first_csv.csv') as f, open('out.csv', 'wb') as fout:
    next(f) #skip header
    csv_out = csv.writer(fout)
    for num,alpha in csv.reader(f, delimiter=','):
        try:
            num2 = dic[num,alpha].popleft()
            csv_out.writerow([num,alpha,num2])
        except IndexError:
            csv_out.writerow([num,alpha])

rawDescription: Comparing Two CSV in Python

description: Comparing Two CSV in Python


code:
from lib2to3.refactor import RefactoringTool, get_fixers_from_package
"""assume `files` to a be a list of all filenames you want to convert"""
r = RefactoringTool(get_fixers_from_package('lib2to3.fixes'))
r.refactor(files, write=True)

rawDescription: python 2to3 manual modification

description: Python 2to3 manual modification


code:
def some_view(request):
    context = {
        'a': 5
    }

    return render_to_response(
        'my_template.html',
        context,
        context_instance=RequestContext(request)
    )

rawDescription: Passing a variable from view to HTML

description: Passing a variable from view to HTML


code:
animals = {}
animals['cat'] = objectOne()
animal = 'cat'
animals[animal].funct1()

rawDescription: PYTHON Add the contents of a string variable to the beginning of a function?


code:
def returnDicts(args=None):
    dicts = {
        'a': {'a1':1, 'a2':2},
        'b': {'b1':1, 'b2':2},
        'c': {'c1':1, 'c2':2},
        'd': {'d1':1, 'd2':2}
    }
    if args is None:
        args = ['a', 'b', 'c', 'd']
    return [dicts[d] for d in args]
returnDicts()
returnDicts(['a'])
returnDicts(['a', 'b'])

rawDescription: Returning multiple dictionaries from python function based on calling argument


rawDescription: How do I get python to display xbar? A line over the letter x

description: Get python to display xbar? A line over the letter x


code:
self.canvas.show() # insert this line
self.canvas.get_tk_widget().update_idletasks()

rawDescription: color plot animation with play, pause, stop cabability using Tkinter with pylab/matplotlib embedding: can't update figure/canvas?

description: Color plot animation with play, pause, stop cabability using Tkinter with pylab/matplotlib embedding: can't update figure/canvas


code:
import numpy as np

n_rows = 100
n_columns = 100000
n_rows_to_drop = 20
n_rows_to_add = 10

# Init huge array
data = np.random.rand(n_rows, n_columns)

# Some rows we drop
to_drop = np.random.randint(0, n_rows, n_rows_to_drop)
to_drop = np.unique(to_drop)

# Some rows we add
new_data = np.random.rand(n_rows_to_add, n_columns)

# Start replacing rows with new rows
data[to_drop[:n_rows_to_add]] = new_data

# These should still be dropped
to_drop = to_drop[:n_rows_to_add]

# Make a list of row indices to keep, last rows first
to_keep = np.setdiff1d(np.arange(n_rows), to_drop, assume_unique=True)[-n_rows_to_add:]

# Replace rows to drop with rows at the end of the matrix
for to_drop_i, to_keep_i in zip(to_drop, to_keep):
    data[to_drop_i] = data[to_keep_i]

# Resize matrix in memory
data.resize(n_rows - n_rows_to_drop + n_rows_to_add, n_columns)

rawDescription: Efficient combined in-place adding/removing of rows of a huge 2D numpy array


code:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

data = np.loadtxt("example.txt", delimiter=",")
x = data[:,0]
y = data[:,1]

fig = plt.figure()
ax = fig.add_subplot(111)
line, = ax.plot([],[], '-')
line2, = ax.plot([],[],'--')
ax.set_xlim(np.min(x), np.max(x))
ax.set_ylim(np.min(y), np.max(y))

def animate(i,factor):
    line.set_xdata(x[:i])
    line.set_ydata(y[:i])
    line2.set_xdata(x[:i])
    line2.set_ydata(factor*y[:i])
    return line,line2

K = 0.75 # any factor
ani = animation.FuncAnimation(fig, animate, frames=len(x), fargs=(K,),
                              interval=100, blit=True)
plt.show()

rawDescription: Passing arguments in animation.FuncAnimation()


code:
import sys
from PyQt4 import QtCore, QtGui, QtSvg
from PyQt4.QtWebKit import QGraphicsWebView
if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)

    scene = QtGui.QGraphicsScene()
    view = QtGui.QGraphicsView(scene)

    br = QtSvg.QGraphicsSvgItem("C:\my_interactive_svg.svg").boundingRect()

    webview = QGraphicsWebView()
    webview.load(QtCore.QUrl("C:\my_interactive_svg.svg"))
    webview.setFlags(QtGui.QGraphicsItem.ItemClipsToShape)
    webview.setCacheMode(QtGui.QGraphicsItem.NoCache)
    webview.resize(br.width(), br.height())

    scene.addItem(webview)
    view.resize(br.width()+10, br.height()+10)
    view.show()
    sys.exit(app.exec_())

rawDescription: Alternative for scripting in SVG for using in python


rawDescription: Rank elements in a data frame while keeping index


code:
import os
import sys
import Tkinter as tkinter

import gobject
import gst

def on_sync_message(bus, message, window_id):
        if not message.structure is None:
            if message.structure.get_name() == 'prepare-xwindow-id':
                image_sink = message.src
                image_sink.set_property('force-aspect-ratio', True)
                image_sink.set_xwindow_id(window_id)

gobject.threads_init()

window = tkinter.Tk()
window.geometry('500x400')

video = tkinter.Frame(window, bg='#000000')
video.pack(side=tkinter.BOTTOM,anchor=tkinter.S,expand=tkinter.YES,fill=tkinter.BOTH)

window_id = video.winfo_id()

player = gst.element_factory_make('playbin2', 'player')
player.set_property('video-sink', None)
player.set_property('uri', 'file://%s' % (os.path.abspath(sys.argv[1])))
player.set_state(gst.STATE_PLAYING)

bus = player.get_bus()
bus.add_signal_watch()
bus.enable_sync_message_emission()
bus.connect('sync-message::element', on_sync_message, window_id)

window.mainloop()

rawDescription: Way to play video files in Tkinter?

description: Way to play video files in Tkinter


code:
import csv

thedata = [
['object', 'weight', 'width', 'favorite color'],
[1, 5.0, 4.0001, 'blue'],
[2, 5.4, 45.444, 'green']
]

myfile = 'object_values.txt'

for object_values in thedata:
    with open(myfile, 'a+') as thefile:
        wr = csv.writer(thefile)
        wr.writerow(object_values)

rawDescription: Simplest and easiest way of storing sortable data


code:
from collections import defaultdict
d = defaultdict(int)
for m, c in data:
    d[m] += c
list(d.items())

rawDescription: Python - Addition and merging with an array


code:
import csv
with open('test.csv', "r") as f:
    reader = csv.reader(f)
    result = {}

    for row in reader:
        key = row[0]
        result[key] = row[1:]

    print(result)

rawDescription: In python, how do I write columns of a CSV file to a dictionary?


code:
import wx
import wx.lib.masked as masked

########################################################################
class MyPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        self.mainSizer = wx.BoxSizer(wx.VERTICAL)

        text1 = wx.StaticText( self, -1, "12-hour format:", size=(150,-1))
        self.time12 = masked.TimeCtrl( self, -1, name="12 hour control" )
        h = self.time12.GetSize().height
        spin1 = wx.SpinButton( self, -1, wx.DefaultPosition, (-1,h), wx.SP_VERTICAL )
        self.time12.BindSpinButton( spin1 )
        self.addWidgets([text1, self.time12, spin1])

        text2 = wx.StaticText( self, -1, "24-hour format:")
        spin2 = wx.SpinButton( self, -1, wx.DefaultPosition, (-1,h), wx.SP_VERTICAL )
        self.time24 = masked.TimeCtrl(
                        self, -1, name="24 hour control", fmt24hr=True,
                        spinButton = spin2
                        )
        self.addWidgets([text2, self.time24, spin2])

        text3 = wx.StaticText( self, -1, "No seconds\nor spin button:")
        self.spinless_ctrl = masked.TimeCtrl(
                                self, -1, name="spinless control",
                                display_seconds = False
                                )
        self.addWidgets([text3, self.spinless_ctrl])

        self.SetSizer(self.mainSizer)

    #----------------------------------------------------------------------
    def addWidgets(self, widgets):
        """"""
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        for widget in widgets:
            if isinstance(widget, wx.StaticText):
                sizer.Add(widget, 0, wx.ALL|wx.CENTER, 5),
            else:
                sizer.Add(widget, 0, wx.ALL, 5)
        self.mainSizer.Add(sizer)

########################################################################
class MyFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Spinner Demo")
        panel = MyPanel(self)
        self.Show()

if __name__ == "__main__":
    app = wx.App(False)
    f = MyFrame()
    app.MainLoop()

rawDescription: How to add and edit time in a textctrl in wxpython?

description: Add and edit time in a textctrl in wxpython


code:
import sys
class_module = sys.modules[instance.__class__.__module__]

rawDescription: How to access class module from object instance?

description: Access class module from object instance


code:
from mpl_toolkits.mplot3d.axes3d import Axes3D
import matplotlib.pyplot as plt
fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

datasets = [{"x":[1,2,3], "y":[1,4,9], "z":[0,0,0], "colour": "red"} for _ in range(6)]

for dataset in datasets:
    ax.plot(dataset["x"], dataset["y"], dataset["z"], color=dataset["colour"])

plt.show()

rawDescription: matplotlib plotting multiple lines in 3D

description: Matplotlib plotting multiple lines in 3D


code: dict(zip(f2.func_code.co_freevars, (c.cell_contents for c in f2.func_closure)))

rawDescription: Reflect / Inspect closed-over variables in Python


code:
vertices = []
for i in range(3):                         # Do this 3 times
    x = random.randint(0, 500)             # Create a random x value
    y = random.randint(0, 500)             # Create a random y value
    vertices.append(graphics.Point(x, y))  # Add the (x, y) point to the vertices
triangle = graphics.Polygon(vertices)      # Create the triangle
triangle.setFill(colour)
triangle.draw(win)

rawDescription: How to Draw a triangle shape in python ?

description: Draw a triangle shape in python


code:
class Current(models.Model):
    field1 = models.IntegerField()
    field2 = models.IntegerField()
    field3 = models.IntegerField()

    def save(self, *args, **kwargs):
        self.field3 = self.field1 + self.field2
        super(Current, self).save(*args, **kwargs)

rawDescription: Django infer a field from other fields

description: Django infer a field from other fields


rawDescription: Django: Get flat value for an item in a QuerySet / dictionary


code:
import numpy as np
fl = np.zeros((5, 3))
labels = np.random.random_integers(0, 2, 5)
fl[range(0, 5), labels] = 1

rawDescription: how to assign a value to numpy array in specific rows and cols

description: Assign a value to numpy array in specific rows and cols


code:
class Auction:
    def __init__(self, manager,auction):
        self.id = auction["id"]
        self.manager = manager
        self.some_data = auction["some_data"]
    def buy(self):
          return self.manager.buy()

class Manager(Auth):
    """used for search auctions, for example"""
    def __init__(self, username, password):
        Auth.__init__(self, username, password)
    def pile(self):
        y = self.some_search_into_a_server()
        for x in y:
            yield Auction(self,x)
    def buy(self):
        """buy method for using by auction"""
        pass

manager = Manager('user@example.com', 'a_very_secure_password')
for auction in manager.pile():
    auction.buy()

rawDescription: Inheritante and class problems in python


code:
var = [[1, 2, 3], [2], [1, 2, 3], [5, 6]]
[i for i in itertools.product(*var) if len(i) == len(set(i))]
var = [[1,2,3,4], [5]]
[i for i in itertools.product(*var) if len(i) == len(set(i))]

rawDescription: List all combinations of a list of lists where no two elements are the same


code:
for row in store:
    if row[0] == item_id:
        store.remove(row.iter)
        break

rawDescription: How to search through a gtk.ListStore in pyGTK and remove elements?

description: Search through a gtk.ListStore in pyGTK and remove elements


code:
with _localimport('lib', eggs=True) as importer:
    import some_package
assert 'some_package' not in sys.modules
assert 'some_package' in importer.modules

rawDescription: Import module from directory without touching sys.path


code:
structure = {}
structure["parent1"] = {}
structure["parent1"]["variable1"] = 23;
structure["parent1"]["variable2"] = 19;
structure["parent1"]["variable3"] = 19;
structure["parent2"] = {}
structure["parent2"]["variable1"] = 10;
structure["parent2"]["variable2"] = 11;

rawDescription: Matlab structure in Python

description: Matlab structure in Python


code:
def get_nearest(points, coord):
    """Return closest point to coord from points"""
    dists = [(pow(point[0] - coord[0], 2) + pow(point[1] - coord[1], 2), point)
              for point in points]              # list of (dist, point) tuples
    nearest = min(dists)
    return nearest[1]  # return point only

next_point = points.pop(0)  # get first point
line_path = []
line_path.append(next_point)

while len(points) > 1:
    next_point = get_nearest(points, next_point)
    line_path.append(next_point)
    points.remove(next_point)

line_path.extend(points)  # add last point

rawDescription: Closest point from certain 2D point to list of 2D points Python


rawDescription: implement an object that holds x seats in y rows

description: Implement an object that holds x seats in y rows


code:
from collections import Counter
def isAnagram(s1, s2):
    return Counter(s1) == Counter(s2)

rawDescription: Understanding a linear runtime implementation of anagram detection


code:
from textblob import TextBlob
import sys
import glob

def optimistic():
    path = 'Download/textfiles/*.txt'
    files = glob.glob(path)
    max_sent = 0
    max_name = ''
    for name in files:
         with open(name, 'r') as f:
            text = f.read()
            sentiment = TextBlob(text).sentiment
            if sentiment > max_sent:
                max_sent = sentiment
                max_name = name
    return max_name

rawDescription: Python - reading all files in a directory and then returning the max value based on some function


code:
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(style="whitegrid")

titanic = sns.load_dataset("titanic")

g = sns.factorplot("class", "survived", "sex",
                   data=titanic, kind="bar",
                   size=6, palette="muted",
                   legend=False)
g.despine(left=True)
plt.legend(loc='upper left')
g.set_ylabels("survival probability")

rawDescription: Move seaborn plot legend to a different position?


code:
import Tkinter as tk

root=tk.Tk()
f1 = tk.Frame(width=200, height=200, background="red")
f2 = tk.Frame(width=100, height=100, background="blue")

f1.pack(fill="both", expand=True, padx=20, pady=20)
f2.place(in_=f1, anchor="c", relx=.5, rely=.5)

root.mainloop()

rawDescription: How do I center a frame within a frame in Tkinter?

description: Center a frame within a frame in Tkinter


code:
L = [1, 1, 1, 2, 3, 3, 3, 3, 4, 4]
[list(g) for i, g in itertools.groupby(L)]
L2 = ['apple', 'aardvark', 'banana', 'coconut', 'crow']
[list(g) for i, g in itertools.groupby(L2, operator.itemgetter(0))]

rawDescription: Splitting a list of arbitrary size into N-not-equal parts


code:
# ... snip ...
class SearchField(core.StringField):
    """
    Represents an ``<input type="search">``.
    """
    widget = widgets.SearchInput()

class TelField(core.StringField):
    """
    Represents an ``<input type="tel">``.
    """
    widget = widgets.TelInput()

class URLField(core.StringField):
    """
    Represents an ``<input type="url">``.
    """
    widget = widgets.URLInput()
# ... snip ...

rawDescription: flask-wtf field rendered examples

description: Flask-wtf field rendered examples


code:
def sync_x_with_y(self, axis):
    # check whether the axes orientation is not coherent
    if (axis.get_ylim()[0] > axis.get_ylim()[1]) != (self.get_xlim()[0] > self.get_xlim()[1]):
        self.set_xlim(axis.get_ylim()[::-1], emit=False)
    else:
        self.set_xlim(axis.get_ylim(), emit=False)

rawDescription: Update the x-axis of a matplotlib subplot according to the y-axis of a different subplot


code: max([y[i] for i in range(len(y)) if x[i] > 3 and y[i]>2])

rawDescription: how to translate matlab function max(y(x>3)>2) to numpy in single line

description: Translate matlab function max(y(x>3)>2) to numpy in single line


code:
import re

data = '<your input data as above>' # or open('data.txt').read()
results = map(lambda m: (m[0], m[1].strip().splitlines()),
    re.findall('^([^\n]+):\n((?:[^\n]+\n)*)\n', data, re.M))

for dirname, files in results:
    f = open(dirname.replace('/', '')+'.txt', 'w')
    for line in files:
        f.write(line + '\n')
    f.close()

rawDescription: Python: How do i split the file?

description: Python: How do i split the file


rawDescription: Boost::Python: embed and load Boost::Python modules and converters


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

er = 6378100*10#m             #earth radius
mr = 1737400*10#m             #moon radius
em = 5.97219*10**24#kg        #earth mass
mm = 7.34767309*10**22#kg     #moon mass
d = 384400000#m               #distance earth-moon
G = 6.67384*10**(-11)         #gravity constant
mv = -1023#m/s                #Moon velocity
nts = 10000                   #no. time steps

def circle(r, h, k, a):
    x = r*math.cos(a)+h
    y = r*math.sin(a)+k
    #### CHANGED
    moony.center = x,y

def simData():
    tmax = 10000*nts
    ts = 10000
    x = 0.0
    t = 0.0
    while t < tmax:
        n = 0
        for i in range(120):
            circle(mr, d, mv*t, n)
            n = n + math.pi/60
        t = t + ts
        yield x, t

def simPoints(simData):
    x, t = simData[0], simData[1]
    time_text.set_text(time_template%(t))
    line.set_data(t, x)
    return line, time_text

fig = plt.figure()
ax = plt.axes(xlim=(-430000000, 430000000), ylim=(-430000000, 430000000))

#### CHANGED: a grey circle of moony dimensions to be moved around
moony = plt.Circle((0,0), mr, facecolor=(.8,.8,.8))
ax.add_artist(moony)

time_template = 'Time = %.1f s'    # prints running simulation time
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)

ani = animation.FuncAnimation(fig, simPoints, simData, blit=False,\
     interval=10, repeat=True)
plt.show()

rawDescription: Python Matplotlib animation frames are overlapping


code:
def start_subquery(lexer):
    lexer.code_start = lexer.lexpos        # Record the starting position
    lexer.level = 1
    lexer.begin("subquery")

def end_subquery(lexer):
    lexer.begin("INITIAL")

def get_subquery(lexer):
    value = lexer.lexdata[lexer.code_start:lexer.code_end-1]
    lexer.lineno += value.count('\n')
    return value

@lex.TOKEN(r"\(")
def t_subquery_OPAR(t):
    lexer.level += 1

@lex.TOKEN(r"\)")
def t_subquery_CPAR(t):
    lexer.level -= 1
    if lexer.level == 0:
        lexer.code_end = lexer.lexpos        # Record the ending position
        return t

@lex.TOKEN(r".")
def t_subquery_anychar(t):
    pass

def p_value_subquery(p):
    """
    value : check_subquery_start OPAR check_subquery_end CPAR
    """
    p[0] = "( " + get_subquery(p.lexer) + " )"

def p_check_subquery_start(p):
    """
    check_subquery_start :
    """
    # Here last_token would be yacc's lookahead.
    if last_token.type == "OPAR":
        start_subquery(p.lexer)

def p_check_subquery_end(p):
    """
    check_subquery_end :
    """
    # Here last_token would be yacc's lookahead.
    if last_token.type == "CPAR":
        end_subquery(p.lexer)

last_token = None

def p_error(p):
    global subquery_retry_pos
    if p is None:
        print >> sys.stderr, "ERROR: unexpected end of query"
    else:
        print >> sys.stderr, "ERROR: Skipping unrecognized token", p.type, "("+ \
                p.value+") at line:", p.lineno, "and column:", find_column(p.lexer.lexdata, p)
        # Just discard the token and tell the parser it's okay.
        yacc.errok()

def get_token():
    global last_token
    last_token = lexer.token()
    return last_token

def parse_query(input, debug=0):
    lexer.input(input)
    return parser.parse(input, tokenfunc=get_token, debug=0)

rawDescription: Controlling Python PLY lexer states from parser


code:
i = 0 # <--- global variable

def next():
    global i # <--- declare `i` as a global variable
    if (i<4):
        i= i + 1

    print (List[i])

rawDescription: How to increment list index in a function

description: Increment list index in a function


code:
import operator
from PySide.QtCore import *
from PySide.QtGui import *
from urllib import request
from lxml import etree
import sched, time

s = sched.scheduler(time.time, time.sleep)

def getData():
    url = "" # Removed url
    response = request.urlopen(url)
    html_parser = etree.HTMLParser()
    tree = etree.parse(response, html_parser)
    data_sets = tree.xpath("//div[@class='dataList']")
    headers = ['Company Name','LTP','Change', '%Chg', 'Volume (lacs)', '30 Days % Change','365 Days % Change']
    share_results = []

    for element in data_sets:
        result_list = []
        share_comp_name = element.xpath('ul/li/p/a')[0]
        result_list.append(share_comp_name.text)
        share_value_list = element.xpath('ul/li/span')
        counter = 0
        for data in share_value_list:
            result_list.append(float(str(data.text)))
            counter += 1
        share_results.append(tuple(result_list))
    return headers, share_results

class MyWindow(QWidget):

    def __init__(self, *args):
        QWidget.__init__(self, *args)
        self.setGeometry(300, 200, 550, 450)
        self.setWindowTitle("Top Shares")
        self.table_model = MyTableModel(self)
        self.table_view = QTableView()
        self.table_view.setModel(self.table_model)
        font = QFont("Verdana", 9)
        self.table_view.setFont(font)
        self.table_view.resizeColumnsToContents()
        self.table_view.setSortingEnabled(True)
        layout = QVBoxLayout(self)
        layout.addWidget(self.table_view)
        self.setLayout(layout)
        # Added timer
        timer = QTimer(self)
        timer.timeout.connect(self.show_data)
        timer.start(10000)

    def show_data(self):
        self.table_model = MyTableModel(self)
        self.table_view.setModel(self.table_model)

class MyTableModel(QAbstractTableModel):
    class_counter = 0
    def __init__(self, parent, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.header, self.mylist = getData()

    def rowCount(self, parent):
        return len(self.mylist)

    def columnCount(self, parent):
        return len(self.header)

    def data(self, index, role):
        if not index.isValid():
            return None
        elif role != Qt.DisplayRole:
            return None
        return self.mylist[index.row()][index.column()]

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self.header[col]
        return None

    def sort(self, col, order):
        """sort table by given column number col"""
        self.emit(SIGNAL("layoutAboutToBeChanged()"))
        self.mylist = sorted(self.mylist,
            key=operator.itemgetter(col))
        if order == Qt.DescendingOrder:
            self.mylist.reverse()
        self.emit(SIGNAL("layoutChanged()"))

app = QApplication([])
win = MyWindow()
win.show()
win.repaint()
win.update()
app.exec_()

rawDescription: How to auto refresh table view in PySide?

description: Auto refresh table view in PySide


code:
def get_first_prime(values):
    for i in values:
        if is_prime(i):
            return i

rawDescription: Getting First Prime in a List of Random Numbers


code:
fig = plt.figure()

# a 2x2 grid and create the fourth (bottom-right) one
ax1 = fig.add_subplot(2,2,4)
ax1.text(.5,.5,'ax1')

# a 2x1 grid and create the top one
ax2 = fig.add_subplot(2,1,1)
ax2.text(.5,.5,'ax2')

rawDescription: Matplotlib: What's the meaning of the 3-digit parameter given to Figure.add_subplot()?


code:
@property
def myattr(self):
    """This is the doc string."""
    return self._half * 2

@myattr.setter
def myattr(self, value):
    self._half = value / 2

@myattr.deleter
def myattr(self):
    del self._half

rawDescription: deprecation of apply decorator

description: Deprecation of apply decorator


code:
# File: ScrollTest.py
# coding: ASCII
"""
Interatively zoom plots together, but permit them to scroll independently.
"""
from matplotlib import pyplot
import sys

def _get_limits( ax ):
    """ Return X and Y limits for the passed axis as [[xlow,xhigh],[ylow,yhigh]]
    """
    return [list(ax.get_xlim()), list(ax.get_ylim())]

def _set_limits( ax, lims ):
    """ Set X and Y limits for the passed axis
    """
    ax.set_xlim(*(lims[0]))
    ax.set_ylim(*(lims[1]))
    return

def pre_zoom( fig ):
    """ Initialize history used by the re_zoom() event handler.
        Call this after plots are configured and before pyplot.show().
    """
    global oxy
    oxy = [_get_limits(ax) for ax in fig.axes]
    # :TODO: Intercept the toolbar Home, Back and Forward buttons.
    return

def re_zoom(event):
    """ Pyplot event handler to zoom all plots together, but permit them to
        scroll independently.  Created to support eyeball correlation.
        Use with 'motion_notify_event' and 'button_release_event'.
    """
    global oxy
    for ax in event.canvas.figure.axes:
        navmode = ax.get_navigate_mode()
        if navmode is not None:
            break
    scrolling = (event.button == 1) and (navmode == "PAN")
    if scrolling:                   # Update history (independent of event type)
        oxy = [_get_limits(ax) for ax in event.canvas.figure.axes]
        return
    if event.name != 'button_release_event':    # Nothing to do!
        return
    # We have a non-scroll 'button_release_event': Were we zooming?
    zooming = (navmode == "ZOOM") or ((event.button == 3) and (navmode == "PAN"))
    if not zooming:                 # Nothing to do!
        oxy = [_get_limits(ax) for ax in event.canvas.figure.axes]  # To be safe
        return
    # We were zooming, but did anything change?  Check for zoom activity.
    changed = None
    zoom = [[0.0,0.0],[0.0,0.0]]    # Zoom from each end of axis (2 values per axis)
    for i, ax in enumerate(event.canvas.figure.axes): # Get the axes
        # Find the plot that changed
        nxy = _get_limits(ax)
        if (oxy[i] != nxy):         # This plot has changed
            changed = i
            # Calculate zoom factors
            for j in [0,1]:         # Iterate over x and y for each axis
                # Indexing: nxy[x/y axis][lo/hi limit]
                #           oxy[plot #][x/y axis][lo/hi limit]
                width = oxy[i][j][1] - oxy[i][j][0]
                # Determine new axis scale factors in a way that correctly
                # handles simultaneous zoom + scroll: Zoom from each end.
                zoom[j] = [(nxy[j][0] - oxy[i][j][0]) / width,  # lo-end zoom
                           (oxy[i][j][1] - nxy[j][1]) / width]  # hi-end zoom
            break                   # No need to look at other axes
    if changed is not None:
        for i, ax in enumerate(event.canvas.figure.axes): # change the scale
            if i == changed:
                continue
            for j in [0,1]:
                width = oxy[i][j][1] - oxy[i][j][0]
                nxy[j] = [oxy[i][j][0] + (width*zoom[j][0]),
                          oxy[i][j][1] - (width*zoom[j][1])]
            _set_limits(ax, nxy)
        event.canvas.draw()         # re-draw the canvas (if required)
        pre_zoom(event.canvas.figure)   # Update history
    return
# End re_zoom()

def main(argv):
    """ Test/demo code for re_zoom() event handler.
    """
    import numpy
    x = numpy.linspace(0,100,1000)      # Create test data
    y = numpy.sin(x)*(1+x)

    fig = pyplot.figure()               # Create plot
    ax1 = pyplot.subplot(211)
    ax1.plot(x,y)
    ax2 = pyplot.subplot(212)
    ax2.plot(x,y)

    pre_zoom( fig )                     # Prepare plot event handler
    pyplot.connect('motion_notify_event', re_zoom)  # for right-click pan/zoom
    pyplot.connect('button_release_event',re_zoom)  # for rectangle-select zoom

    pyplot.show()                       # Show plot and interact with user
# End main()

if __name__ == "__main__":
    # Script is being executed from the command line (not imported)
    main(sys.argv)

# End of file ScrollTest.py

rawDescription: Matplotlib/Pyplot: How to zoom subplots together AND x-scroll separately?


rawDescription: Python "denormalize" unicode combining characters


code:
class MrsRobinson(object):
    '''
    What's that you say?
    '''
    pass

rawDescription: How do I change Emacs's font face for Python docstrings?

description: Change Emacs's font face for Python docstrings


code:
class mem_mon(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.keeprunning = True
        self.maxmem = 0
        self.interrupt = threading.Event()

    def run(self):
        # this loop will run until you call set() on the interrupt
        while not self.interrupt.isSet():
            self.maxmem = max(self.maxmem, ck_mem())

            # this will either sleep for 10 seconds (for the timeout)
            # or it will be interrupted by the interrupt being set
            self.interrupt.wait(10)

mem = mem_mon()
mem.run()

# later, set the interrupt to both halt the 10-second sleep and end the loop
mem.interrupt.set()

rawDescription: joining an always-running thread in python

description: Joining an always-running thread in python


code:
a = Poly(expr, x)
a.coeffs()

rawDescription: How to extract all coefficients in sympy

description: Extract all coefficients in sympy


code:
words = ['abc', 'def', 'abx', 'cfd', 'nab', 'fdd', 'aadsd_ab']
[idx for idx, word in enumerate(words) if 'ab' in word]

rawDescription: Matching a pattern in a list of strings and returning a list of indexes


code:
from collections import defaultdict

def  prevword_ave_len(word, text):

    words = defaultdict(list)    #initialization of default dictionary

    textlist = text.split()      #split text into words
    words[textlist[0]].append(0) #append 0 for first word in text
    #iterate over words, append length of preceding word to values
    for i in range(1,len(textlist)):
        words[textlist[i]].append(len(textlist[i-1]))

    if word in words:
        return sum(words[word])/len(words[word])    #calculate mean
    else: return False

if __name__ == "__main__":

    text = "Call me Ishmael. Some years ago - never mind how long precisely - having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off - then, I account it high time to get to sea as soon as I can. This is my substitute for pistol and ball. With a philosophical flourish Cato throws himself upon his sword; I quietly take to the ship. There is nothing surprising in this. If they but knew it, almost all men in their degree, some time or other, cherish very nearly the same feelings towards the ocean with me."

    print(prevword_ave_len('the', text))

rawDescription: Find the average length of the preceding word of another word in a string of text


code: regex_result += "\\2"

rawDescription: python regex re.sub with strings

description: Python regex re.sub with strings


code:
from mailchimp import Mailchimp
mailchimp = Mailchimp(api_key)
mailchimp.campaigns.send(campaign_id)

rawDescription: python how to use mailchimp to send email

description: Python how to use mailchimp to send email


code:
import itertools

def skip(iterable, n):
    next(itertools.islice(iterable, n, n), None)

outer_numbers = iter(range(...))
for i in outer_numbers:
    inner_numbers = iter(range(...))
    for j in inner_numbers:
        if condition:
            skip(outer_numbers, 3)  # skip 3 items from the outer loop.
            skip(inner_numbers, 2)  # skip 2 items from the inner loop.

rawDescription: How can I skip specific iterations in a for loop?

description: Skip specific iterations in a for loop


code:
from collections import Counter
from itertools import combinations
import pydot

actorslists = [
    [u'Tim Robbins', u'Morgan Freeman', u'Bob Gunton', u'William Sadler'],
    [u'Christian Bale', u'Heath Ledger', u'Aaron Eckhart', u'Michael Caine'],
    [u'Tim Robbins', u'Heath Ledger', u'Michael Caine']
]

# Counter tracks how often each pair of actors has occurred (-> link weight)
actorpairs = Counter(pair for actorslist in actorslists for pair in combinations(sorted(actorslist), 2))

graph = pydot.Dot(graph_type='graph', charset="utf8")
for actors,weight in actorpairs.iteritems():   # or .items() for Python 3.x
    a,b = list(actors)
    edge = pydot.Edge(a, b, weight=str(weight))
    graph.add_edge(edge)
graph.write('dotfile.dot')

rawDescription: Create a permutation array from a list of lists


code:
import csv
import os
def make_csv(in_file, out_file, year):
    with open(in_file, 'rb') as csv_in_file:
        csv_row_list = []
        first_row = True
        csv_reader = csv.reader(csv_in_file)
        for row in csv_reader:
            if first_row:
                csv_row_list.append(row)
                first_row = False
            else:
                if int(row[1]) >= year:
                    csv_row_list.append(row)

    with open(out_file, 'wb') as csv_out_file:
        csv_writer = csv.writer(csv_out_file)
        csv_writer.writerows(csv_row_list)

for root, directories, files in os.walk(working_directory):
    for f in files:
        if f.endswith('.csv'):
            in_file = os.path.join(root, f)
            out_file = os.path.join(root, os.path.splitext(f)[0] + '_new' + os.path.splitext(f)[1])
            make_csv(in_file, out_file, year)

rawDescription: Python: how to slice a csv file with respect to a column other than the first?


code:
import re
split_res = re.findall('[A-Z][^A-Z]*', 'YannickMorin')

rawDescription: Python: Change uppercase letter

description: Python: Change uppercase letter


code: button = Gtk.Button(label='Some text')

rawDescription: Discerning class parameters in documentation/class reference


code:
import gdal
from mpl_toolkits.mplot3d import Axes3D

dem = gdal.Open('gmted_small.tif')
gt  = dem.GetGeoTransform()
dem = dem.ReadAsArray()

fig, ax = plt.subplots(figsize=(16,8), subplot_kw={'projection': '3d'})

xres = gt[1]
yres = gt[5]

X = np.arange(gt[0], gt[0] + dem.shape[1]*xres, xres)
Y = np.arange(gt[3], gt[3] + dem.shape[0]*yres, yres)

X, Y = np.meshgrid(X, Y)

surf = ax.plot_surface(X,Y,dem, rstride=1, cstride=1, cmap=plt.cm.RdYlBu_r, vmin=0, vmax=4000, linewidth=0, antialiased=True)

ax.set_zlim(0, 60000) # to make it stand out less
ax.view_init(60,-105)

fig.colorbar(surf, shrink=0.4, aspect=20)

rawDescription: Display a georeferenced DEM surface in 3D matplotlib


code:
def func_globals(f):
    return f.__globals__ if PY3k else f.func_globals

def filter(self, selector):
    if not hasattr(selector, '__call__'):
        return self._filter_only(selector, self)
    else:
        elements = []
        try:
            for i, this in enumerate(self):

                # The magic happens here
                func_globals(selector)['this'] = this

                if callback(selector, i):
                    elements.append(this)

        finally:
            f_globals = func_globals(selector)
            if 'this' in f_globals:
                del f_globals['this']
        return self.__class__(elements, **dict(parent=self))

rawDescription: Why can this unbound variable work in Python (pyquery)?


code:
import logging

DEFAULT_LOG_CONFIG = 'somepath/logging.conf'

def main(args):
    ...
    # parse command line arguments or similar
    log_config = options.logconfig or DEFAULT_LOG_CONFIG
    logging.fileConfig(DEFAULT_LOG_CONFIG)

rawDescription: Is it possible to control python logging level from outside the script itself, without modifying the scripts?


code:
##-------------demo code--------------------------------------------##

def count_numbers(number):
    i = 0
    while i < number:
        i = i + 1

def some_fct():
    global count
    i = 0
    while i < 5:
        count = count + 1
        count_numbers(5000000)
        i = i + 1

def other_fct():
    global count
    i = 0
    while i < 5:
        count = count + 1
        count_numbers(5000000)
        i = i + 1

def do_stuff():
    some_fct()
    other_fct()

def update_progress(m):
    value = float(count) / total
    if value < 1.0:
        m.set(value)
        m.after(500, lambda: update_progress(m))
    else:
        m.set(value, 'Process Completed')

if __name__ == '__main__':
    global count
    global total
    count = 0
    total = 10
    root = Tkinter.Tk(className='meter demo')
    m = Meter(root, relief='ridge', bd=3)
    m.pack(fill='x')
    m.set(0.0, 'Starting meter')
    m.after(50, lambda: update_progress(m))
    thread.start_new_thread(do_stuff, () )
    root.mainloop()

rawDescription: Tkinter progress bar/window not responding when moved


rawDescription: How to hide a python Command Prompt window

description: Hide a python Command Prompt window


code:
reobj = re.compile(r'<a\b[^>]href=".*?location=cons_tab.*?"[^>]*>(.*?)</a>', re.IGNORECASE | re.DOTALL)
match = reobj.search(text)
if match:
    result = match.group(1)
else:
    result = ""

rawDescription: extract value with regular expression or parsing

description: Extract value with regular expression or parsing


code:
from dis import dis
def f():
    x += y

dis(f)

rawDescription: Differnce between BINARY_ADD and INPLACE_ADD


code:
# start of my code
atenter() # place 1

def main():
   atenter() # place 2
   # run main code

if __name__ == '__main__':
   atenter() # place 3
   main()

rawDescription: Python run before any script

description: Python run before any script


code:
with open('file1') as f1:
    lineset = set(f1)
with open('file2') as f2:
    lineset.difference_update(f2)
with open('file3', 'w') as out:
    for line in lineset:
        out.write(line)

rawDescription: Difference between two files in terms of lines


code:
import urllib, json, pprint

params = urllib.urlencode(dict(q='obama', rpp=10, geocode='37.781157,-122.398720,1mi'))
u = urllib.urlopen('http://search.twitter.com/search.json?' + params)
j = json.load(u)
pprint.pprint(j)

rawDescription: Using Twitter API with Python (geocode)

description: Using Twitter API with Python (geocode)


code:
a = 'GET /dsadda HTTP/1.1\r\nUser-Agent: curl/7.26.0\r\nHost: www.youtube.com\r\nAccept: */*\r\n\r\n'
import re
re.search(r"Host: (.+)\r\n",a).group(1)

rawDescription: Python Regular Expression For Host Header


rawDescription: Python list arithmetic

description: Python list arithmetic


code:
from scipy.stats import gamma
rv = gamma(shape, scale = 1.0/rate)

rawDescription: How to specify gamma distribution using shape and rate in Python?

description: Specify gamma distribution using shape and rate in Python


code:
import os
import psutil

allMatlabIds = [p.pid for p in psutil.process_iter() if "matlab" in str(p.name)]
MatlabIdsToKill = [x for x in allMatlabIds if x != os.getpid()]
for MatlabId in MatlabIdsToKill:
    os.kill(MatlabId, signal.SIGINT)

rawDescription: kill matlab process in task manager using python

description: Kill matlab process in task manager using python


code:
process_list = []
for id  in ids:
    process_list.append(subprocess.Popen(cmd, shell=True))
for process in process_list:
    process.wait()

rawDescription: How can I manage these subprocesses efficiently?

description: Manage these subprocesses efficiently


code:
df = DataFrame(randn(5,2),index=date_range('20130101',periods=5))
df['date'] = Timestamp('20130102')
df
df['td'] = df['date']-df.index.to_series()
df

rawDescription: How to directly use Pandas Date-time index in calculations?

description: Directly use Pandas Date-time index in calculations


code:
import matplotlib.pyplot as plt
plt.plot([0, 1e-9, 0, -1e-9])

# pull out values for y-axis ticks
yticks = plt.gca().get_yticks()

# format new labels
new_yticklabels = ['{:0=4.2f}e-9'.format(tick/1e-9) for tick in yticks]

# set new labels
plt.gca().set_yticklabels(new_yticklabels)

plt.show()

rawDescription: How to plot tick values in-place

description: Plot tick values in-place


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

class Application(object):
    def __init__(self):
        window = gtk.Window()

        model = gtk.TreeStore(str)
        model.append(None, row=('Normal row',))
        model.append(None, row=('Red row',))

        treeview = gtk.TreeView(model)
        renderer = gtk.CellRendererText()
        column = gtk.TreeViewColumn('Column', renderer, markup=0)
        treeview.append_column(column)

        scrolled_window = gtk.ScrolledWindow()
        scrolled_window.add(treeview)

        window.add(scrolled_window)
        window.connect('destroy', lambda w: gtk.main_quit())

        window.show_all()

    def run(self):
        gtk.main()

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

rawDescription: Set cellrenderertext foreground color when a row is highlighted


code:
import numpy as np
import matplotlib.pylab as pl

import matplotlib as mpl
mpl.rcParams['axes.formatter.useoffset'] = False

x = np.arange(10000000, 10000010, 1)
y = np.cos(x)

pl.figure()
pl.subplot(121)
pl.plot(x,y)

pl.subplot(122)
pl.plot(x,y)
locs, labels = pl.xticks()
pl.setp(labels, rotation=90)

rawDescription: How can I rotate the auto-generated x-axis labels of a matplotlib plot?

description: Rotate the auto-generated x-axis labels of a matplotlib plot


code:
for i, item in enumerate(records):
    if item != '#':
        recordcount += 1
        records[i] = item.split('\t')

rawDescription: Split a string within a list python

description: Split a string within a list python


code:
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd

tips = sns.load_dataset("tips")

sns.stripplot(x="day", y="total_bill", hue="smoker",
data=tips, jitter=True,
palette="Set2", split=True,linewidth=1,edgecolor='gray')

# Get the ax object to use later.
ax = sns.boxplot(x="day", y="total_bill", hue="smoker",
data=tips,palette="Set2",fliersize=0)

# Get the handles and labels. For this example it'll be 2 tuples
# of length 4 each.
handles, labels = ax.get_legend_handles_labels()

# When creating the legend, only use the first two elements
# to effectively remove the last two.
l = plt.legend(handles[0:2], labels[0:2], bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

rawDescription: Seaborn boxplot + stripplot: duplicate legend


code:
import numpy as np
from astropy import units as u
from astropy.coordinates import SkyCoord, FK4, FK5, Galactic
clra = np.zeros(3)
cldec = np.zeros(3)
c1 = SkyCoord(clra * u.deg, cldec * u.deg, frame=FK4)
c2 = c1.transform_to(FK5(equinox='J2000'))
c3 = c2.transform_to(Galactic)
print(c3.l.degree)
print(c3.b.degree)

rawDescription: astlib coordinates code to astropy coordinates code

description: Astlib coordinates code to astropy coordinates code


code: import sys; new=sys.path[sys.__plen:]; del sys.path[sys.__plen:]; p=getattr(sys,'__egginsert',0); sys.path[p:p]=new; sys.__egginsert = p+len(new)

rawDescription: python paths and import order

description: Python paths and import order


rawDescription: Using Python's datetime module, can I get the year that UTC-11 is currently in?


code:
def gs(a,b):
    class SameEvent(Exception):
        pass
    def ry():
        if a==b:
            raise SameEvent(a)
    try:
        # Do stuff here, and call ry whenever you want to return if they are the same.
        ry()

        # It will now return 3.
        a = b = 3
        ry()

    except SameEvent as e:
        return e.args[0]

rawDescription: make a parent function return - super return?

description: Make a parent function return - super return


code:
from collections import defaultdict

nd = defaultdict(list)

for item in nodes:
    nd[tuple(item[1:])].append(item[0])

coincident_nodes = [v for k,v in nd.items() if len(v)>1]

rawDescription: Avoid permutations when searching for coincident data


code:
dates = []
for line in f:
    dataItem = line.split() #split by while space by default, as a list
    date = dataItem[0] #index 0 is the first element of the dataItem list
    dates.append(date)
f.close()

rawDescription: Opening a file and selecting specific column in file


code: [i.ljust(4) for i in strs]

rawDescription: Append differing number of characters to strings in list of strings


code:
class SuffixComparingUnicodeString(unicode):
    def __eq__(self, other):
        return isinstance(other, unicode) and other.endswith(self)

rawDescription: Accessing the original value of the unicode string when subclassing unicode


code:
import os
import sys
from mpi4py import MPI
import logging
import random

def getScriptPath():
    return os.path.dirname(os.path.realpath(sys.argv[0]))

if __name__ == '__main__':
    comm = MPI.COMM_WORLD
    rank = MPI.COMM_WORLD.Get_rank()
    size = MPI.COMM_WORLD.Get_size()
    name = MPI.Get_processor_name()
    logging.basicConfig(filename=getScriptPath() + "\\log_filename.log", level=logging.DEBUG,
                            format='%(asctime)s - %(levelname)s - %(message)s')
    logger = logging.getLogger()
    work = True
    if rank == 0:
        for i in range(3):
            for j in range(1, size):
                req = comm.isend(work, dest=j, tag=j+1)
                req.wait()

            data = [random.random() for i in range(100)]
            ndata = len(data)//size

            logger.info("Loop i=%s" % i)
            req = comm.irecv(source=0)
            for j in range(size-1):
                to_send = []
                t = 0
                while t < ndata:
                    to_send.append(data.pop(0))
                    t += 1
                comm.isend(to_send, dest=j, tag=j+1)

            comm.issend(data, dest=size-1)

            # recieve block
            d = req.wait()
            logger.info("i=%s, j=%s: %s" % (i, rank, d))
            requests = []
            for j in range(1, size):
                # d = comm.recv(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG, status=None)
                req = comm.irecv(source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG)
                d = req.wait()
                logger.info("i=%s, j=%s: %s" % (i, j, d))

        work = False
        for j in range(1, size):
            req = comm.isend(work, dest=j, tag=j+1)
            req.wait()

        MPI.Finalize()

    else:
        while True:
            have_job = comm.recv(source=0)
            if have_job == False:
                break

            data = comm.recv(source=0)

            for i in range(len(data)):
                data[i] = rank
            comm.isend(data, dest=0, tag=rank+1)
            print("Data was sent from %s" % rank)
            logger.info("Data was sent from %s: /n %s" % (rank, data))

rawDescription: Bradcasting by send function and recieve messages from different sources by recv


code:
import ctypes, win32gui
def getSystemPalette():
    hwnd = win32gui.GetDesktopWindow()

    hwndDC = win32gui.GetWindowDC(hwnd)

    buff = ctypes.c_buffer("0"*(256*4)) #R, G, B, and flags
    ctypes.windll.gdi32.GetSystemPaletteEntries(hwndDC, 0, 256, buff)

    win32gui.ReleaseDC(hwnd, hwndDC)

    #ignore every 4th entry which is the flags
    res = [ord(x) for i,x in enumerate(buff) if i%4 != 3]
    return res

rawDescription: win32api: get bitmap palette

description: Win32api: get bitmap palette


code:
v = scipy.linalg.eig(A,left=True,right=False)[1][:,0]
v
v / sum(v)

rawDescription: Left eigenvectors not giving correct (markov) stationary probability in scipy


code:
sns.factorplot(x="Month", y="Score",
               row="Player", col="Month", data=df,
               margin_titles=True, kind="bar")

rawDescription: FacetGrid Data Label in Seaborn

description: FacetGrid Data Label in Seaborn


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

y = np.array([1, 4, 3, 2, 7, 11])
colors = cm.hsv(y / float(max(y)))
plot = plt.scatter(y, y, c = y, cmap = 'hsv')
plt.clf()
plt.colorbar(plot)
plt.bar(range(len(y)), y, color = colors)
plt.show()

rawDescription: pyplot/matplotlib Bar chart with fill color depending on value

description: Pyplot/matplotlib Bar chart with fill color depending on value


code:
def ping(host):
  cmd = "ping -c 1 {}".format(host)
  Popen(cmd, shell=True)

ping(input())

rawDescription: subprocess.Popen: sequence vs a single string

description: Subprocess.Popen: sequence vs a single string


code:
if __name__ == '__main__':
    print(approximate_size(1000000000000, False))
    print (approximate_size(1000000000000))

input('Press Enter to exit')

rawDescription: Python: Stop Auto Exiting Cmd Prompt

description: Python: Stop Auto Exiting Cmd Prompt


code:
from itertools import islice

def nth(iterable, n, default=None):
    "Returns the nth item or a default value"
    return next(islice(iterable, n, None), default)

rawDescription: Python go to specific iteration in generator


code:
def APIMiddleware(object):
    def process_request(self, request):
        request.api = API(host, port, user, password, extra={"url": request.get_full_path()})

rawDescription: Using middleware to add arguments to view functions in django


code:
from geospatial import geomodel, geocell, geomath

# query is a db.GqlQuery
# location is a db.GeoPt

# A resolution of 4 is box of environs 150km
bbox = geocell.compute_box(geocell.compute(geo_point.location, resolution=4))
cell = geocell.best_bbox_search_cells (bbox, geomodel.default_cost_function)

query.filter('location_geocells IN', cell)

# I want only results from 100kms.
FETCHED=200
DISTANCE=100
def _func (x):
  x.dist = geomath.distance(geo_point.location, x.location)
  return x.dist

results = sorted(query.fetch(FETCHED), key=_func)
results = [x for x in results if x.dist <= DISTANCE]

rawDescription: GeoModel with Google App Engine - queries


code:
def got_obj1(obj1):
   ...
   def2.addCallback(show, obj1)

def show(value, obj1):
   ...
   PICK = Input("Which card do you want to pick?")
   obj1.callRemote("pick",PICK)

rawDescription: How do I react on user input during reactor.run() in twisted python?

description: React on user input during reactor.run() in twisted python


code:
class MyClass:
    @staticmethod
    def somefunc(text):
        return text + '_NEW'
    @staticmethod
    def cool_function(ixdirname, ixname):
        tmp = MyClass.somefunc(ixname)
        print((ixdirname, ixname, tmp))
        return

MyClass.cool_function('FOODIR', 'FOO')

rawDescription: Calling function from another staticmethod function within a class


code:
import pexpect # $ pip install pexpect

output, status = pexpect.run('foo bar',
    events={r'continue\?': 'yes\n', 'password': 'p4$$W__rd\n'},
    withexitstatus=1)

rawDescription: Multiple inputs in a Python Subprocess PIPE (with stdin or communicate)


rawDescription: How to sort a list of x-y coordinates

description: Sort a list of x-y coordinates


code:
#!/usr/bin/env python
#
# Copyright 2001-2009 by Vinay Sajip. All Rights Reserved.
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
# provided that the above copyright notice appear in all copies and that
# both that copyright notice and this permission notice appear in
# supporting documentation, and that the name of Vinay Sajip
# not be used in advertising or publicity pertaining to distribution
# of the software without specific, written prior permission.
# VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
# ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
# VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
# ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
# IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# This file is part of the standalone Python logging distribution. See
# http://www.red-dove.com/python_logging.html
#
"""
A test harness for the logging module. An example handler - DBHandler -
which writes to an Python DB API 2.0 data source. You'll need to set this
source up before you run the test.

Copyright (C) 2001-2009 Vinay Sajip. All Rights Reserved.
"""
import sys, string, time, logging

class DBHandler(logging.Handler):
    def __init__(self, dsn, uid='', pwd=''):
        logging.Handler.__init__(self)
        import mx.ODBC.Windows
        self.dsn = dsn
        self.uid = uid
        self.pwd = pwd
        self.conn = mx.ODBC.Windows.connect(self.dsn, self.uid, self.pwd)
        self.SQL = """INSERT INTO Events (
                        Created,
                        RelativeCreated,
                        Name,
                        LogLevel,
                        LevelText,
                        Message,
                        Filename,
                        Pathname,
                        Lineno,
                        Milliseconds,
                        Exception,
                        Thread
                   )
                   VALUES (
                        %(dbtime)s,
                        %(relativeCreated)d,
                        '%(name)s',
                        %(levelno)d,
                        '%(levelname)s',
                        '%(message)s',
                        '%(filename)s',
                        '%(pathname)s',
                        %(lineno)d,
                        %(msecs)d,
                        '%(exc_text)s',
                        '%(thread)s'
                   );
                   """
        self.cursor = self.conn.cursor()

    def formatDBTime(self, record):
        record.dbtime = time.strftime("#%m/%d/%Y#", time.localtime(record.created))

    def emit(self, record):
        try:
            #use default formatting
            self.format(record)
            #now set the database time up
            self.formatDBTime(record)
            if record.exc_info:
                record.exc_text = logging._defaultFormatter.formatException(record.exc_info)
            else:
                record.exc_text = ""
            sql = self.SQL % record.__dict__
            self.cursor.execute(sql)
            self.conn.commit()
        except:
            import traceback
            ei = sys.exc_info()
            traceback.print_exception(ei[0], ei[1], ei[2], None, sys.stderr)
            del ei

    def close(self):
        self.cursor.close()
        self.conn.close()
        logging.Handler.close(self)

dh = DBHandler('Logging')
logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)
logger.addHandler(dh)
logger.info("Jackdaws love my big %s of %s", "sphinx", "quartz")
logger.debug("Pack my %s with five dozen %s", "box", "liquor jugs")
try:
    import math
    math.exp(1000)
except:
    logger.exception("Problem with %s", "math.exp")

rawDescription: Creating a logging handler to connect to Oracle?


code:
import wx

class Main(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)

        self.text = wx.TextCtrl(self, wx.NewId(), style=wx.TE_RICH)
        self.check = wx.CheckBox(self, wx.NewId(), 'Make text red if 0')
        self.check.Bind(wx.EVT_CHECKBOX, self.onCheck)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.text, 0)
        sizer.Add(self.check, 0)
        self.SetSizerAndFit(sizer)
        self.Show()

    def onCheck(self, evt):
        value = self.text.GetValue()
        if self.check.IsChecked() and value == '0':
            self.text.SetForegroundColour(wx.RED)
        else:
            self.text.SetForegroundColour(wx.BLACK)

app = wx.App(0)
Main(None, -1, 'Checkbox')
app.MainLoop()

rawDescription: wxPython: How to change the font color in textctrl with a checkbox?

description: WxPython: How to change the font color in textctrl with a checkbox


code:
import glob
paths = glob.glob(r'/v/mybooks.com/*/mbo[1-9]')

rawDescription: python regex os path

description: Python regex os path


code:
import pandas as pd
import numpy as np

# load your data

data['Time'] = pd.to_datetime(data['Time'])

list_of_indexes = [np.argmin(g['Time']) for l, g in data.groupby('ID Name')]
data.ix[list_of_indexes]

rawDescription: How to keep the most recent values and delete all other others in a column (pandas)

description: Keep the most recent values and delete all other others in a column (pandas)


code:
from datetime import datetime as dt
dt.now()
dt.now().minute
0 <= dt.now().minute <= 29  # The minute is between 0 and 29 inclusive

rawDescription: how to check the minutes in python?

description: Check the minutes in python


code:
import matplotlib.pylab as plt
import numpy as np
import scipy.signal

def bode(G,f=np.arange(.01,100,.01)):
    plt.figure()
    jw = 2*np.pi*f*1j
    y = np.polyval(G.num, jw) / np.polyval(G.den, jw)
    mag = 20.0*np.log10(abs(y))
    phase = np.arctan2(y.imag, y.real)*180.0/np.pi % 360

    plt.subplot(211)
    #plt.semilogx(jw.imag, mag)
    plt.semilogx(f,mag)
    plt.grid()
    plt.gca().xaxis.grid(True, which='minor')

    plt.ylabel(r'Magnitude (db)')

    plt.subplot(212)
    #plt.semilogx(jw.imag, phase)
    plt.semilogx(f,phase)
    plt.grid()
    plt.gca().xaxis.grid(True, which='minor')
    plt.ylabel(r'Phase (deg)')
    plt.yticks(np.arange(0, phase.min()-30, -30))

    return mag, phase

f=scipy.signal.lti([1],[1,1])
bode(f)

rawDescription: Modeling a linear system with Python

description: Modeling a linear system with Python


code:
import requests

response  = requests.get(url, data=your_data)

rawDescription: How to use curl -XGET in python

description: Use curl -XGET in python


rawDescription: How to remove characters between the first occurrences of an expression?

description: Remove characters between the first occurrences of an expression


code:
import itertools
zip([1, 2, 3, 4, 5], itertools.repeat(100), itertools.repeat(200))

rawDescription: zip() in python, how to use static values

description: Zip() in python, how to use static values


code:
multiples[:] = [n for i,n in enumerate(multiples)
                       if all(n % small for small in multiples[i+1:])]

rawDescription: Convert function to single line list comprehension


rawDescription: How to check wxPython release from python GUI (IDLE)?

description: Check wxPython release from python GUI (IDLE)


code: #!/usr/bin/python

rawDescription: What parameter does it provide when we use "open with" on a file?


code:
try:
    html = urlopen('http://wenatchee.craigslist.org').read()
    html = html.decode("utf-8") # Decode the bytes into a useful string
    # Now split the string over all whitespace, then join it together again.
    html = ' '.join(html.split())
    print(html)
    s.quit()
except Exception as e:
    print(e)

rawDescription: Impossible to remove \n and \t in python3 string?


code:
import numpy as np
a  = np.array(a)
np.random.shuffle(a[1::2])

rawDescription: How can a two-column Python list be shuffled?


code:
def run_test(test_function):
    tests = []
    numtests = 100
    for i in range(0, numtests):
        #random
        zeros = [0] * 1024
        ones = [1] * 10
        #ones = [randint(0,1023) for _ in range(0,10)]
        input =  zeros + ones
        shuffle(input)
        tests.append(test_function(input,10))

    count = [x[0] for x in tests]
    found = [x[1] for x in tests]
    found.sort()
    num = Counter(found)
    freqs = [x for x in num.values()]
    cumsum = [sum(item for item in freqs[0:rank+1]) for rank in range(len(freqs))]
    normcumsum  = [float(x)/numtests for x in cumsum]

    print(freqs)
    print(cumsum)
    print(normcumsum)
    print(sorted(num.keys()))

    figure(0)
    plt.plot(sorted(num.keys()), normcumsum)
    plt.xlim(0,100)
    plt.show()

run_test(HGBSA)
run_test(SOME_OTHER_FUNCTION)

rawDescription: Analog of templates in Python

description: Analog of templates in Python


code:
def __init__(self,text,begin,end,*args,**kargs):
    try:
        super(Token,self).__init__(*args,**kargs)
    except TypeError:
        # Python 3 and the mixed in type is immutable.
        # Ignoring this is fine, `__new__` took care of this.
        pass
    self.text = text
    self.begin = begin
    self.end = end

rawDescription: Subclassing builtin types -- Python 2 and 3


code: return template('hello_template', name=name, request=request)

rawDescription: How can I access request data in a template

description: Access request data in a template


code:
import getpass
users = {}
username = raw_input('Enter your username?')
password = getpass.getpass('Enter your password?')
users[username] = password

rawDescription: Python - Adding new variables automatically


code:
result = [0]*len(x)   # replace 0 with a suitable default element if necessary.
                      # or just copy x (result = x[:])

rawDescription: Mergesort python

description: Mergesort python


code:
from django.utils.dateformat import DateFormat
DateFormat(datetime.datetime.now()).format('N j, Y, P')

rawDescription: How to get this type of time format "Aug. 13, 2014, 4:04 p.m." using strftime?

description: Get this type of time format "Aug. 13, 2014, 4:04 p.m." using strftime


code:
def penup(self):
    # Your logic
    return self

rawDescription: Python 3: Can we avoid repeating an instance name when calling several of its methods?


code:
class WidgetMeta(type):

    def __new__(cls, name, parents, kwargs):
        '''
        Automate the creation of the class
        '''

        for item in kwargs['_ATTRIBS']:
            kwargs[item] = RecordedProperty(item)
        return super(WidgetMeta, cls).__new__(cls, name, parents, kwargs)

class Widget(ModelObject):

    _ATTRIBS = ['level', 'angle']
    __metaclass__ = WidgetMeta

    def __init__(self, *args, **kwargs):
       super().__init__(self)
       self.Details = {}
       for detail in self._ATTRIBS:
           self.Details[detail] = RecordedDetail()

rawDescription: How to add multiple similar properties in Python

description: Add multiple similar properties in Python


rawDescription: Is it possible to return two lists from a function in python


code:
def recursive_add(s):
    if s:
        return s[0]**2 + recursive_add(s[1:])
    else:
        return 0

rawDescription: Trying to recursively add the square of numbers


code:
cycling_colours = ['red', 'green', 'yellow', 'blue']
colors = []  # List to hold the values of j

for i in range(25):
    for j in cycling_colours:
        drawPatch(win, x, y, j)
        colors.append(j)

rawDescription: Change argument value of a function after function is called


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

# create some random data
x = np.cumsum(np.random.rand(1000)-0.5)

# plot it
fig, ax = plt.subplots(1,1,figsize=(10,3))
plt.plot(x, color='k')
plt.plot(len(x)-1, x[-1], color='r', marker='o')

# remove all the axes
for k,v in ax.spines.items():
    v.set_visible(False)
ax.set_xticks([])
ax.set_yticks([])

#show it
plt.show()

rawDescription: Creating sparklines using matplotlib in python


code:
for perm in permutations:
    for airport in perm:
         print(airports.get(airport))

rawDescription: How do I do a dictionary lookup in a list of permutations of that dictionary?

description: Do a dictionary lookup in a list of permutations of that dictionary


code:
import os

def upload_path(instance, filename):
    return os.path.join('uploads', str(instance.category.pk), str(instance.user.pk))

file = models.FileField(upload_to=upload_path)

rawDescription: How do I get the pk of a ForeignKey?

description: Get the pk of a ForeignKey


code:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import Tkinter as Tk
import networkx as nx
from tkMessageBox import showinfo

root = Tk.Tk()
root.wm_title("Animated Graph embedded in TK")
root.wm_protocol('WM_DELETE_WINDOW', root.quit())

f = plt.figure(figsize=(5,4))
a = f.add_subplot(111)
plt.axis('off')

# the networkx part
G=nx.complete_graph(5)
pos=nx.circular_layout(G)
nx.draw_networkx(G,pos=pos,ax=a)
xlim=a.get_xlim()
ylim=a.get_ylim()

# a tk.DrawingArea
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def next_graph():
    if G.order():
        a.cla()
        G.remove_node(G.nodes()[-1])
        nx.draw_networkx(G, pos, ax=a)
        a.set_xlim(xlim)
        a.set_ylim(ylim)
        plt.axis('off')
        canvas.draw()

b = Tk.Button(root, text="next",command=next_graph)
b.pack()

Tk.mainloop()

rawDescription: animated NetworkX Graph in TkCanvas: background color

description: Animated NetworkX Graph in TkCanvas: background color


code:
def ksp_yen(graph, node_start, node_end, max_k=2):
    distances, previous = dijkstra(graph, node_start)

    A = [{'cost': distances[node_end],
          'path': path(previous, node_start, node_end)}]
    B = []

    if not A[0]['path']: return A

    for k in range(1, max_k):
        for i in range(0, len(A[-1]['path']) - 1):
            node_spur = A[-1]['path'][i]
            path_root = A[-1]['path'][:i+1]

            edges_removed = []
            for path_k in A:
                curr_path = path_k['path']
                if len(curr_path) > i and path_root == curr_path[:i+1]:
                    cost = graph.remove_edge(curr_path[i], curr_path[i+1])
                    if cost == -1:
                        continue
                    edges_removed.append([curr_path[i], curr_path[i+1], cost])

            path_spur = dijkstra(graph, node_spur, node_end)

            if path_spur['path']:
                path_total = path_root[:-1] + path_spur['path']
                dist_total = distances[node_spur] + path_spur['cost']
                potential_k = {'cost': dist_total, 'path': path_total}

                if not (potential_k in B):
                    B.append(potential_k)

            for edge in edges_removed:
                graph.add_edge(edge[0], edge[1], edge[2])

        if len(B):
            B = sorted(B, key=itemgetter('cost'))
            A.append(B[0])
            B.pop(0)
        else:
            break

    return A

rawDescription: k shortest paths implementation in Igraph/networkx (Yen's algorithm)

description: K shortest paths implementation in Igraph/networkx (Yen's algorithm)


code: [ord(i) for i in unicode('ÄÖÜ','utf-8')]

rawDescription: Get ASCII Int with ord() of German umlaute (ÄÜÖ) in python


code: test_reversed = dict((v, k) for k, values in test.iteritems() for v in values)

rawDescription: How to know key in hash by value?

description: Know key in hash by value


code:
import numpy as np
np.random.uniform(-1, 1, size=5)

rawDescription: how to make an array of scaled random digits

description: Make an array of scaled random digits


rawDescription: Disable popup of cmd windows when using gitpython and py2exe?


code:
import matplotlib
import matplotlib.mlab as mlab
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
#%matplotlib inline

delta = 0.00025
A=0
x = np.arange(0, 0.10, delta)
y = np.arange(0, 0.1, delta)
X, Y = np.meshgrid(x, y)
Z = A*(X**2+Y**2)+2*X*Y

manual_locations = [(0.1,0.1), (0.2,0.2), (0.3,0.3),
                    (0.015, 0.015), (0.00255, 0.0025), (0.00005,0.00005)]
line_widths = (1, 1, 1, 1, 1, 1)

plt.figure()
CS = plt.contour(X, Y, Z, 6,                        # add 6 contour lines
                 linewidths=line_widths,
                 #levels=np.linspace(0, .003, 20))
                 levels=np.logspace(-5, -2, 20))

plt.clabel(CS, inline=1,                            # add labels
          fontsize=10,
          fmt="%.5f")
plt.title('Indifference Map')        # title

plt.show()

rawDescription: Location of contour lines

description: Location of contour lines


code:
if isinstance(arg, basestring):
    arg= set([arg])
else:
    try:
        selection= set(arg)
    except TypeError:
        selection= set([arg])

rawDescription: hasattr(obj, '__iter__') vs collections

description: Hasattr(obj, '__iter__') vs collections


code:
import numpy as np
x = np.array([[5, 2, 3],[1, 9, 2]]) # example data
k = 2 # return the indices of the 2 smallest values
np.argsort(x, axis=1)[:,0:k] # by row

array([[1, 2],
       [0, 2]])

rawDescription: Indices of k-minimum values along an axis of a numpy array


code:
class GmailSmpt:
    def __init__(self,sendfrom,sendto,usrname,pswd):
        self.server = smtplib.SMTP('smtp.gmail.com','587')
        ...

rawDescription: passing a return statement into another function in a class

description: Passing a return statement into another function in a class


code:
some_list = ["item1", "item2", "item3"] # over 300 items on the actual code
for item in some_list:
    download_folder = "/Users/myusername/Desktop/" + item
    some_way_magically_do_the_downloading(download_folder)

rawDescription: multiple download folders using Selenium Webdriver?

description: Multiple download folders using Selenium Webdriver


code: [x['answer'] for x in a['b']['c'].values()]

rawDescription: Get all values from nested dictionaries in python


code:
for i in range(len(nestedlist)):
    for j in range(7):
        x = nestedlist[i][j]
        y = unicode(x, 'utf-8')
        nestedlist[i][j] = y.encode('cp1252')

rawDescription: Enabling Excel to Open Python CSV Output as UTF8


code:
def drawing_area_write(self):
    # drawingarea1 is a Gtk.DrawingArea
    window = self.ui.drawingarea1.get_window()

    # Some code to get the coordinates for the image, which is centered in the
    # in the drawing area. You can ignore it for the purpose of this example
    src_x, src_y = self.get_centered_coordinates(self.ui.drawingarea1,
                                                 self.surface)
    image_height = self.surface.get_height() * self.scale_factor
    image_width = self.surface.get_width() * self.scale_factor

    # Fetch what we rendered on the drawing area into a pixbuf
    pixbuf = Gdk.pixbuf_get_from_window(window, src_x, src_y,
                                      image_width, image_height)

    # Write the pixbuf as a PNG image to disk
    pixbuf.savev('/tmp/testimage.png', 'png', [], [])

rawDescription: Save the contents of a Gtk.DrawingArea or Cairo pattern to an image on disk


code:
from sqlalchemy.orm import Session, object_session
from sqlalchemy import event

def preserve_deleted(class_):
    def copy_col(col):
        newcol = col.copy()
        newcol.constraints = set()
        return newcol
    keys = class_.__table__.c.keys()
    cols = dict(
        (col.key, copy_col(col)) for col in class_.__table__.c
    )
    cols['__tablename__'] = "%s_deleted" % class_.__table__.name

    class History(object):
        def restore(self):
            sess = object_session(self)
            sess.delete(self)
            sess.add(copy_inst(self, class_))

    hist_class = type(
                    '%sDeleted' % class_.__name__,
                    (History, Base),
                    cols)

    def copy_inst(fromobj, tocls):
        return tocls(**dict(
                        (key, getattr(fromobj, key))
                        for key in keys
                    ))
    @event.listens_for(Session, 'before_flush')
    def check_deleted(session, flush_context, instances):
        for del_ in session.deleted:
            if isinstance(del_, class_):
                h = copy_inst(del_, hist_class)
                session.add(h)
    class_.deleted = hist_class
    return class_

if __name__ == '__main__':

    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Column, ForeignKey, Integer, String
    from sqlalchemy.orm import relationship, Session
    from sqlalchemy import create_engine

    Base = declarative_base()

    @preserve_deleted
    class A(Base):
        __tablename__ = "a"

        id = Column(Integer, primary_key=True)
        data1 = Column(String)
        data2 = Column(String)

    @preserve_deleted
    class B(Base):
        __tablename__ = 'b'
        id = Column(Integer, primary_key=True)
        data1 = Column(String)
        a_id = Column(Integer, ForeignKey('a.id'))
        a = relationship("A")

    e = create_engine('sqlite://', echo=True)

    Base.metadata.create_all(e)

    s = Session(e)

    a1, a2, a3, a4 = \
        A(data1='a1d1', data2='a1d2'),\
        A(data1='a2d1', data2='a2d2'),\
        A(data1='a3d1', data2='a3d2'),\
        A(data1='a4d1', data2='a4d2')

    b1, b2, b3, b4 = \
        B(data1='b1', a=a1),\
        B(data1='b2', a=a1),\
        B(data1='b3', a=a3),\
        B(data1='b4', a=a4)

    s.add_all([
        a1, a2, a3, a4,
        b1, b2, b3, b4
    ])
    s.commit()

    assert s.query(A.id).order_by(A.id).all() == [(1, ), (2, ), (3, ), (4, )]
    assert s.query(B.id).order_by(B.id).all() == [(1, ), (2, ), (3, ), (4, )]

    s.delete(a2)
    s.delete(b2)
    s.delete(b3)
    s.delete(a3)
    s.commit()

    assert s.query(A.id).order_by(A.id).all() == [(1, ), (4, )]
    assert s.query(B.id).order_by(B.id).all() == [(1, ), (4, )]

    a2_deleted = s.query(A.deleted).filter(A.deleted.id == 2).one()
    a2_deleted.restore()

    b3_deleted = s.query(B.deleted).filter(B.deleted.id == 3).one()
    a3_deleted = s.query(A.deleted).filter(A.deleted.id == 3).one()
    b3_deleted.restore()
    a3_deleted.restore()

    s.commit()

    assert s.query(A.id).order_by(A.id).all() == [(1, ), (2, ), (3, ), (4, )]
    assert s.query(B.id).order_by(B.id).all() == [(1, ), (3, ), (4, )]

rawDescription: Strategy for being able to reverse a deletion using SQLAlchemy


code:
from operator import itemgetter
from itertools import groupby

def grouped(mytuples):
    for timestamp, items in groupby(sorted(mytuples, key=itemgetter(1)),
                                    key=itemgetter(1)):
        yield timestamp, list(items)

rawDescription: Manipulating a list of tuples

description: Manipulating a list of tuples


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

import matplotlib.pyplot as plt
import matplotlib.ticker

import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager

# ------------ Main Data ----------------

xlist = [x for x in xrange(2001, 2016, 1)]
ylist = [0, 1, 3, 3, 5, 7, 4, 4, 5, 10, 10, 30, 27, 43, 45]

# ---------------------------------------

# size of plot in inches
fig = plt.figure(figsize=(9.5, 5))

# init plot
plt.plot(
    xlist,
    ylist,
    linestyle = "-",
    marker = "D",
    color = "#5184be",
    markerfacecolor = "#5184be",
    linewidth = 2)

# axes style
axes = plt.gca()
axes.yaxis.grid(b=True, color='#c0c0c0', linestyle='-', linewidth=2)
axes.set_axisbelow(True)

# Labels
axes.set_xlabel(u'Loads, pts.', fontproperties=prop)
axes.set_ylabel(u'Year, y', fontproperties=prop)

# create line style
locator = matplotlib.ticker.MultipleLocator (base=1)

# set line style
axes.xaxis.set_major_locator (locator)

# view plot
plt.show()

rawDescription: Matplotlib specific axis plotting

description: Matplotlib specific axis plotting


code:
import pickle
serial_str = pickle.dumps(your_rrule_object)
db.store(serial_str)
...
serial_str = db.retrieve()
new_rrule_object = pickle.loads(serial_str)

rawDescription: How to recover python dateutil.rrule object from a dictionary string?

description: Recover python dateutil.rrule object from a dictionary string


code:
import numpy as np

LENGHT = 4
NO_CODES = 100000

alphabet = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789')
np_alphabet = np.array(alphabet, dtype="|S1")
np_codes = np.random.choice(np_alphabet, [NO_CODES, LENGHT])
codes = ["".join(np_codes[i]) for i in range(len(np_codes))]

print(codes)

rawDescription: Generate alphanumeric random numbers in numpy


code: new_lst = [x for t in lst for x in t[1:] if x != 0]

rawDescription: Python, working with lists

description: Python, working with lists


code:
if __name__ == '__main__':
    hello()

rawDescription: Executing Python Script From Command Line is Hiding Print Statements


code:
root = Tk()

...

root.after(2000, callback) # call `callback` function in 2000 ms.

rawDescription: turtle.ontimer() equivalent for tkinter

description: Turtle.ontimer() equivalent for tkinter


code:
class EligibilityForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(EligibilityForm, self).__init__(*args, **kwargs)
        # dynamic fields here ...
        self.fields['plan_id'] = CharField()
    # normal fields here ...
    date_requested = DateField()

rawDescription: Variable number of inputs with Django forms possible?


code:
font = {'family' : 'normal'}
matplotlib.rc('font', **font)

rawDescription: Pandas and matplotlib: Different fonts between showfig and savefig (mac os x backend)


code:
from ftplib import FTP

ftp = FTP("lidar.wustl.edu")
ftp.login()
ftp.cwd("Phelps_Rolla")
# list files with ftplib
file_list = ftp.nlst()

for f in file_list:
    # apply your filters
    if "tile" in f.lower() and any(f.endswith(ext) for ext in ['dbf', 'prj', 'shp', 'shx']):
        # download file sending "RETR <name of file>" command
        # open(f, "w").write is executed after RETR suceeds and returns file binary data
        ftp.retrbinary("RETR {}".format(f), open(f, "wb").write)
        print("downloaded {}".format(f))
ftp.quit()

rawDescription: How to download ftp urls that meet certain conditions?

description: Download ftp urls that meet certain conditions


code:
from skimage import data, color, io, img_as_float
import numpy as np
import matplotlib.pyplot as plt

alpha = 0.6

img = img_as_float(data.camera())
rows, cols = img.shape

# Construct a colour image to superimpose
color_mask = np.zeros((rows, cols, 3))
color_mask[30:140, 30:140] = [1, 0, 0]  # Red block
color_mask[170:270, 40:120] = [0, 1, 0] # Green block
color_mask[200:350, 200:350] = [0, 0, 1] # Blue block

# Construct RGB version of grey-level image
img_color = np.dstack((img, img, img))

# Convert the input image and color mask to Hue Saturation Value (HSV)
# colorspace
img_hsv = color.rgb2hsv(img_color)
color_mask_hsv = color.rgb2hsv(color_mask)

# Replace the hue and saturation of the original image
# with that of the color mask
img_hsv[..., 0] = color_mask_hsv[..., 0]
img_hsv[..., 1] = color_mask_hsv[..., 1] * alpha

img_masked = color.hsv2rgb(img_hsv)

# Display the output
f, (ax0, ax1, ax2) = plt.subplots(1, 3,
                                  subplot_kw={'xticks': [], 'yticks': []})
ax0.imshow(img, cmap=plt.cm.gray)
ax1.imshow(color_mask)
ax2.imshow(img_masked)
plt.show()

rawDescription: Applying a coloured overlay to an image in either PIL or Imagemagik


code:
def float_like_int(n):
    if round(n, 6) == round(n):
        return int(round(n))
    return n

rawDescription: python: float number like integer

description: Python: float number like integer


code:
def __init__( self, datastore ) : # datastore is of type store
    self.store = datastore
    self.num_added = 0

def __enter__( self ) :
    pass

def __exit__( self, type, value, traceback ) :
    l = len(self.store.contents)
    del self.store.contents[l - self.num_added : l]

def append( self, elem ) :
    self.store.contents.append(elem)
    self.num_added += 1

rawDescription: Python with statement: storing context

description: Python with statement: storing context


code:
import random
import wx

########################################################################
class MyPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        self.username = wx.StaticText(self, label="username")
        self.online_status = wx.StaticText(self, label="offline")
        self.dialing_status = wx.StaticText(self, label="no dial tone")

        btn = wx.Button(self, label="Update")
        btn.Bind(wx.EVT_BUTTON, self.onUpdate)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.username, 0, wx.ALL, 5)
        sizer.Add(self.online_status, 0, wx.ALL, 5)
        sizer.Add(self.dialing_status, 0, wx.ALL, 5)
        sizer.Add(btn, 0, wx.ALL, 5)
        self.SetSizer(sizer)

    #----------------------------------------------------------------------
    def update_text(self, info):
        """"""
        index = {
            "username":self.username,
            "online status":self.online_status,
            "dial status":self.dialing_status
            }
        text = index[info[0]]
        data = info[1]
        append = info[2]
        if append:
            current = text.GetLabel()
            text.SetLabel(current + " " + data)
        else:
            text.SetLabel(data)

    #----------------------------------------------------------------------
    def onUpdate(self, event):
        """"""
        info = random.choice(
            [("username", "mork89", 1),
             ("online status", "online", 0),
             ("dial status", "dialing", 1)
             ])
        self.update_text(info)

########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Dynamic StaticText")
        panel = MyPanel(self)
        self.Show()

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

rawDescription: WxPython StaticText dynamic update

description: WxPython StaticText dynamic update


code:
class Beer(object):
    def __init__(self, temp):
        self.__T = temp

    @property
    def temp(self):
        return Param('Beer Temperature', self.__T)

    @temp.setter
    def temp(self,value):
        self.__T = float(value)

rawDescription: Python property being overwritten

description: Python property being overwritten


rawDescription: Search List using Regular Expression

description: Search List using Regular Expression


code:
def write(self, message):
    self.terminal.write(message)
    self.log.write(message)
    self.terminal.flush()
    self.log.flush()

rawDescription: Logging realtime stdout to a file in Python?


code:
from itertools import chain
s = 'HELLOPEOPLE'
min, max = 2, 3
list(chain.from_iterable((s[i:i+k] for i in range(len(s)+1-k))
                         for k in range(min, max+1)))

rawDescription: How to get all consecutive-letter words between length a and b

description: Get all consecutive-letter words between length a and b


rawDescription: Using API authentication with shared python code


code:
import os

tmpl = env.get_template('index.html')
return tmpl.render(folder=os.path.dirname(__file__))

rawDescription: jinja2 basename or dirname from builtin filters?

description: Jinja2 basename or dirname from builtin filters


code:
class translatedDictList(object):
    def __init__(self, dictList, key):
        self.dictList = dictList
        self.key = key

    def __getitem__(self, item):
        return self.dictList[item][self.key]

    def __len__(self):
        return self.dictList.__len__()

def getNearest(self, symbolList, pos, maxDistance):
    translatedList = translatedDictList(symbolList, 'x')

    splitIndex = bisect.bisect(translatedList, pos[0])
    minIndex = bisect.bisect(translatedList, pos[0] - maxDistance)
    maxIndex = bisect.bisect(translatedList, pos[0] + maxDistance)

    # Euclidean distance acutally not needed anymore!
    leftElement = min(symbolList[minIndex:splitIndex],
                      key=lambda n: abs(n['x'] - pos[0]) +
                                    abs(n['y'] - pos[1]))
    rightElement = min(symbolList[splitIndex:maxIndex],
                       key=lambda n: abs(n['x'] - pos[0]) +
                                     abs(n['y'] - pos[1]))

    return leftElement, rightElement

print(getNearest(self.symbolsSorted, (1200, 1500), 1000))

rawDescription: Get closest element from list of dictionaries


rawDescription: Run a shell script in background

description: Run a shell script in background


code:
# Read rawImage from a file, but in reality will have it from TCPServer
f = open('frame.png', "rb")
rawImage = f.read()
f.close()

# Convert rawImage to Mat
pilImage = Image.open(StringIO(rawImage));
npImage = np.array(pilImage)
matImage = cv.fromarray(npImage)

#show it
cv.NamedWindow('display')
cv.MoveWindow('display', 10, 10)
cv.ShowImage('display', matImage)
cv. WaitKey(0)

rawDescription: How to read raw png from an array in python opencv?

description: Read raw png from an array in python opencv


code: script: crawl.crawler.app

rawDescription: Yaml script handlers when porting App Engine app to Python 2.7


code:
from nltk.text import TokenSearcher

def find_donation_orgs(x):
    text = nltk.Text(nltk.word_tokenize(x))
    donation = TokenSearcher(text).findall(r"<\.> <.*>{,15}? <donat.*|contrib.*|Donat.*|Contrib.*> <.*>*? <to> (<.*>+?) <\.|\,|\;> ")
    return donation

rawDescription: .findall Regular Expression wont assign to a variable


code:
class switch:
    def __init__(self):
        self.__case_map = {}

        def set_case(key,f):
            self.__case_map[key] = f

        a = [getattr(self,e) for e in dir(self) if getattr(self,e) is not None and hasattr(getattr(self,e),'_switch__case')]
        for f in a:
            cases = getattr(f,'_switch__case')
            if isinstance(cases,tuple) or isinstance(cases,list):
                for c in cases: set_case(c,f)
            else:
                set_case(cases,f)

    def match(self,value):
        try:
            self.__case_map[value]
        except KeyError:
            return self.__case_map['_default']
        return self.__case_map[value]

    @staticmethod
    def case(comparision):
        def __assign_case(f):
            f.__case = comparision
            return f
        return __assign_case

class b(switch):
    @switch.case((1,3))
    def event_one(self):
        print('Event handler for 1,3 in b')

    @switch.case(2)
    def event_two(self):
        print('Event handler for 2 in b')

    @switch.case('_default')
    def default(self):
        print('No match was found, using default case')

a = b()
a.match(1)()
a.match(2)()
a.match(5)()

rawDescription: Using a decorator function that is a method in a class on other methods within the class in python


code:
def load_library(filename) :
    library = open(filename, 'rb')
    reader = csv.reader(library, delimiter = '|')
    tracks = set([])
    albums = {}

    for row in reader :
        artist, track, album, genre, year = row
        if album not in albums:
            a = Album(artist, album)
            albums[album] = a
        else:
            a = albums[album]
        a.add_track(track)
        track = Track(artist, track)
        track.set_album(album)
        tracks.add(track)
    return tracks, set(albums.values())

rawDescription: Python for loop efficiency

description: Python for loop efficiency


code:
def parseXML(path):
    '''
    @return: {property: value}
    '''
    # ...

def Bunch():
    return type("XML", tuple(), parseXML(PATH))

foo = Bunch()

rawDescription: Instantiate object after a string python?


rawDescription: Matching two comma seperated strings in Python and correct position counts


rawDescription: Count most frequent 100 words from sentences in Dataframe Pandas


code:
from sqlalchemy.orm import relationship

class Term(Base):
  __tablename__ = 'term'
  id = Column(Integer, primary_key=True)

class Node(Base):
  __tablename__ = 'node'
  id = Column(Integer, primary_key=True)
  term = Column(Integer, ForeignKey('term.id'))
  related_term = relationship(Term, backref="nodes")

rawDescription: SQLAlchemy foreign key lazy loading

description: SQLAlchemy foreign key lazy loading


code:
#! /usr/bin/python

import pymssql
con = pymssql.connect (host='xxxxx',user='xxxx',
                       password='xxxxx',database='xxxxx')
cur = con.cursor()
query = "DECLARE @id INT; EXECUTE sp_GetUserID; SELECT @id;"
cur.execute(query)
outputparameter = cur.fetchall()
con.commit()
con.close()

rawDescription: Cron job to connect to sql server and run a sproc using python


code:
class MyModelResource(ModelResource):
    class Meta:
        # If `object_class` is omitted, it's value is taken from
        # `queryset`, so defining both is optional.
        object_class = MyModel
        queryset = MyModel.objects.all()

    def dehydrate(self, bundle):
        # `model_class` == `MyModel`
        model_class = self._meta.object_class

        fields_list = model_class._meta.fields

rawDescription: Tastypie dehydrate for models that have specific types of fields


rawDescription: using list instead-of numpy array

description: Using list instead-of numpy array


code:
with open(...) as fp:
  c = csv.reader(fp)
  while True:
    try:
      title = next(c)[0]
      obj = set()
      store[title] = obj
    except StopIteration:
      break
    for row in itertools.takewhile(bool, c):
      obj.add(tuple(row))

rawDescription: Nested loops, iterators and csv

description: Nested loops, iterators and csv


code:
cursor.execute("SELECT * FROM student WHERE last_name = %(lname)s",
               {"lname": "Robert'); DROP TABLE students;--"})

rawDescription: Parameterized queries with psycopg2 / Python DB-API and PostgreSQL


code:
def my_function(s):
    print("a")
    size = len(s)
    print(size)
    return

my_function("abc")

rawDescription: Why doesn't this function call print anything?


code:
from django.http import HttpResponse
import xlwt

def excel_view(request):
  normal_style = xlwt.easyxf("""
     font:
         name Verdana
     """)
  response = HttpResponse(mimetype='application/ms-excel')
  wb = xlwt.Workbook()
  ws0 = wb.add_sheet('Worksheet')
  ws0.write(0, 0, "something", normal_style)
  wb.save(response)
  return response

rawDescription: Django/Python: Save an HTML table to Excel


code:
class Foo(Bar):
    def baz(self, arg):
        return super(Foo, self).baz(arg)

rawDescription: Call a parent class's method from child class in Python?


code:
s3_client = boto3.client('s3')
open('hello.txt').write('Hello, world!')

# Upload the file to S3
s3_client.upload_file('hello.txt', 'MyBucket', 'hello-remote.txt')

# Download the file from S3
s3_client.download_file('MyBucket', 'hello-remote.txt', 'hello2.txt')
print(open('hello2.txt').read())

rawDescription: How to save S3 object to a file using boto3

description: Save S3 object to a file using boto3


code:
df = pd.DataFrame({'A':[1,1,2,2],'B':[1,2,1,2],'values':np.arange(10,30,5)})
df
df['sum_values_A'] = df.groupby('A')['values'].transform(np.sum)
df

rawDescription: Pandas: Creating aggregated column in DataFrame


rawDescription: How to convert this SQL statement into Python: MID? SUBSTRING?

description: Convert this SQL statement into Python: MID? SUBSTRING