code:
#df is your dataframe
index = pd.date_range(df['time_stamp'])
values = pd.Series(df.values, index=index)

#Read above link about the different Offset Aliases, S=Seconds
resampled_values = values.resample('2.5S')

resampled_values.diff() #compute the difference between each point!

rawDescription: Time differentiation in Pandas

description: Time differentiation in Pandas


code:
lut = np.arange(10) * 10
img = np.random.randint(0,9,size=(3,3))
lut
img
lut[img]

rawDescription: Is there a convenient way to apply a lookup table to a large array in numpy?


code:
plt.ion()
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.scatter(xs, ys)
plt.plot(xs, thetas[0] + thetas[1] * xs, color='red')
fig.canvas.draw()

# Do your updates on thetas.
# ...
# Clear the current plot.
ax.clear()
# Plot your data again.
ax1.scatter(xs, ys)
plt.plot(xs, thetas[0] + thetas[1] * xs, color='red')
# Draw
fig.canvas.draw()

rawDescription: Update line in matplotlib plot in loop

description: Update line in matplotlib plot in loop


code:
import Tkinter as tk

def onvalidate(d,i,P,s,S,v,V,W):
    # only lowercase is valid
    valid = (P.lower() == P)
    # set red background if invalid
    newcolor = 'red' if not valid else default_color
    root.nametowidget(W).configure(background=newcolor)
    return valid

def oninvalid(d,i,P,s,S,v,V,W):
    #called if widget is invalid
    widget = root.nametowidget(W)
    # S is the character that *would* have been
    # inserted or deleted, but won't because it is invalid
    # So we do it ourselves
    if S:
        if d=='0':
            widget.delete(i, len(S))
        elif d=='1':
            widget.insert(i, S)
    # Changing the text clears the 'validate' value
    # so we have to reset it
    widget.after_idle(lambda W,v: root.nametowidget(W).configure(validate=v), W, v)

root = tk.Tk()

valhook = (root.register(onvalidate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
invhook = (root.register(oninvalid), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')

entry = tk.Entry(root, validate="key", validatecommand=valhook, invalidcommand=invhook)

default_color = entry.cget('background')

entry.pack()

root.mainloop()

rawDescription: Does Tkinter validation have to be heavy-handed?


code:
while guess_count < total_tries and word_list != template:
    #one guess per iteration
    guess=letter_guess()

    for i,v in enumerate(word_list):
        if guess == v:
   #adding 1 b/c I don't want a position 0.
            print("letter found at position",i+1)
            template[i]=v
    if guess not in word_list:
        print("letter not in word.\n")
    print(template)
    guess_count+=1

rawDescription: How to determine what should be a function

description: Determine what should be a function


code:
from __future__ import division

eval('14/15')

rawDescription: Python String Parsing Floats

description: Python String Parsing Floats


code:
#!/usr/bin/env python3

from tkinter import *
from tkinter.ttk import *

root = Tk()

text_var = StringVar()
entry = Entry(root, textvariable=text_var)
text_var.trace('w', lambda nm, idx, mode: print(text_var.get()))
entry.grid()

Button(text="Close", command=root.destroy).grid()

root.mainloop()

rawDescription: Why is Entry.get() one key behind?

description: Why is Entry.get() one key behind


code:
from collections import OrderedDict
o = OrderedDict.fromkeys(['hello', 'bye', 'tc', 'iam'], '')
repr(o)
OrderedDict([('hello', ''), ('bye', ''), ('tc', ''), ('iam', '')])

rawDescription: Python - Creating a dictionary using List


code:
Escape = Suppress(Literal("\\")) + Word("\\)]:", exact=1)
Text   = Combine(ZeroOrMore(Escape ^ Regex("[^\\]\\\\:]")))

rawDescription: Handling escapes in pyparsing

description: Handling escapes in pyparsing


code:
WeDoNotWantToDeriveThis.__setitem__ = types.MethodType(set_item_func, None, WeDoNotWantToDeriveThis)
inst[0] = None

rawDescription: Python patch item assignment

description: Python patch item assignment


code:
class CustomerNotification(BaseNotification):
    NEW_PROPOSAL = 1000
    # NEW_MESSAGE_ON_PROJECT = 1001
    # NEW_MESSAGE_ON_PROPOSAL = 1002
    CHOICES = ((NEW_PROPOSAL, "New Prpposal"),
               (BaseNotification.NEW_MESSAGE_ON_PROJECT,
                "New Message on Project"),
               (BaseNotification.NEW_MESSAGE_ON_PROPOSAL,
                "New Message on Proposal"))

rawDescription: How to access superclass properties here

description: Access superclass properties here


code:
import glob
file = open('./blah.html', 'w')
sample = "To create a new blog click post, go over to the left hand menu, and click posts. The posts page shows you all the blog posts that are currently on your web site. Whether they are drafts, like this one we just created, or actually published, like these. You want to sort them, you can come up here, only show published articles, only posts show sticky articles, only show drafts posts, or the trash. Let’s go click back to all."
topics = ['posts','click','blog']
words = sample.split(" ")
i = 0
index_set = set()
for i in range(len(words)):
	if words[i] in topics:
		index_set.add(i)
		if i > 0 :
			index_set.add(i-1)
		if i < len(words):
			index_set.add(i+1)

for i in range(len(words)):
	if i in index_set:
		file.write("""<span style='color: red'>"""+words[i]+""" </span>""")
	else:
		file.write(words[i]+" ")

file.close()

rawDescription: Change the color of some part of the text


rawDescription: Create a gray scale colormap with colorbar on Python


rawDescription: How can I generate a Toeplitz matrix in the correct form for performing discrete convolution?

description: Generate a Toeplitz matrix in the correct form for performing discrete convolution


code:
def createWidgets(self):
    self.value1 = tk.IntVar()
    self.scaleFirstN = tk.Scale(self, from_=0, to=100,tickinterval=10,orient=tk.HORIZONTAL, command=self.onScale, var=self.value1)
    self.scaleFirstN.grid(row=0,column=0,columnspan=5,ipadx=100,padx=40,pady=10,sticky="n")
    self.value2 = tk.IntVar()
    self.scaleSecondN = tk.Scale(self, from_=0, to=100,tickinterval=10, orient=tk.HORIZONTAL, command=self.onScale, var=self.value2)
    self.scaleSecondN.grid(row=1,column=0,columnspan=5,ipadx=100,padx=40,pady=0,sticky="n")
    self.label1 = tk.Label(self,textvariable=self.value1, text=0,foreground="blue")
    self.label1.grid(row=5,column=0,columnspan=5, ipadx=5, sticky="wes")
    self.label2 = tk.Label(self,textvariable=self.value2, text=0,foreground="blue")
    self.label2.grid(row=6,column=0,columnspan=5, ipadx=5, sticky="we")
    self.label3 = tk.Label(self, text=0,foreground="blue")
    self.label3.grid(row=7,column=0,columnspan=5, ipadx=5, sticky="we")

def onScale(self, val):
    self.label3.config(text=self.value1.get() * self.value2.get())

rawDescription: Creating a dynamic multiplication application using scales


code:
import dis
def f1(): return list()

def f2(): return []

dis.dis(f1)
dis.dis(f2)

rawDescription: What's the difference between list() and []


code:
try:
    self._connection.close()
except AttributeError:
    pass
self._connection = psycopg2.connect(connection_string)
return self._connection

rawDescription: Initialising Python properties

description: Initialising Python properties


code:
my_dict = dict((i, i) for i in range(30))
pp.pformat(my_dict)
print(pp.pformat(my_dict))

rawDescription: Python PrettyPrint output to variable

description: Python PrettyPrint output to variable


code:
import collections

channels = {
'24': {'type': 'plain', 'table_name': 'channel.items.AuctionChannel'},
'26': {'type': 'plain', 'table_name': 'channel.gm.DeleteAvatarChannel'},
'27': {'type': 'plain', 'table_name': 'channel.gm.AvatarMoneyChannel'},
'20': {'type': 'plain', 'table_name': 'channel.gm.AvatarMoneyAssertChannel'},
'21': {'type': 'plain', 'table_name': 'channel.gm.AvatarKillMobComplexChannel'},
'22': {'type': 'plain', 'table_name': 'channel.gm.DistributionMarkChannel'},
'23': {'type': 'plain', 'table_name': 'channel.gm.MailChannel'}
}

channels = collection.OrderedDict(sorted(channels.items(), key=lambda item: item[0]))
for key,value in channels.items():
    print(key, ':', value)

rawDescription: How to sort dict of dicts by keys?

description: Sort dict of dicts by keys


code:
def createtxt(number):
    filename = "test" + str(number) + ".txt"
    open(filename, "w")
    print(number)

def createtxt_Launch():
    global txtfile_number
    createtxt(txtfile_number)
    txtfile_number += 1

rawDescription: Variable keeps getting set to 1

description: Variable keeps getting set to 1


code:
def insert_grid(subj, obj, cords=(0, 0)):
    u, v = cords
    w = len(subj[0])
    for index, row in enumerate(subj, u):
        obj[index][v:v+w] = row

rawDescription: Python: inserting a 2D list inside another replacing content


code:
def checkForWord():
    r = requests.get("http://example.com/somepage.html")
    return "myWord" in r.text

rawDescription: Find word in HTML page fast algorithm

description: Find word in HTML page fast algorithm


code:
name = []
name.append(myClass())
name.append(myClass())

rawDescription: Creating an unbounded number of objects in Python 2.7.3


code:
import constants

for name, value in new_config.iteritems():
    setattr(constants, name, value)

rawDescription: Monkeypatching hardcoded global configuration loaded from a .py file


code:
class Foo(object):
    def __init__(self):
        self._bar = []
        self._qnx = 10
        self._locked= False

    @property
    def locked(self):
        return self._locked

    def lock(self):
        self._locked = True

    @property
    def bar(self):
        if self.locked:
            return tuple(self._bar)
        return self._bar

    @property
    def qnx(self):
        return self._qnx
    @qnx.setter
    def qnx(self,val):
        if self.locked:
            raise AttributeError
        self._qnx = val

def lock(obj):
    obj.lock()

rawDescription: Lock mutable objects as immutable in python


code:
import tkinter as Tk

root = Tk.Tk()
canvas = Tk.Canvas(root)
background_image=Tk.PhotoImage(file="map.png")
canvas.pack(fill=Tk.BOTH, expand=1) # Stretch canvas to root window size.
image = canvas.create_image(0, 0, anchor=Tk.NW, image=background_image)
line = canvas.create_line(10, 10, 100, 35, fill="red")
root.wm_geometry("794x370")
root.title('Map')
root.mainloop()

rawDescription: Draw line on image in tkinter

description: Draw line on image in tkinter


code:
locations_ids = [location.id for location in Locations.objects.all()[:5]]
all_ratings = Rating.objects.filter(location__id__in=locations_ids)

rawDescription: django - object filter logic

description: Django - object filter logic


code:
# setup
x, y = 999, 999
array = np.arange(x * y)
array.shape = x, y
little_array_size = 3

# creates an array of "little arrays"
patch = np.empty(array.size, dtype=int)
patch.shape = -1, little_array_size, little_array_size

i = 0
for n in range(0, array.shape[0], little_array_size):
    for m in range(0, array.shape[1], little_array_size):
        # uses view, so data is copied straight from array to patch
        patch[i,:] = array[n:n+little_array_size, m:m+little_array_size]
        i += 1

patch.shape = -1 # flattens array

rawDescription: python numpy arrays. How to slice multiple arrays in an efficient way?

description: Python numpy arrays. How to slice multiple arrays in an efficient way


code:
import random
import string

from django.http import HttpResponse

def draegg_view(request):
    size = 40
    chars = string.ascii_letters + string.digits + string.punctuation
    result = ''.join(random.choice(chars) for _ in range(size))
    return HttpResponse(result)

rawDescription: Print a random string generated

description: Print a random string generated


code:
import base64
base64.b64decode('AME=').decode('UTF-16')
base64.b64decode('AME=').decode('UTF-16LE')
base64.b64decode('AME=').decode('UTF-16BE')

rawDescription: python base64 string decoding

description: Python base64 string decoding


code:
import os

os.system("cls")

rawDescription: Clearing screen in Python (when using Pythonwin)


code:
while True:
    again = input('Go? (y/n): ')
    if again != 'y':
        break

    # The entirety of the rest of your program would go here.

rawDescription: How do I loop this code?

description: Loop this code


code:
import tkinter
import tkinter.messagebox
import time
import random
import _thread

class Menu:

    def __init__(self):

        self.main_window = tkinter.Tk()
        self.main_window.title("Room Light System")
        self.main_window.geometry("1200x600")

        #Frames
        self.frame_2 = tkinter.Frame(self.main_window, bg='Orange') # Receiving DATAs

        #ReceiveLabel
        self.ReceiveLabel = tkinter.Label(self.frame_2,\
                                       text = 'Received DATAs',\
                                       bg = 'White',\
                                       height = 2, width = 20)

        #Temperature
        self.GetTempLabel = tkinter.Label(self.frame_2,\
                                       text='Temperature :')
        self.TempValue = tkinter.StringVar()

        self.GetTempValueLabel = tkinter.Label(self.frame_2,bg = 'Green',\
                                               textvariable = self.TempValue
                                               )

        #PACKING!!! F2

        self.frame_2.pack()
        self.frame_2.place(x=410, y=0, height=300, width=400)
        #ReceiveLabel
        self.ReceiveLabel.pack()
        self.ReceiveLabel.place(x=100, y=10)
        #Temperature
        self.GetTempLabel.pack()
        self.GetTempLabel.place(x=50, y=80, height=20, width=120)
        self.GetTempValueLabel.pack()
        self.GetTempValueLabel.place(x=200, y=80, height=20, width=50)

        #main loop and quit
        self.quitButton = tkinter.Button(self.main_window,\
                                          text = 'Quit',
                                          command = self.main_window.destroy,\
                                          height = 2, width = 6)
        self.quitButton.pack()

        self.quitButton.place(x=200, y=500)

        self.main_window.after(2000, _thread.start_new_thread, self.GetTemp, ())
        tkinter.mainloop()

    def GetTemp(self):

        while(1):
            value = random.random()
            self.TempValue.set(str(value))
            time.sleep(0.5)

gui = Menu()

rawDescription: update tkinter label from serial data whenever there's new data from serial port python 3.x

description: Update tkinter label from serial data whenever there's new data from serial port python 3.x


code:
# code snippet for the usage
""" a short example of how to use this module """
test_cases = []
for i in range(0, 5):
    type_c = ""
    if i % 2 == 0:
        type_c = "failure"
    test_cases.append(TestCase(i, str(i) + "contents", type_c) )

junit_xml = JunitXml("demo test example", test_cases)

rawDescription: Python script to generate JUnit report from another testing result


code:
fg.transform(resize='300x') #resize 'fg' to a width of 300px
                            #and height is set dynamically,
                            #respecting the original aspect ratio

rawDescription: Place image on another image with aspect fill


code:
t_one = threading.Thread(target=self.queue_sort)      # note, fewer parentheses
t_one.start()
t_two = threading.Thread(target=self.priorityQueue_sort)      # here too
t_two.start()
t_three = threading.Thread(target=self.priorityMultiProcess_launch)     # and here
t_three.start()

rawDescription: Multiple Threads not initializing

description: Multiple Threads not initializing


code:
import sys
from PyQt4.QtGui import QPixmap, QApplication

app = QApplication(sys.argv)
QPixmap.grabWindow(QApplication.desktop().winId()).save('screenshot.jpg', 'jpg')

rawDescription: How to grab a desktop screenshot with PyQt?

description: Grab a desktop screenshot with PyQt


code:
from datetime import datetime

def days_between(d1, d2):
    d1 = datetime.strptime(d1, "%Y-%m-%d")
    d2 = datetime.strptime(d2, "%Y-%m-%d")
    return abs((d2 - d1).days)

rawDescription: Difference between two dates?

description: Difference between two dates


code:
import os

def main():
    name = 'log.txt'
    tmpName = 'tmp.txt'
    f = open(name, 'r')
    tmp = open(tmpName, 'w')

    titleLine = f.readline().strip()
    tmp.write(titleLine+'\n')

    prevLine = f.readline().strip()
    tmp.write(prevLine+'\n')
    prevLine = prevLine.split('\t')

    for line in f:
        line = line.split('\t')
        line[2] = str(int(line[1]) - int(prevLine[1]))
        line[4] = str(int(line[3]) - int(prevLine[3]))
        prevLine = line

        displayLine=''
        for i in range(len(line)-1):
            displayLine += line[i]+'\t'
        displayLine += line[len(line)-1]

        tmp.write(displayLine+'\n')

    f.close()
    tmp.close()
    os.remove(name)
    os.rename(tmpName, name)

main()

rawDescription: Difference Between Rows and fill Columns


code:
index_dict = dict((value, idx) for idx,value in enumerate(a))
[index_dict[x] for x in b]

rawDescription: list match in python: get indices of a sub-list in a larger list

description: List match in python: get indices of a sub-list in a larger list


code:
for root, dirs, files in os.walk(path):
    for skip in ('.hg', '.git', '.svn', '.bzr'):
        if skip in dirs:
            dirs.remove(skip)
        # Now process other stuff at this level, i.e.
        # in directory "root". The skipped folders
        # won't be recursed into.

rawDescription: benchmarks: does python have a faster way of walking a network folder?

description: Benchmarks: does python have a faster way of walking a network folder


rawDescription: Find if a number exists between a range of numbers specified by a list


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

img = np.random.randn(300,300)
myplot = plt.imshow(img)

def fmt(x, pos):
    a, b = '{:.2e}'.format(x).split('e')
    b = int(b)
    return r'${} \times 10^{{{}}}$'.format(a, b)

plt.colorbar(myplot, format=ticker.FuncFormatter(fmt))
plt.show()

rawDescription: Scientific notation colorbar in matplotlib


code:
from numpy import linspace, prod
from itertools import combinations

arr = np.array([1,2,3,4])

[sum([prod(x) for x in combinations(arr,int(i))]) for i in linspace(1,len(arr), len(arr))]
[10, 35, 50, 24]

rawDescription: How to get sum of products of all combinations in an array in Python?

description: Get sum of products of all combinations in an array in Python


code:
# default scale is 1 in your original case, scales with other cases:
widthscale = len(yvalues)/4
figsize = (8*widthscale,6) # fig size in inches (width,height)
figure = pylab.figure(figsize = figsize) # set the figsize

rawDescription: increasing width of figure in matplotlib according to number of x values

description: Increasing width of figure in matplotlib according to number of x values


code:
import pandas as pd

# Create a random time series with values over 100 days
# starting from 1st March.
N = 100
dates = pd.date_range(start='2015-03-01', periods=N, freq='D')
ts = pd.DataFrame({'date': dates,
                   'values': np.random.randn(N)}).set_index('date')

# Create the plot and adjust x/y limits. The new x-axis
# ranges from mid-February till 1st July.
ax = ts.plot()
ax.set_xlim(pd.Timestamp('2015-02-15'), pd.Timestamp('2015-07-01'))
ax.set_ylim(-5, 5)

rawDescription: python pandas timeseries plots, how to set xlim and xticks outside ts.plot()?

description: Python pandas timeseries plots, how to set xlim and xticks outside ts.plot()


rawDescription: Python reverse-stride slicing

description: Python reverse-stride slicing


code: d = OrderedDict(sorted(saving.items(), key=lambda t: t[1][2]))

rawDescription: Sorting a dict in python

description: Sorting a dict in python


code:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('0.0.0.0', 0))
print('listening on port:', sock.getsockname()[1])

rawDescription: Sockets Programming with Python: Get the port of a server


code:
k = np.random.randint(n, size = (2,4))
out = colors[k]
out
out.shape
all((out[i]==colors[c]).all() for i,c in np.ndenumerate(k))

rawDescription: Numpy: vectorized operations to create a 3D array


code:
import sqlite3

db = sqlite3.connect('test.db')
db.row_factory = sqlite3.Row
cur = db.cursor() # getting a cursor

cur.execute('drop table if exists test')
cur.execute('create table test (t1 text,i1 text)')
db.commit() # commit the transaction, note commits are done
            # at the connection, not on the cursor

cur.execute('insert into test (t1, i1) values (?, ?)',('xyzs','51'))
db.commit()

cursor = cur.execute('select * from test')

for row in cursor:
    print(row['t1'],row['i1'])

rawDescription: Why doesn't the record get saved in sqlite3?


code:
import os
name = os.path.basename(file.name)

rawDescription: tkinter - retrieve file name during askopenfile

description: Tkinter - retrieve file name during askopenfile


rawDescription: get td which contains specific texts and then find its parents and siblings

description: Get td which contains specific texts and then find its parents and siblings


code:
png = wx.Image(imageFile, wx.BITMAP_TYPE_ANY).ConvertToBitmap()
wx.StaticBitmap(self, -1, png, (10, 5), (png.GetWidth(), png.GetHeight()))

rawDescription: Showing a .png image in a window in wxPython


rawDescription: Create only ONE table with Flask + SqlAlchemy


code:
#!/usr/bin/python

from scrapy.cmdline import execute
execute()

rawDescription: How to use PyCharm to debug Scrapy projects

description: Use PyCharm to debug Scrapy projects


code:
pile1_str = "pile 1: "
x="O"
y=1
while y <= pile1:
    pile1_str = pile1_str + x
    if y%1==0:
        pile1_str = pile1_str + " "
    print(pile1_str)
    y= y+1

rawDescription: How to add a space between a string for every 5th letter?

description: Add a space between a string for every 5th letter


code:
with open(file1) as f1,open(file2) as f2,open("combined_data.txt","w") as fout:
     for t in zip(f1,f2):
         fout.write('\t'.join(x.strip() for x in t)+'\n')

rawDescription: Take lines from two files, output into same line- python


code: _myRe = re.compile("\[\d+: \d+\] \* \$ Total Time To Complete \d+ Jobs: \d+\.\d+ \[Sec\]")

rawDescription: regex for float python is not working

description: Regex for float python is not working


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

a = 0.5

# Get the colormap colors, multiply them with the factor "a", and create new colormap
my_cmap = plt.cm.RdBu(np.arange(plt.cm.RdBu.N))
my_cmap[:,0:3] *= a
my_cmap = ListedColormap(my_cmap)

np.random.seed(1)
data =  np.sort(np.random.rand(8,12))
plt.figure()
plt.subplot(121)
c = plt.pcolor(data, edgecolors='k', linewidths=4, cmap='RdBu', vmin=0.0, vmax=1.0)
plt.colorbar(c)
plt.subplot(122)
c = plt.pcolor(data, edgecolors='k', linewidths=4, cmap=my_cmap, vmin=0.0, vmax=1.0)
plt.colorbar(c)
plt.show()

rawDescription: How can I change the intensity of a colormap in matplotlib?

description: Change the intensity of a colormap in matplotlib


code:
import facebook
fb = facebook.Facebook('YOUR_API_KEY', 'YOUR_SECRET_KEY')
fb.auth.createToken()
fb.login()
fb.auth.getSession()
fb.set_status('Checking out StackOverFlow.com')

rawDescription: Update Facebooks Status using Python

description: Update Facebooks Status using Python


code:
class Cheat(Base):

  __tablename__ = 'cheats'

  id = Column(Integer, primary_key = True, autoincrement = True)
  cheat = deferred(Column(Text))
  name = Column(String(255), index = True)
  _html = Column('html', Text)
  _slug = deferred(Column('slug', String(255)))

rawDescription: SQLAlchemy declarative. Specify columns to select


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

import itertools
import operator
import datetime

data = [{u'timestamp': datetime.datetime(2016, 5, 25, 23, 55, 33), u'sensor': u'GP_PRES', u'value': u'96587'},
        {u'timestamp': datetime.datetime(2016, 5, 25, 23, 56, 33), u'sensor': u'GP_NO2', u'value': u'0.221'},
        {u'timestamp': datetime.datetime(2016, 5, 25, 23, 56, 33), u'sensor': u'GP_TC', u'value': u'14.600'},
        {u'timestamp': datetime.datetime(2016, 5, 25, 23, 56, 33), u'sensor': u'GP_HUM', u'value': u'83.94'}]

groups = list()
data2 = sorted(data, key=lambda d:d['timestamp'])
for k, g in itertools.groupby(data2, key=lambda d:d['timestamp']):
    groups.append(list(g))

print(groups)   # 2 groups
[[  {u'timestamp': datetime.datetime(2016, 5, 25, 23, 55, 33), u'sensor': u'GP_PRES', u'value': u'96587'}],
 [  {u'timestamp': datetime.datetime(2016, 5, 25, 23, 56, 33), u'sensor': u'GP_NO2', u'value': u'0.221'},
    {u'timestamp': datetime.datetime(2016, 5, 25, 23, 56, 33), u'sensor': u'GP_TC', u'value': u'14.600'},
    {u'timestamp': datetime.datetime(2016, 5, 25, 23, 56, 33), u'sensor': u'GP_HUM', u'value': u'83.94'}]]

rawDescription: Group a List of Tuples by an identical tuple (timestamp) with pyhton itertools


code:
def foo(): pass

type(foo)
type(type)
isinstance(type(foo), type)

rawDescription: Is `type` really a function, or not?

description: Is `type` really a function, or not


code:
class NewBaseModel(models.Model):
    user = models.ForeignKey(User)
    another_field = models.CharField(max_length=1000)

    class Meta:
        abstract = True

rawDescription: Using Django South to move from concrete inheritance to abstract inheritance


code:
attr = 'bar'
getattr(foo, attr)  # <=> foo.bar

rawDescription: How can I dynamically get the value of a class variable?

description: Dynamically get the value of a class variable


code:
class Album(models.Model):
    name = models.CharField(max_length=100)
    artist = models.CharField(max_length=100)
    year = models.CharField(max_length=4)
    origin = models.CharField(max_length=50)

    def __str__(self):
         return "%s (by %s)" % (self.name, self.artist)

rawDescription: Django Rest Framework, Relations POST option name


code:
import HTMLParser
parser = HTMLParser.HTMLParser()
unescaped_string = parser.unescape(html_escaped_string)

rawDescription: Trouble Converting Apostrophes in JSON response


code:
from urllib.robotparser import RobotFileParser
import urllib.request

class TimoutRobotFileParser(RobotFileParser):
    def __init__(self, url='', timeout=60):
        super().__init__(url)
        self.timeout = 60

    def read(self):
        """Reads the robots.txt URL and feeds it to the parser."""
        try:
            f = urllib.request.urlopen(self.url, timeout=self.timeout)
        except urllib.error.HTTPError as err:
            if err.code in (401, 403):
                self.disallow_all = True
            elif err.code >= 400:
                self.allow_all = True
        else:
            raw = f.read()
            self.parse(raw.decode("utf-8").splitlines())

rawDescription: Python Robotparser Timeout equivalent

description: Python Robotparser Timeout equivalent


code:
element_to_select = soup.find("p", text="element_to_select")
if element_to_select is not None:
    next_element = element_to_select.find_next_sibling("p")
    print(next_element.get_text())

rawDescription: How to select item in an unordered list during crawling?

description: Select item in an unordered list during crawling


code:
import re
aa = "QDDDDQDTDQTD"
bb = "QDT"
cc = "TDQDQQDTQDQ"
print(*(re.findall(r'Q[^T]*[DQ]', st) for st in (aa,bb,cc)), sep='\n')

rawDescription: Python re.search Patterns

description: Python re.search Patterns


code:
class Agent:
    def __init__(self, world):
        self.location = None
        self.world = world

    def move(self, new_location):
        if self.location is not None:
            self.location.agent = None
        new_location.agent = self
        self.location = new_location

    def update(self):
        for new_location in self.world.locations:
            if self.location_is_good(new_location):
                self.move(new_location)

    def location_is_good(self, location):
        if location.agent is not None:
            return False

class Location:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.agent = None

rawDescription: Which class should store the lookup table?


code:
class Game(object):
    def __init__(self, start):
        self.start = start

rawDescription: Python: must __init__(self, foo) always be followed by self.foo = foo?


code:
List = [68, -99,"abc", -8,100, [-92, 89, 81, 96]]

result = []
def flatten(my_list):
    for i in my_list:
        if isinstance(i, list):
            return flatten(i)
        else:
            result.append(i)
    return result

print(flatten(List))

rawDescription: How do i return a flatten list from my recusive function in python?

description: Return a flatten list from my recusive function in python


code:
url=""         #URL to use
replace=""  #string to replace original with
if "resize=" in url:
    for i in range(len(url)):
        try:
            int(url[-1:])
        except Exception:
            break
        else:
            url=url[:-1]
    url+=str(replace)
elif [e for e in range(len(url)) if url[e:][:(e+10)].replace("/","").isalpha()==False]:
    for e in range(len(url)):
        if url[:(e+10)][e:].replace("/","").isdigit()==True:
            if url[e:][:1]!="/":
                url=url[:e]+replace+url[(e+10):]
                url=url.replace("newfolder","oldfolder")
                break
else:
    url1=url.split("/")
    url1[len(url1)-2]=replace
    url=""
    for i in url1:
        url+=i+"/"
print(url)

rawDescription: Changing out one or more pieces of a url in Python 3


rawDescription: Adding errorbars to 3D plot in matplotlib


code:
from math import ceil, log10
int(pow(10, ceil(log10(abs(x or 0.1)))))

rawDescription: How can I improve this code?

description: Improve this code


rawDescription: Finding recurring patterns in a string

description: Finding recurring patterns in a string


rawDescription: Selecting Randomly within an Array

description: Selecting Randomly within an Array


rawDescription: tkinter: How do I fix my window so that the window doesn't resize when my content resizes?

description: Tkinter: How do I fix my window so that the window doesn't resize when my content resizes


code:
import re
pattern = re.compile('(#[\da-fA-F]{3})')
l = pattern.findall(output)
dict(zip(('red', 'green', 'blue'), l))

rawDescription: Generate values for str.format style template strings from formatted output


code:
def load(timestr):
    hours,minutes,seconds = timestr.split(":")
    return datetime.time(hours,minutes,seconds)

rawDescription: MySQL data type for movie times

description: MySQL data type for movie times


code:
args = ("path\to\application.exe", "--version")
subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()[0]

rawDescription: How to read output from subprocess without printing to terminal?

description: Read output from subprocess without printing to terminal


code:
def swap(lst):
    firstpart=lst[:lst.index("car")]
    secondpart=lst[lst.index("bob")+1:]
    middlepart=lst[lst.index("car"):lst.index("bob")+1]
    return firstpart + middlepart + secondpart

rawDescription: swaping sublists of a list in python

description: Swaping sublists of a list in python


code:
with open("input.txt") as f:
    for s in f:
        print(s.split(",")[1])

rawDescription: Python String Manipulation

description: Python String Manipulation


rawDescription: Converging Pandas Dataframe so that a column only has one value but its other column values are summed up


code:
class Child(Parent):
    foobar = Parent.foobar + ['world']

rawDescription: Inherited class variable modification in Python


code:
import urllib.request
import urllib
import shutil
import os
import os.path
import sys
import time
import threading

class downloadFile:

    def __init__(self, downloadLink, downloadPath, onDiskName):
        self.downloadSize = urllib.request.urlopen(downloadLink).length
        self.downloadLink = downloadLink
        self.downloadPath = downloadPath
        self.onDiskName = onDiskName
        self.hardPath = os.path.join(self.downloadPath, self.onDiskName)

    def returnMode(self, returnMode = 'stats'):
        if returnMode == 'stats':
            return [self.downloadLink, self.downloadPath, self.onDiskName, self.downloadSize]
        elif returnMode == 'printedStats':
            print('self.downloadLink = ' + self.downloadLink)
            print('self.downloadPath = ' + self.downloadPath)
            print('self.onDiskName = ' + self.onDiskName)
            print('self.downloadSize = ' + self.downloadSize)
            print('self.hardPath = ' + self.hardPath)
            return [self.downloadLink, self.downloadPath, self.onDiskName, self.downloadSize, self.hardPath]

    def executeDownload(self):
        self.downloadStart = time.strftime("[%H:%M:%S] ")
        with urllib.request.urlopen(self.downloadLink) as response, open(self.hardPath, 'wb') as currentFile:
            shutil.copyfileobj(response, currentFile)
        currentFile.close()
        self.downloadEnd = time.strftime("[%H:%M:%S] ")

    def downloadStats(self):
        currentFileSize = os.path.getsize(self.hardPath)
        percentManifested = int(currentFileSize/(self.downloadSize/100))
        return [currentFileSize, percentManifested]

    def liveDownloadStats(self):
        if os.path.isfile(self.hardPath) == False:
            time.sleep(1)
        statList = self.downloadStats()
        while statList[0] < self.downloadSize:
            sys.stdout.write("\r" + self.downloadStart + " Downloading {0}... ".format(self.onDiskName) + "[{0}%]".format(statList[1]))
            sys.stdout.flush()
            statList = self.downloadStats() #This is the extra line of code used to update the variable before comparing on the next while loop.
        sys.stdout.write("\r" + self.downloadStart + " Downloading {0}... ".format(self.onDiskName) + "[{0}%]".format(statList[1]))
        sys.stdout.write("\n")

def Main():
    server = downloadFile("https://s3.amazonaws.com/Minecraft.Download/versions/1.8/minecraft_server.1.8.jar", "C:/Users/my-username/Desktop/", "minecraftServer.jar")
    t1 = threading.Thread(target=server.executeDownload, args=())
    t2 = threading.Thread(target=server.liveDownloadStats, args=())
    t1.start()
    t2.start()

if __name__ == "__main__":
    Main()

rawDescription: Python: Threading is not functioning when starting class methods


code: k, v = next(d.items())

rawDescription: non-destructive version of pop() for a dictionary

description: Non-destructive version of pop() for a dictionary


code:
mu = MatrixSymbol('mu', n, 1)
Sigma = MatrixSymbol('Sigma', n, n)

X = Normal('X', mu, sigma)  # A multivariate normal distribution

rawDescription: Defining a set of random numbers

description: Defining a set of random numbers


code:
import requests

r = requests.post('http://www.about.com')

for cookie in r.cookies:
    print(cookie.__dict__)
    print(cookie.secure)

rawDescription: How do I reach cookie information in python requests?

description: Reach cookie information in python requests


code:
from scrapy import Item
from scrapy.contrib.spiders import CrawlSpider, Rule

from foo.items import AtlanticFirearmsItem
from scrapy.contrib.loader import ItemLoader
from scrapy.contrib.linkextractors import LinkExtractor

import json

class AtlanticFirearmsSpider(CrawlSpider):
    name = "atlantic_firearms"
    allowed_domains = ["atlanticfirearms.com"]

    def __init__(self, start_urls=None, *args, **kwargs):
        if start_urls:
            self.start_urls = json.loads(start_urls)
            self.rules = []
            self.parse = self.parse_response
        else:
            self.start_urls = ["http://www.atlanticfirearms.com/"]
            self.rules = [
                Rule(LinkExtractor(allow=['detail.html']), callback='parse_response'),
                Rule(LinkExtractor(allow=[], deny=['/bro', '/news', '/howtobuy', '/component/search', 'askquestion']))
            ]

        super(AtlanticFirearmsSpider, self).__init__(*args, **kwargs)

    def parse_response(self, response):
        l = ItemLoader(item=AtlanticFirearmsItem(), response=response)
        product = l.load_item()
        return product

rawDescription: How can I reuse the parse method of my scrapy Spider-based spider in an inheriting CrawlSpider?

description: Reuse the parse method of my scrapy Spider-based spider in an inheriting CrawlSpider


rawDescription: Filter Query if FileField contains data

description: Filter Query if FileField contains data


code: self.assertEqual(selenium.GetEval("this.browserbot.getUserWindow().functionUnderTest().isNaN();"),"false","There was a NaN detected")

rawDescription: Javascript communication with Selenium (RC)


code: all = __builtins__.all

rawDescription: re-import aliased/shadowed python built-in methods

description: Re-import aliased/shadowed python built-in methods


code:
from crontab import CronTab
monday_morning = CronTab("0 8 * * 1")

def do_something():
    reactor.callLater(monday_morning.next(), do_something)
    # do whatever you want!

reactor.callLater(monday_morning.next(), do_something)
reactor.run()

rawDescription: simulate crontab with twisted deferred and looping calls

description: Simulate crontab with twisted deferred and looping calls


code:
myList = []
for line in myOpenFileObj:
    myList.append(line)

rawDescription: wxpython for each loop from textctrl split by newline

description: Wxpython for each loop from textctrl split by newline


code:
class testFoo(unittest.TestCase):
    def _doTest(self, foo):
         foo.do_something()
         # ...

    def testFoorHorse(self):
        foo = fooHorse.foo()
        self._doTest(foo)
    # and so on.

rawDescription: How to run python unittests for multiple implementations in one go

description: Run python unittests for multiple implementations in one go


code:
import csv, itertools
with open('file.csv', 'wb') as f:
    writer = csv.writer(f, delimiter="\t")
    writer.writerows(list(itertools.chain(*t)) for t in results)

rawDescription: write list of tuples of lists to text file

description: Write list of tuples of lists to text file


rawDescription: separating a list into two lists

description: Separating a list into two lists


code:
def my_func(a, b):
    pass

my_func(1, 2)
my_func(b=2, a=1)

# Both of them get the same results

rawDescription: Regarding Function in Python

description: Regarding Function in Python


code:
for groupID, data in d.groupby(level='id'):
    fig = pyplot.figure()
    ax = fig.gca()
    ax.plot(data.values.ravel())
    ax.set_xticks(np.arange(len(data))*24)
    ax.set_xticklabels(data.index.get_level_values('date'))

rawDescription: Plotting an awkward pandas multi index dataframe


code:
with open('file.txt', 'r') as handle:
    matrix = [map(int, line.strip()) for line in handle]

rawDescription: More efficient way to parse a matrix in python?


code:
def returnSeq(self, numRows):
    i = 0
    items = [0, 1, 2, 3, 2, 1]
    n_items = len(items)
    while True:
        yield items[i]
        i = (i + 1) % n_items

rawDescription: Using generator to cycle through numbers in a list


code:
Foo()
Foo.__new__(Foo)

rawDescription: Preventing invoking C types from Python

description: Preventing invoking C types from Python


code:
import pprint
import sys

RANGE = range(0, 101)
GRADE = {70: 'First', 60: 'Second Upper',
         50: 'Second Lower', 45: 'Third',
         40: 'Pass', 0: 'Fail'}
MARKS = -1, 0, 1, 49, 60, 71, 100, 101

def main():
    """Grade hardcoded marks and grade marks entered by the user."""
    # debug('MARKS')
    grade_all(MARKS)
    grade_all(get_marks())
    print('Goodbye!')

def grade_all(marks):
    """Take an iterable of marks and grade each one individually."""
    for mark in marks:
        # debug('mark')
        if mark in RANGE:
            print(mark, 'gets a grade of', grade_one(mark))
        else:
            print(mark, 'is not a valid mark')

def grade_one(mark):
    """Find the correct grade for a mark while checking for errors."""
    # debug('RANGE')
    if mark in RANGE:
        for score, grade in sorted(GRADE.items(), reverse=True):
            if mark >= score:
                return grade
    raise ValueError(mark)

def get_marks():
    """Create a generator yielding marks until the user is finished."""
    while True:
        try:
            text = input('Mark: ')
        except EOFError:
            sys.exit()
        else:
            # debug('text')
            if text.upper() == 'Q':
                break
            try:
                mark = round(float(text))
            except ValueError:
                print('Please enter a mark')
            else:
                # debug('mark')
                if mark in RANGE:
                    yield mark
                else:
                    print('Marks must be in', RANGE)

def debug(name):
    """Take the name of a variable and report its current status."""
    frame, (head, *tail) = sys._getframe(1), name.split('.')
    for scope, space in ('local', frame.f_locals), ('global', frame.f_globals):
        if head in space:
            value = space[head]
            break
    else:
        raise NameError('name {!r} is not defined'.format(head))
    for attr in tail:
        value = getattr(value, attr)
    print('{} {} {} = {}'.format(
        scope, type(value).__name__, name, pprint.pformat(value)), flush=True)

if __name__ == '__main__':
    main()

rawDescription: Issues with a college assignment using Python


code:
import os

PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))

DATABASE = os.path.join(PROJECT_ROOT, 'tmp', 'test.db')

rawDescription: Flask OperationalError: unable to open database file using sqlite3


code:
import time
...
...
def wait_for_complete_page_load(browser, total_wait=100):
    try:
        elem = browser.find_element_by_xpath('//div[contains(@style, "opacity: 0")]')
    except:
        total_wait -= 1
        time.sleep(2)
        if total_wait > 1: wait_till_page_loaded(browser, total_wait)

rawDescription: Selenium+python: Waiting on changes in style


code:
from main import settings
from logger import Logger

log=Logger(settings['log_level'])

rawDescription: Custom logging class python scope

description: Custom logging class python scope


code:
import matplotlib
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

matplotlib.use('Agg')
fig = plt.figure()
fig.patch.set_facecolor('blue')
fig.patch.set_alpha(0.7)
ax = fig.add_subplot(111)

m = Basemap(projection='ortho',lat_0=0,lon_0=0,resolution='c',ax=ax)
m.drawmapboundary(fill_color='black')
m.drawcoastlines(linewidth=1.25, color='#006600')
plt.savefig('Desktop/out.png',facecolor="red", edgecolor="blue")

rawDescription: Changing image background colour in matplotlib Basemap ortho projection


code:
class A:
    def __init__(self, n=None):
        if n is None:
            n = [0]
        self.data = n

rawDescription: Python, mutable object as default argument, is there any way to solve?


code:
pyrax.settings.set('identity_type', 'rackspace')
pyrax.set_credentials(config.app_config["cdn.account.name"],
                          config.app_config["cdn.account.key"])
rack_conn = pyrax.cloudfiles
rack_conn.upload_folder(folder_path, container)

rawDescription: How can I upload whole folder instead of one by one file in rackspace

description: Upload whole folder instead of one by one file in rackspace


code:
t = '9th of April 2015 03:00'
prefix = t.split()[0][-2:]
datetime.datetime.strptime(t, '%d{0} of %B %Y %H:%M'.format(prefix))

datetime.datetime(2015, 4, 9, 3, 0)

rawDescription: How to convert datetime.strptime() weird date format ( with the word "of" in it)?

description: Convert datetime.strptime() weird date format ( with the word "of" in it)


code:
social = user.social_auth.get(provider='twitter')
access_token = social.extra_data['access_token']['token']

rawDescription: Using django-allauth for authorized Twitter API actions


code:
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(41)

N = 100
x = np.random.randint(0, 9, N)
bins = np.arange(10)

kde = stats.gaussian_kde(x)
xx = np.linspace(0, 9, 1000)
plt, ax = plt.subplots(figsize=(8,6))
ax.hist(x, normed=True, bins=bins, alpha=0.3)
ax.plot(xx, kde(xx))

rawDescription: Add KDE on to a histogram

description: Add KDE on to a histogram


code:
class Foo(object):
    __COUNT = 0
    # or: __COUNT = random.randint(0, 2**N - 1)

    def __init__(self):
        self.unique_id = self.__COUNT  # or take the SHA1 of the count
        type(self).__COUNT += 1

rawDescription: Unique SHA-1 digest generation

description: Unique SHA-1 digest generation


code:
df['max_cat'] = df[['cat1', 'cat2', 'cat3']].idxmax(axis=1)
df

rawDescription: Find max value in row and fill new column with that columns name using Pandas?


code:
import urlparse
url_data = urlparse.urlparse("http://www.youtube.com/watch?v=z_AbfPXTKms&NR=1")
query = urlparse.parse_qs(url_data.query)
video = query["v"][0]

rawDescription: How can I extract video ID from YouTube's link in Python?

description: Extract video ID from YouTube's link in Python


code:
ret = np.zeros_like(data[0,:,:])
for latIdx in xrange(grid.shape[1]):
    for lonIdx in xrange(grid.shape[2]):
        # check if we need to flip the column
        if grid[0,latIdx,lonIdx] > grid[-1,latIdx,lonIdx]:
            ind = -1
        else:
            ind = 1
        f = interpolate.interp1d(grid[::ind,latIdx,lonIdx], \
                data[::ind,latIdx,lonIdx], \
                kind=interp)
        ret[latIdx,lonIdx] = f(value)
return ret

rawDescription: How to improve performance when interpolating on 3d data with SciPy

description: Improve performance when interpolating on 3d data with SciPy


code:
def enumerate(iterable, start=0):
    count = start
    for elem in iterable:
        yield count, elem
        count += 1

rawDescription: What is the implementation detail for enumerate?


rawDescription: Python UCS2 decoding from hex string

description: Python UCS2 decoding from hex string


code: list[MyObject]

rawDescription: How to tell the IDE a method returns a list containing only a specific type of Objects in Python?

description: Tell the IDE a method returns a list containing only a specific type of Objects in Python


code:
class FooForm(forms.Form):
    bar = forms.ModelChoiceField(queryset=Bar.objects.none())

    def __init__(self, *args, **kwargs):
        qs = kwargs.pop('bars')
        super(FooForm, self).__init__(*args, **kwargs)
        self.fields['bar'].queryset = qs

rawDescription: How to dynamically set the queryset of a models.ModelChoiceField on a forms.Form subclass

description: Dynamically set the queryset of a models.ModelChoiceField on a forms.Form subclass


code:
for part in message.walk():
   if part.get_content_type() == "text/plain":
      do_stuff_with_text_parts(part)

rawDescription: read body of email using imapclient in python

description: Read body of email using imapclient in python


code:
def function():
    function.has_been_called = True
    pass
function.has_been_called = False

#Actual Code!:
if function.has_been_called:
    print('function()is called')

rawDescription: How do I conditionally execute code based on if a function is called or not?

description: Conditionally execute code based on if a function is called or not


rawDescription: How can I count occurrences of elements that are bigger than a given number in an list?

description: Count occurrences of elements that are bigger than a given number in an list


code:
@mayavi2.standalone
def view():
    from mayavi.sources.vtk_data_source import VTKDataSource
    from mayavi.modules.outline import Outline
    from mayavi.modules.surface import Surface
    from mayavi.modules.vectors import Vectors

    mayavi.new_scene()
    # The single type one
    src = VTKDataSource(data = ug1)
    mayavi.add_source(src)
    mayavi.add_module(Outline())

rawDescription: Python Mayavi2 @mayavi2.standalone

description: Python Mayavi2 @mayavi2.standalone


code:
import random

#function to determine head or tail of printed random number
def flip(coin):
    #if the coin is zero, then print head
    if coin == 0:
        print("heads!")
    #else print tail
    else:
        print("Tail!")
#simple repeat loop that calls flip() 10 times to generate a random
#sequence of 10 heads and tails
def main():
     for coin in range(10):
        flip(random.randint(0, 1))

main()

rawDescription: Python - Head or Tail Exercise

description: Python - Head or Tail Exercise


rawDescription: Pandas selecting discontinuous columns from a dataframe


code:
x = np.array([0.6, 0.4, 0.2, 0.0])
y = np.array([-0.3, -0.1, 0.1, 0.3])
order = np.argsort(x)
spline = UnivariateSpline(x[order], y[order], w=None, bbox=[None, None], k=1, s=0)
spline([0.15])

rawDescription: Python SciPy UnivariateSpline returns NaN - value in range


code:
import pandas as pd
from cStringIO import StringIO

data = """\
('TIREOO', <type 'str'>, None, 1, 1, 0, False)
('PROFOO', <type 'str'>, None, 10, 10, 0, False)
('DT01OO', <class 'decimal.Decimal'>, None, 8, 8, 0, False)
('DTMNOO', <class 'decimal.Decimal'>, None, 8, 8, 0, False)
('CDDTOO', <type 'str'>, None, 2, 2, 0, False)
('TDOCOO', <type 'str'>, None, 1, 1, 0, False)
('NROROO', <class 'decimal.Decimal'>, None, 7, 7, 0, False)
('NRRGOO', <class 'decimal.Decimal'>, None, 3, 3, 0, False)
('NSRGOO', <class 'decimal.Decimal'>, None, 3, 3, 0, False)
('CDAROO', <type 'str'>, None, 13, 13, 0, False)
('CTGMOO', <type 'str'>, None, 30, 30, 0, False)
"""

data = data.replace('(','')
data = data.replace(')','')

# i've named your columns so they are easier to access
# un-named, they default to integer indexing like the rows
# you probably have more meaningful names for them
df = pd.read_csv(StringIO(data), header=None,
                 names=['a', 'b', 'c', 'd', 'e', 'f', 'g'])

# this is just removing the 'funny' characters from the data
df.g = [item.strip(')') for item in df.g.values]
df.a = [item.strip('(\'') for item in df.a.values]

df.set_index('a')
df

rawDescription: pandas read a file and make a list

description: Pandas read a file and make a list


code:
sizer = wx.BoxSizer(wx.VERTICAL)
text_sizer = wx.BoxSizer(wx.HORIZONTAL)
canvas_sizer = wx.BoxSizer(wx.HORIZONTAL)
stat = wx.StaticText(self, -1, "position")

# for testing I used a panel instead of your ogl object
canvas = wx.Panel(self, -1)
canvas.SetMinSize((-1, 70))     # Needed here to give a min size to panel,
                                # otherwise the panel would not be seen.
                                # The sizer will occupy the minimal
                                # to hold its contents.

canvas_sizer.Add(canvas, 1, wx.EXPAND, 0)
sizer.Add(canvas_sizer, 0, wx.EXPAND, 0)   # <- note proportion 0 here
text_sizer.Add(stat, 1, wx.EXPAND, 0)
sizer.Add(text_sizer, 1, wx.EXPAND, 0)
self.SetSizer(sizer)
sizer.Fit(self)
self.Layout()

rawDescription: Fixed canvas shape in wxpython ogl library


code:
# python 2
from urllib2 import urlopen
# python 3
from urllib.request import urlopen

base_url = "http://example.com/"

# request page 1 through 10
n = 10
for i in range(1, n+1):
    if (i == 1):
        # handle first page
        response = urlopen(base_url)
    response = urlopen(base_url + "?page=%d" % i)

    data = response.read()
    # handle data here

rawDescription: Iterating through a site's pages with python and Beautiful Soup


code:
from sympy import Symbol
x, y = Symbol('x y')
f = x + y
f.subs({x:10, y: 20})
f

rawDescription: How to substitute multiple symbols in an expression in sympy?

description: Substitute multiple symbols in an expression in sympy


code:
string = {1,2,3}
[i for i in sample if string.intersection(i)]

rawDescription: Iteration over elements of a list without redundancy; Python


code:
class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.list = QtGui.QListWidget(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.list)

    def addListItem(self, text):
        item = QtGui.QListWidgetItem(text)
        self.list.addItem(item)
        widget = QtGui.QWidget(self.list)
        button = QtGui.QToolButton(widget)
        layout = QtGui.QHBoxLayout(widget)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addStretch()
        layout.addWidget(button)
        self.list.setItemWidget(item, widget)
        button.clicked[()].connect(
            lambda: self.handleButtonClicked(item))

    def handleButtonClicked(self, item):
        print(item.text())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    for label in 'red blue green yellow purple'.split():
        window.addListItem(label)
    window.setGeometry(500, 300, 300, 200)
    window.show()
    sys.exit(app.exec_())

rawDescription: How to display a list of QPushButton?

description: Display a list of QPushButton


code:
def hole(self):
    hold=[]
    # Pick two cards
    hold.append(self.picker())
    hold.append(self.picker())
    # Make sure the cards aren't the same
    while hold[0]==hold[1]:
        hold[1] = self.picker()
    return hold

rawDescription: Function returning too many list items and duplicates


code:
filterKeyword=['eat','cinnamon','fruit','pie','juice']
for tweet in tweets:
    for key in filterKeyword:
        if key in tweet['text']:
            pass
        else:
            tweetsFiltered.append(tweet)
            tweetStr+=str(tweet['text'])
print(tweetStr)

rawDescription: Python Twitter json text filter

description: Python Twitter json text filter


rawDescription: Convert hex to utf in Python

description: Convert hex to utf in Python


rawDescription: python unicode support

description: Python unicode support


rawDescription: django - having model class how to get list of all fields, their types and parameters passed?

description: Django - having model class how to get list of all fields, their types and parameters passed


code:
import numpy as np
from scipy.spatial import cKDTree

n_voronoi, n_test = 100, 1000

voronoi_points = np.random.rand(n_voronoi, 2)
test_points = np.random.rand(n_test, 2)

voronoi_kdtree = cKDTree(voronoi_points)

test_point_dist, test_point_regions = voronoi_kdtree.query(test_points, k=1)

rawDescription: Finding voronoi regions that contain a list of arbitrary coordinates


code:
@app.context_processor
def inject_dict_for_all_templates():
    return dict(mydict=code_to_generate_dict())

rawDescription: Pass variables to all Jinja2 templates with Flask


code:
def addNameToDictionary(d, tup):
    if tup[0] not in d:
        d[tup[0]] = {}
    d[tup[0]][tup[1]] = [tup[2]]

rawDescription: python dictionary of dictionaries

description: Python dictionary of dictionaries


rawDescription: Using glob() to find directories after a point in time


code:
import matplotlib.pyplot as plt

fig = plt.figure()
s = fig.add_subplot(111)
s.bar([1, 2], [43, 21], width=1)
s.set_xlim(0.5, 3.5)
fig.savefig('t.png')

rawDescription: How to plot a bar plot with matplotlib using two single values?

description: Plot a bar plot with matplotlib using two single values


code:
c = Counter()
for d in d1, d2, d3:
    c.update(d)

c

rawDescription: How to combine multiple dicts, summing the values of common keys (and retaining those with value 0) in Python?

description: Combine multiple dicts, summing the values of common keys (and retaining those with value 0) in Python


code:
import sys
import signal

def cleanup_function(signal, frame):
    # clean up all resources
    sys.exit(0)

signal.signal(signal.SIGINT, cleanup_function)

rawDescription: Python in Linux: kill processes and sub-processes using the shell


code:
"""Making sure they use uppercase and end with a period"""

s = input("Please enter an upper-case string ending with a period: ")

if s.isupper() and s.endswith("."):
     print("Input meets both requirements.")
elif not s.isupper():  #not False -> True
     print ("Input is not all upper case.")
elif not s.endswith("."): #not False -> True
    print ("Input does not end with a period.")
else :
     print ("You just don't want to do this, do you?")

rawDescription: Testing that a string DOES NOT have specific characteristics in a small program (python 3)


code:
@cherrypy.expose
def index(self, **kwargs):
  isPart = lambda v: isinstance(v, cherrypy._cpreqbody.Part)
  files1 = [a for a in kwargs.values() if isPart(a)]
  files2 = [a for a in cherrypy.request.params.values() if isPart(a)]

  assert files1 == files2
  print(files1) # pass it where you want to

rawDescription: How to upload a variable amount of files using a single multipartform post header key

description: Upload a variable amount of files using a single multipartform post header key


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

fig = pl.figure(figsize=(18,4)) #sets a different size (inches wide, inches tall)
ax = pl.subplot(111)
width=1.0
ax.bar(range(0,len(words)), words.values(), width=width/2)
ax.set_xticks(np.arange(0,len(words)) + width/2)
ax.set_xticklabels(words.keys())

locs, labels = pl.xticks() #gets labels
pl.setp(labels, rotation=90) #sets rotation of the labels

pl.show()

rawDescription: Trying to add more space between labels in x-axis on pyplot histogram


code:
inList = [1,2,3,4,5]
inDict = {1:5, 2:2, 3:4, 4:1, 5:3}
sorted(inList, key=lambda x: inDict.get(x,0))

rawDescription: Using histogram to sort list

description: Using histogram to sort list


code:
import re
l = [ "%AB0.1.100", "%TB4.1.15" ]
out = []
for item in l:
   m = re.search(r"(\d+\.\d+)\.(\d+)", item)
   f = float(m.group(1))
   i = int(m.group(2))
   out.append((f, i))
out

rawDescription: Parsing numbers of integer and real type in string


code:
import Tkinter
import pickle

class simpleapp_tk(Tkinter.Tk):
    def __init__(self, parent=None):
        Tkinter.Tk.__init__(self, parent)
        self.parent = parent
        self.initialize()
        self.load_data()
        self.protocol("WM_DELETE_WINDOW", self.save_data)

    def initialize(self):
        self.sclX = Tkinter.Scale(self, from_=0, to=100, orient='horizontal',
            resolution=1,command=self.update_label)
        self.sclX.pack(ipadx=75)

        self.labelVar = Tkinter.StringVar()
        self.label = Tkinter.Label(self,textvariable=self.labelVar)
        self.label.pack(ipadx=75)

        self.frame = Tkinter.Frame(self,relief='ridge',borderwidth=4)
        self.frame.pack()
        #self.LVariable = Tkinter.StringVar()
        self.s = Tkinter.Scrollbar(self.frame)
        self.L = Tkinter.Text(self.frame, borderwidth=0, font=('Arial', 10),
            width=30, height=15)
        self.s.config(command=self.L.yview, elementborderwidth=1)
        self.L.grid(column=0, row=0, sticky='EW')
        self.s.grid(column=1, row=0, sticky='NSEW')

    def update_label(self, event):
        self.labelVar.set(100 - self.sclX.get())

    def save_data(self):
        data = {'scale': self.sclX.get(), 'text': self.L.get('1.0', 'end')}
        with file('config.data', 'wb') as f:
            pickle.dump(data, f)
        self.destroy()

    def load_data(self):
        try:
            with file('config.data', 'rb') as f:
                data = pickle.load(f)
                self.sclX.set(data['scale'])
                self.L.insert("end", data['text'])
        except IOError:
            # no config file exists
            pass

if __name__ == "__main__":
    app = simpleapp_tk()
    app.mainloop()

rawDescription: I want to make this program remember settings


code:
import numpy as np

# Load the files:
answers = np.loadtxt(open("Answer.txt"), dtype='str', delimiter=",")
test = np.loadtxt(open("Text.txt"), dtype='str', delimiter=",")

# Compare
scores = 2 * np.sum(answers == test, axis=0)

# save
np.savetxt("Score.csv", scores, delimiter=",")

rawDescription: How do I compare a record in a csv (txt) file to a record in another csv (txt) file and calculate a number based on their comparison?

description: Compare a record in a csv (txt) file to a record in another csv (txt) file and calculate a number based on their comparison


code:
total_items = [0]*12
for d in q:
  month = int(d['month'], 10)
  total_items[month-1] = d['total_item']

rawDescription: Python: fill in missing months with zero


code:
from datetime import datetime

def print_ts():
    return datetime.now().strftime('%Y%m%d %H:%M:%S')

rawDescription: Python equivalent of perl timestamp

description: Python equivalent of perl timestamp


code:
def addprop(inst, name, method):
  cls = type(inst)
  if not cls.hasattr('__perinstance'):
    cls = type(cls.__name__, (cls,), {})
    cls.__perinstance = True
  setattr(cls, name, property(method))

rawDescription: Dynamically adding @property in python

description: Dynamically adding @property in python


code:
def key_tree_Tab(self, treeview, event,namewidget):
    keyname = Gdk.keyval_name(event.keyval)

    path, col = treeview.get_cursor()
    ## only visible columns!!
    columns = [c for c in treeview.get_columns() if c.get_visible()]
    colnum = columns.index(col)

    if keyname=="Tab" or keyname=="Esc":

        if colnum + 1 < len(columns):
            next_column = columns[colnum + 1]

        else:
            tmodel = treeview.get_model()
            titer = tmodel.iter_next(tmodel.get_iter(path))
            if titer is None:
                titer = tmodel.get_iter_first()
            path = tmodel.get_path(titer)
            next_column = columns[0]

        if keyname == 'Tab':
            #Thank you Jordan!!!!!! Great hack!
            GLib.timeout_add(50,
                            treeview.set_cursor,
                            path, next_column, True)
        elif keyname == 'Escape':
            pass

rawDescription: Python PyGOobject treeview: confirm edit after move between cells with Tab key


code: my_string = my_string.rstrip('\\')

rawDescription: Remove last character if it's a backslash


code:
import os, gtk, gobject
from time import time, sleep
from datetime import datetime

class HeartbeatTrayIcon(object):
    """
    Use GTK to create an object in the system tray
    and manipulate icon shown if there is an issue.
    """
    def __init__(self):
        self.statusIcon = gtk.StatusIcon()

    def check(self):
        rx = os.path.getmtime("test")
        if (time() - rx) > (60*60*24):
            self.statusIcon.set_from_stock(gtk.STOCK_CANCEL)
        else:
            self.statusIcon.set_from_stock(gtk.STOCK_APPLY)
        self.statusIcon.set_tooltip("Last heartbeat received at %s" \
            % datetime.fromtimestamp(int(rx)).strftime('%H:%M:%S %d-%m-%Y'))
        return True

    def tray(self):
        gobject.idle_add(self.check)
        gtk.main()

if __name__ == "__main__":
    i = HeartbeatTrayIcon()
    i.tray()

rawDescription: Refresh Gtk.StatusIcon in python

description: Refresh Gtk.StatusIcon in python


code:
class FiniteField11:
   def __init__(self, element):
       self.elt = element
FiniteField11.generator = FiniteField11(2)

rawDescription: Can a class variable be an instance of the class?


code:
from matplotlib.pylab import *
import matplotlib.cm as cm
import matplotlib.patches as patches

min_val = 0
max_val = 50

my_cmap = cm.get_cmap('jet') # or any other one
norm = matplotlib.colors.Normalize(min_val, max_val) # the color maps work for [0, 1]

x_i = 15
color_i = my_cmap(norm(x_i)) # returns an rgba value

rect = patches.Rectangle((.5, .5), .25, .25, color=color_i) # make your rectangle

cmmapable = cm.ScalarMappable(norm, my_cmap)
cmmapable.set_array(range(min_val, max_val))

figure()
ax = gca()
ax.add_patch(rect)
colorbar(cmmapable)
show()

rawDescription: Matplotlib - Pick up one color associated to one value in a `colorbar`


code:
import cexapi
api = cexapi.API(username, api_key, api_secret)

rawDescription: Problems Using CEX API in Python-- Cannot use module.


code:
import urllib.request
import threading

class MyHandler(urllib.request.HTTPHandler):
    @staticmethod
    def http_response(request, response):
        print(response.code)
        return response

opener = urllib.request.build_opener(MyHandler())
try:
    thread = threading.Thread(target=opener.open, args=('http://www.google.com',))
    thread.start()      #begin thread execution
    print('exit')

    # other program actions

    thread.join()       #ensure thread in finished before program terminates
except Exception as e:
    print(e)

rawDescription: Async http request with python3

description: Async http request with python3


code: x = x.upper()

rawDescription: How to make strings upper case in python

description: Make strings upper case in python


code:
now = dt.now()
microseconds_past_the_hour = now.microsecond + 1000000*(now.minute*60 + now.second)

rawDescription: Getting microseconds past the hour

description: Getting microseconds past the hour


code:
for k in range(0,len(data)):
    stuff = ClassTwo()

rawDescription: python looping and appending to a list

description: Python looping and appending to a list


code:
from zope.component import getUtility
from zope.intid.interfaces import IIntIds

intidutil = getUtility(IIntIds)
object = intidutil.getObject(id)

rawDescription: Resolving an IntId

description: Resolving an IntId


code:
def main_work_subdirs(gl):
    for root, dirs, files in os.walk(gl['pwd']):
        dirs.sort()
        if root == gl['pwd']:
            for d2i in dirs:
                print(d2i)

rawDescription: can i force python3's os.walk to visit directories in alphabetical order? how?

description: Force python3's os.walk to visit directories in alphabetical order? how


code:
@total_ordering
class B_ordering(object):
    __slots__ = ()                 # see Raymond's comment
    def __lt__(self, other):
        return self.y < other.y

class B(B_ordering, namedtuple('B', 'x y')):
    pass

rawDescription: Custom sorting on a namedtuple class

description: Custom sorting on a namedtuple class


code: [x[1] for x in elements]

rawDescription: How to extract the n-th elements from a list of tuples in python?

description: Extract the n-th elements from a list of tuples in python


code:
class MySpider2(MySpider):
    name = 'spider2'
    custom_settings = {'ITEM_PIPELINES': 'project.pipelines.AddToDB'}

rawDescription: Parse single URL without crawlling

description: Parse single URL without crawlling


code:
from bs4 import BeautifulSoup

data = """

text1

text2

"""
soup = BeautifulSoup(data, "html.parser")
[p.get_text() for p in soup.find_all("p", text=True)]

rawDescription: Python regex to extract html paragraph

description: Python regex to extract html paragraph


code:
pd.read_csv("wspace.csv", header=None, delim_whitespace=True)
pd.read_csv("wspace.csv", header=None, sep=r"\s+")

rawDescription: Using pandas to read text file with leading whitespace gives a NaN column


code:
import web

urls = (
    '/(.*)', 'hello'
)
app = web.application(urls, globals())

class hello:
    def GET(self, name):
        if not name:
            name = 'world'
        return 'Hello, ' + name + '!'

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

rawDescription: Python web framework with low barrier to entry


code:
import wx, wx.grid

class GridData(wx.grid.PyGridTableBase):
    _cols = "a b c".split()
    _data = [
        "1 2 3".split(),
        "4 5 6".split(),
        "7 8 9".split()
    ]
    _highlighted = set()

    def GetColLabelValue(self, col):
        return self._cols[col]

    def GetNumberRows(self):
        return len(self._data)

    def GetNumberCols(self):
        return len(self._cols)

    def GetValue(self, row, col):
        return self._data[row][col]

    def SetValue(self, row, col, val):
        self._data[row][col] = val

    def GetAttr(self, row, col, kind):
        attr = wx.grid.GridCellAttr()
        attr.SetBackgroundColour(wx.GREEN if row in self._highlighted else wx.WHITE)
        return attr

    def set_value(self, row, col, val):
        self._highlighted.add(row)
        self.SetValue(row, col, val)

class Test(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)

        self.data = GridData()
        self.grid = wx.grid.Grid(self)
        self.grid.SetTable(self.data)

        btn = wx.Button(self, label="set a2 to x")
        btn.Bind(wx.EVT_BUTTON, self.OnTest)

        self.Sizer = wx.BoxSizer(wx.VERTICAL)
        self.Sizer.Add(self.grid, 1, wx.EXPAND)
        self.Sizer.Add(btn, 0, wx.EXPAND)

    def OnTest(self, event):
        self.data.set_value(1, 0, "x")
        self.grid.Refresh()

app = wx.PySimpleApp()
app.TopWindow = Test()
app.TopWindow.Show()
app.MainLoop()

rawDescription: Highlight a row in wxGrid (with wxPython) when a cell in that row changes programatically


rawDescription: What's the difference between these two codes?


code:
j = [{"source":"AA","target":"BB","metric":"10",
 "local_interface":"100","remote_interface":"200"},
 {"source":"AA","target":"BB","metric":"10",
 "local_interface":"111","remote_interface":"222"},
 {"source":"BB","target":"AA","metric":"10",
 "local_interface":"200","remote_interface":"100"}]

s = j[0]["source"]
print(s)
t = j[0]["target"]
print(t)
li = j[0]["local_interface"]
print(li)

print('Find source ==', t)
for i in range(1,3):
  if j[i]['source'] == t:
    print("Is match:", j[i])

print()

del(j[1])
print("after deletion:", j)

rawDescription: python json match multiple and replace

description: Python json match multiple and replace


code: re.split('(?<!\d)\.|\.(?!\d)', 'hyper count 16.8mmol/l.plz review b4 5pm.just to inform u.thank u')

rawDescription: Sentence segmentation using Regex

description: Sentence segmentation using Regex


code:
libc.gethostbyname.restype = POINTER(hostent)
he = libc.gethostbyname("www.google.com")[0]
he.h_aliases[0]

rawDescription: decoding ctypes structures

description: Decoding ctypes structures


code:
window.opener.location.href = "http://some/new/location";
window.close();

rawDescription: How to close a pop up window and redirect the url to parent page?

description: Close a pop up window and redirect the url to parent page


code:
import os
u = 'http://hapmap.ncbi.nlm.nih.gov/downloads/frequencies/2010-05_phaseIII/'
filename1 = 'allele_freqs_chr' + chromosomes[i] + '_' + populations[0] + '_phase3.3_nr.b36_fwd.txt.gz'
url = u + filename1
try:
    site = urllib.urlretrieve(url,filename1)
except IOError:
    print >> sys.stderr,'Error opening URL.\n'
try:
    f1 = gzip.open(filename1, 'rb')
except IOError:
    print >> sys.stderr, 'Error opening file1.\n'
    sys.exit(1)
else:
    line = f1.readline()
    # ....
finally:
    try:
        f1.close()
    except:
        pass

os.unlink(filename1)

rawDescription: Python: delete the files after i finish reading from FTP


code:
s = sum(hours)*3600+sum(minutes)*60+sum(seconds)
return '%d hours %d minutes %d seconds'%( s/3600, (s%3600)/60, s%60)

rawDescription: converting a list of times to total time

description: Converting a list of times to total time


code:
#!/usr/bin/env python
from tkinter import *
import random

root = Tk()

class Recta:
    def __init__(self, height, width):
        self.height=80
        self.width=100
    def randomRects(self,canvas):
        w = random.randrange(100)
        h = random.randrange(80)
        canvas.create_rectangle(0,0,h,w,fill='green')

c = Canvas(root)
c.pack()

tes = Recta(10,20)
tes.randomRects(c)

root.mainloop()

rawDescription: create random rectangle on canvas

description: Create random rectangle on canvas


code:
from collections import OrderedDict
dic =  OrderedDict([(u'b1', OrderedDict([(u'ip', u'199.0.0.1'), (u'port', u'1122')])), (u'b2', OrderedDict([(u'ip', u'199.0.0.1'), (u'port', u'1123')]))])
":".join(dic)

rawDescription: Saving dictionary keys as strings

description: Saving dictionary keys as strings


code:
#include "PartOneOfUglyCode.cpp"
#include "PartTwoOfUglyCode.cpp"
#include "PartThreeOfUglyCode.cpp"
...

rawDescription: Telling Visual C++ to join several cpp file to make an unity build, to keep my code organized?


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

plt.close('all')

x=[1,2,3,4]
y=[1,4,9,16]

fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y, 'o')

def onclick(event):
    ix, iy = event.xdata, event.ydata
    print("I clicked at x={0:5.2f}, y={1:5.2f}".format(ix,iy))

    # Calculate, based on the axis extent, a reasonable distance
    # from the actual point in which the click has to occur (in this case 5%)
    ax = plt.gca()
    dx = 0.05 * (ax.get_xlim()[1] - ax.get_xlim()[0])
    dy = 0.05 * (ax.get_ylim()[1] - ax.get_ylim()[0])

    # Check for every point if the click was close enough:
    for i in range(len(x)):
        if(x[i] > ix-dx and x[i] < ix+dx and y[i] > iy-dy and y[i] < iy+dy):
            print("You clicked close enough!")

cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

rawDescription: Matplotlib scatterplot : Open image corresponding to point which i click


code:
import time
myList = [1,2,3,4,5,6,7,8]
i = 0
while i < len(myList):
    time.sleep(1)
    print(i)
    if i == 3:
        i -= 1
    i += 1

rawDescription: Don't go to next iteration in for loop

description: Don't go to next iteration in for loop


code:
with open("dest.txt", "w") as template:
  for line in lines:
    line = re.sub(field_one, one, line)  # modify first
    line = re.sub(field_two, two, line)
    template.write(line)  # write once after modifying

rawDescription: Python Replace Multiple Lines in File

description: Python Replace Multiple Lines in File


code:
n = 100000
p1 = RandomRDDs.uniformRDD(sc, n).zip(RandomRDDs.uniformRDD(sc, n))
p2 = RandomRDDs.uniformRDD(sc, n).zip(RandomRDDs.uniformRDD(sc, n))

point_rdd = p1.zip(p2)\
.map(lambda r: Row(x1=r[0][0], y1 = r[0][1], x2=r[1][0], y2 = r[1][1]))

rawDescription: create a multidimensional random matrix in spark

description: Create a multidimensional random matrix in spark


code: range(num - 5, num + 5)

rawDescription: create list by -5 and + 5 from given number

description: Create list by -5 and + 5 from given number


rawDescription: How to divide python list into sublists of unequal length?

description: Divide python list into sublists of unequal length


code:
tup = (2009, 3, 23, 13, 6, 34, 0, 82, 0)
import datetime
d = datetime.datetime(*(tup[0:6]))
#two equivalent ways to format it:
dStr = d.isoformat(' ')
#or
dStr = d.strftime('%Y-%m-%d %H:%M:%S')

rawDescription: Python, Convert 9 tuple UTC date to MySQL datetime format


code:
from shutil import copyfileobj
from urllib3 import HTTPConnectionPool

_http = HTTPConnectionPool(host='www.example.org', port=80)

response = _http.request_encode_url(
    'GET', 'http://www.example.org/',
    {'param1': value1},
    preload_content=False, decode_content=True
)

with open('output.html', 'wb') as fp:
    copyfileobj(response, fp)

rawDescription: Connecting streams in Python

description: Connecting streams in Python


rawDescription: Split array at value in numpy

description: Split array at value in numpy


code:
import os
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES)

with open('output.txt', 'wb') as stream:
    for tr in soup.findAll('tr')[1:]: # [1:] skips the header
        columns = tr.findAll('td')
        line = [columns[0].a.string.strip()]
        for item in (item.strip() for item in columns[1].findAll(text=True)):
            if (item and not item.startswith('Phone:')
                and not item.startswith('Fax:')):
                line.append(item)
        stream.write(' '.join(line).encode('utf-8'))
        stream.write(os.linesep)

rawDescription: Parsing html with Python

description: Parsing html with Python


code:
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt

fig = plt.figure()
ax = Axes3D(fig)
# Specify 4 vertices
x = [0,1,1,0] # Specify x-coordinates of vertices
y = [0,0,1,1] # Specify y-coordinates of vertices
z = [0,1,0,1] # Specify z-coordinates of vertices
verts = [zip(x, y, z)] # [(0,0,0), (1,0,1), (1,1,0), (0,1,1)]
tri = Poly3DCollection(verts) # Create polygons by connecting all of the vertices you have specified
tri.set_color(colors.rgb2hex(sp.rand(3))) # Give the faces random colors
tri.set_edgecolor('k') # Color the edges of every polygon black
ax.add_collection3d(tri) # Connect polygon collection to the 3D axis
plt.show()

rawDescription: Plot3d in Python

description: Plot3d in Python


code:
from random import choice, random

def stack_overflow_example(self):
    def fitness(trial):
        trial_max = self.func(trial, mat)
        if trial_max > self.best_res:
            self.best_res = trial_max
            return trial_max
        else:
            return -sys.maxint

    def mutate(parent):
        mutation = []
        for p in parent:
            if random() < prob:
                mutation.append(choice([0, 1]))
            else:
                mutation.append(p)
        return mutation

    l1 = [3, 4, 7, -2]
    l2 = [0.5, 3, 6, 2.7]
    l3 = [0, 5, 8, 3.6]
    mat = [l1, l2, l3]

    max_num_of_loops = 1000
    prob = 0.075  # mutation probability
    gen_size = 10  # number of children in each generation
    self.bin_parent = [1] * len(mat)  # first parent all ones
    self.best_res = self.func(self.bin_parent, mat)  # starting point for comparison
    for _ in xrange(max_num_of_loops):
        backup_parent = self.bin_parent
        copies = (mutate(self.bin_parent) for _ in xrange(gen_size))
        self.bin_parent = max(copies, key=fitness)
        res = self.func(self.bin_parent, mat)
        if res >= self.best_res:
            self.best_res = res
            print (">> " + str(res))
        else:
            self.bin_parent = backup_parent
    print("Final result: " + str(self.best_res))
    print("Chosen lists:")
    chosen_lists = self.choose_strategies(self.bin_parent, mat)
    for i, li in enumerate(chosen_lists):
        print(">> list[{}] : values: {}".format(i, li))

def func(self, bin_list, mat):
    chosen_mat = self.bin_list_to_mat(bin_list, mat)
    if len(chosen_mat) == 0:
        return -sys.maxint
    # doing some math between lists:
    sum_list = list(chosen_mat[0])
    for li in chosen_mat[1:]:
        sum_list = map(operator.add, sum_list, li)
    accum_min_lst = []
    for i, val in enumerate(sum_list):
        x = sum_list[:i + 1]
        accum_min_lst.append(val - max(x))
    return min(accum_min_lst)

@staticmethod
def bin_list_to_mat(bin_list, mat):
    chosen_lists = []
    for i, stg in enumerate(mat):
        if bin_list[i] == 1:
            chosen_lists.append(stg)
    return chosen_lists

rawDescription: Finding the best combination of lists with maximum function value


code:
s = s.cat.rename_categories(["A", "B", "C"])
s
seaborn.countplot(x=s)

rawDescription: Category names not used by python seaborn


code:
from twisted.names import client
from twisted.internet import reactor

def do_lookup(domain):
    hosts = "/tmp/example"
    resolver = client.createResolver(servers=None, resolvconf=None, hosts="/tmp/example")
    d = resolver.getHostByName(domain)
    d.addBoth(lookup_done)

def lookup_done(result):
    print(result)
    reactor.stop()

domain = b'twistfoo.com'
reactor.callLater(0, do_lookup, domain)
reactor.run()

rawDescription: How does twisted read /etc/hosts?

description: How does twisted read /etc/hosts


code:
r= """[{
  "id": "fhjgjj",
  "OneId": "sjgkhkshgkfh",
  "name": "test_one",
  "value": "/xyz",
  "pdiff": null
}]"""

import json

r= json.loads(r)

rawDescription: How to convert a list of dictionaries which has type as string to a list?

description: Convert a list of dictionaries which has type as string to a list


code:
from pandas import io
class MyXLSWriter(io.excel.xlsx.writer):
     def write_cells(self, cells,*args,**kwargs):
         for cell in cells:
             if isinstance(cell.val,(MyCustomClass1,MyCustomClassN)):
                cell.val = str(cell.val) #or some other representaion...
         io.excel.xlsx.writer.write_cells(self,cells,*args,**kwargs)

my_df.to_excell(fname,engine=MyXLSWriter)

rawDescription: Making custom classes xlsxwriter friendly


code:
from functools import reduce

lines = source.splitlines()
tokens_list = [line.strip().split() for line in lines]
tokens = reduce(lambda x,y: x + ['\n'] + y, tokens_list)
print(tokens)

rawDescription: Split code into tokens (Lexing) in Python


code:
class SomeClass(object):
    authenticated = {}
    def authenticate(self, username, password):
        #do something here
        if authenticate(username, password):
            # make unique token can probably be just a hash
            # of the millisecond time and the username
            self.authenticated[make_unique_token(username)] = True
    def other_action(self, vars):
        # This will return True if the user is authenticated
        # and None otherwise, which evaluates to False
        if authenticated.get(vars.get('authentication-token')):
            #do whatever
            pass
        else:
            return "Not authorized."

server=SimpleXMLRPCServer.SimpleXMLRPCServer("0.0.0.0", 8000)
server.register_instance(someclass())
server.serve_forever()

rawDescription: Python Server for multiple clients with or without XMLRPC


code:
def configsec(self, inp_list):
    # Changed: Remember the current configuration element so that
    # properties can be applied
    self.configuration = SubElement(self.sub_workflow, 'configuration')
    # TODO: this creates properties in the xml but since `property`
    # returns `None` you return a list of `None`s here.
    proptext = [self.property(prop[0], prop[1]) for prop in inp_list]
    return proptext

def property(self, key, value):
    # changed: set the property element on the current configuration
    property = SubElement(self.configuration,'property')
    name = SubElement(property,'name')
    name.text = key
    val = SubElement(property,'value')
    val.text = value

rawDescription: Need to generate SubElement with xml content (not just text) using Python


code:
def drop_privileges(uid_name, gid_name):
    '''If running as root, this function will try to change current uid and gid
    to given values.
    May raise OSError in case of error.
    :param uid_name: Name of the user we need to be running as.
    :param gid_name: Name of the group we need to be running as.
    '''

    starting_uid = os.getuid()
    starting_gid = os.getgid()

    log.info('drop_privileges: started as %s/%s' %
        (pwd.getpwuid(starting_uid).pw_name,
        grp.getgrgid(starting_gid).gr_name))

    if starting_uid == 0:
        # If we started as root, drop privs and become the specified user/group
        log.info("drop_privileges: trying to drop provileges to '%s'" % uid_name)

        # Get the uid/gid from the name
        running_uid = pwd.getpwnam(uid_name).pw_uid
        running_gid = grp.getgrnam(gid_name).gr_gid

        # Try setting the new uid/gid
        # These calls may result in exception, let it propagate back
        # Exception thrown is: OSError (e.errno == 1 means 'Operation not
        # permitted')
        os.setgid(running_gid)
        os.setuid(running_uid)

        final_uid = os.getuid()
        final_gid = os.getgid()
        log.info('drop_privileges: running as %s/%s' %
            (pwd.getpwuid(final_uid).pw_name,
             grp.getgrgid(final_gid).gr_name))

rawDescription: Upstart - how to send reload signal to script started as different user?


code:
lst = [1, 2, 3, 2, 3, 4]
[x for x in lst if lst.count(x) == 1]

rawDescription: Retrieve only non-duplicate elements from a list


code:
import getpass
password = getpass.getpass()

rawDescription: Requesting password in IPython notebook

description: Requesting password in IPython notebook


code:
from itertools import *

combo_list = []

for i in your_list:
    for j in permutations(i, len(i)):
        combo_list.append(j)

rawDescription: Lists of lists python recursive permutation


code:
import codecs
import csv
import json

fields = [
    'status', 'message', 'type', 'addressAccessId', 'municipalityCode',
    'municipalityName', 'streetCode', 'streetName', 'streetBuildingIdentifier',
    'mailDeliverySublocationIdentifier', 'districtSubDivisionIdentifier',
    'postCodeIdentifier', 'districtName', 'presentationString', 'addressSpecificCount',
    'validCoordinates', 'geometryWkt', 'x', 'y']

with open('test.csv', 'wb') as csvfile, open('jsonfile', 'r') as jsonfile:
    writer = csv.DictWriter(csvfile, fields)
    writer.writeheader()

    for line in jsonfile:
        if line.startswith(codecs.BOM_UTF8):
            line = line[3:]
        entry = json.loads(line)
        for item in entry['data']:
            row = dict(item, status=entry['status'], message=entry['message'])
            row = {k.encode('utf8'): unicode(v).encode('utf8') for k, v in row.iteritems()}
            writer.writerow(row)

rawDescription: Converting to csv from?

description: Converting to csv from


code:
from django.views.generic import TemplateView

class RiskView(TemplateView):
    template_name = 'formulare/RiskAssessment/risk.html'
    risk = None
    RiskLineSet = None

    def dispatch(self, request, *args, **kwargs):
        if self.kwargs.get('pk', None) is None:
            return HttpResponseRedirect('/fm/riskassessment/')  # No pk show list
        else:
            self.risk = RiskAssessment.objects.get(id=pk)

        self.RiskLineSet = inlineformset_factory(RiskAssessment, RiskLine, can_delete=False, exclude=('user',))
        return super(RiskView, self).dispatch(self, request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(RiskView, self).get_context_data(**kwargs)
        context['riskform'] = RiskForm(instance=self.risk)
        context['risklineset'] = self.RiskLineSet(instance=self.risk)
        return context

    def post(self, request, *args, **kwargs):
        riskform = RiskForm(request.POST, instance=self.risk)
        risklineset = self.RiskLineSet(request.POST, request.FILES, instance=self.risk)

        if riskform.is_valid() and risklineset.is_valid():
            riskform.save()
            risklineset.save()

            # Redirect to somewhere
            if '_save' in request.POST:
                return HttpResponseRedirect('/fm/riskassessmentlist/')
            if '_addanother' in request.POST:
                return HttpResponseRedirect('/fm/riskassessmentnew/')
            # Otherwise, I guess you want to redirect to the same view
            return HttpResponseRedirect('url_of_the_current_view')

rawDescription: I have the following view working on Django. Can I do the same with a Generic View?


code:
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randn(100,5))

# you get ax from here
ax = df.plot()
type(ax)  # matplotlib.axes._subplots.AxesSubplot

# manipulate
vals = ax.get_yticks()
ax.set_yticklabels(['{:3.2f}%'.format(x*100) for x in vals])

rawDescription: Format y axis as percent

description: Format y axis as percent


code:
tmp = mydict[mykey] = myfunc()
return tmp

rawDescription: Python avoiding using a variable when using a value twice?


code:
seqb = seq.encode('latin-1')
seqb.decode('shift-jis')

rawDescription: Convert string of encoded escape sequences to Unicode in Python 3


code:
import pandas as pd
DF = pd.DataFrame({'COL1': [1.0,2.0,"A"]})

def ToInt(x):
    try:
        x = int(x)
    except:
        pass
    return x

DF.index = [ToInt(x) for x in DF.COL1]
DF

rawDescription: Set Index as Integers with Mixed Types

description: Set Index as Integers with Mixed Types


code:
f = open('file.csv', 'rb')
csv_in = csv.reader(f, quotechar='"', quoting=csv.QUOTE_NONE)
# use a set saving which i's already used
set_i = set()
for row in csv_in:
    i = 0
    while i < list_length:
        if list1[i] == row[0]:

            # Execute the next 2 lines just once for every i using the set
            if not i in set_i:
                set_i.add(i)
                o = open(list2[i], 'wb')
                csv_out = csv.writer(o, quotechar='"', quoting=csv.QUOTE_NONE)

            final_list = [row[-2] + ';' + row[-1]]
            csv_out.writerows([final_list])

        i += 1

f.close()
o.close()

rawDescription: Python CSV module, do statement just once in a loop


rawDescription: Parsing SEC RSS Title field using regex

description: Parsing SEC RSS Title field using regex


code:
import mechanize

self.browser = mechanize.Browser()
self.browser.open(self.url)
self.browser.select_form(name="login")

self.browser["login_nick"] = self.username
self.browser["login_pwd"] = self.password
self.browser.new_control("HIDDEN", "action", {})
control = self.browser.form.find_control("action")
control.readonly = False
self.browser["action"] = "login"
self.browser.method = "POST"
self.browser.action = self.url

response = self.browser.submit()

rawDescription: Python mechanize login to website

description: Python mechanize login to website


code:
class MobileManager(object):
    def __init__(self):
        for prefix_name in prefix:
            for method_name in method:
                func = lambda self, args: getattr(self.mobileLib, method_name)(args, prefix)
                full_method_name = "%s%s" % (prefix, method_name)
                setattr(self, full_method_name, func)
        ...

rawDescription: Generate dynamic methods in a class

description: Generate dynamic methods in a class


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

import cherrypy

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}

class App:

  @cherrypy.expose
  def show_item_cgi(self, id):
    raise cherrypy.HTTPRedirect('https://google.com/search?q={0:d}'.format(int(id)))

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: CherryPy: Perform specific action if user goes to specific URL


code:
import ctypes as c

@c.CFUNCTYPE(None, c.c_int, c.c_int)
def callback(a, b):
    print("foo has finished its job (%d, %d)" % (a.value, b.value))

dll.foo(callback, a, b) # assuming a,b are ints

rawDescription: Callbacks with ctypes (How to call a python function from C)


code:
import xml.etree.ElementTree as ET

tree = ET.parse('C:/Users/Me/Documents/wurfl.xml')

root = tree.getroot()

dicto = {} #to store the data

for device in root.iter("device"): #parse out the device objects

    dicto[device.get("id")] = [0, 0, 0, 0] #set up a list to store the needed variables
    for child in device: #iterate through each device

        if child.get("id") == "product_info": #find the product_info id
            for grand in child:

                if grand.get("name") == "model_name": #and the model_name id
                    dicto[device.get("id")][0] = grand.get("value")
                    dicto[device.get("id")][3] +=1

        elif child.get("id") == "display": #and the display id
            for grand in child:

                if grand.get("name") == "physical_screen_height":
                    dicto[device.get("id")][1] = grand.get("value")
                    dicto[device.get("id")][3] +=1

                elif grand.get("name") == "physical_screen_width":
                    dicto[device.get("id")][2] = grand.get("value")
                    dicto[device.get("id")][3] +=1

    if not dicto[device.get("id")][3] == 3: #make sure I had enough
                                            #otherwise it's an incomplete dataset
        del dicto[device.get("id")]

arrays = []

for key in dicto.keys(): #sort this all into another list

    arrays.append(key)

arrays.sort() #and sort it alphabetically

with open('C:/Users/Me/Documents/wurfl1.js', 'w') as new: #now to write it out

    for item in arrays:

        new.write('{\n    id:"'+item+'",\n    Product_Info:"'+dicto[item][0]+'",\n    Height:"'+dicto[item][1]+'",\n    Width:"'+dicto[item][2]+'"\n},\n')

rawDescription: Parsing large XML data

description: Parsing large XML data


rawDescription: Defining precision of floating point number in Python


rawDescription: Python: Multi-Dimensional Array Using ctypes?


code:
from mock import patch

with patch.object(CommandServer, 'runSQL') as runSQL:
    class res(object):
       rowcount = -1

    runSQL.return_value = res

    p = Process()
    p.process()

    for c in runSQL.call_list:
        assert c[1].lstrip().startswith('insert into') is True

rawDescription: Using mock library to patch a class method


code: all(_ is None for _ in (x,y,z))

rawDescription: Better way to check multiple variables equal a single value in Python


code:
if any(obj.type == 'type 1' for obj in object_list):
    object_list = [obj for obj in object_list if obj.name != 'some_name']

rawDescription: How to check if an object in a list has a certain property

description: Check if an object in a list has a certain property


code:
class Gif(ndb.Model):
    author = ndb.UserProperty()
    link = ndb.StringProperty(indexed=False)
    # you store array of tag keys here you can also just make this
    # StringProperty(repeated=True)
    tag = ndb.KeyProperty(repeated=True)

    @classmethod
    def get_by_tag(cls, tag_name):
        # a query to a repeated property works the same as if it was a single value
        return cls.query(cls.tag == ndb.Key(Tag, tag_name)).fetch()

# we will put the tag_name as its key.id()
# you only really need this if you wanna keep records of your tags
# you can simply keep the tags as string too
class Tag(ndb.Model):
    gif_count = ndb.IntegerProperty(indexed=False)

rawDescription: Searching a many to many database using google datastore


code:
import os
cpstr = 'echo %(pass)s | sudo -S cp "%(from)s" "%(to)s"'
os.system(cpstr % {'pass':'userpassword', 'from':'./build/bin/myapp', 'to':'/bin/myapp'})

rawDescription: Python: how to copy files in /bin/ folder


code:
lst = [(0,1), (0, 2), (1, 0), (1, 3), (2,1)]
tuple(zip(*lst))    # make a tuple of tuples (or lists)
A=np.zeros((3,4),dtype=bool)  # make an array of False
A[tuple(zip(*lst))] = True  # assign True to the 5 values
A

rawDescription: Generate a 2D boolean array from tuples

description: Generate a 2D boolean array from tuples


code:
'''Seven segment display of hex digits.'''
import tkinter as tk
root = tk.Tk()
screen = tk.Canvas(root)
screen.grid()

# Order 7 segments clockwise from top left, with crossbar last.
# Coordinates of each segment are (x0, y0, x1, y1)
# given as offsets from top left measured in segment lengths.
offsets = (
    (0, 0, 1, 0),  # top
    (1, 0, 1, 1),  # upper right
    (1, 1, 1, 2),  # lower right
    (0, 2, 1, 2),  # bottom
    (0, 1, 0, 2),  # lower left
    (0, 0, 0, 1),  # upper left
    (0, 1, 1, 1),  # middle
)
# Segments used for each digit; 0, 1 = off, on.
digits = (
    (1, 1, 1, 1, 1, 1, 0),  # 0
    (0, 1, 1, 0, 0, 0, 0),  # 1
    (1, 1, 0, 1, 1, 0, 1),  # 2
    (1, 1, 1, 1, 0, 0, 1),  # 3
    (0, 1, 1, 0, 0, 1, 1),  # 4
    (1, 0, 1, 1, 0, 1, 1),  # 5
    (1, 0, 1, 1, 1, 1, 1),  # 6
    (1, 1, 1, 0, 0, 0, 0),  # 7
    (1, 1, 1, 1, 1, 1, 1),  # 8
    (1, 1, 1, 1, 0, 1, 1),  # 9
    (1, 1, 1, 0, 1, 1, 1),  # 10=A
    (0, 0, 1, 1, 1, 1, 1),  # 11=b
    (1, 0, 0, 1, 1, 1, 0),  # 12=C
    (0, 1, 1, 1, 1, 0, 1),  # 13=d
    (1, 0, 0, 1, 1, 1, 1),  # 14=E
    (1, 0, 0, 0, 1, 1, 1),  # 15=F
)

class Digit:
    def __init__(self, canvas, *, x=10, y=10, length=20, width=3):
        self.canvas = canvas
        l = length
        self.segs = []
        for x0, y0, x1, y1 in offsets:
            self.segs.append(canvas.create_line(
                x + x0*l, y + y0*l, x + x1*l, y + y1*l,
                width=width, state = 'hidden'))
    def show(self, num):
        for iid, on in zip(self.segs, digits[num]):
            self.canvas.itemconfigure(iid, state = 'normal' if on else 'hidden')

dig = Digit(screen)
n = 0
def update():
    global n
    dig.show(n)
    n = (n+1) % 16
    root.after(1000, update)
root.after(1000, update)
root.mainloop()

rawDescription: Seven segment display in Tkinter

description: Seven segment display in Tkinter


rawDescription: Multiple having statements in a SQLAlchemy query


code:
class MyClass(dict):
    def __init__(self, *args, **kwargs):
            self['mykey'] = 'myvalue'
            self['mykey2'] = 'myvalue2'
x = MyClass()
x['mykey']
x

rawDescription: Creating dictionaries with pre-defined keys


code:
import pyglet
from pyglet.gl import *
from ctypes import pointer, sizeof

window = pyglet.window.Window(width=800, height=800)

''' update function  '''
c = 0
def update(dt):
    global c
    c+=1
    data = calc_point(c)
    # if there's only on VBO, you can comment out the 'glBindBuffer' call
    glBindBuffer(GL_ARRAY_BUFFER, vbo_id)
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(data), data)

pyglet.clock.schedule(update)

''' draw function  '''
@window.event
def on_draw():

    glClear(GL_COLOR_BUFFER_BIT)
    glColor3f(0, 0, 0)

    glVertexPointer(2, GL_FLOAT, 0, 0)
    glDrawArrays(GL_POINTS, 0, 2)

''' calculate coordinates given counter 'c' '''
def calc_point(c):
    data = (GLfloat*4)(*[500+c, 100+c, 300+c, 200+c])
    return data

''' setup points '''
def setup_initial_points(c):
    vbo_id = GLuint()
    glGenBuffers(1, pointer(vbo_id))

    data = calc_point(c)
    glBindBuffer(GL_ARRAY_BUFFER, vbo_id)
    glBufferData(GL_ARRAY_BUFFER, sizeof(data), 0, GL_DYNAMIC_DRAW)

    return vbo_id

############################################

vbo_id = setup_initial_points(c)

glClearColor(0.2, 0.4, 0.5, 1.0)
glEnableClientState(GL_VERTEX_ARRAY)

glPointSize(10)
pyglet.app.run()

rawDescription: How to update data with a VBO and Pyglet

description: Update data with a VBO and Pyglet


code:
from tornado.concurrent import Future
from tornado import gen

@gen.coroutine
def f():
    resolved = Future()
    resolved.set_result(None)

    tasks = {}
    tasks['itemOne'] = make_network_call_one() if should_make_call_one else resolved
    tasks['itemTwo'] = make_network_call_two() if should_make_call_two else resolved
    tasks['itemThree'] = make_network_call_three() if should_make_call_three else resolved
    results = yield tasks

rawDescription: Python Tornado -- Make calls async?

description: Python Tornado -- Make calls async


code:
try:
    import cPickle as pickle  # Improve speed
except ValueError:
    import pickle

file_temp = open('temp', 'w')
pickle.dump(scenes, file_temp)
file_temp.close()

rawDescription: Python save variable to file like save() in MATLAB


rawDescription: Number of floats between two floats

description: Number of floats between two floats