code:
import Tkinter as tk

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.forms = []
        self.toolbar = tk.Frame(self)
        self.toolbar.pack(side="top", fill="x", expand=False)
        button2 = tk.Button(self.toolbar, text="2 columns", command=self.layout2col)
        button3 = tk.Button(self.toolbar, text="3 columns", command=self.layout3col)
        button2.pack(side="left")
        button3.pack(side="left")
        self.forms_frame = tk.Frame(self, borderwidth=2, relief="groove")
        self.forms_frame.pack(side="top", fill="both", expand="True", padx=2, pady=2)
        for i in range(6):
            frame = tk.LabelFrame(self.forms_frame, text="Form %s" % i)
            self.forms.append(frame)
            label = tk.Label(frame, text="Field %s" % i)
            entry = tk.Entry(frame, width=20)
            label.pack(side="left", fill="y")
            entry.pack(side="left", fill="both", expand=True)

        self.layout2col()

    def layout3col(self):
        self.forms[0].grid(column=0, row=0, padx=4, pady=2, sticky="ew")
        self.forms[1].grid(column=0, row=1, padx=4, pady=2, sticky="ew")
        self.forms[2].grid(column=1, row=0, padx=4, pady=2, sticky="ew")
        self.forms[3].grid(column=1, row=1, padx=4, pady=2, sticky="ew")
        self.forms[4].grid(column=2, row=0, padx=4, pady=2, sticky="ew")
        self.forms[5].grid(column=2, row=1, padx=4, pady=2, sticky="ew")
        self.forms_frame.grid_columnconfigure(0, weight=1)
        self.forms_frame.grid_columnconfigure(1, weight=1)
        self.forms_frame.grid_columnconfigure(2, weight=1)

    def layout2col(self):
        self.forms[0].grid(column=0, row=0, padx=4, pady=2, sticky="ew")
        self.forms[1].grid(column=0, row=1, padx=4, pady=2, sticky="ew")
        self.forms[2].grid(column=0, row=2, padx=4, pady=2, sticky="ew")
        self.forms[3].grid(column=1, row=0, padx=4, pady=2, sticky="ew")
        self.forms[4].grid(column=1, row=1, padx=4, pady=2, sticky="ew")
        self.forms[5].grid(column=1, row=2, padx=4, pady=2, sticky="ew")
        self.forms_frame.grid_columnconfigure(0, weight=1)
        self.forms_frame.grid_columnconfigure(1, weight=1)
        self.forms_frame.grid_columnconfigure(2, weight=0)

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

rawDescription: Using Python and TKinter, how do I redraw the main screen


code:
import Image
import ImageDraw
import ImageFont

def draw_underlined_text(draw, pos, text, font, **options):
    twidth, theight = draw.textsize(text, font=font)
    lx, ly = pos[0], pos[1] + theight
    draw.text(pos, text, font=font, **options)
    draw.line((lx, ly, lx + twidth, ly), **options)

im = Image.new('RGB', (400, 400), (255,)*3)
draw = ImageDraw.Draw(im)
font = ImageFont.truetype("arial.ttf", 50)

draw_underlined_text(draw, (50, 150), 'Hello PIL!', font, fill=0)
draw_underlined_text(draw, (50, 300), 'Test', font, fill=128)

im.show()

rawDescription: Draw underline text with PIL

description: Draw underline text with PIL


code:
def getItem(item_id):
    q = Item.all()
    q.filter("itemid = ", int(item_id))

rawDescription: Python appengine Query does not work when using a variable


code:
import ast
ast.parse("(1+2)*3", "", "eval")
ast.dump(_)

rawDescription: Evaluating mathematical expressions in Python


code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()

data = pd.DataFrame(np.random.rand(10,2))

gs = gridspec.GridSpec(2,2)

ax1=fig.add_subplot(gs[0,0])
ax2=fig.add_subplot(gs[0,1])
ax3=fig.add_subplot(gs[1,:])

data.plot(ax = ax1)
data.plot(ax = ax2)
data.plot(ax = ax3)

plt.show()

rawDescription: Fitting 3 subplots on the same figure

description: Fitting 3 subplots on the same figure


code:
oldfile = open("EXISTINGFILENAME", "r")
data = oldfile.read()
oldfile.close()
stripped_data = data.lstrip()
newfile = open("NEWFILENAME", "w")
newfile.write(stripped_data)
newfile.close()

rawDescription: How to remove all whitespace and newlines?

description: Remove all whitespace and newlines


code:
from csv import reader
nan_counts = {}
with open('/path/to/file') as file:
    file_reader = reader(file)
    next(file_reader)  # Skip the first row of headers
    for row in file_reader:
        year, data = row[1], row[4:]
        nan_counts[year] = data.count('NaN') + nan_counts.get(year, 0)

rawDescription: Calculate number of NaN's based on two separate unique columns


code:
import multiprocessing as mp

def square(x):
    for i in range(10000):
         j = i**2
    return x**2

if __name__ == '__main__':
    # pool=mp.Pool(processes=4)
    # pool.map(square,range(1000))
    # pool.close()
    for i in range(1000):
        square(i)

rawDescription: multiprocessing do not work

description: Multiprocessing do not work


code:
import datetime

def userorders(request):
    time_24_hours_ago = datetime.datetime.now() - datetime.timedelta(days=1)
    orders = Orders.objects.using('db1').filter(
        order_owner=request.user,
        order_started__gte=time_24_hours_ago
        ).extra(select={'order_ended_is_null': 'order_ended IS NULL',},)

rawDescription: How to fetch last 24 hours records from database

description: Fetch last 24 hours records from database


code: re.split("['-]", "pete - he's a boy")

rawDescription: Python : split string by ' and -

description: Python : split string by ' and -


code:
for x in list:
    foldername = 'bla/exp-{number}/exp-{number}-A/bls'.format(number = x)
    my_list.append(glob("/bla/bla/bla/" + foldername))

len(my_list)

rawDescription: make a list using format() in python

description: Make a list using format() in python


code: h = lambda x: f(x)+g(x)

rawDescription: Python : addition of lambda defined functions


code:
from calendar import monthrange
from datetime import datetime, timedelta

def monthdelta(d1, d2):
    delta = 0
    while True:
        mdays = monthrange(d1.year, d1.month)[1]
        d1 += timedelta(days=mdays)
        if d1 <= d2:
            delta += 1
        else:
            break
    return delta

rawDescription: Python: Difference of 2 datetimes in months


code:
soup.find_all("a", class_="sister")
# [Elsie,
#  Lacie,
#  Tillie]

rawDescription: direct search by a tag's class beautiful soup

description: Direct search by a tag's class beautiful soup


code:
import socket
sock = socket.socket()
sock.connect((address, port))

rawDescription: Best way to open a socket in Python

description: Open a socket in Python


code:
from functools import reduce # if you are using Python 3
d = {
  '0': {'key_x': 0, 'key_y': 15, 'key_z': 41},
  '1': {'key_x': 5, 'key_y': 22},
  '2': {'key_x': 6, 'key_y': 41}
}
reduce(set.intersection, map(set, d.values()))

rawDescription: Filter common sub-dictionary keys in a dictionary


code:
import sqlite3
import csv

con = sqlite3.connect('mydatabase.db')
outfile = open('mydump.csv', 'wb')
outcsv = csv.writer(outfile)

cursor = con.execute('select * from mytable')

# dump column titles (optional)
outcsv.writerow(x[0] for x in cursor.description)
# dump rows
outcsv.writerows(cursor.fetchall())

outfile.close()

rawDescription: dump csv from sqlalchemy

description: Dump csv from sqlalchemy


rawDescription: Make a numpy array monotonic without a Python loop


code:
from kivy.app import App
from kivy.uix.screenmanager import Screen

from kivy.lang import Builder

gui = '''
LoginScreen:

    GridLayout:
        cols: 2

        Label:
            text: 'Subject'

        Label:

        Label:
            text: '1'

        SingleLineTextInput:

        Label:
            text: '2'

        SingleLineTextInput:

        Label:
            text: '3'

        SingleLineTextInput:

        Label:
            text: '4'

        SingleLineTextInput:

        GreenButton:
            text: 'Exit'
            on_press: app.stop()

        GreenButton:
            text: 'Run'

<SingleLineTextInput@TextInput>:
    multiline: False

<GreenButton@Button>:
    background_color: 0, 1, 0, 1
    size_hint_y: None
    height: self.parent.height * 0.111
'''

class LoginScreen(Screen):
    pass

class SimpleKivy(App):

    def build(self):
        return Builder.load_string(gui)

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

rawDescription: How to set a height to some buttons of GridLayout in Kivy Python?

description: Set a height to some buttons of GridLayout in Kivy Python


code:
from collections import defaultdict

dd = defaultdict(list)
for i in some_list_of_items:
    for k, v in dict_from_an_item(i).iteritems():
        dd[k].extend(v)

rawDescription: Pythonic update of a `defaultdict`

description: Pythonic update of a `defaultdict`


code:
r = redis.StrictRedis()
r.config_get('databases')
r.info('keyspace')

rawDescription: How to get all the databases stored in redis using python

description: Get all the databases stored in redis using python


code:
"""
a) First took all the keys of dictionary and sorted it, which is not necessary.
b) Created a result list which appends value related the headers which is key of our input dict and if key is not available then .get() will return None.
   So result list will contain lists for rows data.
c) Wrote header and each row from result list in csv file
"""

data_dict = [{ "Header_1":"data_1", "Header_2":"data_2", "Header_3":"data_3"},
             { "Header_1":"data_4", "Header_2":"data_5", "Header_3":"data_6"},
             { "Header_1":"data_7", "Header_2":"data_8", "Header_3":"data_9", "Header_4":"data_10"},
             { "Header_1":"data_11", "Header_3":"data_12"},
             { "Header_1":"data_13", "Header_2":"data_14", "Header_3":"data_15"}]

"""
   In the third dict we have extra key, value.
   In forth we dont have have header_2 were we aspect blank value in our csv file.
"""
process_data = [ [k,v] for _dict in data_dict for k,v in _dict.iteritems() ]

headers = [ i[0] for i in process_data ]
headers = sorted(list(set(headers)))

result = []
for _dict in data_dict:
    row = []
    for header in headers:
        row.append(_dict.get(header, None))
    result.append(row)

import csv
with open('demo.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=';', dialect='excel',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(headers)
    for r in result:
        spamwriter.writerow(r)

rawDescription: Using DictWriter to write a CSV when the fields are not known beforehand


code:
#!/usr/bin/python

import os  # We need this module

# Get path of the current dir, then use it to create paths:
CURRENT_DIR = os.path.dirname(__file__)
file_path = os.path.join(CURRENT_DIR, 'test.txt')

# Then work using the absolute paths:
f = open(file_path,'w')
f.write('testing the script')

rawDescription: Running a Python Script Inside Another Directory


code:
WSGIScriptAlias /django1 /home/keratacon/www/django1/wsgi.py
WSGIScriptAlias /django2 /home/keratacon/www/django2/wsgi.py

rawDescription: How to deploy Django application at sub-url?

description: Deploy Django application at sub-url


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

def truncated_power_law(a, m):
    x = np.arange(1, m+1, dtype='float')
    pmf = 1/x**a
    pmf /= pmf.sum()
    return stats.rv_discrete(values=(range(1, m+1), pmf))

a, m = 2, 10
d = truncated_power_law(a=a, m=m)

N = 10**4
sample = d.rvs(size=N)

plt.hist(sample, bins=np.arange(m)+0.5)
plt.show()

rawDescription: Sample a truncated integer power law in Python?


code:
class ChildFoo(ParentFoo):
    def __init__(self, a, b, d, e, f=None):
         ParentFoo.__init__(self, a, b, c="fing")

rawDescription: inheritance -- keyword and regular arguments in parent class

description: Inheritance -- keyword and regular arguments in parent class


code:
result = [{u'broadcast_part': 6, u'featured': True, u'channel_subscription': True, u'embed_count': 0, u'id': u'9602378624', u'category': u'gaming', u'title': u'5x Legend - Playing the TOP DECKS from DECK WARS to Legendary! Handlock, Miracle and Shaman. (Never played Shaman EVUR)', u'video_height': 1080, u'site_count': 0, u'embed_enabled': False, u'channel': {u'category': u'gaming', u'status': u'5x Legend - Playing the TOP DECKS from DECK WARS to Legendary! Handlock, Miracle and Shaman. (Never played Shaman EVUR)', u'views_count': 56403101, u'subcategory': None, u'language': u'en', u'title': u'kungentv', u'screen_cap_url_huge': u'http://static-cdn.jtvnw.net/previews/live_user_kungentv-630x473.jpg', u'producer': True, u'tags': None, u'subcategory_title': u'', u'category_title': u'', u'screen_cap_url_large': u'http://static-cdn.jtvnw.net/previews/live_user_kungentv-320x240.jpg', u'mature': None, u'screen_cap_url_small': u'http://static-cdn.jtvnw.net/previews/live_user_kungentv-70x53.jpg', u'screen_cap_url_medium': u'http://static-cdn.jtvnw.net/previews/live_user_kungentv-150x113.jpg', u'timezone': u'Europe/Stockholm', u'login': u'kungentv', u'channel_url': u'http://www.justin.tv/kungentv', u'id': 30383713, u'meta_game': u'Hearthstone: Heroes of Warcraft'}, u'up_time': u'Mon May 19 00:34:43 2014', u'meta_game': u'Hearthstone: Heroes of Warcraft', u'format': u'live', u'stream_type': u'live', u'channel_count': 3671, u'abuse_reported': False, u'video_width': 1920, u'geo': u'SE', u'name': u'live_user_kungentv', u'language': u'en', u'stream_count': 0, u'video_bitrate': 3665.328125, u'broadcaster': u'obs', u'channel_view_count': 0}]
result[0]['broadcast_part']

rawDescription: Python unicode dictornary to string from twitch stream


code:
import collections

counts = collections.defaultdict(lambda: 0)
for fileid in corpus.fileids():
    for sentence in corpus.sents(fileid):
        cat = str(fileid.split('/')[0])
        s = " ".join(sentence)
        counts[cat] += len(re.findall('(:\)|:\(|:\s|:\D|:\o|:\@)+', s))

rawDescription: group number of counts by category

description: Group number of counts by category


code: data = sorted(enumerate(list), key=operator.itemgetter(1))[:5]

rawDescription: Find indices of x minimum values of a list


code:
import os, sys

# Specify directory
# In your case, you may want something like the following
my_directory = 'C:/Users/<user_name>/Documents/ZoneA'

# Define the counter
counter = 1

# Start the loop
for folder, sub_folders, files in os.walk(my_directory):
  for special_file in files:
    if special_file == 'math.txt':
      file_path = os.path.join(folder, special_file)

      # Open and read
      with open(file_path, 'r+') as read_file:
        print('Reading math txt file ' + str(counter))

        # Print the file
        for line in read_file:
           print(line)

        # Increment the counter
        counter += 1

rawDescription: Python how to access subfolder of subfolders


code:
tables = {
    'e': ('unit1', 'unit2', ...),   # tablename: tuple of column names
}

def generate_conditions(table_name, nameValues):
    if table_name not in tables:
        raise ValueError('No such table %r' % table_name)
    sql = u""
    params = []
    for field in nameValues:
        if field not in tables[table_name]:
            raise ValueError('No such column %r' % field)
        sql += u" AND {0}.{1}=?".format(table_name, field)
        params.append(nameValues[field])
    return sql, params

search_query = u"SELECT * FROM Enheter e LEFT OUTER JOIN Handelser h ON e.Id == h.Enhet WHERE 1=1"

search_params = []
if "Enhet" in args:
    sql, params = generate_conditions("e",args["Enhet"])
    search_query += sql
    search_params.extend(params)
c.execute(search_query, search_params)

rawDescription: Escaping dynamic sqlite query?

description: Escaping dynamic sqlite query


code:
urlpatterns = patterns('',
    url(r'^$', ConfigHomeView.as_view(),
        name='config_home'),

    url(r'^address_labels/create$', AddressLabelCreateView.as_view(),
        name='address_label_create'),
)

rawDescription: Django resolves one URL pattern, but not the other


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

class Mainwindow(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        self.worker = Worker()
        self.thread = QThread()
        self.worker.moveToThread(self.thread)
        self.worker.workRequested.connect(self.thread.start)
        self.thread.started.connect(self.worker.add_tabs)
        self.worker.finished.connect(self.on_finish)

        self.button=QPushButton("Add tabs")
        self.button.clicked.connect(self.on_button_click)

        self.button_responsive=QPushButton("Still responsive?")
        self.button_responsive.clicked.connect(self.responsive)

        self.progress = QProgressDialog("Progress","cancel",0,10)
        self.progress.setCancelButton(None)
        self.worker.relay.connect(self.update_progress)

        vbox=QVBoxLayout()
        vbox.addWidget(self.button)
        vbox.addWidget(self.button_responsive)
        self.setLayout(vbox)

    def on_button_click(self):
        self.button.setEnabled(False)
        self.worker.request_work()
        self.progress.setValue(0)

    def on_finish(self):
        self.button.setEnabled(True)
        self.thread.quit()

    def update_progress(self,value):
        self.progress.setValue(value)

    def responsive(self):
        print("Yes!")

class Worker(QObject):
    workRequested=Signal()
    finished=Signal()
    relay=Signal(int)

    def __init__(self, parent=None):
        super(Worker, self).__init__(parent)
        self.x = 0

    def request_work(self):
        self.workRequested.emit()

    def add_tabs(self):
        self.x=0
        for i in range(10):
            #Do any processing
            for i in xrange(10000):
                i*i
            time.sleep(1)
            self.x+=1
            self.relay.emit(self.x)
        self.finished.emit()

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

rawDescription: How to create a loading progress bar like we see in Photoshop with PySide,PyQt

description: Create a loading progress bar like we see in Photoshop with PySide,PyQt


code:
text = "['abc@gmai.com','abc@gmail.com','abc@gmail.com']"
import ast
ast.literal_eval(text)
type(ast.literal_eval(text))

rawDescription: Convert a String into python list that is already in list format


code:
th = np.linspace(0, 2 * np.pi, 64)
y = np.sin(th)
ax = plt.gca()

lin, = ax.plot(th, y, lw=5)
mark, = ax.plot(th, y, marker='o', alpha=.5, ms=10)

ax.legend([(lin, mark)], ['merged'])
plt.draw()

rawDescription: Matplotlib - How to make the marker face color transparent without making the line transparent


rawDescription: Create (L[i], L[i+1]) tuple list from list L


code:
def square(x):
    return x**2

rawDescription: Why is pool.map slower than normal map?

description: Why is pool.map slower than normal map


code:
class Explosion(pygame.sprite.Sprite):
    def __init__(self, x, y):
        #boilerplate code, loading images, just as you did, etc...
        self.x = x
        self.y = y
        self.counter = 0
        self.all_images = your_list_of_sprites
        self.displayed_image = all_images[0]

    def update(self):
        self.counter += 1
        next_frame = self.counter / someMagicInteger
        if len(self.all_images) > next_frame:
            self.displayed_image = self.all_images[next_frame]
        else:
            self.kill()

rawDescription: Slow down the range function

description: Slow down the range function


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

class frmMain(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.btStart = QPushButton('Start')
        self.btStop = QPushButton('Stop')
        #self.counter = QSpinBox()
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.btStart)
        self.layout.addWidget(self.btStop)
        #self.layout.addWidget(self.counter)
        self.setLayout(self.layout)
        self.btStart.clicked.connect(self.start_thread)
        self.btStop.clicked.connect(self.stop_thread)
        self.boxes = []
        self.threads = []

    def stop_thread(self):
        for th in self.threads:
            th.terminate()

    def loopfunction(self, n, index):
        self.boxes[index].setValue(n)

    def start_thread(self):
        index = len(self.threads)
        th = thread(index)
        th.loop.connect(self.loopfunction)
        th.setTerminationEnabled(True)
        th.start()
        self.threads.append(th)
        self.boxes.append(QSpinBox())
        self.layout.addWidget(self.boxes[index])

class thread(QThread):
    loop = Signal(int, int)

    def __init__(self, index):
        QThread.__init__(self)
        self.index = index

    def run(self):
        for n in range(20):
            self.loop.emit(n, self.index)
            time.sleep(0.5)

app = QApplication(sys.argv)
win = frmMain()

win.show()
sys.exit(app.exec_())

rawDescription: Run multiple qthreads concurrently in Python


code:
f = open("primenumber.lst", "r+")

for i in range(startnumber,highest + 1):      # loop to the highest number
    if str(i)[-1] in ('1', '3', '7', '9'):
        f.seek(0)
        root = int(i ** 0.5)
        for line in f:                       # read *some* primes in the file
            line_str = line.split(';')
            x = int(line_str[1])

            if i % x == 0:
                break
            if x > (root):                   # shortcut when we reach the root
                counter += 1
                distance = i - previous
                previous = i
                write_prime(counter, i, distance)  # No seek before write!
                f.flush()
                break

rawDescription: Python script appends to an existing file but stops after 8192 bytes


code:
reg.sub(rpl, my_string )
reg.sub(lambda x: rpl, my_string )

rawDescription: Python unescaping string in regex replacements


rawDescription: Java - Python - Is there an equivalent of java's Character.getNumericValue in Python?


code:
import subprocess
import os

def is_filesys_fat32(path):

    try:
        subprocess.check_call(['df', '--type=fat32', path], stdout=os.devnull)
    except:
        return False

    return True

rawDescription: how do I know if a "path" is located in a FAT32 partition?

description: Know if a "path" is located in a FAT32 partition


code: getattr(MyModel, attrib_name)

rawDescription: Using string to access datastore column

description: Using string to access datastore column


code:
df = DataFrame({'A' : np.random.randn(9)},index=pd.MultiIndex.from_product([range(3),list('abc')],names=['first','second']))
df
idx = pd.IndexSlice
df.loc[idx[:,'b'],]
df.loc[idx[slice(None),'b'],]
df.loc[(slice(None),'b'),]

rawDescription: Python pandas, how can I pass a colon ":" to an indexer through a variable


code:
m = a_matrix.copy()     # a copy we can change without altering the orignal
c = cluster_1           # an alias to save typing

# Naked NumPy doesn't seem to have a cartesian product, so roll our own
for i in range(c.shape[1]):
    for j in range(c.shape[1]):
        if m[c[0,i]-1,c[1,j]-1]:
            m[c[0,i]-1,c[1,j]-1] = 2

plt.matshow(m, cmap='jet', interpolation='nearest')
plt.show()

rawDescription: How to change colour of certain elements of a matrix in matplotlib matshow?

description: Change colour of certain elements of a matrix in matplotlib matshow


code:
def somefunc():
    pass # do something

class MyClass(object):
    def __init__(self, pos, function):
        self.pos = pos
        self.function = function

myclass = MyClass(0, somefunc)

rawDescription: use functions in a class - python

description: Use functions in a class - python


code:
print("Option A: Show a record\nOption Q: Quit")
decision = input("Enter A or Q: ").lower()
myList = []

if decision == "a":
    myFile = open("Payments.txt")
    customer_number = input("Enter a customer number to view their details: ")
    record = myFile.readlines()
    for line in record:
        if customer_number in line:
            myList.append(line.strip().replace("'","").split(','))
            for info in myList:
                print("Customer number: ", info[0])
                print("Date of payment: ", info[1])
                print("Payment Amount: ", info[2])
                print("Paid Amount: ", info[4])
    myFile.close()

elif decision == "q":
    exit()

rawDescription: Merging two for loops together under an if statement


code:
get = operator.itemgetter(4,5)
w_topic = [get(line.split()) for line in lines]

rawDescription: how to write this in one line in the python way?

description: Write this in one line in the python way


code:
from sphinx.highlighting import PygmentsBridge
from pygments.formatters.latex import LatexFormatter

class CustomLatexFormatter(LatexFormatter):
    def __init__(self, **options):
        super(CustomLatexFormatter, self).__init__(**options)
        self.verboptions = r"formatcom=\footnotesize"

PygmentsBridge.latex_formatter = CustomLatexFormatter

rawDescription: How do you change the code example font size in LaTeX PDF output with sphinx?

description: Change the code example font size in LaTeX PDF output with sphinx


code:
from matplotlib.ticker import FuncFormatter
import matplotlib.pyplot as plt
from matplotlib import rc
import numpy as np

rc('text', usetex=True)

formatter = FuncFormatter(lambda x_val, tick_pos: "$2^{{+{:.0f}}}$".format(np.log2(x_val)))

x = np.array([1, 2, 4, 8, 16])
y = np.array([1, 2, 1, 2, 1])
fig, ax = plt.subplots()
ax.xaxis.set_major_formatter(formatter)
plt.plot(x, y)
plt.show()

rawDescription: Put a function of x as the x tick labels


rawDescription: Multiple pipelines that merge within a sklearn Pipeline?


code:
from collections import deque
from StringIO import StringIO

with open(fname, 'r') as f:
    q = deque(f, 2)  # replace 2 with n (lines read at the end)

In [12]: q
Out[12]: deque(['7,8,9\n', '10,11,12'], maxlen=2)
         # these are the last two lines of my csv

In [13]: pd.read_csv(StringIO(''.join(q)), header=None)

rawDescription: Efficiently Read last 'n' rows of CSV into DataFrame


code:
input_dict = function_to_get_input_dict()
filtered_dict = {}
for metric in input_dict['data']:
    for day in metric['values']:
        parsed_date = parser.parse(day['end_time'])
        date_key = parsed_date.strftime('%m/%d/%Y')
        filtered_dict[date_key] = {}
        filtered_dict[date_key]['Total %s' % metric['title']] = 0
        for k, v in day['value'].iteritems():
            filtered_dict[date_key]['%s : %s' % (metric['title'], k)] = v
            filtered_dict[date_key]['Total %s' % metric['title']] += v
pprint(filtered_dict) #debug

rawDescription: Why is this dictionary overwriting itself during for loop?


code:
ind=np.arange(99)  # multple of 3
ind=ind.reshape(-1,3)
rng.shuffle(ind)
ind.flatten()

rawDescription: How to efficiently shuffle numpy array in chunks

description: Efficiently shuffle numpy array in chunks


code:
import socket

orig_timeout = socket.getdefaulttimeout(timeout)
socket.setdefaulttimeout(timeout)

s = nntplib.NNTP(self.nserver, 119, self.nuser, self.npass)

socket.setdefaulttimeout(orig_timeout)

rawDescription: Program gets stuck attempting to create NNTP connection


code:
from __future__ import print_function
import json

response = """{
    'ok': 1.0,
    'result': [
        {
            'total': 142250.0,
            '_id': 'BC'
        },
        {
            'total': 210.88999999999996,
             '_id': 'USD'
        },

        {
            'total': 1065600.0,
            '_id': 'TK'
        }
        ]
}"""

# JSON requires double-quotes, not single-quotes.
response = response.replace("'", '"')
response = json.loads(response)
for doc in response['result']:
    print(doc['_id'], doc['total'])

rawDescription: Parsing Nested JSON using Python

description: Parsing Nested JSON using Python


code:
from oauth2_provider.models import AccessToken, Application
from braces.views import CsrfExemptMixin
from oauth2_provider.views.mixins import OAuthLibMixin
from oauth2_provider.settings import oauth2_settings

class TokenView(APIView, CsrfExemptMixin, OAuthLibMixin):
    permission_classes = (permissions.AllowAny,)

    server_class = oauth2_settings.OAUTH2_SERVER_CLASS
    validator_class = oauth2_settings.OAUTH2_VALIDATOR_CLASS
    oauthlib_backend_class = oauth2_settings.OAUTH2_BACKEND_CLASS

    def post(self, request):
        username = request.POST.get('username')
        try:
            if username is None:
                raise User.DoesNotExist
            AccessToken.objects.filter(user=User.objects.get(username=username), application=Application.objects.get(name="Website")).delete()
        except Exception as e:
            return Response(e.message,status=400)

        url, headers, body, status = self.create_token_response(request)
        return Response(body, status=status, headers=headers)

rawDescription: Generating single access token with Django OAuth2 Toolkit


code:
class MyModel(models.Model):
    ...
    def clean(self):
        if not self.image and not self.color.strip():
            raise ValidationError('You must specify either an image or color')

rawDescription: Creating Custom Field: how to mix ImageField and ColorField?


code:
if count_int > 1:
    for i in range(count_int):
        turtle.begin_fill()
        turtle.forward(100)
        turtle.right(90)
        turtle.forward(100)
        turtle.right(90)
        turtle.forward(100)
        turtle.right(90)
        turtle.forward(100)
        turtle.end_fill()

        turtle.up()
        turtle.forward(20)
        turtle.color(random.random(),random.random(), random.random())

rawDescription: python turtle loop

description: Python turtle loop


code:
html_code = urllib2.urlopen("xxx")
html_code_list = html_code.readlines()
data = ""
for line in html_code_list:
    line = line.strip()

    if line.startswith("<h2"):
       data = data+line

hp = MyHTMLParser()
hp.feed(data)
hp.close()

rawDescription: Python and HTMLParser.handle_data() - How to get data from tags?


code:
def g(x):
    return 2 * x ** 2 + x + 5

rawDescription: Why is it considered 'powerful' to pass a function as a parameter?


code:
def keyfunc(k):
    return structure[k]['sorting']
sorted(structure, key=keyfunc)

rawDescription: Python: Get dictionary keys as list sorted by sub dictionary value


code:
from utils import options

use_pyqt5 = False

if options.try_pyqt5:

    try:
        import PyQt5
        use_pyqt5 = True
    except ImportError:
        pass

rawDescription: What't the common way to support both PyQt4 and PyQt5 in one application?


code:
import numpy as np
import scipy.signal as sps
import matplotlib.pyplot as plt

np.random.seed(123)

# create an example signal
x = []
ofs = 3.4
slope = 0.002
for t in np.linspace(0, 100, 1000):
    ofs += slope
    x.append(np.sin(t*2) * 0.1 + ofs)
    if x[-1] > 4:
        ofs =3.2
        slope = np.random.rand() * 0.003 + 0.002
x = np.asarray(x)
plt.plot(x, label='original')

# detect and remove jumps
jmps = np.where(np.diff(x) < -0.5)[0]  # find large, rapid drops in amplitdue
for j in jmps:
    x[j+1:] += x[j] - x[j+1]
plt.plot(x, label='unrolled')

# detrend with a low-pass
order = 200
x -= sps.filtfilt([1] * order, [order], x)  # this is a very simple moving average filter
plt.plot(x, label='detrended')

plt.legend(loc='best')
plt.show()

rawDescription: Detrend or Filter a sawtooth signal (Python)


code:
def find(self, key):
    if key == self.key:
        return self.data
    if key < self.key and self.left:
        return self.left.find(key)
    if key > self.key and self.right:
        return self.right.find(key)
    raise KeyError("No such thing")

rawDescription: Raising an Exception from recursive generator function


rawDescription: Django: filtering order_by a generic relation


rawDescription: Convert String to Dict or List in Python?


code:
with open('infile.txt', 'rb') as infile, open('outfile.txt', 'wb') as outfile:
    outfile.writelines(line[:15] + '32' + line[15:] for line in infile)

rawDescription: add new digits to a column of a text file in Python

description: Add new digits to a column of a text file in Python


code:
import re
re.match('llo', 'hello')   # only match at the beginning
re.search('llo', 'hello')  # match anywhere

rawDescription: Unable to match a regex pattern

description: Unable to match a regex pattern


code:
import dir1
if __name__ == '__main__':
    __package__ = 'dir1.dir2'
    from .. import in_dir1

rawDescription: Python relative imports within a package not on the path


rawDescription: Join 2 DataFrames on an index without introducing nans on missing indices


code: spam_list = [spam_list[i] for i in spam_order]

rawDescription: In-place way to apply a permutation to a list? (inverse of sorting-by-key)


code:
fig.xgrid.grid_line_color = None
fig.ygrid.grid_line_color = None

rawDescription: How do I remove grid lines from a Bokeh plot?

description: Remove grid lines from a Bokeh plot


code:
f = open('report.xls', 'wb')
for uchar in driver.page_source:
    f.write(bytearray([ord(uchar)]))
f.close()

rawDescription: How to write driver.page_source to a binary file?

description: Write driver.page_source to a binary file


code:
ax = gca()
ax.set_aspect(2)
plt.draw()

rawDescription: Plot line after line with imshow

description: Plot line after line with imshow


rawDescription: Maximum key value from dictionary

description: Maximum key value from dictionary


code: return getattr(np, input)(matrix, axis=1)

rawDescription: Calculating mean or median in one function in numpy


code:
class CreateDocumentWizard(SessionWizardView):

    ...

    def render(self, form=None, **kwargs):
        name_details_count = NameDetails.objects.filter(user=self.request.user).count()

        # redirect user if no name details held.
        if name_details_count < 1:
            return HttpResponseRedirect('document_start')

        return super(CreateDocumentWizard, self).render(form, **kwargs)

rawDescription: django form wizard redirect

description: Django form wizard redirect


code: a = min(a, b)

rawDescription: Is there a shorter way of writing 'if a > b: a = b' in python?


code:
for i, e in enumerate(myList):
    key = e[e.index("_"):]
    if key not in myDict: continue
    myList[i] = myDict[key]

rawDescription: How to replace strings in a list by numbers based on their endings?

description: Replace strings in a list by numbers based on their endings


code:
def incrementKeys(infilepath, outfilepath, keys, incrementBy):
    with open(infilepath) as infile, open(outfilepath, 'w') as outfile:
        for line in infile:
            if any(line.startswith(key) for key in keys):
                k, tail = line.split(',')
                k, val = k.split(":")
                val = int(val)+incrementBy
                line = "%s:%d,%s\n" %(k, val, tail)
            outfile.write(line)

rawDescription: grep each line of a file, and increment values

description: Grep each line of a file, and increment values


code:
#!/usr/bin/env noscript=True python
import os
if os.getenv('noscript'):
    print("called as executable")
else:
    print("called as script")

rawDescription: Distinguishing between when a script is ran 'directly', or with Python executable


code:
for i in range(5):
    print ("Search for " + str(i) + " element(s), has taken: " + "{0:.2f}".format(round(locals()['time'+str(i+1)],2)))

rawDescription: Assigning index of a for to a variable noun


code:
sc.textFile("test.txt")\
  .map(lambda line: (line.split(',')[0], line.split(',')[1]))\
  .distinct()\
  .count()

rawDescription: PySpark distinct().count() on a csv file


code:
ax = gca()
ax.axhline(.5, linestyle='--')
trans = matplotlib.transforms.blended_transform_factory(
    ax.transAxes,
    ax.transData)

ax.annotate('label', xy=(1.01, .5), xycoords=trans, clip_on=False, va='center')
ax.set_xlim([0,2])
plt.draw()

rawDescription: Add tick labels on right yaxis in matplotlib


code:
m = patsy.ModelDesc.from_formula("xvar + np.log(xvar)+xvar**2 + xvar2")
m
m.rhs_termlist.remove(patsy.Term([patsy.EvalFactor('xvar')]))
m

rawDescription: Removing Terms from Patsy Formulas with re


code:
def new_path(fcheck,fpath):
    """
    fcheck --> filename to check
    fpath  --> file with path component to transfer
               if fcheck has no path component
    """
    head,tail = os.path.split(fcheck)
    return os.path.join(os.path.split(fpath)[0],tail) if not head else fcheck

new_path('foo/bar','baz/qux')   #'foo/bar'  -- has path component.  Leave alone
new_path('bar','baz/qux')       #'baz/bar'  -- No path component.  Transfer
new_path('bar','qux')           #'bar'      -- Neither has path component.  Path must be '.'.  Leave alone.

rawDescription: Common pathname manipulations to save in a specific directory a file


code:
out = []
f = open('test.txt', 'r').read().split('\n')
for i in xrange(0,3):
    out.append(f[i].split()[i])

rawDescription: How to read a number on specific column and line in Python?

description: Read a number on specific column and line in Python


rawDescription: Python regex .match failing to match in strings returned from a C++ process via subprocess


code:
import datetime
import numpy as np
now = np.datetime64(datetime.datetime.now())
(now.astype('uint64') / 1e6).astype('uint32')

rawDescription: How to get unix timestamp from numpy.datetime64

description: Get unix timestamp from numpy.datetime64


code: 'Peter' == d[coursename]['assistant']

rawDescription: Finding membership in Python dictionary

description: Finding membership in Python dictionary


code:
#Calculator
print("This is a program that can be used as a calculator")
print("Press 1 to add two numbers")
print("Press 2 to subtract two numbers")
print("Press 3 to divide two numbers")
print("Press 4 to multiply two numbers")

while True:
    Selection=input("What do you want to choice")
    if Selection  in("1"):
        add1=input("Input your first number")
        add2=input("Input your second number")
        resultAdd= int(add1+add2)
        print ("Your result is ", resultAdd)

    elif Selection in("2"):
        subtract1= input("Input your first number")
        subtract2= input("Input your second number")
        resultSubtract= int(subtract1-subtract2)
        print ("Your result is ", resultSubtract)

    elif Selection in("3"):
        divide1= input("Input your first number")
        divide2= input("Input your second number")
        resultDivide= int(divide1/divide2)
        print ("Your result is ",resultDivide)

    elif Selection in("4"):
        multiply1=input("Input your first number")
        multiply2=input("Input your second number")
        resultMultiply= int (multiply1*multiply2)
        print("Your result is ", resultMultilpy)

        break
    else:
        print("Invalid respnse")

rawDescription: "elif" is said to be the invalid syntax

description: "elif" is said to be the invalid syntax


code:
import subprocess
import os

def is_tool(name):
    try:
        devnull = open(os.devnull)
        subprocess.Popen([name], stdout=devnull, stderr=devnull).communicate()
    except OSError as e:
        if e.errno == os.errno.ENOENT:
            return False
    return True

rawDescription: Check if a program exists from a python script


code:
import random

def gen(n):
    for i in xrange(n):
        if random.randint(0, 1) == 0:
            yield i

iterator = gen(10)

rawDescription: Getting number of elements in an iterator in Python


code:
LOW = 0
NORMAL = 1
HIGH = 2
STATUS_CHOICES = (
    (LOW, 'Low'),
    (NORMAL, 'Normal'),
    (HIGH, 'High'),
)

rawDescription: Set Django IntegerField by choices=... name


code:
class StoreSpider (CrawlSpider):
    name = "storyder"

    allowed_domains = ["example.com"]
    start_urls = ["http://www.example.com/"]

    rules = (
        Rule(LinkExtractor(restrict_css=("#movies", "#books"))),
        Rule(LinkExtractor(), callback="parse_item"),
    )

def parse_item(self, response):
    item = StoreItem()
    # some code for extracting the item's data
    return item

rawDescription: How to feed a spider with links crawled within the spider?

description: Feed a spider with links crawled within the spider


code:
DataFrame.from_records([(int(word['x1']), int(word['x2']))
                        for word in soup.page.findAll('word')],
                       columns=('x1', 'x2'))

rawDescription: XML to pandas dataframe

description: XML to pandas dataframe


code:
from django.core.urlresolvers import reverse

@register.simple_tag(takes_context=True)
def kwargy_url(context, view_str, kwargs):
    ...
    return reverse(view_str, kwargs=kwargs)

# {% kwargy_url 'myapp.views.myview' kwarg_var %}

rawDescription: Django 1.6 templates Is it possible to wrap the {% url %} so it can take ** arguements? How?


code:
from django.contrib.sitemaps import Sitemap

class LimitSitemap(Sitemap):
    limit = 500

class BlogSitemap(LimitSitemap):
    def items(self):
        return Entry.objects.all()

rawDescription: How do I split sitemaps with Django (programatically)?

description: Split sitemaps with Django (programatically)


code:
def decode_heuristically(string, enc = None, denc = sys.getdefaultencoding()):
    """
    Try to interpret 'string' using several possible encodings.
    @input : string, encode type.
    @output: a list [decoded_string, flag_decoded, encoding]
    """
    if isinstance(string, unicode): return string, 0, "utf-8"
    try:
        new_string = unicode(string, "ascii")
        return string, 0, "ascii"
    except UnicodeError:
        encodings = ["utf-8","iso-8859-1","cp1252","iso-8859-15"]

        if denc != "ascii": encodings.insert(0, denc)

        if enc: encodings.insert(0, enc)

        for enc in encodings:
            if (enc in ("iso-8859-15", "iso-8859-1") and
                re.search(r"[\x80-\x9f]", string) is not None):
                continue

            if (enc in ("iso-8859-1", "cp1252") and
                re.search(r"[\xa4\xa6\xa8\xb4\xb8\xbc-\xbe]", string)\
                is not None):
                continue

            try:
                new_string = unicode(string, enc)
            except UnicodeError:
                pass
            else:
                if new_string.encode(enc) == string:
                    return new_string, 0, enc

        # If unable to decode,doing force decoding i.e.neglecting those chars.
        output = [(unicode(string, enc, "ignore"), enc) for enc in encodings]
        output = [(len(new_string[0]), new_string) for new_string in output]
        output.sort()
        new_string, enc = output[-1][1]
        return new_string, 1, enc

rawDescription: how to decode a non unicode character in python?

description: Decode a non unicode character in python


code:
url = "http://abcdef.com/picture.jpg"
data = urllib.request.urlopen(url).read()
file = open("image.jpg", "wb")
file.write(data)
file.close()
worksheet.insert_image('B2', 'image.jpg')

rawDescription: Python Excel Writer (xlswriter) Insert Image from URL


code:
import pygame

screen = pygame.display.set_mode([800, 800], 0, 32)
#initiates screen

image1 = pygame.image.load('testimage0.jpg')
#testimage0.jpg is loaded into the variable image1

image2 = pygame.image.load('testimage.png').convert_alpha()
#testimage.png is loaded into the variable image2

while True:
    screen.fill([0, 0, 0])
    #screen is filled with a black background

    screen.blit(image1, [200, 200])
    #here image1 is blitted onto screen at the coordinates (200,200)

    image1.blit(image2, [0, 0])
    #here image2 is blitted onto image1 at the coordinates (0,0) which starts at the upper left of image1

    pygame.display.update()
    #updates display, which you can just ignore

rawDescription: How to blit an image, in python, inside the area of a specific image?

description: Blit an image, in python, inside the area of a specific image


code:
# Imports
import numpy
import pylab
import scipy
import sklearn.cluster

# Set up original data - note that it's monotonically increasing by X value!
data = {}
data['original'] = {}
data['original']['x'] = [0, 5024.2059124920379, 7933.1645067836089, 7990.4664106277542, 9879.9717114947653, 13738.60563208926, 15113.277958924193]
data['original']['y'] = [0.0, 3072.5653360000988, 5477.2689107965398, 5851.6866463790966, 6056.3852496014106, 7895.2332350173638, 9154.2956175610598]

# Cluster data, sort it and and save
inputNumpy = numpy.array([[data['original']['x'][i], data['original']['y'][i]] for i in range(0, len(data['original']['x']))])
meanShift = sklearn.cluster.MeanShift()
meanShift.fit(inputNumpy)
clusteredData = [[pair[0], pair[1]] for pair in meanShift.cluster_centers_]
clusteredData.sort(lambda pair1, pair2: cmp(pair1[0],pair2[0]))
data['clustered'] = {}
data['clustered']['x'] = [pair[0] for pair in clusteredData]
data['clustered']['y'] = [pair[1] for pair in clusteredData]

# Build a spline using the clustered data and predict
mySpline = scipy.interpolate.UnivariateSpline(x=data['clustered']['x'], y=data['clustered']['y'], k=1)
xi = range(0, round(max(data['original']['x']), -3) + 3000, 20)
yi = mySpline(xi)

# Plot the datapoints
pylab.plot(data['clustered']['x'], data['clustered']['y'], "D", label="Datapoints (%s)" % 'clustered')
pylab.plot(xi, yi, label="Predicted (%s)" %  'clustered')
pylab.plot(data['original']['x'], data['original']['y'], "o", label="Datapoints (%s)" % 'original')

# Show the plot
pylab.grid(True)
pylab.xticks(rotation=45)
pylab.legend( loc="lower right" )
pylab.show()

rawDescription: scipy.interpolate.UnivariateSpline not smoothing regardless of parameters

description: Scipy.interpolate.UnivariateSpline not smoothing regardless of parameters


code:
x = np.float32(1.)
y = np.nextafter(x, np.float32(2.))
y
type(y)

rawDescription: increment float32 by smallest possible amount (using numpy currently)

description: Increment float32 by smallest possible amount (using numpy currently)


code:
from unittest.mock import *
root = '''bin   cdrom  etc   initrd.img  lib32  libx32      media  opt   root  sbin  sys  usr  vmlinuz
boot  dev    home  lib         lib64  lost+found  mnt    proc  run   srv   tmp  var'''
answer = {'ls /': root}
import subprocess
with patch('subprocess.check_output', side_effect=lambda arg, *args, **kwargs: answer[arg]) as mock_check_output :
    assert root == subprocess.check_output('ls /')
    mock_check_output.assert_called_with('ls /')
    subprocess.check_output('something else')

rawDescription: MagicMock return value based on input

description: MagicMock return value based on input


code:
def recursive_sum(nested_num_list):
    sum = 0
    for element in nested_num_list:
        if hasattr(element, '__iter__'):
            sum = sum + recursive_sum(element)
        else:
            sum = sum + element
    return sum

rawDescription: Avoiding the use of type() comparisons where polymorphism won't work


rawDescription: How to raise a numpy.matrix to non-integer power?

description: Raise a numpy.matrix to non-integer power


code:
from os.path import relpath

In [5]: os.path.relpath("test.txt",start="/")
Out[5]: 'Users/ebarr/test.txt'

In [8]: os.path.relpath("test.txt",start="/Var")
Out[8]: '../Users/ebarr/test.txt'

rawDescription: Create XML file with relative paths

description: Create XML file with relative paths


code:
def loop(f, n):         #f repeats n times
    if n<=0:
        return
    else:
        f()             # don't forget to call f()
        loop(f, n-1)

rawDescription: Python function looping only once

description: Python function looping only once


code:
while done==False:
    clock.tick(SETFPS)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done=True
    if event.type == pygame.MOUSEBUTTONDOWN:
        print('a')
    if event.type == pygame.MOUSEMOTION: # We only want to move the image when the mouse is moved.
        mouse_position = pygame.mouse.get_pos() # Where is the mouse at?
        screen.blit(background_image, background_position)
        screen.blit(card,[zx,zy])
        zx=mouse_position[0] # mouse_position is in the form [x,y], we only want the x part
        zy=mouse_position[1]
    pygame.display.flip()

rawDescription: game coding in python using pygame

description: Game coding in python using pygame


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

np.random.seed(937)
data = np.random.lognormal(size=(37, 4), mean=1.5, sigma=1.75)
labels = list('ABCD')
fs = 10  # fontsize

plt.boxplot(data, labels=labels, showfliers=False, widths=(1, 0.5, 1.2, 0.1))

plt.show()

rawDescription: Adjust width of box in boxplot in python matplotlib


code:
mask3 = numpy.dstack(mask,mask,mask)
im = im * (mask3>threshold) + im * (mask3<threshold) * 0.2
im[:,:,0] += 255 * (mask<threshold)

rawDescription: Index 3D array by 2D array

description: Index 3D array by 2D array


code:
df
df.groupby("Duplicate_of").agg({'Gene': ', '.join, 'Value1': np.mean})

rawDescription: Get correlations from multiple rows which have the same value (Python)


code:
for inst in data:
    cl = clusterer.cluster_instance(inst)
    dist = clusterer.distribution_for_instance(inst)
    print("cluster=" + str(cl) + ", distribution=" + str(dist))

rawDescription: How determine cluster assignment of each instances after clustering through weka-python-wrapper


code:
last_div = None
for last_div in post_content:pass
if last_div:
    content = last_div.getText()

rawDescription: Getting content from last element using BeautifulSoup find_all


code:
t=1234
tt=pack('<I', t)
tt
unpack('<I', tt)
ttt, = unpack('<I', tt)
ttt

rawDescription: python pack output in string format

description: Python pack output in string format


code:
from io import BytesIO
from reportlab.pdfgen import canvas

@bottle.route('/pd')
def create_pdf():
    response.headers['Content-Type'] = 'application/pdf; charset=UTF-8'
    response.headers['Content-Disposition'] = 'attachment; filename="test.pdf"'

    buffer = BytesIO()
    p = canvas.Canvas(buffer)
    p.drawString(100,100,'Hello World')
    p.showPage()
    p.save()

    return buffer.getvalue()

rawDescription: Bottle framework generate pdf

description: Bottle framework generate pdf


code: ' '.join( [w for w in input.split() if len(w)>1] )

rawDescription: Removing any single letter on a string in python


code:
import bisect
def snap(myGrid, myValue):
    ix = bisect.bisect_right(myGrid, myValue)
    if ix == 0:
        return myGrid[0]
    elif ix == len(myGrid):
        return myGrid[-1]
    else:
        return min(myGrid[ix - 1], myGrid[ix], key=lambda gridValue: abs(gridValue - myValue))

rawDescription: Efficient pythonic way to snap a value to some grid


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

fig = plt.figure()
ax1 = fig.add_subplot(111)
V = 10
X = range (V)
char = 'a'
leg = []
legp = []
for i in range (0,5):
    Y = np.random.randn(V)
    ap = ax1.plot(X,Y)
    legp.append(ap)
    char = chr(ord(char)+1)
    leg.append(char)
fig.legend(legp,leg)
plt.show()

rawDescription: placing a legend on a subplot in matplotlib, what am I doing wrong?

description: Placing a legend on a subplot in matplotlib, what am I doing wrong


code:
args = [ '<stdin>:'+x[2:] if x.startswith('-:') else x for x in sys.argv[1:] ]
opt_struct = parser.parse_args(args)

rawDescription: Make optparse treat certain options as positional arguments


code:
class ReportingAdmin(ImportExportModelAdmin,admin.ModelAdmin):
    ...

    def get_search_results(self, request, queryset, search_term):
        range = search_term.split('-')
        number1 = None
        number2 = None
        try:
            if len(range>2):
                number1 = int(range[0])
                number1 = int(range[1])
                search_term = ''
        except ValueError:
            pass
        queryset, use_distinct = super(ReportingAdmin, self).get_search_results(request, queryset, search_term)
        if number1 and number2:
            queryset |= self.model.objects.filter(balance__gte=number1, balance__lte=number2)
        return queryset, use_distinct

rawDescription: how can i apply price search between the range like(search between value1-value2) in django admin

description: Apply price search between the range like(search between value1-value2) in django admin


code:
entry1 = Entry(...)
entry2 = Entry(...)
entries = (entry1, entry2)
...
def disable_all_entries():
    for entry in entries:
        entry.configure(state="disabled")

rawDescription: Configure multiple widgets at once by tag


code:
def restore(self):
    self.log('=== powering down')
    wait(self.session.console.powerDown())
    self.session.unlockMachine()

    self.log('=== restoring')
    self.session=self.mgr.openMachineSession(self.vm) # WHY?
    self.vm=self.session.machine
    wait(self.vm.restoreSnapshot(self.vm.findSnapshot(const.VM_BASE_SNAPSHOT)))
    self.session.unlockMachine()

    self.log('=== powering up')
    self.vm=self.vbox.findMachine(const.VM_NAME)
    self.session=self.mgr.getSessionObject(self.vbox)
    while True:
        try:
            wait(self.vm.launchVMProcess(self.session,'gui' if const.DEBUG else 'headless',''))
        except pywintypes.com_error: #unlocking machine
            time.sleep(.1)
        else:
            break

rawDescription: Can't restore VM in Python Virtualbox API


code:
import requests
d = {'content-length': '12276', 'via': '1.1 varnish-v4', 'links': '<http://justblahblahblah.com/link8.html>;rel="last">,<http://justblahblahblah.com/link2.html>;rel="next">', 'vary': 'Accept-Encoding, Origin'}
requests.utils.parse_header_links(d['links'].rstrip('>').replace('>,<', ',<'))

rawDescription: python requests link headers

description: Python requests link headers


code:
import urllib
linkToFile = "http://www.someurl.com/file.pdf"
localDestination = "/home/user/local/path/to/file.pdf"
resultFilePath, responseHeaders = urllib.urlretrieve(linkToFile, localDestination)

rawDescription: Download a file to a particular folder python


code:
for line in headers:
    if "Content-Length:" in line:
        contentLength = line

contentLength = contentLength[16:]

rawDescription: How to find an content length int in http header file

description: Find an content length int in http header file


code: factor(x**2 + 1, extension=[I])

rawDescription: Factor to complex roots using sympy

description: Factor to complex roots using sympy


rawDescription: How to reshape numpy image?

description: Reshape numpy image


rawDescription: Extracting a specific part of a string with regular expression in Python


code:
r= mlab.csv2rec('HeightWeight.csv', delimiter= ',',
                 names=['apple', 'pear'],
                 skiprows=1)

rawDescription: Can I rename fields in a numpy record array

description: Rename fields in a numpy record array


rawDescription: SQLAlchemy equivalent of Django ORM's relationship-spanning filter


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

import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

import random
from PyQt4 import QtGui, QtCore

class MyStandardItemModel(QtGui.QStandardItemModel):
    _colorize = False
    def __init__(self, parent=None):
        super(MyStandardItemModel, self).__init__(parent)

    def setColorized(self, state):
        self._colorize = state

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if role == QtCore.Qt.BackgroundColorRole \
        and not self._colorize:
            return QtGui.QBrush()

        return super(MyStandardItemModel, self).data(index, role)

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

        self.pushButtonColorize = QtGui.QPushButton(self)
        self.pushButtonColorize.setText("Colorize Cells!")
        self.pushButtonColorize.setCheckable(True)
        self.pushButtonColorize.toggled.connect(self.on_pushButtonColorize_toggled)

        self.pushButtonReload = QtGui.QPushButton(self)
        self.pushButtonReload.setText("Reload Data!")
        self.pushButtonReload.clicked.connect(self.on_pushButtonReload_clicked)

        self.modelSource = MyStandardItemModel(self)

        self.tableView = QtGui.QTableView(self)
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.setModel(self.modelSource)

        self.layoutVertical = QtGui.QVBoxLayout(self)
        self.layoutVertical.addWidget(self.pushButtonReload)
        self.layoutVertical.addWidget(self.pushButtonColorize)
        self.layoutVertical.addWidget(self.tableView)

        self.pushButtonReload.click()

    @QtCore.pyqtSlot()
    def on_pushButtonReload_clicked(self):
        self.modelSource.clear()

        for rowNumber in range(3):
            items = []
            for columnNumber in range(3):
                item = QtGui.QStandardItem()
                item.setText(str(random.getrandbits(1)))

                items.append(item)

            self.modelSource.appendRow(items)

        if self.pushButtonColorize.isChecked():
            self.on_pushButtonColorize_toggled(True)

    @QtCore.pyqtSlot(bool)
    def on_pushButtonColorize_toggled(self, state):
        self.modelSource.setColorized(state)

        rowCount    = self.modelSource.rowCount()
        columnCount = self.modelSource.columnCount()

        for rowNumber in range(rowCount):
            for columnNumber in range(columnCount):
                cellIndex = self.modelSource.index(rowNumber, columnNumber)
                cellData  = self.modelSource.data(cellIndex, QtCore.Qt.DisplayRole)

                if str(cellData).isdigit() \
                and int(cellData) == 1:
                    for cellColumn in range(columnCount):
                        self.modelSource.setData(
                            self.modelSource.index(rowNumber, cellColumn),
                            QtGui.QColor(QtCore.Qt.blue),
                            QtCore.Qt.BackgroundColorRole
                        )

        self.modelSource.endResetModel()

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.resize(333, 222)
    main.show()

    sys.exit(app.exec_())

rawDescription: pyqt - put color in a QTableView with existing data

description: Pyqt - put color in a QTableView with existing data


code:
class ProductFactory(factory.django.DjangoModelFactory):
    FACTORY_FOR = Product

    name = "test product"
    offer1 = factory.RelatedFactory(OfferFactory, 'product')
    offer2 = factory.RelatedFactory(OfferFactory, 'product') # add a second offer
    offer3 = factory.RelatedFactory(OfferFactory, 'product') # add a third offer
    merchant1 = factory.RelatedFactory(MerchantFactory, 'product')
    merchant2 = factory.RelatedFactory(MerchantFactory, 'product') # add a second merchant
    merchant3 = factory.RelatedFactory(MerchantFactory, 'product') # add a third"

rawDescription: factory_boy: add several dependent objects

description: Factory_boy: add several dependent objects


code:
for i in xrange(3,51):
    arcpy.MinimumBoundingGeometry_management("bound%i" % i, "bound%iConvexHull" % i, ... )

rawDescription: Are the loops in python similar to matlab?


rawDescription: How do I scrape the website link on the page?

description: Scrape the website link on the page


code:
def test_fact(self):
    tests = [(1,1), (2,2), (3,6), (4,24), (5,120)]
    for n,f in tests:
        self.assertEqual(fact(n), f)

rawDescription: Proper structure for many test cases in Python with unittest


code:
my_id_strs = map(str, my_ids)
for line in source_file:
    first_part = line.split("|")[0]
    if first_part in my_id_strs:
        target_file.write(line.replace(",",";").replace("|",","))

rawDescription: Fastest check if line starts with value in list?


code: [v for v in my_list for _ in range(3)]

rawDescription: Unpacking tuples in a python list comprehension (failing to use the *-operator)


code:
# define necessary urls of your app which should always be present
urlpatterns = patterns('',
    url(r'^$', 'myapp.views.home', name='home'),
)

# then add urls of external apps if the app is present in INSTALLED_APPS
if 'social_networks' in settings.INSTALLED_APPS:
    urlpatterns += patterns('',
        url(r'^social/', include('social_networks.urls')),
    )

rawDescription: Import urls in urls.py based on INSTALLED_APPS Django


code:
import re

matches = re.finditer(r'([aeiou])|([^aeiou])', 'the quick brown fox')
pos = [m.start() for m in matches if m.group(2) is not None]
# [0, 1, 3, 4, 7, 8, 9, 10, 11, 13, 14, 15, 16, 18]

rawDescription: How to I find the location within a string where a match was found for a particular capture group?


code:
data = 'callback({"key": "val"})' # a comman JSONP object
json.loads(data)
data_json = data.split("(")[1].strip(")") # convert to json
data_json
json.loads(data_json)

rawDescription: Django - Parse JSONP (Json with Padding)


code:
import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resp = urllib2.urlopen(req)
content = resp.read()

rawDescription: How do I set headers using python's urllib?

description: Set headers using python's urllib


code:
mapping = dict((w, i) for i, w in enumerate(masterWordList))

def tfidfVector(cleanStringVector, masterWordList):
    featureVector = [0] * len(masterWordList)
    for w in cleanStringVector:
        featureVector[mapping[w]] += 1
    return featureVector

rawDescription: Most efficient histogram code in python

description: Most efficient histogram code in python


code: num_cols = len(reader.next())

rawDescription: To Count the number of columns in a CSV file using python 2.4


rawDescription: UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-6: ordinal not in range(128)


code:
def assertEqualHTML(string1, string2, file1='', file2=''):
    u'''
    Compare two unicode strings containing HTML.
    A human friendly diff goes to logging.error() if there
    are not equal, and an exception gets raised.
    '''
    from BeautifulSoup import BeautifulSoup as bs
    import difflib
    def short(mystr):
        max=20
        if len(mystr)>max:
            return mystr[:max]
        return mystr
    p=[]
    for mystr, file in [(string1, file1), (string2, file2)]:
        if not isinstance(mystr, unicode):
            raise Exception(u'string ist not unicode: %r %s' % (short(mystr), file))
        soup=bs(mystr)
        pretty=soup.prettify()
        p.append(pretty)
    if p[0]!=p[1]:
        for line in difflib.unified_diff(p[0].splitlines(), p[1].splitlines(), fromfile=file1, tofile=file2):
            logging.error(line)
        raise Exception('Not equal %s %s' % (file1, file2))

rawDescription: pretty print assertEqual() for HTML strings

description: Pretty print assertEqual() for HTML strings


code:
import os,sys
this_dir = os.path.dirname(__file__)  #get the current directory of running script
dir_list = (x for x in os.listdir(this_dir) if os.path.isdir(os.path.join(this_dir, x)))     #get the list of directories under current directory
project_path = []
for dirpath in dir_list:
    if dirpath not in project_path:
        project_path.append(os.path.join(this_dir, dirpath))
setattr(sys.modules[__name__], '__path__', project_path) #add to sys modules so any modules can be imported from thsi directories

rawDescription: how to use sys.modules.

description: Use sys.modules.


code:
from __future__ import print_function

items = ['Appname1', 'Appname2', 'Appname2Bootstrap', 'Appname3', 'Appname3Bootstrap']
items_sorted = sorted(items, key=lambda x: (not x.endswith('Bootstrap'), x))

print('Got the sorted items: {}'.format(items_sorted))

rawDescription: Sort by a specific word and by alphabetical order


code:
import multiprocessing
import random

def worker():
    """worker function"""

    x = random.random()*10
    x = round(x)
    while(True):
        print(x , ' Worker')

if __name__ == '__main__':
    jobs = []
    for i in range(5):
        p = multiprocessing.Process(target=worker)
        jobs.append(p)
        p.start()

rawDescription: Why can I not speed up crawling with multithreading in python?


code:
import matplotlib
matplotlib.path.Path.contains_points   # is the function you are looking for

rawDescription: different ways of triangle calculation

description: Different ways of triangle calculation


code:
# testing.py
from . import config, db

class TestCase(unittest.TestCase):

    def setUp(self):
        self.app = create_app(config)
        # db is properly set up to use the testing config
        # but any *changes* you make to the db object
        # (e. g. monkey-patching) will persist between tests
        db.create_all()

    def tearDown(self):
        db.session.remove()
        db.drop_all()

rawDescription: Setting up database for testing in Flask


code:
d = {}
for name, group in data.groupby('hour'):
    d['group_' + str(name)] = group

rawDescription: How to create a data frame for each group in the pandas.groupby function?

description: Create a data frame for each group in the pandas.groupby function


code:
def ddply(rows, cols, op=lambda group_rows: group_rows):
    """group rows by cols, then apply the function op to each group
    rows is list of values or dict with col names (like read from
    csv.reader or   csv.DictReader)"""
    def group_key(row):
        return (row[col] for col in cols)
    rows = sorted(rows, key=group_key)
    return itertools.chain.from_iterable(
        op(group_rows) for k,group_rows in itertools.groupby(rows, key=group_key))

rawDescription: Is there an implementation of Hadley's ddply for python?


code: appstats_TZOFFSET = 0

rawDescription: How can you change the timezone in AppEngine's AppStats?

description: Change the timezone in AppEngine's AppStats


code:
import Tkinter as tk
r=tk.Tk()
r.title('hello')
l= tk.Label(r, name='lbl', width=20, text='reduce the window width')
l.pack(fill=tk.BOTH) # or tk.X, depends; check interactive resizing now
l['text']= "This is a long text, window size should remain the same"

rawDescription: Auto truncation of a Tkinter label

description: Auto truncation of a Tkinter label


code:
from sympy import * # we are importing everything for ease of use
x = Symbol("x")
y = Symbol("y")     # create the two variables
equation = Eq(x ** 2, y) # create the equation
solve(equation, x)

rawDescription: Python - solve polynomial for y

description: Python - solve polynomial for y


code:
import re
re.search(".*color.*sky.*", "where am I?") == None
re.search(".*color.*sky.*", "what color is the sky") == None
re.search(".*color.*sky.*", "what color is a rose") == None

rawDescription: How to stick a wildcard in a string in Python?

description: Stick a wildcard in a string in Python


code:
import socket

def main():
    host = "127.0.0.1"
    port = 5009

    s = socket.socket()
    s.bind((host, port))

    s.listen(1)
    while True:
        c, addr = s.accept()
        print("Connect" + str(addr))
        while True:
            data = c.recv(1024)
            data = str(data, "utf-8")
            print(data)
            if not data:
                break
            data = bytes(data.upper(), "utf-8")
            c.send(data)
        c.close()
    s.close()

if __name__ == '__main__':
    main()

rawDescription: Python 3, networking. Keep server open and make multiple connections?


code:
# models
class MyModel(models.Model):
    # ...
    non_unique_slug = models.SlugField()

    def get_absolute_url(self):
        return "/questions/%s/%s" % (self.id, self.non_unique_slug)

# urls
    r'^questions/(?P<id>\d+)/(?P<slug>[\w-]+)/$'

# views
def my_view(request, id, slug):
    page = Page.objects.get(id=id)
    if not slug == page.slug:
        return http.HttpResponsePermanentRedirect(page.get_absolute_url())

    # render page
    return direct_to_template(request, "foobar.html", {'page': page})

rawDescription: Canonical links and 301 Redirect if URL doesn't match slug


code: " , ".join(" * ".join(".".join(str(xx) + '!' + str(yy) for xx, yy in zip(x[:, 0], x[:, _x])) for _x in range(1, len(x[0]))) for x in a)

rawDescription: Merging numpy array elements using join() in python


code:
from xml.dom import minidom

# Parse the xml
xmldoc = minidom.parse('all.xml')

# Get all Elements with the name t0. This returns a list of Elements..
Sensor0Elm = xmldoc.getElementsByTagName('t0')

# The expectation is to only get one element, so I
# grab the first one in the list
Sensor0Elm = Sensor0Elm[0]

# The element can contain many nodes. The expectation is only
# one node containing the data, so we grab the first node and
# obtain the data.
Sensor0 = Sensor0Elm.childNodes[0].data

# Finally we convert the unicode data into a floating point number
Sensor0 = float(Sensor0)

rawDescription: xml child-value extraction with python

description: Xml child-value extraction with python


code:
from django.contrib.contenttypes.models import ContentType
from django.db import models

class InheritanceCastModel(models.Model):
    """
    An abstract base class that provides a ``real_type`` FK to ContentType.

    For use in trees of inherited models, to be able to downcast
    parent instances to their child types.

    """
    real_type = models.ForeignKey(ContentType, editable=False)

    def save(self, *args, **kwargs):
        if not self.id:
            self.real_type = self._get_real_type()
        super(InheritanceCastModel, self).save(*args, **kwargs)

    def _get_real_type(self):
        return ContentType.objects.get_for_model(type(self))

    def cast(self):
        return self.real_type.get_object_for_this_type(pk=self.pk)

    class Meta:
        abstract = True

rawDescription: How do I access the child classes of an object in django without knowing the name of the child class?

description: Access the child classes of an object in django without knowing the name of the child class


code:
prefix = '111'
suffix = '222'

with open('source.txt', 'r') as src:
    with open('dest.txt', 'w') as dest:
       for line in src:
           dest.write('%s%s%s\n' % (prefix, line.rstrip('\n'), suffix))

rawDescription: Python - Write To Beginning and End of Every Line in TXT


code:
if color.startswith("grey") and color[4:].isdigit():
    return int(color[4:])
else:
    return 'pass'

rawDescription: Being able to detect int's in strings, Python


rawDescription: How to filter JSON data by multi-value column

description: Filter JSON data by multi-value column


code:
import pyximport; pyximport.install()
import foo

rawDescription: Cython development workflow?

description: Cython development workflow


code:
file1=open('file1.txt','r')
file2=open('file2.txt','r')
obj=[file1.read(), file2.read()]
cPickle.dump(obj,open('result.i2','w'),2)

rawDescription: How to pickle several .txt files into one pickle

description: Pickle several .txt files into one pickle


code:
# First get the meta description tag
description = soup.find('meta', attrs={'name':'og:description'}) or soup.find('meta', attrs={'property':'description'}) or soup.find('meta', attrs={'name':'description'})

# If description meta tag was found, then get the content attribute and save it to db entry
if description:
    entry.description = description.get('content')

rawDescription: Get meta description from external website


code:
import multiprocessing
import os
import random
import sys
import threading

def find_lucky_number(x):
    prng = random.Random()
    prng.seed(x)
    for i in range(100000000):
        prng.random()
    return prng.randint(0, 100)

def with_threading(inputs):
    callback = lambda x : print(find_lucky_number(x))
    threads = [threading.Thread(target=callback, args=(x,)) for x in inputs]
    for t in threads:
        t.start()
    for t in threads:
        t.join()

def with_multiprocessing(inputs):
    with multiprocessing.Pool(len(inputs)) as pool:
        for y in pool.map(find_lucky_number, inputs):
            print(y)

def with_forking(inputs):
    pids = list()
    for x in inputs:
        pid = os.fork()
        if pid == 0:
            print(find_lucky_number(x))
            sys.exit(0)
        else:
            pids.append(pid)
    for pid in pids:
        os.waitpid(pid, 0)

if __name__ == '__main__':
    inputs = [1, 2, 3, 4]
    if sys.argv[1] == '--threads':
        with_threading(inputs)
    if sys.argv[1] == '--mp':
        with_multiprocessing(inputs)
    elif sys.argv[1] == '--fork':
        with_forking(inputs)
    else:
        print("What should I do?", file=sys.stderr)
        sys.exit(1)

rawDescription: Operating-System-Level Changes To Speed Up Python's Multiprocessing?


code:
class ArticleView(RestView):

    def GET(request, article_id):
        return render_to_response("article.html", {
            'article': get_object_or_404(Article, pk = article_id),
        })

    def POST(request, article_id):
        # Example logic only; should be using django.forms instead
        article = get_object_or_404(Article, pk = article_id)
        article.headline = request.POST['new_headline']
        article.body = request.POST['new_body']
        article.save()
        return HttpResponseRedirect(request.path)

rawDescription: How to implement restful webservice with python/django

description: Implement restful webservice with python/django


code:
def parse_item(self, response):
    item = MyItem()
    # populate the item with this response data
    yield FormRequest(
        'url',
        formdata={'key': 'value'},
        callback=self.get_currency, meta={'item':item}
    )

def get_currency(self, response):
    self.log('lalalalala')
    item = response.meta['item']
    item['price'] = 123 # get your price from the response body.
    # keep populating the item with this response data
    yield item

rawDescription: Scrapy can't reach callback for Request

description: Scrapy can't reach callback for Request


rawDescription: Consistenly create same random numpy array


code:
import math
import sys
result = []
for line in sys.stdin.readlines():
    data = line.split(' ')
    for Ai in data:
        Ai = Ai.strip()
        try:
            result.append(math.sqrt(int(Ai)))
        except:
            pass

for i in reversed(result):
    print("%.4f"%i)

rawDescription: How to input an unknown size of strings with newlines in Python?

description: Input an unknown size of strings with newlines in Python


code:
while not self.stop:  # self.stop is set to True when stop() is called
    ...
    self.results.append(item) # do some stuff that involves appending results to a list
with open('~/output.txt', 'w') as outfile:
    outfile.write('\n'.join(str(item) for item in item))

rawDescription: understanding this multithreading demon python code

description: Understanding this multithreading demon python code


code:
dates = sorted([datetime.strptime(regex_obtained_str, '%B %d, %Y, %I:%M:%S %p')
                for regex_obtained_str in strings])
l = [date.strftime('%m/%d/%Y %I:%M:%S %p') for date in dates]

rawDescription: Python: sorting datetime objects keeping "AM" and "PM" into account


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

rawDescription: How to know when stdin is empty if it contains EOF?

description: Know when stdin is empty if it contains EOF


code:
import ctypes
_ = lambda i: int(ctypes.c_uint32(i).value)
hex(_(0xF0 + 0xAA))

rawDescription: Python, type byte

description: Python, type byte


code:
keys = {char: chr(i) for i, char in enumerate(self.key)}
match = ''.join([keys[char] for char in data if char in keys])

rawDescription: Python loop efficiency

description: Python loop efficiency


code:
def cmpdirs(dir_cmp):
    # make copies of the comparison results
    left   = dir_cmp.left_only[:]
    right  = dir_cmp.righ_only[:]
    common = dir_cmp.common_files[:]

    for sub_dcmp in dir_cmp.subdirs.values():
        sub_left, sub_right, sub_common = cmpdirs(sub_dcmp)

        # join the childrens results
        left   += sub_left
        right  += sub_right
        common += sub_common

    # return the merged results
    return (left, right, common)

if __name__ == '__main__':
    dcmp   = dircmp('dir1', 'dir2')
    result = cmpdirs(dcmp)

rawDescription: Creating a flat list from return values of a recursive python function


code:
class Application(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.pack()

        self.top = Frame(self)
        self.bottom = Frame(self)
        self.bottom2 = Frame(self)
        self.top.pack(side=TOP)
        self.bottom.pack(side=BOTTOM, fill=BOTH, expand=True)
        self.bottom2.pack(side=BOTTOM, fill=BOTH, expand=True)
        #...
        self.submitbutton = Button(self, text="Submit", command=self.submit)
        self.submitbutton.pack(in_=self.bottom2, side=TOP)
        #...

    #...

    def submit(self):
        page = ('http://www.sec.gov/cgi-bin/browse-edgar?company=&match=&CIK=' +
                 self.entryWidget.get().strip() +
                '&filenum=&State=&Country=&SIC=&owner=exclude'
                '&Find=Find+Companies&action=getcompany')
        #...
        self.soup = ...

    def next(self):
        #...
        #there must be a better way than this to extract the onclick value
        #but I don't use/know BeautifulSoup to help with this part

        npar = str(self.soup.find(value="Next 40"))
        index1 = npar.find('/cgi')
        index2 = npar.find('count=40') + len('count=40')
        page = 'http://www.sec.gov' + npar[index1:index2]

        sock = urllib.urlopen(page)
        raw = sock.read()
        self.soup = BeautifulSoup(raw)

        #...

if __name__ == '__main__':
    root = Tk()
    root.title("SEC Edgar Search")
    root["padx"] = 10
    root["pady"] = 25

    app = Application(root)

    app.mainloop()
    root.destroy()

rawDescription: Problem with Button Command Tkinter Python


code:
text = self.request.get('message')
message = mail.EmailMessage(sender="abc@domain.com", subject="Testing")
message.to = 'bcd@domain.com'
message.html = """The Message: %s """ % (text)
message.send()

rawDescription: Google App Engine Python: How to display textarea value in mail


code:
from flask import url_for, redirect

@app.route('/')
def home():
    return redirect(url_for('static', filename='hi.html'))

rawDescription: python flask - serving static files

description: Python flask - serving static files


code:
secondFile = open(sys.argv[2],'rU')

# skip first line
next(secondFile)

# csv parser does not see the first line of the file
reader2 = csv.reader(secondFile, delimiter=',')

rawDescription: Skip first row in a file

description: Skip first row in a file


rawDescription: xlsxwriter - grouping via set_row()

description: Xlsxwriter - grouping via set_row()


code:
def root_pre(l):
    root = ""
    for t in zip(*l):
        if not all(t[0] == s for s in t):
            break
        root += t[0]
    ln = len(root)
    pres = [s[ln:] for s in listData]
    return root, pres

print(root_pre(listData))
('black', ['ish', 'en', 'ed'])

rawDescription: Root Identification in a list of Data in python:


code:
import os
import time
date1 = time.strftime('%Y%m%d%H%M%S')
cmd1= "cp logfile logfile{0}".format(date1)
cmd2= "cat /dev/null > logfile"
os.system(cmd1)
os.system(cmd2)

rawDescription: Need to do a daily log rotation (0utc) using Python


code:
from django.db import models
from django.contrib import admin
from django.forms.extras.widgets import TextInput

class MyModelAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.TextField: {'widget': TextInput(attrs={'class':'my-widget-class'},)},
    }

rawDescription: adding form styling to django forms

description: Adding form styling to django forms


code:
class Liar(object):
  def __cmp__(self, other):
    return id(self) == id(other)

x = Liar()
x
x == x
x == 1
x == 'hello world'

rawDescription: Does a Python object which doesn't override comparison operators equals itself?


code:
#pseudocode

buf = read(1024)
while True:
   if re.match(regexp, buf):
        buf = re.sub(regexp, do_stuff, buf)
   else:
        buf += read(1024)

rawDescription: run regex on file object instead of string

description: Run regex on file object instead of string


code:
import mechanize

FILE_URL = 'http://mit.edu/img/MIT_logo.gif'
DESTINATION = '/tmp/lol.gif'

br = mechanize.Browser()
br.retrieve(FILE_URL, DESTINATION)

rawDescription: Mechanize (Download to custom directory)


code:
if not map:
    map = base_map.set_a_map()

rawDescription: How to create a reusable basemap

description: Create a reusable basemap


rawDescription: python: force two zeroes after dot when converting float to string

description: Python: force two zeroes after dot when converting float to string


code:
import pandas as pd

T1 = pd.DataFrame(data = {'val':['B','D','E','A','D','B','A','E','A','D','B']})

# use the index to create a new column that's going to be the key (zero based)
T1 = T1.reset_index()

# do the same for the subsequence that we want to find within T1
P = pd.DataFrame(data = {'val': ['E','A','D','B']})
P = P.reset_index()

# join on the val column
J = T1.merge(P,on=['val'],how='inner')

# group by difference in key columns calculating the min, max and count of the T1 key
FullResult = J.groupby(J['index_x'] - J['index_y'])['index_x'].agg({min,max,'count'})

# Final result is where the count is the size of the subsequence - in this case 4
FullResult[FullResult['count'] == 4]

rawDescription: Finding the position of a subsequence in a sequence


code:
import numpy as np

# a 10GB memory-mapped array
x = np.memmap('/tmp/x.mm', mode='w+', dtype=np.ubyte, shape=(int(1E10),))

# create a memory-mapped .npy file with the same dimensions and dtype
y = open_memmap('/tmp/y.npy', mode='w+', dtype=x.dtype, shape=x.shape)

# copy the array contents
y[:] = x[:]

rawDescription: Flushing numpy memmap to npy file

description: Flushing numpy memmap to npy file


code:
class ParentClass:
    logger = logging.getLogger('ParentClass') # class variable
    def __init___(self):
        self.logger.info('This is inside ParentClass')

class ChildClass(ParentClass):
    logger = logging.getLogger('ChildClass') # override parent class variable
    def foo(self):
        self.logger.info('This is inside ChildClass')

rawDescription: Have Parent Class Use Child Class Logger Name


code: foo.sort(key=lambda i: (i[1], i[0]))

rawDescription: Is there a way to sort by a second key in the event that the first key is equal?


rawDescription: How to prevent foreign key lookup in django

description: Prevent foreign key lookup in django


code:
import re
var = "++"
re.search(re.escape(var), '++')

rawDescription: Regex python attaching raw to string variables


rawDescription: How to manage string memory with python ctypes

description: Manage string memory with python ctypes


code: size = sum(1 for _ in bucket.objects.all())

rawDescription: How do I get the size of a boto3 Collection?

description: Get the size of a boto3 Collection


code:
regex = re.compile(r'ORA-16252: unable to extend segment by \d+ in tablespace')
if regex.match(s):
    ...

rawDescription: Python match a number within a string

description: Python match a number within a string


code:
class A(object):
    def __repr__(self):
        return self._repr()
    def _repr(self):
        return object.__repr__(self)

rawDescription: Overriding special methods on an instance


rawDescription: Pandas: DataFrame too long after merge

description: Pandas: DataFrame too long after merge


code:
class ListDashboardView(ListView):
    model = Contact
    template_name = 'dashboard.html'

    def get_context_data(self, **kwargs):
        ctx = super(ListDashboardView, self).get_context_data(**kwargs)
        ctx['polls'] = Poll.objects.all()
        return ctx

rawDescription: Refer to multiple Models in View/Template in Django


code:
def makeNode(val=None, left=None, right=None):
    if right is None:
        val = []
    return Node(val, left, right)

rawDescription: Mutable default argument for a Python namedtuple


code:
from collections import OrderedDict
a=OrderedDict()
s=sorted(d.items())
for i,j in s:
 a.update({i:j})

a

rawDescription: python print dictionary tuples in order grid format

description: Python print dictionary tuples in order grid format


code:
def model(p,x):
    A,x1,sig1,B,x2,sig2 = p
    return A*np.exp(-(x-x1)**2/sig1**2) + B*np.exp(-(x-x2)**2/sig2**2)

def res(p,x,y):
    return model(p,x) - y

from scipy import optimize

p0 = [1e-15,3968,2,1e-15,3972,2]
p1,conv = optimize.leastsq(res,p0[:],args=(x,y))

plot(x,y,'+') # data
#fitted function
plot(arange(3962,3976,0.1),model(p1,arange(3962,3976,0.1)),'-')

rawDescription: Separating gaussian components of a curve using python


code:
from collections import defaultdict

tree = lambda: defaultdict(tree)  # a recursive defaultdict
d = tree()
for _, (region, type, name, value) in df.iterrows():
    d['children'][region]['name'] = region
    ...

json.dumps(d)

rawDescription: Pandas to D3. Serializing dataframes to JSON


code:
import textwrap
s  = "Au Fil Des Antilles De La Martinique a Saint Barthelemy"
textwrap.wrap(s, 30)
"\n".join(textwrap.wrap(s, 30))

rawDescription: python - cut a string in 2 lines

description: Python - cut a string in 2 lines


code:
violin_parts = plt.violinplot(...)

for pc in violin_parts['bodies']:
    pc.set_facecolor('red')
    pc.set_edgecolor('black')

rawDescription: Changing the color of matplotlib's violin plots


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

import webapp2
from google.appengine.ext.webapp.util import run_wsgi_app
import logging
from google.appengine.ext import db

# MODELS
class Child_model(db.Model):
    name = db.StringProperty()

class Parent_model(db.Model):
    name = db.StringProperty()

class Root_model(db.Model):
    pass

# MAIN
class MainHandler(webapp2.RequestHandler):
    def get(self, url):
        if not Root_model.get_by_key_name("root"):
            # Populate db on first run
            self.populate()

        logging.info("-- Get all enteties recursivly --")
        root        = Root_model.get_by_key_name("root")
        logging.info(" - %s", root)

        parents     = Parent_model.all().ancestor(root)

        # Recursivly
        for p in parents:
            logging.info(" -- %s" % p.name)
            children = list(Child_model.all().ancestor(p))
            [logging.info(" --- %s" % c.name) for c in children]

        # Shortcut
        #children   = Child_model.all().ancestor(root)

        logging.info("-- Get all children for a parent --")
        [logging.info(" -- %s" % c.name) for c in self.get_all_children_for_a_parent() ]

        logging.info("-- Get some children for a parent --")
        [logging.info(" -- %s" % c.name) for c in self.get_all_children_for_a_parent() if c.name == "Child num 0 with parent Parent num 0" or c.name == "Doesn't exist" ]

        logging.info("-- Get parent for child --")
        child = Child_model.all()[0]
        logging.info("Child: %s" % child.name)
        logging.info("Parent: %s" % child.parent().name)

    def get_all_children_for_a_parent(self):
        parent = Parent_model.all()[0]
        logging.info(" - %s" % parent.name)
        return Child_model().all().ancestor(parent)

    def populate(self):
        root = Root_model(key_name="root")
        root.put()

        parents = []
        for i in range(3):
            parents.append( Parent_model(parent=root, name="Parent num %d" % i) )
        db.put(parents)

        import random
        children = []
        for p in parents:
            for i in range(random.randint(0,10)):
                children.append( Child_model(parent=p, name="Child num %d with parent %s" % (i, p.name)) )
        db.put(children)

app = webapp2.WSGIApplication([('/(.*)', MainHandler)],
                                debug=True)
def main():
    run_wsgi_app(app)

if __name__ == '__main__':
    main()

rawDescription: Google App Engine Datastore / NoSQL example with ancestor queries


code:
lines = [[tuple(vertices[j]) for j in i]for i in segs]

lc = matplotlib.collections.LineCollection(lines)

rawDescription: In python, drawing a list of line segments given their indices


code:
def activate():
    global x1, y1
    if(ultrasonic.get_sample() < 10):
        both.turn(power=-70, tacho_units=400, brake=False)
    bx, by = get_ballxy()
    rx, ry, a = get_robotxya()

    if sqrt((x1-bx)*(x1-bx)+(y1-by)*(y1-by)) <= 4: #This is the distance parameter, change at will
        turn_to(brick, bx, by, rx, ry, a)
        move_to(brick, bx, by, rx, ry)
        kickBall(brick, by, ry)

    x1, y1 = bx, by

Thread(target=update_coordinates).start()
connect()
x1, y1 = 0, 0
update_coordinates()
while True:
    activate()

rawDescription: How do i return the correct values of to this?

description: Return the correct values of to this


rawDescription: Python Regex: why does this not work?

description: Python Regex: why does this not work


code:
if form.is_valid():
            instance = form.save(commit=False)
            Verbraucher_form = form.cleaned_data['Verbraucher']
            Stand_form = form.cleaned_data['Stand']
            Stand_db = Daten.objects.filter(Verbraucher=Verbraucher_form).values('Stand').order_by('-Stand')[0]
            Stand_db2 = decimal.Decimal(Stand_db['Stand'])
            instance.Verbrauch = (Stand_form - Stand_db2)
            instance.save()

rawDescription: Django calculation based on form and database values


code:
import numpy as np
import cv2

image_src = cv2.imread("roi.png")

gray = cv2.cvtColor(image_src, cv2.COLOR_BGR2GRAY)
ret, gray = cv2.threshold(gray, 250, 255,0)

image, contours, hierarchy = cv2.findContours(gray, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
mask = np.zeros(image_src.shape, np.uint8)
largest_areas = sorted(contours, key=cv2.contourArea)
cv2.drawContours(mask, [largest_areas[-2]], 0, (255,255,255,255), -1)
removed = cv2.add(image_src, mask)

cv2.imwrite("removed.png", removed)

rawDescription: removing largest contour from an image

description: Removing largest contour from an image


code:
appenders = range(7)
mylists = [alist, blist, clist, dlist, elist, flist, glist]
for x, lst in zip(appenders, mylists):
    lst.append(x)

rawDescription: Appending multiple returned values to different lists in Python


code:
chunksize = 43
for i in range(0, len(nums), chunksize):
    #print 'putting chunk %s:%s in job Q' % (i, i + chunksize)
    shared_job_q.put(nums[i:i + chunksize]) # Adds a 43-item chunk to the shared queue.

rawDescription: From multiprocessing to distributed processing in python standard library


code:
from pyPdf import PdfFileReader

pdf = PdfFileReader(file('example.pdf'))
page = pdf.getPage(0).mediaBox
if page.getUpperRight_x() - page.getUpperLeft_x() > page.getUpperRight_y() - page.getLowerRight_y():
    print('Landscape')
else:
    print('Portrait')

rawDescription: PDF FILE ORIENTATION detection

description: PDF FILE ORIENTATION detection


code:
def queryMyUserWithStructuredPropertyFilter():
    shail_users_query = MyUser.query(MyUser.email_id == "napolean@gmail.com", MyUser.my_data.strength > 30)
    shail_users_list = shail_users_query.fetch(10)

    # Here, shail_users_list has at most 10 users with email being
    # 'napolean@gmail.com' and at least one element in my_data
    # with strength > 30

    maindatalist = [
        [[data.strength, str(data.date)] for data in user.my_data if data.strength > 30] for user in shail_users_list
    ]

    # Now in maindatalist you have ONLY those my_data with strength > 30
    return maindatalist

rawDescription: NDB query using filters on Structured property which is also repeated ?


$where: function() { for (var i=0; i<1000000; i++) {}; return true; }

rawDescription: Sanitizing inputs to MongoDB

description: Sanitizing inputs to MongoDB


code:
dict_data = defaultdict(list)
for item in list_data:
    dict_data[item.category].append(item)

rawDescription: multiple values in a dictionary python

description: Multiple values in a dictionary python


code:
import pandas as pd
fd = 'file path'
data = pd.read_excel( fd, sheetname=0 )

rawDescription: Pandas: Always selecting the first sheet/tab in an Excel Sheet


code:
import shutil
def ignored_files(adir,filenames):
    return [filename for filename in filenames if not filename.endswith('foo')]

shutil.copytree(source, destination, ignore=ignored_files)

rawDescription: python copytree with negated ignore pattern

description: Python copytree with negated ignore pattern


code:
tz = timezone('US/Eastern')
datetime.now(timezone(tz)).hour<19

rawDescription: Django How to find out if earlier than 7pm in a specific timezone


code:
from django.http import QueryDict
q = QueryDict(u'x=foo³&x=bar(potato),x=hello world')
q.lists()
q.urlencode(safe='()')

rawDescription: Can I make Django QueryDict preserve ordering?

description: Make Django QueryDict preserve ordering


rawDescription: Removing specific html tags with python

description: Removing specific html tags with python


code:
class MyForm(forms.Form):
  speciality = forms.ModelChoiceField(queryset=Speciality.objects.all())

rawDescription: Populate form field with data from model without using foreign key


rawDescription: Insert values into pandas datafrmae based on MUltiIndex


code:
FROM = "LEEDS BRADFORD"

depart_from = driver.find_element_by_id("ctl00_centralDynamicContent_originatingAirportDropDown")
depart_from.click()

option = depart_from.find_element_by_css_selector('option[title="%s"]' % FROM)
option.click()

rawDescription: Call variable for a drop down menu in python


code:
from matplotlib.pyplot import *
import numpy as np

fig,ax1 = subplots(1,1)
ax2 = ax1.twinx()
ax2.set_navigate(False)
x = np.linspace(0,2*np.pi,100)
ax1.plot(x,np.sin(x),'b')
ax1.set_xlabel('Scaleable axis')
ax1.set_ylabel('Scaleable axis')
ax2.plot(x,np.sin(x+1),'r')
ax2.set_ylabel('Static axis',weight='bold')

rawDescription: Multiple y-scales but only one enabled for pan and zoom


code:
s = pd.Series(['one','two','three','four'])
recodes = {'one':'A', 'two':'B', 'three':'C'}
s.map(recodes)
s.replace(recodes)

rawDescription: Python 'map' function inserting NaN, possible to return original values instead?


code:
def my_function(*args):
   if len(args) == 0:
       return x[y[args[0]]]
   return [x[y[a]] for a in args]

rawDescription: Unpacking arguments from dict and list

description: Unpacking arguments from dict and list


code:
# renamee is the file getting renamed, pre is the part of file name before extension and ext is current extension
pre, ext = os.path.splitext(renamee)
os.rename(renamee, pre + new_extension)

rawDescription: changing file extension in python

description: Changing file extension in python


code:
import os
import sys

# Add vendor directory to module search path
parent_dir = os.path.abspath(os.path.dirname(__file__))
vendor_dir = os.path.join(parent_dir, 'vendor')

sys.path.append(vendor_dir)

# Now you can import any library located in the "vendor" folder!
import requests

rawDescription: Embedding a Python library in my own package


code:
import matplotlib.pyplot as plt

ax = plt.subplot(111)
pos1 = ax.get_position() # get the original position
pos2 = [pos1.x0 + 0.3, pos1.y0 + 0.3,  pos1.width / 2.0, pos1.height / 2.0]
ax.set_position(pos2) # set a new position

rawDescription: Matplotlib: get and set axes position

description: Matplotlib: get and set axes position


code:
def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

rawDescription: Generating an MD5 checksum of a file

description: Generating an MD5 checksum of a file


code:
# there is no need to import the `string` module; `.strip()` is a built-in
# method of strings (i.e. objects of type `str`).

# read in the data as a list of pairs of raw (i.e. unparsed) coordinates in
# string form:
with open(r'C:\coordinates.txt') as in_file:
    coords_raw = [line.strip().split() for line in in_file.readlines()]

# convert the raw list into a list of pairs (2-tuples) containing the parsed
# (i.e. float not string) data:
coord_pairs = [(float(x_raw), float(y_raw)) for x_raw, y_raw in coords_raw]

coord_pairs.sort()  # you want to sort the entire data set, not just values on
                    # individual lines as in your original snippet

# build a list of all x and y values we have (this could be done in one line
# using some `zip()` hackery, but I'd like to keep it readable (for you at
# least)):
all_xs = [x for x, y in coord_pairs]
all_ys = [y for x, y in coord_pairs]
# compute min and max:
x_min, x_max = min(all_xs), max(all_xs)
y_min, y_max = min(all_ys), max(all_ys)

# NOTE: the above section performs well for small data sets; for large ones, you
# should combine the 4 lines in a single for loop so as to NOT have to read
# everything to memory and iterate over the data 6 times.

# write everything out
with open(r'C:\coordinates_sorted.txt', 'wb') as out_file:
    # here, we're doing 3 things in one line:
    #   * iterate over all coordinate pairs and convert the pairs to the string
    #     form
    #   * join the string forms with a newline character
    #   * write the result of the join+iterate expression to the file
    out_file.write('\n'.join('%f,%f' % (x, y) for x, y in coord_pairs))

    out_file.write('\n\n')
    out_file.write('%f %f %f %f' % (x_min, x_max, y_min, y_max))

rawDescription: Python script for trasnforming ans sorting columns in ascending order, decimal cases


code:
@requireparams(['name', 'pass', 'code'])
def complex_function(params):
    print(params['name'])
    print(params['pass'])
    print(params['code'])
params = {
    'name': 'John Doe',
    'pass': 'OpenSesame',
    #'code': '1134',
}
complex_function(params)

rawDescription: Python: Why does this doc test fail?

description: Python: Why does this doc test fail


code:
from BeautifulSoup import BeautifulSoup

# Here's your HTML
html = '
item1

item2

item3
'

# Here's some simple HTML that breaks your accepted
# answer, but doesn't break BeautifulSoup.
# For each example, the regex will ignore the first
 tag.
html2 = '
item1

item2

item3
'
html3 = '
item1

item2

item3
'
html4 = '
item1

item2

item3
'

# This BeautifulSoup code works for all the examples.
paragraphs = BeautifulSoup(html).findAll('p')
items = [''.join(p.findAll(text=True)) for p in paragraphs]

rawDescription: Python regular expression for multiple tags


code:
class Comment(db.Model):
    series = db.ReferenceProperty(reference_class=Series);

    def series_id(self):
        return Comment.series.get_value_for_datastore(self)

rawDescription: How do I get the key value of a db.ReferenceProperty without a database hit?

description: Get the key value of a db.ReferenceProperty without a database hit