code:
from contextlib import contextmanager
import importlib
import random
import sys

MODULE_NAME = 'statictest'
NUM_INSTANCES = 4
instances = []

# initialize module instances
for _ in xrange(NUM_INSTANCES):
    if MODULE_NAME in sys.modules:
        del sys.modules[MODULE_NAME]

    module = importlib.import_module(MODULE_NAME)
    for _ in xrange(random.randrange(10)): # call testcount a random # of times
        module.Test.testcount()

    instances.append(sys.modules[MODULE_NAME])

@contextmanager
def statictest_inst(n):
    save = sys.modules[MODULE_NAME]
    sys.modules[MODULE_NAME] = instances[n]
    yield instances[n]
    sys.modules[MODULE_NAME] = save

def get_counts():
    counts = []
    for i in xrange(NUM_INSTANCES):
        with statictest_inst(i) as inst:
            counts.append(inst.count)
    return counts

print 'initial counts', get_counts()

choice = random.randrange(NUM_INSTANCES)
print 'calling instance[{}].testcount()'.format(choice)
with statictest_inst(choice) as inst: # use context manager
    inst.Test.testcount()

print 'counts after updating one of them', get_counts()

rawDescription: Multiple instances of a global module variable?


code:
import lxml.etree
import urllib2
url='http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true'
doc = lxml.etree.parse( urllib2.urlopen(url) ).getroot()
print dict(((elt.tag,elt.text) for elt in doc))

rawDescription: What's an easy and fast way to put returned XML data into a dict?


code:
for x in chapters:
    print x
    if x == chapters[-1]:
       break
    print 'next'

rawDescription: Python for loop break on the last iteration using slicing


code:
import multiprocessing
import math

print "Reading mptest.py file"
def mp_factorizer(nums, nprocs):

    out_q = multiprocessing.Queue()
    chunksize = int(math.ceil(len(nums) / float(nprocs)))
    procs = []
    for i in range(nprocs):

        p = multiprocessing.Process(
                target=worker,
                args=(nums[chunksize * i:chunksize * (i + 1)],
                      out_q))
        procs.append(p)
        p.start()

    # Collect all results into a single result dict. We know how many dicts
    # with results to expect.
    resultlist = []
    for i in range(nprocs):
        temp=out_q.get()
        index =0
        #print temp
        for i in temp:
            resultlist.append(temp[index][0][0:])
            index +=1

    # Wait for all worker processes to finish
    for p in procs:
        p.join()
        resultlist2 = [x for x in resultlist if x != []]
    return resultlist2

def worker(nums, out_q):
    """ The worker function, invoked in a process. 'nums' is a
        list of numbers to factor. The results are placed in
        a dictionary that's pushed to a queue.
    """
    outlist = []

    for n in nums:
        newnumber= n*2
        newnumberasstring = str(newnumber)
        if newnumber:
            outlist.append(newnumberasstring)
    out_q.put(outlist)

rawDescription: using multiprocessing in a sub process

description: Using multiprocessing in a sub process


code:
config = wx.Config("StackOverflowTest")
print config.Read("testdata")

rawDescription: wxPython - Save Items in ListCtrl

description: WxPython - Save Items in ListCtrl


code: print '*', # note the trailing comma

rawDescription: Hollow Diamond in python

description: Hollow Diamond in python


code:
dict_dict = {'dict1':dict1, 'dicta':dicta, 'dict666':dict666}

for name,dict_ in dict_dict.items():
    print 'the name of the dictionary is ', name
    print 'the dictionary looks like ', dict_

rawDescription: Get name of dictionary

description: Get name of dictionary


code:
import numpy
import os, sys
import math
import fileinput
from random import random

######
run_mode = "s" # or you can change it to "i"
######

class generalSim (object):

    def __init__(self,KVDir):
        self.KVDir = KVDir

    def calcIList(self,params):
        n = 0
        iList = numpy.zeros(shape = (1))
        for line in fileinput.input([self.KVDir]):
            iList.resize(n+1)
            kvAs = line.split(",")
            kvAx = {kvA.split('=')[0]:float(kvA.split('=')[1]) for kvA in kvAs}
            iList[n] = intFn(kvAx,params)
            sys.stdout.write(str(n)+"\r")
            sys.stdout.flush()
            n+=1

        return iList

    def simulate(self,nTrueDir,inputKVDir,outputWeightDir,iList,iMax):

        nTrueList = [((1.0/(iList.shape[0]))*(iList.sum(0)))]
        numpy.save(nTrueDir,nTrueList)

        wList=iList[:]/iMax

        wnList=numpy.zeros(shape=(wList.shape[0]))

        for wn in range(len(wList)):
            if wList[wn]>random():
                wnList[wn] = 1

        numpy.save(outputWeightDir,wnList)

def intFn(kVars,params): # Do not change the name of this function
    sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(1000.)**2))
    I = 4*((numpy.sin((numpy.pi*.7*sinTh)/.0006)/((.7*sinTh)/.0006))**2)*numpy.cos((numpy.pi*1.2*sinTh)/.0006)**2

    if not math.isnan(I):
        return I
    else:
        print 'Hello'
        return 0.0

'''
sinTh = kVars['y']/(numpy.sqrt(kVars['y']**2+(params['R0'])**2))
A1 = numpy.complex(params['A1r'],params['A1i'])*numpy.e**(((-numpy.pi*params['p']*sinTh)/.0006)*1j)
A2 = numpy.complex(params['A2r'],params['A2i'])*numpy.e**(((numpy.pi*params['p']*sinTh)/.0006)*1j)
return (A1+A2)*numpy.conjugate(A1+A2)
'''

def simFn():
    """
        This is the function that will do the actual simulating. Fill out the filepaths below.
    """
    nTrueDir="./data/nTrueSF.npy"#Location to save the nTrue File
    inputKVDir="./data/flatY.txt"#Loaction of the Generated MC KV text File
    outputWeightDir="./data/wnListSF.npy"#Location where the weighted mask file will be saved

    iList = numpy.load("./data/iListSF.npy")#Location of the list of intensities.

    iMax = iList.max()
    print iMax
    gS.simulate(nTrueDir,inputKVDir,outputWeightDir,iList,iMax)

inputKVDir="./data/FlatY.txt"#Loaction of the Generated MC KV File(Same as above)

gS = generalSim(KVDir = inputKVDir)

####
if run_mode == "i":
    numpy.save("./data/iListSF.npy",gS.calcIList({'A2r': 186.55622562665766, 'R0': 1000.0, 'A1r': 186.5549385015023, 'p': 1.2010987369259563, 'A2i': 0.0, 'A1i': 0.4681942082158097}))

elif run_mode == "s":
    simFn()
####

rawDescription: Python: Cannot import name/IndexError: List index out of range


code:
import types

class DecoMeta(type):
   def __new__(cls, name, bases, attrs):

      for attr_name, attr_value in attrs.iteritems():
         if isinstance(attr_value, types.FunctionType):
            attrs[attr_name] = cls.deco(attr_value)

      return super(DecoMeta, cls).__new__(cls, name, bases, attrs)

   @classmethod
   def deco(cls, func):
      def wrapper(*args, **kwargs):
         print "before",func.func_name
         func(*args, **kwargs)
         print "after",func.func_name
      return wrapper

class MyKlass(object):
   __metaclass__ = DecoMeta

   def func1(self):
      pass

MyKlass().func1()

rawDescription: python apply decorator to every method in a class without inspect

description: Python apply decorator to every method in a class without inspect


code: print int(getPrintUnicode(BeautifulSoup('15	 	')))

rawDescription: detecting numbers in an html file using python 3.2

description: Detecting numbers in an html file using python 3.2


code:
def recursive_crawler(url, crawled):
    if len(crawled) >= 500:
        return
    print url
    page_source = urlopen(page)
    s = page_source.read()

    #write to file here, if desired

    soup = BeautifulSoup(s)
    for link in soup.find_all('a', href=True):
        a = link['href']
        if a != url and a.startswith("http") and a not in crawled:
            crawled.add(a)
            recursive_crawler(a, crawled)

rawDescription: Cannot Write Web Crawler in Python

description: Cannot Write Web Crawler in Python


code:
from bs4 import BeautifulSoup
from bs4.dammit import EntitySubstitution

def custom_formatter(string):
    """add " and ' to entity substitution"""
    return EntitySubstitution.substitute_html(string).replace('"','"').replace("'",''')

input_file = '''<tag1>
  <tag2 attr1="a1">" example text "</tag2>
  <tag3>
    <tag4 attr2="a2">" example text "</tag4>
    <tag5>
      <tag6 attr3="a3">' example text '</tag6>
    </tag5>
  </tag3>
</tag1>
'''

soup = BeautifulSoup(input_file, "xml")

print soup.encode(formatter=custom_formatter)

rawDescription: How to retain " and ' while parsing xml using bs4 python

description: Retain " and ' while parsing xml using bs4 python


code:
import re
from collections import defaultdict

dct = {}

str="MOSES_INI_FILE_CONTENTS"

#get [weight] section
match_weight = re.search(r"\[weight][^\n]*(?:\n(?!$|\n)[^\n]*)*", str) # Regex is identical to "(?s)\[weight].*?(?:$|\n\n)"
if match_weight:
    weight = match_weight.group() # get the [weight] text
    dct = dict([(x[0], [float(x) for x in x[1].split(" ")]) for x in  re.findall(r"(\w+)\s*=\s*(.*)\s*", weight)])

print dct

rawDescription: Parsing a Moses config file

description: Parsing a Moses config file


code:
class MovementActuator:
    def __init__(self, x=0, y=0):
        self.x, self.y = (x, y)

    def move(self, x, y):
        print 'Moving to', x, y
        self.x, self.y = (x, y)

    def get_position(self):
        return (self.x, self.y)

class CommunicationActuator:
    def communicate(self):
        return 'Hey you out there!'

class CompositeActuator:
    component_actuators = []

    def __init__(self, component_actuators=None):
        component_actuators = component_actuators \
            or self.component_actuators
        self.actuators = [cls() for cls in component_actuators]

    def __getattr__(self, attr_name):
        """Look for value in component sensors."""
        for actuator in self.actuators:
            if hasattr(actuator, attr_name):
                return getattr(actuator, attr_name)
        raise AttributeError(attr_name)

class MyCompositeActuator(CompositeActuator):
    component_actuators = [MovementActuator, CommunicationActuator]

composite_actuator = MyCompositeActuator()
assert composite_actuator.get_position() == (0, 0)
assert composite_actuator.communicate() == 'Hey you out there!'

rawDescription: Discussion of multiple inheritance vs Composition for a project (+other things)


code:
mydict = dict([('&' + chr(i), str(i)) for i in list(range(65, 91)) + list(range(97, 123))])

# random inserts between keys
from random import randint
rawstr = ''.join(mydict.keys())
mystr = ''
for i in range(0, len(rawstr), 2):
    mystr += chr(randint(65,91)) * randint(0,20) # insert between 0 and 20 chars

from time import time

# How many times to run each solution
rep = 10000

print 'Running %d times with string length %d and ' \
      'random inserts of lengths 0-20' % (rep, len(mystr))

# My solution
t = time()
for x in range(rep):
    for k, v in mydict.items():
        mystr.replace(k, v)
    #print(mystr)
print '%-30s' % 'Tor fixed & variable dict', time()-t

from re import sub, compile, escape

# Peter Hansen
t = time()
for x in range(rep):
    sub(r'(&[a-zA-Z])', r'%(\1)s', mystr) % mydict
print '%-30s' % 'Peter fixed & variable dict', time()-t

# Claudiu
def multiple_replace(dict, text):
    # Create a regular expression  from the dictionary keys
    regex = compile("(%s)" % "|".join(map(escape, dict.keys())))

    # For each match, look-up corresponding value in dictionary
    return regex.sub(lambda mo: dict[mo.string[mo.start():mo.end()]], text)

t = time()
for x in range(rep):
    multiple_replace(mydict, mystr)
print '%-30s' % 'Claudio variable dict', time()-t

# Claudiu - Precompiled
regex = compile("(%s)" % "|".join(map(escape, mydict.keys())))

t = time()
for x in range(rep):
    regex.sub(lambda mo: mydict[mo.string[mo.start():mo.end()]], mystr)
print '%-30s' % 'Claudio fixed dict', time()-t

# Andrew Y - variable dict
def mysubst(somestr, somedict):
  subs = somestr.split("&")
  return subs[0] + "".join(map(lambda arg: somedict["&" + arg[0:1]] + arg[1:], subs[1:]))

t = time()
for x in range(rep):
    mysubst(mystr, mydict)
print '%-30s' % 'Andrew Y variable dict', time()-t

# Andrew Y - fixed
def repl(s):
  return mydict["&"+s[0:1]] + s[1:]

t = time()
for x in range(rep):
    subs = mystr.split("&")
    res = subs[0] + "".join(map(repl, subs[1:]))
print '%-30s' % 'Andrew Y fixed dict', time()-t

rawDescription: Mass string replace in python?

description: Mass string replace in python


code:
from itertools import groupby

str_ = '  d     A7    g7'

for k, g in groupby(enumerate(str_), lambda x: not x[1].isspace()):
    if k:
        pos, first_item = next(g)
        print pos, first_item + ''.join([x for _, x in g])

rawDescription: Python: split string and get position

description: Python: split string and get position


code:
theIP = re.search(r"\d{1,3}\.\d{1,3}\.\d{1,3}.\d{1,3}", request)
if theIP and (theIP.group() == '211.125.122.192'):
    print "You are OK"
else:
    print "BAAD"

rawDescription: Python newbie, equal to a string?

description: Python newbie, equal to a string


code:
import operator
multiadd = lambda a,b: map(operator.add, a,b)
print multiadd([1,2,3], [2,3,4]) #=> [3, 5, 7]

rawDescription: correct style for element-wise operations on lists without numpy (python)

description: Correct style for element-wise operations on lists without numpy (python)


rawDescription: appropriate data structure for sorting a multi dimensional array in python?

description: Appropriate data structure for sorting a multi dimensional array in python


code:
class A(object) :
    def __init__(self, args):
        self.a = 'a'
        self.args = args

    def getattA(self):
        return self.a, self.args

class B(object) :
    b = 'b'
    def __init__(self, args) :
        self.b_init = args

    def getattB(self):
        return self.b

C = type('C', (A,B), dict(c='c'))

instc = C('args')

print 'attributes :', instc.a,  instc.args, instc.b, instc.c
print 'methodes :', instc.getattA(), instc.getattB()

print instc.b_init

rawDescription: Python : How to "merge" two class

description: Python : How to "merge" two class


code:
import requests

r = requests.get('https://github.com/timeline.json', timeout=5, stream=True)

maxsize = 100000
content = ''
for chunk in r.iter_content(2048):
    content += chunk
    if len(content) > maxsize:
        r.close()
        raise ValueError('Response too large')

print content
print json.loads(content)

rawDescription: http request with timeout, maximum size and connection pooling

description: Http request with timeout, maximum size and connection pooling


code:
import threading
import time

boolean = False

class ThreadClass(threading.Thread):
    def __init__(self):
        super(ThreadClass, self).__init__()

    def run(self):
        global boolean
        for i in range(6):
            print str(i), boolean
            time.sleep(1)

t = ThreadClass().start()
time.sleep(3)
boolean = True
print 'end script'

rawDescription: Global variable in thread class does not update


code:
l, b = [1,1,1,1,1,1], ['-', 2, 2, 2, '-', 2, 2, 2]
from itertools import izip_longest
print [e for items in izip_longest(l,b) for e in items if e != None and e != '-']

rawDescription: Python - alternating lists

description: Python - alternating lists


code:
Python
import base64
import cStringIO
import gzip

f = open('test','rb')
s = base64.standard_b64decode(f.read())
buff = cStringIO.StringIO(s)

with gzip.GzipFile(fileobj=buff) as gz:
    decompressed_data = gz.read()
    print decompressed_data.decode('utf-16')

rawDescription: compressing a string in C# and uncompressing in python

description: Compressing a string in C# and uncompressing in python


code:
# assuming you have something such as this:
class User(Document):
    email = TextField()

# you can use the .load() method of the User class
users = [User.load(db, uid) for uid in db]

# now you can do this:
for user in users:
    print user.id, user.email

# but you're using it in flask so, in your view you can send
# this list of users to your template using something like this:

from flask import render_template
@app.route("/users")
def show_users():
    return render_template('users.html', users=users)

rawDescription: How do I return a list as a variable in Python and use in Jinja2?

description: Return a list as a variable in Python and use in Jinja2


code:
s = "a(b,c(d,e(f,g),h(i)))"

import re

level = 0
for tok in re.finditer(r"\w+|[()]", s):
    tok = tok.group()
    if tok == "(":
        level += 1
    elif tok == ")":
        level -= 1
    else:
        print "%s%s" % (" "*level, tok)

rawDescription: simple regex for extracting chars from string with nested paranthesises

description: Simple regex for extracting chars from string with nested paranthesises


code: exec s.replace(",", "\n")

rawDescription: python - break string into variables

description: Python - break string into variables


code:
def ip_sort(key):
    """
    Assumes IP address is first element
    Splits the IP address and orders result numerically.
    """
    return [int(x) for x in key[0].split('.')]

keep = (line for line in fhand if line.startswith('Internet'))
keep = (tuple(line.split()[1::2]) for line in keep)
keep = sorted(keep, key=ip_sort)

for info in keep:
    print '%-15s %s %s' % info

rawDescription: Sort IP addresses with tuple python

description: Sort IP addresses with tuple python


code:
with open('p_match.txt') as f:
    text = f.read()
    chunks = text.split('Scanning sequence ID:')
    for chunk in chunks:
        if chunk:
            lines = chunk.split('\n')
            sequence_id = lines[0].strip()
            for line in lines:
                if line.startswith('              '):
                    start = int(line.split()[0].strip())
                    sequence = line.split()[-2].strip()
                    stop = start + len(sequence)
                    print sequence_id, start, stop

rawDescription: How to extract coordinates in P-match result?

description: Extract coordinates in P-match result


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
print soup.select('.user-info a')[0]['href']
# /kjrphotography

rawDescription: How to do Regex for a href?

description: Do Regex for a href


code:
def is_close(user,company,radius, debug=0):
    "user=(lat, lon) in degrees, company=(lat, lon), radius in m"
    from math import cos, pi, sqrt
    EarthRadius   = 6.371E6 # metre, = 6371 km
    deg2rad = pi/180.0

    # localize the equirectangular projection to the latitude
    # (the 1st coordinate) of the company
    radius_x = EarthRadius*cos(company[0]*deg2rad)
    radius_y = EarthRadius

    dx, dy = ((user[1]-company[1])*deg2rad*radius_x,
              (user[0]-company[0])*deg2rad*radius_y)
    if debug:print dx, dy, sqrt(dx*dx+dy*dy)
    return True if (dx*dx+dy*dy) <= (radius*radius) else False

rawDescription: Is the User's lat/lng inside the Company's lat/lng boundary


code:
import itertools

with open('proxies.txt') as proxies:
    with open('urls.txt') as urls:
        for (proxie, url) in itertools.product(proxies, urls):
            print "access", url.rstrip(), "using", proxie.rstrip()

rawDescription: Python: How to access a list of urls through a list of proxies?


code:
cmds = ['time', 'yep']

while True:
    inp = input('::> ')
    sinp = inp.split()
    if str(sinp[0]) in cmds:
        print('mkay.')
        print cmds.index(inp)

rawDescription: Return the position of an item in a table if it's in it. [Py 3.4]


rawDescription: comparing dicts with additional values

description: Comparing dicts with additional values


code:
f = open('test1.csv')

csv_f = csv.reader(f)

for row in csv_f:
    a = row[1]
    b = row[2]
    csv_x = csv.reader(open('test2.csv')) # assign here
    for nrow in csv_x:
        if a in nrow[0] and b in nrow[1]:
           print nrow[0]

rawDescription: python nested for loop only executes once

description: Python nested for loop only executes once


code:
import os

fileName = os.path.basename(__file__)
print fileName

rawDescription: how to pass filename to the variable in Python

description: Pass filename to the variable in Python


code:
import socket
import threading
import json

host = '0.0.0.0'
port = 1332

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(5)

def handler(client):
    print 'Recieved: %s' % client
    sock_input = client.makefile('r')
    while True:
        command = raw_input('> ')
        if command == 'exit':
            break
        print 'Sending: %s' % command
        client.sendall(command + '\n')
        print json.loads(next(sock_input))
    client.close()

def main():
    while True:
        client,addr = s.accept()
        print 'Accepted connection from: %s:%d' % (addr[0], addr[1])
        client_handler = threading.Thread(target=handler,args=(client,))
        client_handler.start()

if __name__ == '__main__':
    main()

rawDescription: TCP Server not receiving anything after initial connection. Python


code:
D_values = []  # an empty list, not dict
Average = []
for path in glob("F:\Thermal Motion\*.txt"):
    t, x, y = np.loadtxt(path, unpack=True)
    #append to list instead of dict:
    D_values.append((((x - x[0])/.115)**2 + ((y - y[0])/.155)**2)**0.5)
print D_values

rawDescription: Average of nth element of each list in a dictionary


code:
import itertools
import numpy as np

G = np.array(   # clear half of the matrix first
    [[0,0,0,0],
     [1,0,0,0],
     [1,1,0,0],
     [1,1,1,0]])
triples = []
for i in xrange(G.shape[0]):
    row = G[i,:]
    J = np.nonzero(row)[0].tolist() # combinations() with list is faster than NumPy array.
    for t1,t2 in itertools.combinations(J, 2):
        triples.append((i,t1,t2))
print triples

rawDescription: Python, Scipy: Building triplets using large adjacency matrix


code:
time = datetime.strptime(strs[:-5], "%Y-%m-%dT%H:%M:%S.%f")
time -= delta                #reduce the delta from this time object
print time
#2012-05-12 20:04:35.347000

rawDescription: Convert timestamps of "yyyy-MM-dd'T'HH:mm:ss.SSSZ" format in Python


code: print Y

rawDescription: Sklearn trying to convert string list to floats


rawDescription: print corresponding key of dictionary for each element in a set

description: Print corresponding key of dictionary for each element in a set


code:
import os

def three_tries():
    for i in range(3):
        filename = raw_input('please enter filename: ')
        try:
            infile = open(filename,'r')
            return infile
        except IOError:
            if not os.path.exists(filename): print 'File does not exist'
            else: print 'Error opening file'
    print '\nyou have exceed your three tries'
    print 'continuing without reading any file...'
    return

print 'this is a foo bar script'
print 'i am going to ask the user for a filename'
infile = three_tries()

if infile:
    # Do whatever you want with the file, e.g.
    print '\nreading file...'
    print infile.read()
else:
    print 'no file read, continuing to other stuff...'

print 'now you can continues to other parts of the program...'

rawDescription: How to limit checking of file names in python?

description: Limit checking of file names in python


code:
import django.db.backends.util

class PrintQueryWrapper(django.db.backends.util.CursorDebugWrapper):
    user_id = None
    def execute(self, sql, params=()):
        try:
            return self.cursor.execute(sql, params)
        finally:
            print self.user_id, ": ", sql

class PrintQueryMiddleware(object):
    def process_request(self, request):
        PrintQueryWrapper.user_id = request.user.pk
        django.db.backends.util.CursorDebugWrapper = PrintQueryWrapper

rawDescription: Get Django User ID Without Request Object Available


code:
print "Importing module a"
var = ""

rawDescription: How to set dynamic global variables in Python?

description: Set dynamic global variables in Python


rawDescription: How do you calculate the greatest number of repetitions in a list?

description: Calculate the greatest number of repetitions in a list


code:
from flask import Flask

app = Flask(__name__)

@app.route('/')
@app.route('/index')
def index():
    print 'index'
    return 'index'

@app.route('/<path:projectkey>')
def project(projectkey):
    print 'project'
    return 'project'

app.run(debug=True)

rawDescription: Same URL pattern calling different view functions in Flask


rawDescription: Python regex format

description: Python regex format


code:
from itertools import cycle
for i, item in enumerate(cycle([1, 2, 3])):
    print i, item

rawDescription: Is it a way to know index using itertools.cycle()?


code:
import numpy as np
from skimage.morphology import binary_dilation
# Setup
coordx = [110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 110, 100, 101, 102,
          103, 104, 105, 106, 107, 108, 109, 110]
coordy = [110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 110, 111, 112,
          113, 114, 115, 116, 117, 118, 119, 120]
img = np.random.random((128, 128))
img[110, 110] = 1.
img[109, 110] = 1.

# values grater than white_pixel will get detected as white pixels
white_pixel = 1

mask = np.zeros((128, 128), dtype=bool)
mask[coordx, coordy] = 1

structure = np.ones((7, 7))
mask = binary_dilation(mask, structure)

is_white = (img * mask) >= white_pixel

# This will tell you which pixels are white
print np.where(is_white)

# This will tell you if any pixels are white
print np.any(is_white)

rawDescription: How can i know if there are white pixels in a binary image in some coordinates (stored in a list) in python?

description: Know if there are white pixels in a binary image in some coordinates (stored in a list) in python


code:
matrix = [[4,5,6,7],[2,4,9,3]]
i=0
while i<len(matrix):
    j=0
    while j<len(matrix[i]):
        print 'i = {}, j = {}, element = {}'.format(i,j,matrix[i][j])
        print matrix[i][j]
        j=j+1
    i=i+1

rawDescription: Nested loops with matrix - why does this second matrix at all?


code:
selen_html = driver.find_element_by_class_name('suggestions').get_attribute('innerHTML')

hxs = HtmlXPathSelector(text=selen_html)
suggestions = hxs.select('//div[@class="suggestions-results"]/a/@title').extract()
for suggestion in suggestions:
    print suggestion

rawDescription: how to extract data from autocomplete box with selenium python

description: Extract data from autocomplete box with selenium python


code:
def get_operator(number, operators):
    pre = number[2:5]
    suf = int(number[5:])
    for begin, end, name in operators[pre]:
        if begin <= suf <= end:
            return name.strip()
    return Null

print get_operator("+79161234567", operators)

rawDescription: How to properly pass text file to search the data there?

description: Properly pass text file to search the data there


rawDescription: getting values from a numpy array between two points

description: Getting values from a numpy array between two points


code:
import pylab
import numpy

# Create data for plotting
t = numpy.linspace(0, 1.0, 100)
a = numpy.sin(2*numpy.pi*t)

# Set up figure
fig = pylab.figure()
ax = pylab.subplot(111)

# Plot figures
lines = []
for i in range(5):
    line = ax.plot(t, (i+1)*a, linestyle=':', picker=5, label='line%d'%(i+1))
    lines.append(line[0]) # Save plot lines

# Create legend
leg = ax.legend(bbox_to_anchor=(1.01, 1), loc=2) # Does not work as expected
#leg = ax.legend() # Works!!

# Get legend lines
leglines = leg.get_lines()
# Set event for legend lines
for line in leglines:
    line.set_picker(5)

# Create a 2 way mapping between legend lines <-> plot lines
line2leg = dict(zip(lines+leglines, leglines+lines))
count_dict = dict((l, 0) for l in lines )
# Define event function
def onpick(event):
    thisline = event.artist
    print event
    print thisline
    if thisline in lines:
        print 'lines'
        count_dict[thisline] = 0
    elif thisline in leglines:
        print 'leglines'
        thisline = line2leg[thisline]
        count_dict[thisline] += 1
    print 'added'
    if (count_dict[thisline] % 2) == 1:
        print count_dict[thisline]
        return
    print 'tested'
    if thisline.get_linestyle()==':':
        print ": -> -" # For debugging
        thisline.set_linestyle('-')
        line2leg[thisline].set_linestyle('-')
    else:
        print "- -> :" # For debugging
        thisline.set_linestyle(':')
        line2leg[thisline].set_linestyle(':')
    fig.canvas.draw()

# connect event function
fig.canvas.mpl_connect('pick_event', onpick)
pylab.show()

rawDescription: Double event registered on mouse-click if legend is outside axes


code:
from one import two
print two.__name__

rawDescription: What's the best way to retrieve the module path from the project in python?


code:
def flatten(seq,container=None):
    if container is None:
        container = []
    for s in seq:
        if hasattr(s,'__iter__'):
            flatten(s,container)
        else:
            container.append(s)
    return container

c = flatten([(1,2),(3,4),(5,[6,7,['a','b']]),['c','d',('e',['f','g','h'])]])
print c
print c.count('g')

d = flatten([[[1,(1,),((1,(1,))), [1,[1,[1,[1]]]], 1, [1, [1, (1,)]]]]])
print d
print d.count(1)

rawDescription: Nested List and count()

description: Nested List and count()


code:
from threading import Thread
from time import sleep

# Threading.
# The amount of seconds to wait before checking for an unpause condition.
# Sleeping is necessary because if we don't, we'll block the os and make the
# program look like it's frozen.
PAUSE_SLEEP = 5

# The number of iterations we want.
TOTAL_ITERATIONS = 5

class myThread(Thread):
    '''
    A thread used to do some stuff.
    '''
    def __init__(self, gui, otherStuff):
        '''
        Constructor. We pass in a reference to the GUI object we want
        to update here, as well as any other variables we want this
        thread to be aware of.
        '''
        # Construct the parent instance.
        Thread.__init__(self)

        # Store the gui, so that we can update it later.
        self.gui = gui

        # Store any other variables we want this thread to have access to.
        self.myStuff = otherStuff

        # Tracks the paused and stopped states of the thread.
        self.isPaused = False
        self.isStopped = False

    def pause(self):
        '''
        Called to pause the thread.
        '''
        self.isPaused = True

    def unpause(self):
        '''
        Called to unpause the thread.
        '''
        self.isPaused = False

    def stop(self):
        '''
        Called to stop the thread.
        '''
        self.isStopped = True

    def run(self):
        '''
        The main thread code.
        '''
        # The current iteration.
        currentIteration = 0

        # Keep going if the job is active.
        while self.isStopped == False:
            try:
                # Check for a pause.
                if self.isPaused:
                    # Sleep to let the os schedule other tasks.
                    sleep(PAUSE_SLEEP)
                    # Continue with the loop.
                    continue

                # Check to see if we're still processing the set of
                # things we want to do.
                if currentIteration < TOTAL_ITERATIONS:
                    # Do the individual thing we want to do.
                    sleep(10)
                    # Update the count.
                    currentIteration += 1
                    # Update the gui.
                    self.gui.update(currentIteration,TOTAL_ITERATIONS)
                else:
                    # Stop the loop.
                    self.isStopped = True

            except Exception as exception:
                # If anything bad happens, report the error. It won't
                # get written to stderr.
                print exception
                # Stop the loop.
                self.isStopped = True

        # Tell the gui we're done.
        self.gui.stop()

rawDescription: Help adding threading for GUI progress

description: Help adding threading for GUI progress


code: print max(value1,value2,value3) #18

rawDescription: Python Blackjack - Count Hand of Players


code:
for row in input_file:
    print row
for row in input_file:
    print row
# Nothing gets printed, the file is consumed

rawDescription: nested for loop in python not working

description: Nested for loop in python not working


code:
weather = getWeather('94043')
weather
weather['humidity']
print '%(condition)s\nTemperature %(temp_c)s C (%(temp_f)s F)\n%(humidity)s\n%(wind_condition)s' % weather

rawDescription: How to implement python to find value between xml tags?

description: Implement python to find value between xml tags


code:
i_max = 1000
sx, sy = 1000,1000
t = time.time()
for i in range(0,i_max):
    im = np.ones((sx,sy))
    if i>0:
        #stack[:,:,i] = im
        stack[i,:,:] = im
    else:
        #stack = np.empty((sx,sy,i_max))
        #stack[:,:,0] = im
        stack = np.empty((i_max, sx, sy))
        stack[0,:,:] = im
print toc(t)

rawDescription: image stack population is slow in numpy

description: Image stack population is slow in numpy


code:
import zlib
import bz2

def comptest(s):
    print 'original length:', len(s)
    print 'zlib compressed length:', len(zlib.compress(s))
    print 'bz2 compressed length:', len(bz2.compress(s))

rawDescription: Python - Compress Ascii String

description: Python - Compress Ascii String


code:
from cherrypy import request
print request.params['username']

rawDescription: How are POST and GET variables handled in Python?


code:
wordlist = words.split()
for i in xrange(0, len(wordlist), 4):
    print ' '.join(wordlist[i:i+4])

rawDescription: Pythonic way to split a line into groups of four words?


rawDescription: extracting a message from the grid by finding the co-ordinates using a cipher text

description: Extracting a message from the grid by finding the co-ordinates using a cipher text


code:
def my_func(a, b):
    print a, b

buttons = (
   # title, x, y, function name, function arguments)
   ("Hello", 0, 0, my_func, ("abc", 123)),
   ("World", 0, 1, my_func, ("xyz", 987)),
)

for btn in buttons:
   title, x, y, func_name, func_args = btn

   temp = Button(title, command=lambda func=func_name, args=func_args:func(*args) )

   temp.grid(row=y, column=x)

rawDescription: Python 2.7 Tkinter, OOP, and Callbacks

description: Python 2.7 Tkinter, OOP, and Callbacks


code:
print open('test.xml').read()
from xml.etree import ElementTree as ET
ET.parse('test.xml')

rawDescription: Identify corrupt .xml in python

description: Identify corrupt .xml in python


code:
import pymel.core as pm
import pymel.core.uitypes as pmui

modelPanelList = []
modelEditorList = pm.lsUI(editors=True)
for myModelPanel in modelEditorList:
    if myModelPanel.find('modelPanel') != -1:
        modelPanelList.append(myModelPanel)

for modelPanel in modelPanelList:
    if pmui.ModelEditor(modelPanel).getActiveView():
        try:
            # Always better to try in the case of active panel operations
            # as the active panel might not be a viewport.
            pmui.ModelEditor(modelPanel).setRendererName("ogsRenderer")
        except Exception as e:
            # Handle exception
            print e

rawDescription: How to query current viewport renderer in maya

description: Query current viewport renderer in maya


rawDescription: Reshaping an dynamic array of numbers to a fixed size


code:
def c():
    class Clone(object):
        pass

    return Clone

c1 = c()
c2 = c()
print id(c1)
print id(c2)

rawDescription: How do you clone a class in Python?

description: Clone a class in Python


code:
text = """
I have a dictionary of 2 and 3 word phrases that I want to search in rss feeds for a match.

I grab   the rss feeds, process them and they end up as a string IN a list entitled "documents".
I want to check the dictionary below and if any of the phrases in the dictionary match part of a string of text I want to return the values for the key.
I am not sure about the best way to approach this problem. Any suggestions would be greatly appreciated.
"""

ngrams = ["grab the rss", "approach this", "in"]

import re

counts = {}
for ngram in ngrams:
    words = ngram.rsplit()
    pattern = re.compile(r'%s' % "\s+".join(words),
        re.IGNORECASE)
    counts[ngram] = len(pattern.findall(text))

print counts

rawDescription: Python matching n-grams from a dictionary to a string of text


code: print '"{}"'.format(word)

rawDescription: printing double quotes around a variable

description: Printing double quotes around a variable


code:
def my_dec(func):
    def wrapped(request):
        print request.path_info
        return func(request)
    return wrapped

rawDescription: how to get the url of the view calling the decorator in the decorator?

description: Get the url of the view calling the decorator in the decorator


code:
for line in open("file"):
    if " Deposit" in line:
         line=line.rstrip()
         print line.split()

rawDescription: Removing empty items from a list (Python)


code:
N = int(raw_input())
s = []
for i in range(N):
    s.append(raw_input())
for string in s:
    print len(filter(lambda x: x in ("R","K"), string))

rawDescription: Count function counting only last line of my list


code:
for u in users:
    print u.email

rawDescription: Python newbie class design question

description: Python newbie class design question


code:
#!/usr/bin/env python
import re
string = 'something: 20 kg/ something: 120 kg'
print re.findall(r'(?<!\d)\d{1,2}\s+kg', string)

rawDescription: Regular expression to match only two numbers


code:
# Caution! untested code
result = []
process = subprocess.Popen(['sshpass', '-p', password, 'rsync', '-avz',
                            '--info=progress2', source12, destination],
                           stdout=subprocess.PIPE)
while process.poll() is None:
    line = process.stdout.readline()
    print line
    result.append(line)
print sort(result)

rawDescription: How to print progress from this code as the subprocess is running?

description: Print progress from this code as the subprocess is running


code:
def is_iambic_pentameter(line):
    line_stresses = [stress_dict[word] for word in line.split()]
    line_stresses = ''.join(line_stresses)
    return line_stresses == '0101010101'

with open('sentences.txt', 'r') as f:
    for line in f:
        line = line.rstrip()
        line = line.lower()
        if is_iambic_pentameter(line):
            print line

rawDescription: Check for iambic pentameter?

description: Check for iambic pentameter


code:
m = re.search('A{3,}$',s)
if m:
    print"A is more than 3 times at end"

rawDescription: Python - How to identify a string containing a sequence of repeated letters


code:
import re

input_list = ["file1","A","B","C","file2","D","E","F","G","H","I"]
output_list = []

for item in input_list:
    if re.match("file[0-9]+", item):
        output_list.append([item])
    else:
        output_list[-1].append(item)

print output_list

rawDescription: Split list into list of lists by regex

description: Split list into list of lists by regex


code:
def display_queryset_values(paginator_object, page_no=1):
    for item in paginator_object.page(page_no).object_list:
        print item

display_queryset_values(p, 1) #Displays 1st 5 objects
display_queryset_values(p, 2) #Displays next 5 objects

rawDescription: How can I display queryset values by x in group?

description: Display queryset values by x in group


code:
import inspect
print inspect.getframeinfo(inspect.currentframe().f_back)[2]

rawDescription: Profiling in Python: Who called the function?


code:
myString = '<section class="left span9">'
print myString.replace("<", "<!--<").replace(">", ">-->")
print myString.replace("<!--", "").replace("-->", "")

rawDescription: Sleek way of un/commenting out html tags in markdown


code:
a = 5
print eval('a + 4')

rawDescription: Math operations from string

description: Math operations from string


code:
def f(s, c, start):
    i = s.find(c, start)
    return [s] if i < 0 else f(s, c, i+1) + f(s[:i]+s[i+1:], c, i)

s = 'aAabbAA'
print f(s, 'A', 0)
# ['aAabbAA', 'aAabbA', 'aAabbA', 'aAabb', 'aabbAA', 'aabbA', 'aabbA', 'aabb']

rawDescription: Getting a list of strings with character removed in permutation


code:
class IDFactory(object):
  def __init__(self):
    self._by_id = {}
  def register(self, cls):
    self._by_id[cls.ID] = cls
    return cls

  def __call__(self, id, *args, **kwds):
    return self._by_id[id](*args, **kwds)
  # could use a from_id function instead, as above

factory = IDFactory()

@factory.register
class Base(object):
  ID = "base"

@factory.register
class A(Base):
  ID = "A"

@factory.register
class B(Base):
  ID = "B"

print factory("A")
print factory("B")

rawDescription: How to get a reference to the current class from class body?

description: Get a reference to the current class from class body


code:
etc = {'this': {'that': {'theother': 'a'}}}
find_and_replace(etc, "theother")
print etc

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


code:
import sqlite3
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE foo (bar INTEGER PRIMARY KEY AUTOINCREMENT, baz)')
c = conn.cursor()
c.execute('PRAGMA table_info("foo")')
for row in c: print row

[col[0] for col in c.description]

rawDescription: How to programmatically determine whether a column is set to AUTOINCREMENT in SQLite?

description: Programmatically determine whether a column is set to AUTOINCREMENT in SQLite


code:
import re
import os.path

def find_number_in_filename(path):
    # remove the path and the extension
    head, tail = os.path.split(path)
    head = os.path.join(head, "") # include / or \ on the end of head if it's missing
    fn, ext = os.path.splitext(tail)

    m = re.match(r"(\d+)([A-Za-z]+)$", fn)
    if m:
        prefix, suffix, num_length = head, m.group(2)+ext, len(m.group(1))
        return prefix, suffix, num_length

    m = re.match(r"([A-Za-z]+)(\d+)$", fn)
    if m:
        prefix, suffix, num_length = head+m.group(1), ext, len(m.group(2))
        return prefix, suffix, num_length

    return path, "", 0

example_paths = ("/tmp/bar14.so", "/home/someone/0000baz.txt", "/home/someone/baz00bar.zip")
for path in example_paths:
    prefix, suffix, num_length = find_number_in_filename(path)
    if num_length == 0:
        print "%s: does not match" % path
    else:
        print "%s -> %s[%d-digits]%s" % (path, prefix, num_length, suffix)

        all_numbered_versions = [("%s%0"+str(num_length)+"d%s") % (prefix, ii, suffix) for ii in range(0,10**num_length)]
        print "\t", all_numbered_versions[0], "through", all_numbered_versions[-1]

rawDescription: enumerating numbers in strings

description: Enumerating numbers in strings


code:
def floatmethod():
    a,b=3,2
    while True:
        print float(a)/b

rawDescription: In Python 2.* division which has more overhead?


code:
def nonMaximalSupress1(image,NHoodSize):
    #
    dX, dY = NHoodSize
    M, N = image.shape
    for x in range(0,M-dX+1):
        for y in range(0,N-dY+1):
            window = image[x:x+dX, y:y+dY]
            if np.sum(window)==0:
                localMax=0
            else:
                localMax = np.amax(window)
            maxCoord=np.unravel_index(np.argmax(window), window.shape) + np.array((x,y))
            #suppress everything
            image[x:x+dX, y:y+dY]=0
            #reset only the max
            if localMax > 0:
                print localMax
                print "max coord is ", maxCoord
            image[tuple(maxCoord)] = localMax
    return image

rawDescription: Non local maxima suppression in python

description: Non local maxima suppression in python


code:
s = ":dfa:sif:e"
print s[1:]

rawDescription: Remove the first character of a string

description: Remove the first character of a string


code:
import urllib2
import json

url = 'http://api.twitter.com/1/trends/44418.json'

# download the json string
json_string = urllib2.urlopen(url).read()

# de-serialize the string so that we can work with it
the_data = json.loads(json_string)

# get the list of trends
trends = the_data[0]['trends']

# print the name of each trend
for trend in trends:
    print trend['name']

rawDescription: Using Python to extract dictionary keys within a list


code:
import csv
from itertools import islice

with open(r"c:\testing.csv", "rb") as infh:
    reader = csv.reader(infh)
    for row in islice(reader, 1, 2):  # skip first, only read second row
        if row[1] == 'A1' and row[2] == 'CLIENT':
            print "yes"

rawDescription: Reading Cell from CSV, trying to truncate the code


code:
print "Please add paths, enter // to stop" # It is a good idea to tell the user how to stop the input process

l1 = [] # Create empty list
l2 = raw_input('> ') # Ideally, you should verify that the user entered a valid path (eg: are '/' allowed at the end of a path?)

while l2 != '//':
    l1.append(l2)
    l2 = raw_input('> ')

print "Your paths are: "
for path in l1:
    print path

# I am not sure what you are trying to achieve with "print l1[1].count("/")" so leaving it out

# I would suggest to print the options outside the loop, it's a matter of taste,
# but do you really want to keep printing them out?
print "Choose an option: \n\
       1. Number of subfolders of path\n\
       2. Number of folders at a specific path\n\
       3. Max depth between all folders\n\
       4. Quit\n"

choice = raw_input('Enter choice: ')

while choice!='4':
    if choice == '1':
        path = raw_input('Which path are you looking for?')
            # Calculate and print the output here

    # This is the question you asked, so I am answering how to process this step
    if choice == '2':
        level = raw_input('Which level? ') # Ideally, you should verify that the user indeed enters an int here

        # Since your python does not seem to be very advanced, let's use a simple for loop:
        num=0
        for path in l1:
            if str.count(path, '/')==int(level):
                num = num+1

        print 'Number of such paths is: ', num

    if choice == '3':
        print 'this is not yet implemented'
        # Do something

    choice = raw_input('Enter choice: ')

rawDescription: how to compare a string with each element of a list in python

description: Compare a string with each element of a list in python


code:
import time
import sys

print 'this is a text',
sys.stdout.flush()

time.sleep(1)
print '\x1b[80D'+'\x1b[K'+'Second text',
sys.stdout.flush()

rawDescription: display only one logging line

description: Display only one logging line


code:
arr = [5, 8, 2, 4]
for index, value in enumerate(arr):
    print index, value

rawDescription: Finding Index in string with recurring chars


code:
print next(soup.find('a').descendants)
print next(iter(soup.find('a')))

rawDescription: BS4: Getting text in tag

description: BS4: Getting text in tag


code:
from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):

    inlink = False
    data   = []

    def handle_starttag(self, tag, attr):
        if tag.lower() == "a" and "href" in (k.lower() for k, v in attr):
           self.inlink = True
           self.data   = []

    def handle_endtag(self, tag):
        if tag.lower() == "a":
            self.inlink = False
            print "".join(self.data)

    def handle_data(self, data):
        if self.inlink:
            self.data.append(data)

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


code:
numberOfSplChar=pathString.rfind("#") - pathString.find("#")
print numberOfSplChar

rawDescription: how do I find special character in the path string and how many times are they present

description: Find special character in the path string and how many times are they present


code:
import traceback
try:
    pass
    pass
    pass
    pass
    pass
    raise NameError("I dont like your name")
    pass
    pass
    pass
    pass
    pass
except Exception, e:
    traceback.print_exc()

rawDescription: Large try except block in Python - how to understand where was an exception?


code:
import scraperwiki
import simplejson
import urllib2
import re

QUERY = 'sw4'
RESULTS_PER_PAGE = '100'
NUM_PAGES = 10

postcode_match = re.compile('(?<![0-9A-Z])([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {0,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)(?![0-9A-Z])', re.I)

for page in range(1, NUM_PAGES+1):
    base_url = 'http://search.twitter.com/search.json?q=%s&rpp=%s&page=%s' \
         % (urllib2.quote(QUERY), RESULTS_PER_PAGE, page)
    try:
        results_json = simplejson.loads(scraperwiki.scrape(base_url))
        for result in results_json['results']:
            #print result
            data = {}
            data['id'] = result['id']
            data['text'] = result['text']
            data['location'] = scraperwiki.geo.extract_gb_postcode(result['text'])
            data['from_user'] = result['from_user']
            data['created_at'] = result['created_at']
            if data['location'] and postcode_match.search(data['text']):
                print data['location'], data['text']
                scraperwiki.sqlite.save(["id"], data)
    except:
        print 'Oh dear, failed to scrape %s' % base_url
        break

rawDescription: ScraperWiki/Python: filtering out records when property is false


code: print form.fields['answer'].widget.name

rawDescription: Set custom 'name' attribute for RadioSelect in Django


code:
from itertools import izip_longest
def zip_join2(first, second):
    return [(a or c or 0, (b or []) + (d or [])) for (a, b), (c, d) in \
              izip_longest(first, second, fillvalue=(None, None))]

print zip_join2([], [(5, [1, 2]), (6, [3, 4])])
print zip_join2([(5, [1, 2]), (6, [3, 4])], [(5, [11, 12]), (6, [13, 14])])

rawDescription: Is there a better way to build lists like this?


code:
df = pd.read_csv(StringIO(data),header=True)
print df
print df.dtypes

rawDescription: df.apply -- Only on columns of certain type

description: Df.apply -- Only on columns of certain type


code:
print max(user, key=len)
'Hello' # since 'Hello' and 'madam' are both of length 5, max just returns the first one

rawDescription: Searching a list for the longest string

description: Searching a list for the longest string


code: print '\n'.join(x.encode('ascii', 'ignore') for x in your_list)

rawDescription: Solving the unicode output in Python

description: Solving the unicode output in Python


code:
def rest(*args):
    a, b = args
    print a - b

def sum(*args):
    a, b, c, d, e = args
    print a + b + c + d + e

def run(adictio):
    for method, params in adictio.iteritems():
        method(*params)

mydictio = {rest:(3, 2), sum:(4, 5, 6, 7, 8)}

run(mydictio)

rawDescription: Running bunch of python methods on a single piece of data


code:
import time
from threading import Thread

class worker(Thread):
    def run(self):
    	for x in xrange(0,11):
    		print x
    		time.sleep(1)

class waiter(Thread):
    def run(self):
    	for x in xrange(100,103):
    		print x
    		time.sleep(5)

def run():
    worker().start()
    waiter().start()

rawDescription: time.sleep -- sleeps thread or process?

description: Time.sleep -- sleeps thread or process


rawDescription: Checking for overlap between time spans

description: Checking for overlap between time spans


code:
import Tkinter as tk

def swapsies():
    oldfg = label.cget("foreground")
    oldbg = label.cget("background")
    label.config(background=oldfg, foreground=oldbg)
    print "Foreground: {0} Background: {1}".format(oldfg, oldbg)

root = tk.Tk()
label = tk.Label(root, text="Hello there", background="#000000", foreground="#ffffff")
label.pack(side=tk.LEFT)
mega_button = tk.Button(root, text="GO!", command=swapsies)
mega_button.pack(side=tk.LEFT)

root.mainloop()

rawDescription: How to get a value for "foreground" in tkinter/ttk python?

description: Get a value for "foreground" in tkinter/ttk python


code:
import urllib
from bs4 import BeautifulSoup

url="http://www.consilium.europa.eu/uedocs/cms_data/docs/pressdata/en/ecofin/5923en8.htm"
soup=BeautifulSoup(urllib.urlopen(url))

for item in soup.find_all('p'):
    if item.text.startswith('Commission'):
        break
    else:
        print item.text

rawDescription: beautifulsoup with an invalid html document

description: Beautifulsoup with an invalid html document


code:
data = '''2,2,2
3,3,3
6,6,6
0,0,3
4,4,4
0,0,6'''

from StringIO import StringIO

import csv

#f = open('filename.csv')
#csv_reader = csv.reader(f)

csv_reader = csv.reader(StringIO(data))

rows = list(csv_reader)

#print rows

for index_a, a in enumerate(rows[:-1]):
    for index_b, b in enumerate(rows[index_a+1:], index_a+1):
        if a[2] == b[2] :
            print "the same:", index_a, index_b, a, b

rawDescription: CSV rows and columns calculating

description: CSV rows and columns calculating


code:
import datetime
import collections

raw_data = [
{'name':'AB', 'date':datetime.date(2012, 10, 2), 'price': 23.80},
{'name':'AB', 'date':datetime.date(2012, 10, 3), 'price': 23.72},
{'name':'AB', 'date':datetime.date(2012, 10, 4), 'price': 25.90},
{'name':'AB', 'date':datetime.date(2012, 10, 5), 'price': 29.95}
]

#all unique names in raw_data
names = set(row["name"] for row in raw_data)
#lowest prices, keyed by name
lowestPrices = {name: min(row["price"] for row in raw_data) for name in names}

for row in raw_data:
    name = row["name"]
    lowestPrice = lowestPrices[name]
    price = row["price"]
    percentage = ((price/lowestPrice)-1)*100
    row["percentage"] = percentage

print raw_data

rawDescription: Calculating percentage based on python dictionaries


code:
class BankAccount(object):
    def __init__(self, customer_name, balance):
        self.customer_name = customer_name
        self.balance = balance
    def get_interest(self):
        return self.balance / 100

my_savings = BankAccount("Tom", 500)
print "I would get %d interest now" % my_savings.get_interest()
# Deposit some money
my_savings.balance += 100
print "I added more money, my interest changed to %d" % my_savings.get_interest()

rawDescription: Python classes self.variables

description: Python classes self.variables


code:
class Lc:

    d={50:8,100:6,200:4,500:3,1000:2,2000:1}
    he=['container_size_in_ltrs','qty']

    def add_inv(self,k,v):
        d=self.d
        for i,j in d.items():
            if k==i:
                d[k]=d[k]+v
        print d
        return d

z=Lc()
x=Lc()

print "Add 2 to 500, expect 500:5"
g=z.add_inv(500,2)
print z.d

# Notice that x.add_inv also modifies z.d
print "Add 5 to 500, expect 500:7 because x initialized d again"
h=x.add_inv(500,2)
print z.d

rawDescription: Global variable does not update?

description: Global variable does not update


code:
# expensive imports
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import scipy.ndimage
import scipy.signal
import sys
import os

# Echo server program
import socket

HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while 1:
    conn, addr = s.accept()
    print 'Connected by', addr
    data = conn.recv(1024)
    if not data: break
    conn.sendall("PLOTTING:" + data)
    # update plot
    conn.close()

rawDescription: improving speed of Python module import

description: Improving speed of Python module import


code:
def removew(d):
  for k, v in d.iteritems():
    if isinstance(v, dict):
      removew(v)
    else:
      d[k]=v.strip()

removew(dict1)
print dict1

rawDescription: Remove white spaces from dict : Python

description: Remove white spaces from dict : Python


code:
class A(object):
    clsVar = 'a'
    @classmethod
    def clsMeth(cls):
        print 'changing clsVar'
        cls.clsVar = 'b'
A.clsMeth()
A.clsVar

rawDescription: Python Class Variable Initialization

description: Python Class Variable Initialization


code:
for m, l in zip(matching, L):
    if m:
        print l

rawDescription: to check a condition for all the items in two list in python

description: To check a condition for all the items in two list in python


code:
directions = ['UP 5', 'DOWN 3', 'LEFT 3', 'RIGHT 2', 'UP 2', 'LEFT 1']
print calculate_distance(directions)
# prints 4.47213595499958

rawDescription: Function that calculates distance based on a set of instructions


code:
a = ['http://www.yahoo.com', 'http://www.google.net', 'gorilla', 'house.com', 'i love the net very much']
b = ['com', 'http', 'net']
print list(set([i for i in a for j in b if j in i]))

rawDescription: match any of string in list b with list a. a is a long sentences

description: Match any of string in list b with list a. a is a long sentences


code:
data = """Name\tHour\tLocation
A\t4\tSan Fransisco
B\t2\tNew York
C\t4\tNew York
D\t7\tDenton
E\t8\tBoston
F\t1\tBoston
"""

import csv
import StringIO
from collections import Counter

input_stream = StringIO.StringIO(data)
reader = csv.reader(input_stream, delimiter='\t')

reader.next() #skip header
cities = [row[2] for row in reader]

for (k,v) in Counter(cities).iteritems():
    print "%s appears %d times" % (k, v)

rawDescription: Count the frequency of words from a column in Python


code:
from gi.repository import GLib, GObject

counter = 0

def callback(*args):
    global counter
    counter += 1
    print 'callback called', counter
    if counter > 10:
        print 'last call'
        return False

    return True

def terminate(*args):
    print 'Bye bye'
    loop.quit()

GObject.timeout_add(100, callback)
GObject.timeout_add(3000, terminate)
loop = GLib.MainLoop()
loop.run()

rawDescription: GTK main blocks -- Python

description: GTK main blocks -- Python


code:
dic={'BOB':  [['AUDI', 'BLACK', 'PETROL'],
          ['MINI', 'PINK', 'PETROL'],
          ['VW', 'BLUE', 'DIESEL']],
 'DAVE': [['BMW', 'PURPLE', 'PETROL'],
          ['VOLVO', 'GREY', 'PETROL']]}
dic1={'TYRE': 'RUBBER', 'ALLOY': 17, 'SUNROOF': 'YES'}
for x in dic:
    for y in dic[x]:
        y.append(dic1)
print dic

rawDescription: Append a Dict to a Dict

description: Append a Dict to a Dict


code:
print "1) Add"
print "2) Substract"
print "3) Multiply"
print "4) Divide"
print "5) Exit"
while True:
    x=input("Choose an operation: ")
    # ...

rawDescription: How to go back to a specific line

description: Go back to a specific line


code:
d = {item1:item2 for item1, item2 in reflist}
print [item + [d.get(item[1])] for item in testlist]
# [['asd', 7, 2], ['bla', 5, 948], ['hi', 3, 123]]

rawDescription: How to compare one value from a list of lists to another value from a list of lists in Python

description: Compare one value from a list of lists to another value from a list of lists in Python


code:
import json
with open('<MyFilePath>\usTweets0.json', 'r') as f:
    tweet_sample = json.load(f)

rawDescription: Python: Import Tweet unicode data to pandas data frame object


code:
df.dropna(subset=['Tenant'], inplace=True)
print df

rawDescription: Python Pandas DataFrame remove Empty Cells


code:
import sys
import inspect

class PrintSnooper:
    def __init__(self, stdout):
        self.stdout = stdout
    def caller(self):
        return inspect.stack()[2][3]
    def write(self, s):
        self.stdout.write("printed by %s: " % self.caller())
        self.stdout.write(s)
        self.stdout.write("\n")

def test():
    print 'hello from test'

def main():
    # redirect stdout to a helper class.
    sys.stdout = PrintSnooper(sys.stdout)
    print 'hello from main'
    test()

if __name__ == '__main__':
    main()

rawDescription: Is there a trick to break on the print builtin with pdb?


code: {'y': [1L, 3L, 5L], 'x': [0L, 2L, 4L, 6L, 7L]}  #The lists contain row numbers

rawDescription: Using print to access individual cells of pandas dataframe after groupby


code: print re.match(pattern, r"10\xbd") # the r makes it a raw string

rawDescription: The same regular expression doesn't work on my local environment


code:
def combiner(zeros=3, ones=2):
    for indices in itertools.combinations(range(zeros+ones), ones):
        item = ['0'] * (zeros+ones)
        for index in indices:
            item[index] = '1'
        yield ''.join(item)

print list(combiner(3, 2))

['11000',
 '01100',
 '01010',
 '01001',
 '00101',
 '00110',
 '10001',
 '10010',
 '00011',
 '10100']

rawDescription: generating all permutations of 2 ones and 3 zeroes with itertools

description: Generating all permutations of 2 ones and 3 zeroes with itertools


rawDescription: url dispatcher detect all and nothing with regexp

description: Url dispatcher detect all and nothing with regexp


code:
def peek_line(f):
    pos = f.tell()
    line = f.readline()
    f.seek(pos)
    return line

print peek_line(f) # cat1
print peek_line(f) # cat1

rawDescription: Reading a Line From File Without Advancing [Pythonic Approach]


code:
raw = [[(1, None), (2, None)], [(0, None), (2, None)], [(1, None), (0, None)]]
print {i: [el[0] for el in l] for i, l in enumerate(raw)}

rawDescription: Turning a list of lists into a dictionary of lists


code:
for text, time in recs.items():
    print '"%s","%s"' % (text, time.strftime('%H:%M:%S'))

rawDescription: Saving entries of Mongo documents into CSV + Formatting ISODate


code:
def pred_func(predicates):
    # Define a function inside `pred_func`. This function is a "closure" and
    # will have access to the `predicates` parameter
    def func((i, d)):
        # You can simply pass a generator to `all`
        return all(d[param] == val for param, val in predicates.iteritems())

    # Return the function
    return func

rawDescription: How to dynamically pass predicates to filter function?

description: Dynamically pass predicates to filter function


code:
import os
import gc
import psutil

proc = psutil.Process(os.getpid())
gc.collect()
mem0 = proc.get_memory_info().rss

# create approx. 10**7 int objects and pointers
foo = ['abc' for x in range(10**7)]
mem1 = proc.get_memory_info().rss

# unreference, including x == 9999999
del foo, x
mem2 = proc.get_memory_info().rss

# collect() calls PyInt_ClearFreeList()
# or use ctypes: pythonapi.PyInt_ClearFreeList()
gc.collect()
mem3 = proc.get_memory_info().rss

pd = lambda x2, x1: 100.0 * (x2 - x1) / mem0
print "Allocation: %0.2f%%" % pd(mem1, mem0)
print "Unreference: %0.2f%%" % pd(mem2, mem1)
print "Collect: %0.2f%%" % pd(mem3, mem2)
print "Overall: %0.2f%%" % pd(mem3, mem0)

rawDescription: Releasing memory in Python

description: Releasing memory in Python


code:
from nltk.corpus import wordnet as wn
waiter = wn.Synset('waiter.n.01')
employee = wn.Synset('employee.n.01')

all_hyponyms_of_waiter = list(set([w.replace("_"," ") for s in waiter.closure(lambda s:s.hyponyms()) for w in s.lemma_names]))
all_hyponyms_of_employee = list(set([w.replace("_"," ") for s in employee.closure(lambda s:s.hyponyms()) for w in s.lemma_names]))

if 'waiter' in all_hyponyms_of_employee:
  print 'employee more general than waiter'
elif 'employee' in all_hyponyms_of_waiter:
  print 'waiter more general than employee'
else:
  print "The SUMO ontology used in wordnet just doesn't have employee or waiter under the same tree"

rawDescription: How to determine semantic hierarchies / relations in using NLTK?

description: Determine semantic hierarchies / relations in using NLTK


code:
print users['User1']
# 0

rawDescription: Creating variables from string names

description: Creating variables from string names


code:
for line in iter(p.stdout.readline,''):
    print line

rawDescription: printing stdout in realtime from subprocess

description: Printing stdout in realtime from subprocess


code:
from itertools import product

mapping = {1:['a','b'], 2:['c','d']}
data = [1, 2]
for combo in product(*(mapping[d] for d in data)):
    print combo

rawDescription: All combinations of a mapped list of lists in python


code:
print y
y.strides = y.strides[::-1]
print y

rawDescription: Efficient Numpy 2D array construction from 1D array


code:
product_list = []
for hit in res['hits']['hits']:
    product_list.append(hit["_source"])
print product_list

rawDescription: Creating a dictionary of dictionaries in Python


code:
numbers = []

def loop(i, x, new_num):
    for i in range(i, x, new_num):
        print "At the top i is %d" % i
        numbers.append(i)

        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i

    print "The numbers: "

    for num in numbers:
        print num

loop(0, 10, 6)

rawDescription: How can I turn this 'while' loop into a 'for' loop?

description: Turn this 'while' loop into a 'for' loop


code:
def sparse_vec(df):
    return (df['Col3'].values[None,:],)

# Obviously these would be chunk-specific, and you'd need to do
# another pass to get the global sum of unique ids from Col1 and the
# global max of the number of unique rows-per-id.
n_cols = len(df.Col2.unique())
n_rows = len(df.Col1.unique())

vecs = df.groupby("Col1").apply(sparse_vec)
print vecs

rawDescription: Reorganizing output data in python dictionary


code:
import argparse

def scream(args):
    print "you screamed "+' '.join(args.words)

def count(args):
    print "you counted to {0}".format(args.count)

parser = argparse.ArgumentParser()

#tell the parser that there will be subparsers
subparsers = parser.add_subparsers(help="subparsers")

#Add parsers to the object that was returned by `add_subparsers`
parser_scream = subparsers.add_parser('scream')

#use that as you would any other argument parser
parser_scream.add_argument('words',nargs='*')

#set_defaults is nice to call a function which is specific to each subparser
parser_scream.set_defaults(func=scream)

#repeat for our next sub-command
parser_count = subparsers.add_parser('count')
parser_count.add_argument('count')
parser_count.set_defaults(func=count)

#parse the args
args = parser.parse_args()
args.func(args)  #args.func is the function that was set for the particular subparser

rawDescription: Implementing two positional arguments using argparse's `add_subparsers` method


code:
import sched,time

test = 0
s = sched.scheduler(time.time, time.sleep)

Y = 2000

def loop1(sc):
    class fb:
        def link(self):
            global test,Y
            test = test + 1
            self.X = self.X + 1
            print 'Y == %d' % Y
            print 'test == %d     self.X == %d' % (test,self.X)
    print 'id(fb) == %d' % id(fb)
    print '--------'
    m1 = fb()
    m1.X = 0
    m1.link()
    print
    m2 =fb()
    m2.X = 1
    m2.link()
    print
    m3 =fb()
    m3.X = 0
    m3.link()
    print '--------'
    del fb

    # Update loop every 10 second
    sc.enter(10, 10, loop1, (sc,))

# end loop
s.enter(1, 1, loop1, (s,))
s.run()

rawDescription: Local variable in each class - python timed loop


code:
with open(file, 'r') as my_file:
    reader = csv.reader(my_file)
    rows = list(reader)
    print rows[3]

rawDescription: Printing a specific line in CSV file with Python


code:
a = [['John', 'Sergeant '], ['Jack', 'Commander '], ['Jill', 'Captain ']]
b = ['800', '854', '453']
c = [x+[y] for x,y in zip(a,b)]
print c

rawDescription: Merging a list with a list of lists

description: Merging a list with a list of lists


code:
issue = dom.getElementsByTagName('issues')[0]
paging = issue.getElementsByTagName('paging')[0]
total = paging.getElementsByTagName('total')[0]
print total.firstChild.nodeValue   # prints 10000

rawDescription: Python minidom Trouble obtaining value of child node


code:
if mystring.startswith('[city.') and mystring.endswith(']'):
    print 'success'

rawDescription: Python - Does the string contain a specific string within brackets?


code:
import requests
from bs4 import BeautifulSoup

session = requests.Session()

payload = {
    r'TopControl1$ScriptManager1': r'HistoriqueNegociation1$UpdatePanel1|HistoriqueNegociation1$HistValeur1$LinkButton1',
    r'__EVENTTARGET': r'HistoriqueNegociation1$HistValeur1$LinkButton1',
    r'__EVENTARGUMENT': r'',
    r'TopControl1$TxtRecherche': r'',
    r'TopControl1$txtValeur': r'',
    r'HistoriqueNegociation1$HistValeur1$DDValeur': r'9000  ',
    r'HistoriqueNegociation1$HistValeur1$historique': r'RBSearchDate',
    r'HistoriqueNegociation1$HistValeur1$DateTimeControl1$TBCalendar': r'22/12/2014',
    r'HistoriqueNegociation1$HistValeur1$DateTimeControl2$TBCalendar': r'28/12/2014',
    r'HistoriqueNegociation1$HistValeur1$DDuree': r'6',
    r'hiddenInputToUpdateATBuffer_CommonToolkitScripts': r'1'
  }

uri = 'http://www.casablanca-bourse.com/bourseweb/en/Negociation-History.aspx?Cat=24&IdLink=225'
r = session.get(uri)

#Find __VIEWSTATE value, there is only one input tag with type="hidden"
soup = BeautifulSoup(r.text)
viewstate_tag = soup.find('input', attrs={"type" : "hidden"})
payload[viewstate_tag['name']] = viewstate_tag['value']

r = session.post(uri, payload)
print r.text #contains html table with data

rawDescription: Python - Download a file from aspx form

description: Python - Download a file from aspx form


code:
from collections import defaultdict
d = defaultdict(somedefault)
print d[k] # calls somedefault() when the key is missing

rawDescription: Avoid or delay evaluation of things which may not be used


code:
if patchPorts[0][2] == res[1]:              #check which port is unseen and call the function again
    print mylist
    plink(nextObj, patchPorts[1][2], mylist)
else:
    print mylist
    plink(nextObj, patchPorts[0][2], mylist)

rawDescription: Python function returns None for non emptylist


code:
if len(word) != 5:
    print "that's not 5 letters..."

rawDescription: Python how to find the number of characters in the user input


code:
import random
import multiprocessing

def cat(time , dist):
    return random.randint(1, 400) * time + random.randint(1, 5) * dist

def dog(time , dist):
    return random.randint(1, 300) * time + random.randint(1, 7) * dist

def rabbit(time , dist):
    return random.randint(1, 200) * time + random.randint(1, 3) * dist

def turtle(time , dist):
    return random.randint(1, 100) * time + random.randint(1, 1) * dist

if __name__ == '__main__':
    funcs = [cat, dog, rabbit, turtle]
    pool = multiprocessing.Pool(processes=2)
    q=10
    workers = []
    for i, func in enumerate(funcs):
        worker = pool.apply_async(func, args=(i, q))
        workers.append(worker)
    for worker in workers:
        print worker.get()
    pool.close()
    pool.join()

rawDescription: How to use function pointer in multiprocessing argument

description: Use function pointer in multiprocessing argument


code:
world = ["Japan", "China", "Seattle", "Brazil"]

print "This is my story of the following places: ",

for i in range(0,len(world)):
    if i==(len(world)-1):
        print world[i] + '.', #<-- Add another comma
    else:
        print world[i] +',',

rawDescription: For loop in Python In Sentence

description: For loop in Python In Sentence


code:
def count_words(filename, search_list):
    textwords = open(filename, 'r').read().split()
    filteredwords = [t for t in textwords if t in search_list]
    counter = Counter(filteredwords)
    for w in search_list:
        counter[w] += 0        # ensure exists
    wordfreq = sorted(counter.items())
    print "printing from " + filename
    print wordfreq

search_list = ['sale', 'univers', 'money']

rawDescription: How can I add items to collection.Counter? and then sort them into ASC?

description: Add items to collection.Counter? and then sort them into ASC


code:
from sklearn.datasets import make_friedman1
from sklearn.feature_selection import RFE
from sklearn.svm import SVR

# load a dataset
X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)

estimator = SVR(kernel="linear")
selector = RFE(estimator, 5, step=1)
X_new = selector.fit_transform(X, y)

print selector.support_
print selector.ranking_

rawDescription: How to get attribute list from fitted model in Scikit-learn?

description: Get attribute list from fitted model in Scikit-learn


code:
from time import gmtime, strftime
date_string = strftime("%d/%m/%Y %H:%M:%S", gmtime())
print date_string

rawDescription: Convert string datetime to timestamp and vice verse in python


code:
class A:
    x = 1
    def somefunction(self):
        A.x += 1
        print A.x

rawDescription: Can a class variable be created inside one of the class' methods in Python?


code:
from lxml import etree
data = """<job>
  <server>
    <cpu-set>
    </cpu-set>
  </server>
  <ip-routings>
  </ip-routings>
</job>"""
doc = etree.XML(data)
for e in doc.xpath('//*[contains(local-name(),"-")]'):
  e.tag = e.tag.replace('-','_')

print etree.tostring(doc)

rawDescription: Python: String replacement (replace hyphens with underscores) in all tag names inside an XML


code:
import contextlib
import selenium.webdriver as webdriver
display = pyvirtualdisplay.Display(visible = False, size = (800, 600))
display.start()
with contextlib.closing(webdriver.Firefox()) as driver:
    driver.get('http://www.google.com')
    print driver.title
    # Google
display.stop()

rawDescription: Python: selenium.webdriver issue (no X on server)


code:
from twisted.application.service import Service

class ThingDoer(Service):
    def startService(self):
        print "The reactor is running now."

rawDescription: sound way to feed commands to twisted ssh after reactor.run()

description: Sound way to feed commands to twisted ssh after reactor.run()


code:
import delorean
from delorean import stops
for stop in stops(freq=delorean.DAILY, timezone="US/Eastern", start=start_date, stop=end_date):
    value = stop.date.strftime("%Y-%m-%d")
    print value

rawDescription: Writing loop to get the data during some specific periods in Python


code:
class Node:
    def __init__(self, data):
        self._value = data
        self.left = None
        self.right = None

def _is_identical_aux(node1, node2):
    if node1 is None and node2 is None:
        return True
    if node1 is not None and node2 is not None:
        return ((node1._value == node2._value) and
                _is_identical_aux(node1.left, node2.left) and
                _is_identical_aux(node1.right, node2.right))
    return False

root1 = Node(7)
root1.left = Node(3)
root1.right = Node(2)
root1.left.left = Node(123)
root1.left.right = Node(231)
root1.right.left = Node(9)
root1.right.right = Node(5)

root2 = Node(7)
root2.left = Node(3)
root2.right = Node(2)
root2.left.left = Node(123)
root2.left.right = Node(231)
root2.right.left = Node(9)
root2.right.right = Node(5)

root3 = Node(7)
root3.left = Node(3)
root3.right = Node(2)

if _is_identical_aux(root1, root2):
    print "Both trees are identical"
else:
    print "Trees are not identical"

if _is_identical_aux(root1, root3):
    print "Both trees are identical"
else:
    print "Trees are not identical"

rawDescription: python-Implement and test the following BST method

description: Python-Implement and test the following BST method


code:
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class wait_for_text_not_to_end_with(object):
    def __init__(self, locator, text):
        self.locator = locator
        self.text = text

    def __call__(self, driver):
        try :
            element_text = EC._find_element(driver, self.locator).text.strip()
            return not element_text.endswith(self.text)
        except StaleElementReferenceException:
            return False

browser = webdriver.PhantomJS()
browser.maximize_window()
browser.get("http://www.jamiiforums.com/kenyan-news/225589-kenyan-and-tanzanian-surburbs.html")

username = browser.find_element_by_id("navbar_username")
password = browser.find_element_by_name("vb_login_password_hint")

username.send_keys("MarioP")
password.send_keys("codeswitching")

browser.find_element_by_class_name("loginbutton").click()

wait = WebDriverWait(browser, 30)
wait.until(EC.visibility_of_element_located((By.XPATH, '//h2[contains(., "Redirecting")]')))
wait.until(EC.title_contains('Kenyan & Tanzanian'))
wait.until(EC.visibility_of_element_located((By.ID, 'postlist')))

# click "11 others" link
link = browser.find_element_by_xpath('//div[@class="vbseo_liked"]/a[contains(@onclick, "return vbseoui.others_click(this)")]')
link.click()
browser.execute_script("""
function eventFire(el, etype){
  if (el.fireEvent) {
    el.fireEvent('on' + etype);
  } else {
    var evObj = document.createEvent('Events');
    evObj.initEvent(etype, true, false);
    el.dispatchEvent(evObj);
  }
}

eventFire(arguments[0], "click");
""", link)

# wait for the "div" not to end with "11 others link this."
wait.until(wait_for_text_not_to_end_with((By.CLASS_NAME, 'vbseo_liked'), "11 others like this."))

print 'success!!'
browser.close()

rawDescription: Executing a script in selenium python

description: Executing a script in selenium python


code:
from __future__ import division
amount = 1000
people = 3
average = amount/people
print average

rawDescription: Decimal not getting while dividing

description: Decimal not getting while dividing


code:
items = ["Data Here 94/452O", "Data more 94/4522i", "Data bla 94/111", "Data bla 94/459es", "Data bla 94/444"]

items = [item[:-2] + item[-2:].upper() for item in items]

print items

rawDescription: Set the right two characters (if there are any) to capitals?


code:
for x in strings(grammar, 'N'):
    print x
    if len(x) > 4:
        break

rawDescription: Figuring out how to expand a grammar (Python)


code:
for step in directions['Directions']['Routes'][0]['Steps']:
  print step['Point']['coordinates'][1], step['Point']['coordinates'][0]

rawDescription: How to use Google Maps Directions API to get zipcode and addresses passed through in python or R.

description: Use Google Maps Directions API to get zipcode and addresses passed through in python or R.


code:
class StatsObject(object):
    def addScore(self, score):
        print score
file_stats = {"/path/to-something/hyphenated": StatsObject()}
file_stats["/path/to-something/hyphenated"].addScore(10)
file_stats["/another/hyphenated-path"] = 10
file_stats["/another/hyphenated-path"].addScore(10)

rawDescription: Python file names as dictionary keys

description: Python file names as dictionary keys


code:
df = pd.DataFrame(columns=['xAxis', 'yAxis1', 'yAxis2'])
df['xAxis'] = pd.to_datetime(weather['Date'])
df['yAxis1'] = weather_stn1['Tavg']
df['yAxis2'] = weather_stn2['Tavg']

plot_df = plot_df.groupby(plot_df['xAxis']).mean()

print plot_df.reset_index()

rawDescription: How to apply group by on data frame with neglecting NaN values in Pandas?

description: Apply group by on data frame with neglecting NaN values in Pandas


code:
for row in Classobject.collectInfoFromXLS():
    print row

rawDescription: return Set of lists from out of function: python

description: Return Set of lists from out of function: python


code:
while true:
    line = sys.stdin.readline()
    if filter_line(line): print line

rawDescription: running a python script indefinitely (as a process, pretty much)

description: Running a python script indefinitely (as a process, pretty much)


code:
for a, b, c, d in product(range(95), repeat=4):
    print a, b, c, d
    if a == 1: break

rawDescription: How to break nested for loop in Python?

description: Break nested for loop in Python


code:
from django.shortcuts import render
from map.models import *
from django.utils import simplejson
from django.http import HttpResponse

def index(request):
    countries = Country.objects.all()
    print countries
    return render(request, 'index.html', {'countries': countries})

def getdetails(request):
    #country_name = request.POST['country_name']
    country_name = request.GET['cnt']
    print "ajax country_name ", country_name

    result_set = []
    all_cities = []
    answer = str(country_name[1:-1])
    selected_country = Country.objects.get(name=answer)
    print "selected country name ", selected_country
    all_cities = selected_country.city_set.all()
    for city in all_cities:
        print "city name", city.name
        result_set.append({'name': city.name})
    return HttpResponse(simplejson.dumps(result_set), mimetype='application/json',     content_type='application/json')

rawDescription: Django dependent select

description: Django dependent select


code:
def sums(lst, limit):    # prevent global lookups by using a function
    res = set()          # set membership testing is much faster than lists
    res_add = res.add    # cache add method
    for i, first in enumerate(lst):   # get index and item at the same time
        for second in lst[i:]:        # one copy operation saves n index ops.
            res_add(first + second)   # prevent creation/lookup of extra local temporary
    return sorted([x for x in res if x < limit])

print sums(listgen(), 20000)

rawDescription: Generate all possible combinations from a int list under a limit


code:
def my_func1():
    print 'func1'

rawDescription: Importing Modules from Multiple Parallel Subdirectories (Python)


code:
new_frame = [conn for conn in connection_frame if not connection_frame.index(conn) in [i for i in range(len(connection_frame)) if (i != len(connection_frame)-1) and (connection_frame[i][1] == connection_frame[i+1][1])]]
for conn in new_frame:
    print conn

rawDescription: Remove consecutive duplicates from a 2D list , python?


rawDescription: converting numbers to metric unit in python

description: Converting numbers to metric unit in python


code:
def first(_tuple):
    return _tuple[randint(0, len(_tuple) - 1)]

def second(_tuple):
    return choice(_tuple)

print timeit('first(t)', 'from __main__ import first; t = tuple(range(10))')
print timeit('second(t)', 'from __main__ import second; t = tuple(range(10))')

rawDescription: What's the fastest way to get a random element from a tuple? (python)


code:
import operator

lessthan = operator.lt

one = 1
two = 2

if lessthan(one, two):
    print 'yes'

rawDescription: Evaluation with variable pointing to operator


rawDescription: Merge Two Dictionaries that Share Same Key:Value


code:
d={
    'eth1': {
            'R2': 'bw1',
            'R3': 'bw3'
            },
    'eth2': {
            'R2': 'bw2',
            'R3': 'bw4'
        }
}
result = {}
for k, v in d.iteritems():
    for a,b in v.iteritems():
        result.setdefault(a, {}).update({k:b})
print result

rawDescription: Reverse mapping on nested dictionary

description: Reverse mapping on nested dictionary


code: print data

rawDescription: Python, code to csv. Troubles

description: Python, code to csv. Troubles


code:
cnt = Counter(lst)
print {gender: {name: cnt[name] for name in names}
       for gender, names in invert(persons).items()}

rawDescription: Reverse multiple values with keys in dictionary


code:
import os
import rpm
import sys

ts = rpm.TransactionSet()
mi = ts.dbMatch('name', sys.argv[1])
for ind in range(mi.count()):
    h = mi.next()
    for dep in h[rpm.RPMTAG_REQUIRENAME]:
        print dep

rawDescription: Find rpm dependencies using python yum/rpm API?


code:
for k, v in data["clusters"].items():
    print data["clusters"][k]["tag_cl"]

rawDescription: Get yaml key value in python

description: Get yaml key value in python


code:
for item in reversed("1,2,3,4,5,6".split(",")):
    print item

rawDescription: Going through list from the end after split()


code:
import sys
import random

class Question(object):
    def __init__(self, question, answer, options):
        self.question = question
        self.answer = answer
        self.options = options

    def ask(self):
        print self.question + "?"
        for n, option in enumerate(self.options):
            print "%d) %s" % (n + 1, option)

        response = int(sys.stdin.readline().strip())   # answers are integers
        if response == self.answer:
            print "CORRECT"
        else:
            print "wrong"

questions = [
    Question("How many legs on a horse", 4, ["one", "two", "three", "four", "five"]),
    Question("How many wheels on a bicycle", 2, ["one", "two", "three", "twenty-six"]),

    # more verbose formatting
    Question(question="What colour is a swan in Australia",
             answer=1,
             options=["black", "white", "pink"]),    # the last one can have a comma, too
    ]

random.shuffle(questions)    # randomizes the order of the questions

for question in questions:
    question.ask()

rawDescription: Python trivia game

description: Python trivia game


code: print max(max(lst) for lst in scores[1:3])

rawDescription: Max() returns highest list, not number

description: Max() returns highest list, not number


code:
try:
    words.index('earthquake')
except ValueError:
    print 'handle missing word here'

rawDescription: Position of query word

description: Position of query word


code:
# Find all 'a' elements inside 'tr' table rows with xpath
for a in mySearchTree.xpath('.//tr/*/a'):
    print 'found "%s" link to href "%s"' % (a.text, a.get('href'))

rawDescription: Need python lxml syntax help for parsing html


code:
gen = ['A', ('x', 'y'), ('t', 'u'), 'B', ('y', 't'), 'B', ('a', 'z')]

result = []
lastStringSeen = None
for i in gen:
    if isinstance(i, str):
        lastStringSeen = i
    else: #must be a tuple
        result.append((lastStringSeen, i))
print result

rawDescription: Looping through a list of strings and tuples and appending unique combinations


code:
def pattern_writer2(pattern_size):
    for t in range(pattern_size):
        pattern = list("." * pattern_size)
        pattern[t] = "x"
        pattern[-(t+1)] = "x"
        print "".join(pattern)

rawDescription: X pattern in python 3.2

description: X pattern in python 3.2


code:
import csv

def toevoegenIn():
    bron = str(raw_input("Welke bron wilt U toevoegen? "))
    bedrag = int(input("Welk bedrag hoort daarbij? "))
    return {bron: bedrag}

if __name__ == '__main__':
    # Step 1: Load all the data in a dictionary. The cells might come with
    #         undesired extra spaces in them. Use strip to remove those.
    loaded_data = {}
    with open('test.csv', 'r') as csv_file_r:
        reader = csv.reader(csv_file_r, delimiter=':')
        loaded_data = {}
        for row in reader:
            loaded_data[row[0].strip()] = int(row[1].strip())

    print "Initial data: %s" % loaded_data
    # Step 2: Ask the user what data to change.
    #         The toevoegenIn function will return a
    #         one-key dictionary.
    change_data = toevoegenIn()
    # Step 3: Use dict.update to update your initial data with the
    #         dict retrieved above.
    #         If the modified key already existed in the original dict,
    #         it will be modified to the value entered by the user.
    #         If the key wasn't in the original dict, it'll be added.
    loaded_data.update(change_data)
    print "Updated data: %s" % loaded_data

    # Step 4: Write the new data. I put it into a new file, just
    #         in case you don't wanna overwrite the original one. If
    #         you do want to overwrite, just change the file's name to
    #         the original file.
    with open('test.csv.new', 'w') as csv_file_w:
        writer = csv.writer(csv_file_w, delimiter=':')
        for key, val in loaded_data.items():
            writer.writerow([key, val])

    # Make a quick confirmation read:
    with open('test.csv.new', 'r') as f:
        print "new_contents:\n%s" % f.read()

rawDescription: Updating a saved csv

description: Updating a saved csv


code:
import re
s = u'something extra BEGIN the unicode text I want with an é END some more extra stuff'
print re.search(r'BEGIN(.+?)END', s).group(1)

rawDescription: Extract unicode substrings with the re module


code:
import os
import subprocess
from subprocess import check_call

def sync(base_change):

    # Generate a list of integers based on your change_ignore file
    with open('change_ignore.txt', 'rb') as f:
        # Here we make a list of integers based on the file
        change_ignore = [int(line.strip()) for line in f]

    # Store your hits/misses in lists; that way you do not
    # need to continuously open/close files while appending
    change_ignore_base = []
    change_ignore_file = []

    # Now open the file of the IDs
    with open('change_ids.txt', 'rb') as f:
        # Iterate over the file itself
        for line in f:
            # Convert the line to an integer (note that this
            # implicitly removes the newline characters)
            # However we are going to write 'line' to our list,
            # which will keep the newline (more on that later)
            num = int(line)
            print num

            # Now we are comparing ints with ints
            # I'm assuming the print statements are for debugging,
            # so we offset them with some space, making it so that
            # any relevant hits are indented under a number
            if num <= base_change:
                print "  IN line<=base_change"
                change_ignore_base.append(line)
            if num in change_ignore:
                print "  IN change_ignore"
                change_ignore_file.append(line)
            if num > base_change and num not in change_ignore:
                pass

    # Now that you have lists containing the data for your new files,
    # write them (they already have newlines appended so writelines works)
    # You can use 'with' with two files in this way in Python 2.7+,
    # but it goes over 80 characters here so I'm not a huge fan :)
    with open('change_ignore_base', 'wb') as b, open('change_ignore_file', 'wb') as f:
      b.writelines(change_ignore_base)
      f.writelines(change_ignore_file)

def main ():
    base_change=200913
    sync(base_change)

main()

rawDescription: File operations failing

description: File operations failing


code: print "Starting cluster", cluster_id

rawDescription: How to launch and configure an EMR cluster using boto

description: Launch and configure an EMR cluster using boto


code:
import timeit

setup = "i = 1337"

best1 = best2 = float("inf")
for _ in range(5000):
  best1 = min(best1, timeit.timeit("i % 65536", setup=setup, number=10000))
for _ in range(5000):
  best2 = min(best2, timeit.timeit("i % (2**16)", setup=setup, number=10000))
print best1
print best2

rawDescription: Why is taking the mod of a number in python faster with exponents?


code:
import subprocess

process = subprocess.Popen(['df', '-h'], stdout=subprocess.PIPE)
out, err = process.communicate()
out = out.splitlines()[1:] # grab all the lines except the header line

for i in out:
    tmp = i.split(' ')
    tmp2 = []
    for x in tmp:
        if x != '':
            tmp2.append(x)
    print tmp2[-1] + " is " + tmp2[-2] + " full"

rawDescription: In Python, how do I get a list of all partitions in Mac OS X?


code:
from BeautifulSoup import BeautifulSoup, SoupStrainer
import re
import urllib2

doc = urllib2.urlopen("http://www.learnersdictionary.com/search/python").read()
doc = doc.replace('</SCR', '')
audioLinks = SoupStrainer('a', onclick=re.compile(r'^playAudio'))
soup = [str(elm) for elm in BeautifulSoup(doc, parseOnlyThese=audio)]
for elm in soup:
    print re.search(r'playAudio\((.*[^)])\)', elm).group(1)
    # prints 'python01.wav', 'py*thon'

rawDescription: What is the elegant way to get the arguments to a playAudio call from this list


code:
import glob
import os

dir_path = "/home/vivek/Desktop/stackoverflow/input"
text_files = glob.glob(dir_path+"/*.txt")
print "Test Files:", text_files

result = {}
for i in text_files:
    # Read file content.
    with open(i, 'rb') as fp:
        data = fp.read()
    max_no = max([int(j) for j in data.split()])
    result[os.path.basename(i)] = max_no

#- Sort and print File names.
sorted_file_names = sorted(result.keys())
for i in sorted_file_names:
    print "File Name: %s, MAx Random Number: %d"%(i, result[i])

rawDescription: How do I organize data in alphabetical order?

description: Organize data in alphabetical order


code:
def dropns(root):
    for elem in root.iter():
        parts = elem.tag.split(':')
        if len(parts) > 1:
            elem.tag = parts[-1]
        entries = []
        for attrib in elem.attrib:
            if attrib.find(':') > -1:
                entries.append(attrib)
        for entry in entries:
            del elem.attrib[entry]

# Test case
name = '~/tmp/mantisbt/test.xml'
f = open(name, 'rb')
import lxml.etree as etree
parser = etree.XMLParser(ns_clean=True, recover=True)
root = etree.parse(f, parser=parser)
print('=====================================================================')
print etree.tostring(root, pretty_print = True)
print('=====================================================================')
dropns(root)
print etree.tostring(root, pretty_print = True)
print('=====================================================================')

rawDescription: Drop all namespaces in lxml?

description: Drop all namespaces in lxml


code:
# @Dataset img
ra = img.randomAccess()
ra.setPosition([0, 123])
result = ra.get()
print result

rawDescription: How to output the intensity of every point using imageJ?

description: Output the intensity of every point using imageJ


code:
def possible_solutions(neighbors):
    for solution in possible_solution(neighbors):
        print solution

print '-' * 30
possible_solutions([1, 2, 3])

print '-' * 30
possible_solutions([1, 2, 3, 4])

print '-' * 30
possible_solutions([1, 2, 3, 4, 5])

rawDescription: arrangements backtracking python

description: Arrangements backtracking python


code:
data = ["15674 24000 Manager Gregory the 1st John", "15674 24000 Manager Gregory the 1st John",
        "15674 24000 Manager Gregory the 1st John", "15674 24000 Manager Gregory the 1st John"]

data1 = []

for items in data:
    splitNames = items.split()
    number, salary, position, first, des1, des2, last = splitNames
    data1.append([last, first + ' ' + des1 + ' ' + des2, number, position, salary])

for items in data1:
    print items

rawDescription: List position changing

description: List position changing


code:
import operator
from prettytable import PrettyTable

table = PrettyTable(["Name", "Grade"])
table.add_row(["Joe", 90])
table.add_row(["Sally", 100])
table.add_row(["Bill", 90])
table.add_row(["Alice", 90])
print table.get_string(sort_key=operator.itemgetter(1, 0), sortby="Grade")

rawDescription: Python prettytable Sort by Multiple Columns


rawDescription: manipulate list comprehension

description: Manipulate list comprehension


rawDescription: Python RegEx Matching Newline

description: Python RegEx Matching Newline


code:
import re, math
from collections import Counter

WORD = re.compile(r'\w+')

def get_cosine(vec1, vec2):
     intersection = set(vec1.keys()) & set(vec2.keys())
     numerator = sum([vec1[x] * vec2[x] for x in intersection])

     sum1 = sum([vec1[x]**2 for x in vec1.keys()])
     sum2 = sum([vec2[x]**2 for x in vec2.keys()])
     denominator = math.sqrt(sum1) * math.sqrt(sum2)

     if not denominator:
        return 0.0
     else:
        return float(numerator) / denominator

def text_to_vector(text):
     words = WORD.findall(text)
     return Counter(words)

text1 = 'This is a foo bar sentence .'
text2 = 'This sentence is similar to a foo bar sentence .'

vector1 = text_to_vector(text1)
vector2 = text_to_vector(text2)

cosine = get_cosine(vector1, vector2)

print 'Cosine:', cosine

rawDescription: How to calculate cosine similarity given 2 sentence strings? - Python

description: Calculate cosine similarity given 2 sentence strings? - Python


code:
l = [1, 2, 3, 4, 5, 6]
for i in range(len(l)):
    print l[i : i+3]

rawDescription: iterate through list like in sliding window

description: Iterate through list like in sliding window


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        open_button = tk.Button(text='File Open', command=self.open_events_db)
        print_button = tk.Button(text='Print DB', command=self.print_events_db)

        open_button.pack(fill=tk.X)
        print_button.pack(fill=tk.X)

    def open_events_db(self):
        file_path_string = tkFileDialog.askopenfilename()
        self.eventsdb = pd.read_csv(file_path_string,encoding='utf-8')

    def print_events_db():
        print self.eventsdb

def main():
    root=tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

if __name__=="__main__":
    main()

rawDescription: Proper way to pass variables within a tkinter GUI


code:
d = {}
for a in data:
    d.setdefault(a[0], []).append(a.split()[1])
for k,v in sorted(d.iteritems()):
    print k, ', '.join(v)

rawDescription: making index with python

description: Making index with python


code: for i in stack: print i[0]

rawDescription: Can Decorator + Reflection selectively create object trees representing individual function-call chain?


rawDescription: Matching id's in BeautifulSoup

description: Matching id's in BeautifulSoup


code: print asplit[0] + '.' + str(int(float(asplit[1]) *  60))

rawDescription: Convert float into time (hour.minute) in python


code:
rows = soup.find("table").find("tbody").find_all("tr")
print rows[1].find_all("td")[2].get_text()

rawDescription: Find index of tag with certain text in beautifulsoup/python


code:
def key_sort(seq, cmp=None, key=None, reverse=False):
    if key is not None:
        transform = [(key(x), i, x) for i, x in enumerate(seq)]
        transform.sort(None if cmp is None else lambda (k, _, _), (l, _, _): cmp(k, l))
        seq[:] = [x for _, _, x in transform]
    else:
        seq.sort(cmp)
    if reverse:
        seq.reverse()

rawDescription: Sorting a list of lists by item frequency in Python 2.3


code:
response = setattr(a, 'test', 'wow2')
print response  #None
print a.test  #wow2

rawDescription: Dynamically set object attribute with map and setattr function


code:
from cStringIO import StringIO
import sys

sys.stdout = buffer = StringIO()

print "Hello World"

# get output via: buffer.getvalue()

rawDescription: Get current console output in python

description: Get current console output in python


code:
list = [['Date', 'Value'], ['2002-03', '12.9'],['2001-01','11.6']]
list2=[]
for i in list:
    for element in i:
        try:
            datetime.datetime.strptime(element, '%Y-%m')
            list2.append(element)
        except ValueError:
            continue
print list2

rawDescription: if "it is a date" then "do what I say" -

description: If "it is a date" then "do what I say" -


code:
with open('test.txt','r') as f:
    total=0
    for i in f:
        total+=int(i)
    print total

rawDescription: Python: reading integers from a file

description: Python: reading integers from a file