code:
# -*- coding: utf-8 -*-
"""
Created on Tue May 19 10:45:47 2015

@author: greenthumbtack
"""

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector

fig,axarr = plt.subplots(2,3)
#fig = plt.figure(figsize=(10,8))

def make_f(start,end):
    sum = 0
    for n in range(start,end+1):
        sum += np.cos(2 * n * np.pi *time) + 2* np.random.random()
    return sum

time   = np.linspace(0,10,1001)
signal = make_f(1,10)

axarr[0,0].plot(time, signal, '-')
#ax.set_ylim(-2,2)
axarr[0,0].set_title('Press left mouse button and drag to test')

fourier = np.fft.rfft(signal)
n = signal.size
rate = time[1]-time[0]

axarr[1,0].plot(np.fft.rfftfreq(n,rate), 20*np.log10(fourier), '-')
axarr[0,1].plot(time, signal)
axarr[1,1].plot(np.fft.rfftfreq(n,rate), 20*np.log10(fourier), '-')
axarr[0,2].plot(time, signal)
axarr[1,2].plot(np.fft.rfftfreq(n,rate), 20*np.log10(fourier), '-')

def onselect(xmin, xmax):
    indmin, indmax = np.searchsorted(time, (xmin, xmax))
    indmax = min(len(time)-1, indmax)

    thisx = time[indmin:indmax]
    thisy = signal[indmin:indmax]
    thisy_fourier = np.fft.rfft(thisy)
    thisx_n = thisx.size
    rate = thisx[1] - thisx[0]
    axarr[1,0].clear()
    axarr[1,0].plot(np.fft.rfftfreq(thisx_n,rate), 20*np.log10(thisy_fourier))
    axarr[1,0].set_xlim(0, 11)
    #ax2.set_ylim(0, thisy.max())
    fig.canvas.draw()

def onselect2(xmin, xmax):
    indmin, indmax = np.searchsorted(time, (xmin, xmax))
    indmax = min(len(time)-1, indmax)

    thisx = time[indmin:indmax]
    thisy = signal[indmin:indmax]
    thisy_fourier = np.fft.rfft(thisy)
    thisx_n = thisx.size
    rate = thisx[1] - thisx[0]
    axarr[1,1].clear()
    axarr[1,1].plot(np.fft.rfftfreq(thisx_n,rate), 20*np.log10(thisy_fourier))
    axarr[1,1].set_xlim(0, 11)
    #ax2.set_ylim(0, thisy.max())
    fig.canvas.draw()

def onselect3(xmin, xmax):
    indmin, indmax = np.searchsorted(time, (xmin, xmax))
    indmax = min(len(time)-1, indmax)

    thisx = time[indmin:indmax]
    thisy = signal[indmin:indmax]
    thisy_fourier = np.fft.rfft(thisy)
    thisx_n = thisx.size
    rate = thisx[1] - thisx[0]
    axarr[1,2].clear()
    axarr[1,2].plot(np.fft.rfftfreq(thisx_n,rate), 20*np.log10(thisy_fourier))
    axarr[1,2].set_xlim(0, 11)
    #ax2.set_ylim(0, thisy.max())
    fig.canvas.draw()

span = SpanSelector(axarr[0,0], onselect, 'horizontal', useblit=True,
                    rectprops=dict(alpha=0.5, facecolor='red') )
span2 = SpanSelector(axarr[0,1], onselect2, 'horizontal', useblit=True,
                    rectprops=dict(alpha=0.5, facecolor='red') )
span3 = SpanSelector(axarr[0,2], onselect3, 'horizontal', useblit=True,
                    rectprops=dict(alpha=0.5, facecolor='red') )

rawDescription: SpanSelector with Fourier analysis

description: SpanSelector with Fourier analysis


code:
sql = """INSERT INTO teams (Name) VALUES({0})""".format(json.dumps(name))
cur.execute(sql)

rawDescription: Python pymysql INSERT INTO inserting empty values


code:
class Foo(object):
        __slots__ = ['__thisattr', '__thatattr']
        def __init__(self, **kwargs):
            for name,val in kwargs.items():
               setattr(self, "__"+name, val)
        @property
        def thisattr(self):
            return self.__thisattr
        @property
        def thatattr(self):
            return self.__thatattr
f = Foo(thisattr="this", thatattr="that")
f.thisattr
f.thatattr
f.thisattr = "Something Else"

rawDescription: User defined immutables in python w/o subclassing


code:
with open('inputfile.txt') as inf, open('wordsonly.txt', 'w') as outf:
    for line in inf:
        line = line.rstrip()
        if line:
            word, wordtype = line.split()[2:4]
            if wordtype in ('a', 'n', 'v', 'adv'):
                print(word, file=outf)

rawDescription: How to clean Python file (numbers, patterns)?

description: Clean Python file (numbers, patterns)


code: [list(item) for item in s.split()]

rawDescription: Split the string 'abcde' into a list with separate elements


code:
whitelist = set()
f = open("users/"+name+".txt", "r")
print("[INFO]LOADING WHITELIST-LVL-1...")
soundz("info")
time.sleep(1)
for name in os.listdir(path):
    if len(name.strip()[:-4])>0: whitelist.add(name.strip()[:-4])
f.close()

rawDescription: Python append only unique names instead of duplicates


rawDescription: Get Each Element in a List using Python

description: Get Each Element in a List using Python


code:
class MyDefaultDict(dict):
    def __missing__(self, key):
        self[key] = key
        return key
d = MyDefaultDict()
d['joe']
d

rawDescription: Python dictionary that defaults to key?

description: Python dictionary that defaults to key


code:
# Menu
# Ask whether to print BMI, BMR, or to exit
output = str(input('Calulate BMI or BMR or Exit: '))
print ('You entered: ' + output) # Try not to print 'random' info

# Exit, I put it up here to make sure the next step doesn't trigger
if output == 'exit' or output == 'Exit' or output == 'EXIT':
   print('Exiting...') # Try to always notify the user about what is going on
   exit()

# Check if the input is valid
if output != 'BMI' and output != 'bmi' and output != 'BMR' and output != 'bmr':
   print('Please enter a valid choice.')
   exit()

# Get user's height, weight and age values
# Never write code more than once, either place it in a function or
# take it elsewhere where it will be used once only
height = int(input('Please enter your height in inches: '))
weight = int(input('Please enter your weight in pounds: '))

# BMI
if output == 'BMI' or output == 'bmi':

   # Do the first steps of the formula
   heightSquared = (height * height)
   finalWeight = (weight * 703)

   # Figure out and print the BMI
   bmi = finalWeight / heightSquared

   if bmi < 18: # First step, is it less than 18?
      text = 'Underweight'

   elif bmi <= 24: # If it isn't is it less than or equal to 24?
      text = 'Ideal'

   elif bmi <= 29: # If not is it less than or equal to 29?
      text = 'Overweight'

   elif bmi <= 39: # If not is it less than or equal to 39?
      text = 'Obese'

   else: # If none of the above work, i.e. it is greater than 39, do this.
      text = 'Extremely Obese'

   print ('Your BMI is: ' + str(bmi))
   print ('This is: ' + text)

# BMR
elif output == 'bmr' or output == 'BMR':

   gender = str(input('Are you male (M) or female (F): '))
   age = int(input('Please enter your age in years: '))
   bmr = 0 # Initialize the bmr

   if gender == 'M' or gender == 'm':
      # Figure out and print the BMR
      bmr = 66 + (6.2 * weight) + (12.7 * height) - (6.76 * age)

   if gender == 'F' or gender == 'f':
      # Figure out and print the BMR
      bmr = 655 + (4.35 * weight) + (4.7 * height) - (4.7 * age)

   print ('Your BMR is: ' + bmr)

rawDescription: Im tring to make a BMI BMR calculator in Pythion3


code:
[[i[0][0],
int(any([1 for j in i[1] if j>0])),
int(any([1 for j in i[2] if j>=1200])),
int(any([1 for j in i[3] if j=='Yes']))] for i in data]

rawDescription: Creating a boolean list from sublists . Python 2.7


code: re.sub(reg, rep, text)

rawDescription: Fastest Python method for search and replace on a large string


code:
import xlsxwriter

workbook = xlsxwriter.Workbook(r'C:\hello.xlsx')
worksheet = workbook.add_worksheet()
worksheet.write('A1', 'Hello world')
workbook.close()

rawDescription: xlsxwriter not creating a desired Excell file

description: Xlsxwriter not creating a desired Excell file


code: mylist = [item for item in mylist if item != 'cats']

rawDescription: How to delete all instance names in a list?

description: Delete all instance names in a list


rawDescription: regex that extracts $ and % values from the string

description: Regex that extracts $ and % values from the string


code:
score = dict(high=0, medium=1, low=2)
mylist.sort(key=lambda x: score[x.priority])

rawDescription: Sorting a list of objects in python on basis of attribute's three different value?


code:
import pandas as pd
url = 'http://myurl.com/mypage/'

for i, df in enumerate(pd.read_html(url)):
    df.to_csv('myfile_%s.csv' % i)

rawDescription: Script that converts html tables to CSV (preferably python)


code:
int(63.0)
int(sheet.row(1)[0].value)

rawDescription: Integers from excel files become floats?

description: Integers from excel files become floats


code: c = 0xFFFFFFFF & (a+b)

rawDescription: Truncate integers when more than 64 bits


code:
fd = open('file.csv','a')
fd.write(yourCsvRowWithNewIP)
fd.close()

rawDescription: Amend a csv file in Python

description: Amend a csv file in Python


code:
import networkx as nx
G = nx.Graph()
G.add_node(1)
G.node[1]
G.add_node(1,name='firstNode')
G.node[1]
G.add_node(1,name='changed')
G.node[1]
G.add_node(1,name='changed',attribute='new')
G.node[1]
G.add_node(1,name='changed',attribute='new')
G.node[1]
G.add_node(1)
G.node[1]
nx.nodes(G)

rawDescription: In networkX python , is it possible to add the same with same ID ?


code:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect("address")

def send_msg(sock):
    while True:
        data = sys.stdin.readline()
        sock.send(data)

def recv_msg(sock):
    while True:
        data, addr = sock.recv(1024)
        sys.stdout.write(data)

Thread(target=send_msg, args=(sock,)).start()
Thread(target=recv_msg, args=(sock,)).start()

rawDescription: multiple clients cannot listen and write at the same time

description: Multiple clients cannot listen and write at the same time


code:
while not done:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done=True

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                if player.rect.x > 0:
                    player.rect.x -= player.rect.width
            elif event.key == pygame.K_RIGHT:
                if player.rect.x < screen_width: # the screen/game width
                    player.rect.x += player.rect.width
            # Something similar for the up & down keys

rawDescription: Make an Image move one space with arrow keys in python / pygame


code:
import os
my_path = os.environ['VOL']

rawDescription: How to access a drive by volume label in a python script in Ubuntu

description: Access a drive by volume label in a python script in Ubuntu


code:
import pygame
import math
import numpy as np

clock = pygame.time.Clock()
pygame.init()
size = (width, height) = (600,500)
screen = pygame.display.set_mode(size)

class pendulum:
    def __init__(self,x,y,x0,y0):
        self.x0 = np.array((x0, y0))
        self.x = np.array((x, y), dtype=float)
        self.v = np.zeros((2,), dtype=float)
        self.a = np.zeros((2,), dtype=float)
    def CalcForce(self):
        dx = self.x0 - self.x
        angle = math.atan2(-dx[0], dx[1])
        a = g[1]*math.sin(angle)  # tangential accelation due to gravity
        self.a[0] = at*math.cos(angle)
        self.a[1] = at*math.sin(angle)
    def move(self):
        #print np.dot(self.a, self.x-self.x0) #is a perp to string?
        self.x += dt*self.v
        self.v += dt*self.a
    def draw(self):
        pygame.draw.circle(screen, (0,0,0), self.x0, 5)
        pygame.draw.line(screen, (0,0,0), self.x0, self.x.astype(int),3)
        pygame.draw.circle(screen, (0,0,255), self.x.astype(int), 14,0)
        pygame.draw.line(screen, (255, 0, 0), (self.x+200*self.a).astype(int), self.x.astype(int), 4)
dt = .001
g = [0,0.4]
p = pendulum(350,100,300,20)

while 1:
    screen.fill((255,255,255))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
    for i in range(100): # don't plot every timestep
        p.CalcForce()
        p.move()
        p.draw()
    clock.tick(60)
    pygame.display.flip()

rawDescription: Pendulum simulation

description: Pendulum simulation


code:
lda = LDA(n_components=2) #creating a LDA object
lda = lda.fit(X, y) #learning the projection matrix
X_lda = lda.transform(X) #using the model to project X
# .... getting Z as test data....
Z = lda.transform(Z) #using the model to project Z
z_labels = lda.predict(Z) #gives you the predicted label for each sample
z_prob = lda.predict_proba(Z) #the probability of each sample to belong to each class

rawDescription: How to perform prediction with LDA (linear discriminant) in scikit-learn?

description: Perform prediction with LDA (linear discriminant) in scikit-learn


rawDescription: python pick and delete by item using dict comprehension

description: Python pick and delete by item using dict comprehension


code:
menu1.add_command(label='Informationen', command = info, accelerator="F5")
menu1.add_command(label='Beenden', command = ende, accelerator="esc")

rawDescription: Tkinter Menu makes no Tab [Windows only]


code:
def __init__(self, channel, queued):
    """
    @param channel: the channel we're connected to.
    @param queued: are we in the request queue, or can we start writing to
        the transport?
    """
    self.notifications = []
    self.channel = channel
    self.queued = queued
    ...

rawDescription: Access the channel from a http.Request instance in Twisted


code:
import itertools

users = df.user_id.unique()
df_indexed = df.set_index(['user_id', 'day'])
index = pd.MultiIndex.from_tuples(list(itertools.product(users, range(365))))
reindexed = df_indexed.reindex(index, fill_value=0)

rawDescription: Reshaping pandas DataFrame from long to wide while adding many columns


code:
page, created = Page.objects.get_or_create(
    user=request.user,
    link=link,
    title=BeautifulSoup.BeautifulSoup(urllib.urlopen(link)).title.string
  )

rawDescription: Using BeautifulSoup to populate a Django model


code: xdata, ydata = event.artist.get_data()

rawDescription: Label for point in plots in matplotlib

description: Label for point in plots in matplotlib


code:
import numpy as np
import cv2

src = cv2.imread('objects.png')
src_flatten = np.reshape(np.ravel(src, 'C'), (-1, 3))
dst = np.zeros(src.shape, np.float32)

colors = np.array([[0x00, 0x00, 0x00],
                   [0xff, 0xff, 0xff],
                   [0xff, 0x00, 0x00],
                   [0x00, 0xff, 0x00],
                   [0x00, 0x00, 0xff]], dtype=np.float32)
classes = np.array([[0], [1], [2], [3], [4]], np.float32)

knn = cv2.KNearest()
knn.train(colors, classes)
retval, result, neighbors, dist = knn.find_nearest(src_flatten.astype(np.float32), 1)

dst = colors[np.ravel(result, 'C').astype(np.uint8)]
dst = dst.reshape(src.shape).astype(np.uint8)

cv2.imshow('src', src)
cv2.imshow('dst', dst)
cv2.waitKey()

rawDescription: Efficient way to cluster colors using K-Nearest


code:
import inspect

class BaseObject(object):
    def __init__(self):
        frame = inspect.stack()[1][0]
        args, _, _, values = inspect.getargvalues(frame)
        for key in args:
            setattr(self, key, values[key])

class Sub(BaseObject):
    def __init__(self, argone, argtwo, argthree, argfour):
        super(Sub, self).__init__()

rawDescription: how do you automate setting self attributes in init of python class?

description: Automate setting self attributes in init of python class


code:
numOfRooms = int(input("num of rooms:"))
tsa = 0
for n in range(numOfRooms):
    input("name of room:")
    numOfWalls = int(input("num of walls:"))
    sa = 0
    for wall in range(numOfWalls):
        height = int(input("height of wall:"))
        width = int(input("width of wall:"))
        sa = sa + (height * width)
    tsa = tsa + sa

rawDescription: I cant collect answer from my variables in for loop


code:
parameters = ", ".join(["?"] * 30)
query = 'INSERT INTO the_table VALUES(%s);' % parameters
con.executemany(query, data)

rawDescription: how to simplify the so many question mark in the insert string ？

description: Simplify the so many question mark in the insert string ？


code: subprocess.Popen(['example.py', '--q', request.args.get('search_key', '')])

rawDescription: Wrap variable in quotes

description: Wrap variable in quotes


code:
import mymodule
lst = {mymodule.__name__: mymodule}
'mymodule' in globals()   # True
'mymodule' in lst         # True
del mymodule
'mymodule' in globals()   # False
'mymodule' in lst         # Still True

rawDescription: module name in sys.modules and globals()

description: Module name in sys.modules and globals()


code:
class MyForm(forms.ModelForm):
    prioritylevel = forms.ModelChoiceField(queryset=OtherModel.objects.values('level'))

rawDescription: Django Choices based on Foreign Key

description: Django Choices based on Foreign Key


code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        menu = self.menuBar().addMenu('&File')
        action = menu.addAction('&Open')
        action.setShortcut(QtGui.QKeySequence('Ctrl+F'))
        action.triggered.connect(self.handleFind)
        shortcut = QtGui.QShortcut(QtGui.QKeySequence('F3'), self)
        shortcut.activated.connect(self.handleFind)
        label = QtGui.QLabel(self)
        label.setText('<center>Press Ctrl+F or F3<center>')
        self.setCentralWidget(label)

    def handleFind(self):
        reply = QtGui.QMessageBox.question(
            self, 'Message', 'Find Dialog',
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:
            print('Yes')
        else:
            print('No')

if __name__ == '__main__':

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

rawDescription: Keystroke event in Python

description: Keystroke event in Python


code:
import PIL
from PIL import Image

threshold = 220 # Everything below threshold is considered black.

bw = Image.open('abw.jpg')
width, height = bw.size
top = bottom = left = right = None
for y in range(height):
    for x in range(width):
        if bw.getpixel((x,y)) < threshold:
            # if black-ish pixel is found
            if (left is None) or (x < left):
                left = x
            if (right is None) or (x > right):
                right = x
            if (top is None) or (y < top):
                top = y
            if (bottom is None) or (y > bottom):
                bottom = y

im = bw.crop((left, top, right + 1, bottom + 1))
im.show()

rawDescription: Python: Why is my code not cropping a selected image properly?


code:
def g(*args):
    if not args:
        args = (1, 2, 3)
    return 'I received {}!'.format(', '.join(str(arg) for arg in args))

rawDescription: How can I set a default for star arguments?

description: Set a default for star arguments


code: [aList[i] for i in myIndices]

rawDescription: Python: filtering lists by indices

description: Python: filtering lists by indices


code:
import matplotlib.pyplot as plt
import numpy as np
ax = plt.subplot(111, polar=True)

theta = np.linspace(0, 2*np.pi, 100)
r = 2 + np.sin(theta * 2)
ax.patch.set_facecolor('0.5')
ax.plot(theta, r, color='black', ls='-', linewidth=1)
ax.fill(theta,r,'w')
plt.show()
plt.draw() # just to be safe!

rawDescription: Python/Matplotlib Inverse Fill of Polar Plot Polygon


rawDescription: pandas applying regex to replace values

description: Pandas applying regex to replace values


code:
import fileinput
import glob
import re
import sys

files = glob.glob('*.h')
pattern = re.compile(r'#define\s+_([_A-Z]+)_H\s+$')
realstdout = sys.stdout

for line in fileinput.input(files, inplace=True, backup='.bak'):
    sys.stdout.write(line)
    m = pattern.match(line)
    if m:
        sys.stdout.write('\n#define %s_VERSION "10"\n' % m.group(1))
        realstdout.write('%s: %s\n'%(fileinput.filename(),m.group(1)))

rawDescription: Python Script to copy define line in C files


code:
import tkinter as tk
import tkinter.font as tkFont
import tkinter.ttk as ttk
from tkinter import *
def parse_csv(content, delimiter = ';'):  ##We use here ";" to parse CSV because of the European way of dealing with excel-csv
  csv_data = []
  for line in content.split('\n'):
    csv_data.append( [x.strip() for x in line.split( delimiter )] ) # strips spaces also
  return csv_data

canvas=parse_csv(open('canvas.csv','rU',encoding="ISO-8859-1").read())
#fediaf_requirements is a list containing where fediaf has a
fediaf_requirements=[]
for i in range(0,len(canvas)):
               if canvas[i][1]=="FEDIAF":
                  fediaf_requirements.append(canvas[i][0])

car_header = ['Used Nutrients in the Profession', 'Nutrients used in this PetFood (Source : Official Website)', 'FEDIAF Requirement']

#Create the Data to be put into the table
def FromCSV_to_Tree(liste_croq):
    global car_list
    car_list=[]
    value=str(liste_croq.get(liste_croq.curselection()))
    for i in range(0,len(Remplissage)):
               if Remplissage[i][0]=="Name":
                  for j in range(1,len(Remplissage[i])):
                      if Remplissage[i][j]==value:
                          for k in range(0,len(Remplissage)-1):
                              if Remplissage[k][0] in fediaf_requirements :
                                  a="Required"
                              else :
                                  a=""

                              if Remplissage[k][j]!="ND":
                                     car_list.append([Remplissage[k][0],"OK",a])
                              else:
                                  car_list.append([Remplissage[k][0],"",a])

def CurSelet_croq(evt,container):
    global car_list
    FromCSV_to_Tree(liste_croq)
    car_header = ['Used Nutrients in the Profession', 'Nutrients used in this PetFood (Source : Official Website)', 'FEDIAF Requirement']
    print(car_list)

    #create a treeview with dual scrollbars

    #Container and container.pack detached to update the tree with the new datas.
    container.pack(fill='both', expand=True)

    tree = ttk.Treeview(columns=car_header, show="headings")
    vsb = ttk.Scrollbar(orient="vertical",
                        command=tree.yview)
    hsb = ttk.Scrollbar(orient="horizontal",
                        command=tree.xview)
    tree.configure(yscrollcommand=vsb.set,
                   xscrollcommand=hsb.set)
    tree.grid(column=0, row=0, sticky='nsew', in_=container)
    vsb.grid(column=1, row=0, sticky='ns', in_=container)
    hsb.grid(column=0, row=1, sticky='ew', in_=container)

    container.grid_columnconfigure(0, weight=1)
    container.grid_rowconfigure(0, weight=1)

    def sortby(tree, col, descending):
        """sort tree contents when a column header is clicked on"""
        # grab values to sort
        data = [(tree.set(child, col), child) \
            for child in tree.get_children('')]
        # if the data to be sorted is numeric change to float
        #data =  change_numeric(data)
        # now sort the data in place
        data.sort(reverse=descending)
        for ix, item in enumerate(data):
            tree.move(item[1], '', ix)
        # switch the heading so it will sort in the opposite direction
        tree.heading(col, command=lambda col=col: sortby(tree, col, \

            int(not descending)))

##Put data into the tree
    for col in car_header:
        tree.heading(col, text=col.title(),
                     command=lambda c=col: sortby(tree, c, 0))
        # adjust the column's width to the header string
        tree.column(col,
                    width=tkFont.Font().measure(col.title()))

    for item in car_list:
        tree.insert('', 'end', values=item)
        # adjust column's width if necessary to fit each value
        for ix, val in enumerate(item):
            col_w = tkFont.Font().measure(val)
            if tree.column(car_header[ix],width=None)<col_w:
               tree.column(car_header[ix], width=col_w)

Remplissage=parse_csv(open('Remplissage.csv','rU',encoding="ISO-8859-1").read())
root = tk.Tk()
root.wm_title("Visualizer")

container = ttk.Frame()

liste_croq = Listbox(root,width=70, height=10)
for i in range(0,len(Remplissage)):
               if Remplissage[i][0]=="Name":
                  for j in range(1,len(Remplissage[i])):
                      liste_croq.insert(i,Remplissage[i][j])
                      liste_croq.bind('<<ListboxSelect>>', lambda evt, container=container : CurSelet_croq(evt,container))
                      liste_croq.pack()

root.mainloop()

rawDescription: Update the Listbox/Treeview instead of creating a new one each time


code:
rdd = sc.parallelize([('key', ['ele1', 'ele2'])])
rdd.flatMap(lambda data: [(data[0], x) for x in data[1]]).collect()

rawDescription: How to unpack the value (a list) of every item in a RDD in Python?

description: Unpack the value (a list) of every item in a RDD in Python


code:
import pandas as pd
from numpy import diff, concatenate
ff = pd.DataFrame( #acquire data here
      columns=('Year','Recon'))
fd = diff(ff['Recon'], axis=-1)
ff['diff'] = concatenate([[0],fd],axis=0)
ff['rolling10'] = pd.rolling_mean(ff['diff'],10)
ff['rolling5'] = pd.rolling_mean(ff['diff'],5)
ff.plot('Year',['rolling5','rolling10'],subplots=False)

rawDescription: IPython / pandas: Is there an canonical way to detect rapid changes in a timeseries?


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

array = np.random.randn(100)
greater_than_zero = array > 0
lesser_than_zero = array < 0
cax = pl.subplot(111)
cax.bar(np.arange(len(array))[greater_than_zero], array[greater_than_zero], color='b')
cax.bar(np.arange(len(array))[lesser_than_zero], array[lesser_than_zero], color='r')

rawDescription: Bar graph color dependent on value in Matplotlib


code:
class Post(Document):
    title = StringField(max_length=120, required=True)
    author = ReferenceField(User)

class TextPost(Post):
    content = StringField()

class ImagePost(Post):
    image_path = StringField()

class LinkPost(Post):
    link_url = StringField()

rawDescription: MongoDB ORM for Python?

description: MongoDB ORM for Python


code:
from django.db.models.query import CollectedObjects
from django.db.models.fields.related import ForeignKey

def duplicate(obj, value, field):
    """
    Duplicate all related objects of `obj` setting
    `field` to `value`. If one of the duplicate
    objects has an FK to another duplicate object
    update that as well. Return the duplicate copy
    of `obj`.
    """
    collected_objs = CollectedObjects()
    obj._collect_sub_objects(collected_objs)
    related_models = collected_objs.keys()
    root_obj = None
    # Traverse the related models in reverse deletion order.
    for model in reversed(related_models):
        # Find all FKs on `model` that point to a `related_model`.
        fks = []
        for f in model._meta.fields:
            if isinstance(f, ForeignKey) and f.rel.to in related_models:
                fks.append(f)
        # Replace each `sub_obj` with a duplicate.
        sub_obj = collected_objs[model]
        for pk_val, obj in sub_obj.iteritems():
            for fk in fks:
                fk_value = getattr(obj, "%s_id" % fk.name)
                # If this FK has been duplicated then point to the duplicate.
                if fk_value in collected_objs[fk.rel.to]:
                    dupe_obj = collected_objs[fk.rel.to][fk_value]
                    setattr(obj, fk.name, dupe_obj)
            # Duplicate the object and save it.
            obj.id = None
            setattr(obj, field, value)
            obj.save()
            if root_obj is None:
                root_obj = obj
    return root_obj

rawDescription: Duplicating model instances and their related objects in Django / Algorithm for recusrively duplicating an object


code:
import httplib2
from oauth2client.client import OAuth2Credentials

http = httplib2.Http()
credentials = OAuth2Credentials(access_token, client_id, client_secret, refresh_token, None, '', '')
credentials.authorize(http)

rawDescription: how to set up Drive SDK so you dont need a success token each time you run .py

description: Set up Drive SDK so you dont need a success token each time you run .py


code:
reg = r"if\s+\((.*?)\)\s+then\s(.*?)end"
match = re.findall(reg, text, re.DOTALL)

rawDescription: multi-line regex with groups python

description: Multi-line regex with groups python


code:
df
df.columns = [['odd','even','odd'],df.columns]
df

rawDescription: Convert dataframe columns to MultiIndex

description: Convert dataframe columns to MultiIndex


code:
for tokens in text:
    for match in matching_strings:
        if match in tokens:
            sents.append(tokens)
            break
return sents

rawDescription: How could I search specific strings from a text file?


code:
status = ['deleted', '']
Object.objects.filter(country_send=country).exclude(status__in=status).order_by('-id')

rawDescription: Django - Exclude two conditions in query


code: df[df.cancel_date - df.login >= 3].user.value_counts().sort_index()

rawDescription: Pandas: Group-by and Aggregate Column 1 with Condition from Column 2


code:
from Tkinter import *

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        sv = StringVar()
        endHourEntry = Entry(self, textvariable=sv)
        sv.trace("w", lambda name, index, mode, sv=sv:
                             entryUpdateEndHour(endHourEntry))
        endHourEntry.pack()

def entryUpdateEndHour(entry):
    text = entry.get()
    if len(text) in (2,5):
        entry.insert(END,':')
        entry.icursor(len(text)+1)
    elif len(text) not in (3,6):
        if not text[-1].isdigit():
            entry.delete(0,END)
            entry.insert(0,text[:-1])
    if len(text) > 8:
        entry.delete(0,END)
        entry.insert(0,text[:8])

root = Tk()
app = Application(master=root)
app.mainloop()

rawDescription: Tkinter Format Text on Entry

description: Tkinter Format Text on Entry


code:
import wx
import wx.lib.agw.rulerctrl as rc

class MinMax(rc.RulerCtrl):
    def __init__(self, parent, range_min, range_max, orient=wx.HORIZONTAL):
        rc.RulerCtrl.__init__(self, parent, orient)

        self.SetRange(range_min, range_max)
        self.LabelMinor(False)
        self.range_min = range_min
        self.range_max = range_max

        self.AddIndicator(wx.NewId(), range_min)
        self.AddIndicator(wx.NewId(), range_max)

        self.Bind(rc.EVT_INDICATOR_CHANGING, self.OnIndicatorChanging)

    def GetMinIndicatorValue(self):
        return self._indicators[0]._value

    def GetMaxIndicatorValue(self):
        return self._indicators[1]._value

    def SetMinIndicatorValue(self, value):
        # Value must be within range and <= Max indicator value.
        if value < self.range_min or value > self.GetMaxIndicatorValue():
            raise ValueError('Out of bounds!')
        self._indicators[0]._value=value
        self.Refresh()

    def SetMaxIndicatorValue(self, value):
        # Value must be within range and >= Min indicator value.
        if value > self.range_max or value < self.GetMinIndicatorValue():
            raise ValueError('Out of bounds!')
        self._indicators[1]._value=value
        self.Refresh()

    def OnIndicatorChanging(self, evt):
        # Eat the event so the user can't change values manually.
        # Do some validation here and evt.Skip() if you want to allow it.
        # Related: EVT_INDICATOR_CHANGED
        pass

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

        self.minmax = MinMax(self, 0, 100)
        self.minmax.SetSpacing(20)
        self.minmax.SetMinIndicatorValue(30)
        self.minmax.SetMaxIndicatorValue(84)
        self.Show()

app = wx.App(redirect=False)
frame = MainWindow(None, wx.ID_ANY, "Range Indicator")
app.MainLoop()

rawDescription: double valued gauge in wxpython

description: Double valued gauge in wxpython


code: pd.concat((pd.read_json(d) for d in data), axis=0)

rawDescription: JSON dictionaries to Pandas DataFrame in Python


code:
import sqlite3

def main():
    try:
        conn=sqlite3.connect(":memory:")
        cur = conn.cursor()
        cur.execute("create table master(id text, sub text)")
        cur.execute("insert into master(id, sub) values ('1', 'abc')")
        cur.execute("insert into master(id, sub) values ('2', 'def')")
        cur.execute("insert into master(id, sub) values ('3', 'ghi')")
        conn.commit()
    except:
        print("I am unable to connect to the database.")
        sys.exit()

    cur.execute("select id, sub from master where sub='abc'")
    print(cur.fetchall())
    cur.execute("UPDATE master SET sub = ('xyz') WHERE sub = 'abc'")
    conn.commit()
    cur.execute("select id, sub from master where sub='abc'")
    print(cur.fetchall())
    cur.execute("select id, sub from master where sub='xyz'")
    print(cur.fetchall())

if __name__=="__main__":
    main()

rawDescription: Confirmation that a postgres 'update' query worked in python


code:
if event.buttons() & Qt.MidButton:
    if event.modifiers() & Qt.ControlModifier:
        self.camera.pan(dx, dy)
    else:
        self.camera.rotate(dx, dy)

rawDescription: Use Qt.MidButton and Qt.MidButton+Qt.ControlModifier in PyQt to rotate and translate/pan


code:
def test_update_using_positional_operator(self):
    """Ensure that the list fields can be updated using the positional
    operator."""

    class Comment(EmbeddedDocument):
        by = StringField()
        votes = IntField()

    class BlogPost(Document):
        title = StringField()
        comments = ListField(EmbeddedDocumentField(Comment))

    BlogPost.drop_collection()

    c1 = Comment(by="joe", votes=3)
    c2 = Comment(by="jane", votes=7)

    BlogPost(title="ABC", comments=[c1, c2]).save()

    BlogPost.objects(comments__by="jane").update(inc__comments__S__votes=1)

    post = BlogPost.objects.first()
    self.assertEquals(post.comments[1].by, 'jane')
    self.assertEquals(post.comments[1].votes, 8)

rawDescription: How to Do An Atomic Update on an EmbeddedDocument in a ListField in MongoEngine?


code:
bitsums = list()
with open('test.txt') as fobj:
    for line in fobj:
        bitsums.append(sum(int(c) for c in line.strip()[1::7]))

rawDescription: Save python output into variable

description: Save python output into variable


code:
clam = lambda a: max(min(a, 0.8), 0.2)
def clamp(a, *args):
    if args:
       return [ clam(arg) for arg in (a,)+args]
    else:
       return clam(a)

clamp(123, 123)
clamp(123)

rawDescription: Unpacking variable length list returned from function


code:
date_xf = easyxf(num_format_str='DD/MM/YYYY') # sets date format in Excel
data = [list(n) for n in cursor.fetchall()]
for row_index, row_contents in enumerate(data):
    for column_index, cell_value in enumerate(row_contents):
        if isinstance(cell_value, datetime.date):
            sheet1.write(row_index+1, column_index, cell_value, date_xf)
        else:
            sheet1.write(row_index+1, column_index, cell_value)

rawDescription: only apply date format to date columns with xlwt

description: Only apply date format to date columns with xlwt


code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import random

count = []
for i in range(1, 4):
    for j in range(3, 6):
        for k in range(15,19):
            count.append((i, j, k, random.random()))

data = np.array(count)
fig = plt.figure()
ax = fig.gca(projection='3d')

# I think this is the sort of thing you want:

ax.plot_trisurf(data[:,0], data[:,1], data[:,3])
plt.show()

rawDescription: 3d plot in python based on matrix

description: 3d plot in python based on matrix


rawDescription: Is there a way to `apply` a function to one column of a dataframe while leaving the other columns fixed?


rawDescription: How to find the number of times function f is executed?

description: Find the number of times function f is executed


code:
L = [['a', 'b'], ['c', 'd'], ['e']]
import itertools
list(itertools.product(*L))
list(''.join(tup) for tup in list(itertools.product(*L)))

rawDescription: Combining two lists ( so [['a', 'b'], ['c', 'd']] = ['ac', 'ad', 'bc', 'bd] ) the pythonic way


code:
def check_file_for_string(filename,string):
    with open(filename) as fin:
         return string in fin.read()

rawDescription: Delete file if it contains a string

description: Delete file if it contains a string


code:
sorted(x.items(), key=lambda t: -len(t[1]))
# [('THREE', ['up', 'side', 'down']), ('TWO', ['hot', 'mess']), ('ONE', ['foo'])]

rawDescription: Can keys be rearranges after dictionary creation?


code:
def fetchFuction():
    QtGui.QApplication.setOverrideCursor(QtGui.QCursor(QtCore.Qt.WaitCursor))
    # if incase function failed then restore it
    try:
        yourFetchFucn()
        QtGui.QApplication.restoreOverrideCursor()
    except:
        QtGui.QApplication.restoreOverrideCursor()

rawDescription: How to disable button(or whole main window) in PyQt4 until the function returns 0

description: Disable button(or whole main window) in PyQt4 until the function returns 0


code: x.join(y, getattr(x, 'column1') == getattr(y, 'column2'))

rawDescription: How to pass an argument to a function that doesn't take string (Pyspark)

description: Pass an argument to a function that doesn't take string (Pyspark)


code:
range(5)
range(5.0)
range("5")
range(0, 5)
range(0, 5.0)

rawDescription: Functions: changing variable from int to float


code:
class SomeDataStructure(object):
    def sum(self):
        return sum(self._data)
    def otherCalc(self):
        return sum(item for item in somethingElse)

rawDescription: Why doesn't "class" start a new scope like "def" does?


code:
infile = open('MyFile.csv', 'r')
for line in infile.readlines():
    spl_line = line.split(',')
    if int(spl_line[0]) in MyDict.keys():
        MyDict[spl_line[0]].update(spl_line[1:])

rawDescription: Generating a .CSV with Several Columns - Use a Dictionary?


code: {x[1]:x for x in lol}

rawDescription: From a list of lists to a dictionary

description: From a list of lists to a dictionary


code:
from difflib import get_close_matches
orders_list = ["initiate", "eat", "run", "set coords to"]
get_close_matches('eating', orders_list)

rawDescription: How to know if a part of my string is in another one

description: Know if a part of my string is in another one


code:
class http(object):
    def get(self, resource=None):
        self.resource = resource
        self._response = requests.get(self.resource)
        return self._response

def get(resource=None):
    temp_instance = http()
    return temp_instance.get(resource)

rawDescription: Why cannot I not create an object like this in Python?


code:
from numpy import float128
from sympy.abc import x
from sympy.utilities import lambdify

f = lambdify(x, x ** 2)
result = f(float128(2))

result
#>>> 4.0

type(result)
#>>> <class 'numpy.float128'>

rawDescription: Can lambdify return an array with dytpe np.float128?


code:
when(module_declaring_UserAdapter)\
    .UserAdapter(self.user_public_key)\
    .thenReturn(UserAdapter_mock)

rawDescription: Python mockito - Mocking a class which is being instantiated from the testable function


rawDescription: Flask - How to make an app externally visible through a router?


code:
class List(list):
    pass

weaklist = List()
weaklist.append('a')
weaklist.append('b')
stronglist = [ ['c','d','e'] ]
weaklist
stronglist
import weakref
stronglist.append(weakref.ref(weaklist))
stronglist
stronglist[1]()
del weaklist
stronglist
stronglist[1]()

rawDescription: Total object deletion in python

description: Total object deletion in python


code:
def pytest_generate_tests(metafunc):
    data = [
        # input # output # is expected to fail?
        (2, 4, False),
        (3, 10, True),
        (4, 16, False),
        (5, 26, True),
        ]
    for input, expected, xfail in data:
        if metafunc.function is test_evenHigherThanSquare:
            metafunc.addcall(funcargs=dict(input=input, expected=expected),
                             param=xfail)

def pytest_funcarg__xfail(request):
    if request.param:
        request.applymarker(py.test.mark.xfail)

def test_evenHigherThanSquare(input, expected, xfail):
    assert evenHigherThanSquare(input) == expected

rawDescription: How to mark some generated tests as xfail/skip?

description: Mark some generated tests as xfail/skip


code:
def execute_sp( sp_name, paramaters ):
    #helper method to run sp's and return results
    db = Db()
    cursor = db.cursor()
    cursor.callproc(sp_name,paramaters)
    cursor.nextset() #Need the second result set in the proc
    results = cursor.fetchallDict()
    cursor.close()
    return results

rawDescription: SQL_CALC_FOUND_ROWS in mysql stored procedure with python


code:
request = webapp2.get_request()
host_url = request.host_url

rawDescription: How can I access current request in appengine?

description: Access current request in appengine


code:
import ctypes
x=ctypes.c_char_p(0)
x
x=ctypes.c_char_p(None)
x

rawDescription: Python interfacing with C library - How to have a null c pointer


code:
import numpy as np
import gdal

cols = 50539
rows = 10000
offset = 1000

dst_filename = 'test.tif'
format = 'GTiff'
driver = gdal.GetDriverByName(format)

dst_ds = driver.Create(dst_filename, cols, rows, 1, gdal.GDT_Byte)

for i in range(10):
    # generate random integers from 1 to 10
    a = np.random.random_integers(1, 10, size=(offset, cols))
    # write data to band 1
    dst_ds.GetRasterBand(1).WriteArray(a, 0, offset * i)

dst_ds = None

rawDescription: Write data to GeoTiff using GDAL without creating data array?


code:
e = pygame.event.poll()
if e == pygame.MOUSEBUTTONDOWN:
    pos = e.pos
    # where "screen" is your variable holding the screen surface
    color = screen.get_at((pos))

rawDescription: pygame - pixel collision map

description: Pygame - pixel collision map


code:
import lxml.etree as ET
doc = ET.fromstring(data)
c = doc.find('.//c2')
c
c.findall('..//s2')

rawDescription: Relative python xml node traversal

description: Relative python xml node traversal


code:
class EventList(list):
    pass

def GetEvents(file_path):

    ...

    events = EventList(events)
    events.event_header = some_header
    return events

rawDescription: Best practice for refactoring a python function to return a tuple, instead of a single variable?


code:
import win32gui, win32api, win32con

hwnd = app.dlg.ctrl.handle
ex_style = app.dlg.ctrl.ExStyle()
win32gui.SetWindowLong (hwnd, win32con.GWL_EXSTYLE, ex_style | win32con.WS_EX_LAYERED )
win32gui.SetLayeredWindowAttributes(hwnd, win32api.RGB(0,0,0), 180, win32con.LWA_ALPHA)

rawDescription: How to make a window transparent with pywinauto?

description: Make a window transparent with pywinauto


code:
import signal
class SignalHandler(object):
    def __init__(self):
        self.retval = None
    def handle(self, sig, frm):
        self.retval = sig

s = SignalHandler()
s.retval
signal.signal(signal.SIGALRM, s.handle)
signal.alarm(1)
s.retval

rawDescription: Python signal: reading return from signal handler function


code:
def remove_accents(data):
    return ''.join(x for x in unicodedata.normalize('NFKD', data) if x in string.ascii_letters).lower()

rawDescription: removing accent and special characters

description: Removing accent and special characters


code:
data = [good, bad]
theList = [obj for obj in (MyObject(some_data) for some_data in data) if obj.data_is_valid]

rawDescription: Python: Cancel object creation during initialization


code:
from IPython.core.display import HTML
HTML("<style> div.code_cell{width: 75%;float: left;}"
    +"div.text_cell{width: 25%;float: right;}"
    +"div.text_cell div.prompt {display: none;}</style>")

rawDescription: Ipython notebook on 2 columns

description: Ipython notebook on 2 columns


rawDescription: Join two pandas data frames with the indices of the first?


code:
import decimal
decimal.Decimal('1.99')

rawDescription: Calculate a tip & total, without rounding errors. (Python)


code:
def recursively_default_dict():
    return collections.defaultdict(recursively_default_dict)

my_dict = recursively_default_dict()
my_dict['a']['b'] = 'c'

rawDescription: Automatically add key to Python dict

description: Automatically add key to Python dict


code:
def evalBooleans(value):
    """Assumes we're getting either booleans or strings!"""
    return (value if isinstance(value, bool)
                else value.lower() == "true")

cb2 = evalBooleans(config.StartValues['Checkbox2'])
self.Checkbox2.SetValue(cb2)
self.Checkbox2TextCtrl.Enable(cb2)
self.Checkbox2StaticText.Enable(cb2)

rawDescription: wxPython: Enabling and disabling widgets dynamically, getting settings from a csv file

description: WxPython: Enabling and disabling widgets dynamically, getting settings from a csv file


code:
from flask.ext.stormpath import login_user
from flask.ext.stormpath.models import User

from app import stormpath_manager

# ...

main_cloud_directory = stormpath_manager.client.directories.search({
    'name': 'Directory Name'
})[0]
accounts = main_cloud_directory.accounts.search({'email': email})

if accounts.size == 1:
    account = accounts[0]
    account.__class__ = User
    login_user(account, remember=False)

    return redirect('/settings')
else:
    abort(404)

rawDescription: How to implement "login as" admin function with `stormpath-flask`

description: Implement "login as" admin function with `stormpath-flask`


code:
import markdown
mode = "remove" # or "replace" or "escape"
md = markdown.Markdown(safe_mode=mode)
html = md.convert(text)

rawDescription: Lightweight markup language for Python

description: Lightweight markup language for Python


code:
import sys
import os
from PySide import QtGui, QtCore

class TestListView(QtGui.QListWidget):

    fileDropped = QtCore.Signal(list)

    def __init__(self, type, parent=None):
        super(TestListView, self).__init__(parent)
        self.setAcceptDrops(True)
        self.setIconSize(QtCore.QSize(72, 72))

    def dragEnterEvent(self, event):
        if event.mimeData().hasUrls:
            event.accept()
        else:
            event.ignore()

    def dragMoveEvent(self, event):
        if event.mimeData().hasUrls:
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        if event.mimeData().hasUrls:
            event.setDropAction(QtCore.Qt.CopyAction)
            event.accept()
            links = []
            for url in event.mimeData().urls():
                links.append(str(url.toLocalFile()))
            self.fileDropped.emit(links)
        else:
            event.ignore()

class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        self.view = TestListView(self)
        self.view.fileDropped.connect(self.pictureDropped)
        self.setCentralWidget(self.view)

    def pictureDropped(self, l):
        for url in l:
            if os.path.exists(url):
                print(url)
                icon = QtGui.QIcon(url)
                pixmap = icon.pixmap(72, 72)
                icon = QtGui.QIcon(pixmap)
                item = QtGui.QListWidgetItem(url, self.view)
                item.setIcon(icon)
                item.setStatusTip(url)

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

rawDescription: PySide: Drag and drop files into QListWidget


code:
import json

projects = []
projects.append({'project_name': 'foobar',
                 'author': 'John Doe',
                 'email': 'spam@example.com',
                 'year': '2010'})
projects.append({'project_name': 'baz',
                 'author': 'Cat Stevens',
                 'email': 'cs@example.com',
                 'year': '2009'})

with open('projects.json', 'w') as f:
    json.dump(projects, f)

rawDescription: Updating section in ConfigParser (or an alternative)


code:
def get_int(prompt, minval, maxval):
    '''Prompt for integer value between minval and maxval, inclusive.
    Repeat until user provides a valid integer in range.
    '''
    while 1:
        n = int(input(prompt))
        if (n < minval):
            print("value too small")
            print("value must be at least {0}".format(minval))
        elif (n > maxval):
            print("value too large")
            print("value must be not more than {0}".format(maxval))
        else:
            print("value accepted")
            return n
    pass
    # TODO: raise a ValueError or a RuntimeError exception
    # if user does not provide valid input within a preset number tries

if __name__ == "__main__":
    # Example: test the get_int function
    # Requires user interaction.
    # Expect out-of-range values 0, 101, -5, etc. should be rejected.
    # Expect range limit values 1 and 100 shoudl be accepted.
    # Expect in-range values like 50 or 75 should be accepted.
    minval = 1
    maxval = 100
    test1 = get_int("Choose a number between {0} and {1}: ".format(
        minval,maxval), minval, maxval)
    print("get_int returned {0}".format(test1))

rawDescription: Name "prompt" not defined

description: Name "prompt" not defined


code:
class SubItemForm(ModelForm):

    def __init__(self,user,*args,**kwargs):
        super(SubItemForm, self).__init__(*args, **kwargs)
        self.fields['advisor'].queryset = User.objects.filter(groups__name='advisor')

rawDescription: Selecting specific users

description: Selecting specific users


rawDescription: How to add a tuple to the first position of a list in Python

description: Add a tuple to the first position of a list in Python


code:
from bs4 import BeautifulSoup

VALID_TAGS = ['strong', 'em', 'p', 'ul', 'li', 'br']

def sanitize_html(value):

    soup = BeautifulSoup(value)

    for tag in soup.findAll(True):
        if tag.name not in VALID_TAGS:
            tag.hidden = True

    return soup.renderContents()

rawDescription: Python HTML sanitizer / scrubber / filter


code:
def merge(self, request, queryset):
    main = queryset[0]
    tail = queryset[1:]

    related = main._meta.get_all_related_objects()

    valnames = dict()
    for r in related:
        valnames.setdefault(r.model, []).append(r.field.name)

    for place in tail:
        for model, field_names in valnames.iteritems():
            for field_name in field_names:
                model.objects.filter(**{field_name: place}).update(**{field_name: main})

        place.delete()

    self.message_user(request, "%s is merged with other places, now you can give it a canonical name." % main)

rawDescription: Django: merging objects

description: Django: merging objects


code:
def find_index(needle, haystack):
    for i in range(len(haystack)):
        if needle == haystack[i]:
            return i
    else:
        return -1    # didn't find it

rawDescription: How do you find the index of a character in a string?

description: Find the index of a character in a string


code:
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches

verts = [(0., 0.), # left, bottom
         (-1., 1.), # left, top
         (1., 3.), # right, top
         (2., 2.), # right, bottom
         (0., 0.),] # ignored

codes = [Path.MOVETO,
         Path.LINETO,
         Path.LINETO,
         Path.LINETO,
         Path.CLOSEPOLY,]

path = Path(verts, codes)
fig = plt.figure()
ax = fig.add_subplot(111)
patch = patches.PathPatch(path, facecolor='orange', lw=2)
ax.add_patch(patch)
ax.axis('equal')
plt.show()

rawDescription: matplotlib - How to plot a random-oriented rectangle (or any shape)?

description: Matplotlib - How to plot a random-oriented rectangle (or any shape)


code:
def game():

    isWinner = False
    while isWinner == False:
       # as the user for a guess
       # check the guess
       isWinner = isWon()
    return "You won!"

rawDescription: Hangman Program: Loop Validation

description: Hangman Program: Loop Validation


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

from PyQt4 import QtCore, QtGui

class myWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(myWindow, self).__init__(parent)
        self.centralwidget  = QtGui.QWidget(self)
        self.lineEdit       = QtGui.QLineEdit(self.centralwidget)
        self.view           = QtGui.QTableView(self.centralwidget)
        self.comboBox       = QtGui.QComboBox(self.centralwidget)
        self.label          = QtGui.QLabel(self.centralwidget)

        self.gridLayout = QtGui.QGridLayout(self.centralwidget)
        self.gridLayout.addWidget(self.lineEdit, 0, 1, 1, 1)
        self.gridLayout.addWidget(self.view, 1, 0, 1, 3)
        self.gridLayout.addWidget(self.comboBox, 0, 2, 1, 1)
        self.gridLayout.addWidget(self.label, 0, 0, 1, 1)

        self.setCentralWidget(self.centralwidget)
        self.label.setText("Regex Filter")

        self.model = QtGui.QStandardItemModel(self)

        for rowName in range(3) * 5:
            self.model.invisibleRootItem().appendRow(
                [   QtGui.QStandardItem("row {0} col {1}".format(rowName, column))
                    for column in range(3)
                    ]
                )

        self.proxy = QtGui.QSortFilterProxyModel(self)
        self.proxy.setSourceModel(self.model)

        self.view.setModel(self.proxy)
        self.comboBox.addItems(["Column {0}".format(x) for x in range(self.model.columnCount())])

        self.lineEdit.textChanged.connect(self.on_lineEdit_textChanged)
        self.comboBox.currentIndexChanged.connect(self.on_comboBox_currentIndexChanged)

        self.horizontalHeader = self.view.horizontalHeader()
        self.horizontalHeader.sectionClicked.connect(self.on_view_horizontalHeader_sectionClicked)

    @QtCore.pyqtSlot(int)
    def on_view_horizontalHeader_sectionClicked(self, logicalIndex):
        self.logicalIndex   = logicalIndex
        self.menuValues     = QtGui.QMenu(self)
        self.signalMapper   = QtCore.QSignalMapper(self)

        self.comboBox.blockSignals(True)
        self.comboBox.setCurrentIndex(self.logicalIndex)
        self.comboBox.blockSignals(True)

        valuesUnique = [    self.model.item(row, self.logicalIndex).text()
                            for row in range(self.model.rowCount())
                            ]

        actionAll = QtGui.QAction("All", self)
        actionAll.triggered.connect(self.on_actionAll_triggered)
        self.menuValues.addAction(actionAll)
        self.menuValues.addSeparator()

        for actionNumber, actionName in enumerate(sorted(list(set(valuesUnique)))):
            action = QtGui.QAction(actionName, self)
            self.signalMapper.setMapping(action, actionNumber)
            action.triggered.connect(self.signalMapper.map)
            self.menuValues.addAction(action)

        self.signalMapper.mapped.connect(self.on_signalMapper_mapped)

        headerPos = self.view.mapToGlobal(self.horizontalHeader.pos())

        posY = headerPos.y() + self.horizontalHeader.height()
        posX = headerPos.x() + self.horizontalHeader.sectionPosition(self.logicalIndex)

        self.menuValues.exec_(QtCore.QPoint(posX, posY))

    @QtCore.pyqtSlot()
    def on_actionAll_triggered(self):
        filterColumn = self.logicalIndex
        filterString = QtCore.QRegExp(  "",
                                        QtCore.Qt.CaseInsensitive,
                                        QtCore.QRegExp.RegExp
                                        )

        self.proxy.setFilterRegExp(filterString)
        self.proxy.setFilterKeyColumn(filterColumn)

    @QtCore.pyqtSlot(int)
    def on_signalMapper_mapped(self, i):
        stringAction = self.signalMapper.mapping(i).text()
        filterColumn = self.logicalIndex
        filterString = QtCore.QRegExp(  stringAction,
                                        QtCore.Qt.CaseSensitive,
                                        QtCore.QRegExp.FixedString
                                        )

        self.proxy.setFilterRegExp(filterString)
        self.proxy.setFilterKeyColumn(filterColumn)

    @QtCore.pyqtSlot(str)
    def on_lineEdit_textChanged(self, text):
        search = QtCore.QRegExp(    text,
                                    QtCore.Qt.CaseInsensitive,
                                    QtCore.QRegExp.RegExp
                                    )

        self.proxy.setFilterRegExp(search)

    @QtCore.pyqtSlot(int)
    def on_comboBox_currentIndexChanged(self, index):
        self.proxy.setFilterKeyColumn(index)

if __name__ == "__main__":
    import sys

    app  = QtGui.QApplication(sys.argv)
    main = myWindow()
    main.show()
    main.resize(400, 600)
    sys.exit(app.exec_())

rawDescription: How to create filters for QTableView in PyQt

description: Create filters for QTableView in PyQt


code:
A = []
B = []
C = []

group_dict = {'A': A, 'B': B, 'C': C}

for line in test_file:
    group = line.strip()[0]
    group_dict[group].append(line)

rawDescription: Python appending to a list from a string with the same name


code:
for alist in mylists:           # Use alist, not list, to avoid shadowing list built-in
    while alist:                 # Faster equivalent to while len(alist) > 0:
        print(' '.join(alist))   # Join and print current value
        alist.pop()              # Remove last, finished when emptied

rawDescription: Iterate through a list in python

description: Iterate through a list in python


code:
def exists_pair(seq):
    if len(seq) < 2:
        return False
    a, b = seq[0]  # could be: seq.pop() if modifications are allowed
    a_group = set()
    b_group = set()
    for c, d in seq:
        if not ({a,b} & {c,d}):
            return True
        elif {a,b} == {c,d}:
            continue
        elif a in {c,d}:
            a_group.add(c if c != a else d)
        else:
            b_group.add(c if c != b else d)

    if not a_group:
        return False

    # b_group - a_group: elements of b_group that do not appear in a_group
    return bool(b_group - a_group)

rawDescription: Find a pair of pairs with no intersection


code: result = [[str(subitem) for subitem in sublist] for sublist in start]

rawDescription: In python, is there a way to convert of list of integer-lists into a list of string-lists without creating a custom function?


code:
number = 12
a = False
myResult  = ''
for myCounter in range (8):

    if (number % 2 == 1):#if remainder is equal to 1
        myResult = ' 1 ' + myResult#add '1' character to the string

    else:
        (number % 2 == 0)#if input has no remainder
        myResult = ' 0 ' + myResult#add '0' character to the string

    number = number // 2

print("Binary equivalent is: %s" %myResult)

rawDescription: Converting Integer to Binary return wrong values


code:
import numpy
data = "1|234|4456|789"
numpy.fromstring(data, dtype=int, sep="|")

rawDescription: Efficient way to convert delimiter separated string to numpy array


rawDescription: Python multiply list of lists element-wise


code:
if request.env.http_referer:
    redirect(request.env.http_referer)

rawDescription: web2py redirect to previous page

description: Web2py redirect to previous page


code:
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import randn

fig = plt.figure()
data = np.clip(randn(250,250),-1,1)
cax = plt.imshow(data, interpolation='nearest')

title_obj = plt.title('my random fig') #get the title property handler
plt.getp(title_obj)                    #print out the properties of title
plt.getp(title_obj, 'text')            #print out the 'text' property for title
plt.setp(title_obj, color='r')         #set the color of title to red

axes_obj = plt.getp(cax,'axes')                 #get the axes' property handler
ytl_obj = plt.getp(axes_obj, 'yticklabels')     #get the properties for
                                                #  yticklabels
plt.getp(ytl_obj)                               #print out a list of properties
                                                #  for yticklabels
plt.setp(ytl_obj, color="r")                    #set the color of yticks to red

plt.setp(plt.getp(axes_obj, 'xticklabels'), color='r') #xticklabels: same

color_bar = plt.colorbar()                            #this one is a little bit
cbytick_obj = plt.getp(color_bar.ax.axes, 'yticklabels')                #tricky
plt.setp(cbytick_obj, color='r')

plt.savefig('temp.png')
plt.savefig('temp2.png', facecolor="black", edgecolor="none")

rawDescription: matplotlib: change title and colorbar text and tick colors

description: Matplotlib: change title and colorbar text and tick colors


code: {{ url_for('content', values=name) }}

rawDescription: Send GET parameter on url_for inside HTML


code:
if __name__ == "__main__":
    main(*sys.argv[1:])

rawDescription: Using sys.argv for input through Terminal


code: {{ content|safe }}

rawDescription: Django form modifying HTML tags

description: Django form modifying HTML tags


code:
from PySide import QtGui

def do_something():
    id = g.checkedId()
    if id == -1:
        print('no option selected')
    else:
        print('selected option {}, read for display'.format(id))

app = QtGui.QApplication([])

w = QtGui.QWidget()
l = QtGui.QVBoxLayout(w)

# three radio buttons
b1 = QtGui.QRadioButton('Option 1')
l.addWidget(b1)
b2 = QtGui.QRadioButton('Option 2')
l.addWidget(b2)
b3 = QtGui.QRadioButton('Option 3')
l.addWidget(b3)

# a button group (mapping from buttons to integers)
g = QtGui.QButtonGroup(w)
g.addButton(b1, 1)
g.addButton(b2, 2)
g.addButton(b3, 3)

# display button
b = QtGui.QPushButton('Display')
b.clicked.connect(do_something)
l.addWidget(b)

w.show()

app.exec_()

rawDescription: How to set up and react to multiple display options?

description: Set up and react to multiple display options


code:
soup = BeautifulSoup(open('yourhtml.html').read())
for tr in soup('tr'):
    if tr('td')[3].text == '0.00':
         tr.extract()

rawDescription: how to remove table row based on contents of one of the cells in the row using python?

description: Remove table row based on contents of one of the cells in the row using python


code:
def callfunc(self, f, args):
  f(*args)

rawDescription: How does function call another function in Python


rawDescription: "is" operator behaves unexpectedly with integers


code:
x=np.arange(1,7).reshape(2,3)
x
mask=np.ones_like(x,bool)
mask
mask[0,0]=False
mask[1,1]=False
mask
x[mask]
x[mask].reshape(2,2)

rawDescription: Deleting elements at specific positions in a M X N numpy array


code:
item["Attribute"] = []
item["Attribute"].append({'type':"ip-dst"})
item["Attribute"][0]["category"] ="Network activity"
item["Attribute"][0]["to-ids"] = True
item["Attribute"][0]["distribution"] = "3"
item["Attribute"][0]['ip']  = response.xpath('//*[@id="contacted-   hosts"]//tr[1]/td[1]/text()').extract()

item["Attribute"].append({'type':"domain"})
item["Attribute"][1]["category"] ="Network activity"
item["Attribute"][1]["to-ids"] = True
item["Attribute"][1]["distribution"] = "3"
item["Attribute"][1]['domain'] = response.xpath('//*[@id="dns-requests"]//a/text()').extract()

item["Attribute"].append({'type':"md5"})
item["Attribute"][2]["category"] ="Payload delivery"
item["Attribute"][2]["to-ids"] = True
item["Attribute"][2]["distribution"] = "3"
item["Attribute"][2]['md5'] = response.xpath('//*[contains(text(), "MD5")]/following-sibling::dd[1]/text()')[0].extract()

rawDescription: Scrapy json modifying array

description: Scrapy json modifying array


code: scoring_matrix += (data_random >= data_sorted).astype(int)

rawDescription: Efficiently update values held in scoring matrix


code:
class Spinner(object):
  def __init__(self):
    self._chars = r"-\|/-\|/"
    self._pos = 0

  def spin(self):
    sys.stdout.write(self._chars[self._pos])
    sys.stdout.write("\r")
    sys.stdout.flush()
    self._pos += 1
    if self._pos >= len(self._chars):
      self._pos = 0
    return True

spinner = Spinner()
gobject.timeout_add(2 * 1000, spinner.spin)

rawDescription: python gtk loop ascii spinner

description: Python gtk loop ascii spinner


code:
d = {'foo':'bar'}
kwargs = {'bar':'baz'}
dict(d,**kwargs)

rawDescription: How does the double asterik operator work here?


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

def main():
    nrows = 3
    fig, axes = plt.subplots(nrows, 2)

    for row in axes:
        x = np.random.normal(0, 1, 100).cumsum()
        y = np.random.normal(0, 0.5, 100).cumsum()
        plot(row, x, y)

    plt.show()

def plot(axrow, x, y):
    axrow[0].plot(x, color='red')
    axrow[1].plot(y, color='green')

main()

rawDescription: populating matplotlib subplots through a loop and a function

description: Populating matplotlib subplots through a loop and a function


code:
class A(object):
    def __init__(self):
        self.dict = {}

    def stuff(self, name):
        self.dict[name] = 'toto'

rawDescription: Python object's attribute

description: Python object's attribute


code:
def model_changed(self):
    self.model_changed_stamp = datetime.datetime.now()

rawDescription: changing value of datetimefield from instance method

description: Changing value of datetimefield from instance method


rawDescription: Does ruby have a zip function like python's?


code:
import itertools
list(itertools.chain.from_iterable([['a', 'b', 'c'], ['ab', 'ac', 'bc'], ['abc']]))

rawDescription: Combine a 2D array into 1D without numpy


code:
def group_by_day(self, event):
    result = {}
    for e in event:
        day = event.start.day
        result.setdefault(day, []).append(event)
    return result

rawDescription: Explain this python lambda

description: Explain this python lambda


rawDescription: Valid domain name regex

description: Valid domain name regex


code:
def obj_get_list(self, bundle, **kwargs):

    param =  bundle.request.GET['param']
    #fetch objects based on param
    return objects

rawDescription: get request parameters in Tastypie

description: Get request parameters in Tastypie


code: foo.bar is not foo.bar

rawDescription: How should functions be tested for equality or identity?


code:
text = open('txt_filename').read()
data = eval('[' + text + ']')

rawDescription: Parsing a plaintext document into a python array


code:
from itertools import product
product(range(2), repeat=3)

rawDescription: How to flatten large loop stacks?

description: Flatten large loop stacks


code:
t = datetime.strptime(self.start, "%H:%M:%S").time()
start = datetime.combine(self.job_record.date, t)

rawDescription: Python: Testing for unicode, and converting to time()


code:
from tkinter import *

root = Tk()

b = Button(root, text="Delete me", command=lambda: b.pack_forget())
b.pack()

root.mainloop()

rawDescription: How to delete Tkinter widgets from a window?

description: Delete Tkinter widgets from a window


code:
#### import the simple module from the paraview
from paraview.simple import *

# save animation images/movie
WriteAnimation('/tmp/movie.ogv', Magnification=1, FrameRate=15.0, Compression=True)

rawDescription: Save Animation via Python Script in ParaView


code: req = urllib2.Request('{}?{}'.format(google.urls['directions'], urllib.urlencode(data)))

rawDescription: Request to google directions api wrongly asks for sensor


code:
rng = pd.date_range("20150105","20150620",freq="D",tz="Asia/Hong_Kong")
rng.format(formatter=lambda x: x.strftime('%Y%m%d'))

rawDescription: How to change date_range into string with the method in array?

description: Change date_range into string with the method in array


code:
for line in input_f:

    # find the positions of As in the line
    positions = [n for n, letter in enumerate(line, 1) if letter == 'a']

    # Create list of strings of the form "x:y"
    pairs = [("%d:%d" % (i, n)) for i, n in enumerate(positions, 1)]

    # Join all those strings into a single space-separated string
    all_pairs = ' '.join(pairs)

    # Write the string to the file, with a + sign at the beginning
    # and a newline at the end
    output_f.write("+ %s\n" % all_pairs)

rawDescription: I am not able to use enumerate function properly


code:
import datetime

my_dict = {'date': datetime.date(2018, 9, 30),'Number': u'4929000000006'}

def substring(item):
    if isinstance(item, unicode):
        return repr(item)[1:]

    if isinstance(item, datetime.date):
        return repr(str(item))

    return repr(item)

def dict_substrings(dict):
    yield u"{"

    if my_dict:
        nameitems = my_dict.iteritems()
        name, item = next(nameitems)

        yield substring(name)
        yield u": "
        yield substring(item)

        for name, item in nameitems:
            yield u", "

            yield substring(name)
            yield u": "
            yield substring(item)

    yield u"}"

def dict_representation(dict):
    return "".join(dict_substrings(dict))

print(dict_representation(my_dict))

rawDescription: Django and kwargs why do I get this?

description: Django and kwargs why do I get this


code: soup = BeautifulSoup(htmlcontent, 'html5')

rawDescription: Prevent bs4 from truncating html

description: Prevent bs4 from truncating html


rawDescription: How to generate a "big" random number in Python?

description: Generate a "big" random number in Python


code:
import csv

result={}
with open('/tmp/test.csv','r') as f:
    red=csv.DictReader(f)
    for d in red:
        result.setdefault(d['team'],[]).append(d['bldg'])

#results={'1': ['1450'], '3': ['204', '250', '1437'], '2': ['1440']}

rawDescription: Read two column CSV as dict with 1st column as key


code:
from tornado.ioloop import IOLoop
import tornado.web
from tornado import gen
import time

@gen.coroutine
def async_sleep(timeout):
    """ Sleep without blocking the IOLoop. """
    yield gen.Task(IOLoop.instance().add_timeout, time.time() + timeout)

class MainHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self):
        print("Start request")
        yield async_sleep(4)
        print("Okay done now")
        self.write("Howdy howdy howdy")
        self.finish()

if __name__ == "__main__":
    application =  tornado.web.Application([
        (r'/', MainHandler),
    ])
    application.listen(8888)
    IOLoop.instance().start()

rawDescription: How does long-polling work in Tornado?

description: How does long-polling work in Tornado


code:
def logged_in(self, response):
    if response.url == 'http://my.yahoo.com':
        self.log("Successfully logged in. Now requesting message page.",
                level=log.INFO)
        return Request(MSG_URL % self.msg_id, callback=self.parse_msg,
                errback=self.error, dont_filter=True)
    else:
        self.log("Login failed.", level=log.CRITICAL)

rawDescription: Problem using scrapy to scrape a yahoo group


code:
def plot_cuboid(center, size):
    """
       Create a data array for cuboid plotting.

       ============= ================================================
       Argument      Description
       ============= ================================================
       center        center of the cuboid, triple
       size          size of the cuboid, triple, (x_length,y_width,z_height)
       :type size: tuple, numpy.array, list
       :param size: size of the cuboid, triple, (x_length,y_width,z_height)
       :type center: tuple, numpy.array, list
       :param center: center of the cuboid, triple, (x,y,z)
   """
    # suppose axis direction: x: to left; y: to inside; z: to upper
    # get the (left, outside, bottom) point
    import numpy as np
    ox, oy, oz = center
    l, w, h = size

    x = np.linspace(ox-l/2,ox+l/2,num=10)
    y = np.linspace(oy-w/2,oy+w/2,num=10)
    z = np.linspace(oz-h/2,oz+h/2,num=10)
    x1, z1 = np.meshgrid(x, z)
    y11 = np.ones_like(x1)*(oy-w/2)
    y12 = np.ones_like(x1)*(oy+w/2)
    x2, y2 = np.meshgrid(x, y)
    z21 = np.ones_like(x2)*(oz-h/2)
    z22 = np.ones_like(x2)*(oz+h/2)
    y3, z3 = np.meshgrid(y, z)
    x31 = np.ones_like(y3)*(ox-l/2)
    x32 = np.ones_like(y3)*(ox+l/2)

    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib.pyplot as plt
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    # outside surface
    ax.plot_wireframe(x1, y11, z1, color='b', rstride=1, cstride=1, alpha=0.6)
    # inside surface
    ax.plot_wireframe(x1, y12, z1, color='b', rstride=1, cstride=1, alpha=0.6)
    # bottom surface
    ax.plot_wireframe(x2, y2, z21, color='b', rstride=1, cstride=1, alpha=0.6)
    # upper surface
    ax.plot_wireframe(x2, y2, z22, color='b', rstride=1, cstride=1, alpha=0.6)
    # left surface
    ax.plot_wireframe(x31, y3, z3, color='b', rstride=1, cstride=1, alpha=0.6)
    # right surface
    ax.plot_wireframe(x32, y3, z3, color='b', rstride=1, cstride=1, alpha=0.6)
    ax.set_xlabel('X')
    ax.set_xlim(-100, 100)
    ax.set_ylabel('Y')
    ax.set_ylim(-100, 100)
    ax.set_zlabel('Z')
    ax.set_zlim(-100, 100)
    plt.show()

def test():
    center = [0, 0, 0]
    length = 32 * 2
    width = 50 * 2
    height = 100 * 2
    plot_cuboid(center, (length, width, height))

if __name__ == '__main__':
    test()

rawDescription: python : plotting a wireframe 3D cuboid

description: Python : plotting a wireframe 3D cuboid


code:
a
x = numpy.ones(5)
x
a[:,1] = x
a

rawDescription: Assigning to columns in NumPy?

description: Assigning to columns in NumPy


code: [50 if hasProperty(x) else 10 for x in alist]

rawDescription: Piecewise list comprehensions in python

description: Piecewise list comprehensions in python


code:
@app.route('/')
def index():
    return flask.Response("Foo bar baz"), 204

rawDescription: Send HTTP response that doesn't change the user's current page


code:
import imp
import os
MODULE_EXTENSIONS = ('.py', '.pyc', '.pyo')

def package_contents(package_name):
    file, pathname, description = imp.find_module(package_name)
    if file:
        raise ImportError('Not a package: %r', package_name)
    # Use a set because some may be both source and compiled.
    return set([os.path.splitext(module)[0]
        for module in os.listdir(pathname)
        if module.endswith(MODULE_EXTENSIONS)])

rawDescription: Is there a standard way to list names of Python modules in a package?


code:
import struct
data = '\x37\x01\x37'
struct.unpack('!BBB', data)

rawDescription: pySerial receives as ASCII how to convert into integer?

description: PySerial receives as ASCII how to convert into integer


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

app = QApplication(sys.argv)

web = QWebView()
web.settings().setAttribute(
    QWebSettings.WebAttribute.DeveloperExtrasEnabled, True)
# or globally:
# QWebSettings.globalSettings().setAttribute(
#     QWebSettings.WebAttribute.DeveloperExtrasEnabled, True)

web.load(QUrl("http://www.google.com"))
web.show()

inspect = QWebInspector()
inspect.setPage(web.page())
inspect.show()

sys.exit(app.exec_())

rawDescription: Pyside, webkit basic question

description: Pyside, webkit basic question


code:
UNITS = (
    ('kg', 'kg'),
    ('g', 'g')
)
class Product(models.Model):
    name = models.CharField(max_length=100)
    unit = models.CharField(choices=UNITS)

class Amount(models.Model):
    year = models.IntegerField()
    value = models.FloatField()
    product = models.ForeignKey(Product)

rawDescription: database design in django models for multiple columns for multiple rows.

description: Database design in django models for multiple columns for multiple rows.


code:
import dateutil.parser
d = dateutil.parser.parse('2015-01-05T10:30:47-0800')
d.astimezone(dateutil.tz.tzutc())

rawDescription: Convert datetime to UTC

description: Convert datetime to UTC


code:
def func1():
    my_list=[]
    """Do stuff
    """
    return list

def func2(my_list):
    """Do stuff with my_list
    """
    return

def func3(my_list):
    """Do stuff with my_list
    """
    return

def main():
    """First we retrieve the list from func1,
    func2/3 get it passed to them as an argument
    """
    foo=func1
    func2(foo)
    func3(foo)

if __name__ == "__main__":
    main()

rawDescription: Use a list in different functions in python


code: print(textwrap.wrap(txt, 160))

rawDescription: Python convert for/while into list comprehensions using takewhile


code:
import random

foo = ['a', 'b', 'c', 'd', 'e']
print(random.choice(foo))

rawDescription: How do I randomly select an item from a list using Python?

description: Randomly select an item from a list using Python


code: re.findall(r"/r/([^\s/]+)", string1)

rawDescription: Python regex to match subreddit names

description: Python regex to match subreddit names


code:
newNode = [None,head,newElement]
head[0] = newNode
head = newNode

rawDescription: How can I implement doubly linked lists into my tree structure in Python?

description: Implement doubly linked lists into my tree structure in Python


code:
import sys
sys.path.append('/backend')

rawDescription: Configuring python imports with PyCharm tips


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

# Create a random image 200x360
image = np.random.randn(200, 360)

# Create a sin function from x = 0 - 360, y = -100 - 100
x = np.arange(0, 360, 0.01)
y = 100 * np.sin(np.pi * x / 180)

figure = plt.figure(dpi=70)
subplot = figure.add_subplot(111)
subplot.set_xlim(0, 360)
subplot.set_ylim(-100, 100)
subplot.imshow(image, extent=[min(x), max(x), min(y), max(y)])
subplot.plot(x, y)

figure.show()

rawDescription: Display a image with imshow to be behind another plot in matplotlib


code:
class Assignment(dict):
    '''This inherits from a dict, student will be the key, grade as the score'''
    def __init__(self, name, max_score):
        self.name = name
        self.max_score = max_score
        self.grades = {} # this will be used to store students and grades.

    def __getitem__(self, student):
        # we're overriding getitem, because the default is 0 if a student doesn't turn in their work
        if student in self:
            return dict.__getitem__(self, student)
        return 0.0

class GradeBook(dict):
    '''A gradebook is a dict of assignments'''
    def get_max_score(self):
        return sum(assignment.max_score for assignment in self.values())

    def get_percentage(self, student):
        return 100.0 * sum(assignment[student] for assignment in self.values()) / self.get_max_score()

class Course(object):
    def __init__(self, name, time, teacher, students):
        self.name = name
        self.time = time # can teach multiple courses with the same name, but not at the same time
        self.teacher = teacher
        self.students = students
        self.grade_book = GradeBook()

    def add_assignment(self, assignemnt):
        self.grade_book.append(assignment)

class Person(object):
    def __init__(self, first, last):
        self.first = first
        self.last = last
    def __repr__(self):
        return '<{} {} {}>'.format(self.__class__.__name__, self.first, self.last)

class Student(Person):
    '''A student is a person...'''

class Teacher(Person):
    '''A teacher is a person...'''

rawDescription: How to use nested *Nested Dictionaries*

description: Use nested *Nested Dictionaries*


code:
def __init__(*args, **kwds):
    ...
    self._set_attributes(kwds)

rawDescription: Initializing a instance of a class with dictionary


code:
def pytest_exception_interact(node, call, report):
    pass

rawDescription: Py.Test getting remaining test case count


code:
data_points = [(random.randint(low,high), random.randint(low,high),
                15, random.randint(low,high))for x in range(count)]
plt.scatter(*zip(*data_points))
plt.show()

rawDescription: plotting list of tuples (x coord, y coord, color) with pyplot.scatter() method

description: Plotting list of tuples (x coord, y coord, color) with pyplot.scatter() method


code:
class CSSSelector(etree.XPath):
    """ ...
    To use CSS namespaces, you need to pass a prefix-to-namespace
    mapping as ``namespaces`` keyword argument::

        >>> rdfns = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'
        >>> select_ns = cssselect.CSSSelector('root > rdf|Description',
        ...                                   namespaces={'rdf': rdfns})

        >>> rdf = etree.XML((
        ...     '<root xmlns:rdf="%s">'
        ...       '<rdf:Description>blah</rdf:Description>'
        ...     '</root>') % rdfns)
        >>> [(el.tag, el.text) for el in select_ns(rdf)]
        [('{http://www.w3.org/1999/02/22-rdf-syntax-ns#}Description', 'blah')]
    """

rawDescription: XHTML namespace issues with cssselect in lxml


code:
def sieve(n):
    """Returns a list of primes less than n."""

    # n-long list, all entries initially True
    # prime[n] is True if we haven't found a factor of n yet.
    prime = [True]*n

    # 0 and 1 aren't prime
    prime[0], prime[1] = False, False

    for i in range(2, n):
        if prime[i]:
            # Loop from i*2 to n, in increments of i.
            # In other words, go through the multiples of i.
            for j in range(i*2, n, i):
                prime[j] = False

    return [x for x, x_is_prime in enumerate(prime) if x_is_prime]

rawDescription: How to improve memory intensive Python scripts?

description: Improve memory intensive Python scripts


code:
bytearray('abc')
bytearray('abc')[1]

rawDescription: Python converting UINT8

description: Python converting UINT8


code:
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}
r = requests.post(url, data=json.dumps(payload), headers=headers)

rawDescription: How to write curl get request on python to decrease parsing time

description: Write curl get request on python to decrease parsing time


code:
from pyramid.events import NewRequest
from pyramid.events import subscriber

@subscriber(NewRequest)
def new_request_subscriber(event):
    validate_request(event.request)

rawDescription: Validating pyramid requests

description: Validating pyramid requests


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

fig, ax = plt.subplots()
ax.plot_date(data['time'], data['packets'])
hours = mdates.HourLocator()
fmt = mdates.DateFormatter('%H:%M')
ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(fmt)

rawDescription: Python - Matplotlib - Setting X axis range - Plotting Packets Per Second


code:
class YourObject:
    [...]
    def __eq__(self, other):
        return self.title == other.title

rawDescription: Python check if object is in list of objects


code:
import inspect
class MyClass():
    def a(self):
        pass
    def b(self,foo):
        pass
    def c(self,foo,*extras):
        pass
    def d(self,foo,food='spam'):
        pass
    def e(self,foo,**kwargs):
        pass
    def f(self,foo,*extras,food='spam'):
        pass
    def g(self,foo,*extras,**kwargs):
        pass
    def h(self,foo,*extras,food='spam',**kwargs):
        pass
    def i(self,*extras):
        pass
    def j(self,*extras,food='spam'):
        pass
    def k(self,*extras,**kwargs):
        pass
    def l(self,*extras,food='spam',**kwargs):
        pass
    def m(self,food='spam'):
        pass
    def n(self,food='spam',**kwargs):
        pass
    def o(self,**kwargs):
        pass

def dynamic_invoke(obj,name,parameters):
    action = getattr(obj,name)
    spec = inspect.getfullargspec(action)

    used = []
    args = ()
    kwargs = {}

    for a in spec.args[1:]:
        # skip the "self" argument since we are bound to a class
        args += (parameters[a], )
        used.append(a)

    if spec.varargs:
        args += tuple(parameters[spec.varargs])
        used.append(spec.varargs)

    for kw in spec.kwonlyargs:
        try:
            kwargs[kw] = parameters[kw]
            used.append(kw)
        except KeyError:
            pass

    # pass remaining parameters to kwargs, if allowed
    if spec.varkw:
        for k,v in parameters.items():
            if k not in used:
                kwargs[k] = v

    return action(*args,**kwargs)

me = MyClass()
params = {
        'foo':'bar',
        'extras':['one','two','three','four'],
        'food':'eggs',
        'parrot':'blue'
        }

dynamic_invoke(me,'a',params)
dynamic_invoke(me,'b',params)
dynamic_invoke(me,'c',params)
dynamic_invoke(me,'d',params)
dynamic_invoke(me,'e',params)
dynamic_invoke(me,'f',params)
dynamic_invoke(me,'g',params)
dynamic_invoke(me,'h',params)
dynamic_invoke(me,'i',params)
dynamic_invoke(me,'j',params)
dynamic_invoke(me,'k',params)
dynamic_invoke(me,'l',params)
dynamic_invoke(me,'m',params)
dynamic_invoke(me,'n',params)
dynamic_invoke(me,'o',params)
print('done!')

rawDescription: Python3: Dynamically invoking a method with dictionary of parameters


code:
y_map = {'A':0, 'B':1, 'C':2, 'D':3, 'E':4, 'F':5}

def get_coords(coord_str):
    x,y = coord_str.split()
    x -= 1
    y = y_map[y]
    return (x,y)

user_coords = "A 4"
user_input = 1
user_coords = get_coords(user_coords)
grid[user_coords[1]][user_coords[0]] = user_input

rawDescription: Creating a puzzle

description: Creating a puzzle


code:
t = linspace(0, 4*numpy.pi, 20)
x = sin(2*t)
y = cos(t)
z = cos(2*t)
s = 2 + sin(t)
mlab.points3d(x, y, z, s, colormap="copper", scale_mode='none')

rawDescription: Disable points scaling in 3D scatter plots in Mayavi


code:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.label import Label

class TestApp(App):
    def build(self):
        return  Button(text="show", on_press=self.anim_btn)

    def anim_btn(self, *args):
        popup = Popup(title='Test popup',
            content=Label(text='Hello world'),
            size_hint=(None, None),
            size=(400, 400),
            background = 'atlas://data/images/defaulttheme/button_pressed'
        ).open()

if __name__ == "__main__":
    TestApp().run()

rawDescription: How to change popup color in kivy

description: Change popup color in kivy


code:
x = 0
y = 1
print("a" if x < y else "b")

rawDescription: python (bool) ? then : else syntax?

description: Python (bool) ? then : else syntax


rawDescription: How to find dimension of a tuple?

description: Find dimension of a tuple


code: {{ form.DELETE }}

rawDescription: Django - Customising the display of FormSet objects?


rawDescription: Python string representation of binary data


code:
class MyRouter(routers.DefaultRouter):
    def get_api_root_view(self):
        """
        Return a view to use as the API root.
        """
        api_root_dict = OrderedDict()
        list_name = self.routes[0].name
        for prefix, viewset, basename in self.registry:
            api_root_dict[prefix] = list_name.format(basename=basename)

        class APIRoot(views.APIView):
            _ignore_model_permissions = True

            def get(self, request, *args, **kwargs):
                ret = OrderedDict()
                namespace = request.resolver_match.namespace
                for key, url_name in api_root_dict.items():
                    if namespace:
                        url_name = namespace + ':' + url_name
                    try:
                        ret[key] = reverse(
                            url_name,
                            args=args,
                            kwargs=kwargs,
                            request=request,
                            format=kwargs.get('format', None)
                        )
                    except NoReverseMatch:
                        # Don't bail out if eg. no list routes exist, only detail routes.
                        continue

                ret['book-featured-list'] = '%s%s' % (ret['books'], 'featured/')

                return Response(ret)

        return APIRoot.as_view()

rawDescription: Include list_route methods in Django REST framework's API root


code:
def get_items(cheapness):
    """ Return a list of (item, (price, count)) tuples that are the given
    cheapness. Note that the second element of the tuple is another tuple. """

    if cheapness == 'CHEAP':
        return [(item, (price,count)) for (item, (price,count)) in inventory.items() if price < 20]
    elif cheapness == 'MODERATE':
        return [(item, (price,count)) for (item, (price,count)) in inventory.items() if price > 20 and price < 100]
    elif cheapness == 'EXPENSIVE':
        return [(item, (price,count)) for (item, (price,count)) in inventory.items() if price > 100]

rawDescription: How do I return this as a list

description: Return this as a list


code:
map = {}
with open(r'c:\temp\input.csv', 'r') as fin:
    reader = csv.reader(fin)
    with open(r'c:\temp\output.csv', 'w') as fout:
        writer = csv.writer(fout)
        # omit this if the file has no header row
        writer.writerow(next(reader))
        for row in reader:
            (id, name, phone, ref, discard) = row
            if map.has_key(phone):
                ref = map[phone]
                discard = "YES"
            else:
                map[phone] = id
            writer.writerow((id, name, phone, ref, discard))

rawDescription: marking duplicates in a csv file

description: Marking duplicates in a csv file


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

def plot(x,y,i,num):
    snum = np.sqrt(num)+1
    ax = plt.subplot(snum,snum,i)
    ax.plot(x,y)

numberofplots = 31
for i in range(1,numberofplots+1):
    x = np.random.randint(0,100,10)
    y = np.random.randint(0,100,10)
    plot(x,y,i,numberofplots)

rawDescription: How to use a python produce as many subplots of arbitrary size as necessary accommodate all data?

description: Use a python produce as many subplots of arbitrary size as necessary accommodate all data


rawDescription: Changing axis options for Polar Plots in Matplotlib/Python


code:
filename = 'test.txt'

filetxt = """\
X_0_Gui_Menu_400_Menu_System
X_0_Gui_Menu_400_Menu_System
X_0_Gui_Menu_000_Menu_root
X_0_Gui_Menu_000_Menu_root
X_0_Gui_Menu_000_Menu_root
X_0_Gui_Menu_300_Menu_Outputs
X_0_Gui_Menu_300_Menu_Outputs
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
X_0_Gui_Menu_320_Menu_Outputs_SDI
"""

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

from collections import Counter
with open(filename, 'r') as f:
    c = Counter(f)

# use iteritems() in python 2.7 instead of items
for key, value in c.items():
    print(key.strip())
    print('{:d} times'.format(value))

rawDescription: Counting number of times a group of string have occurred and print the string and number of occurrence in python 2.7


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

import wx
import wx.lib.sized_controls as sc

import matplotlib as mpl
mpl.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas

import numpy as np

class CanvasPanel(sc.SizedPanel):
    def __init__(self, parent):
        super(CanvasPanel, self).__init__(parent)
        self.figure = mpl.figure.Figure(figsize=(10, 8), dpi=75,
                                        facecolor='white', edgecolor='white')

        self.fake_depthplot()
        self.canvas = FigureCanvas(self, -1, self.figure)

        # these print statements give me a number like (1600, 1600)
        # however, when I use the wxpython inspector, it shows that the actual display size is MUCH smaller
        print(self.Size)
        print(self.canvas.Size)

    def fake_depthplot(self):
        main_plot = self.figure
        main_plot.add_axes([0, 0, 1, 1])

        x1 = np.linspace(0.0, 5.0)
        x2 = np.linspace(0.0, 2.0)

        y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
        y2 = np.cos(2 * np.pi * x2)

        plt = main_plot.add_subplot(4, 2, 1)
        plt.plot(x1, y1, 'ko-')
        plt.title.set_text('A tale of 2 subplots')
        plt.set_ylabel('Damped oscillation')

        plt = main_plot.add_subplot(2, 1, 2)
        plt.plot(x2, y2, 'r.-')
        plt.set_xlabel('time (s)')
        plt.set_ylabel('Undamped')

if __name__ == "__main__":
    app = wx.App()
    fr = sc.SizedFrame(None, title='test')
    print(fr.Size)
    pane = fr.GetContentsPane()
    panel = CanvasPanel(pane)
    fr.Fit()
    import sys
    if '-i' in sys.argv:
        import wx.lib.inspection
        wx.lib.inspection.InspectionTool().Show()
    fr.Show()
    app.MainLoop()

rawDescription: sizing problems embedding matplotlib figure in wxpython GUI

description: Sizing problems embedding matplotlib figure in wxpython GUI


code:
from StringIO import StringIO
c = StringIO(contents.replace(';', ''))
np.loadtxt(c, delimiter=",", dtype=structure)

rawDescription: Loading a string into numpy record array


code:
def output(level):
   level = raw_input("Enter a number from 0-4 (Press <Enter> to quit): ")
   while level != "":
        check_mark(level)
        level = raw_input("\nEnter a number from 0-4 (Press <Enter> to quit): ")

rawDescription: Integer and string conflicts

description: Integer and string conflicts


code:
np.eye(m.shape[0], dtype='bool')
m[~np.eye(m.shape[0], dtype='bool')]

rawDescription: NumPy: Return a flat matrix where if the row == col, ignore value


code:
# urls.py
(r"^([^/]*?(19|20)\d{2}[^/]*?)/?$", RemoveYearRedirect.as_view()),

# views.py
from django.views.generic.base import RedirectView
import re

class RemoveYearRedirect(RedirectView):
    query_string = True

    def get_redirect_url(self, **kwargs):
        """
        This has been overriden to remove any year from 1900 to 2099 from the URL
        """
        url = re.sub("(19|20)\d{2}", "", self.args[0])
        return "/" + re.sub("-+", "-", url).strip("-")

rawDescription: Dynamic redirecting pages in Django with regular expressions?


code:
df2 = df.groupby(['Col1', 'Value']).size().reset_index()
df2.columns = ['Col1', 'Value', 'Count']
df2

rawDescription: Rolling up data frame along with count of rows in python


code:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
from matplotlib import _tri, tri, cm

def contour_bands_3d(x, y, z, nbands=20):
    # obtain the contouring engine on a triangulation
    TRI = tri.Triangulation(x, y)
    C = _tri.TriContourGenerator(TRI.get_cpp_triangulation(), z)

    # define the band breaks
    brks = np.linspace(z.min(), z.max(), nbands+1)

    # the contour lines
    lines = [C.create_contour(b) for b in brks]

    # the contour bands
    bands = [C.create_filled_contour(brks[i], brks[i+1]) for i in xrange(nbands)]

    # compare the x, y vertices of each band with the x, y vertices of the upper
    # contour line; if matching, z = z1, otherwise z = z0 (see text for caveats)
    eps = 1e-6
    verts = []
    for i in xrange(nbands):
        b = bands[i][0]
        l = lines[i+1][0]
        z0, z1 = brks[i:i+2]
        zi = np.array([z1 if (np.abs(bb - l) < eps).all(1).any() else z0 for bb in b])
        verts.append(np.c_[b, zi[:,None]])
    return brks, verts

x = np.array([0, 0, 1, 1])
y = np.array([0.5, 0.75, 1, 0.5])
z = np.array([0, 0.5, 1,0])

fig = plt.figure()
ax = Axes3D(fig)
verts = [zip(x, y, z)]
PC = Poly3DCollection(verts)
ax.add_collection3d(PC)

# calculate the 3d contour bands
brks, verts = contour_bands_3d(x, -y, z)

cmap = cm.get_cmap('jet')
norm = plt.Normalize(vmax=abs(y).max(), vmin=-abs(y).max())

PC = Poly3DCollection(verts, cmap=cmap, norm=norm, edgecolors='none')
PC.set_array(brks[:-1])
ax.add_collection(PC)
ax.set_ylim((-1, 1))
plt.show()

rawDescription: Interpolating a 3D surface known by its corner nodes and coloring it with a colormap


code:
import time

def calc():
    print ("CALCULATOR")
    num1 = input("Number 1: ")
    num2 = input("Number 2: ")
    print ("Adding numbers...")
    answer = num1+num2
    print (answer)
    time.sleep(4)

def edit():
    print ("EDIT")

while True:
    print ("PyDOS VERSION 1.1")
    shell = input("> ")
    if shell == "calc":
        time.sleep(3)
        calc()

    elif shell == "edit":
        edit()

    elif shell == 'exit':
        break
    else:
        print('Wrong command')

rawDescription: How do I fix a if inside def loop?

description: Fix a if inside def loop


code:
Parent.objects.filter(
    child__isnull=False,
    child__timeStamp__gt=datetime.strptime(
        '2016-01-01 00.00.00',
        '%Y-%m-%d %H.%M.%S'
    )
)

rawDescription: How to get all objects of a Parent model of which foreign key exist in child model in Django?

description: Get all objects of a Parent model of which foreign key exist in child model in Django


rawDescription: Make FileChooserDialog allow user to select a folder/directory


code:
data_str = '''A    F
              G    H
              F    J
              Y    G
              H    G'''
data = [line.strip().split() for line in data_str.splitlines()]

list_ids = {}
next_id = 0
for a, b in data:
    if a in list_ids and b in list_ids:
        pass # do nothing if they both are already in a list
    elif a in list_ids:
        list_ids[b] = list_ids[a]
    elif b in list_ids:
        list_ids[a] = list_ids[b]
    else:
        list_ids[a] = list_ids[b] = next_id
        next_id += 1

for name, id in list_ids.items():
    print(name, id)

rawDescription: Python script to add items falling on the same line into named groups


code:
import subprocess
with open("ip.txt", "r") as file_in:
  fname = "scan.txt"
  with open("scan.txt","w") as file_out:
    for line in file_in:
      process = subprocess.Popen(["python", "sslyze.py", "--regular", line], stdout=subprocess.PIPE)
      file_out.write(process.communicate()) # you might need to append \n to whatever you write

rawDescription: Python command in python script from another python script


code:
class AnLinearAxis(AnAxis, LinearAxis):
    def move_linear(self, move_um):
        pass

    def __init__(self):
        # Do stuff...
        super().__init__()

rawDescription: Python constructors in ABC inheritance chain for interfaces


code:
import numpy as np

def random_with_nan_and_inf(shape, count):
    a = np.random.rand(*shape)
    idx = [np.random.randint(0, n, count) for n in shape]
    a[idx] = ([np.nan, np.inf] * count)[:count]
    return a

a = random_with_nan_and_inf((100, 3), 5)
b = random_with_nan_and_inf((100, 4), 10)
c = random_with_nan_and_inf((100, 5), 15)

mask = np.isfinite(a.sum(-1) + b.sum(-1) + c.sum(-1))
a2, b2, c2 = a[mask], b[mask], c[mask]

rawDescription: Python: Drop Rows With NaNs When Memory Constrained


code:
import inspect

def get_subclasses(mod, cls):
    """Yield the classes in module ``mod`` that inherit from ``cls``"""
    for name, obj in inspect.getmembers(mod):
        if hasattr(obj, "__bases__") and cls in obj.__bases__:
            yield obj

rawDescription: Iterate over subclasses of a given class in a given module


code:
def FunctionWrapper(object):
    def __init__(self, callable):
        self._callable = callable
    def __call__(self, *args, **kwargs):
        return self._callable(*args, **kwargs)
    def __repr__(self):
        return '<custom representation for {}>'.format(self._callable.__name__)

rawDescription: In Python 2.7, how do I override the string representation of a single function?