code:
def main():
    line = r'<para>06.00        na hrvatskom Zona gradnje: Izgradnja zelenog Pekinga</para>'
    if re.search(r'^(<para>)\d{2}.\d{2}', line):
        line_time = re.findall(r'\d{2}.\d{2}',line)[0]
        line_title = line[line.find(re.findall(r'[A-Z]',line)[0]):line.find(':')]
        line_sub = line[line.find(':')+1:line.find(r'</')].strip()

        print '<start>'+line_time+'</start><title>'+line_title+'</title><sub>'+line_sub+'</sub>'

rawDescription: Python regex on text file

description: Python regex on text file


code:
cats = {}

with open('my.csv', "r") as ins:
    # check each line of the fine
    for line in ins:
        # remove double quotes: replace('"', '')
        # remove break line : rstrip()
        a = str(line).replace('"', '').rstrip().split('|')
        if a[0] != 'CatNo':
            cats[int(a[0])] = a[1:];

for p in cats:
    print 'cat_id: %d, value: %s' % (p, cats[p])

# you can access the value by the int ID
print cats[1001]

rawDescription: Convert a csv into category-subcategory using array


code:
def foo(x):
    a = x
    def bar():
        print a
    return bar

bar1 = foo(5)
bar2 = foo(6)
bar1()
bar2()

rawDescription: Merge two lists inside __init__ without instantiation. Python


code:
user = User(email='example@example.com', favorites=UserFavorites(color='green'))
db.session.add(user)
db.session.commit()

user = User.query.filter(
    User.email == 'example@example.com'
).options(
    db.joinedload(User.favorites)
).one()
print user.favorites.color

rawDescription: Creating a basic Table with Flask-SQLAlchemy


code:
users = {}
for i in range(1,4):
    users["User"+str(i)]=0
print users
# {'User1': 0, 'User2': 0, 'User3': 0}

rawDescription: Creating variables from string names

description: Creating variables from string names


code:
x = Parameter()
y = 2*x*x + 3*x - x/2

x.value = 10
print y.value
# prints 225

x.value = 20
print y.value
# prints 850

# compute a series of x-y values for the function
print [(x.value, y.value) for x.value in range(5)]
# prints [(0, 0), (1, 5), (2, 13), (3, 26), (4, 42)]

rawDescription: Python number-like class that remembers arithmetic operations?


code:
import nltk.collocations
import nltk.corpus
import collections

bgm    = nltk.collocations.BigramAssocMeasures()
finder = nltk.collocations.BigramCollocationFinder.from_words(
    nltk.corpus.brown.words())
scored = finder.score_ngrams( bgm.likelihood_ratio  )

# Group bigrams by first word in bigram.
prefix_keys = collections.defaultdict(list)
for key, scores in scored:
   prefix_keys[key[0]].append((key[1], scores))

# Sort keyed bigrams by strongest association.
for key in prefix_keys:
   prefix_keys[key].sort(key = lambda x: -x[1])

print 'doctor', prefix_keys['doctor'][:5]
print 'baseball', prefix_keys['baseball'][:5]
print 'happy', prefix_keys['happy'][:5]

rawDescription: Understanding NLTK collocation scoring for bigrams and trigrams


code:
for inputs,outputs in testcases:
    print '%r, %r' % (inputs, outputs)

rawDescription: Creating and accessing list of lists in python


code:
import argparse
import os.path

def CheckExt(choices):
    class Act(argparse.Action):
        def __call__(self,parser,namespace,fname,option_string=None):
            ext = os.path.splitext(fname)[1][1:]
            if ext not in choices:
                option_string = '({})'.format(option_string) if option_string else ''
                parser.error("file doesn't end with one of {}{}".format(choices,option_string))
            else:
                setattr(namespace,self.dest,fname)

    return Act

parser = argparse.ArgumentParser()
parser.add_argument('fn',action=CheckExt({'csv','txt'}))

print parser.parse_args()

rawDescription: python argparse file extension checking

description: Python argparse file extension checking


code:
lc = sorted(sorted([k] + sorted(v.values()) for k,v in myDict.items()))
for row in lc:
    print row

rawDescription: Shortening a list comprehension that taps into a nested dictionary


rawDescription: Creating D3 nested JSON Data with Python


code:
import csv

BR = [(71001, 8427,{'lanes': 9, 'length': 0.1,}),
        (71003, 8429,{'lanes': 9, 'length': 0.8,}),
        (71007, 71008,{'lanes': 6, 'length': 0.3,}),
        (7100, 7104,{'lanes': 6, 'length': 0.3,})]

with open('result4.csv') as f:
        for row in csv.DictReader(f):
            for nodeA, nodeB, attrDict in BR:
                if nodeA == int(row['NodeA']) and nodeB == int(row['NodeB']):
                    attrDict.update({'volume' : str(row['LOAD'])})
print BR

rawDescription: Read a CSV file and Append to dictionary


code:
def fooFighters( self ):
    print "fooFighters"
A.fooFighters = fooFighters
a2 = A()
a2.fooFighters
a2.fooFighters()

rawDescription: Adding a Method to an Existing Object Instance


code:
foo = MyInt(8)
print foo.difference()(7)

rawDescription: Setting a lambda function as a property

description: Setting a lambda function as a property


code:
l = [("timestamp1", 1),("timestamp1", 2),("timestamp1", 1),("timestamp2", 2)]
d = {}
for ts, val in l:
    d.setdefault(ts,0)
    d[ts] += val
print d.items()
[('timestamp2', 2), ('timestamp1', 4)]

rawDescription: How do I merge tuples in a list based on the values?

description: Merge tuples in a list based on the values


code:
line = '-------------------------------------------------------------\n'

ss = ('I gave two similar things to my two twin sons: '
      'two spankings, two nice BICYCLES of 300 dollars each, '
      'yes 600 dollars for two horridly nice BICYCLES, '
      'two times 300 dollars for two sons receiving two BICYCLES !, '
      'two dollars too, but never two dogs')
print ss,'\n\n'

print line + '1) Replacing the more at right before the first "BICYCLES":\n'
fb = ss.find('BICYCLES')
print '@@@@'.join(ss[0:fb].rsplit('two',1)) + ss[fb:] if fb+1 else ss

print line + '2) Replacing the more at right before the last "BICYCLES":\n'
fb = ss.rfind('BICYCLES')
print '@@@@'.join(ss[0:fb].rsplit('two',1)) + ss[fb:] if fb+1 else ss

print line + '3) Replacing all before the first "BICYCLES":\n'
fb = ss.find('BICYCLES')
print ss[0:fb].replace('two','@@@@') + ss[fb:] if fb+1 else ss

print line + '4) Replacing all before the last "BICYCLES":\n'
fb = ss.rfind('BICYCLES')
print ss[0:fb].replace('two','@@@@') + ss[fb:] if fb+1 else ss

rawDescription: Python regular expressions - find a string in a file that occurs somewhere before another string?


code:
def encode_model(obj, recursive=False):
    if obj is None:
        return obj
    if isinstance(obj, (mongoengine.Document, mongoengine.EmbeddedDocument)):
        out = dict(obj._data)
        for k,v in out.items():
            if isinstance(v, ObjectId):
                if k is None:
                    out['_id'] = str(v)
                    del(out[k])
                else:
                    # Unlikely that we'll hit this since ObjectId is always NULL key
                    out[k] = str(v)
            else:
                out[k] = encode_model(v)
    elif isinstance(obj, mongoengine.queryset.QuerySet):
        out = encode_model(list(obj))
    elif isinstance(obj, ModuleType):
        out = None
    elif isinstance(obj, groupby):
        out = [ (g,list(l)) for g,l in obj ]
    elif isinstance(obj, (list)):
        out = [encode_model(item) for item in obj]
    elif isinstance(obj, (dict)):
        out = dict([(k,encode_model(v)) for (k,v) in obj.items()])
    elif isinstance(obj, datetime.datetime):
        out = str(obj)
    elif isinstance(obj, ObjectId):
        out = {'ObjectId':str(obj)}
    elif isinstance(obj, (str, unicode)):
        out = obj
    elif isinstance(obj, float):
        out = str(obj)
    else:
        raise TypeError, "Could not JSON-encode type '%s': %s" % (type(obj), str(obj))
    return out

rawDescription: MongoAlchemy Document Encode to JSON via Flask-MongoAlchemy


code:
print u'惨事'.encode('utf8').decode('cp1252')
print u'最'.encode('utf8').decode('cp1252')

rawDescription: Converting incorrectly encoded Chinese characters in MySQL to UTF-8


code:
#!python2.7
print "Hello"

rawDescription: How to invoke a specific Python version WITHIN a script.py -- Windows

description: Invoke a specific Python version WITHIN a script.py -- Windows


code:
from itertools import takewhile
primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
for p in takewhile(lambda i: i < 20, primes):
    print p

rawDescription: Is there a built-in function (or other method) to iterate over a list while the elements <= limit?


code:
def nth_day_of_month(start, end, nth, weekday):
    assert start.day == 1, "start on the first day of a month"
    assert nth > 0
    assert 1 <= weekday <= 7

    candidate = start
    seen_in_month = 0
    while candidate <= end:
        if candidate.isoweekday() == weekday:
            seen_in_month += 1
            if seen_in_month == nth:
                yield candidate
                current_month = candidate.month
                while candidate.month == current_month:
                    candidate += timedelta(1)
                seen_in_month = 0
            else:
                if (candidate + timedelta(1)).month != candidate.month:
                    seen_in_month = 0
                candidate += timedelta(1)
        else:
            if (candidate + timedelta(1)).month != candidate.month:
                seen_in_month = 0
            candidate += timedelta(1)

# third wednesday
print list(nth_day_of_month(date(2011, 1, 1), date(2012, 1, 1), nth=3, weekday=3))

# fifth sunday
print list(nth_day_of_month(date(2011, 1, 1), date(2012, 1, 1), nth=5, weekday=7))

# 9th monday
print list(nth_day_of_month(date(2011, 1, 1), date(2012, 1, 1), nth=9, weekday=1))

rawDescription: Whats the most pythonic way to generate a list of dates from two dates


code:
def f(arg):
 print arg

arguments = ('aa', 'bb') # it is a tuple
for arg in arguments:
 f(arg)

rawDescription: celery beat schedule arguments

description: Celery beat schedule arguments


code:
def addconnection(self,sender,weight=0.0):
    self.connections.append(Connection(self,sender,weight))
    print "Node", str(self), "now contains", str(self.connections[-1])

rawDescription: Python Neural Networking: Run 10 iterations but I get the same output


code:
s='SSPQQQQPSSSSQQQSSQPSPSQSSQPSSQPPSSSSQPSPSQSSQPSSSSQPSPSQSSQPSSSSQPSPSQ'

substring='SSQP'
print list(sub_findre(s,substring,2))

['SSPQ', 'SPQQ', 'QQQP', 'SSSS', 'SSSQ', 'SSQQ', 'SQQQ', 'SSQP', 'PSQS', 'SSQP', 'SSQP', 'SQPP', 'SSSS', 'SSSQ', 'SSQP', 'PSQS', 'SSQP', 'SSSS', 'SSSQ', 'SSQP', 'PSQS', 'SSQP', 'SSSS', 'SSSQ', 'SSQP', 'PSQ']

rawDescription: String regex two mismatches Python

description: String regex two mismatches Python


code:
value = 'bcvfdvdfvcdjbcdscv'
count_letters(value, 'b')
ds=count_letters(value, 'd') #if you assign the return value to some variable, print it out:
print ds

rawDescription: How to count the number of letters in a string with a list of sample?

description: Count the number of letters in a string with a list of sample


code:
from itertools import islice

with open(file, 'r') as my_file:
    reader = csv.reader(my_file)
    print next(islice(reader, 3, 4))

rawDescription: Printing a specific line in CSV file with Python


code:
from csv import DictReader
from collections import Counter

with open('counts.txt') as f:
    reader = DictReader(f, delimiter='\t')
    wordCounts = Counter({row['wordform']: int(row['abs']) for row in reader})
    print wordCounts.most_common(3)

rawDescription: Python Counter from txt file

description: Python Counter from txt file


code:
source = open(datafile, 'rb')
skip_ = source.read(32) # Skip non-zlib header

buf = ''
while True:
    decomp = zlib.decompressobj()
    # Find the start of the next stream
    buf = findstart(ZHEAD, buf, source)
    try:
        stream = decomp.decompress(buf)
    except zlib.error:
        print "Spurious match(?) at output offset %d." % outfile.tell(),
        print "Skipping 2 bytes"
        buf = buf[2:]
        continue

    # Read until zlib decides it's seen a complete file
    while decomp.unused_data == '':
        block = source.read(2**12)
        if len(block) > 0:
            stream += decomp.decompress(block)
        else:
            break # We've reached EOF

    outfile.write(stream)
    buf = decomp.unused_data # Save for the next stream
    if len(block) == 0:
        break  # EOF

outfile.close()

rawDescription: Python and zlib: Terribly slow decompressing concatenated streams


code:
# create subprocess command
subprocess_cmd = r'''java -Xmx16g -jar snpeff.jar -t GRCh37.75 > out_file}'''.format(query_df)

# run the subprocess command
ps = sp.Popen(subprocess_cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, cwd=os.getcwd())
try:
  print ps.communicate(query_df.to_csv(sep='\t'))
except sp.CalledProcessError as e:
  print e

rawDescription: Export Pandas Dataframe to subprocess as stdin


code:
if mystring[:6] == '[city.' and mystring[-1:] == ']':
    print 'success'

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


code:
for i in [1,2,3,4,5,'cat','fish']:
    i = i + i
    print i

rawDescription: modifying iterator in for loop in python

description: Modifying iterator in for loop in python


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

rawDescription: Python function returns None for non emptylist


code:
a = [4, 2, 1, 5]
a.sort()
print [x - i for i, x in enumerate(a)]

rawDescription: How to do an inverse `range`, i.e. create a compact range based on a set of numbers?

description: Do an inverse `range`, i.e. create a compact range based on a set of numbers


code:
data = {}
for lhs,rhs in my_list_of_tuples:

    try:
        data[lhs].append(rhs)
    except KeyError:
        data[lhs] = [rhs]

print data.items()[:5]

rawDescription: How can I separate and traverse data in a list of tuples in Python 2.6?

description: Separate and traverse data in a list of tuples in Python 2.6


code:
from itertools import takewhile
from bs4 import NavigableString

not_link = lambda t: getattr(t, 'name') not in ('a', 'strong')

for link in soup.find_all("a"):
    print 'Link contents:'
    text = link.text.strip()
    for sibling in takewhile(not_link, link.next_siblings):
        if isinstance(sibling, NavigableString):
            text += unicode(sibling).strip()
        else:
            text += sibling.text.strip()
    print text

rawDescription: How to extract text, with link and text after the link and another text after br with python

description: Extract text, with link and text after the link and another text after br with python


code:
from statsmodels.stats.multicomp import pairwise_tukeyhsd
print pairwise_tukeyhsd(Data, Group)

rawDescription: What statistics module for python supports one way ANOVA with post hoc tests (Tukey, Scheffe or other)?


code:
import re

str = 'ABCDX PPP [ATT:A01AD05 B01AC06 N02BA01]'
matched = re.search('([\S\s]+?)\s\[.*?(ATT:\S+)\s*(\S+)\s*(\S+)', str)
if matched:
    tokens = matched.groups()
    print tokens

rawDescription: Python regex expression and return an array


code: print '{:0{width}}'.format(k, width=kw) # prints 0000120000210000

rawDescription: Python, string , integer

description: Python, string , integer


code:
def prime2(n):
    for i in range(2, int(math.sqrt(n)) + 1):

        if n % i == 0:
            return False

    return True

max = int(input("What is your number? "))
print [x for x in range(max) if prime2(x)]

rawDescription: python - returning values for which if statement is true

description: Python - returning values for which if statement is true


code:
import os

class FileStats(object):
    def addScore(self, score):
        print score

score = 10
file_stats = {}
for root, directories, files in os.walk ("/tmp", followlinks=False):
    for filename in files:
        filePath = os.path.join(root,filename)
        if not filePath in file_stats:
            file_stats[filePath] = FileStats()
            file_stats[filePath].addScore(score)

rawDescription: Python file names as dictionary keys

description: Python file names as dictionary keys


code:
if age<1:
    print 'we have an infant'

rawDescription: How are these values being counted?

description: How are these values being counted


code:
import re

word = "james is funny"

new_word = re.sub('[^aeiou]', ' ', 'james is funny')

print new_word

rawDescription: How to use Python to show only the letters from words with vowels

description: Use Python to show only the letters from words with vowels


code:
for group in df2.groupby('type'):
    print group
    if group[0] == 'A':
        print group[1].min()
    if group[0] == 'B':
        print group[1].max()
    if group[0] == 'C':
        print group[1].mean()

rawDescription: how to apply different functions to each group of pandas groupby?

description: Apply different functions to each group of pandas groupby


code:
from collections import defaultdict
import csv

# you probably can think up better names
fields = ('x', 'class', 'indicator', 'col3', 'col4', 'col5', 'col6', 'col7', 'col8')

entries = defaultdict(list)

with open(filename, 'rb') as fd:
    reader = csv.DictReader(fd, fields)

    for row in reader:
        # each row is now a dictionary
        # make your numbers, numbers
        for field in fields[3:]:
            row[field] = row[field] and float(row[field])

        previous = entries[row['indicator']]
        for p in previous:
            if (row['col3'], row['col6']) == (2, 2) and (p['col3'], p['col6']) == (1, 1):
                print 'text data text {p[class]} text data {r[class]} text {r[col8]}'.format(p=p, r=row)
            # etc, testing againts previous rows with the same indicator

        # remember this row for later rows to match against.
        previous.append(row)

rawDescription: Selecting data from groups within a csv and appending data to text file


code:
import markdown
from markdown.treeprocessors import Treeprocessor
from markdown.extensions import Extension

# First create the treeprocessor

class ImgExtractor(Treeprocessor):
    def run(self, doc):
        "Find all images and append to markdown.images. "
        self.markdown.images = []
        for image in doc.findall('.//img'):
            self.markdown.images.append(image.get('src'))

# Then tell markdown about it

class ImgExtExtension(Extension):
    def extendMarkdown(self, md, md_globals):
        img_ext = ImgExtractor(md)
        md.treeprocessors.add('imgext', img_ext, '>inline')

# Finally create an instance of the Markdown class with the new extension

md = markdown.Markdown(extensions=[ImgExtExtension()])

# Now let's test it out:

data = '''
**this is some markdown**
blah blah blah
![image here](http://somewebsite.com/image1.jpg)
![another image here](http://anotherwebsite.com/image2.jpg)
'''
html = md.convert(data)
print md.images

rawDescription: How can I get a list of image URLs from a Markdown file in Python?

description: Get a list of image URLs from a Markdown file in Python


code:
if rank == 0:
    cb = numpy.zeros(size)
    rstat = MPI.Status()
    for i in range((size-1)*3):
        (neww,newdeltaw) = comm.recv(source=MPI.ANY_SOURCE, tag=1)
        print "newdelw is",newdeltaw,"neww is",neww
        cb[neww]=cb[neww]+newdeltaw
        print "cb=",cb

else:
    data = rank
    for i in range(3):
        comm.send((rank,data),dest=0,tag=1)

rawDescription: Ensuring two messages come from the same MPI task


rawDescription: python merge two lists (even/odd elements)

description: Python merge two lists (even/odd elements)


code:
print gr.number_of_edges(0, 1) # clearly has an edge
print gr.number_of_edges(2, 0) # no edge between 2 and 0

rawDescription: How to find the number of edges bewteen any two nodes using networkx?

description: Find the number of edges bewteen any two nodes using networkx


code:
import maya.standalone
maya.standalone.initialize()

import maya
print 'maya:\n', dir(maya)

from maya import cmds
print 'cmds:\n', len(dir(cmds)) # too many to print

print 'sphere: ', cmds.sphere

rawDescription: Eclipse environment for Maya's python modules


code:
def read(file):
    column1=[]
    column2= []
    readfile = open(file, 'r')
    data_separator = ' '  # one space to separate xxx and yyy
    column_separator = '    '  # 4 spaces to separate groups xxx,yyy    xxx,yyy

    for line in readfile.readlines():  # In case you have more than 1 line
         line = line.rstrip('\n')  # Remove EOF from line
         print line

         columns = line.split(column_separator)  # Get the data groups
         # columns now is an array like ['xxx yyy', 'xxx yyy', 'xxx yyy']

         for column in columns:
             if not column: continue  # If column is empty, ignore it
             column1.append(column.split(data_separator)[0])
             column2.append(column.split(data_separator)[1])
    readfile.close()

rawDescription: How to Split into Columns

description: Split into Columns


code:
import bisect
ranges = [0, 11, 21, 31]
di = {}
di[0] = 'A'
di[11] = 'B'
di[21] = 'C'
di[31] = 'unknown' # special value to indicate the end of the range

print di[ranges[bisect.bisect(ranges, 24) - 1]]
# C
print di[ranges[bisect.bisect(ranges, 6) - 1]]
# A
print di[ranges[bisect.bisect(ranges, 31) - 1]]
# Unknown

rawDescription: Associative array in python with keys as a fragment of array


code:
class Foobar(object):
    def __init__(self, value):
        self.value = value

class FoobarMixin(object):
    def __init__(self, **kwargs):
        foobar = kwargs['foobar']
        if isinstance(foobar, Foobar):
            self.foobar = foobar
        else:
            self.foobar = Foobar(foobar)

class Foo(FoobarMixin):
    def __init__(self, value, **kwargs):
        super(Foo, self).__init__(**kwargs)
        self.value = value
        print self.value, self.foobar

class Bar(FoobarMixin):
    def __init__(self, value, **kwargs):
        super(Bar, self).__init__(**kwargs)
        self.value = value
        print self.value, self.foobar

foo = Foo('foo', foobar='foobar')
bar = Bar('bar', foobar=Foobar('foobar'))

rawDescription: How can I make __init__ take a new value or an existing instance?

description: Make __init__ take a new value or an existing instance


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

rawDescription: Reverse multiple values with keys in dictionary


code:
for v2 in sorted(mapping):
    print '{} maps to {}'.format(v2, ', '.join(map(str, sorted(mapping[v2]))))

rawDescription: Python mapping between lists for duplicates


rawDescription: Beautiful Soup decode string

description: Beautiful Soup decode string


code:
from lxml import html
doc = html.parse('input.html')
print [ul.xpath('li[1] | li[2] | li[3]') for ul in doc.xpath('//ul')]

rawDescription: How do you find all list items between two tags with BeautifulSoup?

description: Find all list items between two tags with BeautifulSoup


code:
import json
json1 = '{\
    "choice_list": {\
        "name": "Boston Street Names",\
        "choices":[ {"value": "127906", "label": "DAVIS STREET"},\
                    {"value": "129909", "label": "NORTH QUINCY STREET" },\
                    { "value": "134194", "label": "ADAMS STREET" }]\
     } \
}'

json2 = '[{"value": "134484", "label": "PRISCILLA ALDEN ROAD"},\
 {"value": "134487", "label": "VAN BUREN DRIVE"}]'

res = json.loads(json1)
res['choice_list']['choices'] = json.loads(json2)
print json.dumps(res)

rawDescription: Replace object in json with another json file using python


code:
import fileinput

seen = set()
for line in fileinput.FileInput('test.csv', inplace=True):
    value = float(line)
    while value in seen:
        value -= 0.000001
    seen.add(value)
    print str(value).strip()

rawDescription: slightly fidgeting data that is equal

description: Slightly fidgeting data that is equal


code:
if __name__=='__main__':
    # these variables would normally be called in from a config file
    job_type = 'job1'
    uni_var = 10

    job_select = optionFactory(job_type, uni_var)
    job_select.job()

class superClass(object):
    def __init__(self, job_type, uni_var):
        self.job_type = job_type
        self.uni_var = uni_var

    # This is the definition called by the main function it then
    # redirects the request to the appropriate job sub class
    def job(self):
        raise NotImplementedError()

class option1(superClass):
    def __init__(self, job_type, uni_var):
        super(option1, self).__init__(job_type, uni_var)

    def job(self):
        print 'job option 1'
        print uni_var

class option2(superClass):
    def __init__(self, job_type, uni_var):
        super(option2, self).__init__(job_type, uni_var)

    def job(self):
        print 'job option 2'
        print uni_var

def optionFactory(job_type, uni_var):
    "Return an instance of superClass based on job_type and uni_var."
    if job_type == "job1":
        return option1(job_type, uni_var)
    else:
        return option2(job_type, uni_var)

rawDescription: correct class inheritance

description: Correct class inheritance


code:
from sys import argv # imports the opening of two separate files
import random # imports the 'random' string
script, filename = argv # sets two variables, one on the py file and the other on the txt file
txt = open(filename, 'r+') # opens the txt file

# card variables assigning values
Two = 1
Three = 2
Four = 3
Five = 4
Six = 5
Seven = 6
Eight = 7
Nine = 8
Ten = 9
Jack = 10
Queen = 11
King = 12
Ace = 13
# chooses a random card
score = 0 # score at game start
def scores(): # this will print out the current high scores.
    print "The current scores in file: %r" % filename
    print txt.read() # prints the open txt file

def start(): # this is sent after the scores. welcomes play to game.
    print "Welcome %s, the computer and you will both draw a card. Whoever gets the higher card wins" % name
    print "Try to in a row to go on the high scores!"
    print "Good luck %s" % name
    game() #starts the game

def game(): # begins the actual game
    global score
    print "The dealer draws a card..."
    dealer = random.choice([Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace]) # gives the dealer a random card
    print "You draw a card..."
    user = random.choice([Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace]) # gives the user a random card
    if dealer > user: # if dealer wins
        print "You lose!"
        if score > 1: # checks if score is better than 1, then writes score to txt doc
            txt.write("\n")
            txt.write("%s=%d" % (name, score))
            txt.close()
        else: # aren't good enough, game quits
            print "You didn't get a score over 1, you suck and aren't going to be on high scores."
            txt.close()
    elif user > dealer: # if user wins
        print "Nice! You won that round"
        score = score + 1 # adds 1 to current score
        game() # next round
    else:
        print "Um no idea what you did there, again?"
        game()

scores() # score def
name = raw_input("First off let's get your name. \n >") # asks the users name for recording high scores
start() # start def

rawDescription: Making a simple card game in python 2.7

description: Making a simple card game in python 2.7


code:
class Person():

    def __init__(self,name,number,email):
        self.name = name
        self.number = number
        self.email = email

# creating some example contacts
c1 = Person('Mike','1-800-foo-spam','email@email.com')
c2 = Person('Jim','1-700-foo-spam','e111mail@email.com')
c3 = Person('Kim','1-600-foo-spam','e222mail@email.com')

# creating a dictionary to fill it with c1..cn contacts
contacts = {}

# helper function to automate dictionary filling
def contactToDict(list_of_contacts):
    for item in list_of_contacts:
        contacts[item.name] = (item.number, item.email)

contactToDict([c1, c2, c3])

"""
expected output:
Mike: ('1-800-foo-spam', 'email@email.com')
Jim: ('1-700-foo-spam', 'e111mail@email.com')
Kim: ('1-600-foo-spam', 'e222mail@email.com')
"""
for key, val in contacts.items():
    print str(key) + ": " + str(val)

rawDescription: How do i store multiple object attibutes to a single dictionary key?

description: Store multiple object attibutes to a single dictionary key


rawDescription: itertools.product eliminating repeated elements

description: Itertools.product eliminating repeated elements


code:
def group_by_person(names_file, attributes_files):
    with open(names_file) as names, open(attributes_files) as attributes:
        for name in names:
            line = [name.strip()]
            for attribute in attributes:
                if attribute.startswith("$$$$"):
                    break
                line.append(attribute.strip())
            print line
            yield line

names_count = {}

for name in group_by_person('Names.txt', 'Attributes.txt'):
    n = name[0]
    names_count[n] = names_count.setdefault(n, 0) + 1
    with open("%s%s.txt" % (n, names_count[n]), 'w') as f:
        f.write('\n'.join(name))

rawDescription: Python Splitting a file into many files and adding in extra info


code:
class SetupClass(type):
    def __call__(cls, *args, **kwargs):
        # create the instance as normal.  this will invokoe the class's
        # __init__'s as expected.
        self = super(SetupClass, cls).__call__(*args, **kwargs)

        # this steps through the MRO in ascending order (so that child
        # classes can be confident their bases are "set up").  A corresponding
        # teardown() method should probably be `reversed(cls.__mro__)`
        for base in cls.__mro__:
            setup = vars(base).get('setup')
            # in the general case, we have to use the descriptor protocol
            # to setup methods/staticmethods/classmethods properly
            if hasattr(setup, '__get__'):
                setup = setup.__get__(self, cls)
            if callable(setup):
                setup()

        return self

class A(object):
    __metaclass__ = SetupClass
    def __init__(self):
        print "A.__init__"
    def setup(self):
        print "A.setup"
class B(A):
    def __init__(self):
        print "B.__init__"
        super(B, self).__init__()

rawDescription: in python is it possible to write a method that will be automatically called after __init__ of subclass

description: In python is it possible to write a method that will be automatically called after __init__ of subclass


code:
if threadCanStart:
    myThread(threadNumber, threadQueue).start()
    threadNumber += 1
    threadCanStart = False

try:
    #we have a return in the quqe
    returnValue = threadQueue.get(False)
    print "Queue return: ", returnValue
    threadCanStart = True
except Empty:
    print "Waiting for thread....."

rawDescription: Start one thread at a time with queqe

description: Start one thread at a time with queqe


code:
pages
print pages[0]

rawDescription: How to split a html page to multiple pages using python and beautiful soup

description: Split a html page to multiple pages using python and beautiful soup


code:
import csv

def split(path_to_file):
  reader = csv.reader(file(path_to_file))

  split_1 = []
  split_2 = []
  i = 0
  for line in reader:
    if i == 0:
        split_1.append(line[:-1])
        split_2.append(line[:-1])
    elif  i % 2 == 0:
      split_1.append(line[:-1])
    else:
      split_2.append(line[:-1])
    i = i + 1

  print split_1
  print split_2

rawDescription: Split CSV data in python

description: Split CSV data in python


code:
def process_element(elem):
    print "why does this consume all my memory?"
context = lxml.etree.iterparse('really-big-file.xml', tag='schedule', events = ('end', ))
fast_iter(context, process_element)

rawDescription: Why is lxml.etree.iterparse() eating up all my memory?


code:
def unset_mask(index):
    return ~(1 << index)

x = 0b11111111
x &= unset_mask(3)
print x == 0b11110111  # prints True

rawDescription: Creating a bit mask with BigInts

description: Creating a bit mask with BigInts


code:
for _, df_k in df.groupby(lambda x: x/2):
    print df_k.reset_index(drop=True)

rawDescription: Subsetting Data Frame into Multiple Data Frames in Pandas


code:
import re
with open("input") as f:
    for line in f:
        mo=re.match(r'[^\d]*(\d+).*?(tons|feet|lbs)', line)
        if mo: print mo.group(1), mo.group(2)

rawDescription: Matching Regex in Python

description: Matching Regex in Python


code:
with open("filename","rb") as myfile:
    mydata = myfile.read()
    for m in re.findall(r'[0-9]{8}.*\n.*\n.*\n.*\n.*', mydata):
        print m

rawDescription: Python RegEx Matching Newline

description: Python RegEx Matching Newline


code:
import numpy as np

a = np.random.randint(0, 100, [100,100])
b = a[:, a.sum(axis=0) > 5000]
print b.sum(axis=0)

rawDescription: Efficiently reduce a big np.array

description: Efficiently reduce a big np.array


code: print 'a' * 10

rawDescription: Python - print "x" "y" times when passed in a list of [x,y]


code:
class OmNom(object):
  def __init__(self):
     self.bacon = True
  def eat(self):
     self.bacon = False
     return 'Om nom nom'

monster = OmNom()
y = raw_input('Type eat: ')
print getattr(monster, y)()
# This is the same as
# z = getattr(monster, 'eat')
# Now z points to the eat method of the object, then
# z() will call that method.

rawDescription: Turning variable contents into line of code


code:
for row in db(db.reviews.game_id == 1).select():
    print row.title   # just an example

rawDescription: Web2Py getting/posting values

description: Web2Py getting/posting values


code:
from bs4 import BeautifulSoup
import urllib2

url = 'http://www.zooplus.co.uk/shop/dogs/dry_dog_food/royal_canin_vet_diet'
response = urllib2.urlopen(url)
html = response.read()
soup = BeautifulSoup(html,"html.parser")

product_list = soup.find_all("tbody", {"class":"product-variants-list"})

i=0

def visible(text):
    lines = (line.strip() for line in text.splitlines())
    # break multi-headlines into a line each
    chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
    # drop blank lines
    text = ''.join(chunk for chunk in chunks if chunk)
    return text

for product in product_list:

    product_name = product.find("a",{"class":"follow3"}).find("b").text
    print i, product_name
    product_variants = product.find_all("tr",{"class":"product-variant"})

    i +=1

    for variant in product_variants:
        product_weight = variant.find_all("td")[0].string
        print '-'+product_weight,
        print ' | ',
        if variant.find_all("td")[1].find("span",{"class":"specialPrices"}) is not None:
            product_price = variant.find_all("td")[1].find("span",{"class":"specialPrices"}).find("span",{"class":"smalltextPrices"}).get_text(" ", strip=True)
            product_price_per_kg = visible(product_price)
        else:
            product_price = variant.find_all("td")[1].find("span",{"class":"smalltext"}).get_text(" ", strip=True)
            product_price_per_kg = visible(product_price)

        print product_price_per_kg

rawDescription: What is the appropriate tag to scrape those particular informations?


code:
# Tally occurrences of words in a list
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
    cnt[word] += 1
print cnt

# Find the ten most common words in Hamlet
import re
words = re.findall('\w+', open('hamlet.txt').read().lower())
Counter(words).most_common(10)

rawDescription: How can I find frequency of a specific word from document in python?

description: Find frequency of a specific word from document in python


code:
prev = None
it = iter(data)
for point in it:
    if point == 'red':
       print '#',
    else:
       print '.',
       if prev == 'red': # encounted ['red', 'blank']
          break
    prev = point

for point in it:
    print '.',
print

rawDescription: running through a loop and find a condition that match

description: Running through a loop and find a condition that match


code: print df.groupby('Loser').size()

rawDescription: pandas dataframe aggregate calculation

description: Pandas dataframe aggregate calculation


code: print sum([int(i) for i in f])

rawDescription: Python: reading integers from a file

description: Python: reading integers from a file


code:
#Build default data list
defdata = '''
Data1 = 1
Data2 = 2
Data3 = 3
Data4 = 4
Data5 = 5
Data6 = 6
'''.splitlines()[1:]

#Build output data list
outdata = '''
Data1 = 1
Data2 = 2
Data3 = 8
Data4 = 7
Data8 = 8
'''.splitlines()[1:]

def make_dict(data):
    return dict((line.split(None, 1)[0], line) for line in data)

defdict = make_dict(defdata)
outdict = make_dict(outdata)

#Create a sorted list containing all the keys
allkeys = sorted(set(defdict) | set(outdict))
#print allkeys

difflines = []
for key in allkeys:
    indef = key in defdict
    inout = key in outdict
    if indef and not inout:
        difflines.append(defdict[key])
    elif inout and not indef:
        difflines.append(outdict[key])
    else:
        #key must be in both dicts
        defval = defdict[key]
        outval = outdict[key]
        if outval != defval:
            difflines.append(outval)

for line in difflines:
    print line

rawDescription: Compare two text files to find differences and output them to a new text file


code:
soup.find(text='Titles').parent
for elem in soup.find_all(text='Titles'):
    parent_h3 = elem.find_parent('h3')
    if parent_h3 is None:
        continue
    print parent_h3

rawDescription: BeautifulSoup not finding parents

description: BeautifulSoup not finding parents


code:
from pyparsing import Word, nums, oneOf, Combine, Group, Optional

integer = Word(nums)

sign = oneOf("+ -")
signedInteger = Combine(sign + integer)

integerExpr = Group(integer("base") + Optional(signedInteger, default="0")("offset"))

integerRange = integerExpr("start") + Optional('_' + integerExpr("end"))

tests = """\
12
12+34
12_56
12+34_56-78""".splitlines()

for t in tests:
    result = integerRange.parseString(t)
    print t
    print result.dump()
    print result.asDict()
    print result.start.base, result.start.offset
    if result.end:
        print result.end.base, result.end.offset
    print

rawDescription: parsing nested structures with pyparsing

description: Parsing nested structures with pyparsing


code:
import sys
print sys.maxunicode

rawDescription: How to find out if Python is compiled with UCS-2 or UCS-4?

description: Find out if Python is compiled with UCS-2 or UCS-4


code:
l = [['ServerA','Envname1','abc','xyz'],
     ['ServerA','Envname2','abc','xyz'],
     ['ServerB','Envname3','aaa','bbb'],
     ['ServerC','EnvName4','uuu','vvv'],
     ['ServerB','Envname5','aaa','bbb'],
     ]

d = {}
for item in l:
    key = (item[0], item[2], item[3])
    env = d.setdefault(key, [])
    env.append(item[1])

final_list = [[k[0], ",".join(v), k[1], k[2]] for k, v in d.items()]
print final_list

rawDescription: grouping list of list in python for a particular element

description: Grouping list of list in python for a particular element


code:
def add(a, b):
    c = a+b
    return c

def sub(a, b):
    c = a-b
    return c

def print_result(fn, a, b):
    print "Your answer is: ", str(fn(a, b))    ## print function's return value

answer = add(10, 15)
print answer
## Will print 25

print_result(add, 10, 20)
## Will print """Your answer is 30"""

print_result(sub, 10, 20)
## Will print """Your answer is -10"""

rawDescription: How to tell if a function will be returning a value to a variable?

description: Tell if a function will be returning a value to a variable


code:
count = 0
total = 0
fname = raw_input("Enter file name: ")
fh = open(fname)

for lines in fh:
    if lines.startswith ("X-DSPAM-Confidence:"):
        count += 1
        total += float (lines [20:50])
        print lines
        print count

print(total/count)

rawDescription: work with files, how to calculate Avrg

description: Work with files, how to calculate Avrg


code:
from suds.client import Client
url = 'http://www.thomas-bayer.com/axis2/services/BLZService?wsdl'
client = Client(url)
print client

rawDescription: Changing web service url in SUDS library


code:
import re
import ast

def match_line(line):
    while line:
        print "Trying to match:", line
        try:
            return ast.literal_eval(line)
        except SyntaxError, e:
            line = line[:e.offset - 1]
        except ValueError: # No way it would ever match
            break
    return None

with open('test.txt.') as f:
    for line in f:
        match = match_line(line.strip())
        print "Matched:", match
        print

rawDescription: Escaping quotes when isolating strings from input


rawDescription: Parsing apache log files

description: Parsing apache log files


code:
import urllib2
html = urllib2.urlopen("http://www.amazon.co.uk/product-reviews/B00143ZBHY").read()
from lxml import etree
tree = etree.HTML(html)
r = tree.xpath(".//*[@id='productReviews']/tr/td[1]/div[9]/text()[4]")
print r[0]

rawDescription: Not able to parse html using lxml Xpath parser


code:
def function(a, b, c, d):
    l= locals()
    dirty= False
    for i in l:
        key = l[i]
        if isinstance(key, str):
            l[i] = [l[i]]
            dirty= True
    if dirty:
        function(**l)
    else:
        print a, b, c, d
    print (l)

function('one', 'two', ['bla','bla'], ['ble'])

rawDescription: Convert function arguments to lists

description: Convert function arguments to lists


code:
df
print df.to_latex()

rawDescription: Formatting latex (to_latex) output

description: Formatting latex (to_latex) output


code:
from Tkinter import*
import time
import tkMessageBox
import random

def Questions():
    number1 = random.randrange(1,25)
    number2 = random.randrange(1,50)
    answer = number1 + number2
    prompt = ("Add " + str(number1) + " and " + str(number2))
    label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
    label1.pack()
    return answer

def start():
    global count_flag
    global answer
    answer = Questions()
    count_flag = True
    count = 0.0
    while True:
        if count_flag == False:
            break
        # put the count value into the label
        label['text'] = str(count)
        # wait for 0.1 seconds
        time.sleep(0.1)
        # needed with time.sleep()
        root.update()
        # increase count
        count += 0.1

def Submit(answer, entryWidget):
     """ Display the Entry text value. """
     global count_flag

     count_flag = False
     print answer

     if entryWidget.get().strip() == "":
         tkMessageBox.showerror("Tkinter Entry Widget", "Please enter a number.")

     if answer != int(entryWidget.get().strip()):
         tkMessageBox.showinfo("Answer", "INCORRECT!")
     else:
         tkMessageBox.showinfo("Answer", "CORRECT!")

# create a Tkinter window
root = Tk()

root.title("Math Quiz")
root["padx"] = 40
root["pady"] = 20

# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(root)

#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Answer:"
entryLabel.pack(side=LEFT)

# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)

textFrame.pack()

#directions
directions = ('Click start to begin. You will be asked a series of questions.')
instructions = Label(root, text=directions, width=len(directions), bg='orange')
instructions.pack()

# this will be a global flag
count_flag = True

Sub = lambda: Submit(answer, entryWidget)
#stopwatch = lambda: start(answer)

# create needed widgets
label = Label(root, text='0.0')
btn_submit = Button(root, text="Submit", command = Sub)
btn_start = Button(root, text="Start", command = start)
btn_submit.pack()
btn_start.pack()
label.pack()

# start the event loop
root.mainloop()

rawDescription: Tkinter Math Quiz

description: Tkinter Math Quiz


code:
fun = ugly_math()
cid_dict = {}
# Define the event
def ontype(event):
    if event.key == '1':
        print 'It is working'
        try:
            vector = fun.next()
            plt.plot(vector)
            fig.canvas.draw()
        except StopIteration:
            plt.gcf().canvas.mpl_disconnect(cid_dict['cid'])
            del cid_dict['cid']

# Create figure an connect the event to it
fig=plt.figure(figsize=(16,8))
cid_dict['cid'] = plt.gcf().canvas.mpl_connect('key_press_event',ontype)

vector = np.random.random(10)
plt.plot(vector)
plt.show()

rawDescription: Using events with matplotlib in a for loop


code:
def ctrl_buttons(self, button):
    if button.text=="PLAY":
        print "pressed play"
    elif button.text=="STOP":
        print "pressed stop"

rawDescription: Kivy/python. One callback function for several buttons


code:
def a(ret):
    print 'run a, a succeeded?', ret
    return ret

def b(ret):
    print 'run b, b succeeded?', ret
    return ret

def c(ret):
    print 'run c, c succeeded?', ret
    return ret

rawDescription: Pythonic way to "run X before Y if Y fails"?


code:
from sqlalchemy.ext import compiler
from sqlalchemy.sql.expression import Executable, ClauseElement

class InsertFromSelect(Executable, ClauseElement):
    def __init__(self, table, select):
        self.table = table
        self.select = select

@compiler.compiles(InsertFromSelect)
def visit_insert_from_select(element, compiler, **kw):
    return "INSERT INTO %s (%s)" % (
        compiler.process(element.table, asfrom=True),
        compiler.process(element.select)
    )

insert = InsertFromSelect(t1, select([t1]).where(t1.c.x>5))
print insert

rawDescription: How do I INSERT INTO t1 (SELECT * FROM t2) in SQLAlchemy?


code:
from itertools import count, islice
item_count_per_section, counter = {1: 3, 2: 5, 3: 2, 4: 2}, count()
print {k:list(islice(counter, v)) for k, v in item_count_per_section.items()}

rawDescription: Slice list to ordered chunks

description: Slice list to ordered chunks


code: print "Length: %s" % len(self.listOfThings)

rawDescription: Python List length as a string

description: Python List length as a string


code:
L1 = readRows()
for row in L1:
    print row[0], row[1], row[2]

rawDescription: Help with Excel, Python and XLRD

description: Help with Excel, Python and XLRD


code:
result = []
for c in this.s:
   result.append(((c in this.d) and this.d[c]) or c)
print "".join(result)

rawDescription: Dissecting a line of (obfuscated?) Python


code:
import httplib
conn = httplib.HTTPConnection("sstatic.net")
conn.request("HEAD", "/stackoverflow/img/favicon.ico")
res = conn.getresponse()
print res.getheaders()

rawDescription: Django: check if an image exists at some particular url


code:
import urllib2
from bs4 import BeautifulSoup

base_url = "http://www.boostmobile.com/stores/?page={page}&zipcode={zipcode}"
num_pages = 10
zipcode = 30008

for page in xrange(1, num_pages + 1):
    url = base_url.format(page=page, zipcode=zipcode)
    soup = BeautifulSoup(urllib2.urlopen(url))

    print "Page Number: %s" % page
    results = soup.find('table', class_="results")
    for h2 in results.find_all('h2'):
        print h2.text

rawDescription: Trouble printing all items from a list in python


code:
@app.route("/client")
def initial_template():
    return render_template('client.html')

@app.route("/client_state")
def get_change():
    print request.args.get('firstchange')

rawDescription: flask receiving url changes from pushstate

description: Flask receiving url changes from pushstate


rawDescription: Storing image data (fonts) in hexadecimal format in Python


code:
import shlex
s = shlex.split("./script --arg1 --cmdname otherscript --a1 --a2 --cmdname-- --arg3")
def preprocess(lst):
    """
    process an iterable into 2 lists.
    The second list contains the portion bracketed by '--cmdname' and '--cmdname--'
    whereas the first portion contains the rest of it.
    """
    argv1,argv2 = [],[]
    current = argv1
    for i in lst:
        if i == '--cmdname':
           current = argv2
        elif i == '--cmdname--':
           current = argv1
        else:
           current.append(i)
    return argv1,argv2

l1,l2 = preprocess(s)
print l1
print l2

rawDescription: How do I parse argparse arguments into a list of strings, stopping on a predefined flag argument?

description: Parse argparse arguments into a list of strings, stopping on a predefined flag argument


code:
import json
import urllib2
import twitter

ckey = 'Your consumer key'
csecret = 'your consumer secret'
atoken = 'your token'
asecret = 'your secret token'

auth = twitter.oauth.OAuth(atoken, asecret,
                           ckey, csecret)

twitter_api = twitter.Twitter(auth=auth)

q = 'http://on.fb.me'

count = 100

search_results = twitter_api.search.tweets(q=q, count=count)

statuses = search_results['statuses']

# Iterate through 5 more batches of results by following the cursor

for _ in range(5):
    print "Length of statuses", len(statuses)
    try:
        next_results = search_results['search_metadata']['next_results']
    except KeyError, e: # No more results when next_results doesn't exist
        break

    # Create a dictionary from next_results, which has the following form:
    # ?max_id=313519052523986943&q=NCAA&include_entities=1
    kwargs = dict([ kv.split('=') for kv in next_results[1:].split("&") ])

    search_results = twitter_api.search.tweets(**kwargs)
    statuses += search_results['statuses']

# Show one sample search result by slicing the list...
print json.dumps(statuses[0], indent=1)

# get relevant data into lists
user_names = [ user_mention['name']
                 for status in statuses
                     for user_mention in status['entities']['user_mentions'] ]

screen_names = [ user_mention['screen_name']
                 for status in statuses
                     for user_mention in status['entities']['user_mentions'] ]

id_str = [ user_mention['id_str']
                 for status in statuses
                     for user_mention in status['entities']['user_mentions'] ]

t_id = [ status['id']
         for status in statuses ]

# print out first 5 results
print json.dumps(screen_names[0:5], indent=1)
print json.dumps(user_names[0:5], indent=1)
print json.dumps(id_str[0:5], indent=1)
print json.dumps(t_id[0:5], indent=1)

rawDescription: extracting data from the tweets of the twitter using python

description: Extracting data from the tweets of the twitter using python


code:
import distutils.sysconfig
print distutils.sysconfig.get_config_vars()

rawDescription: How to get the list of options that Python was compiled with?

description: Get the list of options that Python was compiled with


code:
import pandas as pd

df = pd.DataFrame( [
    ['2011-01-01 01:00', 1, 2, 3],
    ['2011-01-01 02:00', 10, 20, 30],
    ['2011-01-01 03:00', 100, 200, 300],
    ['2011-01-02 01:00', 4, 5, 6],
    ['2011-01-02 02:00', 40, 50, 60],
    ['2011-01-02 03:00', 400, 500, 600],
], columns=['datetime','a','b','c'])

# convert string datetime to object datetime
df['datetime'] = pd.to_datetime(df['datetime'])

# now I have example dataframe for work

# create row with date only
df['date'] = df['datetime'].apply(lambda t: t.date())

# groupe by date
g = df.groupby('date').mean()

# change `date` from index to normal column
g2 = g.reset_index()

# merge by `date` columns
new_df = pd.merge(left=df, right=g2, on='date', suffixes=('_df','_group') )

print df
print g
print g2
print new_df

rawDescription: Add multi year average column to each row


code:
import sys
print sys.path #  print a list of locations Python searches for modules
sys.path.append('Z:\\path\\I\\need')

# now import your modules
import my_module

rawDescription: Pydev wine pythonpath issues/console initialization timeout issue


code:
# This must have the same number of values as lines in the file
L = ['2.3','1.2']
with open("file1.txt", "r") as f:
    # skip the first line but output it?
    print f.readline().rstrip('\n')

    for value,line in zip(L,f):
        elements = line.split()
        print "{}\t{}\t{}".format(elements[0],value,elements[2])

rawDescription: How to replace a column in a text file using a list?

description: Replace a column in a text file using a list


code:
array = '[1, 2, 3]' # Or array = '1, 2, 3', whatever the case may be
for item in array:
    try:
        print int(item)
    except ValueError:
        pass

rawDescription: Exclude Char from Python For

description: Exclude Char from Python For


code: print "<%s>" % my_dict[key].attribute

rawDescription: Python: Accessing object attributes from objects stored in a dictionary


code:
#!/usr/bin/env python

def make_list(first_item):
    list_new = []
    list_new.append(first_item)
    return list_new

def add_item(list, item):
    list.append(item)
    return list

mylist = make_list(1)
mylist = add_item(mylist, 2)

print mylist    # prints [1, 2]

rawDescription: adding to a list defined in a function

description: Adding to a list defined in a function


code:
data = r.content.decode('UTF-8')
# or
data = r.content.decode(r.encoding)
# then
node = lxml.html.fromstring(data)
self.fingerprint['Title'] = node.cssselect('.document-title div')[0].text
print '@@####', self.fingerprint['Title']

rawDescription: lxml not parsing unicode properly for HTML

description: Lxml not parsing unicode properly for HTML


code:
import re
pattern = re.compile(
    r'(?<!\\)(?:\\\\)*(?P<quote>["\'])(?P<value>.*?)(?<!\\)(?:\\\\)*(?P=quote)'
)

for s in data:
    print pattern.findall(s)

rawDescription: Extract unquoted text from a string

description: Extract unquoted text from a string


code:
print [text.parent for text in soup.find_all(text=must_contain_all("world", "puzzle"))]
# [
Who in the world am I? Ah, that's the great puzzle.
]

rawDescription: Find different strings and return containing tag in BeautifulSoup


code:
Session = sessionmaker(bind=engine)
s = Session()

i = Item('ball', 'A round full ball')
i.notes['color'] = 'orange'
i.notes['size'] = 'big'
i.notes['data'] = 'none'

s.add(i)
s.commit()
print i.notes

rawDescription: SQLAlchemy - Dictionary of tags

description: SQLAlchemy - Dictionary of tags


code:
html = """

MyWord

    MyWord

MyWord!

        MyWord

    MyWord

"""

import lxml.etree as etree

tree = etree.fromstring(html)
for elem in tree.iter():
    if elem.text:
        elem.text = re.sub(r'MyWord', 'Myword', elem.text)
    if elem.tail:
        elem.tail = re.sub(r'MyWord', 'Myword', elem.tail)

print etree.tostring(tree)

rawDescription: How can I determine if it's ok to change this word... python script

description: Determine if it's ok to change this word... python script


code:
print min(zip(list1, list2))[1]
# 3

rawDescription: Find the minimum value of a list and print the corresponding index from another list


code:
from collections import defaultdict
from itertools import izip, tee
import os
import sys

# http://en.wikipedia.org/wiki/Hamming_distance#Algorithm_example
def hamming_distance(s1, s2):
    """ Count number of mismatched characters in equal length strings. """
    if not isinstance(s1, basestring): raise ValueError('s1 is not a string')
    if not isinstance(s2, basestring): raise ValueError('s2 is not a string')
    if len(s1) != len(s2): raise ValueError('string lengths do not match')
    return sum(a != b for a, b in izip(s1, s2))

def pairwise(iterable):  # itertools recipe
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

inp = sys.argv[1]  # Input file

unique = defaultdict(list)
with open(inp, 'rb') as file:
    for fields in (line.strip().split('-') for line in file):
        id = '-'.join(fields[:-1])  # recombine all but last field into an id
        unique[id].append(fields[-1])  # accumulate ending fields with same id

for id in sorted(unique):
    final_fields = unique[id]
    final_fields.sort(key=lambda field: len(field))  # sort by length
    print id + ':' + '-'.join(final_fields)
    if len(final_fields) > 1:  # at least one pair to compare for mismatches?
        for a, b in pairwise(final_fields):
            if len(a) == len(b) and hamming_distance(a, b) < 2:
                print '  {!r} and {!r} differ by < 2 characters'.format(a, b)

rawDescription: Comparing items in large list - finding items differing in 1 letter by length - Python


code:
my_list = [lambda x:x**2,lambda x:x**3]
print my_list[0](2)  #4
print my_list[1](2)  #8

rawDescription: Python functions within lists

description: Python functions within lists


code:
from random import randint as ri; x = 'fo0'; \
    print ' '.join([''.join([c*ri(1, 5) for c in x]) for i in range(ri(1, 5))])

rawDescription: Printing a random amount of characters a random amount of times in one line


code:
# Get the set for clusters 0 and 1
print union_find[0]
print union_find[1]

rawDescription: Implementing Disjoint Set Data Structure in Python


code:
for acid in formate:
    weight = sum(weights[a] for a in acid)
print "The molecular weight of this protein is", weight

rawDescription: How I can add the molecular Weight of my new list of strings using a mw dictionary?


code:
print timeit.timeit("z[:,ycond,:]", setup="from __main__ import solution4, z, xcond, ycond, xx, yy", number=N)
print timeit.timeit("z[:,:,xcond]", setup="from __main__ import solution4, z, xcond, ycond, xx, yy", number=N)

# running the above with xx=6000, yy=6000 gives
# 1.44903206825
# 5.98445320129

rawDescription: Conditioning and operation on multidimensional (3D) array in Python-NumPy


code:
print 'bc' < 'ba'
# False
print 'bc' < 'bda'
# True
print 'bcxyzterry' < 'bda'
# True

rawDescription: Finding out exact match in python

description: Finding out exact match in python


code:
a = 25

def enclosing():
   a = 2
   def enclosed():
       print a
   enclosed()

enclosing()

# Prints 2, as supplied in the enclosing scope, instead of 25 (found in the global scope)

rawDescription: Python : Why is it said that variables that are only referenced are implicitly global?


code:
set_1 = [["yes", 1], ["maybe", 1], ["never", 0], ["nopes", 0], ["si", 1]]
set_2 = ["of course", "yes", "always", "never", "no way", "no"]

def predict_label(item):
    return 2 # just to check which items got predicted

def labeled_set(set1, set2):
    dset_1 = dict(set1)
    labeled_set_2 = []
    for item in set2:
        if item in dset_1.keys():
            labeled_set_2.append([item, dset_1[item]])
        else:
            labeled_set_2.append([item, predict_label(item)])
    return labeled_set_2

print labeled_set(set_1, set_2)

rawDescription: How to find and order duplicates in data sets

description: Find and order duplicates in data sets


code:
from SimpleCV import *

image = Image('image.png')
binarized = image.binarize(220).invert()
blobs = binarized.findBlobs()
rabbit = next(b for b in blobs if abs(750 - b.area()) < 60)

print rabbit.coordinates()

rawDescription: How do I locate the rabbit?

description: Locate the rabbit


code:
import difflib as dl

fone = set(['apple', 'orange', 'ice', 'icecream'])
ftwo = set(['apple' ,'pear' ,'ice'])

result = []
for wone in fone:
    for wtwo in ftwo:
        s = dl.SequenceMatcher(None, wone, wtwo)
        if s.ratio() > 0.6:  #0.6 is the conventional threshold to define "close matches"
            result.append(wone)
            result.append(wtwo)
for w in set(result):
    print w

rawDescription: Comparing two .txt files in Python and saving exact and similar matches to .txt file


code:
import ast
import inspect

def is_variable_used(func, variable):
    source = inspect.getsource(func).split('\n', 1)[1]  # Split to drop the decorator part
    return sum(node.id == variable for node in ast.walk(ast.parse(source))
               if isinstance(node, ast.Name)) > 1

def auth(func):
    def dec(self, *args):
        if is_variable_used(func, 'user'):
            print 'Calling {func_name} with user.'.format(func_name=func.__name__)
            return func(self, user=100)
        else:
            print 'Calling {func_name} without user.'.format(func_name=func.__name__)
            return func(self)
    return dec

@auth
def func1_with_user(foo, user=None):
    return 10 + user

@auth
def func2_with_user(foo, user=None):
    a = 10 + foo
    b = a + foo
    c = a + b + user
    return a + b + c

@auth
def func1_without_user(foo, user=None):
    pass

@auth
def func2_without_user(foo, user=None):
    return 10 + foo

print func1_with_user(10)
print func2_with_user(20)
print func1_without_user(100)
print func2_without_user(200)

rawDescription: Check if a function uses a specific keyword argument


code:
from collections import namedtuple
xyz = namedtuple('xyz', ['a', 'b', 'c', 'd', 'e'])  # Creates an 'xyz' class
my_var = xyz(0x64, 0x32, 0x16, True, 'a')  # Creates an instance of that class
print my_var.a

rawDescription: How to implement c++ type structures in python?

description: Implement c++ type structures in python


code:
def wrap_me(fn):
    names = fn.func_code.co_varnames
    if names and names[0]=='self':
        print 'looks like an instance method'
    else: print 'looks like a function'
    return fn

rawDescription: Python: decorate __call__ and ordinary function with the same decorator?


code:
import re

dic = dict()

with open('txt', 'r') as fh:
    memory = None
    for line in fh.readlines():
        lines = line.rstrip('\n')
        if line.split():
            try:
                match = re.search('(BoardType|Subject)', line)
                if match:
                    memory = match.group(1)
                    dic.setdefault(memory, {})
                    header = line.split()
                    mark_index = header[2:]
                else:
                    mark_dict = dict()
                    lines = [ x for x in line.split(' ') if x]
                    date, sub, num = lines[0], lines[1], [str(x) for x in lines[2:]]
                    dic[memory].setdefault(sub, {})
                    mark = dict(zip(mark_index, num))
                    dic[memory][sub][date] = mark
            except Exception as error:
                print 'Error: ', error
import pprint
pprint.pprint(dic)

rawDescription: How to create a dictionary from a dictionary in python?

description: Create a dictionary from a dictionary in python


code:
import os, new

class DynamicKargs(object):
    """
    Class that makes a run method with same arguments
    as those given to the constructor
    """
    def __init__(self, **kargs):
        karg_repr = ','.join([str(key)+'='+repr(value) \
                              for key,value in kargs.iteritems()])
        exec 'def run(self,' + karg_repr + ',**kargs):\n    return self._run(' + karg_repr + ',**kargs)'

        self.run = new.instancemethod(run, self)

    def _run(self, **kargs):
        print kargs

# this can also be done with a function
def _run(**kargs):
    print kargs

def dynamic_kargs(**kargs):
    karg_repr = ','.join([str(key)+'='+repr(value) for key,value in kargs.iteritems()])
    exec 'def run(' + karg_repr + ',**kargs):\n    return _run(' + karg_repr + ',**kargs)'
    return run

# example of use
# --------------
def example():
    dyn_kargs = DynamicKargs(question='ultimate', answer=42)
    print 'Class example \n-------------'
    print 'var number:', dyn_kargs.run.im_func.func_code.co_argcount
    print 'var names: ', dyn_kargs.run.im_func.func_code.co_varnames
    print 'defaults:  ', dyn_kargs.run.im_func.func_defaults
    print 'run print: ',
    dyn_kargs.run()
    print ''

    dyn_kargs = dynamic_kargs(question='foo', answer='bar')
    print 'Function example \n----------------'
    print 'var number:', dyn_kargs.func_code.co_argcount
    print 'var names: ', dyn_kargs.func_code.co_varnames
    print 'defaults:  ', dyn_kargs.func_defaults
    print 'run print: ',
    dyn_kargs()

rawDescription: Dynamically adding key-arguments to method


code:
import types

class obj(object):
    def __init__(self, arg):
        self.name = arg

def extract_name(obj):
    if type(obj) is types.DictType:
        return obj['name']
    else:
        return obj.__dict__['name']

d = { 'name': 'Jill'}
print sorted([obj('Jack'), d], key=extract_name)

rawDescription: Sorting a heterogeneous list of objects in Python


code:
base = __import__("_base")  # This is equivalent to `import base`. Python understands it, but PyCharm doesn't.

class YourBaseClass(base.DjangoBaseClass):  # PyCharm doesn't know what class this is! No autocomplete.
    def method_that_shows(self):
        print "The method that shows is there!"

rawDescription: In Python, can I hide a base class's members?


code:
def onOpenFile(self, event):
    """
    Create and show the Open FileDialog
    """
    dlg = wx.FileDialog(
        self, message="Choose a file",
        defaultDir=self.currentDirectory,
        defaultFile="",
        wildcard=wildcard,
        style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
        )
    if dlg.ShowModal() == wx.ID_OK:
        paths = dlg.GetPaths()
        print "You chose the following file(s):"
        for path in paths:
            print path
    dlg.Destroy()

#----------------------------------------------------------------------
def onSaveFile(self, event):
    """
    Create and show the Save FileDialog
    """
    dlg = wx.FileDialog(
        self, message="Save file as ...",
        defaultDir=self.currentDirectory,
        defaultFile="", wildcard=wildcard, style=wx.SAVE
        )
    if dlg.ShowModal() == wx.ID_OK:
        path = dlg.GetPath()
        print "You chose the following filename: %s" % path
    dlg.Destroy()

rawDescription: Set extension type for open and save dialogs


rawDescription: Python -Filtering links from user inputted data


code:
s = Stack()

# fill the stack with values:
for i in xrange(10):
    s.push(i+1)

print s # Outputs: [1,2,3,4,5,6,7,8,9,10]

s.pop()
s.pop()

print s # Outputs: [1,2,3,4,5,6,7,8]

rawDescription: Python stack simulation using list structure but not list methods


code:
print 'Check C-order'
for k in xrange(N):
    ii = tuple(binassign[:,k])
    jj = tuple(bassign_rev_C[k,:])
    print ii==jj,ii,jj

print 'Check F-order'
for k in xrange(N):
    ii = tuple(binassign[:,k])
    jj = tuple(bassign_rev_F[k,:])
    print ii==jj,ii,jj

rawDescription: Numpy interconversion between multidimensional and linear indexing


rawDescription: Matching substring in pattern in Python

description: Matching substring in pattern in Python


code:
from lxml import etree

with open('file.xml') as xml_file:
    tree = etree.fromstring(xml_file.read())

for child in tree.xpath('//root/Module/register'):
    name = ''.join(child.xpath('./@name'))
    offset = ''.join(child.xpath('./@offset'))
    width = ''.join(child.xpath('./@width'))
    access = ''.join(child.xpath('./@access'))
    description = ''.join(child.xpath('.//description/text()'))

    print "[*] Register Name: {}".format(name)
    print "[*] Register Offset: {}".format(offset)
    print "[*] Register Width: {}".format(width)
    print "[*] Register Access: {}".format(access)
    print "[*] Description: {}".format(description)
    print ""

rawDescription: Display the contents of an element in xml using python


rawDescription: super simple cipher function in python. comparing a list to keys in a dictionary

description: Super simple cipher function in python. comparing a list to keys in a dictionary


code:
from bs4 import BeautifulSoup as bsoup

html = """

	Snap Id	Snap Time	Sessions	Cursors/Session

Begin Snap:	98810	29-Jun-15 08:00:02	700	    129.6

End Snap:	98864	29-Jun-15 17:00:23	703	    129.1

Elapsed:	 	             540.35 (mins)

DB Time:	 	           2,963.17 (mins)

"""

soup = bsoup(html)

list_of_tables = soup.find_all("table", {"summary":"This table displays snapshot information"}) # This will return 3 tables based on the above HTML.
target_table = list_of_tables[0] # Target the first one.

list_of_tds = target_table.find_all('td', class_='awrnc')
target_td = list_of_tds[2]
target_value = target_td.get_text()
print target_value
# 29-Jun-15 08:00:02

rawDescription: extract date from html document

description: Extract date from html document


code:
class MyClass():
    temp = []
    def myfunc(self, val):
          self.temp.append(val)
          print self.temp

instance1 = MyClass()
instance1.myfunc(1)    # [1]
instance2 = MyClass()
instance2.myfunc(2)    # [1, 2]

rawDescription: Understanding instance and class variable python


code:
from Crypto.Cipher import Blowfish
from binascii import hexlify, unhexlify

perl_pass = unhexlify("9033c838e4418fbdc50a9fc0813745296d195d59954008f94b2b36a8e65dca959686206960a7828a")

key = unhexlify("781e5e245d69b566979b86e28d23f2c78e938564cd1410f0ec1c1781466a6738bab0a6ed984c75ab34c68bbf7558077714043c5bdb959e46")
iv  = '$KJh#(}q'
print Blowfish.new(key, Blowfish.MODE_CBC, iv).decrypt(perl_pass)

rawDescription: Using PyCrypto to decrypt Perl encrypted password


code:
for pair in pairs:
    print '{0:10} {1}'.format(pair[0], pair[1])

rawDescription: How to use python to format strings with delimiter into columns

description: Use python to format strings with delimiter into columns


rawDescription: Given a list, How to count items in that list?


code:
with Capturing() as output:
    print 'hello world'

print 'displays on screen'

with Capturing(output) as output:  # note the constructor argument
    print 'hello world2'

print 'done'
print 'output:', output

rawDescription: How to capture stdout output from a Python function call?

description: Capture stdout output from a Python function call


code:
PROGRAM_NAME = "python2\0stack.py"
MAX_PID = int(open("/proc/sys/kernel/pid_max").read())

for pid in xrange(MAX_PID):
    try:
        cmd = open("/proc/" + str(pid) + "/cmdline").read().strip("\0")
        if PROGRAM_NAME in cmd:
            print cmd.split("\0")
            break
    except IOError:
        continue

rawDescription: In Python, command line args without import?


code:
for span in soup.select('div.views-row-1 > span'):
    print span.text.strip()

rawDescription: Extra newline character for children of Beautiful Soup


code:
from bs4 import BeautifulSoup

html = """

         November General Election Day.Scheduled Elections:
            My Test String

Federal, Statewide, Legislative and Judicial Offices

County Offices

Initiatives and Constitutional Amendments, if applicable

New Paragraph

"""

soup = BeautifulSoup(html)
table = soup.find("table", {"class": "election"})
rows = table.find_all("tr")

data = []
for row in rows:
    for element in row.select('td li'):
        element.insert(0, '\n')
    data.append([ele.text.strip() for ele in row('td')])

print data

rawDescription: Can I modify the text within a beautiful soup tag without converting it into a string?

description: Modify the text within a beautiful soup tag without converting it into a string


rawDescription: Replace index of a DataFrame with another index from another DataFrame


code:
from robobrowser import RoboBrowser

url = "http://www.google.com"
br = RoboBrowser(history=True)
br.open(url)
print br.parsed

rawDescription: How to return html of a page using robobrowser

description: Return html of a page using robobrowser


code:
for start, stop in contiguous_regions(x != 0):
    print x[start:stop]

rawDescription: Numpy Detection of region borders

description: Numpy Detection of region borders


code:
import gtk
print "\n".join(name for name in dir(gtk) if name.startswith("STOCK_"))

rawDescription: What icons are available to use when displaying a notification with libnotify?


code:
js = json.dumps("Almodóvar", ensure_ascii=False)
res = json.loads(js, encoding="utf-8")
print res

rawDescription: Searching on json encoded string in Postgres with Python


code:
import numpy as np

class PointSet(object):
    def __init__(self, numpoints):
        self.coords = np.random.random((numpoints, 2))
        self.points = [Point(i, self.coords) for i in xrange(numpoints)]

    def update(self):
        """Update along a random walk."""
        # The "+=" is crucial here... We have to update "coords" in-place, in
        # this case.
        self.coords += np.random.random(self.coords.shape) - 0.5

class Point(object):
    def __init__(self, i, coords):
        self.i = i
        self.coords = coords

    @property
    def x(self):
        return self.coords[self.i,0]

    @property
    def y(self):
        return self.coords[self.i,1]

points = PointSet(100000)
point = points.points[10]

for _ in xrange(1000):
    points.update()
    print 'Position of one point out of 100000:', point.x, point.y

rawDescription: Storing Python objects in a Python list vs. a fixed-length Numpy array


code:
from bs4 import BeautifulSoup

data = """

Some text

More text here

"""

soup = BeautifulSoup(data)
for script in soup.find_all('script'):
    script.extract()

print soup.text

rawDescription: Regex for capturing everything between curly braces in HTML source


code:
import lxml.etree

def xpath_ns(tree, expr):
    "Parse a simple expression and prepend namespace wildcards where unspecified."
    qual = lambda n: n if not n or ':' in n else '*[local-name() = "%s"]' % n
    expr = '/'.join(qual(n) for n in expr.split('/'))
    nsmap = dict((k, v) for k, v in tree.nsmap.items() if k)
    return tree.xpath(expr, namespaces=nsmap)

doc = '''<root xmlns="http://really-long-namespace.uri"
    xmlns:other="http://with-ambivalent.end/#">
    <other:elem/>
</root>'''

tree = lxml.etree.fromstring(doc)
print xpath_ns(tree, '/root')
print xpath_ns(tree, '/root/elem')
print xpath_ns(tree, '/root/other:elem')

rawDescription: How to find XML Elements via XPath in Python in a namespace-agnostic way?

description: Find XML Elements via XPath in Python in a namespace-agnostic way


code:
from bs4 import BeautifulSoup as bsoup

ofile = open("htmlsample.html")
soup = bsoup(ofile)
soup.prettify()

tables = soup.find_all("tbody")

storeTable = tables[0].find_all("tr")
storeValueRows = tables[2].find_all("tr")

storeRank = []
for row in storeTable:
    storeRank.append(row.get_text().strip())

storeMatrix = []
for row in storeValueRows:
    storeMatrixRow = []
    for cell in row.find_all("td")[::2]:
        storeMatrixRow.append(cell.get_text().strip())
    storeMatrix.append(", ".join(storeMatrixRow))

for record in zip(storeRank, storeMatrix):
    print " ".join(record)

rawDescription: BeautifulSoup extracting data from multiple tables


code:
import csv

with open('/tmp/test.csv', 'r') as csvin:
    tgt='label,path,value'
    for line in csv.reader(csvin):
        if ','.join(e.strip() for e in line)==tgt:
            break

    data={k:[] for k in line}
    for line in csv.DictReader(csvin, data.keys()):
        for k,v in line.items():
            data[k].append(v)

print data
# {'path': ['/path', '/path'], 'value': ['1', '2'], 'label': ['a', 'b']}

rawDescription: Use DictReader in Python to determine table header in CSV file


code: print intersection

rawDescription: Python - Intersection of two lists of lists


rawDescription: Python - Find K max values in each row of one matrix and compare to binary matrix


code:
for t1 in tickers:
    for t2 in tickers:
        if t2 == t1:
            continue
        print "t1=%s, t2=%s" % (t1, t2)
        pairfinder(t1, t2)

rawDescription: python function taking arguments from list

description: Python function taking arguments from list


code:
import __builtin__
__builtin__.True = False
True
False
__builtin__.False = True
True
False

rawDescription: Why were True and False changed to keywords in Python 3


code:
births = 4
print "If there was a birth every 7 seconds, there would be: ",births,"births"
print "If there was a birth every 7 seconds, there would be: {} births".format(births)

rawDescription: How can I print variable and string on same line in Python?

description: Print variable and string on same line in Python


code:
exec compile(source_func1, "__remote__func1__", "exec") in a_module.__dict__
exec compile(source_func2, "__remote__func2__", "exec") in a_module.__dict__

a_module.func1 = a_module.func1_implementation
a_module.func2 = a_module.func2_implementation

rawDescription: Binding functions (`exec`uted at runtime) to a module (created at runtime)


code:
import random

x_min, x_max = (21, 99)
y_min = 11
answer_min = 10

triangles = [ (q*(q+1)/2, q) for q in range(1, x_max-x_min+2) ]
upper = (x_max-x_min+1) * (1 + x_max - (answer_min + y_min) + 1) / 2

for i in range(0, 20):
    r = 1 + random.randrange(0, upper)
    (t, q) = next(a for a in triangles if a[0] >= r)
    x = x_min + q - 1
    y = y_min + t - r
    print "%d - %d = ?" % (x, y)

rawDescription: Avoiding bias in randomly generated subtraction problems


code:
code = r"""// this is a comment
var x = 2 * 4 // and this is a comment too
var url = "http://www.google.com/" // and "this" too
url += 'but // this is not a comment' // however this one is
url += 'this "is not a comment' + " and ' neither is this " // only this

bar = 'http://no.comments.com/' // these // are // comments
bar = 'text // string \' no // more //\\' // comments
bar = 'http://no.comments.com/'
bar = /var/ // comment

/* comment 1 */
bar = open() /* comment 2 */
bar = open() /* comment 2b */// another comment
bar = open( /* comment 3 */ file) // another comment
"""

parts = rx.findall(code)
print '*' * 80, '\nCode:\n\n', '\n'.join([x[0] for x in parts if x[0].strip()])
print '*' * 80, '\nMulti line comments:\n\n', '\n'.join([x[1] for x in parts if x[1].strip()])
print '*' * 80, '\nOne line comments:\n\n', '\n'.join([x[2] for x in parts if x[2].strip()])

rawDescription: Matching one-line JavaScript comments (//) with re


code:
for i in range(1,1):
    print i

for i in range(1,2):
    print i

rawDescription: Untar file using python no error/warnings?


code:
def handle(block):
    f.write(block)
    print ".",

rawDescription: Python ftplib and storbinary

description: Python ftplib and storbinary


code:
#!/usr/bin/env python
# grep_some_condition.py
import fileinput

for line in fileinput.input(inplace=True, backup='.bak'):
    if some_condition(line):
        print line, # this goes to the current file

rawDescription: Is it possible to modify lines in a file in-place?


code:
def trip_cost(miles):
    if(miles == 0):
        return False
    fuelEcon = miles / 20
    fuelCost = float(input ('Enter Cost of Fuel: $'))
    costOfTrip = miles * fuelCost
    fuelIncrease = (fuelCost * .1) + fuelCost
    futureTrip = miles * fuelIncrease
    print "Cost of Trip: $", costOfTrip
    print "Cost of Trip With 10% Increase in Fuel Cost: $", futureTrip

    return True

while trip_cost(float(raw_input ('Enter Miles: '))):
    pass

rawDescription: cannot create a working loop in python

description: Cannot create a working loop in python


code:
from csv import DictReader
fname = "data.csv"
f = open(fname)
reader = DictReader(f, delimiter=";")
for rec in reader:
    print rec

rawDescription: Parsing CSV data based on header fields using Pyparsing


code:
import sys
new_list = sorted(sys.argv[1:])
print '\n'.join(new_list)

rawDescription: Transfering arguments in Automator's workflow . Python Shells


code:
while True:
    x1 = raw_input("please enter a number x1=")
    x2 = raw_input("please enter a number x2=")
    quit = ('q','Q')
    if x1 in quit or x2 in quit:
        break
    else:
        try:
            x1, x2 = int(x1), int(x2)
        except:
            print("please enter only numbers")
            continue
    # The mathematical part... (for completeness) (not my code)
    if x1>x2:
        x1,x2=x2,x1
    for n in xrange(x1,x2):
        i=n/100
        j=n/10%10
        k=n%10
        if i*100+j*10+k==i+j**2+k**3:
            print "%-5d"%n

rawDescription: Output Daffodils-Numbers with python

description: Output Daffodils-Numbers with python


code:
sums = []

for i in range(1,4):

    sums.append(
        QUERYSET.filter( related__value = i ).count()
    )

print sums # will show you a list of sums of the values you want

rawDescription: Is there a way to improve the queries in a loop on one in django?


code:
f = open(file_name)
total = 0
for line in f:
    if line.endswith("pizza"):
        total += 1
f.close()
print total

rawDescription: How do i count and dispaly number of occurance word ending in "pizza" (only pizza) using input text

description: Count and dispaly number of occurance word ending in "pizza" (only pizza) using input text


code:
def onclick(event):
    print event.__class__
    wedge = event.artist
    label = wedge.get_label()
    print label
    fig.canvas.figure.clf()
    ax=fig.add_subplot(111)
    wedges, plt_labels = ax.pie([50, 100, 60],labels=labels)
    fig.canvas.draw()
    for wedge in wedges:
        wedge.set_picker(True)

rawDescription: Unusual behaviour of pick_event in a matplotlib


code:
import sys
import mainscript

part1Cache = None
if __name__ == "__main__":
    while True:
        if not part1Cache:
            part1Cache = mainscript.part1()
        mainscript.part2(part1Cache)
        print "Press enter to re-run the script, CTRL-C to exit"
        sys.stdin.readline()
        reload(mainscript)

rawDescription: Keep persistent variables in memory between runs of Python script


code:
import numpy as np

count = 0
iters = 1000000

l=10
k=10
l0=l+k-1

t = np.random.choice([-1,1], size = l0 * iters)
v = np.random.choice([-1,1], size = l  * iters)

for i in xrange(iters):
    if (not np.convolve(v[(l*i):(l*(i+1))], t[(l0*i):(l0*(i+1))], 'valid').any()):
        count += 1

print count

rawDescription: How to get the hardest part to take longest in python

description: Get the hardest part to take longest in python


code:
import json, urllib2

url = 'https://ip-ranges.amazonaws.com/ip-ranges.json'
req = urllib2.Request(url)
res = urllib2.urlopen(req)
j = json.load(res)
print j['prefixes'][0]['ip_prefix']

prefixes = j['prefixes']
for i in prefixes:
    print i['ip_prefix']

rawDescription: Python: How to add content of file to list from position


code:
for row, col, value in zip(my_coo_matrix.row, my_coo_matrix.col, my_coo_matrix.data):
    print "({0}, {1}) {2}".format(row, col, value)

rawDescription: Printing complete coo_matrix

description: Printing complete coo_matrix


code:
import simplejson as json

str = """{
  "main" : "value_to_replace"
}"""
data = json.loads(str)
print data
data["main"] = "test"
print data

rawDescription: Replacing JSON value in python

description: Replacing JSON value in python


code:
dfs = {}
for fname, dfname in zip(CSV_files, DF_names):
    filepath = find(fname, path)
    df = pd.DataFrame.from_csv(filepath)
    dfs[dfname] = df
print dfs[DF_names[1]]

rawDescription: Creating pandas dataframes within a loop


code:
myDict = {}
linenum = 0
with open("eng.txt", "r") as f:
    for word in f.read().split():
        myDict.setdefault(word,[]).append(linenum)

print "%-15s %-15s" %("Word", "Frequency")
for key in sorted(myDict):
    print '%-15s: %-15d' % (key, len(myDict[key]))

rawDescription: How to read the data from a file and get the concordance output

description: Read the data from a file and get the concordance output


code:
def function_writer():
    print "I am a function writer"
    def new_function():
        print "I am a new function"
    globals()['new_function'] = new_function

function_writer()
new_function()

rawDescription: Python: defining a function inside of a function


code:
class Foo(object):
    @allowed('GET', 'POST')
    def do(self, request):
        print "Request %s on %s" % (request, self)

@allowed('GET')
def do(request):
    print "Plain request %s" % request

Foo().do('GET')  # Works
Foo().do('POST') # Raises

rawDescription: Using the same decorator (with arguments) with functions and methods


code:
#!/usr/bin/env python

import subprocess
import sys

phrase = "bar"
if len(sys.argv) > 1 and sys.argv[1] == 'print_all':
    tee_args = ['tee', '/dev/tty']
else:
    tee_args = ['tee']

p1 = subprocess.Popen(["./program"], stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=False)
p2 = subprocess.Popen(tee_args, stdin=p1.stdout, stdout=subprocess.PIPE, shell=False)
p3 = subprocess.Popen(["grep", phrase], stdin=p2.stdout, stdout=subprocess.PIPE, shell=False)
p1.wait()
p2.wait()
p3.wait()
p = str(p3.stdout.readlines())
print 'p is ', p

rawDescription: How do I print outputs from calls to subprocess.Popen(...) in a loop?

description: Print outputs from calls to subprocess.Popen(...) in a loop


code:
i = 0
print i
i = 1
print i
i = 2
print i
i = 3
print i
i = 4
print i

rawDescription: How does the Python's range function work?


rawDescription: Extract first date from string in a data frame


code:
i = len(full_name.split()) - 1
while(i >= 0):
    print full_name.split()[i]
    i = i-1

rawDescription: Python & Strings/Loops help please

description: Python & Strings/Loops help please


code:
s = 'aspire systems is in america'
li = s.split(' ') #["aspire", "systems", "is", "in", "america"]
#Reverse alternate words
for index in range (0,len(li),2): #0, 2, 4
    rev = ''
    for ch in li[index]: #'a', 's', 'p' ...
        rev = ch + rev
    li[index] = rev
#Now reverse the list of words
revli = []
for word in li:
    revli = word + revli
print ' '.join(revli) #Should print expected result

rawDescription: generic code to reverse alternate words in a sentence using python

description: Generic code to reverse alternate words in a sentence using python


code:
for i,j in d.items():
    print 'jarid:', i,
    for k,m in j.items():
        print k, m,
    print

rawDescription: Python query: iterating through log file


code:
import EXIF

with open(r"sample.jpg", 'rb') as f_jpg:
    tags = EXIF.process_file(f_jpg, details=True)
    print tags['Image Make']
    print tags['Image Model']

rawDescription: Getting Camera model information of an image using Python


code:
rgx = '(?P<foo>ABC)(?P<bar>DEF)?(?P<norf>HIJK)'
p = re.compile(rgx, re.IGNORECASE)
m = re.match(p, 'ABCDEFHIJKLM')

for key in m.groupdict():
    print key, m.span(key)

rawDescription: Extract the Name and Span of Regex Matched Groups


code:
file_list = drive.ListFile({'q': "'root' in parents and trashed=false"}).GetList()
for file in file_list:
  print 'title: %s, id: %s' % (file['title'], file['id'])

rawDescription: Google Drive SDK: I want to update a file, not create new one


rawDescription: Print list of strings to file with newline inserted after n items


rawDescription: How to use the regular Expression in python

description: Use the regular Expression in python


code:
import threading

class CountDownLatch(object):
    def __init__(self, count=1):
        self.count = count
        self.lock = threading.Condition()

    def count_down(self):
        self.lock.acquire()
        self.count -= 1
        if self.count <= 0:
            self.lock.notifyAll()
        self.lock.release()

    def await(self):
        self.lock.acquire()
        while self.count > 0:
            self.lock.wait()
        self.lock.release()

rawDescription: How to prevent task marking as success on return [celery]

description: Prevent task marking as success on return [celery]


code:
def changeX():
  global x
  x = 3

x = 5
import threading
threading.Timer(3, changeX).start()  # executes changeX after 3 seconds in a second thread

while True:
  print x

rawDescription: change value when python is in infinite loop

description: Change value when python is in infinite loop


code:
import ast

examples = ["1", "1.5", "999999999999999999999999999999999999999999", "23+42j"]
for item in examples:
    result = ast.literal_eval(item)
    print result
    print type(result)

rawDescription: Automatically convert string to the right numerical type


code:
command1.wait()
print command1.stdout

rawDescription: python execute shell command and continue without waiting and check if running before executing

description: Python execute shell command and continue without waiting and check if running before executing


code:
from StringIO import StringIO
from lxml import etree

xml = """<root>
<note>
<id>51</id>
<Name>Jani</Name>
<city>Frankfurt</city>
<IQ>Intelligent</IQ>
</note>

<note>
<id>71</id>
<Name>Peter</Name>
<city>Paris</city>
<IQ>Average</IQ>
</note>

<note>
<id>81</id>
<Name>Asho</Name>
<city>Paris</city>
<IQ>Intelligent</IQ>
</note>

</root>"""

tree = etree.parse(StringIO.StringIO(xml))
for note in tree.xpath("//note[IQ='Intelligent']"):
    print note.getchildren()[1].tag + "=" + note.getchildren()[1].text

rawDescription: Create a search engine using python ( search from an XML file only )


code:
if any('L_' in key and 'R_' in key for key in dict):
    print 'has both'

rawDescription: Does dictionary contain key containing multiple partial strings?


code:
from itertools import product, starmap

def solve(*tups):
    key = tups[0][:2]
    if all(x[:2] == key for x in tups):
        return key + (sum(x[2] for x in tups), )

for p in product(a, b, c):
    out = solve(*p)
    if out:
        print out
        #(1, 2, 16)

rawDescription: Pythonistic way to intersect and add elements of lists at the same time


code:
for dir,files in dirs.items(): # notice the call to dirs.items(), thats what was missing.
  print "directory: ",dir
  print "files:"
  for f in files:
    print f

rawDescription: Python nested loop

description: Python nested loop


code:
#!/bin/env python
import fileinput

if __name__ == '__main__':
    print "Hi. printing stdin"
    for line in fileinput.input():
        print line

    print "fin"

rawDescription: csh stdin to Python stdin?

description: Csh stdin to Python stdin


code:
class MutableString(object):
    def __init__(self, s):
        self._characters = [c for c in s]

    def __str__(self):
        return "".join(self._characters)

    def __repr__(self):
        return "MutableString(\"%s\")" % str(self)

    def __getattr__(self, name):
        return str(self).__getattribute__(name)

    def __len__(self):
        return len(self._characters)

    def __getitem__(self, index):
        return self._characters[index]

    def __setitem__(self, index, value):
        self._characters[index] = value

    def __getslice__(self, start, end=-1, stride=1):
        return str(self)[start:end:stride]

if __name__ == "__main__":
    m = MutableString("Hello")
    print m
    print len(m)
    print m.find("o")
    print m.find("x")
    print m.replace("e", "a") #translate to german ;-)
    print m
    print m[3]
    m[1] = "a"
    print m
    print m[:]

    copy1 = m
    copy2 = m[:]
    print m, copy1, copy2
    m[1] = "X"
    print m, copy1, copy2

rawDescription: Python why would you use [:] over =

description: Python why would you use [:] over =


code:
from collections import OrderedDict
order_dict = OrderedDict()
order_dict[4] = "Hello"
order_dict[3] = "World"
order_dict[5] = "Bah"
print order_dict

rawDescription: Append key value pair to a dictionary

description: Append key value pair to a dictionary


code:
import re
line = '|person=[[Old McDonald]]'
matchLine = re.match ('\|[a-z]+=(?:\[\[)?([A-Z][A-Za-z ]*)\]\]', line)
print matchLine.group (1)

rawDescription: Extracting text from a line: Regex in Python


code:
def foo(foo):
    print type(foo)

rawDescription: How to make Robot Framework functions accept arguments as strings instead of the default unicode type

description: Make Robot Framework functions accept arguments as strings instead of the default unicode type


code:
exits = (session.query(Exit, Room)
         .join(s, Exit.dst == s.c.room_id)
         .join(Room, Room.id == s.c.room_id))
for exit, room in exits:
    print exit, room

rawDescription: Recursively select (with limited depth) relationships in SQLAlchemy using ORM, declarative style, and Association objects


code:
import matplotlib.pyplot as plt

def on_timer():
    print 'Hi!'

fig, ax = plt.subplots()

# The interval is in milliseconds.
# "callbacks" expects a sequence of (func, args, kwargs)
timer = fig.canvas.new_timer(interval=5000, callbacks=[(on_timer, [], {})])
timer.start()

plt.show()

rawDescription: Pyplot connect to timer event?

description: Pyplot connect to timer event


code:
RNA = 'AGCCAUGUAGCUAACUCAGGUUACAUGGGGAUGACCCCGCGACUUGGAUUAGAGUCUCUUUUGGAAUAAGCCUGAAUGAUCCGAGUAGCAUCUCAG'
candidates = []
start = 0

while (RNA.find('AUG', start) > -1):
    start = RNA.find('AUG', start) #Confound python and its lack of assignment returns
    candidates.append(RNA[start+3:])
    start += 1

matches = []

for candidate in candidates:
    for terminator in ['UAG', 'UGA', 'UAA']:
        end = 1;
        while(candidate.find(terminator, end) > -1):
            end = candidate.find(terminator, end)
            matches.append(candidate[:end])
            end += 1

for match in matches:
    print match

rawDescription: Overlapping regex matches

description: Overlapping regex matches


code:
s = "hello"
s = s.rstrip(s[-3:])  # s[-3:] are the last three characters of string
                      # returns a copy of the string with them removed
print s
# he

rawDescription: String Manipulation in Python

description: String Manipulation in Python


code:
template = """
{%- set idxs = [0] -%}
{%- for item in sitemap recursive %}
    depth={{idxs|length}}. idx={{loop.index}}. pidx={{idxs[-1]}}. title={{item.title}}
    {%- if item.children -%}
        {%- do idxs.append(loop.index) -%}
        {{ loop(item.children) }}
        {%- do idxs.pop() -%}
    {%- endif %}
{%- endfor %}
"""

class Node():
    def __init__(self, title, children=[]):
        self.title = title
        self.children = children

sitemap = [
    Node('a', [
        Node('a_a', [
            Node('a_a_a'),
            ]),
        Node('a_b', [
            Node('a_b_a', [
                Node('a_b_a_0'),
                ]),
            ]),
        ]),
    Node('b'),
    ]

env = jinja2.Environment(extensions=['jinja2.ext.do'])
print env.from_string(template).render(sitemap=sitemap)

rawDescription: I use Jinja2 "recursive" tag in my code,but how can I get the depth of current loop?


code:
@key_memoized
def foo(bar, baz, spam):
    print 'calling foo: bar=%r baz=%r spam=%r' % (bar, baz, spam)
    return bar + baz + spam

print foo(1, 2, 3)
print foo(1, 2, spam=3)         #memoized
print foo(spam=3, baz=2, bar=1) #memoized

rawDescription: Is there a pythonic way to support keyword arguments for a memoize decorator in Python?


code:
import lxml

# I wrap your sample with an empty div
s = '''

This

AAA

BBB

CCC

That

DDD

EEE

'''

tree = lxml.etree.fromstring(s)
# search for all
 with "Title" element
for node in tree.xpath('.//li[@class="Title"]'):
    print '\n'
    # loop in
 to find for any siblings with  element
    for sub in node.xpath('.//following-sibling::li'):
        # break out the loop if another
 is found
        # you can implement other logic to break out as well
        if sub.get('class') == 'Title':
            break
        print node.text
        print ''.join(sub.xpath('./a/text()'))

rawDescription: Can following-sibling get many attributes?


code:
while True:
    message = stomp.get
    message = simplejson.loads(message.body)

    # If the message doesn't match this criterion,
    # we need to abort everything.
    if not message[0]['fieldname1']:
        global ShutdownState
        ShutdownState = True
        break

    try:
        # get the first item in message[0]['fieldname2'][0]['fieldname2-1']
        # such item['fieldname2-1-1'] is true.  Whether we
        # find one and do this code, or don't and catch the
        # StopIteration, we wrap back to the while loop.
        item = next(x
                    for x in message[0]['fieldname2'][0]['fieldname2-1']
                    if item['fieldname2-1-1'])
        list1_new[len(list_new),:] = item['fieldname2-1-2']
        list1_state = (set(list1) == set(list1_new))

        if not list1_state:
            list1 = list1_new # should print the new list1 and then reset the while loop
            print list1
    except StopIteration:
        # There was no such item.
        pass

rawDescription: Python Continue inside nested loops, getting to the right level of the nesting


code:
class A(object):
  def __init__(self):
    print "A"

class B(A):
  def __init__(self):
    super(B,self).__init__()
    print "B"

class C(A):
  def __init__(self):
    super(C,self).__init__()
    print "C"

class D(B,C):
  def __init__(self):
    super(D,self).__init__()
    print "D"

D()

rawDescription: Class Initialization

description: Class Initialization


code:
#Example CGI script
if __name__ == "__main__":
    params = cgi.FieldStorage()
    if "image" in params:
        img = params['image']
        #Generate the image and output it with the correct headers
    else:
        #Exception handling
        print "Content-Type: text/html\n"
        print """No image name was specified!"""

rawDescription: Return Image from python CGI using javascript


code:
my_dict = {"a": 1, "b": 2, "c": 3, "d": 4}

from itertools import combinations
for key1, key2 in combinations(my_dict.keys(), r = 2):
    print key1, key2

rawDescription: Double for loop in a dictionary in python


code:
import itertools
lst = [{'a': 1}, {'b': 2}, {'c': 3}]
print ', '.join(itertools.chain(*lst))

rawDescription: How to access key in Python dictionary

description: Access key in Python dictionary


code:
a = [datetime.timedelta(0, 1800)] * 4
print sum([d.seconds for d in a])
print sum([d.seconds for d in a]) / 60.0 / 60.0

rawDescription: Adding together timedeltas in Python

description: Adding together timedeltas in Python


code:
import random
import datetime
from optparse import make_option
from django.utils.timezone import utc

from django.core.management.base import BaseCommand
from school.models import Rank, Student

def utcnow():
    return datetime.datetime.utcnow().replace(tzinfo=utc)

class Command(BaseCommand):
    help = "Compute ranks and cull the old ones"
    option_list = BaseCommand.option_list + (
        make_option('--fake-now',
                    default=None,
                    help='Fake the now value to X days ago.'),
    )

    def handle(self, *args, **options):
        now = utcnow()
        fake_now = options["fake_now"]
        if fake_now is not None:
            now -= datetime.timedelta(days=int(fake_now))
            print "Setting now to: ", now

        for student in Student.objects.all():
            # This simulates a rank computation for the purpose of
            # illustration.
            rank_value = random.randint(1, 1000)
            try:
                rank = Rank.objects.get(student=student, date=now)
            except Rank.DoesNotExist:
                rank = Rank(
                    student=student, date=now)
            rank.value = rank_value
            rank.save()

        # Delete all ranks older than 180 days.
        Rank.objects.filter(
            date__lt=now - datetime.timedelta(days=180)).delete()

rawDescription: How do I record daily rankings for a model in Django?

description: Record daily rankings for a model in Django