code:
from IPython.parallel import Client
rc = Client(profile='ssh')
dview = rc[:]
dview.execute('reload(<module>)', block = True)

rawDescription: Reload module on remote ipengine when using ipython


code:
def raw_response(template):
    def wrap(view):
        def response(request, *args, **kwargs):
            context = view(request, *args, **kwargs)
            if request.method == 'GET' and request.GET.get('raw', '0') == '1':
                return HttpResponse(render_to_string(template, context),
                                    content_type='text/plain')
            # POST or not raw
            return render_to_response(template, context)
        return response
    return wrap

@raw_response('my_template_name.html')
def view_name(request):
    return {'x': 42}

rawDescription: Decorator for determining HTTP response from a view


code:
# main: axis; olocs: locations list; ocols: location colours
def overlay_labels(main, olocs, ocols):
    # Append the overlay labels as ticks
    main.yaxis.set_ticks(np.append(main.yaxis.get_ticklocs(), olocs))

    # Perform generic formatting to /all/ ticks
    # [...]

    labels  = reversed(main.yaxis.get_ticklabels())
    markers = reversed(main.yaxis.get_ticklines()[1::2]) # RHS ticks only
    glines  = reversed(main.yaxis.get_gridlines())
    rocols  = reversed(ocols)

    # Suitably format each overlay tick (colours and lines)
    for label,marker,grid,colour in izip(labels, markers, glines, rocols):
        label.set_color('white')
        label.set_backgroundcolor(colour)
        marker.set_visible(False)
        grid.set_visible(False)

rawDescription: Matplotlib adding overlay labels to an axis


code:
try:
    # python 3.x
    import tkinter as tk
except ImportError:
    # python 2.x
    import Tkinter as tk

class Example(tk.Frame):

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

        # valid percent substitutions (from the Tk entry man page)
        # %d = Type of action (1=insert, 0=delete, -1 for others)
        # %i = index of char string to be inserted/deleted, or -1
        # %P = value of the entry if the edit is allowed
        # %s = value of entry prior to editing
        # %S = the text string being inserted or deleted, if any
        # %v = the type of validation that is currently set
        # %V = the type of validation that triggered the callback
        #      (key, focusin, focusout, forced)
        # %W = the tk name of the widget

        vcmd = (self.register(self.onValidate),
                '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W')
        self.entry = tk.Entry(self, validate="key", validatecommand=vcmd)
        self.text = tk.Text(self, height=10, width=40)
        self.entry.pack(side="top", fill="x")
        self.text.pack(side="bottom", fill="both", expand=True)

    def onValidate(self, d, i, P, s, S, v, V, W):
        self.text.delete("1.0", "end")
        self.text.insert("end","OnValidate:\n")
        self.text.insert("end","d='%s'\n" % d)
        self.text.insert("end","i='%s'\n" % i)
        self.text.insert("end","P='%s'\n" % P)
        self.text.insert("end","s='%s'\n" % s)
        self.text.insert("end","S='%s'\n" % S)
        self.text.insert("end","v='%s'\n" % v)
        self.text.insert("end","V='%s'\n" % V)
        self.text.insert("end","W='%s'\n" % W)

        # Disallow anything but lowercase letters
        valid = (S.lower() == S)
        if not valid:
            self.bell()
        return valid

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

rawDescription: Interactively validating Entry widget content in tkinter


code:
class Dummysink(object):
    def write(self, data):
        pass # ignore the data
    def __enter__(self): return self
    def __exit__(*x): pass

def datasink(filename):
    if filename:
        return open(filename, "w")
    else:
        return Dummysink()

...

results = []
with datasink(filename) as output:
    for item in items:
        result = compute_stuff(item)
        write_result(item, result, output)
        results.append(result)
return results

rawDescription: Can a "with" statement be used conditionally?


code:
cache = {}
df.groupby(lambda d: cache.setdefault(d.isocalendar()[:2], d)).agg(agg)

rawDescription: Pandas: Separating grouping and indexing


code:
def login_required():
    def wrapper(fn):
        @wraps(fn)
        def decorated_view(*args, **kwargs):
            if not current_user.is_authenticated():
                abort(401)
                # return jsonify(status='logged_off')
            return fn(*args, **kwargs)
        return decorated_view
    return wrapper

rawDescription: Is there a way to manage authentication for web services with Flask?


code:
import csv
with open('input.csv', 'r') as inf, open('output.csv','wb') as outf:
    reader = csv.reader(inf, delimiter=',')
    writer = csv.writer(outf, delimiter=',' )
    for row in reader:
        t = row
        (h,m,s) = t[1].split(':')
        result = int(h) * 3600 + int(m) * 60 + float(s)
        t[1] = result
        writer.writerow(t)

rawDescription: Python - Time conversion in a loop through a .csv column


code:
import dis
dis.dis(StressTestLocal.do_work)
dis.dis(StressTestMember.do_work)

rawDescription: Why is local variable access faster than class member access in Python?


code:
while True: #select algorithm type
    #code: ask for algorithm
    if answer not in "pmc":
        #some message
        continue #non-valid algorithm selected, ask again
    #...
    if answer == 'p':
        while True: #select iteration range
            #code: ask for iteration
            if answer_not_in_range:
                #some message
                continue #non-valid iteration value, ask again
            #...
            #perform calculation upon valid selections
            #...
            #calculation ends
            #code: ask for try again with other iteration (algorithm stays same)
            if answer != "yes":
                break #break out of "iteration" loop
            #else loop continues asking for new iteration
    #code: ask for try again with other algorithm
    if answer != "yes":
        break #"algorithm" loop ends, program ends

rawDescription: User interaction via while-loops / jumping out of 2 while loops


code: cmd6 = "vnoremap d :<C-u>call DelSelection()<cr>"

rawDescription: A function to apply to selection in vim

description: A function to apply to selection in vim


code:
x='gewfsafg'
id(x)
x=x[x.index('f'):]
x
id(x)

rawDescription: Memory usage when "cutting" a string variable and assigning the new part to the same variable name


code:
def check_if_first_time_login(user):
    is_first_time_login = None
    for type in ['administrator', 'agent']:
        try:
            user_type = getattr(user, type)
            is_first_time_login = user_type.is_first_time_login
        except ObjectDoesNotExist:
            pass
        else:
            log.info('The user {user} is an {type}'.format(**locals()))
            user_type.is_first_time_login = False
            user_type.save()

    return is_first_time_login

class AccountAdapter(DefaultAccountAdapter):

    def get_login_redirect_url(self, request):
        user = get_object_or_404(get_user_model(), pk=request.user.id)

        is_first_time_login = check_if_first_time_login(user)

        if is_first_time_login:
            log.info(
                'The user {user} is login in for the first time so '
                'lets set a new password'.format(**locals())
            )
            url = '/accounts/password/change/'
        else:
            log.info(
                'The user {user} is NOT login in for the first '
                'time'.format(**locals())
            )
            url = settings.LOGIN_REDIRECT_URL
        return resolve_url(url)

rawDescription: Django First time Login detection with django-allauth


rawDescription: How can I split a 8 byte array into two four byte arrays in Python?

description: Split a 8 byte array into two four byte arrays in Python


code:
blank_page = PDFFileReader('blank.pdf').pages[0]
dest = PDFFileWriter()
for source in sources:
    PDF = PDFFileReader(source)
    dest.addPage(PDF.pages)
    if PDF.numPages % 2: #odd number of pages in source
        dest.addPage(blank_page)

rawDescription: Manipulate and print to PDF files in a script


code:
from pyPdf import PdfFileWriter, PdfFileReader
from pdfnup import generateNup

output = PdfFileWriter()
input1 = PdfFileReader(file("in.pdf", "rb"))

page1 = input1.getPage(0)
page2 = input1.getPage(1)

output.addPage(page1)
output.addPage(page2)

outputStream = file("out.pdf", "wb")
output.write(outputStream)
outputStream.close()

generateNup("out.pdf", 2)

rawDescription: Shrink and merge PDFs in Python

description: Shrink and merge PDFs in Python


code:
childJoins = parentTable
for child in childTables:
    childJoins = childJoins.join(child)

query = sa.select(['*'], from_obj=childJoins)

rawDescription: How to dynamically join multiple tables using SQLalchemy Core?

description: Dynamically join multiple tables using SQLalchemy Core


code:
from multiprocessing import Process, Queue
import time
def consumer(q):
         while(True):
            data=q.get()
            if (data[0]==False):
                print("Killing")
                return
            print((data[1]))
            time.sleep(1)

if __name__ == '__main__':
    maxitems=3
    q = Queue(maxitems)
    p = Process(target=consumer, args=(q,))
    p.start()
    for idx in range(0,10):
        q.put((True,idx))
        #Where idx would normally be a chunk of data
    q.put((False,False))
    p.join()

rawDescription: Producer consumer in python locks on get


code:
def add_docs_for(other_func):
    def dec(func):
        func.__doc__ = other_func.__doc__ + "\n\n" + func.__doc__
        return func
    return dec

def foo():
    """documentation for foo"""
    pass

@add_docs_for(foo)
def bar():
    """additional notes for bar"""
    pass

help(bar) # --> "documentation for foo // additional notes for bar"

rawDescription: String manipulation in Python docstrings


code:
from pygame.locals import *
import pygame
import os
import sys

pygame.init()

CAPTION = "TEST"

class Game():
    def __init__(self):
        #window setup
        pygame.display.set_caption(CAPTION)
        os.environ["SDL_VIDEO_CENTERED"] = "True"
        self.fps = 60.0

        self.clock = pygame.time.Clock()
        self.last_tick = pygame.time.get_ticks()
        self.screen_res = [200, 200]

        self.screen = pygame.display.set_mode(self.screen_res,pygame.HWSURFACE)

        self.rect = pygame.Surface((100, 100))
        self.rect.fill((250, 0,0))

        self.alpha = 1
        self.a_change = True
        #Tweak this to change speed
        self.blink_spd = 0.1

        #start loop
        self.clock.tick(self.fps)
        while 1:
            self.Loop()

    def Loop(self):
        # main game loop
        self.eventLoop()

        self.last_tick = pygame.time.get_ticks()

        self.screen.fill((0,0,0))
        #Check if alpha is going up
        if self.a_change:
            self.alpha += self.blink_spd
            if self.alpha >= 175:#if all the way up go down
                self.a_change = False
        #Check if alpha is going down
        elif self.a_change == False:
            self.alpha += -self.blink_spd
            if self.alpha <= 30: #if all the way down go up
                self.a_change = True

        self.rect.set_alpha(self.alpha)
        self.screen.blit(self.rect,(50,50))

        pygame.display.update()

    def eventLoop(self):
        # the main event loop, detects keypresses
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

Game()

rawDescription: how to create a blinking or glowing button using pygame

description: Create a blinking or glowing button using pygame


code:
ax.set_ylim(0.1, 1)
import matplotlib.ticker as tick
ax.yaxis.set_major_locator(tick.MultipleLocator(0.1))

rawDescription: Matplotlib label y axis

description: Matplotlib label y axis


code:
# create item widget
item = QListWidgetItem()
w = CustomItemWidget()
w.setTitle = "Title"
w.setDescription = "Blah blah"
# would have a QPixmap already cached
w.setBadgeImage = preCreatedPixmaps['thisBadge']
listWidget.insertItem(item)
listWidget.setItemWidget(item, w)

rawDescription: Custom Items in QListView

description: Custom Items in QListView


code:
import glob, os

os.chdir('/root')

with open('result.txt', 'w+') as result_file:
    for filename in glob.glob('result*.txt'):
        with open(filename) as file:
            result_file.write(file.read())
            # append a line break if you want to separate them
            result_file.write("\n")

rawDescription: File append in python

description: File append in python


rawDescription: Converting a very small python Decimal into a non-scientific notation string


code: "hello world my name is".split(' ')

rawDescription: cutting a string at spaces python

description: Cutting a string at spaces python


code:
np.random.uniform(5,10) # A single value
np.random.uniform(5,10,[2,3]) # A 2x3 array

rawDescription: sampling random floats on a range in numpy

description: Sampling random floats on a range in numpy


rawDescription: How to keep ranges with python?

description: Keep ranges with python


code:
from datetime import date, timedelta
a=[date.today(), date.today() + timedelta(days=1), date.today() - timedelta(days=1)]
a
a.sort()
a
a[0] # min
a[-1] # max

rawDescription: How to sort list of date object?

description: Sort list of date object


code:
import os

if __name__ == '__main__':
    while True:
        exec_cmd = raw_input("enter your command:")
        os.system(exec_cmd)

rawDescription: How can I execute an os/shell command from python

description: Execute an os/shell command from python


code: [Config(*x) for x in itertools.product([False, True], repeat=4)]

rawDescription: generate cartesian product of boolean parameter values

description: Generate cartesian product of boolean parameter values


code:
def multicolor_message(msgs, colors=None):
  if colors is None:
    colors=[libtcod.white for x in len(msgs)]

rawDescription: List comprehension in function arguments


code:
num1 = input('Enter 1st number:')
num2 = input('Enter 2nd number:')

# while both strings are not a bunch of digits

while not (num1.isdigit() and num2.isdigit()):
    num1 = input('Enter 1st number:')
    num2 = input('Enter 2nd number:')

rawDescription: How I can get back at the beginning of my code, when statement isn't meet?


code:
f = open(r'full_path_to_your_file', 'r')    # pass an appropriate path of the required file
lines = f.readlines()
lines[n-1] = "your new text for this line"    # n is the line number you want to edit; subtract 1 as indexing of list starts from 0
f.close()   # close the file and reopen in write mode to enable writing to file; you can also open in append mode and use "seek", but you will have some unwanted old data if the new data is shorter in length.

f = open(r'full_path_to_your_file', 'w')
f.writelines(lines)
# do the remaining operations on the file
f.close()

rawDescription: Modifying a single line in a file

description: Modifying a single line in a file


code:
from collections import defaultdict

d = defaultdict(dict) # dict where the default values are dicts.
for a, b, c in list_of_tuples: # Each tuple is "key1, key2, value"
    d[a][b] = c

rawDescription: How to convert tuple to a multi nested dictionary in python?

description: Convert tuple to a multi nested dictionary in python


rawDescription: Using Pandas how do I count groups of data?


code: sliceno = numpy.int32((pi + numpy.arctan2(Y, X)) * (N / (2*pi)))

rawDescription: Slicing a circle in equal segments, Python


code:
arr = np.zeros((n,n))
for i,(t,e,b) in enumerate(g):
    arr[i,np.array(t) - 1] = e

rawDescription: Most efficient way to construct a square matrix in numpy using values from a generator


code:
import itertools as IT

targets = 'domain forwarding transport user'.split()
actions = 'list add'.split()

dispatch = {key:globals()['%s_%s' % key] for key in IT.product(targets, actions)}

# This calls the function specified by (target, action).
# The `dict.get` method is used so that if the key is not in `dispatch`, the `all_list` function is called.
dispatch.get((args.target, args.action), all_list)()

rawDescription: Using positional arguments from argparse as function name


code:
globals().update((name, getattr(context._default_context, name))
                 for name in context._default_context.__all__)
__all__ = context._default_context.__all__

rawDescription: In Python's multiprocessing package, why is there multiprocessing.Pool and multiprocessing.pool.Pool?


code:
w = QWidget()
w.resize(800, 800)

i = QWidget(w)
i.move(200, 200)
i.setFixedSize(400, 400)
#alternatively: i.setGeometry(200, 200, 400, 400)

i.setStyleSheet("QWidget {background-color:blue}")
w.show()

rawDescription: PyQt4: How to specify the length and width of the squares of the QGridLayout


rawDescription: Aligning Floats to decimal points in Python 2.7 using the format() mini-language


code:
import numpy as np
x = np.array(x).reshape((12, 18))
y = np.array(y).reshape((12, 18))
z = np.array(z).reshape((12, 18))
mlab.surf(x, y, z, ...)

rawDescription: 3D Surface Plots Using Mayavi.mlab

description: 3D Surface Plots Using Mayavi.mlab


code:
name = request.forms.get('name')
data = request.files.get('data')
raw = ""
if name and data.file:
    while True:
        datachunk = data.file.read(1024)
        if not datachunk:
            break
        raw = raw + datachunk

    filename = data.filename
    return "Hello %s! You uploaded %s (%d bytes)." % (name, filename, len(raw))

rawDescription: How to check size of uploaded file safely in bottlepy?

description: Check size of uploaded file safely in bottlepy


code:
row = [4,7]
data = range(10000)
data[slice(*row)]

rawDescription: how to use the row [a,b] to index another array as data[a:b]?

description: Use the row [a,b] to index another array as data[a:b]


code:
def char_check(x,y):
    if set(x) & set(y):
        return True
    else:
        return False

rawDescription: In Python (2.7.3) how do I write a function that answers if any characters in str(x) are in str(y) (or str(y) are in str(x))?


code:
mydict = {'a': 1, 'b': 89, 'c': 56, 'd': 9123, 'e':-23}
mylist = []
for k in mydict:
    mylist.append(mydict[k])

mylist.sort()
mylist.reverse()
mylist

rawDescription: How do I loop over a map object's 2ND value in reverse?

description: Loop over a map object's 2ND value in reverse


code: [m.group(1) for l in lines for m in [regex.search(l)] if m]

rawDescription: How to use re match objects in a list comprehension

description: Use re match objects in a list comprehension


code:
import Image
import numpy as np

im = Image.open('snapshot.jpg')

# In this case, it's a 3-band (red, green, blue) image
# so we'll unpack the bands into 3 separate 2D arrays.
r, g, b = np.array(im).T

# Let's make an alpha (transparency) band based on where blue is < 100
a = np.zeros_like(b)
a[b < 100] = 255

# Random math... This isn't meant to look good...
# Keep in mind that these are unsigned 8-bit integers, and will overflow.
# You may want to convert to floats for some calculations.
r = (b + g) * 5

# Put things back together and save the result...
im = Image.fromarray(np.dstack([item.T for item in (r,g,b,a)]))

im.save('output.png')

rawDescription: edit rgb values in a jpg with python

description: Edit rgb values in a jpg with python


code:
def getWins():
    week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    scores = {} # Perhaps you want to return a dictionary? If not, just set this to 0 and += score below. Also, remove sum()
    for day in week:
        score = int(raw_input("Enter the number of wins on {}: ".format(day)))
        scores[day] = score
    return sum(scores.values())

getWins()
"""
>>> getWins()
Enter the number of wins on Monday: 5
Enter the number of wins on Tuesday: 4
Enter the number of wins on Wednesday: 5
Enter the number of wins on Thursday: 1
Enter the number of wins on Friday: 3
Enter the number of wins on Saturday: 7
Enter the number of wins on Sunday: 9
34
"""

rawDescription: I would like to know if this is possible in python


code:
def run(self):
    threads = [
         threading.Thread(target=run_A),
         threading.Thread(target=run_B)
    ]

    for thread in threads:
         thread.start()
    for thread in threads:
         thread.join()

rawDescription: Python Run Two Functions With Different Timers In One Daemon


code:
z = zipfile.ZipFile(file_name)
z.extractall()

rawDescription: Extract a zip file in python [zip file contains .img file in it, and zipfile gets stuck]


code:
buttons = [stop, lap, reset, close]
my_font = tkFont.Font(family='Helvetica',size='18')
for button in buttons:
    button.config(font=my_font)

rawDescription: Changing font for four buttons at once in tkinter


code:
df = pd.DataFrame(["BULL GOOGLE X3 VON", "BEAR TWITTER 12X S"], columns ["Name"])

#Dict
google = {"GOOG":"Google"}
twitter = {"TWITT":"Twitter"}
dictionary = google.copy()
dictionary.update(twitter)

#Regex
regex = re.compile(r"\b((%s)\S*)\b" %"|".join(dictionary.keys()), re.I)

def dictionary_lookup(match):
    return dictionary[match.group(2)]

#Function
def f(value):
    match = dictionary[regex.search(value).group(2)]
    #Do stuff
    statement = regex.sub(dictionary_lookup, value)
    return statement

#Map Function
df["Statement"] = df["Name"].map(lambda x:f(x))

rawDescription: Pandas: Make function map partial Dict match


code:
for xs in itertools.product('ab', repeat=2): # 2 == len('ab')
    print(xs)
for xs in itertools.product('ab', repeat=2):
    print(''.join(xs))

rawDescription: Finding all possible combinations

description: Finding all possible combinations


code:
def getname():
    name = raw_input("What is your name?")
    print("Ok," + name)
    return name # return the name so we can use it later

def getage(name):
    age = raw_input("What is you age," + name)
    print ("Great!")

name = getname() # assign name to return value from getname
getage(name) # pass it to getage

rawDescription: Why when I define a variable in one function, it can't be accesed in another one


code:
import types
types.FunctionType
def func():
    pass
type(func)
isinstance(func, types.FunctionType)

rawDescription: Type of Python function pointer

description: Type of Python function pointer


code:
df = pd.DataFrame(['Slow', 'Normal', 'Fast', 'Slow'], columns=['Speed'])
df
pd.get_dummies(df['Speed'])

rawDescription: Creating new binary columns from single string column in pandas


code:
from math import cos

def diff(lhs, rhs, delta):
    return abs(lhs - rhs) > delta

curr = 2.0
prev = 0.1
while diff(curr, prev, 0.00000001):
    curr, prev = cos(curr), curr

rawDescription: Is it normal that my 2015 macbook air having trouble at running a simple while loop?


code:
# get the width of your widest label, since every label will need
# to shift by this amount after we align to the right
shift = max([t.get_window_extent().width for t in legend.get_texts()])
for t in legend.get_texts():
    t.set_ha('right') # ha is alias for horizontalalignment
    t.set_position((shift,0))

rawDescription: Text alignment in a Matplotlib legend

description: Text alignment in a Matplotlib legend


code: id = mongoengine.StringField(required=True, primary_key=True)

rawDescription: MongoEngine specifying an ID

description: MongoEngine specifying an ID


code:
def update(self, collidable):
    self.rect.x += self.hspeed

    collision_list = pygame.sprite.spritecollide(self, collidable, False)
    for collided_object in collision_list:
        if (self.hspeed > 0):
            # right direction
            self.rect.left = collided_object.rect.right # rect.right and rect.left swapped

        elif (self.hspeed < 0):
            # left direction
            self.rect.right = collided_object.rect.left # rect.right and rect.left swapped

    self.rect.y += self.vspeed

    collision_list = pygame.sprite.spritecollide(self, collidable, False)
    for collided_object in collision_list:
        if (self.vspeed > 0):
         # down direction
            self.rect.bottom = collided_object.rect.up

        elif (self.vspeed < 0):
            # up direction
            self.rect.top = collided_object.rect.bottom

rawDescription: Trying to make a "solid" block in pygame


code:
def write_to_file(file_name, n_t_argument):
    with open(file_name + '.txt', 'a', newline='') as outputfile:
        wrtr  = csv.writer(outputfile, dialect = 'excel-tab')
        wrtr.writerow(n_t_argument)

rawDescription: Using writerow with numbers

description: Using writerow with numbers


code: lineNumStr = str(int(lineNumStr)+1)

rawDescription: Number String converting to INT,adding to it, and back to string


code:
from myapp.utils import my_cool_func

def view_coolness(request):
    data = my_cool_func(request)
    return render_to_response("xxx.html")

rawDescription: Django: Where to put helper functions?

description: Django: Where to put helper functions


code:
from bisect import bisect_left

x = [(0, 1), (0, 2), (1, 1), (1, 2), (2, 1), (2, 2)]

start = bisect_left(x, (1, None))  # index of the very first (1, i)
end = bisect_left(x, (2, None))  # index after the very last (1, i)

y = x[start:end]

# y: [(1, 1), (1, 2)]

rawDescription: Pythonic way of slicing a list w.r.t. first element in tuple


code:
import tornado.ioloop
import tornado.web
from tornado import escape

class MainHandler(tornado.web.RequestHandler):
    def prepare(self):
        # work out url regex match as in
        # tornado/web.py:1283
        handlers = self.application._get_host_handlers(self.request)
        for spec in handlers:
            match = spec.regex.match(self.request.path)
            def unquote(s):
                if s is None: return s
                return escape.url_unescape(s, encoding=None)
            args = [unquote(s) for s in match.groups()]
            # do something with args

    def get(self, who):
        self.write('hello ' + who)

if __name__ == "__main__":
    application = tornado.web.Application([
        (r"/(\w+)", MainHandler),
    ])
    application.listen(8999)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Getting Tornado URL's matched groups

description: Getting Tornado URL's matched groups


code:
import collections
d = collections.defaultdict(int)
for n1, n2, v in arcdata:
    d[min(n1, n2), max(n1, n2)] += v
result = [[k[0], k[1], v] for k, v in d.iteritems()]

rawDescription: Fast way to convert directed to undirected graph (array of lists) in python?


code:
while True:
    # other stuff here

    reply = input("Please choose a menu item:")
    if reply.upper() == 'Q':
        break # Break out of the while loop.

    # We didn't break, so now we can try to parse the input to an integer.
    spent = spent + float(menu[int(reply)+1][2])

rawDescription: How to quit loop to display selected list items

description: Quit loop to display selected list items


code:
main = ["pinecone", "treeleaf", "dishwasher"]
secondary = ["pine", "washer", "unrelated", "flowerbed"]
[x for x in main if any(x in y or y in x for y in secondary)]

rawDescription: Find elements of a list that contain substrings from another list in Python


code:
from PyQt4 import QtCore, QtGui
from functools import partial

class Dialog(QtGui.QDialog):

    DOWN    = 1
    UP      = -1

    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.resize(800,600)

        self.table = QtGui.QTableView(self)
        self.table.setSelectionBehavior(self.table.SelectRows)

        self.model = QtGui.QStandardItemModel(20, 6, self)
        self.table.setModel(self.model)

        self.upBtn = QtGui.QPushButton('Up', self)
        self.downBtn = QtGui.QPushButton('Down', self)

        self.mainLayout = QtGui.QVBoxLayout(self)
        self.mainLayout.addWidget(self.table)

        self.buttonLayout = QtGui.QHBoxLayout()
        self.buttonLayout.addWidget(self.upBtn)
        self.buttonLayout.addWidget(self.downBtn)
        self.mainLayout.addLayout(self.buttonLayout)

        self.upBtn.clicked.connect(partial(self.moveCurrentRow, self.UP))
        self.downBtn.clicked.connect(partial(self.moveCurrentRow, self.DOWN))

        self._initTable()

    def _initTable(self):
        for row in xrange(self.model.rowCount()):
            for col in xrange(self.model.columnCount()):
                item = QtGui.QStandardItem('%d_%d' % (row+1, col+1))
                self.model.setItem(row, col, item)

    def moveCurrentRow(self, direction=DOWN):
        if direction not in (self.DOWN, self.UP):
            return

        model = self.model
        selModel = self.table.selectionModel()
        selected = selModel.selectedRows()
        if not selected:
            return

        items = []
        indexes = sorted(selected, key=lambda x: x.row(), reverse=(direction==self.DOWN))

        for idx in indexes:
            items.append(model.itemFromIndex(idx))
            rowNum = idx.row()
            newRow = rowNum+direction
            if not (0 <= newRow < model.rowCount()):
                continue

            rowItems = model.takeRow(rowNum)
            model.insertRow(newRow, rowItems)

        selModel.clear()
        for item in items:
            selModel.select(item.index(), selModel.Select|selModel.Rows)

if __name__ == "__main__":
    app = QtGui.QApplication([])
    d = Dialog()
    d.show()
    d.raise_()
    app.exec_()

rawDescription: Move row up and down in PyQT4

description: Move row up and down in PyQT4


code:
...
def frameh(self):
    self.fh=Frame(root, width=400, height=40, bg="red")
    self.fh.grid(sticky=N+E+W, row=0, columnspan=2)

def framev(self):
    self.fv=Frame(root, height=200, width=100, bg="blue")
    self.fv.grid(sticky=S+W, row=1, column=0)
...

rawDescription: Widgets not visible or not filling all intended space


code:
some_list = [1, 2, 3]
some_list[-1] = 5 # Set the last element
some_list[-2] = 3 # Set the second to last element
some_list

rawDescription: Getting the last element of a list in Python


code:
import openpyxl

wb = openpyxl.load_workbook('spreadsheet.xlsx')

sheet1 = wb.get_sheet_by_name('Sheet1')
sheet2 = wb.get_sheet_by_name('Sheet2')

for i in range(1, 201):
    if sheet1.cell(row = i, column = 1).value == sheet2.cell(row = i, column = 1).value:
        sheet1.cell(row = i, column = 2).value = sheet2.cell(row = i, column = 2).value
        sheet1.cell(row = i, column = 3).value = sheet2.cell(row = i, column = 3).value

wb.save('spreadsheet2.xlsx')

rawDescription: Loop through and compare spreadsheet cells in Python


code:
with open("somefile.jpg","wb") as f:
     f.write(file.content)

rawDescription: How can I download this image in Python, without seeing "figure is damaged"?

description: Download this image in Python, without seeing "figure is damaged"


code:
frames = range(20)
threads = 16
[frames[x::threads] for x in range(threads)]

rawDescription: a lil bit of programming math

description: A lil bit of programming math


code:
def is_capital(state, city):
    if state not in d:
        return False
    return d[state] == city

rawDescription: Checking dictionary keys and values

description: Checking dictionary keys and values


code:
import numpy as np
first_answer = np.transpose(a)
second_answer = [list(i) for i in zip(*a)]

rawDescription: python matrix transpose and zip

description: Python matrix transpose and zip


code:
_ATTRIBUTE_PATTERN = r'[\w_]+\s*=\s*[\w\.\-]+' # matches ad = 0.013p
# _ATTRIBUTE_PATTERN = r'[^=]+=[^=]+' # matches string containing '='
_PIN_PATTERN = r'\w+\s*:\s*\w+'  # matches VSS:F85
# _PIN_PATTERN = r'[^=]+' # if you want to match any string which does not contain '=' char

rawDescription: How to exclude a sign of equality in regular expressions?

description: Exclude a sign of equality in regular expressions


code:
lines = cv2.HoughLinesP(edge_image, rho=1.0, theta=math.pi/180.0,
                                    threshold=thresholdVal,
                                    minLineLength=minlinelengthVal,
                                    maxLineGap=maxlinegapVal)

rawDescription: Probabilistic Hough transform in OpenCV 2.4.9 (Python)


code:
x = re.search('\((.*),\s*(.*)\)', " {'result':(Boolean, MessageString)} ")
x.group(1)
x.group(2)

rawDescription: Regular expression to extract "Boolean" and "MessageString" from {'result':(Boolean, MessageString)}


code:
import matplotlib.pyplot as plt

# Create Figure and Axes instances
fig,ax = plt.subplots(1)

# Make your plot, set your axes labels
ax.plot(sim_1['t'],sim_1['V'],'k')
ax.set_ylabel('V')
ax.set_xlabel('t')

# Turn off tick labels
ax.set_yticklabels([])
ax.set_xticklabels([])

plt.show()

rawDescription: Hide axis values in matplotlib

description: Hide axis values in matplotlib


code:
lst1 = ['a', 'b', 'c', 'd', 'e']
lst2 = ['q', 'r', 's']
mapping = [4, 0, 3]

for lst2_n, lst1_n in enumerate(mapping):
    lst1[lst1_n] = lst2[lst2_n]

rawDescription: How to modify the elements of one list based on another

description: Modify the elements of one list based on another


code:
def decorator_name(whatevs):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            pass # sweet decorator goodness
        return wrapper
    return decorator

rawDescription: Python naming conventions in decorators

description: Python naming conventions in decorators


code:
# annotate whether you've already voted on this item
table = Vote._meta.db_table
select = 'SELECT COUNT(id) FROM %s' %table
where1 = 'WHERE ' + table + '.user_id = %s'
where2 = 'AND ' + table + '.item_id = appname_item.id'
items = items.extra(
        select={'votes':" ".join((select, where1, where2,))},
        select_params=(request.user.id,)
    )

rawDescription: Django: Determining if a user has voted or not


code: bar = [ i.bar for i in foo ]

rawDescription: Python make list of list contents

description: Python make list of list contents


code:
#!/usr/bin/env python

import os

# A dict with keys being the old filenames and values being the new filenames
mapping = {}

# Read through the mapping file line-by-line and populate 'mapping'
with open('mapping.txt') as mapping_file:
    for line in mapping_file:
        # Split the line along whitespace
        # Note: this fails if your filenames have whitespace
        new_name, old_name = line.split()
        mapping[old_name] = new_name

suffix = '_full'

# List the files in the current directory
for filename in os.listdir('.'):
    root, extension = os.path.splitext(filename)
    if not root.endswith(suffix):
        # File doesn't end with this suffix; ignore it
        continue
    # Strip off the number of characters that make up suffix
    stripped_root = root[:-len(suffix)]
    if stripped_root in mapping:
        os.rename(filename, ''.join(mapping[stripped_root] + suffix + extension))

rawDescription: Bulk renaming of files based on lookup

description: Bulk renaming of files based on lookup


code:
import re

keyword = input("...")
found_at = []
counter = 0  # Number_Of_Key_Words is not a good python name
# file is a PY2 built in, so I use 'f' instead
# also you should be explicit for the open mode, 'r' == read mode
with open("...", "r") as f:
    for num, line in enumerate(f, 1):
        # re.findall() will return a list of all keyword occurrence
        # len() will then measure the occurrence effectively
        count = len(re.findall(keyword, line))
        if count > 0:  # ie. keyword in line at least once
            found_at.append(num)
            counter += count

    print(found_at)
    print(counter)

rawDescription: Python 3 searching for a keyword more than once per line in a text file


rawDescription: Clean Way to Fill Third Dimension of Numpy Array


code:
for line in open('myfile.txt'):  # opened in text-mode; all EOLs are converted to '\n'
    line = line.rstrip('\n')
    process(line)

rawDescription: End-line characters from lines read from text file, using Python


code: names = [v[0] for v in professions.values()]

rawDescription: Get list from list values in a python dictionary


code:
class MyMeta(type):
    def __new__(mcl, name, bases, nmspc):
        if "__call__" in nmspc:
            nmspc["__call__"] = trace(nmspc["__call__"])
        return super(MyMeta, mcl).__new__(mcl, name, bases, nmspc)

class BaseClass(object):
    __metaclass__ = MyMeta

rawDescription: Python: Force decorator inheritance?

description: Python: Force decorator inheritance


code: np.transpose(np.meshgrid(a, b))

rawDescription: All pairs of numbers between 2 arrays

description: All pairs of numbers between 2 arrays


code:
class User(db.Document):
    email = db.EmailField()
    username = db.StringField()
    password = db.StringField()
    liked_games = db.ListField(
        db.ReferenceField('Game', reverse_delete_rule=db.PULL)
    )

rawDescription: Resolve circular import issue

description: Resolve circular import issue


code:
for klass in [FacebookProfile, FacebookUser, FacebookLike, FacebookInvite]:
    try:
        for fb in klass.objects.filter(user_id=user.id):
            fb.delete()
    except klass.DoesNotExist:
        pass

rawDescription: Python: loop over classes?

description: Python: loop over classes


code:
class MainHandler(webapp2.RequestHandler):
    def test_download(self):
        self.response.headers.add_header('content-disposition','attachment',filename='text.txt')

        self.response.write("hello world")

rawDescription: Serve a txt file programmatically with gae python


code:
router.register(r'planner_agent', views.PlannerAgentViewSet, base_name='planner_agent')
router.register(r'planner_client', views.PlannerClientViewSet, base_name='planner_client')

rawDescription: Django Rest Framework viewsets queyset duplicate


code:
import numpy
a = numpy.array([1,2,3,4,5,6])
b = numpy.array([2,3,5])
numpy.setxor1d(a, b)

rawDescription: How to convert a python set to a numpy array?

description: Convert a python set to a numpy array


code:
import android
import datetime
droid = android.Android()
s1= '09:40:00'
s2= datetime.datetime.now().strftime('%H:%M:%S')
s3= datetime.datetime.now().strftime('%I:%M:%S %p')
FMT = '%H:%M:%S'
tdelta = datetime.datetime.strptime(s2,FMT) -    datetime.datetime.strptime(s1,FMT)
print ('I have arrived ['+str(tdelta)+']')
number = "XXXXXXXXXX"
message = str(tdelta)
droid.smsSend(number, message.encode("utf"))

rawDescription: Merge Python and Android SL4A code

description: Merge Python and Android SL4A code


code: y, x = a.shape

rawDescription: How can I get the x and y dimensions of a ndarray - Numpy / Python

description: Get the x and y dimensions of a ndarray - Numpy / Python


code:
def IsCloseEnough(num1, num2 ):
     return abs(float(num1 - num2) / float(num1)) < 0.1

rawDescription: Efficiently checking if number is in range of 2nd number +-10%?


code:
fields = [tup[0] for tup in querycurs.description]
dict_agriculture = [dict(zip(fields, row)) for row in querycurs]

rawDescription: Creating list of dictionaries efficiently


code:
data = get_file()
samples_subset1(data)

rawDescription: python: proper usage of global variable

description: Python: proper usage of global variable


rawDescription: Optional named groups Python re

description: Optional named groups Python re


code:
for index in range(1, count + 1):
    currentChart = wbSheet.ChartObjects(index)
    currentChart.Copy
    currentChart.Chart.Export("chart" + str(index) + ".png")

rawDescription: Using win32com via python to scrape excel file for chart objects and convert them to images


code:
from PIL import Image

image = Image.open('logo.png')
assert im.mode.endswith('A'), 'This will only work with images having alpha!'

image.load()
alpha = image.split()[-1]
image2 = Image.new(image.mode, image.size, (255, 0, 0, 0))
image2.putalpha(alpha)

image2.save('logo-red.png')

rawDescription: How can I convert an partially alpha transparent image to have single (non-transparent) colour in PIL?

description: Convert an partially alpha transparent image to have single (non-transparent) colour in PIL


code:
bt_retval = bt(x, y, carries, n)
if bt_retval is not None:
    return bt_retval
del bt_retval # optional (it really isn't wasting much memory)
# otherwise carry on

rawDescription: Return expensive function call if not None


code:
list_of_menuitems = [['image00', 'image01'], ['image10'], []]
import itertools
chain = itertools.chain(*list_of_menuitems)
print(list(chain))

rawDescription: Flattening a shallow list in Python

description: Flattening a shallow list in Python


code: len(set([x.attrib for x in objects]))

rawDescription: Python : count the number of different values for a given attribute in a list of objects


code:
unpack_options = { 'unpack_pdb_line' : unpack_pdb_line,
                   'some_other' : some_other_function }

unpack_function = unpack_options[options.unpack_method]

rawDescription: Python: Convert string into function name; getattr or equal?


rawDescription: How can I use Python to get the system hostname?

description: Use Python to get the system hostname


code: strategies = [strategy0.__name__, strategy1.__name__, strategy2.__name__, strategy3.__name__]

rawDescription: Python3 changes function name <...>

description: Python3 changes function name <...>


code:
def ask(text):
    temp = raw_input(text)
    try:
        retVal = int(temp)
        return retVal
    except ValueError:
        return False

a = False
b = False
c = False

while not a:
    a = ask("Enter A:")
    if a == False:
        continue
    while not b:
        b = ask("ENter B:")
        if b == False:
            continue
        while not c:
            c = ask("Enter C:")

rawDescription: How to validate python raw_input for digits

description: Validate python raw_input for digits


code:
from pylab import *

N = 10
r0 = 0.6
x = linspace(0, 1, 10)
y = linspace(0, 1, 10)
X, Y = meshgrid(x, y)
size = rand(N,N)
c = size
scatter(X,Y,s=700*size, marker='o', c=c)

show()

rawDescription: Matplotlib imshow with circular units

description: Matplotlib imshow with circular units


code:
import socket
from threading import Thread

def wait_response(s):
    while True:
        data, addr = s.recvfrom(1024)
        if data:
            data = data.decode('utf-8')
            print("Received from server: " + data)

def main():
    host = ''
    port = 5000
    server = ('', 6000)

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.bind((host, port))

    d = Thread(target=wait_response, args = (s,))
    d.setDaemon(True)
    d.start()

    message = input("->")

    while message != 'q':
        s.sendto(message.encode('utf-8'), server)
        message = input("->")
    s.close()

if __name__ == '__main__':
        main()

rawDescription: Threading issue in Python

description: Threading issue in Python


code:
self.button = Tkinter.Button(master=self.root,
                             command=lambda:sys.stdout.write("Hello!\n"),
                             text='say hello')

rawDescription: Code style - 'hiding' functions inside other functions


code:
def list_delta(before, after):
    out = {}

    for key in before:
        if isinstance(before[key], list):
            out[key] = len(after[key]) - len(before[key])

    return out

before = {'name': 'davidism', 'numbers': [0, 1, 2, 3, 4]}
after = do_update(before)
# after = {'name': 'davidism', 'numbers': [0, 1, 2, 3, 4, 5]}
list_delta(before, after)
# returns {'numbers': 1}

rawDescription: Retrieve the fields that have been updated in a record


code:
def process_number(result,tokval):
    if '.' in tokval:
        result.extend([
            (NAME, 'Decimal'),
            (OP, '('),
            (STRING, repr(tokval)),
            (OP, ')')
            ])
def process_default(result,tokval):
    result.append((toknum, tokval))

dispatcher={NUMBER: process_number, }
for toknum, tokval, _, _, _  in g:
    dispatcher.get(toknum,process_default)(result,tokval)

rawDescription: Efficient and clean way of growing a tokenizer function in Python


code:
def calculate(self, alist, days=2):

    # rest of your functions

    tol=0.01
    averages[:] = ("%.2f" % avg if abs(avg)>=tol else ' '  for avg in averages)

    return averages, signals

rawDescription: removing initial values from a list

description: Removing initial values from a list


rawDescription: Calling types via their name as a string in Python


code: MyList = [v for v in MyList if v != 'hi']

rawDescription: Completely remove one item from a list

description: Completely remove one item from a list


code:
if y == 1:
    return x * x
else:
    # return x**2 * real_multiply(x, 2**(y-1))
    return x * 2 * real_multiply(x, real_multiply(2, y-1))

rawDescription: Using recursion to raise a base to an exponent to an exponent


rawDescription: How to change bits in byte with python?

description: Change bits in byte with python


code:
class Application(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.grid()

        self.entry1 = Text(self)
        self.entry1.grid(row=0, column=0, sticky=W)

        self.bttn1 = Button(self, text="Execute code", command=self.execute_code)
        self.bttn1.grid(row=1, column=0, sticky=W)

    def execute_code(self):
        code = self.entry1.get("0.0", "end")
        try:
            exec(code)
        except:
            print("There is something wrong with this code!")

rawDescription: My exec program isn't working

description: My exec program isn't working


code:
def find_max(pyramid, x, y):
    if y >= len(pyramid):   # base case, we're off the bottom of the pyramid
        return 0            # so, return 0 immediately, without recursing

    left_value = find_max(pyramid, x - 1, y + 1)     # first recursive call
    right_value = find_max(pyramid, x + 1, y + 1)    # second recursive call

    if left_value > right_value:
        return left_value + pyramid[y][x]
    else:
        return right_value + pyramid[y][x]

rawDescription: Recursion not breaking

description: Recursion not breaking


code:
class SampleView(APIView):

 def post(self, request, format=None):
     if request.version == '1':
         return Response(status=status.HTTP_410_GONE)

rawDescription: Django Rest Framework - how to get Http header information in urls.py


code:
x=np.array([3,4,5])
y=np.array([2,50,-1])
z=np.array([30,0,3])
mya = [x,y,z]
maximum = np.amax(mya, axis=0)
# maximum will store a list as [maximumofx, maximumofy, maximumofz] -> [30,50,5]

rawDescription: Most pythonic way to find the maximum elements out of list of np.array?


code:
def search_photos(fl_tags, license_val=''):
    if not license_val:
        photos = flickr.photos_search(
            tags=fl_tags,
            is_commons="True")
    else:
        photos = flickr.photos_search(
            tags=fl_tags,
            license=license_val)
    return photos

search_photos("foo") # gives you the same output as before
search_photos("foo", "9") # gives you the search with license as 9

rawDescription: Passing key-value pairs as function parameters in Python


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

fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
ax.plot(x,y)
ax.set_yticklabels([str(abs(x)) for x in ax.get_yticks()])
ax.show()

rawDescription: Convert negative y axis to positive (matplotlib)


code: any(a[i:i + len(b)] == b for i in range(len(a) - len(b) + 1))

rawDescription: Seeing if a list exists within another list?


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

fig = plt.figure()
x = np.linspace(-np.pi, np.pi, 100)
y = 2*np.sin(x)

ax = fig.add_subplot(111)
ax.set_title('zeroed spines')
ax.plot(x, y)
ax.spines['left'].set_position('zero')
ax.spines['right'].set_color('none')
ax.spines['bottom'].set_position('zero')
ax.spines['top'].set_color('none')

# remove the ticks from the top and right edges
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

rawDescription: How can I draw axis lines inside a plot in Matplotlib?

description: Draw axis lines inside a plot in Matplotlib


code:
the_string = "New Cars, Used Cars, Car Reviews, Car Finance Advice - Cars.com"
re.sub(r'(car)', r'<b>\1</b>', the_string, flags=re.I)

rawDescription: Bold searched text that is contained in a string with Python


code:
import re
parts = [
    r'(?P<host>\S+(,\s*\S+)*)',         # comma-separated list of hosts
    r'\S+',                             # indent %l (unused)
    r'(?P<user>\S+)',                   # user %u
    r'\[(?P<time>.+)\]',                # time %t
    r'"(?P<request>.+)"',               # request "%r"
    r'(?P<status>[0-9]+)',              # status %>s
    r'(?P<size>\S+)',                   # size %b (careful, can be '-')
    r'"(?P<referer>.*)"',               # referer "%{Referer}i"
    r'"(?P<agent>.*)"',                 # user agent "%{User-agent}i"
]
pattern = re.compile(r'\s+'.join(parts)+r'\s*\Z')

test = 'xxx.xx.xx.xxx, yy.yyy.yy.yyy - - [14/Feb/2013:03:55:21 +0000] "GET /alink HTTP/1.0" 200 90210 "http://www.google.com/search" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.4 (KHTML,like Gecko; Google Web Preview) Chrome/22.0.1229 Safari/537.4"'
m = pattern.match(test)
res = m.groupdict()

rawDescription: Parse apache log that has 2 ip addresses


code:
import bpy

if(len(bpy.data.cameras) == 1):
    obj = bpy.data.objects['Camera'] # bpy.types.Camera
    obj.location.x = 0.0
    obj.location.y = -10.0
    obj.location.z = 10.0
    obj.keyframe_insert(data_path="location", frame=10.0)
    obj.location.x = 10.0
    obj.location.y = 0.0
    obj.location.z = 5.0
    obj.keyframe_insert(data_path="location", frame=20.0)

rawDescription: How to move a camera in Blender 2.61 with Python

description: Move a camera in Blender 2.61 with Python


code:
rst_prolog = """
.. role:: test2
"""

rawDescription: custom CSS styles in sphinx?

description: Custom CSS styles in sphinx


code:
import wx
import string
AF = string.ascii_uppercase[:7]

class MyFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, size=(300,300))

        a, b, c, d, e, f, g = [wx.Button(self, -1, 4*c) for c in AF]
        a.SetMaxSize((200,100))   # 'a' won't get bigger than 200 wide

        # build the top row (with sizers I usually work from inside to out)
        hs0 = wx.BoxSizer(wx.HORIZONTAL)
        hs0.Add(a, 1, wx.ALIGN_LEFT)  # 1 here means expand with weight 1
        hs0.Add((0,0), 1)  # also expand the spacing
        hs0.Add(b, 0, wx.ALIGN_RIGHT)  # 0 means don't expand this

        # build the bottom row
        hs1 = wx.BoxSizer(wx.HORIZONTAL)
        hs1.Add(d, 0, wx.ALIGN_LEFT)
        hs1.Add((10,10), 0)
        hs1.Add(e, 0)
        hs1.Add((10,10), 0)
        hs1.Add(f, 0)
        hs1.Add((10, 10), 1)
        hs1.Add(g, 0, wx.ALIGN_RIGHT)

        # stack the rows vertically
        vs = wx.BoxSizer(wx.VERTICAL)
        vs.Add(hs0, flag=wx.EXPAND)   # expand in the orthogonal direction to sizer (here horizontal)
        vs.Add(c, 1, flag=wx.EXPAND)
        vs.Add(hs1, flag=wx.EXPAND)
        self.SetSizer(vs)

app = wx.PySimpleApp()
frame = MyFrame()
frame.Show(1)
app.MainLoop()

rawDescription: Appropriate wx.Sizer(s) for the job?

description: Appropriate wx.Sizer(s) for the job


code:
import requests
import json
headers = {'SEC': 'c79c321c-3061-49f1-8117-0d6f873a6f26', 'Allow-Hidden': true}
response = requests.get("https://127.0.0.1/api/configuration/log_sources", headers=headers , verify=False)
json_data = json.loads(response.text)
print (json_data)

rawDescription: How to set Allow-Hidden header to true to get undocumented endpoint resources in API?

description: Set Allow-Hidden header to true to get undocumented endpoint resources in API


code:
def auth_header(creds, http_session):
    auth = 'OAuth ' + 'oauth_consumer_key=\"' + creds['oauth_consumer_key']
    auth = auth + '\",oauth_nonce=\"' + creds['oauth_nonce']
    auth = auth + '\",oauth_signature=\"' + creds['oauth_signature']
    auth = auth + '\",oauth_signature_method=\"' + creds['oauth_signature_method']
    auth = auth + '\",oauth_timestamp=\"' + creds['oauth_timestamp']
    auth = auth + '\",oauth_version=\"' + creds['oauth_version'] + '\"'
    http_session.headers['Authorization'] = auth

rawDescription: How would you format an Auth/OAuth header like this a Python dict?


rawDescription: Is it possible to capture optional argument for handlers in Tornado


code:
session = requests.Session()

def web_spider(max_pages, query):
    page = 1
    while page <= max_pages:
        url = 'http://website.com/search/index'
        params = {'page': page, 'q': query}
        source_code = session.get(url, params=params)
        plain_text = source_code.content
        soup = BeautifulSoup(plain_text)
        for link in soup.select('a.comments_link[href]'):
            href = 'http://website.com/' + link['href']
            print(href)
        page += 1

rawDescription: Simulating cookies with python web crawler


code: sorted(list_with_none, key=lambda k: (k[col] is not None, k[col] != "", k[col]), reverse=True)

rawDescription: Reverse sort when values are None or empty strings in Python 3


code:
import csv
DELIMITER = ','

with open('data.csv', 'wb') as csvfile:
    writer = csv.writer(csvfile, delimiter=DELIMITER)
    row = [None, None]
    with open('input_data.txt', 'rt') as textfile:
        for line in (line.strip() for line in textfile):
            if line.endswith('(i)'):
                row[0] = line
                writer.writerow(row)
            else:
                row[1] = line

rawDescription: Reformat CSV file in python for spreadsheet


code:
import clr
clr.AddReference('MyInterfaces')

from Company.Shared.MyInterfaces import IDevice

rawDescription: Having trouble importing C# interface into Python


rawDescription: Subtract items in a single list and retrieve items that match a condition


code:
import string
string.uppercase
string.uppercase[5:]+string.uppercase[:5]
table = string.maketrans(string.uppercase, string.uppercase[5:]+string.uppercase[:5])
'CAR'.translate(table)
'HELLO'.translate(table)

rawDescription: Encrypting the lines in a file

description: Encrypting the lines in a file


code:
import glob
filenames = glob.glob('<some_path>/*.<extension>')

rawDescription: read filenames and write directly into a list

description: Read filenames and write directly into a list


code:
import datetime

_3AM = datetime.time(hour=3)
_FRI = 4 # Monday=0 for weekday()

def next_friday_3am(now):
    now += datetime.timedelta(days=7)
    if now.time() < _3AM:
        now = now.combine(now.date(),_3AM)
    else:
        now = now.combine(now.date(),_3AM) + datetime.timedelta(days=1)
    return now + datetime.timedelta((_FRI - now.weekday()) % 7)

if __name__ == '__main__':
    start = datetime.datetime.now()
    for i in xrange(7*24*60*60):
        now = start + datetime.timedelta(seconds=i)
        then = next_friday_3am(now)
        assert datetime.timedelta(days=7) < then - now <= datetime.timedelta(days=14)
        assert then.weekday() == _FRI
        assert then.time() == _3AM

rawDescription: How to calculate next Friday at 3am?

description: Calculate next Friday at 3am


code:
with open('yourtextfile.txt') as file: #this is like file=open('yourtextfile.txt')
    lines=file.readlines()                   #read all the lines in the file
                                       #when the code executed in the with statement is done, the file is automatically closed, which is why most people use this (no need for .close()).

rawDescription: Safe way to read directory in Python

description: Safe way to read directory in Python


code:
import requests
#Set the stock we are interested in, AAPL is Apple stock code
stock = 'AAPL'
#Your code
api_url = 'https://www.quandl.com/api/v1/datasets/WIKI/%s.json' % stock
session = requests.Session()
session.mount('http://', requests.adapters.HTTPAdapter(max_retries=3))
raw_data = session.get(api_url)

# Probably want to check that requests.Response is 200 - OK here
# to make sure we got the content successfully.

# requests.Response has a function to return json file as python dict
aapl_stock = raw_data.json()
# We can then look at the keys to see what we have access to
aapl_stock.keys()
# column_names Seems to be describing the individual data points
aapl_stock['column_names']
# A big list of data, lets just look at the first ten points...
aapl_stock['data'][0:10]

rawDescription: Quandl data, API call

description: Quandl data, API call


code:
import struct

def nth_fp(n):
    if n < 0:
        sign_bit = 0x8000000000000000
        n = -n
    else:
        sign_bit = 0
    if n >= 0x7ff0000000000000:
        raise ValueError('out of range')
    bit_pattern = struct.pack('Q', n | sign_bit)
    return struct.unpack('d', bit_pattern)[0]

rawDescription: How to compute the n-th floating point from 0 in python

description: Compute the n-th floating point from 0 in python


code:
with open('f.txt') as raw:
    data = ''.join(raw.read().split()) #If you want to remove newlines only, use split('\n')

with open('f.txt', 'w') as raw:
    raw.write(data)

rawDescription: How remove large space between the sentences in text file?


code:
import matplotlib.pylab as pl

for i in range(0, 2):
    pl.plot([0, df.iloc[i][0]], [0,df.iloc[i][1]], label=(i+1))
pl.legend(loc='upper left')
pl.show()

rawDescription: Plot lines from pandas dataframe

description: Plot lines from pandas dataframe


code:
from sets import Set
...
call_range_set = Set()
while call_start_epoch <= call_end_epoch:
    call_duration_two = call_start_epoch + 60
    call_start_epoch += 60
    call_range_set.add(call_duration_two)
...

rawDescription: Dynamically creating a new set for each iteration of a while loop


code:
for entry in info_estab:
    if entry.get('Year') == y:
        entry[m] += 1
    else:
        new_info = {'Year': y, 'Jan': 0, 'Feb': 0, 'Mar': 0, 'Apr': 0, 'Mai': 0, 'Jun': 0, 'Jul': 0, 'Aug': 0, 'Sep': 0, 'Oct': 0, 'Nov': 0, 'Dec': 0}
        new_info[m] = 1
        info_estab.append(new_info)

rawDescription: Iteration over dictionary - Python

description: Iteration over dictionary - Python


code: img.sum(axis=(1, 2))

rawDescription: Efficient conversion of a 3D numpy array to a 1D numpy array


code:
chunksize, extra = divmod(len(iterable), len(self._pool) * 4)
if extra:
  chunksize += 1

rawDescription: multiprocessing pool.map call functions in certain order

description: Multiprocessing pool.map call functions in certain order


code:
from __future__ import with_statement
import random
import os

with open('File1', 'r') as f1:
    beginnings = [word.rstrip() for word in f1]

with open('File2', 'r') as f2:
    endings = [word.rstrip() for word in f2]

with open('File3', 'w') as f3:
    for beginning in beginnings:
        f3.write('%s %s' % (beginning, random.choice(endings)))
        f3.write(os.linesep)

rawDescription: Python: Random combination from two files


code:
page = 1
numResults = 0

while page <= max_page:
    url = 'http://www.hdwallpapers.in/page/' + str(page)
    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text, 'html.parser')

    for div in soup.select('.thumb a'):
        href = 'http://www.hdwallpapers.in' + div.get('href')
        numResults += 1
    page += 1

print("There are " + numResults + " results.")

rawDescription: Python BeautifulSoup : Is there a way to count the number of results crawled?


code:
s = ''
for i in word:
  if i in vowel:
     s += i*4
  else:
     s += i
s += '!'

rawDescription: Python: Adding Copies of a Character in a String


code:
#!/usr/bin/env python

from random import randint
import time
import pyaudio
import threading
import multiprocessing
import wave

# play wav file
chunk = 1024

def playAudio(x):
    f = wave.open(r"%d.wav" % x,"rb")
    p = pyaudio.PyAudio()
    stream = p.open(format = p.get_format_from_width(f.getsampwidth()),
                    channels = f.getnchannels(),
                    rate = f.getframerate(),
                    output = True)
    data = f.readframes(chunk)

    while data != '':
        stream.write(data)
        data = f.readframes(chunk)

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

if __name__ == '__main__':
    while True:
        x = randint(1,45)
        p = multiprocessing.Process(target=playAudio, args=(x,))
        p.start()
        time.sleep(5)
        p.terminate()
        p.join()

rawDescription: Play .wav file for x number of seconds

description: Play .wav file for x number of seconds


code:
def lookup_bus_stop_by_road_name(bus_stops, name):
    return [bus_stop for bus_stop in bus_stops if name.lower() in bus_stop[1].lower()]

rawDescription: how to get the second word of an element in a list

description: Get the second word of an element in a list


code:
class MyModel(Base):
    foo = sa.Column(sa.String, default='bar')

rawDescription: SQLAlchemy Inserting into Existing Table, default item value for columns unspecified in Model


code:
from tkinter import *
import sys

cp = ''
root = Tk()

def process(event):
    global cp
    key = event.keysym
    if key == 'Return':
        sys.stdout.write('\n')
        print(cp)
        sys.exit()
    else:
        if len(key) == 1:
            cp += key
            sys.stdout.write('*')

root.bind('<Key>', process)

root.withdraw()
root.mainloop()

rawDescription: How do you create a passcode entry in the python shell?

description: Create a passcode entry in the python shell


code:
mods = ('Project','Links','Profile','Contact')

urlpatterns = patterns('',
   *(('^%s/$'%n, 'mysite.app.views.%s'%n.lower()) for n in mods)
)

rawDescription: Django: How do I create a generic url routing to views?


rawDescription: Regex: how to match overlapping patterns (maybe Python specific)


code: data.groupby(['Hs', 'Tp', 'wd'])[['max', 'min']].std(ddof=0).max(level=[0, 1])

rawDescription: operations in pandas DataFrame

description: Operations in pandas DataFrame


code:
def maximum(items, default=None):
    iterator = iter(items)
    m = next(iterator)
    for item in iterator:
        if item > m:
            m = item
    return m

rawDescription: Get the maximum value from an array without the max() function in python


code:
from collections import defaultdict

dicts = [{'a':1, 'b':2, 'c':3},
         {'a':1, 'd':2, 'c':'foo'},
         {'e':57, 'c':3} ]

super_dict = defaultdict(set)  # uses set to avoid duplicates

for d in dicts:
    for k, v in d.iteritems():
        super_dict[k].add(v)

rawDescription: Python Dedup/Merge List of Dicts

description: Python Dedup/Merge List of Dicts


code: import movie_analysis

rawDescription: Execute Python Script Line by Line

description: Execute Python Script Line by Line


code:
files = sys.stdin.splitlines()
for n in range(start,end):
  fname = 'test%02d.ext' % (n,)
  if fname in files:
    some_loop(fname)

rawDescription: Pass range of files to stdin in Python

description: Pass range of files to stdin in Python


code:
df
df.mean()
df.fillna(df.mean())

rawDescription: pandas DataFrame: replace nan values with average of columns

description: Pandas DataFrame: replace nan values with average of columns


code:
import numpy as np
temp = np.array(modes[0].values())
result = np.hstack( (np.zeros((temp.shape[0], 1)), temp) )
for i in range(1, len(modes)):
    temp = np.array(modes[i].values())
    result = np.vstack( (result, np.hstack((i * np.ones((temp.shape[0], 1)), temp))) )

rawDescription: Saving values in a list of lists (Numpy)


code:
import xml.etree.ElementTree as etree
import html5lib

tb = html5lib.getTreeBuilder("etree", implementation=etree)
p = html5lib.HTMLParser(tb)
tree = p.parse("<html>")

rawDescription: using html5lib with xml.etree.ElementTree

description: Using html5lib with xml.etree.ElementTree


rawDescription: Determine the Kind (int, float) of Number a Python numeric literal represents?


code:
def callback(event):
    x, y = event.x, event.y
    c.coords(rect, x - 10, y - 10, x + 10, y + 10)

root = Tk()
c = Canvas(root)
rect = c.create_rectangle(0, 0, 0, 0)
c.bind('<Motion>', callback)
c.pack()
root.mainloop()

rawDescription: Tkinter - Creating a square that follows my mouse location


code: db.stuff.ensureIndex( { "i.elements.timestamp" : 1 });

rawDescription: Quicker way of updating subdocuments

description: Quicker way of updating subdocuments


code:
stream = p.open(format=p.get_format_from_width(WIDTH),
                channels=CHANNELS,
                rate=RATE,
                input=True,
                output=True,
                frames_per_buffer=4096,
                stream_callback=callback)

rawDescription: pyaudio change the number of samples of calling the callback function

description: Pyaudio change the number of samples of calling the callback function


code:
import numpy as np
m = np.random.randint(-10,10,size=(4,6))
m
m2 = np.zeros_like(m) # or m2 = m*0
m2[::2, ::2] = m[::2, ::2]
m2

rawDescription: Sampling a numpy array by zeroing non-sampled values?


code:
from scipy.spatial import ConvexHull
cv = ConvexHull(pointList)

hull_points = cv.vertices
# the vertices of the convex hull

set(range(len(pointList))).difference(ch.vertices)
# the vertices inside the convex hull

rawDescription: Python convex hull with scipy.spatial.Delaunay, how to eleminate points inside the hull?


rawDescription: Convert from ASCII string encoded in Hex to plain ASCII?


code:
def add2D(array):
    for row in array:
        for entry in row:
            print(entry, end='  ')
        print()

    sum = 0
    for row in array:
        for col in row:
            sum = sum + col
    return sum

rawDescription: Summing a 2d array in Python 3.x

description: Summing a 2d array in Python 3.x


code:
import datetime
import time
x = datetime.datetime.now()
x
time.sleep(5)
x

rawDescription: Python, hard-code it time for filename manipulation


code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.io.wavfile as wave

rate,data = wave.read('57.wav')
spectre = np.fft.fft(data)
freq = np.fft.fftfreq(data.size, 1/rate)
mask=freq>0
plt.plot(freq[mask],np.abs(spectre[mask]))

rawDescription: find the frequency amplitude and phase of a wav file by fft

description: Find the frequency amplitude and phase of a wav file by fft


rawDescription: Convert String to Integer, Preserving Leading Zeroes


code:
l1 = [4,3,5,2]
l2 = [3]
# remove 3, keep other ordering
st = set(l2)

print([x for x in l1 if x not in st])

[4, 5, 2]

rawDescription: Set subtraction while retaining order

description: Set subtraction while retaining order


code: DF.eval('Percent = Earned / Total')

rawDescription: Modifying Pandas DF Class outside of Class?


code:
l = ['hat', 'coat']
x = l + ['suit', 'shoes', 'socks']
x

rawDescription: Using .append for several string items at a time


code:
#!/usr/bin/env python
from xml.etree import ElementTree
import sys
tree = ElementTree.ElementTree()
tree.parse(sys.stdin)
b = tree.find("B")
for e in b.getiterator("D"):
    if e.find("E").text in ["123", "789"]:
        b.remove(e)
tree.write(sys.stdout)

rawDescription: Taking some part of an xml file with python


code:
from multiprocessing import Pool

my_pool = Pool(3)
# `cards` is a list of cards. Send rename requests to workers.
my_pool.map(renameImages, cards)

# Close the pool and wait for processes to close.
my_pool.close()
my_pool.join()

rawDescription: Asynchronous running of Python functions


code:
import logging, urllib2, sys

hh = urllib2.HTTPHandler()
hsh = urllib2.HTTPSHandler()
hh.set_http_debuglevel(1)
hsh.set_http_debuglevel(1)
opener = urllib2.build_opener(hh, hsh)
logger = logging.getLogger()
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.NOTSET)

rawDescription: How do I get urllib2 to log ALL transferred bytes

description: Get urllib2 to log ALL transferred bytes


rawDescription: HTML returning empty NDB Key to Python

description: HTML returning empty NDB Key to Python


code:
def BindEvents(self):

    self.ctrl.Bind(wx.EVT_LEFT_DOWN, self.OnMouseClickDelay)

def OnMouseClickDelay(self, evt):
    wx.CallAfter(self.OnMouseClick, evt)
    evt.Skip()

def OnMouseClick(self, evt):
    foo()

rawDescription: wxPython - Running built in event prior to custom bound event

description: WxPython - Running built in event prior to custom bound event


code:
import tkinter as tk
root = tk.Tk()
d = {'bg': 'red'}
tk.Label(root, d).pack()
tk.Label(root, d, text='abc').pack()
tk.Label(root, cnf=d, text='abc').pack()
tk.Label(root, d, text='abc', bg='blue').pack()
tk.Label(root, d, cnf=d, text='abc').pack()

rawDescription: cnf argument for tkinter widgets

description: Cnf argument for tkinter widgets


code:
import pandas as pd
from datetime import datetime

df = pd.DataFrame([datetime(2014, 9, 18, 12, 30, 5, 60000)])

writer = pd.ExcelWriter("time.xlsx",  datetime_format='hh:mm:ss.000')

df.to_excel(writer, "Sheet1")

writer.close()

rawDescription: Python Pandas custom time format in Excel output


code:
from evdev import InputDevice, ecodes
from select import select

while True:
    dev = InputDevice('/dev/input/event3')  # look into /dev/input
    select([dev], [], [])
    for event in dev.read():
        print("type: ", event.type)
        print("code: ", event.code)
        if event.code == ecodes.KEY_ENTER:
            print("Hey, it was ENTER!")

rawDescription: Is this possible to get the system level key events and re-produce system level key events in Python?


code:
from copy import deepcopy
state = (5,[1,2,3])
current_state = deepcopy(state)
state[1].remove(3)
state
current_state

rawDescription: How to prevent value change in python

description: Prevent value change in python


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

x, y = np.mgrid[0:20, 0:25]
u = np.sin(2 *x * np.pi / 20)
v = np.cos(2 * y * np.pi / 25)

fig, (ax_l, ax_r) = plt.subplots(1, 2, figsize=(8, 4))

ax_r.quiver(x, y, u, v, scale=5, scale_units='inches')
ax_l.quiver(x, y, 2*u, 2*v, scale=5, scale_units='inches')

ax_l.set_title('2x')
ax_r.set_title('1x')

rawDescription: how to use matplotlib quiver scale

description: Use matplotlib quiver scale


code:
clamp_sel = [int(clamp_normalized[i][j][0])
    for i in range(0, len(clamp_normalized))
    for j in range(0, len(clamp_normalized[i]))
    if clamp_normalized[i][j][0] < int(max_min_band[index_selec])]

rawDescription: Convert nested loops and conditions to a list comprehension


code:
def addlinks(text):
    from flask import Markup
    idlist = getallissueids()
    for issueid in idlist:
        parts = text.split(issueid)
        text = Markup("" + issueid + "").join(parts)
    return text

rawDescription: Flask + python + jinja2: how can I partialy replace template arguments with html code?


code:
def random_derangement(n):
    while True:
        v = np.arange(n)
        for j in np.arange(n - 1, -1, -1):
            p = np.random.randint(0, j+1)
            if v[p] == j:
                break
            else:
                v[j], v[p] = v[p], v[j]
        else:
            if v[0] != 0:
                return v

rawDescription: numpy shuffle with constraint

description: Numpy shuffle with constraint


code:
r_vals = [u['item3'].r for u in mydict.itervalues() if 'item3' in u]
if r_vals:
   r_avg = sum(r_vals)/len(r_vals)
else:
   r_avg = 0   # ???

rawDescription: Python: How to access tuple values inside a dictionary of a dictionary


code:
...
def get(self):
    self.write("Hello, world")
    light_the_leds()
...

rawDescription: Python app to serve a webpage and detect when someone visits it?


code:
import numpy as np

a = np.loadtxt('a.txt', dtype=str, delimiter=';')
s = a[0].argsort() # produces the indexes which would sort the header
s = np.append(0, s[s!=0]) # put 0 at the front again, that's Timestamp
final = a[:,s]
np.savetxt('final.txt', final, fmt='%s', delimiter=';')

rawDescription: Sort csv columns with Python

description: Sort csv columns with Python


code:
class PARTS(models.Model):
    partid = models.IntegerField(primary_key = True)
    productid = models.ForeignKey(PRODUCTS, related_name = 'parts', db_column='productid')

rawDescription: django models.ForeignKey behavior

description: Django models.ForeignKey behavior


code:
with open(r"E:\file.txt", 'w') as f:
    for key, value in userAccounts.items():
       f.write('{} {}\n'.format(key, value))

rawDescription: splitting a dictionary into original format python

description: Splitting a dictionary into original format python


code:
def dehydrate(self, bundle):
    for item in bundle.obj.iteritems():
        bundle.data["new_key"] = "new_value"
    return bundle

rawDescription: Returning non-predefined fields via. API with Tastypie in Django


code:
class CronForm(forms.Form):
    days = forms.ChoiceField(choices=[(x, x) for x in range(1, 32)])

rawDescription: django form dropdown list of numbers

description: Django form dropdown list of numbers


code:
from itertools import groupby, count
inp = [0, 1, 3, 5, 6, 7]
[list(g) for k, g in groupby(inp, key=lambda i,j=count(): i-next(j))]

rawDescription: Python: split list of integers based on step between them


code:
df.reset_index()
df['date'] = df['date_timestamp'].dt.date
del df['date_timestamp']
df2 = pd.pivot_table(df, index=['date', 'user'], columns=['ticket'], values='time', aggfunc=np.sum)
df2.fillna(value=0, inplace=True)
df2.plot(kind='bar', stacked=True)

rawDescription: Python pandas resample by day, group by value


code:
from collections import Counter

x = Counter(length)
vowel_count = 0
for v in "aeiou":
    vowel_count += x[v]
return vowel_count

rawDescription: How to create vowel counter in python

description: Create vowel counter in python


code:
class GERPYFrame(wx.Frame):
    def __init__(self, parent, id, dirname, filename):
        wx.Frame.__init__(self, parent, id, 'GERPY Compiler', size=(300,600))
        self.dirname = dirname
        self.filename = filename

rawDescription: How to pass strings from class to another in wxPython

description: Pass strings from class to another in wxPython


code:
import re
re.findall(r"([a-zA-Z]+) loves ([a-zA-Z]+)", "Mary loves Mike,Jack loves Lily,Ethan loves Lydia")

rawDescription: Extract names around each word regex

description: Extract names around each word regex


code:
import webapp2
import StringIO
import xlwt

def makeit():
    workbook = xlwt.Workbook()
    sheet = workbook.add_sheet("Hello World")
    sheet.write(0, 0, 'Hello world!')
    out = StringIO.StringIO()
    workbook.save(out)
    return out

class MainHandler(webapp2.RequestHandler):
    def get(self):
        self.response.headers['Content-Type'] = 'application/vnd.ms-excel'
        out = makeit()
        self.response.write(out.getvalue())

app = webapp2.WSGIApplication([
    ('/', MainHandler)
], debug=True)

rawDescription: GAE/webapp2: Serving Excel file created by script using xlwt


code:
# set up the socket, and a stream wrapped around the socket
s = ctx.socket(zmq.REP)
s.bind('tcp://localhost:12345')
stream = ZMQStream(s)

# Define a callback to handle incoming messages
def echo(msg):
    # in this case, just echo the message back again
    stream.send_multipart(msg)

# register the callback
stream.on_recv(echo)

# start the ioloop to start waiting for messages
ioloop.IOLoop.instance().start()

rawDescription: How to avoid high cpu usage?

description: Avoid high cpu usage


code:
mydict = {}
with open('ref') as f1:
    for line in f1:
        key, value = line.split()
        mydict[key] = value

with open('file.txt') as f2, open('out.txt', 'w') as f3:
    for l in f2:
        line = l.split()
        newline = ''
        for item in line:
            newline += mydict[item] + " "
        f3.write(newline + "\n")

rawDescription: Modifying text file using reference value


code:
from bokeh.io import vplot
import pandas as pd
from bokeh.models import CustomJS, ColumnDataSource
from bokeh.models.widgets import Button
from bokeh.plotting import figure, output_file, show

output_file("load_data_buttons.html")

df1 = pd.read_csv("data_file_1.txt")
df2 = pd.read_csv("data_file_2.txt")

plot = figure(plot_width=400, plot_height=400)

source = ColumnDataSource(data=dict(x=[0, 1], y=[0, 1]))
source2 = ColumnDataSource(data=dict(x1=df1.x.values, y1=df1.y.values,
                                    x2=df2.x.values, y2=df2.y.values))

plot.line('x', 'y', source=source, line_width=3, line_alpha=0.6)

callback = CustomJS(args=dict(source=source, source2=source2), code="""
        var data = source.get('data');
        var data2 = source2.get('data');
        data['x'] = data2['x' + cb_obj.get("name")];
        data['y'] = data2['y' + cb_obj.get("name")];
        source.trigger('change');
    """)

toggle1 = Button(label="Load data file 1", callback=callback, name="1")
toggle2 = Button(label="Load data file 2", callback=callback, name="2")

layout = vplot(toggle1, toggle2, plot)

show(layout)

rawDescription: load graph data from files on button click with bokeh

description: Load graph data from files on button click with bokeh


rawDescription: Python - default arguments in function

description: Python - default arguments in function


code:
'a'.isupper()
'A'.isupper()
'b'.islower()
'B'.islower()

rawDescription: Get the case of a character in python

description: Get the case of a character in python


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

def generate_data():
    # do calculations and stuff here
    return # an array reshaped(cols,rows) you want the color map to be

def update(data):
    mat.set_data(data)
    return mat

def data_gen():
    while True:
        yield generate_data()

fig, ax = plt.subplots()
mat = ax.matshow(generate_data())
plt.colorbar(mat)
ani = animation.FuncAnimation(fig, update, data_gen, interval=500,
                              save_count=50)
plt.show()

rawDescription: Matplotlib animation too slow ( ~3 fps )


code:
content_len = int(self.headers.getheader('content-length', 0))
post_body = self.rfile.read(content_len)

rawDescription: How to extract HTTP message body in BaseHTTPRequestHandler.do_POST()?

description: Extract HTTP message body in BaseHTTPRequestHandler.do_POST()


code:
import matplotlib.pyplot as plt

plt.close('all')

#---- create figure ----

fwidth = 8.  # total width of the figure in inches
fheight = 4. # total height of the figure in inches

fig = plt.figure(figsize=(fwidth, fheight))

#---- define margins -> size in inches / figure dimension ----

left_margin  = 0.95 / fwidth
right_margin = 0.2 / fwidth
bottom_margin = 0.5 / fheight
top_margin = 0.25 / fheight

#---- create axes ----

# dimensions are calculated relative to the figure size

x = left_margin    # horiz. position of bottom-left corner
y = bottom_margin  # vert. position of bottom-left corner
w = 1 - (left_margin + right_margin) # width of axes
h = 1 - (bottom_margin + top_margin) # height of axes

ax = fig.add_axes([x, y, w, h])

#---- Define the Ylabel position ----

# Location are defined in dimension relative to the figure size

xloc =  0.25 / fwidth
yloc =  y + h / 2.

ax.set_ylabel('yLabel', fontsize=16, verticalalignment='top',
              horizontalalignment='center')
ax.yaxis.set_label_coords(xloc, yloc, transform = fig.transFigure)

plt.show(block=False)
fig.savefig('figure_margins.png')

rawDescription: Matplotlib: fixed spacing between left edge of figure and y-axis


code:
import cv2

im=cv2.imread('test.jpg')
cv2.imshow('main',im)

#find ascii key codes here  http://www.asciitable.com/
#Escape == 27
while (cv2.waitKey(5) != 27): pass

rawDescription: Trouble with plots in opencv 2.4.7, python 2.7.6, OS X Mavericks


code:
for i,item in enumerate(listA):
    if (i+1)%4 == 0:
        print(item)
    else:
        print(item,end=' ')

rawDescription: How to print X items in a list per line

description: Print X items in a list per line


code:
class VideoForm(forms.ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        super(VideoForm, self).__init__(*args, **kwargs)
        self.fields['tags'].widget.attrs['maxlength'] = 5

rawDescription: Django use Widget to Override ModelForm Attributes


code:
import httplib

HOST = 'staging.linkpt.net'
API_URL = '/lpc/servlet/lppay'
PORT = 1129
CERTFILE = 'my_cert_file.pem'

headers = { 'User-Agent'     : 'Rico',
            'Content-type'   : 'text/xml; charset=\"UTF-8\"',
            'Content-length' : len(xml_str),
          }

conn = httplib.HTTPSConnection(HOST, PORT, cert_file = CERTFILE)
conn.putrequest("POST", API_URL)
conn.putheader(headers)
conn.endheaders()
conn.send(xml_str)
response = conn.getresponse()

rawDescription: Interfacing to the LinkPoint API with Python - Sending XML Over SSL with Authentication


code:
k = [1, 2, 3]
k2 = k  # reference to k
k3 = k.copy()  # a copy of k
k4 = k[:]  # also a copy of k

rawDescription: Odd "inheritance" of linkage between variables


code:
import os
import random
import pygame

# Class for the orange dude
class Player(object):

    def __init__(self, pos):
        self.rect = pygame.Rect(pos[0], pos[1], 16, 16)

    def move(self, dx, dy):

        # Move each axis separately. Note that this checks for collisions both times.
        if dx != 0:
            self.move_single_axis(dx, 0)
        if dy != 0:
            self.move_single_axis(0, dy)

    def move_single_axis(self, dx, dy):

    # Move the rect
        self.rect.x += dx
        self.rect.y += dy

    # If you collide with a wall, move out based on velocity
        for wall in walls:
            if self.rect.colliderect(wall.rect):
                if dx > 0: # Moving right; Hit the left side of the wall
                    self.rect.right = wall.rect.left
                if dx < 0: # Moving left; Hit the right side of the wall
                    self.rect.left = wall.rect.right
                if dy > 0: # Moving down; Hit the top side of the wall
                    self.rect.bottom = wall.rect.top
                if dy < 0: # Moving up; Hit the bottom side of the wall
                    self.rect.top = wall.rect.bottom

# Nice class to hold a wall rect
class Wall(object):

    def __init__(self, pos):
        self.rect = pygame.Rect(pos[0], pos[1], 16, 16)

class Finish(object):

    def __init__(self, pos):
        self.rect = pygame.Rect(pos[0], pos[1], 16, 16)

# Variables
currentLevel = 0

# Initialise pygame
pygame.init()

# Set up the display
pygame.display.set_caption("Change level")
screen = pygame.display.set_mode((320, 240))

clock = pygame.time.Clock()

levels = [[
    "WWWWWWWWWWWWWWWWWWWW",
    "W                  W",
    "W  P      WWWWWW   W",
    "W   WWWW       W   W",
    "W   W        WWWW  W",
    "W WWW  WWWW        W",
    "W   W     W W      W",
    "W   W     W   WWW WW",
    "W   WWW WWW   W W  W",
    "W     W   W   W W  W",
    "WWW   W   WWWWW W  W",
    "W W      WW        W",
    "W W   WWWW   WWW   W",
    "W     W   F    W   W",
    "WWWWWWWWWWWWWWWWWWWW",
    ],
    [
    "WWWWWWWWWWWWWWWWWWWW",
    "W                  W",
    "W                  W",
    "W   WWWWWWWWWWWWW  W",
    "W                  W",
    "W         P        W",
    "W                  W",
    "W   WWWWWWWWWWWWW  W",
    "W                  W",
    "W   WWWWWWWWWWWWW  W",
    "W                  W",
    "W         F        W",
    "W                  W",
    "W                  W",
    "WWWWWWWWWWWWWWWWWWWW",
    ]]

def load_level(level):
    walls = []
    players = []
    finishes = []

    # Parse the level string above
    x = y = 0
    for row in levels[level]:
        for col in row:
            if col == "W":
                walls.append(Wall((x, y)))
            if col == "P":
                players.append(Player((x, y)))
            if col == "F":
                finishes.append(Finish((x, y)))
            x += 16
        y += 16
        x = 0
    return walls, players, finishes

walls, players, finishes = load_level(currentLevel)
running = True
while running:

    clock.tick(60)

    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            running = False
        if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
            running = False

    # Move the player if an arrow key is pressed
    key = pygame.key.get_pressed()
    if key[pygame.K_LEFT]:
        player.move(-2, 0)
    if key[pygame.K_RIGHT]:
        player.move(2, 0)
    if key[pygame.K_UP]:
        player.move(0, -2)
    if key[pygame.K_DOWN]:
        player.move(0, 2)

    # Just added this to make it slightly fun ;)
    for player in players:
        for finish in finishes:
            if player.rect.colliderect(finish.rect):
                currentLevel += 1
                walls, players, finishes = load_level(currentLevel)

    # Draw the scene
    screen.fill((0, 0, 0))
    for wall in walls:
        pygame.draw.rect(screen, (255, 255, 255), wall.rect)
    for player in players:
        pygame.draw.rect(screen, (255, 200, 0), player.rect)
    for finish in finishes:
        pygame.draw.rect(screen, (0, 200, 0), finish.rect)
    pygame.display.flip()

rawDescription: Pygame change level - level made of list


code:
from datetime import datetime
from pytz import timezone
# define date format
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
# define eastern timezone
eastern = timezone('US/Eastern')
# naive datetime
naive_dt = datetime.now()
# localized datetime
loc_dt = datetime.now(eastern)
print(naive_dt.strftime(fmt))
# 2015-12-31 19:21:00
print(loc_dt.strftime(fmt))
# 2015-12-31 19:21:00 EST-0500

rawDescription: how to set timezone to eastern for DateTime module in python?

description: Set timezone to eastern for DateTime module in python


code:
def setupUi(self, Interface):
    # Interface.setObjectName("Interface")
    # Interface.resize(1152, 1009)
    # sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
    # sizePolicy.setHorizontalStretch(0)
    # sizePolicy.setVerticalStretch(0)
    # sizePolicy.setHeightForWidth(Interface.sizePolicy().hasHeightForWidth())
    # Interface.setSizePolicy(sizePolicy)
    # Interface.setMouseTracking(False)
    # icon = QtGui.QIcon()
    self.centralWidget = QtWidgets.QWidget(Interface)
    # self.centralWidget.setObjectName("centralWidget")
    layout = QtWidgets.QVBoxLayout(self.centralWidget)

    self.scrollArea = QtWidgets.QScrollArea(self.centralWidget)
    # self.scrollArea.setGeometry(QtCore.QRect(0, 0, 1131, 951))
    # self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
    # self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
    # self.scrollArea.setWidgetResizable(True)
    # self.scrollArea.setObjectName("scrollArea")
    # self.scrollArea.setEnabled(True)
    layout.addWidget(self.scrollArea)

    self.scrollAreaWidgetContents = QtWidgets.QWidget()
    self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 1112, 932))
    # self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")

    self.scrollArea.setWidget(self.scrollAreaWidgetContents)

    layout = QtWidgets.QHBoxLayout(self.scrollAreaWidgetContents)
    # self.horizontalLayout.setObjectName("horizontalLayout")
    # add child widgets to this layout...

    Interface.setCentralWidget(self.centralWidget)

rawDescription: PyQt add a scrollbar to MainWindow

description: PyQt add a scrollbar to MainWindow


code: errs = dict((f.auto_id, f.errors) for f in form if f.errors)

rawDescription: How can this be written on a single line?


code: ln -s  /path/to/hello.py /usr/local/bin/hello

rawDescription: Open python script using command line

description: Open python script using command line


code:
df = pd.DataFrame(np.random.choice([True]+[False]*5, size=(6,5)), columns=list("abcde"))
df
df.any(axis=1)
df[df.any(axis=1)]

rawDescription: Generate condition for selecting rows in pandas.DataFrame


code:
my_directory = r'e:\\one\\two\\three\\four\\KNOWN\\data'
myFolder = re.search(r'([a-zA-Z_]+)\\[^\\]+\\KNOWN', my_directory).group(1)

rawDescription: Extracting a folder name using Regex

description: Extracting a folder name using Regex


code:
def sortColumn(item1, item2):
    try:
        i1 = int(item1)
        i2 = int(item2)
    except ValueError:
        return cmp(item1, item2)
    else:
        return cmp(i1, i2)

rawDescription: Displaying integers in a wxpython listctrl


code:
l=[(0, 9), (14, 23), (25, 27)]
flatten_l= [x for y in l for x in y]
flatten_l
get_num_after=[y[1] for y in l for x in y if x ==0 ]
get_num_after

rawDescription: How to use a nested list as input?

description: Use a nested list as input


code:
attr_string ="fill:#00ff00;fill-opacity:1;stroke:#000000;stroke-width:2;stroke-miterlimit:4;stroke-opacity:1;stroke-dasharray:none"

attr_dict = {pair.split(":")[0]:pair.split(":")[1] for pair in attr_string.split(";")}

rawDescription: Python parse inline css

description: Python parse inline css


code:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10, 10, 1000)
y = np.sin(x)
plt.plot(x, y)
plt.show()

rawDescription: getting sin curve values using python

description: Getting sin curve values using python


code: svc.query("SELECT ID,Website FROM Account where ID in (SELECT accountId FROM Opportunity)")

rawDescription: Beatbox: How do I add a WHERE clause when pulling data from SFDC?


code:
name = input("Please enter a name: ")

while True:
    try:
        if name == "Mitnick":
            print("Most Wanted")
            break
        elif name.isalpha():
            print(name,"not on the Most Wanted List")
            break
        else:
            raise ValueError
    except ValueError:
        print("You didn't enter a name")
        break

rawDescription: trying to detect three different inputs

description: Trying to detect three different inputs


code:
import csv
with open('some.csv', newline='') as f:
    reader = csv.reader(f)
    w = []
    for row in reader:
        w.extend(row)

print(list(itertools.permutations(w, 2)))

rawDescription: How to import data from a CSV file and store it in a variable?

description: Import data from a CSV file and store it in a variable


code: y2 = integrate.odeint(eqexec2,inits, trange, full_output=0, printmessg=1,hmax=1.0)

rawDescription: integrate.odeint gives two very different answers when it shouldn't

description: Integrate.odeint gives two very different answers when it shouldn't


code:
class Point(object):
    __slots__ = ("x", "y")

point = Point()
point.x = 5 # OK
point.y = 1 # OK
point.X = 4 # AttributeError is raised

rawDescription: Python objects - avoiding creation of attribute with unknown name


code:
try:
    if string.index("Long") < string.index("Short"):
        length = "Long"
    else:
        length = "Short"
except ValueError:
    if "Long" in string:
        length = "Long"
    elif "Short" in string:
        length = "Short"
    else:
        print ("Long and Short not in string")

rawDescription: If statements depending on order of content in a string


code:
w = root.winfo_reqwidth()
h = root.winfo_reqheight()
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry('+%d+%d' % (x, y)) ## this part allows you to only change the location

rawDescription: Centering window python tkinter

description: Centering window python tkinter


code:
import csv

txt_file = r"mytxt.txt"
csv_file = r"mycsv.csv"

# use 'with' if the program isn't going to immediately terminate
# so you don't leave files open
# the 'b' is necessary on Windows
# it prevents \x1a, Ctrl-z, from ending the stream prematurely
# and also stops Python converting to / from different line terminators
# On other platforms, it has no effect
in_txt = csv.reader(open(txt_file, "rb"), delimiter = '\t')
out_csv = csv.writer(open(csv_file, 'wb'))

out_csv.writerows(in_txt)

rawDescription: Convert tab-delimited txt file into a csv file using Python


code:
class WindowSapper(QtGui.QMainWindow):

    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self,parent)
        self.resize(450,350)
        self.centralwidget = QtGui.QWidget()
        self.setCentralWidget(self.centralwidget)

        self.vLayout = QtGui.QVBoxLayout(self.centralwidget)
        self.hLayout = QtGui.QHBoxLayout()

        self.gridLayout = QtGui.QGridLayout()
        self.gridLayout.setSpacing(0)

        # center the grid with stretch on both sides
        self.hLayout.addStretch(1)
        self.hLayout.addLayout(self.gridLayout)
        self.hLayout.addStretch(1)

        self.vLayout.addLayout(self.hLayout)
        # push grid to the top of the window
        self.vLayout.addStretch(1)

        self.buttons = []
        for i in xrange(10):
            l=[]
            for j in xrange(10):
                b=QtGui.QPushButton()
                b.setFixedSize(40,30)
                l.append(b)
                self.gridLayout.addWidget(b, i, j)
                self.gridLayout.setColumnMinimumWidth(j, 40)
            self.buttons.append(l)
            self.gridLayout.setRowMinimumHeight(i, 26)

rawDescription: The distances between the QPushButton in QGridLayout


code:
with gzip.open(filename) as f:
    reader = csv.reader(f)
    #...

rawDescription: Using csvreader against a gzipped file in Python


code:
import csv

newrow = []
csvFileRead = open('c:/temp/csvfile.csv', 'rb')
csvFileNew = open('c:/temp/csvfilenew.csv', 'wb')

# Open the CSV
csvReader = csv.reader(csvFileRead, delimiter = ',')

# Append the rows to variable newrow
for row in csvReader:
    newrow.append(row)

# Add quotes around the third list item
for row in newrow:
    row[2] = "'"+str(row[2])+"'"

csvFileRead.close()

# Create a new CSV file
csvWriter = csv.writer(csvFileNew, delimiter = ',')

# Append the csv with rows from newrow variable
for row in newrow:
    csvWriter.writerow(row)

csvFileNew.close()

rawDescription: Python to insert quotes to column in CSV


code:
import matplotlib.font_manager
[f.name for f in matplotlib.font_manager.fontManager.ttflist]
[f.name for f in matplotlib.font_manager.fontManager.afmlist]

rawDescription: How can i get list of font family(or Name of Font) in matplotlib

description: Get list of font family(or Name of Font) in matplotlib


code:
def handle(self, *args, **options):
    if args:
        ids = args
    else:
        ids = raw_input('Enter comma-delimited list of ids: ').split(',')
    for client_id in ids:
        ...

rawDescription: Request input from django custom command?


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

x=np.linspace(0,1,11)

y=np.vstack((np.sin(x),np.cos(x),np.log1p(x)))

xi=np.linspace(0,1,101)

intf= interp1d(x,y,axis=1)

yi=intf(xi)

plt.ioff()
plt.plot(x,y.T,'x',
         xi,yi.T)
plt.show()

rawDescription: Interpolate each row of 2d array with same 1d array


rawDescription: how to read html tag's content by BeautifuSoup?

description: Read html tag's content by BeautifuSoup


code:
class pair(frozenset):
    def __new__(cls, a, b):
        return super().__new__(cls, {a, b})
    def __repr__(self):
        a, b = sorted(self)
        return "{} & {}".format(a, b)

rawDescription: Customizing immutable types in Python

description: Customizing immutable types in Python


code:
all_categories = {
    category
    for value in a.values() for category in value['categories']
}

if 'cms' in all_categories and 'ecommerce' in all_categories:
    print("Yes, that strange order of for clauses is actually correct...")

rawDescription: Python - Check if two values(strings) are both in dict


code:
import csv
import collections

def do_work():
    data, counter = get_file('thefile.csv')
    b = samples_subset1(data, counter, '/pythonwork/samples_subset3.csv', 500)

def get_file(start_file):
    with open(start_file, 'rb') as f:
        counter = collections.defaultdict(int)
        data = list(csv.reader(f))

        for row in data:
            counter[row[10]] += 1

    return (data, counter)

def samples_subset1(data, counter, output_file, sample_cutoff):
    with open(output_file, 'wb') as outfile:
        writer = csv.writer(outfile)
        b = []
        for row in data:
            if counter[row[10]] >= sample_cutoff:
                b.append(row)
                writer.writerow(row)

    return b

rawDescription: python newbie question: converting code to classes

description: Python newbie question: converting code to classes


code:
df1 = pd.pivot_table(df, rows=['A','B'], cols='C', aggfunc=np.sum)
df1
index = list(iter.product(df['A'].unique(), df['B'].unique()))
df1.reindex(index)

rawDescription: Pandas Handling Missing Values when going from Data Frame to Pivot Table


code: from gevent import monkey; monkey.patch_all()

rawDescription: SleekXMPP and Gevent

description: SleekXMPP and Gevent


code:
from collections import defaultdict

price_date_dict = defaultdict(list)

for name, price, date in t:
    price_date_dict[(price, date)].append(name)

return [tuple(names) for names in price_date_dict.values() if len(names) > 1]

rawDescription: how to find the same element in list of tuple and substitute it in Python?

description: Find the same element in list of tuple and substitute it in Python


code: plt.plt(row[1], row[2], 'b-', marker='o');

rawDescription: python plot points

description: Python plot points


code:
import csv

cursor.execute(query_str)
with open(out_file, 'w') as f:
    csv.writer(f, quoting=csv.QUOTE_NONE).writerows(cursor)

rawDescription: How would you create a comma-delimited string from a pyodbc result row?


code: reverse(viewname, urlconf=None, args=None, kwargs=None)

rawDescription: How to generate urls in django

description: Generate urls in django


rawDescription: Is there something that looks like white space but it is not and how to remove it?


rawDescription: Python - delete object that points to another object


code:
df = pd.DataFrame([['AB de Villiers', 0], ['AB de Villiers', 0], ['AB de Villiers', 1], ['Abdur Razzak', 0], ['Abdur Razzak', 1], ['Abdur Razzak', 1]], columns=['batsman', 'runs'])
df
df.groupby(['runs']).apply(lambda x: x['batsman'].value_counts().index[0])

rawDescription: Get maximum of value_counts after groupby


code:
def getSec(s):
    l = map(int, s.split(':')) # l = list(map(int, s.split(':'))) in Python 3.x
    return sum(n * sec for n, sec in zip(l[::-1], (1, 60, 3600)))

getSec('20') # 20
getSec('1:20') # 80
getSec('1:30:01') # 5401

rawDescription: Another converting hh:mm:ss to seconds

description: Another converting hh:mm:ss to seconds