code:
#!/usr/bin/python

import pygst
pygst.require("0.10")
import gst

player = gst.Pipeline("player")
source = gst.element_factory_make("videotestsrc", "testsource")
effect = gst.element_factory_make("clockoverlay", "clock")
freeze = gst.element_factory_make("imagefreeze", "freeze")
colorspace = gst.element_factory_make("ffmpegcolorspace", "colorspace")
sink = gst.element_factory_make("ximagesink", "imagesink")

player.add(source, effect, freeze, colorspace, sink)
gst.element_link_many(source, effect, freeze, colorspace, sink)
player.set_state(gst.STATE_PLAYING)

while True:
  inp = raw_input("Press enter:")
  player.set_state(gst.STATE_READY)
  player.set_state(gst.STATE_PLAYING)

rawDescription: GStreamer How to extract video frame from the flow?


code:
from collections import Mapping

class EnvironmentStoreMapping(Mapping):
    def __init__(self, user, environments):
        self._user = user
        self._envs = {env.name: env for env in environments}
        self._cache = {}

    def __getitem__(self, key):
        try:
            return self._cache[key]
        except KeyError:
            store = EnvironmentStore(self._user, self._envs[key])
            self._cache[key] = store
            return store

    def __iter__(self):
        return iter(self._envs)

    def __len__(self):
        return len(self._envs)

    def __contains__(self, key):
        return key in self._envs

_environments_cache = EnvironmentStoreMapping(user, userEnvironments)

rawDescription: Most optimized way for creating objects from a huge set of objects


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

class PiecewiseNormalize(Normalize):
    def __init__(self, xvalues, cvalues):
        self.xvalues = xvalues
        self.cvalues = cvalues

        Normalize.__init__(self)

    def __call__(self, value, clip=None):
        # I'm ignoring masked values and all kinds of edge cases to make a
        # simple example...
        if self.xvalues is not None:
            x, y = self.xvalues, self.cvalues
            return np.ma.masked_array(np.interp(value, x, y))
        else:
            return Normalize.__call__(self, value, clip)

data = np.random.random((10,10))
data = 10 * (data - 0.8)

fig, ax = plt.subplots()
norm = PiecewiseNormalize([-8, -1, 0, 1.5, 2], [0, 0.1, 0.5, 0.7, 1])
im = ax.imshow(data, norm=norm, cmap=plt.cm.seismic, interpolation='none')
fig.colorbar(im)
plt.show()

rawDescription: Associating colors from a continuous colormap to specific values in matplotlib


code:
from tkinter import *
import pyaudio
import wave
import sys
import threading

# --- classes ---

def play_audio():
    chunk = 1024
    wf = wave.open('misc_environment3.wav', 'rb')
    p = pyaudio.PyAudio()

    stream = p.open(
        format = p.get_format_from_width(wf.getsampwidth()),
        channels = wf.getnchannels(),
        rate = wf.getframerate(),
        output = True)

    data = wf.readframes(chunk)

    while data != '' and is_playing: # is_playing to stop playing
        stream.write(data)
        data = wf.readframes(chunk)

    stream.stop_stream()
    stream.close()
    p.terminate()

# --- functions ---

def press_button_play():
    global is_playing
    global my_thread

    if not is_playing:
        is_playing = True
        my_thread = threading.Thread(target=play_audio)
        my_thread.start()

def press_button_stop():
    global is_playing

    if is_playing:
        is_playing = False
        my_thread.join()

# --- main ---

is_playing = False
my_thread = None

root = Tk()
root.title("Compose-O-Matic")
root.geometry("400x300")

button_start = Button(root, text="PLAY", command=press_button_play)
button_start.grid()

button_start = Button(root, text="STOP", command=press_button_stop)
button_start.grid()

root.mainloop()

rawDescription: Tkinter button calling function to play wave with PyAudio -- crashes


code:
import tkinter as tk

def center(toplevel):
    toplevel.update_idletasks()
    w = toplevel.winfo_screenwidth()
    h = toplevel.winfo_screenheight()
    size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
    x = w/2 - size[0]/2
    y = h/2 - size[1]/2
    toplevel.geometry("%dx%d+%d+%d" % (size + (x, y)))

if __name__ == '__main__':
    root = tk.Tk()
    root.title("Not centered")

    win = tk.Toplevel(root)
    win.title("Centered!")
    center(win)

    root.mainloop()

rawDescription: How to center a window on the screen in Tkinter?

description: Center a window on the screen in Tkinter


code:
import numpy as np
x = np.array(['1.1', '2.2', '3.3'], dtype='|S4')
y = x.astype(np.float)

rawDescription: How to convert an array of strings to an array of floats in numpy?

description: Convert an array of strings to an array of floats in numpy


code:
words = ['run', 'windless', 'marvelous']
prons = ['rVn', 'wIndl@s', 'mArv@l@s']

for (i, word) in enumerate(words):
    if "less" in word:
        prons[i] = prons[i].replace("l@s", "lIs")

print(prons)

rawDescription: Python: Compare two lists and update value in list2 based on value in list1


code:
arr = np.random.rand(5,2)
arr
arr[2:, ]

rawDescription: Select from row 2 to end row in Python Numpy


rawDescription: Replacing Values in Pandas Columns

description: Replacing Values in Pandas Columns


code:
class ImageColumn(tables.Column):
    def render(self, value):
        return mark_safe('<img src="/media/%s" height="50" />' % escape(value))

rawDescription: Django tables2 resize image in cell

description: Django tables2 resize image in cell


code:
class K(object):
    __slots__ = ['obj']
    def __init__(self, obj, *args):
        self.obj = obj
    def __lt__(self, other):
        return mycmp(self.obj, other.obj) < 0
    def __gt__(self, other):
        return mycmp(self.obj, other.obj) > 0
    def __eq__(self, other):
        return mycmp(self.obj, other.obj) == 0
    def __le__(self, other):
        return mycmp(self.obj, other.obj) <= 0
    def __ge__(self, other):
        return mycmp(self.obj, other.obj) >= 0
    def __ne__(self, other):
        return mycmp(self.obj, other.obj) != 0
    def __hash__(self):
        raise TypeError('hash not implemented')

rawDescription: How does Python's cmp_to_key function work?


code:
from sqlalchemy import *
e = create_engine("postgresql://xxx:xxx@localhost:5432/db")
c = e.connect()
c.dialect.dbapi.extensions.register_adapter
c.dialect.dbapi.extensions.new_type

rawDescription: psycopg2 register_composite from sqlalchemy

description: Psycopg2 register_composite from sqlalchemy


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

np.random.seed(12345) # set seed for reproducibility

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]
plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker = 'o', c = data[:, 2], s = data[:, 3]*1500,
    cmap = plt.get_cmap('Spectral'))
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.text(x-.05, y+.05,
        label,
        ha = 'right', va = 'bottom')
    plt.plot([x-.05,x], [y+.05,y], 'k-')

rawDescription: mpld3 plot, annotations issues

description: Mpld3 plot, annotations issues


code:
from django.core.urlresolvers import reverse

def comment(request):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            # save, process, etc..
            # ...
            return HttpResponseRedirect(
                reverse('question', args=[form.cleaned_data.question])
            )
    else:
        form = CommentForm()
    return render(request, 'question.html', {'form': form})

rawDescription: Redirect after form validation fails

description: Redirect after form validation fails


code:
results = ['', '', '', '390', '66', ['Name', 'SerialNumber', 'Model', 'Year'], 'SW_Version', ['HD_Loc', 'HD_Model', 'HD_FW', 'HD_SerialNumber', 'Man_Yr', 'Man_Mth'], '', '', '']

flatList = [item for sublist in [[item] if not isinstance(item,list) else item for item in results] for item in sublist]

flatListWithoutBlanks = [item for item in [item for sublist in [[item] if not isinstance(item,list) else item for item in results] for item in sublist] if item != '' ]

rawDescription: Expanding list of lists

description: Expanding list of lists


code:
from itertools import zip_longest
[sum(i) for i in zip_longest(*l, fillvalue=0)]

rawDescription: Sum element by element multiple lists of different lengths


rawDescription: Resize/stretch 2d histogram in matplotlib with x-y dependent number of bins?


code:
from sqlalchemy import or_
filter(or_(User.name == 'ed', User.name == 'wendy'))

rawDescription: Using OR in SQLAlchemy

description: Using OR in SQLAlchemy


code:
import datetime

dt = datetime.datetime.strptime(datecolumn, '%m/%d/%Y').date()

rawDescription: Python output mistakes caused by csv, txt, and xls switching date formats (MM/DD/YYYY and M/D/YY)


code:
def blendShape(self, *args):

    blendshape_name = cmds.textField(self.widgets['bs'],  q=True, text=True)
    cmds.blendShape(cmds.ls(sl=True)[1], cmds.ls(sl=True)[0], frontOfChain=True, n=blendshape_name)

rawDescription: use text from textField for naming - maya python

description: Use text from textField for naming - maya python


code:
class Mixin(object):
    def __init__(self, parent=None, arg=None):
        super(Mixin, self).__init__(parent=parent)  # This will call QWidget.__init__
        self.arg = arg
        self.parent = parent

        # Setup the UI from QDesigner
        ui = Ui_widget()
        ui.setupUi(self.parent)

    def setLayout(self, layout, title):
        self.parent.setWindowTitle(title)
        self.parent.setLayout(layout)

    def doSomething(self):
        # Do something awesome.
        pass

class Widget(Mixin, QtGui.QWidget):
    def __init__(self, parent, arg):
        super(Widget, self).__init__(parent=parent, arg=arg)  # Calls Mixin.__init__

rawDescription: PySide Multiple Inheritance: Inheriting a QWidget and a Mixin


code:
from lxml import etree

tree = etree.parse("test.xml")
string = etree.tostring(tree.getroot(), pretty_print = True, xml_declaration = True, standalone = False, encoding = "UTF-16")
with open("test2.xml", "wb") as f:
    f.write(string)

rawDescription: Modify XML declaration with python

description: Modify XML declaration with python


code:
def yield_urls():
    with open("paths.txt") as f:
        paths = f.readlines() # needed in each iteration and iterates over, may be list

    with open("done.txt") as f:
        done_urls = set(f.readlines()) # needed in each iteration and looked up, set is O(1) vs O(n) in list

    # resources are cleaned up after with

    with open("urls.txt", "r") as f:
        for url in f: # iterate over list, not big list of ints generated before iteratiob, much quicker
            for subpath in paths:
                full_url = ''.join((url[7:], subpath)) # no regex means faster, maybe string formatting is quicker than join, you need to check
                # also, take care about trailing newlines in strings read from file
                if full_url not in done_urls:  # fast lookup in set
                    yield full_url  # yield instead of appending

# usage
for url in yield_urls():
    pass  # to something with url

rawDescription: Python List Append Slow?

description: Python List Append Slow


code:
s = "the dude is a cool dude"
s.find('dude')

rawDescription: How can I find the first occurrence of a sub-string in a python string?

description: Find the first occurrence of a sub-string in a python string


code: mylist.extend(x[:5] for x in otherlist)

rawDescription: What does [u'abcd', u'bcde'] mean in Python?


code:
def append(self, newitem):
    self.chromosomes.append(newitem)

rawDescription: What happens when you call `append` on a list?


code:
import os
import sys

class AddToFile(object):
    def __init__(self, filename):
        self.data_file = open(filename,'a')
    def __enter__(self):  # __enter__ and __exit__ are there to support
        return self       # `with self as blah` syntax
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.data_file.close()
    def __iter__(self):
        return self
    def append(self, s):
        self.data_file.write(s)

with AddToFile("Junk") as atf:
    atf.append("PQR")

with open("Junk") as file:
    print(file.read())  # --> PQR

rawDescription: Python append to file opened inside a class


code:
import operator
years = ['1995','1996','1997', ...]
query = reduce(operator.or_, [Q(year__startswith=year) for year in years])
results = queryset.filter(query)

rawDescription: matching substring to list of string in django

description: Matching substring to list of string in django


code:
def a():
    pass

callbacks_to_name = {a: 'a'
                     # ...
                     }

callbacks_by_name = {'a': a,
             # ...
             }

class C:
    def __init__(self, cb):
        self._callback = cb

    def __getstate__(self):
        self._callback = callbacks_to_name[self._callback]
        return self.__dict__

    def __setstate__(self, state):
        state[_callback] = callbacks_by_name[self._callback]

rawDescription: (Un)Pickle Class having Instancemethod Objects


code:
from Bio.SeqIO.QualityIO import FastqGeneralIterator
with open("prova_FiltraN_CE_filt.fastq", "rU") as handle:
    for (title, sequence, quality) in FastqGeneralIterator(handle):
        print("@%s\n%s\n+\n%s" % (title, sequence, quality))

rawDescription: FastqGeneralIterator Output

description: FastqGeneralIterator Output


code:
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
ax1.plot(df["..."])
# ...
ax2 = ax1.twinx()
ax2.plot(df["Market"])
ax2.set_ylim([0, 5])

rawDescription: How to set a secondary y-axis in Python

description: Set a secondary y-axis in Python


code:
import requests
from bs4 import BeautifulSoup

url = "https://www.rockethub.com/projects/34210-lunar-lion-the-first-ever-university-led-mission-to-the-moon/"
with requests.Session() as session:
    session.headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
    }

    # get the token
    response = session.get(url)
    soup = BeautifulSoup(response.content, "html.parser")
    token = soup.find("meta", {"name": "csrf-token"})["content"]

    # get the description
    description_url = url + "description"
    response = session.get(description_url, headers={"X-CSRF-Token": token, "X-Requested-With": "XMLHttpRequest"})

    soup = BeautifulSoup(response.content, "html.parser")
    description = soup.find('div', {'id':'description_section', 'class': 'description-section'})
    print(description.get_text(strip=True))

rawDescription: Scraping: cannot access information from web


code: max(some_function(i,j) for i in xrange(1, 1499) for j in xrange(1, i))

rawDescription: Best way to make loop range conditional?

description: Make loop range conditional


code:
from scrapy import signals, Spider
from scrapy.xlib.pydispatch import dispatcher

class ExampleSpider(Spider):
    name = "example"
    start_urls = ['http://www.example.com/']

    def __init__(self, *args, **kwargs):
        super(ExampleSpider, self).__init__(*args, **kwargs)
        # connect the function to the spider_idle signal
        dispatcher.connect(self.queue_more_requests, signals.spider_idle)

    def queue_more_requests(self, spider):
        # this function will run everytime the spider is done processing
        # all requests/items (i.e. idle)

        # get the next urls from your database/file
        urls = self.get_urls_from_somewhere()

        # if there are no longer urls to be processed, do nothing and the
        # the spider will now finally close
        if not urls:
            return

        # iterate through the urls, create a request, then send them back to
        # the crawler, this will get the spider out of its idle state
        for url in urls:
            req = self.make_requests_from_url(url)
            self.crawler.engine.crawl(req, spider)

    def parse(self, response):
        pass

rawDescription: Scrapy Memory Error (too many requests) Python 2.7


code:
[item for item in myList if item.flag]
[item for item in myList if not item.flag]

rawDescription: Python: sub list of items depending on a certain value of the items, e.g. boolean


code:
import os
os.chdir('test')
f = open('testfile', 'w')
print>>f, 'hello world'
f.close()

rawDescription: Saving to particular directory from Python 2.7


code: speed = pd.DataFrame(data=speed)

rawDescription: AttributeError: 'list' object has no attribute 'dtype'


code:
target = txt
for _ in range(depth - 1):
    target = target[0]
target[0] = target[0][s:]

rawDescription: Slice nested list at variable depth

description: Slice nested list at variable depth


code:
class test:
    pass

t = test()
'a' > 5
t > 'a'
type(t)
t > 10
type(True)
True > 100
False > 100

rawDescription: Behavior of max() with string parameters?


code:
from pytz import timezone
zone_tz = timezone(zone)
zone_aware_dt = zone_tz.localize(dt)
local_tz = timezone("America/Los_Angeles")
local_dt = local_tz.normalize(zone_aware_dt)

rawDescription: Converting an ambigious time to a correct local time with Python


code:
import numpy as np
np.arange(9).reshape(3,3)
a = np.arange(9).reshape(3,3)
a[0, :]
a[:, 0]

rawDescription: Which one is which between column slicing and row slicing?


code:
import itertools
[ list(x[1]) for x in itertools.groupby(data, lambda x: x == 0) if not x[0] ]

rawDescription: How to slice list into contiguous groups of non-zero integers in Python

description: Slice list into contiguous groups of non-zero integers in Python


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

a = pd.date_range(start="2015-06-16 ",end="2015-06-23 ", freq='H')

x = np.linspace(-3, 3, 24)
norm_pdf = stats.norm.pdf(x, 0, 1)
density = np.tile(norm_pdf, (len(a)-1)/24)

fig, ax = plt.subplots(figsize=(8,6))
ax.plot(a[1:], density)
ax.set_ylim([0, 1])

rawDescription: plot gaussian between points

description: Plot gaussian between points


code:
import arcpy
import arcpy.mapping
# get the map document
mxd = arcpy.mapping.MapDocument("CURRENT")

# get the data frame
df = arcpy.mapping.ListDataFrames(mxd,"*")[0]

# create a new layer
newlayer = arcpy.mapping.Layer(theShape)

# add the layer to the map at the bottom of the TOC in data frame 0
arcpy.mapping.AddLayer(df, newlayer,"BOTTOM")

# Refresh things
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
del mxd, df, newlayer

rawDescription: How do I add a shapefile in ArcGIS via python scripting?

description: Add a shapefile in ArcGIS via python scripting


rawDescription: I need help setting up matrices to solve using Gaussian elimination in Python


code:
test = pandas.DataFrame({"score": numpy.random.randn(10)})
test
test.set_index([index, 'name'], inplace=True)

rawDescription: Split a data frame using groupby and merge the subsets into columns


code:
import Tkinter as tk

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

        self.choices = ("one", "two", "three", "four", "five",
                        "six", "seven", "eight", "nine", "ten",
                        "eleven", "twelve", "thirteen", "fourteen",
                        "fifteen", "sixteen", "seventeen", "eighteen",
                        "nineteen", "twenty")

        self.entryVar = tk.StringVar()
        self.entry = tk.Entry(self, textvariable=self.entryVar)
        self.listbox = tk.Listbox(self)
        self.listbox.insert("end", *self.choices)

        self.entry.pack(side="top", fill="x")
        self.listbox.pack(side="top", fill="both", expand=True)

        self.entryVar.trace("w", self.show_choices)
        self.listbox.bind("<<ListboxSelect>>", self.on_listbox_select)

    def on_listbox_select(self, event):
        """Set the value based on the item that was clicked"""
        index = self.listbox.curselection()[0]
        data = self.listbox.get(index)
        self.entryVar.set(data)

    def show_choices(self, name1, name2, op):
        """Filter choices based on what was typed in the entry"""
        pattern = self.entryVar.get()
        choices = [x for x in self.choices if x.startswith(pattern)]
        self.listbox.delete(0, "end")
        self.listbox.insert("end", *choices)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Dynamic tkinter entry box

description: Dynamic tkinter entry box


code: album_urls = [album.GetHtmlLink().href for album in albums.entry]

rawDescription: How can I get an album URL from the Picasa API?

description: Get an album URL from the Picasa API


code: tuple(second for first, second in li)

rawDescription: Zip up alternating elements

description: Zip up alternating elements


code:
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/home/media/media.lawrence.com/static/"

rawDescription: Static folders structure in Django 1.4?

description: Static folders structure in Django 1.4


code:
from copy import deepcopy

dist = getDistances(deepcopy(qt), ex)

rawDescription: Function argument: original variable is modified even if passed by value


code:
import argparse
parser = argparse.ArgumentParser()

parser.add_argument("-t","--time")
parser.add_argument("-x","--expression")
parser.add_argument("-n","--name")
parser.add_argument("-f", "--file")

args = parser.parse_args()

has_file = args.file is not None
has_txn = None not in frozenset([args.time, args.expression, args.name])
assert (has_file ^ has_txn), "File or time, expression and name must be provided"

rawDescription: How to let argparse check mutually exclusive groups of arguments

description: Let argparse check mutually exclusive groups of arguments


code:
with open('2016_01_22_Reps.txt', 'r') as reps:
    Reps1dic={}
    contents = reps.read()
    pairs = contents.split(',')
    for pair in pairs:
        parts = pair.split(':')
        a = parts[0].replace('"', '').strip()
        b = parts[1].replace('"', '').strip()
        Reps1dic[a] = b
print(Reps1dic)

rawDescription: Reading text file into dic file results in incomplete dic file


code:
results = []
for item in dirlist:
  newsML = ET.parse(item)
  NewsLines = newsML.getroot()
  HeadLine = NewsLines.getiterator("HeadLine")
  results.append(HeadLine)

rawDescription: Python development - Storing results in a for loop


rawDescription: In Python, How can I remove some empty elements


code:
def Foo(Bar):
   def __setattr__(self, attr, value):
       # do something with attr and value
       super(Foo, self).__setattr__(attr, value)

rawDescription: setattr(object, name, value) vs object.__setattr__(name,value)

description: Setattr(object, name, value) vs object.__setattr__(name,value)


code:
path_dict1 = something()
path_dict2 = something_else()
save_list = [(path, md5) for path, md5 in path_dict2.viewitems()
             if md5 != path_dict1.get(path)]

rawDescription: Python check list inside other list

description: Python check list inside other list


code:
import pylab as pl
import numpy as np
import Image

path = r'\path\to\image\file.jpg'

img = Image.open(path)

img.resize((200,200))

a = np.asarray(img)

pl.imshow(a)
pl.show()

rawDescription: Scale imread matrix in python

description: Scale imread matrix in python


code:
def dict_intersection(dicts):
    result = {}
    conflicting = set()
    for d in dicts:
        for k, v in d.iteritems():
            if k not in conflicting and result.setdefault(k, v) != v:
                del result[k]
                conflicting.add(k)
    return result

rawDescription: Create a dictionary of non-contradicting items from a list of dictionaries


code:
def delete_everything(self):
    Reporter.objects.all().delete()

def drop_table(self):
    cursor = connection.cursor()
    table_name = self.model._meta.db_table
    sql = "DROP TABLE %s;" % (table_name, )
    cursor.execute(sql)

rawDescription: How to remove all of the data in a table using django

description: Remove all of the data in a table using django


code:
def find_peak_15_minutes(data_frame, column):

    max_sum = 0
    start_of_max15 = 0
    for start in data_frame[column].values:
        series_sum = data_frame[column][data_frame[column].between(start, start + 15)].count()
        if series_sum > max_sum:
            max_sum = series_sum
            start_of_max15 = start
    return (start_of_max15, max_sum)

rawDescription: How to calculate the maximum 15-min sum from a Pandas Series or Dataframe

description: Calculate the maximum 15-min sum from a Pandas Series or Dataframe


code:
from Flask import request

...

weekno = int(request.form['weekno'])

rawDescription: Linking html, python and sql

description: Linking html, python and sql


code:
import itertools

def find_expressions(digits, target):
    if not (isinstance(digits, str) or isinstance(digits, list)) or not isinstance(target, int):
        raise TypeError

    solutions = []
    operators = ('', ' + ', ' - ', ' * ', ' / ')
    for ops in itertools.product(operators, repeat=len(digits)-1):
        s = digits[0] + ''.join(op + digit for op, digit in zip(ops, digits[1:]))
        try:
            if eval(s) == target:
                solutions.append(s + ' == {}'.format(target))
        except (ZeroDivisionError, SyntaxError):
            pass
    print('\n'.join(solutions))

rawDescription: Make this function take strings of arbitrary length


rawDescription: Dictionary to Histogram

description: Dictionary to Histogram


code:
html = '

 '
soup = BeautifulSoup(html)

attrs = [li['id'] for li in soup.find_all('li')]

rawDescription: How to extract the attribute's value in python?

description: Extract the attribute's value in python


code:
import cgi

text = "LOG OUTPUT: " + sys.argv[1] + "\n"
with open(sys.argv[2], "rb") as f:
    text += f.read()

html = """\

LOG OUTPUT: {0}

{1}

""".format(unicode(str(sys.argv[1]), 'utf-8'),
                  unicode(cgi.escape(text), 'utf-8'))

rawDescription: Python - sending HTML Mail with Variables


code:
import re
string = 'Item key: 0.1234 xY ( -2.6 GMc)'
re.search(r'(?<=\( ).*?(?= GMc)', string).group()

rawDescription: Using python look behind to isolate part of string


rawDescription: Multiplying Binary Numbers in Python

description: Multiplying Binary Numbers in Python


code:
from mpl_toolkits.axes_grid.axislines import SubplotZero
from matplotlib.transforms import BlendedGenericTransform
import matplotlib.pyplot as plt
import numpy

fig = plt.figure(1)
ax = SubplotZero(fig, 111)
fig.add_subplot(ax)

ax.axhline(linewidth=2.0, color="black")
ax.axvline(linewidth=2.0, color="black")

ax.set_xticks([])
ax.set_yticks([])

ax.text(0, 1.05, 'y', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')
ax.text(1.05, 0, 'x', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')

for direction in ["xzero", "yzero"]:
    ax.axis[direction].set_axisline_style("-|>")
    ax.axis[direction].set_visible(True)

for direction in ["left", "right", "bottom", "top"]:
    ax.axis[direction].set_visible(False)

x = numpy.linspace(-0.5, 1., 100)
ax.plot(x, numpy.sin(x*numpy.pi), linewidth=2.0)

plt.show()

rawDescription: Cartesian axis labels in matplotlib

description: Cartesian axis labels in matplotlib


code:
class Track:
    def __init__(self, artist, title, album=None):
        self._artist = str(artist)
        self._title = str(title)
        self._album = album

    def __str__(self):
        return self.artist + " " + self.title + " " + self.album
    #example for artist
    @property
    def artist(self):
        return self._artist
    @artist.setter
    def artist(self, artist):
        if artist != type("string"):#ensure that value is of string type.
            raise ValueError
        else:
            self._artist = artist
    #this way you could properly make setters and getter for your attributes
    #same ofr the other stuff

Track = Track("Andy", "Me", "Self named")

rawDescription: Defining a class using objects and strings with python


code: legend( ('label1', 'label2', 'label3'), loc='upper left')

rawDescription: matplotlib legend location numbers

description: Matplotlib legend location numbers


code:
import sys
from PySide import QtGui

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

        self.output = QtGui.QTextEdit()
        self.output.setReadOnly(True)

        self.input = QtGui.QLineEdit()
        self.input.returnPressed.connect(self.addInput)
        self.input.setPlaceholderText('input here')

        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.output)
        layout.addWidget(self.input)

    def addInput(self):
        # skip empty text
        if self.input.text():
            self.output.append(self.input.text())
        # clear the QLineEdit for new input
        self.input.clear()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    w = Window()
    w.show()

    sys.exit(app.exec_())

rawDescription: Pyside keypress event for textedit

description: Pyside keypress event for textedit


code:
import elixir
elixir.options_defaults['mapper_options'] = { 'save_on_init': False }

rawDescription: How to create a non-persistent Elixir/SQLAlchemy object?

description: Create a non-persistent Elixir/SQLAlchemy object


code:
wsdl_file = os.path.abspath(args.wsdl_file)
client = Client("file://%s" % wsdl_file, transport=t, username=sip_user, password=sip_pwd, doctor=doctor)
client.set_options(location=url)

#Get the results.
user_search = client.factory.create("UserSearch")
user_search.byUserName = args.find_user
user_search.byFuzzyUserNameOrAlias = args.fuzzy
user_search.byGroup = args.group

result = client.service['UserService'].findUser(user_search)
#                      ^^^^^^^^^^^^^^^
# This was the missing bit that threw me off!

rawDescription: Is there a way to provide an external WSDL file to a Python Suds client


code:
L1.sort()
[next(j) for i, j in itertools.groupby(L1, lambda x: x.rsplit(",", 1)[0])]

rawDescription: selecting the earliest entry in a list

description: Selecting the earliest entry in a list


code:
x = np.random.randn(2, 10)
y = np.ones((4, 10))
x[0] = 0  # To make it clear which side is up, etc
y[0] = -1

plt.imshow(x, extent=(0, 10, 0, 2))
plt.imshow(y, extent=(0, 10, 2, 6))
# This is necessary, else the plot gets scaled and only shows the last array
plt.ylim(0, 6)
plt.colorbar()
plt.show()

rawDescription: Plot really big file in python (5GB) with x axis offset


code:
def deleteAtTail(self):   # remove_last would likely be a better name
    """ removes the last element of the singly linked list
    """
    temp = self.head
    while(temp.next is not None):
        temp = temp.next
    temp.next = None

rawDescription: Removing the lastNode in a singly Linked List


code:
source_path = r"\\mynetworkshare"
dest_path = r"C:\TEMP"
file_name = "\\myfile.txt"

shutil.copyfile(source_path + file_name, dest_path + file_name)

rawDescription: Network Path and Variables in Python

description: Network Path and Variables in Python


code:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import colors as c

X = np.linspace(0,1,100)
Y = np.linspace(0,1,100)
X,Y = np.meshgrid(X,Y)
Z = (X**2 + Y**2) < 1.
Z = Z.astype(int)
Z += (X**2 + Y**2) < .5

cMap = c.ListedColormap(['y','b','m'])

plt.pcolormesh(X,Y,Z,cmap=cMap)
plt.show()

rawDescription: Specifying colours when using matplotlib's pcolormesh


code: parser = etree.XMLParser(load_dtd=True, no_network=False)

rawDescription: The choice of XML/XSL lib for Python 2.6.x


rawDescription: Make new column in Panda dataframe by adding values from other columns


code:
from __future__ import print_function

bigrams = tuple(nltk.bigrams(tokens))
bi_freq = nltk.FreqDist(bigrams)

# Calculate data here
mle_probs = {k: v / tokens.count(k[0])
             for k, v in bi_freq.iteritems()}
bigram_count = sum(bi_freq.itervalues())

# Then display it, sorted
for k, v in sorted(mle_probl, key=lambda x: x[1], reverse=True):
    print(k, v)

rawDescription: how can I sort MLE Probability according to the value?

description: Sort MLE Probability according to the value


code:
config.add_route('index', '/')
config.add_route('api.users', '/api/users')
config.add_route('api.user_by_id', '/api/users/{userid}')

@view_config(route_name='index', renderer='myapp:templates/index.html', http_cache=3600*24*365)
def index_view(request):
    return {}

@view_config(route_name='api.users', request_method='POST', renderer='json')
def create_user_view(request):
    # create a user via the request.POST parameters
    return {
        'userid': user.id,
    }

@view_config(route_name='api', request_method='GET', renderer='json')
def user_info_view(request):
    userid = request.matchdict['userid']
    # lookup user
    return {
        'name': user.name,
    }

rawDescription: How should an index.html file be served from Python Pyramid for an AngularJS app?


code:
from path.to.view import Custom404
handler404 = Custom404.as_view()

rawDescription: How to specify a custom 404 view for Django using Class Based Views?

description: Specify a custom 404 view for Django using Class Based Views


code:
with open('args.txt', 'w') as fp:
   fp.write('-f\nbar')
parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
parser.add_argument('-f')
parser.parse_args(['-f', 'foo', '@args.txt'])

rawDescription: Can Python argparse take its input from a file?


code:
from gi.repository import Gio, Gtk

class App(Gtk.Application):
    def __init__(self, **props):
        super(App, self).__init__(application_id='org.gnome.example',
            flags=Gio.ApplicationFlags.FLAGS_NONE, **props)
        # Activating the LEP GEX VEN ZEA menu item will rotate through these
        # accelerator keys
        self.keys = ['L', 'G', 'V', 'Z']

    def do_activate(self):
        Gtk.Application.do_activate(self)

        actions = self.create_actions()
        self.add_action(actions['quit'])

        self.win = Gtk.ApplicationWindow()
        self.add_window(self.win)
        self.win.add_action(actions['lep'])
        self.set_accels_for_action('win.lep', ['<primary>' + self.keys[0]])
        # Ctrl-Q is automatically assigned to an app action named quit

        model = self.create_menus()
        self.set_menubar(model)

        actions['lep'].connect('activate', self.on_lep_activate)
        actions['quit'].connect('activate', lambda *args: self.win.destroy())

        self.win.show_all()

    def create_actions(self):
        return {name: Gio.SimpleAction(name=name) for name in ['lep', 'quit']}

    def create_menus(self):
        file_menu = Gio.Menu()
        file_menu.append('LEP GEX VEN ZEA', 'win.lep')
        file_menu.append('Quit', 'app.quit')
        menu = Gio.Menu()
        menu.append_submenu('File', file_menu)
        return menu

    def on_lep_activate(self, *args):
        self.keys = self.keys[1:] + self.keys[:1]
        self.set_accels_for_action('win.lep', ['<primary>' + self.keys[0]])

if __name__ == '__main__':
    App().run([])

rawDescription: Changing Gtk accelerator set by glade

description: Changing Gtk accelerator set by glade


code:
if easy_mode.lower() in {'yes','y'}:
    (...)

rawDescription: Better coding: simple way to cover all writing possibilities?


rawDescription: Test a function on all the values in a list?


code:
frameLine = Frame(...)
frameMatrix = Frame(...)
frameImage = Frame(...)
...
frameLink.pack(side="bottom", fill="x")
frameMatrix.pack(side="left", fill="both")
frameImage.pack(side="right", fill="both")

rawDescription: Python Tkinter Layout Management with Grids


code:
node_response = requests.request(method="POST", url=node_url,
               data=jetty_response.content)

rawDescription: Passing JSON data from response to request in Django


code:
levenshtein('hello', 'world')
lev_using_difflib('hello', 'world')

rawDescription: Is it possible that the SequenceMatcher in Python's difflib could provide a more efficient way to calculate Levenshtein distance?


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

# an empty variable, whre we store the returned line of plot:
line = None

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def main(i):

    # we have to make line global:
    global line

    # Actual parameters
    A0 = 10
    K0 = random.uniform(-15,-1)
    C0 = random.uniform(0,10)

    # Generate some data based on these
    tmin, tmax = 0, 0.5
    num = 20
    t = np.linspace(tmin, tmax, num)
    y = model_func(t, A0, K0, C0)
    # check if line already exists, if yes make it gray:
    if line is not None:
        line.set_color('gray')
    # plot returns a list with line instances, one for each line you draw,
    # the comma is used to unpack the one element list
    line, = ax1.plot(t,y, color='red')

def model_func(t, A, K, C):
        return A * np.exp(K * t)

ani = animation.FuncAnimation(fig, main, interval=1000)

plt.show()

rawDescription: How to change color of plotted curves when using Animations in Python MatPlotLib?

description: Change color of plotted curves when using Animations in Python MatPlotLib


code:
x = 1
y = "foo" + str(x)

rawDescription: Casting an int to a string in Python

description: Casting an int to a string in Python


rawDescription: Sending HTTP GET request using urllib

description: Sending HTTP GET request using urllib


rawDescription: Delineate twice through a dataframe in pandas


code:
import IPython
js = "IPython.CodeCell.config_defaults.highlight_modes['magic_fortran'] = {'reg':[/^%%fortran/]};"
IPython.core.display.display_javascript(js, raw=True)

rawDescription: IPython change input cell syntax highlighting logic for entire session


code:
handler = logging.handlers.TimedRotatingFileHandler("C:\\isis_ops\\logs\\Rotate_Test",'midnight',1)
handler.suffix = "%Y-%m-%d" # or anything else that strftime will allow
root_logger.addHandler(handler)

rawDescription: TimedRotatingFileHandler Changing File Name?


code:
type(A.f)
type(A.g)

rawDescription: Python: check if method is static

description: Python: check if method is static


code:
x = np.zeros((10,10))
x[3, 8] = 1
upper = np.triu(x, 1)
idx = np.argmax(upper)
row, col = np.unravel_index(idx, upper.shape)

rawDescription: Get indices of matrix from upper triangle


code:
import random

WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone", "truck" , "doom" , "mayonase" ,"flying" ,"magic" ,"mine" ,"bugle")

word = random.choice(WORDS)
correct_answer = word
max_guesses = 5

print("Word length:", len(word))
print("Attempts Available:", max_guesses)

for guesses in range(max_guesses):
    guess = input("\nEnter your guess, or a letter: ")
    if guess == correct_answer:
        print("Yay! '%s' is the correct answer.\n" % guess)
        break
    elif guess != "":
        if guess[0] in correct_answer:
            print("Yes, '%s' appears in the answer" % guess[0])
        else:
            print("No, '%s' does not appear in the answer" % guess[0])
else:
    print("\nYou ran out of maximumum tries!\n")

rawDescription: How to pull info from a string and output it?

description: Pull info from a string and output it


code:
def update_table_value(*args):
    sql = "Update TABLE SET ({}) VALUES ({}) "
    sql.format(",".join([args[0::2]]),
               ",".join([args[1::2]]))
return sql

rawDescription: Good design for modifying various combination of columns in a table


code:
# I create a class (a structure that stores data along with functions that
# operate on the data) to store information about each driver:
class Driver(object):
    def __init__(self, number, name, make, sponsor):
        self.number = number
        self.name = name
        self.make = make
        self.sponsor = sponsor

# Then I make a bunch of drivers, and store them in a list:
drivers = [
    Driver(1, "Jamie McMurray", "Chevrolet", "Bass Pro Shops/Allstate"),
    Driver(2, "Brad Keselowski", "Dodge", "Miller Lite")
]

# Then I use a comprehension (x for d in drivers) - it's kind of
# like a single-line for statement - to look at my list of drivers
# and create a dictionary so I can quickly look them up by driver number.
# It's a shorter way of writing:
#   number_index = {}  # an empty dictionary
#   for d in drivers:
#       number_index[d.number] = d
number_index = {d.number:d for d in drivers}

# Now I make a "main" function - this is a naming convention for
# "here's what I want this program to do" (the preceding stuff is
# just set-up):
def main():
    # show the welcome message
    print("\t\t\tWelcome to NASCAR Numbers!")
    print("\t\t Match Car Numbers to the Driver Names.")

    # loop forever
    # (it's not actually forever - when I want to quit, I call break to leave)
    while True:
        # prompt for input
        # get input from keyboard
        # strip off leading and trailing whitespace
        # save the result
        inp = input("\nEnter a car number (or 'exit' to quit):").strip()

        # done? leave the loop
        # .lower() makes the input lowercase, so the comparison works
        #   even if you typed in 'Exit' or 'EXIT'
        if inp.lower()=='exit':
            break

        try:
            # try to turn the input string into a number
            inp = int(inp)
        except ValueError:
            # int() didn't like the input string
            print("That wasn't a number!")

        try:
            # look up a driver by number (might fail)
            # then print a message about the driver
            print("Car #{} is driven by {}".format(inp, number_index[inp].name))
        except KeyError:
            # number[inp] doesn't exist
            print("I don't know any car #{}".format(inp))

# if this script is called directly by Python, run the main() function
# (if it is loaded as a module by another Python script, don't)
if __name__=="__main__":
    main()

rawDescription: Printing a variable based on an input + another variable


code:
by_color = {}
for obj in color_values:
    by_color.setdefault(obj['color'], []).append(obj['score'])
color_values = [{'score': float(sum(value)) / len(value), 'color': key}
                for key, value in by_color.items()]

rawDescription: Averaging scores of same type in an array in Python


code:
import pytz, datetime

timeUTC = datetime.datetime(2013, 5, 23, 19, 27, 50, 0)
timezoneLocal = pytz.timezone('Europe/Vilnius')
utc = pytz.utc
timeLocal = utc.localize(timeUTC).astimezone(timezoneLocal)
print(timeLocal)
# 2013-05-23 22:27:50+03:00

rawDescription: How to `strftime` having timezone adjusted?

description: `strftime` having timezone adjusted


code:
driver = webdriver.Firefox()
driver.get("https://twitter.com")
cookies = pickle.load(open("/home/ro/A_Python_Scripts/twitter/twitter_loggins.pkl", "rb"))
for cookie in cookies:
    #del cookie['domain'] # uncomment this if you get different domain error
    driver.add_cookie(cookie)

driver.get("https://twitter.com") # Reload & you will be logged in automatically

rawDescription: My pickled cookies won't work in selenium - python?


code:
def values(self):
    for v in self.items:
        while not self.flag:
            yield None
        yield v

rawDescription: Writing a 'non-readable' list

description: Writing a 'non-readable' list


code:
from itertools import groupby

filter(lambda x: len(x)>1, [list(g) for i,g in groupby(input, key=lambda x: x[0])])
[[('a', 1), ('a', 10)], [('c', 31), ('c', 45)]]

rawDescription: Pythonic way to generate a list of list

description: Pythonic way to generate a list of list


code:
with open(EMCMD_INCORRECT_PARAMS, 'r') as fd_usage:
    usageLines = fd_usage.read().replace('\n', fd_usage.newline)

rawDescription: Compare output from check_output() with text in file


code:
import re
re.match('\w+', 'bob!')
re.match('\w+', "there's")

rawDescription: Python Regex - not catching non-alphanumerics


rawDescription: dot products of rows and columns

description: Dot products of rows and columns


code:
zip(*[iter(range(10))]*3)
[range(n,n+3) for n in range(1,10,3)]
it = iter(range(10))
[list(islice(it,3)) for _ in range(3)]

rawDescription: Python, making a two dimensional list

description: Python, making a two dimensional list


code: 'ac milan'.title()

rawDescription: Python First Letter of a word Upper CASE


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

N = 100
width = 20
height = 20
Z = np.random.random((width, height))

G = np.zeros((width, height, 3))

# Here we set the RGB for each pixel
G[Z > 0.5] = [1, 1, 1]
G[Z < 0.5] = [0, 0, 0]

fig, ax = plt.subplots(figsize=(2, 5))
ax.imshow(G, interpolation='nearest')
ax.set_aspect('auto')
plt.show()

rawDescription: Is it possible to change the width of an imshow matplotlib visualization?


code: (array != 0).sum()

rawDescription: Custom count_nonzero function for numpy versions below 1.6


code:
mapper = dict(a = 'ac', b = 'bd', c = 'ac', d = 'bd')
df['C'] = [ mapper[x] for x in df['A'] ]
df

rawDescription: make a new variable from existing data in pandas dataframe

description: Make a new variable from existing data in pandas dataframe


code: wanted = d[d['id'] == id]

rawDescription: Select specific rows from a groupby DataFrame


code:
class sale_report(osv.osv):
    _inherit = 'sale.report'

    date_order_month = fields.Char(string='Date Month')
    date_order_day = fields.Char(string='Date Day')

    def _select(self):
        select_str = """
             SELECT min(l.id) as id,
                    l.product_id as product_id,
                    t.uom_id as product_uom,
                    sum(l.product_uom_qty / u.factor * u2.factor) as product_uom_qty,
                    sum(l.product_uom_qty * l.price_unit * (100.0-l.discount) / 100.0) as price_total,
                    count(*) as nbr,
                    s.date_order as date,
                    date_part('month', s.date_order) as date_order_month,
                    date_part('day', s.date_order) as date_order_day,
                    s.date_confirm as date_confirm,
                    s.partner_id as partner_id,
                    s.user_id as user_id,
                    s.company_id as company_id,
                    extract(epoch from avg(date_trunc('day',s.date_confirm)-date_trunc('day',s.create_date)))/(24*60*60)::decimal(16,2) as delay,
                    s.state,
                    t.categ_id as categ_id,
                    s.pricelist_id as pricelist_id,
                    s.project_id as analytic_account_id,
                    s.section_id as section_id
        """
        return select_str

rawDescription: Odoo , Domain, filter date and month

description: Odoo , Domain, filter date and month


code:
#!/usr/bin/env python

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

app = QApplication(sys.argv)

web = QWebView()
web.load(QUrl("http://www.stackoverflow.com"))
web.show()

sys.exit(app.exec_())

rawDescription: How to make a simple cross-platform webbrowser with Python?

description: Make a simple cross-platform webbrowser with Python


code:
def copytotemp(logfile, fromline, toline):
    with open(logfile) as origfile:
        with open("templog.log", "w") as tempfile:
            for num, line in enumerate(origfile, 1):
                if num >= fromline and num <= toline:
                    tempfile.write(line)

rawDescription: python: copy specific lines from one file to anther file

description: Python: copy specific lines from one file to anther file


rawDescription: how to represent a sorted dictionary?

description: Represent a sorted dictionary


code:
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()

G.add_node("ROOT")

for i in xrange(5):
    G.add_node("Child_%i" % i)
    G.add_node("Grandchild_%i" % i)
    G.add_node("Greatgrandchild_%i" % i)

    G.add_edge("ROOT", "Child_%i" % i)
    G.add_edge("Child_%i" % i, "Grandchild_%i" % i)
    G.add_edge("Grandchild_%i" % i, "Greatgrandchild_%i" % i)

# write dot file to use with graphviz
# run "dot -Tpng test.dot >test.png"
nx.write_dot(G,'test.dot')

# same layout using matplotlib with no labels
plt.title("draw_networkx")
pos=nx.graphviz_layout(G,prog='dot')
nx.draw(G,pos,with_labels=False,arrows=False)
plt.savefig('nx_test.png')

rawDescription: Is there a way to guarantee hierarchical output from NetworkX?


code:
job = Job(field1=value1, field2=value2)
job.save()

rawDescription: how to save an instance of a Django model to my database

description: Save an instance of a Django model to my database


code:
import csv
with open('test.csv') as f:
    a = [{k: int(v) for k, v in row.items()}
         for row in csv.DictReader(f, skipinitialspace=True)]
a

rawDescription: convert csv file to list of dictionaries

description: Convert csv file to list of dictionaries


code:
phones = []
for k, v in PHONE_CHOICES:
    try:
        current = ClientPhone.objects.filter(client=clientKEY, phone_type=k)
        if current.deleted is None:
            phones.append(current.latest('id'))
    except ClientPhone.DoesNotExist:
        pass

rawDescription: Django query filter, return object if attr delete is false (i.e if it hasn't been deleted)


code:
form=TestPostForm(data=request.POST)
if form.is_valid():
  object=form.save(commit=False)
  object.ip_address=request.META['REMOTE_ADDR']
  object.save()

rawDescription: How do add multiple fields to a Form when trying to validate data?


code: return 0.5 * np.nansum(((array1 - array2) ** 2) / (array1 + array2))

rawDescription: Numpy conditional arithmetic operations on two arrays


rawDescription: What is the most efficient and readable way to create a list of lists of integer ranges in Python?


code:
with open('words.txt', "r") as word_list:
    words = word_list.read().split(' ')

rawDescription: How can I add each word in a .txt file to a list in Python?

description: Add each word in a .txt file to a list in Python


code: os.system('setx PATH "%PATH%;C:\Python27" /M')

rawDescription: How to set Environment system variable for python through COMMAND Prompt after installing python?

description: Set Environment system variable for python through COMMAND Prompt after installing python


code: "Hello there. My name is Fr.ed. I am 25.5 years old.".split(". ")

rawDescription: Python split string with multiple-character delimiter


rawDescription: How to pad with n characters in Python

description: Pad with n characters in Python


code:
for tarifa in tarifas:
    tot = {'tarifa': tarifa}
    data_json['datos_TOT'].append(tot)

    teu = {'tarifa': tarifa}
    values = []
    for j, termino in enumerate(terminos):
        value = {'termino': termino, 'periodo': "{0}-{1}".format(j,j+1)}
        values.append(value)
    teu['values'] = values
    data_json['datos_TEU'].append(teu)

rawDescription: Nested "for" in Django view won´t work

description: Nested "for" in Django view won´t work


code:
import sys, os
import matplotlib.pyplot as plt

path = sys.path[0]
sizes = [(12,3,), (4,3,)]
x =  range(20)

for i, size in enumerate(sizes):
    fig = plt.figure(figsize = size, dpi = 80, facecolor='white',edgecolor=None,linewidth=0.0, frameon=True, subplotpars=None)
    ax = fig.add_subplot(111)
    ax.plot(x)
    plt.ylabel ('Some label')
    plt.tight_layout()

    make_invisible = True
    if (make_invisible):
        xticks = ax.xaxis.get_major_ticks()
        xticks[0].label1.set_visible(False)
        xticks[-1].label1.set_visible(False)

plt.show()

rawDescription: Matplotlib - hiding specific ticks on x-axis


rawDescription: Wrong exponential fit with `scipy.optimize.curve_fit`


code:
rawfiles = glob.glob(path + "/*.csv")
tempframe = []
for file_ in rawfiles:
    df = pd.read_csv(file_, header=0)
    df["ID"] = file_[:-4]
    tempframe.append(df)

rawDescription: python / pandas copy filename

description: Python / pandas copy filename


code:
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw

img=Image.open("pathToImage")

font = ImageFont.truetype("pathToFont",10)

draw = ImageDraw.Draw(img)
draw.text((0, 0),"This is a test",(255,255,0),font=font)
draw = ImageDraw.Draw(img)
draw = ImageDraw.Draw(img)
img.save("a_test.png")

rawDescription: Adding a text to an image in Python

description: Adding a text to an image in Python


code:
def wait_prompt(device, msg):
        device.write("\n\n")
        device.flush()
        output = device.readline()

        if msg in output:
                return 1
        return 0

def initialize_router(device):

        print ("Router connected on port " + port[0])

        while wait_prompt(device, "[yes/no]:") == 0:
                time.sleep(1)

        device.write("no\n")
        device.flush()

        while wait_prompt(device, "Line protocol on Interface Vlan1, changed state to up") == 0:
                time.sleep(1)

        time.sleep(2)
        device.write("\n")
        device.flush()

rawDescription: Python Compare strings

description: Python Compare strings


code: map(lambda f: f(3), [lambda x: x**2,lambda x: x**3])

rawDescription: Python Map() reverse

description: Python Map() reverse


code:
from __future__ import print_function

import sys
import readline
from os import environ

class MyCompleter(object):  # Custom completer

    def __init__(self, options):
        self.options = sorted(options)

    def complete(self, text, state):
        if state == 0:  # on first trigger, build possible matches
            if not text:
                self.matches = self.options[:]
            else:
                self.matches = [s for s in self.options
                                if s and s.startswith(text)]

        # return match indexed by state
        try:
            return self.matches[state]
        except IndexError:
            return None

    def display_matches(self, substitution, matches, longest_match_length):
        line_buffer = readline.get_line_buffer()
        columns = environ.get("COLUMNS", 80)

        print()

        tpl = "{:<" + str(int(max(map(len, matches)) * 1.2)) + "}"

        buffer = ""
        for match in matches:
            match = tpl.format(match[len(substitution):])
            if len(buffer + match) > columns:
                print(buffer)
                buffer = ""
            buffer += match

        if buffer:
            print(buffer)

        print("> ", end="")
        print(line_buffer, end="")
        sys.stdout.flush()

dates = [
    '10/10/2013 13:03:51',
    '10/10/2013 13:54:32',
    '10/10/2013 18:48:48',
    '10/10/2013 19:13:00',
    '10/13/2013 12:58:17',
    '10/13/2013 13:38:15',
    '10/13/2013 16:48:58',
    '10/13/2013 17:23:59',
    '10/13/2013 20:09:56',
    '10/13/2013 21:54:14',
    '10/13/2013 21:57:43',
    '10/13/2013 22:47:40',
    '10/14/2013 13:32:53',
    '10/14/2013 21:14:51',
    '10/15/2013 10:18:23'
    ]

dates = [x.split(' ')[0] for x in dates]

completer = MyCompleter(list(set(dates)))
readline.set_completer_delims(' \t\n;')
readline.set_completer(completer.complete)
readline.parse_and_bind('tab: complete')
readline.set_completion_display_matches_hook(completer.display_matches)
print('Enter a date in m/d/yy format\n\t')
date = input("> ")

rawDescription: Autocomplete with readline in python3

description: Autocomplete with readline in python3


code:
def drop(local_store):
    global store
    backup(local_store)
    del store

store = {}
drop(store)

rawDescription: Python 2.7 - How to delete a dictionary using a function?


code:
import win32com.client
oSiebelApp = win32com.client.Dispatch("SiebelDataControl.SiebelDataControl.1")
oSiebelApp.Login("Connection String")

rawDescription: Siebel COM interface - Python

description: Siebel COM interface - Python


code:
p = re.compile('\{\{*.*?\}\}', re.DOTALL)
nonBracketedString = p.sub('', bracketedString)

rawDescription: How to remove blocks surrounded by curly brackets via python

description: Remove blocks surrounded by curly brackets via python


code:
def magic_default(node):
    return magic(node.l) + magic(node.r)

MAGIC_SPELLS = {
    'AR_OP': ar_op_magic,
    'PRE_OP': pre_op_magic,
}

def magic(node):
    if node:
        func = MAGIC_SPELLS.get(node.text, magic_default)
        return func(node)
    return ""

rawDescription: Local const in recursion call

description: Local const in recursion call


code:
def smallest_diff_key(A, B):
    """return the smallest key adiff in A such that A[adiff] != B[bdiff]"""
    diff_keys = [k for k in A if A.get(k) != B.get(k)]
    return min(diff_keys)

def dict_cmp(A, B):
    if len(A) != len(B):
        return cmp(len(A), len(B))
    adiff = smallest_diff_key(A, B)
    bdiff = smallest_diff_key(B, A)
    if adiff != bdiff:
        return cmp(adiff, bdiff)
    return cmp(A[adiff], b[bdiff])

rawDescription: Is there a description of how __cmp__ works for dict objects in Python 2?


code:
import curses
stdscr = curses.initscr()
curses.cbreak()
stdscr.keypad(1)

stdscr.addstr(0,10,"Hit 'q' to quit")
stdscr.refresh()

key = ''
while key != ord('q'):
    key = stdscr.getch()
    stdscr.addch(20,25,key)
    stdscr.refresh()
    if key == curses.KEY_UP:
        stdscr.addstr(2, 20, "Up")
    elif key == curses.KEY_DOWN:
        stdscr.addstr(3, 20, "Down")

curses.endwin()

rawDescription: How to accept keypress in command line python?

description: Accept keypress in command line python


code:
def func(t, a0, a1, a2, T, tau1, tau2):
    return np.where(
        t < T,
        a0 + a1 * np.exp(-t/tau1) + a2 * np.exp(-t/tau2),
        a0 + a1 * np.exp(-T/tau1) * (1 - t/tau1 + T/tau1) + a2 * np.exp(-T/tau2) * (1 - t/tau2 + T/tau2) )

rawDescription: scipy optimize.curve_fit cannot fit a function whose return value depends on a conditional

description: Scipy optimize.curve_fit cannot fit a function whose return value depends on a conditional


code:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

binary = FirefoxBinary('path/to/binary')
profile = webdriver.FirefoxProfile()
profile.add_extension('path/to/xpi') #XPI needs to be on disk and not downloaded from AMO
profile.set_preference('general.useragent.local','<enter your value')

driver = webdriver.Firefox(firefox_binary=binary, firefox_profile=profile)
# Carry on with what you want

rawDescription: Selenium change firefox browser language python mac


code: command = re.search("(" + re.escape(MyDir) + ")", body).group(1)

rawDescription: variable regex python

description: Variable regex python


code:
str = "def Hello(self,event):"
str.split(' ')[1].split('(')[0]

rawDescription: Split string from one point to another (different delimiters)


code:
class BAdmin(admin.TabularInline):
    ...

    def get_queryset(self, request):
        qs = super(BAdmin, self).get_queryset(request)
        return qs.filter(user=request.user)

rawDescription: how to limit the queryset of an inline model in django admin

description: Limit the queryset of an inline model in django admin


code:
tview = gtk.TextView()
tview.set_property('editable', False)

# Insert text at the end on the textview.
buffer = tview.get_buffer()
buffer.insert(buffer.get_end_iter(), 'This text goes at the end of the existing text')

rawDescription: pygtk read-only gtk.TextView (make it ignore mouse clicks)

description: Pygtk read-only gtk.TextView (make it ignore mouse clicks)


code:
# prepare command
command = 'if [ -w {filename} ]; then echo True; else echo False; fi;'
# add filename
command = command.format(filename=temp_path)
# execute command
stdin, stdout, stderr = ssh.exec_command(command)
# read the result from stdout and remove the trailing newline character
result = stdout.readline().rstrip()
print(result)

rawDescription: How to check if a remote file is writable using python Paramiko (SSHClient)?

description: Check if a remote file is writable using python Paramiko (SSHClient)


code:
a=range(40)
b=range(30)
x=np.zeros((2,max(len(a),len(b))))
for i,j in enumerate([a,b]): x[i][:len(j)]=j
x

rawDescription: Create an ndarray from arrays of different lengths


code:
def app(environ, start_response):
    output = "
Räksmörgås
".encode('utf-8')
    start_response('200 OK', [
        ('Content-Type', 'text/html; charset=utf-8'),
        ('Content-Length', str(len(output)))
    ])

    return [output]

rawDescription: How do I encode WSGI output in UTF-8?

description: Encode WSGI output in UTF-8


code:
import sys
from PyQt4 import QtGui

class QCustomTabWidget (QtGui.QTabWidget):
    def __init__ (self, parent = None):
        super(QCustomTabWidget, self).__init__(parent)
        self.setTabsClosable(True)
        self.tabCloseRequested.connect(self.closeTab)
        for i in range(1, 10):
            self.addTab(QtGui.QWidget(), 'Tab %d' % i)

    def closeTab (self, currentIndex):
        currentQWidget = self.widget(currentIndex)
        currentQWidget.deleteLater()
        self.removeTab(currentIndex)

myQApplication = QtGui.QApplication([])
myQCustomTabWidget = QCustomTabWidget()
myQCustomTabWidget.show()
sys.exit(myQApplication.exec_())

rawDescription: Pyqt close unselected tab

description: Pyqt close unselected tab


code:
class NotchianProcessProtocol(protocol.ProcessProtocol):
    ...
    def listPlayers(self):
        self.transport.write("list")
        self._waiting.append(Deferred())
        return self._waiting[-1]

    def outReceived(self, bytes):
        outbuffer = self.outbuffer + bytes
        lines, leftover = parseLines(outbuffer)
        self.outbuffer = leftover

        for line in lines:
            if line.startswith('[INFO] Connected players: '):
                self._waiting.pop(0).callback(line)

rawDescription: Twisted Python + spawnProcess. Getting output from a command


code:
import urllib.request
import random
import os

def download_img(url, path):
    name = random.randrange(1, 100)
    full_name = str(name) + ".png"
    response = urllib.request.urlopen(url)
    data = response.read()
    f = open(os.path.join(path , full_name), 'wb')
    f.write(data)
    f.close()

download_img('http://www.mtv.com/crop-images/2013/11/05/the_killers_elle_exclusive_williams_hirakawa.jpg', '/tmp')

rawDescription: Python how to import an image in a certain location?


code:
class CommandSource(object):

    def listCommands(self, *args, **kwargs):
        commands = []
        for command in dir(self.__class__):
            func = getattr(self, command, None)
            if func == None or getattr(func, 'command', False) == False:
                continue
            for validator in func.validators:
                if not validator(self, *args, **kwargs):
                    break
            else:
                commands.append(command)
        return commands

rawDescription: How to handle 'self' argument with Python decorators

description: Handle 'self' argument with Python decorators


code:
d = {('Hello','my'): 1, ('Hello','world'): 2, ('my','name'): 3, ('my','house'): 1}
d_max = {}
for (first, second), count in d.items():
    if count >= d_max.get(first, (None, 0))[1]:
        d_max[first] = (second, count)

d_max
output = [(first, second) for (first, (second, count)) in d_max.items()]
output

rawDescription: Make a list with the most frequent tuple of a dictionary acording the first element


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

names = ['A', 'B', 'C', 'D', 'E', 'F']
values = [0, 1, 2, 3, 1, 2]
n = len(names)
gradient = np.linspace(0, 1, 100).reshape(1, -1)
plt.imshow(gradient , extent=[-0.25, 3.25, -1, n], aspect='auto', cmap='RdYlGn_r')
sns.stripplot(x=values, y=names, color='b', size=12, edgecolor='b')
plt.hlines(np.arange(0, n), -0.25, 3.25, linestyles='--', linewidth=1)
plt.grid(False)
plt.xlim(-0.25, 3.25)
plt.xticks([0, 1, 2, 3])

rawDescription: DotPlot with Gradient Background in Python?


rawDescription: Python - generate case insensitive REGEXP like string


code:
def __iter__(self):
    for k in self.keys():
        yield k

rawDescription: Iterating through a dictionary of a class object without mixin - python


rawDescription: Ignore/skip a value in a numpy array?

description: Ignore/skip a value in a numpy array


code:
import logging
...
def on_response(self, response):
    logging.debug(response)
    self.write(response.body)

rawDescription: Tornado: Make Blocking HTTP Request in Async Handler


code:
def sumD(num):
    if num == 0: return 0
    return (num % 10) + sumD(num // 10)

rawDescription: How can I add integers recursively in Python?

description: Add integers recursively in Python


code:
temp1 = ['a' , 'b' , 'c']
temp2 = ['d' , 'e' ,'' ]
temp3 = ['f']
temp4 = ['g']

templist = [i+j+k+l for i in temp1 for j in temp2 for k in temp3 for l in temp4]
# Result - ['adfg', 'aefg', 'afg', 'bdfg', 'befg', 'bfg', 'cdfg', 'cefg', 'cfg']

rawDescription: How to join array more than one array in python

description: Join array more than one array in python


code:
from urlparse import urlparse, parse_qs
parse_qs(urlparse('/test?testing=test&greeting=smile').query)

rawDescription: Python http get parameters

description: Python http get parameters


code:
import collections
vals = collections.OrderedDict([("Brazil", 55), ("USA", 12), ("Greece", 32), ("India", 56)])
with open('result.txt', 'w') as fo:
    for country,score in vals.iteritems():
        fo.write("{} {}".format(country, score))

rawDescription: How to shorten my code to write a simple text file?

description: Shorten my code to write a simple text file


code:
from bs4 import BeautifulSoup
from urllib.request import urlopen

u = urlopen("http://www.nhl.com/ice/teamstats.htm")
soup = BeautifulSoup(u)
u.close()

for table in soup.find_all('table', class_='data stats'):
    row = table.find('tr')
    header = []
    for cell in row.find_all('th')[1:]:
        name = cell.string.strip()
        header.append(name)
    for row in table.find_all('tr')[1:]:
        for name, cell in zip(header, row.find_all('td')[1:]):
            value = cell.string.strip()
            print('{}: {}'.format(name, value), end=', ')
        print()

rawDescription: Associating multiple teams with multiple headers/values:


code:
import pygame, sys

SCREEN_SIZE = (600, 400)
BG_COLOR = (0, 0, 0)
LINE_COLOR = (0, 255, 0)
pygame.init()
clock = pygame.time.Clock() # to keep the framerate down

image1 = pygame.Surface((50, 50))
image2 = pygame.Surface((50, 50))
image1.set_colorkey((0, 0, 0)) # The default background color is black
image2.set_colorkey((0, 0, 0)) # and I want drawings with transparency

screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
screen.fill(BG_COLOR)

# Draw to two different images off-screen
pygame.draw.line(image1, LINE_COLOR, (0, 0), (49, 49))
pygame.draw.line(image2, LINE_COLOR, (49, 0), (0, 49))

# Optimize the images after they're drawn
image1.convert()
image2.convert()

# Get the area in the middle of the visible screen where our images would fit
draw_area = image1.get_rect().move(SCREEN_SIZE[0] / 2 - 25,
                                   SCREEN_SIZE[1] / 2 - 25)

# Draw our two off-screen images to the visible screen
screen.blit(image1, draw_area)
screen.blit(image2, draw_area)

# Display changes to the visible screen
pygame.display.flip()

# Keep the window from closing as soon as it's finished drawing
# Close the window gracefully upon hitting the close button
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)
    clock.tick(30)

rawDescription: How to draw to an off-screen display in PyGame

description: Draw to an off-screen display in PyGame


code:
firstFS = FS.FloatSpin(self, -1, min_val=0, max_val=None, increment=1, value=1, agwStyle=FS.FS_RIGHT)
firstFS.SetName('firstFS')  # for example
secondFS = FS.FloatSpin(self, -1, min_val=0, max_val=None, increment=1, value=1, agwStyle=FS.FS_RIGHT)
secondFS.SetName('secondFS')  # for example

self.Bind(FS.EVT_FLOATSPIN, self.OnFloatSpin)

def OnFloatSpin(self, event):
    floatspin = event.GetEventObject()
    floatspinID = event.GetId()  # grab the widgets id that is firing the event
    '''OR'''
    floatspinName = event.GetEventObject().GetName()  # grab the widget name

rawDescription: How to tell which FloatSpin is firing the EVT_FLOATSPIN event in wxPython?

description: Tell which FloatSpin is firing the EVT_FLOATSPIN event in wxPython


code:
import tkinter as tk
import time

class ButtonTimer:
    def __init__(self, root):
        self.master = root
        self.button = tk.Button(self.master, text="press me")  # Notice I haven't assigned the button a command - we're going to bind mouse events instead of using the built in command callback.
        self.button.bind('<ButtonPress>', self.press)       # call 'press' method when the button is pressed
        self.button.bind('<ButtonRelease>', self.release)   # call 'release' method when the button is released
        self.label = tk.Label(self.master)
        self.startTime = time.time()
        self.endTime = self.startTime

        self.button.grid(row=1, column=1)
        self.label.grid(row=2, column=1)

    def press(self, *args):
        self.startTime = time.time()

    def release(self, *args):
        self.endTime = time.time()
        self.label.config(text="Time pressed: "+str(round(self.endTime - self.startTime, 2))+" seconds")

root = tk.Tk()
b = ButtonTimer(root)
root.mainloop()

rawDescription: Testing a Tkinter Button object with an if statement


code:
s = '1x2X3, 10x10x12, 25X35X4 G, XXX expert, 3x world champ, great x2'
import re
re.sub(r'(?<=\d)x(?=\d)', ' ', s, flags=re.I)

rawDescription: How can I recognize the x in the string "x-ring closing10.00x10.00mm" and replace it with a space

description: Recognize the x in the string "x-ring closing10.00x10.00mm" and replace it with a space


rawDescription: How can i append an item more than once at the same time in Python?

description: Append an item more than once at the same time in Python


code:
if member.filename[-1] == '/':
    if not os.path.isdir(targetpath):
        os.mkdir(targetpath)
    return targetpath

with self.open(member, pwd=pwd) as source, \
     file(targetpath, "wb") as target:
    shutil.copyfileobj(source, target)

return targetpath

rawDescription: Get Local File name after ZipFile extract()


code:
# get some data
import pandas.io.data as web
import datetime
start = datetime.datetime(2015, 1, 1)
end = datetime.datetime(2015, 4, 30)
df=web.DataReader("F", 'yahoo', start, end)

# a bit of munging - better column name - Day as integer
df = df.rename(columns={'Adj Close':'AdjClose'})
dayZero = df.index[0]
df['Day'] = (df.index - dayZero).days

# fit a linear regression
import statsmodels.formula.api as sm
fit = sm.ols(formula="AdjClose ~ Day", data=df).fit()
print(fit.summary())
predict = fit.predict(df)
df['fitted'] = predict

# plot
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8,4))
ax.scatter(df.index, df.AdjClose)
ax.plot(df.index, df.fitted, 'r')
ax.set_ylabel('$')
fig.suptitle('Yahoo')

plt.show()

rawDescription: timeseries fitted values from trend python

description: Timeseries fitted values from trend python


code:
import platform
platform.system()

rawDescription: Reliably detect Windows in Python

description: Reliably detect Windows in Python


code:
for g, p in zip(g_data, p_data):
    print(g.text, p.text)

rawDescription: Combine two texts into one in Python

description: Combine two texts into one in Python


code: sorted(range(1, len(a) + 1), key=lambda i: a[i-1], reverse=True)

rawDescription: Sort list values to get a new order of its index, Python way


code:
# griddata expects an ndarray for the interpolant coordinates
interpolants = numpy.array([xnew, ynew])

# defaults to linear interpolation
znew = scipy.interpolate.griddata((x, y), z, interpolants)

rawDescription: 2d interpolation in python with random spot


code:
if item in my_canvas.find_all():
   my_canvas.delete(item)
else:
   print("Item not on canvas")

rawDescription: Check if widget exist(Tkinter)

description: Check if widget exist(Tkinter)


code:
class EventForm(ModelForm):
    account = ModelChoiceField(queryset=Account.objects.all())
    background = CharField(widget=Textarea(attrs={'class':'form-textarea resizeoff auto-resize js_auto_resize  default'}), required=False)
    opportunities = ModelMultipleChoiceField(queryset=Opportinuty.objects.all(), label='SalesForce ID', required=False)

rawDescription: Accessing a m2m field values in django templates using forms


code: movie_data.drop_duplicates(subset='movie_id').sort('rating', ascending = False).head(5)

rawDescription: Top 5 movies with most number of ratings


code:
html_theme_options = {
    'page_width': 'auto',
}

rawDescription: How can the line wrapping width on Sphinx with alabaster be increased?


code:
from datetime import datetime, timedelta
import pandas as pd
from dateutil import parser

df = pd.read_csv('acc.csv')
tidx = pd.to_datetime(df['timestamp'].values)
past_24 = (pd.datetime.now() - tidx).total_seconds() > 60 * 60 * 24
user = df[df['is_valid'] & past_24]

rawDescription: Select rows in pandas matching time condition


code: [k for k, v in menu.iteritems() if 'chips' in v]

rawDescription: Is there a way of checking for membership from the values of a dictionary? Once confirmed, can we do other things?


code:
from Tkinter import *

class LabeledEntry(Frame):
    def __init__(self, parent, *args, **kargs):
        text = kargs.pop("text")
        Frame.__init__(self, parent)
        Label(self, text=text, justify=LEFT).grid(sticky = W, column=0,row=0)
        Entry(self, *args, **kargs).grid(sticky = E, column=1, row=0)

class User_Input:
    def __init__(self, parent):
        fields = ['Text Label 1', 'This is the text Label 2']
        GUIFrame =Frame(parent)
        GUIFrame.pack(expand=True, anchor=NW)
        parent.minsize(width=350, height=325)
        field_index = 1
        for field in fields:
            self.field = LabeledEntry(GUIFrame, text=field)
            self.field.grid(column=0, row=field_index)
            self.field.grid_columnconfigure(index = 0, minsize = 150)
            field_index += 1
        self.Button2 = Button(parent, text='exit', command= parent.quit)
        self.Button2.place(x=25, y=300)

root = Tk()

MainFrame =User_Input(root)
root.mainloop()

rawDescription: How to line left justify label and entry boxes in Tkinter grid

description: Line left justify label and entry boxes in Tkinter grid


code: blocks = ["".join(adpcm_packets[i:i+13]) for i in range(0, len(adpcm_packets), 13)]

rawDescription: Joining elements in a list to a new list in Python


code:
x = np.array([0, 1, 2])
y = np.array([1, 2, 0])
np.maximum(x, y)

rawDescription: Distributive "if" with numpy arrays

description: Distributive "if" with numpy arrays


code:
import numpy as np
x = np.array(x)
y = np.array(y)
cond = (x>=10) & (x<=20)
xFit = x[ cond ]
yFit = y[ cond ]

rawDescription: matlibplot polyfit to subset of x values

description: Matlibplot polyfit to subset of x values


code:
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import Column
from sqlalchemy.dialects.mysql import MEDIUMINT, TINYINT

db = SQLAlchemy(app)

class User(db.Model):
    id = Column(MEDIUMINT(unsigned=True), primary_key=True)

rawDescription: Flask-SQLAlchemy declarative and MySQL specific data types


code:
lines = []
stopword = ""
while True:
    line = input()
    if line.strip() == stopword:
        break
    lines.append(line) # Add to the list of lines
for line in lines[::-1]: # [::-1] inverts the list
    print(line)

rawDescription: Vertically flip ASCII art with Python

description: Vertically flip ASCII art with Python


code:
from Tkinter import *

root = Tk()
v = IntVar()

group1 = []
group2 = []

group1.append( Entry(root) )
group1[0].insert(0, "Entry1")

group1.append( Button(root, text='Button1') )

group2.append( Entry(root) )
group2[0].insert(0, "Entry2")
group2.append( Button(root, text='Button2') )

def show1():

    for w in group2:
        w.pack_forget()

    for w in group1:
        w.pack()

def show2():
    for w in group1:
        w.pack_forget()

    for w in group2:
        w.pack()

Radiobutton(root,
            text="Single Component",
            padx= 20,
            variable=v,
            value=1,
            command=show1).pack(anchor=W)
Radiobutton(root,
            text="Complete Component",
            padx = 20,
            variable=v,
            value=2,
            command=show2).pack(anchor=W)

mainloop()

rawDescription: How to Kill/Disable the Command/Function Launched when We Click the RadioButton in Python-Tkinter?


code:
def merge_subs(lst_of_lsts):
    res = []
    for row in lst_of_lsts:
        for i, resrow in enumerate(res):
            if row[0]==resrow[0]:
                res[i] += row[1:]
                break
        else:
            res.append(row)
    return res

rawDescription: Merge List of lists where sublists have common elements


code:
label1.grid(row = 1, column = 1)
label2.grid(row = 1, column = 2)

rawDescription: Creating a GUI with Tkinter of Python

description: Creating a GUI with Tkinter of Python


code:
def traverse(tree_of_lists):
    for item in tree_of_lists:
        if isinstance(item, list):
            for x in traverse(item):
                yield x
        else:
            yield item

rawDescription: Traverse Non-Binary Tree

description: Traverse Non-Binary Tree


code:
data=io.StringIO(csv)
df = pd.read_csv(data, sep=',', skip_blank_lines=True, quoting=2,
                 skipinitialspace=True, usecols = columns)
img = df.pivot(index='Y', columns='X', values='V')
img = img.reindex(index=range(df['Y'].min(), df['Y'].max() + 1),
                  columns=range(df['X'].min(), df['X'].max() + 1))

extent = [df['X'].min() - 0.5, df['X'].max() + 0.5,
          df['Y'].min() - 0.5, df['Y'].max() + 0.5]
plt.imshow(img, origin='lower', extent=extent)
plt.colorbar()

rawDescription: Optimizing non regularized data reading to image


code:
import pygame
import sys
pygame.init()

pygame.display.set_mode((100, 100))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                print('Forward')
            elif event.key == pygame.K_s:
                print('Backward')

rawDescription: pygame - Key pressed

description: Pygame - Key pressed


code: aspectTermTag = etree.SubElement(aspectTermsTag, "aspectTerm", {"term":asp[0], "from": asp[1], "to":asp[2]})

rawDescription: How to add python keyword terms as tag attributes in lxml?

description: Add python keyword terms as tag attributes in lxml


code:
class SomeResource(Resource):
    class Meta(...):
         ...
         field_list_to_remove = [ 'field1', 'field2' ]
         ...

    def alter_list_data_to_serialize(request, to_be_serialized):
        for obj in to_be_serialized['objects']:
            for field_name in self._meta.field_list_to_remove:
                del obj[field_name]
        return to_be_serialized

rawDescription: Can django-tastypie display a different set of fields in the list and detail views of a single resource?


rawDescription: python matplotlib imshow() custom tickmarks

description: Python matplotlib imshow() custom tickmarks


code: etree.fromstring('''Texas A&M	''').text

rawDescription: Use Python to parse html data which contains "&"


code:
from collections import defaultdict

lines = defaultdict(list)
for line in slicedFile:
  num, restOfLine = line.split('\t', 1)
  lines[num].append(line)

for fN, dummy in gA:
  for line in lines[fN]:
    out.write(line)

rawDescription: Fast rearranging of a text file

description: Fast rearranging of a text file


code:
TYPES = [(int, 1), (Decimal, 2),(date, 3), (str, 4)]
class MyTag(models.Model):
    name = models.CharField(max_length=50)
    data_type = models.IntegetField(choices=TYPES)
    value = models.CharField(max_length=100)

    def set_the_value(self, value):
        choices = dict(TYPES)
        self.data_type = choices[type(value)]
        if self.data_type == int:
            self.value = "%010d" % value
        # else... repeat for other data types

    def get_the_value(self):
        choices = dict([(y,x) for x,y in TYPES])
        return choices[self.data_type](self.value)

rawDescription: Django ForeignKey to Generic Python Data Type?


code:
responses = {}

def cache_response(self, key, response):
    self.responses[key] = {}
    self.responses[key]['response'] = response
    self.responses[key]['time'] = dt.datetime.now()

def get_cached_url(self, path):
    if path not in self.responses.keys():
        self.http_client.fetch(self.get_url(path), self.stop)
        self.cache_response(path, self.wait(timeout=30))
    return self.responses[path]

rawDescription: Caching HTTP responses in a Tornado AsyncHTTPTestCase


code:
import csv

with open("temp.csv", mode="rU") as infile:
    reader = csv.reader(infile, dialect="excel")
    with open("temp2.txt", mode="w") as outfile:
        writer = csv.writer(outfile, delimiter=':')
        writer.writerows(rows)

rawDescription: Python parse csv file - replace commas with colons


code:
from models import MyModel
try:
    max_length = MyModel._meta.get_field('source_url').max_length
except:
    max_length = None

rawDescription: Reading a Django model's field options

description: Reading a Django model's field options


code: my_dict = eval(Cell("Data Sheet", "A1").value)

rawDescription: Reading Excel Cell Value directly to complex Python Obects, DataNitro


code:
with app.test_client() as c:
    with c.session_transaction() as sess:
        sess['user_id'] = 'myuserid'
        sess['_fresh'] = True # https://flask-login.readthedocs.org/en/latest/#fresh-logins
    resp = c.get('/someurl')

rawDescription: flask unit test: how to test request from logged in user

description: Flask unit test: how to test request from logged in user


code:
x = re.compile("([A-Za-z0-9%./]+=[^\s]+)")
out = x.findall(input_str)

# out = ['website=http%3A%2F%2Fwww.test.com%2F&number=1037319821&comment=Test+mea&gender=male&submit=Submit', 'id=1234&variable=test&firstname=John&lastname=Doe&gender=male&submit=Submit']'

rawDescription: Match urlencoded data from file

description: Match urlencoded data from file


code:
import os,sys

print("CWD: "+os.getcwd())
print("Script: "+sys.argv[0])
print(".EXE: "+os.path.dirname(sys.executable))
print("Script dir: "+ os.path.realpath(os.path.dirname(sys.argv[0])))
pathname, scriptname = os.path.split(sys.argv[0])
print("Relative script dir: "+pathname)
print("Script dir: "+ os.path.abspath(pathname))

rawDescription: Get my current path using a python script as a command


code:
if process_id != os.getpid():
   clear_local_data()

rawDescription: Python's multiprocessing Does Not Play Nicely With threading.local?


code:
subscription_id = '****-***-***-**'
certificate_path = 'CURRENT_USER\\my\\***'
sms = ServiceManagementService(subscription_id, certificate_path)
result=sms.get_deployment_by_name("your service name","your deployment name")

rawDescription: Get VM status using Azure Python SDK

description: Get VM status using Azure Python SDK


code:
from tkinter import *

class Gui:

    def __init__(self, root):
        tframe = Frame(root)
        tframe.pack(side='top')
        bframe = Frame(root)
        bframe.pack(side='bottom')
        self.txt = Text(tframe)
        self.txt.insert('0.0', 'Totally foobar')
        self.txt.pack()
        self.btn = Button(bframe, text='OK')
        self.btn.pack()

    def get_big_text(self, callback, title='', text=''):
        popup = Toplevel(height=160, width=180)
        popup.title(title)
        txtframe = Frame(popup)
        txtframe.pack()
        big_text = Text(txtframe)
        big_text.insert('0.0',text)
        big_text.pack()
        btnframe = Frame(popup)
        btnframe.pack()
        grab_text = Button(btnframe)
        grab_text.config(text="Done", command=lambda:callback(big_text.get('0.0', 'end')))
        grab_text.pack()

root=Tk()
root.title('Example')
foo = Gui(root)
foo.get_big_text(lambda x:print(x))
root.mainloop()

rawDescription: Tkinter Large Text Dialogue (save string on button click)


code:
def check_input_file():
    input_file = raw_input('Please enter a filename: ')
    if input_file.endwith('.txt'):
        return input_file
    else:
        print('File name should end in .txt')
        return check_input_file()

filename = check_input_file()

rawDescription: Pass input function as a variable

description: Pass input function as a variable


code:
import numpy as np
arr = np.array([234, 235, 23, 6, 3, 6, 23])
elim = [3, 5, 6]
np.delete(arr, elim)

rawDescription: Python (numpy): drop columns by index

description: Python (numpy): drop columns by index


code:
s = "Hello *|FOO|*, let's play with *|BAAAAAR|*"
re.findall(r'\*\|.*?\|\*', s)

rawDescription: Regular expression, match substring between asterisks and pipes


code:
import random
running=True
while running:
    a=random.randint(1,1000)
    with open ("lookin.txt") as f:
        rl=f.readlines()
        for i in rl:
            if int(i)==a:
                print ("Match found")
                with open("found.txt","w") as t:
                    t.write(str(a))
                    running=False

rawDescription: Reading a file until a match found with python


code:
import pyvisa

def findInstrumentByDescriptor(descriptor):
    devName = descriptor

    rm = pyvisa.ResourceManager()
    com_names=rm.list_resources()
    devicesFound = []

    #loop over all devices, open them, and check the descriptor
    for com in range(len(com_names)):
        try:
            #try to open instrument, if failed, just skip to the next device
            my_instrument=rm.open_resource(com_names[com])
        except:
            print("Failed to open " + com_names[com])
            continue
        try:
            # VI_ATTR_INTF_INST_NAME is 3221160169, it contains the model name "GPS DATA LOGGER" (check pyvisa manual for other VISA attributes)
            modelStr = my_instrument.get_visa_attribute(3221160169)

            #search for the string you need inside the VISA attribute
            if modelStr.find(devName) >= 0:
                #if found, will be added to the array devicesFound
                devicesFound.append(com_names[com])
                my_instrument.close()
        except:
            #if exception is thrown here, then the device should be closed
            my_instrument.close()

    #return the list of devices that contain the VISA attribute required
    return devicesFound

#here's the main call
print(findInstrumentByDescriptor("GPS DATA LOGGER"))

rawDescription: Python: Get device "model" using pyvisa or pyserial


code:
def check(vat_num):
    if len(vat_num) != 9 or vat_num[0] not in "ABCDEFGHIJKLMNPQRSVW":
        return False # trivial checks first
    nums = list(map(int, vat_num[1:8])) # numbers to check
    nums[1::2] = ((i * 2) - (9 if i > 4 else 0) for i in nums[1::2]) # alter odds
    return int(vat_num[8]) == (sum(nums) % 10) # compare to check digit

rawDescription: Disgruntled with VAT number check digit algorithm


code:
firstTextArea = []
secondTextArea = []
x = 1
while True:
    try:
        firstTextArea.append(request.form['firstTextArea' + str(x)])
        secondTextArea.append(request.form['secondTextArea' + str(x)])
    except:
        break
    x += 1

rawDescription: How to send large amounts of HTML form input to Flask?

description: Send large amounts of HTML form input to Flask


rawDescription: python: dict as prototype/template for another dict - std.lib way to solve this?

description: Python: dict as prototype/template for another dict - std.lib way to solve this


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import ImageGrid
foo = np.arange(5 * 7).reshape(5, 7)
bar = np.arange(11 * 7).reshape(11, 7)
baz = np.arange(3 * 7).reshape(3, 7)
data = [foo, bar, baz]
nrows = [x.shape[0] for x in data]
row_labels = np.array([x for x in 'abcdefghijk'])
col_labels = [x for x in 'ABCDEFG']
fig = plt.figure()
axs = ImageGrid(fig, 111, nrows_ncols=(3, 1), axes_pad=0.1)
for ix, d in enumerate(data):
    ax = axs[ix]
    _ = ax.imshow(d)
    _ = ax.yaxis.set_ticks(range(d.shape[0]))
    _ = ax.xaxis.set_ticks(range(d.shape[1]))
    _ = ax.yaxis.set_ticklabels(row_labels[np.arange(d.shape[0])])
    _ = ax.xaxis.set_ticklabels(col_labels)

rawDescription: prevent cutoff of imshow subplots of unequal dimension w/ sharex

description: Prevent cutoff of imshow subplots of unequal dimension w/ sharex


code:
urlpatterns = [
    url(r'^books/(.*?)/availability/$', views.book_availability),
    url(r'^books/(.*?)/$', views.list_books),
]

rawDescription: Django: Matching anything but forward slash in url?


code: [(k, '=', v) for k, v in d.items()]

rawDescription: Convert dictionary to tuple with additional element inside tuple


code:
from bs4 import BeautifulSoup as bs
import requests
s = requests.session()
url = r'url_i_care_about'

def authenticate(s, url):
    headers = {'username': 'myuser', 'password': 'mypasss', '_Id': 'submit'}
    page=s.get(url)
    soup=bs(page.content)
    value=soup.form.find_all('input')[2]['value']
    headers.update({'value_name':value})
    auth = s.post(url, params=headers, cookies=page.cookies)

rawDescription: Authentication and python Requests

description: Authentication and python Requests


code:
import win32com.client, sys
Application = win32com.client.Dispatch("PowerPoint.Application")
Application.Visible = True
Presentation = Application.Presentations.Open(sys.argv[1])
for Slide in Presentation.Slides:
    for Shape in Slide.Shapes:
        try:
            Shape.TextFrame.TextRange.Font.Name = "Arial"
            Shape.TextFrame.TextRange.Font.Size = "12"
            Shape.TextFrame.TextRange.Font.Color.RGB = "000000"
        except:
            pass
Presentation.Save()
Application.Quit()

rawDescription: PowerPoint & Python: Editing PPT fails when an image is reached


code:
replies_by_link = {}
replies = Publicreply.objects.filter(answer_to_id__in=link_ids).order_by('answer_to', 'submitted_on')

for reply in replies:
    if reply.answer_to_id not in replies_by_link:
        replies_by_link[reply.answer_to_id] = reply

rawDescription: Rewriting this database access query to circumvent 'DISTINCT ON' error, in Django


code:
def getLocalizedMonth(j):
  locale.set_locale(locale.LC_ALL, "")
  datetime.datetime.strptime(j, "%m").strftime("%B")
  locale.setlocale(locale.getdefaultlocale())

rawDescription: Localized month name in Python

description: Localized month name in Python


code:
minRow = treeView.rowAt(0) # very top of scrollable area
if minRow >= 0: # ensure there is at least one row
    maxRow = treeView.rowAt(treeView.height()) # very bottom...

    # there may not be enough rows to fill scrollable area
    if maxRow < 0: maxRow = model.rowCount() - 1

    for row in range(minRow, maxRow + 1):
        model.dataChanged.emit(model.index(row, 0), model.index(row, model.columnCount()))

rawDescription: What rows are in view of a QAbstractTableModel


code:
def wlanCheck():
    #Do something..

    #Timer controller...
    if util.getThreadKill() != 1:
        global tWLAN
        tWLAN = 0
        tWLAN = Timer(900, wlan.WLAN_check)
        tWLAN.start()

tWLAN = Timer(900, wlan.WLAN_check)

rawDescription: How to better work with time related commands in Python?

description: Better work with time related commands in Python


code:
import base64

# Set the location of the proxy
proxy_string = choice(self._get_proxies_from_file('proxies.txt')) # user:pass@ip:port
proxy_items = proxy_string.split('@')
request.meta['proxy'] = "http://%s" % proxy_items[1]

# setup basic authentication for the proxy
user_pass=base64.encodestring(proxy_items[0])
request.headers['Proxy-Authorization'] = 'Basic ' + user_pass

rawDescription: Authenticate Scrapy HTTP Proxy

description: Authenticate Scrapy HTTP Proxy


code:
cursor.execute (
    "INSERT INTO text (text_key, language_id, text) VALUES (%s, %s, %s)",
    (key, language_id, text))

rawDescription: How to protect text when doing INSERT using MySQLdb

description: Protect text when doing INSERT using MySQLdb


code:
with open(filename) as f:
    lines = [l.split() for l in f.readlines()]
lines = [map(float, l[:3]) for l in lines if len(l)>=3]

rawDescription: read in specific values from a file and store them in a list python

description: Read in specific values from a file and store them in a list python


code: def __iter__(self): return self.books.itervalues()

rawDescription: How do I use __getitem__ and __iter__ and return values from a dictionary?

description: Use __getitem__ and __iter__ and return values from a dictionary


code:
def compare(a,b):
    if len(a) != len(b):
        return False
    return all(i == j for i,j in itertools.izip(a,b))

rawDescription: What are the best ways to compare the contents of two list-like objects?


code:
def print_report(symbol:str, strategy:str,
                 dates:list, closings:list, indicators:list, signals:list):
    fmt = '{0[0]:<0}{0[1]:>13}{0[2]:>15}{0[3]:>15}'
    print()
    print('SYMBOL:   ', symbol.upper())
    print('STRATEGY: ', strategy)
    print()
    print(fmt.format(('DATE', 'CLOSING', 'INDICATOR', 'SIGNAL')))
    for d in zip(dates, closings, indicators, signals):
        print(fmt.format(d))

rawDescription: output alignment issue with lists

description: Output alignment issue with lists


code:
if settings.DEBUG:
    urlpatterns += patterns('',
            (r'^static/media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT, 'show_indexes':True}),
        )
    urlpatterns += patterns('',
                 (r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_ROOT, 'show_indexes':True}),
            )

rawDescription: Not serving staticfiles default behavior when running `gunicorn_django`?


code:
import string

def getAvailableLetters(lettersGuessed):
    return sorted(set(string.ascii_lowercase) - set(lettersGuessed))

lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's']
getAvailableLetters(lettersGuessed)

rawDescription: Need to set i as zero everytime the for loop is run in python


code:
import pprint

file_1="""[92.5] Text Text : Text: xxx
[91.5] Text Text : Text: xxx"""

file_2="""[91.7] [Text] Some text.
Some text of variable size, may be on multiple lines. Number of lines is variable also.
[90.5] [Text] Some text.
Some text of variable size, may be on multiple lines. Number of lines is variable also."""

## Write data to some test log files
with open("./log_1.txt", "w") as fp_out:
    fp_out.write(file_1)
with open("./log_2.txt", "w") as fp_out:
    fp_out.write(file_2)

def input_recs(f_name):
    recs=open(f_name, "r").readlines()
    ## assume you want to omit text only lines
    return_list=[rec.strip() for rec in recs if rec[1].isdigit()]
    return return_list

sorted_list=[]
for f_name in ["log_1.txt", "log_2.txt"]:
    recs=input_recs(f_name)
    sorted_list.extend(recs)

sorted_list.sort()
pprint.pprint(sorted_list)

rawDescription: Combining Log Files and Sorting by Time in Python


code:
from Tkinter import *
import datetime

root = Tk()

lab = Label(root)
lab.pack()

def clock():
    time = datetime.datetime.now().strftime("Time: %H:%M:%S")
    lab.config(text=time)
    #lab['text'] = time
    root.after(1000, clock) # run itself again after 1000 ms

# run first time
clock()

root.mainloop()

rawDescription: How do I create an automatically updating GUI using Tkinter?

description: Create an automatically updating GUI using Tkinter


code:
import Tkinter as tk

class MyApplication(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Root Window")
        self.bind("<1>", self.showChild)

    def showChild(self, event=None):
        self.top = tk.Toplevel(self)
        self.top.title("This is the CHILD window")

app = MyApplication()
app.mainloop()

rawDescription: How to set a child window's title

description: Set a child window's title


code:
# from original example
with open('simple.py', 'r') as f:
    code = f.read()
exec(code)
# compile and run again
a = compile(code, "simple_compiled_this_file_not_created", "exec")
exec(a)
# marshal and unmarshal
import marshal
f = open("./marshalfoo.bin", "wb")
marshal.dump(a,f)
f.close()
b = marshal.load(open("./marshalfoo.bin", "rb"))
exec(b)

rawDescription: Python exec() of a marshaled code object


code:
import itertools
list(itertools.combinations([1,2,3,4,5,6], 2))

rawDescription: python list item combinations

description: Python list item combinations


code:
levels = np.logspace(0, np.log10(Z.max()), 100 )[30:80]
color_levels = ['r' if (i+5) % 10 == 0 else 'k' for i in range(len(levels))]
pyplot.contour(X, Y, Z, locator=ticker.LogLocator(), colors=color_levels, levels=levels, lw=2, norm=colors.LogNorm(), vmin=1, vmax=Z.max())

rawDescription: Contourplot matplotlib with every n-th line a different color


code:
import wx

class Frame(wx.Frame):
    def __init__(self):
        super(Frame, self).__init__(None, -1, 'CursorTracker')
        self.mdc = None # memory dc to draw off-screen
        self.Bind(wx.EVT_SIZE, self.on_size)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase)
        self.Bind(wx.EVT_PAINT, self.on_paint)
        w, h = wx.GetDisplaySize()
        w, h = w * 3 / 4, h * 3 / 4
        self.SetSize((w, h))
        self.Center()
        self.on_timer()
    def on_size(self, event):
        # re-create memory dc to fill window
        w, h = self.GetClientSize()
        self.mdc = wx.MemoryDC(wx.EmptyBitmap(w, h))
        self.redraw()
    def on_erase(self, event):
        pass # don't do any erasing to avoid flicker
    def on_paint(self, event):
        # just blit the memory dc
        dc = wx.PaintDC(self)
        if not self.mdc:
            return
        w, h = self.mdc.GetSize()
        dc.Blit(0, 0, w, h, self.mdc, 0, 0)
    def on_timer(self):
        # refresh every N milliseconds
        self.redraw()
        wx.CallLater(100, self.on_timer)
    def redraw(self):
        # do the actual drawing on the memory dc here
        dc = self.mdc
        w, h = dc.GetSize()
        dc.Clear()
        dc.DrawLine(0, 0, w, h)
        self.Refresh()

if __name__ == '__main__':
    app = wx.PySimpleApp()
    frame = Frame()
    frame.Show()
    app.MainLoop()

rawDescription: Can't get wx.BufferedDC to draw anything


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

fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2, sharex=ax1)

t = np.linspace(0, 1, 1000)

ax1.plot(t, np.sin(2 * np.pi * t))
ax2.plot(t, np.cos(2 * np.pi * t))

plt.show()

rawDescription: How to set same scale for subplots in python using matplotlib

description: Set same scale for subplots in python using matplotlib