code:
def concreter(abclass):
    """
    >>> import abc
    >>> class Abstract(metaclass=abc.ABCMeta):
    ...     @abc.abstractmethod
    ...     def bar(self):
    ...        return None

    >>> c = concreter(Abstract)
    >>> c.__name__
    'dummy_concrete_Abstract'
    >>> c().bar() # doctest: +ELLIPSIS
    (<abc_utils.Abstract object at 0x...>, (), {})
    """
    if not "__abstractmethods__" in abclass.__dict__:
        return abclass
    new_dict = abclass.__dict__.copy()
    for abstractmethod in abclass.__abstractmethods__:
        #replace each abc method or property with an identity function:
        new_dict[abstractmethod] = lambda x, *args, **kw: (x, args, kw)
    #creates a new class, with the overriden ABCs:
    return type("dummy_concrete_%s" % abclass.__name__, (abclass,), new_dict)

rawDescription: Python - Testing an abstract base class

description: Python - Testing an abstract base class


code:
class Upperware(object):
  def __init__(self, app):
    self.wrapped_app = app

  def __call__(self, environ, start_response):
    def my_start_response(status, response_headers, exc_info=None):
      write = start_response(status, response_headers, exc_info)
      def my_write(body_data):
        # Do your middleware handling of writes here
        body_data = body_data.upper()
        write(body_data)
      return my_write
    return self.wrapped_app(environ, my_start_response)

rawDescription: How to add to AppEngine a WSGI middleware that modifies the body of the response

description: Add to AppEngine a WSGI middleware that modifies the body of the response


code:
from scipy.stats.distributions import norm

def prob_distribution(day, mean_day, std):
    start_z = float((day - mean_day).days) / std
    end_z = float((day - mean_day).days + 1) / std
    return norm.cdf(end_z) - norm.cdf(start_z)

df['Prob'] = df['Poss_Date'].apply(lambda day: prob_distribution(day, datetime(2016,2,1), 10))

rawDescription: Input a mean and standard deviation to apply probability distribution across DataFrame Pandas Python


code:
from gdata.media import YOUTUBE_NAMESPACE
from atom import ExtensionElement

# set video as unlisted
kwargs = {
    "namespace": YOUTUBE_NAMESPACE,
    "attributes": {'action': 'list', 'permission': 'denied'},
}
extension = ([ExtensionElement('accessControl', **kwargs)])

# create the gdata.youtube.YouTubeVideoEntry
video_entry = gdata.youtube.YouTubeVideoEntry(media=my_media_group,
    geo=where, extension_elements=extension)

rawDescription: Upload a video to Youtube using the python API and set it as unlisted


code:
import csv
import sys
import urllib2

csvfile = list(csv.reader(open(sys.argv[1])))
for row in csvfile:
  sid = "http://myurl.com?sid="+row[13]
  urllib2.urlopen(sid)

rawDescription: Hitting url's stored in a variable in python


code:
dis.dis(method1)
dis.dis(method2)

rawDescription: Performance of Python list comprehension: rebuilding lambda in `if` part?


code:
dropdown = driver.find_element_by_css_selector("div.frequency_select")
dropdown.click()

once_a_week = driver.find_element_by_xpath("//*[. = 'At most once a week']")
once_a_week.click()

rawDescription: Manipulating the html source-code of a third party website using python


rawDescription: How to subtract multiple string values from another string

description: Subtract multiple string values from another string


code:
import urllib2
opener = urllib2.build_opener()
response = opener.open('http://downloads.raspberrypi.org/NOOBS_latest')
response.read(4)
response.close()

rawDescription: Interrupting urllib.read

description: Interrupting urllib.read


code:
row_len = M.shape[0]
for j in range(M.shape[1]):
    T = range(j*row_len, (j+1)*row_len)
    plt.plot(T, M[j, :])
plt.show()

rawDescription: Concatenating plots of rows of a matrix in a single plot - Python


code: set(map(lambda url: url.rstrip('/'), myList))

rawDescription: Python removing similar urls from a list


rawDescription: itertools.product() return value

description: Itertools.product() return value


code:
import numpy as np
count_array = np.array([('foo',2),('bar',5),('baz',0)], dtype = np.object)
print(count_array)
# [[foo 2]
#  [bar 5]
#  [baz 0]]

idx = np.argsort(count_array[:, 1])
print(idx)
# [2 0 1]

print(count_array[idx])
# [[baz 0]
#  [foo 2]
#  [bar 5]]

rawDescription: sorting a python multi-dimensional array?

description: Sorting a python multi-dimensional array


code:
dup = "abc"
dup1 = str()  # a new, empty string.
for char in dup:
   dup1 += char + char  # strings concatenate using + and +=
dup1  # the duplicant string
dup  # the original is preserved

rawDescription: Duplicate each character in a string

description: Duplicate each character in a string


code:
url = "http://www.allflicks.net/wp-content/themes/responsive/processing/processing_us.php?draw=5&columns[0][data]=box_art&columns[0][name]=&columns[0][searchable]=true&columns[0][orderable]=false&columns[0][search][value]=&columns[0][search][regex]=false&columns[1][data]=title&columns[1][name]=&columns[1][searchable]=true&columns[1][orderable]=true&columns[1][search][value]=&columns[1][search][regex]=false&columns[2][data]=year&columns[2][name]=&columns[2][searchable]=true&columns[2][orderable]=true&columns[2][search][value]=&columns[2][search][regex]=false&columns[3][data]=genre&columns[3][name]=&columns[3][searchable]=true&columns[3][orderable]=true&columns[3][search][value]=&columns[3][search][regex]=false&columns[4][data]=rating&columns[4][name]=&columns[4][searchable]=true&columns[4][orderable]=true&columns[4][search][value]=&columns[4][search][regex]=false&columns[5][data]=available&columns[5][name]=&columns[5][searchable]=true&columns[5][orderable]=true&columns[5][search][value]=&columns[5][search][regex]=false&columns[6][data]=director&columns[6][name]=&columns[6][searchable]=true&columns[6][orderable]=true&columns[6][search][value]=&columns[6][search][regex]=false&columns[7][data]=cast&columns[7][name]=&columns[7][searchable]=true&columns[7][orderable]=true&columns[7][search][value]=&columns[7][search][regex]=false&order[0][column]=5&order[0][dir]=desc&start=0&length=25&search[value]=sherlock&search[regex]=false&movies=true&shows=true&documentaries=true&rating=netflix&_=1451768717982"
with requests.Session() as session:
    session.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"}
    session.get("http://www.allflicks.net/")

    response = session.get(url, headers={"Accept" : "application/json, text/javascript, */*; q=0.01",
                                         "X-Requested-With": "XMLHttpRequest",
                                         "Referer": "http://www.allflicks.net/",
                                         "Host": "www.allflicks.net"})
    print(response.json())

rawDescription: python requests.get() returns an empty string

description: Python requests.get() returns an empty string


code:
rate, data = wavfile.read(path)
# data0 is the data from channel 0.
data0 = data[:, 0]

rawDescription: Read the data of a single channel from a stereo wave file in Python


code:
def get_open_port():
        import socket
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(("",0))
        s.listen(1)
        port = s.getsockname()[1]
        s.close()
        return port

rawDescription: get open TCP port in Python

description: Get open TCP port in Python


code:
def spider_opened(self, spider):
    spider.started_on = datetime.now()
    ...

def spider_closed(self, spider):
    work_time = datetime.now() - spider.started_on
    ...

rawDescription: Calculating the total time for running a scrapy


code:
import html.parser
h = html.parser.HTMLParser()
with urllib.request.urlopen(link) as fin, open(
           "file.html", 'w', encoding='utf-8') as fout:
    for line in fin:
        fout.write(h.unescape(line.decode('utf-8')))

rawDescription: urllib.urlretrieve encoding is not kept

description: Urllib.urlretrieve encoding is not kept


code:
s=set(graph.subcomponent(source, mode="out"))
t=set(graph.subcomponent(target, mode="in"))
s.intersection(t)

rawDescription: Python igraph: get all possible paths in a directed graph


code:
f = request.files['file']
c = checksumMD5(f.stream)
f.seek(0)

sendFile = {"file": (f.filename, f.stream, f.mimetype)}

r = requests.post("http://myservicedotcom/upload", files=sendFile,
                  headers={"X-Auth-Token": token, "Checksum": c, "File-Size": actualSize})

rawDescription: Post uploaded file using requests

description: Post uploaded file using requests


code: struct.pack('>I', some_integer) + struct.pack('b'*len(long_array), *long_array)

rawDescription: How do I convert Perl's pack 'Nc*' format to struct.pack for Python?

description: Convert Perl's pack 'Nc*' format to struct.pack for Python


code:
#df['another']=np.random.random(some_number)
ax2=ax.twinx()
ax2.bar(left=x, height=df.another, width=0.02)

rawDescription: Matplotlib line collection and additional line


code:
_insecure_views = []

@my_blueprint.before_request
def require_login():
    if request.endpoint in _insecure_views:
        return
    # check for login here

def login_not_required(fn):
    '''decorator to disable user authentication'''
    endpoint = ".".join([some_blueprint.name, fn.func_name])
    _insecure_views.append(endpoint)
    return fn

@some_blueprint.route('/')
@login_not_required
def index():
    pass

rawDescription: Flask: Decorate every route at once?

description: Flask: Decorate every route at once


code:
delete_table = string.maketrans(string.ascii_lowercase, ' '*len(string.ascii_lowercase))
delete_table
''.join(c for c in map(chr, range(0, 256)) if c not in delete_table)

rawDescription: translate with empty string

description: Translate with empty string


rawDescription: python reassigment of variable

description: Python reassigment of variable


rawDescription: convert dec number to 6 bit binary number

description: Convert dec number to 6 bit binary number


code:
import gc
gc.set_debug(gc.DEBUG_STATS)
gc.collect()

rawDescription: How much time is the garbage collector using?


code:
from Tkinter import Frame, Tk, Label, Button
from PIL import Image, ImageTk, ImageFilter

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

    def createWidgets(self):
        self.img = Image.open("lineage.jpg")
        self.photo1 = ImageTk.PhotoImage(self.img.convert("RGB"))
        self.label1 = Label(self, image=self.photo1)
        self.label1.grid(row=0, column=0)

        self.photo2 = ImageTk.PhotoImage(self.img.convert("RGB"))
        self.label2 = Label(self, image=self.photo2)
        self.label2.grid(row=0, column=1)

        button = Button(self, text="Brighten", command=self.brighten)
        button.grid(row=0, column=2)

    def brighten(self):
        img2 = self.img.point(lambda p: p * 1.9)
        self.photo2 = ImageTk.PhotoImage(img2)
        self.label2 = Label(self, image=self.photo2)
        self.label2.grid(row=0, column=1)

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

rawDescription: python PIL and tkinter; brightening image and displaying it

description: Python PIL and tkinter; brightening image and displaying it


code:
# RasPi Temperature Sensor - Beginning Sensor Networks

#

# For this script, we explore connecting a digital temperature sensor

# to the Raspberry Pi and reading the data. We display the

# temperature

# in Celsius and Fahrenheit.

# Import Python modules (always list in alphabetical order)

import glob

import os

import time

# Issue the modprobe statements to initialize the GPIO and

# temperature sensor modules

os.system('modprobe w1-gpio')

os.system('modprobe w1-therm')

# Use glob to search the file system for directories that match the

# prefix.

# Save the path to the directory.

datadir = glob.glob('/sys/bus/w1/devices/28*')[0]

# Create the full path to the file

datafile = os.path.join(datadir, 'w1_slave')

# Procedure for reading the raw data from the file.

# Open the file and read all of the lines then close it.

def read_data():

    f = open(datafile, 'r')

    lines = f.readlines()

    f.close()

    return lines

# Read the temperature and return the values found.

def get_temp():

# Initialize the variables.

    temp_c = None

    temp_f = None

    lines = read_data()

    # <<<<<<<<<<<<<<< I INDENTED FROM HERE... <<<<<<<<<<<<<<<

    # If the end of the first line ends with something other than

    # 'YES'

    # Try reading the file again until 'YES' is found.

    while not lines[0].strip().endswith('YES'):

        time.sleep(0.25)

        lines = read_data()

    # Search the second line for the data prefixed with 't='

        pos = lines[1].find('t=')

    # A return code of -1 means it wasn't found.

    if pos != -1:

    # Get the raw data located after the 't=' until the end of the

        temp_string = lines[1][ pos+2:]

    # Convert the scale for printing

        temp_c = float(temp_string) / 1000.00

    # Convert to Farenheit

        temp_f = temp_c * 9.00 / 5.00 + 32.00

    return temp_c, temp_f

    # <<<<<<<<<<<<<<< ... TO HERE <<<<<<<<<<<<<<<

# Main loop. Read data then sleep 1 second until cancelled with CTRL-
# C.

while True:

    temp_c, temp_f = get_temp()

    print("Temperature is {0} degrees Celsius, "

    "{1} degrees Fahrenheit.".format(temp_c, temp_f))
    time.sleep(1)

rawDescription: Python: SyntaxError: 'return' outside of function


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

# some random data (10x10)
image = np.random.uniform(size=(10, 10))

plt.figure()

# draw the pixel image
#   interpolation='nearest': draw blocky pixels, do not smooth
#   cmap=pl.cm.gray: use gray scale colormap (autoscale, no vmin or vmax defined
#   origin='lower': draw first row of the array to the bottom if the image
#   extent=[-3,3,-10,10]: draw the image so that it covers area (-3,-10)..(3,10)
plt.imshow(image, cmap=plt.cm.gray, interpolation='nearest', origin='lower', extent=[-3,3,-10,10])

# this is needed to make the pixels non-square if needed
plt.axis('normal')

plt.colorbar()

plt.show()

rawDescription: Matplotlib, 3rd set of values as colors of colorbar


rawDescription: optimize the number of comparisons

description: Optimize the number of comparisons


code:
# Encoding Utf-8*
try:
    _from_utf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _from_utf8(s):
        return s
try:
    _encoding = QtGui.QApplication.UnicodeUTF8

    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

# Main Window

class Window (QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()

        self.setGeometry(100, 100, 800, 600)
        self.setWindowTitle(_from_utf8("Virtual Library"))
        self.setStyleSheet("background-image: url(nwlib.jpg);")

        # ExitOption
        menu_action1 = QtGui.QAction("Exit", self)
        menu_action1.setShortcut("Ctrl+Q")
        menu_action1.setStatusTip('Exit The App')
        menu_action1.triggered.connect(self.close_application)

        self.statusBar()

        # MenuBar
        main_menu = self.menuBar()
        file_menu = main_menu.addMenu('Options')
        file_menu.addAction(menu_action1)

        self.home()

    def home(self):

        # NewLibrary btn
        centralwidget = QtGui.QWidget(self)
        self.mainLayout = QtGui.QVBoxLayout(centralwidget)
        new_lib_btn = QtGui.QPushButton("New Library", self)
        new_lib_btn.setMinimumSize(141, 41)

        # AccessLibrary btn
        access_lib_btn = QtGui.QPushButton("Access Library", self)
        access_lib_btn.setMinimumSize(141, 41)

        # FindNewBooks btn
        find_nbooks = QtGui.QPushButton("Find New Books", self)
        find_nbooks.setMinimumSize(141, 41)

        self.mainLayout.addWidget(new_lib_btn)
        self.mainLayout.addWidget(access_lib_btn)
        self.mainLayout.addWidget(find_nbooks)

        self.mainLayout.setAlignment(QtCore.Qt.AlignCenter)

        self.setCentralWidget(centralwidget)

        self.show()

    def close_application(self):
        choice = QtGui.QMessageBox.question(self, 'Exit',
                                        "Close the application?",
                                        QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if choice == QtGui.QMessageBox.Yes:
            sys.exit()
        else:
            pass

def run():
    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())

run()

rawDescription: How do I make a resizable window and a resizable background image using PyQt?

description: Make a resizable window and a resizable background image using PyQt


code:
#!/usr/bin/env python
import random

k = 10
filename = 'TestingDeleteLines.txt'
with open(filename) as file:
    lines = file.read().splitlines()

if len(lines) > k:
    random_lines = random.sample(lines, k)
    print("\n".join(random_lines)) # print random lines

    with open(filename, 'w') as output_file:
        output_file.writelines(line + "\n"
                               for line in lines if line not in random_lines)
elif lines: # file is too small
    print("\n".join(lines)) # print all lines
    with open(filename, 'wb', 0): # empty the file
        pass

rawDescription: Python: Choose random line from file, then delete that line


code:
import unittest

from mock import patch, Mock

class MyTestCase(unittest.TestCase):
    @patch('boto.beanstalk.connect_to_region')
    def test_boto(self, connect_mock):
        eb = Mock()
        eb.create_storage_location.return_value = 'test'
        connect_mock.return_value = eb

        to_be_tested = ToBeTested()
        # assertions

rawDescription: Mocking modules from boto in python

description: Mocking modules from boto in python


code:
yy = numpy.tan(2*(x - numpy.pi/2))
threshold = 10000
yy[yy>threshold] = numpy.inf
yy[yy<-threshold] = numpy.inf
ax.plot(x, yy, linewidth=1.2, color="black")

rawDescription: Graphing tan in matplotlib

description: Graphing tan in matplotlib


code:
import os
import datetime

for filename in directory:
    modified_time = os.path.getmtime(filename)   # get file modification timestamp
    modified_date = datetime.date.fromtimestamp(modified_time)  # convert timestamp to a date
    os.rename(filename, modified_date.strftime("%Y-%m-%d"))

rawDescription: Change file name to date of modification


code:
tfidf = TfidfVectorizer(preprocessor=lambda x: x, tokenizer=lambda x: x)
tfidf_matrix = tfidf.fit_transform(corpus)

rawDescription: Scikit Learn - Calculating TF-IDF from a corpus of arrays of features instead of from a corpus of raw documents


code:
import Tkinter as tk
import ttk

#from PIL import Image

class Application:

    def __init__(self, parent):
        self.parent = parent

        self.content = ttk.Frame(parent, padding=(3,3,12,12))
        self.content.pack()
        self.content.columnconfigure(1, weight=1)
        self.content.rowconfigure(1, weight=1)

        self.row1()

    def row1(self):
        self.enButton = ttk.Button(self.content, text="Enable", command=self.enableCmd)
        self.disButton = ttk.Button(self.content, text="Disable", command=self.disableCmd)
        self.enButton.grid(column=1, row=1)
        self.disButton.grid(column=2, row=1)
        self.disButton.state(['disabled'])

    def enableCmd(self):
        self.disButton.state(['!disabled'])
        self.enButton.state(['disabled'])
        # self.ser.write("pe001\n")

    def disableCmd(self):
        self.disButton.state(['disabled'])
        self.enButton.state(['!disabled'])

if __name__ == '__main__':
    root = tk.Tk()
    root.title("PC Control Interface")
    #img = Image("photo", file="T.ico") # "appicon.gif"
    #root.tk.call('wm','iconphoto',root._w,img)

    app = Application(root)

    root.mainloop()

rawDescription: ttk widgets in frame not displayed

description: Ttk widgets in frame not displayed


code:
def average(D, i):
    # key iterates over all keys in the dictionary.
    # D[key][i] is the ith element of the list whose key is "key"
    return sum(D[key][i] for key in D)/len(D)

rawDescription: average of i-th position elements of a list in a dictionary python

description: Average of i-th position elements of a list in a dictionary python


code:
my_str = "thisissometextthatiwrote"
substr = "text"
inserttxt = "XX"

idx = my_str.index(substr)
my_str = my_str[:idx] + inserttxt + my_str[idx:]

rawDescription: Insert a string before a substring of a string


code:
# we need this:
from flask_login import encode_cookie

# ...then in the test:
with self.client.session_transaction():
    self.client.set_cookie(
        self.app.config['SERVER_NAME'],
        'remember_token',
        encode_cookie(user_id)
    )
    # assertions here... User is now logged in! \0/

rawDescription: Programmatically Flask login during tests


code:
import Image, colorsys

def HSVColor(img):
    if isinstance(img,Image.Image):
        r,g,b = img.split()
        Hdat = []
        Sdat = []
        Vdat = []
        for rd,gn,bl in zip(r.getdata(),g.getdata(),b.getdata()) :
            h,s,v = colorsys.rgb_to_hsv(rd/255.,gn/255.,bl/255.)
            Hdat.append(int(h*255.))
            Sdat.append(int(l*255.))
            Vdat.append(int(s*255.))
        r.putdata(Hdat)
        g.putdata(Sdat)
        b.putdata(Vdat)
        return Image.merge('RGB',(r,g,b))
    else:
        return None

a = Image.open('/tmp/a.jpg')
b = HSVColor(a)
b.save('/tmp/b.jpg')

rawDescription: RGB to HSV via PIL and colorsys

description: RGB to HSV via PIL and colorsys


code:
#import functions from selenium module
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# open chrome browser using webdriver
path_to_chromedriver = '/Users/Michael/Downloads/chromedriver'
browser = webdriver.Chrome(executable_path=path_to_chromedriver)

# open web page using browser
browser.get('http://kllads.kar.nic.in/MLAWise_reports.aspx')

# wait for page to load then find 'Constituency Name' dropdown and select 'Aland (46)''
const_name = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="ddlconstname"]')))
browser.find_element_by_xpath('//*[@id="ddlconstname"]/option[2]').click()

# wait for the page to load then find 'Select Status' dropdown and select 'OnGoing'
sel_status = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="ddlstatus1"]')))
browser.find_element_by_xpath('//*[@id="ddlstatus1"]/option[2]').click()

# wait for browser to load then click 'Generate Report'
gen_report = WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="BtnReport"]')))
browser.find_element_by_xpath('//*[@id="BtnReport"]').click()

rawDescription: How can I scrape this?

description: Scrape this


code:
filename = raw_input("enter file:")
with open(filename, 'r') as f, open(filename + '_value','w') as ff:
    # Read each line sequentially
    for line in f.read():
        # In each line, read each word
        total = 0
        for word in line.split():
            if word in list1:
                ff.write("%s\t%s\n" % (word, list1[word]))
                total += int(list1[word])
            else:
                ff.write(word+'\n')

        ff.write("\ntotal: %s\n" % total)

rawDescription: how to loop around every word in a line and then every line in a file?

description: Loop around every word in a line and then every line in a file


code:
class MyClass():

    def __init__(self, value):
        self.something = value

    @property
    def something(self):
        return self.item

    @something.setter
    def set_something(self, value):
        if value is not None:
            self.time = value
        else:
            raise Error

rawDescription: assigning a value to a class object

description: Assigning a value to a class object


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.lines import Line2D

# The line format you curently have:
lines = [[(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)],
         [(0, 1, 2, 3, 4), (0, 1, 2, 3, 4)],
         [(0, 1, 2, 3, 4), (8, 7, 6, 5, 4)],
         [(4, 5, 6, 7, 8), (0, 1, 2, 3, 4)]]

# Reformat it to what `LineCollection` expects:
lines = [zip(x, y) for x, y in lines]

z = np.array([0.1, 9.4, 3.8, 2.0])

fig, ax = plt.subplots()
lines = LineCollection(lines, array=z, cmap=plt.cm.rainbow, linewidths=5)
ax.add_collection(lines)
fig.colorbar(lines)

# Manually adding artists doesn't rescale the plot, so we need to autoscale
ax.autoscale()

def make_proxy(zvalue, scalar_mappable, **kwargs):
    color = scalar_mappable.cmap(scalar_mappable.norm(zvalue))
    return Line2D([0, 1], [0, 1], color=color, **kwargs)
proxies = [make_proxy(item, lines, linewidth=5) for item in z]
ax.legend(proxies, ['Line 1', 'Line 2', 'Line 3', 'Line 4'])

plt.show()

rawDescription: Add legends to LineCollection plot

description: Add legends to LineCollection plot


code:
from sklearn import preprocessing
X = [[ 1., -1.,  2.],
     [ 2.,  0.,  0.],
     [ 0.,  1., -1.]]
X_scaled = preprocessing.scale(X)
X_scaled

rawDescription: Scaling data in scikit-learn SVM

description: Scaling data in scikit-learn SVM


code:
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate

def send_mail(send_from, send_to, subject, text, files=None,
              server="127.0.0.1"):
    assert isinstance(send_to, list)

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
            part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
            msg.attach(part)

    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

rawDescription: How to send email attachments with Python

description: Send email attachments with Python


code:
def close_far(a, b, c):
  x, y, z = sorted([a, b, c])
  delta_close, delta_far = sorted([y - x, z - y])
  return delta_close <= 1 and delta_far >= 2

rawDescription: Alternative approaches to comparing values


code:
class Edge(EdgeBase):
    def __new__(cls, left, right):
        self = super(Edge, cls).__new__(cls, left, right)
        self._hash = hash(self.left) * hash(self.right)
        return self

    def __hash__(self):
        return self._hash

rawDescription: How to provide additional initialization for a subclass of namedtuple?

description: Provide additional initialization for a subclass of namedtuple


rawDescription: Pairwise circular Python 'for' loop

description: Pairwise circular Python 'for' loop


code: r'^\s*service (.*)$\n^\s*enable (\w+)$^\s*frequency (\d+)$'

rawDescription: select text in a string and convert into a table in python

description: Select text in a string and convert into a table in python


code:
def main():
    import argparse
    parser = argparse.ArgumentParser(description='user-data-script.py: initial python instance startup script')
    parser.add_argument('--skip-update', default=False, action='store_true', help='skip apt package updates')
    # parser.add_argument whatever else you need
    args = parser.parse_args()

    if not args.skip_update:
        # do update
        import apt
        cache = apt.Cache()
        cache.update()
        cache.open(None)
        cache.upgrade()
        cache.commit()

        # restart, and skip update
        import os, sys
        command = sys.argv[0]
        args = sys.argv
        if skipupdate:
            args += ['--skip-update']
        os.execv(command, args)

    else:
        # run your usual code
        pass

if __name__ == '__main__':
    main()

rawDescription: Update python itself using the apt module


code:
merged = df.merge(df2)
merged
merged.pivot_table('rating', 'title', 'userId')

rawDescription: Python Pandas: combine 2 dataframes, one frame's column as the final result's index


code:
def my_func(context, data):
    try:
        reference, saved = my_func.cache
    except AttributeError:
        reference, saved = None, None
    computed = saved if reference == context else foo(context)
    my_func.cache = context, computed
    return bar(computed, data)

rawDescription: Can I use (mis-use) the globals() namespace for persistent storage?

description: Use (mis-use) the globals() namespace for persistent storage


code:
import io

import ctypes
msvcrt = ctypes.cdll.msvcrt
kernel32 = ctypes.windll.kernel32
user32 = ctypes.windll.user32

from PIL import ImageGrab

img = ImageGrab.grab()
output = io.BytesIO()
img.convert('RGB').save(output, 'BMP')
data = output.getvalue()[14:]
output.close()

CF_DIB = 8
GMEM_MOVEABLE = 0x0002

global_mem = kernel32.GlobalAlloc(GMEM_MOVEABLE, len(data))
global_data = kernel32.GlobalLock(global_mem)
msvcrt.memcpy(ctypes.c_char_p(global_data), data, len(data))
kernel32.GlobalUnlock(global_mem)
user32.OpenClipboard(None)
user32.EmptyClipboard()
user32.SetClipboardData(CF_DIB, global_mem)
user32.CloseClipboard()

rawDescription: Copy PIL/PILLOW Image to Windows Clipboard


code:
if len(cmdtup) >= 3:
    cmdtup.append(1)

rawDescription: Handling variable length command tuple with try...except


rawDescription: aggregating within a groupby

description: Aggregating within a groupby


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

im = plt.imread('example.jpg')
im /= 255.   # normalise to 0-1, it's easier to work in float space

# make some kind of kernel, there are many ways to do this...
t = 1 - np.abs(np.linspace(-1, 1, 21))
kernel = t.reshape(21, 1) * t.reshape(1, 21)
kernel /= kernel.sum()   # kernel should sum to 1!  :)

# convolve 2d the kernel with each channel
r = scipy.signal.convolve2d(im[:,:,0], kernel, mode='same')
g = scipy.signal.convolve2d(im[:,:,1], kernel, mode='same')
b = scipy.signal.convolve2d(im[:,:,2], kernel, mode='same')

# stack the channels back into a 8-bit colour depth image and plot it
im_out = np.dstack([r, g, b])
im_out = (im_out * 255).astype(np.uint8)

plt.subplot(2,1,1)
plt.imshow(im)
plt.subplot(2,1,2)
plt.imshow(im_out)
plt.show()

rawDescription: Image smoothing in Python

description: Image smoothing in Python


code:
if is_suse10():
    from MyClass import MyClass as Base
elif is_suse11():
    from MyClass1 import MyClass1 as Base
else:
    raise UnsupportedPlatformError()

class SubClass(Base):
    def __init__(self, Sample):
        super(SubClass, self).__init__(Sample)

rawDescription: How to inherit from one of two base classes, deciding on runtime

description: Inherit from one of two base classes, deciding on runtime


code:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

mu = 0.09
v = 0.15
s0 = 500
#Expected return k (per year), k = mu-(v**2)/2
k = mu-(v**2)/2

t=np.arange(0,250)

#Simulation
s1 =  s0*np.exp(k*t/250+v*s0*np.sqrt(t/250))
plt.figure(figsize=(10, 6), dpi=80)

plt.plot(t,s1)

plt.xlim(0.0, 250.0)
plt.xticks(np.linspace(0, 250, 11, endpoint=True))
#plt.ylim(0, 10000)
# plt.yticks(np.linspace(00, 10000, 10, endpoint=True))

plt.title(r'Stock Returns')

rawDescription: Iterating and graph plotting in Python?

description: Iterating and graph plotting in Python


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

# Note the non-"even" size... (not a multiple of 2, 5, or 10)
data = np.random.random((73, 78))

fig, axes = plt.subplots(ncols=3)
for ax, title in zip(axes, ['Default', 'axis("tight")', 'axis("image")']):
    ax.pcolormesh(data)
    ax.set(title=title)

axes[1].axis('tight')
axes[2].axis('image')

plt.show()

rawDescription: Remove whitespace from matplotlib heatplot


code:
from reportlab.pdfbase.pdfmetrics import stringWidth
from reportlab.rl_config import defaultPageSize

PAGE_WIDTH  = defaultPageSize[0]
PAGE_HEIGHT = defaultPageSize[1]

text = "foobar foobar foobar"
text_width = stringWidth(text)
y = 1050 # wherever you want your text to appear
pdf_text_object = canvas.beginText((PAGE_WIDTH - text_width) / 2.0, y)
pdf_text_object.textOut(text) # or: pdf_text_object.textLine(text) etc.

rawDescription: Python Reportlab PDF - Centering Text on page


code: [re.sub("/\*.+\*/", "", m).replace('\n', '').strip() for m in re.findall("{(.+?)};", c_file_as_string, re.S)]

rawDescription: How to parse C array in python

description: Parse C array in python


code:
# Finds all bold matches which contain the class title
bold_matches = driver.find_elements_by_class_name('bold')
class_title = ''
class_description = ''
for bold_match in bold_matches:
    # If the class title matches, we set our class title
    if bold_match.text[:bold_match.text.find('.')] == class_number:
        class_title = bold_match.text

        # We find the class description from the class title
        all_elements = driver.find_elements_by_xpath('//*')
        matching_index = all_elements.index(bold_match) + 2
        class_description = all_elements[matching_index].text

rawDescription: Find next tag using Selenium Python

description: Find next tag using Selenium Python


code:
users = ["user1", "user2"]
pws = ["password", "12354"]
dict(zip(users, pws))

rawDescription: Python33 - SQLite3 accounts with authentication


code:
for coin in coinlist[:]:
    coin.pickup()

rawDescription: why won't all coins on the list be deleted?

description: Why won't all coins on the list be deleted


code:
from tornado.httpclient import HTTPRequest
request = HTTPRequest(opt.site_url + '/api/user/', method="PUT", body=urlencode(pdata))
response = yield gen.Task(http_client.fetch, request)

rawDescription: PUT request from tornado.httpclient.AsyncHTTPClient


code:
ns=[2, 2, 2, 0, 2, 1, 3, 3]
{x: ns.count(x) for x in set(ns) if ns.count(x) > 1}

rawDescription: finding and returning names and counts of duplicate values in Python list

description: Finding and returning names and counts of duplicate values in Python list


code:
from theano.compile.ops import as_op

@as_op(itypes=[theano.tensor.imatrix],
       otypes=[theano.tensor.imatrix])
def numpy_unique(a):
    return numpy.unique(a)

rawDescription: Theano get unique values in a tensor

description: Theano get unique values in a tensor


code:
import telnetlib
# ...

a_tuple = [('172.28.247.240', 66)]
HOST = a_tuple[0] # do you mean to use 'a_tuple' instead of 'j'?
# ...

tn = telnetlib.Telnet(HOST[0], HOST[1]) # <-- pass the port, I don't think this accepts tuples of hostname/ip and port
# ...

rawDescription: Python program to connect to console via telnetlib


code:
codes = list('ABCDEFGH');
dates = pd.Series(pd.date_range('2013-11-01', '2014-01-31'));
dates = dates.append(dates)
dates.sort()
df = pd.DataFrame({'amount': np.random.randint(1, 10, dates.size), 'col1': np.random.choice(codes, dates.size), 'col2': np.random.choice(codes, dates.size), 'date': dates})

kw = lambda x: x.isocalendar()[1];
kw_year = lambda x: str(x.year) + ' - ' + str(x.isocalendar()[1])
grouped = df.groupby([df['date'].map(kw_year), 'col1'], sort=False, as_index=False).agg({'amount': 'sum'})
A = grouped.pivot(index='date', columns='col1', values='amount').fillna(0).reset_index()

ticks = A.date.values.tolist()
del A['date']
ax = A.plot(kind='bar')
ax.set_xticklabels(ticks)

rawDescription: Pandas: Group by calendar-week, then plot grouped barplots for the real datetime


code:
shape = array.shape
array = array.flatten()
numpy.random.shuffle(array)
array = array.reshape(shape)

rawDescription: Unexpected result from numpy random.shuffle


code:
import ast

txt = r"{u'results': [{u'status': u'OK', u'time': 199, u'name': u'Macap\xe1'}]}"
obj = ast.literal_eval(txt)

rawDescription: Read malformed JSON in Python

description: Read malformed JSON in Python


code:
import pyqtgraph as pg
plot = pg.plot()

e1 = pg.QtGui.QGraphicsEllipseItem(0, 0, 4, 4)
# MUST have width=0 here, or use a non-cosmetic pen:
e1.setPen(pg.mkPen('r', width=0))
e1.setFlag(e1.ItemClipsChildrenToShape)
plot.addItem(e1)

e2 = pg.QtGui.QGraphicsEllipseItem(2, 2, 4, 4)
e2.setPen(pg.mkPen('g'))
e2.setParentItem(e1)

rawDescription: Pyqtgraph clip line

description: Pyqtgraph clip line


code:
def f1(deck):
    deck = [1,2,3] # This does not change the `deck` passed.
def f2(deck):
    deck[:] = [4,5,6] # This change the `deck` passed.
deck = [0]
f1(deck)
deck
f2(deck)
deck

rawDescription: Why doesn't my code mutate the list?

description: Why doesn't my code mutate the list


code:
shapes = ["tri", "angle"]
groupedShapes = "".join(shapes)
# "triangle"

rawDescription: How do you turn lists with multiple characters into strings?

description: Turn lists with multiple characters into strings


code:
from datetime import datetime, timedelta
dt = datetime.now()
td = timedelta(days=4)
# your calculated date
my_date = dt + td

rawDescription: Python Get Date In Future (x) Days, And Hours Left To Date?


code:
lists = []

for dirpath, dirnames, filenames in os.walk(...):
    lists.append(...)

rawDescription: Creating many arrays at once

description: Creating many arrays at once


code:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
import numpy as np

im = np.array(Image.open('stinkbug.png'), dtype=np.uint8)

# Create figure and axes
fig,ax = plt.subplots(1)

# Display the image
ax.imshow(im)

# Create a Rectangle patch
rect = patches.Rectangle((50,100),40,30,linewidth=1,edgecolor='r',facecolor='none')

# Add the patch to the Axes
ax.add_patch(rect)

plt.show()

rawDescription: matplotlib: how to draw a rectangle on image

description: Matplotlib: how to draw a rectangle on image


code:
import pandas as pd
from StringIO import StringIO
import matplotlib.pyplot as plt

data = \
"""wafer_number,test_type,test_pass,x_coord,y_coord,test_el_id,wavelength,intensity
HT2731,T2,1,38,54,24,288.68,4413
HT2731,T2,1,40,54,25,257.42,2595
HT2731,T2,1,50,54,28,300.00,2836
HT2731,T2,1,52,54,29,300.00,2862
HT2731,T2,1,54,54,30,300.00,3145
HT2731,T2,1,56,54,31,300.00,2804
HT2731,T2,1,58,54,32,255.69,2803
HT2731,T2,1,59,54,33,257.23,2991
HT2731,T2,1,60,54,34,262.45,3946
HT2731,T2,1,62,54,35,291.84,9398
HT2801,T2,1,38,55,54,288.68,4125
HT2801,T2,1,38,56,55,265.25,4258"""

df = pd.read_csv(StringIO(data),sep = ',')
dfg = df.groupby('wafer_number')

colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k')
fig, ax = plt.subplots()
for i,k in enumerate(dfg.groups.keys()):
    currentGroup = df.loc[dfg.groups[k]]
    color = colors[i % len(colors)]
    ax.plot(currentGroup['wavelength'].values,currentGroup['intensity'].values,\
            ls='', color = color, label = k, marker = 'o', markersize = 8)
legend = ax.legend(loc='upper center', shadow=True)
plt.xlabel('wavelength')
plt.ylabel('intensity')
plt.show()

rawDescription: Pandas dataframe manipulation and plotting


code: probs = probs / np.sum(probs)

rawDescription: Getting an arrays of equal length from numpy histogram or plotting the uneven array


code:
class BrokenIterator(object):
    def __init__(self):
        self.callcount = 0
    def __iter__(self):
        return self
    def next(self):
        self.callcount += 1
        if self.callcount == 1:
            return 1
        elif self.callcount == 3:
            return 2
        else:
            raise StopIteration

rawDescription: Two-shot generator

description: Two-shot generator


code:
from PyQt4.Qt import *
import math

app = QApplication([])

img = QImage(256, 256, QImage.Format_RGB32)
dc = QPainter(img)
dc.fillRect(0, 0, 256, 256, QColor(192, 192, 192))
dc.setRenderHints(QPainter.Antialiasing)
dc.setPen(QPen(QColor(128, 128, 192),
               12.0,
               Qt.SolidLine,
               Qt.RoundCap,
               Qt.RoundJoin))
pts = []
for i in xrange(7):
    t = i * 2 * 3 * math.pi / 7
    pts.append(QPointF(128 + 100 * math.cos(t),
                       128 + 100 * math.sin(t)))
dc.drawPolyline(QPolygonF(pts))
dc = None
img.save("output.png")

rawDescription: Draw lines with settings for line cap and line join


code:
data = json.load(...)
pprint.pprint(data)

rawDescription: How do I view this in an easy format to read? (JSON)

description: View this in an easy format to read? (JSON)


code: found = next((tup for tup in outer_tuple if tup.id == desired_id), None)

rawDescription: how to 'index' a named tuple

description: 'index' a named tuple


code:
def figure_out_spouse_class(self):
    return [b.__name__ for b in self.__class__.__bases__ if b != Father]

rawDescription: Python: Figure out "Spouse" class?

description: Python: Figure out "Spouse" class


code:
import re
from voluptuous import All, Invalid, Required, Schema

def Email(msg=None):
    def f(v):
        if re.match("[\w\.\-]*@[\w\.\-]*\.\w+", str(v)):
            return str(v)
        else:
            raise Invalid(msg or ("incorrect email address"))
    return f

schema = Schema({
        Required('email') : All(Email())
    })

schema({'email' : "invalid_email.com"}) # <-- this will result in a MultipleInvalid Exception
schema({'email' : "valid@email.com"}) # <-- this should validate the email address

rawDescription: How can i validate an url and email with python voluptuous?

description: Validate an url and email with python voluptuous


code:
def allclose(x, y, rtol=1.e-5, atol=1.e-8):
    return all(less_equal(abs(x-y), atol + rtol * abs(y)))

rawDescription: numpy.allclose and multiprecision with mpmath

description: Numpy.allclose and multiprecision with mpmath


rawDescription: Python regex help

description: Python regex help


code:
[l[1] for l in DICT['XYZ']]
min(l[1] for l in DICT['ABC'])
sorted(DICT, key=lambda k: min(l[1] for l in DICT[k]))

rawDescription: Python sorting a dictionary whose value is a multidimensional list


rawDescription: How to convert a binary file into a Long integer?

description: Convert a binary file into a Long integer


code:
import urllib2
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', 'cookiename=cookievalue'))
f = opener.open("http://example.com/")

rawDescription: python: urllib2 how to send cookie with urlopen request

description: Python: urllib2 how to send cookie with urlopen request


code:
import Image, StringIO
from cairo import PDFSurface, Context, ImageSurface

pdf = PDFSurface("out.pdf", 1000, 1000)
cr = Context(pdf)
im = Image.open("/home/seif/Pictures/prw.jpg")
buffer = StringIO.StringIO()
im.save(buffer, format="PNG")
buffer.seek(0)
cr.save()
cr.set_source_surface(ImageSurface.create_from_png(buffer))
cr.paint()

rawDescription: paint decoded jpeg to cairo surface

description: Paint decoded jpeg to cairo surface


code:
import re
line = '10.223.157.186 - - [15/Jul/2009:15:50:35 -0700] "GET /assets/css/reset.css HTTP/1.1" 200 1014'
regexString = r'(?P<IP>[0-9.]+) (?P<ID>[\w-]+) (?P<user>[\w-]+) (?P<time>\[.*\]) (?P<request>".*") (?P<status>\d+) (?P<size>\d+)'
regex = re.compile(regexString)
match = regex.match(line)
if match != None:
    ip = match.group('IP')
    id = match.group('ID')
    # etc.

rawDescription: Spliting a sever access log string

description: Spliting a sever access log string


code: verb, title, definition = myString.split (' ', 2)

rawDescription: Need some help with python string / slicing operations


code: csv_writer = csv.writer(outfile, delimiter=';')

rawDescription: Why doesn't my CSV look like what i need it to look like?


code:
with fetch_lock:
    if url in fetching:
        lock = fetching[url]
    else:
        lock = threading.Lock()
        fetching[url] = lock
        do_fetch = True
        lock.acquire()
if not do_fetch:
    lock.acquire()

rawDescription: Python 3 - Race condition on lock indexed by string


rawDescription: Square root of all values in numpy array, preserving sign


code:
import sys
import os
from ftplib import FTP

ftp = FTP("ftpsite.com")
ftp.login()
ftp.cwd("/ftp/site/directory/")

listing = []
ftp.retrlines("LIST", listing.append)
words = listing[0].split(None, 8)
filesize = int(words[4])
filename = words[-1].lstrip()

class VerboseWriter:
    def __init__(self, lf, filesize):
        self.progress = 0
        self.lf = lf
        self.filesize = filesize
    def write(self, data):
        self.lf.write(data)
        self.progress += len(data)
        sys.stdout.write('\r{}/{} ({:.1%})'.format(self.progress, self.filesize, float(self.progress)/self.filesize))
        sys.stdout.flush()

#download the file
with open(os.path.join(r"c:\example", filename), 'wb') as f:
    ftp.retrbinary("RETR " + filename, VerboseWriter(lf, filesize).write, 8*1024)
print
ftp.quit()

rawDescription: Python FTPLIB error 530 Permission Denied


rawDescription: Creating new pandas DataFrame from existing DataFrame and index


code:
import itertools

with open('fileA.csv') as fa:
    with open('fileB.csv') as fb:
        for (i, (la, lb)) in enumerate(itertools.izip_longest(fa, fb)):
            print(i, la, lb)

rawDescription: Simultaneous file reading

description: Simultaneous file reading


rawDescription: Addressing ranges in a Scipy sparse matrix


rawDescription: Redirect to a URL which contains a 'variable part' in Flask (Python)


rawDescription: bits to string python

description: Bits to string python


rawDescription: Drawing an Arrow in Pygame

description: Drawing an Arrow in Pygame


code:
import operator
with open("file.txt") as f:
    data = []
    for line in f:
        parts = line.split()
        name = parts[0]
        vals = parts[1:]
        avg = sum(int(x) for x in vals)/len(vals)
        data.append((name, avg))
    for person in sorted(data, key=operator.itemgetter(1), reverse=True):
        print("{} {}".format(*person))

rawDescription: Sort Average In A file

description: Sort Average In A file


code:
df = read_csv('GOOG Key Ratios.csv', skiprows=2, index_col=0, names=['Y%d' % i for i in range(11)])
df.head() # not homogeneously typed columns
df.convert_objects(convert_numeric=True).head()

rawDescription: NaN results with pandas mean function

description: NaN results with pandas mean function


rawDescription: Iterating through a list of string lists?


rawDescription: save a plot in python

description: Save a plot in python


code:
with open(args.filename, 'rb') as holter, open("copied_holter.ecg", 'w') as output_file:
    holter.seek(start)
    data = holter.read(end-start)
    output_file.write(data)

rawDescription: Using seek() in Python

description: Using seek() in Python


rawDescription: Datetime.now() abnormality - Python

description: Datetime.now() abnormality - Python


code:
def RomanToDecimal(roman):
    DecimalValue=0
    i = 0 # Position in string

    while i < len(roman):

        # Test for 2 char first
        if i < len(roman)-1: # Make sure we're not on the last letter
            # Get current + next letters
            s = roman[i:i+2]
            add = False

            if s == "CM":
                add = 900
            elif s == "IV":
                add = 4
            elif s == "IX":
                add = 9
            elif s == "XL":
                add = 40
            elif s == "XC":
                add = 90
            elif s == "CD":
                add = 400

            if add: # We've found a match
                i += 2 # Step 2
                DecimalValue += add # Add the value
                continue # Next loop

        # If we get here the 2 character match failed
        # Single char match
        s = roman[i]

        if s == "I":
            DecimalValue += 1
        elif s == "V":
            DecimalValue += 5
        elif s == "X":
            DecimalValue += 10
        elif s == "L":
            DecimalValue += 50
        elif s == "C":
            DecimalValue += 100
        elif s == "D":
            DecimalValue += 500
        elif s == "M":
            DecimalValue += 1000

        i += 1

    return DecimalValue

RomanToDecimal('XIXIX')
28

rawDescription: Roman to Numeral calculator with "for i in X"


code:
class BaseTestCase(TestCase):
    def error_outcome(self, response):
        self.assertEqual(response.status_code, 403)
        data = json.loads(response._get_content())
        self.assertEquals(data, {'error': 1})

class SomeTest(BaseTestCase):
    def test_foo(self):
        request = RequestFactory().post('/someurl')
        response = view_method(request)
        self.error_outcome(response)

rawDescription: reusable helper for test assertion in Django

description: Reusable helper for test assertion in Django


code:
def some_function(arg, property):
    return getattr(Some_Object, propery)

rawDescription: python passing a variable to an object property or method through a function argument

description: Python passing a variable to an object property or method through a function argument


code: ''.join(c for c in x if c != '\n')

rawDescription: Joining elements of list: Python

description: Joining elements of list: Python


code:
import datetime
obj.email_token_expiry = datetime.datetime.now()+datetime.timedelta(hours=24)

rawDescription: How can i set email_token_expiry time for 24 hours?

description: Set email_token_expiry time for 24 hours


rawDescription: Best way to store large tables that require sorting in python

description: Store large tables that require sorting in python


code:
import gtk

about = gtk.AboutDialog()
about.set_program_name("name")
about.set_version("0.0.1")
about.set_logo(gtk.gdk.pixbuf_new_from_file("file.png"))
about.show()

vbox = about.get_children()[0].get_children()[0]  # vbox containing everything but the buttons at the bottom
label = vbox.get_children()[1] # Label containing name and version
alignment = gtk.Alignment(xalign=0.5, yalign=0.5)
alignment.set_padding(100, 0, 0, 0)
alignment.show()

vbox.remove(label)
alignment.add(label)
vbox.add(alignment)
vbox.reorder_child(alignment, 1)  # Put it back in the correct order, rather than below the URL and stuff

gtk.main()

rawDescription: python aboutdialog space between program name/version and logo

description: Python aboutdialog space between program name/version and logo


code:
import os
os.system("your command line expression")

rawDescription: Write a program in Python that interacts with terminal in Raspbian


code: [ dict(y.split(':') for y in x.split(',')) for x in 'name:mickey,age:58|name:minnie,age:47,weight:60'.split('|')]

rawDescription: string to list of dictionaries (python)

description: String to list of dictionaries (python)


code:
xdf = pd.DataFrame({'value': X, 'serie': 'X'})
ydf = pd.DataFrame({'value': Y, 'serie': 'Y'})
pd.concat([xdf, ydf], ignore_index=True)

rawDescription: Dataframe building by aggregating lists

description: Dataframe building by aggregating lists


rawDescription: In Django, how can I use a request to determine its URLconf viewname?


code:
#!/usr/bin/env python
from Crypto.Cipher import AES
obj = AES.new('This is a key456', AES.MODE_ECB)
message = "The answer is no"
ciphertext = obj.encrypt(message)
ciphertext
#'o\x1aq_{P+\xd0\x07\xce\x89\xd1=M\x989'
obj2 = AES.new('This is a key456', AES.MODE_ECB)
x = obj2.decrypt(ciphertext)
print(x)
#or, just print obj2.decrypt(ciphertext)

rawDescription: Why does my script not produce output, when the same code in an interactive session does?


code:
def read_lengths(path):
    """Reads "length file" into dict mapping sequence ID to length."""
    lengths = {}
    with open(path) as f:
        for line in f:
            seq, length = line.strip().split()
            lengths[seq] = int(length)
    return lengths

def enclosed_substrings(s, start, stop):
    """Find all substrings starting with `start` and ending with `stop`."""
    startpos = 0
    stoppos = 0
    while True:
        startpos = s.find(start, startpos)
        if startpos < 0:
            break
        stoppos = s.find(stop, startpos + 1)
        if stoppos < 0:
            break
        yield s[startpos:stoppos + 1]
        startpos += 1

def seq_check(record, expected_lens, len_factor=0.9, start='M', stop='*'):
    min_len = expected_lens[record.id] * len_factor
    for sub in enclosed_substrings(record.seq, start, stop):
        if len(sub) >= min_len:
            return True
    return False

source_file = 'protein.fasta'
out_file = 'filtered.fa'
length_file = 'protein_length.txt'

expected_lengths = read_lengths(length_file)
seqs = SeqIO.parse(source_file, 'fasta')
filtered = (seq for seq in seqs if seq_check(seq, expected_lengths))
SeqIO.write(filtered, out_file, 'fasta')

rawDescription: Filter sequences

description: Filter sequences


code:
def heat(x, y):
    x1 = x - 20
    y1 = y - 10
    if x1 < 0 or x1 > 9 or y1 < 0 or y1 > 9:    # out of range
        return 0
    if (x1 == y1) or (x1 == 9-y1):
        return 5000
    else:
        return 0

rawDescription: Non rectangular heat source Python

description: Non rectangular heat source Python


code:
Month = input("Enter name of month: ")

if Month in {'September','April','June','November'}:
    print("There are 30 days in that month")

rawDescription: Always executing if statment have been messing with it but cant figure out why it always executes


rawDescription: Accessing range of values within lists in Numpy


code: image.transform(image.size, Image.MESH, mesh, self.filtering)

rawDescription: Python CAPTCHA-like image disortion

description: Python CAPTCHA-like image disortion


code:
import urllib
urllib.urlretrieve('http://i.imgur.com/Ph4Xw.jpg', 'duck.jpg')

rawDescription: Python -- how to grab images off the internet


code:
import numpy as np
import pandas as pd
from xlsxwriter.utility import xl_range

writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
workbook = writer.book

df = pd.DataFrame(data=np.random.rand(255))
df.to_excel(
    writer, 'TEST',
    startcol=4,
    startrow=2
)
writer.close()

rawDescription: Python write multiple matrix into excel using XlsxWriter


code:
for x in [1, 2, 3]:
    for y in [4, 5, 6]:
        print('x =', x, 'y =', y)
    else:
        continue
    print('here')

rawDescription: the continue in for else in python

description: The continue in for else in python


code:
timestamps = {'03-08-2012': 108, '15-08-2012': 16}  # Sample data

# Get the heights and labels from the dictionary
heights, labels = [], []
for key, val in timestamps.iteritems():
    labels.append(key)
    heights.append(val)

# Create a set of fake indexes at which to place the bars
indexes = np.arange(len(timestamps))
width = 0.4

# Generate a matplotlib figure and plot the bar chart
fig, ax = plt.subplots()
ax.bar(indexes, heights)

# Overwrite the axis labels
ax.set_xticks(indexes + width)
ax.set_xticklabels(labels)

rawDescription: Histogram Generation with Python

description: Histogram Generation with Python


code:
import pylab

formula = r'$x=3^2, y = \frac{1}{\frac{2}{3}}, %s$' % ('test' * 20)

fig = pylab.figure()
text = fig.text(0, 0, formula)

# Saving the figure will render the text.
dpi = 300
fig.savefig('formula.png', dpi=dpi)

# Now we can work with text's bounding box.
bbox = text.get_window_extent()
width, height = bbox.size / float(dpi) + 0.005
# Adjust the figure size so it can hold the entire text.
fig.set_size_inches((width, height))

# Adjust text's vertical position.
dy = (bbox.ymin/float(dpi))/height
text.set_position((0, -dy))

# Save the adjusted text.
fig.savefig('formula.png', dpi=dpi)

rawDescription: Creating images of mathematical expressions from TeX, using matplotlib


code: newdata = [ (pixel[0] - 50, pixel[1] , pixel[2]) for pixel in pixels ]

rawDescription: python - not creating image

description: Python - not creating image


code:
files = MultipartEncoder(fields={'file': (file, open(file, "rb"), 'audio/mpeg')})
audio_headers = {'Authorization': 'Bearer ' + token, 'Content-Type': files.content_type}
add_file = requests.post(file_url, headers=audio_headers, data=files)

rawDescription: Capturing filename with python requests toolbelt


rawDescription: Allocating large arrays in memory with Python


code:
DATA = {"records": [{"key1": "AAA", "key2": "BBB", "key3": "CCC", "key4": "AAA"}]}

for name, datalist in DATA.iteritems():  # Or items() in Python 3.x
    for datadict in datalist:
        for key, value in datadict.items():
            if value == "AAA":
                datadict[key] = "XXX"

print (DATA)
# Prints {'records': [{'key3': 'CCC', 'key2': 'BBB', 'key1': 'XXX', 'key4': 'XXX'}]}

rawDescription: Replacing values in a Python list/dictionary?


code:
for welement, text in zip(webelements_list, text_list):
    welement.send_keys(text)

rawDescription: python - map two lists of different types

description: Python - map two lists of different types


code:
def functionA():
    var1 = hi
    var2 = bye
    return (var1, var2)

class A(object):
    def functionB(self):
        var1, var2 = functionA()
        var3 = "something not in functionA"

rawDescription: How do you append to an existing function?

description: Append to an existing function


code:
class SomeClass(object):

    @property
    def x(self):
        return x

rawDescription: Automatic Redefining a global variable in the class


code:
p.grid_columnconfigure(1, weight=1)
p.grid_rowconfigure(1, weight=1)

rawDescription: Setting Tkinter/ttk Frame background color


code: etree.tostring(tree, pretty_print = True, xml_declaration = True, encoding='UTF-8', standalone="yes")

rawDescription: XML Declaration standalone="yes" lxml

description: XML Declaration standalone="yes" lxml


code:
from ctypes import CDLL, c_uint, c_char_p

class Flag(object):
    flags = [(0x1, 'fun'), (0x2, 'toy')]
    @classmethod
    def from_param(cls, data):
        return c_uint(encode_flags(self.flags, data))

libc = CDLL('libc.so.6')
printf = libc.printf
printf.argtypes = [c_char_p, Flag]

printf("hello %d\n", ["fun", "toy"])

rawDescription: Does ctypes provide anything for enums and flags?


code: {k: oldk for oldk, oldv in swapdict.items() for k in oldv}

rawDescription: Swap dictionary keys and values when values are lists


code:
import Image
import ImageFilter

file = '/home/phius/test.jpg'
img = Image.open(file)
img2 = img.filter(ImageFilter.UnsharpMask) # note it returns a new image
img2.save(file)

rawDescription: ImageOps.unsharp_mask not working on PIL


code:
sorted(chain(posts_type1, posts_type2),
       key=lambda x: x.created_date if isinstance(x, PostType1)
                                    else x.publish_date)

rawDescription: Sort two different models on differently named fields


code:
result = image[:, :, np.newaxis] * spectral_range
result.shape
result

rawDescription: numpy multiply array elements with another array

description: Numpy multiply array elements with another array


code:
def generate_sample(self, ob, preview):
    print("* Generating sample...")
    tone_out = array(ob, dtype=int16)

    if preview:
        print("* Previewing audio file...")

        bytestream = tone_out.tobytes()
        pya = pyaudio.PyAudio()
        stream = pya.open(format=pya.get_format_from_width(width=2), channels=1, rate=OUTPUT_SAMPLE_RATE, output=True)
        stream.write(bytestream)
        stream.stop_stream()
        stream.close()

        pya.terminate()
        print("* Preview completed!")
    else:
        write('sound.wav', SAMPLE_RATE, tone_out)
        print("* Wrote audio file!")

rawDescription: Python: realtime audio streaming with PyAudio (or something else)?


code:
def copy_uuid(apps, schema_editor):
    User = apps.get_model("myapp", "User")

    # loop, or...
    User.objects.update(uuid=F("userprofile__uuid"))

class Migration(migrations.Migration):
    dependencies = []

    operations = [
        migrations.RunPython(copy_uuid),
    ]

rawDescription: Django migrate unique field between models with data


code: details[2:] = reversed(splitdata)

rawDescription: Python: Append correct string to END of list


code:
with open('myInput01.txt') as fin, open('myOutput01.txt', 'w') as fout:
    fout.writelines(sorted(fin))

rawDescription: Sorting a file in ascending order

description: Sorting a file in ascending order


code:
def write(self, text):
    if text!="\n":
       self.stdout.write('###' + text)

rawDescription: Clear buffered input stream

description: Clear buffered input stream


code:
import requests

face_token = 'your_token'
post = 'Your Post wowzers'
post.replace(' ', '+')
requests.post("https://graph.facebook.com/me/feed/?message=" + post + "&access_token=" + face_token)

rawDescription: Python how to do facebook wall post using graph api?


code:
import os, sys

path = os.path.dirname(os.path.abspath(__file__))

for py in [f[:-3] for f in os.listdir(path) if f.endswith('.py') and f != '__init__.py']:
    mod = __import__('.'.join([__name__, py]), fromlist=[py])
    classes = [getattr(mod, x) for x in dir(mod) if isinstance(getattr(mod, x), type)]
    for cls in classes:
        setattr(sys.modules[__name__], cls.__name__, cls)

rawDescription: Import all classes in directory?

description: Import all classes in directory


rawDescription: variance vs coefficient of variation

description: Variance vs coefficient of variation


code:
def log_message(self, format, *args):
    """Log an arbitrary message.

    This is used by all other logging functions.  Override
    it if you have specific logging wishes.

    The first argument, FORMAT, is a format string for the
    message to be logged.  If the format string contains
    any % escapes requiring parameters, they should be
    specified as subsequent arguments (it's just like
    printf!).

    The client host and current date/time are prefixed to
    every message.

    """

    sys.stderr.write("%s - - [%s] %s\n" %
                     (self.address_string(),
                      self.log_date_time_string(),
                      format%args))

rawDescription: how to redirect the logging output of xmlrpc server to some file

description: Redirect the logging output of xmlrpc server to some file


code:
class Meta:
     unique_together = ( ('name', 'active'),)

rawDescription: Django unique_together and flagging objects as "deleted"


code:
old_items = relationship(lambda: Item, secondary=Item_sets.__table__,
                         primaryjoin=id==Item_sets.id_item_new,
                         secondaryjoin=Item_sets.id_item_old == id)

rawDescription: Many to one self refering to SQLAclhemy table, and returning the table content


code:
import os
from scipy import ndimage, misc

images = []
for root, dirnames, filenames in os.walk("/foo/bar"):
    for filename in filenames:
        if re.search("\.(jpg|jpeg|png|bmp|tiff)$", filename):
            filepath = os.path.join(root, filename)
            image = ndimage.imread(filepath, mode="RGB")
            image_resized = misc.imresize(image, (64, 64))
            images.append(image_resized)

rawDescription: Using python load images from directory and reshape


code:
def next_file(filename):
    """
    filename: string. Name only of the current file
    returns: string. The name of the next file to be created
    assumes the padding of the file is filename_001.txt The number of starting zeros does   not not matter
    """
    fill_exists = True
    current = '001'
    padding = len(current)  # length of digits
    file = '{}_{}.txt'.format(filename, current)  # the actual name of the file, inlc. extension
    while fill_exists:
        if not os.path.isfile(file):  # if the file does not already exist
            f = open(file, 'w')  # create file
            f.write(filename)
            f.close()
            return 'Created new file: {}_{}.txt'.format(filename, current)  # shows the name of file just created
        else:
            current = str(int(current)+1).zfill(padding)  # try the next number
            file = '{}_{}.txt'.format(filename, current)

rawDescription: Python - create next file

description: Python - create next file


code:
a = np.array([1,2,3])
b = np.array([4])
c = np.hstack([a,b])

rawDescription: How to extend a numpy.ndarray

description: Extend a numpy.ndarray


code:
osize = (320, 320, 1)
img_o = numpy.tile(fill_value, osize)
img_o.shape

rawDescription: conversion from matlab to python of repmat

description: Conversion from matlab to python of repmat


code:
import re
s = 'Part 1. Part 2. Part 3 then more text'
re.search(r'Part 1\.(.*?)Part 3', s).group(1)
re.search(r'Part 1(.*?)Part 3', s).group(1)

rawDescription: Match text between two strings with regular expression


code:
class DataModel(QtCore.QAbstractTableModel):
    def __init__(self):
        QtCore.QAbstractTableModel.__init__(self)
        self.modelDict={}
        self.names=[]
    def rowCount(self, parent=QtCore.QModelIndex()):
        return len(self.names)
    def columnCount(self, index=QtCore.QModelIndex()):
        return 4

    def data(self, index, role):
        if not index.isValid() or not (0<=index.row()<len(self.names)): return QtCore.QVariant()
        row,col = index.row(),index.column()
        if col==0:
            if role==QtCore.Qt.DisplayRole:
                return self.names[row]
        else:
            if role==QtCore.Qt.DisplayRole:
                return self.modelDict[self.names[row]][col]

    def addItem(self, itemName=None, column=0):
        totalItems=self.rowCount()+1
        self.beginInsertRows(QtCore.QModelIndex(), totalItems, column)
        if not itemName:            itemName='Item %s'%self.rowCount()
        self.names.append(itemName)
        self.endInsertRows()

    def buildItems(self):
        for key in self.modelDict:
            index=QtCore.QModelIndex()
            self.addItem(key)

class ProxyModel(QtGui.QSortFilterProxyModel):
    def __init__(self, parent=None):
        super(ProxyModel, self).__init__(parent)

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        mainLayout=QtGui.QHBoxLayout()
        self.setLayout(mainLayout)

        self.dataModel=DataModel()
        self.dataModel.modelDict=elements
        self.dataModel.buildItems()

        self.proxyModel=ProxyModel()
        self.proxyModel.setFilterKeyColumn(0)
        self.proxyModel.setSourceModel(self.dataModel)

        self.viewA=QtGui.QListView()
        self.viewA.setModel(self.dataModel)
        self.viewA.clicked.connect(self.onClick)
        self.viewB=QtGui.QTableView()
        self.viewB.setModel(self.proxyModel)
        self.viewB.setColumnHidden(0,True)

        mainLayout.addWidget(self.viewA)
        mainLayout.addWidget(self.viewB)
        self.show()

    def onClick(self):
        index=self.viewA.currentIndex()
        key=self.dataModel.data(index, QtCore.Qt.DisplayRole)
        self.proxyModel.setFilterRegExp('%s'%key)

rawDescription: When single model is shared by multiple views


code:
class ImageSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Image
        fields = ('file', 'caption','id')

    def saveImage(self, imgFileUri):
        #parse dataUri and save locally, return local path
        return 'somewhereOverTheBlah'

    def restore_fields(self, data, files):
        """
        Core of deserialization, together with `restore_object`.
        Converts a dictionary of data into a dictionary of deserialized fields.
        """
        reverted_data = {}

        if data is not None and not isinstance(data, dict):
            self._errors['non_field_errors'] = ['Invalid data']
            return None

        for field_name, field in self.fields.items():
            """
            So it  is iterating over the fields to serialize, when we find the file field
            do something different (in this case look for the fileUri field, handle it and replace
            it inside of the reverted_data dictionary with the intended file field
            """

            if(field_name == 'file'):
                field_name = 'dataUri'
                field = fields.CharField()
                try:
                    # restore using the built in mechanism
                    field.field_from_native(data, files, field_name, reverted_data)
                    # take the dataUri, save it to disk and return the Path
                    value = reverted_data[field_name]
                    path = self.saveImage(value)
                    # set the file <Path> property on the model, remove the old dataUri
                    reverted_data['file'] = path
                    del reverted_data[field_name]

                except ValidationError as err:
                    self._errors[field_name] = list(err.messages)
            else:
                field.initialize(parent=self, field_name=field_name)
                try:
                    field.field_from_native(data, files, field_name, reverted_data)
                except ValidationError as err:
                    self._errors[field_name] = list(err.messages)

        return reverted_data

rawDescription: Django REST Framework and File Upload (Data URI)


code: items = re.split(" and |[^a-zA-Z ]+",text)

rawDescription: Python regex re.split using a specific word as a delimiter


code:
from pprint import pprint
import datetime
l = [('a', 'b', datetime.datetime.now(), 'd') for _ in xrange(10)]
pprint(l)
l_desc = sorted(l, key=lambda t: t[2], reverse=True)
pprint(l_desc)
l_asc = sorted(l_desc, key=lambda t: t[2])
pprint(l_asc)

rawDescription: Sorting Lists By DateTime in Python

description: Sorting Lists By DateTime in Python


code:
bool([])
bool([]) == False

rawDescription: Why does "[] == False" evaluate to False when "if not []" succeeds?


code:
import psycopg2

conn = psycopg2.connect(database="postgres")
cur = conn.cursor()

title = ['a', 'b', 'c']
description = ['good love', 'sun beautiful', 'wind go']
director = ['tom', 'jack', 'john']
directors = [ [d, ] for d in director ]
roles=[['kate', 'back', 'jon'], ['tian', 'den', 'lucy'], ['cruse', 'jodan', 'peter']]

sql = "INSERT INTO movies (title, description, directors, roles) VALUES (%s, %s, %s, %s);"
for obj in zip(title, description, directors, roles):
    cur.execute(cur.mogrify(sql, obj))
conn.commit()

cur.close()
conn.close()

rawDescription: python: insert the list data into database

description: Python: insert the list data into database


code:
import re
sections = []
current = []
with open("myfile.txt") as f:
    for line in f:
        if re.search(r"(?i)\d+ of \d+ documents", line):
            sections.append("".join(current))
            current = [line]
        else:
            current.append(line)
    if current:
        sections.append("".join(current))

rawDescription: Tokenizing in Python

description: Tokenizing in Python


code:
import os
os.system("scp FILE USER@SERVER:PATH")
#e.g. os.system("scp foo.bar joe@srvr.net:/path/to/foo.bar")

rawDescription: How do I copy a file to a remote server in python using scp or ssh?

description: Copy a file to a remote server in python using scp or ssh


code:
x, y = np.random.uniform(-1, 1, size=(2, 1000))
z = np.arctan2(y, x) % (2*np.pi)

# convert from polar --> cartesian
u, v = np.cos(z), np.sin(z)

# interpolate x and y components separately
rbf_u = interpolate.Rbf(x, y, u, function='linear', smooth=0.1)
rbf_v = interpolate.Rbf(x, y, v, function='linear', smooth=0.1)
xi, yi = np.mgrid[-1:1:100j, -1:1:100j].reshape(2, -1)
ui = rbf_u(xi, yi)
vi = rbf_v(xi, yi)

# convert from cartesian --> polar
zi = np.arctan2(ui, vi) % (2*np.pi)

rawDescription: Two-dimensional interpolation/smoothing of unevenly sampled angular values


code:
with open('file_output.html', 'w') as f:
  for tag in soup.select("#ModelTable"):
    f.write(tag.prettify())

rawDescription: Beautiful Soup: Copy a table to a new file


code:
from collections import defaultdict
kvmap= defaultdict(int)
for k in a_list:
    kvmap[k] += 1

rawDescription: what's the pythonic way to count the occurrence of an element in a list?

description: What's the pythonic way to count the occurrence of an element in a list


code:
for combo in combos:
    pt1  = geometry.Point(positions[combo[0]],evaluate=False)
    pt2  = geometry.Point(positions[combo[1]],evaluate=False)
    line = geometry.Polygon(pt1,pt2)
    try:
        if poly.encloses(line.midpoint):
            pass
        else:
            continue
    except NotImplementedError:
        continue
    intersect = geometry.intersection(line,poly)
    if len(intersect)>2:
        continue
    keepcombos.append(combo)

rawDescription: iteratively intersecting line segments in Sympy... is there a better way?

description: Iteratively intersecting line segments in Sympy... is there a better way


code: B = np.reshape(A, (-1, 2))

rawDescription: Convert a 1D array to a 2D array in numpy


rawDescription: extract uuid from url

description: Extract uuid from url


code:
import os
dirpath='C:/Users/Temp/AppData/Local/Temp'
dirpath
os.path.split(dirpath)
result = os.path.split(dirpath)
result[0]

rawDescription: How to remove sub-directory name from filepath

description: Remove sub-directory name from filepath


code:
login_url = ''
for link in showlinks():
    if link.text == "login":
        login_url = link.url

go(login_url)

rawDescription: Voting on Hacker News stories programmatically?


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

# generate some sample data
import scipy.misc
lena = scipy.misc.lena()

# downscaling has a "smoothing" effect
lena = scipy.misc.imresize(lena, 0.15, interp='cubic')

# create the x and y coordinate arrays (here we just use pixel indices)
xx, yy = np.mgrid[0:lena.shape[0], 0:lena.shape[1]]

# create the figure
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(xx, yy, lena ,rstride=1, cstride=1, cmap=plt.cm.gray,
        linewidth=0)

# show it
plt.show()

rawDescription: How to create surface plot from greyscale image with Matplotlib?

description: Create surface plot from greyscale image with Matplotlib


code:
import PyQt4.QtGui as gui

app = gui.QApplication([])

w = gui.QWidget()

la = gui.QFormLayout()
w.setLayout(la)

tw = gui.QTreeWidget()
sp = tw.sizePolicy()
sp.setVerticalStretch(1)
tw.setSizePolicy(sp)

la.addWidget(tw)

w.show()

app.exec_()

rawDescription: Contolling Widget Placement inside PyQt QFormLayout


code: 'sitting' + text.split('sitting')[3]

rawDescription: Python 3: splitting by 3rd delimiter

description: Python 3: splitting by 3rd delimiter


code:
def launchVim():
    os.system("vim")

def testThatVimIsLaunched():
    try:
        realSystem = os.system
        called = []
        def stubSystem(command):
            if command == "vim":
                called.append(True)
        os.system = stubSystem

        launchVim() # function under test

        assert(called == [True])
    finally:
        os.system = realSystem

rawDescription: unit testing a python function which invokes a vim subprocess

description: Unit testing a python function which invokes a vim subprocess


code:
# for create and update view
def form_valid(self, form):
    admin_time = form.cleaned_data.get('admin_time')
    task_object = form.save(self.request.user, commit=False)
    if admin_time:
        task_object.execution_time = admin_time
    task_object.save(self.request.user)

# update
def clean_execution_time(self):
    execution_time = self.cleaned_data.get('execution_time')
    admin_time = self.cleaned_data.get('admin_time')
    if admin_time:
        self.cleaned_data['execution_time'] = execution_time = admin_time

    return execution_time

rawDescription: Not able to compare and update a form field and model field django


code:
from django.core import urlresolvers

match = urlresolvers.resolve(urlsplit(url).path)
view = match.func
params = match.args

rawDescription: How to decompose URL into model and parameters in Django

description: Decompose URL into model and parameters in Django


code:
c = http.client.HTTPConnection('t.co')
c.request('GET', '/7fGoazTYpc')          # or HEAD, but body is empty anyway
r = c.getresponse()
r.getheader('Location')

rawDescription: Unwrapping t.co link that links to bit.ly


code:
n_intervals = 15
delta       = 1.0 / n_intervals
base_index  = df.index.year
df.index    = base_index
new_index   = np.arange(base_index.min(), base_index.max()+delta, delta)

df = df.reindex(new_index, tolerance=0.000001, method='nearest')
df.interpolate('cubic', inplace=True)

rawDescription: Upsample pandas DataFrame with integer multiple of current frequency


code:
def makeOrderedDict(dictToOrder, keyOrderList):
    tupleList = []
    for key in keyOrderList:
        tupleList.append((key, dictToOrder[key]))
    return OrderedDict(tupleList)

rawDescription: Get an ordered dictionary from an ordinary one


rawDescription: a list > a list of lists

description: A list > a list of lists


rawDescription: How do I "truncate" the last column of a tuple of same length tuples?


code:
# Area of an equal sided polygon with given radius and number of sides
def polygon_area_outer(r, n):
    return n * r**2 / 2 * sin(2*pi/n) / cos(pi/n)**2

# Side length of an equal sided polygon with given radius and number of sides
def polygon_side_outer(r, n):
    return 2 * r * sin(pi/n) / cos(pi/n)

# Perimeter of an equal sided polygon with given radius and number of sides
def polygon_perimeter_outer(r, n):
    return polygon_side_outer(r, n) * n

rawDescription: Polygon area, perimeter and side length around the circle with python


code:
cats = [{'parent_id': False, 'id': 1, 'title': u'All'},
        {'parent_id': False, 'id': 2, 'title': u'Toys'},
        {'parent_id': 2, 'id': 3, 'title': u'Toypads'},
        {'parent_id': 3, 'id': 4, 'title': u'Green'},]

cats_dict = dict((cat['id'], cat) for cat in cats)

for cat in cats:
    if cat['parent_id'] != False:
        parent = cats_dict[cat['parent_id']]
        parent.setdefault('children', []).append(cat)

cats = [cat for cat in cats if cat['parent_id'] == False]

rawDescription: How to create dict with childrens from dict with parent_id

description: Create dict with childrens from dict with parent_id


code:
import glob

l = [pd.read_csv(filename) for filename in glob.glob("/path/*.txt")]
df = pd.concat(l, axis=0)

rawDescription: How can I read the contents of all the files in a directory with pandas?

description: Read the contents of all the files in a directory with pandas


rawDescription: Python GAE webapp2 output formatting

description: Python GAE webapp2 output formatting


code:
s = '''\n#here's a title\n\nhello world!!!\n\nPosted on 11-09-2014 02:32:30'''
m1 = re.search(r'^#.+$', s, re.MULTILINE)
m2 = re.search(r'^Posted on ', s, re.MULTILINE)
m1.end()
m2.start()
s[m1.end():m2.start()]

rawDescription: Regular expression, matching between two patterns in a multiline string


code:
m = {
  "-" : '"expanded":true, ',
  "+" : '"expanded":false, ',
}

if aline[0] in m:
  extraval = m[aline[0]]
  aline = aline[1:]

rawDescription: What data structures can be used to enhance code maintainability?


code:
def L_before_O(s):
    return (s.index('L') - s.index('O') == 1)

def N_after_L(s):
    return (s.index('L') < s.index('N'))

def G_and_P(s):
    return (abs(s.index('G') - s.index('P')) == 2)

def all_perms(s):    #this is from the link
    if len(s) <=1:
        yield s
    else:
        for perm in all_perms(s[1:]):
            for i in range(len(perm)+1):
                yield perm[:i] + s[0:1] + perm[i:]

def get_the_answer():
    permutations = [i for i in all_perms('GHLOPSN')] #N is the news tape
    a = [i for i in permutations if L_before_O(i)]
    b = [i for i in a if N_after_L(i)]
    c = [i for i in b if G_and_P(i)]
    return c

rawDescription: What category of combinatorial problems appear on the logic games section of the LSAT?


code:
def refresh(*args):

    if  v.get() == 'Disable' :
        fb_entry.state(['disabled'])
        fw_entry.state(['disabled'])
        fb.set('')
        fw.set('')
    elif v.get() == 'Enable' :
        fb_entry.state(['!disabled'])
        fw_entry.state(['!disabled'])

root = Tk()
v = StringVar()
var = StringVar()

entry1 = ttk.Entry (root, textvariable= var)
entry1.grid(row=2, column=2, sticky=(E,W))

entry2 = ttk.Entry (root, textvariable= var)
entry2.grid(row=4, column=2, sticky=(E,W))

v_list=['Disable','Enable']
v.set(v_list[1])
v_optionmenu = apply(OptionMenu, (root,v) + tuple(v_list))
v_optionmenu.grid(column=4,row=11,sticky=(W,E))

var = v

root.bind('<Enter>',refresh_widget)
root.mainloop()

rawDescription: Conditional disabling of widget

description: Conditional disabling of widget


rawDescription: Setting a variable to the name of a class and calling a function from that class


code:
import locale
locale.setlocale(locale.LC_ALL, '')
locale.currency(123.2342343234234234)
locale.currency(123.2342343234234234, '')  # the second argument controls the symbol

rawDescription: Python how to format currency string

description: Python how to format currency string


code:
array1 = np.array([0, 1, 2, 5, 0])
array2 = np.array([0, 10, 20, 1, 2, 30, 5])
np.in1d(array1, array2)
np.all(np.in1d(array1, array2))

rawDescription: Check if all of the elements in one numpy array exist in a second numpy array


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

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class embeddedTerminal(QWidget):

    def __init__(self):
        QWidget.__init__(self)
        self._processes = []
        self.resize(800, 600)
        self.terminal = QWidget(self)
        layout = QVBoxLayout(self)
        layout.addWidget(self.terminal)
        self._start_process(
            'xterm',
            ['-into', str(self.terminal.winId()),
             '-e', 'tmux', 'new', '-s', 'my_session']
        )
        button = QPushButton('List files')
        layout.addWidget(button)
        button.clicked.connect(self._list_files)

    def _start_process(self, prog, args):
        child = QProcess()
        self._processes.append(child)
        child.start(prog, args)

    def _list_files(self):
        self._start_process(
            'tmux', ['send-keys', '-t', 'my_session:0', 'ls', 'Enter'])

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main = embeddedTerminal()
    main.show()
    sys.exit(app.exec_())

rawDescription: how to use a terminal embedded in a PyQt GUI

description: Use a terminal embedded in a PyQt GUI


code:
subq = (session.query(b.col5).join(c, c.col4 == b.col4)).subquery("subq")
qry = session.query(a).outerjoin(subq, a.col5 == subq.c.col5)
print(qry)

rawDescription: Nested Joins in SQLAlchemy

description: Nested Joins in SQLAlchemy


code:
def sched ():
    i = 0

    while True:
        x = datetime.today()
        current_hour = datetime.now().hour
        y=x.replace(day=x.day+1, hour=i, minute=00, second=00, microsecond=00)
        delta_t=y-x
        secs=delta_t.seconds+1
        t=Timer(secs, hello_world)
        t.start()
        i = i + 1
        i = i % 24

rawDescription: I would like make a function begin at the top of the hour, every hour (python)


code: token = (a, )

rawDescription: Converting a word into a token in python


code:
from django.contrib import admin
from djcelery.models import (TaskState, WorkerState,
                 PeriodicTask, IntervalSchedule, CrontabSchedule)

admin.site.unregister(TaskState)
admin.site.unregister(WorkerState)
admin.site.unregister(IntervalSchedule)
admin.site.unregister(CrontabSchedule)
admin.site.unregister(PeriodicTask)

rawDescription: How can I disable the Django Celery admin modules?

description: Disable the Django Celery admin modules


code:
import heapq

class Item(object):
    def __init__(self, letter, value):
        self.letter = letter
        self.value = value

    def __repr__(self):
        return "Item({0}, {1})".format(self.letter, self.value)

    def __le__(self, other):
        # This is where you control whether it's a min heap or a max heap,
        # and also what you want to sort on: value, letter or both.
        return self.value > other.value

items = [Item(*x) for x in a]
heapq.heapify(items)

rawDescription: insert a list to a binary tree

description: Insert a list to a binary tree


code:
from Tkinter import *

class ResizableCanvasFrame(Frame):
    '''
    Class that handles creating resizable frames on a canvas.
    Don't pack it.

    Set save_callback to whatever you want to happen when the mouse
    lets up on the border. You can catch <Configure> too, but at least
    in my case I didn't want to save the new position on every mouse move.
    '''
    def __init__(self, master, x, y, w, h, *args, **kwargs):
        # master should be a Canvas
        self.frame_thickness = 5
        Frame.__init__(
            self,
            master,
            *args,
            borderwidth = self.frame_thickness,
            cursor = 'fleur',
            **kwargs
        )
        self.canvas = master
        self.resize_state = None
        self.bind('<Button-1>', self.mousedown)
        self.bind('<B1-Motion>', self.mousemove)
        self.bind('<ButtonRelease-1>', self.mouseup)
        self.bind('<Destroy>', self.delete_item)
        # add self to canvas
        self.itemid = self.canvas.create_window(
            x,
            y,
            window=self,
            anchor="nw",
            width=w,
            height=h
        )
        self.save_callback = None

    def canvas_coords(self):
        return map(int, self.canvas.coords(self.itemid))

    def move(self, dx, dy):
        # strictly, this is out of the range of RCF,
        # but it helps with the law of demeter
        self.canvas.move(self.itemid, dx, dy)

    def mousedown(self, event):
        window_width = self.winfo_width()
        window_height = self.winfo_height()
        self.resize_state = {
            'start_coords': (event.x, event.y),
            'last_coords': (event.x, event.y),
            'left_edge': (0 <= event.x < self.frame_thickness),
            'right_edge': (window_width - self.frame_thickness <= event.x < window_width),
            'top_edge': (0 <= event.y < self.frame_thickness),
            'bottom_edge': (window_height - self.frame_thickness <= event.y < window_height),
        }

    def mousemove(self, event):
        if self.resize_state:
            resize = self.resize_state # debug var
            event_x = event.x
            event_y = event.y
            # distance of cursor from original position of window
            delta = map(int, (event.x - self.resize_state['start_coords'][0],
                              event.y - self.resize_state['start_coords'][1]))
            # load current pos, size
            new_x, new_y = self.canvas_coords()
            new_width = int(self.canvas.itemcget(self.itemid, 'width'))
            new_height = int(self.canvas.itemcget(self.itemid, 'height'))
            # handle x resize/move
            if self.resize_state['left_edge']:
                # must move pos and resize
                new_x += delta[0]
                new_width -= delta[0]
            elif self.resize_state['right_edge']:
                new_width += (event.x - self.resize_state['last_coords'][0])
            # handle y resize/move
            if self.resize_state['top_edge']:
                new_y += delta[1]
                new_height -= delta[1]
            elif self.resize_state['bottom_edge']:
                new_height += (event.y - self.resize_state['last_coords'][1])
            # save new settings in item, not card yet
            self.resize_state['last_coords'] = (event.x, event.y)
            self.canvas.coords(self.itemid, new_x, new_y)
            self.canvas.itemconfig(self.itemid, width=new_width, height=new_height)

    def mouseup(self, event):
        if self.resize_state:
            self.resize_state = None
            if self.save_callback:
                self.save_callback()

    def delete_item(self, event):
        self.canvas.delete(self.itemid)

rawDescription: Make widgets/frames inside tkinter canvas resizable


code:
requires=IS_EMPTY_OR(IS_IN_DB(db(db.owner.user_id == auth.user_id),
                              db.owner.id, db.owner._format))

rawDescription: web2py, creating a form with dropdown of thing a user own to choose from

description: Web2py, creating a form with dropdown of thing a user own to choose from


code:
import re

# 'cloudy1rain0sprinkler1' => ['cloudy1', 'rain0' and 'sprinkler1'].
evidence_dict = {}
input_evidence = 'cloudy1rain0sprinkler1'
# looks for a sequence of alphabets followed by any number of digits
evidence_list = re.findall('([a-z]+\d+)', input_evidence.lower())
for evidence in evidence_list:
    name, val, _ = re.split('(\d+)', evidence)
    if name in allNodes:
        evidence_dict[name] = val

# evidence_dict = {'cloudy': 1, 'rain': 0, 'sprinkler': 1}

rawDescription: GET Request Flask - Python

description: GET Request Flask - Python


code:
import itertools

for elem1, elem2 in itertools.combinations(a, 2):
    do_whatever_with(elem1, elem2)

rawDescription: Double for loop in python

description: Double for loop in python


code:
from cStringIO import StringIO
lines = tn.read_all().splitlines(True) # keep \n
o = StringIO()
for line in lines:
    if search_string in line:
        line = replacement_string # or line = line.replace(search_string, new_string)
    o.write(line)

rawDescription: Python search and replace in StringIO buffer?


code:
population = {}
total = 0
with open('list.txt', 'r') as handle:
    for line in handle:
        state, sep, pop = line.partition(' ')
        population[state] = int(pop)
        total += population[state]

total

rawDescription: Iterating through a list to add values

description: Iterating through a list to add values


code:
#!/usr/bin/env python
import time
from contextlib import closing
from selenium.webdriver import Firefox # pip install selenium

with closing(Firefox()) as browser:
    browser.set_window_position(0, 0) #NOTE: 0,0 might fail on some systems
    browser.set_window_size(800, 600)
    time.sleep(2)

rawDescription: How to maximize a browser window using the Python bindings for Selenium 2-WebDriver?

description: Maximize a browser window using the Python bindings for Selenium 2-WebDriver


code:
for c in word:            # go through each character in code
    if char == c:         # if the character is the one we're counting
        count = count + 1 # add one to the current count of characters

rawDescription: Counting letters in a string

description: Counting letters in a string


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

x1, x2 = [np.linspace(0, 10, num) for num in [10, 100]]
y1 = np.cos(x1)
y2 = np.sin(x2)

plt.plot(x1, y1)
plt.plot(x2, y2)
plt.show()

rawDescription: Plotting 2 plots with different size in the same figure using python


rawDescription: Regex first string between characters

description: Regex first string between characters


code:
df['day_name'] = df['pub_date'].apply(
    lambda x: pd.to_datetime(x).strftime("%A"))

rawDescription: Pandas Groupby Name of Day

description: Pandas Groupby Name of Day


code:
import requests
import http.cookiejar

class Parent:

    CookieFile = 'tmp/cookies.txt'

    def __init__(self):
        self.cj = http.cookiejar.LWPCookieJar(Parent.CookieFile)
        self.cj.load(ignore_discard=True)
        self.session = requests.Session()
        self.session.cookies = self.cj

    def save_cookies(self):
        self.cj.save(Parent.CookieFile, ignore_discard=True)

class Child(Parent):

    def __init__(self):
        Parent.__init__(self)

    def main(self):
        # Do stuff, connect if necessary
        self.save_cookies()

a = Child
a.main()

rawDescription: Requests and File cookiejar not working in a class


rawDescription: Regex for extraction in Python

description: Regex for extraction in Python


code:
import re
def get_year(citation):
    citation = citation.strip()
    year = re.search(r"\((\d{4}).*\)\.$", citation).group(1)
    return int(year)
test_list = ['Bauer et al. (2000).', 'G. M. Kirwan in litt. (1999).', 'Pacheco (1999).', 'Scott (1997).', 'Venturini et al.(2002).', 'Venturini et al. (2005).', 'P. Develey in litt. (2007, 2008).']
test_list
test_list.sort(key = get_year)
test_list

rawDescription: How do I sort a dictionary of results into a list of strings by date order of part of the strings (in python)

description: Sort a dictionary of results into a list of strings by date order of part of the strings (in python)


code: data=dataset.map(lambda word: (word,len(word))).filter(lambda t : t[1] >=6)

rawDescription: Pyspark-length of an element and how to use it later


code:
import my_module
def my_implementation():
    pass

my_module.implementation = my_implementation

rawDescription: How to parameterize a generic Python module?

description: Parameterize a generic Python module


code:
HTML = """

    X
    X
    X

"""
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(HTML)
tr = soup.find('tr', {'id':'one'})
span = tr.find('span', {'class':'x'})
span
span.text

rawDescription: Python splitting the HTML

description: Python splitting the HTML


code:
import zipfile
import os

dir_to_zip = "test_dir"
zip_file_name = "myzipfile.zip"
tempfile = "myzipfile.zip.tmp"
X = 2

# Create the first zipfile
z = zipfile.ZipFile(zip_file_name, "w")

z.write(dir_to_zip)

for dirpath, dirnames, filenames in os.walk(dir_to_zip):
    for filename in filenames:
        z.write(os.path.join(dirpath, filename))

z.close()

for _i in range(X):

    # Create the new zipfile as a temp file
    z = zipfile.ZipFile(tempfile, "w")
    z.write(zip_file_name)
    z.close()

    # Now remove the old zip file, replacing it with the new
    os.remove(zip_file_name)
    os.rename(tempfile, zip_file_name)

rawDescription: how can I create a loop that will zip a folder then the zipped folder "x" amount of times, Python 3.4?

description: Create a loop that will zip a folder then the zipped folder "x" amount of times, Python 3.4


code:
import math

def collision(rleft, rtop, width, height,   # rectangle definition
              center_x, center_y, radius):  # circle definition
    """ Detect collision between a rectangle and circle. """

    # complete boundbox of the rectangle
    rright, rbottom = rleft + width/2, rtop + height/2

    # bounding box of the circle
    cleft, ctop     = center_x-radius, center_y-radius
    cright, cbottom = center_x+radius, center_y+radius

    # trivial reject if bounding boxes do not intersect
    if rright < cleft or rleft > cright or rbottom < ctop or rtop > cbottom:
        return False  # no collision possible

    # check whether any point of rectangle is inside circle's radius
    for x in (rleft, rleft+width):
        for y in (rtop, rtop+height):
            # compare distance between circle's center point and each point of
            # the rectangle with the circle's radius
            if math.hypot(x-center_x, y-center_y) <= radius:
                return True  # collision detected

    # check if center of circle is inside rectangle
    if rleft <= center_x <= rright and rtop <= center_y <= rbottom:
        return True  # overlaid

    return False  # no collision detected

rawDescription: Detecting Rectangle collision with a Circle


code:
from mapreduce import context

def mapper(model_entity_instance, params_dict):
  """ my mapper function """
  ctx=context.get()
  mapper_params=ctx.mapreduce_spec.mapper.params

rawDescription: Passing parameters to mapper function in a pipeline


code:
import xml.etree.ElementTree as ET

tree = ET.parse("my_file.xml")   # iterparse would process one element at a time
root = tree.getroot()

for testdata in root.findall("testdata"):
    if testdata.get("execute") == "yes":
        command_list = []
        for command in testdata.findall("command"):
            command_list.append(command.text)
        verify = testdata.find("verification").text
        # Insert your code here.

rawDescription: use python to read xml one block at a time

description: Use python to read xml one block at a time


code:
import random

def test():
    with open('cache.txt','r') as cache:
        existing = [l.rstrip("\n") for l in cache.readlines()]

    with open('cache.txt', 'a+') as cache:
        for x in range(10):
            number = str(random.randint(1,20))
            if number not in existing:
                existing.append(number)
                cache.write(number + '\n')
    print("Finished.")

test()

rawDescription: Check existing values in text file before appending new values


rawDescription: Python Scraping From Html Code

description: Python Scraping From Html Code


rawDescription: python: append only specific elements from a list

description: Python: append only specific elements from a list


code:
if len( jd['coordinates'] ) > 1:
    self.db.tweets.insert( { 'text' : jd['text'], 'coordinates' : jd['coordinates'], 'lang' : jd['lang'] } )

rawDescription: Filtering Tweets By Location

description: Filtering Tweets By Location


code:
for index, Player in enumerate(PlayerID):
    if Player['ID'] == SearchID:
        PlayerID.pop(index)
        print("The user with ID", SearchID, ", has been deleted")
        break
else:
    print("The ID provided does not exist.")

rawDescription: How do I remove a dictionary index from a list on Python?

description: Remove a dictionary index from a list on Python


code:
class MyForm(forms.ModelForm):

    campaign = forms.BooleanField(widget=forms.HiddenInput())

rawDescription: BooleanField vs. CharField in Django Models


code:
from cStringIO import StringIO
sio = StringIO()
canvas.print_png(sio)
return sio.getvalue()

rawDescription: Get Binary Image Data From a MatPlotLib Canvas?


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
x = np.linspace(-4,4,150)
# plot density with shaded area showing Pr(-2 <= x <= 1)
lb = -2
ub = 1
d = norm.pdf(x)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(x, d)

idx = np.searchsorted(x,[lb,ub])
sx = x[idx[0]:idx[1]]
sd = d[idx[0]:idx[1]]
plt.fill_between(sx, sd, 0, color = 'b')
plt.show()

rawDescription: matplotlib colored segment of a function plot

description: Matplotlib colored segment of a function plot


code:
event.set()
event.clear()

rawDescription: Better pattern for multi-listener notifications with `gevent.event.Event`?


code:
rdd = sc.parallelize([('http://www.google.com/base/feeds/snippets/11448761432933644608', ['spanish', 'vocabulary']),
                      ('http://www.google.com/base/feeds/snippets/8175198959985911471', ['topics', 'presents', 'museums'])])
rdd.map(lambda x: len(x[1])).reduce(lambda x, y : x + y)
# returns 5

rawDescription: spark key find total elements in all tuples ignoring keys

description: Spark key find total elements in all tuples ignoring keys