code:
def same(iterable):
    it = iter(iterable)
    start_val = it.__next__()
    for val in it:
        if val != start_val:
            return
    if start_val != 0:
        return start_val

nr = [0] * 9

nr[1] = 1
nr[2] = 2
nr[4] = 2
nr[6] = 2
nr[7] = 1
nr[8] = 1

for i in range(0, len(nr), 3):
    print(nr[i:i+3])

winner = (
    same(nr[0:3]) or same(nr[3:6]) or same(nr[6:9]) or
    same(nr[0::3]) or same(nr[1::3]) or same(nr[2::3]) or
    same(nr[::4]) or same(nr[2:-1:2])
)

if winner is not None:
    print("Player %i won!" % winner)

rawDescription: Python tic tac toe detecting cheating

description: Python tic tac toe detecting cheating


code:
class ModelFoo(Base):
    __tablename__ = 'foo'
    id = Column("id", Integer, primary_key=True, autoincrement=True)
    os = Column(String, nullable=False)
    platform = Column(String)
    search_cols = ["os", "value"]

for k, v in list(Base._decl_class_registry.items()):
    if (hasattr(v, "search_cols")):
        cols = [getattr(v, val) for val in v.search_cols]
        query = sess.query(*cols)
        solr.add(query.all())

rawDescription: marking columns in sqlalchemy tables

description: Marking columns in sqlalchemy tables


code:
import fileinput
import re
found = False
for line in fileinput.input("your_file",inplace=True):
    if re.match("pattern",line):
        found = True
    if found:
        print(line,end="") # print line, python2
    else:
        print(end="") # print, python2

rawDescription: Python delete lines of text line #1 till regex


code:
import datetime
datetime.datetime.strptime('december', '%B').month
datetime.datetime.strptime('january', '%B').month

rawDescription: Converting human readable date into integer values


rawDescription: Converting a float to hh:mm format

description: Converting a float to hh:mm format


code:
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.contrib.auth import authenticate, login

def login_user(request, template_name='registration/login.html'):
    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
            return HttpResponseRedirect('/home/')
        else:
            # Return a 'disabled account' error message
            return render(request, template_name, {'error': 'disabled account'})
    else:
        # Return an 'invalid login' error message.
        return render(request, template_name, {'error': 'invalid login'})

rawDescription: Error when attempting to extend django.contrib.auth.views.login


code:
import win32gui
import win32con
import winxpgui
import win32api
import subprocess
import time

subprocess.Popen("notepad.exe", shell=True)
time.sleep(1)
hwnd = win32gui.FindWindow(None, "New file - metapad")  ## The caption of my empty notepad (MetaPad)

win32gui.SetWindowLong (hwnd, win32con.GWL_EXSTYLE, win32gui.GetWindowLong (hwnd, win32con.GWL_EXSTYLE ) | win32con.WS_EX_LAYERED )
winxpgui.SetLayeredWindowAttributes(hwnd, win32api.RGB(0,0,0), 180, win32con.LWA_ALPHA)

rawDescription: Make a window transparent using Win32?

description: Make a window transparent using Win32


code: min(x[1] for x in lstoflsts)

rawDescription: how to determine the minimal value in a column of a list of tuples in python

description: Determine the minimal value in a column of a list of tuples in python


code:
import unittest

class ts(unittest.TestCase):
    def test_null(self): self.assertTrue(True)
class ts1(unittest.TestCase):
    def test_null(self): self.assertTrue(True)

testSuite = unittest.TestSuite()

testSuite.addTests(unittest.makeSuite(ts))
testSuite.addTest(unittest.makeSuite(ts1))

import doctest
import my_module_with_doctests

testSuite.addTest(doctest.DocTestSuite(my_module_with_doctests))

unittest.TextTestRunner(verbosity = 2).run(testSuite)

rawDescription: Using doctests from within unittests

description: Using doctests from within unittests


code:
import math
# Use input() instead of raw_input() in 3.x
s = raw_input("Input numbers, delimited by spaces: ")
numbers = [float(n) for n in s.split()]
print("Average:", math.fsum(numbers) / len(numbers))

rawDescription: How to find average of user-entered floats?

description: Find average of user-entered floats


code: X_s = sorted(X, key=lambda x: [(f0, g(x, f0)) for f0 in [f(x)]][0])

rawDescription: Python One-Liner: Sorting by multiple, interdepending keys


code: ('^servertest/(?P<path>.*)$', 'redirect_to', {'url': '/server-test/%(path)s'}),

rawDescription: How do I rewrite this URL in Django?

description: Rewrite this URL in Django


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from matplotlib.patches import Polygon
np.random.seed(1977)

def main():
    for _ in range(5):
        gradient_fill(*generate_data(100))
    plt.show()

def generate_data(num):
    x = np.linspace(0, 100, num)
    y = np.random.normal(0, 1, num).cumsum()
    return x, y

def gradient_fill(x, y, fill_color=None, ax=None, **kwargs):
    """
    Plot a line with a linear alpha gradient filled beneath it.

    Parameters
    ----------
    x, y : array-like
        The data values of the line.
    fill_color : a matplotlib color specifier (string, tuple) or None
        The color for the fill. If None, the color of the line will be used.
    ax : a matplotlib Axes instance
        The axes to plot on. If None, the current pyplot axes will be used.
    Additional arguments are passed on to matplotlib's ``plot`` function.

    Returns
    -------
    line : a Line2D instance
        The line plotted.
    im : an AxesImage instance
        The transparent gradient clipped to just the area beneath the curve.
    """
    if ax is None:
        ax = plt.gca()

    line, = ax.plot(x, y, **kwargs)
    if fill_color is None:
        fill_color = line.get_color()

    zorder = line.get_zorder()
    alpha = line.get_alpha()
    alpha = 1.0 if alpha is None else alpha

    z = np.empty((100, 1, 4), dtype=float)
    rgb = mcolors.colorConverter.to_rgb(fill_color)
    z[:,:,:3] = rgb
    z[:,:,-1] = np.linspace(0, alpha, 100)[:,None]

    xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()
    im = ax.imshow(z, aspect='auto', extent=[xmin, xmax, ymin, ymax],
                   origin='lower', zorder=zorder)

    xy = np.column_stack([x, y])
    xy = np.vstack([[xmin, ymin], xy, [xmax, ymin], [xmin, ymin]])
    clip_path = Polygon(xy, facecolor='none', edgecolor='none', closed=True)
    ax.add_patch(clip_path)
    im.set_clip_path(clip_path)

    ax.autoscale(True)
    return line, im

main()

rawDescription: Is it possible to get color gradients under curve in matplotlb?


code:
def aSillyBlockingMethod(bot):
    import time
    while True:
        msg = raw_input()
        bot.threadSafeMsg("#bottest", msg)

class LogBot(irc.IRCClient):
    """A logging IRC bot."""

    nickname = "twistedbot"

    def connectionMade(self):
        irc.IRCClient.connectionMade(self)
        self.logger = MessageLogger(open(self.factory.filename, "a"))
        self.logger.log("[connected at %s]" %
                        time.asctime(time.localtime(time.time())))

        # The bot is now connected.  Start reading input here.
        # Pass a reference to this protocol instance, so that
        # messages can be sent to this protocol instance.
        deferToThread(aSillyBlockingMethod, self)

    # Define a helper function for aSillyBlockingMethod to use.
    # Since aSillyBlockingMethod runs in a thread, it cannot just call
    # IRCClient.msg, since that method - like almost all methods in Twisted -
    # is not thread-safe.  Instead it must call this thread-safe wrapper.
    def threadSafeMsg(self, channel, message):
        reactor.callFromThread(self.msg, channel, message)

rawDescription: Twisted Python - IRC Client

description: Twisted Python - IRC Client


code:
def month(n):
 lst = ['Months','Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
 return lst[n]

rawDescription: finding a list item by its index

description: Finding a list item by its index


code:
a
b
concat([a, b])
concat([a, b], axis=1)

rawDescription: Concatenating pandas DataFrames with datetime columns


code:
#make dictionary
user_data = {}

#make a new user object
new_user = CsrUser(...)

#insert your new user object into the dictionary
#use new_user.f_name or new_user.l_name here in place of new_user.name (or combine both)
user_data[new_user.name] = new_user

#to get a user object out of the dictionary
a_user = user_data["name_here"]

rawDescription: Create dynamic objects python

description: Create dynamic objects python


code:
from collections import defaultdict
def cdict():
    return defaultdict(cdict)

d = cdict()
d['a']=1
d['b']=3
d
d['c']['d'] = 33
d['c']['d']
d
d['c']['e']

rawDescription: Equivalent of Clojure's "assoc-in" and "get-in" in Python


code:
import sys
import numpy
from PIL import Image, ImageOps, ImageDraw
from scipy.ndimage import morphology, label

def boxes(orig):
    img = ImageOps.grayscale(orig)
    im = numpy.array(img)

    # Inner morphological gradient.
    im = morphology.grey_dilation(im, (3, 3)) - im

    # Binarize.
    mean, std = im.mean(), im.std()
    t = mean + std
    im[im < t] = 0
    im[im >= t] = 1

    # Connected components.
    lbl, numcc = label(im)
    # Size threshold.
    min_size = 200 # pixels
    box = []
    for i in range(1, numcc + 1):
        py, px = numpy.nonzero(lbl == i)
        if len(py) < min_size:
            im[lbl == i] = 0
            continue

        xmin, xmax, ymin, ymax = px.min(), px.max(), py.min(), py.max()
        # Four corners and centroid.
        box.append([
            [(xmin, ymin), (xmax, ymin), (xmax, ymax), (xmin, ymax)],
            (numpy.mean(px), numpy.mean(py))])

    return im.astype(numpy.uint8) * 255, box

orig = Image.open(sys.argv[1])
im, box = boxes(orig)

# Boxes found.
Image.fromarray(im).save(sys.argv[2])

# Draw perfect rectangles and the component centroid.
img = Image.fromarray(im)
visual = img.convert('RGB')
draw = ImageDraw.Draw(visual)
for b, centroid in box:
    draw.line(b + [b[0]], fill='yellow')
    cx, cy = centroid
    draw.ellipse((cx - 2, cy - 2, cx + 2, cy + 2), fill='red')
visual.save(sys.argv[3])

rawDescription: Finding properties of sloppy hand-drawn rectangles


code:
# ...
writer = pd.ExcelWriter('final.xlsx')
data.to_excel(writer,'original')

# data.fillna() or similar.

data.to_excel(writer,'result')
writer.save()
# ...

rawDescription: creating multiple excel worksheets using data in a pandas dataframe

description: Creating multiple excel worksheets using data in a pandas dataframe


rawDescription: How to specify a string value from a returned database returned tuple

description: Specify a string value from a returned database returned tuple


code:
df= pd.DataFrame(np.random.randn(10,4))
df[4]= [[df[2][x],df[3][x]] for x in range(df.shape[0])]

rawDescription: Pandas combine row element in one

description: Pandas combine row element in one


code:
versions = [m.group(1) for m in [regex.match(lib) for lib in libs] if m]
versions

rawDescription: Python list filtering and transformation


code:
def my_annotate(ax, s, xy_arr=[], *args, **kwargs):
  ans = []
  an = ax.annotate(s, xy_arr[0], *args, **kwargs)
  ans.append(an)
  d = {}
  try:
    d['xycoords'] = kwargs['xycoords']
  except KeyError:
    pass
  try:
    d['arrowprops'] = kwargs['arrowprops']
  except KeyError:
    pass
  for xy in xy_arr[1:]:
    an = ax.annotate(s, xy, alpha=0.0, xytext=(0,0), textcoords=an, **d)
    ans.append(an)
  return ans

ax = plt.gca()
ax.plot([1,2,3,4],[1,4,2,6])
my_annotate(ax,
            'Test',
            xy_arr=[(2,4), (3,2), (4,6)], xycoords='data',
            xytext=(30, -80), textcoords='offset points',
            bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3),
            arrowprops=dict(arrowstyle="-|>",
                            connectionstyle="arc3,rad=0.2",
                            fc="w"))
plt.show()

rawDescription: Annotate several points with one text in matplotlib


code:
lower_stream = (line.lower() for line in file_stream)
csv_reader = csv.reader(lower_stream, delimiter=' ', quotechar='"', escapechar='^')

rawDescription: Read in a CSV file in lower case with Python


code: [dict(zip(TEMPLATE,d)) for d in DATA]

rawDescription: Template-based dictionary creation out of a list of lists


rawDescription: how to switch a nested list to a array

description: Switch a nested list to a array


rawDescription: Round half to even on decimal

description: Round half to even on decimal


code:
df
df.groupby('a').agg({'b': 'sum', 'c': lambda x: ' '.join(x)})

rawDescription: pandas groupby and join lists

description: Pandas groupby and join lists


rawDescription: Create a sqlalchemy engine using an existing psycopg2 connection pool


code: self.send = Button(self.framepack, text="Send", width=10, command=self.send_email)

rawDescription: Getting a NameError for my class in Python


code:
class HandlerMixin(object):
    def get_logged_in_user(self):
        ...

class Handler(webapp2.RequestHandler, HandlerMixin):
    pass

class UploadHandler(blobstore.BlobstoreUploadHandler, HandlerMixin):
    def post(self):
        ...

rawDescription: Retrieving uploaded Blob info from a regular handler


code:
import functools

def undoable(f):
    @functools.wraps(f)
    def wrapper(self, *a, **k):
        tok = k.get('undo_token')
        if tok is None:
            tok = k['undo_token'] = self.get_undo_token()
        return f(self, *a, **k), tok
    return wrapper

rawDescription: Is it bad practice to use self in decorators?


code:
xpath = '//li[contains(@class,"our-age")]/span/text()'
item["age"] = hxs.select(xpath).extract() or [' ']

rawDescription: Scrapy: How to make a conditional (present or absent) XPATH return values when absent?


code:
t = axes.transAxes.transform([(0,0), (1,1)])
t = axes.get_figure().get_dpi() / (t[1,1] - t[0,1]) / 72

# Height = 18 points
height = 18 * t

rawDescription: Matplotlib Patch Size in Points

description: Matplotlib Patch Size in Points


code:
def time_seconds(self, obj):
    return obj.timefield.strftime("%d %b %Y %H:%M:%S")
time_seconds.admin_order_field = 'timefield'
time_seconds.short_description = 'Precise Time'

list_display = ('id', 'time_seconds', )

rawDescription: In the Django admin site, how do I change the display format of time fields?


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

x = np.array([6, 3, 5, 2, 1, 4, 9, 7, 8])
y = np.array([2, 1, 3 ,5 ,3 ,9 ,8, 10, 7])

# sort the data in x and use that to rearrange y
sortId = np.argsort(x)
x = x[sortId]
y = y[sortId]

# this way the x-axis corresponds to the index of x
plt.plot(x-1, y)
plt.show()
maxm = argrelextrema(y, np.greater)  # (array([1, 3, 6]),)
minm = argrelextrema(y, np.less)  # (array([2, 5, 7]),)

rawDescription: Find all local Maxima and Minima when x and y values are given as numpy arrays


code:
vals = zip(*(x.split(',') for x in original.itervalues()))
[dict(zip(original, v)) for v in vals]

rawDescription: Turn a dictionary of lists in to a list of dictionaries in Python 2.7


code:
import re
reg = "(foo)(?i)"
re.split(reg, "fOO1foo2FOO3")

rawDescription: Python regex split case insensitive in 2.6


code:
def userInput1():
    x = int(input("Product Number?"))
    return x
def userInput2():
    q = int(input("Quantity?"))
    return q
def calculations(x,q):
    p1 = 2.98
    p2 = 4.5
    p3 = 9.98
    p4 = 4.49
    p5 = 6.87
    subtotal = q * x
#here you are multiplying the item number by quantity
#not the price by quantity (use proper if else to check price for item number
# return to main function again for more comments
    return subtotal
def final(subtotal):
    print ("Total:", subtotal)
#nothing wrong here but since we have declared subtotal as global (remember that?)
#so no need to pass subtotal by argument.
def loop():
    cont = input("Do you want to continue? (yes/no)")
    if cont == 'yes':
        main()
        return
    else:
        final()
#you are calling final() but you declared with argument (are you mad?)
#now check final function

def main():
    x = userInput1()
#Where you are taking input from user for quantity??
#first take quantity as input q = userInput2()
    subtotal = calculations(x,q)
#now every time you call main function your subtotal will be revised
#remember teacher talking about global and local variables?
#subtotal needs to be global (declare it somewhere outside the functions
#now even if subtotal is global you need to increment it (not reassign)
# use subtotal += calculations(x,q)
#now check your calculations function
    final(subtotal)
#you are calling final subtotal but where the hell you calling your loop?
#call it before calling final and now check your loop function
main()

rawDescription: Python: Using defs in a program about ordering stuff


code:
import tkinter as tk
import os

def onKeyPress(event):
    if event.char == 'a':
        os.system('start C:\mold\MoldFlowMaster_exce.xlsx')

root = tk.Tk()
root.geometry('300x200')
text = tk.Text(root, background='black', foreground='white', font=('Comic Sans MS', 12))
text.pack()
root.bind('<KeyPress>', onKeyPress)
root.mainloop()

rawDescription: Using keyboard actions to open files outside of Python


code:
from random import shuffle
data = []
maxlength = 10

while len (data) < maxlength:
    country = input("please enter a country: ")
    capital = input("please enter the capital of the country entered: ")

    # for this scenario, probably better to keep rows together instead of columns.
    data.append((country, capital)) # using a tuple here. It's like an array, but immutable.

# this will make them come out in a random order!
shuffle(data)

for i in range(maxlength):
    country = data[i][0]
    capital = data[i][1]
    print("Capital for the country {0}?".format(country))
    user_said_capital_was = input("What do you think?")
    if user_said_capital_was == capital:
        print("Correct!")
    else:
        print("Incorrect!")

rawDescription: lists of list and random choice

description: Lists of list and random choice


code:
import gc
import weakref

def __call__(cls, *args, **kwargs):
    gc.collect()  # optional, clear existing weak references
    inst = cls._instance and cls._instance()  # de-reference the weakref
    if inst is None:
        inst = cls.__new__(cls, *args, **kwargs)
        inst.__init__(*args, **kwargs)
        cls._instance = weakref.ref(inst)
        return inst
    else:
        del inst  # clear local early
        raise SingletonError("Cannot initialize multiple singletons.")

rawDescription: Magic method for python del statement?

description: Magic method for python del statement


code:
def is_chars_in_strings(strings, chars):
    answer = []
    for string in strings:
        a = False
        for char in chars:
            if char in string:
                a = True
                break
        if not a:
            answer.append(string)
    return answer

print (is_chars_in_strings(['abc', 'def'], 'ab'))

rawDescription: Python how to evaluate if one of two substrings in string using OR operator


code:
while True:
    #this will keep prompting the user to provide an input that is listed in 'options'
    while True:
        selection = input("Please select choose an option to continue")
        if selection in options:
            break
        else:
            print("Please choose a valid option")

    if selection == '0':
        break

    ...

rawDescription: Working on a basic python calculator and can't get my menu to loop properly


code:
from Tkinter import *

import MySQLdb

class App:

    def __init__(self, master):
        Button3 = Button(master, text="Transaction", command=self.tran).pack()

    def tran(self) :

        first = Tk()

        label1 = Label(first ,text="From")

        label1.pack()

        self.box1=Entry(first )

        self.box1.pack()

        label2=Label(first ,text="To")

        label2.pack()

        self.box2=Entry(first )

        self.box2.pack()

        label3=Label(first ,text="Amt")

        label3.pack()

        self.box3=Entry(first )

        self.box3.pack()

        Button1 = Button(first , text="Next", command=self.func3).pack()

    def func3(self) :

        conn = MySQLdb.connect (host = "localhost", user = "root", passwd = "natty", db = "dbms")

        cursor=conn.cursor()

        From=int(self.box1.get().strip())

        To=int(self.box2.get().strip())

        Amt=int(self.box3.get().strip())
        cursor.execute ("select bal from account where acc="+str(From)+"")

        a=cursor.fetchone()

        fromval=int(a[0])

        cursor.execute ("select bal from account where acc="+str(To)+"")

        b=cursor.fetchone()

        toval=int(b[0])

        fromval=fromval-Amt

        toval=toval+Amt

        cursor.execute("update account set bal="+str(fromval)+" where acc="+str(From)+"")

        cursor.execute("update account set bal="+str(toval)+" where acc="+str(To)+"")

        cursor.close ()

        conn.close ()

master = Tk()

app = App(master)

master.mainloop()

rawDescription: python Tk interface : NameError: global name 'box1' is not defined

description: Python Tk interface : NameError: global name 'box1' is not defined


code:
#from gi.repository import Gtk  # uncomment to use PyGObject
import gtk as Gtk

class TestCase:
    def __init__(self):
        win = Gtk.Window()
        button = Gtk.Button('Show')
        button.connect('clicked', self.on_button_clicked)

        self.clicked = 0
        self.liststore = Gtk.ListStore(int)
        self.liststore.append((self.clicked,))
        view = Gtk.TreeView(self.liststore)
        renderer = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn('demo', renderer, text=0)
        view.append_column(column)

        box = Gtk.HBox()
        box.pack_start(button, True, True, 0)
        box.pack_start(view, True, True, 0)
        win.add(box)
        win.connect('delete-event', Gtk.main_quit)
        win.show_all()

    def on_button_clicked(self, button):
        self.clicked += 1
        self.liststore.clear()
        self.liststore.append((self.clicked,))

if __name__ == "__main__":
    TestCase()
    Gtk.main()

rawDescription: gtk.TreeView does not change after changing its gtk.ListStore:

description: Gtk.TreeView does not change after changing its gtk.ListStore:


code:
var = {}
for set, list in records.iteritems():
    var[set] = [i['Time Stamp'] for i in list]

rawDescription: Python intersection of datetimes from multiple lists/dictionaries


code:
from collections import defaultdict

# count all the emails before we write anything out
emails = defaultdict(int)
for row in f:
    emails[row[0]] += 1

# now write the file
for row in email.items():
    writer.writerow(row)

rawDescription: Count duplicate rows in a csv using python


rawDescription: Trying to reference an attribute with a variable (Python)


code:
for event_date in soup.findAll('time',{'class':"poster-card__date"}):
        print(str(event_date.contents[0])),

rawDescription: python-Don't want the inside tag to be crawled

description: Python-Don't want the inside tag to be crawled


code:
df = pd.DataFrame({'x': pd.Series(['1.0', '2.0', '3.0'], dtype=float), 'y': pd.Series(['1', '2', '3'], dtype=int)})
df
df.dtypes

rawDescription: Pandas DataFrame cast multiple types to columns


code:
from urlparse import urlparse
urlparse('http://www.stackoverflow.com/questions/answers/help/').netloc

rawDescription: Regular expression that matches the third instance of something? (python)


code: Samples.objects.filter(when__year = mydate.year, when__month = mydate.month, when__day = mydate.day)

rawDescription: Matching a datetime against a date in django


rawDescription: About django wrapper example in spyne documentation


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

# Get an example image
import matplotlib.cbook as cbook
image_file = cbook.get_sample_data('grace_hopper.png')
img = plt.imread(image_file)

# Make some example data
x = np.random.rand(5)*img.shape[1]
y = np.random.rand(5)*img.shape[0]

# Create a figure. Equal aspect so circles look circular
fig,ax = plt.subplots(1)
ax.set_aspect('equal')

# Show the image
ax.imshow(img)

# Now, loop through coord arrays, and create a circle at each x,y pair
for xx,yy in zip(x,y):
    circ = Circle((xx,yy),50)
    ax.add_patch(circ)

# Show the image
plt.show()

rawDescription: drawing circles on image with matplotlib and numpy

description: Drawing circles on image with matplotlib and numpy


code:
rx = re.compile(r'^(\d+)((?:sheep)*)$')
m = rx.match(theString)
if m and len(m.group(2)) == 5 * int(m.group(1)):
   print ("Matched")

rawDescription: Your typical sheep counting regular expression in python question


code:
import matplotlib.pyplot as plt
import matplotlib.patches as ptc
import numpy as np
from shapely.geometry import Point
from shapely.ops import cascaded_union

n = 100
size = 0.02
alpha = 0.5

def points():
    x = np.random.uniform(size=n)
    y = np.random.uniform(size=n)
    return x, y

x1, y1 = points()
x2, y2 = points()
polygons1 = [Point(x1[i], y1[i]).buffer(size) for i in range(n)]
polygons2 = [Point(x2[i], y2[i]).buffer(size) for i in range(n)]
polygons1 = cascaded_union(polygons1)
polygons2 = cascaded_union(polygons2)

fig = plt.figure(figsize=(4,4))
ax = fig.add_subplot(111, title="Test scatter")
for polygon1 in polygons1:
    polygon1 = ptc.Polygon(np.array(polygon1.exterior), facecolor="red", lw=0, alpha=alpha)
    ax.add_patch(polygon1)
for polygon2 in polygons2:
    polygon2 = ptc.Polygon(np.array(polygon2.exterior), facecolor="blue", lw=0, alpha=alpha)
    ax.add_patch(polygon2)
ax.axis([-0.2, 1.2, -0.2, 1.2])

fig.savefig("test_scatter.png")

rawDescription: How to make Matplotlib scatterplots transparent as a group?

description: Make Matplotlib scatterplots transparent as a group


code:
#!/usr/bin/env python

import urllib
import json

response_1 = json.loads(urllib.urlopen("http://search.twitter.com/search.json?q=microsoft&page=1").read())
for i in response_1['results']:
    print (i, "\n")

rawDescription: How to make each tweet on its own line?

description: Make each tweet on its own line


code:
seq = "KA13-1 KA13-2 KA14-2 KA14-1 KA11-12 KA13-12".split()
seq.sort(key=lambda x: tuple(map(int, x[2:].split("-"))))
seq

rawDescription: Sort Set of Numbers in the form (XX-YY) in Python


code:
rdd = sc.parallelize(range(0, -10000, -1))
rdd.zipWithIndex().filter(lambda kv: 9 <= kv[1] < 999).keys()

rawDescription: How do I get a subset of a csv file as a Spark RDD

description: Get a subset of a csv file as a Spark RDD


code: ds_new.to_netcdf('saved_on_disk1.nc', encoding={'dis': {'zlib': True}})

rawDescription: Python xarray.concat then xarray.to_netcdf generates huge new file size


code:
from datetime import datetime, timedelta, date

(datetime.combine(date.today(), c.video_length) + timedelta(minutes=5)).time()

rawDescription: How to add timedelta to time

description: Add timedelta to time


code:
# Generally I found the following might be useful for verifying the page:
driver.current_url
driver.title

# The following might be useful for verifying the driver instance:
driver.name
driver.orientation
driver.page_source
driver.window_handles
driver.current_window_handle
driver.desired_capabilities

rawDescription: Selenium Webdriver with Python - driver.title parameter


code: latlongs = LatLong.objects.filter(date__gte=time1, date__lte=time2, vehicle__omei=omei)

rawDescription: Nested SELECT vs INNER JOIN

description: Nested SELECT vs INNER JOIN


rawDescription: Django query optimization: retrieve values in groups possible?


code:
def not3(string2, string1):
    if len(string2) < 3:  return True    # reaching here, the sequence wasn't found
    if string2[:3] in string1: return False      # test beginning of string2 for existence in string1
    return not3(string2[1:], string1)  # recurse from next char of string2

rawDescription: Check a string for all or 3 consecutive characters of another string? Regex python NOT case-sensitive


code: logger.info('the length of my list is %d' % len(mylist))

rawDescription: Getting the length of a list as string

description: Getting the length of a list as string


code:
# Downsample data
downsampled_data = downsample(data, 100)

# Replacement for the default getData function
def getData(obj):
    # Calculate the visible range
    range = obj.viewRect()
    if range is not None:
        dx = float(data[-1, 0] - data[0, 0]) / (data.size[0] - 1)
        x0 = (range.left() - data[0, 0]) / dx
        x1 = (range.right() - data[0, 0]) / dx
    # Decide whether to use downsampled or original data
    if (x1 - x0) > 20000:
        obj.xData = downsampled_data[:, 0]
        obj.yData = downsampled_data[:, 1]
    else:
        obj.xData = data[:, 0]
        obj.yData = data[:, 1]
    # Run the original getData of PlotDataItem
    return PlotDataItem.getData(obj)

# Replace the original getData with our getData
plot_data_item.getData = types.MethodType(getData, plot_data_item)

rawDescription: Using pre-downsampled data when plotting large time series in PyQtGraph


code:
from urllib.request import urlopen
from shutil import copyfileobj

with urlopen(image['url']) as in_stream, open(p, 'wb') as out_file:
    copyfileobj(in_stream, out_file)

rawDescription: What command to use instead of urllib.request.urlretrieve?


rawDescription: Mysql, python, SQL not executing

description: Mysql, python, SQL not executing


rawDescription: Mapping URL Pattern to a Single RequestHandler in a WSGIApplication


code:
s="The Dog Jumped"

In [14]: enc = "".join([chr(ord(c)+1) for c in s])
In [15]: enc
Out[15]: 'Uif!Eph!Kvnqfe'
In [16]: dec = "".join([chr(ord(c)-1) for c in enc])
In [17]: dec
Out[17]: 'The Dog Jumped'

rawDescription: Python-need help on how to make a crpyter shifting+1 on alphabet


code:
df = pd.read_csv('test.csv')
df['date'] = pd.to_datetime(df['date'])
df['date_delta'] = (df['date'] - df['date'].min())  / np.timedelta64(1,'D')
city_data = df[df['city'] == 'London']
result = sm.ols(formula = 'sales ~ date_delta', data = city_data).fit()

rawDescription: Convert date to float for linear regression on Pandas data frame


code:
from celery import Celery
import time

app = Celery(
    'test_celery'
    ,broker= 'redis://localhost/0'
)

app.conf.update(
    CELERY_RESULT_BACKEND = 'redis://localhost/1'
)

@app.task
def add(x, y):
    time.sleep(2)
    return x + y

if __name__ == '__main__':
    result = add.delay(4, 4)
    print( result.get() )

rawDescription: Canonical Celery single file hello world


code:
from Tkinter import *
from itertools import combinations
import ttk
import time

class ProgBarApp:
    def __init__(self):
        self.vals = range(1, 20)
        self.combs = list(combinations(self.vals,3))
        self.n = len(self.combs)
        self.progressbar = ttk.Progressbar(root, maximum = self.n+1)
        self.progressbar.pack()

    def start(self):
        for c in self.combs:
            self.progressbar.step()
            time.sleep(0.01)
            root.update()
        root.destroy()

root = Tk()
p = ProgBarApp()
root.after(0, p.start())
root.mainloop()

rawDescription: Progressbar and combinations in Python

description: Progressbar and combinations in Python


code: y = itertools.product((1, -1, 1j, -1j), repeat=13)

rawDescription: Generate a list of length n with m possible elements


code:
import wx
from wx.lib.scrolledpanel import ScrolledPanel

class TestPanel(ScrolledPanel):
  def __init__(self, parent):
    ScrolledPanel.__init__(self, parent)
    self.SetupScrolling(scroll_x=False)

    self.textctrls = [wx.TextCtrl(self) for _ in range(4)]

    sizer = wx.BoxSizer(wx.VERTICAL)
    hsizer = wx.BoxSizer(wx.HORIZONTAL)
    for textctrl in self.textctrls:
      hsizer.Add(textctrl, 1, wx.EXPAND)
      textctrl.SetMinSize((0, -1))

    sizer.Add(hsizer, 0, wx.EXPAND)
    self.SetSizer(sizer)

class MyFrame(wx.Frame):
  def __init__(self, parent):
    wx.Frame.__init__(self, parent, title="test", size=(320, 240))
    self.SetBackgroundColour('#ffffff')
    self.panel = TestPanel(self)
    self.Show()

if __name__ == '__main__':
  app = wx.App(False)
  MyFrame(None)
  app.MainLoop()

rawDescription: Resize multiple items inside of a WxPython BoxSizer evenly?


code:
def repeated(f, count):
    callable = f
    for _ in range(count - 1):
        callable = compose(f, callable)
    return callable

rawDescription: Python Lambda usage

description: Python Lambda usage


code:
import csv
import itertools

with open('VI(12).csv') as input, open('VI_avg(12).csv','w') as output:
    reader = csv.reader(input)
    writer = csv.writer(output)
    for current, row in itertools.groupby(reader, lambda x: x[1]):
        biaslist = [float(x[0]) for x in row]
        biasavg = float(sum(biaslist))/len(biaslist)
        writer.writerow([biasavg, current])

rawDescription: How to average values in one column of a csv if the values in another column are not changing?

description: Average values in one column of a csv if the values in another column are not changing


code:
import matplotlib.pyplot as plt
import numpy as np
sin = np.sin
cos = np.cos
pi = np.pi

def delete(event):
    artist = event.artist
    artist.remove()
    event.canvas.draw()

fig = plt.figure()
ax = fig.add_subplot(111)

x = np.linspace(0, 2*pi, 50)
y = 2*sin(x)
z = 2*cos(x)
line1, = ax.plot(x,y)
line2, = ax.plot(x,z)
for artist in [line1, line2]:
    artist.set_picker(5)
fig.canvas.mpl_connect('pick_event', delete)

plt.show()

rawDescription: Removing a certain part of a figure in matplotlib


code:
# sort the list using the 'link' item as the sort key
biglist.sort(key=lambda elt: elt['link'])

newbiglist = []
for item in biglist:
    if newbiglist == [] or item['link'] != newbiglist[-1]['link']:
        newbiglist.append(item)

rawDescription: How to remove these duplicates in a list (python)

description: Remove these duplicates in a list (python)


code:
import time
import wx

class Loader(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(sizer)
        self.btn1 = wx.Button(self, label="Option 1")
        self.btn2 = wx.Button(self, label="Option 2")
        sizer.Add(self.btn1, flag=wx.EXPAND)
        sizer.Add(self.btn2, flag=wx.EXPAND)
        self.btn1.Bind(wx.EVT_BUTTON, self.OnOption1)
        self.btn2.Bind(
            wx.EVT_BUTTON, lambda e: wx.MessageBox("There is no option 2")
        )

    def OnOption1(self, event):
        self.btn1.Hide()
        self.btn2.Hide()
        self.Sizer.Add(
            wx.StaticText(self, label="Loading Option 1..."),
            1, wx.ALL | wx.EXPAND, 15
        )
        self.Layout()
        self.Update()
        AppFrame(self).Show()

class AppFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)
        time.sleep(3)
        parent.Hide()

        # the top window (Loader) is hidden so the app needs to be told to exit
        # when this window is closed
        self.Bind(wx.EVT_CLOSE, lambda e: wx.GetApp().ExitMainLoop())

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

rawDescription: Opening a wx.Frame in Python via a new thread


code:
from selenium import webdriver
profile = webdriver.FirefoxProfile();
profile.set_preference("browser.startup.homepage", "about:blank");
profile.set_preference("startup.homepage_welcome_url", "about:blank");
profile.set_preference("startup.homepage_welcome_url.additional", "about:blank");
dr = webdriver.Firefox(profile)
dr.title

rawDescription: Selenium: how to open a blank Firefox browser


code:
import wx

class TextFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Text Editor', size=(300, 250))

        self.panel = wx.Panel(self, -1)

        self.multiText = wx.TextCtrl(self.panel, -1,"",size=(200, 100), style=wx.TE_MULTILINE|wx.EXPAND)

        sizer = wx.BoxSizer()
        sizer.Add(self.multiText, proportion=1, flag=wx.CENTER|wx.EXPAND)
        self.panel.SetSizer(sizer)

        self.CreateStatusBar()

        self.multiText.Bind(wx.EVT_KEY_UP, self.updateLineCol)
        self.multiText.Bind(wx.EVT_LEFT_DOWN, self.updateLineCol)

    def updateLineCol(self, event):
        #lineNum = len(self.multiText.GetRange( 0, self.multiText.GetInsertionPoint() ).split("\n"))
        l,c = self.multiText.PositionToXY(self.multiText.GetInsertionPoint())

        stat = "col=%s, row=%s" % (l,c)

        self.StatusBar.SetStatusText(stat, number=0)

        event.Skip()

app = wx.App(False)
frame = TextFrame()
frame.Show()
app.MainLoop()

rawDescription: wxpython textctrl line and column

description: Wxpython textctrl line and column


code:
def background_task(entry_value):
    thread1 = Thread(target=continuous_tasks, args=(entry_value,))
    thread1.start()
    return None

rawDescription: trying to multi-thread in python with an infinite loop, however my GUI still freezes

description: Trying to multi-thread in python with an infinite loop, however my GUI still freezes


code:
data = soup2.findAll(text=True) #mind the not casting it to a string
(var1, var2, var3, var4) = data

rawDescription: Extracting strings from list

description: Extracting strings from list


code:
img = Image.open(imgName).convert("RGBA")
arr = numpy.array(img)

# Split the channels of the image by rotating the axes
r, g, b, a = arr.transpose(2, 0, 1)

# Create Boolean array: True means pixel is above threshold
bw = (r > threshold) | (g > threshold) | (b > threshold)

# Set R, G and B channel to the 255 times the B/W array
arr[:, :, :2] = 255 * bw[:, :, numpy.newaxis]

# Set alpha channel to 255
arr[:, :, 3] = 255

# Create new PIL image from array
new_img = Image.fromarray(arr)

rawDescription: Threading Performance Degradation when Handling Pixels


code:
from django.core.cache import cache

client = cache._client  # <--direct reference to memcached.Client object

rawDescription: Django atomic increase with initial value


rawDescription: numpy.where() with 3 or more conditions

description: Numpy.where() with 3 or more conditions


code:
import psutil, os
Parent=psutil.Process(os.getpid()).parent()
ParentName=Parent.name() # e.g. bash, cmd.exe, etc

rawDescription: Determine calling executable in Python - 2


code:
def count_seq(input_file):
    dic1={}
    with open(input_file, "r") as f:
        for line in f:
            line = line.strip()
            if not line.startswith('#'):
                line = line.split()
                seq_id = line[1]
                if not seq_id in dic1:
                    dic1[seq_id] = 1
                else:
                    dic1[seq_id] += 1

    return dic1

print(count_seq("blast_file"))

rawDescription: Creating a dictionary to count the number of occurrences of Sequence IDs


code:
del myDict[item]
for key, value in myDict.items():
    if item in value:
        myDict[key] = value.difference(set([item]))

rawDescription: Deleting a Key and its occurrence in other key's Value in python dictionary


code:
from gi.repository import Gtk, Gdk
import cairo
import sys

class MyWindow(Gtk.ApplicationWindow):
    # constructor for a Gtk.ApplicationWindow

    def __init__(self, app, image_file="/tmp/window.png"):
        Gtk.Window.__init__(self, title="Welcome to GNOME", application=app)
        self.set_default_size(200, 100)
        self.image_file = image_file

        vbox = Gtk.VBox()
        self.add(vbox)

        # create a label
        label = Gtk.Label()
        # set the text of the label
        label.set_text("Hello GNOME!")
        # add the label to the window
        vbox.pack_start(label, True, True, 0)

        button = Gtk.Button("ScreenshotMe!")
        button.connect("clicked", self.on_save_image)
        vbox.pack_start(button, False, False, 0)

    def on_save_image(self, button):
        """
        Get the surface of the current window and save it as a png
        """
        window = self.get_window()
        width, height = window.get_width(), window.get_height()
        surface = Gdk.Window.create_similar_surface(window,
                                                    cairo.CONTENT_COLOR,
                                                    width, height)
        cairo_context = cairo.Context(surface)
        Gdk.cairo_set_source_window(cairo_context, window, 0, 0)
        cairo_context.paint()

        surface.write_to_png(self.image_file)

class MyApplication(Gtk.Application):

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

    def do_activate(self):
        win = MyWindow(self)
        win.show_all()

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

app = MyApplication()
exit_status = app.run(sys.argv)
sys.exit(exit_status)

rawDescription: How to capture image of a gtk ApplicationWindow in Python in linux?

description: Capture image of a gtk ApplicationWindow in Python in linux


code: f = open('savefile', 'w')

rawDescription: Rewriting a file Python

description: Rewriting a file Python


rawDescription: If/else alternative

description: If/else alternative


code:
connection = monetdb.sql.connect(username=username,password=password,hostname=hostname,port=port,database=database)
cursor = connection.cursor()
cursor.execute('create table test (id int, name varchar(50));')
connection.commit()

rawDescription: sql (MonetDB) commands from Python stalling

description: Sql (MonetDB) commands from Python stalling


code: XML('<style>body { font: normal 16px/1.6em "Open Sans",Arial,Helvetica,sans-serif; }</style>')

rawDescription: Avoid CDATA tag in STYLE component

description: Avoid CDATA tag in STYLE component


code:
from win32com.client import Dispatch

excel = Dispatch('Excel.Application')
wb = excel.Workbooks.Open("D:\\output.xlsx")

#Activate second sheet
excel.Worksheets(2).Activate()

#Autofit column in active sheet
excel.ActiveSheet.Columns.AutoFit()

#Save changes in a new file
wb.SaveAs("D:\\output_fit.xlsx")

#Or simply save changes in a current file
#wb.Save()

wb.Close()

rawDescription: Using Python To Autofit All Columns of an Excel Sheet


code:
for i, d in enumerate([360, 30, 7, 1]):
    ax = axes.flatten()[i]
    earlycut = now - relativedelta(days=d)
    data = df.loc[df.index>=earlycut, :]
    ax.plot(data.index, data['value'])

    ax.get_xaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())
    ax.get_yaxis().set_minor_locator(mpl.ticker.AutoMinorLocator())

    ax.grid(b=True, which='major', color='w', linewidth=1.5)
    ax.grid(b=True, which='minor', color='w', linewidth=0.75)

    plt.setp(ax.get_xticklabels(), rotation=30, horizontalalignment='right')

fig.tight_layout()

rawDescription: Matplotlib showing x-tick labels overlapping despite best efforts


code:
hex(ord("c"))
format(ord("c"), "x")
"c".encode("hex")

rawDescription: How do I convert a single character into it's hex ascii value in python

description: Convert a single character into it's hex ascii value in python


code:
s.sprintf(
  "import imp\n"
  "imp.load_source('%s', r'%s')", modname, script_path);
PyRun_SimpleString(s.c_str());

rawDescription: How to import a file by its full path using C api?

description: Import a file by its full path using C api


code:
from urllib2 import urlopen
import re

urlpath =urlopen('http://www.divms.uiowa.edu/~jni/courses/ProgrammignInCobol/presentation/')
string = urlpath.read().decode('utf-8')

pattern = re.compile('ch[0-9]*.ppt"') #the pattern actually creates duplicates in the list

filelist = pattern.findall(string)
print(filelist)

for filename in filelist:
    filename=filename[:-1]
    remotefile = urlopen('http://www.divms.uiowa.edu/~jni/courses/ProgrammignInCobol/presentation/' + filename)
    localfile = open(filename,'wb')
    localfile.write(remotefile.read())
    localfile.close()
    remotefile.close()

rawDescription: Python urllib downloading contents of an online directory


code:
def has_dups(arr):
    return len(set(arr)) != len(arr)

rawDescription: Coding Style in Python

description: Coding Style in Python


code:
for dir, subdir, files in os.walk(src):
    for f in files:
        targ = os.path.join(dest, f)
        if os.path.exists(targ):
            for i in itertools.count():
                targ = os.path.join(dest, '%s(%s)' % (f, i))
                if not os.path.exists(targ):
                    break
        shutil.copy(os.path.join(dir, f), targ)

rawDescription: Python copy file ignoring tree structure


code:
from time import sleep

for i in range(60):  # Change this number to make it longer or shorter.
    print('█', end='')
    sleep(0.1)  # Change this number to make it faster or slower.

rawDescription: How to add a progress bar in python?

description: Add a progress bar in python


rawDescription: Regex to match a non numeric value or end of string in Python


code:
# sender side
data = struct.pack('!d', 3.1415)  # float -> bytes

# receiver side
x = struct.unpack('!d', data)  # bytes -> float

rawDescription: [Python]Conversion issue: Float --> Bytes and viceversa


code:
from urllib import urlencode
import urllib2

url ='http://online.wsj.com/search/term.html?KEYWORDS=alibaba'
data = urlencode({'page_no':3})

contents = urllib2.urlopen(url, data=data).read()

rawDescription: How to extract hyperlinked hrefs from html using urllib2

description: Extract hyperlinked hrefs from html using urllib2


code:
from threading import Thread
import gobject

gobject.threads_init()

time_to_wait = 2.0      # time in seconds
nonblocking_wait = Thread(target=sleep, args=(timetowait,))
nonblocking_wait.start()

while nonblocking_wait.is_alive():
    nonblocking_wait.join(.05)
    gtk.main_iteration_do(True)     # blocks if no event is pending

rawDescription: Getting the interface to block in PyGTK

description: Getting the interface to block in PyGTK


code:
# filename = input("Enter a file name: ")
filename = "input.txt"

def avg_file(filename):

    with open(filename, 'r') as f:
        data = [int(line.split()[2]) for line in f]
        return sum(data)/len(data)

avg =  avg_file(filename)

print("The average value is: ", avg)
# The average value is:  40.5

rawDescription: average of .txt file with str and int within it

description: Average of .txt file with str and int within it


code:
sc._conf.getAll()

## [('spark.rdd.compress', 'True'),
##  ('spark.executor.memory', '8g'),
##  ('spark.serializer.objectStreamReset', '100'),
##      ...
## ('spark.app.name', 'PySparkShell')]

rawDescription: dumping the SparkConf object of a SparkContext

description: Dumping the SparkConf object of a SparkContext


code:
import subprocess
subprocess.call(['osascript', '-e', 'tell application "iTunes" to pause'])

rawDescription: Python – Check if Mac is Playing Music

description: Python – Check if Mac is Playing Music


code: struct.pack('<h', 1500)

rawDescription: Python - decimal to integer low byte then high byte


code:
def rating(row):
    return float(row.split(None, 2)[1])

star_nums = [rating(row) for row in star]
star_avg = sum(star_nums) / len(star_nums)

rawDescription: get only numbers in a list after crawling from the web

description: Get only numbers in a list after crawling from the web


code:
from BeautifulSoup import BeautifulSoup
import urllib

post_params = {
    param1 : val1,
    param2 : val2,
    param3 : val3
        }
post_args = urllib.urlencode(post_params)

url = 'http://www.website.com/'
fp = urllib.urlopen(url, post_args)
soup = BeautifulSoup(fp)

rawDescription: Fill input of type text and press submit using python


code:
import json

js_value = json.dumps(python_value)

rawDescription: How to pass dictionary from Jinja2 (using Python) to Javascript?

description: Pass dictionary from Jinja2 (using Python) to Javascript


code: pd.merge(df2, df1, left_index=True, right_index=True, on='date', how='outer')

rawDescription: Pandas merging data and overwrite a column


code:
class Rest_Menu():
    def __init__(self, menu):
        self.menu = menu
        self.all_price = []

    def min_price(self, order, total_price=0):
        """
        Return minm menu price by calculating all possible combination.
        """
        if order:
            for item, price in self.menu.iteritems():
                if isSubset(order[0], item):
                    new_order = [each for each in order]
                    for itm in item:
                        try:
                            new_order.remove(itm)
                        except ValueError:
                            pass
                    self.min_price(new_order, price+total_price)
        else:
            self.all_price.append(total_price)
        return min(self.all_price)

rawDescription: correct me for using generators or tell me other way

description: Correct me for using generators or tell me other way


code:
import csv
from collections import deque
import datetime
from glob import iglob
import os

class Criterion(object):
    """ represents one of the criteria to be checked.
        in_a_row is the number of consecutive rows in which the expression,
        given as a string, evaluated to True """
    def __init__(self, in_a_row, expression):
        self.in_a_row = in_a_row
        self.expression = expression
        self.bytecode = compile(expression, '<string>', 'eval')
        self.deque = deque(maxlen=in_a_row)
    def eval_and_check(self, local_vars):
        """ evaluate expression in context of local variables, append result
            to deque, and return whether 'in_a_row' criterion was satisfied """
        self.deque.append(eval(self.bytecode, globals(), local_vars))
        return self.deque.count(True) == self.in_a_row
    def reset(self):
        self.deque.clear()
    def format_match(self, filename, linenum):
        return 'lines {}-{} in {} had {} consecutive rows with "{}"'.format(
            linenum-self.in_a_row+1, linenum, filename, self.in_a_row,
            self.expression)

criteria = [Criterion(5, 'Test_Res_2 < 40'),
            Criterion(3, '13 <= Test_Res_4 <= 15'), ]
flagtotal = []
datapath = "datafiles"  # directory path to location of csv files

for filename in iglob(os.path.join(datapath, '*.csv')):
    with open(filename) as csvfile:
        reader = csv.reader(csvfile, skipinitialspace=True)
        reader.next() # skip over initial fieldnames row
        for criterion in criteria:  # initialize all before processing file
            criterion.reset()
        condition_satisfied = False
        for linenum, row in enumerate(reader, start=1):
            # define local vars for use in criterion expression evaluation
            (Test_num, Test_Res_1, Test_Res_2, Test_Res_3, Test_Res_4,
             Test_div, Test_time) = [int(row[0])] + map(float, row[1:])
            for criterion in criteria:
                if criterion.eval_and_check(locals()):
                    #print criterion.format_match(filename, linenum)
                    flagtotal.append(os.path.basename(filename))
                    condition_satisfied = True
                    break  # quit criterion checking for this row
            if condition_satisfied:
                break  # quit processing rows of this csv file

with open('test.txt', 'w') as f:
    f.write('Date of testing: {}\n'.format(
            datetime.date.today().strftime('%m/%d/%Y')) +
            'The following files met the criteria:\n'
            '-------------------------------------\n')
    if flagtotal:
        print('\n'.join(flagtotal))
        f.write('\n'.join(flagtotal) + '\n')
    else:
        print('no files met the criteria')
        f.write('no files met the criteria\n')

rawDescription: How to check for multiple concurrent events in several rows for several columns at the same time in Python?

description: Check for multiple concurrent events in several rows for several columns at the same time in Python


code:
import csv
with open("input.csv", "rb") as input, open("output.csv", "wb") as output:
    w = csv.writer(output)
    for record in csv.reader(input):
        w.writerow(tuple(s.remove("\n") for s in record))

rawDescription: How could I remove newlines from all quoted pieces of text in a file?


code:
import subprocess, time

p = subprocess.Popen(['mplayer', 'http://173.239.76.147:8090'])
time.sleep(5)
p.terminate()
p.wait()  # important!

subprocess.Popen(['reset']).wait()

print('Hello, World!')

rawDescription: Shell hangs after killing subprocess

description: Shell hangs after killing subprocess


code:
import itertools

class Rectangle:
    def intersection(self, other):
        a, b = self, other
        x1 = max(min(a.x1, a.x2), min(b.x1, b.x2))
        y1 = max(min(a.y1, a.y2), min(b.y1, b.y2))
        x2 = min(max(a.x1, a.x2), max(b.x1, b.x2))
        y2 = min(max(a.y1, a.y2), max(b.y1, b.y2))
        if x1<x2 and y1<y2:
            return type(self)(x1, y1, x2, y2)
    __and__ = intersection

    def difference(self, other):
        inter = self&other
        if not inter:
            yield self
            return
        xs = {self.x1, self.x2}
        ys = {self.y1, self.y2}
        if self.x1<other.x1<self.x2: xs.add(other.x1)
        if self.x1<other.x2<self.x2: xs.add(other.x2)
        if self.y1<other.y1<self.y2: ys.add(other.y1)
        if self.y1<other.y2<self.y2: ys.add(other.y2)
        for (x1, x2), (y1, y2) in itertools.product(
            pairwise(sorted(xs)), pairwise(sorted(ys))
        ):
            rect = type(self)(x1, y1, x2, y2)
            if rect!=inter:
                yield rect
    __sub__ = difference

    def __init__(self, x1, y1, x2, y2):
        if x1>x2 or y1>y2:
            raise ValueError("Coordinates are invalid")
        self.x1, self.y1, self.x2, self.y2 = x1, y1, x2, y2

    def __iter__(self):
        yield self.x1
        yield self.y1
        yield self.x2
        yield self.y2

    def __eq__(self, other):
        return isinstance(other, Rectangle) and tuple(self)==tuple(other)
    def __ne__(self, other):
        return not (self==other)

    def __repr__(self):
        return type(self).__name__+repr(tuple(self))

def pairwise(iterable):
    # https://docs.python.org/dev/library/itertools.html#recipes
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

# 1.
a = Rectangle(0, 0, 1, 1)
b = Rectangle(0.5, 0.5, 1.5, 1.5)
print(a&b)
# Rectangle(0.5, 0.5, 1, 1)
print(list(a-b))
# [Rectangle(0, 0, 0.5, 0.5), Rectangle(0, 0.5, 0.5, 1), Rectangle(0.5, 0, 1, 0.5)]

# 2.
b = Rectangle(0.25, 0.25, 1.25, 0.75)
print(a&b)
# Rectangle(0.25, 0.25, 1, 0.75)
print(list(a-b))
# [Rectangle(0, 0, 0.25, 0.25), Rectangle(0, 0.25, 0.25, 0.75), Rectangle(0, 0.75, 0.25, 1), Rectangle(0.25, 0, 1, 0.25), Rectangle(0.25, 0.75, 1, 1)]

# 3.
b = Rectangle(0.25, 0.25, 0.75, 0.75)
print(a&b)
# Rectangle(0.25, 0.25, 0.75, 0.75)
print(list(a-b))
# [Rectangle(0, 0, 0.25, 0.25), Rectangle(0, 0.25, 0.25, 0.75), Rectangle(0, 0.75, 0.25, 1), Rectangle(0.25, 0, 0.75, 0.25), Rectangle(0.25, 0.75, 0.75, 1), Rectangle(0.75, 0, 1, 0.25), Rectangle(0.75, 0.25, 1, 0.75), Rectangle(0.75, 0.75, 1, 1)]

# 4.
b = Rectangle(5, 5, 10, 10)
print(a&b)
# None
print(list(a-b))
# [Rectangle(0, 0, 1, 1)]

# 5.
b = Rectangle(-5, -5, 10, 10)
print(a&b)
# Rectangle(0, 0, 1, 1)
print(list(a-b))
# []

rawDescription: Intersection and difference of two rectangles


code:
for p in story:
    while f.add(p, c) == 0:
        f.split(p, c)
        f = Frame(0.5*inch, inch, 7*inch, 10.5*inch, showBoundary=1)

rawDescription: how to know the end of a frame to create a new one reportlab

description: Know the end of a frame to create a new one reportlab


code:
import subprocess

subprocess.Popen(('find', '/tmp/mount', '-type', 'f',
                  '-name', '*.rpmsave', '-exec', 'rm', '-f', '{}', ';'))

rawDescription: Python equivilant to find -exec

description: Python equivilant to find -exec


code: evals, evecs = scipy.sparse.linalg.eigsh(a, k=1)

rawDescription: SciPy - Compute eigenvector for particular eigenvalue in symmetric matrix


code:
original_start_point = 1000
start_point = original_start_point

rawDescription: Python: Resetting a variable

description: Python: Resetting a variable


code:
from django.template.loader import render_to_string
from django.core.mail import send_mail
email_messsage = render_to_string(template_path, template_context)
send_mail(subject, email_message, sender_email, [recipient_email])

rawDescription: how to send mail notification automatically using django modules?

description: Send mail notification automatically using django modules


code: arr = numpy.random.binomial(1, p, count)

rawDescription: Fastest way to fill numpy array with zeros and ones


code:
from mayavi import mlab

currfig = mlab.test_plot3d()
mlab.draw()

cam = currfig.scene.camera
for ii in range(100):
  cam.zoom(0.99)
  mlab.draw()

mlab.show()

rawDescription: How to set zoom factor in Mayavi

description: Set zoom factor in Mayavi


code:
def _python_interactive_indent(self, code):
    prev_toktype = tokenize.INDENT
    first_line = None
    last_lineno = -1
    last_col = 0

    output = ''

    tokgen = tokenize.generate_tokens(StringIO.StringIO(code).readline)
    indent = 0
    hasNL = False
    prefixed = False
    for toktype, ttext, (slineno, scol), (elineno, ecol), ltext in tokgen:
        done = False
        if toktype == tokenize.INDENT:
            indent = indent + 1
        if toktype == tokenize.DEDENT:
            indent = indent - 1
        if slineno > last_lineno:
            last_col = 0
        if not done and toktype == tokenize.NL:
            hasNL = True
            done = True
        if not done and toktype == tokenize.COMMENT:
            done = True
        if not done and toktype == tokenize.STRING and prev_toktype == tokenize.INDENT:
            done = True
        if not done and hasNL and toktype != tokenize.DEDENT and toktype != tokenize.INDENT:
            hasNL = False
            output = output + ("    " * indent) + '\n'
            output += "    " * indent
            prefixed = True
        if not done:
            if not prefixed and scol > last_col:
                output += (" " * (scol - last_col))
            output += (ttext)
        prefixed = False
        prev_toktype = toktype
        last_col = ecol
        last_lineno = elineno
    return output

rawDescription: tokenize/untokenize python string code so that it is compatible with interactive-mode

description: Tokenize/untokenize python string code so that it is compatible with interactive-mode


code:
def change_sign(list1,n):
    if n in list1:
        return [-i if i==n else i for i in list1]
    elif n not in list1:
        print("The number is not in the list")

rawDescription: Change a positive number in to a negative number in a function


rawDescription: Replacing Whitespace between Variables with Commas in Python


code:
Test = namedtuple('Test',['a','b'])

@total_ordering
class TestOrdBase:
    def __lt__(self ,other):
        return self.b < other.b or self.b == other.b and self.a < other.a

class TestOrd(TestOrdBase, Test):
    pass

rawDescription: Total_ordering and class inheritance

description: Total_ordering and class inheritance


code:
if count % 10 in skipNum:
    continue

rawDescription: while loop and skipping numbers in python

description: While loop and skipping numbers in python


code:
import wx
import functools
import threading
import subprocess
import time

class Frame(wx.Frame):
    def __init__(self):
        super(Frame, self).__init__(None, -1, 'Threading Example')
        # add some buttons and a text control
        panel = wx.Panel(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        for i in range(3):
            name = 'Button %d' % (i+1)
            button = wx.Button(panel, -1, name)
            func = functools.partial(self.on_button, button=name)
            button.Bind(wx.EVT_BUTTON, func)
            sizer.Add(button, 0, wx.ALL, 5)
        text = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE|wx.TE_READONLY)
        self.text = text
        sizer.Add(text, 1, wx.EXPAND|wx.ALL, 5)
        panel.SetSizer(sizer)
    def on_button(self, event, button):
        # create a new thread when a button is pressed
        thread = threading.Thread(target=self.run, args=(button,))
        thread.setDaemon(True)
        thread.start()
    def on_text(self, text):
        self.text.AppendText(text)
    def run(self, button):
        cmd = ['ls', '-lta']
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        for line in proc.stdout:
            wx.CallAfter(self.on_text, line)

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

rawDescription: wxPython: execute command asynchronously, display stdout in text widget

description: WxPython: execute command asynchronously, display stdout in text widget


code: # /path/to/python-2.5 easy_install Django

rawDescription: Trouble Upgrading Python / Django on CentOS


code: import re

rawDescription: Using Python 3.3 to access blocked webpages


code:
y, x = 35, 570
for line in attText.splitlines():
    draw.text( (x,y), line, ... )
    y = y + attSpacing

rawDescription: Writing text with carriage return to image in Python using PIL


code:
FILTER_SOURCE_FILES = YES
INPUT_FILTER = "python path/to/doxypy.py"

rawDescription: How to make doxygen ignore the first line of a Python script?

description: Make doxygen ignore the first line of a Python script


code:
class PicklablePacket:
    """A container for scapy packets that can be pickled (in contrast
    to scapy packets themselves)."""
    def __init__(self, pkt):
        self.contents = bytes(pkt)
        self.time = pkt.time

    def __call__(self):
        """Get the original scapy packet."""
        pkt = scapy.Ether(self.contents)
        pkt.time = self.time
        return pkt

rawDescription: How to pickle a scapy packet?

description: Pickle a scapy packet


code:
def node_depth(node, depth=0, colored_nodes=None):
    ...
    if colored_nodes is None: colored_nodes = set()

rawDescription: Python: Strange behaviour of recursive function with keyword arguments


code:
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import sql
Base = declarative_base()
engine = sqlalchemy.create_engine('sqlite:///:memory:')
Session = sessionmaker(bind=engine)
session = Session()

class Info(Base):
    __tablename__ = 'info'
    id = Column(Integer(), primary_key=True)
    type = Column(String())
    item_id = Column(Integer())

    @property
    def item(self):
        if self.type == 'car':
            return self._car
        elif self.type == 'suv':
            return self._suv
        return None

    @item.setter
    def item(self, value):
        if value is not None:
            self.item_id = value.id
            self.type = value.__tablename__
        else:
            self.item_id = None

class Car(Base):
    __tablename__ = 'car'
    id = Column(Integer(), primary_key=True)
    info = relationship(Info, primaryjoin=sql.and_(id == Info.item_id, Info.type == 'car'), foreign_keys=Info.item_id, uselist=False, backref='_car')

class Suv(Base):
    __tablename__ = 'suv'
    id = Column(Integer(), primary_key=True)
    info = relationship(Info, primaryjoin=sql.and_(id == Info.item_id, Info.type == 'suv'), foreign_keys=Info.item_id, uselist=False, backref='_suv')

rawDescription: SqlAlchemy Model association based on record data


code:
adding = input("Enter Name: ")

with open("settings.txt", "a") as f:
    f.write(adding)

with open("settings.txt", "r") as fp:
    print(fp.readlines())

rawDescription: Make letters appear on the same line instead of each appearing on its own line


code:
import numpy as np
a = np.zeros((2,3,4))
i = np.array([0,0,1])
j = np.array([0,0,1])
k = np.array([0,0,3])

ijk = np.vstack((i,j,k)).T
H,edge = np.histogramdd(ijk,bins=a.shape)
a += H

rawDescription: Increment Numpy multi-d array with repeated indices


code:
from django.core.urlresolvers import resolve
resolve(url).kwargs

rawDescription: django find object from url

description: Django find object from url


code:
a = [('tore',), ('ngaming',), ('sittam',)]
" ".join([x[0] for x in a])

rawDescription: How to convert single element tuple into string?

description: Convert single element tuple into string


code:
def p_commands(self, p):
    """commands :
                | commands command"""
    # This will fail when running optimized

def p_command(self, p):
    """command : foo
               | bar"""
    p[0] = p[1]

rawDescription: Using PLY with python -OO?

description: Using PLY with python -OO


code: set(bird.color for bird in birds)

rawDescription: list of class objects (birds). each bird has a color. how do I most efficiently get a set of all colors?

description: List of class objects (birds). each bird has a color. how do I most efficiently get a set of all colors


code:
while True:
    print('''Current balance: $''',balance)

    choice = int(input('''
Please choose an option from the following:
1 - Withdraw
2 - Deposit
3 - Check Balance
4 - Exit:  '''))

    if choice == 1:
        print(withdraw());
    elif choice == 2:
        print(deposit());
    elif choice == 3:
        print(bal());

    more = input("Would you like another transaction? (y/n)")
    if more.lower() != 'y':
        print("Goodbay")
        break

rawDescription: python ATM loop trouble

description: Python ATM loop trouble


code:
text = row
if row.find('=') > 0:
    data = row.split('=')
    var, val = data[0], data[1]
    text = "{0:<15} = {1:<15}\n".format(var, val.strip())

rawDescription: Align values in an INI file generated using ConfigParser


code:
primes = []
for num in nums:
    for divisor in range(2, int(num ** .5) + 1):
        if num % divisor == 0:
            break
    else:
        primes.append(num)

rawDescription: Why my code doesn't deciding correctly from list elements that they are prime numbers or not?


rawDescription: use list tuple as 2d index to loop through another 2d list

description: Use list tuple as 2d index to loop through another 2d list


code:
match_region = [map(str, blob.sentences[i-1:i+2])     # from prev to after next
                for i, s in enumerate(blob.sentences) # i is index, e is element
                if search_words & set(s.words)]       # same as your condition

rawDescription: Text search using python

description: Text search using python


rawDescription: Python: filenames with german umlaut

description: Python: filenames with german umlaut


code:
def combine(all_ensembles):
    """Combine the sub-estimators of a group of ensembles

        >>> from sklearn.datasets import load_iris
        >>> from sklearn.ensemble import ExtraTreesClassifier
        >>> iris = load_iris()
        >>> X, y = iris.data, iris.target

        >>> all_ensembles = [ExtraTreesClassifier(n_estimators=4).fit(X, y)
        ...                  for i in range(3)]
        >>> big = combine(all_ensembles)
        >>> len(big.estimators_)
        12
        >>> big.n_estimators
        12
        >>> big.score(X, y)
        1.0

    """
    final_ensemble = copy(all_ensembles[0])
    final_ensemble.estimators_ = []

    for ensemble in all_ensembles:
        final_ensemble.estimators_ += ensemble.estimators_

    # Required in old versions of sklearn
    final_ensemble.n_estimators = len(final_ensemble.estimators_)

    return final_ensemble

rawDescription: parallel generation of random forests using scikit-learn

description: Parallel generation of random forests using scikit-learn


code:
Latest_scores = lines.split(":")[1][-7:].split(",")
Highscore = max(map(int, Latest_scores))
Print(Highscore)

rawDescription: python won't count two digit number as highest value

description: Python won't count two digit number as highest value


code:
#Open the document
document = Document(args.inputFile)

#changing the page margins
sections = document.sections
for section in sections:
    section.top_margin = Cm(margin)
    section.bottom_margin = Cm(margin)
    section.left_margin = Cm(margin)
    section.right_margin = Cm(margin)

document.save(args.outputFile)

rawDescription: Modify docx page margins with python-docx


rawDescription: Reshaping a numpy  array

description: Reshaping a numpy  array


rawDescription: how to split column of tuples in pandas dataframe?

description: Split column of tuples in pandas dataframe


code:
dates = []
def store_dates(match):
    dates.append(match.group())
    return 'DATE'

data = re.sub('some-date-string', store_dates, data)

# data is now your data with all the date strings replaced with 'DATE'
# dates now has all of the date strings that matched your regex

rawDescription: Speed up python regex matching

description: Speed up python regex matching


code:
from matplotlib.widgets import Lasso
from matplotlib.colors import colorConverter
from matplotlib.collections import RegularPolyCollection
from matplotlib import path

import matplotlib.pyplot as plt
from numpy import nonzero
from numpy.random import rand

class Datum(object):
    colorin = colorConverter.to_rgba('red')
    colorout = colorConverter.to_rgba('blue')

    def __init__(self, x, y, include=False):
        self.x = x
        self.y = y
        if include:
            self.color = self.colorin
        else:
            self.color = self.colorout

class LassoManager(object):
    def __init__(self, ax, data):
        self.axes = ax
        self.canvas = ax.figure.canvas
        self.data = data

        self.Nxy = len(data)

        facecolors = [d.color for d in data]
        self.xys = [(d.x, d.y) for d in data]
        self.ind = []
        fig = ax.figure
        self.collection = RegularPolyCollection(
            fig.dpi, 6, sizes=(100,),
            facecolors=facecolors,
            offsets=self.xys,
            transOffset=ax.transData)

        ax.add_collection(self.collection)

        self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)

    def callback(self, verts):
        facecolors = self.collection.get_facecolors()
        p = path.Path(verts)
        ind = p.contains_points(self.xys)
        self.ind = nonzero([p.contains_point(xy) for xy in self.xys])[0]
        for i in range(len(self.xys)):
            if ind[i]:
                facecolors[i] = colorConverter.to_rgba('red')
#                print ind
            else:
                facecolors[i] = colorConverter.to_rgba('blue')

        self.canvas.draw_idle()
        self.canvas.widgetlock.release(self.lasso)
        del self.lasso

    def onpress(self, event):
        if self.canvas.widgetlock.locked():
            return
        if event.inaxes is None:
            return
        self.lasso = Lasso(event.inaxes,
                           (event.xdata, event.ydata),
                           self.callback)
        # acquire a lock on the widget drawing
        self.canvas.widgetlock(self.lasso)

data = np.random.rand(5, 5)
fig, ax = plt.subplots()
# No, no need for collection
ax.imshow(data, aspect='auto', origin='lower',picker=True)
data = [Datum(*xy) for xy in rand(10, 2)]
lman = LassoManager(ax, data)
plt.show()

rawDescription: Select points in python imshow() plot with lasso or lassomanager


code:
from django.db.models import Avg
class Subject(models.Model):
    ...
    def avg_price_per_hour(self):
        # returns None if no SubjectUser is related to this instance
        return self.subject_tutors.aggregate(Avg('price_per_hour'))

class Tutor(models.Model):
    ...

class SubjectTutor(models.Model):
    subject = models.ForeignKey(Subject, related_name='subject_tutors')
    tutor = models.ForeignKey(Tutor, related_name='subject_tutors')
    price_per_hour = model.DecimalField(...)

rawDescription: Django: Tracking average values of a table


code:
#!/usr/bin/env python

import argparse as ap

parser = ap.ArgumentParser(usage='%(prog)s [-h] [a b]\n')
parser.add_argument('ab',
                    nargs='*',
                    help='specify 2 or 0 items',
                    default=['a', 'b'])

args = parser.parse_args()
if len(args.ab) != 2:
    parser.error('expected 2 arguments')

print(args.ab)

rawDescription: Ask for 0 or 2 positionnal arguments whit argparse?


code:
with open('file.csv', 'r') as src, open('file2.csv', 'w') as dst:
    dst.write(next(src).replace(" ", ""))     # delete whitespaces from header
    dst.writelines(line for line in src)

rawDescription: Python loops through CSV, but writes header row twice


code:
count = 0
with open('/Users/john/Work/html/Ribbon/header.css', 'r') as f:
    for line in f:
        if "width:" in line:
            count+=1
print("Found %d instances of 'width:'." % count)

rawDescription: Python: Finding width from imported css file


code: t1 = [L.pop(random.randrange(len(L))) for _ in xrange(2)]

rawDescription: Random Sample with remove from List

description: Random Sample with remove from List


code: df[[col for col in cols_to_keep if col not in dummies]]

rawDescription: Python - Create An Empty Pandas DataFrame and Populate From Another DataFrame Using a For Loop


code:
# users in projects owned by request.user
users = User.objects.filter(projectmodel__owner=request.user).distinct()

rawDescription: Smart Querying in Django, ManyToMany relationships with User


code:
class domParser(object):
    def __init__(self):
    #initialize dom object here, and obtain the root for the destination file object.
        self.dom = newAwesomeCompliantDom()
        self.document = self.dom.document
        self.this = self.document

    def comment(self, commentText):
    #add commentText to self.document or the above dom object you created
        self.this.appendChild(self.document.DOMImplementation.createComment(commentText))

    def start(self, tag, attrs):
    #same here
        self.this = self.this.appendChild(self.document.DOMImplimentation.newElement(tag,attrs))

    def data(self, dataText):
    #append data to the last accessed element, as a new Text child
        self.this.appendChild(self.document.DOMImpl.createDataNode(dataText))

    def end(self):
    #closing element, so move up the tree
        self.this = self.this.parentNode

    def close(self):
        return self.document

#unchecked, please validate yourself
x = lxml.etree.parse(target=domParser)
x.feed(htmlFile)
newDom = x.close()

rawDescription: PyV8, can I manipulate DOM structure?

description: PyV8, can I manipulate DOM structure


code:
import wx
from wx.lib.scrolledpanel import ScrolledPanel

class MyFrame( wx.Frame ):
    def __init__( self, parent, ID, title ):
        wx.Frame.__init__( self, parent, ID, title,
                         wx.DefaultPosition, wx.Size( 600, 400 ) )
        #Controls
        self.tin = wx.TextCtrl( self,
                                size = wx.Size( 600, 400 ),
                                style=wx.TE_MULTILINE )
        self.test_panel = ScrolledPanel( self,
                                         size = wx.Size( 600, 400 ) )
        self.test_panel.SetupScrolling()
        self.tin2 = wx.StaticText( self.test_panel )

        #Layout
        #-- Scrolled Window
        self.panel_sizer = wx.BoxSizer( wx.HORIZONTAL )
        self.panel_sizer.Add( self.tin2, 0, wx.EXPAND )
        self.test_panel.SetSizer( self.panel_sizer )
        self.panel_sizer.Fit(self.test_panel)
        #-- Main Frame
        self.inner_sizer = wx.BoxSizer( wx.HORIZONTAL )
        self.inner_sizer.Add( self.tin, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 50  )
        self.inner_sizer.Add( self.test_panel, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 50  )

        self.sizer = wx.BoxSizer( wx.VERTICAL )
        self.sizer.Add(self.inner_sizer, 1, wx.ALL | wx.EXPAND, 20)
        self.SetSizer(self.sizer)
        self.sizer.Fit(self)
        self.sizer.Layout()

        self.test_panel.SetAutoLayout(1)

        #Bind Events
        self.tin.Bind( wx.EVT_TEXT, self.TextChange )

    def TextChange( self, event ):
        self.tin2.SetLabel(self.tin.GetValue())
        self.test_panel.FitInside()

class MyApp( wx.App ):
    def OnInit( self ):
        self.fr = MyFrame( None, -1, "TitleX" )
        self.fr.Show( True )
        self.SetTopWindow( self.fr )
        return True

app = MyApp( 0 )
app.MainLoop()

def main():

    win = 1

if ( __name__ == "__main__" ):
    main()

rawDescription: wxpython scrolled Panel Not Updating scroll bars

description: Wxpython scrolled Panel Not Updating scroll bars


code:
@mock.patch.object(os, 'remove')
@mock.patch('%s.sorted' % __name__, create=True)
@mock.patch('%s.open' % __name__, create=True)
def test_compile(mock_open, mock_sort, mock_os_remove):
    mock_sort.return_value = ['parts']
    compile()
    mock_open.assert_any_call('output.file', 'wb')
    mock_sorted.assert_called_with(['parts'])
    mock_os_remove.assert_called_with('parts','rb')

rawDescription: Concatenating files in a mockable/testable way


code:
cellposX = [100]     # is a list with only one '100' inside
cellposX = [100]*100 # is a list with 100 '100' inside

rawDescription: Python Snake Game Cell Positions with Lists


code:
import urllib
import urllib.request
myurl = "http://www.mysite.com"

sock = urllib.request.urlopen(myurl)
pagedata = str(sock.read())
sock.close()

file = open("output.txt","w")
file.write(pagedata)
file.close()

rawDescription: Trouble Getting a clean text file from HTML


code:
rays_players = {'DeJesus': ['DH', 6, 299],
                'Loney': ['1B', 4, 222],
                'Rivera': ['C', 9, 194],
                'Forsythe': ['2B', 5, 304],
                'Souza Jr': ['RF', 2, 229],
                'Longoria': ['3B', 3, 282],
                'Cabrera': ['SS', 7, 214],
                'Kiermaier': ['CF', 1, 240],
                'Guyer': ['LF', 8, 274]}

for key, value in sorted(rays_players.items(), key=lambda v: v[1][1]):
    print("Batting {}: {} {}, current avg: {}".format(value[1], value[0], key, value[2]))

rawDescription: Python Dictionary/Loop Output

description: Python Dictionary/Loop Output


code:
from collections import defaultdict

def countWords(target, source, env):
    words = defaultdict(int)
    if (len(target) == 1 and len(source) == 1):
        with open(str(source[0]), 'r') as fin:
            for line in fin:
                for word in line.split():
                    words[word] += 1

        with open(str(target[0]), 'w') as fout:
            for word in sorted(words, key=words.__getitem__, reverse=True):
                fout.write('%s\n' % word)
    return None

rawDescription: example function in Python: counting words

description: Example function in Python: counting words


code:
class MyClass:
    def __init__(self, someval):
        self.someval = someval
    def get_a_function(self):
        def result():
            return self.someval
        return result

inst = MyClass("my value")
func = inst.get_a_function()
func
func.func_closure
func.func_closure[0].cell_contents

rawDescription: Get Context Object from Wrapped Function in Python


code:
# Open your text file
f = open('file.dat')

# Create empty dictionary
graph = {}

for line in f:
    x = line.rstrip().split(";")
    if not x[0] in graph:
        graph[x[0]] = {x[1] : x[2]}
    else:
        graph[x[0]][x[1]] = x[2]

    if not x[1] in graph:
        graph[x[1]] = {x[0] : x[2]}
    else:
        graph[x[1]][x[0]] = x[2]

print(graph)

rawDescription: Reading from a .txt file and creating a nested dictionary python


code:
class MySQLAlchemy(SQLAlchemy):
    def _execute_for_all_tables(self, app, bind, operation, **kwargs):
        app = self.get_app(app)

        if bind == '__all__':
            binds = [None] + list(app.config.get('SQLALCHEMY_BINDS') or ())
        elif isinstance(bind, basestring) or bind is None:
            binds = [bind]
        else:
            binds = bind

        for bind in binds:
            tables = self.get_tables_for_bind(bind)
            op = getattr(self.Model.metadata, operation)
            op(bind=self.get_engine(app, bind), tables=tables, **kwargs)

    def reflect(self, bind='__all__', app=None, **kwargs):
        self._execute_for_all_tables(app, bind, 'reflect', **kwargs)

rawDescription: Flask-SqlAlchemy views reflection

description: Flask-SqlAlchemy views reflection


code:
def get_indices(l):
    last = len(l) - 2
    diff = last / 3
    return [range(i, i + diff) for i in range(2, last, diff)]

get_indices(l1)
get_indices(l2)
get_indices(l3)

rawDescription: Getting indices of sequential chunks of a list


code:
def delete(self):
    files = WidgetFile.objects.filter(widget=self)
    if files:
        for file in files:
            file.delete()
    super(Widget, self).delete()

rawDescription: How do I override delete() on a model and have it still work with related deletes

description: Override delete() on a model and have it still work with related deletes


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

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

fig = plt.figure()
plt.plot(t,s)
#plt.show()
plt.draw()
plt.pause(1) # <-------
raw_input("<Hit Enter To Close>")
plt.close(fig)

rawDescription: How to close a python figure by keyboard input?

description: Close a python figure by keyboard input


rawDescription: Python iterates row data into another file


code:
sns.set_context("paper", font_scale=2)
sns.set_style("white")
plt.rc('text', usetex=False)
fig, ax = plt.subplots(figsize=(4,4))
sns.despine(left=True)

# mats=dict()
mats0=[1,1,1,1,1,2,3,3,2,3,3,3,3,3]
mats1=[3,3,3,3,3,4,4,4,5,6,1,1,2,3,4,5,5,5]
N=max(mats0 + mats1)

# binsize = np.arange(0,N+1,1)
binsize = N
B=['Thing1','Thing2']

ax.hist([mats0, mats1], binsize, histtype='bar',
        align='mid', label=B, alpha=0.4)#, rwidth=0.6)

ax.set_xlabel('My label')
ax.get_yaxis().set_visible(False)
# ax.set_xlim(0,N+1)
ax.legend()
plt.show()

rawDescription: Two seaborn distplots one same axis

description: Two seaborn distplots one same axis


code:
from django.utils.timezone import utc
utcnow = datetime.utcnow().replace(tzinfo=utc)

rawDescription: Django Datetime Query

description: Django Datetime Query


code:
directions = []
directions.append('forward')
#execute command here
directions.append('right')
#execute command here then turn car 180 degrees
#at this point directions = ['forward', 'right'] now you need to just pop the commands to execute
issueCommand(directions.pop()) #sends 'right'
issueCommand(directions.pop()) #sends 'forward'

rawDescription: Python2.7: Saving executed program steps and read them one by one


code:
ids = {}
with open('input1.txt') as fobj:
    for line in fobj:
        if line.strip():
            key, value = [x.strip() for x in line.split(',')]
            ids[key] = value

arrays = []
with open('input2.txt') as fobj:
    for line in fobj:
        if line.strip():
            values = [x.strip() for x in line.split(':')]
            arrays.append((values[2], values[3:]))

with open('output.txt', 'w') as fobj:
    for key, values in arrays:
        item = ids[key]
        fobj.write('Item={}; Var:{}\n'.format(item, key))
        fobj.write('read_Var:read_{}: Get_Data: {}\n\n'.format(item.lower(),
                                                            ':'.join(values)))

rawDescription: How to compare two different columns data regardless the order in different text files?

description: Compare two different columns data regardless the order in different text files


code:
def parse_main_page(self, response):
    item = MyItem()
    item['main_url'] = response.url

    url1 = response.xpath('//a[@class="link1"]/@href').extract()[0]
    request1 = scrapy.Request(url1, callback=self.parse_page1)

    url2 = response.xpath('//a[@class="link2"]/@href').extract()[0]
    request2 = scrapy.Request(url2, callback=self.parse_page2)

    url3 = response.xpath('//a[@class="link3"]/@href').extract()[0]
    request3 = scrapy.Request(url3, callback=self.parse_page3)

    request.meta['item'] = item
    request.meta['requests'] = [request2, request3]
    return request1

def parse_page1(self, response):
    item = response.meta['item']
    item['data1'] = response.xpath('//div[@class="data1"]/text()').extract()[0]

    return request.meta['requests'].pop(0)

def parse_page2(self, response):
    item = response.meta['item']
    item['data2'] = response.xpath('//div[@class="data2"]/text()').extract()[0]

    return request.meta['requests'].pop(0)

def parse_page3(self, response):
    item = response.meta['item']
    item['data3'] = response.xpath('//div[@class="data3"]/text()').extract()[0]

    return item

rawDescription: Python Scrapy, return from child page to carry on scraping


code:
from PIL import Image

def iter_frames(im):
    try:
        i = 0
        while 1:
            im.seek(i)
            frame = im.copy()
            if i == 0:
                # Save pallete of the first frame
                palette = frame.getpalette()
            else:
                # Copy the pallete to the subsequent frames
                frame.putpalette(palette)
            yield frame
            i += 1
    except EOFError:  # End of gif
        pass

im = Image.open('animated.gif')
middle_frame_pos = int(im.n_frames / 2)
durations = []

for i, frame in enumerate(iter_frames(im)):
    if i == middle_frame_pos:
        middle_frame = frame.copy()

    try:
        durations.append(frame.info['duration'])
    except KeyError:
        pass

middle_frame.save('middle_frame.png', **frame.info)

duration = float("{:.2f}".format(sum(durations)))
print('Total duration: %d ms' % (duration))

rawDescription: Imagemagick & Pillow generate malformed GIF frames


rawDescription: Pandas WHERE clause for string index?

description: Pandas WHERE clause for string index


code:
with open('text.csv') as text:
    # iterate the list except for the title line and grab desired items
    data = [a for a, b, c in list(csv.reader(text))[1:] if float(b) > 0]

rawDescription: How to read a .csv file specific items that hold this contrait?

description: Read a .csv file specific items that hold this contrait


code:
import os,sys
import pygame as pg

DIRECTDICT = {pg.K_LEFT  : (-1, 0),
          pg.K_RIGHT : ( 1, 0),
          pg.K_UP    : ( 0,-1),
          pg.K_DOWN  : ( 0, 1)}

class Player:

    def __init__(self,rect,speed):
          self.rect = pg.Rect(rect)
          self.speed = speed
          self.movement = [0,0]
          self.make_image()
    def make_image(self):

         self.image = pg.Surface((self.rect.size)).convert_alpha()
         self.image.fill((0,0,0,0))
         pg.draw.ellipse(self.image,(0,0,0),(1,1,self.rect.size[0]-2,self.rect.size[1]-2))
         pg.draw.ellipse(self.image,(255,0,0),(6,6,self.rect.size[0]-12,self.rect.size[1]-12))
    def update(self,Surf):

        self.rect.move_ip(self.movement)
        self.draw(Surf)

    def draw(self,Surf):
        Surf.blit(self.image,self.rect)

def quit_game():

     pg.quit();sys.exit()

state = 0
points = []
def game(Player):
    global state
    global points
    keys = pg.key.get_pressed()
    for event in pg.event.get():
        if event.type == pg.QUIT or keys[pg.K_ESCAPE]:
            quit_game()
        ### change state when space is pressed
        if event.type == pg.KEYDOWN and event.key == pg.K_SPACE:
            if state == 0:
                state = 1
            elif state == 1:
                state = 2
            else:
                ### clear the points list
                state = 0
                points = []
    Player.movement = [0,0]
    for key in DIRECTDICT:
        if keys[key]:
            for i in (0,1):
                Player.movement[i] += DIRECTDICT[key][i]*Player.speed

### helper method to get each element of a list and each previous element
def offset(iterable):
    prev = None
    for elem in iterable:
        yield prev, elem
        prev = elem

def main(Surf,Player):
       global state
       global points
       game(Player)
       Surf.fill((255,255,255))
       Player.update(Surf)
       ### in state 1, start "collecting" the player position
       if state == 1:
           points.append(Player.rect.center)
       ### in state 1 and 2, draw the line
       if state in (1, 2):
           for p1, p2 in offset(points):
                if p1 and p2:
                   pg.draw.line(Surf, (255,0,0), p1, p2)
       pg.display.update()

if __name__ == "__main__":
      os.environ['SDL_VIDEO_CENTERED'] = '1'
      Surface = pg.display.set_mode((500,500))
      pg.init()
      Myclock = pg.time.Clock()
      Myplayer = Player((250,250,100,100),3)
      while 1:
              main(Surface,Myplayer)
              Myclock.tick(60)

rawDescription: Make a line based on ball movement in pygame


code: getattr(args, 'inputfile.txt')

rawDescription: How to access a python argparse argument with a dot in the name

description: Access a python argparse argument with a dot in the name


code:
soldier = soldier()
soldier.x() # should return the soldiers x value.

rawDescription: How to pass values from pygame sprite group

description: Pass values from pygame sprite group


code:
import bisect
import datetime as dt

def get_quarter_begin():
    today = dt.date.today()

    qbegins = [dt.date(today.year, month, 1) for month in (1,4,7,10)]

    idx = bisect.bisect(qbegins, today)
    return str(qbegins[idx-1])

rawDescription: Python get first and last day of current calendar quarter


code:
objects = Entity.objects.filter(active=True,
                                key__is_valid=True,
                                user__profile__profile_id__isnull=False)

rawDescription: Selecting data from few relational tables based on few conditions in Django


code:
class Game:
    def __init__(self):
        self.name = raw_input("What is your name?\n")
        print("Hello " + self.name)
        self.ask()

    def ask(self):
        askplay = raw_input("Would you like to play a game? Yes or No?\n").lower()
        if askplay == "yes":
            self.game()
        elif askplay == "no":
            print("That's alright. Thanks for hanging out, though. Bye!")
        else:
            print("Sorry, I didn't get that. Please try again.")
            self.ask()

    def game(self):
        self.charchoose = raw_input("What will be your character " + self.name + ": "
            "Mage, Wizard or Knight?\n")
        print("You chose " + self.charchoose)
        self.path()

    def path(self):
        pathchoose = raw_input("You are a " + self.charchoose + " "
            "who was walking down Tranversia and came across a three-way road. "
            "Which on will you choose? Land, Sea or Clouds\n").lower()
        self.confirmpath(pathchoose)

    def confirmpath(self, pathchoose):
        confirmpaths = raw_input("You chose " + pathchoose + ". "
            "Are you sure you want to continue? Yes or No?\n").lower()
        self.pathcond(confirmpaths, pathchoose)

    def pathcond(self, confirmpaths, pathchoose):
        if confirmpaths == "no":
            self.path()
        if confirmpaths == "yes":
            print("Good choice, you win!")
        else:
            print("Sorry, we didn't get that. Can you answer again, please?")
            self.confirmpath(pathchoose)

Game()

rawDescription: How to access nested function globally in Python 2.7

description: Access nested function globally in Python 2.7


rawDescription: How does exec("dir /w"); function work in imageJ?


code: [[item]+sub_list for item,sub_list in lista]

rawDescription: list of (string, some_list) tuples to list of [string, <items from some_list>] lists

description: List of (string, some_list) tuples to list of [string, <items from some_list>] lists


code:
from django.db import connection
cursor = connection.cursor()
cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
result = cursor.fetchall()

rawDescription: Create tuple from Django Raw Query Set

description: Create tuple from Django Raw Query Set


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

x, y = np.random.random((2, 100))*8 - 4
points = np.column_stack([x, y])
verts = np.array([[-1, -1, 2, 2, ], [4, 1, -2, 4]]).T
path = mpath.Path(verts)
points_inside = points[path.contains_points(points)]

plt.figure()
plt.scatter(x, y)
plt.plot([-1, -1, 2, 2, ], [4, 1, -2, 4], color='r', linewidth=1, linestyle='--')
plt.scatter(points_inside[:,0], points_inside[:,1], c='r', s=50)
plt.xlim(-4,4)
plt.ylim(-4,4)
plt.show()

rawDescription: Identify and count points inside a user defined segment


rawDescription: Split a string around any characters not specified


code: url('user', id=1)

rawDescription: Pylons Routes url_for for a map.resource


rawDescription: Going one directory behind using OS in Python


code:
import errno

write_str = "!"*1024*1024*5  # 5MB

output_path = sys.argv[1]

with open(output_path, "w") as f:
    while True:
        try:
            f.write(write_str)
            f.flush()
        except IOError as err:
            if err.errno == errno.ENOSPC:
                write_str_len = len(write_str)
                if write_str_len > 1:
                    write_str = write_str[:write_str_len/2]
                else:
                    break
            else:
                raise

rawDescription: Python Filling Up Disk

description: Python Filling Up Disk


code:
A = [0] * (N + 1)

for i, j, k in queries:
    A[i] += k
    A[j + 1] -= k

v, m = 0, 0
for k in A:
    v += k
    m = max(m, v)

return m

rawDescription: Find maximal element from range operations


code:
auth = client.factory.create('UserAuthentication')
auth.sApiKey = [api-key]
client.set_options(soapheaders=auth)

rawDescription: python soap suds authenticate to affiliatewindow

description: Python soap suds authenticate to affiliatewindow


code:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.audio import SoundLoader,Sound
from kivy.lang import Builder
Builder.load_string('''
<MenuPage>:
    BoxLayout:
        orientation:'vertical'
        Button:
            text:'song'
            on_press:root.plays()
''')

class MenuPage(Screen):
    M = SoundLoader.load('/home/hosein/Music/Man.mp3')

    def plays(self):
        if MenuPage.M.state == 'stop':
            MenuPage.M.play()
        else:
            MenuPage.M.stop()

sm = ScreenManager()
menu = MenuPage(name='menu')
sm.add_widget(menu)

class TestApp(App):
    def build(self):
        return sm

TestApp().run()

rawDescription: Play/stop music with classes in kivy

description: Play/stop music with classes in kivy


code:
np.argwhere(a1!=a2)
np.where(a1!=a2)

rawDescription: Obtaining indexes of changed data between two numpy arrays


code:
s = 'AGTAATGGCGATTGAGGGTCCACTGTCCTGGTAC'
[s[i:i+6] for i in range(len(s)-5)]

rawDescription: easy method for spliting substrings of a given length from a string

description: Easy method for spliting substrings of a given length from a string


code:
import wx
import wx.lib.newevent

(PageChangeEvent, EVT_PAGE_CHANGE) = wx.lib.newevent.NewEvent()

class Data:
    foo = None
    bar = None

class Page1(wx.Panel):
    def __init__(self, parent, data):
        wx.Panel.__init__(self, parent)
        self.parent = parent
        self.data = data

        sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(sizer)
        label = wx.StaticText(self, label="Page 1 - foo")
        self.foo = wx.TextCtrl(self)
        goto_page2 = wx.Button(self, label="Go to page 2")

        for c in (label, self.foo, goto_page2):
            sizer.Add(c, 0, wx.TOP, 5)

        goto_page2.Bind(wx.EVT_BUTTON, self.OnPage2)

    def OnPage2(self, event):
        self.data.foo = self.foo.Value
        wx.PostEvent(self.parent, PageChangeEvent(page=Page2))

class Page2(wx.Panel):
    def __init__(self, parent, data):
        wx.Panel.__init__(self, parent)
        self.parent = parent
        self.data = data

        sizer = wx.BoxSizer(wx.VERTICAL)
        self.SetSizer(sizer)
        label = wx.StaticText(self, label="Page 2 - bar")
        self.bar = wx.TextCtrl(self)
        goto_finish = wx.Button(self, label="Finish")

        for c in (label, self.bar, goto_finish):
            sizer.Add(c, 0, wx.TOP, 5)

        goto_finish.Bind(wx.EVT_BUTTON, self.OnFinish)

    def OnFinish(self, event):
        self.data.bar = self.bar.Value
        wx.PostEvent(self.parent, PageChangeEvent(page=finish))

def finish(parent, data):
    wx.MessageBox("foo = %s\nbar = %s" % (data.foo, data.bar))
    wx.GetApp().ExitMainLoop()

class Test(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        self.data = Data()
        self.current_page = None

        self.Bind(EVT_PAGE_CHANGE, self.OnPageChange)
        wx.PostEvent(self, PageChangeEvent(page=Page1))

    def OnPageChange(self, event):
        page = event.page(self, self.data)
        if page == None:
            return
        if self.current_page:
            self.current_page.Destroy()
        self.current_page = page
        page.Layout()
        page.Fit()
        page.Refresh()

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

rawDescription: Alternatives to a wizard

description: Alternatives to a wizard


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

width = 0.8

highPower   = [1184.53,1523.48,1521.05,1517.88,1519.88,1414.98,
               1419.34,1415.13,1182.70,1165.17]
lowPower    = [1000.95,1233.37, 1198.97,1198.01,1214.29,1130.86,
               1138.70,1104.12,1012.95,1000.36]

indices = np.arange(len(highPower))

plt.bar(indices, highPower, width=width,
        color='b', label='Max Power in mW')
plt.bar([i+0.25*width for i in indices], lowPower,
        width=0.5*width, color='r', alpha=0.5, label='Min Power in mW')

plt.xticks(indices+width/2.,
           ['T{}'.format(i) for i in range(len(highPower))] )

plt.legend()

plt.show()

rawDescription: How to plot a superimposed bar chart using matplotlib in python?

description: Plot a superimposed bar chart using matplotlib in python


code:
import numpy
import csv

N = 126
M = 81

g = numpy.random.rand(N, M)

with open('test.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerow(['x', 'y', 'value'])
    for (n, m), val in numpy.ndenumerate(g):
        writer.writerow([n, m, val])

rawDescription: In Python: how to write a sparse matrix to a csv file?