code:
class transact:
    def __enter__(a):
        print "enter"
    def __exit__(a,b,c,d):
        print "exit"

class transact2:
    def __enter__(a):
        print "enter2"
    def __exit__(a,b,c,d):
        print "exit2"

class Parent():
    @staticmethod
    def gettrans():
        return transact()
    def methodA(cl):
        with cl.gettrans():
            print "A"

class Child(Parent):
    pass
    @staticmethod
    def gettrans():
        return transact2()

p=Parent()
p.methodA()
c=Child()
c.methodA()

rawDescription: python: cleanest way to wrap each method in parent class in a "with"

description: Python: cleanest way to wrap each method in parent class in a "with"


code:
def check_for_duplicates(filename):
    import numpy
    with open(filename, 'r') as fil:
        lines = fil.readlines()
    lines = [line.strip().split() for line in lines]
    arr = numpy.array(lines)

    for row in arr:
        if len(set(row)) != len(row):
            print 'Duplicates in row: ', row

    for col in arr.T:
        if len(set(col)) != len(col):
            print 'Duplicates in column: ', col

rawDescription: Finding duplicates in each row and column


code:
print get_name(name1)
print get_name(name2)

rawDescription: Extracting part of a string with irregular delimiters in python


code:
for name, section in load_sections(somefilename):
    print name, section

rawDescription: How can I parse a formatted file into variables using Python?

description: Parse a formatted file into variables using Python


code:
def nDigits(i):
    return len(str(i))
results = []
for i in xrange(1000000):
    results.append(nDigits(i))
print len(results)

rawDescription: the different efficiency for number digits counting with python & C

description: The different efficiency for number digits counting with python & C


code:
import re
for word in sidemembers:
    if re.search(r'^Base', word) is not None:
        print word

for word in sidemembers:
    if word[:4] == 'Base':
        print word

rawDescription: Check if a string starts with the a specific word, if True then print word - PYTHON


code:
from PIL import Image
img = Image.new('L', (100,100))
img.putpixel((0,0), 100000)
print list(img.getdata())[0]

rawDescription: Bradley adaptive thresholding algorithm

description: Bradley adaptive thresholding algorithm


code:
import threading

shared = threading.local()

def print_value():
    print shared.name

rawDescription: Sharing data between two functions in two different modules in python 2.x


code:
for section in ("+SECTION1\n", "+SECTION2\n", "+SECTION3\n"):
    printing = False
    for line in f:
        if line == "--":
            print line
            printing = False
        if printing:
            print line
        if line == section:
            print line
            printing = True

rawDescription: Print between to points in a txt file

description: Print between to points in a txt file


code:
matrix_string = """
afaaf
rbaca
rlaff
"""

def find_longest_repetition(matrix):
    rows = len(matrix)
    cols = len(matrix[0])

    # row, col - row and column of the current character.
    # direction - 'h' if we are searching for repetitions in horizontal direction (i.e., in a row).
    #             'v' if we are searching in vertical direction.
    # result - (count, letter) of the longest repetition we have seen by now.
    #          This order allows to compare results directly and use `max` to get the better one
    # current - (count, letter) of the repetition we have seen just before the current character.
    def recurse(row, col, direction, result, current=(0, None)):
        # Check if we need to start a new row, new column,
        #   new direction, or finish the recursion.
        if direction == 'h':    # If we are moving horizontally
            if row >= rows:     # ...  and finished all rows
                return recurse( # restart from the (0, 0) position in vertical direction.
                    0, 0,
                    'v',
                    result
                )
            if col >= cols:     # ... and finished all columns in the current row
                return recurse( # start the next row.
                    row + 1, 0,
                    direction,
                    result
                )
        else:                   # If we are moving vertically
            if col >= cols:     # ... and finished all columns
                return result   # then we have analysed all possible repetitions.
            if row >= rows:     # ... and finished all rows in the current column
                return recurse( # start the next column.
                    0, col + 1,
                    direction,
                    result
                )

        # Figure out where to go next in the current direction
        d_row, d_col = (0, 1) if direction == 'h' else (1, 0)

        # Try to add current character to the current repetition
        count, letter = current
        if matrix[row][col] == letter:
            updated_current = count + 1, letter
        else:
            updated_current = 1, matrix[row][col]

        # Go on with the next character in the current direction
        return recurse(
            row + d_row,
            col + d_col,
            direction,
            max(updated_current, result), # Update the result, if necessary
            updated_current
        )

    return recurse(0, 0, 'h', (0, None))

def main():
    matrix = [[letter for letter in row.strip()]
              for row in matrix_string.strip().split('\n')]

    count, letter = find_longest_repetition(matrix)

    print letter, count

if __name__ == '__main__':
    main()

rawDescription: Trying to figure out longest path algorithm python


code:
var = 'ME\x00\x00'
print repr(var)

rawDescription: How can you pack an array of 2 chars + 2 null characters with python's struct?

description: Pack an array of 2 chars + 2 null characters with python's struct


code: print "\r{0}".format((float(i)/n)*100),

rawDescription: progress of loop indicator

description: Progress of loop indicator


code:
f = lambda: 'foo'
print f()

rawDescription: What is key=lambda

description: What is key=lambda


code:
for child in soup.find(id='main'):
    if isinstance(child, bs4.Tag):
        print child.text

rawDescription: How do I ignore tags while getting the .string of a Beautiful Soup element?

description: Ignore tags while getting the .string of a Beautiful Soup element


code:
from itertools import cycle

values = [10,0,0,14,14,123,235,0,0,0,0,0,12,12,1235,23,234,15,15,23,136,34,34,37,45]
splits = cycle([2,3])
bins = []
count = 0

while count < len(values):
    splitby = splits.next()
    bins.append(values[count:count+splitby])
    count += splitby

print bins

rawDescription: Python - How to generate a binning index for a list?


code:
with open("input.txt") as f:
  for line in f:
    print line == "asd"
    print line.strip() == "asd"

rawDescription: Why don't these two string equal each other?


code:
from bs4 import BeautifulSoup as bs
data = '''

username

Level 8

'''
soup = bs(data)
div_ele = soup.find('div')
b_ele = div_ele.find('b')
print b_ele.get_text()

rawDescription: Extracting certain text from within element


code: results = map((lambda (f, v): f(v)), zip(functions, values))

rawDescription: Apply a different Python function to corresponding element


code:
import time

class TestUploadHandler(tornado.web.RequestHandler):
   def post(self):
        logging.debug("Testing upload")
        start = time.time()
        self.write({})
        end = time.time()
        print "Time to write was {} seconds.".format(end-start)

rawDescription: How can I benchmark a tornado handler within the handler?

description: Benchmark a tornado handler within the handler


code:
print [max(dVals['items'], key=lambda x: x['age']) for dVals in yourData]

{'id': 0, 'age': 17, 'name': 'Pam1'}
{'id': 1, 'age': 8, 'name': 'Tom12'}
{'id': 2, 'age': 77, 'name': 'Pam13'}

rawDescription: Find maximum value in a list of dictionaries


code:
def wiggle(start, end, moves):
    if moves == 0:
        return 1 if start == end else 0
    else:
        return wiggle(start-1, end, moves-1) + wiggle(start+1, end, moves-1)

print wiggle(1,3,4)

rawDescription: recursion in python for delivering something by only going back and forth

description: Recursion in python for delivering something by only going back and forth


code:
for child in tree.findall('.//child'):
    attribute1 = int(child.attrib['attribute1'])
    attribute2 = [int(v) for v in child.attrib['attribute2'].split(',')]
    print attribute1, attribute2

rawDescription: Python. Parsing XML: getting separated values of attributes as a list


code:
import wmi
c = wmi.WMI()
for item in c.Win32_PhysicalMedia():
    print item

rawDescription: How to get hard disk serial number using Python

description: Get hard disk serial number using Python


code:
from Tkinter import *
import numpy as np
import cv2

class Test:
    def __init__(self):
        self.b1="up"
        self.xold=None
        self.yold=None
        self.liste=[]
    def test(self,obj):
        self.drawingArea=Canvas(obj)
        self.drawingArea.pack()
        self.drawingArea.bind("<Motion>",self.motion)
        self.drawingArea.bind("<ButtonPress-1>",self.b1down)
        self.drawingArea.bind("<ButtonRelease-1>",self.b1up)
    def b1down(self,event):
        self.b1="down"
    def b1up(self,event):
        self.b1="up"
        self.xold=None
        self.yold=None
        self.liste.append((self.xold,self.yold))
    def motion(self,event):
        if self.b1=="down":
            if self.xold is not None and self.yold is not None:
                event.widget.create_line(self.xold,self.yold,event.x,event.y,fill="red",width=3,smooth=TRUE)
            self.xold=event.x
            self.yold=event.y
            self.liste.append((self.xold,self.yold))
    def get_points(self):
        #for i in range(len(self.liste)):
            #print self.liste[i]
        return self.liste

class MaClasse:
    def __init__(self):
        self.s=600,600,3
        self.ma=np.zeros(self.s,dtype=np.uint8)
    def maclasse(self):
        cv2.namedWindow("OpenCV",cv2.WINDOW_AUTOSIZE)
        cv2.imshow("OpenCV",self.ma)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    def dessiner_lignes(self, les_points=[]):
        print "number of points: {}".format(len(les_points))
        for i in range(len(les_points)):
            #print i
            if i<len(les_points)-1:
                #print les_points[i]
                first_point=les_points[i]
                second_point=les_points[i+1]
                if not first_point == (None, None) and not second_point == (None, None):
                    cv2.line(self.ma,first_point,second_point,[255,255,255],2)

if __name__=="__main__":
    root = Tk()
    root.wm_title("Test")
    v = Test()
    v.test(root)
    root.mainloop()
    points = v.get_points()

    MC = MaClasse()
    MC.dessiner_lignes(points)
    MC.maclasse()

rawDescription: Draw same lines drawn on a Tkinter Canvas on an OpenCV image


code:
# Two 1D arrays
team1_scores = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
team2_scores = [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]

# This is your 2D array
scores = [ team1_scores, team2_scores ]

# You can sum an array using pythons built-in sum method
for idx, score in enumerate(scores):
    print 'Team {0} score: {1}'.format(idx+1, sum(score))

# Add a blank line
print ''

# Or you can manually sum each array
# Iterate through first dimension of array (each team)
for idx, score in enumerate(scores):
    team_score = 0
    print 'Summing Team {0} scores: {1}'.format(idx+1, score)
    # Iterate through 2nd dimension of array (each team member)
    for individual_score in score:
        team_score = team_score + individual_score
    print 'Team {0} score: {1}'.format(idx+1, team_score)

rawDescription: Python 2D Arrays Team Table

description: Python 2D Arrays Team Table


code:
class Map():

    def returnWay(self, node1, node2):
        final_list = []
        temp_list = []
        self._returnWay(node1, node2, final_list, temp_list)
        return final_list

    def _returnWay(self, node1, node2, final_list, temp_list):
        if node1 not in temp_list:
            temp_list.append(node1)
            if node1 == node2:
                final_list.append(temp_list[:])
                del temp_list[-1]
            else:
                for x in node1.nexts():
                    self._returnWay(x, node2, final_list, temp_list[:])
                del temp_list[-1]

path = Map()

for x in path.returnWay(node1, node2):
    print x

rawDescription: Python returning empty lists

description: Python returning empty lists


code:
code = "%d%d%d" % (randint(1,9), randint(1,9), randint(1,9))
cheat = 'cheat'
guess = raw_input("[keypad]> ")
guesses = 0

while guess not in [cheat, code] and guesses < 9:
    print "WRONG!"
    guesses += 1
    guess = raw_input("Guess 3 numbers> ")

if guess == code:
    print "Correct!"
    return my_func()
else:
    print "Game over"
    return exit()

rawDescription: How can I add a "cheat code" to this guess a number code I have?

description: Add a "cheat code" to this guess a number code I have


code:
def subprocess_cmd(command):
    process = subprocess.Popen(command,stdout=subprocess.PIPE, shell=True)
    proc_stdout = process.communicate()[0].strip()
    print proc_stdout

subprocess_cmd('echo a; echo b')

rawDescription: running multiple bash commands with subprocess

description: Running multiple bash commands with subprocess


code:
def decompose(number):
    # returns a generator of tuples (m, n1, r)
    for m in range(1, number+1):
        yield m, number // m, number % m

for m, n1, r in decompose(5):
    print "5 = %s * %s + %s" % (m, n1, r)

rawDescription: Decomposition function

description: Decomposition function


code:
import scipy.special
print scipy.special.k0.__doc__
scipy.special.k0(1)

rawDescription: Zeroth-order Bessel function Python

description: Zeroth-order Bessel function Python


code:
start_marker = 'startdel'
end_marker = 'enddel'

with open('data.txt') as inf:
    ignoreLines = False
    for line in inf:
        if start_marker in line:
            print line,
            ignoreLines = True
        if end_marker in line:
            ignoreLines = False
        if not ignoreLines:
            print line,

rawDescription: delete only lines after match1 up to match2

description: Delete only lines after match1 up to match2


code:
def sendGroupChatMessage():
    """
    Send Group Chat Messages.
    """
    import Skype4Py as skype
    skypeClient = skype.Skype()
    skypeClient.Attach()
    for elem in skypeClient.ActiveChats:
        if len(elem.Members) > 2:
            for friend in elem.Members:
                  print friend.Handle
            elem.SendMessage("SomeMessageHere")

rawDescription: How can I send a message to a group conversation with Skype4Py in Python

description: Send a message to a group conversation with Skype4Py in Python


code:
try:
    float(element)
except ValueError:
    print "Not a float"

rawDescription: Checking if a string can be converted to float in Python


code:
import shlex, subprocess, os, os.path
cmd = "ls ~/Downloads"
print os.popen(cmd).read()
print subprocess.check_output(shlex.split(cmd))

rawDescription: Subprocess call fails

description: Subprocess call fails


code:
inval = ['48998.tyrone-cluster;gic1_nwgs;mbupi;18:45:44;R;qp32\n', '48999.tyrone-cluster;gic2_nwgs;mbupi;0;Q;batch\n', '49005.tyrone-cluster;...01R-1849-01_2;mcbkss;00:44:23;R;qp32\n', '49032.tyrone-cluster;gaussian_top.sh;chemraja;0;Q;qp32\n', '49047.tyrone-cluster;jet_egrid;asevelt;312:33:0;R;qp128\n', '49052.tyrone-cluster;case3sqTS1e-4;mecvamsi;0;Q;qp32\n', '49053.tyrone-cluster;...01R-1850-01_1;mcbkss;0;Q;batch\n', '49054.tyrone-cluster;...01R-1850-01_2;mcbkss;0;Q;batch\n']

def parse(raw):
    parts = raw.strip().split(';')
    _id, _ = parts[0].split('.')
    return _id, parts[3], parts[4], parts[5]

print map(parse, inval)

# or
# print [parse(val) for val in inval]

rawDescription: separate list elements based on semicolon

description: Separate list elements based on semicolon


rawDescription: is there built-in custom numeric formating in python?

description: Is there built-in custom numeric formating in python


code:
if __name__=="__main__":
    import matplotlib.pyplot as plt
    from matplotlib import patches

    rectangles = [Rectangle(random()*5, random()*5, random()*5+5, random()*5+5) for i in range(5)]

    for i in range(len(rectangles)):
        for j in range(i):
            rectangles[i].check_relation_and_connect(rectangles[j])

    for rectangle in rectangles:
        print rectangle

    colormap = plt.get_cmap("Paired")
    for i, rect in enumerate(rectangles):
        ax = plt.axes()
        color = colormap((1.*i)/len(rectangles))
        patch = patches.Rectangle(rect.p1, rect.p2[0]-rect.p1[0], rect.p2[1]-rect.p1[1], fc="none", ec=color, lw=2)
        ax.add_patch(patch)
    plt.xlim(-1,11)
    plt.ylim(-1,11)
    plt.show()

rawDescription: Data structure(s) for storing nested boxes?


code:
d = {}

for row in rows:
  c = list_of_categories.index(row["id"])
  print c
  d[c] = row["name"]

rawDescription: How do you create a list like PHP's in Python?

description: Create a list like PHP's in Python


code: print post

rawDescription: Feedparser newbie questions

description: Feedparser newbie questions


code:
for elem in tree.findall('.//success'):
    if elem.attrib.get('field_name') == "success":
        print elem.tag, elem.attrib, elem.text

rawDescription: What is python 2.6 equivalent of iterfind()


code:
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason

rawDescription: How do you send an HTTP Get Web Request in Python?

description: Send an HTTP Get Web Request in Python


code: print sum(one_child_number(i) for i in xrange(8))

rawDescription: Optimizing Brute Force process in python / pypy for finding One-Child numbers


code:
import urllib2, json
data = json.load(urllib2.urlopen('http://www.ows.newegg.com/Products.egg/N82E16822148992'))
print data[u'FinalPrice']

rawDescription: Decoding JSON to give me a certain variable in Python?


code:
original = "/users/experiment_in14"
output2 = subprocess.check_output("find {} -empty".format(original), shell=True)
print output2

rawDescription: replace path in subprocess.check_output()

description: Replace path in subprocess.check_output()


rawDescription: Working with big data in python and numpy, not enough ram, how to save partial results on disc?


code:
element = driver.find_elements_by_xpath('//div[@class="d3-tip n"]')[0]
print element.text

rawDescription: Unable to read text from a div tag in python


code:
import math
a_lambda = 1.0
rho = 0.8
c = 1.0
b = rho * c / a_lambda
p0 = (1 - (a_lambda*b))
p1 = (1-(a_lambda*b))*(math.exp(a_lambda*b) - 1)
p_dict = {0: p0, 1: p1}

def a(n):
    return math.exp(-a_lambda*b) * ((a_lambda*b)**n) / math.factorial(n)

def get_nth_p(n, p_dict):
    # return pre-calculated value if p(n) is already known
    if n in p_dict:
        return p_dict[n]

    # Calculate p(n) using modified formula
    p_n = ((get_nth_p(n-1, p_dict)
            - (get_nth_p(0, p_dict) + get_nth_p(1, p_dict)) * a(n - 1)
            - sum(get_nth_p(j, p_dict) * a(n + 1 - j) for j in xrange(2, n)))
          / a(0))

    # Save computed value into the dict
    p_dict[n] = p_n
    return p_n

get_nth_p(6, p_dict)
print p_dict

rawDescription: Solving a mathematical equation recursively in Python


code:
import numpy as np

z = '''33 33 33 37 38 37 43 40
33 33 33 38 38 38 44 40
36 36 36 36 38 39 44 41
35 36 35 35 34 30 40 41
36 36 35 35 34 30 30 41
38 38 35 35 34 30 30 41'''
z = np.array([[int(i) for i in line.split()] for line in z.splitlines()])

neighbours = [(-1,-1), (-1,0), (-1,1), (0,1), (1,1), (1,0), (1,-1), (0,-1)]
mask = np.zeros_like(z, dtype = bool)
stack = [(3,2)] # push start coordinate on stack

while stack:
    x, y = stack.pop()
    mask[x, y] = True
    for dx, dy in neighbours:
        nx, ny = x + dx, y + dy
        if (0 <= nx < z.shape[0] and 0 <= ny < z.shape[1]
            and not mask[nx, ny] and abs(z[nx, ny] - z[x, y]) <= 1):
            stack.append((nx, ny))

for line in mask:
    print ''.join('01'[i] for i in line)

rawDescription: How to iterate through a numpy array and select neighboring cells

description: Iterate through a numpy array and select neighboring cells


code:
class BaseType(type):
    _iden = 0
    def _get_iden(cls):
        return BaseType._iden
    def _set_iden(cls, value):
        BaseType._iden = value
    iden = property(_get_iden, _set_iden)

class BaseClass(object):
    __metaclass__ = BaseType

class Child1(BaseClass):
    pass

class Child2(BaseClass):
    pass

print Child1.iden
Child1.iden = 5
print Child1.iden
print Child2.iden

rawDescription: Share class attributes among several classes in Python


rawDescription: How to compute huge numbers with python?

description: Compute huge numbers with python


code:
import time,os
while True:
    print "OK ?"+os.environ["LD_PRELOAD"]
    time.sleep(1)

rawDescription: How can I execute a shell command in a child process in Python?

description: Execute a shell command in a child process in Python


code:
def dicList():
    dictList = csv.reader(open('C:/Python/data.txt', 'rb'), delimiter="|")
    for row in dictList:
       #the data should now be pre-separated into a list
       print row

rawDescription: How to write into, or create a dictionary, using indexes in a row from another file

description: Write into, or create a dictionary, using indexes in a row from another file


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://groceries.asda.com/asda-webstore/landing/home.shtml?cmpid=ahc--ghs-d1--asdacom-dsk-_-hp#/shelf/1215337195041/1/so_false')

div = driver.find_element_by_id('listings')
for item in driver.find_elements_by_xpath('//div[@id="listings"]//a[@title]'):
    print item.text.strip()

driver.close()

rawDescription: My first scrapy xpath selector

description: My first scrapy xpath selector


code:
from operator import add, mul, sub

ops = [add, sub, mul]

a = 3
b = 4

for op in ops:
    print op(a, b)

rawDescription: Call each method in a list in a loop?

description: Call each method in a list in a loop


code:
print myType.Options['Minimum']
print myType.Minimum

rawDescription: Change values of internal dictionary via attributes


code:
import copy
import random
validNames=["John", "Aaron", "Lydia", "Robin"]

def drawNames(namelist,currentname):
    '''
    namelist: list of names to draw from
    currentname: name of person doing the current draw
    '''
    draw_namelist = copy.copy(namelist) # make a copy to remove person drawing if needed
    if currentname in draw_namelist: # check if the person drawing is in the list
        draw_namelist.remove(currentname) # remove current name if in list
    try:
        drawn_name = random.choice(draw_namelist)
        namelist.remove(drawn_name)
        newnamelist = namelist
        print "Drew {}".format(drawn_name)
        print "New list: {}".format(newnamelist)
    except:
        print "Nobody for me to draw!"
        drawn_name=None
        newnamelist = namelist
    return drawn_name, newnamelist

rawDescription: Python - list.remove(x) x not in list

description: Python - list.remove(x) x not in list


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

def save_coastal_data(path,resolution='f'):

    m = Basemap(projection='robin',lon_0=0,resolution=resolution)

    coast = m.drawcoastlines()

    coordinates = np.vstack(coast.get_segments())
    lons,lats = m(coordinates[:,0],coordinates[:,1],inverse=True)

    D = {'lons':lons,'lats':lats}

    np.save(os.path.join(path,'coastal_basemap_data.npy'),D)

def distance_from_coast(lon,lat,fpath,degree_in_km=111.12):

    D = np.load(fpath).tolist()

    lons,lats = D['lons'],D['lats']

    dists = np.sqrt((lons-lon)**2+(lats-lat)**2)

    print np.min(dists)*degree_in_km

#Define path
path = 'path/to/directory'
#Run just one time to save the data. Will cost less time
save_coastal_data(path,resolution='h')

distance_from_coast(-117.2547,32.8049,
os.path.join(path,'coastal_basemap_data.npy'))

rawDescription: Matplotlib Basemap Coastal Coordinates

description: Matplotlib Basemap Coastal Coordinates


code:
FLAGS = ('User', 'Redo', 'Enqueue', 'Cache', 'OS',
         'Real Application Clusters', 'SQL', 'Debug')
def getFlags(value):
  flags = []
  for i, flag in enumerate(FLAGS):
    if value & (1 << i):
      flags.append(flag)
  return flags
print getFlags(22)

rawDescription: Standard Solution for Decoding Additive Numbers


code:
transientvariables = []
transientvariables.append(makenewtransientvariable())
# ...
for tv in transientvariables:
    print tv

rawDescription: Natural Naming Scheme for a dynamic set of members


code:
for result in data:
    # Here, we get either a dictionary or a `None`
    if result:  # Filter out the `None` rows. You could also do a isinstance(result, (dict)) if you're paranoid
        for key, value in result.iteritems():
            print key, value

rawDescription: is null row allowed in json

description: Is null row allowed in json


code:
import argparse

def main():
    parser = argparse.ArgumentParser(
        description = 'three positional integer arguments.')
    parser.add_argument('picks', type = int, default = 10, nargs = '?',
                       help = 'number of selections per execution')
    parser.add_argument('minchunk', type = int, default = 2, nargs = '?',
                       help = 'min chunk size')
    parser.add_argument('maxchunk', type = int, default = 8, nargs = '?',
                       help = 'max chunk size')

    args = parser.parse_args()
    print args

main()

rawDescription: can argparse store positional number arguments as simple variables?

description: Can argparse store positional number arguments as simple variables


code:
"""returns a list of length `size` whose elements are evenly distributed between start and end"""
def interpolate(start, end, size):
    delta = float(end - start) / (size-1)
    return [start + i*delta for i in range(size)]

def interpolate_color(start, end, size):
    red   = interpolate(start[0], end[0], size)
    green = interpolate(start[1], end[1], size)
    blue  = interpolate(start[2], end[2], size)
    return zip(red, green, blue)

start = (100,200,150)
end = (255,255,255)
for c in interpolate_color(start, end, 5):
    print c

rawDescription: Finding a ratio to multiply RGB values by to get multiple tints of a color in Python


code: print dir(B)

rawDescription: Why does a class have the attributes of its metaclass?


rawDescription: sort a 2D list first by 1st column and then by 2nd column

description: Sort a 2D list first by 1st column and then by 2nd column


code:
sum_size = 0
for i in a:
        dest = '/home/zurelsoft/my_files'
        fullname = os.path.join(dest, i) #Get the file_full_size to calculate size
        st = int(os.path.getsize(fullname))
        sum_size += size(st)
print sum_size

rawDescription: How to add all the elements inside loop in Python?

description: Add all the elements inside loop in Python


code:
print u'\u0022\u002F\u005C\u0022'
print(''.join(u'\\u{:04X}'.format(ord(c)) for c in su))

rawDescription: Converting a unicode string to see unicode code points


rawDescription: Slice pandas dataframe into equal lengths of 34


code:
students = {"lloyd" : [], "alice" : [], "tyler" : []}

for student in students:
    students[student] = {  # Notice the change here
        "name" : [],
        "homework" : [],
        "quizzes" : [],
        "tests" : []
    }

print students

rawDescription: Using Loops to Simplify Python Dictonaries


code:
def func(*vargs):
    for a in vargs:
       print a

func(*main_list)

rawDescription: Python function parameters inside a list of lists


code:
import numpy as np
x = np.arange(4)
numrepeats = 3

y = np.lib.stride_tricks.as_strided(x, (numrepeats,)+x.shape, (0,)+x.strides)

print y
x[0] = 9
print y

rawDescription: repeated numpy subarrays

description: Repeated numpy subarrays


code:
result = r.lrange ('stlfile', 0, 0)
string = result[0]
x = string[1:-1]
print x

rawDescription: Check redis get key available, if else python script


code:
siblings_removed = remove_siblings_of('name', 'G', root)
print et.tostring(siblings_removed)

rawDescription: Remove element siblings from etree in python


code:
def myprint(d):
    if isinstance(d,dict): #check if it's a dict before using .iteritems()
        for k, v in d.iteritems():
            if isinstance(v, (list,dict)): #check for either list or dict
                myprint(v)
            else:
                print "Key :{0},  Value: {1}".format(k, v)
    elif isinstance(d,list): #allow for list input too
        for item in d:
            myprint(item)

rawDescription: Python: Loop through all nested key-value pairs created by xmltodict


code: print 'b'

rawDescription: Multiple -m command line arguments (Python)


code:
def find_and_replace(d, key, replacement="replacement"):
    for k,v in d.items():
        if isinstance(v, dict):
            print "found nested dict"
            if find_and_replace(v, key):
                return True

        elif isinstance(v, str):
            if k==key:
                d.update({k:replacement})
                print "replaced [%s] with [%s]" % (v, replacement)
                return True

rawDescription: Check if dictionary exist within dictionary and if so change it


code:
class ClassA:
    def __init__(self):
        # CREATE ClassB right here
        print 'self is an INSTANCE of ClassA, look: ' + repr(self)
        print 'self.__class__ is a TYPE OF THE INSTANCE of ClassA, see? ' \
                                            + repr(self.__class__)
        class ClassB(self.__class__):
            # ClassA is a base class, ClassB is a child class
            def __init__(self):
                pass

            def main(self):
                a = self.randomword(10)
                print 'hello, the output of ClassA.randomword is "'+str(a)+'"'

        # Instantiate ClassB
        class_b = ClassB()
        class_b.main()

    def randomword(self, num):
        print 'randomword was called'
        return 'hey there'

a = ClassA()

rawDescription: how to call a method from a class imported dynamically

description: Call a method from a class imported dynamically


code:
from pyparsing import *

parser = "A" + SkipTo("B") + "B"

for test in ("ABC", "AXBC"):
    try:
        print test
        print parser.parseString(test)
    except ParseException as pe:
        print "exception:", pe
    print

rawDescription: Right way to SkipTo not empty tokens with ZeroOrMore in pyparsing


code:
import pickle
import random

def load_data():
    try:
        with open("bin.dat") as f:
            x, y = pickle.load(f)
    except:
        x, y = [], []
    return x, y

def save_data(data):
    with open("bin.dat", "wb") as f:
        pickle.dump(data, f)

if __name__ == "__main__":
    x, y = load_data()
    print x, y
    x.append(random.randint(1, 10))
    y.append(random.randint(1, 10))
    save_data([x, y])

rawDescription: Python: how to save a list with objects in a file?


code:
s = "Stack_overflow_question_0.3.jpg"

print s.replace(".jpg", "").rsplit("_", 1)
['Stack_overflow_question', '0.3']

rawDescription: Save file list into text file using python


code:
import pandas as pd

df = pd.read_excel(excel_file_path, sheetname="Sheet1")
print len(df)

rawDescription: Count rows in excel sheet in Python with xlwings


code:
import math

def map_nested(input, function):
    if type(input) is list:
        return [map_nested(e, function) for e in input]
    else:
        return function(input)

print map_nested([[[1,2],[3,4]],[[5,6],[7,8]]], math.sqrt)

rawDescription: returning from recursive function in python

description: Returning from recursive function in python


code:
def f():
    print 'f called'
f = countcalls(f)

rawDescription: Unable to understand this python decorator


code:
# query parameters
keyword, start, limit = 'xxx', 1, 3

# subquery for the last_time
sq2h = session.query(Deb.package_id, func.max(Deb.id).label("max_id")).group_by(Deb.id).subquery("max_deb")
sq2 = (session.query(Deb.package_id, Deb.last_time).
        join(sq2h, Deb.id == sq2h.c.max_id))
sq2 = sq2.subquery("deb")

qry = (session.query(Package.id, Package.name, sq2.c.last_time).
        outerjoin(sq2, sq2.c.package_id == Package.id).
        filter(Package.name.contains(keyword))
        )[start:(start + limit)]
print qry

rawDescription: how to generate this sql in sqlalchemy,i am trying hard but didn't know what to do

description: Generate this sql in sqlalchemy,i am trying hard but didn't know what to do


code:
def create_sub_cat(parent):
    print "creating subcat\n {} > ".format(parent)
    for conf in iter(lambda: raw_input("type new subcat or"
                                       " press \"ENTER\" to save changes\n"),""): # empty string for sentinel value
        parent += " > " + conf
    return parent

rawDescription: Function that calls itself returns only first result of its call


code:
class _specialmethod:
  def __init__(self,func):
     self.func = func

  def __call__(self,arg1,arg2):
     print arg1,arg2
     self.func(arg1,arg2)

def specialmethod(f):
    wrapper_class = _specialmethod(f)
    @functools.wraps(f)
    def wrapper(arg1, arg2):
        wrapper_class(arg1, arg2)
    return wrapper

rawDescription: Python decorate method with callable outside parent class


code:
import csv
import StringIO
from collections import OrderedDict

output = """
QueryTime
start,end
144488,144490

Data

Data - AData
id,G_id,name,type,time,sid,channel
23,-1,"B1",type1,144488,11,CH23
23,-1,"B1",type1,144488,11,CH23
Data - BData
id,G_id,time,se
23,-1,144488,undefined
23,-1,144488,undefined"""

sections = ['QueryTime', 'Data - AData', 'Data - BData', 'Data']
re_sections = '|'.join([re.escape(s) for s in sections])
tables = re.split(r'(' + re_sections + ')', output)
tables = [t.strip() for t in tables[1:]]

d_tables = OrderedDict()

for section, table in zip(*[iter(tables)]*2):
    if len(table):
        csv_input = csv.reader(StringIO.StringIO(table))
        d_tables[section] = list(csv_input)

for section, entries in d_tables.items():
    print section
    print entries
    print

rawDescription: reading comma separated value from string object in python

description: Reading comma separated value from string object in python


code:
import traceback
def f(depth=0):
    print depth, traceback.print_stack()
    if depth < 2:
        f(depth + 1)
f()

rawDescription: Can a Python method check if it has been called from within itself?


code:
def cpu_usage_str(cpu_percentage):
    return 'CPU:[%s]' % ('#' * cpu_percentage / 10)

print cpu_usage_str(52)
print cpu_usage_str(64)
print cpu_usage_str(72)

rawDescription: Python: Add character to string an amount of times depending on an int


code:
class ThesaurusBase:
    @classmethod
    def initClassWide(cls):
        cls._shared = cls()

class T(ThesaurusBase):
    def foo(self):
        print self._shared

ThesaurusBase.initClassWide()
t = T()
t.foo()

rawDescription: Python2.7: infinite loop when super __init__ creates an instance of it's own subclass


code:
with open("donations.txt", "r") as in_file:
    highest = lowest = donation = None
    number = total = 0
    for line in in_file:
        try:
            donation = float(line)
        except ValueError:
            continue
        if highest is None or donation > highest:
            highest = donation

        if lowest is None or donation < lowest:
            lowest = donation

        number += 1
        total += donation

        average = total / number

print "The highest amount is $%.2f" %highest
print "The lowest amount is $%.2f" %lowest
print "The total donation is $%.2f" %total
print "The average is $%.2f" %average

rawDescription: How to read numbers in a text file for python?

description: Read numbers in a text file for python


rawDescription: Python | How to create complex dictionary


code:
import numpy
import lomb
numpy.random.seed(999)
nd = 20
fs = 10
x = numpy.arange(nd)
y = numpy.random.randn(nd)
fx, fy, nout, jmax, prob = lomb.fasper(x, y, 1., fs)
fNy = fx[-1]
fy = fy/fs
Si = numpy.mean(fy)*fNy
print fNy, Si, Si*2

rawDescription: How do I match lomb-scargle and FFT plots of same dataset?

description: Match lomb-scargle and FFT plots of same dataset


code:
import string
import random
characters = string.ascii_letters + string.punctuation  + string.digits

password = ""
password_length = random.randint(8, 16)

for x in range(password_length):
    char = random.choice(characters)
    password = password + char

print password

rawDescription: password generator using Python

description: Password generator using Python


code:
for i in ['hello', 'world', 'app']:
    def method(i=i):
        print i
    setattr(self, i, method)

rawDescription: Dynamic assignment of methods in python class


code:
import os,sys
fd = "./p1.txt"
try:
    os.mkfifo(fd)
except OSError:
    pass
rp = os.open(fd, os.O_RDONLY)

#Need to create new thread, for background reading file
while True:
    response = os.read(rp, 54)
    if response == "COMMAND":
        #do
        print 'ICATCHYOU'

rawDescription: How to make simple interacting with running python script for web?

description: Make simple interacting with running python script for web


code:
pool = multiprocessing.Pool()
for proc in pool._pool:
  print proc.pid

rawDescription: Retrieve exit code of processes launched with multiprocessing.Pool.map


code:
import os
import datetime

print datetime.datetime.fromtimestamp(os.stat(".").st_atime)

rawDescription: ctime, atime, and mtime - How to interpret them?

description: Ctime, atime, and mtime - How to interpret them


code:
for (xrange, yrange), zrange in product(product(rangeList,rangeList),rangeList):
    print xrange, yrange, zrange

rawDescription: Python itertools: Best way to unpack product of product of list of lists


code:
from urllib2 import urlopen
from bs4 import BeautifulSoup

data = urlopen('your URL here')
soup = BeautifulSoup(data)

entry = soup.find('div', class_="entry")

for p in entry.find_all('p'):
    for row in p.find_all(text=True):
        try:
            print row.split(' ')[-2]
        except IndexError:
            continue

rawDescription: How to extract html to text in BeautifulSoup?

description: Extract html to text in BeautifulSoup


code:
j=0
for i in range (0, 5):
    #Other things you want to do
    j+=1
print j

rawDescription: How to get the count of output in python

description: Get the count of output in python


code:
from BeautifulSoup import BeautifulSoup
import urllib2

def scrap(url):

    soup = BeautifulSoup(urllib2.urlopen(url))

    break_tags = ['h2', 'h3']

    h2s = soup.findAll("h2")

    do_tag = None

    for tag in h2s:
        if tag.find(id="Do"):
            do_tag = tag
            break

    next_tag = do_tag.findNextSibling()
    while 1:
        if next_tag.name in ['div', 'p']:
            next_tag = next_tag.findNextSibling()
            continue
        if next_tag.name in break_tags:
            break

        #if next_tag.name in ['ul']:
        #    print next_tag.name

        #
        # The structure of the HTML is very bad.. no consistency !
        if next_tag.find("span"):
            print next_tag.find("span").span.text
        else:
            print next_tag.li.b.text

        next_tag = next_tag.findNextSibling()

rawDescription: Scraping data only after beginning of a certain text


code:
import matplotlib
import matplotlib.pyplot as plt

matplotlib.rc('text', usetex = True)
matplotlib.rc('font', **{'family':"sans-serif"})
params = {'text.latex.preamble': [r'\usepackage{siunitx}',
    r'\usepackage{sfmath}', r'\sisetup{detect-family = true}',
    r'\usepackage{amsmath}']}
plt.rcParams.update(params)

fig = plt.figure(figsize = (4,4))
ax = fig.add_subplot(1,1,1)
ax.set_xlabel('$\si{\um} detection$')
ax.set_ylabel(r"$\mu \boldsymbol{\mu}$")
plt.show()

rawDescription: Upright mu in plot label: retaining original tick fonts


code:
import numpy as np, statsmodels.stats.api as sms

X1, X2 = np.arange(10,21), np.arange(20,26.5,.5)

cm = sms.CompareMeans(sms.DescrStatsW(X1), sms.DescrStatsW(X2))
print cm.tconfint_diff(usevar='unequal')

rawDescription: Confidence Interval for t-test (difference between means) in Python


code:
import numpy
import theano
import theano.tensor as tt

embeddings_matrix = theano.shared(numpy.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]], dtype=theano.config.floatX))
index_matrix = tt.imatrix()
y = embeddings_matrix[index_matrix]
f = theano.function([index_matrix], y)
output = f(numpy.array([[0, 1], [2, 1]], dtype=numpy.int32))
print output.shape, '\n', output

rawDescription: theano ~ use an index matrix and embeddings matrix to produce a 3D tensor?

description: Theano ~ use an index matrix and embeddings matrix to produce a 3D tensor


code:
import threading
import time
from Queue import Queue

print_lock = threading.Lock()

class MyThread(threading.Thread):
    def __init__(self, queue, args=(), kwargs=None):
        threading.Thread.__init__(self, args=(), kwargs=None)
        self.queue = queue
        self.daemon = True
        self.receive_messages = args[0]

    def run(self):
        print threading.currentThread().getName(), self.receive_messages
        val = self.queue.get()
        self.do_thing_with_message(val)

    def do_thing_with_message(self, message):
        if self.receive_messages:
            with print_lock:
                print threading.currentThread().getName(), "Received {}".format(message)

if __name__ == '__main__':
    threads = []
    for t in range(10):
        q = Queue()
        threads.append(MyThread(q, args=(t % 2 == 0,)))
        threads[t].start()
        time.sleep(0.1)

    for t in threads:
        t.queue.put("Print this!")

    for t in threads:
        t.join()

rawDescription: How do I send data to a running python thread?

description: Send data to a running python thread


code:
gen = printit()
for i, number in enumerate(gen):
    print i, number
    if i > 3:
        try:
            gen.send(True)
        except StopIteration:
            print "stopped"

rawDescription: How can I return a changing variable without ending the function in Python?

description: Return a changing variable without ending the function in Python


code:
a = 'aBcDeFg'
print a.lower() # abcdefg

rawDescription: How to make letters in a string lowercas, Python

description: Make letters in a string lowercas, Python


code:
#!/usr/bin/python

import sys

for line in sys.stdin:
  print "hello " + line

rawDescription: How to Use both Scala and Python in a same Spark project?


code:
subq = self.session.query(DataMeasurement).\
    filter_by(data_source='Sensor1').subquery()
# Use alias to associate mapped class to a subquery.
dmalias = aliased(DataMeasurement, subq)
q = self.session.query(dmalias, DataMeasurement).filter(
    (DataMeasurement.data_source == 'Sensor2') &
    (DataMeasurement.timestamp == dmalias.timestamp)
)

# For each row you get a tuple containing two DataMeasurement objects.
for dm1, dm2 in q:
    print dm1.timestamp, dm1.sensor_output, dm2.sensor_output

rawDescription: How can I join two queries on the same table with python / sqlalchemy?

description: Join two queries on the same table with python / sqlalchemy


code:
out=repo.diff(t0,t1)
print out
print out.patch

rawDescription: How to print the contents of a pygit object in python

description: Print the contents of a pygit object in python


code:
import pandas as pd
import numpy as np

df=pd.DataFrame({'group':[1,2,3,' No Data',4,5,6]})

df = df.applymap(lambda x: np.nan if type(x) == str and 'No Data' in x else x)
print df

rawDescription: Python ignoring leading whitespace when doing .replace on dataframe column with strings


code: print data.encode('hex')

rawDescription: Manipulating binary data in Python

description: Manipulating binary data in Python


code:
from dis import dis

def test(expression):
    while expression:
        check, expression = expression, expression.replace('()', '').replace('[]', '').replace('{}', '')
        if expression == check:
            return False
    return True

print dis(test)

rawDescription: How does a comma followed by a variable assignment concatenate?


code:
import csv

def process(rows, chunk_no):
    for no, data in rows:
        print no, data
    print 'chunk no {} process {} rows'.format(chunk_no, len(rows))

csv_file='really_simple.csv'
with open(csv_file) as fo:
    reader = csv.reader(fo)
    _headers = reader.next()

    chunk_no = 1
    tobesaved = []
    for row in reader:
        tobesaved.append(row)
        if len(tobesaved) == 10:
            process(tobesaved, chunk_no)
            chunk_no += 1
            tobesaved = []
    if tobesaved:
        process(tobesaved, chunk_no)

rawDescription: Python csv reader-zipping reader with range


code:
import re

def extract_current(s):
    s = s[s.rfind(' ')+1:-1]
    s = re.sub('\d{6}-\d{6}', '', s)
    s = re.sub('[A-Z]+', '', s)
    return s

print extract_current('24.02 24.02VALINTATALO MEGAHERTSI4,76-')
print extract_current('24.02 24.02DOE MRIDANG 157235-1234582,00-')

rawDescription: Regex pattern problem in python

description: Regex pattern problem in python


code:
__name__
def a():
    print 'a'

def b():
    print 'b'

import sys
sys.modules['__main__'].b = a
b()

rawDescription: can one function be overwritten by calling another?

description: Can one function be overwritten by calling another


rawDescription: Printing data from list

description: Printing data from list


code:
import ruamel.yaml as yaml

infile = yaml.load(open('yamlfile'), Loader=yaml.RoundTripLoader)

for key, value in infile['main'].items():
    if key == 'keepalivetimeout':
        item = value['item']
        item['keepalivetimeout'] = 400

print yaml.dump(infile, Dumper=yaml.RoundTripDumper)

rawDescription: Pyyaml - Using different styles for keys and integers and strings


code:
# List of LEADINs to buy time.
leadins = """To characterize a linguistic level L,
        On the other hand,
        This suggests that
        It appears that
        Furthermore """

# List of SUBJECTs chosen for maximum professorial macho.
subjects = """ the notion of level of grammaticalness
        a case of semigrammaticalness of a different sort
        most of the methodological work in modern linguistics
        a subset of English sentences interesting on quite independent grounds
        the natural general principle that will subsume this case """

#List of VERBs chosen for autorecursive obfuscation.
verbs = """can be defined in such a way as to impose
        delimits
        suffices to account for
        cannot be arbitrary in
        is not subject to """

# List of OBJECTs selected for profound sententiousness.

objects = """ problems of phonemic and morphological analysis.
        a corpus of utterance tokens upon which conformity has been defined by the paired utterance test.
        the traditional practice of grammarians.
        the levels of acceptability from fairly high (e.g. (99a)) to virtual gibberish (e.g. (98d)).
        a stipulation to place the constructions into these various categories.
        a descriptive fact.
        a parasitic gap construction."""

import textwrap, random
from itertools import chain, islice, izip
from time import sleep

def chomsky(times=1, line_length=72):
    parts = []
    for part in (leadins, subjects, verbs, objects):
        phraselist = map(str.strip, part.splitlines())
        random.shuffle(phraselist)
        parts.append(phraselist)
    output = chain(*islice(izip(*parts), 0, times))
    return textwrap.fill(' '.join(output), line_length)

print chomsky()

rawDescription: How to use NLTK to generate random paragraphs

description: Use NLTK to generate random paragraphs


code:
try:
   smtpObj = smtplib.SMTP('smtp.gmail.com', 587) # or 465
   smtpObj.ehlo()
   smtpObj.starttls()
   smtpObj.login(account, password)
   smtpObj.sendmail(sender, receivers, message)
   print "Successfully sent email"
except:
   print "Error: unable to send email"

rawDescription: Cannot send an email with python smtp

description: Cannot send an email with python smtp


code:
import regex as re

def remove_punctuation(text):
    return re.sub(ur"\p{P}+", "", text)

rawDescription: Remove punctuation from Unicode formatted strings


code:
import timeit

import pickle
import cPickle

import json
import simplejson
import ujson
import yajl

def load_pickle(f):
    return pickle.load(f)

def load_cpickle(f):
    return cPickle.load(f)

def load_json(f):
    return json.load(f)

def load_simplejson(f):
    return simplejson.load(f)

def load_ujson(f):
    return ujson.load(f)

def load_yajl(f):
    return yajl.load(f)

print "pickle:"
print timeit.Timer('load_pickle(open("test.pickle"))', 'from __main__ import load_pickle').timeit()

print "cpickle:"
print timeit.Timer('load_cpickle(open("test.pickle"))', 'from __main__ import load_cpickle').timeit()

print "json:"
print timeit.Timer('load_json(open("test.json"))', 'from __main__ import load_json').timeit()

print "simplejson:"
print timeit.Timer('load_simplejson(open("test.json"))', 'from __main__ import load_simplejson').timeit()

print "ujson:"
print timeit.Timer('load_ujson(open("test.json"))', 'from __main__ import load_ujson').timeit()

print "yajl:"
print timeit.Timer('load_yajl(open("test.json"))', 'from __main__ import load_yajl').timeit()

rawDescription: What is faster - Loading a pickled dictionary object or Loading a JSON file - to a dictionary?


code:
test = u'ë́aúlt'
print test[0]

rawDescription: Python returning the wrong length of string when using special characters


code:
import threading

class MyLock(threading._RLock):
    def release(self):
        print("releasing")
        super(MyLock, self).release()

class Obj():
    def test(self):
        print "in test"

l = MyLock()
obj = Obj()

def f():
    with l:
        return obj.test()

f()

rawDescription: Correct usage of Python threading.RLock

description: Correct usage of Python threading.RLock


code:
import glob

from classify import MultinomialNB
from PIL import Image

TRAINING_POSITIVE = 'training-positive/*.jpg'
TRAINING_NEGATIVE = 'training-negative/*.jpg'
TEST_POSITIVE = 'test-positive/*.jpg'
TEST_NEGATIVE = 'test-negative/*.jpg'

# How many pixels to grab from the top-right of image.
CROP_WIDTH, CROP_HEIGHT = 100, 100
RESIZED = (16, 16)

def get_image_data(infile):
    image = Image.open(infile)
    width, height = image.size
    # left upper right lower
    box = width - CROP_WIDTH, 0, width, CROP_HEIGHT
    region = image.crop(box)
    resized = region.resize(RESIZED)
    data = resized.getdata()
    # Convert RGB to simple averaged value.
    data = [sum(pixel) / 3 for pixel in data]
    # Combine location and value.
    values = []
    for location, value in enumerate(data):
        values.extend([location] * value)
    return values

def main():
    watermark = MultinomialNB()
    # Training
    count = 0
    for infile in glob.glob(TRAINING_POSITIVE):
        data = get_image_data(infile)
        watermark.train((data, 'positive'))
        count += 1
        print 'Training', count
    for infile in glob.glob(TRAINING_NEGATIVE):
        data = get_image_data(infile)
        watermark.train((data, 'negative'))
        count += 1
        print 'Training', count
    # Testing
    correct, total = 0, 0
    for infile in glob.glob(TEST_POSITIVE):
        data = get_image_data(infile)
        prediction = watermark.classify(data)
        if prediction.label == 'positive':
            correct += 1
        total += 1
        print 'Testing ({0} / {1})'.format(correct, total)
    for infile in glob.glob(TEST_NEGATIVE):
        data = get_image_data(infile)
        prediction = watermark.classify(data)
        if prediction.label == 'negative':
            correct += 1
        total += 1
        print 'Testing ({0} / {1})'.format(correct, total)
    print 'Got', correct, 'out of', total, 'correct'

if __name__ == '__main__':
    main()

rawDescription: Detecting a Specific Watermark in a Photo with Python (without SciPy)


code:
import fcntl
import time
fd = open('lock_file', 'w')
fcntl.lockf(fd, fcntl.LOCK_EX)
# optionally write pid to another file so you have an indicator
# of the currently running process
print 'Hello'
time.sleep(1)

rawDescription: Creating a processing queue in python

description: Creating a processing queue in python


code:
import time
import numpy as np

#### create some sample data ####
np.random.seed(1)

V_NUM = 6000
P_NUM = 8000

size = 0.1

vertices = np.random.rand(V_NUM, 3)
points = np.random.rand(P_NUM, 3)

numpoints = np.zeros(V_NUM, np.int32)

#### brute force ####
start = time.clock()
for i in xrange(len(vertices)):
    cube=((vertices[i,0]<= points[:,0]) &
    (points[:,0]<(vertices[i,0]+size)) &
    (vertices[i,1]<= points[:,1]) &
    (points[:,1] < (vertices[i,1]+size)) &
    (vertices[i,2]<= points[:,2]) &
    (points[:,2] < (vertices[i,2]+size))
    )
    numpoints[i]=len(points[cube])

print time.clock() - start

#### KDTree ####
from scipy.spatial import cKDTree
center_vertices = vertices + [[size/2, size/2, size/2]]
start = time.clock()
tree_points = cKDTree(points)
_, result = tree_points.query(center_vertices, k=100, p = np.inf, distance_upper_bound=size/2)
numpoints2 = np.zeros(V_NUM, np.int32)
for i, neighbors in enumerate(result):
    numpoints2[i] = np.sum(neighbors!=P_NUM)

print time.clock() - start
print np.all(numpoints == numpoints2)

rawDescription: Speed up array query in Numpy/Python

description: Speed up array query in Numpy/Python


code:
class Accumulator(object):
    none = None
    def also(self, condition):
        self.none = not condition and (self.none is None or self.none)
        return condition

acc = Accumulator()
also = acc.also

if also(condition1):
    action1()
if also(condition2):
    action2()
if also(condition3):
    action3()
if also(condition4):
    action4()
if acc.none:
    print "none passed"

rawDescription: How could an "also if" be implemented in Python?


code:
def loadModule(self, moduleName):
    """
    Load the module with the give name
    i.e. "admin" would load modules/admin.py

    Args:
        moduleName (str): name of the module (admin would load the admin.py file)

    Returns:
        boolean: success or failure of load

    Raises:
        None
    """
    retLoadedCorrectly = False
    # reload everything to dynamically pick up new stuff
    reload(modules)

    # if the module was already loaded, then we need to reload it
    for cmd in self.loadedModules.keys():
        if  self.loadedModules[cmd]['module'] == moduleName:
            modules.reload(moduleName)

    # try to grab the module and get parameters from it
    try:
        # grab the module
        m = getattr(modules, moduleName)

        # save it
        self.loadedModules[m.commandName] = {'module': moduleName, 'admin': m.adminOnly, 'version': m.version}

        # Yay it loaded :)
        retLoadedCorrectly = True

        # log it
        self.log('Loaded module: {0}, {1}, {2}, {3}'.format(moduleName, m.commandName, m.adminOnly, m.version))
    except AttributeError, e:
        self.log('Failed to load module: {0}'.format(moduleName), level='WARNING')
        self.log(e, level='WARNING')

    return retLoadedCorrectly

rawDescription: How do I dynamically reload a module in a custom package?

description: Dynamically reload a module in a custom package


code:
filtered = [word for word in array if word.isalpha()]
print filtered

rawDescription: python regular expression

description: Python regular expression


code:
import array

class Secret(object):
  def __init__(self, secret=None):
    if secret is None: secret = os.urandom(16)
    self.secret = secret
    self.reset()
  def counter(self):
    for i, c in enumerate(self.current):
      self.current[i] = c + 1
      if self.current: break
    return self.current.tostring()
  def reset(self):
    self.current = array.array('B', self.secret)

secret = Secret()
crypto = AES.new(os.urandom(32), AES.MODE_CTR, counter=secret.counter)
encrypted = crypto.encrypt(16*'a' + 16*'b' + 16*'c')
secret.reset()
print crypto.decrypt(encrypted)

rawDescription: PyCrypto problem using AES+CTR

description: PyCrypto problem using AES+CTR


code:
items = sorted(a.items())
grouped = zip(*[iter(items)]*2)
print ' '.join('{} - {} , {} - {}'.format(*chain(*x)) for x in grouped)

rawDescription: How do I retrieve more than one item pair from a dictionary

description: Retrieve more than one item pair from a dictionary


code:
#resample and fill missing data
df = df.groupby(df.index).apply(lambda x: x.set_index('Bin_time').resample('100ms',how='first',fill_method='ffill'))

df = df.reset_index()
df = df.drop(['row'], axis=1)

#convert timedelta to integer back
df['Bin_time'] = (df['Bin_time'] / np.timedelta64(1, 'ms')).astype(int)

print df.head()
#  Bin_time  TRIAL_No itemnr
#0  2403950  Trial: 1    P14
#1  2404050  Trial: 1    P14
#2  2404150  Trial: 1    P14
#3  2404250  Trial: 1    P14
#4  2404350  Trial: 1    P14

rawDescription: Resampling with start and end date columns


code:
import re
p = re.compile(ur'\b\d+\w*\b')
test_str = u"he will be 60 years old today\nshe turns 79yo today this afternoon"

print re.findall(p, test_str)

rawDescription: python re match digits or digits followed by characters

description: Python re match digits or digits followed by characters


code: print titlecase(u"börek")

rawDescription: How can I use str.title with another language?

description: Use str.title with another language


code:
example.py
import argparse

class JoinAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, " ".join(values))

parser = argparse.ArgumentParser()
parser.add_argument("-copyDir", action="store_true")
parser.add_argument("-d", "--dir", nargs="+", action=JoinAction)
args = parser.parse_args()
print args.__dict__

rawDescription: Checking if quotes surround input argument


code:
mylogfile = open("test10.txt", "w+")
print >> mylogfile, 'hola'
mylogfile.flush()        #just in case
print mylogfile.read()
mylogfile.seek(0)
print mylogfile.read()

rawDescription: Unable to write to a text file

description: Unable to write to a text file


code:
def dec2hex(num):
    if num == 0:
        return 0
    ans = ""
    while num > 0:
        ans = str(num%6) + ans
        num /= 6
    return int(ans)

def hex2dec(num):
    if num == 0:
        return 0
    num = str(num)
    ans = int(num[0])
    for i in num[1:]:
        ans *= 6
        ans += int(i)
    return ans

if __name__ == '__main__':
    a = dec2hex(78)
    b = hex2dec(a)
    print a, b

rawDescription: Converting base 6 to decimal and vice versa in Python?


code:
from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):

    lasttag = None

    def handle_starttag(self, tag, attr):
        self.lasttag = tag.lower()

    def handle_data(self, data):
        if self.lasttag == "a" and data.strip():
            print data

rawDescription: Have HTMLParser differentiate between link-text and other data?


code: print ra[idx]

rawDescription: numpy recarray minimum diffrences

description: Numpy recarray minimum diffrences


code:
#!\user\bn\env python
import random,time
#Colors
BLACK = (  0,   0,   0)
WHITE =  (255, 255, 255)
BLUE =    (  0,   0, 255)
GREEN = (  0, 255,   0)
RED =      (255,   0,   0)
#default starting platform

#[  x, y, width, height, color ]
#[126, 404, 536, 33, BLACK ] ,
xco_ord = 126
yco_ord = 404
width = 536
height = 33

a = []
holder = []
level = []

while True:
    #random numbers
    gaps = random.randrange(300, 480)
    width = random.randrange(100, 700)
    height = random.randrange(28, 140)

    Uyco_ord = yco_ord  + 113
    up_height = random.randrange(yco_ord, Uyco_ord)

    Dyco_ord = yco_ord - 300
    down_height = random.randrange(Dyco_ord, yco_ord)

    up_down_choice = random.choice('DU')

    count = 0
    other_counter = 7
    while count <= other_counter:
        if up_down_choice == 'U':
            up_down_height = down_height
        if up_down_choice == 'D':
            up_down_height = up_height

        #  [30, 355, 503, 28, BLACK ]
        #===================================================================
        a.append(gaps)
        a.append(up_height)
        a.append(width)
        a.append(height)
        a.append(BLACK)
        holder.append(a)
        a = []
        count+=1
        other_counter +=1
        #===================================================================
        rgaps = gaps + 180
        gaps =random.randrange(gaps,rgaps )

        width = random.randrange(100, 700)
        height = random.randrange(28, 140)

        yco_ord = up_height
        Uyco_ord = yco_ord  + 113
        up_height = random.randrange(yco_ord, Uyco_ord)
        yco_ord = down_height
        Dyco_ord = yco_ord - 300
        down_height = random.randrange(Dyco_ord, yco_ord)
        up_down_choice = random.choice('DU')
        #===================================================================
        time.sleep(2)
        if len(level)> 25:
            time.sleep(2)
            del(block[0])
            time.sleep(2)
            del(block[1])
            time.sleep(2)
            del(block[2])
            time.sleep(2)
            del(block[3])
            time.sleep(2)
            del(block[4])

        for blocks in holder:
            level.append(blocks)
            del(holder[0])
            print '\n'
            print '\nup_down_choice: %s' % up_down_choice
            print '\n'
            print '\nlevel:'
            print level

rawDescription: Random platform generator in pygame

description: Random platform generator in pygame


code:
from django.utils import dateformat
fmt = "Y-m-d\TH:i:sO"
import datetime
now = datetime.datetime.now()
now
str = dateformat.format(now, fmt)
print str

rawDescription: How to convert seconds to hh:mm:ss with the Django's date template tag?

description: Convert seconds to hh:mm:ss with the Django's date template tag


code:
import timeit

setup='''
class MyClass(object):
    def __init__(self, arg):
        super(MyClass, self).__init__()
        self.arg = arg
args=[1,2,3,4,5]
'''

action1='''
instanceList=[]
for arg in args:
    inst=MyClass(arg)
    instanceList.append(inst)
'''
action2='''instanceList=[MyClass(arg) for arg in args]'''
action3='''map(instanceList=MyClass, args)'''

print timeit.timeit(action1, setup, number=int(1e6)) / 1e6
print timeit.timeit(action2, setup, number=int(1e6)) / 1e6
print timeit.timeit(action3, setup, number=int(1e6)) / 1e6

rawDescription: Rapid Class Declaration

description: Rapid Class Declaration


code:
from sys import exit
import lxml.html
import requests

url = 'http://www.myfxbook.com/community/outlook'
doc = requests.get(url)
root = lxml.html.fromstring(doc.text)

all_id_inputs = root.xpath("//input[starts-with(@id,'outlookTip')]/@id")

for ids in all_id_inputs:
    xpath_value = '//*[@id="{}"]/@value'.format(ids)
    table_value = root.xpath(xpath_value)
    root_table  = lxml.html.fromstring(table_value[0])

    # print table_value[0]
    # print
    firt_value      =  root_table.xpath("//table/tr[2]/td[3]/text()")
    second_value    =  root_table.xpath("//table/tr[3]/td[3]/text()")
    third_value     =   root_table.xpath("//div/text()")[1]

    print firt_value
    print second_value
    print third_value
    print

rawDescription: Python Web Scraping - trying to get numbers from table tags


code:
def get_cars(infile):
    in_car = False
    current_car = {}
    for (event, element) in lxml.etree.iterparse(infile, events=('start', 'end')):
        if event == 'start':
            if element.tag == 'Car':
                in_car = True
                current_car = {}
            continue
        if not in_car: continue
        if element.tag == 'Car':
            yield current_car
            continue
        current_car[element.tag] = element.text

for car in get_cars(infile = cStringIO.StringIO('''<root><Car><Color>Blue</Color><Make>Chevy</Make><Model/></Car></root>''')):
  print car

rawDescription: Parsing blank XML tags with LXML and Python


code:
p = re.compile(r'^#.*', re.M)
print p.search(test_str).group()

rawDescription: Python Regex starting with hashtag

description: Python Regex starting with hashtag


code:
import re

processes = ['\\\\TEST-PC\\Process(python)\\Operations/sec',
'\\\\TEST-PC\\Process(process#2)\\Operations/sec',
'\\\\TEST-PC\\Process(process#1)\\Operations/sec',
'\\\\TEST-PC\\Process(process)\\Operations/sec',
'\\\\TEST-PC\\Process(python)\\Thread Count',
'\\\\TEST-PC\\Process(process#2)\\Thread Count',
'\\\\TEST-PC\\Process(process#1)\\Thread Count',
'\\\\TEST-PC\\Process(process)\\Thread Count']

rx = re.compile(r'Process\(([^)]+)\)')

processes_filtered = []
for process in processes:
    match = rx.search(process)
    if match is not None:
        if match.group(1) not in processes_filtered:
            processes_filtered.append(match.group(1))

print processes_filtered
# ['python', 'process#2', 'process#1', 'process']

rawDescription: Python: Using Regex to create an array of non-duplicate entries


code: [obj.setStart(start).setStop(stop) for obj, start, stop in objects, starts, stops]

rawDescription: Placing variables inside a python list comprehension


code:
import re
for x in soup.find_all('a'):    # will give you all a tag
    try:
        if re.match('searchDB',x['onclick']):    # if onclick attribute exist, it will match for searchDB, if success will print
            print x['onclick']        # here you can do your stuff instead of print
    except:pass

rawDescription: Python to get onclick values

description: Python to get onclick values


code:
from itertools import combinations

for paired in (dict(p) for v in pleio.itervalues() for p in combinations(v.iteritems(), 2)):
    print paired

rawDescription: Pair combinations of elements in dictionary without repetition


code:
l = filter(lambda d: d['acronym'] == 'lol', loaded_data)
if l:
    print "found"
    print l[0]

rawDescription: Get Dictionary value Python

description: Get Dictionary value Python


code:
import itertools

def my_generator():
    yield 1
    yield 2

for i in itertools.chain(my_generator(), [5]):
    print i

rawDescription: Concatenate generator and item

description: Concatenate generator and item


code:
import subprocess

def sshcommand(command):
    return subprocess.check_output(['ssh', 'localhost', command]).splitlines()

command = raw_input("command> ")
print sshcommand(command)

rawDescription: printing output python subprocess

description: Printing output python subprocess


code:
for num in range(int(input), int(input2)):
    for j in primes:            #there is nothing in list 'primes'
        if not primes:          #this won't execute
            break               #this won't execute
        else:                   #this will execute
            if j % num ==0:     #this will execute
                break           #break if statement, repeat for loop
    for i in range(2, num):
        if num % i == 0:
            break
        else:
            primes.append(num)
            break
print primes

rawDescription: Incorrect Prime number list in python

description: Incorrect Prime number list in python


code:
import multiprocessing as mp
import sys
import os

def ask(stdin):
    print 'Your name? ',
    a = stdin.readline().strip()
    if a == 'Tester':
        print 'Hello'
    else:
        print 'Bye'
    stdin.close()

def writeFiles():
    pass

newstdin = os.fdopen(os.dup(sys.stdin.fileno()))

if __name__ == '__main__':
    p1 = mp.Process(target=writeFiles)
    p1.start()
    p2 = mp.Process(target=ask, args=(newstdin,))
    p2.start()
    p1.join()
    p2.join()

rawDescription: Raw_input inside a Python process

description: Raw_input inside a Python process


code:
def merge(**extra_kws):
    class _Merge(object):
        def __init__(self, function):
            self.extra_kws = extra_kws
            self.function = function
        def __call__(self, *args, **kws):
            kws.update(self.extra_kws)
            return self.function(*args, **kws)
    return _Merge

@merge(foo='bar')
def test(*args, **kws):
    print 'args:', args
    print 'kws:', kws

test(sun='dock')
test.extra_kws['trog'] = 'cube'
test(sun='dock')

rawDescription: Merge decorator function as class

description: Merge decorator function as class


code:
s = u"En g茅n茅ral un tr猫s bon hotel La terrasse du bar pr猫s du lobby"
s
import re
re.sub(ur'[\u4e00-\u9fa5]', '', s)

rawDescription: Cleaning text files with regex of python


code:
import re, os

mykey = open("text.txt", "r")
take = open("take.txt", "w")

print "I have opened a file object to read stuff. That is: %s" % mykey
print "I have opened a file object to write stuff. That is: %s" % take

for text in mykey:
    print "I have read the line: %s" % text
    match = re.search('"JOL":"(.+?).tr', text)
    match2 = re.search('"CRY":"(.+?).tr', text)
    match3 = re.search('"LAY":"(.+?).tr', text)
    if match:
        print >> take, match.group(1)
    elif match2:
        print >> take, match2.group(1)
    elif match3:
        print >> take, match3.group(1)

rawDescription: How to include "Elif" in "if match" command - Python

description: Include "Elif" in "if match" command - Python


code:
job_IDs = ['13453', '123', '563456'];
memory_used = ['30', '150.54', '20.6'];
memory_units = ['MB', 'GB', 'MB'];

w1=15
w2=6
w3=6
w4=3
for i in range(len(job_IDs)):
    v=memory_used[i].split('.') if '.' in memory_used[i] else  (memory_used[i], '0')

    print "Job {item:{w1}} {value[0]:>{w2}}.{value[1]:<{w3}} {units:{w4}}".format(
       item=job_IDs[i]+':', w1=w1, w2=w2,w3=w3,w4=w4, value=v, units=memory_units[i])

rawDescription: Using Python's Format Specification Mini-Language to specify or automatically determine column widths


code:
from bs4 import BeautifulSoup

data = """

            3.87 dollarsHousewares
            Brass-plated door knob

Brass-plated door knob

            410.25 dollarsHousewares
            Brass-plated door knob2

Brass-plated door knob2

"""

soup = BeautifulSoup(data)
result = []
for post in soup.select('div.post'):
    link = post.a.get('href')
    price = float(post.find('em', class_='fl').text.split(' ')[0])
    result.append({'link': link, 'price': price})

print result

rawDescription: Beautiful Soup sorting output

description: Beautiful Soup sorting output


code:
s = "Hello, my name is [lol] bob [not[really]] john[son]"
s = ''.join(c for c in s if c in '[]')
print s

rawDescription: Python 2.7 edit a string of characters

description: Python 2.7 edit a string of characters


code: print "Hello World"

rawDescription: Difference between statement and function


rawDescription: Python: adding strings from one list into a second list, themselves inside lists


code:
r,c = input.shape
output = np.zeros([r-1, c])

for i in range(0, r - 1):
    output[i] = np.abs(input[i+1] - input[i])

print output

rawDescription: Python - sobel x derivative

description: Python - sobel x derivative


code:
#find all index value in level SYMBOL
print df[~(df['INFORMATION_SURPLUS_PCT'] <= 0).values].index.get_level_values('SYMBOL')
Index([u'AAL', u'AAL', u'AAL', u'AAL', u'ADBE'], dtype='object', name=u'SYMBOL')

#get unique values of index
idx = df[~(df['INFORMATION_SURPLUS_PCT'] <= 0).values].index.get_level_values('SYMBOL').unique()
print idx
['AAL' 'ADBE']

#select all unique values
print df.loc[(idx, slice(None)),:]

rawDescription: Pandas MultiIndex: How to remove entire level that has zero positive values in specific column?


code:
target = "some_string_key1_key3_key5_key6"

some_dict = {
    ('key1', 'key2'): 'value1',
    ('key3', 'key4'): 'value2',
    ('key5',): 'value3',
    ('key6',): 'value6',
}

for k, v in some_dict.iteritems():
    target = reduce(lambda x, y: x.replace(y, v), k, target)

print target

rawDescription: Less code on multi key dictionary initialization


code: print to_json(f)

rawDescription: Easier way to create a JSON object from an SQLObject


code:
import numpy as np
from collections import Counter
a = [2, 1, 3, 1, 2, 3, 1, 2, 2, 2]
b = np.zeros((3,3))
for (x,y), c in Counter(zip(a, a[1:])).iteritems():
    b[x-1,y-1] = c
print b
array([[ 0.,  2.,  1.],
       [ 1.,  2.,  1.],
       [ 2.,  0.,  0.]])

rawDescription: Python transition matrix

description: Python transition matrix


code:
value = 'B'
row, col = map(numbertoletter, findvalue(grid, value))
print "Value '%s' found at location (%s, %s)" % (value, row, col)

rawDescription: How to search nested list grid and give lettered coordinates in Python?

description: Search nested list grid and give lettered coordinates in Python


code:
import numpy as np
import PIL

image = PIL.Image.open("14767594_in.png")

image_data = np.asarray(image)
image_data_blue = image_data[:,:,2]

median_blue = np.median(image_data_blue)

non_empty_columns = np.where(image_data_blue.max(axis=0)>median_blue)[0]
non_empty_rows = np.where(image_data_blue.max(axis=1)>median_blue)[0]

boundingBox = (min(non_empty_rows), max(non_empty_rows), min(non_empty_columns), max(non_empty_columns))

print boundingBox

rawDescription: How to detect object on images?

description: Detect object on images


code:
import requests
res = requests.get("http://localhost:5000/")
print res.text

rawDescription: [Python-Webservice]: How to return and consume on XML format on Flask


code:
def followpath(a1,a2):
    needle = 1
    path = []
    for ii,item,newneedle in zip(np.arange(a1.size)+1,a1,a2):
        if item == needle:
            path.append(ii)
            needle = newneedle
    return np.array(path) - 1

thepath = followpath(startpos,endpos)
print names[thepath]

rawDescription: Python: comparing columns in numpy

description: Python: comparing columns in numpy


code:
for x, y in zip(i, item):
    print y

rawDescription: Break out of inner loop in Python

description: Break out of inner loop in Python


code:
import numpy as np
strarray = ["535.","535.","534.68"]
floatarray = np.array(filter(None,strarray),dtype='|S10').astype(np.longdouble)
print floatarray

rawDescription: How to set precision of numpy float array when converting from string array?

description: Set precision of numpy float array when converting from string array


code:
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector
X=[1,2,3,4,5,6,7,8,9,10]
Y=[1,1,1,2,10,2,1,1,1,1]
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(X,Y,label="prova") #plot the function
#plt.legend(loc=1, ncol=1, shadow=True)
plt.xlim(min(X) * 0.9, max(X) * 1.1)
plt.ylim(min(Y) * 0.9, max(Y) * 1.1)
plt.ylabel(r'Y axis')
plt.xlabel(r'X axis')
Diz=dict(zip(X,Y)) #create a dictionary that associate X with Y
Interval=[] #interval where the user search for peaks
PeaksList=[] #list of peaks found
def onclick(xmin, xmax):
    print 'Interval: {0} - {1}'.format(xmin,xmax)
    peakY=0 #max Y value
    piccoX=0 #value of the X associate to the peak
    for i in [ j for j in X if xmin<j<xmax] :
        if Diz[i]>peakY:
            peakY=Diz[i]
            piccoX=i
    print "Peak at: %f " % piccoX
    PeaksList.append([piccoX,peakY])
    ax.annotate("picco", xy=(piccoX,peakY),  xycoords='data',
            xytext=(-50, 30), textcoords='offset points',
            arrowprops=dict(arrowstyle="->"))
    plt.draw()

span = SpanSelector(ax, onclick, 'horizontal', useblit=True,
                    rectprops=dict(alpha=0.5, facecolor='blue') )
plt.show()

rawDescription: How to interactively find and annotate local max (peaks) in matplotlib?

description: Interactively find and annotate local max (peaks) in matplotlib


code:
class matrix:
    def __getitem__(self, pos):
        x,y = pos
        return "fetching %s, %s" % (x, y)

m = matrix()
print m[1,2]

rawDescription: Possible to use more than one argument on __getitem__?


code: print [line.split() for line in open('ARCC_Challenge1.txt', 'rb')]

rawDescription: Splitting a text file into a list of lists


code: print raw_input()

rawDescription: program input redirected via python subprocess

description: Program input redirected via python subprocess


code:
for keys, values in my_dict.iteritems():
    fmt_str = ', '.join(chain(keys, *values))
    print fmt_str

rawDescription: More pythonic way for dealing with lists and dicts


rawDescription: Rename row indexes of pandas groupby object


code:
import csv
a = []

reader = csv.DictReader(open("so.csv",'rU'), dialect=csv.excel_tab, delimiter=',')
print reader
for row in reader:
    print row
    a.append(row)

print a[2]['Make']

rawDescription: How can I put a CSV file in an array?

description: Put a CSV file in an array


code:
l = list()
l.add(tuple(username, socket))

print l[0][0], l[0][1] # will print username and soket of first item

rawDescription: Python - How to store a socket and a username in a list?


code:
k = 's.data'
print [x[k] for x in r]

rawDescription: How can iterate throught a dictionary in a list in python


code:
if re.match(" *WID \d+.\d+ ;",x):
  print x

rawDescription: matching only the first variable with the value

description: Matching only the first variable with the value


rawDescription: creating a list of tuples (x, y) from a string

description: Creating a list of tuples (x, y) from a string


code:
from apiclient import errors
from apiclient.http import MediaFileUpload
# ...

def insert_file(service, title, description, parent_id, mime_type, filename):
  """Insert new file.

  Args:
    service: Drive API service instance.
    title: Title of the file to insert, including the extension.
    description: Description of the file to insert.
    parent_id: Parent folder's ID.
    mime_type: MIME type of the file to insert.
    filename: Filename of the file to insert.
  Returns:
    Inserted file metadata if successful, None otherwise.
  """
  media_body = MediaFileUpload(filename, mimetype=mime_type, resumable=True)
  body = {
    'title': title,
    'description': description,
    'mimeType': mime_type
  }
  # Set the parent folder.
  if parent_id:
    body['parents'] = [{'id': parent_id}]

  try:
    file = service.files().insert(
        body=body,
        convert=true,
        media_body=media_body).execute()

    # Uncomment the following line to print the File ID
    # print 'File ID: %s' % file['id']

    return file
  except errors.HttpError, error:
    print 'An error occured: %s' % error
    return None

rawDescription: python + google drive: upload xlsx, convert to google sheet, get sharable link

description: Python + google drive: upload xlsx, convert to google sheet, get sharable link


code:
import numpy as np
ind = np.array([[4, 5, 6],
                [0, 1, 2]])

print X[np.arange(len(ind))[:, np.newaxis], 0] - X[ind, 0]

rawDescription: Using ndarray.flatten() python for array of several arrays, Python


code:
def to_month(yyyymm):
    y, m = int(yyyymm[:4]), int(yyyymm[4:])
    return y * 12 + m

def iter_months(start, end):
    for month in range(to_month(start), to_month(end) + 1):
        y, m = divmod(month-1, 12)  # ugly fix to compensate
        yield y, m + 1              # for 12 % 12 == 0

for y, m in iter_months('201406', '201501'):
    print y, m

rawDescription: how to generate a range of yyyymm values?

description: Generate a range of yyyymm values


code:
def addname(x,y):
    dicname = {(x): (y)}
    return dicname

stocksymbol = (raw_input("what is the symbol of your stock: "))
stockname = (raw_input("what is the name of your stock: "))
dnames = addname(stocksymbol, stockname)
print dnames

rawDescription: python help me with this function

description: Python help me with this function


code:
class Item(object):
    def __init__(self, name, weight):
         self.name = name
         self.weight = weight
tempDict = {
     'flashlight' : ['flashlight',5],
}
flashlight1 = Item(*tempDict['flashlight'])
print flashlight1.name
print flashlight1.weight

rawDescription: Storing Class Arguments in a List

description: Storing Class Arguments in a List


code:
w = ['zero', 'one']
x = ['one', 'two', 'four']
y = ['two', 'three', 'five']
z = ['one', 'three', 'four']

def get_score(m, k):
    v = m[k]
    return sum(get_score(m, kk) for kk in v) + 1

m = {}
for lst in [w,x,y,z]:
    for (i,src) in enumerate(lst):
        if src not in m: m[src] = []
        for (j,dst) in enumerate(lst[i+1:]):
            m[src].append(dst)

scored_u = [(k,get_score(m,k)) for k in m]
scored_s = sorted(scored_u, key=lambda (k,s): s, reverse=True)

for (k,s) in scored_s:
    print(k,s)

rawDescription: Merge sequences of unique elements

description: Merge sequences of unique elements


code:
import sys
from PySide import QtCore, QtGui, QtNetwork
import requests

def finished(reply):
  print "Finished: ", reply.readAll()
  app.quit()

app = QtGui.QApplication(sys.argv)
url = 'http://localhost:3000/qwertytest1'
data = { 'text1': 'test1', 'text2': 'test2' }
files = {'file1': open('/tmp/1.txt') }
request = requests.Request('POST', url, data=data, files=files).prepare()
request_qt = QtNetwork.QNetworkRequest(url)
for header, value in request.headers.items():
  request_qt.setRawHeader(header, value)
manager = QtNetwork.QNetworkAccessManager()
manager.finished.connect(finished)
request = manager.post(request_qt, request.body)

sys.exit(app.exec_())

rawDescription: upload files through http post in Pyside/PyQt

description: Upload files through http post in Pyside/PyQt


code:
sub = '\w*\W*\w*\W*name\W*\w*\W*\w*'
for i in re.findall(sub, str1, re.I):
    i=i.strip(" .")
    print i

rawDescription: Finding words around a substring

description: Finding words around a substring


code:
import freebase

f = file('types.txt')
for t in f:
    t=t.strip()
    q = [{'type':t,
          'mid':None,
          'name':None,
          '/common/topic/alias':[],
          'limit':500,
          }]
    for r in freebase.mqlreaditer(q):
        print '\t'.join([t,r['mid'],r['name']]+r['/common/topic/alias'])
f.close()

rawDescription: How to use Freebase to label a very large unlabeled NLP dataset?

description: Use Freebase to label a very large unlabeled NLP dataset


code:
for result in driver.find_elements_by_css_selector("div.market_listing_row"):
    price = result.find_element_by_css_selector("div.market_listing_their_price")
    print price.text.strip()

rawDescription: Selenium Steam community market listings python


code:
import execnet

gw = execnet.makegateway("popen//python=python")
channel = gw.remote_exec("""
    from numpy import *
    a = array([2,3,4])
    channel.send(a.size)
""")

for item in channel:
    print item

rawDescription: Invoking Jython from Python (or Vice Versa)


code:
zebra = 'Yout caretak taking care of something'

count = len(re.findall(r'\w+', zebra))
words = nltk.word_tokenize(zebra)
def looper(a,count):
    print " ".join([ correct(words[i]) for i in range(len(words)) ])

rawDescription: Python Converting output into sentence

description: Python Converting output into sentence


code:
import random
def randomArray(n_Elementi, my_Vector):
    for i in range(0, n_Elementi):
        newElement=random.randint(1,500)
        my_Vector.append(newElement)
    return

def shift(seq, n):
    newElement = []
    for i in range(len(seq)):
        newElement.append(seq[(i-n) % len(seq)])
    return newElement

n_Elementi = 10
my_vector=[]
randomArray(n_Elementi, my_vector)
print my_vector
print shift (my_vector, 3)

rawDescription: Python- Shifting the position of each object to left or right in a random Array


code:
colors = ["red", "black", "blue",]
text = "Hello World"

def animate(counter):
    for index, char in enumerate(text):
        color_index = (index + counter) % len(colors)
        print "{0} - {1}".format(char, colors[color_index])
    print "Next iteration..."

#while True:
for i in range(3): # Short example loop - range(3)
    animate(i)

rawDescription: Python: Combining array elements in particular manner


code:
for list1_dict in list1:
    for x in list1_dict:
        if x in dict1:
            resultDict = {list_dict[x]: dict1[x]}
            print resultDict

rawDescription: combining a list of dictionaries with another dictionary

description: Combining a list of dictionaries with another dictionary


code:
import wget
from bs4 import BeautifulSoup
url = "https://www.facebook.com/hellomeets/events"

down = wget.download(url)

f = open(down, 'r')
htmlText = "\n".join(f.readlines())
f.close()
print htmlText

rawDescription: Python wget saves a file. how to get data in variable


code:
cnt = 0

while cnt < 10:
    print str(cnt) + " + 1 = " + str(cnt + 1)
    cnt = cnt + 1

rawDescription: Using a variable as both an integer and a string (Python)


code:
X = range(4, 7)  # List of number from 4 to 6
Y = range(2)     # List of number from 0 to 1
X
Y
X[2] = Y         # Stored 'Y' at X[2] in place of '6'
X
print X[2][0]    # '0'th index of X[2] i.e Y[0]
print X[2][1]    # '1'th index of X[2] i.e Y[1]
X[2][0] = 9      # Set '0'th index of X[2] i.e Y[0] as 9
Y[0]
Y
X

rawDescription: Explain the output of this code with nested ranges


code:
from Tkinter import *
import time
import threading

class ScaleValue:
    def __init__(self):
        self.value1 = None
        self.value2 = None

def tkinter_loop(scale):
    root=Tk()
    s1 = Scale(root, from_=0, to=42, tickinterval=8, command=lambda v: setattr(scale, 'value1', v))
    s1.set(19)
    s1.pack()
    s2 = Scale(root, from_=0, to=200, length=600, tickinterval=10, orient=HORIZONTAL, command=lambda v: setattr(scale, 'value2', v))
    s2.set(23)
    s2.pack()
    root.mainloop()

scale = ScaleValue()
threading.Thread(target=tkinter_loop, args=(scale,)).start()

# ROP
while 1:
    time.sleep(1)
    print scale.value1, scale.value2

rawDescription: Tkinter scale in realtime

description: Tkinter scale in realtime


code:
from itertools import groupby
txt = ['First paragraph', ' continues',
       '',
       'Second ', 'paragraph']
paragraphs = (list(g) for empty, g in groupby(txt, lambda l: not len(l)) if not empty)
for para in paragraphs:
    print para

rawDescription: Grouping strings by paragraph

description: Grouping strings by paragraph


code:
import re

file = open("file","r")

for line in file:
    if re.search('->',line):
        print ' '.join(re.findall('[0-9]+',line))

rawDescription: File read and processing using regular expressions


code:
import data
def function():
    print data.formations['Tight']

rawDescription: I can't but help get the idea I'm doing it all wrong (Python, again)


code:
import sys
print sys.path

rawDescription: python + from <module> + how from - import know the PATH

description: Python + from <module> + how from - import know the PATH


code:
import collections
letters = "abctk"
words = "cat back track tact".split()
letter_counts = collections.Counter(letters)
for word in words:
    word_counts = collections.Counter(word)
    if all(letter_counts.get(c, 0) >= n for c, n in word_counts.iteritems()):
        print word

rawDescription: program takes long time to calculate........recursion(python)

description: Program takes long time to calculate........recursion(python)


code:
import re

units = [ 'g', 'cup', 'kg', 'L' ]
anyUnitRE = '|'.join(units)

inputs = [ '1 banana', '100 g of sugar', '1 cup of flour' ]

for input in inputs:
  m = re.match(
    r'(?P<amount>\d{1,3})\s*'
    r'(?P<unit>(' + anyUnitRE + r')?)\s*'
    r'(?P<preposition>(of)?)\s*'
    r'(?P<name>.*)', input)
  print m and m.groupdict()

rawDescription: A regular expression using a list of words


code:
# construct list from the query by removing 'OR', 'AND'
query = "tom OR jerry OR desperate AND dan OR mickey AND mouse"
lst = [term for term in query.split() if term not in ["OR", "AND"]]

string = "cartoon dan character desperate"
print any(word in string for word in lst)

rawDescription: Determining if a query is in a string

description: Determining if a query is in a string


rawDescription: Check if certain value is contained in pandas column python


code: print form.getvalue('email')

rawDescription: How to get data from instancetype variable in python

description: Get data from instancetype variable in python


code:
import time
import sys

for i in range(4, 0, -1):
    print '\rTime left:', i,
    sys.stdout.flush()
    time.sleep(1)

rawDescription: How to alter a string after it has been printed

description: Alter a string after it has been printed


code:
my_list = ['dog', 'cat', 'bird', 'dog', 'dog']
for word in sorted(set(my_list)):
    count = my_list.count(word)
    print "{} is repeated {} time{}.".format(word, count, 's' if count > 1 else '')

rawDescription: Python item sort

description: Python item sort


code:
from bs4 import BeautifulSoup
import urllib2
import re
for i in xrange(1,461,10):
  try:
    page = urllib2.urlopen("http://cms.onlinedemos.in/directory.php?click=n&startline={}#lst".format(i))
  except urllib2.HTTPError:
    continue
  else:
    pass
  finally:
    soup = BeautifulSoup(page)
    td1=soup.findAll('td', {'class':'comtext'})
    td2 = soup.findAll('td',{'class':'comuser'})
    td345 = soup.findAll('td',{'class':'com'})
    #for td3, td4, and td5, use slicing method: s[i:j:k] slice of s from i to j with step k
    td3 = td345[0::3]
    td4 = td345[1::3]
    td5 = td345[2::3]
    for td1s, td2s, td3s, td4s, td5s in zip(td1,td2,td3,td4,td5):
      data = [re.sub('\s+', ' ', text).strip().encode('utf8').replace(",", "") for text in td1s.find_all(text=True) + td2s.find_all(text=True) + td3s.find_all(text=True) + td4s.find_all(text=True) + td5s.find_all(text=True) if text.strip()]
      print ', '.join(data)

rawDescription: scraping using BS4 python

description: Scraping using BS4 python


code:
data = validLine.parseString(t)
print "%(key)s: %(title)s, %(qty)d in stock at $%(price).2f" % data
print data.qty*data.price

rawDescription: Verify CSV against given format

description: Verify CSV against given format


code:
a = 'hello'
try:
    print a[6:]
except:
    pass

rawDescription: Python: how to ignore 'substring not found' error


rawDescription: Using regex for mutliple lines

description: Using regex for mutliple lines


code:
import pandas as pd
import csv

top = pd.read_csv("flu.csv", nrows=1)
headers = top.columns.values

with open("flu.csv", "r") as f, open("flu2.csv","w") as g:
    last_line = f.readlines()[-1].strip().split(",")
    c = csv.writer(g)
    c.writerow(headers)
    c.writerow(last_line)

bottom = pd.read_csv("flu2.csv")
concatenated = pd.concat([top, bottom])
concatenated.reset_index(inplace=True, drop=True)

print concatenated

rawDescription: Python pandas DataFrame from first and last row of csv


code:
class Mixin(object):
    def __getattribute__ (self, attr):
        print self, "getting", attr
        return object.__getattribute__(self, attr)

rawDescription: Mixin class to trace attribute requests - __attribute__ recursion


code:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

rawDescription: Parsing a YAML file in Python, and accessing the data?


code:
data = []
prompt = "Please input text (Q to quit):\n"
while True:
    if data:
        A = raw_input()
    else:
        A = raw_input(prompt)
    while len(A) == 0:
        A = raw_input(prompt)
    if len(A) == 1 and A[0].lower() == "q":
        break
    data.append(A)

for A in data:
    print "%s - %i" % (A, len(A))

rawDescription: python only recognizes first line of my input

description: Python only recognizes first line of my input


code: print sumsqrt()  # call the function and print what it returns.

rawDescription: my script prints the function without calling the function

description: My script prints the function without calling the function


code:
text = 'This is a dummy dummy text'

def callback(m):
    string = m.group()
    subst = string.upper()
    start = m.start()
    question = 'subst {:s} at pos {:d}:'.format(string, start)
    ans = raw_input(question)
    if ans[0] in 'Yy':
        return subst
    else:
        return string

print re.sub(r'\bdummy\b', callback, text)

rawDescription: Add confirmation to search and replace using regex in Python


code:
def f(group):
    group['pct']=group['value'].pct_change(periods=1)*100
    return group
print df.groupby('country').apply(f)

rawDescription: Combine groups after iteration

description: Combine groups after iteration


code:
for location in api_calls:
     for business in location['businesses']:
         print business['name'], business['phone']

rawDescription: Looping over dictionary python

description: Looping over dictionary python


code:
string = '\\n    this is a docstring for\\n    the main function.\\n    a,\\n    b,\\n    c\\n    '
string.decode('string_escape')
print string.decode('string_escape')
'\\t\\n\\r\\xa0\\040'.decode('string_escape')

rawDescription: How to convert a python string

description: Convert a python string


code:
from types import FunctionType

new_args = {"x":10, "y":20}

def process(func):
    def new_func(*args, **kw):
        temp_func = FunctionType(func.func_code,
                                 new_args,
                                 func.func_name,
                                 func.func_defaults,
                                 func.func_closure)
        return temp_func(*args, **kw)
    return new_func

@process
def foo():
    global x, y
    print x + y

rawDescription: Prepend function call in other function in Python


rawDescription: Calculating element with most occurrences in list


code:
# Echo client program
import socket
import sys

HOST = ''    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall(sys.argv[1])
data = s.recv(1024)
s.close()
print 'Received', repr(data)

rawDescription: improving speed of Python module import

description: Improving speed of Python module import


code:
tmp = np.eye(3)
offsets = np.concatenate((tmp, -tmp, [[0, 0, 0]]), 0).astype(int)[:, None, :]

def fast_cF2(cArr, cEDA):
    cArr = cArr[:, 1:4]
    t = cArr[None,:,:] + offsets
    X0, Y0, Z0 = t[:, 0, :].T
    X1, Y1, Z1 = t[:, 1, :].T

    d1 = 0.4799/np.linalg.norm(t[:, 0, :] - cArr[1], axis=1)
    d0 = 0.4799/np.linalg.norm(t[:, 1, :] - cArr[0], axis=1)

    cEDA[X0, Y0, Z0, 0] = cEDA[X0, Y0, Z0, -2] - d1
    cEDA[X1, Y1, Z1, 1] = cEDA[X1, Y1, Z1, -2] + d0
    return cEDA

np.random.seed(42)
cArr = np.random.randint(0, 100, (2, 5))
cEDA = np.random.rand(100, 100, 100, 4)
r2 = fast_cF2(cArr, cEDA)
print np.allclose(r1, r2)

rawDescription: Using NumPy in the correct way to apply a function to specific points in an array


code:
log_lines =[('2014-01-28 16:54:58', 'LOGON', 'jane', 'machinename'),
('2014-01-28 17:50:18', 'LOGOFF', 'jane', 'machinename'),
('2014-01-28 19:53:02', 'LOGON', 'skip', 'machinename'),
('2014-01-28 19:54:12', 'LOGOFF', 'skip', 'machinename'),
('2014-01-29 09:41:52', 'LOGON', 'jim', 'machinename'),
('2014-01-29 09:42:45', 'LOGOFF', 'jim', 'machinename'),
('2014-01-29 11:59:20', 'LOGON', 'skip', 'machinename'),
('2014-01-29 12:00:52', 'LOGOFF', 'skip', 'machinename'),
# Following are made up, weird logs
('2014-01-29 12:00:52', 'LOGOFF', 'dooz', 'machinename'),
('2014-01-29 12:00:52', 'LOGOFF', 'booz', 'machinename'),
('2014-01-29 12:00:52', 'LOGON', 'fooz', 'machinename'),]

from pprint import pprint

logged_in = {}
transactions_matched = []
transactions_weird = []
for line in log_lines:
    action = line[1]
    user = line[2]
    if action == 'LOGON':
        if user not in logged_in:
            logged_in[user] = line
        else: # Abnormal case 1: LOGON again when the user is already LOGON
            transactions_weird.append(logged_in.pop(user))
            logged_in[user] = line
    elif action == 'LOGOFF':
        if user in logged_in:
            transactions_matched.append((logged_in.pop(user), line))
        else: # Abnormal case 2: LOGOFF when the user is never LOGIN yet
            transactions_weird.append(line)

# Dangling log-in actions, considered as abnormal
transactions_weird.extend(logged_in.values())

print 'Matched:'
pprint(transactions_matched)
print 'Weird:'
pprint(transactions_weird)

rawDescription: (python) find matching loglines

description: (python) find matching loglines


code: print response.registers[2]

rawDescription: Reading registers with pymodbus

description: Reading registers with pymodbus


code:
def Max(maxValue):
    def checkMax(value):
        return value <= maxValue
    checkMax.__doc__ = "Value must be less than or equal to " + str(maxValue)
    return checkMax

def Even():
    def checkEven(value):
        "Value must be even"
        return value%2 == 0
    return checkEven

def constrain_field(*constraints):
    def constraint_decorator(setter):
        def checkConstraints(self, value):
            ok = True
            for c in constraints:
                if not c(value):
                    ok = False
                    print "Constraint breached: " + c.__doc__
            if ok:
                setter(self, value)
        return checkConstraints
    return constraint_decorator

class Demo(object):
    def __init__(self):
        self._count = 2

    @property
    def count(self):
        return self._count

    @count.setter
    @constrain_field(Max(9), Even())
    def count(self, value):
        self._count = value

d = Demo()
print "Setting to 8"
d.count = 8
print "Setting to 9"
d.count = 9
print "Setting to 10"
d.count = 10
print "Count is now " + str(d.count)

rawDescription: Inherited but not shared (static) class members in Python


code:
import sqlite3
import pandas as pd

conn = sqlite3.connect(':memory:')
c = conn.cursor()

c.execute('create table stu ( ID, Name, ShoeSize, Course, IQ, Partner )')
conn.commit()
c.executemany('insert into stu VALUES (?, ?, ?, ?, ?, ?)',
    [(1234567890, u'John Doe', 3852, u'DEGR-AA', 4, None),
     (1234567890, u'John Doe', 3852, u'DEGR-AA', 4, None),
     (1234567890, u'John Doe', 3852, u'DEGR-AA', 4, None),
     (1234567890, u'John Doe', 3852, u'DEGR-AA', 4, None),
     (1234567890, u'John Doe', 3852, u'DEGR-AA', 4, None),
     (1234567890, u'John Doe', 3852, u'DEGR-AA', 4, None),
     (1234567890, u'John Doe', 3852, u'DEGR-AA', 4, None),
     (1234567890, u'John Doe', 3852, u'DEGR-AA', 4, None),
     (1234567890, u'John Doe', 3852, u'DEGR-AA', 4, None),
     (1234567890, u'John Doe', 3852, u'DEGR-AA', 4, None)])
conn.commit()

# Ugly way
print list(c.execute("SELECT * FROM stu"))

# Pretty way
print pd.read_sql_query("SELECT * FROM stu", conn)

rawDescription: Printing a properly formatted SQLite table in Python