code:
#!usr/bin/env python

import wx
import random

colorEventType = wx.NewEventType()
EVT_COLOR_EVENT = wx.PyEventBinder(colorEventType, 1)

class ButtonPanel(wx.Panel):
    def __init__(self, parent, *args, **kwargs):
        wx.Panel.__init__(self, parent, *args, **kwargs)

        vsizer = wx.BoxSizer(wx.VERTICAL)
        self.rstbutt = wx.Button(self, wx.ID_ANY, label='Restore')
        self.rstbutt.Disable()
        self.Bind(wx.EVT_BUTTON, self.OnButt, self.rstbutt)
        vsizer.Add(self.rstbutt, 0, wx.ALIGN_CENTER)
        vsizer.Add((500,150), 0)
        self.SetSizer(vsizer)

    def OnButt(self, evt):
        self.SetBackgroundColour(wx.NullColor)
        self.GetParent().Refresh()
        self.rstbutt.Disable()

class ColorEvent(wx.PyCommandEvent):
    def __init__(self, evtType, id):
        wx.PyCommandEvent.__init__(self, evtType, id)
        self.color = None

    def SetMyColor(self, color):
        self.color = color

    def GetMyColor(self):
        return self.color

class MainFrame(wx.Frame):
    def __init__(self, parent, *args, **kwargs):
        wx.Frame.__init__(self, parent, *args, **kwargs)
        framesizer = wx.BoxSizer(wx.VERTICAL)
        self.panel = ButtonPanel(self, wx.ID_ANY)
        framesizer.Add(self.panel, 1, wx.EXPAND)

        menubar = wx.MenuBar()
        filemenu = wx.Menu()
        menuquit = filemenu.Append(wx.ID_ANY, '&Quit')
        menubar.Append(filemenu, 'File')
        colormenu = wx.Menu()
        switch = colormenu.Append(wx.ID_ANY, '&Switch Color')
        menubar.Append(colormenu, '&Color')
        self.SetMenuBar(menubar)

        self.Bind(wx.EVT_MENU, self.OnQuit, menuquit)
        self.Bind(wx.EVT_MENU, self.OnColor, switch)
        self.Bind(EVT_COLOR_EVENT, self.ColorSwitch)
        self.SetSizerAndFit(framesizer)

    def OnQuit(self, evt):
        self.Close()

    def OnColor(self, evt):
        colevt = ColorEvent(colorEventType, -1)
        colors = ['red', 'green', 'blue', 'white', 'black', 'pink',
            (106, 90, 205), #slate blue
            (64, 224, 208), #turquoise
            ]
        choice = random.choice(colors)
        colevt.SetMyColor(choice)
        self.GetEventHandler().ProcessEvent(colevt)
        #evt.Skip()

    def ColorSwitch(self, evt):
        color = evt.GetMyColor()
        #print(color)
        self.panel.SetBackgroundColour(color)
        self.Refresh()
        self.panel.rstbutt.Enable()

if __name__ == "__main__":
    app = wx.App()
    frame = MainFrame(None, wx.ID_ANY, title="Change Panel Color Custom Event")
    frame.Show(True)

    app.MainLoop()

rawDescription: Updating the wx.gauge without while-loop


rawDescription: Making a wxPython application multilingual


code:
from bs4 import BeautifulSoup

html = """

        name here

    Length: 99:99

"""

soup = BeautifulSoup(html, "lxml")
sec = soup.find("span", {"class": "someclass"})
# get a tag with frame class
fr = sec.find("a", {"class": "frame"})

# pull img src and href from the a/frame
url, img = fr["href"], fr.find("img")["src"]

# get h3 with title class and extract the text from the anchor
name =  sec.select("h3.title a")[0].text

# "size" is in the span with the details class
size = sec.select("span.details")[0].text.split(None,1)[-1]

print(url, img, name.strip(), size.split(None,1)[1].strip())

rawDescription: xbmc/kodi python scrap data using BeautifulSoup

description: Xbmc/kodi python scrap data using BeautifulSoup


code:
palette = self.stat_lbl.palette()
color = QColor('#112233')
palette.setColor(QPalette.Foreground, color)
self.stat_lbl.setPalette(palette)

rawDescription: Set label font color from hex value

description: Set label font color from hex value


code:
from moo import BaseTest

class CoolTest(BaseTest):
    def setUp(self):
        BaseTest.setUp(self)
        args = BaseTest.initialisation_script_stuff()
        do_stuff(args)

    def testNumberOne(self):
        self.assertEqual(1,1)

rawDescription: boilerplateless tests

description: Boilerplateless tests


code: df['C1_C2'] = gb[['C1','C2']].apply(lambda x: pd.DataFrame(x.sum().sum(), index=x.index, columns=['']))

rawDescription: Pandas: conditional group-specific computations


rawDescription: how to create a sub list for a specific string in a nested list

description: Create a sub list for a specific string in a nested list


code: [name[:-4] for name in list_of_names]

rawDescription: removing a pattern from a list items in python

description: Removing a pattern from a list items in python


rawDescription: How can implement foreign key in admin and model


code: message = {'default':'default message','APNS_SANDBOX':apns_string}

rawDescription: Format APNS-style JSON message in Python for use with Amazon SNS


code: route2 = min(d, e)

rawDescription: Python logic - how do I code the maximum weight for two roads that have a variety of maximum weight values?


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.format_xdata = '{:0.1f}meters'.format
plt.show()

rawDescription: Matplotlib : Default Resolution of Plot Mouse-over Values


code: result = [dict(item.split(':') for item in value.split()) for value in inputlist]

rawDescription: how to convert list containing ' : ' to dictionary in python

description: Convert list containing ' : ' to dictionary in python


code:
inp = raw_input('what character sets do you want? ')
chars = ''.join(input_to_chars[i] for i in inp.split('+'))
chars

rawDescription: Getting function as string then run it

description: Getting function as string then run it


code:
def fitnessextract(x):
   return x.fitness

rawDescription: Python: how to make a function visible throughout a program


rawDescription: Detect if a NumPy array contains at least one non-numeric value?


code:
def bincount_where(y):
    counts = np.bincount(y)
    return y[np.in1d(y,np.where(counts>=3)[0])]

def bincount_arange(y):
    counts = np.bincount(y)
    return y[np.in1d(y,np.arange(y.max())[counts>=3])]

rawDescription: remove items with low frequency

description: Remove items with low frequency


code: from __future__ import division

rawDescription: Computing total_seconds in Python for datetime module with true division enabled


code:
returned_value = fun()
del returned_value

rawDescription: When are return values garbage collected?


code: text.translate(dict.fromkeys(ord(c) for c in string.punctuation))

rawDescription: Strip special characters and punctuation from a unicode string


code:
def write(self, cr, uid, ids, vals, context=None):
    quotation_obj=self.browse(cr, uid, ids,context=context)
    if partner_id:
                count = quotation_obj.number_of_edits + 1
                vals.update({'number_of_edits': count})

    return super(sale_order, self).write(cr, uid, ids, vals, context=context)

rawDescription: How to count the 'number of time a field is edited or updated' in Odoo 8?

description: Count the 'number of time a field is edited or updated' in Odoo 8


code:
from numpy import array
from scipy.interpolate import RegularGridInterpolator as rgi
my_interpolating_function = rgi((x,y,z), V)
Vi = my_interpolating_function(array([xi,yi,zi]).T)

rawDescription: interpolate 3D volume with numpy and or scipy

description: Interpolate 3D volume with numpy and or scipy


rawDescription: Integer division instead of regular one in Python


code:
# Specify the index, and whether reverse should be True/False
sort_spec = ((0, True), (1, False), (2, False), (3, True))

# Sort repeatedly from last tuple to the first, to have final output be
# sorted by first tuple, and ties sorted by second tuple etc
for index, reverse_value in sort_spec[::-1]:
    list_of_tuples.sort(key = lambda x: x[index], reverse=reverse_value)

rawDescription: sort list of tuples with multiple criteria

description: Sort list of tuples with multiple criteria


code:
tmp = im1 + im2
mask = (tmp < im1) | (tmp < im2)
tmp[mask] = 255

rawDescription: Difference in adding two images in numpy and opencv


rawDescription: Understanding the syntax of numpy.r_() concatenation


code:
try:
    productToUpdate = session.query(Product).filter(Product.name == "my-tshirt", Product.quantity - Product.reservations >= quantityToReserve).with_for_update().one() #assume Product.name is unique and name exists
except sqlalchemy.orm.exc.NoResultFound as e:
    return "No reservations available" #Handle no reservation case here
productToUpdate.reservations += quantityToReserve
#can put in another query and logic here to see if you're updating a reservation, or creating a new one
newReservation = Reservation(reservationQuantity = quantityToReserve)
newReservation.product = productToUpdate #assume relationship setup
newReservation.user = userForReservation #assume relationship setup
session.commit()

rawDescription: How can I limit rows and prevent race conditions for a reservation system

description: Limit rows and prevent race conditions for a reservation system


code: cax = ax.matshow(cm,cmap=cmap)

rawDescription: Matplotlib matshow with many string labels


rawDescription: Using Xpath in Scrapy to select any text below paragraph


code:
def pathgen(self, test):
    test = dict(test)
    ...

rawDescription: Python dict as local, not reference

description: Python dict as local, not reference


code:
#test_case_2.py
import foo
from mock import patch

@patch.object(foo, 'some_fn')
def test_foo(test_some_fn):
    test_some_fn.return_value = 'test-val-1'
    tmp = foo.Foo()
    assert tmp.method_1() == 'test-val-1'
    test_some_fn.return_value = 'test-val-2'
    assert tmp.method_1() == 'test-val-2'

rawDescription: Using python's mock patch.object to change the return value of a method called within another method


code:
import re
import csv
with open('file') as f:
    reader = csv.reader(f)
    for i in reader:
        print(re.sub(r'(,|^)(?:age\s*(?:\(years\))?:\s*(\d+)\s*(?:years)?)(?=,|$)', r'\1\2 years', ','.join(i)))

rawDescription: Replace a pattern in CSV file Python

description: Replace a pattern in CSV file Python


code:
import json

graph = {
    'nodes': [ {'id': 'Class1'}, {'id': 'Class2'} ],
    'links': [
        { 'id': 1, 'source': 'Class1', 'target': 'prereq' },
        { 'id': 2, 'source': 'Class2', 'target': 'prereq' }
    ]
}

with open('graph.js', 'w') as out_file:
  out_file.write('var graph = %s;' % json.dumps(graph))

rawDescription: Send Python information to a JavaScript file


code:
class DBConnection(object):

    def __init__(self, DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME):
        self.host = DB_HOST
        self.port = DB_PORT
        self.name = DB_NAME
        self.user = DB_USER
        self.password = DB_PASSWORD
        self.con = None

    def connect_db(self):
        if self.con is None:
            self.con = MySQLdb.connect(host = self.host,
                                        port = self.port,
                                        db = self.name,
                                        user = self.user,
                                        passwd = self.password)
            self.con.set_character_set("utf8")
        return self.con

    def fetch_db(self, query):
        self.query = query
        self.cursor = self.con.cursor()
        self.cursor.execute("SET NAMES utf8;")
        self.cursor.execute("SET CHARACTER SET utf8;")
        self.cursor.execute("SET character_set_connection=utf8;")
        self.cursor.execute(self.query)
        self.result = self.cursor.fetchall()

        return self.result

    def insert_db(self, query):
        self.query = query
        self.cursor = self.con.cursor()
        self.cursor.execute("SET NAMES utf8;")
        self.cursor.execute("SET CHARACTER SET utf8;")
        self.cursor.execute("SET character_set_connection=utf8;")
        self.cursor.execute(self.query)
        self.con.commit()

        return

rawDescription: Retrieving New Rows of MySQL Database without Restarting App in Python


code: iter([])

rawDescription: Python for loop implementation

description: Python for loop implementation


code:
import csv
import urllib2
from datetime import datetime
from urlparse import urljoin
from bs4 import BeautifulSoup

base_url = 'http://en.wikipedia.org'
page = urllib2.urlopen("http://en.wikipedia.org/wiki/List_of_human_stampedes")
soup = BeautifulSoup(page)

# build a list of references
references = {}
for item in soup.select('ol.references li[id]'):
    links = [a['href'] if a['href'].startswith('http') else urljoin(base_url, a['href'])
             for a in item.select('span.reference-text a[href]')]
    references[item['id']] = links

events = soup.find('span', id='20th_century').parent.find_next_siblings()
with open('output.csv', 'wb') as f:
    writer = csv.writer(f)
    for tag in events:
        if tag.name == 'h2':
            break

        for event in tag.find_all('li'):
            # extract text
            try:
                date_string, _ = event.text.split(':', 1)
                date = datetime.strptime(date_string, '%B %d, %Y').strftime('%d/%m/%Y')
            except ValueError:
                continue

            # extract links and write data
            links = event.find_all('a', href=lambda x: x.startswith('#cite_note-'))
            if links:
                for link in links:
                    for ref in references[link['href'][1:]]:
                        writer.writerow([date, ref])
            else:
                writer.writerow([date, ''])

rawDescription: Extract relevant links and storing them as .csv file


rawDescription: Python/Boto + AWS S3 versioning: how do I replace the current key with older version?


code:
def get_account_balances(db, number):
    totals = []

    con =  sqlite3.connect(db)
    cur = con.cursor()

    cur.execute('SELECT Savings, Chequing FROM Accounts WHERE Number == (?)',
                [number])

    return cur.fetchone()

rawDescription: Calling to a database in Python

description: Calling to a database in Python


code:
text = 'blabla word1 word2 WORD word book BOOK bLaBlA'
unique_words =  list(set(text.lower().split(' ')))
print('text : %s' % text)
print('unique words : %s' % ','.join(unique_words))

rawDescription: How to strip capital letters and then put them back in again in the same place?

description: Strip capital letters and then put them back in again in the same place


code:
class Device(models.Model):
    username = models.ForeignKey(User)
    hardware_key = models.CharField(max_length=32, primary_key=True)

rawDescription: How to implement hardware device registration to a Django user account

description: Implement hardware device registration to a Django user account


code:
for header in h3s.select("h3"):
    print("Feature title: ", header.text)
    ul = header.find_next_sibling("ul")
    print(ul.get_text(' ', strip=True))

rawDescription: Unable to scrape the text from a certain LI element


code:
r_server = UnicodeRedis('localhost')
city = r_server.get('city')

rawDescription: Distinction between str and unicode: why Redis returns binary data when passed unicode?


rawDescription: Recurse through dictionary of dictionaries, always starting from the top


rawDescription: Tokenizing a string into a list of nested arrays with Python


code: results = filter(lambda x:x["parentSubject"]["code"] == "soggetto1", j)

rawDescription: JSON GET Request with Python

description: JSON GET Request with Python


rawDescription: Dynamically change y limit

description: Dynamically change y limit


code:
import os

OLD_BASE = '/tmp/so/merge/old'
NEW_BASE = '/tmp/so/merge/new'
NEW_NAME = 'merged.txt'

def merge_files(infiles, outfile):
    with open(outfile, 'wb') as fo:
        for infile in infiles:
            with open(infile, 'rb') as fi:
                fo.write(fi.read())

for (dirpath, dirnames, filenames) in os.walk(OLD_BASE):
    base, tail = os.path.split(dirpath)
    if base != OLD_BASE: continue  # Don't operate on OLD_BASE, only children directories

    # Build infiles list
    infiles = sorted([os.path.join(dirpath, filename) for filename in filenames])

    # Create output directory
    new_dir =  os.path.join(NEW_BASE, tail)
    os.mkdir(new_dir)  # This will raise an OSError if the directory already exists

    # Build outfile name
    outfile = os.path.join(new_dir, NEW_NAME)

    # Merge
    merge_files(infiles, outfile)

rawDescription: How to merge files within a sub-directory and perform this function on mutliple sub-directories

description: Merge files within a sub-directory and perform this function on mutliple sub-directories


code:
import numpy as np
Y = [10, 20, 40, 80, 110]
N = len(Y)
X = np.arange(0, 2*N, 2)
X_new = np.arange(2*N-1)       # Where you want to interpolate
Y_new = np.interp(X_new, X, Y)
print(Y_new)

rawDescription: Double the length of a python numpy array with new values


code:
numbers = {1: 5.01, 11: 7.02, 21: 9.03, 31: 11.04, 41: 15.0, 51: 71.08, 61: 19.15}
output = {}
# loop over the (key, value) pairs in the numbers dictionary
for start, v in numbers.items():
    for k in range(start, start + 10):
        output[k] = v
numbers = output

rawDescription: Python - Assigning Multiple Keys for a Single Value


code:
{'utm_campaign': ['Feed: zones/python (Python Zone)'],
 'utm_medium': ['feed'],
 'utm_source': ['feedburner']}

rawDescription: Handling HTTP Query Parameters

description: Handling HTTP Query Parameters


code:
import Tkinter
import threading
import subprocess
import Queue
import shlex
import re
import matplotlib.pyplot as plt
import matplotlib.backends.backend_tkagg as tkagg
import atexit
import numpy as np

pingers=[]
def cleanup():
    print('terminating ping subprocesses...')
    for pinger in pingers:
        pinger.proc.terminate()
atexit.register(cleanup)

class Pinger(threading.Thread):
    def __init__(self,app,queue):
        threading.Thread.__init__(self)
        self.app=app
        self.queue=queue
    def run(self):
        # One ping subprocess is started by each Pinger thread.
        # The ping subprocess runs indefinitely, terminated by the cleanup function
        # which is called by atexit right before the main program terminates.
        ip = self.queue.get()
        cmd="ping %s" % ip
        self.proc = subprocess.Popen(shlex.split(cmd),
                                     stdout=subprocess.PIPE)
        for line in iter(self.proc.stdout.readline,''):
            match=re.search('time=(.*)\s+ms',line)
            if match:
                avg=float(match.group(1))
                self.app.update(ip,avg)

class App(object):
    def __init__(self,master,ips):
        self.ips=ips
        self.fig = plt.Figure(figsize=(5,4), dpi=100)
        self.fig.subplots_adjust(bottom=0.25)
        self.ax=self.fig.add_subplot(1,1,1)
        self.canvas = tkagg.FigureCanvasTkAgg(self.fig, master=master)
        self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
        self.canvas.show()
        N=len(self.ips)
        self.idx=dict(zip(self.ips,range(N)))
        # I set an initial ping time of 200 just to make the initial bar chart
        times=[200]*N
        self.rects=self.ax.bar(range(N), times)
        self.ax.set_xticks(np.arange(N)+0.8*0.5)
        self.ax.set_xticklabels(self.ips, rotation=25)
    def update(self,ip,avg):
        # This is called by Pinger threads, each time a new ping value is obtained
        print(ip,avg)
        self.rects[self.idx[ip]].set_height(avg)
        self.canvas.draw()

def main():
    root = Tkinter.Tk()
    root.wm_title("Connection Speed")
    ips=['bbc.co.uk', 'google.co.uk', 'nhgs.co.uk', 'bing.co.uk', 'msn.com']
    app = App(root,ips)
    queue = Queue.Queue()
    for ip in ips:
        queue.put(ip)
        # This starts one Pinger for each ip.
        pinger=Pinger(app,queue)
        pingers.append(pinger)
        pinger.daemon=True
        pinger.start()
    Tkinter.mainloop()

if __name__=='__main__':
    main()

rawDescription: Python script freezes for no apparent reason (afaik)


code:
A2, B = np.broadcast_arrays(A, b)
result = A2*B

rawDescription: np.tile to repeat an 1D array

description: Np.tile to repeat an 1D array


code:
from django.contrib.gis.db import models
class City(models.Model):
    name = models.CharField(max_lenght=255)
    geometry = models.MultiPolygonField()

    objects = models.GeoManager()

rawDescription: Geo Django get cities from latitude and longitude


code:
my_new_list = [i for i in myList if i.count(None) < 4]

[OUTPUT]
[[3, 4, None, None, None]]

rawDescription: Python: How to remove a list containing Nones from a list of lists?


code:
import  requests
from lxml.html import fromstring
r = requests.get("https://itunes.apple.com/us/app/candy-crush-saga/id553834731")
tree = fromstring(r.content)
a = tree.xpath('//div[@class="content"]//a[@class="name"]/@href')
b =  tree.xpath('//div[@class="center-stack"]//*/a[@class="name"]/@href')
print(a == b)
print(a)
print(b)

rawDescription: Python Xpath: lxml.etree.XPathEvalError: Invalid predicate


rawDescription: Pythonic iteration over multiple lists in parallel


code:
def read_ticker():
    c = {}
    with open('tickers.csv') as f:
        for line in f:
            items = [item.strip('"').strip() for item in line.split(",")]
            c[items[0]] = items[1:]

    print(c)
    return c

rawDescription: Printing a dictionary value of a function in another function


code:
import re

a = 'x11 + x111 + x1111 + x1'

def substitute(matched_obj):
    from_ = ['1', '11', '111', '1111']
    to = ['2', '22', '333', '3333']
    part = matched_obj.group(0)
    if part in from_:
        return to[from_.index(part)]
    return part

anew = re.sub(r'\d+',substitute,a)

rawDescription: Replacing multiple similar strings

description: Replacing multiple similar strings


code:
def e_dec():
    return z(e_cf_expansion())

rawDescription: Code to Generate e one Digit at a Time

description: Code to Generate e one Digit at a Time


code:
from qutip import Bloch
from math import sqrt, sin, cos, pi
from colorsys import hsv_to_rgb

from numpy import linspace, outer, ones, sin, cos, arccos, arctan2, size, empty
class BlochDensity(Bloch):
  def plot_back(self):
    # back half of sphere
    u = linspace(0, pi, 25)
    v = linspace(0, pi, 25)
    x = outer(cos(u), sin(v))
    y = outer(sin(u), sin(v))
    z = outer(ones(size(u)), cos(v))

    colours = empty(x.shape, dtype=object)
    for i in range(len(x)):
      for j in range(len(y)):
        theta = arctan2(y[i,j], x[i,j])
        phi = arccos(z[i,j])

        colours[i,j] = self.density(theta, phi)

    self.axes.plot_surface(x, y, z, rstride=1, cstride=1,
                           facecolors=colours,
                           alpha=self.sphere_alpha,
                           linewidth=0, antialiased=True)
    # wireframe
    self.axes.plot_wireframe(x, y, z, rstride=5, cstride=5,
                             color=self.frame_color,
                             alpha=self.frame_alpha)
    # equator
    self.axes.plot(1.0 * cos(u), 1.0 * sin(u), zs=0, zdir='z',
                   lw=self.frame_width, color=self.frame_color)
    self.axes.plot(1.0 * cos(u), 1.0 * sin(u), zs=0, zdir='x',
                   lw=self.frame_width, color=self.frame_color)

  def plot_front(self):
    # front half of sphere
    u = linspace(-pi, 0, 25)
    v = linspace(0, pi, 25)
    x = outer(cos(u), sin(v))
    y = outer(sin(u), sin(v))
    z = outer(ones(size(u)), cos(v))

    colours = empty(x.shape, dtype=object)
    for i in range(len(x)):
      for j in range(len(y)):
        theta = arctan2(y[i,j], x[i,j])
        phi = arccos(z[i,j])

        colours[i,j] = self.density(theta, phi)

    self.axes.plot_surface(x, y, z, rstride=1, cstride=1,
                           facecolors=colours,
                           alpha=self.sphere_alpha,
                           linewidth=0, antialiased=True)

    # wireframe
    self.axes.plot_wireframe(x, y, z, rstride=5, cstride=5,
                             color=self.frame_color,
                             alpha=self.frame_alpha)
    # equator
    self.axes.plot(1.0 * cos(u), 1.0 * sin(u),
                   zs=0, zdir='z', lw=self.frame_width,
                   color=self.frame_color)
    self.axes.plot(1.0 * cos(u), 1.0 * sin(u),
                   zs=0, zdir='x', lw=self.frame_width,
                   color=self.frame_color)

rawDescription: density plot on a sphere Python

description: Density plot on a sphere Python


code:
[
    {"categoryName":"AAAS","categoryId":"63420700","categoryIdentifier":"670_1_F14_4","title":"AAAS"},
    {"categoryName":"ACCT","categoryId":"63420752","categoryIdentifier":"670_1_F14_5","title":"ACCT"},
    ...
]

rawDescription: Get all combinations from selenium drop down list without options or select tag


code:
course_details = CourseDetail.objects.filter(course__name='Django 101', date__range=[start_date, end_date])
cc_attendance = CourseDetailAttendance.objects.filter(course_details__in=course_details).count()

rawDescription: Queryset across fours models

description: Queryset across fours models


code:
import time
int(time.time())

rawDescription: In Python Create A Numeric Date/Time Representation


code:
def update(self, t_step, t_end, u):
  t_array = np.arange(self.time, t_end, t_step)  # time values at which to evaluate ODE
  response = scipy.integrate.odeint(self.ode, self.y, t_array, (u,))
  self.y = response[-1]  # current state is the last evaluated state

rawDescription: Passing parameterized function handle in Python


code:
def getaddrinfo(self, host, port, *,
                family=0, type=0, proto=0, flags=0):
    if self._debug:
        return self.run_in_executor(None, self._getaddrinfo_debug,
                                    host, port, family, type, proto, flags)
    else:
        return self.run_in_executor(None, socket.getaddrinfo,
                                    host, port, family, type, proto, flags)

rawDescription: Why is the asyncio library slower than threads for this I/O-bound operation?


code:
import example
bar = example.Bar()
foo = bar.foo()
del bar
del foo

rawDescription: Double checking: passing out internal reference from member function


code:
import json

def make_my_scanner(context):
    # reference to actual scanner
    interal_scanner = json.scanner.py_make_scanner(context)

    # some references for the _scan_once function below
    parse_object = context.parse_object
    parse_array = context.parse_array
    parse_string = context.parse_string
    encoding = context.encoding
    strict = context.strict
    object_hook = context.object_hook
    object_pairs_hook = context.object_pairs_hook

    # customized _scan_once
    def _scan_once(string, idx):
        try:
            nextchar = string[idx]
        except IndexError:
            raise StopIteration

        # override some parse_** calls with the correct _scan_once
        if nextchar == '"':
            return parse_string(string, idx + 1, encoding, strict)
        elif nextchar == '{':
            return parse_object((string, idx + 1), encoding, strict,
                _scan_once, object_hook, object_pairs_hook)
        elif nextchar == '[':
            return parse_array((string, idx + 1), _scan_once)
        elif nextchar == 'n' and string[idx:idx + 4] == 'null':
            return 'Cat', idx + 4

        # invoke default scanner
        return interal_scanner(string, idx)

    return _scan_once

rawDescription: Python JSONDecoder custom translation of null type


rawDescription: Converting Decimal to %

description: Converting Decimal to %


code:
new_list= [0, 25, 2, 1, 14, 1, 14, 1, 4, 6, 6, 7, 0, 10, 11]
subseq = [[]]
for e in new_list:
    if not subseq[-1] or subseq[-1][-1] <= e:
        subseq[-1].append(e)
    else:
        subseq.append([e])

rawDescription: How to find longest consistent increment in a python list?

description: Find longest consistent increment in a python list


code:
unq_count = np.diff(np.concatenate(np.nonzero(unq_first) + ([a.size],)))
unq_idx = np.split(sort_idx, np.cumsum(unq_count[:-1]))

rawDescription: Grouping indices of unique elements in numpy


rawDescription: Rearranging Data in Python/Pandas: Turn specific column vlaues into headers


rawDescription: Python selenium- Clicking a javascript link doesn't load the new page but shows the url


code:
class CorrectionHandler(webapp2.RequestHandler):
    def post(self):
        polyhedron_object_key = self.request.get("key")
        polyhedron_object = Polyhedron.get_by_id(polyhedron_object_key)
        polyhedron_object.color = self.request.get('color')

rawDescription: How do I return the key of an appengine datastore object from the template in index.html?

description: Return the key of an appengine datastore object from the template in index.html


rawDescription: Find the row and column with the min value in python?


code:
def mult(lst):
    mul = 1
    for i in lst:
        mul *= i
    return mul

out = [mult(i) for i in zip(x1, x2, x3)]

rawDescription: Reduce list based on index

description: Reduce list based on index


code:
rafay = 10
jamie = 2
jamie = 5

rawDescription: How do I order a file of scores in Python?

description: Order a file of scores in Python


code:
good = (0,1,2,3)
bad =  (0,10,20,3)
from itertools import product
for combo in product(*map(set, zip(good, bad))):
    print(combo)

rawDescription: all combinations of differences of two lists

description: All combinations of differences of two lists


rawDescription: Identifying the underlying dataset from the print statement


code: ['1  one' '2  two' '3  three' '4  four' '5  five']

rawDescription: Converting plain text list into array in python program


code:
def grouper(iterable, n, fillvalue=None):
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

rawDescription: What filter do I need? Want to keep high frequency values only


code:
def my_view(request, movie):
    return render_to_template('my_view.html',
                              {'movie': settings.MEDIA_URL + 'flash.swf?' + movie})

rawDescription: Convert param into python?

description: Convert param into python


code:
names = random.sample(population, 5)
names

rawDescription: randomly choose from list using random.randint in python

description: Randomly choose from list using random.randint in python


code: df.merge(df2, on=["First", "Last"], how='outer', suffixes=('', '_new'))

rawDescription: Combining data with overlap

description: Combining data with overlap


code:
w, h = self.canvas.winfo_width(), self.canvas.winfo_height()
if event.x > 0.9*w:
    self.canvas.xview_scroll(1, 'units')
elif event.x < 0.1*w:
    self.canvas.xview_scroll(-1, 'units')
if event.y > 0.9*h:
    self.canvas.yview_scroll(1, 'units')
elif event.y < 0.1*h:
    self.canvas.yview_scroll(-1, 'units')

rawDescription: Tkinter: Draw rectangle using a mouse

description: Tkinter: Draw rectangle using a mouse


code:
class BitArray(object):
    def __init__(self, lenght):
        self.values = bytearray(b"\x00" * (lenght // 8 + (1 if lenght % 8  else 0)))
        self.lenght = lenght

    def __setitem__(self, index, value):
        value = int(bool(value)) << (7 - index % 8)
        mask = 0xff ^ (7 - index % 8)
        self.values[index // 8] &= mask
        self.values[index // 8] |= value
    def __getitem__(self, index):
        mask = 1 << (7 - index % 8)
        return bool(self.values[index // 8] & mask)

    def __len__(self):
        return self.lenght

    def __repr__(self):
        return "<{}>".format(", ".join("{:d}".format(value) for value in self))

rawDescription: Is there a builtin bitset in Python that's similar to the std::bitset from C++?


code:
from collections import OrderedDict
def get_uniq_by_value(data, val_name):
    return list(OrderedDict.fromkeys(val for value in data.values() for val in value.get(val_name,[])))

rawDescription: Get unique list items by nested dictionary key


code:
def clean_status(self):
    return self.instance.status

rawDescription: How can I disable a model field in a django form

description: Disable a model field in a django form


code:
a = s.index.values
idx = np.array([a, a]).T.flatten()[:len(a)]
idx
s.groupby(idx).mean()

rawDescription: Python, Pandas: average every 2 rows together


code:
from win32api import GetSystemMetrics

width = GetSystemMetrics(0)
height = GetSystemMetrics(1)

win = GraphWin('Face', width, height)

rawDescription: Python full-screen graphics

description: Python full-screen graphics


rawDescription: Built-in method to Generate Random Strings of Fixed Length From Given Characters


rawDescription: A pythonic way to remove all instances of an element without generating a new list


code:
A = [1,2,3,4,5,6,7,8,9,10]
B = [11,12,13,14,15]
for a in A:
    results = []           # define new list for each item in A
    #loop over B and collect the result in a list(results)
    for b in B:
        result = a + b
        results.append(result)   #append the result to results
    #print results               # uncomment this line to see the content of results
    filename = '{}.txt'.format(a)      #generate file name, based on value of `a`
    #always open file using `with` statement as it automatically closes the file for you
    with open( filename , 'w') as f:
       #now loop over results and write them to the file
       for res in results:
          #we can only write a string to a file, so convert numbers to string using `str()`
          f.write(str(res)+'\n') #'\n' adds a new line

rawDescription: writing multiple out files from for loop

description: Writing multiple out files from for loop


rawDescription: Averaging the values in a dictionary based on the key


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

n_points = 1000
x = np.random.normal(0, 2, n_points)
y = np.random.normal(0, 2, n_points)

hist, xedges, yedges = np.histogram2d(x, y, bins=np.sqrt(n_points))

fig2D = plt.figure()
ax2D = fig2D.add_subplot(111)
ax2D.contourf(hist, interpolation='nearest',
              extent=(xedges[0], xedges[-1], yedges[0], yedges[-1]))
plt.show()

rawDescription: 3D histograms and Contour plots Python

description: 3D histograms and Contour plots Python


code:
# foo.py
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.publisher.browser import BrowserPage
class FooView(BrowserPage):
    index = ViewPageTemplateFile('foo.pt')

rawDescription: What is the difference between template in ZCML and ViewPageTemplateFile


code:
while True:
    encrypt = raw_input("Encrypt or decrypt a file (E/d):")

    # Convert to lowercase
    encrypt = encrypt.lower()

    # If it's e or d then break out of the loop
    if encrypt in ('e', 'd'):
        break

    # Otherwise, it'll loop back and ask them to input again

rawDescription: Python Input validation

description: Python Input validation


code:
df['Last Value'] = df.shift(1).Value
...
df = df.reset_index() # go back to tabular format from this hierarchy

rawDescription: value from a past, potentially missing month in dataframe

description: Value from a past, potentially missing month in dataframe


code:
def print_reports(self, cr, uid, ids, context):
    """DO NOT EDIT !"""

rawDescription: Print two report in Odoo8

description: Print two report in Odoo8


code: isinstance(currentValue, (int, long))

rawDescription: Python: integer precision and type checking


code: current_salary += current_salary * amount_of_raise

rawDescription: Should I do anything to make my code more pythonic?


rawDescription: Preferred way to format a dictionary being passed to a function?


code:
range(3, 6)             # normal call with separate arguments
args = [3, 6]
range(*args)            # call with arguments unpacked from a list

rawDescription: Fast matrix transposition in Python

description: Fast matrix transposition in Python


rawDescription: rearranging an array of arrays (python)

description: Rearranging an array of arrays (python)


code:
@periodic_task(run_every=timedelta(seconds=10))
def pprint_dict2():
    import pprint
    values = {
        u'key1': 'value1',
        u'_id1': "ObjectId('55fff3b74322c53d18ae4687')",
        u'key2': 'value2',
        u'_id2': "ObjectId('55fff3b74322c53d18ae4687')",
        u'key3': 'value3',
        u'_id3': "ObjectId('55fff3b74322c53d18ae4687')",
        u'key4': 'value4',
        u'_id3': "ObjectId('55fff3b74322c53d18ae4687')",
    }
    s = pprint.pformat(values, width=1)
    print(s)  # or even better logger.info(...)

rawDescription: How to remove timestamps from celery pprint output?

description: Remove timestamps from celery pprint output


code: n = int(raw_input("#"))

rawDescription: Why is this python while loop missing the logical operator?


code:
hst, edges, bincounts = binned_statistic_dd([np.ones(10), np.ones(10)], None, 'count', bins=3)
hst

description: Output in scipy.stats.binned_statistic_dd()


rawDescription: sqlachemy hybrid property error - operator is not supported on this expression

description: Sqlachemy hybrid property error - operator is not supported on this expression


code:
def _bin(x, width):
    return ''.join(str((x>>i)&1) for i in xrange(width-1,-1,-1))

rawDescription: Base-2 (Binary) Representation Using Python


rawDescription: PIL Plus/imToolkit replacements

description: PIL Plus/imToolkit replacements


code:
class Genre(models.Model):
    parent = models.ForeignKey(Genre, null=True, related_name='sub_genre')
    description = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(unique=True)

    def __unicode__(self):
        return self.description

    @property
    def is_top_level(self):
        return bool(self.parent)

rawDescription: Conditional form display logic with Django ModelForm


code:
class FunctionFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Function
    name = factory.Sequence(lambda n: "Function %d" % n)

class FunctionParameterFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.FunctionParameter
    function = factory.SubFactory(FunctionFactory)

class FunctionInstantiationFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.FunctionInstantiation
    function = factory.SubFactory(FunctionFactory)

class ParameterSettingFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.ParameterSetting

    function_instantiation = factory.SubFactory(FunctionInstantiationFactory)
    function_parameter = factory.SubFactory(FunctionParameterFactory,
        function=factory.SelfAttribute('..function_instantiation.function'))

class FunctionToParameterSettingsFactory(FunctionInstantiationFactory):
    class Meta:
        model = models.FunctionInstantiation

    # This overrides the function_instantiation created inside
    # ParameterSettingFactory, which then overrides the Function creation,
    # with the SelfAttribute('..function_instantiation.function') syntax.
    parameter_setting_1 = factory.RelatedFactory(ParameterSettingFactory,
        'function_instantiation')
    parameter_setting_2 = factory.RelatedFactory(ParameterSettingFactory,
        'function_instantiation')

rawDescription: Getting id of associated child records in factory_boy


code:
class C(object):
    pass

C = decorated_by_class(C)

rawDescription: Subclass from a class decorated by a class


code:
import random
joke_list = ['joke1', 'joke2', 'joke3']
random.choice(joke_list)

rawDescription: How to choose a random interaction with user input in Python?

description: Choose a random interaction with user input in Python


code:
class delegate(object):

    def __init__(self, func):
        self.callbacks = []
        self.basefunc = func

    def __iadd__(self, func):
        if callable(func):
            self.__isub__(func)
            self.callbacks.append(func)
        return self

    def callback(self, func):
        if callable(func):
            self.__isub__(func)
            self.callbacks.append(func)
        return func

    def __isub__(self, func):
        try:
            self.callbacks.remove(func)
        except ValueError:
            pass
        return self

    def __call__(self, *args, **kwargs):
        result = self.basefunc(*args, **kwargs)
        for func in self.callbacks:
            newresult = func(result)
            result = result if newresult is None else newresult
        return result

rawDescription: What's the preferred way to implement a hook or callback in Python?


code:
def hstack2(arrays) :
  return arrays[0].__array_wrap__(numpy.hstack(arrays))

rawDescription: Stacking numpy recarrays without losing their recarrayness


code:
dd2=list(d2[0])
dd2

rawDescription: Best Way to Resize Numpy Dtype for Structured data


code:
from distutils.core import setup, Extension
import numpy as np
from Cython.Distutils import build_ext

setup(
    ext_modules=[Extension("myfunc", ["myfunc.pyx"])],
    cmdclass = {'build_ext': build_ext},
    include_dirs=[np.get_include()])

rawDescription: C Function in Python: Return an Array and Variables


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

import webapp2

class ActionPage(webapp2.RequestHandler):

    def get(self, action):

        self.response.headers['Content-Type'] = 'text/plain'
        self.response.out.write('Action, ' + action)

class MainPage(webapp2.RequestHandler):

    def get(self):

        self.response.headers['Content-Type'] = 'text/plain'
        self.response.write('Hello, webapp2 World!')

app = webapp2.WSGIApplication([
        webapp2.Route(r'/<action:(start|failed)>', handler=ActionPage),
        webapp2.Route(r'/', handler=MainPage),
], debug=True)

rawDescription: How to parse path-parameter with webapp2

description: Parse path-parameter with webapp2


rawDescription: Django URLs: matching a fixed number of optional parameters?


rawDescription: Python getting unique pairs from multiple lists of different lengths


code: {'what': '\n            This is python file, not json\n            ', 'font_size': 14.0, 'translate_tabs_to_spaces': True, 'font_face': 'Monaco', 'word_wrap': 'true', 'highlight_line': True, 'ignored_packages': ['']}

rawDescription: Loading settings.py config file into a dict


code:
class DictWatch(dict):
    def __init__(self, *args, **kwargs):
        self.callback = kwargs.pop('callback')
        dict.__init__(self, args)

    def __setitem__(self, key, val):
        # YOUR HOOK HERE
        self.callback(key, val)
        dict.__setitem__(self, key, val)

    # and other overrided dict methods if you need them

rawDescription: Python 3: hook list & dict changes

description: Python 3: hook list & dict changes


code:
df3 = df2.apply(cond_sum,axis=1)
df3

rawDescription: Summing over a DataFrame with two conditions and multiple values


code:
def flatten(obj, allowed=(u'p', u'em')):
    collector = []

    def process(v, collector=collector):
        if isinstance(v, (list, collections.Mapping)):
            collector += flatten(v, allowed=allowed)
        elif isinstance(v, basestring):
            collector.append(v)
        else:
            raise ValueError('Cannot handle type: {t}'.format(t=v.__class__))

    if isinstance(obj, list):
        for v in obj:
            process(v)

    if isinstance(obj, collections.Mapping):
        for k, v in obj.iteritems():
            if k in allowed:
                process(v)

    return collector

if __name__ == '__main__':
    print(flatten(a))

rawDescription: Separate text from nested OrderedDict in Python


code:
import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)

def log1():
    logging.info('log1')

def log2():
    logging.info('log2')

if __name__ == '__main__':
    log1()
    log2()

rawDescription: Multiple functions to write into a single log file using Python


rawDescription: Reorganizing a Pandas DataFrame

description: Reorganizing a Pandas DataFrame


code:
src_tz = pytz.timezone('GMT')
dt = src_tz.localize(dt)

rawDescription: Converting GMT to EST from CSV file using Python


rawDescription: Python script, runs well, but not perfectly, debugging help


code:
d1['Category'] = d1['event name'].map(d2.set_index('Event name')['Category'])
d1

rawDescription: Python - Pandas - How to mark elements in 1 dataframe with elements from a second dataframe?


rawDescription: How do I add tags to certain strings in python using re.sub?

description: Add tags to certain strings in python using re.sub


rawDescription: How to get the Django model with maximum field value?

description: Get the Django model with maximum field value


rawDescription: how to group new dictionaries by using common strings from my dictionary

description: Group new dictionaries by using common strings from my dictionary


code:
def writeToCSVFile(self,csvFilePath,testResultList, counter):
    #Open a CSV file object
    reportname = "toxedo_report{}.csv".format(counter)
    csvFilObj=open(csvFilePath+reportname,"wb")
    #writing CSV file with the statistical values
    mywritter=csv.writer(csvFilObj)
    for rowVal in testResultList:
        mywritter.writerows(rowVal)
    #Closing the CSV file object
    csvFilObj.close()

rawDescription: create csv file on each run

description: Create csv file on each run


rawDescription: Appending a list to the top of Pandas DataFrame output


rawDescription: Negative exponent with NumPy array operand


code: {'things': [Key('Thing', 'roro')]}

rawDescription: Get properties of ndb model instance where Python name != datastore name


code:
for i in xrange(0,10,2):
  print(i)

rawDescription: How do I loop through a Python list by twos?

description: Loop through a Python list by twos


rawDescription: Use pandas (and glob?) to merge numerous (csv) data text files from a directory.


code:
from collections import defaultdict
with open("filename", 'r') as f:
    for text in f:
        decoded = text.decode("utf-8")
        count = defaultdict(int)
        for i in decoded:
            count[i] += 1

rawDescription: python string including double quote character

description: Python string including double quote character


code:
from lxml import etree
outtxt = response.read()
root = etree.fromstring(outtxt)
root.xpath("my_xpath_expression")

rawDescription: XPath for sub-element's text value in lxml


rawDescription: Filter Data Frame by dates in another dataframe


code:
items = {'item1': 'bill', 'item2': 'cows', 'item3': 'abcdef'}
choice = input("Select your item: ")
if choice in items:
    the_choice = items[choice]
else:
    print("Uh oh, I don't know about that item")

rawDescription: Python 3: Get value of variable entered from user input


code:
def set_occupancy(dt1, dt2, YD, occupancy, fill_gap_days=0):
    """
    For a date range starting dt1 and ending, inclusively, dt2,
    sets the corresponding 'pixels' in occupancy vector to 1.
    If fill_gap_days > 0, then the end 'pixel' is extended
    (dilated) by this many positions, so that we can fill
    the gaps between intervals that are close to each other.
    """
    pos1 = map_date_to_position(dt1, YD)
    pos2 = map_date_to_position(dt2, YD) + fill_gap_days
    occupancy[pos1:pos2] = 1

rawDescription: How to combine records based on date using python connected components?

description: Combine records based on date using python connected components


rawDescription: Python: How to store a REQUEST for input in a variable?


code:
import operator

output = dict()
container =  [[u'unicode_text', 5, 395, 2, 0, 2],
              [u'unicode_text', 235, 5, 3, 3, 10],
              [u'other_unicode_text', 3, 65, 28, 16, 52],
              [u'unicode_text', 95, 5, 8, 7, 38]]

for sublist in container:
    try:
        output[sublist[0]] = map(operator.add, output[sublist[0]], sublist[1:])
    except KeyError:
        output[sublist[0]] = sublist[1:]

rawDescription: Lists aggregation in python

description: Lists aggregation in python


code:
def plot_contour(x_dim, y_dim, x_steps, y_steps, scalar_field, file_path, v_min, v_max, levels=None):
    x, y = numpy.mgrid[-x_dim/2:x_dim/2:x_steps*1j, -y_dim/2:y_dim/2:y_steps*1j]
    cs = plt.contourf(x, y, scalar_field, zorder=1, cmap=cm.jet, extent=[-x_dim/2.0, x_dim/2.0, -y_dim/2.0, y_dim/2.0], vmin=v_min, vmax=v_max, levels=levels)
    plt.colorbar(cs)
    return cs.levels

v_min, v_max = bounds([Za, Zb])

plt.figure()
plt.subplot(121)
levels = plot_contour(x_dim, y_dim, x_steps, y_steps, Za, 'Za', v_min, v_max)
plt.subplot(122)
plot_contour(x_dim, y_dim, x_steps, y_steps, Zb, 'Zb', v_min, v_max, levels=levels)
plt.show()

rawDescription: Same color bar range for different plots - Matplotlib


code:
if isinstance(src, io.TextIOBase):
    srctxt = src
else:
    srctxt = io.TextIOWrapper(src)

rawDescription: Text mode adapter for binary (or text) mode file


code: [each for each in my_json if each.get('infos', {}).get('spam') == 'eggs']

rawDescription: Filtering json response with python list comprehension


code:
lst = [range(5) for _ in range(5)]
[ls for ls in lst if not ls.insert(2, 'null')]

rawDescription: List comprehension expression showing none value insted of sublist


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

class Comment(models.Model):
    text = models.TextField(max_length = 300)
    author = models.ForeignKey(User)
    timestamp = models.DateTimeField(auto_now_add = True)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

rawDescription: Django ManyToMany doubt

description: Django ManyToMany doubt


code:
case = 'anchorage,ak'
case_list = case.replace(' ', '').split(',')  # remove all whitespace and split case by comma
for elem in case_list:
    if elem in A:
        # insert code to replace case with B[A[elem]]
        break

rawDescription: Matching partial cases to Python dictionary


code:
class Reader:
    def __init__(self, filename):
        self.m_headers = []
        self.m_seclist = []
        ...

rawDescription: Python class instance not being destroyed at end of method


code:
import subprocess, re

RE_MAC = re.compile(r'\bHWaddr\s+(((?(2):|)[\dA-Fa-f]{2}){6})\b')
match = RE_MAC.search(subprocess.check_output(["ifconfig", "wlan0"]))
if match:
    mac_addr = match.group(1)

rawDescription: Python string extraction from Subprocess


code:
myList = {'fileOne', 'fileTwo', 'fileThree'}
import importLib
gbl = globals()
for toImport in myList:
    moduleToImport = 'parentDirectory.'+toImport
    gbl[moduleToImport] = importlib.import_module(moduleToImport)

rawDescription: Import files in python with a for loop and a list of names


rawDescription: Increase all of a lists values by an increment


code:
from gi.repository import Gtk
from os.path import abspath, dirname, join

WHERE_AM_I = abspath(dirname(__file__))

# My Model map
mm = {
    'name'        : 0,
    'catalog_num' : 1,
    'comment'     : 2,
    'component'   : 3,
    'is_top'      : 4,
    'is_child'    : 5,
}

class MyApp(object):

    def __init__(self):
        """
        Build GUI
        """

        # Build GUI from Glade file
        self.builder = Gtk.Builder()
        self.glade_file = join(WHERE_AM_I, 'gui.glade')
        self.builder.add_from_file(self.glade_file)

        # Get objects
        go = self.builder.get_object
        self.window = go('window')
        self.treestore = go('treestore')

        # Fill model
        self._load_model()

        # Connect signals
        self.builder.connect_signals(self)
        self.window.connect('delete-event', lambda x,y: Gtk.main_quit())

        # Everything is ready
        self.window.show()

    def _load_model(self):

        my_data = [
                ['Cheese', 'F001', 'This is the best cheese ever!', '', True, False],
                ['Pepperoni', 'F002', 'Delicious pepperoni :}', '', True, False],
                ['Pepperonni Pizza', 'P001', 'Yes, I\'m hungry :(', '', True, False],
                ['', '', None, 'Cheese', False, True],
                ['', '', None, 'Pepperonni', False, True],
            ]

        parent = None
        for i in my_data:
            if i[mm['is_child']]:
                self.treestore.append(parent, i)
            else:
                parent = self.treestore.append(None, i)

if __name__ == '__main__':
    gui = MyApp()
    Gtk.main()

rawDescription: Different models for different level TreeView nodes


code:
import crunchers
crunchers.installed # all names
crunchers.cruncherA # actual module object, but you can't use it since you don't know the name when you write the code
# turns out the be pretty much the same as the first solution :p
mycruncher = getattr(crunchers, crunchers.installed[0])

rawDescription: Python: importing through function to main namespace


rawDescription: How do I implement a null coalescing operator in SQLAlchemy?

description: Implement a null coalescing operator in SQLAlchemy


code:
t = datetime.datetime(2012, 2, 23, 0, 0)
t.strftime('%m/%d/%Y')

rawDescription: Convert datetime object to a String of date only in Python


code:
enteramt = input ("How many")
value = int(enteramt) * 275
print("This is worth" , value)

rawDescription: Issues multiplying in python

description: Issues multiplying in python


rawDescription: What Can I do for sorting algorithm with my number language?


rawDescription: Python pandas equivalent for replace

description: Python pandas equivalent for replace


code: plt.rcParams['font.family'] = 'DejaVu Sans'

rawDescription: matplotlib show works while savefig fails for unicode

description: Matplotlib show works while savefig fails for unicode


rawDescription: Python script as a cron job - how to format the output as an e-mail with attachments?


code:
# plotfile.py
import matplotlib.pyplot as plt

class Plotter(object):
    def __init__(self, xval=None, yval=None):
        self.xval = xval
        self.yval = yval

    def plotthing(self):
        f = plt.figure()
        sp = f.add_subplot(111)
        sp.plot(self.xval, self.yval, 'o-')
        return f

rawDescription: Passing plots out of a class

description: Passing plots out of a class


code:
import collections
def top5_words(text):
    counts = collections.Counter(text.split())
    return counts.most_common(5)

rawDescription: Python - Return top 5 words with highest frequency


code:
#!/usr/bin/env python
blocks = [b'\xa1\r\xa594\x92z\xf8\x16\xaa', b'xfbI\xfdqx|\xcd\xdb\x1b\xb3']

# save blocks
with open('blocks.netstring', 'wb') as output_file:
    for blob in blocks:
        # [len]":"[string]","
        output_file.write(str(len(blob)).encode())
        output_file.write(b":")
        output_file.write(blob)
        output_file.write(b",")

rawDescription: Python: write and read blocks of binary data to a file


code:
def runQuery(query,port,flag):
    #ADOMD assembly
    ADOMDConn=ADOMD.AdomdConnection("Data Source=localhost:{0}".format(port))
    ADOMDConn.Open()
    ADOMDCommand=ADOMDConn.CreateCommand()
    ADOMDCommand.CommandText = query

    #read data in via AdomdDataReader object
    DataReader = ADOMDCommand.ExecuteReader()

    #get metadata, number of columns
    SchemaTable=DataReader.GetSchemaTable()
    numCol = SchemaTable.Rows.Count #same as DataReader.FieldCount

    #get column names
    columnNames = []
    for i in range(numCol):
        columnNames.append(str(SchemaTable.Rows[i][0]))

    #fill with data
    data = []
    while DataReader.Read()==True:
        row=[]
        for j in range(numCol):
            try:
                row.append(DataReader[j].ToString())
            except:
                row.append(DataReader[j])
        data.append(row)
    df = pandas.DataFrame(data)
    df.columns = columnNames

    if flag==0:
        DataReader.Close()
        ADOMDConn.Close()

        return df
    else:
        #metadata table
        metadataColumnNames = []
        for j in range(SchemaTable.Columns.Count):
            metadataColumnNames.append(SchemaTable.Columns[j].ToString())
        metadata=[]
        for i in range(numCol):
            row=[]
            for j in range(SchemaTable.Columns.Count):
                try:
                    row.append(SchemaTable.Rows[i][j].ToString())
                except:
                    row.append(SchemaTable.Rows[i][j])
            metadata.append(row)
        metadf = pandas.DataFrame(metadata)
        metadf.columns = metadataColumnNames

        DataReader.Close()
        ADOMDConn.Close()

        return df, metadf

rawDescription: Extracting raw data from a PowerPivot model using Python


code:
def largest_primes_under(number, cap):
    n = cap - 1
    while number and n >= 2:
        if all(n % d for d in range(2, int(n ** 0.5 + 1))):
            yield n
            number -= 1
        n -= 1

rawDescription: Finding the n largest primes under m

description: Finding the n largest primes under m


code:
from collections import Counter
def isPerm(s1, s2):
   return Counter(s1) == Counter(s2)

rawDescription: Why does this Python Dict code work?

description: Why does this Python Dict code work


code:
@test_decorator('found it', 'y')
def foo(x="bad", y="dog"):
    print("x={}, y={}".format(x, y))

def bar(x="bad", y="dog"):
    print("x={}, y={}".format(x, y))

print ("foo argspec={}".format(inspect.getargspec(foo)))
print ("bar argspec={}".format(inspect.getargspec(bar)))

foo(y='cat')

rawDescription: How to allow parameters for a decorator while keep the function's signature at the same time?

description: Allow parameters for a decorator while keep the function's signature at the same time


code: explore()

rawDescription: Truth tables in python using sympy

description: Truth tables in python using sympy


code:
def allocate_goals(prop_low, prop_high):
    all_goals = prop_low + prop_high * 3
    while True:
        yield random.choice(all_goals)

rawDescription: Allocate items according to an approximate ratio in Python


code:
x_min = min(points)
x_max = max(points)

rawDescription: List Comprehensions in Python to compute minimum and maximum values of a list


code:
c = Channel()
c.public_address()

rawDescription: How to create channel with socket in Python

description: Create channel with socket in Python


code: (fname for fname in os.listdir(your_dir) if time_filt(fname))

rawDescription: python find all file names in folder that follows a pattern

description: Python find all file names in folder that follows a pattern


code: pd.read_csv(file_path, nrows=1).columns

rawDescription: take column headers only from ASCII file in python

description: Take column headers only from ASCII file in python


code:
import sys
fname = sys.argv[1]
with open(fname, 'r') as f:
    print(f.read())

rawDescription: Print file passed in as argument

description: Print file passed in as argument


rawDescription: Remove older elements from a list

description: Remove older elements from a list


code: all(testList[0][i:i+j] in x for x in testList)

rawDescription: Longest repeated substring

description: Longest repeated substring


code:
import json
d = json.load(open('very_small_dic.txt', 'r'))
print(d) # {'somestring': 'myfunction'}

rawDescription: Clean way to manage parse-dictionaries that contain function names


code:
insert_indices = np.ravel_multi_index((range(A.shape[0]), C), A.shape) + 1
insert_indices

rawDescription: Efficent insertion of not aligned elements in a numpy array


rawDescription: Find sequence in two Numpy arrays

description: Find sequence in two Numpy arrays


code:
import pandas as pd

df = pd.DataFrame(feature_list, columns = mega_list)

rawDescription: How to get the indices for randomly selected rows in a list (Python)

description: Get the indices for randomly selected rows in a list (Python)


code:
import pandas as pd

data = pd.DataFrame({'interest':['one.a', 'two.a', 'three.a', 'four.b']})
data['i'] = data['interest'].map(lambda x:x.split('.', 1)[0])
print(data)

rawDescription: Python - map() to split and get first part only


code:
#get the img portion in the buffer
import base64
img = base64.b64decode(fetched_img)
# write it to disk or whatever

rawDescription: Sending text and binary using sockets in python


code: d2 = {'edges' : [i.getDict() for i in d1['edges']]}

rawDescription: Recursive __dict__ call on python object?


code:
from itertools import takewhile, imap
def sections(fle):
    with open(fle) as f:
        # python3 just use map
        stp = imap(str.strip, f)
        for line in imap(str.strip,stp):
            if line.startswith(":50:"):
                yield("".join(takewhile(lambda x: not x.startswith(":52A:"), stp)))

rawDescription: Python, optimal way of looping through a file, match two lines after a pattern and then join them


code: cursor = MySQLdb.connect(host='<xxx>',user="<xxx>", charset='utf8', passwd="<xxx>", db="<xxx>", unix_socket = 'path/mysql.sock').cursor()

rawDescription: MySQL special chars lost when queried in Python. (But works with Django.)


code:
def GetOddEvenCount(n):
    odd_count = 0
    even_count = 0

    for elem in range(n):
        if elem % 2 == 0: even_count += 1
        else: odd_count += 1
    return odd_count, even_count

rawDescription: Iterate through list of intervals in Python and return odd and even values?


code:
class WTrainning(wMeta.WMeta, QtGui.QWidget):

    def __init__(self):
        super(WTrainning, self).__init__()
        self.crono = Crono()

    def createUI(self):
        #Create GUI stuff here

        #Connect signal of self.crono to a slot of self.progressBar
        self.crono.tick.connect(self.progressBar.setValue)

rawDescription: Progress bar with pyqt

description: Progress bar with pyqt


code:
from itertools import compress, imap
import operator
lis = range(10)
output = [random.choice([True, False]) for _ in xrange(10)]
output
truthy = list(compress(lis, output))
truthy
falsy = list(compress(lis, imap(operator.not_,output)))
falsy

rawDescription: Python - Splitting an array into two using an optimized for loop


rawDescription: How do I do extract information from two different indices in two different data frames in Python?

description: Do extract information from two different indices in two different data frames in Python


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

def interval_mapping(image, from_min, from_max, to_min, to_max):
    from_range = from_max - from_min
    to_range = to_max - to_min
    scaled = np.array((image - from_min) / float(from_range), dtype=float)
    return to_min + (scaled * to_range)

img = cv2.imread('ygqCd.jpg', 0)
blurred_img = cv2.medianBlur(img, 11)

s_mask = 17

sobelx = np.abs(cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=s_mask))
b_sobelx = np.abs(cv2.Sobel(blurred_img, cv2.CV_64F, 1, 0, ksize=s_mask))
sobelx = interval_mapping(sobelx, np.min(sobelx), np.max(sobelx), 0, 255)
b_sobelx = interval_mapping(b_sobelx, np.min(sobelx), np.max(sobelx), 0, 255)

sobely = np.abs(cv2.Sobel(img,cv2.CV_64F,0,1,ksize=s_mask))
sobely = interval_mapping(sobely, np.min(sobely), np.max(sobely), 0, 255)
b_sobely = np.abs(cv2.Sobel(blurred_img, cv2.CV_64F, 0, 1, ksize=s_mask))
b_sobely = interval_mapping(b_sobely, np.min(sobely), np.max(sobely), 0, 255)

sobel_xy = 0.5 * sobelx + 0.5 * sobely
b_sobel_xy = 0.5 * b_sobelx + 0.5 * b_sobely

fig = plt.figure(figsize=(10, 14))
plt.subplot(3,2,1),plt.imshow(sobelx,cmap = 'gray')
plt.title('Sobel X'), plt.xticks([]), plt.yticks([])
plt.subplot(3,2,2),plt.imshow(b_sobelx,cmap = 'gray')
plt.title('Blurred Sobel X'), plt.xticks([]), plt.yticks([])
plt.subplot(3,2,3),plt.imshow(sobely,cmap = 'gray')
plt.title('Sobel Y'), plt.xticks([]), plt.yticks([])
plt.subplot(3,2,4),plt.imshow(b_sobely,cmap = 'gray')
plt.title('Blurred Sobel Y'), plt.xticks([]), plt.yticks([])
plt.subplot(3,2,5),plt.imshow(sobel_xy,cmap = 'gray')
plt.title('Sobel XY'), plt.xticks([]), plt.yticks([])
plt.subplot(3,2,6),plt.imshow(b_sobel_xy,cmap = 'gray')
plt.title('Blurred Sobel XY'), plt.xticks([]), plt.yticks([])
plt.tight_layout()

plt.show()

rawDescription: applying sobel filter on image

description: Applying sobel filter on image


code:
import types

class B:
    def b_func(self, arg):
        """Some doc."""
        print('ok', arg)

class A(B):
    def __init__(self):
        pass

a = A()
a.b_func('test')

help(A)

rawDescription: Delegate function to class instance attribute


code:
import csv

with open(filename) as file:
    reader = csv.DictReader(
        file,
        delimiter='\t',
        fieldnames=['y', 'x', 'box', 'direction', 'word', 'clue'],
    )
    puzzle = {dct['word']: dct for dct in reader}

rawDescription: How to add CSV file to dictionary using specific keys in python?

description: Add CSV file to dictionary using specific keys in python


rawDescription: Python to read \n and \r in a txt file

description: Python to read \n and \r in a txt file


code: melted['col_name'] = 'test' + melted['test'] + '-' + melted['variable']

rawDescription: Pandas - restructure longitudinal data in a multilevel df to a single-level column


code: df2 = df2.interpolate()

rawDescription: What is the Pythonic way to apply a function to multi-index multi-columns dataFrame?


code:
def countries_view(request):
    if request.method == 'POST':
        form = CountryForm(request.POST)
        if form.is_valid():
            countries = form.cleaned_data.get('countries')
            # do something with your results
    else:
        form = CountryForm

    return render_to_response('render_country.html', {'form':form },
        context_instance=RequestContext(request))

rawDescription: Django: How can i create a multiple select form?


code:
def foo1(a, b):
    return b + a

def foo2(a, b):
    return a + b

import unittest

class TestFooBase:
    def test_1(self):
        self.assertEqual(self.impl(0, 0), 0)
    def test_2(self):
        self.assertEqual(self.impl(1, 2), 3)

class TestFoo1(unittest.TestCase, TestFooBase):
    impl = staticmethod(foo1)

    # OR
    # def impl(self, *args, **kwargs):
    #    return foo1(*args,**kwargs)

class TestFoo2(unittest.TestCase, TestFooBase):
    impl = staticmethod(foo2)

rawDescription: running the same test against multiple implementations

description: Running the same test against multiple implementations


code:
mask = df == 2
inds_a = mask.A[mask.A].index.values
inds_b = mask.B[mask.B].index.values

for ind in [inds_a, inds_b]:
    for sub in np.split(ind,   np.where(np.diff(ind) != 1)[0]+1):
        if sub.size > 1:
            print("2 appeared at {} to {}".format(sub[0], sub[-1]))

rawDescription: Identify continuous occurrences of a value in a dataframe


code: pattern = r'(\d-){n}\d'

rawDescription: How to match multiple characters 'n' times using Python RE module?

description: Match multiple characters 'n' times using Python RE module


code:
# -*- coding: utf-8 -*-
from django.db import models, migrations

def add_group_permissions():
    #read_only
    group, created = Group.objects.get_or_create(name='read_only')
    if created:
        group.permissions.add(can_read_campaign)
        logger.info('read_only_user Group created')

    #standard
    group, created = Group.objects.get_or_create(name='standard_user')
    if created:
        group.permissions.add(can_edit_users)
        logger.info('standard_user Group created')

    #admin
    group, created = Group.objects.get_or_create(name='admin_user')
    if created:
        group.permissions.add(can_edit_campaign, can_edit_users)
        logger.info('admin_user Group created')

class Migration(migrations.Migration):

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(add_group_permissions),
    ]

rawDescription: Django 1.7 where to put the code to add Groups programatically?


code:
small_names = []

for n in names:
    if len(n) <= 4:
        small_names.append(n)

rawDescription: Python: how to create a list from elements that don't meet a certain condition


code:
l1 = set(s for x in list1 for s in x)
l2 = set(s for x in list2 for s in x)

rawDescription: Python - Comparing two lists of sets

description: Python - Comparing two lists of sets


code: sys.argv = [ ipython_path, "notebook", "path/to/notebooks" ]

rawDescription: Launching ipython notebook via the api (script)


code:
final = [x.replace(' ', '-') for x in words]
final

rawDescription: Python to Transforming elements in a list when split


code:
def autoparts():
  parts_dict={}
  list_of_parts = open('list_of_parts.txt', 'r')
  for line in list_of_parts:
        k, v = line.split()
        parts_dict[k] = v
  return parts_dict

rawDescription: How is returning the output of a function different than printing it?


code: conj_patt = r'\b(' + '|'.join(conjunctions) + r')\b'

rawDescription: Find Pattern in Textfile From Several Elements In Several Lists?


code:
#!/usr/bin/python

import sys
import random

from gi.repository import Vips

# make vips leaktest itself .. this also reports a memory high-water mark
# you'll get a small speedup if you comment this out
Vips.leak_set(True)

composite = Vips.Image.black(10000, 10000)

for filename in sys.argv[1:]:
    tile = Vips.Image.new_from_file(filename, access = Vips.Access.SEQUENTIAL)
    x = random.randint(0, 10000)
    y = random.randint(0, 10000)
    composite = composite.insert(tile, x, y)

composite.write_to_file("output.tif")

rawDescription: Does Python-VIPS support assignment to part of its image ?


code: new_file = open("path/to/FILE_NAME.ext", "w")

rawDescription: creating a tmp file in python

description: Creating a tmp file in python


code:
import mechanize
import re
br=mechanize.Browser()
br.open('http://www.example.com')
br.links()
list(br.links())
list(br.links(text_regex=re.compile("About")))

rawDescription: python mechanize find_link find the final matching link

description: Python mechanize find_link find the final matching link


code: numbers = [n.strip() for n in numbers] # takes out unwanted spaces on the ends

rawDescription: Python, reading lines from a file one by one


rawDescription: Unpacking deeply nested struct with given C header into dictionary?


rawDescription: append 2dim arrays to one array

description: Append 2dim arrays to one array


code:
res = []
for word, frequency in fdist.most_common(words_count):
    word_dict = {}
    word_dict['word'] = word
    word_dict['count'] = frequency
    res.append(word_dict)
return res

rawDescription: How to get frequency of words in text depends of they part of speech?

description: Get frequency of words in text depends of they part of speech


code:
class Parent(Base):
    id = Column(Integer, primary_key=True)
    name = Column(String)
    children = relationship('Child', lazy='joined',
                            backref=backref('parent', lazy='joined'))

class Child(Base):
    id = Column(Integer, primary_key=True)
    parent_id = Column(ForeignKey(Parent.id))
    age = Column(Integer)

rawDescription: How to use a subquery to filter a sqlalchemy query on a one to many relationship?

description: Use a subquery to filter a sqlalchemy query on a one to many relationship


rawDescription: Numpy array slicing vs. for-loop results


code:
with open('inputFile.txt', 'r') as inp:
    fixed = inp.read().replace('blah', '!blah!')
with open('inputFile.txt', 'w') as out:
    out.write(fixed)

rawDescription: How to write before & after certain substrings in an Open file in python?

description: Write before & after certain substrings in an Open file in python


code: range(0, len(data), 2)

rawDescription: Average on overlapping windows in Python


code:
import lxml.etree as ET
# import xml.etree.ElementTree as ET
text = '''\
<root>
<foo>
    <bar/>
    <bar/>
</foo>
</root>'''

root = ET.fromstring(text)
for elt in root.findall('foo/bar'):
    parent = elt.getparent()
    print(parent)

rawDescription: XML Library Suggestions

description: XML Library Suggestions


code:
d = {}
for dte, val in zip(dates,values):
    d[dte] = d.get(dte, 0) + val

rawDescription: Python dictionary from two lists

description: Python dictionary from two lists


code:
import numpy as np
from scipy.interpolate import interp1d

# generate some example data
W = 3
H = 10
M = 5

A2 = np.arange(W * M).reshape(W, M)
print(A2)
# [[ 0  1  2  3  4]
#  [ 5  6  7  8  9]
#  [10 11 12 13 14]]

# the initial column indices for A2
x = np.arange(M)

# we create a scipy.interpolate.interp1d instance
itp_A2 = interp1d(x, A2, kind='nearest')

# the output column coordinates for A1
xi = np.linspace(0, M - 1, H)

# we get the interpolated output by calling the interp1d instance with the
# output coordinates
A1 = itp_A2(xi)
print(A1)
# [[  0.   0.   1.   1.   2.   2.   3.   3.   4.   4.]
#  [  5.   5.   6.   6.   7.   7.   8.   8.   9.   9.]
#  [ 10.  10.  11.  11.  12.  12.  13.  13.  14.  14.]]

rawDescription: Interpolate between rows or columns of a Numpy array


rawDescription: Regular expression for multiple matching in a hierarchical string


rawDescription: How to access C structs from a python array

description: Access C structs from a python array


code:
import re

txt = '''ip access-list IpAclDscpTest
   10 permit ip any any dscp 0
   20 permit ip any any dscp af31
   30 permit ip any any dscp ef
   40 permit ip any any dscp 34
   50 permit ip any any dscp 46'''

regex = r'''dscp\s+ # matches dscp and one or more spaces
            ([a-z0-9]+) # capture group, one or more lowercase alphanumerics
             \s*  # matches possible spaces after (0+)
              $ # this matches every endline (with MULTILINE flag below)
         '''

number_list = re.findall(regex, txt, re.MULTILINE | re.VERBOSE)

rawDescription: Filtering values after a string using regex


code:
for l in open('some_file.txt', 'r'):
    ...

rawDescription: Python Tokenization

description: Python Tokenization


code:
def iter_file(filename):
    with open(filename) as inp:
        for line in inp:
            line = line.split(' ')
            yield line[:-1] + line[-1].split('\t')

def do_correction(n4, n5):
    n4 = list(n4)

    for words_n5 in n5:
        for words_n4 in n4:

            # if n4 y == n5
            if (words_n4[0]+words_n4[1] == words_n5[0] and
                words_n4[2] == words_n5[1] and
                words_n4[3] == words_n5[2] and
                words_n4[4] >= words_n5[3]):
                yield words_n4[:-1] + words_n5[3:]
                break

            # if x n4 == n5
            elif (words_n4[0] in words_n5[0] and
                words_n4[1] == words_n5[1] and
                words_n4[2] == words_n5[2] and
                words_n4[3] == words_n5[3] and
                words_n4[4] >= words_n5[4]):
                idx = words_n5[0].find(words_n4[0])
                yield [words_n5[:idx], words_n5[idx:]], words_n5[1:]
                break
        else: # not found
            yield ['none'] + words_n5

with open('corrected', 'w') as output:
    for words in do_correction(iter_file('N4'), iter_file('N5')):
        output.write('%s\t%s' %(' '.join(words[:-1]), words[-1]))

rawDescription: Faster way to search strings in big file with python


code: l1 = [item for sublist in [list(itertools.repeat(k,25)) for k in l] for item in sublist]

rawDescription: python list average over bin sizes

description: Python list average over bin sizes


code:
def new_function():
    can.coords(oval1, *(moveLeft() + addThirty(moveLeft())))

rawDescription: Passing function returns as method parameters in Python


code:
@mock.patch('lib.mymodule.ClassC')
@mock.patch('lib.mymodule.ClassB')
@mock.patch('lib.mymodule.ClassA')
def TestHostRecordCreation(self):
    def test_A(self, MockClassA, MockClassB, MockClassC):
        f = MyClass("host", "user", "password")
        self.assertEqual(f, "bogus result")

    def test_B(self, MockClassA, MockClassB, MockClassC):
        f = MyClass("myhost", "myuser", "password")
        self.assertEqual(f, "other bogus result")

rawDescription: Good approach to mocking objects in Python?


code: app.config['WTF_CSRF_ENABLED'] = True

rawDescription: Creating flask form with selects from more than one table


code:
ts = df['X'] == df['X'].min()
pd.rolling_sum(ts, win_size).argmax()

rawDescription: pandas rolling computation to find set of small numbers

description: Pandas rolling computation to find set of small numbers


code: display(cell)

rawDescription: How do I use mlabwrap to call a matlab function with cell arguments from python?

description: Use mlabwrap to call a matlab function with cell arguments from python


code:
weapons = {}
weapons['Long_Swordsmenc'] = {'as': 4, 'ar': 5, 'de': 2, 'co': 2, 'asr': 7, 'he': 10, 'wm': 1, 'am': 1}

x1=raw_input('Player 1, enter your unit: ')

rawDescription: How to set a variable to a dictionary in python?

description: Set a variable to a dictionary in python


rawDescription: Mass Restore a Prior Version on Amazon's S3


code:
os.environ.clear() # NOTE: it clears C environ too!
getattr(os, 'environb', os.environ).update(env) # single source Python 2/3 compat.

rawDescription: python: getting actual environment variables to modify and pass to subprocess

description: Python: getting actual environment variables to modify and pass to subprocess


rawDescription: python shutil: only copy part of the file

description: Python shutil: only copy part of the file


code:
class MyParserLinkExtractor(LxmlParserLinkExtractor):
    def _extract_links(self, selector, response_url, response_encoding, base_url):
        links = []
        # hacky way to get the underlying lxml parsed document
        for el, attr, attr_val in self._iter_links(selector.root):
            # pseudo lxml.html.HtmlElement.make_links_absolute(base_url)
            try:
                attr_val = urljoin(base_url, attr_val)
            except ValueError:
                continue # skipping bogus links
            else:
                url = self.process_attr(attr_val)
                if url is None:
                    continue
            if isinstance(url, unicode):
                url = url.encode(response_encoding)

            # url here is a list
            for item in url:
                url = urljoin(response_url, item)
                link = Link(item, _collect_string_content(el) or u'',
                            nofollow=rel_has_nofollow(el.get('rel')))
                links.append(link)

        return unique_list(links, key=lambda link: link.url) \
                if self.unique else links

rawDescription: Scrapy - get multiple urls from one link


code:
nums = [x - 4.2315222659844824 + 2.5 for x in nums]
nums
sum(nums)/len(nums)

rawDescription: Create a random array with a particular average


code:
from string import uppercase

#Make a list of the column letters
cols = list(uppercase[3:]) + ['A' + c for c in uppercase]
#print(cols)

with open('example.csv', 'w') as f:
    for r in range(4, 53):
        row = ','.join([dict1.get(c + str(r), '') for c in cols])
        f.write(row + '\n')

rawDescription: Using dictionary keys as coordinates when writing to csv


rawDescription: Swapping characters within a list of strings in Python


code:
extent = [xbins.min(), xbins.max(), ybins.min(), ybins.max()]

fig, ax = plt.subplots()
mesh = ax.imshow(values, extent=extent, origin='lower', aspect='auto',
                 cmap='gist_earth', norm=LogNorm())

ax.axis('tight')
ax.set(title='Log Normalized Plot of Values')
fig.colorbar(mesh)

plt.show()

rawDescription: python, matplotlib: specgram data array values does not match specgram plot

description: Python, matplotlib: specgram data array values does not match specgram plot


code:
ids_file = '''\
id,site,longitude,latitude
9936,north,18.2,62.8
5856,north,17.4914,63.0167
1298,north,18.177,62.877
'''.splitlines()
reader = csv.reader(ids_file)
next(reader, None)
ids = {r[0] for r in reader}
ids

rawDescription: print columns matching a header value

description: Print columns matching a header value


code:
import re
a = "I am inclin- ed to ask simple questions"
result = re.findall('([a-zA-Z]+-)\s+(\w+)', a)
result
[first.rstrip('-') + second for first, second in result]

rawDescription: removing relevant hyphens in text

description: Removing relevant hyphens in text


code:
def list_to_tree(data):
    out = {
        'root': { 'id': 0, 'parent_id': 0, 'name': "Root node", 'sub': [] }
    }

    for p in data:
        pid = p['parent_id'] or 'root'
        out.setdefault(pid, { 'sub': [] })
        out.setdefault(p['id'], { 'sub': [] })
        out[p['id']].update(p)
        out[pid]['sub'].append(out[p['id']])

    return out['root']
    # or return out['root']['sub'] to return the list of root nodes

rawDescription: Building a menu tree from an adjacency list in Python


code: np.add.reduceat(b, i) / np.diff(np.r_[i, len(b)])

rawDescription: Digitize numpy array

description: Digitize numpy array


code:
mag_to_keep = []
for mag in kept:
    if float(mag['M_P']) <= -4.5:
        mag_to_keep.append(mag)

kept = mag_to_keep

rawDescription: Python ignoring command to remove items from list


rawDescription: Generate list of range tuples with given boundaries in python


code:
l = ['ab']
'a' in l
False

rawDescription: Python 'in' function , pandas dataframe wrongly populated


code:
df2 = df.pivot_table(values='CalciumConc_mgL',
                     index='SampleDate',
                     columns='SampleLocation').ffill()

rawDescription: Use Python/Pandas to Match Sample Pairs Yearly Data


code:
from datetime import datetime
import time
time_now = datetime.now()
time_at_start_of_today_local = datetime( n.year, n.month, n.day )
epochal_time_now = time.mktime( time_now.timetuple() )
epochal_time_at_start_of_today_local = time.mktime( time_at_start_of_today.timetuple() )
hours_since_start_of_day_today = (epochal_time_at_start_of_today_local - epochal_time_now) / 60 / 60

rawDescription: get unix time from yesterday 0000 hrs to today 0000 hours using python

description: Get unix time from yesterday 0000 hrs to today 0000 hours using python


code:
def filter_function(elm):
    return elm and "class" in elm.attrs and "A" in elm["class"] and "Y" not in elm["class"]

rawDescription: Selecting Tags With Multiple Part Class in BeautifulSoup


rawDescription: Create django join with fields that don't have same name


code:
env = Environment()

env.SConscript('src/SConscript', 'env')

rawDescription: scons construction environment inheritance

description: Scons construction environment inheritance


code:
def findWords(filepath):
  with open(filepath) as infile:
    for line in infile:
      words = re.findall('\w+', line.lower())
      yield from words

cnt = collections.Counter(findWords('02.2003.BenBernanke.txt'))

rawDescription: Counting phrase frequency in Python 3.3.2


code:
from abc import ABCMeta, abstractmethod

class ABCFileLike(metaclass=ABCMeta):
    @abstractmethod
    def __init__(self): pass

    @abstractmethod
    def write(self, line): pass

    @abstractmethod
    def close(self): pass

    @abstractmethod
    def flush(self): pass

rawDescription: How to make a file-like class work with `isinstance(cls, io.IOBase)`?

description: Make a file-like class work with `isinstance(cls, io.IOBase)`


code:
from ConfigParser import ConfigParser
import sys, os

# server variables
SITE_ROOT = os.path.split(__file__)[0]
WWW = os.path.split(SITE_ROOT)[0]

config = ConfigParser()
config.read([os.path.join(DK_SITE_ROOT, 'site.ini')])

# site properties
SITE_NAME = config.get('site', 'sitename')
DNS = config.get('site', 'dns')
SRV = config.get('server', 'srv')
# virtualenv variables
VENV_NAME = "dev"   # only

# derived settings
DJANGO_SETTINGS_MODULE = "%s.settings" % SITE_NAME
VIRTUAL_ENV = "%s/venv/%s" % (SRV, VENV_NAME)

# activate virtualenv
# (warning: https://code.google.com/p/modwsgi/wiki/CheckingYourInstallation)
_activate = "%s/%s/activate_this.py" % (
    VIRTUAL_ENV,
    'Scripts' if sys.platform == 'win32' else 'bin'
)
if sys.version_info >= (3, 0):
    exec(compile(open(_activate, 'rb').read(), _activate, 'exec'))
else:
    execfile(_activate, dict(__file__=_activate))

# make site directory importable
sys.path.insert(0, WWWDIR)

# set all GLOBAL vars as environment variables
for _varname in [k for k in globals().keys() if k == k.upper()]:
    _val = globals()[_varname]
    if type(_val) == str:
        os.environ[_varname] = _val

# This application object is used by the development server
# as well as any WSGI server configured to use this file.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

rawDescription: My virtualenv is not taking into account ? [apache, mod_wsgi and django]


code: df.to_csv('out.csv', index=False)

rawDescription: Create unique ID from the existing two columns, python


code: {k: bigdict[k] for k in ('l', 'm', 'n')}

rawDescription: best way to extract subset of key-value pairs from python dictionary object

description: Extract subset of key-value pairs from python dictionary object


code:
def anagrams(word):
    if len(word) == 1:
        return [word]
    current = word[0]
    anags = []
    for anag in anagrams(word[1:]):
        anags += [anag[:i] + current + anag[i:] for i in range(len(anag) + 1)]
    return anags

rawDescription: Generate all k-size anagrams of a string


code:
new_text = ""
for strg in string.splitlines():
    if strg == '@r=v4 "v4"':
        i += 1
        new_text += '@r=v{} "v{}"\n'.format(i,i)
    else:
        new_text += strg + '\n'

rawDescription: Using regex's to relabel and remove redundent items in a string


rawDescription: Issue with using the chr() method to add \x to characters in a list


code:
m  = MyDict()
m[0] = 5
m

rawDescription: How to change the behavior of a python dictionary's __setattr__?

description: Change the behavior of a python dictionary's __setattr__


rawDescription: Finding a match in two sets of synchronized lists


rawDescription: Python counter key value

description: Python counter key value


rawDescription: Graphs: contours, arrow and naming

description: Graphs: contours, arrow and naming


code:
key = [33, 53, 2, 42]
id = "%04d" % 1
x = ''.join([chr(a^ord(b)) for a, b in zip(key, id)])
x
int(''.join([chr(a^ord(b)) for a, b in zip(key, x)]))

rawDescription: How to calculate a short fixed length obfuscated ID similar to YouTube (e.g. 2WNrx2jq184)

description: Calculate a short fixed length obfuscated ID similar to YouTube (e.g. 2WNrx2jq184)


code:
class ServeImage(webapp2.RequestHandler):
  def get(self):
    key = self.request.get('key')
    image = Stocks.get(key)
    if image:
      self.response.headers['Content-Type'] = 'image/jpeg'
      self.response.out.write(image.picture)
    else:
      self.abort(404)

rawDescription: GAE python display multiple images in on page


code:
lst = [
    ['24', 'john', 'july', 'email@gmail.com'],
    ['12', 'alice', 'auguts', 'email@hotmail.com'],
    ['48', 'john', 'september', 'email@outlook.com'],
]

seen = set()
result = []
for item in lst:
    name = item[1]
    if name not in seen:
        seen.add(name)
        result.append(item)

result

rawDescription: How to erase duplicated element in row of a list in python

description: Erase duplicated element in row of a list in python


code: 'he said she was a nice girl'

rawDescription: Regular Expressions in Python - combining two operations in re.sub


code: G.get_edge_data(1, 2, key='xyz')

rawDescription: Changing edge attributes in networkx multigraph


code:
try:
    import Tkinter as tk
except ImportError:
    import tkinter as tk

class MainApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # the main container that holds all the frames
        container = tk.Frame(self)

        container.pack(side = "top", fill = "both", expand = True)
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0,weight = 1)

        def show_1(button):
            self.frame_2.grid_remove()
            self.frame_1.show(button)

        def show_2(button):
            self.frame_1.grid_remove()
            self.frame_2.show(button)

        self.frame_1 = Page1(container, show_2)
        self.frame_2 = Page2(container, show_1)

class Page1(tk.Frame):
    def __init__(self,parent,callback):
        tk.Frame.__init__(self,parent)
        self.grid(row = 0, column = 0, sticky = "w")
        self.callback = callback

        lbl1 = tk.Label(self,text = "Yes",font =("Helvetica",12,"bold"))
        lbl1.grid(row=1,sticky="W")

        lbl2 = tk.Label(self,text = "No",font =("Helvetica",12,"bold"))
        lbl2.grid(row=1,column=1,sticky="W")

        btn1 = tk.Button(self, text="next page", font=('MS', 24, 'bold'))
        btn1.grid(row=3,column = 0,columnspan=1)

        self.var1 = tk.BooleanVar()
        rButton1 = tk.Radiobutton(self,variable = self.var1,value=True)

        rButton1.grid(row=2,sticky = "W")

        rButton2 = tk.Radiobutton(self,variable = self.var1,value=False)
        rButton2.grid(row=2,column=1,sticky = "W")

        btn1['command']= self.button_clicked

    def button_clicked(self):
        if self.var1.get():
            self.callback('button_one')
        else:
            self.callback('button_two')

class Page2(tk.Frame):
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)

    def show(self, selected_button):
        if selected_button == 'button_one':
            text = "This is reccomendation 2"
        elif selected_button == 'button_two':
            text = "This is reccomendation 3"
        else:
            text = selected_button
        print(selected_button)
        lbl = tk.Label(self,text=text,font=("Helvetica",12,"bold"))
        lbl.pack()
        self.grid()

app = MainApp()
app.mainloop()

rawDescription: Displaying Label widget based on Radio Button answer


code:
a,b,c,d = map(int,input("Enter four numbers separated by spaces").split())

print(a,b,c,d)

rawDescription: Entering few integers in one line

description: Entering few integers in one line


code: all_locs = Location.objects.all()

rawDescription: django related manager - in template

description: Django related manager - in template


code: map(lambda color: reduce(lambda x,y: x+y, map(lambda y: 1,filter(lambda x: x==color, c))), colours)

rawDescription: Use map over a list of 50 generated colours to count, using filter, and reduce, or len, the frequency of occurence


code:
app_name = {'free': 'APP_FREE',
            'paid': 'APP_PAID'} # this can be extended if needed
APP_VER = app_name.get(version)
# APP_VER is None if version unknown

rawDescription: Assign dynamic key string in python

description: Assign dynamic key string in python


code: df1.groupby(['a','b']).filter(lambda x: len(x['c']) > 2)

rawDescription: How to delete minority rows from a pandas data frame?

description: Delete minority rows from a pandas data frame


rawDescription: Spin up new EC2 instances programatically with Python Boto


rawDescription: How to pass more than one parameter to map function in panda

description: Pass more than one parameter to map function in panda


code:
class My_Num(object):
    def __init__(self, val):
        self.val = val
    def __add__(self, other_num):
        if isinstance(other_num, My_Num):
            return self.val + other_num.val
        else:
            return self.val + other_num
    __radd__ = __add__

rawDescription: Operator overloading in python with the object on the right hand side of the operator


rawDescription: Numpy - summing up a list of vectors

description: Numpy - summing up a list of vectors


code:
# imagegrab.py
from PIL import ImageGrab
import time
time.sleep(5)
ImageGrab.grab().save("screen_capture.jpg", "JPEG")

rawDescription: My .bat file wont read the lines after using `python`


code:
class myParent( object ):
    def __init__( self, customParam ):
        self.parentNumber = 5
        self.customParam = customParam

class Child( myParent ):
    def __init__( self, customParam ):
        myParent.__init__( self, customParam )
        self.childNumber = 4

rawDescription: Python: Getting baseclass values from derived class


rawDescription: Trying to remove nan from csv file in python pandas


code:
'''/osm/way/nd[@ref=203936110]/following-sibling::nd[1]
   | /osm/way/nd[@ref=203936110]/preceding-sibling::nd[1]'''

rawDescription: XPath - Selecting preceding and following sibling of a specific node in a single query


rawDescription: Errors with obtaining and reading data from a file


rawDescription: Python- add to dictionary based on an incrementing value in 2 lists


code: print >> j, user[0].strip(), user[1].strip()

rawDescription: Printing a dictionary without newlines?

description: Printing a dictionary without newlines


code: any(x in new_names for x in t.lower().split())

rawDescription: What's a more efficient way of looping with regex?


code:
from google.appengine.ext.webapp import template

parent = template.Template("{% block content %}{% endblock %}")
path = os.path.join(os.path.dirname(__file__), 'index.html')
template.render(path, template.Context({"baseTemplate": parent}))

rawDescription: How to extend django template from python string

description: Extend django template from python string


rawDescription: Analysis of running time on recursive function


rawDescription: Python etag/last modified not working; how to get latest rss


code:
defect = defect_averaged.flatten()
sigma_flat = np.tile(sigma, 9)    # This gives you [.001, .01, .1, .001, .01, .1...]
mu_flat = np.tile(np.repeat(sigma, 3), 3)     # This is to get [.001, .001, .001, .1, .1....001, .001, .001, .1, .1...]
accuracy_flat = np.repeat(accuracy, 9)   # This gives you [.51, .51, .51, .51,....

rawDescription: How to reformat data for a 4 Dimensional Heatmap (3 space dimensions + intensity)

description: Reformat data for a 4 Dimensional Heatmap (3 space dimensions + intensity)


rawDescription: Python 3 - A Specific Operation on a List


code:
xx, yy = np.mgrid[0:4, 10:14]
top = xx[:-1,1:]
bot = xx[1:,1:]
left = yy[1:,:-1]
right = yy[1:,1:]
np.column_stack(v.ravel()
    for v in (top, left, top, right, bot, right, bot, left))

rawDescription: Gridding a numpy array

description: Gridding a numpy array


code:
Import('env')

def my_emitter( env, target, source ):
    data = str(source[0])
    target = []
    with open( data, 'r' ) as lines:
        for line in lines:
           line = line.strip()
           name, contents = line.split(' ', 1)
           if not name: continue

           generated_source  = env.Command( name, [], 'echo "{0}" > $TARGET'.format(contents) )
           source.extend( generated_source )
           target.append( name+'.c' )

    return target, source

def my_action( env, target, source ):
    for t,s in zip(target, source[1:]):
        with open(t.abspath, 'w') as tf:
            with open(s.abspath, 'r') as sf:
                tf.write( sf.read() )

SourcesGenerator = env.Builder( action = my_action, emitter = my_emitter )
generated_sources = SourcesGenerator( env, source = 'source.txt' )

lib = env.Library( 'functions', generated_sources )

rawDescription: SCons to generate variable number of targets


code:
from pyDes import *
plaintext = "The secret message is : "
iv = 'kritanj '
key = '7chrkey'
plaintext = plaintext.encode("utf-8")
iv = 'kritanj '
k = des(key+'\0', CBC, iv)
print (iv + k.encrypt(plaintext)).encode("base64", "strict")

rawDescription: Python equivalent of PHP Mcrypt

description: Python equivalent of PHP Mcrypt


code:
import logging

logger = logging.getLogger('mod1')

def fctn1():
    logger.getChild('fctn1').debug('I am chatty')
    # do stuff (notice, no setLevel)

def fctn2():
    logger.getChild('fctn2').debug('I am even more chatty')
    # do stuff (notice, no setLevel)

rawDescription: Preferred method for controlled logging of Python debug messages?


code: result = {key: [v for v in value if v != ''] for key, value in result.items()}

rawDescription: Iterate an operation on a dictionary in python


rawDescription: python pandas beginner: multi-dimensional data-analysis workflow (groupby+agg+plot)

description: Python pandas beginner: multi-dimensional data-analysis workflow (groupby+agg+plot)


code:
from collections import defaultdict
value, key = defaultdict(list), []

for x in l:
    key.append(x[0])
    for k, v in x[1].items():
        value[k].append(v)

rawDescription: Get data from dict by using for-loop in Python


rawDescription: Dynamically assigning variable with locals() isn't working in recursive function


code:
fig, ax = plt.subplots()
fig.set_size_inches(14, 7)
uniform_data = np.random.rand(10, 12)
#add an axis to our plot for our cbar, tweak the numbers there to play with the sizing.
cbar_ax = fig.add_axes([.92, .3, .02, .4])
#assign the cbar to be in that axis using the cbar_ax kw
sns.heatmap(uniform_data, ax=ax, cbar_ax=cbar_ax)

#hacky solution to change the highest (last) yticklabel
changed_val = ">= " + cbar_ax.get_yticklabels()[-1].get_text()

#make a new list of labels with the changed value.
labels = [x.get_text() for x in cbar_ax.get_yticklabels()[:-1]] + [changed_val]

#set the yticklabels to the new labels we just created.
cbar_ax.set_yticklabels(labels)

rawDescription: Python - Seaborn: Modifying the heatmap legend


code:
df_new1 = df.groupby('id').apply(lambda x: pd.Series(dict(
 new_col1=(x['foo'].notnull()).sum(),
 new_col2=np.in1d(x['bar'],'P').sum(),
 new_col3=np.in1d(x['bar'],'C').sum(),
 new_col4=(np.in1d(x['Status'],['Approved, not yet paid']) & np.in1d(x['Current_Status'],['Approved, paid'])).sum(),
 new_col5=(np.in1d(x['Status'],['Approved, not yet paid']) & np.in1d(x['Current_Status'],['Approved, not yet paid'])).sum(),
 new_col6=(np.in1d(x['Status'],['Approved, paid']) & np.in1d(x['Current_Status'],['Approved, paid'])).sum()
)))

rawDescription: Pandas, long processing time of groupby and comparisons


rawDescription: Leibniz formula for π - Is this any good? (Python)


code:
import os
os.remove(something_you_know)

rawDescription: Downloading Image with urllib.urlretrieve() in Django


code:
import re
s='[<span class="street-address">\n            510 E Airline Way\n           </span>]'
re.sub(r'\[|\]|\s*<[^>]*>\s*', '', s)

rawDescription: Python beautifulsoup trying to remove html tags 'span'


code: topiclist = [topic for topic in dictionary if word in dictionary[topic]]

rawDescription: Find which dictionaries from a list contain word


rawDescription: extract a pattern from different string in Python

description: Extract a pattern from different string in Python


code:
params = {}
params['something'] = "Task_{0}".format(i)
params['something_else'] = "task{0}_types".format(i)
# ...
params['last_thing'] = None
t = Task(**params)

rawDescription: Passing formatted strings to functions as arguments