code:
import collections
from itertools import islice

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        collections.deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

def process_things(things):
    """
    build list from things where we skip every test_skip() and the next num_to_skip() items
    """
    result = []
    things = iter(things)
    for thing in things:
        if test_skip(thing):
            consume(things, num_to_skip(thing) - 1)
        else:
            result.append(thing)
    return result

rawDescription: Skip n list items in for loop

description: Skip n list items in for loop


code: l = [os.path.join(dir,x) for x in n]

rawDescription: python list from for loop into one list

description: Python list from for loop into one list


code:
import Tkinter as tk
import ttk

root=tk.Tk()
pb = ttk.Progressbar(mode="indeterminate")
pb.pack(side="bottom", fill="x")
pb.start()
root.wm_geometry("300x300")
root.mainloop()

rawDescription: Python 2.7/Windows resizable ttk progressbar?


code:
import mimetypes
mimetypes.init()
mimetypes.knownfiles

rawDescription: hgweb raw view returns the wrong content-type

description: Hgweb raw view returns the wrong content-type


code:
from Tkinter import *
from glob import glob

class ImageFrame(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.images = glob("*.gif")
        self.cur = 0
        # label showing the image
        self.image = PhotoImage()
        imagelabel = Label(self, image=self.image)
        imagelabel.grid(row=1, column=1)
        # button cycling through the images
        button = Button(self, text="NEXT", command=self.show_next)
        button.grid(row=2, column=1)
        # layout and show first image
        self.grid()
        self.show_next()

    def show_next(self):
        self.cur = (self.cur + 1) % len(self.images)
        self.image.configure(file=self.images[self.cur])

ImageFrame().mainloop()

rawDescription: Adding image to Tkinter

description: Adding image to Tkinter


rawDescription: Autoscroll PyQT QTextWidget

description: Autoscroll PyQT QTextWidget


rawDescription: Add rate of change to Pandas DataFrame

description: Add rate of change to Pandas DataFrame


code:
class BulkDeleteView(View):
    model = None

    def post(self, request, *args, **kwargs):
        delete_ids = request.POST['delete_ids'].split(',')  # should validate
        self.model.objects.filter(pk__in=delete_ids).delete()
        return render / redirect

rawDescription: Django - how to bulk delete

description: Django - how to bulk delete


code:
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        do_the_login()
    else:
        show_the_login_form()

rawDescription: Writing webapps in python without Django or any framework


code:
from multiprocessing import Pool
import sys

if __name__ == '__main__':

    job_list = [xrange(10000000)]*6

    if 'p' in sys.argv:
        p = Pool(2)
        print("Parallel map")
        print(p.map(sum, job_list))
    else:
        print("Sequential map")
        print(map(sum, job_list))

rawDescription: Multithreading in Python with a ThreadPool


code: [plt.plot(data[0],data[x]) for x in range(1,len(data[:,0]))]

rawDescription: matplotlib plot csv file of all columns

description: Matplotlib plot csv file of all columns


code:
import pygame
import Tkinter as tk
from Tkinter import *
import os

root = tk.Tk()
embed = tk.Frame(root, width = 500, height = 500) #creates embed frame for pygame window
embed.grid(columnspan = (600), rowspan = 500) # Adds grid
embed.pack(side = LEFT) #packs window to the left
buttonwin = tk.Frame(root, width = 75, height = 500)
buttonwin.pack(side = LEFT)
os.environ['SDL_WINDOWID'] = str(embed.winfo_id())
os.environ['SDL_VIDEODRIVER'] = 'windib'
screen = pygame.display.set_mode((500,500))
screen.fill(pygame.Color(255,255,255))
pygame.display.init()
pygame.display.update()
def draw():
    pygame.draw.circle(screen, (0,0,0), (250,250), 125)
    pygame.display.update()
button1 = Button(buttonwin,text = 'Draw',  command=draw)
button1.pack(side=LEFT)
root.update()

while True:
    pygame.display.update()
    root.update()

rawDescription: Draw a circle in Pygame using Tkinter

description: Draw a circle in Pygame using Tkinter


code:
# first we need a generator for each type of response to `input()`

def tray_number_generator():
    trays = ["1", "5", "7"]
    for i in trays:
        yield i

trays = tray_number_generator()

def room_number_generator():
    rooms = ["112", "543", "724"]
    for i in rooms:
        yield i

rooms = room_number_generator()

# this can be written simpler as a generator expression like this:

trays = (tray for tray in ["1", "5", "7"])
rooms = (room for room in ["112", "543", "724"])

# now you can write a function that selects the next output depending on the prompt:

def mock_input(prompt):
    if "room" in prompt.lower():
        return next(rooms)
    if "tray" in prompt.lower():
        return next(trays)

# this can now be used to replace the `input()` function

with mock.patch('builtins.input', mock_input):
    do_stuff()

rawDescription: Python using mock for a multiple user inputs


code:
l = ['a', 'b', 'c', 'A', 'B', 'C', 'a', 'b', 'c']
new_list = list(set(elem.lower() for elem in l))
new_list

rawDescription: The condition skips 2 members of a list

description: The condition skips 2 members of a list


code:
p1 = Session.query(Parent).get(...)
p2 = Session.query(Parent).get(...)

for child in p2.children[:]:
    child.parent = p1

Session.delete(p2)
Session.commit()

rawDescription: How to change parent using relations in sqlalchemy?

description: Change parent using relations in sqlalchemy


code:
import matplotlib.pyplot as plt

plt.plot(range(10))

plt.figure()
plt.plot(range(10), 'ro-')

plt.show()

rawDescription: Is it possible to have multiple PyPlot windows? Or am I limited to subplots?


code:
def sortqns(qnlist):
    return sorted(qnlist, key = lambda x: (len(x), x))

rawDescription: Python sorted with list of alpha-numeric strings?


code:
class C(metaclass=MC):
    pass

rawDescription: String representation of a class in Python 3


code: takewhile(lambda x: x<1, accumulate(math.log(x,2) for x in items.values()))

rawDescription: Partial sums of a dictionary's values

description: Partial sums of a dictionary's values


code:
from flask import Flask

app = Flask(__name__, static_folder='static', static_url_path='')

rawDescription: Static files in Flask - robot.txt, sitemap.xml (mod_wsgi)


code:
from ckeditor.fields import RichTextField
class Heading(models.Model):
    content = models.RichTextField()

rawDescription: is there any way to change the default text editor for textfield django in admin panel?

description: Is there any way to change the default text editor for textfield django in admin panel


code:
df = DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})
df.columns
df.columns.get_loc("pear")

rawDescription: Retrieving column index from column name in python pandas


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

x  = np.random.random(200)
y1 = np.random.random(200)
y2 = np.random.random(200)

pl.figure()
pl.subplot(131)
h1=pl.hexbin(x, y1, gridsize=3, vmin=0, vmax=40, cmap=pl.cm.RdBu_r)
pl.colorbar()

pl.subplot(132)
h2=pl.hexbin(x, y2, gridsize=3, vmin=0, vmax=40, cmap=pl.cm.RdBu_r)
pl.colorbar()

pl.subplot(133)
# Create dummy hexbin using whatever data..:
h3=pl.hexbin(x, y2, gridsize=3, vmin=-10, vmax=10, cmap=pl.cm.RdBu_r)
h3.set_array(h1.get_array()-h2.get_array())
pl.colorbar()

rawDescription: How to create a difference map between two matplotlib hexbin maps?

description: Create a difference map between two matplotlib hexbin maps


code:
import networkx as nx
G = nx.DiGraph()
G.add_edge(1,2)
G.graph['graph']={'rankdir':'LR'}
import sys
nx.write_dot(G, sys.stdout)

rawDescription: How to add dot's graph attribute into final dot output

description: Add dot's graph attribute into final dot output


code:
d = {}

keyList1 = ["Person", "Male", "Boy", "Student", "id_123", "Name"]
keyList2 = ["Person", "Male", "Boy", "Student", "id_123", "Age"]
value1 = "Roger"
value2 = 3

def insert(cur, list, value):
    if len(list) == 1:
        cur[list[0]] = value
        return
    if not cur.has_key(list[0]):
        cur[list[0]] = {}
    insert(cur[list[0]], list[1:], value)

insert(d, keyList1, value1)
insert(d, keyList2, value2)

{'Person': {'Male': {'Boy': {'Student': {'id_123': {'Age': 3, 'Name': 'Roger'}}}}}}

rawDescription: Python Generate a dynamic dictionary from the list of keys


code:
from tkinter import *
v=Tk()
v.geometry("400x400")
a= IntVar()
# round function simply rounds the var upto given number of decimal places in the function argument
a.set(round(5.494949,2))

l=Label(textvariable= a)
l.pack()

rawDescription: How use decimal in a label with IntVar on tkinter


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

mu = 0
variance = 1
sigma = math.sqrt(variance)
x = np.linspace(-3, 3, 100)
plt.plot(x,mlab.normpdf(x, mu, sigma))

plt.show()

rawDescription: python pylab plot normal distribution

description: Python pylab plot normal distribution


code:
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import matplotlib.dates as mdates

import datetime as dt

n_pts = 10
dates = [dt.datetime.now() + dt.timedelta(days=i) for i in range(n_pts)]

ax1 = plt.subplot(2, 1, 1)
ax1.plot(dates, range(10))

ax2 = plt.subplot(2, 1, 2, sharex=ax1)
ax2.bar(dates, range(10, 20))

# Now format the x axis. This *MUST* be done after all sharex commands are run.

# put no more than 10 ticks on the date axis.
ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
# format the date in our own way.
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

# rotate the labels on both date axes
for label in ax1.xaxis.get_ticklabels():
    label.set_rotation(30)
for label in ax2.xaxis.get_ticklabels():
    label.set_rotation(30)

# tweak the subplot spacing to fit the rotated labels correctly
plt.subplots_adjust(hspace=0.35, bottom=0.125)

plt.show()

rawDescription: matplotlib: Creating two (stacked) subplots with SHARED X axis but SEPARATE Y axis values

description: Matplotlib: Creating two (stacked) subplots with SHARED X axis but SEPARATE Y axis values


code: results = re.search('ipAddress=([^&]*)', line)

rawDescription: Regex in Python

description: Regex in Python


code:
class ValidationRule:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

rawDescription: Copy **kwargs to self?

description: Copy **kwargs to self


code:
def safe_cast(val, to_type, default=None):
    try:
        return to_type(val)
    except ValueError:
        return default

safe_cast('tst', int) # will return None
safe_cast('tst', int, 0) # will return 0

rawDescription: Safe casting in python

description: Safe casting in python


code: s.split(", ")

rawDescription: Regex to match comma-separated strings containing comma-formatted decimals


code:
import numpy as np

df['Dcount'] = np.where(df['A']=='foo', sum((df.A=='foo') & (df.D==2)), np.NaN)

#In [34]: df
#Out[34]:
#     A  D  Dcount
#0  foo  2       2
#1  foo  4       2
#2  foo  4       2
#3  foo  2       2
#4  bar  5     NaN
#5  bar  4     NaN
#6  bar  3     NaN
#7  bar  2     NaN

rawDescription: Pandas Conditional Groupby Count Part 2

description: Pandas Conditional Groupby Count Part 2


code:
aux = ''
'\n'.join(iter(input, aux))

rawDescription: Input a multiline string in python

description: Input a multiline string in python


code: [''.join(str(y) for y in x) for x in itertools.product(a, b, c)]

rawDescription: Simple way to create possible case

description: Simple way to create possible case


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

x = np.array( [
[ [0.0, 1.0], [0.0, 1.0], [0.0, 1.0]  ],  #element 0
[ [1.0, 2.0], [1.0, 2.0], [1.0, 2.0]  ],  #element 1
[ [2.0, 3.0], [2.0, 3.0], [2.0, 3.0]  ],  #element 2
] )

y = np.array( [
[ [0.0, 0.0], [0.5, 0.5], [1.0, 1.0]  ],  #element 0
[ [0.0, 1.0], [0.5, 1.5], [1.0, 2.0]  ],  #element 1
[ [1.0, 1.0], [1.5, 1.5], [2.0, 2.0]  ],  #element 2
] )

z = np.array( [
[ [0.0, 0.5], [0.0, 0.8], [0.0, 1.0]  ],  #element 0
[ [0.3, 1.0], [0.6, 1.2], [0.8, 1.3]  ],  #element 1
[ [1.2, 1.5], [1.3, 1.4], [1.5, 1.7]  ],  #element 2
] )

global_num_pts =  z.size
global_x = np.zeros( global_num_pts )
global_y = np.zeros( global_num_pts )
global_z = np.zeros( global_num_pts )
global_triang_list = list()

offset = 0;
num_triangles = 0;

#process triangulation element-by-element
for k in range(z.shape[0]):
    points_x = x[k,...].flatten()
    points_y = y[k,...].flatten()
    z_element = z[k,...].flatten()
    num_points_this_element = points_x.size

    #auto-generate Delauny triangulation for the element, which should be flawless due to quadrilateral element shape
    triang = tri.Triangulation(points_x, points_y)
    global_triang_list.append( triang.triangles + offset ) #offseting triangle indices by start index of this element

    #store results for this element in global triangulation arrays
    global_x[offset:(offset+num_points_this_element)] = points_x
    global_y[offset:(offset+num_points_this_element)] = points_y
    global_z[offset:(offset+num_points_this_element)] = z_element

    num_triangles += triang.triangles.shape[0]
    offset += num_points_this_element

#go back and turn all of the triangle indices into one global triangle array
offset = 0
global_triang = np.zeros( (num_triangles, 3) )
for t in global_triang_list:
    global_triang[ offset:(offset+t.shape[0] )] = t
    offset += t.shape[0]

plt.figure()
plt.gca().set_aspect('equal')

plt.tripcolor(global_x, global_y, global_triang, global_z, shading='gouraud' )
#plt.tricontour(global_x, global_y, global_triang, global_z )
#plt.triplot(global_x, global_y, global_triang, 'go-') #plot just the triangle mesh

plt.xlim((-0.25, 3.25))
plt.ylim((-0.25, 2.25))
plt.show()

rawDescription: python: How to plot 2D discontinuous node-centered data?

description: Python: How to plot 2D discontinuous node-centered data


code:
import random

def shuffle_list(some_list):
    randomized_list = some_list[:]
    while True:
        random.shuffle(randomized_list)
        for a, b in zip(some_list, randomized_list):
            if a == b:
                break
        else:
            return randomized_list

rawDescription: python shuffle such that position will never repeat

description: Python shuffle such that position will never repeat


code:
from chef import autoconfigure, Client
api = autoconfigure()
Client.delete('notcool.my.com')
Client.create('cool.my.com')

rawDescription: how to do 'knife client delete' and 'knife client create' using PyChef?

description: Do 'knife client delete' and 'knife client create' using PyChef


code:
def do_something():
    """
    @rtype: list of SomeClass
    """
    pass

rawDescription: PyCharm autocomplete, list of types

description: PyCharm autocomplete, list of types


code:
from numpy import *

hit_idx = (0,4)

# Define a graph by edge list
edges = [[0,1],[1,2],[2,3],[2,4]]

# Create adj. matrix
A = zeros((5,5))
A[zip(*edges)] = 1
# Undirected condition
A += A.T

# Make the final state an absorbing condition
A[hit_idx[1],:] = 0
A[hit_idx[1],hit_idx[1]] = 1

# Make a proper Markov matrix by row normalizing
A = (A.T/A.sum(axis=1)).T

B = A.copy()
Z = []
for n in xrange(100):
    Z.append( B[hit_idx] )
    B = dot(B,A)

from pylab import *
plot(Z)
xlabel("steps")
ylabel("hit probability")
show()

rawDescription: Calculate Hitting Time between 2 nodes using NetworkX


code:
class Subclass(Superclass):
    def __init__(self):
        Superclass.__init__(self)

class Subclass(Superclass):
    def __init__(self):
        super(Subclass, self).__init__()

rawDescription: subclass __init__ overrides superclass's

description: Subclass __init__ overrides superclass's


code:
for my_key in my_dict:
    my_dict[my_key] = IntVar()
    cb = Checkbutton(text=my_key, variable=my_dict[my_key])
    self.checkbox_text.window_create("END", window=cb)
    self.checkbox_text.insert("END", "\n")

rawDescription: Tkinter: Working with Checkbutton + Scrollbar inside a Text widget


code:
from multiprocessing import Queue, Process

def processor():
    setproctitle('%s - processor ' % (__file__,))

    while True:
        time.sleep(1)
        do_stuff()

my_processor = Process(target=processor)

rawDescription: Long running background task in a Bottle application


code:
with open("mytextfile.txt", "rtU") as f:
  for line in f:
    # Now you have one line of text in the variable "line" and can
    # iterate over its characters like so:
    for ch in line:
      ... # do something here

rawDescription: How to parse a file line by line, char by char in Python?

description: Parse a file line by line, char by char in Python


code:
def view_handler(request):
    if hasattr(request, 'mycache'):
        request.mycache['counter'] += 1
    else:
        request.mycache = {'counter':1,}

    return HttpResponse("counter="+str(request.mycache["counter"]))

rawDescription: How can I create a variable that is scoped to a single request in app engine?

description: Create a variable that is scoped to a single request in app engine


code:
class ConvertingDateTimeFeild(models.DateTimeField):

    def get_prep_value(self, value):
        return str(datetime.strptime(value, FORMAT_STRING))

rawDescription: Passing date time in a different format to models.DateTimeField in Django?


code:
def processRGB(item, matrix):
    threshhold = 229
    red, green, blue = matrix[0, 0]
    if red <= threshhold and green <= threshhold and blue <= threshhold:
        picture, boundary = RGBUpright(item, matrix, 0)
        red, green, blue = matrix[item[0].size[0] - 1, 0]
    elif red <= threshhold and green <= threshhold and blue <= threshhold:
        picture, boundary = RGBUpright(item, matrix, 90)
        red, green, blue = matrix[0, item[0].size[1] - 1]
    elif red <= threshhold and green <= threshhold and blue <= threshhold:
        picture, boundary = RGBUpright(item, matrix, 180)
        red, green, blue = matrix[item[0].size[0] - 1, item[0].size[1] - 1]
    elif red <= threshhold and green <= threshhold and blue <= threshhold:
        picture, boundary = RGBUpright(item, matrix, 270)
    final = picture[0].crop(boundary)
    final.load()
    return final

rawDescription: in Python 2.7.5, why is "if (code)" valid syntax but "elif (same code)" isn't?

description: In Python 2.7.5, why is "if (code)" valid syntax but "elif (same code)" isn't


code: article.find_all(lambda x: x.name == 'ul' and x.find_parent("ul") is None)

rawDescription: BeautifulSoup dont search recursive in already found tag


code:
from multiprocessing import Process, Queue
from subprocess import check_output, CalledProcessError

def cmdloop(inQueue,outQueue):
    while True:
        command = inQueue.get()
        try:
            result = check_output(command,shell=True)
        except CalledProcessError as e:
            result = e

        outQueue.put(result)

inQueue = Queue()
outQueue = Queue()
cmdHostProcess = Process(target=cmdloop, args=(inQueue,outQueue,))
cmdHostProcess.start()

def callCommand(command):
    global inQueue,outQueue
    inQueue.put(command)
    return outQueue.get()

def killCmdHostProcess():
    global cmdHostProcess
    cmdHostProcess.terminate()

rawDescription: subprocess.check_output without high memory usage

description: Subprocess.check_output without high memory usage


code:
import sets
string = "garbage1and2recycling"
charlist = ['1', '2']
charset = sets.Set(charlist)
index = 0
for index in range(len(string)):
    if string[index] in charset: break
print(index) # 7

rawDescription: using find with multiple strings to search within larger string

description: Using find with multiple strings to search within larger string


code:
my_list = ['csv (2).zip', 'csv (5).zip', 'csv (1).zip']
print(sorted(my_list, key = lambda x: int(x[x.index("(") + 1 : x.rindex(")")])))
# ['csv (1).zip', 'csv (2).zip', 'csv (5).zip']

rawDescription: Python - Ordering a list numerically

description: Python - Ordering a list numerically


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

def axis_to_fig(axis):
    fig = axis.figure
    def transform(coord):
        return fig.transFigure.inverted().transform(
            axis.transAxes.transform(coord))
    return transform

def add_sub_axes(axis, rect):
    fig = axis.figure
    left, bottom, width, height = rect
    trans = axis_to_fig(axis)
    figleft, figbottom = trans((left, bottom))
    figwidth, figheight = trans([width,height]) - trans([0,0])
    return fig.add_axes([figleft, figbottom, figwidth, figheight])

x = np.linspace(-np.pi,np.pi)
fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10,10))

for axis in axes.ravel():
    axis.set_xlim(-np.pi, np.pi)
    axis.set_ylim(-1, 3)
    axis.plot(x, np.sin(x))
    subaxis = add_sub_axes(axis, [0.2, 0.6, 0.3, 0.3])
    subaxis.plot(x, np.cos(x))

plt.show()

rawDescription: fig.add_subplot() *transform* doesn't work?

description: Fig.add_subplot() *transform* doesn't work


code:
@app.task
def determine_bmi(person_id):
    person = Person.objects.get(pk=person_id)
    person.compute_bmi()

rawDescription: Celery object editing best-practices

description: Celery object editing best-practices


code:
import pygame, sys
from pygame.locals import *
import random

FPS = 30  # frames per second
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

class Thing(pygame.Rect):
    def __init__(self, *args, **kwargs):
        super(Thing, self).__init__(*args, **kwargs)  # init Rect base class
        # define additional attributes
        self.color = tuple(random.randrange(0, 256) for _ in range(3))
        self.x_speed, self.y_speed = 5, 5  # how fast it moves

    def draw(self, surface, width=0):
        pygame.draw.rect(surface, self.color, self, width)

def main():
    pygame.init()
    fpsclock = pygame.time.Clock()
    pygame.key.set_repeat(250)  # enable keyboard repeat for held down keys
    gameDisplay = pygame.display.set_mode((500,400), 0,32)
    gameDisplay.fill(WHITE)

    thingx,thingy, thingw,thingh = 200,150, 100,50
    thing = Thing(thingx, thingy, thingw, thingh)  # create an instance

    while True:  # display update loop
        gameDisplay.fill(WHITE)

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == KEYDOWN:
                if event.key == K_DOWN:
                    thing.y += thing.y_speed
                elif event.key == K_UP:
                    thing.y -= thing.y_speed
                elif event.key == K_RIGHT:
                    thing.x += thing.x_speed
                elif event.key == K_LEFT:
                    thing.x -= thing.x_speed

        thing.draw(gameDisplay)  # display at current position
        pygame.display.update()
        fpsclock.tick(FPS)

main()

rawDescription: Python random colors flickering on object


code:
import random

with\
  open('vocablist.text') as input,\
  open('vocab_out.txt', 'w') as output:
    lines = [line.rstrip('\n') for line in input.readlines()]
    random.shuffle(lines)
    zz = 0
    for x in lines:
      zz += 1
      if zz > 142:
          output.write('END OF SECTION' + '\n')
          zz = 0
      output.write(x + '\n')

rawDescription: Opening, randomizing, writing a list of lines in Python 2.7.6.1


code:
count = 148833
print(str(count)[0:2])

rawDescription: Putting a cap on the display of an integer in python?


code:
import numpy as np
single_point = [3, 4]
points = np.arange(20).reshape((10,2))

dist = (points - single_point)**2
dist = np.sum(dist, axis=1)
dist = np.sqrt(dist)

rawDescription: python numpy euclidean distance calculation between matrices of row vectors

description: Python numpy euclidean distance calculation between matrices of row vectors


code:
import wx

def scale(widget, percentage):
    font = widget.GetFont()
    font.SetPointSize(int(font.GetPointSize() * percentage / 100.0))
    widget.SetFont(font)

class Frame(wx.Frame):
    def __init__(self):
        super(Frame, self).__init__(None, -1, 'Scaling Fonts')
        panel = wx.Panel(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        for i in range(50, 201, 25):
            widget = wx.StaticText(panel, -1, 'Scale Factor = %d' % i)
            scale(widget, i)
            sizer.Add(widget, 0, wx.ALL, 5)
        panel.SetSizer(sizer)

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = Frame()
    frame.Show()
    app.MainLoop()

rawDescription: Flexible 'em' style Fonts with wxPython

description: Flexible 'em' style Fonts with wxPython


code:
import pandas
from faker import Factory
import random

faker = Factory.create()
status = 'created,delivered,returned'.split(',')

def date_between(d1, d2):
    f = '%b%d-%Y'
    return faker.date_time_between_dates(datetime.strptime(d1, f), datetime.strptime(d2, f))

def fakerecord():
    return {'awb': faker.numerify('######'),  # random number eg:235533
            'destination_city': faker.city(),  # random cities
            'product': 'random_product',  # different products
            'product_category': 'random_category',  # different categories
            'origin_city': faker.city(),  # random metro cities
            'logistics_provider_id': faker.numerify('##'),  # id's eg:1,20,28,27
            'dispatch_date': date_between('mar01-2015', 'mar15-2015'),  # datetime between mar01-2015 to mar15-2015
            'final_delivery_status': random.choice(status),  # created,delivered,returned
            'actual_delivery_date': date_between('mar16-2015', 'mar30-2015'),  # datetime between mar16-2015 to mar30-2015
            'promised_delivery_date': date_between('mar25-2015', 'apr06-2015'),  # datetime between mar25-2015 to Apr6-2015
            }

example_dummy_data = pandas.DataFrame([fakerecord() for _ in range(1000)])

rawDescription: How to create dummy data with different datatypes in python?

description: Create dummy data with different datatypes in python


code:
def my_view(request, ):
   search_term = request.GET.get("q", None) #--> q means "name" of select box in html.
   # use search_term whatever you wants.

rawDescription: How to get the value from html form and use it in views.py?

description: Get the value from html form and use it in views.py


code:
import matplotlib.pyplot as plt

# Create something similar to your pickled figure......
fig, (ax1, ax2) = plt.subplots(ncols=2)
ax1.plot(range(10), 'r^-')
ax1.set(title='Originally on the left')

ax2.plot(range(10), 'gs-')
ax2.set(title='Originally on the right')

# Now we'll swap their positions after they've been created.
pos1 = ax1.get_position()
ax1.set_position(ax2.get_position())
ax2.set_position(pos1)

plt.show()

rawDescription: Matplotlib: reorder subplots

description: Matplotlib: reorder subplots


rawDescription: using python.itertools to sum slots across multiple lists

description: Using python.itertools to sum slots across multiple lists


code:
from datetime import datetime, timedelta
Example.objects.filter(date_created__lte=datetime.utcnow() -
                          timedelta(days=6*30)).delete()

rawDescription: Django Queryset for date

description: Django Queryset for date


code:
class TestClass:

  def __init__(self, adir=None, alist=None, avar=None):
    if alist is None:
      alist = []
    if adir is None:
      adir = {}

rawDescription: In python __init__ dictionary arguments defaulting to previous class values


code:
import arff

X = []
y = []

for row in arff.load('cpu.arff'):
    X.append(row[:-1])
    y.append(row[-1])

rawDescription: How to deal with data from arff file with python?

description: Deal with data from arff file with python


code:
import ogr
import matplotlib.path as mpath
import matplotlib.patches as patches
import matplotlib.pyplot as plt

ds = ogr.Open('lmes_64.shp')
lyr = ds.GetLayer(0)
ft = lyr.GetFeature(38)
geom = ft.GetGeometryRef()
ds = None

codes = []
all_x = []
all_y = []

if (geom.GetGeometryType() == ogr.wkbPolygon):
  for i in range(geom.GetGeometryCount()):

    r = geom.GetGeometryRef(i)
    x = [r.GetX(j) for j in range(r.GetPointCount())]
    y = [r.GetY(j) for j in range(r.GetPointCount())]

    codes += [mpath.Path.MOVETO] + (len(x)-1)*[mpath.Path.LINETO]
    all_x += x
    all_y += y

if (geom.GetGeometryType() == ogr.wkbMultiPolygon):
  codes = []
  for i in range(geom.GetGeometryCount()):
    # Read ring geometry and create path
    r = geom.GetGeometryRef(i)
    for part in r:
      x = [part.GetX(j) for j in range(part.GetPointCount())]
      y = [part.GetY(j) for j in range(part.GetPointCount())]
      # skip boundary between individual rings
      codes += [mpath.Path.MOVETO] + (len(x)-1)*[mpath.Path.LINETO]
      all_x += x
      all_y += y

carib_path = mpath.Path(np.column_stack((all_x,all_y)), codes)
carib_patch = patches.PathPatch(carib_path, facecolor='orange', lw=2)

poly1 = patches.Polygon([[-80,20],[-75,20],[-75,15],[-80,15],[-80,20]], zorder=5, fc='none', lw=3)
poly2 = patches.Polygon([[-65,25],[-60,25],[-60,20],[-65,20],[-65,25]], zorder=5, fc='none', lw=3)

fig, ax = plt.subplots(1,1)

for poly in [poly1, poly2]:
    if carib_path.intersects_path(poly.get_path()):
        poly.set_edgecolor('g')
    else:
        poly.set_edgecolor('r')

    ax.add_patch(poly)

ax.add_patch(carib_patch)
ax.autoscale_view()

rawDescription: Create closed polygon from boundary points


code:
def newfile():
    current = None
    def create_file(entry):
        nonlocal current
        current = open(entry.get(),'w')
        e.master.destroy()
    chdir(askdirectory())
    name=Tk()
    name.title("Name the File?")
    prompt=Label(name, text="Enter name for new file:")
    prompt.grid(row=0)
    e=Entry(name)
    e.grid(row=1)
    e.insert(0, "Untitled")
    create=Button(name, text="Create", command = lambda: create_file(e))
    create.grid(row=2, column=3)
    name.mainloop()
    return current

rawDescription: Getting return value from tkinter button when clicked


rawDescription: How can I append these entries to the list?

description: Append these entries to the list


code:
from flask import g, request

@babel.localeselector
def get_locale():
    # if a user is logged in, use the locale from the user settings
    user = getattr(g, 'user', None)
    if user is not None:
        return user.locale
    # otherwise try to guess the language from the user accept
    # header the browser transmits.  We support de/fr/en in this
    # example.  The best match wins.
    return request.accept_languages.best_match(['de', 'fr', 'en'])

rawDescription: Flask-babel: translation per user

description: Flask-babel: translation per user


code:
@register.filter
@stringfilter
def datedate(value,format="%d/%m/%Y"):
    try:
        return parse_datetime(value).strftime(format)
    except Exception as e:
        return ""

rawDescription: How to get a localized date on Django template using a specific format?

description: Get a localized date on Django template using a specific format


code:
EVT_SET_FOCUS
EVT_KILL_FOCUS

rawDescription: wxPython: Making a frame be on top of everything

description: WxPython: Making a frame be on top of everything


rawDescription: Test if numpy array contains only zeros

description: Test if numpy array contains only zeros


code:
from PyQt4.QtCore import Qt, QRect
from PyQt4.QtGui import QTableWidget, QApplication, QHeaderView, QStyleOptionButton, QStyle

import sys

class MyHeader(QHeaderView):

    isOn = False

    def __init__(self, orientation, parent=None):
        QHeaderView.__init__(self, orientation, parent)

    def paintSection(self, painter, rect, logicalIndex):
        painter.save()
        QHeaderView.paintSection(self, painter, rect, logicalIndex)
        painter.restore()

        if logicalIndex == 0:
            option = QStyleOptionButton()
            option.rect = QRect(10, 10, 10, 10)
            if self.isOn:
                option.state = QStyle.State_On
            else:
                option.state = QStyle.State_Off
            self.style().drawControl(QStyle.CE_CheckBox, option, painter)

    def mousePressEvent(self, event):
        self.isOn = not self.isOn
        self.updateSection(0)
        QHeaderView.mousePressEvent(self, event)

class MyTable(QTableWidget):
    def __init__(self):
        QTableWidget.__init__(self, 3, 3)

        myHeader = MyHeader(Qt.Horizontal, self)
        self.setHorizontalHeader(myHeader)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    myTable = MyTable()
    myTable.show()
    sys.exit(app.exec_())

rawDescription: PySide/PyQt4: adding a checkbox to QTableWidget Horizontal (column) Header


code:
import networkx as nx
import matplotlib.pyplot as plt

def flatline(iterable):
    for line in iterable:
        for val in line.split():
            yield float(val)

with open(filename, 'r') as f:
    G = nx.balanced_tree(r = 2, h = 100, create_using = nx.DiGraph())
    for (a, b), val in zip(G.edges(), flatline(f)):
        G[a][b]['weight'] = val

# print(G.edges(data = True))

pred, distance = nx.dijkstra_predecessor_and_distance(G, 0)

# Find leaf whose distance from `0` is smallest
min_dist, leaf = min((distance[node], node)
                     for node, degree in G.out_degree_iter()
                     if degree == 0)
nx.draw(G)
plt.show()

rawDescription: Directed, weighted balanced tree import and shortest path in networkx


code:
class Machine(object):
    def __init__(self, name, max_rating, min_rating, cur_rating=1):
        self.max_rating = max_rating
        self.min_rating = min_rating
        self._cur_rating = cur_rating

    @property
    def cur_rating(self):
        return self._cur_rating

    @cur_rating.setter
    def cur_rating(self, value):
        if value > self.max_rating or value < self.min_rating:
            raise Exception()
        self._cur_rating = value

rawDescription: Raise an exception if class attribute is set to a certain value after instantiation


code:
sorted(lst, key=lambda x: x[1], reverse=True)
sorted(lst, key=lambda x: -x[1])
import operator
sorted(lst, key=operator.itemgetter(1), reverse=True)

rawDescription: Python Sort Multidimensional Array Based on 2nd Element of Subarray


code:
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    (r'^django/demoInstall/', include('site_urls.py')),
)

rawDescription: Django-modpython deploying project

description: Django-modpython deploying project


code: take = [row for row in lines if row[:3] == seen]

rawDescription: variable size array matching

description: Variable size array matching


code:
fd = open(filename, "r+")
text = fd.read()
text = text.replace("\t", "\t" + "Inserted text", 1)
fd.seek(0)
fd.write(text)
fd.close()

rawDescription: Python: Inserting text after a tab in a text file


code:
def read_utf8(filename):
    with codecs.open(filename, mode="r", encoding="utf8") as f:
         return f.read()

header = read_utf8("static/header")

rawDescription: How to shorten some lines that include codecs.open?

description: Shorten some lines that include codecs.open


code:
from xml.etree import ElementTree
elt = ElementTree.Element("")
callable(elt.keys)
callable(elt.text)

rawDescription: how to distinguish between a method and an attribute in python by name

description: Distinguish between a method and an attribute in python by name


code:
with open("objectname.p","w") as f:
    pickle.dump(objectname, f)

rawDescription: do I still need to file.close() when dumping a pickle in one line?

description: Do I still need to file.close() when dumping a pickle in one line


code: y = v + z.sum(axis=1)

rawDescription: Add the elements in a row, for each row, in a matrix, using theano


rawDescription: PySide QTextEdit or QPlainTextEdit update faster?


code:
import json

with open('data.js') as f:
    content = json.load(f)

name = input("Name: ")
age = input("Age: ")

person = {"name": name, "Age": age} #Build object for new person ...
content['data'].append(person) # .. and append it to your existing 'data'

with open("data.js", "w") as file:
    json.dump(content, f)

rawDescription: How do I add/append data to a js file, from html and or python3

description: Add/append data to a js file, from html and or python3


code:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1,101,100)
y = np.linspace(-1,101,100)
x, y = np.meshgrid(x, y)
z = x*x+y*y
plt.figure()
plt.xlim(0, 50)
plt.contourf(x, y, z)
plt.show()

rawDescription: Can python/matplotlib's confourf be made to plot a limited region of data?


code:
def foo():
    if not hasattr(Singleton, "_instance"):
        with Singleton._instance_lock:
            if not hasattr(Singleton, "_instance"):
                Singleton._instance = Singleton()
    return Singleton._instance

dis.dis(foo)

rawDescription: Is getattr/setattr/hasattr/delattr thread safe?


code:
import os
import fnmatch
path='Your Path'
with open(os.path.join(path,'horse.txt'),'w') as hfile:
    for r, d, fs in os.walk(path):
      for f in fnmatch.filter(fs, '*.jpg'):
          hfile.write(os.path.join(r, f))
          hfile.write(os.linesep)

rawDescription: Python search for file and create output, write content


code:
pat = 'TimeStamp    GazePointXLeft  GazePointYLeft  ValidityLeft    GazePointXRight GazePointYRight ValidityRight   GazePointX  GazePointY  Event'
with open(bhpath+fileid+'_wmet.tsv') as infile:
    eye_data = infile.read().split(pat)
    eye_data = [trial.split('\r\n') for trial in eye_data] # split at '\r'
    for idx, trial in enumerate(eye_data):
        trial = [row.split('\t') for row in trial]
        eye_data[idx] = trial

rawDescription: iteratively read (tsv) file for Pandas DataFrame

description: Iteratively read (tsv) file for Pandas DataFrame


rawDescription: How to vertically align Paragraphs within a Table using Reportlab?

description: Vertically align Paragraphs within a Table using Reportlab


code: max(((k, len(v)) for k, v in dic.items()), key=lambda x: x[1])

rawDescription: How to count the number of values associated with a key

description: Count the number of values associated with a key


rawDescription: Pandas: frequency of an element in two groups of columns


code:
import operator
import sys

py3k = sys.version_info[0] > 2

a = dict()
b = dict()
a[1,3] = 5, 6, 7
b[1,4] = 5, 9, 7

if(py3k):
  a_tuple = next(iter(a.values()))
  b_tuple = next(iter(b.values()))
else:
  a_tuple = a.values()[0]
  b_tuple = b.values()[0]

cmp_key=operator.itemgetter(0,2)
if cmp_key(a_tuple) == cmp_key(b_tuple):
  print('Equal')

rawDescription: Comparing the values of two dict_values based on certain criteria


rawDescription: Python Regex not extracting function name from line


rawDescription: Pairwise matrix multiplication with MultiIndex


code:
import os.path
import glob
jsons = glob.glob(os.path.join(DIR2, dirname, '*', '*.json'))
subprocess.Popen(["nohup", "python", DIR4] + jsons)

rawDescription: Getting path in python script

description: Getting path in python script


code:
np.std(sd)
np.std(df.values)

rawDescription: Standard deviation for DF, pandas

description: Standard deviation for DF, pandas


code:
array = [[1,2,3], [4,5,6]]
[3 in elem[:2] for elem in array]
any(3 in elem[:2] for elem in array)
array = [[1,3,7], [4,5,6]]
[3 in elem[:2] for elem in array]
any(3 in elem[:2] for elem in array)

rawDescription: How do I find if an int is in array of arrays?

description: Find if an int is in array of arrays


code: d = pd.DataFrame(0, index=np.arange(len(data)), columns=feature_list)

rawDescription: Creating a zero-filled pandas data frame


code:
import matplotlib.pyplot as plt

for ax, color in zip([ax1, ax2, ax3, ax4], ['green', 'green', 'blue', 'blue']):
    plt.setp(ax.spines.values(), color=color)
    plt.setp([ax.get_xticklines(), ax.get_yticklines()], color=color)

rawDescription: Elegantly changing the color of a plot frame in matplotlib


code:
import os
ROOT_PATH = os.path.dirname(os.path.abspath(__file__))

# then:
myfile_path = os.path.join(ROOT_PATH, "myfile.txt")

rawDescription: How to set current working directory in python in a automatic way

description: Set current working directory in python in a automatic way


code:
# scatter3d_demo.py
# ...
# Set the background color of the pane YZ
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
plt.show()

rawDescription: Changing the background color of the axes planes of a matplotlib 3D plot


rawDescription: Calling itertools.product with unkown number of args


code:
import fileinput

for fl, line in zip(li, fileinput.input(['a.txt'], inplace=True)):
    print(line.strip() + '\t' + str(fl))

rawDescription: Python - add a column to an existing tab separated file


code:
x = linspace(0, 2 * pi, 1000)
y = sin(x)
fig, ax = subplots()
ax.plot(x, y)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.grid(axis='y')

rawDescription: Borderless matplotlib plots

description: Borderless matplotlib plots


code: isgood = all(re.search(regex, s) for regex in regexPatterns)

rawDescription: valdiating an array of regex string on a string

description: Valdiating an array of regex string on a string


code:
def form_valid(self, form):
    post_to_api(form.cleaned_data)
    # now call superclass to save the form
    return super(UpdateProfileView, self).form_valid(form)

rawDescription: Post to API before saving to database in django class-based views


code:
p1 = subprocess.Popen(['convert', fileIn, 'bmp:-'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['mkbitmap', '-f', '2', '-s', '2', '-t', '0.48'],
     stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()
p3 = subprocess.Popen(['potrace', '-t' , '5', '-s' , '-o', fileOut],
     stdin=p2.stdout,stdout=subprocess.PIPE)
p2.stdout.close()

output = p3.communicate()[0]

rawDescription: Python subprocess: how to use pipes thrice?


rawDescription: How can I test if a list contains another list with particular items in Python?

description: Test if a list contains another list with particular items in Python


code:
story = db.get(story_key)
author_id = Story.author.get_value_for_datastore(story).id()

rawDescription: Fetching just the Key/id from a ReferenceProperty in App Engine


code:
## Create a new Document in Google Drive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
gauth = GoogleAuth()
gauth.LocalWebserverAuth()
drive = GoogleDrive(gauth)
folder = "########"
title = "Copy of my other file"
file = "############"
drive.auth.service.files().copy(fileId=file,
                           body={"parents": [{"kind": "drive#fileLink",
                                 "id": folder}], 'title': title}).execute()

rawDescription: How can I make a copy of a file in Google Drive via Python?

description: Make a copy of a file in Google Drive via Python


code:
new_d = {}
for k, v in d.items():
   u, n, r = k.split('_')
   new_d[(n, r)] = v + new_d.get((n, r), 0)

rawDescription: Python: Adding dictionary values to form new tuple-keyed dictionary


code:
cursor = mywidget.getCursor() # or event.getCursor()
pos = cursor.pos()
cursor.setPos((pos[0]+1, pos[1]+1))

rawDescription: SImulate a mouse move in pyqt

description: SImulate a mouse move in pyqt


code:
d = dict()
column = list()
for _, a, b in df.itertuples():
    if b != '0':
        d[a] = b
    else:
        d.pop(a, None)
    column.append(d.copy())

df['C'] = column

rawDescription: Series dictionary with Cumulative result of other columns


code:
d
max(d, key=lambda v: d[v]['c'])

rawDescription: Get the key with the maximum nested key in a python dictionary


code:
import os
import os.path
import re
from mmap import mmap
from contextlib import closing

id_filename = 'path/to/id/file'
directory_name = 'directory/to/replace/in'

# read the ids into a dictionary mapping old to new
with open(id_filename) as id_file:
    ids = dict(line.split()[1:] for line in id_file)

# compile a regex to do the replacement
id_regex = re.compile('|'.join(map(re.escape, ids)))

def translate(match):
    return ids[match.group(0)]

def multiwordReplace(text):
    return id_regex.sub(translate, text)

for code_filename in os.listdir(directory_name):
    with open(os.path.join(directory, code_filename), 'r+') as code_file:
        with closing(mmap(code_file.fileno(), 0)) as code_map:
            new_file = multiword_replace(code_map)
    with open(os.path.join(directory, code_filename), 'w') as code_file:
        code_file.write(new_file)

rawDescription: What is the best way to do a find and replace of multiple queries on multiple files?


code:
class LocationAdmin(SuitedUpAdmin):
    formfield_overrides = dict(SuitedUpAdmin.formfield_overrides, **{
        models.TextField: {'widget': AutosizedTextarea},
    })

rawDescription: How to avoid ModelAdmin options being overridden in subclasses?

description: Avoid ModelAdmin options being overridden in subclasses


code:
import csv
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt

threshold = 30000
x,y,z = [],[],[]
csv_reader = csv.reader(open('input.csv'))

for line in csv_reader:
    y.append(int(line[2]))
    x.append(dt.datetime.strptime(line[1],'%H:%M'))
    z.append(line[3])

x=np.array(x)
y=np.array(y)

tags = list(set(z))
z=np.array(z)

fig=plt.figure()

for tag in tags:
    plt.plot(x[z==tag],y[z==tag],'o-',label=tag)

fig.autofmt_xdate()

plt.legend(loc=2)

plt.savefig('test.png')

rawDescription: Read One Input File and plot multiple

description: Read One Input File and plot multiple


code:
Y = []
A = [['2925750', ' Everything he mentioned, I could have evaluated on my own'], ['2925750', ' I do wish he could have shown us more at this point that could have set the fox apart.']]
B = ['mentioned','evaluated','fox','wish']

for sent in A:
    o = 0
    for i in sent:
        o +=sum(i.count(col) for col in B)
    Y.append((sent, o))

rawDescription: Python for loop counter list - counter not working


code:
import sys
from PyQt4.QtGui import QApplication, QWidget, QVBoxLayout, \
    QLineEdit, QRadioButton

class Widget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.widget_layout = QVBoxLayout()

        self.radio1 = QRadioButton('Radio 1')
        self.radio2 = QRadioButton('Radio 2')
        self.line_edit = QLineEdit()

        self.radio1.toggled.connect(self.radio1_clicked)
        self.radio2.toggled.connect(self.radio2_clicked)

        self.widget_layout.addWidget(self.radio1)
        self.widget_layout.addWidget(self.radio2)
        self.widget_layout.addWidget(self.line_edit)
        self.setLayout(self.widget_layout)

    def radio1_clicked(self, enabled):
        if enabled:
            self.line_edit.setText('Radio 1')

    def radio2_clicked(self, enabled):
        if enabled:
            self.line_edit.setText('Radio 2')

if __name__ == '__main__':
  app = QApplication(sys.argv)
  widget = Widget()
  widget.show()

  sys.exit(app.exec_())

rawDescription: change text of lineEdit when a radio button is selected in pyqt

description: Change text of lineEdit when a radio button is selected in pyqt


code: print(re.sub(r't[^t].', lambda m: m.group(0)[::-1], 'testtext')) # settxett

rawDescription: Replace regular expression match with result of applying a function


code:
import re

# Strip all spaces and dump all data into an array
lines = [mo for mo in re.findall('(?s)(?<=\|)([<\w].+?)\s+?\|', open('py.txt').read())]
# Create an array to hold the transformation
combined = ['' for x in range(len(lines) / lines.count("<DOg>|"))]
# Append by rows
for idx in range(len(lines)):
  combined[idx % len(combined)] += lines[idx] + ','

# Write array to file
output = open('numbersConverted.csv','w')
for comb in combined:
  output.write(comb + "\n")
output.close

rawDescription: Splitting a text document into an excel sheet xls


code:
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'project1.search_backends.CustomElasticSearchEngine',
        'URL': '123.123.123.123:9200',
        'INDEX_NAME': 'haystack',
    },
}

rawDescription: Haystack: Make query from one project to another


code: images.crop(image, 0.0, 1.0, 1.0, 0.0, output_encoding=images.JPEG)

rawDescription: How to compress PNG image fetched from url without changing it's dimenstions

description: Compress PNG image fetched from url without changing it's dimenstions


code:
import csv
import itertools
import collections

ID = itertools.count(1)
labels = collections.defaultdict(lambda : next(ID))
with open('path/to/input') as infile, open('path/to/output', 'w') as fout:
    outfile = csv.writer(fout, delimiter=' ', dialect='excel')
    for val, name in csv.reader(infile, delimiter=' '):
        outfile.writerow([name.strip(), labels[val]])

rawDescription: list of random numbers to list of consecutive real numbers in python

description: List of random numbers to list of consecutive real numbers in python


code:
srcDir = '/user/local'
targetDir = '/user/data'
for fname in os.listdir(srcDir):
    if not os.path.isdir(os.path.join(srcDir, fname)):
        for prefix in ['jenjar.dat', 'jenmis.dat']:
            if fname.startswith(prefix):
                if not os.path.isdir(os.path.join(targetDir, prefix)):
                    os.mkdir(os.path.join(targetDir, prefix))
                shutil.move(os.path.join(srcDir, fnmae), targetDir)

rawDescription: How to move files based on their names to specific directories in python?

description: Move files based on their names to specific directories in python


code:
from eve.auth import BasicAuth

class MyBasicAuth(BasicAuth):
    def check_auth(self, username, password, allowed_roles, resource, method):
        if username == 'user1':
            self.set_mongo_prefix('MONGO1')
        elif username == 'user2':
            self.set_mongo_prefix('MONGO2')
        else:
            # serve all other users from the default db.
            self.set_mongo_prefix(None)
        return username is not None and password == 'secret'

app = Eve(auth=MyBasicAuth)
app.run()

rawDescription: How to have eve write to different databases based on various URL parameters and request values?

description: Have eve write to different databases based on various URL parameters and request values


code:
from gi.repository import Gtk, Gdk

win = Gtk.Window(title="Hello World")
win.show_all()
cursor = Gdk.Cursor.new(Gdk.CursorType.BLANK_CURSOR)
win.get_window().set_cursor(cursor)
Gtk.main()

rawDescription: pyGObject transparent cursor

description: PyGObject transparent cursor


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

plt.figure()
plt.axis([0, 16, 0, 16])
plt.grid(False)                         # set the grid
data= [(8,2,'USA'), (2,8,'CHN')]

for obj in data:
    plt.text(obj[1],obj[0],obj[2])      # change x,y as there is no view() in mpl

ax=plt.gca()                            # get the axis
ax.set_ylim(ax.get_ylim()[::-1])        # invert the axis
ax.xaxis.tick_top()                     # and move the X-Axis
ax.yaxis.set_ticks(np.arange(0, 16, 1)) # set y-ticks
ax.yaxis.tick_left()                    # remove right y-Ticks

rawDescription: Matplotlib: move Origin to upper left corner


code:
with open(source_file) as source:
    json_source = source.read()
    data = json.loads('[{}]'.format(json_source))

rawDescription: Parsing comma separated JSON from a file


code:
def unite_intervals(intervals):
    def f(acc, element):
        if acc and intersects(acc[-1], element):
            return acc[:-1] + [extend(acc[-1], element)]
        else:
            return acc + [element]
    return reduce(f, intervals, [])

rawDescription: Rewrite an interval union algorithm functionally


code:
parser.add_argument('-b', '--blacklist', nargs='+', type=str)
...
args = parser.parse_args()
main(**vars(args))

rawDescription: How do you add an n-long list of arguments to a flag via argparse?

description: Add an n-long list of arguments to a flag via argparse


code:
class Question(forms.Form):
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        super(QuestionForm, self).__init__(*args, **kwargs)
        self.fields["community"].queryset = self.user.communities.all()

    community = forms.ModelChoiceField(queryset=Community.objects.none())
    description = forms.CharField(widget=forms.Textarea)

rawDescription: Django ModelChoiceField in forms not displaying properly


code:
import bisect
t3 = ['carver', 'carvers', 'carves', 'carving', 'carvings']
bisect.bisect(t3, 'carves')
bisect.bisect_left(t3, 'carves')
bisect.bisect == bisect.bisect_right
bisect.bisect == bisect.bisect_left

rawDescription: Bisect a Python List and finding the Index


code:
import pydoc
strhelp = pydoc.render_doc(str, "Help on %s")

rawDescription: python "help" function: printing docstrings

description: Python "help" function: printing docstrings


code:
from tkinter import *
root = Tk()
def add():
    global x
    x += 1
    messagebox.showinfo(message=x)

from tkinter import messagebox
x = 0
adder = Button(root, text='ADD 1 TO X', command=add)
adder.grid()

rawDescription: Plus 1 to variable with tkinter button

description: Plus 1 to variable with tkinter button


code:
import numpy
import matplotlib.pyplot as plt

#Random data
data = numpy.random.random((10, 10))

#Set all data points equal to zero to NaN
#data[data == 0.] = float("NaN")

#Set single data value to nan
data[2][2] = float("NaN")

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

ax.imshow(data, interpolation = "nearest")

plt.show()

rawDescription: matplotlib, pyplot : custom color for a specific data value

description: Matplotlib, pyplot : custom color for a specific data value


code:
def rep_str(string, search, replacement):
    result = ''
    i = 0
    while i < len(string):
        if string[i : i + len(search)] == search:
            result += replacement
            i += len(search)
        else:
            result += string[i]
            i += 1
    return result

rawDescription: Replace a substring in a string with python


code:
import wx
import wx.stc as stc
import os
import platform
import time
systemType = platform.system()
if systemType == "Windows":
    import win32wnet

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

        run_params = {}
        self.run_params = run_params

        # OS dependent info
        self.run_params["systemType"] = systemType
        if systemType == "Windows":
            self.run_params["fontSize"] = 8
            self.run_params["fontSize2"] = 7
        else:
            self.run_params["fontSize"] = 10
            self.run_params["fontSize2"] = 9

        wx.Frame.__init__(self, parent, id, title, size=(900, 710), style=wx.DEFAULT_FRAME_STYLE & ~ (wx.RESIZE_BORDER |
                                                wx.RESIZE_BOX |
                                                wx.MAXIMIZE_BOX))

        ##########################################################
        # Passed self here and removed the unnecessary second self
        ##########################################################
        self.submissions = SubmissionPane(self, run_params)
        self.CreateStatusBar()

        menuBar = wx.MenuBar()

        self.Centre()
        self.Show()

class SubmissionPane(wx.Panel):
    ################################################
    # changed the init here
    ################################################
    def __init__(self, parent, run_params):
        wx.Panel.__init__(self, parent)

        self.parent = parent
        self.selected_folders = None
        self.params = run_params
        ################################################
        # changed the ref below
        ################################################
        self.frame = self

        main_sizer = wx.BoxSizer(wx.VERTICAL)
        self.top_row_sizer = wx.BoxSizer(wx.HORIZONTAL);
        radio_static_box = wx.StaticBox(self, label='Some Text')
        radio_static_box_sizer = wx.StaticBoxSizer(radio_static_box, wx.HORIZONTAL)

        job_static_box = wx.StaticBox(self, label='Some Text')
        job_static_box_sizer = wx.StaticBoxSizer(job_static_box, wx.HORIZONTAL)

        '''
        radio_labels = ['Some Text', 'Some Text2']
        self.radio_box = wx.RadioBox(
                self, -1, "",
                choices=radio_labels,
        )
        '''
        self.radio1 = wx.RadioButton(self, label='Some Text', style=wx.RB_GROUP)
        self.radio2 = wx.RadioButton(self, label='Some Text')
        self.radio1.SetValue(True)

        radio_static_box_sizer.Add(self.radio1, flag=wx.BOTTOM, border=0)
        radio_static_box_sizer.Add(self.radio2, flag=wx.LEFT, border=10)
        self.top_row_sizer.Add(radio_static_box_sizer, flag=wx.LEFT, border=10)

        self.check_box = wx.CheckBox(self, label="Some Text")
        self.check_box.SetValue(False)

        if self.params["systemType"] == "Windows":
            self.txtTitle = wx.TextCtrl(self, style=wx.SUNKEN_BORDER, value="Some Text...", size=(200, -1), pos=(306, 14))
        else:
            self.txtTitle = wx.TextCtrl(self, style=wx.SUNKEN_BORDER, value="Some Text...", size=(200, -1), pos=(350, 19))

        job_static_box_sizer.Add(self.check_box, flag=wx.LEFT, border=0)

        self.top_row_sizer.Add(job_static_box_sizer, flag=wx.LEFT, border=10);
        self.txtTitle.Show(False)

        main_sizer.Add(self.top_row_sizer);
        main_sizer.Add((-1, 10))

        job_static_box2 = wx.StaticBox(self, label='Some Text')

        third_row_sizer = wx.StaticBoxSizer(job_static_box2, wx.HORIZONTAL);
        self.tc_files = wx.TextCtrl(self, size=(375, 25))
        self.buttonGo = wx.Button(self, label='Go')
        self.buttonGo.Bind(wx.EVT_BUTTON, self.OnSubmit)
        third_row_sizer.Add(self.tc_files, flag=wx.RIGHT, border=8)

        if self.params["systemType"] == "Windows":
            third_row_sizer.Add(self.buttonGo, flag=wx.LEFT | wx.TOP, border=0)
        else:
            third_row_sizer.Add(self.buttonGo, flag=wx.LEFT | wx.TOP, border=2)

        main_sizer.Add(third_row_sizer, flag=wx.LEFT, border=10)

        self.log_text22 = wx.ListCtrl(self,size=(875,275),
                         style=wx.LC_REPORT | wx.BORDER_SUNKEN | wx.LC_SINGLE_SEL | wx.LC_VRULES | wx.LC_HRULES)

        font = wx.Font(self.params["fontSize2"], wx.FONTFAMILY_DEFAULT, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
        self.log_text22.SetFont(font)

        self.log_text22.InsertColumn(1, '1', width=40, format=wx.LIST_FORMAT_CENTRE)
        self.log_text22.InsertColumn(2, '2', width=50, format=wx.LIST_FORMAT_CENTRE)
        self.log_text22.InsertColumn(3, '3', width=156)
        self.log_text22.InsertColumn(4, '4', width=332)
        self.log_text22.InsertColumn(5, '5', width=100, format=wx.LIST_FORMAT_CENTRE)
        self.log_text22.InsertColumn(6, '6', width=82, format=wx.LIST_FORMAT_CENTRE)
        self.log_text22.InsertColumn(7, '7', width=60, format=wx.LIST_FORMAT_CENTRE)
        self.log_text22.InsertColumn(8, '8', width=50, format=wx.LIST_FORMAT_CENTRE)

        main_sizer.Add((-1, 10))
        list_sizer = wx.BoxSizer(wx.VERTICAL)
        list_sizer.Add(self.log_text22, flag=wx.LEFT, border=10)
        main_sizer.Add(list_sizer)

        self.running_log1 = wx.stc.StyledTextCtrl(self, -1, size=(875,175))
        self.running_log1.StyleSetFont(wx.stc.STC_STYLE_DEFAULT, font)
        self.running_log1.SetMarginWidth(1, 0)
        self.running_log1.StyleSetBackground(wx.stc.STC_STYLE_DEFAULT, (0,0,0))
        self.running_log1.StyleSetForeground(wx.stc.STC_STYLE_DEFAULT, (0,255,0))
        self.running_log1.StyleClearAll()

        main_sizer.Add((-1, 5))
        list_sizer = wx.BoxSizer(wx.VERTICAL)
        list_sizer.Add(self.running_log1, flag=wx.LEFT, border=10)
        main_sizer.Add(list_sizer)

        list_sizer.Add((-1, 10))
        self.buttonClose = wx.Button(self, -1, "Quit")
        list_sizer.Add(self.buttonClose, flag=wx.ALIGN_CENTER | wx.TOP | wx.LEFT, border=10)

        self.SetBackgroundColour("Light Grey")

        self.SetSizer(main_sizer)

        self.Layout()

    def OnSubmit(self, event):
        msg = "Running"
        jobSubmitmsg = wx.BusyInfo(msg, self)
        time.sleep(3)
        jobSubmitmsg = None

app = wx.App(redirect=False)
MainWindow(None, -1, 'Application')
app.MainLoop()

rawDescription: Wxpython - remove tabs in application

description: Wxpython - remove tabs in application


code:
import turtle

def drawTriangle(size):
    turtle.left(30)
    turtle.forward(size)
    turtle.right(120)
    turtle.forward(size)
    turtle.right(120)
    turtle.forward(size)
    turtle.right(120)
    turtle.up()
    turtle.forward(size)
    turtle.right(30)
    turtle.down()

def drawTriangles(size, depth, baseTriangle = False):
    if (depth < 1):
        pass
    else:
        drawTriangle(size)
        drawTriangles(size / 2, depth - 1)
        if baseTriangle:
            return
        turtle.up()
        turtle.left(30)
        turtle.forward(-size)
        turtle.right(120)
        turtle.forward(size * 2)
        turtle.left(90)
        turtle.down()
        drawTriangle(size)
        drawTriangles(size / 2, depth - 1)
        turtle.up()
        turtle.left(30)
        turtle.forward(-size)
        turtle.left(60)
        turtle.forward(size * 2)
        turtle.right(90)
        turtle.down()
turtle.home()
turtle.left(90)
turtle.down()
turtle.speed("normal")
drawTriangles(100, 4, baseTriangle = True)
input("pause")

rawDescription: Recursive method of shrinking triangles in Python


code:
from wx.tools.img2py import img2py
from glob import glob

for f in glob('*.png'):
  o = f.replace('-', '').replace('_', '').replace('.png', '')
  img2py(f, 'Images.py', append=True, imgName=o, icon=True)

rawDescription: Py2Exe & Img2Py - Images Missing after Compiling


code: numpy.interp(3.,y,x)  #1.5

rawDescription: Interpolation in PyLab

description: Interpolation in PyLab


code:
class Node:
    value = ""
    leftChild = None
    rightChild = None
    def __init__(self, parent):
        self.parent = parent
    def isLeaf(self):
        if (self.leftChild == None and self.rightChild == None):
            return True
        else:
            return False

def convertTreeAux(node, newick):
    if node.isLeaf():
        newick.append(node.value)
    if node.leftChild != None:
        newick.append("(")
        convertTreeAux(node.leftChild, newick)
        newick.append(",")
    if node.rightChild != None:
        convertTreeAux(node.rightChild, newick)
        newick.append(")")

tree =  Node(None)
tree.value = "A"
tree.leftChild = Node(tree)
tree.leftChild.value = "B"
tree.rightChild = Node(tree)
tree.rightChild.value = "C"
tree.rightChild.leftChild = Node(tree.rightChild)
tree.rightChild.leftChild.value = "E"
tree.rightChild.rightChild = Node(tree.rightChild)
tree.rightChild.rightChild.value = "F"

newick = []
convertTreeAux(tree, newick)

print (''.join(newick))

rawDescription: convert tree to string which contains only the leafs

description: Convert tree to string which contains only the leafs


code:
import numpy as np
with open(filename) as f:
    for line in f:
        a=np.array(line.split(),dtype=int)
        print(a.std(),a.mean(),np.median(a))  #standard-deviation, mean, median

rawDescription: Statistics of a number stream

description: Statistics of a number stream


code:
infile = open('europenewMatrix.txt','r')
infile.readline() # skip the first line
numbers = []
for line in infile:
    numbers.append([int(val) for val in line.split(',')[2:]])
infile.close()
travelMat = array(numbers)

rawDescription: Python and excel reading files problem

description: Python and excel reading files problem


code:
import yaml

config_file = open('myFile', 'r')
config = yaml.read(config_file)

keys = config.keys()
values = config.values()

for key,val in zip(keys,values):
    if key not in locals():
        locals()[key] = val
    else:
        locals()[key+"_yaml"] = val

rawDescription: Extract dictionary pairs into the interactive workspace using ConfigObj or PyYaml


code:
parser.set('SETTINGS', 'value', '15')

# Writing our configuration file to 'example.ini'
with open('example.ini', 'wb') as configfile:
    parser.write(configfile)

rawDescription: Change value in ini file using ConfigParser Python


code:
process = multiprocessing.Process(target=start_remote_runner, args=(context,))
process.start()

rawDescription: Share complex object with another process


code:
import sys

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

rawDescription: How do I run a function in a Python module using only the Windows command line?

description: Run a function in a Python module using only the Windows command line


rawDescription: Scrapy: Store/scrape current start_url?

description: Scrapy: Store/scrape current start_url


code:
# models.py

class MyModel(models.Model):
    extracted_data_1 = models.IntegerField()
    # more fields
    ...

# forms.py

class MyModelForm(forms.ModelForm):
    cell_a = forms.IntegerField()
    cell_b = forms.IntegerField(required=False)

    def clean(self):
        cell_a = self.cleaned_data['cell_a']
        cell_b = self.cleaned_data.get('cell_b', 0)
        self.cleaned_data['extracted_data_1'] = cell_a + cell_b
        return self.cleaned_data

    class Meta:
        model = MyModel
        fields = ('cell_a', 'cell_b', 'extracted_data_1')

rawDescription: Django Model Save Method: Pass raw data to calculate final data for write to db


code:
from django.http import HttpResponse
return HttpResponse(str(var))

rawDescription: Equivalent of PHP "echo something; exit();" with Python/Django?


rawDescription: Django/Python: How can I make the following number increment (not in database)


code:
import re
string = """

"""
re.search('(p[0-9])', string)
re.findall('(p[0-9])', string)

rawDescription: My regex "appears" to work in a tester, but not in my actual code


code:
replacements = {'Geboren am':';', 'Nato/a il':';', 'Né(e) le':';'}

lines = []
with open('DATEN2.txt') as infile, open('DATENBEARBEITET2.txt', 'w') as outfile:
    for line in infile:
        line = line.strip()
        if not line:
            continue
        for src, target in replacements.iteritems():
            line = line.replace(src, target)
        lines.append(line)
    outfile.write(', '.join(lines))

rawDescription: Removing whitespace and newlines in txt file with python


rawDescription: Set minimum length of a list?

description: Set minimum length of a list


code:
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from brute_force.items import BruteForceItem
from urlparse import urljoin

class DmozSpider(BaseSpider):
    name = "brutus"
    allowed_domains = ["tool.httpcn.com"]
    start_urls = ['http://tool.httpcn.com/Zi/BuShou.html']

    def parse(self, response):
        for url in response.css('td a::attr(href)').extract():
            cb = self.parse if '/zi/bushou' in url.lower() else self.parse_item
            yield Request(urljoin(response.url, url), callback=cb)

    def parse_item(self, response):
        hxs = HtmlXPathSelector(response)
        item =  BruteForceItem()
        item["the_strokes"] = hxs.xpath('//*[@id="div_a1"]/div[2]').extract()
        item["character"] = hxs.xpath('//*[@id="div_a1"]/div[3]').extract()
        return item

rawDescription: brute force web crawler, how to use Link Extractor towards increased automation. Scrapy

description: Brute force web crawler, how to use Link Extractor towards increased automation. Scrapy


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

sample = np.random.normal(size=10000)

vert_hist = np.histogram(sample, bins=30)
ax1 = plt.subplot(2, 1, 1)
ax1.plot(vert_hist[0], vert_hist[1][:-1], '*g')

ax2 = plt.subplot(2, 1, 2)
ax2.hist(sample, bins=30, orientation="horizontal");

rawDescription: Vertical Histogram in Python and Matplotlib


code:
def receive():
    parameters = pika.ConnectionParameters(RabbitMQ_server)
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()
    channel.queue_declare(queue='toM')
    method_frame, header_frame, body = channel.basic_get(queue = 'toM')
    if method_frame.NAME == 'Basic.GetEmpty':
        connection.close()
        return ''
    else:
        channel.basic_ack(delivery_tag=method_frame.delivery_tag)
        connection.close()
        return body

rawDescription: RabbitMQ consume one message if exists and quit


code:
def flatten(*args):
    output = []
    for arg in args:
        if hasattr(arg, '__iter__'):
            output.extend(flatten(*arg))
        else:
            output.append(arg)
    return output

rawDescription: Convert args to flat list?

description: Convert args to flat list


code: command = r"elev.cmd {0}\data\nssm.exe install service {1}\data\service.exe".format(targetdir,targetdir)

rawDescription: Why is the command string not passed entirely from Python to system?


code:
def password_check(pw):
    if len(pw) < 2:
        print ('Password must be at least 2 characters long')
        return False
    elif pw.isalpha():
        print('Password must contain at least one number.')
        return False
    elif pw.isdigit():
        print('Password must contain at least one letter. ')
        return False
    for a in pw:
        if a * 2 in pw:
            print('Password contains a consecutive character')
            return False
    print('Password was accepted')
    return True

rawDescription: How can I search for repeating characters in a string?

description: Search for repeating characters in a string


code:
if 'test' in sys.argv:
    DATABASES['default']['ENGINE'] = 'django.db.backends.sqlite3'
    DATABASES['default']['NAME'] = 'databasename.db3'

rawDescription: How to use different database engines in Django for testing and production

description: Use different database engines in Django for testing and production


code: ["foo", "bar", "baz"].index("bar")

rawDescription: Finding the index of an item given a list containing it in Python


rawDescription: Create new Excel process with COM (pywin32)


rawDescription: Anything wrong with a really large __init__?


code:
import copy
# fake....err, simulated... data

# elevation
X, Y = np.meshgrid(np.linspace(-50, 50, 1024), np.linspace(-50, 50, 1024))
elv = np.sin(np.pi * X / 50) * np.cos(2*np.pi * Y / 50)

# radar
R, theta = np.meshgrid(np.linspace(0, 35, 512), np.linspace(0, 2*np.pi, 512))
rad = np.sin(3*theta) ** 2 * np.cos(R / 10) ** 2

Rt_x = R * np.sin(theta)  # turn radial grid points into (x, y)
Rt_y = R * np.cos(theta)

fig, ax = plt.subplots(1, 1)
ax.set_aspect('equal')
# plot contour
ax.contour(X, Y, elv, cmap='gray')

# tweak color map so values below a threshold are transparent
my_cmap = copy.copy(cm.get_cmap('jet'))
my_cmap.set_under(alpha=0)
# plot the radar data
ax.pcolormesh(Rt_x, Rt_y, rad, zorder=5, edgecolor='face', cmap=my_cmap, vmin=.5, shading='flat')

rawDescription: matplotlib combine polar and cartesian gridded data

description: Matplotlib combine polar and cartesian gridded data


code:
generator = (item for item in a if item > 10)
for item in generator:
    ...

rawDescription: Efficient list culling

description: Efficient list culling


code:
import re
re.findall("{{(.*?)}}", "this {{is}} a sample {{text}}")

rawDescription: Python - extracting a list of sub strings


rawDescription: Django: queryset multiple conditions or gather into new object


code:
t_2 = (0, 3)
t_1 = (23, 59)

from datetime import timedelta

t1 = timedelta(hours=t_1[0],minutes=t_1[1])
t2 = timedelta(hours=t_2[0],minutes=t_2[1])
print((t2-t1).seconds/60)
4.0

rawDescription: Time difference in Python 2.7

description: Time difference in Python 2.7


code:
import urllib
from sqlalchemy import create_engine
connection_string = '127.0.0.1;Database=MyDatabase;MultiSubnetFailover=True'
engine_string = 'mssql+pyodbc:///?odbc_connect={}'.format(urllib.quote_plus(connection_string))
engine = create_engine(engine_string)

rawDescription: How to connect to a high availability SQL Server from Python + SQL Alchemy

description: Connect to a high availability SQL Server from Python + SQL Alchemy


code:
import time

filePath = '/var/log/logfile.log'

lastLine = None
with open(filePath,'r') as f:
        while True:
            line = f.readline()
            if not line:
                break
            print(line)
            lastLine = line

while True:
    with open(filePath,'r') as f:
        lines = f.readlines()
    if lines[-1] != lastLine:
        lastLine = lines[-1]
        print(lines[-1])
    time.sleep(1)

rawDescription: Get only new lines from file

description: Get only new lines from file


rawDescription: Python - Convert List

description: Python - Convert List


code:
import numpy as np
X = np.random.randn(1000, 100000)
block_size = 10000
from sklearn.externals.joblib import Parallel, delayed
products = Parallel(n_jobs=10)(delayed(np.dot)(X[:, pos:pos + block_size], X.T[pos:pos + block_size]) for pos in range(0, X.shape[1], block_size))
product = np.sum(products, axis=0)

rawDescription: fast dot product on all pair of rows

description: Fast dot product on all pair of rows


code: devFound = any(d['name'] == devName for d in dev['devices'])

rawDescription: Python - shortening an if / for loop

description: Python - shortening an if / for loop


code:
import cherrypy
cherrypy.config.update({'server.socket_port': 8099})
cherrypy.engine.restart()

rawDescription: Change Cherrypy Port and restart web server


code:
df = pd.DataFrame(pd.date_range('2015-01-01 05:00', periods=3), columns=['datetime'])
df
df["date"] = pd.DatetimeIndex(df["datetime"]).normalize()
df

rawDescription: Matching two similar dates with different times


code:
cordlist = [0, 0, 0]
for i in xrange(n):
    cordlist = map(sum, zip(cordlist, map(int, raw_input().split())))

rawDescription: Updating list values with new values read - Python


code:
df = pd.DataFrame({"appid": [1,2,2,3,3], "mac_id": ['a', 'b', 'c', 'd', 'e'], "count": [1,1,1,1,1]})
summer = lambda x: x[x["mac_id"].isin(mac_list)].sum()
df.groupby("appid").apply(summer)["count"]

rawDescription: python pandas groupby filter

description: Python pandas groupby filter


rawDescription: Sort Django query result by number of matches


code:
import statsmodels.api as sm
mod = sm.OLS.from_formula('y ~ x', data=df)  # y and x are column names in the DataFrame
res = mod.fit()
fig, ax = plt.subplots()
sm.graphics.abline_plot(model_results=res, ax=ax)
df.plot(kind='scatter', x='x', y='y', ax=ax)

rawDescription: Pandas stock regression chart

description: Pandas stock regression chart


code:
check = True
while check :
    port_input = raw_input("port(number must be higher than 49152: ")
    try:
        port_number = int(port_input)
        check = (port_number < 49152)
    except ValueError:
        check = True

rawDescription: More efficient way to write this small bit of Python code?


code:
class MyView(View):
    @my_decorator
    def dispatch(self, *args, **kwargs):
        return super(MyView, self).dispatch(*args, **kwargs)

rawDescription: How to attach data to view methods with django class based views and decorators?

description: Attach data to view methods with django class based views and decorators


code:
for i in range(0, len(x_lolots)):
    for j in range(0, len(x_lolots[i])):
        plt.ion()
        plt.subplot(rows, cols, (i+1))
        plt.plot(x_lolots[i][j], y_lolots[i][j])

rawDescription: Pyplot: Plotting [Lists of [(Lists of Tuples)]]


code:
np.mod(x, 1, out=x)
mask = (x == 0)

rawDescription: Numpy: Check if float array contains whole numbers


code:
def safely_int(value, default=0):
    try:
        return int(value)
    except (TypeError, ValueError):
        return default

rawDescription: Python unexpected int(0 or ...) behaviour


rawDescription: Using ast.literal_eval on a nested dictionary


code:
import djcelery
djcelery.setup_loader()

rawDescription: Celery, Django.. making a Task / thread launch sub-task / threads?


code:
def f(val):
    result = a.get(val, False)
    return (result[0], True) if result else (val, result)

rawDescription: Pythonic way for the following code

description: Pythonic way for the following code


code:
import subprocess
import sys

perl_script = subprocess.Popen(["script.pl", params], stdout=sys.stdout)
perl_script.communicate()

rawDescription: Run a perl script from my python script, print the output and wait for it to finish


code:
a = [(u'we', 'PRP'), (u'saw', 'VBD'), (u'you', 'PRP'), (u'bruh', 'VBP'), (u'.', '.')]
import operator
a.sort(key = operator.itemgetter(1))
a

rawDescription: How do I order this list in Python?

description: Order this list in Python


code:
import os
import datetime

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
]

MY_APPS = [
    'accounts'
]

INSTALLED_APPS += MY_APPS

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
    },
    'loggers': {
    }
}

MY_LOGGERS = {}
MY_HANDLERS = {}
for app in MY_APPS:
    directory = os.path.dirname(os.path.dirname(__file__)) + "/var/log/" + app + "/"
    if not os.path.exists(directory):
        os.makedirs(directory)

    MY_HANDLERS[app] = {
        'level': 'DEBUG',
        'class': 'logging.handlers.RotatingFileHandler',
        'filename': directory + '/' + str(datetime.date.today()) + '.log',
        'maxBytes': 1024*1024*5,
        'backupCount': 5,
        'formatter': 'verbose'
    }

    MY_LOGGERS[app] = {
        'handlers': [app],
        'level': 'DEBUG',
        'propagate': True,
    }
LOGGING['handlers'].update(MY_HANDLERS)
LOGGING['loggers'].update(MY_LOGGERS)

rawDescription: Django How can we generate app wise log with app name directory and todaydate.log file


code:
import unittest

import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declarative_base

from alembic.operations import Operations
from alembic.migration import MigrationContext

Base = declarative_base()
engine = sa.create_engine('mysql://root:root@localhost/jpic')
Session = orm.sessionmaker(bind=engine)
session = Session()

conn = engine.connect()
ctx = MigrationContext.configure(conn)
op = Operations(ctx)

for table in ('person_car', 'cars', 'houses', 'persons'):
    op.drop_table(table)

class PersonTest(unittest.TestCase):
    def test_000_create_table(self):

        self.__class__.Person = type('Person', (Base,), {'__tablename__': 'persons',
            'id': sa.Column(sa.Integer, primary_key=True)})

        self.__class__.Car = type('Car', (Base,), {'__tablename__': 'cars',
            'id': sa.Column(sa.Integer, primary_key=True)})

        self.__class__.House = type('House', (Base,), {'__tablename__': 'houses',
            'id': sa.Column(sa.Integer, primary_key=True)})

        Base.metadata.create_all(engine)

    def test_001_create_unicode_field(self):
        # create the column in the table - does not add it in the class
        field = sa.Column('unicode_field', sa.Unicode(50))
        op.add_column('persons', field)

        # create the column in the class - was not done above
        # a new instance to avoid conflicts
        field = sa.Column('unicode_field', sa.Unicode)
        self.__class__.Person.unicode_field = field

        subject = self.__class__.Person(unicode_field='hello unicode field')
        session.add(subject)

        subject = session.query(self.__class__.Person).first()
        self.assertEqual(subject.unicode_field, 'hello unicode field')

    def test_002_create_foreign_key(self):
        field = sa.Column('owner_id', sa.Integer, sa.ForeignKey('persons.id'))
        op.add_column('houses', field)

        # create fk
        op.create_foreign_key('fk_house_owner', 'houses', 'persons', ['owner_id'], ['id'])

        field = sa.Column('owner_id', sa.Integer, sa.ForeignKey('persons.id'))
        relation = orm.relationship('Person',
                backref=orm.backref('houses', lazy='dynamic'))
        self.__class__.House.owner_id = field
        self.__class__.House.owner = relation

        owner = session.query(self.__class__.Person).first()

        house = self.__class__.House()
        house.owner = owner
        session.add(house)

        house = session.query(self.__class__.House).first()

        self.assertEqual(house.owner, owner)
        # also test the reverse relation
        self.assertEqual(owner.houses.all(), [house])

    def test_003_create_many_to_many(self):
        association_table = sa.Table('person_car', Base.metadata,
            sa.Column('person_id', sa.Integer, sa.ForeignKey('persons.id')),
            sa.Column('car_id', sa.Integer, sa.ForeignKey('cars.id'))
        )

        Base.metadata.create_all(engine)

        self.__class__.Person.cars = orm.relationship('Car',
                secondary=association_table,
                backref=orm.backref('persons', lazy='dynamic'))

        user1 = session.query(self.__class__.Person).first()
        user2 = self.__class__.Person()
        session.add(user2)

        car1 = self.__class__.Car()
        session.add(car1)
        car2 = self.__class__.Car()
        session.add(car2)

        user1.cars.append(car1)
        car2.persons.append(user1)
        session.commit()

        fresh_user1 = session.query(self.__class__.Person).get(user1.id)
        self.assertEqual(len(fresh_user1.cars), 2)
        self.assertTrue(car1 in fresh_user1.cars)
        self.assertTrue(car2 in fresh_user1.cars)

        fresh_car1 = session.query(self.__class__.Car).get(car1.id)
        self.assertEqual(fresh_car1.persons.all(), [user1])

rawDescription: How to add a ManyToManyField at runtime?

description: Add a ManyToManyField at runtime


code:
s1 = 'Loan Coordinator'
sList = ['Financial Student Loan Coordinator', 'Loan Operator', 'Coordinator', 'Financial Assistant']
unique = set(s1.split())  # unique words in string 1
[i for i in sList if unique & set(i.split())]

rawDescription: Text Classification and Searching in Python


code:
import re

nameList = ['Boulder Highway and US 95 NB',  'Boulder Hwy and US 95 SB',
'Buffalo and Summerlin N', 'Charleston and I-215 W', 'Eastern and I-215 S', 'Flamingo and NB I-15',
'S Buffalo and Summerlin', 'Flamingo and SB I-15', 'Gibson and I-215 EB', 'I-15 at 3.5 miles N of Jean',
'I-15 NB S I-215 (dual)', 'I-15 SB 4.3 mile N of Primm', 'I-15 SB S of Russell', 'I-515 SB at Eastern W',
'I-580 at I-80 N E', 'I-580 at I-80 S W', 'I-80 at E 4TH St Kietzke Ln', 'I-80 East of W McCarran',
'LV Blvd at I-215 S', 'S Buffalo and I-215 W', 'S Decatur and I-215 WB', 'Sahara and I-15 East',
'Sands and Wynn South Gate', 'Silverado Ranch and I-15 (west side)']

dirMap = {'N': 'North', 'S': 'South', 'E': 'East', 'W': 'West'}

dirPattern = re.compile(r'(?:^| )(?<! at )(?<! of )([NSEW])B?(?! of )(?: |$)')

print('name\tdirSting\tdirection')
for name in nameList:
    match = dirPattern.search(name)
    direction = None
    dirString = None
    if match:
        dirString = match.group(1)
        direction = dirMap.get(dirString)
    print('> %s\t\t%s\t%s'%(name, dirString, direction))

rawDescription: Trouble matching pattern at start or end with regex in Python


code:
class ScrollableListbox(tk.Listbox):
    def __init__(self, master, *arg, **key):
        self.frame = tk.Frame(master)
        self.yscroll = tk.Scrollbar(self.frame, orient=tk.VERTICAL)
        tk.Listbox.__init__(self, self.frame, yscrollcommand=self.yscroll.set, *arg, **key)
        self.yscroll['command'] = self.yview

    def grid(self, *arg, **key):
        self.frame.grid(*arg, **key)
        tk.Listbox.grid(self, row=0, column=0, sticky='nswe')
        self.yscroll.grid(row=0, column=1, sticky='ns')

rawDescription: Tkinter Python managing scrollbar inside the listbox in a canvas


code:
dictio = {}
file2 = open(file)
for line in file2.readlines():
    parts = line.split(' ')
    if parts[0] in dictio:
        print('duplicate ' + line)
    else:
        dictio[parts[0]] = parts[1]

rawDescription: Comparing Large CSV file rows to other rows - Python - Memory Issues


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

import logging
import sys
from PyQt4 import QtGui

log = logging.getLogger(__name__)

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

        vbox = QtGui.QVBoxLayout(self)
        self.setLayout(vbox)

        self.a = QtGui.QLineEdit(self)
        self.b = QtGui.QLineEdit(self)

        vbox.addWidget(self.a)
        vbox.addWidget(self.b)

        self.a.textChanged.connect(self.textchangedA)
        self.b.textChanged.connect(self.textchangedB)

    def textchangedA(self, text):
        log.info("Text from a: %s", text)
        log.info("Text from b: %s", self.b.text())
        # do the processing

    def textchangedB(self, text):
        log.info("Text from b: %s", text)
        log.info("Text from a: %s", self.a.text())

def test():
    app = QtGui.QApplication(sys.argv)
    w = MyWidget()
    w.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    test()

rawDescription: How could get String(Text) from QlineEdit dynamically?


code:
from collections import defaultdict

scores = defaultdict(int)

with open('score.txt') as infile:
    for line in infile:
        fields = line.split()
        name, score = ' '.join([fields[0], fields[1]]), int(fields[2])
        scores[name] += score

print(max(scores, key=scores.get), scores[max(scores, key=scores.get)])

rawDescription: Score calculation in dictionary looking for improvment


code:
import os
import time
modified = os.stat(file)[stat.ST_MTIME]
mtime = time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(modified))
response.headers['Last-Modified'] = mtime
response.headers['Pragma'] = 'cache'
response.headers['Cache-Control'] = 'private'

rawDescription: How to modify web2py download function to return "304 Not Modified" in case the file did not change?

description: Modify web2py download function to return "304 Not Modified" in case the file did not change


code:
import wx
import wx.lib.scrolledpanel

class gui(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, None, id, title, style=wx.DEFAULT_FRAME_STYLE)
        mainPanel = wx.lib.scrolledpanel.ScrolledPanel(self, -1)
        mainPanel.SetupScrolling()
        myImage = wx.Image('greensquares.jpg', wx.BITMAP_TYPE_ANY).ConvertToBitmap()
        myBitmap = wx.StaticBitmap(mainPanel, -1, myImage, (0, 0))
        self.myPanelA = wx.Panel(myBitmap, -1, style=wx.TRANSPARENT_WINDOW, pos=(100,0), size=(150,150))
        wx.StaticText(self.myPanelA, -1, 'self.myPanelA')
        myButton1A = wx.Button(self.myPanelA, -1, size=(20,20))
        myButton2A = wx.Button(self.myPanelA, -1, size=(20,20))
        mySizerA = wx.BoxSizer(wx.HORIZONTAL)
        mySizerA.Add(myButton1A, 0, wx.ALL, 20)
        mySizerA.Add(myButton2A, 0, wx.ALL, 20)
        self.myPanelA.SetSizer(mySizerA)
        self.myPanelA.Layout()

        self.myPanelB = wx.Panel(myBitmap, -1, style=wx.TRANSPARENT_WINDOW, pos=(100,130), size=(250,200))
        wx.StaticText(self.myPanelB, -1, 'self.myPanelB')
        myButton1B = wx.Button(self.myPanelB, -1, size=(20,20))
        myButton2B = wx.Button(self.myPanelB, -1, size=(20,20))
        myButton3B = wx.Button(self.myPanelB, -1, size=(20,20))
        myButton4B = wx.Button(self.myPanelB, -1, size=(20,20))
        mySizerB1 = wx.BoxSizer(wx.HORIZONTAL)
        mySizerB1.Add(myButton1B, 0, wx.ALL, 20)
        mySizerB1.Add(myButton2B, 0, wx.ALL, 20)
        mySizerB1.Add(myButton3B, 0, wx.ALL, 20)
        mySizerB1.Add(myButton4B, 0, wx.ALL, 20)
        myButton5B = wx.Button(self.myPanelB, -1, size=(20,20))
        myButton6B = wx.Button(self.myPanelB, -1, size=(20,20))
        myButton7B = wx.Button(self.myPanelB, -1, size=(20,20))
        myButton8B = wx.Button(self.myPanelB, -1, size=(20,20))
        mySizerB2 = wx.BoxSizer(wx.HORIZONTAL)
        mySizerB2.Add(myButton5B, 0, wx.ALL, 20)
        mySizerB2.Add(myButton6B, 0, wx.ALL, 20)
        mySizerB2.Add(myButton7B, 0, wx.ALL, 20)
        mySizerB2.Add(myButton8B, 0, wx.ALL, 20)
        mySizerC = wx.BoxSizer(wx.VERTICAL)
        mySizerC.Add(mySizerB1)
        mySizerC.Add(mySizerB2)
        self.myPanelB.SetSizer(mySizerC)
        self.myPanelB.Layout()

        self.Bind(wx.EVT_SIZE, self.OnResize)
        self.Bind(wx.EVT_SCROLL, self.OnResize)

    def OnResize(self, e):
        self.myPanelA.Update()
        self.myPanelB.Update()
        e.Skip()

if __name__ == '__main__':
    app = wx.App()
    frame = gui(parent=None, id=-1, title="My-App")
    frame.Show()
    app.MainLoop()

rawDescription: Graphics issue upon resizing a panel in wxPython


code:
vars = {"var": 5}
array = []
array.append("var")
vars[array[0]] = 1

print(vars[array[0]]) # prints "1"
print(vars["var"])    # ditto

rawDescription: Python - List of variables

description: Python - List of variables


code:
from Crypto.Cipher import Blowfish
from struct import pack

bs = Blowfish.block_size
key = b'An arbitrarily long key'
ciphertext = b'\xe2:\x141vp\x05\x92\xd7\xfa\xb5@\xda\x05w.\xaaRG+U+\xc5G\x08\xdf\xf4Xua\x88\x1b'
iv = ciphertext[:bs]
ciphertext = ciphertext[bs:]

cipher = Blowfish.new(key, Blowfish.MODE_CBC, iv)
msg = cipher.decrypt(ciphertext)

last_byte = msg[-1]
msg = msg[:- (last_byte if type(last_byte) is int else ord(last_byte))]
print(repr(msg))

rawDescription: How to decrypt using Blowfish in Pycrypto?

description: Decrypt using Blowfish in Pycrypto


code:
import numpy as np
from scipy.optimize import curve_fit, leastsq

def f(x,r,s):
    """ The fit function, applied to every x_k for the vectors r_i and s_i. """
    x = x[...,np.newaxis]  # add an axis for the summation
    # by virtue of numpy's fantastic broadcasting rules,
    # the following will be evaluated for every combination of k and i.
    x2s2 = (x*s)**2
    return np.sum(r * x2s2 / (1 + x2s2), axis=-1)

# fit using curve_fit
popt,pcov = curve_fit(
    lambda x,*params: f(x,params[:N],params[N:]),
    X,Y,
    np.r_[R0,S0],
)
R = popt[:N]
S = popt[N:]

# fit using leastsq
popt,ier = leastsq(
    lambda params: f(X,params[:N],params[N:]) - Y,
    np.r_[R0,S0],
)
R = popt[:N]
S = popt[N:]

rawDescription: Fitting a sum to data in Python

description: Fitting a sum to data in Python


code:
def random_partition(k, iterable):
  results = [[] for i in range(k)]
  for value in iterable:
    x = random.randrange(k)
    results[x].append(value)
  return results

rawDescription: How to generate a random partition from an iterator in Python

description: Generate a random partition from an iterator in Python


code: a, b = np.polyfit(n, np.log(k), 1)

rawDescription: Line of best fit for a log graph in python 3.3


code:
import wx

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

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Test")
        panel = wx.Panel(self)
        self.count = 0

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

        usernameLbl = wx.StaticText(panel, label="Username:")
        self.username = wx.TextCtrl(panel)
        self.addWidgets(usernameLbl, self.username)

        pwLbl = wx.StaticText(panel, label="Password:")
        self.pw = wx.TextCtrl(panel)
        self.addWidgets(pwLbl, self.pw)

        btn = wx.Button(panel, label="Login")
        btn.Bind(wx.EVT_BUTTON, self.onClick)
        self.mainSizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)

        panel.SetSizer(self.mainSizer)
        self.Show()

    #----------------------------------------------------------------------
    def addWidgets(self, lbl, txt):
        """"""
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(lbl, 0, wx.ALL|wx.CENTER, 5)
        sizer.Add(txt, 1, wx.ALL|wx.EXPAND, 5)
        self.mainSizer.Add(sizer, 0, wx.ALL|wx.EXPAND)

    #----------------------------------------------------------------------
    def onClick(self, event):
        """"""
        password = self.pw.GetValue()
        user = self.username.GetValue()

        if user!="Username" and password!="Password":
            # count for the number of tries
            msg = "You have %s tries left"%(str(3-self.count))
            dlg = wx.MessageDialog(self, msg, "", wx.OK)
            dlg.ShowModal()
            dlg.Destroy()

            self.count += 1
            password=self.pw.GetValue() #retakes the password
            user=self.username.GetValue() #retakes the username
            if self.count == 3:
                self.Destroy()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

rawDescription: Getting input form a GUI within a loop in python


rawDescription: Python: Create Generators at Runtime

description: Python: Create Generators at Runtime


code:
def forwards(self, orm):
    from django.core.management import call_command
    call_command("loaddata", "my_fixture.json")

rawDescription: How would I use a South migration to load data into Django's auth_group table?


code:
import numpy as np
# Just an example array, you need to define your array here
my_array = np.random.normal(0,1e-7,10000).reshape(100,100)
# np.sum instead of normal python sum. If you have NaNs try np.nansum
np.sum(my_array)
# 2.9210826829167365e-06

rawDescription: Integrating an array over all elements in python


code:
from twisted.web import xmlrpc, server

class MultiStep(xmlrpc.XMLRPC):
    def __init__(self) :
        xmlrpc.XMLRPC.__init__(self)
        self.db = {}
    def getX(self, user, x):
       self.db[user] = {'x' : x}
       return 'OK'
    def getY(self, user, y):
       self.db[user]['y'] = y
       return 'OK'
    def plus(self,user) :
       return self.db[user]['x'] + self.db[user]['y']

if __name__ == '__main__':
    from twisted.internet import reactor
    r = MultiStep()
    reactor.listenTCP(6666, server.Site(r))
    reactor.run()

rawDescription: Tack on session support to a 'stateless' xml-rpc app


rawDescription: Calculate Pandas dataframe column - boolean logic and offset data


code:
from sqlalchemy.sql import column
column('YourColumn') != None
str(column('YourColumn') != None)

rawDescription: sqlalchemy IS NOT NULL select

description: Sqlalchemy IS NOT NULL select


code:
import random
print ("Welcome to Math Extreme PRE EARLY PRE-ALPHA")
score = 0
def AskAQuestion1():
    global score
    Number1 = random.randint(0,10)
    Number2 = random.randint(0,10)
    print ("Calculate"+ str(Number1) + "+"+ str(Number2)+"")
    answer = input ()
    answer = int (answer)
    if answer == Number1+Number2:
         print ("Correct")
         score = score + 1
    else:
         print ("wrong")

rawDescription: Fixing scoring system

description: Fixing scoring system


code:
dataInSocket, _, _ = socket.select.select([sock], [], [])
if dataInSocket:
    data, addr = sock.recvfrom(MAX_MESS_LEN)
    thread.start_new_thread(message_handler, (data, addr,))

rawDescription: How can I interrupt a recvfrom() call in Python with keyboard?

description: Interrupt a recvfrom() call in Python with keyboard


code:
from django.utils.timezone import localtime

localtime(obj.start_time)

rawDescription: How can i remove the timezone offset from datetime in python

description: Remove the timezone offset from datetime in python


code:
import platform
platform.linux_distribution()
" ".join(platform.linux_distribution())

rawDescription: How to Strip Python Output

description: Strip Python Output


code: days = [today.strftime("%a %b %y"), ...]

rawDescription: Getting Python to print pretty date strings?


code:
def total_ups():
    children = json.loads(reddit_front)["data"]["children"]
    return sum(c["data"]["ups"] for c in children)

rawDescription: Python Json loops

description: Python Json loops


code:
def factorial( n ):
   if n <1:   # base case
       return 1
   else:
       returnNumber = n * factorial( n - 1 )  # recursive call
       print(str(n) + '! = ' + str(returnNumber))
       return returnNumber

rawDescription: recursive factorial function

description: Recursive factorial function


code:
import numpy as np
a
b
np.dot(a,b)

rawDescription: Python - cross array multiplication

description: Python - cross array multiplication


code:
class MyLocIndexer(_LocIndexer):
    def __getitem__(self, key):
        try:
            return super().__getitem__(key)
        except KeyError:
            item = db.fetch_item(key)
            self[key] = item
            return item
            # `return self[key]' is better as it also works when accessing a
            # whole axis

class MyDataFrame(DataFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._loc = MyLocIndexer(self, "loc")

rawDescription: Overloading in python - pandas

description: Overloading in python - pandas


code:
import imp
import sys

def loadm(name, path):
    fp, pathname, description = imp.find_module(name,[path])
    try:
        _module = imp.load_module(name, fp, pathname, description)
        return _module
    finally:
        # Since we may exit via an exception, close fp explicitly.
        if fp:
            fp.close()

numpy = loadm("numpy", "/home/username/py-virtual27/lib/python2.7/site-packages/")
scipy = loadm("scipy", "/home/username/py-virtual27/lib/python2.7/site-packages/")

rawDescription: How to speed up python starting up and/or reduce file search while loading libraries?

description: Speed up python starting up and/or reduce file search while loading libraries


code:
def intersect(a, b):
    if len(a) > len(b):
        a, b = b, a

    c = set()
    for x in a:
        if x in b:
            c.add(x)
    return c

rawDescription: What's the algorithm of 'set.intersection()' in python?


code:
incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)

rawDescription: Inserting the same value multiple times when formatting a string


code:
w, v = linalg.eig(L)
seen = {}
unique_eigenvalues = []
for (x, y) in zip(w, v):
    if x in seen:
        continue
    seen[x] = 1
    unique_eigenvalues.append((x, y))
fiedler = sorted(unique_eigenvalues)[1][1]

rawDescription: Computing the Fiedler Vector in Python

description: Computing the Fiedler Vector in Python