code:
import threading

def data_processing():
    pass
def print_some_jokes():
    pass

def do_both():
    t1 = threading.Thread(target=data_processing)
    t2 = threading.Thread(target=print_some_jokes)

    t1.start()
    t2.start()

    t1.join()
    t2.join()

both = threading.Thread(target=do_both)
both.start()
both.join()

rawDescription: Write a string when I wait for the return answer of a function


rawDescription: Is it possible to easily center side-stacked frames in a frame in tkinter?


code:
MyModel.objects.filter(**your_filters).extra(select={
  'measure_name':
    'SELECT measure.name FROM measure WHERE mymodeltable.measure_id = measure.id'
})

rawDescription: telling django to use an integer as a foreign key on demand

description: Telling django to use an integer as a foreign key on demand


code:
def books():

    points = [0,5,15,30,60];    #  list of the points
    inp = 0;

    while inp < 0 or inp >= len(points):
        a = input("Enter number of books:")
        inp = int(a)

    print("You earned",points[inp],"points")

books()

rawDescription: How to write test sets to test the decision in the program in Python?

description: Write test sets to test the decision in the program in Python


code:
#Loading Dataframe
from StringIO import StringIO
x=StringIO('''Idnumber,X,y
1,a,a
2,a,a
1,b,b
1,NaN,d
2,b,NaN
1,d,c
2,c,NaN
1,NaN,e
2,d,d
2,e,e''')

#Operations on Dataframe
df = pd.read_csv(x)
df1 = df[['Idnumber','X']]
df2 = df[['Idnumber','y']]
df2.rename(columns={'y': 'X'}, inplace=True)
pd.concat([df1,df2]).dropna().drop_duplicates()

rawDescription: Create value if missing for this identifier


code:
from StringIO import StringIO # for python 2.7; import from io for python 3
import pandas as pd
import matplotlib.pyplot as plt

# get data
data = """,sample1, sample2
300, 1,   0
400, 5,   4
500, 6,   0
600, 0,   8"""
df = pd.read_csv(StringIO(data), header=0, index_col=0, skipinitialspace=True)

# and plot
df.plot()
plt.gca().invert_xaxis()
plt.show()

rawDescription: Pandas plot x or index_column in descending order


rawDescription: Applying a Django queryset filter using an attribute value AND exists()


code:
import re
s = 'Hello, this is a string'
m = re.search(',\s[a-z]',s)
m.group()
m.start()

rawDescription: How can I get the offset where a Python regular expression search found a match?

description: Get the offset where a Python regular expression search found a match


code:
a = np.arange(2*3).reshape(2,3)
np.mgrid[:2, :3]
np.indices(a.shape)
a = np.arange(2*3*5).reshape(2,3,5)
(np.mgrid[:2, :3, :5] == np.indices(a.shape)).all()

rawDescription: Numpy slice with array as index

description: Numpy slice with array as index


rawDescription: Getting Unique Foreign Keys in Django?

description: Getting Unique Foreign Keys in Django


code: dict( (o.name,o) for o in obj_list )[name]

rawDescription: Shortest way to find if a string matchs an object's attribute value in a list of objects of that type in Python


code:
self.scrolledwindow = Gtk.ScrolledWindow()
self.scrolledwindow.set_policy(Gtk.PolicyType.NEVER,
                               Gtk.PolicyType.AUTOMATIC)

...

renderer_text = Gtk.CellRendererText(weight=600)
renderer_text.set_fixed_size(200, -1)
column_text = Gtk.TreeViewColumn('Name', renderer_text, text=1)

rawDescription: Gtk.ScrolledWindow without horizontal scroll bar


code:
from operator import itemgetter
from itertools import groupby

lst = [(1, 5),  (5, 4), (13, 3), (4, 3), (3, 2), (14, 1),
       (12, 1), (10, 1), (9, 1), (8, 1),  (7, 1), (6, 1), (2, 1)]

result = [[x for x, y in group]
          for key, group in groupby(lst, key=itemgetter(1))]

rawDescription: Converting a Tuples List into a nested List using Python


code:
rgb = button.winfo_rgb("orchid4")
rgb

rawDescription: Tkinter color name to color object

description: Tkinter color name to color object


code: x = struct.pack(4*'B' + 'HB'[ALPHA<256] + 4*'B', *data)

rawDescription: Converting list of integers into a binary "string" in python


code:
import pandas as pd
arr = pd.np.array([[1, 2, 3], [4, 5, 6]])
arr
df = pd.DataFrame(pd.np.tile(arr, (5, 1)))
df
df = pd.DataFrame(pd.np.tile(arr, (1, 3)))
df

rawDescription: Duplicating a Pandas DF N times

description: Duplicating a Pandas DF N times


code:
import subprocess
import signal
import os
from datetime import datetime as dt

process_name = sys.argv[1]
log_file_name = sys.argv[2]

proc = subprocess.Popen(["pgrep", process_name], stdout=subprocess.PIPE)

# Kill process.
for pid in proc.stdout:
    os.kill(int(pid), signal.SIGTERM)
    # Check if the process that we killed is alive.
    try:
       os.kill(int(pid), 0)
       raise Exception("""wasn't able to kill the process
                          HINT:use signal.SIGKILL or signal.SIGABORT""")
    except OSError as ex:
       continue

# Save old logging file and create a new one.
os.system("cp {0} '{0}-dup-{1}'".format(log_file_name, dt.now()))

# Empty the logging file.
with open(log_file_name, "w") as f:
    pass

# Run the process again.
os.sytsem("<command to run the process>")
# you can use os.exec* if you want to replace this process with the new one which i think is much better in this case.

# the os.system() or os.exec* call will failed if something go wrong like this you can check if the process is runninh again.

rawDescription: kill process with python

description: Kill process with python


code:
colors=[]
for n in nodes:
    if n in hybrids:
        colors.append('g')
    else:
        colors.append('b')

nx.draw_graphviz(g, prog="fdp", node_color = colors, node_size = sizes)

rawDescription: python - networkx - graph different colored nodes using two lists

description: Python - networkx - graph different colored nodes using two lists


rawDescription: Stripping variable borders with python re


rawDescription: Get last answer

description: Get last answer


code:
def make_station_files(traveltimes, header_lines):
    'Gives the STAxx.tgrid files required by loc3d'

    with open (header_lines, 'r') as f:
        headers = f.readlines()

    def station_counter(line, cnt=[1]):
        'Stateful station counter -- Keeps the count in a mutable list'
        if line.strip() == '':
            cnt[0] += 1
        return cnt[0]

    with open(traveltimes, 'r') as times_file:
        for station, group in groupby(times_file, station_counter):
            with open('STA%s' % (station), 'w') as output_file:
                for header in headers[:3]:
                    output_file.write ('%s\n\t1\n' % (header.strip()))
                for line in group:
                    if not line.startswith('           '):
                        output_file.write ('%s' % (line))

rawDescription: writing lines group by group in different files

description: Writing lines group by group in different files


code:
import re
s = """\
/*
* REMOVE ME
*
* */
blah
more blah
/*
* REMOVE ME
*
* */"""
re.sub("/\*[\S\s]*?\*/", "", s)

rawDescription: Python find and remove between tags

description: Python find and remove between tags


code:
from itertools import product
[''.join(i) for i in product('ABC',repeat=3)]

rawDescription: A good pythonic way to map bits to characters in python?


rawDescription: django-haystack with elastic search not building index for newly created objects

description: Django-haystack with elastic search not building index for newly created objects


code:
from flask import request

@app.after_request
def after_request(response):
    do_something_based_on_the_request_endpoint(request)

rawDescription: Flask - access the request in after_request or teardown_request


code: smaller_array = np.delete(array,index)

rawDescription: pythonic way to delete elements from a numpy array

description: Pythonic way to delete elements from a numpy array


code:
df
df.dates - pd.to_timedelta(df.floats.astype(str), unit='D')

rawDescription: Subtracing float from a datetime in Pandas (numpy)


rawDescription: Numpy array dimensions

description: Numpy array dimensions


code:
s = 'gpmetisfile.txt.part.4'
import re
re.sub('\D', '', s)

rawDescription: Can I remove all the letters from a string and keep just the numbers?

description: Remove all the letters from a string and keep just the numbers


code: cursor.execute("SELECT COUNT(DISTINCT provider_id) FROM main_iteminstance")

rawDescription: Get row count in MySQLdb

description: Get row count in MySQLdb


code:
# use a Tkinter label as a panel/frame with a background image
# note that Tkinter only reads gif and ppm images
# use the Python Image Library (PIL) for other image formats
# free from [url]http://www.pythonware.com/products/pil/index.htm[/url]
# give Tkinter a namespace to avoid conflicts with PIL
# (they both have a class named Image)

import Tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
root.title('background image')

# pick an image file you have .bmp  .jpg  .gif.  .png
# load the file and covert it to a Tkinter image object
imageFile = "Flowers.jpg"
image1 = ImageTk.PhotoImage(Image.open(imageFile))

# get the image size
w = image1.width()
h = image1.height()

# position coordinates of root 'upper left corner'
x = 0
y = 0

# make the root window the size of the image
root.geometry("%dx%d+%d+%d" % (w, h, x, y))

# root has no image argument, so use a label as a panel
panel1 = tk.Label(root, image=image1)
panel1.pack(side='top', fill='both', expand='yes')

# put a button on the image panel to test it
button2 = tk.Button(panel1, text='button2')
button2.pack(side='top')

# save the panel's image from 'garbage collection'
panel1.image = image1

# start the event loop
root.mainloop()

rawDescription: Python images display

description: Python images display


rawDescription: python lookup table

description: Python lookup table


rawDescription: python list expression

description: Python list expression


code:
from google.appengine.api import users
from google.appengine.api.namespace_manager import set_namespace

class ClientClass(webapp.RequestHandler):
  def get(self):
    # For this example let's assume the user_id is your unique id.
    # You could just as easily use a parameter you are passed.
    user = users.get_current_user()
    if user:
       # If there is a user, use their queue.  Otherwise the global queue.
       set_namespace(user.user_id())

    item = QueueItem.pop()
    self.response.out.write(str(item))

    QueueItem.push('The next task.')

rawDescription: How to implement a FIFO queue that supports namespaces

description: Implement a FIFO queue that supports namespaces


code:
import nltk
from nltk.tag.simplify import simplify_wsj_tag
tagged_sent = nltk.pos_tag(tokens)
simplified = [(word, simplify_wsj_tag(tag)) for word, tag in tagged_sent]

rawDescription: Python NLTK: How to tag sentences with the simplified set of part-of-speech tags?


code:
minidx = []
for cluster in sumErrors:
    minidx.append(np.argsort(cluster)[:3])

rawDescription: Finding the indices of the top three values via argmin() or min() in python/numpy without mutation of list?


code:
from cv2 import __version__
__version__

rawDescription: Determine which version of OpenCV

description: Determine which version of OpenCV


code:
l = ['a', 'b', 'c', 'd']
[l[i%len(l)]+l[(i+1)%len(l)] for i in range(len(l))]
[l[i%len(l)]+l[(i+1)%len(l)] for i in range(2*len(l))]

rawDescription: getting the last and first few elements in a list in python

description: Getting the last and first few elements in a list in python


rawDescription: Python regex with unicode ranges matches characters not in range


code:
import itertools
for line in itertools.islice(list , start, stop):
     foo(line)

rawDescription: pythonic way to iterate over part of a list

description: Pythonic way to iterate over part of a list


code:
from matplotlib.backends.backend_wxagg import \
FigureCanvasWxAgg as FigureCanvas

class MyFigurePanel(wx.Panel):
  """Class to represent a Matplotlib Figure as a wxFrame"""
  def __init__(self, parent):
    wx.Panel.__init__(self, parent)
    self.figure = Figure()#figsize=(6, 4), dpi=100)
    self.axes = self.figure.add_subplot(111)
    x = np.arange(0, 6, .01)
    y = np.sin(x**2)*np.exp(-x)
    self.axes.plot(x, y)
    self.canvas = FigureCanvas(self, wx.ID_ANY, self.figure)

class MyButtonPanel(wx.Panel):
  def __init__(self, parent):
    wx.Panel.__init__(self, parent)
    button = wx.Button(self, label = 'SAVE se')

class MyFrame(wx.Frame):
  def __init__(self):
    wx.Frame.__init__(self, None)
    self.figure = MyFigurePanel(self)
    self.buttons = MyButtonPanel(self)
    grid = wx.BoxSizer(wx.VERTICAL)
    grid.Add(self.buttons, flag=wx.EXPAND)
    grid.Add(self.figure, flag=wx.EXPAND)
    self.SetSizer(grid)
    self.Fit()

# Create a wrapper wxWidgets application
app = wx.PySimpleApp()
# instantiate the Matplotlib wxFrame
frame = MyFrame()
# show it
frame.Show(True)
# start wxWidgets mainloop
app.MainLoop()

rawDescription: simple application using wxPython and matplotlib freezes

description: Simple application using wxPython and matplotlib freezes


code:
from pylab import *
from numarray import *

x = arange(10)
y = x

# Plot junk and then a filled region
plot(x, y)

# Now lets make an arrow object
arr = Arrow(2, 2, 1, 1, edgecolor='white')

# Get the subplot that we are currently working on
ax = gca()

# Now add the arrow
ax.add_patch(arr)

# We should be able to make modifications to the arrow.
# Lets make it green.
arr.set_facecolor('g')

rawDescription: Adding arrows to parametric plots in matplotlib


code:
class HandleAction(tornado.web.RequestHandler):
    def take_appropriate_action(route):
        print("Responding to action/{}".format(route))

class HandleThis(HandleAction):
    def get(self):
        self.take_appropriate_action('doThis')

class HandleThat(HandleAction):
    def get(self):
        self.take_appropriate_action('requestThat')

app = tornado.web.Application([
    (r'/action/doThis', HandleThis),
    (r'/action/requestThat', HandleThat)
])

rawDescription: Structure RESTful Tornado Web App

description: Structure RESTful Tornado Web App


code:
from tkinter import *

class App(object):

    def __init__(self, master):
        self.master = master
        self.frame = Frame(master)
        self.frame.grid()
        self.addFrame = Frame(master)
        self.addFrame.grid(row=0, column=0, columnspan=2, sticky='N')
        self.listFrame = Frame(master)
        self.listFrame.grid(row=1, column=0, columnspan=2, sticky='NW')
        self.todoList = []
        self.buttonList = []  #<--- button list is here now
        self.initUI()

    def initUI(self):

        self.entryBox = Entry(self.frame, width = 15)
        self.entryBox.grid(row=0, column=0, sticky='N')

        self.addButton = Button(self.frame, text="<-ADD->", command=self.add)
        self.addButton.grid(row=0, column=1, sticky='N')

    def removeCheckButton(self, button_no):
        # - CONFUSED HOW TO REMOVE THE SPECIFIC CHECKBUTTON
       # print(button_no, self.buttonList[button_no])
        #self.buttonList[button_no].grid_forget()
        self.buttonList[button_no].destroy()
       # del self.buttonList[button_no]
       # del self.todoList[button_no]

    def add(self):
        entry = self.entryBox.get()
        self.entryBox.delete(0, END)
        self.todoList.append(entry)
        print(self.todoList)
        var1 = IntVar()
        #self.buttonList = [] #<--- not sense having this here
      #  for n in range(len(self.todoList)): #<-- this for also very strange here.
        n = len(self.buttonList)
        lx = Checkbutton(self.listFrame,
                         text=self.todoList[n],
                         variable=self.todoList[n],
                         command=lambda ni=n: self.removeCheckButton(ni))
        lx.grid(row=n, column=0, sticky='NW')
        self.buttonList.append(lx)
         #   print(self.buttonList)

root = Tk()
app = App(root)
root.mainloop()

rawDescription: How do I remove a checkbutton when it is checked

description: Remove a checkbutton when it is checked


code:
import inspect
def foo(bar, baz):
    pass

inspect.getargspec(foo)

rawDescription: List all function argument names (no docu)


code:
browser.find_element_by_css_selector("[href='" + lStr + "']")
#browser.find_element_by_css_selector("[href='"+ str(lStr) + "']")

rawDescription: How to pass variable inside find element method in Selenium , Python

description: Pass variable inside find element method in Selenium , Python


code:
def application(environ, start_response):
    status = '200 OK'
    output = 'Hello World!'

    response_headers = [('Content-type', 'text/plain')]
    start_response(status, response_headers)

    file = open('/usr/share/dict/words', 'rb')
    return environ['wsgi.file_wrapper'](file)

rawDescription: How to improve performance of python cgi that reads a big file and returns it as a download?

description: Improve performance of python cgi that reads a big file and returns it as a download


code:
new = ""
file = open("file.cpp")
for line in file:
    if "#define" in file:
        splitline = line.split(" ")
        new += "static const "
        if '"' in line:
            new += "string "
        else:
            new += "int "
        new += splitline[1]
        new += " = "
        new += splitline[2]
        new += ";\n"
    else:
        new += line + "\n"
file.close()
newfile = open("new.cpp")
newfile.write(new)

rawDescription: replacing #define with static const with python

description: Replacing #define with static const with python


rawDescription: Array Values Based on Index Contained in Another Array


code: getattr(CallMe, variable)()

rawDescription: Call method from string

description: Call method from string


code:
signals.satchmo_cart_add_verify.disconnect(
    signals.satchmo_cart_add_verify.receivers[0][1]())

rawDescription: How to override Django's signal handler?

description: Override Django's signal handler


code: op.execute ('ALTER TABLE users DROP COLUMN nickname')

rawDescription: How do I handle migrations in sqlalchemy without any framework?

description: Handle migrations in sqlalchemy without any framework


code:
class B:
    """docs for B with reference to :class:`.A`"""
    pass

rawDescription: sphinx automodule: how to reference classes in same module?

description: Sphinx automodule: how to reference classes in same module


code:
from account.urls import urlpatterns as accounts_urlpatterns
from django_authopenid.urls import urlpatterns as authopenid_urlpatterns

urlpatterns = patterns("")
urlpatterns += accounts_urlpatterns
urlpatterns += authopenid_urlpatterns

rawDescription: any method to mix these urls in django

description: Any method to mix these urls in django


code: re.findall(r"/\,\b", "/NN ,/, breeding/VBG Lilacs/NNP out/RB of/IN the/DT dead/JJ land/NN")

rawDescription: Python Regex punctuation recognition

description: Python Regex punctuation recognition


rawDescription: Sorting list of strings using L.sort with key multiple parameters


code: setattr(A, 'foo', 10)

rawDescription: Dynamically add class member using string to name it


code:
def _compute_workers(self, cr, uid, ids, fieldname, arg, context=None):
    result = dict.fromkeys(ids, False) # default result for each id
    for this in self.browse(cr, uid, ids, context=context):
        # let's assume you have a one2many called worker_ids
        result[this.id] = len(this.worker_ids)
    return result

_columns = {
    'total_workers': fields.function(_compute_workers, type="integer",
                                     string="Total Workers")
}

rawDescription: override create method with multiple returns in OpenERP ver 7

description: Override create method with multiple returns in OpenERP ver 7


code:
import Tkinter as tk

class ExampleView(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        cbframe = tk.Frame(self)
        cb1 = tk.Checkbutton(cbframe, text="Choice 1")
        cb2 = tk.Checkbutton(cbframe, text="Choice 2")
        cb3 = tk.Checkbutton(cbframe, text="Choice 3")

        cb1.pack(side="left", fill=None, expand=False)
        cb2.pack(side="left", fill=None, expand=False)
        cb3.pack(side="left", fill=None, expand=False)

        # this entry is for illustrative purposes: it
        # will force column 2 to be widget than a checkbutton
        e1 = tk.Entry(self, width=20)
        e1.grid(row=1, column=1, sticky="ew")

        # place our frame of checkbuttons in the same column
        # as the entry widget. Because the checkbuttons are
        # packed in a frame, they will always be "stuck"
        # to the left side of the cell.
        cbframe.grid(row=2, column=1, sticky="w")

        # let column 1 expand and contract with the
        # window, so you can see that the column grows
        # with the window, but that the checkbuttons
        # stay stuck to the left
        self.grid_columnconfigure(1, weight=1)

if __name__ == "__main__":
    root = tk.Tk()
    view = ExampleView(root)
    view.pack(side="top", fill="both", expand=True)
    root.wm_geometry("400x200")
    root.mainloop()

rawDescription: Tkinter configure columnwidth

description: Tkinter configure columnwidth


code:
file=open("file.csv", "r")
data=csv.reader(file)

data=[[row[0],row[1],eval(row[2]),eval(row[3]),eval(row[4])] for row in data]

from statistics import mean

newdata=[[row[0],row[1],mean([row[2],row[3],row[4]])] for row in data]
sort=sorted(newdata,key=operator.itemgetter(2), reverse=True)

for eachline in sort:
    print(eachline)

file.close()

rawDescription: Calculating mean of certain list values in Python


code:
import one
import two
import three

if __name__ == '__main__':
    one.foo()
    two.bar()
    three.baz()

rawDescription: Execute multiple python files using a single main


code:
from turtle import*

def file():
    filename = "t.txt"
    openfile = open(filename, "r")
    readlines = openfile.readlines()
    nums=[]
    for lines in readlines:
        nums.append(lines.strip().split(","))

    return nums

def turtle(n):
    print(n)
    row = 0
    col = 0
    wn = Screen()
    pen = Turtle()
    wn.setworldcoordinates(-0.5,3.5,4.5,-1.0)

    pen.up()
    for numberRow in n:
        for number in numberRow:
            pen.goto(col,row)
            pen.write(number, font=("arial", 30))
            col+=1
        row += 1
        col = 0

def main():
    y = file()
    w = turtle(y)

main()
r = input()

rawDescription: Write a program that reads a file with numbers separated by commas and print those numbers to the turtle screen


code:
s = "Nima Python: how are you?"
s.replace("Nima Python: ", "") # replace with empty string to remove

rawDescription: Filter out a specific string in a larger string?


rawDescription: Is there any way to make a soft reference or Pointer-like objects using Numpy arrays?


code:
class MyClass(models.Model):
    # some fields here

    def save(self, *args, **kwargs):
       # strip spaces here
       super(MyClass, self).save(*args, **kwargs)
       # make sure to call parent save method ^

rawDescription: Strip spaces when saving a model

description: Strip spaces when saving a model


code:
from itertools import permutations
array = ["a", "b", "c", "d"]
for p in permutations(array, r=2):
    print(p)

rawDescription: Filtering a permutation

description: Filtering a permutation


rawDescription: Python: adding calculated list elements

description: Python: adding calculated list elements


code:
res = service.cse().list(
     q='lectures',
     cx='013036536707430787589:_pqjad5hr1a',
     num=10, #Valid values are integers between 1 and 10, inclusive.
).execute()

next_response = service.cse().list(
     q='lectures',
     cx='013036536707430787589:_pqjad5hr1a',
     num=10,
     start=res['queries']['nextPage'][0]['startIndex'],
).execute()

rawDescription: Google custom search next page

description: Google custom search next page


code:
s = 'home_id: [redacted] id: [7] name: [] model: []'
d = dict([pair.strip().split(': [') for pair in s.split(']') if pair])

rawDescription: Python -- making a dict out of a string

description: Python -- making a dict out of a string


code:
import os, zipfile

dir_name = 'C:\\SomeDirectory'
extension = ".zip"

os.chdir(dir_name) # change directory from working dir to dir with files

for item in os.listdir(dir_name): # loop through items in dir
    if item.endswith(extension): # check for ".zip" extension
        file_name = os.path.abspath(item) # get full path of files
        zip_ref = zipfile.ZipFile(file_name) # create zipfile object
        zip_ref.extractall(dir_name) # extract file to dir
        zip_ref.close() # close file
        os.remove(file_name) # delete zipped file

rawDescription: Unzip all zipped files in a folder to that same folder using Python 2.7.5


code:
# Set limits to x < 10^1 and x > 10^-1
# (overlapping, thus all inclusive, hopefully)
gca().get_yaxis().get_major_formatter().set_powerlimits((0, 0))

rawDescription: Matplotlib.pyplot: force exponential axis label notation


code:
from django.db.models import Q

def clean(self):
   mn = ModelName.objects.filter(Q(field_one=self.field_one,field_two=field_two)|Q(field_one=self.field_two,field_two=field_one))
   if mn.exists():
      raise ValidationError('Already exist')

rawDescription: Prevent permutations of foreign keys in Django


code:
def pred():

    with open('AquaticFoodWeb.txt') as input:
        for line in input:
            animal, prey = line.strip().split(' eats ')
            foodweb.setdefault(animal, []).append(prey)

    print ("Predators and Prey:")

    for animal, prey in sorted(foodweb.items()):
        if len(prey) > 1:
            print ("{} eats {} and {}".format(animal, ",     ".join(prey[:-1]), prey[-1]))
        else:
            print ("{} eats {}".format(animal, ", ".join(prey)))

if __name__ == "__main__":
    pred()

rawDescription: Issue Creating a function

description: Issue Creating a function


code:
import json
def extend_json(obj):
    if isinstance(obj, date):
        return str(obj)
    elif isinstance(obj, datetime):
        return obj.strftime("%Y-%m-%d %H:%M:%S")
    elif isinstance(obj, Decimal):
        return float(obj)

data = json.dumps(obj, indent=4, sort_keys=True, default=extend_json)

rawDescription: Render python object to HTML - simple types but nested - in django


code:
install_requires = [
        "parsedatetime >= 1.1.2",
        "colorama >= 0.2.5",
        "pycrypto >= 2.6"
        ] + ["pyreadline >= 2.0"] if "win" in sys.platform else [],

rawDescription: Operating-system specific requirements with pip


code:
import resolve_ip
import os
host = resolve_ip.get_host_to_use() # you figure this part out
os.execlp('ssh', 'ssh', host)

rawDescription: Spawn a subprocess in foreground, even after python exits


code:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np                           # <---- New line

ext_modules = [Extension("hello", ["hello.pyx"])]

setup(
  name = 'Hello world app',
  cmdclass = {'build_ext': build_ext},
  include_dirs = [np.get_include()],         # <---- New line
  ext_modules = ext_modules
)

rawDescription: Make distutils look for numpy header files in the correct place


code:
if not 'seen' in session.data:
    # new session, set a flag
    session.data['seen'] = True

rawDescription: Python, handling session in CGI

description: Python, handling session in CGI


rawDescription: get dataframe row count based on conditions

description: Get dataframe row count based on conditions


code:
from multiprocessing.dummy import Pool

import requests

pool = Pool(10) # Creates a pool with ten threads; more threads = more concurrency.
                # "pool" is a module attribute; you can be sure there will only
                # be one of them in your application
                # as modules are cached after initialization.

if __name__ == '__main__':
    futures = []
    for x in range(10):
        futures.append(pool.apply_async(requests.get, ['http://example.com/']))
    # futures is now a list of 10 futures.
    for future in futures:
        print(future.get()) # For each future, wait until the request is
                            # finished and then print the response object.

rawDescription: Python Requests: Don't wait for request to finish


code:
def getHigh(pricedata, start=None, end=None):
    start = min(pricedata) if start is None else start
    end = max(pricedata) if end is None else end

rawDescription: Change values of a python dictionary contigent on the other values of the dictionary


code:
def plotA(ax, data):
    pass

def plotB(ax, data):
    pass

def dispatcher(data, list_of_plot_types):
    function_map = {'A': plotA, 'B': plotB}
    fig, list_of_axes = plt.subplots(1, len(list_of_plot_types))

    for ax, plot_type in zip(list_of_axes, list_of_plot_types):
        function_map[plot_type](ax, data)

rawDescription: Matplotlib: variable size of subplots?

description: Matplotlib: variable size of subplots


rawDescription: Array interpolation in python?

description: Array interpolation in python


code:
list1 = [1,5,56,2] # First list
list2 = [3,85,1,5] # Second list
common_elements = [x for x in list1 if x in list2]
common_elements # Common elements in 2 lists

rawDescription: Python - Test if an element exists on an other list (no matter the place in the list)


type: number

rawDescription: JSON Schema: validate a number-or-null value


code:
#!/usr/bin/env python3
import h5py
import numpy

output = h5py.File('foo.h5', 'w')

len = 50

x0 = 1.23
y0 = 2.25
z0 = 7.84

a0 = numpy.random.uniform(size=len)

x1 = 2.34;
y1 = 4.38;
z1 = 7.25;

a1 = numpy.random.uniform(size=len)

comp_type = numpy.dtype([('x', numpy.float64), ('y', numpy.float64), ('z', numpy.float64), ('trace', (numpy.dtype('<d'), len))])
g = output.create_dataset('my_type', (2,), comp_type)
data = numpy.array([(x0, y0, z0, a0), (x1, y1, z1, a1)], dtype=comp_type)
g[...] = data

output.close()

rawDescription: Convert C++ datastructure into intelligible HDF5 dataset (Vector of Pairs)


code:
class Node(object):

  __slots__ = 'payload', 'left', 'right'

  def __init__(self, payload=None, left=None, right=None):
    self.payload = payload
    self.left = left
    self.right = right

rawDescription: Data Structures in Python

description: Data Structures in Python


rawDescription: Best method for reading newline delimited files in Python and discarding the newlines?


code:
import glob

directory = "/Users/.../.../files/*"
output = "/Users/.../.../output.txt"

filepath = glob.glob(directory)

def wordCount(filepath):
    for file in filepath:
        name = file
        fileO = open(file, 'r')
        sentences = 0
        words = 0
        for line in fileO:
            sentences += line.count('.') + line.count('!') + line.count('?')

            tempwords = line.split()
            words += len(tempwords)

        outputO = open(output, "a")
        outputO.write("Name: " + name + "\n" + "Words: " + str(words) + "\n")

wordCount(filepath)

rawDescription: Wordcounts line breaks in python

description: Wordcounts line breaks in python


code:
def square(sq):
    rows = len(sq)
    for row in sq:
        if (len(row) != rows) or (len(set(row)) != rows):
            return False
    return True

rawDescription: Python - n Different characters used in a grid


rawDescription: Is there a way to get remote peer certificate with certificate verification disabled (CERT_NONE) in Python?


code:
tags = ['ID','Name','Size','Color']
sort_order = { tag : i for i,tag in enumerate(tags) }

def elem_key(x):
    for tag in tags:
        if x.startswith(tag):
            suffix = x[len(tag) : ]
            return ( sort_order[tag],
                     int(suffix) if suffix else None )
    raise ValueError("element %s is not prefixed by a known tag. order is not defined" % x)

list1.sort(key = elem_key)

rawDescription: Sort strings in Python list using another list


code:
class Question(models.Model):
    blablabla #your definition

    def count_yes(self):
        return Vote.objects.filter(question__exact = self,
                                   choice__exact = 'Y').count()

rawDescription: Manipulating another model's data from a model save method


code:
import ast
s = u'[obj1,obj2,ob3]'
n = ast.literal_eval(s)
n
[obj1, obj2, ob3]

rawDescription: unicode to python object conversion

description: Unicode to python object conversion


code:
from elasticsearch import RequestsHttpConnection

class MyConnection(RequestsHttpConnection):
    def __init__(*args, **kwargs):
        proxies = kwargs.pop('proxies', {})
        super(MyConnection, self).__init__(*args, **kwargs)
        self.session.proxies = proxies

es = Elasticsearch([es_url], connection_class=MyConnection, proxies = {'https': 'http://user:pw@proxy.org:port'})

print(es.info())

rawDescription: Elasticsearch / Python / Proxy

description: Elasticsearch / Python / Proxy


rawDescription: Django Queryset for substr matching that starts from the beginning of a string


code:
eps = 1e-30
1 - eps  # eps is smaller than 1 ULP, so 1-eps == 1.
ellipk(1 - eps)  # Of course, this gives inf.
ellipkm1(eps)  # This is the value we want.

rawDescription: Scipy: Difference between ellipk and ellipkm1


code:
def multi(request):
    if 'hobbies' in request.GET and request.GET['hobbies']:
        message = ','.join(request.GET.getlist('hobbies'))
    else:
        message = 'enterd wrong datails'
    return HttpResponse(message)

rawDescription: Showing multi selected values with same name


code:
seq2 = 'ggggugcccQgcuagagaZgacagu'
re.findall(r'[^GaAgUuCc]',seq2)

rawDescription: Regular expression - such that a string does not contain specific characters


code:
d = { 'key1': { 'foo': 1233, 'bar': 1234, 'baz': 122 }, 'key2': { 'foo': 113, 'bar': 333 } }
keys = (x.keys() for x in d.itervalues())
common_keys = set(next(keys)).intersection(*keys)
{k : {k_: v[k_] for k_ in common_keys} for k, v in d.iteritems()}

rawDescription: new dictionary with common subkey

description: New dictionary with common subkey


code:
xl = pd.ExcelFile('foo.xls')

xl.sheet_names  # see all sheet names

xl.parse(sheet_name)  # read a specific sheet to DataFrame

rawDescription: Pandas: Looking up the list of sheets in an excel file


code:
class ObjectDict(dict):
    """
    Object like dict, every dict[key] can be visited by dict.key
    """

    def __getattr__(self, name):
        return self.__getitem__(name)

rawDescription: Convert dictionary to object (or copy to local object var)


code:
n = 2
groups = text.split('_')
'_'.join(groups[:n]), '_'.join(groups[n:])

rawDescription: Split string at nth occurrence of a given character


code:
def satisfiesF(L):

   count= len(L)
   rec_list=list()

   for i in range(0,count):
     if(f(L[i])==False):
        rec_list.append(L[i])

   if(rec_list):
     for j in rec_list:
      L.remove(j)

   return len(L)
run_satisfiesF(L, satisfiesF)

rawDescription: How to mutate a List in python inside a function, which changes List outside the function too?

description: Mutate a List in python inside a function, which changes List outside the function too


code:
import operator as op
from distutils.version import LooseVersion

lookup = {'<': op.lt, '<=': op.le, '==': op.eq, '>=': op.ge, '>': op.gt}

def check_versions(ver1, specifier, ver2):
    try:
        return lookup[specifier](LooseVersion(ver1), LooseVersion(ver2))
    except KeyError:
        # unknown specifier
        return False

rawDescription: Python compare version numbers with dynamic comparison specifier


code:
string = 'anarchism/NOUN originated/VERB as/ADP a/DET term/NOUN of/ADP abuse/NOUN first/ADV used/VERB against/ADP early/ADJ working/NOUN class/NOUN radicals/NOUN'
string = string.split(' ')
temp = ''
for a in string:
    if '/NOUN' in a:
        temp += a + ' '
    else:
        temp += 'NIL '
string = temp
print(string)

rawDescription: Replace words into special string except nouns and adjectives in Python


code:
cleaners = set()

def _call_cleaners():
    for cleaner in list(cleaners):
        cleaner()

atexit.register(_call_cleaners)

class Foo(object):
  def cleanup(self):
     if self.cleaned:
         raise RuntimeError("ALREADY CLEANED")
     self.cleaned = True
  def start(self):
     self.cleaned = False
     cleaners.add(self.cleanup)
  def end(self):
     self.cleanup()
     cleaners.remove(self.cleanup)

rawDescription: python: closures and classes

description: Python: closures and classes


rawDescription: how use struct.pack for list of strings

description: How use struct.pack for list of strings


code:
import random

def main():
    value_1=random.randrange(1,6)
    value_2=random.randrange(1,6)
    show_larger(value_1, value_2)

def show_larger(value_1, value_2):
    if value_1 == value_2:
        print('The integers are equal, both are' + str(value_1))
        return
    else:
        print(("value_1" if value_1>value_2 else "value_2") + "is bigger by" + str(abs(value_1 - value_2)))

main()

rawDescription: Which number is bigger and by how much for random numbers


code:
import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        # formatting
        self.resize(1000, 1000)
        self.setWindowTitle("Cameras")

        # widgets
        self.ListA = QtGui.QTreeWidget()
        self.ListB = QtGui.QTreeWidget()
        self.Button = QtGui.QPushButton()

        # layout Splitter
        # QHBoxLayout
        self.mainLayout = QtGui.QGridLayout(self)
        self.mainLayout.setContentsMargins(5,5,5,5)

        self.leftPanel = QtGui.QFrame(self)
        # self.leftPanel.setFrameShape(QtGui.QFrame.StyledPanel)
        self.leftPanelLayout = QtGui.QHBoxLayout(self.leftPanel)
        self.leftPanelLayout.setContentsMargins(0,0,0,0)
        self.leftPanelLayout.addWidget(self.ListA)

        self.rightPanel = QtGui.QFrame(self)
        # self.rightPanel.setFrameShape(QtGui.QFrame.StyledPanel)
        self.rightPanelLayout = QtGui.QHBoxLayout(self.rightPanel)
        self.rightPanelLayout.setContentsMargins(0,0,0,0)
        self.rightPanelLayout.addWidget(self.Button)

        self.splitter = QtGui.QSplitter(QtCore.Qt.Horizontal)
        self.splitter.addWidget(self.leftPanel)
        self.splitter.addWidget(self.rightPanel)
        self.splitter.setCollapsible(0,False)
        self.splitter.setCollapsible(1,False)

        self.mainLayout.addWidget(self.splitter,0,0)

        self.setWindowTitle('QtGui.QSplitter')
        self.show()

        self.set_panel_sizes(self.splitter)

    def onChanged(self, text):

        self.lbl.setText(text)
        self.lbl.adjustSize()

    def set_panel_sizes(self, ctrl):
        width = ctrl.frameSize().width() / 2.0
        ctrl.setSizes( [width,width] )

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: force python pyside splitter to start window center

description: Force python pyside splitter to start window center


code:
df = pd.DataFrame(np.random.randn(4, 3), columns=[[1, 2, 3], ['d', 's', 'd']])
df.columns.names = ['PLOT', 'DEPTH']
df
df.groupby(level='DEPTH', axis=1).mean()

rawDescription: Group data based on column label in pandas dataframe


rawDescription: How to mock a decorated function

description: Mock a decorated function


code:
class Mehod1(models.Model):
    # other param
    species_param = models.CharField(max_length=20, choices=(('mouse', 'Mouse'), ('human', 'Human')), default='mouse')

rawDescription: How can I enable default value display under Django CharField

description: Enable default value display under Django CharField


code:
import IPython.core.completer
old_dir = IPython.core.completer.dir2

def my_dir(obj):
    methods = old_dir(obj)
    #merge your swig methods in
    return methods

IPython.core.completer.dir2 = my_dir

rawDescription: How can I make dir(obj) return non-function members in swig generated python classes?

description: Make dir(obj) return non-function members in swig generated python classes


code:
cricket_balls, total_score = 0, 0
while cricket_balls < 6:
    score = int(input('What was the score of bowl {} ?'.format(cricket_balls)))
    cricket_balls += 1
    total_score += score
    print(score)
total_score = score
print('The total score for this over is', total_score)

rawDescription: How do i set a variable value into another variable in Python?

description: Set a variable value into another variable in Python


code:
import os,mmap
f=os.open("afile",os.O_RDWR)
m=mmap.mmap(f,0)
m[4:9]="01234"
os.close(f)

rawDescription: String replacing in a file by given position


rawDescription: initiliase list with empty elements python

description: Initiliase list with empty elements python


code:
def countsort(unsorted):
    unsorted = numpy.asarray(unsorted)
    return numpy.repeat(numpy.arange(1+unsorted.max()), numpy.bincount(unsorted))

rawDescription: How can I vectorize this python count sort so it is absolutely as fast as it can be?

description: Vectorize this python count sort so it is absolutely as fast as it can be


code:
from Tkinter import *

class MyLabel(Frame):
    '''inherit from Frame to make a label with customized border'''
    def __init__(self, parent, myborderwidth=0, mybordercolor=None,
                 myborderplace='center', *args, **kwargs):
        Frame.__init__(self, parent, bg=mybordercolor)
        self.propagate(False) # prevent frame from auto-fitting to contents
        self.label = Label(self, *args, **kwargs) # make the label

        # pack label inside frame according to which side the border
        # should be on. If it's not 'left' or 'right', center the label
        # and multiply the border width by 2 to compensate
        if myborderplace is 'left':
            self.label.pack(side=RIGHT)
        elif myborderplace is 'right':
            self.label.pack(side=LEFT)
        else:
            self.label.pack()
            myborderwidth = myborderwidth * 2

        # set width and height of frame according to the req width
        # and height of the label
        self.config(width=self.label.winfo_reqwidth() + myborderwidth)
        self.config(height=self.label.winfo_reqheight())

root=Tk()
MyLabel(root, text='Hello World', myborderwidth=4, mybordercolor='red',
        myborderplace='left').pack()
root.mainloop()

rawDescription: how to add a left or right border to a tkinter Label

description: Add a left or right border to a tkinter Label


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

from selenium import webdriver
from threading import Thread

with open("url_lists.txt","r") as fi:  ###The text file contains hundreds of urls
    urls = fi.read().splitlines()

def func(url, bro):

    browserFunc = getattr(webdriver, bro, webdriver.Firefox)
    browser = browserFunc()
    browser.get(url)
    browser.find_element_by_id('download').click()

t = []
urls = [1,2,3,4,5]
bros = [1,2,3,4,5]

for i in range(len(urls)):
    t.append(Thread(target=func, args=[urls[i], bros[i]]))
for i in t:
    t.start()
for i in t:
    t.join()

if __name__ == '__main__':

    a = test1()

rawDescription: Performing multiple tasks at the same time in Python


code:
list = []
if list:
    print("not empty")
else:
    print("empty")

rawDescription: Can I use find on both a non empty and empty list?

description: Use find on both a non empty and empty list


code: contents.insert(0, "import sys; sys.path.append('lib'); sys.path.append('device')")

rawDescription: Absolute and relative importing for scripts


code: '\n'.join(itertools.islice((tag for tag in tags if tag.startswith(tag_filter)), 20))

rawDescription: Fastest method to filter and get a chunk of a list of strings


code:
runs = []
curr = 0
for x in list1:
    if x == 0:
        if curr != 0:
            runs.append(curr)
            curr = 0
    else:
        curr = curr + 1
if curr > 0: runs.append(curr)

rawDescription: Finding 'runs' within a list

description: Finding 'runs' within a list


code:
import fileinput

for line in fileinput.input(): ...

rawDescription: Python equivalent of Perl's while (<>) {...}?


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

from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

x = []
y = []
t = []

fig = plt.figure()
rect = fig.patch
rect.set_facecolor('#31312e')

readFile = open('C:\\Temp\\001.txt', 'r')
sepFile = readFile.read().split('\n')
readFile.close()

for idx, plotPair in enumerate(sepFile):
    if plotPair in '. ':
        # skip. or space
        continue
    if idx > 1:  # to skip the first line
        xAndY = plotPair.split(',')
        time_string = xAndY[0]
        time_string1 = datetime.strptime(time_string, '%d/%m/%Y %H:%M')
        t.append(time_string1)
        y.append(float(xAndY[1]))

ax1 = fig.add_subplot(1, 1, 1, axisbg='white')
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y %H:%M'))
ax1.plot(t, y, 'c', linewidth=3.3)

plt.title('IRRADIANCE')
plt.xlabel('TIME')
fig.autofmt_xdate(rotation=45)
fig.tight_layout()
fig.show()

a = raw_input('enter to stop...')

rawDescription: Plot date and time (x axis) versus a value (y axis) using data from txt file (Python)


code:
a = "\n"
b = "\n"
a is b
a == b

rawDescription: While loop comparison behaving odd

description: While loop comparison behaving odd


code:
# in the test's setup code
from unittest import mock
sys = mock.MagickMock()
sys.configure_mock(platform='win32')
sys.platform
'win32'

rawDescription: Change OS for unit testing in Python

description: Change OS for unit testing in Python


code: result = {k: d2.get(v) for k, v in d1.items()}

rawDescription: Python: comprehension to compose two dictionaries


code:
grid = np.transpose(grid)
plt.imshow(grid, cmap=cm.gist_gray)
plt.show()

rawDescription: 2D heat map using python and matplotlib

description: 2D heat map using python and matplotlib


rawDescription: Retrieving data from a class without the str method


code:
import networkx as nx
from nxpd import draw
G = nx.DiGraph()
G.graph['dpi'] = 120
G.add_nodes_from(range(1,9))
G.add_edges_from([(1,2),(1,3),(2,4),(3,6),(4,5),(4,6),(5,7),(5,8)])
draw(G, show='ipynb')

rawDescription: How to represent graphs with ipython

description: Represent graphs with ipython


code:
l = ['SPRD', '60', 'p25']
filter(None,(s.translate(None,'1234567890') for s in l))

rawDescription: What is the most pythonic way to filter list from number?


code:
# If your equations are simple enough, do operations column-wise in Pandas:

import pandas as pd

test = pd.DataFrame([[1,2],[3,4],[5,6]])
test # Default column names are 0, 1
test[0] # This is column 0
test.icol(0) # This is COLUMN 0-indexed, returned as a Series
test.columns=(['S','Q']) # Column names are easier to use
test #Column names! Use them column-wise:
test['result'] = test.S**2 + test.Q
test # results stored in DataFrame

# For more complicated stuff, try apply, as in Python pandas apply on more columns :

def toyfun(df):
    return df[0]-df[1]**2

test['out2']=test[['S','Q']].apply(toyfun, axis=1)

# You can also define the column names when you generate the DataFrame:
test2 = pd.DataFrame([[1,2],[3,4],[5,6]],columns = (list('AB')))

rawDescription: Reading values from Pandas dataframe rows into equations and entering result back into dataframe


code:
def get_np_array_from_tar_object(tar_extractfl):
     '''converts a buffer from a tar file in np.array'''
     return np.asarray(
        bytearray(tar_extractfl.read())
        , dtype=np.uint8)

tar0 = tarfile.open('mytar.tar')

im0 = cv2.imdecode(
        get_np_array_from_tar_object(tar0.extractfile('fname.png'))
        , 0 )

rawDescription: having cv2.imread reading images from file objects or memory-stream-like data (here non-extracted tar)

description: Having cv2.imread reading images from file objects or memory-stream-like data (here non-extracted tar)


code:
import enthought.mayavi.mlab as mylab
import numpy as np
x, y, z, value = np.random.random((4, 40))
mylab.points3d(x, y, z, value)
mylab.show()

rawDescription: Any easy way to plot a 3d scatter in Python that I can rotate around?


code:
def reverse_complement(my_bitarray):
    # First reverse by twos
    my_bitarray = zip(my_bitarray[0::2], my_bitarray[1::2])
    my_bitarray = reversed(list(my_bitarray))
    my_bitarray = (i for t in my_bitarray for i in t)
    my_bitarray = bitarray(my_bitarray)

    # Then complement
    my_bitarray.invert()
    return my_bitarray

rawDescription: Python bitarray reverse complement

description: Python bitarray reverse complement


code:
def func(arg1, arg2):
    """Summary line.

    Extended description of function.

    Parameters
    ----------
    arg1 : int
        Description of arg1
    arg2 : str
        Description of arg2

    Returns
    -------
    bool
        Description of return value

    """
    return True

rawDescription: Making API from Python docstrings written in PEP8


code:
def addInPlace(self, mAdd, lIndex):
    if type(lIndex) == list:
        mAdd[lIndex[0], lIndex[1]] += 1
    else:
        mAdd += lIndex
    return mAdd

rawDescription: pyspark matrix accumulator

description: Pyspark matrix accumulator


code:
import pandas as pd

# Create DataFrame
df = pd.DataFrame(
{'id':[2967, 5335, 13950, 6141, 6169],\
 'Player': ['Cedric Hunter', 'Maurice Baker' ,\
            'Ratko Varda' ,'Ryan Bowen' ,'Adrian Caldwell'],\
 'Year': [1991 ,2004 ,2001 ,2009 ,1997],\
 'Age': [27 ,25 ,22 ,34 ,31],\
 'Tm':['CHH' ,'VAN' ,'TOT' ,'OKC' ,'DAL'],\
 'G':[6 ,7 ,60 ,52 ,81]})

# Define the sorter
sorter = ['TOT', 'ATL', 'BOS', 'BRK', 'CHA', 'CHH', 'CHI', 'CLE', 'DAL','DEN',\
          'DET', 'GSW', 'HOU', 'IND', 'LAC', 'LAL', 'MEM', 'MIA', 'MIL',\
          'MIN', 'NJN', 'NOH', 'NOK', 'NOP', 'NYK', 'OKC', 'ORL', 'PHI',\
          'PHO', 'POR', 'SAC', 'SAS', 'SEA', 'TOR', 'UTA', 'VAN',\
          'WAS', 'WSB']

# Create the dictionary that defines the order for sorting
sorterIndex = dict(zip(sorter,range(len(sorter))))

# Generate a rank column that will be used to sort
# the dataframe numerically
df['Tm_Rank'] = df['Tm'].map(sorterIndex)

# Here is the result asked with the lexicographic sort
# Result may be hard to analyze, so a second sorting is
# proposed next
df.sort(['Player', 'Year', 'Tm_Rank'], \
        ascending = [True, True, True], inplace = True)
df.drop('Tm_Rank', 1, inplace = True)
print(df)

# Here is an example where 'Tm' is sorted first, that will
# give the first row of the DataFrame df to contain TOT as 'Tm'
df['Tm_Rank'] = df['Tm'].map(sorterIndex)
df.sort(['Tm_Rank', 'Player', 'Year'], \
        ascending = [True , True, True], inplace = True)
df.drop('Tm_Rank', 1, inplace = True)
print(df)

rawDescription: sorting by a custom list in pandas

description: Sorting by a custom list in pandas


rawDescription: Center Pivot without xform

description: Center Pivot without xform


code:
# loop over rows with label column not equal to 'None',
# collect consecutive rows with same location into a
# list (grp) and return list of those lists (groups)
groups = []
grp = []
df1 = df[df['label'] != 'None']
prev = df1.iloc[0]['label']
for r in df1.iterrows():
    curr = r[1]['label']
    if curr == prev:
        grp.append(r[1])
    else:
        groups.append(grp)
        grp = []
        prev = curr

# extract stop locations get middle distances
loclines = []
for g in groups:
    mids = g[len(g)/2]
    loclines.append([mids['TotalDist'], mids['label']])

# mark stops on plot as coloured vertical lines
plt.figure()
df.plot(x='TotalDist', y='val')
ax = plt.gca()
ax.set_title('TotalDist vs val')
for li, l in enumerate(loclines):
    if loclines[li][1] == 'A': color = 'r'
    if loclines[li][1] == 'B': color = 'g'
    if loclines[li][1] == 'C': color = 'y'
    plt.axvline(x=loclines[li][0],color= color)

plt.show()

rawDescription: Compute unique axis labels according to gps data in pandas DataFrame


code:
#!/usr/bin/env python
# coding: utf8
from __future__ import absolute_import, division, print_function
from itertools import product

def main():
    filename = 'test.txt'
    coach_count = 3
    player_count = 5

    already_scored = set()
    with open(filename) as lines:
        for line in lines:
            coach_id, player_id, _ = map(int, line.split())
            already_scored.add((coach_id, player_id))

    with open(filename, 'w') as score_file:
        for coach_id, player_id in product(
            xrange(coach_count), xrange(player_count)
        ):
            if (coach_id, player_id) not in already_scored:
                score = get_score_somehow(coach_id, player_id)
                record = [coach_id, player_id, score]
                score_file.write(' '.join(map(str, record)) + '\n')

if __name__ == '__main__':
    main()

rawDescription: Writing to a text file by adding new entries


rawDescription: In Django, Can I `defer()` fields in an object that's being queried by `select_related()`


code:
import ConfigParser
from pprint import pprint
cfg = ConfigParser.ConfigParser()
cfg.read('config.cfg')
CONFIG_DATA = {}
for section_name in cfg.sections():
    CONFIG_DATA[section_name] = {}
    for item_name in cfg.items(section_name):
        CONFIG_DATA[section_name][item_name] = cfg.get(section_name, item_name)
pprint(CONFIG_DATA)

rawDescription: Smarter way to load config values in python?


rawDescription: Pandas group dataframe by column and index adjacency


code:
import os
from shutil import copyfile

path = "videos/"
for root, dirs, files in os.walk(path):
    for name in files:
       if name.endswith((".mp4", ".mp4")):
          print(os.path.join(root, name))
          # copyfile(src, dst)

rawDescription: Find the sub-paths of files with specific externsion in python


code:
#!/usr/bin/env python
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

# ==================================
# Define the form of the function
# ==================================
def model(x, A=190, k=1):
    return A * np.exp(-k*x/50)

# ==================================
# How many data points are generated
# ==================================
num_samples = 15

# ==================================
# Create data for plots
# ==================================
x_model = np.linspace(0, 130, 200)

x_data1 = np.random.rand(num_samples) * 130
x_data1.sort()

x_data2 = np.random.rand(num_samples) * 130
x_data2.sort()

data1 = model(x_data1, k=1) * (1 + np.random.randn(num_samples) * 0.2)
data2 = model(x_data2, k=2) * (1 + np.random.randn(num_samples) * 0.15)

model1 = model(x_model, k=1)
model2 = model(x_model, k=2)

# ==================================
# Plot everything normally
# ==================================
fig = plt.figure()
ax = fig.add_subplot('111')
ax.plot(x_data1, data1, 'ok', markerfacecolor='none', label='Data (k=1)')
ax.plot(x_data2, data2, 'sk', markeredgecolor='0.5', markerfacecolor='0.5', label='Data (k=2)')
ax.plot(x_model, model1, '-k', label='Model (k=1)')
ax.plot(x_model, model2, '--k', label='Model (k=2)')

# ==================================
# Format plot
# ==================================
ax.set_xlabel('Distance from heated face($10^{-2}$ m)')
ax.set_ylabel('Temperature ($^\circ$C)')
ax.set_xlim((0, 130))
ax.set_title('Normal way to plot')
ax.legend()
fig.tight_layout()

plt.show()

# ==================================
# ==================================
# Do it again, but with custom
# legend
# ==================================
# ==================================
class AnyObject(object):
    pass

class data_handler(object):
    def legend_artist(self, legend, orig_handle, fontsize, handlebox):
        scale = fontsize / 22
        x0, y0 = handlebox.xdescent, handlebox.ydescent
        width, height = handlebox.width, handlebox.height
        patch_sq = mpatches.Rectangle([x0, y0 + height/2 * (1 - scale) ], height * scale, height * scale, facecolor='0.5',
                edgecolor='0.5', transform=handlebox.get_transform())
        patch_circ = mpatches.Circle([x0 + width - height/2, y0 + height/2], height/2 * scale, facecolor='none',
                edgecolor='black', transform=handlebox.get_transform())

        handlebox.add_artist(patch_sq)
        handlebox.add_artist(patch_circ)
        return patch_sq

# ==================================
# Plot everything
# ==================================
fig = plt.figure()
ax = fig.add_subplot('111')
d1 = ax.plot(x_data1, data1, 'ok', markerfacecolor='none', label='Data (k=2)')
d2 = ax.plot(x_data2, data2, 'sk', markeredgecolor='0.5', markerfacecolor='0.5', label='Data (k=1)')
m1 = ax.plot(x_model, model1, '-k', label='Model (k=1)')
m2 = ax.plot(x_model, model2, '-k', label='Model (k=2)')

# ax.legend([d1], handler_map={ax.plot: data_handler()})
ax.legend([AnyObject(), m1[0]], ['Data', 'Model'], handler_map={AnyObject: data_handler()})

# ==================================
# Format plot
# ==================================
ax.set_xlabel('Distance from heated face($10^{-2}$ m)')
ax.set_ylabel('Temperature ($^\circ$C)')
ax.set_xlim((0, 130))
ax.set_title('Custom legend')
fig.tight_layout()

plt.show()

rawDescription: How to make two markers share the same label in the legend using matplotlib?

description: Make two markers share the same label in the legend using matplotlib


code: from nltk.metrics.association import QuadgramAssocMeasures

rawDescription: nltk quadgram collocation finder

description: Nltk quadgram collocation finder


code:
from StringIO import StringIO
import ldif
from ldap import modlist

ldif_file = StringIO("""dn: cn=vpupkin,cn=people,ou=company,dc=domain,dc=com
c: UA
cn: vpupkin
""")

parser = ldif.LDIFRecordList(ldif_file)
parser.parse()

for dn, entry in parser.all_records:
    add_modlist = modlist.addModlist(entry)
    ldap_conn.add_s(dn, add_modlist)

rawDescription: Python-Ldap lib. Import LDIF

description: Python-Ldap lib. Import LDIF


code:
import  requests

print(requests.head(url).headers["Content-Type"])

rawDescription: How to get content-type from selenium page_source

description: Get content-type from selenium page_source


code:
for i, n in zip(idx, new):
    L[i] = n

rawDescription: replace a list using a list of indexes

description: Replace a list using a list of indexes


code: FORMAT = "[%(pathname)s:%(lineno)s - %(funcName)20s() ] %(message)s"

rawDescription: How to get the app name in django logger

description: Get the app name in django logger


code:
import glob

files = [open(f) for f in glob.glob("*.txt")]

# Given file, Read the 6th column in each line
def readcol5(f):
    return [line.split(' ')[5] for line in f]

filecols = [ readcol5(f) for f in files ]
maxrows = len(max(filecols, key=len))

# Given array, make sure it has maxrows number of elements.
def extendmin(arr):
    diff = maxrows - len(arr)
    arr.extend([''] * diff)
    return arr

filecols = map(extendmin, filecols)

lines = zip(*filecols)
lines = map(lambda x: ','.join(x), lines)
lines = '\n'.join(lines)

fout = open('output.csv', 'wb')
fout.write(lines)
fout.close()

rawDescription: Copy columns from multiple text files in Python


code: label= "Change the\n Address"

rawDescription: wxpython : wrap button label

description: Wxpython : wrap button label


rawDescription: replacing last part of string after pattern

description: Replacing last part of string after pattern


path: XYZ

path: ABC

rawDescription: Is this possible > Sublime3 + a python linter + virtualenv?


rawDescription: Optional group following non-greedy group


code:
start = -3
stop = None
result = a[start:stop]

rawDescription: when use negative number to slice a string in Python, 0 is disabled?

description: When use negative number to slice a string in Python, 0 is disabled


code:
import wx
import sys

class Frame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, size=(380, 230))

        dl = wx.ListCtrl(self, -1, style=wx.LC_REPORT)
        dl.InsertColumn(0, 'File')
        dl.InsertColumn(1, 'Progress')
        dl.InsertColumn(2, 'State')

        for row in range(3):
            labels = [l+str(row) for l in "FILE PERCENT STATE".split()]
            # sys.maxint inserts at the end of the list
            index = dl.InsertStringItem(sys.maxint, labels[0])
            dl.SetStringItem(index, 1, labels[1])
            dl.SetStringItem(index, 2, labels[2])

        self.Show(True)

app = wx.App()
Frame(None)
app.MainLoop()

rawDescription: wx.ListCtrl not displaying strings added by SetStringItem

description: Wx.ListCtrl not displaying strings added by SetStringItem


code:
with open(filename, "r") as f:
    for line in f:
        url = urllib2.urlopen(line)
        ...

rawDescription: Fetch URLs from a Text File Using Python


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

import sys
import re

def extract_id(line):
    """
    input: HumanDistalGut_READ_00048904.2  GO:0006412  TIGRFAM TIGR00001
    returns: 00048904.2
    """
    result = re.search(r'READ_(\d{8}\.\d)', line)
    if result != None:
        return result.group(1)
    else:
        return None

def extract_go_num(line):
    """
    input: HumanDistalGut_READ_00048904.2  GO:0006412  TIGRFAM TIGR00001
    returns: 0006412
    """
    result = re.search(r'GO:(\d{7})', line)
    if result != None:
        return result.group(1)
    else:
        return None

def main(argv = None):
    if argv is None:
        argv = sys.argv

    with open('readID.txt', 'r') as f:
        ids = frozenset(f.readlines())

    with open('GO.txt', 'r') as haystack, \
        open('GOLines.txt', 'w') as output:

        for line in haystack:
            if extract_id(line) in ids:
                output.write(extract_go_num(line) + '\n')

if __name__ == "__main__":
    sys.exit(main())

rawDescription: Searching a file with the contents of another file python


code:
class NoneWrapper(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped

    def __getattr__(self, name):
        value = getattr(self.wrapped, name)
        if value is None:
            return ''
        else:
            return value

mydb = NoneWrapper(database)
color = mydb.color
size = mydb.size
shape = mydb.shape
name = mydb.name

# All of these will be set to an empty string if their
# original value in the database is none

rawDescription: Python: Efficient way to put multiple variables through a function


code:
import OrcFxAPI
import numpy as np

g = 9.80665002864

# Load file name
filename = 'CX15-Anchor Plan.dat'
model = OrcFxAPI.Model(filename)

# Pipe tensions to be solved for; units are in MT then converted to kN for Orcaflex
min_tension = float(raw_input("\n Please enter the minimum tension to calculate catenary in MT: "))
max_tension = float(raw_input("\n Please enter the maximum tension to calculate catenary in MT: "))
tension_increment = float(raw_input("\n Please enter the tension increment to calculate catenary in MT: "))
pipe_tensions = (np.arange(min_tension, max_tension, tension_increment) * g).tolist()

# Grab lines in model
objects = model.objects # returns a tuple
lines = [obj for obj in objects if obj.type == OrcFxAPI.otLine] # All line objects in model

# Solve all lines in model for all line tensions
print('\nSolving line tensions...')
for tension in pipe_tensions:
    print('\nLine tension being solved for is {:.2f} kN.\n').format(tension)
    for line in lines:
        model.general.LineSetupCalculationMode = 'Calculate Line Lengths'
        model[line.name].LineSetupIncluded = 'Yes'
        model[line.name].LineSetupTargetVariable = 'Tension'
        model[line.name].LineSetupTargetValue = tension
        model[line.name].LineSetupLineEnd = 'End A'
        print('Line {} set.').format(line.name)
    print('\nInvoking Line Setup Wizard...')
    model.InvokeLineSetupWizard()
    print('\nLine Setup Wizard done.')
    # Calculate static position of mooring lines and buoys
    model.CalculateStatics()
    # Save static simulation and load into new object
    model.SaveSimulation(('{} - {:.2f} kN.sim').format(filename, tension))

print('\nLine Wizard has completed!')

rawDescription: How to iterate through a tuple containing class objects?

description: Iterate through a tuple containing class objects


code:
u1 = User.objects.get(id = 1)
u2 = User.objects.get(id = 1)

rawDescription: Test not passing in Django when it should


code:
import xlwt

style = xlwt.easyxf('align: rotation 90')

workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Test')
worksheet.write(0, 0, label='Formatted value', style=style)
workbook.save('test.xls')

rawDescription: text orientation on excel(individual cell) in python

description: Text orientation on excel(individual cell) in python


code:
import tkinter
import sys
from fractions import gcd

CURRENT_LABELS = []

def pythagorean_primitive(a, b, c):
    """returns True if a,b,c are pythagorean primitives, False otherwise"""
    return a**2 + b**2 == c**2 and gcd(a, b) == 1

def generate_results(n):
    """lists each triplet of distinct integers <n that is a pythagorean primitive"""
    results = []
    for a in range(1, n):
        for b in range(a, n):
            for c in range(b, n):
                if pythagorean_primitive(a, b, c):
                    results.append([a, b, c])
    return results

def generate_labels(sequence):
    """returns a list of tkinter labels from the sequence provided"""
    labels = []
    for elt in sequence:
        a, b, c = elt[0], elt[1], elt[2]
        labels.append(tkinter.Label(root, text='[' + str(a) + ', '+ str(b) + ", " + str(c) + "]"))
    return labels

def destroy_old():
    """purges the current tkinter labels from root, and destroys them"""
    global CURRENT_LABELS
    for elt in CURRENT_LABELS:
        elt.grid_forget()
        elt.destroy()

def show_new_labels(sequence):
    """assembles a new display of tkinter labels from the sequence provided"""
    r, c = 1, 0
    for label in sequence:
        label.grid(row=r, column=c, ipadx=5, ipady=5, sticky='W''E')
        r += 1
        if not r % 10:
            r = 1
            c += 1

def event_handler(event):
    """deals with the input of a number in the Entry field"""
    global CURRENT_LABELS
    x = int(e1.get())  # get max number
    results = generate_results(x)
    try:
        destroy_old()
    except IndexError:
        pass
    CURRENT_LABELS = generate_labels(results)
    show_new_labels(CURRENT_LABELS)

def close():  # close program
    tkinter.sys.exit(0)
    sys.exit(0)

root = tkinter.Tk()  # establish main gui
root.title('Generator')
e1 = tkinter.Entry(root)
assert isinstance(e1, object)  # only method I've found to allow for Entry().grid()
e1.grid(ipadx=5, ipady=5, sticky='W''E')
root.bind('<Return>', event_handler)  # bind to Enter, cleaner and quicker than a button
root.mainloop()

rawDescription: How would I remove labels in my for loops


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

# fake data
x = np.random.lognormal(mean=2.25, sigma=0.75, size=37)

# setup the figure and axes
fig = plt.figure(figsize=(6,4))
bpAx = fig.add_axes([0.2, 0.7, 0.7, 0.2])   # left, bottom, width, height:
                                            # (adjust as necessary)
histAx = fig.add_axes([0.2, 0.2, 0.7, 0.5]) # left specs should match and
                                            # bottom + height on this line should
                                            # equal bottom on bpAx line
# plot stuff
bp = bpAx.boxplot(x, notch=True, vert=False)
h = histAx.hist(x, bins=7)

# confirm that the axes line up
xlims = np.array([bpAx.get_xlim(), histAx.get_xlim()])
for ax in [bpAx, histAx]:
    ax.set_xlim([xlims.min(), xlims.max()])

bpAx.set_xticklabels([])  # clear out overlapping xlabels
bpAx.set_yticks([])  # don't need that 1 tick mark
plt.show()

rawDescription: Matplotlib: Can we draw a histogram and a box plot on a same chart?


code:
class Rider(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    def __unicode__(self):
        return self.first_name + " " + self.last_name

class Ride(models.Model):
    name = models.CharField(max_length=200)
    meeting_place = models.CharField(max_length=2000)
    description = models.CharField(max_length=2000)
    leader = models.ForeignKey(Rider)
    date = models.DateTimeField('date of ride')
    miles = models.FloatField('scheduled miles')
    def __unicode__(self):
        return self.name

class Miles(models.Model):
    rider = models.ForeignKey(Rider)
    ride = models.ForeignKey(Ride)
    actual_miles = models.FloatField('actual miles')
    def __unicode__(self):
        return "%s %s %s" % (self.rider, self.ride, self.actual_miles)

rawDescription: Referencing fields from other models

description: Referencing fields from other models


code:
from twisted.internet import reactor
reactor.listenTCP(4321, FirstProtocolFactory())
reactor.listenTCP(5432, SecondProtocolFactory())
reactor.listenTCP(6543, ThirdProtocolFactory())
reactor.run()

rawDescription: Multiple reactors (main loops) in one application through threading (or alternative means)


code:
from dateutil.parser import parse
dt = parse('19981024103115+0100')
dt
dt.utctimetuple()

rawDescription: Get the GMT time given date and UTC offset in python


code:
import wave

data = [128 for i in range(100)] # zeroes
data[50] = 255 # except for one spike
data = bytes(data) # convert to bytes

with open(r'D:\foo.wav', 'wb') as file:
    f = wave.open(file)
    f.setnchannels(1) # mono
    f.setsampwidth(1)
    f.setframerate(44100) # standard sample rate
    f.writeframes(data)

rawDescription: I need to generate a unit impulse .wav file?


code:
class x(object):
    pass

for item in mystr:
    setattr(x, item, item + commonstr)

rawDescription: Python - creating a struct with '.' from an array of strings


code:
from pywinauto import Application

app = Application().start(u'your_app.exe')
app.MainWindow.MenuSelect(u'File->Open')

app.OpenDialog.Edit.SetEditText(u'some path')
app.OpenDialog.Open.Click()
app.OpenDialog.WaitNot('visible', timeout=10)

new_main_window = app.Window_(title_re='^.* - The Software$')
new_main_window.Wait('ready', timeout=15)

rawDescription: Windows Desktop GUI Automation using Python - Sleep vs tight loop


code:
d = defaultdict(int, {u'Kiwi': defaultdict(int, {u'NZKiwi': 1.2}), u'Pear': defaultdict(int, {u'PearShaped': 6.2}), u'Banana': defaultdict(int, {u'BananaBrand': 4.0, u'OtherBrand': 3.2}), u'Apple': defaultdict(int, {u'CrunchApple': 1.7})})
d1 = defaultdict(int, {u'Kiwi': defaultdict(int, {u'n': 1.2}), u'Pear': defaultdict(int, {u'p': 6.2}), u'Banana': defaultdict(int, {u'b': 4.0, u'o': 3.2}), u'Apple': defaultdict(int, {u'a': 1.7})})
for k,v in d.items():
    v.update(d1[k])
d

rawDescription: How to concatenate or combine two defaultdicts of defaultdicts that have overlapping keys?

description: Concatenate or combine two defaultdicts of defaultdicts that have overlapping keys


code:
class X(object):
    def func(self, *, arg1, arg2, arg3):
        pass

rawDescription: python: validating function parameters

description: Python: validating function parameters


code:
with openMySpecialFile('/path/to/file.zip', 'rb') as msf:
    ...

rawDescription: Create file wrapper that can be opened

description: Create file wrapper that can be opened


code:
def wordset(data):
    return sorted(set(data))

rawDescription: Python - wordset() function

description: Python - wordset() function


code:
b = [row for row in data if counter[row[10]] >= sample_cutoff]
map(writer.writerow, b)

rawDescription: python: inserting a whole line into a list

description: Python: inserting a whole line into a list


code:
import Tkinter as tk

class App(object):
    def __init__(self, master, **kwargs):
        frame = tk.Frame(master)
        self.variables = {}
        s = {'WZ':1,'ZB':2,'RS':3,'CC':4,'CL':5}
        for k, v in s.iteritems():
             self.variables[k] = tk.IntVar()
             cb = tk.Checkbutton(
                 frame, text=k, onvalue=v, offvalue=0,
                 variable=self.variables[k],
                 command=self.oncheck(k),
                 anchor='w')
             cb.pack(side='top',fill='x')
        frame.pack()
    def oncheck(self, key):
        def _oncheck():
            print('{l} => {v}'.format(l=key, v=self.variables[key].get()))
        return _oncheck

root = tk.Tk()
app = App(root)
root.mainloop()

rawDescription: Reading variables for a set of Checkbuttons in TKinter


rawDescription: How to get last items of a list in Python?

description: Get last items of a list in Python


code:
custom_tick_locs = [datetime.time(hour=8), datetime.time(hour=16)]
custom_tick_labels = map(lambda x: x.strftime('%H'), custom_tick_locs)
plt.xticks(custom_tick_locs, custom_tick_labels)

rawDescription: xtick label formatting in pandas when using time index

description: Xtick label formatting in pandas when using time index


code:
import sys, signal
from bs4 import BeautifulSoup
from bs4.dammit import UnicodeDammit
from PyQt4 import QtCore, QtGui, QtWebKit

class WebPage(QtWebKit.QWebPage):
    def __init__(self):
        QtWebKit.QWebPage.__init__(self)
        self.mainFrame().loadFinished.connect(self.handleLoadFinished)

    def process(self, items):
        self._items = iter(items)
        self.fetchNext()

    def fetchNext(self):
        try:
            self._url, self._func = next(self._items)
            self.mainFrame().load(QtCore.QUrl(self._url))
        except StopIteration:
            return False
        return True

    def handleLoadFinished(self):
        self._func(self._url, self.mainFrame().toHtml())
        if not self.fetchNext():
            print('# processing complete')
            QtGui.qApp.quit()

def funcA(url, html):
    print('# processing:', url)
    # soup = BeautifulSoup(UnicodeDammit(html).unicode_markup)
    # do stuff with soup...

def funcB(url, html):
    print('# processing:', url)
    # soup = BeautifulSoup(UnicodeDammit(html).unicode_markup)
    # do stuff with soup...

if __name__ == '__main__':

    items = [
        ('http://stackoverflow.com', funcA),
        ('http://google.com', funcB),
        ]

    signal.signal(signal.SIGINT, signal.SIG_DFL)
    print('Press Ctrl+C to quit\n')
    app = QtGui.QApplication(sys.argv)
    webpage = WebPage()
    webpage.process(items)
    sys.exit(app.exec_())

rawDescription: PyQt Class not working for the second usage


code:
import webapp2
import google.appengine.api.images as images

class Uploader(webapp2.RequestHandler):
    def post(self):
        img_stream = self.request.get ('file')
        mimetype = self.request.POST['file'].type
        img_format = mimetype.split('/')[1]

        if (img_format == 'jpeg' or 'jpg' or 'gif' or 'png' or 'bmp' or 'tiff' or 'ico' or 'webp'):
            imageObj = images.Image (img_stream)
            width = imageObj.width
            height = imageObj.height
            self.response.out.write ('uploaded image is %s x %s [%s]' % (width, height, img_format))
        else:
            self.response.out.write ('not valid format')

rawDescription: How to get image Type and size when uploading it ? google app engine

description: Get image Type and size when uploading it ? google app engine


code:
foo="""
Quick Start*

Parsing a Document*

Parsing HTML*

Parsing XML*

"""

foo = foo.replace('*', '')

rawDescription: simple recursive string replace in python?

description: Simple recursive string replace in python


code:
with open("/my/output/path.txt", "w") as out_file:
    # Rest of code
    # ...
    out_file.write("%s|%s|%s|%s|%s|%s\n" % (asn,range,len(ran),org,ip,count))

rawDescription: Python script stops writing but in shown as a running process


rawDescription: How to pass Selenium html page to htmlXpathSelector

description: Pass Selenium html page to htmlXpathSelector


rawDescription: Check if modulo of a number exists in a tuple


code: max(abs(x - y) for (x, y) in zip(values[1:], values[:-1]))

rawDescription: Finding the largest delta between two integers in a list in python


code:
assigned_leads = lead.objects.filter(assigned_to__in=usercompany).distinct()
csvfile = StringIO.StringIO()
csvwriter = csv.writer(csvfile)
for leads in assigned_leads:
    csvwriter.writerow([leads.business_name, leads.first_name, leads.last_name, leads.email, leads.phone_number,leads.address, leads.city, leads.state, leads.zipcode, leads.submission_date, leads.time_frame, leads.comments])
message = EmailMessage("Hello","Your Leads","myemail@gmail.com",["myemail@gmail.com"])
message.attach('invoice.csv', csvfile.getvalue(), 'text/csv')

rawDescription: Attach generated CSV file to email and send with Django


code:
for item in input_list:
    print(item.split(" ", 1)[0])

rawDescription: Regex to search point numbers from the start of a list item from a list of strings


code: foo.translate(None," \"':; ")

rawDescription: How to give some specific symbols to python translate function

description: Give some specific symbols to python translate function


code:
import sys

_pyversion = sys.version_info[0]

def callback_method(func):
    def notify(self,*args,**kwargs):
        for _,callback in self._callbacks:
            callback()
        return func(self,*args,**kwargs)
    return notify

class NotifyList(list):
    extend = callback_method(list.extend)
    append = callback_method(list.append)
    remove = callback_method(list.remove)
    pop = callback_method(list.pop)
    __delitem__ = callback_method(list.__delitem__)
    __setitem__ = callback_method(list.__setitem__)
    __iadd__ = callback_method(list.__iadd__)
    __imul__ = callback_method(list.__imul__)

    #Take care to return a new NotifyList if we slice it.
    if _pyversion < 3:
        __setslice__ = callback_method(list.__setslice__)
        __delslice__ = callback_method(list.__delslice__)
        def __getslice__(self,*args):
            return self.__class__(list.__getslice__(self,*args))

    def __getitem__(self,item):
        if isinstance(item,slice):
            return self.__class__(list.__getitem__(self,item))
        else:
            return list.__getitem__(self,item)

    def __init__(self,*args):
        list.__init__(self,*args)
        self._callbacks = []
        self._callback_cntr = 0

    def register_callback(self,cb):
        self._callbacks.append((self._callback_cntr,cb))
        self._callback_cntr += 1
        return self._callback_cntr - 1

    def unregister_callback(self,cbid):
        for idx,(i,cb) in enumerate(self._callbacks):
            if i == cbid:
                self._callbacks.pop(idx)
                return cb
        else:
            return None

if __name__ == '__main__':
    A = NotifyList(range(10))
    def cb():
        print ("Modify!")

    #register a callback
    cbid = A.register_callback(cb)

    A.append('Foo')
    A += [1,2,3]
    A *= 3
    A[1:2] = [5]
    del A[1:2]

    #Add another callback.  They'll be called in order (oldest first)
    def cb2():
        print ("Modify2")
    A.register_callback(cb2)
    print ("-"*80)
    A[5] = 'baz'
    print ("-"*80)

    #unregister the first callback
    A.unregister_callback(cbid)

    A[5] = 'qux'
    print ("-"*80)

    print (A)
    print (type(A[1:3]))
    print (type(A[1:3:2]))
    print (type(A[5]))

rawDescription: List callbacks?

description: List callbacks


code:
imagea = PIL.Image.open('temp.png')
imageb = PIL.Image.open('temp.png')

for y in xrange(imagea.size[1]):
  for x in xrange(imagea.size[0]):
    currentPixel = imagea.getpixel((x,y))

    if currentPixel[0] >  50:
    #if currentPixel ==(0,0,0):
      #this is a black pixel, you can directly modify image 2 now
      imageb.putpixel((x,y),(0,0,0))

imageb.save('outputfile.png')

rawDescription: Python Imaging Library- Merging one type of pixel into another image


code:
class MyObjectsViewSet(viewsets.ModelViewSet):
    """
    A simple ViewSet for viewing and editing instances.
    """
    serializer_class = MyObjectsSerializer

    def get_queryset(self):
        queryset = MyModel.objects.all()
        pks = self.request.query_params.get('pks', None)

        if pks is not None:
            queryset = queryset.filter(pks__in=pks)

        return queryset

rawDescription: Django Rest Framework: using ModelViewSet to get a list of instances by their PKs


code:
class JobPostingListView(ListView):
    form_class = JobPostingSearchForm
    model = JobPosting
    template_name = 'recruiters/job_posting_list.html'

    def get_queryset(self):

        form = self.form = self.form_class(self.request.GET)
        if not self.request.user.is_authenticated():
            form.fields['date_posted'].choices.pop(1)
            form.fields['date_posted'].widget.choices.pop(1)
    ...

rawDescription: Delete dropdown choice dynamically in Django


code:
import numpy as np

def argmax(array):
    shape = array.shape
    array = array.reshape((shape[0], -1))
    ravelmax = np.argmax(array, axis=1)
    return (np.arange(shape[0]),) + np.unravel_index(ravelmax, shape[1:])

rawDescription: Taking argmax over all axes except first


code:
def run_command(command):
    p = subprocess.Popen(command, shell=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT)
    return p.communicate()

rawDescription: Using python with subprocess Popen

description: Using python with subprocess Popen


code:
from Tkinter import *
file = open("filename.txt")
data = file.read()
file.close()

root = Tk()
widget = Text(root)
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
widget.pack(side=LEFT, fill=Y)
scrollbar.config(command=widget.yview)
widget.config(yscrollcommand=scrollbar.set)
widget.insert(END, data)

root.mainloop()

rawDescription: How would i take all of the data in a text file and put it into a text widget in tkinter + add a scroll bar


code:
for vid, name in zip(ids, names):
        vid = vid['href'].split('=')
        vid = vid[1]

        name = name.contents[0]
        name = name.encode('iso-8859-1')

        data_content = (vid, name)
        cursor.execute(data_query, data_content)
        emp_no = cursor.lastrowid

rawDescription: Adding multiple arrays to a MySQL Table

description: Adding multiple arrays to a MySQL Table


code:
class A(object):
   def foo(self, bar):
      self.zoo = bar
i = A()
i.__dict__ # instance dict is empty
i.foo('hello') # assign a value to an instance
i.__dict__
i.z = {'another':'dict'}
i.__dict__
A.__dict__.keys() # at the CLASS level, only holds items in the class's namespace

rawDescription: What is the dfifference between instance dict and class dict


code:
proc = subprocess.Popen(["mysqld_safe", "--init-file=/var/lib/mysql/mysql-init"])
time.sleep(5)
proc.kill()

rawDescription: How to send a subprocess to the background & without using shell=True

description: Send a subprocess to the background & without using shell=True


code:
# The point (6, 28) is the location of my hotspot. This is in reference
# to the top left corner of the image.
cursor = wx.Cursor(os.path.join("path", "to", "cursor.ico"), wx.BITMAP_TYPE_ICO, 6, 28)
frame.SetCursor(cursor)

rawDescription: How do I create a custom cursor with a custom hotspot in wxPython?

description: Create a custom cursor with a custom hotspot in wxPython


code:
import subprocess
p1 = subprocess.Popen(["dpkg", "--list"], stdout=subprocess.PIPE, env={'LANG':'C'})
p2 = subprocess.Popen(["grep", "linux-image"], stdin=p1.stdout, stdout=subprocess.PIPE)
out,err=p2.communicate()
print(out)

rawDescription: Stdout captured from pipe in Python is truncated


rawDescription: get python argparser attributes into script namespace

description: Get python argparser attributes into script namespace


code: packages=['vector', 'exlib'],

rawDescription: Not install all files in site_packages using setup.py


code:
from IPython.html.widgets import interact, interactive, fixed
from IPython.display import display
import skimage
from skimage import data, filter, io

i = data.coffee()

def add_lines(image, line1 = 100, line2 = 200):
  new_image = image.copy()  # Work on a copy
  new_image[line1,:,:] = 0
  new_image[line2,:,:] = 0
  new_image = io.Image(new_image)
  display(new_image)

lims = (0,400,2)
interactive(add_lines, image=fixed(i), line1 = lims, line2 = lims)

rawDescription: adding moving horizontal lines to ipython interactive widgets

description: Adding moving horizontal lines to ipython interactive widgets


code: df['value'].apply(lambda x: 0 if not re.findall('\d+', str(x)) else re.findall('\d+', str(x))[0])

rawDescription: Extract Number from Varying String

description: Extract Number from Varying String


code:
if 'c' in locals():
    print ('Ok')
else:
    print('no')

rawDescription: Check if name is defined?

description: Check if name is defined


code:
# Half of the remainder of the image height when space for all lines has been reserved:
line_dimensions = [draw.textsize(line, font=font) for line in para]
offset = (MAX_H - sum(h for w, h in line_dimensions)) // 2

current_h = offset
for line, (w, h) in zip(para, line_dimensions):
    draw.text(((MAX_W - w) // 2, current_h), line, font=font)
    current_h += h

rawDescription: horizontally and vertically align of text with PIL

description: Horizontally and vertically align of text with PIL


code:
subclasses = set(cls.__subclasses__())
return subclasses + set(sc.get_subclasses() for sc in subclasses)

rawDescription: Is there a way to "one-line" this using list/set comprehension?


code:
import matplotlib.pyplot as plt

fig = plt.figure()

# Add subplots
nRows = 4
nCols = 2
nPlots = 7
ax1 = fig.add_subplot(nRows,nCols,1)
ax1.set_yscale('log')
ax1.set_xscale('log')

for n in range(1, nPlots+1):
    plt.subplot(nRows,nCols,n, sharex=ax1, sharey=ax1)

# Turn off tick lables where needed.
index = 0
for r in range(1, nRows +1):
     for c in range(1, nCols + 1):
         index += 1
         # Turn off y tick labels for all but the first column.
         if ((c != 1) and (index <= nPlots)):
             ax = plt.subplot(nRows, nCols, index, sharex=ax1, sharey=ax1)
             plt.setp(ax.get_yticklabels(), visible=False)
          # Turn off x tick lables for all but the bottom plot in each
          # column.
         if ((nPlots - index) >= nCols):
             ax = plt.subplot(nRows, nCols, index, sharex=ax1, sharey=ax1)
             plt.setp(ax.get_xticklabels(), visible=False)

plt.subplots_adjust(wspace=0, hspace=0)

plt.show()

rawDescription: Matplotlib/Pyplot shared axis for odd number of subplots


code:
from IPython.utils.coloransi import TermColors as color
class Test(object):
   def __init__(self, x):
       self.x = x
   def __repr__(self):
       return '{0}Test{{{1}{2}{0}}}'.format(color.Green, color.Red, self.x)

rawDescription: Colored representation of objects in IPython terminal shell


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

fig = plt.figure()

ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

xs = np.array( [ 1, 0 ,2 ])
ys = np.array( [ 1, 0, 2 ])
zs = np.array( [ 1, 2, 3 ])
ax.scatter(xs, ys, zs)

plt.show()

rawDescription: Two different graphs in the same plot

description: Two different graphs in the same plot


code:
import bs4
blah = '

one

something

'
soup = bs4.BeautifulSoup(blah)
soup('div', {'id': 'test'})[0].extract()
soup

rawDescription: Deleting all data between two html tags in python


code:
def pre(self,name):
    # name being 'prin' in your case
    if hasattr(self, name):
        getattr(self, name)()

rawDescription: How to find a function of a class by its name in python?

description: Find a function of a class by its name in python


code:
r = subprocess.getoutput("google-chrome-stable https://www.google.com/")
r

rawDescription: How to use webbrowser module open a web site but at background in python 3?

description: Use webbrowser module open a web site but at background in python 3


code:
import codecs
codecs.open('f.txt','r',encoding=None).read()
codecs.open('f.txt','r',encoding='ascii').read() # Note Unicode string returned.
open('f.txt','r').read()

rawDescription: What is the default encoding for Python 2.7.8?


code:
#!/usr/bin/env python

import cgi
import json
import os.path

new_data = {"2": {"title": "what", "date": "tomorrow"}}

print("Content-type: application/json\n\r")

script_dir = os.path.dirname(os.path.abspath(__file__))
fname = os.path.join(script_dir, 'jobs.json')

with open(fname) as f:
    data = json.load(f)

data.update(new_data)

with open(fname, 'w') as f:
    json.dump(data, f)

rawDescription: How do I append further JSON to the end of another JSON file when the scripts are in cgi-bin?

description: Append further JSON to the end of another JSON file when the scripts are in cgi-bin


code: names = [v for k, v in request.POST.items() if k.startswith('name')]

rawDescription: Getting POST values from a Django request when they start with the same string


code:
class Users(Base):
    __tablename__ = 'users'

    @classmethod
    def by_id(cls, userid):
        return Session.query(Users).filter(Users.id==userid).first()

rawDescription: sqlalchemy search function on table as classmethod?

description: Sqlalchemy search function on table as classmethod


code:
arg = sys.argv[1]

# intarg = 65 == 0x41
intarg = int(arg, 16)

# now convert to byte string '\x41'
hexstring = struct.pack('B', intarg)

rawDescription: Sending Hex Values through UDP or TCP socket via parameter passing to script


code:
import urllib.request
response = urllib.request.urlopen("https://aaa.com/api").read()

def test_api(a):
    if isinstance(a, int):
        if (a <= 5):
           return ("not good..")
        elif (a == 25):
           return ("great...")
    else :
        return "Opps...I was expecting an Integer"

def type_conversion(val, to_type, default=None):
    try:
        return to_type(val)
    except ValueError:
        return default

# type_conversion('str', int) # returns None
# type_conversion('str', int, 0) # returns 0
print (test_api(type_conversion(response, int)))

rawDescription: Storing data from API inside a function

description: Storing data from API inside a function


code:
import salt.client
import salt.key

client = salt.client.LocalClient()
key_manager = salt.key.Key(client.opts)
key_manager.accept('web*')

rawDescription: Salt-key command in runner

description: Salt-key command in runner


code:
def AutoFloatProperties(*props):
    '''metaclass'''
    class _AutoFloatProperties(type):
        # Inspired by autoprop (http://www.python.org/download/releases/2.2.3/descrintro/#metaclass_examples)
        def __init__(cls, name, bases, cdict):
            super(_AutoFloatProperties, cls).__init__(name, bases, cdict)
            for attr in props:
                def fget(self, _attr='_'+attr): return getattr(self, _attr)
                def fset(self, value, _attr='_'+attr): setattr(self, _attr, float(value))
                setattr(cls, attr, property(fget, fset))
    return _AutoFloatProperties

class Vector(object):
    '''Creates a Maya vector/triple, having x, y and z coordinates as float values'''
    __metaclass__ = AutoFloatProperties('x','y','z')
    def __init__(self, x=0, y=0, z=0):
        self.x, self.y, self.z = x, y, z # values converted to float via properties

if __name__=='__main__':
    v=Vector(1,2,3)
    print(v.x)
    # 1.0
    v.x=4
    print(v.x)
    # 4.0

rawDescription: Python Vector Class

description: Python Vector Class


code:
tags_to_be_removed = Tags.objects.filter(pk__gte=5) # use your filter
restaurant.tags.remove(*tags_to_be_removed)

rawDescription: Removing only certain associations of many-to-many in Django


code:
class HealthUnit(Unit):
    def __init__(self, **kwargs):
        self.health = kwargs.pop('health')
        super(HealthUnit, self).__init__(**kwargs)

class AttackUnit(Unit):
    def __init__(self, **kwargs):
        self.attack = kwargs.pop('attack')
        super(AttackUnit, self).__init__(**kwargs)

class TribeUnit(Unit):
    def __init__(self, **kwargs):
        self.tribe = kwargs.pop('tribe')
        super(TribeUnit, self).__init__(**kwargs)

class HealthAttackTribeUnit(HealthUnit, AttackUnit, TribeUnit):
    pass

rawDescription: How to use multiple (re-)inheritance properly

description: Use multiple (re-)inheritance properly


code:
s = """12/31/1991
December 10, 1980
September 25, 1970
2005-11-14
December 1990
October 12, 2005
1993-06-26"""
from dateutil import parser
for i in s.splitlines():
    d = parser.parse(i)
    print(d.strftime("%Y-%m-%d"))

rawDescription: Normalize different date data into single format in Python


rawDescription: how to assign a new element in array.array

description: Assign a new element in array.array


code:
class C:
   def __init__(self):
       self.a = 1
       self.b = 2

c=C
def f(o):
   o.a = 23

f(c)
c
c.a

rawDescription: Python: emulate C-style pass-by-reference for variables


code:
from sys import stderr
from Tkinter import *

def func(b):
    number = 2*b
    stderr.write('number=%d\n'%number)
    return

root=Tk()

# By clicking this button I want to set b = 1 and call func

b1 = Button(root,command=lambda : func(1))
b1.pack()

# By clicking this button I want to set b = 2 and call func

b2 = Button(root,command=lambda : func(2))
b2.pack()

root.mainloop()

rawDescription: How to set function parameter with Button in Tkinter?

description: Set function parameter with Button in Tkinter


code:
from PIL import Image
im = Image.open('polar-bear-cub.jpg')
from collections import defaultdict
by_color = defaultdict(int)
for pixel in im.getdata():
    by_color[pixel] += 1
by_color

rawDescription: Python how to get a list of color that used in one image


code:
import csv

price_list = {} # this is an empty dictionary

with open('gamesandprices.csv') as csvfile:
    readCSV = csv.reader(csvfile)
    for row in readCSV:
        price_list[row[0]] = row[1]

what_game = input("Which game(s) would you like to find out the price of?: ")
what_game = what_game.split(' ')

# Now what we want to do, is for each word in the input, check if it
# exists in our dictionary. If it does exist, it must be the name of
# a game, so we need to know its price.

# We also want to make sure we limit the number of games in one
# request to 6 games. To find out how many games the person entered,
# lets filter all the words and collect those words (and prices)
# that are games in a list.

# The long way of writing this is:
# results = [] - this is an empty list
# for word in what_game:
#    if word in price_list:
#        results.append(word, price_list[word])

results = [(game, price_list[game]) for game in what_game if game in price_list]

if len(results) > 6:
    print('Please ask prices for a maximum of 6 games')
else:
    for game, price in results:
        print('The price of {} is {}'.format(game, price))

rawDescription: User entering a sentence in an input and Python picking out keywords and getting it from CSV file


code:
bytes = file.read(4)
bytesAsInt = struct.unpack("l",bytes)
do_something_with_int(bytesAsInt)

rawDescription: Converting string to number in python

description: Converting string to number in python


rawDescription: convert vim regex to python for re.sub

description: Convert vim regex to python for re.sub


code: a *= fact[:, np.newaxis, :, np.newaxis, np.newaxis]

rawDescription: Avoid for loop using numpy matrices

description: Avoid for loop using numpy matrices


code:
import multiprocessing as mp
import os
import re
import sys

from stat import S_ISREG

# uncomment these if you really want a hard-coded $HOME/patterns file
#home = os.environ.get('HOME')
#patterns_file = os.path.join(home, 'patterns')

target = sys.argv[1]
size_limit = int(sys.argv[2])
assert size_limit >= 0
patterns_file = sys.argv[3]

# build s_pat as string like:  (?:foo|bar|baz)
# This will match any of the sub-patterns foo, bar, or baz
# but the '?:' means Python won't bother to build a "match group".
with open(patterns_file) as f:
    s_pat = r'(?:{})'.format('|'.join(line.strip() for line in f))

# pre-compile pattern for speed
pat = re.compile(s_pat)

def walk_files(topdir):
    """yield up full pathname for each file in tree under topdir"""
    for dirpath, dirnames, filenames in os.walk(topdir):
        for fname in filenames:
            pathname = os.path.join(dirpath, fname)
            yield pathname

def files_to_search(topdir):
    """yield up full pathname for only files we want to search"""
    for fname in walk_files(topdir):
        try:
            # if it is a regular file and big enough, we want to search it
            sr = os.stat(fname)
            if S_ISREG(sr.st_mode) and sr.st_size >= size_limit:
                yield fname
        except OSError:
            pass

def worker_search_fn(fname):
    with open(fname, 'rt') as f:
        # read one line at a time from file
        for line in f:
            if re.search(pat, line):
                # found a match! print filename to stdout
                print(fname)
                # stop reading file; just return
                return

mp.Pool().map(worker_search_fn, files_to_search(target))

rawDescription: Parallel file matching, Python

description: Parallel file matching, Python


code:
from django import forms
from django.core.exceptions import ValidationError

class MyForm(forms.Form):

    field_1 = forms.CharField(required=False)

    field_2 = forms.CharField(required=False)

    def clean(self):

        # Get the field values submitted
        cleaned_data = super(MyForm, self).clean()
        field_1_data = cleaned_data.get('field_1')
        field_2_data = cleaned_data.get('field_2')

        # Check that only one field is filled out.
        if field_1_data and field_2_data:
            raise ValidationError('Only fill out one field please.', code='invalid')

rawDescription: Django forms: How do I make it necessary to fill out one field but not possible to fill out both?


code:
x="the name of 33e4853h45y45 is one of the 33e445a64b65 and we want all the 33e5c44598e46 to be matched"
re.findall("33e\w+",x)

rawDescription: grep prefix python strings

description: Grep prefix python strings


code: sqlalchemy.schema.Column(name, type, *args, **kwargs)

rawDescription: Arguments of Column in SqlAlchemy Flask

description: Arguments of Column in SqlAlchemy Flask


code:
thread = Thread(target=start_message_server)
thread.daemon = True
thread.start()

rawDescription: Starting new thread via an RPC from C++ causes process to be zombied?


code:
class Test(object): # make sure you inherit from object
    @property
    def x(self):
        return 4

p = Test()
p.x # returns 4

rawDescription: Python: How to make object attribute refer call a method