code:
import csv
with open ('data.txt', 'r') as f:
    first_column = [row[0] for row in csv.reader(f,delimiter='\t')]
    print (first_column[1:])

rawDescription: What is the easiest way to read the text file delimited by tab in python?


code:
import matplotlib.pyplot as plt
import shapely
from shapely.geometry import Polygon
from descartes import PolygonPatch
import numpy as np

def create_tube(a,height):
    x_tube_up = np.linspace(-4,4,300)
    y_tube_up = a*x_tube_up**2 + height
    x_tube_down = np.flipud(x_tube_up)          #flip for correct definition of polygon
    y_tube_down = np.flipud(y_tube_up - 2)

    points_x = list(x_tube_up) + list(x_tube_down)
    points_y = list(y_tube_up) + list(y_tube_down)

    return Polygon([(points_x[i], points_y[i]) for i in range(600)])

def plot_coords(ax, ob):
    x, y = ob.xy
    ax.plot(x, y, '+', color='grey')

area_1 = Polygon()          #First area, a MultiPolygon object
for h in [-5, 0, 5]:
    area_1 = area_1.union(create_tube(2, h))

area_2 = Polygon()
for h in [8, 13, 18]:
    area_2 = area_2.union(create_tube(-1, h))

solution = area_1.intersection(area_2)      #What I was looking for

##########  PLOT  ##########

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

for tube in area_1:
    plot_coords(ax, tube.exterior)
    patch = PolygonPatch(tube, facecolor='g', edgecolor='g', alpha=0.25)
    ax.add_patch(patch)

for tube in area_2:
    plot_coords(ax, tube.exterior)
    patch = PolygonPatch(tube, facecolor='m', edgecolor='m', alpha=0.25)
    ax.add_patch(patch)

for sol in solution:
    plot_coords(ax, sol.exterior)
    patch = PolygonPatch(sol, facecolor='r', edgecolor='r')
    ax.add_patch(patch)

plt.show()

rawDescription: Area intersection in Python

description: Area intersection in Python


code:
from django.contrib.gis.geos import Point
Point(0,1).wkt

rawDescription: get Well Known Text from lat long

description: Get Well Known Text from lat long


code:
import urllib
url_base = "https://maps.googleapis.com/maps/api/place/search/json?"
params = urllib.urlencode(
    {'location': '{},{}'.format(r['lat'], r['lng']),
     'radius': 500,
     'types': 'food|doctor',
     'sensor': 'false',
     'key': YOUR_API_KEY,
     'pagetoken': ''
     })
url = url_base + params

rawDescription: how to format this string with % arguments according to PEP8

description: Format this string with % arguments according to PEP8


code:
def score(s, d):
    included = [d[word][0] for word in d if word in s]
    return sum(included) / float(len(included))

rawDescription: Function for averages of tuples in a dictionary


code:
#Define the board
row = int(input("Please enter # of rows: ")) #User input Rows
column = int(input("Please enter # of columns: ")) #User input Columns

board = [] #empty board
space = ' '
p1 = 'x'
p2 = 'o'

#create board based on user input
for i in range(0,row):
    board.append([])
    for j in range(0, column):
        board[i].append(space)

print(board)

#print board with character decorations
for i in board:
    line=''
    print('+'+'-+'*len(i))
    for j in range(len(i)):
        line = line + '|'+i[j]
    line = line + '|'
    print(line)
print('+'+'-+'*len(i))

print(len(board))

while True:
    #User input column
    myC = int(input("Player 1, choose your column: "))

    i = len(board)-1
    x = len(board)-1
    while i >= 0:
        if board[x][myC] == space:
            i = i+1
            board[x][myC] = 'x'
            break
        # Find last empty row for new piece
        elif board[x][myC] == p1 or p2:
            for j in range(x-1,-1,-1):
                if board[j][myC] == space:
                    x = j
                    break

            i = i+1
            #x = x - 1
            print(x)
            board[x][myC] = 'x'
            break

    # print the board!
    for i in board:
        line=''
        print('+'+'-+'*len(i))
        for j in range(len(i)):
            line = line + '|'+i[j]
        line = line + '|'
        print(line)
    print('+'+'-+'*len(i))

    #Computer input column
    from random import randint
    theC = randint(0, len(board)-1)
    print("Computer's Turn: Column " , theC)

    i = len(board)-1
    x = len(board)-1
    while i >= 0:
        if board[x][theC] == space:
            board[x][theC] = 'o'
            i = i+1
            break
        # Find last empty row for new piece
        elif board[x][theC] == p1 or p2:
            for j in range(x-1,-1,-1):
                if board[j][theC] == space:
                    x =j
                    break
            i = i+1
            #x = x - 1
            print(x)
            board[x][theC] = 'o'
            break

    # print the board!
    for i in board:
        line=''
        print('+'+'-+'*len(i))
        for j in range(len(i)):
            line = line + '|'+i[j]
        line = line + '|'
        print(line)
    print('+'+'-+'*len(i))

rawDescription: Connect 4 Like Game

description: Connect 4 Like Game


rawDescription: Get two numbers in regex

description: Get two numbers in regex


code:
import os, sys

def fck_handler(environ, start_response):
    path = environ['PATH_INFO']
    if path.endswith(('upload.py', 'connector.py')):
        sys.path.append('/#correct_path_to#/fckeditor/editor/filemanager/connectors/py/')
        if path.endswith('upload.py'):
            from upload import FCKeditorQuickUpload
            conn = FCKeditorQuickUpload(environ)
        else:
            from connector import FCKeditorConnector
            conn = FCKeditorConnector(environ)
        try:
            data = conn.doResponse()
            start_response('200 Ok', conn.headers)
            return data
        except:
            start_response("500 Internal Server Error",[("Content-type","text/html")])
            return "There was an error"
    else:
        sys.path.append('/path_to_your_django_site/')
        os.environ['DJANGO_SETTINGS_MODULE'] = 'your_django_site.settings'
        import django.core.handlers.wsgi
        handler = django.core.handlers.wsgi.WSGIHandler()
        return handler(environ, start_response)

application = fck_handler

rawDescription: How do you use FCKEditor's image upload and browser with mod-wsgi?

description: Use FCKEditor's image upload and browser with mod-wsgi


code:
# Put this after your existing code
newline = doc.createTextNode('\n')
calcSequence.insertBefore(newline, entrys[2])

rawDescription: minidom appendchild/insertBefore

description: Minidom appendchild/insertBefore


code:
import struct
struct.unpack('H', struct.pack('h', number))

rawDescription: How to get a 16bit Unsigned integer in python

description: Get a 16bit Unsigned integer in python


code:
def perform( fun, *args ):
    fun( *args )

def action1( args ):
    something

def action2( args ):
    something

perform( action1 )
perform( action2, p )
perform( action3, p, r )

rawDescription: Passing functions with arguments to another function in Python?


code: print(sorted(sellGuide, reverse = True)[0])

rawDescription: Assignment: Python 3.3: How to call an instance from a class through user-input


rawDescription: How to set the default item of a QComboBox

description: Set the default item of a QComboBox


code:
def wrapper(*args, **kwargs):
    print('inside wrapper')
    return func(*args, **kwargs)

rawDescription: Tab completion of decorated functions in IPython Notebook


code:
import dis
def foo():
    if seconds > 24*60*60:
        pass
dis.dis(foo)

rawDescription: Are simple hardcoded arithmetics cached/compiled away?


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

G = nx.Graph()
G.add_edges_from(
    [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
     ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
           'D': 0.5714285714285714,
           'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

nx.draw(G, cmap=plt.get_cmap('jet'), node_color=values)
plt.show()

rawDescription: Draw different color for nodes in networkx based on their node value


code:
user_answer = raw_input("> ")
if user_answer == 'a':
    player_pos -= 1
elif user_answer == 'd':
    player_pos += 1

rawDescription: Python: raw_input asks for input once the first time, then twice


code:
existing_set = {os.path.basename(f) for f in existing_list}  # set comprehension, python2.7+
# alternatively:  set(os.path.basename(f) for f in existing_list)

remaining_list = [f for f in all_list if f not in existing_set]

rawDescription: Fastest way of comparison of string elements in Python


code:
with Pool(processes=4) as pool:
  pool.map(my_func, itertools.product(Range, repeat=8))

rawDescription: Evaluating a function parallely using itertools product


rawDescription: Iterate through parts of a string

description: Iterate through parts of a string


code:
# get our initial input:
n = input()
result = int(n)

# subtract the rest of the user's inputs:
for x in range(9):
    n = input()
    result -= int(n)

# ... do something with the result ...

rawDescription: Python : Subtracting inside an array

description: Python : Subtracting inside an array


code:
...
response = ""
while True:
    data = mysock.recv(3000)
    if len(data) < 1: break
    response += data

iterator = iter(response.split("\n"))

for line in iterator:
    if not line.strip():  # empty line
        break

body = "\n".join(iterator)  # put the rest of the data in a string

rawDescription: Regular Expression: (or not) Looking to print only data after the header


code:
def get_element(node):
  # for XPATH we have to count only for nodes with same type!
  length = len(list(node.previous_siblings)) + 1
  if (length) > 1:
    return '%s:nth-child(%s)' % (node.name, length)
  else:
    return node.name

def get_css_path(node):
  path = [get_element(node)]
  for parent in node.parents:
    if parent.name == 'body':
      break
    path.insert(0, get_element(parent))
  return ' > '.join(path)

soup = bs4.BeautifulSoup('

bla
')
assert get_css_path(soup.i) == 'div:nth-child(2) > strong > i'

rawDescription: BeautifulSoup extract XPATH or CSS Path of node


code:
from django.db.models import Min
Choclate.objects.filter().values_list('name').annotate(Min('price')).order_by('price')[0]

rawDescription: Get minimum value field name using aggregation in django


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

x, y, z = np.random.random((3, 10))

fig, ax = plt.subplots()
scat = ax.scatter(x, y, c=z, s=200, cmap='gray_r')
fig.colorbar(scat)
plt.show()

rawDescription: How to draw a 2-D graph with 3-D data (x, y and z arrays given) with color coded Z axes representation in Matplotlib?

description: Draw a 2-D graph with 3-D data (x, y and z arrays given) with color coded Z axes representation in Matplotlib


code:
cells = npar.db.execute("SELECT cellid FROM data "
                        "WHERE block > 1 "
                        "AND date >= ? "
                        "GROUP BY cellid "
                        "HAVING COUNT(*) = 3", (files[0][1],)).fetchall()

rawDescription: Is there a better way to do this?

description: Is there a better way to do this


rawDescription: Comments on this assumption about running on dev server vs a real instance in app engine (python)?


code:
results = {key: min(values, key=lambda x:x[-1].f())
           for key, values in myD.iteritems()}

rawDescription: return object from dictionary of nested lists when a condition (python)

description: Return object from dictionary of nested lists when a condition (python)


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title='Select 4 points')

xy = plt.ginput(4)
x, y = zip(*xy)

ax.fill(x, y, color='lightblue')
ax.plot(x, y, ls='', mfc='red', marker='o')

plt.show()

rawDescription: Preventing execution until points are selected on matplotlib graph


code: r = '(\\w+) access = (\\w+)\\s+Vol ID = (\\w+)\\s+Snap ID = (\\w+)\\s+Inode = (\\w+)\\s+IP = ((\\d|\\.)+)\\s+UID = (\\w+)\\s+Full Path = (\\S+)\\s+Handle ID: (\\S+)\\s+Operation ID: (\\S+)\\s+Process ID: (\\d+)\\s+Image File Name: (\\w+\\s+\\w+\\s+\\w+)\\s+Primary User Name: (\\S+)\\s+Primary Domain: (\\S+)\\s+Primary Logon ID: (.....\\s+......)\\s+Client User Name: (\\S+)\\s+Client Domain: (\\S+)\\s+Client Logon ID: (\\S+)\\s+Accesses: (.*)'

rawDescription: Python Beginner - Build a regex with optionnal characters


code:
from docopt import docopt
usage = """
usage: prog.py command [--test]
       prog.py another [--test]

--test  Perform the test."""
docopt(usage, argv='command --test')
docopt(usage, argv='--test command')

rawDescription: Python: argument parser that handles global options to sub-commands properly


code:
...
RunningSumA = MyDataFrame.groupby([UniqueID])[Var1].cumsum().reset_index(name="suma")
RunningSumB = MyDataFrame.groupby([UniqueID])[Var2].cumsum().reset_index(name="sumb")
...

rawDescription: Renaming series column names after applying function and returning mutiple dataframes


code:
#! /usr/bin/env python
import urllib2
import StringIO
import gzip

baseURL = "https://www.kernel.org/pub/linux/docs/man-pages/"
filename = "man-pages-3.34.tar.gz"
outFilePath = "man-pages-3.34.tar"

response = urllib2.urlopen(baseURL + filename)
compressedFile = StringIO.StringIO()
compressedFile.write(response.read())
#
# Set the file's current position to the beginning
# of the file so that gzip.GzipFile can read
# its contents from the top.
#
compressedFile.seek(0)

decompressedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb')

with open(outFilePath, 'w') as outfile:
    outfile.write(decompressedFile.read())

rawDescription: Download and decompress gzipped file in memory?


code:
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/dim_lights/<room>')
def dim_lights(**kwargs):
    dim_lights_for_room(kwargs['room'])

rawDescription: Python http server interaction

description: Python http server interaction


code:
import re
text = """foo bar baz
/*
       * Copyright blah blah blha blah
       * blah blah blah blah
       * 2008 blah blah blah @ org
       */"""
rx = re.compile(r"/[^/]*/", re.DOTALL)
mo = rx.search(text)
text[mo.start(): mo.end()]

rawDescription: Regular Expression To Find C Style Comments


code: data1['E'] = [row for row in data1[data1.columns[0:3]].values]

rawDescription: Concatenate columns and create a list

description: Concatenate columns and create a list


code:
from PIL import Image

frame = Image.open('frame.png')
img = Image.open('image.jpg')

img_dest = img.copy().convert('RGBA')
img_dest.paste(frame, (0, 0, 100, 100), frame)

img_dest = img_dest.convert('RGB') # Optional, to remove transparency info

img_dest.save('output.png')

rawDescription: PIL - make 1 PNG from JPG and PNG frame

description: PIL - make 1 PNG from JPG and PNG frame


code:
def write(self, file, encoding="us-ascii"):
    assert self._root is not None
    if not hasattr(file, "write"):
        file = open(file, "wb")
    if not encoding:
        encoding = "us-ascii"
    elif encoding != "utf-8" and encoding != "us-ascii":
        file.write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
    self._write(file, self._root, encoding, {})

rawDescription: Add xml metatag on python 2.54

description: Add xml metatag on python 2.54


code:
from datetime import datetime

dates = ['2014-01-01', '2014-03-07']
date_objects = [datetime.strptime(date, '%Y-%m-%d').date()
                     for date in dates]

rawDescription: Convert 'yyyy-mm-dd' string to 3-tuple datetime objects in python 2.7


code:
import csv

with open('test.csv', 'rb') as f, open('test1.csv', 'wb') as o:
    reader = csv.reader(f)
    writer = csv.writer(o)

    # skip the header
    next(reader, None)

    # print the new header
    writer.writerow(['inches'])

    for row in reader:
        newVal = float(row[0]) * 0.393701
        writer.writerow([newVal])

rawDescription: How to output calculations in python?

description: Output calculations in python


code: from django.conf import settings

rawDescription: Recommended way of accessing BASE_DIR in Django


code:
from pytz import timezone
right_time = utc_from_db.astimezone(timezone('Europe/Berlin'))

rawDescription: How to get time from PostgreSQL in the same TZ, which was initialy used while uploading to DB, instead of UTC?

description: Get time from PostgreSQL in the same TZ, which was initialy used while uploading to DB, instead of UTC


code:
fields = ("field1", "field2", "field3")

output = [[k] + [mydict[k].get(x) for x in fields] for k in mydict]

rawDescription: Pythonic way to flatten a dictionary into a list using list comprehension


code:
f_values = sample_data[[sample_data[:, -1] == c], f]
#                      ^                       ^

rawDescription: numpy returns 1d array and 2d array for same code

description: Numpy returns 1d array and 2d array for same code


code:
mask = np.random.binomial(1, 0.5, size=10).astype(bool); mask
idx = np.flatnonzero(mask); idx
np.bincount(idx, minlength=len(mask)).astype(bool)

rawDescription: How do I obtain a mask, reversing numpy.flatnonzero?

description: Obtain a mask, reversing numpy.flatnonzero


rawDescription: How to get a value from a Pandas DataFrame and not the index and object type

description: Get a value from a Pandas DataFrame and not the index and object type


code:
response = another_view(request)
rendered_html_text = response.content

rawDescription: geting rendered html text in django

description: Geting rendered html text in django


code:
import pygame, sys, time
from pygame.locals import *

pygame.init()
WINDOWWIDTH = 200
WINDOWHEIGHT = 300
screen = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Animation')

DOWNLEFT = 1
DOWNRIGHT = 3
UPLEFT = 7
UPRIGHT = 9

MOVESPEED = 1

BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

b1 = {'rect':pygame.Rect(0, 50, 25, 25), 'color':RED, 'dir':DOWNRIGHT}
b2 = {'rect':pygame.Rect(0, 100, 25, 25), 'color':GREEN, 'dir':DOWNRIGHT}
b3 = {'rect':pygame.Rect(0, 150, 25, 25), 'color':BLUE, 'dir':DOWNRIGHT}
blocks = [b1, b2, b3]

while True:
# check for the closing of the 'x' button
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
    screen.fill(BLACK)
    pygame.draw.line(screen,BLUE,(150,0),(150,150),5)

    for b in blocks:
    #moves the blocks
        if b['dir'] == DOWNLEFT:
            b['rect'].left -= MOVESPEED
            b['rect'].top += MOVESPEED
        if b['dir'] == DOWNRIGHT:
            b['rect'].left += MOVESPEED
            b['rect'].top += MOVESPEED
        if b['dir'] == UPLEFT:
            b['rect'].left -= MOVESPEED
            b['rect'].top -= MOVESPEED
        if b['dir'] == UPRIGHT:
            b['rect'].left += MOVESPEED
            b['rect'].top -= MOVESPEED

    # check if the block has move out of the window
        if b['rect'].top < 0:
        # block has moved past the top
            if b['dir'] == UPLEFT:
                b['dir'] = DOWNLEFT
            if b['dir'] == UPRIGHT:
                b['dir'] = DOWNRIGHT
        if b['rect'].bottom > WINDOWHEIGHT:
        # block has moved past the bottom
            if b['dir'] == DOWNLEFT:
                b['dir'] = UPLEFT
            if b['dir'] == DOWNRIGHT:
                b['dir'] = UPRIGHT
        if b['rect'].left < 0:
        # block has moved past the left side
            if b['dir'] == DOWNLEFT:
                b['dir'] = DOWNRIGHT
            if b['dir'] == UPLEFT:
                b['dir'] = UPRIGHT
        if b['rect'].right > WINDOWWIDTH:
        # block has moved past the right side
            if b['dir'] == DOWNRIGHT:
                b['dir'] = DOWNLEFT
            if b['dir'] == UPRIGHT:
                b['dir'] = UPLEFT
        if b['dir'] == UPLEFT or b['dir'] == DOWNLEFT: # In this case it's rather easy to check for the exact conditions when direction changes should be made. Being the movement speed is only 1, at some point the b['rect'].right/left will be exactly 150. It's easier to check for that than deal with greater than less than problems which tend to only work for one way. If movement was higher than one you'd have to switch to short ranges instead.
            if b['rect'].left == 150 and b['rect'].top > 0 and b['rect'].top < 150:
                if b['dir'] == DOWNLEFT:
                    b['dir'] = DOWNRIGHT
                if b['dir'] == UPLEFT:
                    b['dir'] = UPRIGHT

        if b['dir'] == DOWNRIGHT or b['dir'] == UPRIGHT:
            if b['rect'].right == 150 and b['rect'].top < 150:
                if b['dir'] == DOWNRIGHT:
                    b['dir'] = DOWNLEFT
                if b['dir'] == UPRIGHT:
                    b['dir'] = UPLEFT
        print(b['rect'].right)
        pygame.draw.rect(screen, b['color'], b['rect'])

    pygame.display.update()
    time.sleep(0.00001)

rawDescription: Making a block bounce off a line in pygame


code: " or ".join("id = %d" % id for id in ids)

rawDescription: Join list of string in python with string %s replacement


code:
with open('products.csv',newline='') as f:
    reader = csv.reader(f, delimiter='\t')
    found = False
    for line in f:
        if code in line:
            print(line)
            found = True
            break
    if not found:
        f = open("reciepts","a")
        f.write(code)
        f.write("Product Not Found")
        f.close()

rawDescription: Unexpected Writing To A File

description: Unexpected Writing To A File


code:
re.match("([abc])", "abc").groups()
re.match("([abc]+)", "abc").groups()

rawDescription: The groups() method in regular expressions in Python


code:
import collections
import itertools

with open("file.dat") as f:
    tokens = itertools.chain.from_iterable(line.split() for line in f)
    numbers = itertools.imap(int, tokens)
    counts = collections.Counter(numbers)

for n in sorted(counts):
    print(n, counts[n])

rawDescription: counting and printing each number present in a file using python

description: Counting and printing each number present in a file using python


code:
random.shuffle(candidates)

min_candidate = min(candidates, key=usage_counts.get)

rawDescription: How to get the least used item?

description: Get the least used item


code:
def delayed_loader(*args, **kwargs):
    """
    Replace each real_* function with the corresponding function from either
    trans_real or trans_null (e.g. real_gettext is replaced with
    trans_real.gettext or trans_null.gettext). This function is run once, the
    first time any i18n method is called. It replaces all the i18n methods at
    once at that time.
    """
    #...

rawDescription: Where is the function 'real_ugettext' in django?


code:
import pandas as pd
dates = pd.DatetimeIndex(['2010-10-17', '2011-05-13', "2012-01-15"])
dates.year

rawDescription: Get year, month or day from numpy datetime64


code:
class infoClass(object):
    pass

def infoCollection(string_a, string_b, string_c):
    i = infoClass()
    i.string_a = string_a
    i.string_b = string_b
    i.string_c = string_c
    return i

rawDescription: Python pickle scross platform __dict__ attribute error


code: numpy.reshape(input_in_4D, (1800,3))

rawDescription: How to reshape 4d array to 2d array in numpy

description: Reshape 4d array to 2d array in numpy


rawDescription: Render an xml to a view

description: Render an xml to a view


code:
def getOutputs(s):
    keep = []
    for row_index in range(28):
        v = s.cell_value(row_index, 1)
        if v != "" :
            keep.append(v)
    return keep

rawDescription: Excel and lists with Python

description: Excel and lists with Python


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

xsize = 1000
ysize = 4000
data = np.loadtxt('data')
x, y, dz = data[:, 0], data[:, 1], data[:, 2]
dx, dy, z = np.ones(x.shape)*xsize, np.ones(x.shape)*ysize, np.zeros(x.shape)

fig = plt.figure()
ax = fig.gca(projection='3d')

ax.bar3d(x, y, z, dx, dy, dz, color='green')

plt.show()

rawDescription: 3-d Rectangles in Matplotlib

description: 3-d Rectangles in Matplotlib


code:
my_scope = {}
data = "var1 = {'id': '12345', 'name': 'John White'}"
exec(data, my_scope)
my_scope['var1']

rawDescription: How to extract variable name and value from string in python

description: Extract variable name and value from string in python


code:
import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt
np.random.seed(0)

x = np.random.normal(size=200)
y = np.random.normal(size=200)
v = np.sqrt(x**2+y**2)

xg, yg = np.mgrid[x.min():x.max():100j, y.min():y.max():100j]
vg = griddata((x, y), v, (xg, yg), method='cubic')
plt.contourf(xg, yg, vg)
plt.scatter(x, y, c=v)
plt.show()

rawDescription: Countour lines Matplotlib Python

description: Countour lines Matplotlib Python


code:
from math import log10, floor

def convert(self, x, ROUND=0):

    conv = []

    for _ in range(x.size[0]):
        lst = x._data[_::x.size[0]].tolist()

        if ROUND is not 0:
            lst = [self.round_sig(elem, ROUND) if elem != 0 and
                   elem == elem else elem for elem in lst]

        conv.append(lst)

    return conv

def round_sig(self, x, sig=2):
    return round(x, sig-int(floor(log10(abs(x))))-1)

rawDescription: Convert matlab.double array to python array


code:
step1 = Popen(['ip','addr','show','br0'],stdout=PIPE)
step2 = Popen(['grep','inet6'],stdout=PIPE,stdin=step1.stdout)
step3 = Popen(['sed','-e','/fe80/d','-e','s/ *inet6 *//g','-e','s/\/64.*$//g'],stdout=PIPE,stdin=step2.stdout)
step4 = Popen(['tail','-n1'],stdout=PIPE,stdin=step3.stdout)
step4.communicate()[0]

rawDescription: How to get the IPv6 address of an interface under linux

description: Get the IPv6 address of an interface under linux


code:
s = "There are LJFK$(#@$34)(,0,ksdjf apples in the (4,5)"
import re
list(map(int, re.findall(r'[0-9]+', s)))

rawDescription: How to map all numbers in a string to a list in Python?

description: Map all numbers in a string to a list in Python


code:
class MyType(object):
    def __init__(self, value):
        self.value = value
    def __bool__(self):
        return self.value != 0

rawDescription: How to define `bool` conversion for custom data type?

description: Define `bool` conversion for custom data type


rawDescription: How to unravel array?

description: Unravel array


code:
from datetime import date
from django.utils.timezone import now

def age_range(min_age, max_age):
    current = now().date()
    min_date = date(current.year - min_age, current.month, current.day)
    max_date = date(current.year - max_age, current.month, current.day)

    return user_profiles.filter(birthdate__gte=max_date,
                                birthdate__lte=min_date).order_by("birthdate")

rawDescription: How to query from the DB by age in Django when birthday is stored as year/month/day fields

description: Query from the DB by age in Django when birthday is stored as year/month/day fields


rawDescription: pandas - add a column with value based on exisitng one (bins, qcut)

description: Pandas - add a column with value based on exisitng one (bins, qcut)


code:
child = pexpect.spawn('scp foo myname@host.example.com:.')
child.expect ('Password:')
child.sendline (mypassword)

rawDescription: Python run shell command and emulate user input


code:
import fabric.api as fab
from fabric.network import disconnect_all
from contextlib import contextmanager

@context_manager
def ssh(settings):
    with settings:
         try:
            yield
         finally:
            disconnect_all()

def hostname(request, host='somehost', user='someuser', pw='secret'):
    with ssh(fab.settings(host_string=host, user=user, password=pw)):
         return fab.run('hostname')

rawDescription: how to call a remote fabric method in django

description: Call a remote fabric method in django


code:
import AppKit
path = os.path.expanduser('~/src/foo.xcodeproj/project.pbxproj')
d = AppKit.NSDictionary.dictionaryWithContentsOfFile_(path)

rawDescription: What data structure does Apple use for managing Xcode projects?


code:
def addFirstAndLast(x):
  return (x[0]+x[-1])/(1/len(x)+1) if x else 0

addFirstAndLast([])
addFirstAndLast([1])
addFirstAndLast([1,3])

rawDescription: addition of specific elements of a list python

description: Addition of specific elements of a list python


code:
from nltk.tokenize import regexp_tokenize

sent = "I like apple fruit but grape fruit more"
dict_list = ["apple fruit", "grape fruit"]
newdict = {}
for item in dict_list:
    dk = item.replace(" ", "_")
    newdict[item] = dk

for key, val in newdict.items():
    if key in sent:
        sent = sent.replace(key, val)

res = regexp_tokenize(sent, pattern='\S+')
print(res)

rawDescription: Can you use dictionary( text) to regex tokenization?

description: Use dictionary( text) to regex tokenization


code:
import logging
logger = logging.getLogger(__name__)

class QtHandler(logging.Handler):

    def __init__(self):
        logging.Handler.__init__(self)

    def emit(self, record):
        record = self.format(record)
        XStream.stdout().write("{}\n".format(record))

handler = QtHandler()
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

rawDescription: How to Redirect Logger Output into PyQt Text Widget


code:
#!/usr/bin/env python
import numpy as np

a = np.fromfile(open('file', 'r'), sep='\n')
# [ 0.     0.005  0.124  0.     0.004  0.     0.111  0.112]

# You can set arbitrary bin edges:
bins = [0, 0.150]
hist, bin_edges = np.histogram(a, bins=bins)
# hist: [8]
# bin_edges: [ 0.    0.15]

# Or, if bin is an integer, you can set the number of bins:
bins = 4
hist, bin_edges = np.histogram(a, bins=bins)
# hist: [5 0 0 3]
# bin_edges: [ 0.     0.031  0.062  0.093  0.124]

rawDescription: Howto bin series of float values into histogram in Python?


code:
bucket.put('path/to/your/pdf/object/on/s3',
           pdf_object_bytes,
           headers={'Content-Disposition': 'attachment;filename=test.pdf'})

rawDescription: how to add http header to a pdf file using python?

description: Add http header to a pdf file using python


code:
def flatten(lst):
    if not isinstance(lst,list):
        return [lst]
    else:
        return reduce(lambda x,y:x+y,[flatten(x) for x in lst],[])

rawDescription: Is there a functional way to do this?

description: Is there a functional way to do this


code:
class MyClass(object):
    def __del__(self):
        object.__del__(self)
        dosomething()

rawDescription: How to do something when a python object is destroyed?

description: Do something when a python object is destroyed


code:
Text_in=Setdocsprj.objects.all()
res1=Text_in.filter(name=u'Template name')
f1=open('test_gen.txt',"wb")
for j in res1:
    t=j.doc
    f1.write(t)
f1.close()

rawDescription: Cant get the template from DB

description: Cant get the template from DB


code: request.args.get('foo', '');

rawDescription: Using Flask to emulate PHP page

description: Using Flask to emulate PHP page


code:
title = quest1.find_element_by_class_name("title").text
desc = quest1.find_element_by_class_name("desc").text
progress = quest1.find_element_by_class_name("progress").text

rawDescription: Extracting data from a find_element query (Python)


code:
end = Literal("\n").suppress()
firstLine = Literal("ABC") + SkipTo(end)
secondLine = Literal("DEF") + SkipTo(end)
line = ~secondLine + SkipTo(end)
test = firstLine + OneOrMore(line) + secondLine

test.searchString(myText)

rawDescription: python parsing a block of text betwen 2 known lines

description: Python parsing a block of text betwen 2 known lines


code:
sentence = "Tom's boat is blue"
mydict = { 'Tom': 'green' }
import re
re.sub("(\S+)'s boat is (\w+)", lambda m: "{}'s boat is actually {}".format(m.group(1), mydict[m.group(1)]), sentence)

rawDescription: How to do regex replace in Python using dictionary values, where key is another matched object from the same string

description: Do regex replace in Python using dictionary values, where key is another matched object from the same string


code:
binplace = np.digitize(avgs, bins) #Returns which bin an average belongs
binplace
np.where(binplace == 1)
np.where(binplace == 2)
avgs[np.where(binplace == 1)]

rawDescription: How to organize values in a numpy array into bins that contain a certain range of values?

description: Organize values in a numpy array into bins that contain a certain range of values


code:
import clr
clr.AddReference('Microsoft.DirectX.AudioVideoPlayback')
from Microsoft.DirectX import AudioVideoPlayback
mp3 = AudioVideoPlayback.Audio("C:\\myreallyfunky.mp3")
mp3.Play()

rawDescription: How to access DirectSound device info from Python?

description: Access DirectSound device info from Python


code:
def negate(func):
  def result(*args):
    return not func(*args)
  return result

rawDescription: How to pass a function as argument to another function and use the value returned by that function in python?

description: Pass a function as argument to another function and use the value returned by that function in python


code:
import glob

# reads all IS.T.BCA.* files into a list
files=glob.glob('IS.T.BCA.*')

# iterate over that list
for file in files:
    with open('IS.T.BCA.SomethingMore','r') as f:
        new=open('new.txt','w')
        ...
        ...

rawDescription: Find Files in Path and Read all Files starts with same pattern


code:
url = "http://www.cne.gob.ve/web/registro_electoral/firmantes.php"

params = {"nacionalidad":"V",
"cedula":"12345678"}

page = requests.get(url, params=params)
print(page.content)

rawDescription: Submiting Javascript Form and Scrap with Python


code:
class ColorAction(QtGui.QWidgetAction):
    colorSelected = QtCore.pyqtSignal(QtGui.QColor)

    def __init__(self, parent):
        QtGui.QWidgetAction.__init__(self, parent)
        widget = QtGui.QWidget(parent)
        layout = QtGui.QGridLayout(widget)
        layout.setSpacing(0)
        layout.setContentsMargins(2, 2, 2, 2)
        palette = self.palette()
        count = len(palette)
        rows = count // round(count ** .5)
        for row in range(rows):
            for column in range(count // rows):
                color = palette.pop()
                button = QtGui.QToolButton(widget)
                button.setAutoRaise(True)
                button.clicked[()].connect(
                    lambda color=color: self.handleButton(color))
                pixmap = QtGui.QPixmap(16, 16)
                pixmap.fill(color)
                button.setIcon(QtGui.QIcon(pixmap))
                layout.addWidget(button, row, column)
        self.setDefaultWidget(widget)

    def handleButton(self, color):
        self.parent().hide()
        self.colorSelected.emit(color)

    def palette(self):
        palette = []
        for g in range(4):
            for r in range(4):
                for b in range(3):
                    palette.append(QtGui.QColor(
                        r * 255 // 3, g * 255 // 3, b * 255 // 2))
        return palette

class ColorMenu(QtGui.QMenu):
    def __init__(self, parent):
        QtGui.QMenu.__init__(self, parent)
        self.colorAction = ColorAction(self)
        self.colorAction.colorSelected.connect(self.handleColorSelected)
        self.addAction(self.colorAction)
        self.addSeparator()
        self.addAction('Custom Color...')

    def handleColorSelected(self, color):
        print(color.name())

rawDescription: How to display color icons in menu, PyQt?

description: Display color icons in menu, PyQt


code:
haystack = np.array([[1, -1, 1, -1],
                     [1, 1, -1, 1],
                     [1, -1, 1, -1]])
needle = np.array([1, -1, 1, -1])
haystack.dot(needle)
np.sum(haystack.dot(needle) == len(needle))

rawDescription: Python: Find number of occurrences of given array within two-dimensional array


code:
class Article(object):
    def __init__(self, name, available):
        self._name = name
        self.available = available

    @property
    def name(self):
        return self._name

rawDescription: How should I expose read-only fields from Python classes?


code:
import re
str = "<20"
output = re.sub(r'<(?=\d)', r'\r\n<', str)
output

rawDescription: Python replace using regex

description: Python replace using regex


code:
import time

while True:
    time.sleep(10)
sched.shutdown()

rawDescription: APScheduler not starting?

description: APScheduler not starting


code:
import random

playing = True

while playing:
    # Generate a new arithmetic problem.
    a = random.randint(1, 50)
    b = random.randint(1, 50)
    solution = a + b
    print('\nWhat is %d + %d? (to quit, enter nothing)' % (a, b))

    # Keep reading input until the reply is empty (to quit) or the right answer.
    while True:
        reply = input()
        if reply.strip() == '':
            playing = False
            break
        if int(reply) == solution:
            print('Correct. Good job!')
            break
        else:
            print('Wrong. Try again.')

print('Thank you for playing. Goodbye!')

rawDescription: How to generate a new arithmetic exercise in a quiz game

description: Generate a new arithmetic exercise in a quiz game


code:
def minimum_distance(p1, p2):

    i1, i2 = int(p1[0]), int(p2[0])

    # if both x-coordinates are floats and they have the same integer part
    if i1 != p1[0] and i2 != p2[0] and i1 == i2:

        # find the decimal parts
        d1, d2 = p1[0] - i1, p2[0] - i2

        # find the smaller "C"
        x = min(d1 + d2, (1-d1) + (1-d2))

        # add the y distance to the "C" distance
        return abs(p1[1] - p2[1]) + x

    # repeat with the "y-coordinates are floats" case
    i1, i2 = int(p1[1]), int(p2[1])
    if i1 != p1[1] and i2 != p2[1] and i1 == i2:
        d1, d2 = p1[1] - i1, p2[1] - i2
        y = min(d1 + d2, (1-d1) + (1-d2))
        return abs(p1[0] - p2[0]) + y

    # simple case, return the Manhattan distance
    return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])

print(minimum_distance([0.4, 1], [0.9, 3]))
# 2.7

rawDescription: Find distance between 2 points on grid

description: Find distance between 2 points on grid


code:
import wx

class MyCheckBox(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Values', size=(490, 250))
        panel = wx.Panel(self, -1)

        positions = [(70, 55), (170, 55), (270, 55), (370, 55),
                     (70, 85), (170, 85), (270, 85), (370, 85)]

        values = ['a', 'a','a', 'a','a', 'a','a', 'a',]

        self.controls = []
        for pos, value in zip(positions, values):
           control = wx.TextCtrl(panel, -1, value=str(value),
                                 pos=pos, size=(60,25))
           self.controls.append(control)

        self.to_show = wx.TextCtrl(panel, -1, value='',
                                   pos=(90, 120), size=(290,25))

        self.btnOK = wx.Button(panel, label="OK", pos=(190, 180))
        self.Bind(wx.EVT_BUTTON, self.OnOK, self.btnOK)

    def OnOK(self, event):
        all_values = []
        for control in self.controls:
            all_values.append(control.GetValue())

        self.to_show.SetValue(str(all_values))

if __name__ == '__main__':
    app = wx.PySimpleApp()
    f = MyCheckBox()
    f.Show()
    app.MainLoop()

rawDescription: How to retrieve multiple numbers from TextCtrl?

description: Retrieve multiple numbers from TextCtrl


code:
try:
    var1, var2 = re.search(r"detail\/([a-z0-9\-]+)\/([a-z]+)", my_url).groups()
except AttributeError:
    var1 = var2 = ""

rawDescription: Extracting substring from URL using regex


code:
newbuttonname = username
newbuttonname = Tkinter.Button(win, text = newbuttonname,
    command = lambda name=username:click_one(name))

rawDescription: tkinter - get button name?

description: Tkinter - get button name


code:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np

m = Basemap(width=12000000,height=9000000,projection='lcc',
            resolution='c',lat_1=45.,lat_2=55,lat_0=50,lon_0=-107.)
m.drawcoastlines(linewidth=0.25)

data = 100*np.random.rand(10,10)
m.imshow(data, interpolation = 'none')

plt.show()

rawDescription: Offline heat map with map background

description: Offline heat map with map background


code:
import jsonpickle
import sqlalchemy.types as types

class JsonType(types.MutableType, types.TypeDecorator):
    impl = types.Unicode

    def process_bind_param(self, value, engine):
        return unicode(jsonpickle.encode(value))

    def process_result_value(self, value, engine):
        if value:
            return jsonpickle.decode(value)
        else:
            # default can also be a list
            return {}

rawDescription: sqlalchemy map object which contains dicts

description: Sqlalchemy map object which contains dicts


rawDescription: python - forward iteration / extending list of tuples

description: Python - forward iteration / extending list of tuples


code:
import pygame
from pygame import Surface
from pygame.locals import *
# Todo: remove font object from TextLine() , to TextWall(). Then share a list of font's with any line.

"""Example of multi-line text class, with alpha transparency."""
lorem = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed aliquet
tellus eros, eu faucibus dui. Phasellus eleifend, massa id ornare sodales, est urna
congue tellus, vitae varius metus nunc non enim. Mauris elementum, arcu vitae tempor euismod, justo turpis malesuada est, sed dictum nunc nulla nec mauris. Cras felis eros, elementum vitae sollicitudin in, elementum et augue. Proin eget nunc at dui congue pretium. Donec ut ipsum ut lacus mollis tristique. In pretium varius dui eu dictum.

Proin pulvinar metus nec mi semper semper. Pellentesque habitant morbi tristique
senectus et netus et malesuada fames ac turpis egestas. Proin in diam odio. Vestibulum
at neque sed ante sodales eleifend quis id dui. Mauris sollicitudin, metus a semper consectetur,
est lectus varius erat, sit amet ultrices tortor nisi id justo. Aliquam elementum vestibulum dui ut auctor. Mauris commodo sapien vitae augue tempus sagittis. Morbi a nibh lectus, sed porta nibh. Donec et est ac dui sodales aliquet tristique et arcu. Nullam enim felis, posuere vel rutrum eu, euismod a purus. Morbi porta cursus libero, id rutrum elit lacinia vitae.

In condimentum ultrices ipsum, ut convallis odio egestas et. Cras at egestas elit. Morbi
quis neque ligula. Sed tempor, sem at fringilla rhoncus, diam quam mollis nisi, vitae semper
mi massa sit amet tellus. Vivamus congue commodo ornare. Morbi et mi non sem malesuada rutrum. Etiam est purus, interdum ut placerat sit amet, tempus eget eros. Duis eget augue quis diam facilisis blandit. Ut vulputate adipiscing eleifend. """

class TextLine(object):
    # Manages drawing and caching a single line of text
    # You can make font size, .color_fg etc be properties so they *automatically* toggle dirty bool.
    def __init__(self, font=None, size=16, text="hi world"):
        self.font_name = font
        self.font_size = size
        self.color_fg = Color("white")
        self.color_bg = Color("gray20")

        self._aa = True
        self._text = text
        self.font = pygame.font.Font(font, size)
        self.screen = pygame.display.get_surface()

        self.dirty = True
        self.image = None
        self._render()

    def _render(self):
        # render for cache
        """no AA = automatic transparent. With AA you need to set the color key too"""
        self.dirty = False
        self.image = self.font.render(self._text, self.aa, self.color_fg)
        self.rect = self.image.get_rect()

    def draw(self):
        # Call this do draw, always prefers to use cache
        if self.dirty or (self.image is None): self._render()
        self.screen.blit(self.image, self.rect)

    @property
    def text(self):
        return self._text

    @text.setter
    def text(self, text):
        self.dirty = True
        self._text = text

    @property
    def aa(self): return self._aa

    @aa.setter
    def aa(self, aa):
        self.dirty = True
        self._aa = aa

class TextWall(object):
    # Manages multiple lines of text / paragraphs.
    def __init__(self, font=None, size=16):
        self.font = font
        self.font_size = size
        self.offset = Rect(20,20,1,1) # offset of whole wall

        self.screen = pygame.display.get_surface()
        self.dirty = True
        self.text_lines = []
        self._text_paragraph = "Empty\nText"
        self._render()

    def _render(self):
        # render list
        self.dirty = False
        self.text_lines = [ TextLine(self.font, self.font_size, line) for line in self._text_paragraph ]

        # offset whole paragraph
        self.text_lines[0].rect.top = self.offset.top

        # offset the height of each line
        prev = Rect(0,0,0,0)
        for t in self.text_lines:
            t.rect.top += prev.bottom
            t.rect.left = self.offset.left
            prev = t.rect

    def parse_text(self, text):
        # parse raw text to something usable
        self._text_paragraph = text.split("\n")
        self._render()

    def draw(self):
        # draw with cached surfaces
        if self.dirty: self._render()
        for text in self.text_lines: text.draw()

    @property
    def font_size(self):
        return self._font_size

    @font_size.setter
    def font_size(self, size):
        self.dirty = True
        self._font_size = size

    @property
    def text(self):
        return self._text_paragraph

    @text.setter
    def text(self, text_paragraph):
        self.dirty = True
        self.parse_text(text_paragraph)

class Game():
    done = False
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode ((640,480))
        self.text = Surface([200,100])

        self.text_wall = TextWall()
        self.toggle_bg = True

        self.text_wall.parse_text(lorem)

    def loop(self):
        while not self.done:
            self.handle_events()
            self.draw()

    def draw(self):
        if self.toggle_bg: bg = Color("gray60")
        else: bg = Color("gray20")

        self.screen.fill(bg)
        self.text_wall.draw()
        pygame.display.update()

    def handle_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT: self.done = True

            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE: self.done = True
                elif event.key == K_SPACE: self.toggle_bg = not self.toggle_bg
                elif event.key == K_1: self.text_wall.font_size -= 3
                elif event.key == K_2: self.text_wall.font_size += 3

if __name__ == "__main__":
    g = Game()
    g.loop()

rawDescription: Render anti-aliased text on transparent surface in pygame


code:
import os
import os.path
import string
[ 'xvd' + e for e in string.ascii_lowercase if not os.path.exists('/dev/xvd' + e)]

rawDescription: Is there a more Pythonic way to get a list of the available disk device names on Linux?


code: from xml.etree import cElementTree as ElementTree

rawDescription: Repeatedly querying xml using python

description: Repeatedly querying xml using python


code:
def coords(s):
    try:
        x, y, z = map(int, s.split(','))
        return x, y, z
    except:
        raise argparse.ArgumentTypeError("Coordinates must be x,y,z")

parser.add_argument('--cord', help="Coordinate", dest="cord", type=coords, nargs=3)

rawDescription: Python argument parser list of list or tuple of tuples


code: scipy.optimize.curve_fit(f, np.vstack(x, y), z)

rawDescription: How to do a simple 'model fitting' in python?

description: Do a simple 'model fitting' in python


code:
jobs = {}
job = Job()
jobs[job.name] = job
# insert other jobs in the normal dictionary

mgr = multiprocessing.Manager()
mgr_jobs = mgr.dict()
mgr_jobs.update(jobs)

rawDescription: Python manager.dict() is very slow compared to regular dict


code:
import os
folders = [x for x in os.listdir(path) if x.startswith('B07')]

rawDescription: Identify folders with a specific string in Python


rawDescription: How can I reverse multirow python list

description: Reverse multirow python list


code:
import sys
import urllib
from PyQt4.QtGui import *

def on_click():
    #change window contents to new contents

    # Creates text that says "Hello"
    text = QLabel('Hello', Window)
    # Text is moved to coordinates 21, 30
    text.move(21, 30)
    QLabel.show(text)
    button.hide()

# Creates PyQt4 Application object
App = QApplication(sys.argv)
# Create Window object
Window = QWidget()
Window.resize(320, 240)

# Creates button object called "Submit"
button = QPushButton('Submit', Window)
# Moves button (Right, Down)
button.move(200, 180)
# When button's clicked executes function called on_click()
button.clicked.connect(on_click)

# Displays window
Window.show()
# Needed so the gui window stays open until user closes it
App.exec_()

rawDescription: PyQt4 Using button to change current window contents


code:
import locale
locale.getdefaultlocale()

rawDescription: How to detect the OS default language in python?

description: Detect the OS default language in python


code: accum_value = function(accum_value, x)

rawDescription: Python map a filesystem to a directory structure: works, ...but how?


code:
import collections

class DictWrapper(collections.Mapping):

    def __init__(self, data):
        self._data = data

    def __getitem__(self, key):
        return self._data[key]

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

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

rawDescription: How to make dictionary read-only in python

description: Make dictionary read-only in python


code:
def textClicked(text, event, row):
    input = hippo.CanvasEntry()
    input.set_property('text', text.get_property('text'))
    entry = input.get_property("widget")
    def grabit(widget):
        entry.grab_focus()
    entry.connect("realize", grabit)
    parent = text.get_parent()
    parent.insert_after(input, text)
    parent.remove(text)

rawDescription: Programmatically focusing a hippo.CanvasEntry?


rawDescription: Most efficent Way to get lowest 10 bits of a hash as an int in Python


code:
for table in tree.xpath('(//tr[ td[span="Baccalaureate"] or td[contains(span,"Master")] ]/ancestor::tr[1])'):
  print('-- NEW TABLE -- \n')
  tab = table.xpath('.//table[@width="260px"]/tr/td[@style="width: 100%;"]/text()')
  print(tab)

rawDescription: XPath keep track of data from every table


code:
import glob
types = ('*.pdf', '*.cpp') # the tuple of file types
files_grabbed = []
for files in types:
    files_grabbed.extend(glob.glob(files))

files_grabbed   # the list of pdf and cpp files

rawDescription: Python glob multiple filetypes

description: Python glob multiple filetypes


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.special import wofz

def Z(x):
    return wofz(x)

## first derivative of wofz (analytically)
def Zp(x):
    return -2/1j/np.pi**0.5 - 2*x*Z(x)

def dawsn_expansion(x):
    # Accurate to order x^-9, or, relative to the first term x^-8
    # So when x > 100, this will be as accurate as you can get with
    # double floating point precision.
    y = 0.5 * x**-2
    return 1/(2*x) * (1 + y * (1 + 3*y * (1 + 5*y * (1 + 7*y))))

def dawsn_expansion_drop_first(x):
    y = 0.5 * x**-2
    return 1/(2*x) * (0 + y * (1 + 3*y * (1 + 5*y * (1 + 7*y))))

def dawsn_expansion_drop_first_two(x):
    y = 0.5 * x**-2
    return 1/(2*x) * (0 + y * (0 + 3*y * (1 + 5*y * (1 + 7*y))))

def blend(x, a, b):
    # Smoothly blend x from 0 at a to 1 at b
    y = (x - a) / (b - a)
    y *= (y > 0)
    y = y * (y <= 1) + 1 * (y > 1)
    return y*y * (3 - 2*y)

def g(x):
    """Calculate `x + (1-2x^2) D(x)`, where D(x) is the dawson function"""
    # For x < 50, use dawsn from scipy
    # For x > 100, use dawsn expansion
    b = blend(x, 50, 100)
    y1 = x + (1 - 2*x**2) * special.dawsn(x)
    y2 = dawsn_expansion_drop_first(x) - dawsn_expansion_drop_first_two(x) * 2*x**2
    return b*y2 + (1-b)*y1

def Zpp(x):
    # only return the imaginary component
    return -4j/np.pi**0.5 * g(x)

x = np.logspace(0, 5, 2000)
dx = 1e-3
plt.plot(x, (Zp(x+dx) - Zp(x-dx)).imag/(2*dx))
plt.plot(x, Zpp(x).imag)
ax = plt.gca()
ax.set_xscale('log')
ax.set_yscale('log')

rawDescription: second derivative of fadeeva function from scipy.special

description: Second derivative of fadeeva function from scipy.special


code:
def clone_entity(e, **extra_args):
  """Clones an entity, adding or overriding constructor attributes.

  The cloned entity will have exactly the same property values as the original
  entity, except where overridden. By default it will have no parent entity or
  key name, unless supplied.

  Args:
    e: The entity to clone
    extra_args: Keyword arguments to override from the cloned entity and pass
      to the constructor.
  Returns:
    A cloned, possibly modified, copy of entity e.
  """
  klass = e.__class__
  props = dict((k, v.__get__(e, klass)) for k, v in klass.properties().iteritems())
  props.update(dict([(k, getattr(e, k)) for k in e.dynamic_properties()]))
  props.update(extra_args)
  return klass(**props)

rawDescription: Clone and Expando class object in Python for App Engine


code:
import os
os.stat("file").st_size == 0

rawDescription: python how to check file empty or not

description: Python how to check file empty or not


code:
def makeSelect(name,values):
    SEL = '<select name="{0}">\n{1}</select>\n'
    OPT = '<option value="{0}">{0}</option>\n'
    return SEL.format(name, ''.join(OPT.format(v) for v in values))

rawDescription: In Python CGI create select menu using list variable


code: number = base36encode(base36decode(number) + 1)

rawDescription: Python increment string with both letters and numbers


code:
import threading
import socket
import Queue

class ClientThread(threading.Thread):

    def __init__(self,ip,port,clientsocket, in_q, out_q):
        threading.Thread.__init__(self)
        self.ip = ip
        self.port = port
        self.csocket = clientsocket
        self.in_q = in_q
        self.out_q = out_q
        self._tid = "{}:{}".format(ip, port)
        self.daemon = True # Assuming you want the client thread to shutdown when the main thread does
        print ("[+] New thread started for "+ip+":"+str(port))

    def run(self):
        # Stuff happens here
        while True:
            try:
                # Wait 8 seconds for an incoming command
                cmd = self.in_q.get(timeout=8)
                self.csocket.sendall(cmd)
                data = self.csocket.recv(56)
                # Send result to main thread.
                self.out_q.put({'tid' : self._tid, 'data' : data})
            except Queue.Empty:
                # No incoming command after 8 seconds, do a keep-alive instead.
                data = 'someinfo'
                self.csocket.sendall(data)
                data = self.csocket.recv(56)

def handle_socket_connections(resp_queue):
    """ Thread for handling connections from devices. """
    while True:
        host = "127.0.0.1"
        port = 3000
        tcpsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        tcpsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        tcpsock.bind((host,port))
        tcpsock.listen(5)
        print ("\nListening for incoming connections...")
        (clientsock, (ip, port)) = tcpsock.accept()
        q = Queue.Queue() # Create a Queue for sending commands to this device.
        queues["{}:{}".format(ip,port)] = q
        newthread = ClientThread(ip, port, clientsock, q, resp_queue)
        newthread.start()

queues = {} # dict for managing input queues
resp_queue = Queue.Queue()  # Shared response queue
socket_handler = threading.Thread(target=handle_socket_connections, args=(resp_queue,))
socket_handler.daemon = True
socket_handler.start()

# Wait for user input
while True:
    # example input format: '1.2.3.4:55 ON'
    in_data = raw_input("Enter using the format - <IP>:<Port> <cmd>")
    if in_data == "EXIT":
        break
    ip_port, cmd = in_data.split()
    try:
        queues[ip_port].put(cmd)  # Send command to the appropriate thread.
        result = resp_queue.get()  # Wait for a response.
        print("Got '{data}' from {tid}".format(**result))
    except KeyError:
        print("No conection on {}".format(ip_port))

rawDescription: Communicating from main code to multiple threads (that have sockets, if that matters)


code:
#!/usr/bin/env python
from datetime import date, datetime

Y = 2000 # dummy leap year to allow input X-02-29 (leap day)
seasons = [('winter', (date(Y,  1,  1),  date(Y,  3, 20))),
           ('spring', (date(Y,  3, 21),  date(Y,  6, 20))),
           ('summer', (date(Y,  6, 21),  date(Y,  9, 22))),
           ('autumn', (date(Y,  9, 23),  date(Y, 12, 20))),
           ('winter', (date(Y, 12, 21),  date(Y, 12, 31)))]

def get_season(now):
    if isinstance(now, datetime):
        now = now.date()
    now = now.replace(year=Y)
    return next(season for season, (start, end) in seasons
                if start <= now <= end)

print(get_season(date.today()))

rawDescription: Determine season given timestamp in Python using datetime


rawDescription: Split integer into two concatenated hex strings- Python


code:
class MyModel(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    my_field = db.Column(db.String(128))

class MyModelView(ModelView):
    """
    Admin manager for MyModel
    """

    form_overrides = dict(
        my_field=SelectField
    )
    form_args = dict(
        my_field=dict(
            choices=[
                ('choice_1', 'Choice 1'),
                ('choice_2', 'Choice 2')
            ]
        )
    )
    def __init__(self):
        super(MyModelView, self).__init__(MyModel, db.session)

rawDescription: How can I turn a string model field into a select input in Flask-Admin?

description: Turn a string model field into a select input in Flask-Admin


code:
from collections import defaultdict
list1 = ['cat', 'sat', 'on', 'mat', 'xx', 'yy']
list2 = ['cow', 'sat', 'on', 'carpet', 'xx', 'yy']
var_it = iter('IJKLMNOPQRSTUVWXYZ') # variable candidates
counters = defaultdict(int)
c = next(var_it)
for word1, word2 in zip(list1, list2):
    if word1 == word2:
        counters[c] += 1
    else:
        if counters: # Prevent counting until first match
            counters[next(var_it)] = 1
            c = next(var_it)
for var in sorted(counters):
    print('{}: {}'.format(var, counters[var]))

rawDescription: Find common subsequence in list

description: Find common subsequence in list


code:
import Tkinter as tk

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

        self.one = tk.Label(text="1", borderwidth=1, relief="raised")
        self.two = tk.Label(text="2", borderwidth=1, relief="raised")
        self.three = tk.Label(text="3", borderwidth=1, relief="raised")
        self.four = tk.Label(text="4", borderwidth=1, relief="raised")
        self.five = tk.Label(text="5", borderwidth=1, relief="raised")

        self.one.pack(side="left")
        self.two.pack(side="left")
        self.three.pack(side="left", fill="x", expand=True)
        self.four.pack(side="left")
        self.five.pack(side="left")

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

rawDescription: Packing stuff in a line - Python tkinter


rawDescription: Cleaner regex for removing characters before dot or slash


code:
import codecs
import csv

with codecs.open('eprime.txt', encoding='utf-16') as f, open('output.csv', 'w') as fout:
    writer = csv.writer(fout, delimiter='\t')
    writer.writerow(['Subject', 'itemID', 'bias1Answer'])
    for line in f:
        if ':' in line:
            value = line.split()[-1]

        if 'Subject:' in line:
            subject = value
        elif 'itemID:' in line:
            itemID = value
        elif 'bias1Answer:' in line:
            bias1Answer = value
            writer.writerow([subject, itemID, bias1Answer])

rawDescription: Parsing a txt file into a dictionary to write to csv file


code:
import glob
pyFiles = glob.glob('path/*.py')
for pyFile in pyFiles:
    execfile(pyFile)

rawDescription: Utility to manage multiple python scripts


code:
def save(self, force_insert=False, force_update=False):
    new_task = False
    if not self.id:
        new_task = True
    super(Task, self).save(force_insert, force_update)
    end = self.startDateTime + timedelta(minutes=24*60)
    title = "This is test Task"
    if new_task:
        event = Event(start=self.startDateTime, end=end,title=title,
                  description=self.description)
        event.save()
        rel = EventRelation.objects.create_relation(event, self)
        rel.save()
        try:
            cal = Calendar.objects.get(pk=1)
        except Calendar.DoesNotExist:
            cal = Calendar(name="Community Calendar")
            cal.save()
        cal.events.add(event)
    else:
        event = Event.objects.get_for_object(self)[0]
        event.start = self.startDateTime
        event.end = end
        event.title = title
        event.description = self.description
        event.save()

rawDescription: How to use django-scheduler app in existing app

description: Use django-scheduler app in existing app


code:
def counts(x, y, z):
    if(x + y + z > 1000):
        return

    if x + y + z == 1000:
        print(" {} coin $1 , {} coin $2 , {} coin $5".format(x,y/2,z/5))

    counts(x+1, y, z)
    counts(x, y+2, z)
    counts(x, y, z+5)

counts(1, 2, 5)

rawDescription: Recursive solution?

description: Recursive solution


code:
import numpy as np
import pylab as pl

class Radar(object):

    def __init__(self, fig, titles, labels, rect=None):
        if rect is None:
            rect = [0.05, 0.05, 0.95, 0.95]

        self.n = len(titles)
        self.angles = np.arange(90, 90+360, 360.0/self.n)
        self.axes = [fig.add_axes(rect, projection="polar", label="axes%d" % i)
                         for i in range(self.n)]

        self.ax = self.axes[0]
        self.ax.set_thetagrids(self.angles, labels=titles, fontsize=14)

        for ax in self.axes[1:]:
            ax.patch.set_visible(False)
            ax.grid("off")
            ax.xaxis.set_visible(False)

        for ax, angle, label in zip(self.axes, self.angles, labels):
            ax.set_rgrids(range(1, 6), angle=angle, labels=label)
            ax.spines["polar"].set_visible(False)
            ax.set_ylim(0, 5)

    def plot(self, values, *args, **kw):
        angle = np.deg2rad(np.r_[self.angles, self.angles[0]])
        values = np.r_[values, values[0]]
        self.ax.plot(angle, values, *args, **kw)

fig = pl.figure(figsize=(6, 6))

titles = list("ABCDE")

labels = [
    list("abcde"), list("12345"), list("uvwxy"),
    ["one", "two", "three", "four", "five"],
    list("jklmn")
]

radar = Radar(fig, titles, labels)
radar.plot([1, 3, 2, 5, 4],  "-", lw=2, color="b", alpha=0.4, label="first")
radar.plot([2.3, 2, 3, 3, 2],"-", lw=2, color="r", alpha=0.4, label="second")
radar.plot([3, 4, 3, 4, 2], "-", lw=2, color="g", alpha=0.4, label="third")
radar.ax.legend()

rawDescription: Radar chart with multiple scales on multiple axes


code:
IDs = ["1","A","2","B","3","C","4","D","5","E"]

N = len(IDs)
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

set_count = 2
set_label = np.vstack([j*ones(len(IDs)//set_count) for j in range(set_count)]).T.ravel()

property1 = numpy.array([1,3,4,2,3,5,6,7,3,2])
property2 = numpy.array(range(10))
property3 = numpy.array(range(10,0,-1))

props = [property1,property2,property3]

ind = numpy.arange(N/set_count)
width = 0.9
b_width = 0.9/set_count

color_sets = [['red','green','blue'],['black','magenta','yellow']]

for j in range(set_count):
    tmp_accum = np.zeros(len(props[0]))
    for k in range(len(props)):
        ax1.bar(ind +j*b_width, props[k][set_label==j], width=b_width, color=color_sets[j][k], bottom=tmp_accum[set_label==j])
        tmp_accum += props[k]

lab_ind = []
for j in range(set_count):

    lab_ind.append(ind + (j+.5)*b_width)

plt.xticks(np.vstack(lab_ind).T.ravel(), IDs )

rawDescription: Alternate colors in stacked matplotlib bar


code:
for number in range(1, 301, 100):
    low = number
    high = low + 100

rawDescription: To/From Paging in Python

description: To/From Paging in Python


code:
import os.path
from flask import Flask
from flask.ext.autoindex import AutoIndex

app = Flask(__name__)
AutoIndex(app, browse_root=os.path.curdir)

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

rawDescription: Flask : define a route to explore files and folders like SimpleHTTPSever does


rawDescription: adding directory to sys.path /PYTHONPATH

description: Adding directory to sys.path /PYTHONPATH


code:
def BuildSuit(self, pnl):
  cards=['AS', 'KS', 'QS', 'JS']
  suitSizer=wx.GridBagSizer(1, 13)
  border = 0
  for ii in range(0, len(cards)):
    card=cards[ii]
    image = wx.Bitmap('Images/CardImages/'+card+'.png',wx.BITMAP_TYPE_PNG).ConvertToImage()
    image=image.GetSubImage(wx.Rect(0, 0, 26, 96))
    img = wx.StaticBitmap(pnl, -1, image.ConvertToBitmap(), name=card)
    img.Bind(wx.EVT_LEFT_DCLICK, self.onSuitClick)
    suitSizer.Add(img, pos=(0,ii), flag=wx.LEFT, border=border)
    border = -13
  return suitSizer

rawDescription: wxPython overlapping images

description: WxPython overlapping images


rawDescription: Python using a string (with variables) in lambda expression


code:
def remove_table(s):
    left_index = s.find('<table>')
    if -1 == left_index:
        return s
    right_index = s.find('</table>', left_index)
    return s[:left_index] + remove_table(s[right_index + 8:])

rawDescription: How to remove <table> structure with python from this case?

description: Remove <table> structure with python from this case


code:
def populate(self):
    with open('Log.csv', 'rt') as f:
        reader = csv.reader(f)
        for row in reader:
            item = QtGui.QTreeWidgetItem(self.treeWidgetLog, row)

rawDescription: Populate QTreeWidget from CSV file - PySide/PyQt


code:
"""
    This is a collapsible doc string
"""

"""This is not"""

"""
Neither is this
"""

"""
 This one is, but I think it looks a little odd"""

rawDescription: Make Notepad++ collapse Python triple double content?


rawDescription: How to explain django that my custom backend is inside of my app?

description: Explain django that my custom backend is inside of my app


code:
import select
f = open('/sys/bus/clockevents/devices/clockevent0/uevent', 'r')
p = select.poll()
p.register(f, select.POLLPRI | select.POLLERR)
result = p.poll(10)
result

rawDescription: How can you generate a POLLPRI event on a regular file?

description: Generate a POLLPRI event on a regular file


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

gs = gridspec.GridSpec(4, 2)
ax00 = plt.subplot(gs[:2, 0])
ax01 = plt.subplot(gs[:2, 1])
ax10a = plt.subplot(gs[2, 0])
ax10b = plt.subplot(gs[3, 0])
ax11 = plt.subplot(gs[2:, 1])

x = np.linspace(-1, 1, 500)
y = 100*np.cos(10*x)**2*np.exp(-x**2)
for ax in (ax00, ax01, ax10a, ax10b, ax11):
    ax.plot(x, y)

ax10a.set_ylim(60, 110)
ax10b.set_ylim(0, 10)

ax10a.spines['bottom'].set_visible(False)
ax10b.spines['top'].set_visible(False)
ax10a.xaxis.tick_top()
ax10a.tick_params(labeltop='off') # don't put tick labels at the top
ax10b.xaxis.tick_bottom()

d = .015 # how big to make the diagonal lines in axes coordinates
# arguments to pass plot, just so we don't keep repeating them
kwargs = dict(transform=ax10a.transAxes, color='k', clip_on=False)
ax10a.plot((-d,+d),(-d,+d), **kwargs)      # top-left diagonal
ax10a.plot((1-d,1+d),(-d,+d), **kwargs)    # top-right diagonal

kwargs.update(transform=ax10b.transAxes)  # switch to the bottom axes
ax10b.plot((-d,+d),(1-d,1+d), **kwargs)   # bottom-left diagonal
ax10b.plot((1-d,1+d),(1-d,1+d), **kwargs) # bottom-right diagonal

plt.tight_layout()
plt.show()

rawDescription: discontinous axis in subplot - python matplotlib

description: Discontinous axis in subplot - python matplotlib


code:
def tree_max(node):
    maxleft  = float('-inf') if not node.left  else tree_max(node.left)
    maxright = float('-inf') if not node.right else tree_max(node.right)
    return max(node.value, maxleft, maxright)

rawDescription: Assigning local variable in recursion

description: Assigning local variable in recursion


code:
n = 5
r = (1 + 5 ** 0.5) / 2
r
total = 2.28
a = total * (1 - r) / (1 - r ** n)
a
sequence = [a * r ** i for i in range(n)]
sequence
sum(sequence)
sequence[1] / sequence[0]
sequence[2] / sequence[1]
sequence[2] / sequence[1] == r

rawDescription: Creating an exponentially growing list thats sum equals its "seed" to create list


code:
paddle_y_velocity = 0

while 1:
    if paddleRect.top < 0:
        paddleRect.top = 0
    if paddleRect.bottom > 800:
        paddleRect.bottom = 800

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                paddle_y_velocity -= 1
            if event.key == pygame.K_DOWN:
                paddle_y_velocity += 1

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                paddle_y_velocity = 0

    paddleRect.top += paddle_y_velocity

    ballRect = ballRect.move(speed)
    #etc

rawDescription: Pygame Pong, Paddle only moves once up and down and ball doesn't move after regen


code: soup.find('', 'x-btn x-component x-btn-text-icon')['id']

rawDescription: Using BeautifulSoup to find ID from Class


code: os.path.dirname("http://www.google.com/test")  # outputs http://www.google.com

rawDescription: Python os.path.dirname returns unexpected path when changing directory


code:
import random
from pprint import pprint
from collections import Counter

runLength = 600000

sequenceCount = Counter()
originalCards = ["1", "2", "3"]
ncards = len(originalCards)

for k in range(runLength): # use xrange on python 2
    cards = list(originalCards)

    # naive shuffle
    for i in range(ncards):
        n = random.randint(0, ncards - 1)
        cards[i], cards[n] = cards[n], cards[i] #swap

    sequenceCount[''.join(cards)] += 1

# results summary
print(sequenceCount)

# result: Counter({'132': 111424, '231': 111194, '213': 110312,
#                  '123': 89533, '321': 88846, '312': 88691})

rawDescription: Python (naive) shuffle in place -- towards reproducing Fisher-Yates


code:
import inspect
filter(lambda x: not (x.startswith('__') and x.endswith('__')), [a for (a, b) in inspect.getmembers(MyClass, lambda x : (not inspect.ismethod(x) and not inspect.isbuiltin(x)) )])

rawDescription: How to get all atrributes of a class/instance?

description: Get all atrributes of a class/instance


code:
import selenium
from bs4 import BeautifulSoup
webpage = selenium.webdriver.Firefox()
webpage.get('http://www1.chineseshipping.com.cn/en/indices/ccfinew.jsp')
html = webpage.page_source
soup = BeautifulSoup(html)
tables = soup.find_all('table')

rawDescription: python BeautifulSoup strange behaviour

description: Python BeautifulSoup strange behaviour


code:
class myWorker(QtCore.QThread):
    # Register the signal as a class variable first
    mySignal = QtCore.pyqtSignal(QtCore.QString)

    # init and other stuff...

    def someFunction(self):
        #....
        # emit the signal with the parameter
        self.mySignal.emit(msg)

# GUI
class myWindow(QtGui.QMainWindow):
    def __init__(self):
        # usual init stuff and gui setup...
        self.mytext = QTextEdit()

        # worker
        self.worker = myWorker()
        # register signal to a slot
        self.worker.mySignal.connect(self.mytext.setText)

rawDescription: Using SIgnals with variables PyQT

description: Using SIgnals with variables PyQT


rawDescription: python regex of a date in some text

description: Python regex of a date in some text


code:
import tkinter as tk
from tkinter import ttk

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

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

        self.frames = {}
        for F in (Login, AdminHome):

            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row = 0, column = 0, sticky = "nsew")

        self.show_frame(Login)

    def show_frame(self,cont):
        frame = self.frames[cont]
        frame.tkraise()

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

        innerFrame = tk.Frame(self)
        innerFrame.place(relx=.5, rely=.5, anchor="c")

        name = tk.Label(innerFrame, text = "Program")
        name.grid(row=0, columnspan=5, sticky="W"+"E")

        username = tk.Label(innerFrame, text="Username: ")
        username.grid(row=1, columnspan=2, sticky="W")

        user = ttk.Entry(innerFrame, text ="", width=45)
        user.grid(row=1, column=2 ,columnspan=3, sticky="w")

        password = tk.Label(innerFrame, text="Password: ")
        password.grid(row=2, columnspan=2, sticky="W")

        passentry = ttk.Entry(innerFrame, text ="", width=45)
        passentry.grid(row=2, column=2 ,columnspan=3, sticky="W")

        loginb = ttk.Button(innerFrame, text = "Login", command = lambda: controller.show_frame(AdminHome))
        loginb.grid(row=3, columnspan=5, sticky="W"+"E")

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

        innerFrame = tk.Frame(self)
        innerFrame.place(relx=.5, rely=.5, anchor="c")

        name = tk.Label(innerFrame, text = "Admin Home")
        name.grid(row=0, sticky="W")

        name = tk.Label(innerFrame, text = "FirstName + LastName")
        name.grid(row=0, column=5 ,sticky="E")

        update = ttk.Button(innerFrame, text = "Update Online", command = lambda: controller.show_frame(AdminHome))
        update.grid(row=1, columnspan=6, sticky="W"+"E")

        fetch = ttk.Button(innerFrame, text = "Fetch Data", command = lambda: controller.show_frame(AdminHome))
        fetch.grid(row=2, columnspan=6, sticky="W"+"E")

        a = ttk.Button(innerFrame, text = "a", command = lambda: controller.show_frame(AdminHome))
        a.grid(row=3, columnspan=2, sticky="W"+"E")

        b = ttk.Button(innerFrame, text = "b", command = lambda: controller.show_frame(AdminHome))
        b.grid(row=3, column=2, columnspan=2, sticky="W"+"E")

        c = ttk.Button(innerFrame, text = "c", command = lambda: controller.show_frame(AdminHome))
        c.grid(row=3, column=4, columnspan=2, sticky="W"+"E")

        edit = ttk.Button(innerFrame, text = "Edit Details", command = lambda: controller.show_frame(AdminHome))
        edit.grid(row=4, columnspan=6, sticky="W"+"E")

app = Program()
app.state('zoomed')
app.mainloop()

rawDescription: Python Tkinter Object Oriented- Centering Multiple Frames


code:
from collections import defaultdict

a = defaultdict(bool)
a[i,j,k,m] = True

rawDescription: Good way to make a multi dimensional array without numpy


code:
grouped = data['2013-08-17'].groupby(axis=1, level='SPECIES').T
grouped.boxplot()

rawDescription: Boxplot with pandas groupby

description: Boxplot with pandas groupby


code:
import csv
from collections import defaultdict

summary = defaultdict(list)
csvin = csv.reader(open('testdata.txt'), delimiter='|')
for row in csvin:
    summary[(row[1].split(' ')[0], row[2])].append(int(row[5]))

csvout = csv.writer(open('testdata.out','wb'), delimiter='|')
for who, what in summary.iteritems():
    csvout.writerow( [' '.join(who), len(what), sum(what)] )

rawDescription: String Grouping Based On Name

description: String Grouping Based On Name


code:
tgt
tgt.replace('\\', '')

rawDescription: Not able to decode escaped strings python


code: from __future__ import absolute_import

rawDescription: Force import module from Python standard library instead of PYTHONPATH default


code:
def find_ge(a, key):
    '''Find smallest item greater-than or equal to key.
    Raise ValueError if no such item exists.
    If multiple keys are equal, return the leftmost.

    '''
    i = bisect_left(a, key)
    if i == len(a):
        raise ValueError('No item found with key at or above: %r' % (key,))
    return a[i]

find_ge(somenumbers, 262139)

rawDescription: Python binary search-like function to find first number in sorted list greater than a specific value


code: Books.objects.all().only('title', 'author', 'date').extra(where=['library IS NOT NULL']).distinct()

rawDescription: Django - How to filter down duplicates in a query?


code:
importer = zipimport.zipimporter('module.mod')
chardet = importer.load_module('chardet')

rawDescription: Hadoop: How to include third party library in Python MapReduce


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

import pygame

class Tile:

    def __init__(self, x, y, image, cover):
        self.image = image
        self.cover = cover
        self.rect = pygame.Rect(x, y, 60, 60)
        self.covered = True
        self.time_to_cover = None

    def draw(self, screen):
        # draw cover or image
        if self.covered:
            screen.blit(self.cover, self.rect)
        else:
            screen.blit(self.image, self.rect)

    def update(self):
        # hide card (after 2000ms)
        if not self.covered and pygame.time.get_ticks() >= self.time_to_cover:
            self.covered = True

    def handle_event(self, event):
        # check left button click
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            # check position
            if self.rect.collidepoint(event.pos):
                self.covered = not self.covered
                if not self.covered:
                    # if uncovered then set +2000ms to cover
                    self.time_to_cover = pygame.time.get_ticks() + 2000

#----------------------------------------------------------------------

# init

pygame.init()

screen = pygame.display.set_mode((320,320))

# create images

img = pygame.surface.Surface((60, 60))
img.fill((255,0,0))

cov = pygame.surface.Surface((60, 60))
cov.fill((0,255,0))

# create tiles

tiles = []
for y in range(5):
    for x in range(5):
        tiles.append( Tile(x*65, y*65, img, cov) )

# mainloop

clock = pygame.time.Clock()
running = True

while running:

    # events

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        for x in tiles:
            x.handle_event(event)

    # updates

    for x in tiles:
        x.update()

    # draws

    for x in tiles:
        x.draw(screen)

    pygame.display.flip()

    # clock

    clock.tick(25)

pygame.quit()

rawDescription: How to draw cover on each tile in 'memory' in pygame

description: Draw cover on each tile in 'memory' in pygame


code:
dic={10:(1,4),20:(2,4),30:(3,4)}
[x[0] for x in dic.values()]
# Or if you want that as a tuple
tuple(x[0] for x in dic.values())
# Or a string
",".join([str(x[0]) for x in dic.values()])

rawDescription: Getting single value from multiple values in dictionary


code:
class A:
    l = []
a = A()
b = A()
a.l
A.l
a.l = 3
b.l
b.l.append(1)
b.l
A.l
a.l

rawDescription: Understanding classes 'self'

description: Understanding classes 'self'


code:
import gtk

def inIta(col, cell, model, iter, mymodel):
    s = model.get_string_from_iter(iter)
    niter = mymodel.get_iter_from_string(s)
    obj = mymodel.get_value(niter, 0)
    cell.set_property('text', obj)

model = gtk.ListStore(str)
model2 = gtk.ListStore(str)
view = gtk.TreeView(model)
rend1 = gtk.CellRendererText()
col1 = gtk.TreeViewColumn('hello', rend1, text=0)
view.append_column(col1)
rend2 = gtk.CellRendererText()
col2 = gtk.TreeViewColumn('ciao', rend2)
col2.set_cell_data_func(rend2, inIta, model2)
view.append_column(col2)

model.append(['hello world'])
model2.append(['ciao mondo'])

win = gtk.Window()
win.connect('delete_event', gtk.main_quit)
win.add(view)
win.show_all()
gtk.main()

rawDescription: Can I add a column to an existing treemodel in gtk?

description: Add a column to an existing treemodel in gtk


code:
# We assume we already have sword, fists, and stern_glare objects
# representing weapons.
weapons = {'sword': sword, 'fists': fists, 'stern glare': stern_glare}

# Prompt for a choice, and keep prompting until you get a valid choice.
# You'll probably want a more user-friendly prompt.
valid_choice = False
while not valid_choice:
    weapon_choice = raw_input('Select your weapon')
    valid_choice = weapon_choice in weapons

# Create the character.
dean = Char('Dean', weapons[weapon_choice])

rawDescription: How to give an object (has-a) an object of another class

description: Give an object (has-a) an object of another class


code:
file = open('file.der')
bio = BIO.File(file)
smime_object = SMIME.PKCS7(m2.pkcs7_read_bio_der(bio._ptr()))

rawDescription: M2Crypto: read PKCS#7 structure in DER format?


code:
def spellcheck(inputfile):

    filebeingchecked=open(inputfile,'r')
    spellcheckfile=open("words.txt",'r')

    dictionary=spellcheckfile.read().split()
    checkedwords=filebeingchecked.read().split()

    for word in checkedwords:

        low = 0
        high=len(dictionary)-1

        while low <= high:

            mid=(low+high)//2
            item=dictionary[mid]

            if word == item:
                break

            elif word < item:
                high=mid-1

            else:
                low=mid+1
        else:
            yield word

def main():

    print("This program accepts a file as an input file and uses a spell check function to \nidentify any problematic words that are not found in a common dictionary.")
    inputfile=input("Enter the name of the desired .txt file you wish to spellcheck: ")
    for word in spellcheck(inputfile):
        print(word)

main()

rawDescription: Binary Search Python Spell Check

description: Binary Search Python Spell Check


rawDescription: Get token from a tab seperated string in python


code:
#Load Data
string_data = "gene cell_1  cell_2 \nMYC 5.0 P 4.0 A\nAKT 3.0 A 1.0 P"
A_pre = np.array([row.split(" ") for row in string_data.split("\n")])
DF_data = pd.DataFrame(A_pre[1:,1:],
                       index=pd.Series(A_pre[1:,0],name=A_pre[0,0]),
                       columns=A_pre[0,1:])

A_data = DF_data.as_matrix() #Set the data array b/c it's quicker to slice than DF
rowLabels, colLabels = DF_data.index, DF_data.columns

# #Get blank columns
gene_idx = np.where(np.array(colLabels) != "")[0] #Used later
numColBlank = len(colLabels) - len(gene_idx)

# #Placeholder to fill
DF_placeholder = pd.DataFrame(np.zeros((DF_data.shape[0],DF_data.shape[1] - numColBlank)),
                              index = DF_data.index,
                              columns = DF_data.columns[gene_idx]
                              )
DF_data

#Populate matrix
query = "P"
for i in range(DF_data.shape[0]):
    for j in range(DF_data.shape[1]):
        if colLabels[j] == "":
            if A_data[i,j] == query:
                cell = colLabels[j-1]
                gene = rowLabels[i]
                metric = A_data[i,j-1]
                DF_placeholder.loc[gene,cell] = metric

#I just found out about masks they are useful
mask = DF_placeholder == 0.0
DF_placeholder[mask] = np.nan
DF_processed = DF_placeholder
DF_processed

rawDescription: Tab files into pandas dataframe according to columns with missing headers


code:
with open("filename", "w") as f:
    f.write(ET.tostring(tree))

rawDescription: How do i parse a string in python and write it as an xml to a new xml file?

description: Parse a string in python and write it as an xml to a new xml file


code: SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTOCOL', 'https')

rawDescription: Django HTTPS settings: Why does setting both SESSION_SAVE_EVERY_REQUEST and SESSION_COOKIE_SECURE break sessions?


code:
import cloudstorage as gcs
import endpoints
import os

from google.appengine.api import app_identity
from protorpc import messages
from protorpc import message_types
from protorpc import remote

class Base64File(messages.Message):
    file = messages.BytesField(1, required=True, variant=messages.Variant.BYTES)

class ResponseMSG(messages.Message):
    message = messages.StringField(1)

FILE_RESOURCE = endpoints.ResourceContainer(Base64File,
                                            file_name=messages.StringField(2,required=True),
                                            content_type=messages.StringField(3,required=True))

@endpoints.api(name='gcsuploadapi', version='v0.1',
                                      description='Upload a file to GCS.')
class GCSUploadAPI(remote.Service):
    @endpoints.method(FILE_RESOURCE, ResponseMSG,
                        path='upload/{file_name}', http_method='POST',
                        name='upload.file')
    def upload_file(self, request):
        # get app default bucket and prepare filename (project should have billing enabled)
        bucket_name = os.environ.get('BUCKET_NAME',
                                 app_identity.get_default_gcs_bucket_name())
        bucket = '/' + bucket_name
        filename = bucket + '/' + request.file_name

        # create file (request.content_type contains MIME type submitted)
        write_retry_params = gcs.RetryParams(backoff_factor=1.1)
        gcs_file = gcs.open(filename, 'w',
                            content_type=request.content_type,
                            retry_params=write_retry_params)
        gcs_file.write(request.file)
        gcs_file.close()

        return ResponseMSG(message="done")

app = endpoints.api_server([GCSUploadAPI])

rawDescription: Upload a recording to Google App Engine from Android app


code:
root = Tk()

def clear_all():
    for widget in root.winfo_children():      # get all children of root
        if widget.winfo_class() == 'Entry':   # if the class is Entry
            widget.delete(0,END)              # reset its value
        elif widget.winfo_class() == 'Label': # get Label widgets
            widget.config(bg='green')         # and change them as well

# set up misc. widgets
for i in range(5):
    Entry(root).pack()
Label(root, height=10, width=100, bg='red').pack()
Button(root, text='Refresh', command=clear_all).pack()

mainloop()

rawDescription: how to refresh the window in python

description: Refresh the window in python


code:
from urlparse import urlparse
o = urlparse('http://www.facebook.com/pages/create.php')
o.netloc

rawDescription: Split from a specific delimiter

description: Split from a specific delimiter


code:
def contains(container, contained):
    return all(container[x] >= contained[x] for x in contained)

rawDescription: Test if python Counter is contained in another Counter


code:
from random import random

class Object(object):

    def __init__(self):
        self._x = None

    @property
    def x(self):
        if self._x is None:
            self._x = random()
        return self._x

rawDescription: How to make Python object pre-compute a property if the property is currently None?

description: Make Python object pre-compute a property if the property is currently None


code:
data = {}
key = operator.itemgetter("name", "class")
for record in myjson:
    k = key(record)
    if k in data:
        data[k]["topic"].append(record["topic"])
    else:
        data[k] = record.copy()
        data[k]["topic"] = [record["topic"]]
result = data.values()

rawDescription: Python functional transformation of JSON list of dictionaries from long to wide


code:
def unsortedSearch(list1, i, u):
    found = False
    pos = 0
    pos2 = 0

    while pos < len(list1) and not found:
        if list1[pos] < u : # <--------------- fixed here
            if list1[pos2] > i: # <----------- and here
                found = True
            pos2 = pos2 + 1
        pos = pos + 1
    return found

rawDescription: Python - 'type' object is not subscriptable


code:
#!/usr/bin/env python

import subprocess

interval = 300  # secs

while True:
    p = subprocess.Popen(['pythonw.exe', 'foo.py'])
    time.sleep(interval)

rawDescription: Scheduled tasks in Win32

description: Scheduled tasks in Win32


code:
def __init__(self, value):
        self.key1 = value
        arr={}
        #append value to arr
        arr.update({'key2':'value2'})
        arr.update({'key':'value'})
        self.key2 = arr

rawDescription: Create nested json object using python jsonpickle


code:
x = pd.np.tile(xi, 3)
y = pd.np.r_[df['A'], df['B'], df['C']]

slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)
line4 = intercept + slope * xi

plt.plot(line4,'k-')

rawDescription: pandas - linear regression of dataframe columns values

description: Pandas - linear regression of dataframe columns values


code:
for i in [i for i, x in enumerate(hanksArray) if x == hanksYear]:
        print(hanksArray[i-1])
        print(hanksArray[i])
        print(hanksArray[i+1])

rawDescription: Print from enumerated list in python

description: Print from enumerated list in python


rawDescription: Subscripting more than one symbol in python


code:
import uinput

device = uinput.Device([
        uinput.KEY_E,
        uinput.KEY_H,
        uinput.KEY_L,
        uinput.KEY_O,
        ])

device.emit_click(uinput.KEY_H)
device.emit_click(uinput.KEY_E)
device.emit_click(uinput.KEY_L)
device.emit_click(uinput.KEY_L)
device.emit_click(uinput.KEY_O)

rawDescription: How can we generate Keyboard interrupts using python


code: buffer.append(String.format("%02x", 0xFF & digest[i]));

rawDescription: Difference between android sha224 and python sha224


code:
from IPython.utils import io

with io.capture_output() as captured:
    foo()

rawDescription: iPython notebook avoid printing within a function

description: IPython notebook avoid printing within a function


code:
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        # put your calculation logic in here (instead of "Hello World"
        self.write("Hello, world")

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Simplest way to expose my python program to .Net/C# - can't use ironpython


code:
import pandas
my_series = pandas.Series([1,2,2,3,3,3, "fred", 1.8, 1.8])
my_series
counts = my_series.value_counts()
counts
len(counts)
sum(counts)
counts["fred"]
dict(counts)

rawDescription: pandas: Frequency table for a single variable

description: Pandas: Frequency table for a single variable


code: df['difference'] = df.date.diff()

rawDescription: how to reproduce this excel formula in python-pandas

description: Reproduce this excel formula in python-pandas


code:
regex = re.compile('(?P<hel>hell[oa])\s*(?P<wrl>w[oa]rld)')
line = "hello world hella warld"
[m.groupdict() for m in regex.finditer(line)]

rawDescription: Is there a function in like re.findall but that returns dictionaries instead of tuples?


code:
from io import BytesIO

def extract(kv):
    k, v = kv
    with BytesIO(v) as r:
        for f, x in np.load(r).items():
            yield "{0}\t{1}".format(k, f), x

sc.binaryFiles(inputPath).flatMap(extract)

rawDescription: Loading numpy arrays stored in npz archive in PySpark


code: all(item in superset.items() for item in subset.items())

rawDescription: Python: Check if one dictionary is a subset of another larger dictionary


code:
a_ids = A.objects.values_list('id', flat=True)
b_values = B.objects.filter(param='foo', id__in=a_ids).values_list('value', flat=True).distinct()

rawDescription: SQLite to Django - join tables with same field names


code:
import re
reg_exp = '(\w+)\.(\w+)\(?([^)]*)\)?'
re.match(reg_exp, 'class.method("params")').groups()
re.match(reg_exp, "class.method('params')").groups()
re.match(reg_exp, "class.method()").groups()
re.match(reg_exp, 'class.method(params)').groups()
re.match(reg_exp, 'class.method').groups()

rawDescription: Solving simple regex

description: Solving simple regex


code:
input_string = "I only want the vowels"
allowed_chars = 'AEIOUaeiou'
output_string = ''.join((c for c in input_string if c in list(allowed_chars)))

rawDescription: Selectable string filter

description: Selectable string filter


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy.misc import derivative

x = np.array([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,\
              16,17,18,19,20,21,22,23,24,25,26,27,28,29,30])
y = np.array([2,5,7,9,10,13,16,18,21,22,21,20,19,18,\
              17,14,10,9,7,5,7,9,10,12,13,15,16,17,22,27])

# Simple interpolation of x and y
f = interp1d(x, y)
x_fake = np.arange(1.1, 30, 0.1)

# derivative of y with respect to x
df_dx = derivative(f, x_fake, dx=1e-6)

# Plot
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

ax1.errorbar(x, y, fmt="o", color="blue", label='Input data')
ax1.errorbar(x_fake, f(x_fake), label="Interpolated data", lw=2)
ax1.set_xlabel("x")
ax1.set_ylabel("y")

ax2.errorbar(x_fake, df_dx, lw=2)
ax2.errorbar(x_fake, np.array([0 for i in x_fake]), ls="--", lw=2)
ax2.set_xlabel("x")
ax2.set_ylabel("dy/dx")

leg = ax1.legend(loc=2, numpoints=1,scatterpoints=1)
leg.draw_frame(False)

rawDescription: identify graph uptrend or downtrend

description: Identify graph uptrend or downtrend


code:
cmd = ["convert", "test.bmp", "jpg:-"]
output_stream = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout

rawDescription: Using Imagemagick without making files?

description: Using Imagemagick without making files


rawDescription: How can I declare a 5x5 grid of numbers in Python?

description: Declare a 5x5 grid of numbers in Python


code:
div = soup.find('div', id='cmeProductSlatePaginiationTop')
lis = div.find_all('li')
num_lis = len(lis)

rawDescription: Search within tags with BeautifulSoup Python


code:
class BillingAPI(object):

    def __init__(self, token, root_url='https://api.billysbilling.com/v2/'):
        self._session = requests.Session()
        self._session.headers['X-Access-Token'] = token
        self.root_url = root_url

    def get(self, url_part):
        url = self.root_url + str(url_part)
        return self._session.get(url).json()

def invoiceLines(token):
    api = BillingAPI(token)
    inv = api.get('invoices')['invoices']
    # ...

rawDescription: Python Rest API call speed

description: Python Rest API call speed


code:
original = "abc\0"
finish_correct = "cba\0"
original
finish_correct

answer = original[:-1]  # remove final null
answer = answer[::-1]  # reverse string
# Extended slice syntax:  [begin:end:step]
# So, [::-1] means take whole string, but in reverse.
answer
answer = answer + "\0"
answer
answer == finish_correct

rawDescription: 'C-style' strings in Python

description: 'C-style' strings in Python


code:
colours = np.array(colours)
colours[indices, :] = (1, 0, 0, 1)

rawDescription: efficient way for replacing sub-arrays within numpy array - numpy.put or similar?

description: Efficient way for replacing sub-arrays within numpy array - numpy.put or similar


code:
ax.plot_date(dates_to_plot, y_obs2)

# Get the current ylims
foo = ax.get_ylim()

# Prevent the axes ylims from changing automatically with new plots
ax.set_ylim(auto=False)

ax.fill_between(dates_to_plot, foo[0], y_obs2)

# You can always manually specify the ylims as well
# ax.set_ylim((lower, upper))

rawDescription: Difference Between xlim/ylim and Axis Boundaries


code:
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO

def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = file(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
        interpreter.process_page(page)

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    return text

rawDescription: Extracting text from a PDF file using PDFMiner in python?


code:
# saved encoding-sample to /tmp/encoding-sample
import codecs
fp= codecs.open("/tmp/encoding-sample", "r", "utf8")
data= fp.read()

import unicodedata as ud

chars= sorted(set(data))
for char in chars:
    try:
        charname= ud.name(char)
    except ValueError:
        charname= "<unknown>"
    sys.stdout.write("char U%04x %s\n" % (ord(char), charname))

rawDescription: How to convert \xXY encoded characters to UTF-8 in Python?

description: Convert \xXY encoded characters to UTF-8 in Python


code:
from scipy import interpolate

x,y,u = createInterpolatedSurface()

#Create an interpolation function
f = interpolate.interp2d(x, y, u, kind='cubic')

#Use interpolation function to get results
xpoint = 0.5
ypoint = 0.1
upoint = f(xpoint, ypoint)

rawDescription: Python Extract PointProbes from Surface Contour Plot


code:
from itertools import compress
sum(compress(list1, list2))

rawDescription: Sum elements of array using condition on indexes - Python


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

# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)

plt.scatter(t,x,c=y)
plt.show()

rawDescription: matplotlib: how to change data points color based on some variable

description: Matplotlib: how to change data points color based on some variable


code:
import numpy as np

#Generate random "image" (replace this with your original image)
img = np.random.randint(0,256, size=512**2).reshape(512,512)

#Make white box
box = np.array([255]*5*5).reshape(5,5)

#Generate random coordinates
x, y = np.random.randint(0,512-5, size=2)

#Replace original image with white box
img[x:x+5, y:y+5] = box

rawDescription: Create Random White Rectangle/Array into Image/Matrix


code:
from datetime import datetime
today = datetime.today()
b.utcoffset(today) == c.utcoffset(today)

rawDescription: How to compare two timezones in python?

description: Compare two timezones in python


code:
words = 'She sells seashells by the seashore'

unique_letters = set(words.lower())
unique_letters.discard(' ') # If there was a space, remove it.

rawDescription: How to go from list of words to a list of distinct letters in Python

description: Go from list of words to a list of distinct letters in Python