rawDescription: Python compare list and store in new variable


code:
import wx

class myFrame(wx.Frame):
    def __init__(self, testImage):
        wx.Frame.__init__(self, None, size=testImage.Size)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.testImage = testImage
        self.Show()

    def OnPaint(self, event):
        dc = wx.PaintDC(self)
        background = wx.Colour(255, 0, 0)
        dc.SetBackground(wx.Brush(background))
        dc.Clear()
        #dc.DrawBitmap(self.testImage, 0,  0)  # black background
        dc.DrawBitmap(self.testImage, 0,  0, True)  # transparency on, now red

def main():
    app = wx.App(None)
    testImage = wx.Image(r"path_to_image.png", wx.BITMAP_TYPE_PNG).ConvertToBitmap()
    Frame = myFrame(testImage)
    app.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: Is there a max image size (pixel width and height) within wx where png images lose there transparency?


code:
X, Y = a.shape
x = X // n
y = Y // n
a = a.reshape( (x, n, y, n) )
a = a.transpose( [1, 3, 0, 2] )
a = a.reshape( (n*n, x, y) )

rawDescription: 'Tiling' a 2d array using numpy

description: 'Tiling' a 2d array using numpy


code:
s = "I'm a little bit like a list"
s[0]
Out[7]: 'I'
s[-1]
Out[8]: 't'
s[6:16]
Out[14]: 'little bit'

rawDescription: python add to string after nth characters

description: Python add to string after nth characters


code:
axes[0].set(yticks=y, yticklabels=[])
for yloc, state in zip(y, states):
    axes[0].annotate(state, (0.5, yloc), xycoords=('figure fraction', 'data'),
                     ha='center', va='center')

rawDescription: Using Python libraries to plot two horizontal bar charts sharing same y axis


code:
def reduceOutputListToPossibleMatches(outputList, detailsList):
    details = {}
    for detailsItem in detailsList:
        key = detailsItem[14]
        if key in details:
            details[key].append(detailsItem)
        else:
            details[key] = [detailsItem]

    for outputItem in outputList:
        key = outputItem[4]
        if key in details:
            for item in details[key]:
                if len(details[key]) > 1:
                    item[30] = "1"
                yield item

res = reduceOutputListToPossibleMatches(outputList, detailsList)
with open('somefile', 'w') as f:
    f.writelines(res)

rawDescription: Can Lists cope with a million items?

description: Can Lists cope with a million items


code:
import sys, re

regex = sys.argv[1]

someOtherString = 'hi there'

found = re.search(regex, someOtherString)
print('ok' if found else 'nope')

rawDescription: Python string (argument) -> Regex

description: Python string (argument) -> Regex


code: array = [[False for _ in range(n)] for _ in range(n)]

rawDescription: How to create a 2D list in python where all elements are the same?

description: Create a 2D list in python where all elements are the same


code:
complete = np.concatenate((a1,a2,a3,a4))
uvals, uind = np.unique(complete, return_inverse=True)
uvals[np.bincount(uind).argsort()[-4:]][::-1]

array([8, 3, 2, 9])

rawDescription: get the first few items order by item's count

description: Get the first few items order by item's count


code:
import pandas as pd
df1 = pd.read_csv("coord1.csv")
df2 = pd.read_csv("coord2.csv")
df1
df2

rawDescription: efficient method for merging 2 sorted files with duplicate coordinates in python

description: Efficient method for merging 2 sorted files with duplicate coordinates in python


code:
firstPoint = True
iteration = 0

xopt, fopt, iter, funcalls, warnflag, allvecs = sp.optimize.fmin(f,x0,full_output=True,xtol=0.9,retall=True)

rawDescription: How do you stop the scipy.optimize.fmin function and start it again using the optimization history?

description: Stop the scipy.optimize.fmin function and start it again using the optimization history


code: print("%.5f" % randomList[index])

rawDescription: creating list of random numbers in python

description: Creating list of random numbers in python


code:
global name
name = raw_input("What is your name? ")

rawDescription: Same Variable in different Functions. (Python)


code:
def __init__(self):
    attrs = ('g','t','d','fft','freq')
    self.__dict__.update(zip(attrs,([] for _ in range(len(attrs)))))

rawDescription: What's the neatest way of writing assignments in Python?


code:
txt = open(files[0]).read()           # read the file into a big string
before, after = txt.split('1:', 1)    # split the file on the first "1:"
after_lines = after.split('\n')       # create lines from the after text
lines_to_save = after_lines[:19]      # grab the first 19 lines after "1:"

rawDescription: parse blocks of text from text file using Python

description: Parse blocks of text from text file using Python


code:
grade = '14 sur 20'
re.split(r'sur|/', grade)
map(int, re.split(r'sur|/', grade))

rawDescription: Getting integers out of Python list

description: Getting integers out of Python list


code:
for x,y in zip(range(1, len(a), 2), range(2, len(b), 3)):
    a[x] = '{}\n'.format(b[y])

rawDescription: Replace every second element in list with every third in other list.


code: {{ results.cssjsslinks }}

rawDescription: Getting count of elements sent to html in Django


code: "Hello %s" % user_name_function()

rawDescription: Evaluation inside string

description: Evaluation inside string


code:
df
df.ix[pd.isnull(df['a']), 'b']

rawDescription: Collect values of pandas dataframe column A if column B is NaN (Python)


code:
register = template.Library()

@register.assignment_tag(takes_context=True)
def get_user_perm(context, perm):
    try:
        request = context['request']
        obj = Profile.objects.get(user=request.user)
        obj_perms = obj.permission_tags.all()
        flag = False
        for p in obj_perms:
            if perm.lower() == p.codename.lower():
                flag = True
                return flag
        return flag
    except Exception as e:
        return ""

rawDescription: Django - How to use custom template tag with 'if' and 'else' checks?


code:
huge_list = []

with open(huge_file, "r") as f:
    for line in f:
        huge_list.extend(line.split())

rawDescription: Reading words from a file and putting into list


code:
# groupby 'A'
grouped = df.groupby('A')

# transform B so every row becomes the maximum along the group:
max_B = grouped['B'].transform('max')

# add the new column to the old df
df['D'] = df['A'] + max_B

rawDescription: Python pandas - apply function to grouped dataframe


code: df.loc[df['column_name'] != some_value]

rawDescription: Select rows from a DataFrame based on values in a column in pandas


code:
goto(195+position,(191 * xy) - y)
goto(22+position,(23 * xy) - y)
goto(18+position,(252 * xy) - y)
goto(172+position,(221 * xy) - y)

rawDescription: Editing a list to add strings in in different positions to output a formatted string


code:
sr, stereo_data = sciwav.read('filename')
nparts = 100
part_length = len(stereo_data) // nparts

stereo_parts = numpy.split(stereo_data[:part_length*nparts], nparts)

new_data = numpy.vstack([numpy.zeros((1, 2), dtype=stereo_data.dtype)] +
                        stereo_parts)

sciwav.write('new_filename', sr, new_data)

rawDescription: constructing a wav file and writing it to disk using scipy

description: Constructing a wav file and writing it to disk using scipy


code:
from collections import defaultdict

dict_STU = defaultdict(list)
with open('all_spot_uniprot.txt', 'rbU') as spot_to_uniprot:
    reader = csv.reader(spot_to_uniprot, delimiter='\t')
    for row in reader:
        dict_STU[int(row[0])].append(row[2])

rawDescription: Computation time insanely long in python


code:
from itertools import combinations
teams = ['india', 'australia', 'new zealand']
[" and ".join(items) for items in combinations(teams, r=2)]

rawDescription: Itertools product without repeating duplicates


code:
import numpy as np
import pandas as pd
np.random.seed(2014)
df = pd.DataFrame(np.random.binomial(1, 0.1, size=(10,3)).astype(bool),
                  columns=list('ABC'))
print(df)
#        A      B      C
# 0  False  False  False
# 1   True  False  False
# 2  False  False  False
# 3   True  False  False
# 4  False  False  False
# 5  False  False  False
# 6  False   True  False
# 7  False  False  False
# 8  False  False  False
# 9  False  False  False

mylist = list('ABC')
print(df[ df[mylist[0]] | df[mylist[1]] | df[mylist[2]] ])
print(df.loc[df[mylist].any(axis=1)])
print(df.loc[np.logical_or.reduce(df[mylist], axis=1)])

rawDescription: Logical OR on a subset of columns in a DataFrame


rawDescription: press Javascript generated button with Selenium?

description: Press Javascript generated button with Selenium


code:
import csv
from collections import defaultdict

d = defaultdict(float)
with open('test.txt', 'rb') as f:
    reader = csv.reader(f, delimiter=';')
    next(reader) # skip header
    for name, val in reader:
        d[name] += float(val.lstrip("-"))

rawDescription: CSV in hashtable then calculate sum

description: CSV in hashtable then calculate sum


rawDescription: Getting two separateed integer values

description: Getting two separateed integer values


code:
def map_lists_to_ints(list_of_lists):  # Name this better
    tuples = (tuple(l) for l in list_of_lists)

    seen = {}
    next_int = 0
    for tup in tuples:
        if tup not in seen:
            seen[tup] = next_int
            next_int += 1

        yield seen[tup]

list_of_lists = [[0, 1, 1], [1, 0, 0], [1, 1, 0], [0, 1, 1], [1, 0, 0]]

result = list(map_lists_to_ints(list_of_lists))

print(result)

listified_result = [[x] for x in result]

print(listified_result)

rawDescription: Map arrays to integers in python

description: Map arrays to integers in python


code:
for ((animal, food), count) in counts.items():
    csv_writer.writerow([animal, food, count])

rawDescription: storing .csv data in Python

description: Storing .csv data in Python


code: line.strip().split(' | ')

rawDescription: Only the last row is inserted to my sql database from a text file after splitting it with PYTHON


code: df.pivot_table(index=['Name'], columns=['Car'], aggfunc=len, fill_value=0).reset_index()

rawDescription: count distinct occurrences in pandas

description: Count distinct occurrences in pandas


code:
import logging
import multiprocessing as mp
import time

logger = mp.log_to_stderr(logging.WARNING)

def worker(x):
    try:
        if not terminating.is_set():
            logger.warn("Running worker({x!r})".format(x = x))
            time.sleep(3)
        else:
            logger.warn("got the message... we're terminating!")
    except KeyboardInterrupt:
        logger.warn("terminating is set")
        terminating.set()
    return x

def initializer(terminating_):
    # This places terminating in the global namespace of the worker subprocesses.
    # This allows the worker function to access `terminating` even though it is
    # not passed as an argument to the function.
    global terminating
    terminating = terminating_

def main():
    terminating = mp.Event()
    result = []
    pool = mp.Pool(initializer=initializer, initargs=(terminating, ))
    params = range(12)
    try:
         logger.warn("starting pool runs")
         result = pool.map(worker, params)
         pool.close()
    except KeyboardInterrupt:
        logger.warn("^C pressed")
        pool.terminate()
    finally:
        pool.join()
        logger.warn('done: {r}'.format(r = result))

if __name__ == '__main__':
    main()

rawDescription: multiprocessing.Pool spawning new childern after terminate() on Linux/Python2.7?

description: Multiprocessing.Pool spawning new childern after terminate() on Linux/Python2.7


code:
import random
pickone = random.choice(where0s)
pickone
# if replacing:

pieces[pickone] = 'BA'
''.join(pieces)
# if removing:

del pieces[pickone]
''.join(pieces)

rawDescription: replace or remove one null (python)

description: Replace or remove one null (python)


code:
class Person():
    name = "temp"
    def __init__(self, aname):
        print("A Person is created!")
        self.name=aname
        self.test()

    def test(self):
        print(self.name)

p1 = Person("Tim")

rawDescription: Multiple values for same variable when designing Objects (use of self in Python)


rawDescription: Python convention for variables that won't be used, but are reuturned from a function nonetheless


code: soup.find('p', class_='scroll-down')

rawDescription: How to select everything but a certain html element using beautifulsoup4?

description: Select everything but a certain html element using beautifulsoup4


code: re.match('(Good|Bad|Ugly)', text)

rawDescription: Capture any occurrence of word in a text; RegEx; Python


code:
number_required = y * z
container_holds = x
reqd_containers = (number_required + container_holds - 1) // container_holds

rawDescription: Return minimum X (that can contain Y items) for arbitrary number of items


code:
from tkinter import *
import tkinter.font

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

        self.fonts = list(tkinter.font.families())
        self.fonts.sort()

        self.list = Listbox(self)
        for item in self.fonts:
            self.list.insert(END, item)
        self.list.pack(side=LEFT, expand=YES, fill=BOTH)
        self.list.bind("<<ListboxSelect>>", self.PrintSelected)

        self.scroll = Scrollbar(self)
        self.scroll.pack(side=RIGHT, fill=Y)

        self.scroll.configure(command=self.list.yview)
        self.list.configure(yscrollcommand=self.scroll.set)

    def PrintSelected(self, e):
        print(self.fonts[int(self.list.curselection()[0])])

root = Main()
root.mainloop()

rawDescription: Tkinter - How to assign variable to currently selected item in Listbox?


rawDescription: Replace a substring selectively inside a string


rawDescription: Making a index array from an array in numpy


code:
from itertools import islice

my_list = ["abra", "cada", "bra", "hum", "dee", "dum"]
it = iter(my_list)
for sli in iter(lambda:list(islice(it, 3)), []):
    print("".join(sli))

rawDescription: How to retrieve groups of n items in list

description: Retrieve groups of n items in list


code: var.sort(key=lambda v: v.upper())

rawDescription: python sort upper case and lower case

description: Python sort upper case and lower case


code: x

rawDescription: Substituting only unmasked values in a masked numpy array


code:
from tkinter import *

def doFoo(*args):
    print("Hello, world")

root = Tk()
root.bind("<<Foo>>", doFoo)

# some time later, inject the "<<Foo>>" virtual event at the
# tail of the event queue
root.event_generate("<<Foo>>", when="tail")

rawDescription: Tkinter: invoke event in main loop

description: Tkinter: invoke event in main loop


code:
A=10*np.eye(10) + np.random.rand(100).reshape(10,10)
imshow(A, interpolation="nearest")

rawDescription: Prevent anti-aliasing for imshow in matplotlib


code:
class Doctor(models.Model):
    name = models.CharField()
    primarycity = models.ForeignKey(City, related_name='primary_doc')
    secondarycity = models.ForeignKey(City, related_name='secondary_doc')

rawDescription: Django join tables with two FK fields backwards


code: df["kWh"] = df3["kWh"].reindex(df["DATE"], method="ffill")

rawDescription: How to compare dates from Excel sheets for value filling purposes on python

description: Compare dates from Excel sheets for value filling purposes on python


code:
import urllib

f = open('stackoverflow.png','wb')
f.write(urllib.urlopen('http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=3c6263c3453b').read())
f.close()

rawDescription: web scraping - how to download image into a folder python

description: Web scraping - how to download image into a folder python


code:
import requests

res=requests.get('http://www.hulu.com/return-of-the-one-armed-swordsman')
res.url
# http://www.hulu.com/watch/800769
res.history[0].url
# http://www.hulu.com/return-of-the-one-armed-swordsman

rawDescription: How to get original url from requests

description: Get original url from requests


code: shutil.move(mod_time, 'dest\path')

rawDescription: Find files by creation/modification date then moving to another dir in Python


code:
df = df.pivot_table(index=['fruit', 'year'], columns='col')
df.columns = df.columns.droplevel(0)

rawDescription: Pandas reshaping

description: Pandas reshaping


code: result = multiplications[userinput1, userinput2]

rawDescription: Is my thought process right?

description: Is my thought process right


code:
class A(object):
    if use_metaclass:
        __metaclass__ = B

rawDescription: Using a metaclass depending on configuration


code:
maximi = dict.fromkeys(list1, (None, float('-inf')))
for key, nested in dictionary.items():
    for k in nested.keys() & maximi:  # intersection of keys
        if maximi[k][0] is None or dictionary[maximi[k][0]][k] < nested[k]:
            maximi[k] = (key, nested[k])

maximi
for value in list1:
    print(value, maximi[value][0])

rawDescription: Find Maximum Value in Nested Dictionary and return Key


code:
y = MyYql(env="store://datatables.org/alltableswithkeys")
query = 'SELECT * FROM yahoo.finance.option_contracts WHERE symbol="SPY"'
r = y.execute(query)

rawDescription: YQL - No definition found for Table

description: YQL - No definition found for Table


code: df1 = df.unstack(level=-1)

rawDescription: Python pandas: How do I drop specific levels in a hierarchical index if any column values are NaN?


code:
from itertools import islice

def foo(input_string, num):
    return "".join(islice((char for char in input_string if char.isdigit()),num))

rawDescription: Python print first N integers from a string


code: messages = [(msg.id, msg.string) for msg in cat if msg.id and msg.string]

rawDescription: Storing a text file into SQLite3 database using python


rawDescription: Intersection of two lists including duplicates?


code:
class DescDict(dict):
    def __init__(self, *args, **kwargs):
        self.descs = {}
        dict.__init__(self)

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

    def __setitem__(self, name, tup):
        value, description = tup
        self.descs[name] = description
        dict.__setitem__(self, name, value)

    def get_desc(self, name):
        return self.descs[name]

rawDescription: Returning default members when accessing to objects in python


code:
username = ""
for i in range(0, len(stuff)):
    if stuff[i] == "Users":
        username = stuff[i + 1]

rawDescription: Editing Paths in Python

description: Editing Paths in Python


rawDescription: How do I sort the rows of a 2d numpy array based on indices given by another 2d numpy array

description: Sort the rows of a 2d numpy array based on indices given by another 2d numpy array


code:
readfile = f.readlines()
print(sorted(readfile))

rawDescription: Python 3.4.3 - Sorting statistical list alphabetically


code:
df = DataFrame(dict(A = 'foo', B = 'bar', C = 'bah'),index=range(5))
df.loc[[3,4],'C'] = 'bah2'
df
df.apply(lambda x: x['A'] + x['B'] if x['C'] == 'bah' else x['A'] + x['C'],axis=1)

rawDescription: Using .apply() with more than 1 df column


code:
my_dict= {'C':{'3':'sd','34':'cb'}} # created by loop3
my_big_dict = {}
my_big_dict.update(my_dict)
my_big_dict

rawDescription: Edit Dictionary in python

description: Edit Dictionary in python


code:
from mymodule import do_stuff
do_stuff()

rawDescription: How to import a module as __main__?

description: Import a module as __main__


code: string = ''.join(re.split(r'\b{} '.format(pattern), string))

rawDescription: Removing any pattern (word or regex) defined in a list from a string


code: url if url.startswith('http') else ('http://events.foo.edu%s' % (url,));

rawDescription: Broken images in calendar feed in Plone CMS


code: OrderItem.objects.extra(select={'total': 'unit_price * quantity'})

rawDescription: Getting the total of unit price * quantity


rawDescription: Python - How to transform a list of tuple to a tuple


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

maxwell = stats.maxwell
data = maxwell.rvs(loc=0, scale=5, size=10000)

params = maxwell.fit(data, floc=0)
print(params)
# (0, 4.9808603062591041)

plt.hist(data, bins=20, normed=True)
x = np.linspace(0, 25, 100)
plt.plot(x, maxwell.pdf(x, *params), lw=3)
plt.show()

rawDescription: Fitting Maxwell-Boltzman distribution in Python


code:
ten_min_ago = datetime.datetime.now() - datetime.timedelta(seconds=10 * 60)
rs = Request.select().where(Request.TIME_STAMP > ten_min_ago)

rawDescription: Python peewee, filtering query based on ellapsed time


code:
im = cv.CreateImage( ( 5 , 5 ) , 8 , 1 )
cv.Set( im , 100 )
im_array = np.asarray( im )
im_array
im_array = np.asarray( im[:,:] )
im_array

rawDescription: how to transform a OpenCV cvMat back to ndarray in numpy ？

description: Transform a OpenCV cvMat back to ndarray in numpy ？


rawDescription: How to accumulate unique sum of columns across pandas index

description: Accumulate unique sum of columns across pandas index


code:
import csv
import sqlite3

db = sqlite3.connect(':memory:')

def init_db(cur):
    cur.execute('''CREATE TABLE foo (
        Row INTEGER,
        Name TEXT,
        Year INTEGER,
        Priority INTEGER)''')

def populate_db(cur, csv_fp):
    rdr = csv.reader(csv_fp)
    cur.executemany('''
        INSERT INTO foo (Row, Name, Year, Priority)
        VALUES (?,?,?,?)''', rdr)

cur = db.cursor()
init_db(cur)
populate_db(cur, open('my_csv_input_file.csv'))
db.commit()

rawDescription: Python: Data Structure for Maintaing Tabular Data in Memory?


rawDescription: Enclose a variable in single quotes in Python


code:
def myLog(x, b):
    result = 1
    if b > x:
            result -= 1
            return result
    elif x == b:
            return result
    else:
            x /= b
            return 1 + myLog(x, b)

rawDescription: Computing logarithm

description: Computing logarithm


code: list (s.split(",") for s in l)

rawDescription: keys with multiple values in a dictionary (Python)

description: Keys with multiple values in a dictionary (Python)


code:
bytes = struct.unpack('6B', 't\xe5\x93$\x95\x04')
bytes
bin(sum(x * 256 ** i for i, x in enumerate(bytes)))

rawDescription: python Binary string to binary data

description: Python Binary string to binary data


code:
import re
[sent for sent in a+b if re.search("horse", sent)]

rawDescription: Extract some items from a list to build a new list


code:
def append_loop(items):
  func_items = []
  for i in items:
      if isinstance(i, list):
          func_items.extend(append_loop(i))
      else:
          func_items.append(i)
  return func_items
append_loop([1,2,[3,[4,5]]])

rawDescription: How to append a multiply nested list into and empty one?

description: Append a multiply nested list into and empty one


code: latest = MyObject.latest()

rawDescription: Equivalent of objects.latest() in App Engine


code:
monitor_thread = threading.Thread(target=self._pollBuild())
#                                                       ^^

rawDescription: Threading halts execution of Tkinter program


code:
import lxml.html as lh
import urllib2

url='http://bit.ly/bf1T12'
doc=lh.parse(urllib2.urlopen(url))

blurb=doc.xpath('//td[child::*[text()="Additional  Info"]]/following-sibling::td/text()')

blurb=[text for text in blurb if text != u'\xa0']
print('\n'.join(blurb))

rawDescription: Parsing HTML with Lxml

description: Parsing HTML with Lxml


code: df["Date"]

rawDescription: python pandas extract unique dates from time series

description: Python pandas extract unique dates from time series


rawDescription: Pretty-printing physical quantities with automatic scaling of SI prefixes


rawDescription: Python: create fixed point decimal from two 32-bit ints (one for int portion, one for decimal)


code:
import math
sides = [3, 5, 5, 4]
angles = [90, 95, 75, 100]
area1 = 0.5 * sides[0] * sides[1] * math.sin(math.radians(angles[1]))
area2 = 0.5 * sides[2] * sides[3] * math.sin(math.radians(angles[3]))
area1 + area2

rawDescription: Calculate the area of a quadrilateral

description: Calculate the area of a quadrilateral


code:
ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])

rawDescription: Python matplotlib image + points plot

description: Python matplotlib image + points plot


rawDescription: Python import_array makes it impossible to kill embedded python with ctrl-c


code:
import datetime as DT
import matplotlib.ticker as ticker
xfmt = ticker.FuncFormatter(lambda timestamp, pos: DT.fromtimestamp(x/1000.0).strftime('%Y-%m-%d'))
ax.xaxis.set_major_formatter(xfmt)

rawDescription: Python Use data/time as x-axis?

description: Python Use data/time as x-axis


code:
sum(1 for row in rows
      for i in row if i)

rawDescription: Python Multidimensional Arrays - most efficient way to count number of non-zero entries


code:
from smartfields import fields

def upload_path(instance, filename):
    if " " in instance.album.title:
        instance.album.title.replace(" ", "_")
    return '/'.join([instance.album.title, filename])

class Photo(models.Model):
    title = models.CharField(max_length=50, blank=True)
    album = models.ForeignKey(Album)
    photo = fields.ImageField(upload_to=upload_path, keep_orphans=True)
    upload = models.DateTimeField(auto_now_add=True)

rawDescription: upload_to value changes photo.name attribute

description: Upload_to value changes photo.name attribute


code:
def toDoc(self):
    ...

rawDescription: How do you name your json methods?

description: Name your json methods


code:
files = ["some_long_text_file.txt", "another_file.png", "short.jpg"]

previous = ""
for line in files:
    stdout.write("\r" + " " * len(previous) + "\r" + line)
    previous = line

rawDescription: Python - how to get text to appear on same line when iterating?


code:
def build_make_1():
    return 1

def build_make_2():
    return 2

@pytest.fixture(params=[build_make_1, build_make_2])
def make(request):
    return request.param()

def test_make(make):
    # Run your test
    pass

rawDescription: output of fixture in params in pytest

description: Output of fixture in params in pytest


code:
chars2=[]
for list in example:
    a = []
    chars2.append(a)
    for string in list:
        a.extend(string)

rawDescription: Get the characters from a list of lists

description: Get the characters from a list of lists


code: request.tmpl_context.name = 'Bob'

rawDescription: Equivalent of template context in Pyramid (pylons user)


code:
not 1
not 0

rawDescription: python how to "negate" value : if true return false, if false return true

description: Python how to "negate" value : if true return false, if false return true


code:
Code
# scikit-learn vs. R
# http://stackoverflow.com/questions/28747019/comparison-of-r-statmodels-sklearn-for-a-classification-task-with-logistic-reg

import pandas as pd
import sklearn

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from sklearn import preprocessing

# Data is available here.
Default = pd.read_csv('https://d1pqsl2386xqi9.cloudfront.net/notebooks/Default.csv', index_col = 0)

Default['default'] = Default['default'].map({'No':0, 'Yes':1})
Default['student'] = Default['student'].map({'No':0, 'Yes':1})

I = Default['default'] == 0
print("Number of 'default' values : {0}".format(Default[~I]['balance'].count()))

feats = ['balance', 'income']

Default[feats] = preprocessing.scale(Default[feats])

# C = 1e6 ~ no regularization.
classifier = LogisticRegression(C = 1e6, random_state = 42)

classifier.fit(Default[feats], Default['default'])  #fit classifier on whole base
print("Intercept: {0}".format(classifier.intercept_))
print("Coefficients: {0}".format(classifier.coef_))

y_true = Default['default']
y_pred_cls = classifier.predict_proba(Default[feats])[:,1] > 0.5

confusion = confusion_matrix(y_true, y_pred_cls)
score = float((confusion[0, 0] + confusion[1, 1])) / float((confusion[0, 0] + confusion[1, 1] + confusion[0, 1] + confusion[1, 0]))
precision = float((confusion[1, 1])) / float((confusion[1, 1] + confusion[0, 1]))
recall = float((confusion[1, 1])) / float((confusion[1, 1] + confusion[1, 0]))
print("\nConfusion matrix")
print(confusion)
print('\n{s:{c}<{n}}{num:2.4}'.format(s = 'Score', n = 15, c = '', num = score))
print('{s:{c}<{n}}{num:2.4}'.format(s = 'Precision', n = 15, c = '', num = precision))
print('{s:{c}<{n}}{num:2.4}'.format(s = 'Recall', n = 15, c = '', num = recall))

rawDescription: Comparison of R, statmodels, sklearn for a classification task with logistic regression


code:
for scores in d.itervalues():
    scores.sort(key=lambda x: next(x.itervalues()), reverse=True)

rawDescription: python: sort a nested dictionary

description: Python: sort a nested dictionary


code: import simplejson as json

rawDescription: how can i use a json output in python

description: Use a json output in python


code:
['asaasdfg', 'fdhshs', 'kgk jjjd', 'jdyesgs']
['gdgdg', 'urur', 'irit jhd *', 'djjdj']
['trteyuueu', 'ueue', 'jyuoro', 'ooyoy']

rawDescription: Python module for parsing cusomized config files


rawDescription: Missing and Additional values in 2 list

description: Missing and Additional values in 2 list


code:
dump("Search from (0,0), replace all found with color from (1,1)"
    , change_masked(colors[1][1], colors, find_connected(0, 0, colors, true)));

rawDescription: Finding out same colored block in a 2D matrix


rawDescription: Delete a Variable that has been Pickled

description: Delete a Variable that has been Pickled


code:
kinds = {'water': is_water_dwelling, 'land': is_land_dwelling, 'air': is_flying}
result = {}

for kind, classifier in kinds.iteritems():
  result[kind] = [x for x in animals if classifier(x)]

# If you just want to go over animals once, you can do this instead:
from collections import defaultdict
result = defaultdict(list)

for x in animals:
  for kind, classifier in kinds.iteritems():
    if classifier(x):
      result[kind].append(x)

rawDescription: python: many to many groupings using iterator module

description: Python: many to many groupings using iterator module


rawDescription: How do I create a line-break in Terminal?

description: Create a line-break in Terminal


code:
x = a.set_index('t1').reindex(ind).fillna(0).reset_index()
x
y = b.set_index('t2').reindex(ind).fillna(0).reset_index()
y

rawDescription: Interleaving Pandas Dataframes by Timestamp


code: [mapping[char] for char in l if char in mapping]

rawDescription: List comprehension with two conditions

description: List comprehension with two conditions


code:
file_handle.write("""Hello {0}
Hello1 {0}""".format("world"))

rawDescription: Python equivalent syntax for verbatim string literal in C#


code:
import Tkinter as tk

class MyOtherFrame(object):
    def __init__(self,parent):
        self.root = parent
        self.enable_button = tk.Button(self.root,text="enable",command=self.enable)
        self.enable_button.pack()
        self.disable_button = tk.Button(self.root,text="disable",command=self.disable)
        self.disable_button.pack()
        self.child_frame = tk.Frame(self.root)
        self.child_frame.pack()
        self.child_frame_obj = MyFrame(self.child_frame)

    def enable(self):
        self.child_frame_obj.button.config(state="active")

    def disable(self):
        self.child_frame_obj.button.config(state="disabled")

class MyFrame(object):
    def __init__(self,parent):
        self.root = parent
        self.button = tk.Button(self.root,text="useless button")
        self.button.pack()

def main():
    root = tk.Tk()
    x = MyOtherFrame(root)

    root.mainloop()

if __name__ == "__main__":
    main()

rawDescription: Python Tkinter Sibling windows interacting


code: pymongo_collection_object.remove({'sku': {'$in': ['100-00', '200-00']}}, safe=True)

rawDescription: Removing multiple MongoDB documents in Python


code: date_sequence = pd.date_range(start, end, freq='M').shift(num_of_days, freq=pd.datetools.day)

rawDescription: Python Time Series

description: Python Time Series


code:
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
import datetime
mycollection.insert(post1)
[x for x in mycollection.find()]
mycollection.find_and_modify(query={'author':'Mike'}, update={"$set": {'author': "Mike2"}}, upsert=False, full_response= True)
[ x for x in mycollection.find()]

rawDescription: Pymongo find and modify

description: Pymongo find and modify


code: n = add(n)

rawDescription: n+=1 returns 0 python function cannot change variable

description: N+=1 returns 0 python function cannot change variable


code:
class Parent:

    PATH_PROPERTIES = [ 'parent' ]

    def __init__(self, path):
        self.props = { self.PATH_PROPERTIES[0]: path }

    def getPath(self):
        return self.props[self.PATH_PROPERTIES[0]]

class Child(Parent):

    PATH_PROPERTIES = [ 'child' ]

c = Child('path')
print(c.getPath())

rawDescription: Python class inheritance: dynamic attribute creation


code:
# User-Agent (this is cheating, ok?)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

rawDescription: Python: Save page's dynamic image

description: Python: Save page's dynamic image


code:
# ------------------- #
# == aux functions == #
# ------------------- #

to_clean = string.whitespace + string.punctuation
def clean_word(word):
    res = ''.join(c for c in word if c not in to_clean)
    return res

rawDescription: Python: How to sum up the word count for each person in a dialogue?


code:
class Model(models.Model):
    image_1 = ProcessedImageField([Adjust(contrast=1.2, sharpness=1.1), ResizeToFill(500, 370)], upload_to=generate_image_filename_1, format='JPEG', options={'quality': 90})
    thumbnail_1 = ImageSpec([Adjust(contrast=1.2, sharpness=1.1), ResizeToFill(83, 78)], image_field='image_1', cache_to=generate_cache_filename, format='JPEG', options={'quality': 90})

rawDescription: Django- Imagekit Not Creating Thumbnails


code:
import bisect

GRADES = 'FDCBA'
GRADE_THRESHOLDS = (60, 70, 80, 90)

def grade(score):
    i = bisect.bisect(GRADE_THRESHOLDS, score)
    return GRADES[i]

if __name__ == '__main__':
    a = int(input('1st Quarter: '))
    b = int(input('2nd Quarter: '))
    c = int(input('Midterm: '))
    weighted = a * 0.4 + b * 0.4 + c * 0.2
    final_grade = grade(weighted)
    print('Your semester grade is', final_grade)

rawDescription: How to change an integer value to a letter python

description: Change an integer value to a letter python


code:
if __name__ == "__main__":
    main()
    try:
        import myTests
        myTests.unittest.main(myTests)
    except SystemExit:
        pass

rawDescription: Right way to write Unit-Tests in module?

description: Right way to write Unit-Tests in module


code:
import matplotlib.pyplot as plt

plt.plot(x,y)
plt.axis((2,4,None,None))
plt.show()

rawDescription: select a specific range from a numpy 2d array to plot values

description: Select a specific range from a numpy 2d array to plot values


code:
class YourItem(Item):
    sponsors = Field()

rawDescription: items.py and nested xml tags with scrapy

description: Items.py and nested xml tags with scrapy


rawDescription: Clustering in python(scipy) with space and time variables


code:
class State(models.Model):
    slug = models.SlugField()

class City(models.Model):
    slug = models.SlugField()
    state = models.ForeignKey(State)

rawDescription: Clean, name-based urls with class-based views


code: rdd.toDF(["foo", "bar"])

rawDescription: How do I order fields of my Row objects in Spark (Python)

description: Order fields of my Row objects in Spark (Python)


code: i, r = divmod(a,d)

rawDescription: More efficient method for this calculation?


rawDescription: python django partial match regular expression

description: Python django partial match regular expression


code:
class Bit_writer:
    def __init__(self,file):
        self.file = file
        self.buffer = ""

    def write(self,bits):
        byte_data, self.buffer = bits_to_bytes(self.buffer + bits)
        self.file.write(byte_data)

    def close(self):
        #you may want to handle the padding differently?
        byte_data,_ = bits_to_bytes("{0.buffer:0<8}".format(self))
        self.file.write(byte_data)
        self.file.close()

    def __enter__(self): # This will let you use a 'with' block
        return self
    def __exit__(self,*unused):
        self.file.close()

rawDescription: Writing bits as bits to a file

description: Writing bits as bits to a file


rawDescription: Subtract a column from one pandas dataframe from another


code:
def PopulateList(self):
    if 0:
        # for normal, simple columns, you can add them like this:
        self.list.InsertColumn(0, "Artist")
        self.list.InsertColumn(1, "Title", wx.LIST_FORMAT_RIGHT)
        self.list.InsertColumn(2, "Genre")
    else:
        # but since we want images on the column header we have to do it the hard way:
        info = wx.ListItem()
        info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT
        info.m_image = -1
        info.m_format = 0
        info.m_text = "Artist"
        self.list.InsertColumnInfo(0, info)

        info.m_format = wx.LIST_FORMAT_RIGHT
        info.m_text = "Title"
        self.list.InsertColumnInfo(1, info)

        info.m_format = 0
        info.m_text = "Genre"
        self.list.InsertColumnInfo(2, info)

    items = musicdata.items()
    for key, data in items:
        index = self.list.InsertImageStringItem(sys.maxint, data[0], self.idx1)
        self.list.SetStringItem(index, 1, data[1])
        self.list.SetStringItem(index, 2, data[2])
        self.list.SetItemData(index, key)

rawDescription: Problems with wx.ListCtrl

description: Problems with wx.ListCtrl


code:
from collections import namedtuple
MyStruct = namedtuple("MyStruct", "Var1 Var2 Var3")
value = MyStruct('foo', 'bar', 'baz')
value._asdict()

rawDescription: Get the object name of a specific object from namedtuple


code:
import base64
from Crypto.Cipher import AES
from Crypto import Random

class AESCipher:
    def __init__( self, key ):
        self.key = key

    def encrypt( self, raw ):
        raw = pad(raw)
        iv = Random.new().read( AES.block_size )
        cipher = AES.new( self.key, AES.MODE_CBC, iv )
        return base64.b64encode( iv + cipher.encrypt( raw ) )

    def decrypt( self, enc ):
        enc = base64.b64decode(enc)
        iv = enc[:16]
        cipher = AES.new(self.key, AES.MODE_CBC, iv )
        return unpad(cipher.decrypt( enc[16:] ))

rawDescription: Encrypt & Decrypt using PyCrypto AES 256


code:
def find_nearest_triangle(points, screen_center):
    # Returns the nearest triangle, sorted by distance to center
    dist_to_center = lambda p: distance(p, screen_center)

    # Use the first three points in the list to create the inital triangle
    nearest_triangle = set(points[:3])
    farthest_point = max(nearest_triangle, key=dist_to_center)
    farthest_dist = dist_to_center(farthest_point)
    for point in points[3:]:
        dist = dist_to_center(point)
        if dist < farthest_dist: # Check for a closer point
            farthest_dist = dist
            nearest_triangle.remove(farthest_point)
            nearest_triangle.add(point)
            # Find the new farthest point
            farthest_point = max(nearest_triangle, key=dist_to_center)

    return sorted(list(nearest_triangle), key=dist_to_center)

def get_location(nearest_triangle, screen_center):
    # nearest_triangle should be the same as returned by find_nearest_triangle.
    # This algorithm only returns the 1-3 points that make up the triangle.

    A, B = nearest_triangle[:2]
    side_length = distance(A, B)

    vertex_radius = side_length / 3.0

    if distance(A, screen_center) < vertex_radius:
        return [A], nearest_triangle

    def cross(o, a, b): # Cross product
        return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])

    angle_AB = angle(A, B)
    angle_AC = angle(A, C)
    middle_angle = ((angle_AB + angle_AC) % 360) / 2.0 # For angle in degrees

    p1 = offset_point_by_angle_dist(A, middle_angle, distance)
    p2 = offset_point_by_angle_dist(p1, angle_AB, side_length)

    if cross(p1,screen_center,p2) < 0:
        return [A,B]
    return [A,B,C]

def lookup_location(triangle_lookup, image_point_to_letter, points, screen_center):
    nearest_triangle = find_nearest_triangle(points, screen_center)
    triangle = canonize_triangle_letters([image_point_to_letter[p] for p in nearest_triangle])
    letter_to_position = triangle_lookup[triangle]
    location = get_location(nearest_triangle, screen_center)
    letters = [image_point_to_letter[p] for p in location]
    return [letter_to_position[L] for L in letters]

rawDescription: Find the location of an airplane on a grid given some nodes of the grid


code:
def generate_pratt(max_size):
    """Generate a sorted list of products of powers of 2 and 3 below max_size"""
    # for https://stackoverflow.com/q/25964453/2738262
    products = []
    pow3 = 1  # start with q = 0
    while pow3 <= max_size:
        # At this point, pow3 = 3**q, so set p = 0
        pow2 = pow3
        while pow2 <= max_size:
            # At this point, pow2 = 2**p * 3**q
            products.append(pow2)
            pow2 = pow2 * 2  # this is like adding 1 to p
        # now that p overflowed the maximum size, add 1 to q and start over
        pow3 = pow3 * 3

    # the Pratt sequence is the result of this process up to the given size
    return sorted(products)

print(generate_pratt(12))

rawDescription: How do I implement the Pratt gap sequence? (Python, Shell Sort)

description: Implement the Pratt gap sequence? (Python, Shell Sort)


code:
query = None
for x in values_list:
    if not query:
        query = Q(title__values=x)
    else:
        query &= Q(title__values=x)

qs = Category.objects.filter(query)

rawDescription: Django reverse queryset containing all values in list


code: df.replace({'\n': '<br>'}, regex=True)

rawDescription: Replace all occurrences of a string in a pandas dataframe (Python)


code:
class Child1(Parent):
   def function(self):
       super(Child1, self).function()
       do_something_else_1()

rawDescription: How to enforce (with a warning) that parent functions are called by the children that override them?

description: Enforce (with a warning) that parent functions are called by the children that override them


code:
def weekend(day):
    return day == 'Saturday' or day == 'Sunday'

rawDescription: Return a Boolean instead of a string containing True or False in Python


code: str.maketrans({i:None for i in string.ascii_lowercase if i not in "aeiou"})

rawDescription: Deleting consonants from a string in Python


code:
field3d_mask_1 = np.zeros(field3d.shape, dtype=bool)
field3d_mask_2 = np.zeros(field3d.shape, dtype=bool)

for t in range(nt):
    field3d_mask_1[t,:,:] = field2d > 0.3

field3d_mask_2[:,:,:] = field2d[np.newaxis,:,:] > 0.3

print((field3d_mask_1 == field3d_mask_2).all())

rawDescription: Mask a 3d array with a 2d mask in numpy

description: Mask a 3d array with a 2d mask in numpy


code: image_bgr = image[:, :, ::-1]

rawDescription: Reverse a 3d array in python

description: Reverse a 3d array in python


code:
import pandas as PD
from pandas.util.testing import rands

data = [PD.Series([rands(4) for j in range(6)],
                  index=PD.date_range('1/1/2000', periods=6),
                  name='col'+str(i)) for i in range(4)]

df = PD.concat(data, axis=1, keys=[s.name for s in data])
print(df)

rawDescription: How do I Pass a List of Series to a Pandas DataFrame?


code:
dates1 = {'21/5/2015', '4/4/2015', '15/6/2015', '30/1/2015', '19/3/2015', '25/2/2015', '25/5/2015', '8/2/2015', '6/6/2015', '15/3/2015', '15/1/2015', '30/5/2015'}

from collections import Counter
import re

def dates(data, dates1):
    lines = data.split("\n")
    dict_days = Counter()
    r = re.compile("\d+/\d+/\d+")
    for line in lines:
        match = r.search(line)
        if match:
            dte = match.group()
            if dte in dates1:
                dict_days[dte] += 1
    return dict_days.most_common(5)

rawDescription: Performance - searching a string in a text file - Python


rawDescription: pandas joining multiple dataframes on columns

description: Pandas joining multiple dataframes on columns


code:
from nltk.corpus import treebank
from nltk import ConditionalFreqDist as cfd
from itertools import chain
treebank_tagged_words = list(chain(*list(chain(*[[tree.pos() for tree in treebank.parsed_sents(pf)] for pf in treebank.fileids()]))))
wordcounts = cfd(treebank_tagged_words)
treebank_tagged_words[0]
wordcounts[u'Pierre']
treebank_tagged_words[100]
wordcounts[u'asbestos']

rawDescription: Create Dictionary from Penn Treebank Corpus sample from NLTK?


rawDescription: Python Sort List, Skipping a Character

description: Python Sort List, Skipping a Character


code: ids = [a.get('id') for a in BeautifulSoup(cont).select('a') if a.get('id') is not None]

rawDescription: Capturing ids by xpath in python from url source


code:
_, bp = pd.DataFrame.boxplot(df, return_type='both')

outliers = [flier.get_ydata() for flier in bp["fliers"]]
boxes = [box.get_ydata() for box in bp["boxes"]]
medians = [median.get_ydata() for median in bp["medians"]]
whiskers = [whiskers.get_ydata() for whiskers in bp["whiskers"]]

rawDescription: Getting Data of a boxplot - Pandas

description: Getting Data of a boxplot - Pandas


code:
for key, count in your_counter.iteritems():
    location, lat, long = key
    writer.writerow([location, lat, long, count])

rawDescription: Python Counter results to csv file

description: Python Counter results to csv file


code:
# tty reader

def listen_to_device():
    with open('/dev/ttyXX', 'r') as tty:
        for line in tty:
            create_db_record(line)

if __name__ == '__main__':
    listen_to_device()

rawDescription: Moving Terminal Program from Bash to Python on Linux


code:
timeit.timeit("deque([m(i) for i in ['x', 'y', 'z']], maxlen=0)",
              "from collections import deque; from operator import methodcaller; m = methodcaller('__add__', 'abc')")
timeit.timeit("deque(map(methodcaller('__add__', 'abc'), ['x', 'y', 'z']), maxlen=0)",
              'from collections import deque; from operator import methodcaller')

rawDescription: Python 2 vs 3: Replace list comprehensions with map()?


code: sorted(results,key=itemgetter('year'))

rawDescription: Sorting JSON data by keys value

description: Sorting JSON data by keys value


code: import matplotlib.pyplot as plt

rawDescription: fillplots module in Python

description: Fillplots module in Python


code: assert organism in kegg_con.organismIds

rawDescription: How to access a KEGG entry without specifying the organism using bioservices?

description: Access a KEGG entry without specifying the organism using bioservices


code:
def f2(a, s):
    if s in a["contents"]:
        if "phrase" not in a:
            a["phrase"] = [s]
        else:
            a["phrase"].append(s)
    for b in a["descendent"]:
        f(b, s)

rawDescription: How to look through a phrase in a dictionary?

description: Look through a phrase in a dictionary


code:
alist = np.arange(10)
foo('test.mat', alist)

foo('test.mat', np.arange(10))

rawDescription: Can someone explain mdict in python (scipy.io), for example in scipy.io.savemat()?


code:
import re
d = {u'spam': u'spam, ham, spam and eggs', u'eggs': u'saussages'}
p = re.compile("|".join(re.escape(k) for k in d))
def repl(m):
    return d[m.group(0)]
p.sub(repl, u"spam, vikings, eggs and vikings")

rawDescription: Optimizing find and replace over large files in Python


code:
while True:
    nxt = raw_input("> ")
    try:
        nxt = int(nxt)
        break # break if we got valid input that can be cat
    except ValueError: # else we get here and print our message and go back to start again
        print("Man,you need to learn how to print a number!")
        continue
if nxt < 50: # if we get here we got valid input from the potentially greedy  b!*!*!*d!"
   print("Nice, you're not greedy, you win!")
   return
dead("You greedy b!*!*!*d!") # we don't need an else as if previous statement in True we will have exited the function

rawDescription: About if x is int

description: About if x is int


code:
def get_text_blocks(filename):
    import itertools
    with open(filename,'r') as f:
        groups = itertools.groupby(f, lambda line:line.startswith('-- -'))
        return [''.join(lines) for is_separator, lines in groups if not is_separator]

rawDescription: How to check for EOF in Python?

description: Check for EOF in Python


rawDescription: Pandas: Reading Excel with merged cells

description: Pandas: Reading Excel with merged cells


code: np.einsum('ij, jkl', M, a)

rawDescription: Iterate over vectors in a multidimensional numpy array


rawDescription: GtkAboutDialog Close Button Bug

description: GtkAboutDialog Close Button Bug


code:
from datetime import datetime

fmt = '%Y-%m-%d %H:%M:%S'
tstamp1 = datetime.strptime('2016-04-06 21:26:27', fmt)
tstamp2 = datetime.strptime('2016-04-07 09:06:02', fmt)

if tstamp1 > tstamp2:
    td = tstamp1 - tstamp2
else:
    td = tstamp2 - tstamp1
td_mins = int(round(td.total_seconds() / 60))

print('The difference is approx. %s minutes' % td_mins)

rawDescription: Python finding difference between two time stamps in minutes


rawDescription: Check if values exist

description: Check if values exist


code: journalist = Journalist(contact_ptr = contact)

rawDescription: Django model inheritance problem. How to solve?


rawDescription: Get all "grand"-Children of a given Model


code:
import numpy as np
day1 = np.random.randint(255, size=(1, 81, 141))

rawDescription: How to merge multiple arrays in python?

description: Merge multiple arrays in python


rawDescription: What is the best approach to matching/joining elements in two non-identical unsorted python lists of different lengths?


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button

class DummyPlot(object):
    def __init__(self):
        self.imsize = (10, 10)
        self.fig, self.ax = plt.subplots()

        self.ax.axis([-0.5, self.imsize[1] - 0.5,
                      self.imsize[0] - 0.5, -0.5])
        self.ax.set_aspect(1.0)
        self.ax.autoscale(False)

        buttonax = self.fig.add_axes([0.45, 0.9, 0.1, 0.075])
        self.button = Button(buttonax, 'Update')
        self.button.on_clicked(self.update)

    def update(self, event):
        self.ax.imshow(np.random.random(self.imsize))
        self.fig.canvas.draw()

    def show(self):
        plt.show()

p = DummyPlot()
p.show()

rawDescription: Preserve zoom settings in interactive navigation of matplotlib figure


code:
import numpy as np
from itertools import groupby,izip_longest

def f1(fname):
    with open(fname) as f:
        return np.matrix(list(izip_longest(
               *(map(lambda x: float(x[1]),v)
               for k,v in groupby(map(str.split,f),
               key=lambda x: len(x) == 2) if k),
               fillvalue=np.nan)))
d1('testfile')

rawDescription: How can I efficiently load this kind of ASCII files with python?

description: Efficiently load this kind of ASCII files with python


code: return query.first()

rawDescription: SQLAlchemy: One-Way Relationship, Correlated Subquery


rawDescription: Naming dimensions in python?

description: Naming dimensions in python


code:
from future_builtins import map  # Only on Python 2

from collections import Counter
from itertools import chain

def countInFile(filename):
    with open(filename) as f:
        return Counter(chain.from_iterable(map(str.split, f)))

rawDescription: Efficiently count word frequencies in python


code:
minus1 = functools.partial(minus, b=1)
minus1(4)

rawDescription: Python callback function placeholders?

description: Python callback function placeholders


code: [handler.regex.pattern for handler in self.application.handlers[0][1]]

rawDescription: Is there a way to print the configured route handlers on a tornado web server internally?


rawDescription: PySide. Extracting DOM HTML. AccessNetworkmanager


code:
t = df.values.tolist()
t

rawDescription: Python Pandas Dataframe to Nested Tuples


code:
def kijiji_spider(max_pages):
    page = 1
    collected_urls = [] # store all URLs on each "run"
    while page <= max_pages:
        url = "http://www.kijiji.ca/b-cars-trucks/alberta/convertible__coupe__hatchback__other+body+type__sedan__wagon/page-" + str(page) + "/c174l9003a138?price=__5000"
        sourcecode = requests.get(url)
        plain_text = sourcecode.text
        soup = BeautifulSoup(plain_text)
        links = [i.get('href') for i in soup.find_all('a', {'class': 'title'})]
        titles = [i.string.strip() for i in soup.find_all('a', {'class': 'title'})]
        prices = [i.string.strip() for i in soup.find_all("td", {"class": "price"})]
        results = zip(links, titles, prices)
        collected_urls.append(results)
        page += 1

data = kijiji_spider(5)
for results in data:
    for link, title, price in results:
        print('http://www.kijiji.ca{} | {} | {}'.format(link, title, price))

rawDescription: Can't figure out why list index out of range


code: dictionary[newkey] = newvalue

rawDescription: How to store a list as a dictionary - python

description: Store a list as a dictionary - python


code:
from pyspark.sql import functions as f
from pyspark.sql.window import Window

w = Window().partitionBy("individual").orderBy("datetime")

rawDescription: PySpark - Combining Session Data without Explicit Session Key / Iterating over All Rows


code:
def w_sum(a, b, w=1):
    """Calculate the pair sum of bases a and b with weighting w."""
    if a == b:
        return 3 * w
    elif a == "_" or b == "_":
        return -1 * w
    else:
        return 2 * w

rawDescription: consensus score and WSP score in python

description: Consensus score and WSP score in python


code:
if 'test' in sys.argv:
    DATABASES['default'] = {'ENGINE': 'django.db.backends.sqlite3'}

rawDescription: How to run Django's test database only in memory?

description: Run Django's test database only in memory


rawDescription: An unusual Python syntax element frequently used in Matplotlib


code:
data = {}
for i in list_of_stuff:
  data[i["title"]] = i["value"]

rawDescription: Using Python's csv.dictreader to search for specific key to then print its value


code:
[['Bacteria 3', 'Aquificae 2', 'Persephonella 1'],
 ['-', '-', 'Thermovibrio 1'],
 ['-', 'Firmicutes 1', 'Bacillus 1']]

rawDescription: python nested list: replace repeted items in nested list while retaining first occurrence

description: Python nested list: replace repeted items in nested list while retaining first occurrence


code:
with open('file1.txt','r+') as f1 ,open('file2.txt','r+') as f2:
    file1=set(x.strip() for x in f1 if x.strip())
    file2=set(x.strip() for x in f2 if x.strip())
    newfile=file1.symmetric_difference(file2) #symmetric difference removes those values which are present in both sets, and returns a new set.
    f2.truncate(0) #truncate the file to 0 bytes
    f1.truncate(0)
    f2.seek(0) # to push the cursor back to the starting pointing in the file.
    f1.seek(0)
    for x in newfile:
        f1.write(x+'\n')
        f2.write(x+'\n')

rawDescription: how to delete words which are same in two files?

description: Delete words which are same in two files


rawDescription: Python Sympy Arbitrary Approximation to Arbitrary Sympy Expression?


code:
windowPidsAndTitle = []
win32gui.EnumWindows(lambda hwnd, resultList: resultList.append((win32gui.GetWindowThreadProcessId(hwnd),win32gui.GetWindowText(hwnd))), windowPidsAndTitle)

rawDescription: Get name of active Excel workbook from Python


code:
from scrapy.http import FormRequest
from scrapy.item import Item, Field
from scrapy.selector import HtmlXPathSelector

from scrapy.spider import BaseSpider

class AcrisItem(Item):
    borough = Field()
    block = Field()
    doc_type_name = Field()

class AcrisSpider(BaseSpider):
    name = "acris"
    allowed_domains = ["a836-acris.nyc.gov"]
    start_urls = ['http://a836-acris.nyc.gov/DS/DocumentSearch/DocumentType']

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        document_classes = hxs.select('//select[@name="combox_doc_doctype"]/option')

        form_token = hxs.select('//input[@name="__RequestVerificationToken"]/@value').extract()[0]
        for document_class in document_classes:
            if document_class:
                doc_type = document_class.select('.//@value').extract()[0]
                doc_type_name = document_class.select('.//text()').extract()[0]
                formdata = {'__RequestVerificationToken': form_token,
                            'hid_selectdate': '7',
                            'hid_doctype': doc_type,
                            'hid_doctype_name': doc_type_name,
                            'hid_max_rows': '10',
                            'hid_ISIntranet': 'N',
                            'hid_SearchType': 'DOCTYPE',
                            'hid_page': '1',
                            'hid_borough': '0',
                            'hid_borough_name': 'ALL BOROUGHS',
                            'hid_ReqID': '',
                            'hid_sort': '',
                            'hid_datefromm': '',
                            'hid_datefromd': '',
                            'hid_datefromy': '',
                            'hid_datetom': '',
                            'hid_datetod': '',
                            'hid_datetoy': '', }
                yield FormRequest(url="http://a836-acris.nyc.gov/DS/DocumentSearch/DocumentTypeResult",
                                  method="POST",
                                  formdata=formdata,
                                  callback=self.parse_page,
                                  meta={'doc_type_name': doc_type_name})

    def parse_page(self, response):
        hxs = HtmlXPathSelector(response)

        rows = hxs.select('//form[@name="DATA"]/table/tbody/tr[2]/td/table/tr')
        for row in rows:
            item = AcrisItem()
            borough = row.select('.//td[2]/div/font/text()').extract()
            block = row.select('.//td[3]/div/font/text()').extract()

            if borough and block:
                item['borough'] = borough[0]
                item['block'] = block[0]
                item['doc_type_name'] = response.meta['doc_type_name']

                yield item

rawDescription: Python data scraping with Scrapy

description: Python data scraping with Scrapy


code:
if newCoord == [n, n]:
    foundRoute = foundRoute + 1
    coordList = [[1,1]]
    i,j = (1,1)
    break

rawDescription: Python Monte Carlo Simulation Loop

description: Python Monte Carlo Simulation Loop


code:
# ax.scatter(angles, np.ones(100)*1, marker='_', s=20)
ax.bar(angles, np.full(100, 0.9), width=0.1, bottom=0.0, color='r', linewidth=0)

rawDescription: How to plot points on a clock

description: Plot points on a clock


code: lst[:] = ['lst{}'.format(item) for item in lst]

rawDescription: Python, Appending string on each item on the list


code:
timeit.timeit('responses = list(r)\nwhile responses and isnan(responses[-1]): responses.pop()', 'from math import isnan; nan = float("nan"); r = [1.0, nan, 9.0, nan, nan, nan, nan, nan, nan, nan, nan]')
timeit.timeit('responses = list(r)\nresponses = responses[:3]', 'from math import isnan; nan = float("nan"); r = [1.0, nan, 9.0, nan, nan, nan, nan, nan, nan, nan, nan]')

rawDescription: Python: remove repeated values only if at end of list


code:
import re
any(re.search(r"\b{0}\b".format(x),strs) for x in lis)
strs="foo bar"
any(re.search(r"\b{0}\b".format(x),strs) for x in lis)

rawDescription: Multi-condition regex in Python

description: Multi-condition regex in Python


code: res = lambda x: all(test(v) for v in x)

rawDescription: How to make my code more Pythonic?

description: Make my code more Pythonic


code:
class TestClass(object):
    def timed_method(self, return_queue):
        do_other_stuff()
        return_queue.put(True)
        return

rawDescription: Limit function execution in Python

description: Limit function execution in Python


code: d = dict(map(str.strip, a.split('=', 1)) for a in l)

rawDescription: Remove repeated elements from list and HTML Tag


rawDescription: Copy and Write XML Node in Python

description: Copy and Write XML Node in Python


code:
keys = ('a', 'b', 'c')
value = 'bar'
for c in reversed(keys):
  value = {c: value}

value

rawDescription: Create Nested Python Dictionary From Tuple of Keys


code:
zip([sum(t) for t in zip( \
               *[(1,0,0) if p.type==PRODUCT_UNISEX \
                 else (0,1,0) if p.type==PRODUCT_MENS \
                 else (0,0,1) for p in products] \
                        ) \
    ], \
    ['Unisex','Mens','Womans'])

rawDescription: Sort list elements belonging to enumerable object


code:
shv="abcdefgh"
[shv[i:i+3] for i in range(0, len(shv), 3)]
[shv[i:i+3] for i in range(0, len(shv)-1, 3)]
[shv[i:i+3] for i in range(0, len(shv)-2, 3)]

rawDescription: Return a list of string letters grouped by two


rawDescription: How to select multiple non-contigous columns from a list into another dataframe in python

description: Select multiple non-contigous columns from a list into another dataframe in python


code:
x = 6
next((i for i, (a, b) in enumerate(zip(list1, list2)) if a<=x<=b), None)

rawDescription: python iterating two lists in a tuple and comparing a integer between tem

description: Python iterating two lists in a tuple and comparing a integer between tem


code:
def get_diff (list_1, list_2):
    d = []
    for item in list_1:
        if item not in list_2:
            d.append(item)
    return d

difference = get_diff(text_1, text_2) + get_diff(text_2, text_1)

rawDescription: Delta words between two TXT files

description: Delta words between two TXT files


code:
def timing_function(some_function):
    """Outputs the time a function takes to execute."""
    def wrapper(*args, **kw):
        t1 = time.time()
        some_function(*args, **kw)
        time.sleep(1)
        t2 = time.time()
        return "Time it took to run the function " + some_function.__name__ + " is " + str((t2-t1)) + "\n"
    return wrapper

rawDescription: Using decorators with and without arguments simultaneously


code:
cmd = 'bash run.sh {} {}'.format(var1, var2)
call(shlex.split(cmd))

rawDescription: Pass a variable from python to shell script


rawDescription: Numbers ending with j

description: Numbers ending with j


code:
nums = [[int(num) for num in substring.split(',')] for substring in s.split()]
for row in nums:
    row[1] = 0

rawDescription: Is there an elegant and concise syntax to do this in Python?


code:
class MyApp(Flask):
    def static_dispatchers(self):
        yield super(MyApp, self).send_static_file
        for blueprint in self.blueprints.values():
            yield blueprint.send_static_file

    def send_static_file(self, filename):
        last_exception = None
        for static_dispatcher in self.static_dispatchers():
            try:
                return static_dispatcher(filename)
            except NotFound as e:
                last_exception = e
        raise last_exception

rawDescription: Serve static files from blueprints without url prefix


rawDescription: Efficient way of appending / extracting list elements


rawDescription: Matplotlib changing axis ticks

description: Matplotlib changing axis ticks


code:
import os.path

img_dir = "C:/Users/Pygame draw/"

image_files = [
    'black.png',
    'white.png',
    'blue.png',
]

py_images = {}

for image_file in image_files:
    color_name, ext = os.path.splitext(image_file)

    py_image = pygame.image.load(
        os.path.join(img_dir, image_file)
    )

    py_images[color_name] = py_image

points = {
    'blue' : (63, 0),
    'white' : (169, 0),
    'black' : (0, 0)
}

for color_name, point in points.items():
    py_image = py_images[color_name]
    screen.blit(py_image, point)

rawDescription: Pygame project i'm stuck, please reply

description: Pygame project i'm stuck, please reply


code: lines = list(sys.stdin)

rawDescription: How to show EOF in Python? / how to identify lines?

description: Show EOF in Python? / how to identify lines


code: np.max([a, b], axis=0)

rawDescription: Star trails image stacking in python

description: Star trails image stacking in python


code:
from fnmatch import fnmatch
[i for i in urls if fnmatch(i,'*.html')]

rawDescription: Using Regular Expressions to extract specific urls in python


code:
def partition3(max_range, max_sum, out = None, n_part = None):
    if out is None:
        max_range = np.asarray(max_range, dtype = int).ravel()
        n_part = number_of_partitions(max_range, max_sum)
        out = np.zeros(shape = (n_part[0], max_range.size), dtype = int)

    if(max_range.size == 1):
        out[:] = np.arange(min(max_range[0],max_sum) + 1, dtype = int).reshape(-1,1)
        return out

    P = partition3(max_range[1:], max_sum, out=out[:n_part[1],1:], n_part = n_part[1:])
    # P is now a useful reference

    S = np.minimum(max_sum - P.sum(axis = 1), max_range[0])
    offset, sz  = 0, S.size
    out[:sz,0] = 0
    for i in range(1, max_range[0]+1):
        ind, = np.nonzero(S)
        offset, sz = offset + sz, ind.size
        out[offset:offset+sz, 0] = i
        out[offset:offset+sz, 1:] = P[ind]
        S[ind] -= 1
    return out

rawDescription: Generating a numpy array with all combinations of numbers that sum to less than a given number


code:
x = bytes([67, 128])
print(''.join(r'\x'+hex(letter)[2:] for letter in x))

rawDescription: Show hex value for all bytes, even when ASCII characters are present


code:
version = '*/2.4.7'
prefix, _, sprint = version.rpartition('.')
'{}.{}'.format(prefix, int(sprint) + 1)
prefix, sprint = version.rsplit('.', 1)  # split just once
'{}.{}'.format(prefix, int(sprint) + 1)

rawDescription: increment a variable like */2.4.7 via python

description: Increment a variable like */2.4.7 via python


rawDescription: Transposing arrays in an array

description: Transposing arrays in an array


code: fourier_transform(ssexp, x, k)

rawDescription: Sympy Fourier Transform of exponential decay


code:
from collections import Counter

result = Counter()
for name, count in a_list:
    result[name] += count

rawDescription: Adding and combining values with dictionary comprehensions?


rawDescription: make only left subplots and bottom subplots (in MxN panels) contain x and y axis labels

description: Make only left subplots and bottom subplots (in MxN panels) contain x and y axis labels


code: E_initial[x_contact,y_contact] += 1

rawDescription: How do I use Python multiprocessing to get rid of nested while loops

description: Use Python multiprocessing to get rid of nested while loops


rawDescription: Python Build tuples from a dictionary with key and multiple values


code:
import csv
open('test.csv','w').write('1,one\n2,two\n3,three\n')
list(csv.reader(open('test.csv')))

rawDescription: python program for accessing values from csv files and storing it into a database using wamp

description: Python program for accessing values from csv files and storing it into a database using wamp


rawDescription: Reduce dimensionality in pandas.Panel

description: Reduce dimensionality in pandas.Panel


rawDescription: Invalid Syntax in Python for RPG game

description: Invalid Syntax in Python for RPG game


code: myval = myval if myval is not None else defaultval

rawDescription: Most idiomatic way to provide default value in python?


code:
def foo(bar: str, baz: list, spam: str = 'eggs', *, monty: str = 'python', **kw) -> None: pass

import inspect
inspect.getfullargspec(foo)

rawDescription: How to check which arguments a function/method takes?

description: Check which arguments a function/method takes


rawDescription: numpy selecting every other n entries

description: Numpy selecting every other n entries


code:
#------ file model.py -------------

@gen.coroutine
def push_event_to_user(user_id, event):

    ## Ajout de la demande dans les events du demandé:
    result = yield motor.Op(db.users.update,
                            {'_id': ObjectId(user_id)},
                            {'$push': {'evts': event}}
                           )
    raise gen.Return(result)

rawDescription: How to move db request (which uses yield) in an other function?

description: Move db request (which uses yield) in an other function


rawDescription: Sorting file contents into a list in Python


rawDescription: Split a list of tuples into sub-lists of the same tuple field


rawDescription: Sending hand-crafted BPDU (Spanning Tree Protocol packet) with Python


code:
def edit_image():
    """
        Edit a profile image, creates a thumb...
    """
    thumb=""
    profile = db.profile(request.vars.profile_id)
    image = db(db.image.id==profile.image).select().first()
    if image:
        form = SQLFORM(db.image, image, deletable=True, showid=False)
        thumb = image.thumb
    else:
        form = SQLFORM(db.image)
    if form.accepts(request.vars, session):
        response.flash = T('form accepted')
        #resize the original image to a better size and create a thumbnail
        __makeThumbnail(db.image,form.vars.id,(800,800),(260,260))
        redirect(URL('images'))
    elif form.errors:
        response.flash = T('form has errors')
    return dict(form=form,thumb=thumb)

rawDescription: How to change the format of an Image upload field in Web2py?

description: Change the format of an Image upload field in Web2py


code:
for r in range(height*yscale):
    for c in range(width*xscale):
        pixel = oldImage.getPixel(r // yscale, c // xscale)
        newImage.setPixel(r, c, pixel)

rawDescription: Rescale an Image using Python3.2

description: Rescale an Image using Python3.2


rawDescription: How can I print 4 bytes as an integer

description: Print 4 bytes as an integer


code:
def print_map(self):
    for y in range(0, self.height):
        # print the yth row of rooms
        for x in range(0, self.width):
            if self.x == x and self.y == y:
                sys.stdout.write("[u]")  # this is the player's room
            else:
                sys.stdout.write("[ ]")  # empty room
            # now see whether there's a path to the next room
            if ((x, y), (x + 1, y)) in self.paths:
                sys.stdout.write("-")
            else:
                sys.stdout.write(" ")
        # now that we've written the rooms, draw paths to next row
        print  # newline
        for x in range(0, self.width):
            sys.stdout.write(" ")  # spaces for above room
            if ((x, y), (x, y + 1)) in self.paths:
                sys.stdout.write("|  ")
            else:
                sys.stdout.write("   ")
        print

rawDescription: Python Drawing ASCII Map

description: Python Drawing ASCII Map


code: out = [l for l in out if l]

rawDescription: Pythonic way to split a list after elements for which a given predicate is true


code:
import asyncio
import sse

loop = asyncio.get_event_loop()
sse_host, sse_port = '0.0.0.0', 8888

class Telnet(asyncio.Protocol):
    def connection_made(self, transport):
        print("Connection received!");
        self.transport = transport

    def data_received(self, data):
        SSEHandler.broadcast(data.decode('ascii'))

    def connection_lost(self, esc):
        print("Connection lost!")
        SSEHandler.abort()
        telnet_server.close()

class SSEHandler(sse.Handler):
    _instances = {}
    @classmethod
    def broadcast(cls, message):
        for instance, future in cls._instances.items():
            instance.send(message)

    @classmethod
    def abort(cls):
        for instance, future in cls._instances.items():
            future.set_result(None)
        cls._instances = {}

    @asyncio.coroutine
    def handle_request(self):
        self.send('Working')
        my_future = asyncio.Future()
        SSEHandler._instances[self] = my_future
        yield from my_future

sse_server = sse.serve(SSEHandler, sse_host, sse_port)
telnet_server = loop.run_until_complete(loop.create_server(Telnet, '0.0.0.0', 7777))
loop.run_until_complete(sse_server)
loop.run_until_complete(telnet_server.wait_closed())

rawDescription: Python - Communicate between asyncio protocol/servers


code:
for i in countries:
    (xcor1, ycor1) = starcoords[i][1]
    c.create_text(xcor1, ycor1,fill='grey', text=i)
    #...assuming `i` is a string containing the name of the country

rawDescription: Tkinter in python- why can I not create text?


code:
from scipy.io import wavfile

x = band_limited_noise(200, 2000, 44100, 44100)
x = np.int16(x * (2**15 - 1))
wavfile.write("test.wav", 44100, x)

rawDescription: How to generate noise in frequency range with numpy?

description: Generate noise in frequency range with numpy


code:
result = {}
for (key, value) in the_list:
    result.setdefault(key, []).append(value)

rawDescription: converting a list of lists ina dictionary where inner lists are key-value pairs

description: Converting a list of lists ina dictionary where inner lists are key-value pairs


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

def main():
    textFileName = 'C:\\temp\\001.txt'
    total = 0
    for line in open(textFileName):
        line = str.strip(line)
        for char in line:
            if char == ' ':
                total += 1
        total += 1
    print(total, "words")
main()

rawDescription: How do I count the words in a string using only loops and string.strip()?

description: Count the words in a string using only loops and string.strip()


code: ydata = y + 0.2 * np.random.normal(size=len(xdata))

rawDescription: Curve fitting in Python using scipy

description: Curve fitting in Python using scipy


code: dataset.loc[dataset['Postcode'].str.startswith("WC1"), 'Postcode'] = 'center'

rawDescription: How to find strings in pandas

description: Find strings in pandas


code:
def is_corner(lst, i, j):
    return (0 < i < len(lst) and 0 < j < len(lst[0]) and
           (lst[i-1][j] == "bar" or lst[i+1][j] == "bar") and
           (lst[i][j-1] == "bar" or lst[i][j+1] == "bar"))

rawDescription: How to correctly access elements of a nested list in python

description: Correctly access elements of a nested list in python


code:
def print_dict(_dict, indent="", depth=0, max_depth=-1):
    if max_depth > 0 and depth > max_depth:
        return

rawDescription: python ordereddict: access certain depth within dict

description: Python ordereddict: access certain depth within dict


code:
def userDecode(s):
    status = 0
    lst = []                       # result as list of bytes as ints
    xx = None                      # variable for one byte escape conversion
    for c in s:                    # unicode character
        print(status, ' c ==', c)  ## just for debugging
        if status == 0:
            if c == '\\':
                status = 1         # escape sequence for a byte starts
            else:
                lst.append(ord(c)) # convert to integer

        elif status == 1:          # x expected
            assert(c == 'x')
            status = 2

        elif status == 2:          # first nibble expected
            xx = c
            status = 3

        elif status == 3:          # second nibble expected
            xx += c
            lst.append(int(xx, 16)) # this is a hex representation of int
            status = 0

    # Construct the bytes from the ordinal values in the list, and decode
    # it as UTF-8 string.
    return bytes(lst).decode('utf-8')

if __name__ == '__main__':

    s = userDecode('\\xd0\\xb1whatever')
    print(ascii(s))    # cannot be displayed on console that does not support unicode

    with open('output.txt', 'w', encoding='utf-8') as f:
        f.write(s)

rawDescription: Decoding bytes as unicode string

description: Decoding bytes as unicode string


rawDescription: Curious Python behaviour when approaching x.0


code:
knownfiles = [
    "/etc/mime.types",
    "/etc/httpd/mime.types",                    # Mac OS X
    "/etc/httpd/conf/mime.types",               # Apache
    "/etc/apache/mime.types",                   # Apache 1
    "/etc/apache2/mime.types",                  # Apache 2
    "/usr/local/etc/httpd/conf/mime.types",
    "/usr/local/lib/netscape/mime.types",
    "/usr/local/etc/httpd/conf/mime.types",     # Apache 1.2
    "/usr/local/etc/mime.types",                # Apache 1.3
    ]

rawDescription: How to set the content type header in response for a particular file type in Pyramid web framework

description: Set the content type header in response for a particular file type in Pyramid web framework


code:
def _sql_to_data(sql, values):
    ...
    conn.execute(sql, values)

rawDescription: Python, SQLAlchemy pass parameters in connection.execute


code:
import pandas as pd

df0 = pd.ExcelFile("id_data1.xls").parse("Sheet1")
df1 = pd.ExcelFile("id_data2.xls").parse("Sheet1")
df0 = df0.set_index("ID")
df1 = df1.set_index("ID")
df0
df1

rawDescription: Compare records of 1 column from 2 different Excel files, report what is missing or added


code:
class Foo(object):
    def __init__(self):
        self.bar = 3
foo = Foo()
eval('a', globals(), foo.__dict__)

rawDescription: How do you do a python 'eval' only within an object context?

description: Do a python 'eval' only within an object context


code:
s = "AbCd"
result = [i for i, a in enumerate(s) if a.islower()]

rawDescription: Detect index of lower case letters

description: Detect index of lower case letters


code:
meshgrid(*[np.arange(j,k) for j,k in zip(temp[i,:],shape)],indexing='ij')
np.mgrid[[slice(j,k) for j,k in zip(temp[i,:],shape)]]

meshgrid(*[np.arange(j,k) for j,k in zip(temp[i,:],shape)],sparse=True,indexing='ij')
np.ogrid[[slice(j,k) for j,k in zip(temp[i,:],shape)]]

rawDescription: python: making array index generation more efficient/elegant

description: Python: making array index generation more efficient/elegant


code:
from coco import bunny
from coco.bungy import carrot
from meta import teta
from rocket import spaceship as sp
import bingo
import com.stackoverflow
import motorbike as car
import module1, module2

s="a random variable"

def func():
    """And a function"""

rawDescription: Python easy way to read all import statements from py module


code:
def test_authenticate_success(self):
    self.mocked_auth_user.return_value = (1, "abc", "paris", "admin")

    def _doTest(auth_result):
        attempted_auth_result = {
            "secret": "abc",
            "role": "admin",
            "authid": "1",
            "salt": "paris",
            "iterations": 1000,
            "keylen": 32
        }

        self.assertEqual(auth_result, attempted_auth_result)
        self.mocked_auth_user.assert_called_with(self.api.database, "raito")

    return self.api.authenticate("test", "raito", {}).addCallback(_doTest)

rawDescription: How to do unit test on Autobahn applications using Twisted Trial?

description: Do unit test on Autobahn applications using Twisted Trial


code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (C) 2013-2014  Diego Torres Milano
Created on 2015-08-19 by Culebra v10.7.1
                      __    __    __    __
                     /  \  /  \  /  \  /  \
____________________/  __\/  __\/  __\/  __\_____________________________
___________________/  /__/  /__/  /__/  /________________________________
                   | / \   / \   / \   / \   \___
                   |/   \_/   \_/   \_/   \    o \
                                           \_____/--<
@author: Diego Torres Milano
@author: Jennifer E. Swofford (ascii art snake)
'''

import re
import sys
import os

try:
    sys.path.insert(0, os.path.join(os.environ['ANDROID_VIEW_CLIENT_HOME'], 'src'))
except:
    pass

from com.dtmilano.android.viewclient import ViewClient

TAG = 'CULEBRA'

_s = 5
_v = '--verbose' in sys.argv

kwargs1 = {'ignoreversioncheck': False, 'verbose': False, 'ignoresecuredevice': False}
device, serialno = ViewClient.connectToDeviceOrExit(**kwargs1)
kwargs2 = {'forceviewserveruse': False, 'useuiautomatorhelper': False, 'ignoreuiautomatorkilled': True, 'autodump': False, 'startviewserver': True, 'compresseddump': True}
vc = ViewClient(device, serialno, **kwargs2)
#vc.dump(window='-1') # FIXME: seems not needed

vc.dump(window=-1)
vc.findViewWithTextOrRaise("u'Name'").type(u"My Contact")

rawDescription: Setting text in UIAutomator

description: Setting text in UIAutomator


code:
['activebackground', 'activeborderwidth', 'activeforeground', 'background', 'bd', 'bg',
 'borderwidth', 'cursor', 'disabledforeground', 'fg', 'font', 'foreground', 'postcommand',
 'relief', 'selectcolor', 'takefocus', 'tearoff', 'tearoffcommand', 'title', 'type']

rawDescription: Changing the colour of the tk.optionmenu widget


code:
import other_module

x, y = other_module.some_function(param='z')

rawDescription: Python subprocess.Popen : sys.stdout vs .txt file vs Cpickle.dump


code: array([array([0, 3]), array([3, 0]), array([6, 7, 8])], dtype=object)

rawDescription: Access 1D array with array of lists or arrays


code:
class Friend(Base):
    __tablename__ = 'friend'

    user_id = Column(Integer, ForeignKey(User.id), primary_key=True)
    friend_id = Column(Integer, ForeignKey(User.id), primary_key=True)
    request_status = Column(Boolean)

    user = relationship('User', foreign_keys='Friend.user_id')
    friend = relationship('User', foreign_keys='Friend.friend_id')

rawDescription: sqlalchemy foreign key relationship attributes

description: Sqlalchemy foreign key relationship attributes


code:
codepoint.sub(replace, r'\u201cquotes\u201d').encode('utf8')
codepoint.sub(replace, r'"foo\r\nbar"').encode('utf8')

rawDescription: Unescape unicode-escapes, but not carriage returns and line feeds, in Python


code:
tmp = obj.attrib
tmp(...)

rawDescription: Python "callable" attribute (pseudo-property)


code:
arr1 = arr1.astype(float)
arr1[arr1 != 0.0] = numpy.NaN
arr1[arr1 == 0.0] = 1.0

rawDescription: Compare two numpy arrays and insert nans


code:
data = [1, 2, 3]
output = (lambda x=data[2] : x +x)()

rawDescription: binding local variables in python

description: Binding local variables in python


code:
from scipy.interpolate import SmoothBivariateSpline

# play around with the s= parameter to control the degree of smoothing
spl = SmoothBivariateSpline(x, y, z)

# coordinates to evaluate the spline fit at
xeval = np.linspace(xmin, xmax, nx)
yeval = np.linspace(ymin, ymax, ny)

# evaluate the spline fit
H = spl(xeval, yeval, grid=True)

rawDescription: How to generate data for matplotlib filled contour plots given the real coordinates?

description: Generate data for matplotlib filled contour plots given the real coordinates


rawDescription: How to obtain absolute path via relative path for 'other' project files?

description: Obtain absolute path via relative path for 'other' project files


rawDescription: Sorting a 2D numpy array by multiple axes


code:
yy = np.concatenate((y, y))
smoothed = np.convolve(np.array([1] * 5), yy)[5: len(x) + 5]

rawDescription: Smooth circular data

description: Smooth circular data


rawDescription: Testing specific apps in Django

description: Testing specific apps in Django


code:
_columns = {
    'course_rel_ids': fields.one2many('partner_course_rel', 'partner_id'),
}

rawDescription: How to add and show some attributes to a many2many relationship (OpenERP7)?

description: Add and show some attributes to a many2many relationship (OpenERP7)


code: rlist = list(reversed(slist))

rawDescription: Correct way to iterate twice over a list?


rawDescription: Getting selected text (python-gtk)

description: Getting selected text (python-gtk)


code:
data = '\n'.join(','.join('"%s"' % field for field in row) for row in data)
f= open('data.txt', 'w')
f.write(data)
f.close()

rawDescription: What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django)


code:
import re, nltk, string

dataFile = open(inputFile, 'r')
fileContent = dataFile.read()
fileContent = re.sub("\n+", ".", fileContent)
fileContentAscii = ''.join(filter(lambda x:x in string.printable,fileContent))
sentences = nltk.sent_tokenize(fileContentAscii)

rawDescription: How to use nltk sentence tokenizer in case of bulleted-data or listed data?

description: Use nltk sentence tokenizer in case of bulleted-data or listed data


code: from my_module import my_variable

rawDescription: Python passing variable values via import


code:
for i, b in itertools.izip(I, B):
    A[i] = b

rawDescription: Assignment to discontinuous slices in python


code:
import networkx as nx
import pylab as py
blue_edges = [('B', 'C'), ('B', 'D'), ('B', 'E'), ('E', 'F')]
red_edges = [('A', 'B'), ('A', 'C'), ('C', 'E'), ('D', 'E'), ('D', 'F')]

G=nx.Graph() #define G
G.add_edges_from(blue_edges)
G.add_edges_from(red_edges)

pos = {'A':(0,0), 'B':(1,1), 'C':(1,-1), 'D':(2,1), 'E':(2,-1), 'F':(3,0)}

nx.draw_networkx(G, pos=pos, edgelist = [], node_color = 'k')
nx.draw_networkx(G, pos=pos, nodelist = [], edgelist = blue_edges, edge_color = 'b')
nx.draw_networkx(G, pos=pos, nodelist = [], edgelist = red_edges, edge_color = 'r')

rawDescription: NetworkX: Drawing Graph

description: NetworkX: Drawing Graph


code:
seen = set()
filtered = dict()
for k, v in yourdict.iteritems():
    if v['name'] in seen:
        continue
    seen.add(v['name'])
    filtered[k] = v

rawDescription: How to remove dictionaries with duplicate values from a nested dictionary

description: Remove dictionaries with duplicate values from a nested dictionary


code:
import multiprocessing

def foo(m, d):
    m.acquire()
    print(d['key'])

def bar(m, d):
    d['key'] = 'value'
    m.release()

if __name__ == '__main__':

    manager = multiprocessing.Manager()

    m = multiprocessing.Lock()
    m.acquire()

    d = manager.dict()

    p1 = multiprocessing.Process(target=foo, args=(m, d))
    p2 = multiprocessing.Process(target=bar, args=(m, d))

    p1.start()
    p2.start()

rawDescription: Share a dictionary betweeen multiple live threads


code: 'string' == "string"

rawDescription: inverted comma and string in python

description: Inverted comma and string in python


code: assert np.allclose(cdf[-1], 1)

rawDescription: How to get cumulative distribution function correctly for my data in python?

description: Get cumulative distribution function correctly for my data in python


code: np.r_[0., np.cumsum(tmp)]

rawDescription: Python Custom Zipf Number Generator Performing Poorly


rawDescription: Find duplicate items within a list of list of tuples Python


code:
farm = []

def sow(val):
    if farm:
        farm[-1].append(val)
    return val

def reap(expr):
    farm.append([])
    val = expr()
    return val, farm.pop()

rawDescription: Python equivalent of Mathematica's Sow/Reap


code:
query = """SELECT * FROM df
     WHERE unix_timestamp(datetime, 'dd-MMM-yy HH.mm.ss.SSSSSS a') > {0}
     """.format(time.mktime((now - timedelta(minutes=5)).timetuple()))

sqlContext.sql(query)

rawDescription: Column filtering in PySpark

description: Column filtering in PySpark


code:
root = ElementTree.XML(xml_string)
xmldict = XmlDictConfig(root)

rawDescription: How to convert an xml string to a dictionary in Python?

description: Convert an xml string to a dictionary in Python


code:
raw = struct.pack('>HH', 16282, 1147)    # from two unsigned shorts
struct.unpack('>f', raw)[0]              # to one float

rawDescription: python 32 bit float conversion

description: Python 32 bit float conversion


code:
def post_message(request):
    form = forms.MessageForm()
    if request.method == 'POST':
        p_form = forms.MessageForm(request.POST)
        if p_form.is_valid():
            data = p_form.save(commit=False)
            data.owner = request.user
            data.save()
            return redirect('/success/')  # Redirect to a success page
        else:
            raise ValidationError('The Form did not validate')
    return render_to_response('post_message.html', {'form' : form}, context_instance=RequestContext(request))

rawDescription: Twitter API - how to have a user log in via Twitter to submit text to a database


rawDescription: packaging common python namespaces

description: Packaging common python namespaces


code:
import requests
help(requests.get)

rawDescription: How did I get informations on the module I'm writting?


code:
queryset = Profile.objects.all()
strings = ['keith', 's', 'thompson']
for string in strings:
    queryset = queryset.filter(full_name__icontains=string)

rawDescription: Filter Django database for field containing any value in an array


code:
z = []
for y in x:
    z.append(y-256 if y>256 else y)

rawDescription: Tuple Subtract statement in Python

description: Tuple Subtract statement in Python


code:
import itertools
AB = [a + b for a, b in itertools.izip_longest(A, B, fillvalue=0)]

rawDescription: Finding the sum of matching components in two lists


code:
15% complete
30% complete
45% complete
60% complete
75% complete
90% complete
100% complete

rawDescription: Track and display percentage of code already executed


code: ' '.join(re.findall("[^ ]+","text text                  blabla bla "))

rawDescription: python - remove whitespaces that are not needed

description: Python - remove whitespaces that are not needed


code:
soup = BeautifulSoup(match3, "html.parser")
names = []
allTds = soup.find_all("td")
for i,item in enumerate(allTds[::3]):
    #            firstname   hp                email
    names.append((item.text, allTds[(i*3)+1].text, allTds[(i*3)+2].text))

rawDescription: how do i loop a re.search for the next data

description: Loop a re.search for the next data


code:
from collections import defaultdict
groups=defaultdict(list)
for e in flat:
    groups[len(e)].append(e)
# groups=defaultdict(<type 'list'>, {5: ['Shoes', 'pants', 'shirt'], 3: ['tie', 'hat'], 6: ['jacket']})

rawDescription: Nest a flat list based on an arbitrary criterion


code: import ipdb; ipdb.set_trace()

rawDescription: Is it possible to go into ipython from code?


code:
...
hm = plt.contourf(x, levels = levels, cmap = "rainbow", vmax = levels[-2])
...

rawDescription: Nonlinear Colormap/Heatmap

description: Nonlinear Colormap/Heatmap


code:
def get_day(date_string):
    return datetime.strptime(date_string, '%m/%d/%Y').date()

rawDescription: How to do groupby in pandas with part of date string?

description: Do groupby in pandas with part of date string


code: tuple(x for x in 'SUP E P I C' if not x.isspace())

rawDescription: Convert a string list to a tuple in Python


code: bg_pixmap[state] = "<none>"

rawDescription: Disable pixmap background defined by GTK theme per application


rawDescription: Smarter way of calling boost::python::call?


rawDescription: Turn off auto-closing parentheses in ipython


code:
SOCIAL_AUTH_PIPELINE = (
    'social.pipeline.social_auth.social_details',
    'social.pipeline.social_auth.social_uid',
    'social.pipeline.social_auth.auth_allowed',
    'social.pipeline.social_auth.social_user',
    'social.pipeline.user.get_username',
    'social.pipeline.user.create_user',
    'social.pipeline.social_auth.associate_user',
    # the following custom pipeline func goes before load_extra_data
    'backends.pipeline_api.set_last_update',
    'social.pipeline.social_auth.load_extra_data',
    'social.pipeline.user.user_details',
    'backends.pipeline_api.update_profile_from_edx',
    'backends.pipeline_api.update_from_linkedin',
)

rawDescription: Decide when to refresh OAUTH2 token with Python Social Auth


code:
def first_saturday(year):
     candidate = dt.datetime(year, 1, 4)
     day = dt.timedelta(days=1)
     while candidate.weekday() != 6:
         candidate += day
     return candidate

rawDescription: Finding week of year with week ending on Saturday and first week containing atleast 4 days, in python


code: print(x)

rawDescription: In-place type conversion of a NumPy array


code: ['list', 'elements', 'go', 'here']

rawDescription: Python random sequence with seed

description: Python random sequence with seed


code:
def DictAccess(kls):
    kls.__getitem__ = lambda self, attr: getattr(self, attr)
    kls.__setitem__ = lambda self, attr, value: setattr(self, attr, value)
    return kls

rawDescription: Python class decorator converting element access to attribute access


code:
updated = orig.append(new).groupby('Name').last().fillna(0)
updated

rawDescription: Updating a 2D database (CSV) with other databases in Python?


rawDescription: get QuadMesh object from Axes (or Figure)

description: Get QuadMesh object from Axes (or Figure)


rawDescription: Preceding Word Length

description: Preceding Word Length


code:
def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise

rawDescription: What's the difference between subprocess Popen and call (how can I use them)?


code:
def checkSequence(*letters):
    return ''.join(letters).lower() in ascii_lowercase

rawDescription: how to check if 3 characters are in consecutive alpha order

description: Check if 3 characters are in consecutive alpha order


code:
import ctypes

class WinProcInfo(ctypes.Structure):
    _fields_ = [
        ('hProcess', ctypes.wintypes.HANDLE),
        ('hThread', ctypes.wintypes.HANDLE),
        ('dwProcessID', ctypes.wintypes.DWORD),
        ('dwThreadID', ctypes.wintypes.DWORD),
        ]
LPWinProcInfo = ctypes.POINTER(WinProcInfo)

lp = ctypes.cast(int(self.process.pid()), LPWinProcInfo)
print(lp.contents.dwProcessID)

rawDescription: When using pyqt on Windows, what does the QProcess.pid() result represent?


code:
class Number(messages.Message):
    number = messages.IntegerField(1, variant=messages.Variant.INT32)

rawDescription: IntegerField() is converted to string in JSON for any number


code:
import sys
from collections import Sequence,defaultdict

#making code python3-compatible
if sys.version_info[0] == 3:
    basestring = str

def buildLocator(tree):
    locator = defaultdict(list)
    def fillLocator(tree, locator,location):
        for index,item in enumerate(tree):
            if isinstance(item,basestring):
                locator[item].append(location+(index,))
            elif isinstance(item,Sequence):
                fillLocator(item,locator, location+(index,))
    fillLocator(tree,locator,())
    return locator

RECIPES = (
    ('apple', 'sugar', 'extreme_Force'),
    ('banana', 'syrup', 'magical_ends'),
    ('caramel', 'chocolate', 'pancake_MONSTER'),
    ('banana',('someAnother','banana'))
)
locator = buildLocator(RECIPES)

print(locator['banana'])

rawDescription: Finding if a string exists in a nested tuple in Python


code: new_df = df[df['type'] == 'buy_signal']

rawDescription: Write a loop in Python to print out the words when the condition is valid


code:
def show_progress(self):
    print (round((self._k / 1000000), 5))
    self._timer = Timer(1, self.show_progress)
    self._timer.start()

def process_with_timer(self):
    self._start = time.time()
    self._timer = Timer(1, self.show_progress)
    self._timer.start()
    self._k = 0
    while self._k < 100000000:
        self._k = self._k+1
    self._timer.cancel()

    print("duration:")
    print (time.time() - self._start)

rawDescription: Python, calculating the status of computation slows down the computation itself


code:
import json

some_json = """{
"id":               35436,
"url":              "https://company.zendesk.com/api/v2/tickets/35436.json",
"external_id":      "ahg35h3jh",
"created_at":       "2009-07-20T22:55:29Z",
"updated_at":       "2011-05-05T10:38:52Z",
"type":             "incident",
"subject":          "Help, my printer is on fire!",
"raw_subject":      "{{dc.printer_on_fire}}",
"description":      "The fire is very colorful.",
"priority":         "high",
"status":           "open",
"recipient":        "support@company.com",
"requester_id":     20978392,
"submitter_id":     76872,
"assignee_id":      235323,
"organization_id":  509974,
"group_id":         98738,
"collaborator_ids": [35334, 234],
"forum_topic_id":   72648221,
"problem_id":       9873764,
"has_incidents":    false,
"due_at":           null,
"tags":             ["enterprise", "other_tag"],
"via": {
    "channel": "web"
},
"custom_fields": [
    {
    "sid":    27642,
    "value": "745"
    },
    {
    "id":    27648,
    "value": "yes"
    }
],
"satisfaction_rating": {
    "id": 1234,
    "score": "good",
    "comment": "Great support!"
},
"sharing_agreement_ids": [84432]
}"""

# load the json object
zenJSONObj = json.loads(some_json)

# Shows a list of all custom fields
print("All the custom field data")
print(zenJSONObj['custom_fields'])
print("----")
# Tells you all the keys in the custom_fields
print("How keys and the values")
for custom_field in zenJSONObj['custom_fields']:
    print("----")
    for key in custom_field.keys():
        print("key:",key," value: ",custom_field[key])

rawDescription: Getting Deeper Level JSON Values in Python


rawDescription: Sort generated numbers using another python generator


code:
kargs = {'dollar': 1, 'euro': 3, 'foo': 'bar'}
{}.viewkeys() < kargs.viewkeys() < {'dollar', 'euro'}
del kargs['foo']
{}.viewkeys() < kargs.viewkeys() < {'dollar', 'euro'}
del kargs['dollar']
{}.viewkeys() < kargs.viewkeys() < {'dollar', 'euro'}
del kargs['euro']
{}.viewkeys() < kargs.viewkeys() < {'dollar', 'euro'}

rawDescription: Require one out of two keyword arguments


code: SubClass = type('SubClass', (EntityResource,), {})

rawDescription: Is there a way to create subclasses on-the-fly?


code:
while True:            # Loop continuously
    inp = input()      # Get the input
    if inp == 'quit':  # If it equals 'quit'...
        break          # ...then break the loop
    print(inp)         # Otherwise, continue with the loop

rawDescription: Loop with sub assignment in parenthesis

description: Loop with sub assignment in parenthesis


code:
with open("out.txt","w") as f:
 f.write("\n".join([s[i:i+15] for i in range(0,len(s),15)]))

rawDescription: Splitting a text file into columns

description: Splitting a text file into columns


code:
import requests
import json
headers = {'Accept': 'application/json', 'Authorization': 'Bearer <access_token>'}
json_data = {'rajNames': ['WAR']}
params = {'jsonRequest': json.dumps(json_data)}
url = 'http://258.198.39.215:8280/areas/0.1/get/raj/name'
requests.Request('GET', url, params=params, headers=headers).prepare().url

rawDescription: Python requests module url encode

description: Python requests module url encode