code:
class B(object):
    def __init__(self):
        print 'Perhaps __init__ must not happen twice?'
        print
        self.val = 100

    def __str__(self):
        """What a looks like if your print it"""
        return 'B:'+str(self.val)

    def __getstate__(self):
        return self.val

    def __setstate__(self,val):
        self.val = val

b = B()
b_pickled = pickle.dumps(b)
b.val = 200
b2 = pickle.loads(b_pickled)
print 'the original b'
print b
print # newline
print 'b2 - b clone of b before we changed the value'
print b2

rawDescription: how to use 'pickle'

description: Use 'pickle'


code:
max_value, max_index = max(((x, (i, j))
                            for i, row in enumerate(li)
                            for j, x in enumerate(row)),
                           key=lambda (x, (i, j)): (x, -i, -j))

rawDescription: Maximum value from a list of lists and its index


code:
fullstr = "my|name|is|will"
begin = fullstr.find('|')+1
end = fullstr.find('|', begin)
print fullstr[begin:end]

rawDescription: Getting Substring in Python

description: Getting Substring in Python


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

rawDescription: Do you change variables AFTER you run a function in python?


code:
f = db.search(Query().time != 0)[-1]['glucose']
print f

rawDescription: How to save information to json as array python

description: Save information to json as array python


code:
import itertools

def ranges(i):
    for a, b in itertools.groupby(enumerate(i), lambda (x, y): y - x):
        b = list(b)
        yield b[0][1], b[-1][1]

print list(ranges([0, 1, 2, 3, 4, 7, 8, 9, 11]))

rawDescription: converting a list of integers into range in python

description: Converting a list of integers into range in python


code:
a = 5     # In binary: 0101
b = 3     # In binary: 0011
c = a & b # In binary: 0001

print c   # In decimal: 1

rawDescription: How do the bitwise operations work?

description: How do the bitwise operations work


code:
lines = [line.rstrip('\n').split() for line in open('C:/Users/Simon/Desktop/test.txt')]

sports = {}

for el in lines:
    number = el.pop()
    curItem = ' '.join(el)

    sports[curItem] = int(number)

print sports

rawDescription: How can I add variables into a dictionary with a loop?

description: Add variables into a dictionary with a loop


rawDescription: calculate dates in python

description: Calculate dates in python


code:
import turtle

bob = turtle.Turtle()
xx,yy= turtle.window_width(), turtle.window_height()
print 'window size: ',xx,yy
bob.speed(15)

stl=int(raw_input("Please enter length of first side: "))

while stl>turtle.window_width()/2:
    stl=int(raw_input("Please enter a shorter length that will fit into the window: "))

dec=int(raw_input("Please enter the change in length per iteration: "))

while stl > dec:
    bob.forward(stl)
    bob.right(90)
    stl= stl- dec

turtle.done()

rawDescription: Drawing Lines and Limiting Them by Screen Size in Python Turtle Graphics


code:
from django.db import models
from django.forms import ModelForm
from django.contrib import admin

class Author(models.Model):
   pass

class AuthorForm(ModelForm):
    class Meta:
        model = Author

class AuthorAdmin(admin.ModelAdmin):
    pass
admin.site.register(Author, AuthorAdmin)

print AuthorForm.__class__ == AuthorAdmin.form.__class__ # True

rawDescription: Display django admin form only

description: Display django admin form only


code:
ans = {'count': 0, 'items': []}
ans['items'].append('/\xd7\x9e\xd7\xa4\xd7\xaa-\xd7\x96\xd7\xa8\xd7\x96\xd7\x99\xd7\xa8/\xd7\x92\xd7\xa8\xd7\x99\xd7\xa4\xd7\x90\xd7\xaa/1/'.decode('utf8'))
import json
print json.dumps(ans)

rawDescription: losing encoding of string when pushing to json in python

description: Losing encoding of string when pushing to json in python


code:
def press_Z():
    while True:
        user_input = raw_input("Type Z to continue: ")
        if user_input == "Z":
            break

print "Dialogue 1"
press_Z()
print "Dialogue 2"

rawDescription: Press "Z" key to continue

description: Press "Z" key to continue


code:
def CommonLetters(s1, s2):
    l1=list(''.join(s1.split()))
    l2=list(''.join(s2.split()))
    return [x for x in l1 if x in l2]

print CommonLetters('Tom','Dom de Tommaso')

rawDescription: Python Function to return a list of common letters in first and last names


code:
for i in get_string(r"""x = 'x=\"x=\'Python\n\'\"'"""): print i

for i in get_string(r"""x = r'x=\"x=\'Python\n\'\"'"""): print i

rawDescription: Python find python strings in string

description: Python find python strings in string


code:
s = "New builds available Version: 20120418-abcdef-1 (based on SDK 0.0.0.1)"

import re
version, sdk = re.findall(r'(?:Version: |SDK )([\w.-]+)', s)

print version
print sdk

## 20120418-abcdef-1
## 0.0.0.1

rawDescription: Regular Expression usage in python

description: Regular Expression usage in python


code:
server.py
from subprocess import Popen, PIPE
from os import kill
import signal

talkpipe = Popen(['python', 'talker.py', '3'],
    shell=False, stdout=PIPE)
try:
    while True:
        line = talkpipe.stdout.readline()
        print "SERVER HEARD", line.strip()
except KeyboardInterrupt:
    print "Killing child..."
    kill(talkpipe.pid, signal.SIGTERM)

rawDescription: How to constantly send STDOUT to my python TCP server?

description: Constantly send STDOUT to my python TCP server


code:
from  collections import defaultdict

lst = ['A', 'A', 'B', 'B', 'A', 'A', 'A', 'A', 'A', 'B', ' C', ' C', ' B', 'B']
d = defaultdict(list)
for i, x in enumerate(lst):
    d[x].append(i)

items = []
indices = []
for k, v in d.items():
    n = len(v)//2
    items.extend([k]*n)
    indices.extend(v[:n])

for k, v in d.items():
    n = len(v)//2
    items.extend([k]*(len(v)-n))
    indices.extend(v[n:])

print items
print indices

rawDescription: "Balancing" a list of symbols

description: "Balancing" a list of symbols


code:
import re
text = 'Found to A from:\n\t-B\n\t-C\nFound to K from:\n\t-B\n\t-D\n\t-E\nFound to A from:\n\t-D\nMax time: 20s'
for name in ['A', 'K']:
    print name
    print [ n for i in re.findall('(?:Found to ' + name + ' from:)(?:\\n\\t-([A-Z]))(?:\\n\\t-([A-Z]))?(?:\\n\\t-([A-Z]))?', text) for n in i if n ]

rawDescription: Find repeated pattern in text with "Re" Python


code:
print '\n'.join(original)
modified = [parser.parse(od, default=DEFAULT_DATE) for od in original]
in_utc = [to_utc(md) for md in modified]
for d in in_utc:
    print d

rawDescription: Convert a list of sample dates into GMT

description: Convert a list of sample dates into GMT


code:
# setting up the indices and the series
arrays = [['@str1', '@str2'], [1, 2]]
ind = pd.MultiIndex.from_arrays(arrays, names=['index', 'other_index'])
series = pd.Series(['s1', 's2'], index=ind)

# index  other_index
# @str1  1              s1
# @str2  2              s2
# dtype: object

vals = zip(*series.index.get_values()) ## values of indices reshaped into a list of tuples
# [('@str1', '@str2'), (1L, 2L)]

# find out where is the index that we want to change
pos = series.index.names.index('index')
# now we can modify the tuple by replacing the strings we do not want
vals[pos] = tuple([x.replace('@', '') for x in vals[pos]])

# Re-create the multi-index
series.index = pd.MultiIndex.from_arrays(vals, names=series.index.names)

print series
# index  other_index
# str1   1              s1
# str2   2              s2
# dtype: object

rawDescription: Replacing Index values using regex matching


code:
import os

def search(path,filename):
    retval = []
    r.retval = retval

    for (dirpath, dirnames, filenames) in os.walk(path):
         retval.extend(os.path.join(path,dirpath,item) for item in filenames if item == filename)
    return retval

path = 'C:\\'
filename = 'test.txt'
print search(path,filename)

rawDescription: Python - Print a value without intterupting a loop/function


code:
blocksize = 100000

with open('/Users/.../lexicon.txt', "rb") as lex_file:
    data = []
    line_counter = 0
    for line in lex_file:
        data.append(line.strip().split('\t'))
        line_counter += 1
        if line_counter % blocksize == 0:
            try:
                c.executemany ('insert or replace into lex values (?, ?, ?, ?, ?)', data)
                conn.commit()
            except IndexError:
                block_start = line_counter - blocksize + 1
                print 'Lex error lines {}-{}'.format(block_start, line_counter)
                conn.rollback()
            finally:
                data = []

with open('/Users/.../x2.txt', "rb") as x2_file:
    data = []
    line_counter = 0
    for line in x2_file:
        data.append(line.strip().replace('\x00','').replace('\xff\xfe','').split('\t'))
        line_counter += 1
        if line_counter % blocksize == 0:
            try:
                c.executemany('insert or replace into x2 values (?, ?, ?)', data)
                conn.commit()
            except IndexError:
                block_start = line_counter - blocksize + 1
                print 'x2 error lines {}-{}'.format(block_start, line_counter)
                conn.rollback()
            finally:
                data = []

rawDescription: Trouble with a join statement in SQLite

description: Trouble with a join statement in SQLite


rawDescription: Django filter queryset __in for *every* item in list


code:
import pandas as pd
import numpy as np

s = pd.Series([1,2,3,4,1,2,3,3,2,1])

def ascends(s):
    diff = np.r_[0, (np.diff(s.values)>=0).astype(int), 0]
    diff2 = np.diff(diff)
    descends = np.where(np.logical_not(diff)[1:] & np.logical_not(diff)[:-1])[0]
    starts = np.sort(np.r_[np.where(diff2 > 0)[0], descends])
    ends = np.sort(np.r_[np.where(diff2 < 0)[0], descends])
    return ends - starts + 1

b = ascends(s)
print b
print b.max()
print b.min()
print b.mean()

rawDescription: Stats of consecutive increasing values of a dataframe column


code:
import threading
import datetime

class ThreadClass(threading.Thread):
    def run(self):
        now = datetime.datetime.now()
        pool.acquire()
        print "%s says hello, World! at time: %s"  % (self.getName(),now)
        pool.release()

pool = threading.BoundedSemaphore(value=1)

for i in range(10):
        t = ThreadClass()
        t.start()

rawDescription: synchronization across multiple processes in python

description: Synchronization across multiple processes in python


code:
L = ['aa', 'bb']

for row, each in enumerate(L):
    percent = float(row)/150 * 100
    print "{0:.2f}%".format(percent)

rawDescription: Python - printing % from division

description: Python - printing % from division


code: print MyClass().__dict__

rawDescription: Python Class. key exists as self.key, but doesn't exists in self.__dict__


rawDescription: Passing struct with pointer members to OpenCL kernel using PyOpenCL


code:
import rsa

(pubkey, privkey) = rsa.newkeys(512)
message = 'hello Bob!'
for _ in range(5):
    crypto = rsa.encrypt(message, pubkey)
    print "Ciphertext: %r" % crypto
    assert rsa.decrypt(crypto, privkey) == message

rawDescription: Export message that encrypted with python-rsa


code:
import pickle

with open('pickle-example.p', 'rb') as pfile:
    integers = pickle.load(pfile)
    print integers

rawDescription: What is the difference between pickle and shelve?


code: print sys.version

rawDescription: Override namespace in Python

description: Override namespace in Python


code:
following_siblings_untilh3 = lxml.etree.XPath("""
        set:difference(
            following-sibling::*,
            (following-sibling::h3|following-sibling::h3/following-sibling::*))""",
        namespaces={"set": "http://exslt.org/sets"})

for heading in root.iter("h3"):
    print "----", heading
    for e in following_siblings_noth3(heading): print e

rawDescription: what is the next tag after the specific tag in html using xpath

description: What is the next tag after the specific tag in html using xpath


code:
def guess(text):
    for t in text.split(','):
        for typ in (int, float, str):
            try:
                yield typ(t)
                break
            except ValueError as e:
                pass

d = '3, 4.32, hi'

print list(guess(d))
# [3, 4.32, ' hi']
# [<type 'int'>, <type 'float'>, <type 'str'>]

rawDescription: python: reading in a table and converting each column to the right data type

description: Python: reading in a table and converting each column to the right data type


code:
list1=[1,2,3,4]
list2=[1,5,3,4]
print [(i,j) for i,j in zip(list1,list2) if i!=j]

rawDescription: Pythonic way to compare two lists and print out the differences


code:
for t in data:
    print  " ".join(t)

rawDescription: Sorting items in a text file in python

description: Sorting items in a text file in python


code:
for line in tablerow:
     match = re.search("\b.heck\b", line)
     if match:
         print "Yay"

rawDescription: Using Beautifulsoup to find cell data, then print entire row if certain cell value is found


code: print list(enumerate(sentence))

rawDescription: Searching for Unicode characters in Python


code:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Firefox()
url = 'http://www.nice.org.uk/Search.do?searchText=bevacizumab&newsearch=true#/search/?searchText=bevacizumab&mode=&staticTitle=false&SEARCHTYPE_all2=true&SEARCHTYPE_all1=&SEARCHTYPE=GUIDANCE&TOPICLVL0_all2=true&TOPICLVL0_all1=&HIDEFILTER=TOPICLVL1&HIDEFILTER=TOPICLVL2&TREATMENTS_all2=true&TREATMENTS_all1=&GUIDANCETYPE_all2=true&GUIDANCETYPE_all1=&STATUS_all2=true&STATUS_all1=&HIDEFILTER=EGAPREFERENCE&HIDEFILTER=TOPICLVL3&DATEFILTER_ALL=ALL&DATEFILTER_PREV=ALL&custom_date_from=&custom_date_to=11-06-2014&PAGINATIONURL=%2FSearch.do%3FsearchText%40%40bevacizumab%26newsearch%40%40true%26page%40%40&SORTORDER=BESTMATCH'
driver.get(url)

page_number = 1
while True:
    try:
        link = driver.find_element_by_link_text(str(page_number))
    except NoSuchElementException:
        break
    link.click()
    print driver.current_url
    page_number += 1

rawDescription: Selenium Python - Access next pages of search results


code:
import glob
import pandas as pd

all_data = pd.DataFrame() #initializes DF which will hold aggregated csv files

#list of all df
dfs = []
for f in glob.glob("*.csv"): #for all csv files in pwd
    #add parameters to read_csv
    df = pd.read_csv(f, header=None) #create dataframe for reading current csv
    #print df
    dfs.append(df) #appends current csv to final DF
all_data = pd.concat(dfs, ignore_index=True)
print all_data
#       0      1      2
#0  test1  test1  test1
#1  test1  test1  test1
#2  test1  test1  test1
#3  test2  test2  test2
#4  test2  test2  test2
#5  test2  test2  test2
all_data.to_csv("test/final.csv", index=None, header=None)

rawDescription: using pandas in python to append csv files into one

description: Using pandas in python to append csv files into one


code:
import functools

def a(p):
    return p+1

def b(func, p):
    return functools.partial(func, p)

c = b(a,10)
print c() # >>  11

rawDescription: return a function object with parameter binded?

description: Return a function object with parameter binded


code:
print 'How old are you?', raw_input()
_

rawDescription: Why does LPTHW call "print 'How old are you?', raw_input()" invalid?


code:
import select
r, w, e = select.select([ f ], [], [], 0)
if f in r:
  print os.read(f.fileno(), 50)
else:
  print "nothing available!"  # or just ignore that case

rawDescription: Read file with timeout in Python

description: Read file with timeout in Python


code:
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

# Added a software pull-up here for increased stability
GPIO.setup(25, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(4, GPIO.OUT)
# The relay seems to be active low. Default to off.
GPIO.output(4, GPIO.HIGH)

# This function is run every time the button state changes
# from low to high or high to low (GPIO.BOTH)
def callback_func(pin):
    # The button transitioned to high (released)
    if GPIO.input(pin):
        # Relay off
        GPIO.output(4, GPIO.HIGH)
    else:
        # The button went low (it was pressed). Relay on.
        GPIO.output(4, GPIO.LOW)

# Set up threaded event detection (no constant polling of pin states).
# Fires on both high-to-low and low-to-high state changes.
GPIO.add_event_detect(25, GPIO.BOTH, callback=callback_func)

def main():
    while True:
        print "Not blocking! You're free to do other stuff here"
        time.sleep(5)

if __name__ == "__main__":
    main()

rawDescription: GPIO Momentary button controls relay

description: GPIO Momentary button controls relay


code:
entries = [
    u'aaaaa', [1, 6, u'testing', 20.0, 18.0, 2.0, 'In time'],
    u'zzzzzz', [1, 6, u'testing', 20.0, 18.0, 2.0, 'In time'],
    [1, 1, u'xyz ', 30.0, 25.0, 5.0, 'On Going'],
    [2, 1, u'abcd', 10.0, 8.0, 2.0, 'In time'],
    u'bbbbb',
    [1, 6, u'testing', 20.0, 18.0, 2.0, 'In time'],
    [1, 1, u'xyz ', 30.0, 25.0, 5.0, 'On Going'],
    [2, 1, u'abcd', 10.0, 8.0, 2.0, 'In time'],
    [1, 7, u'develop', 20.0, 15.0, 5.0, 'On Going']]

d = {}
output = []
entry = []

for item in entries:
    if type(item) == type([]):
        t = tuple(item)
        if t not in d:
            d[t] = 0
            entry.append(item)
    else:
        if len(entry):
            output.append(entry)

        entry = [item]

output.append(entry)

print output

rawDescription: Unique value in list of lists in Python

description: Unique value in list of lists in Python


code:
from PyQt4.QtCore import QObject

def makec(base):
  class X( base ):
      def __init__(self):
          self.__x = 10
      def get_x(self):
          print 'getting',
          return self.__x
      def set_x(self, x):
          print 'setting', x
          self.__x = x
      x = property(get_x, set_x)

  print 'made class of mcl', type(X), issubclass(type(X), type)
  return X

class old: pass
for base in (QObject, old):
  X = makec(base)
  x = X()
  print x.x # Should be 10
  x.x = 30
  print x.x # Should be 30

rawDescription: Does using properties on an old-style python class cause problems


code: print dir(t)

rawDescription: How do I iterate over all imported functions

description: Iterate over all imported functions


code:
from lxml.html import fromstring

data = """

Aspect Ratio:
 2.35 : 1

"""

root = fromstring(data)
print root.xpath('//h4[@class="inline"]')[0].tail

rawDescription: Get value using lxml

description: Get value using lxml


code:
reader_list = csv.DictReader(s.splitlines())
print reader_list.fieldnames
for row in reader_list:
    print row

rawDescription: Python csv.DictReader: parse string?

description: Python csv.DictReader: parse string


code:
import sys
import threading

def show_guts(f):
    sentinel = object()
    gutsdata = threading.local()
    gutsdata.captured_locals = None
    gutsdata.tracing = False

    def trace_locals(frame, event, arg):
        if event.startswith('c_'):  # C code traces, no new hook
            return
        if event == 'call':  # start tracing only the first call
            if gutsdata.tracing:
                return None
            gutsdata.tracing = True
            return trace_locals
        if event == 'line':  # continue tracing
            return trace_locals

        # event is either exception or return, capture locals, end tracing
        gutsdata.captured_locals = frame.f_locals.copy()
        return None

    def wrapper(*args, **kw):
        # preserve existing tracer, start our trace
        old_trace = sys.gettrace()
        sys.settrace(trace_locals)

        retval = sentinel
        try:
            retval = f(*args, **kw)
        finally:
            # reinstate existing tracer, report, clean up
            sys.settrace(old_trace)
            for key, val in gutsdata.captured_locals.items():
                print '{}: {!r}'.format(key, val)
            if retval is not sentinel:
                print 'Returned: {!r}'.format(retval)
            gutsdata.captured_locals = None
            gutsdata.tracing = False

        return retval

    return wrapper

rawDescription: Printing a function's local variable names and values


code:
import urlparse
url_to_parse = "http://example.com/servlet/charting?base_color=grey&chart_width=288&chart_height=160&chart_type=png&chart_style=manufund_pie&3DSet=true&chart_size=small&leg_on=left&static_xvalues=10.21,12.12,43.12,12.10,&static_labels=blue,red,green,purple"
parsed_url = urlparse.urlparse(url_to_parse)
query_as_dict = urlparse.parse_qs(parsed_url.query)
print query_as_dict

rawDescription: Having trouble parsing HTML

description: Having trouble parsing HTML


code:
l1 = [{'a': 1, 'b': 2, 'c': 3, 'd': 4}, {'a': 5, 'b': 6, 'c': 7, 'd': 8}]
l2 = [{'a': 5, 'b': 6, 'e': 100}, {'a': 1, 'b': 2, 'e': 101}]

from collections import defaultdict
D = defaultdict(dict)
for lst in l1, l2:
    for item in lst:
        key = item['a'], item['b']
        D[key].update(item)

l3 = D.values()
print l3

rawDescription: How to join 2 lists of dicts in python?

description: Join 2 lists of dicts in python


code:
for varname in a.__class__.__dict__['A1'].__code__.co_varnames:
    print varname

rawDescription: Python Introspection: How to get varnames of class methods?


code: print len(words_par)

rawDescription: How to count the number of words in a paragraph and exclude some words (from file)?

description: Count the number of words in a paragraph and exclude some words (from file)


code:
import imp

def my_import(name):
    file, pathname, description = imp.find_module(name)
    code = compile(file.read(), pathname, "exec", dont_inherit=True)
    file.close()
    module = imp.new_module(name)
    exec code in module.__dict__
    return module

rawDescription: Python: How to load a module twice?

description: Python: How to load a module twice


code:
import robot
print robot.__file__

rawDescription: Create Python object from different .py file


code:
# dd.py
import sys
def main(arg):
    # do something here
    print arg

if __name__ == "__main__":
    arg = sys.argv[1]
    main(arg)

rawDescription: How to link PyQt4 script button to activate another script?

description: Link PyQt4 script button to activate another script


code:
from csv import DictReader as dr
cols = "TitleB", "TitleRNum", "TitlePNum", "TitleBF", "TitleCheck"
mark = 0
with open("exampledata.csv", "rb") as f:
    for row in dr(f, f.readline().strip().split(",")):
        if mark:
            print ",".join([",".join([mark[c], row[c]]) for c in cols])
        mark = row if row["TitlePNum"]==row["TitleRNum"]=="1" else 0

rawDescription: Matching keys in csv file and producing desired output


code:
for gene in list_a:
    for start, stop, name in ranges[gene['Ch']]:
        if start <= gene['site'] <= stop:
            print name, gene['site']
            break

rawDescription: Is there a way to get next value for the same key in the next dictionary in the list of dictionaries?


code:
while True:
    myVar = myFunc()
    if myVar == sentinel:
        break
    print myVar

rawDescription: Call function in loop line and store return value to variable to then be used in the loop?


code:
def question(question, correct_answers):
    user_answer = raw_input(question)
    if user_answer in correct_answers:
        print "Correct!"
        return True
    else:
        print "False!"
        return False

correct_count = 0
if question(question1, [answer1, answer1_5]):
    correct_count += 1
if question(question2, [answer2, answer2]):
    correct_count += 1

rawDescription: Is there any way to make this Python function run for more intervals?


code:
import time
import threading
import Tkinter as Tk

def do_something():
    T0 = time.clock()
    while (time.clock() - T0) < 60 and not e.isSet(): #as long as 60s haven't elapsed
                                                      #and the flag is not set
        #here do a bunch of stuff
        time.sleep(5)

def _quit():
    print 'Exiting...'
    e.set()
    thread.join() #wait for the thread to finish
    root.quit()
    root.destroy()

root = Tk.Tk()
QuitButton = Tk.Button(master=root, text='Quit', command=_quit) #the quit button
QuitButton.pack(side=Tk.BOTTOM)

thread = threading.Thread(target=do_something, args=())
e = threading.Event()
thread.start()
root.mainloop()

rawDescription: Python - do something until keypress or timeout


code:
class C(object):
    def __init__(self, lst):
        self.lst = lst
    def __iter__(self):
        return iter(self.lst)
def f(a, b, c):
    print "Arguments: ", a, b, c
c = C([1, 2, 3])
f(*c)

rawDescription: What does a class need to implement in order to be used as an argument tuple?


code:
import Tkinter as tk
import tkFont

root = tk.Tk()
label = tk.Label(root, text="Hello, world")
font = tkFont.Font(font=label['font'])
print font.actual()

rawDescription: How to change a widget's font style without knowing the widget's font family/size?

description: Change a widget's font style without knowing the widget's font family/size


code:
b = B()
c = C()
cc = C()
c.foo.this_val = 456
print c.foo.this_val   # 456
print cc.foo.this_val  # 456
print b.foo.this_val   # 123

rawDescription: help with python inheritance

description: Help with python inheritance


code:
def putfirst(n,df):
    if not isinstance(n, int):
        print 'error: 1st arg must be an int'
        return
    if n < 1:
        print 'error: 1st arg must be an int > 0'
        return
    if n == 1:
       print 'nothing to do when first arg == 1'
       return
    if n > len(df):
       print 'error: n exceeds the number of rows in the DataFrame'
       return
    df.index = range(1,n) + [0] + range(n,df.index[-1]+1)
    df.sort(inplace=True)

rawDescription: Python Pandas: How to move one row to the first row of a Dataframe?


code:
list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']
string = 'there is an : error: and a cc1plus: in this string'
pattern = "|".join(re.escape(p) for p in list_patterns)
print re.findall(pattern, string)

rawDescription: Python: defining a union of regular expressions


code:
d = {}
set_if_not_there(d, ['cnt1', 'cnt2'], int)
set_if_not_there(d, ['tags1', 'tags2'], list)
d['cnt1'] += 1
d['tags1'].append('work')
print d

rawDescription: Problems with a shared mutable?

description: Problems with a shared mutable


code:
from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)              # start 4 worker processes
    result = pool.apply_async(f, [10])    # evaluate "f(10)" asynchronously
    print result.get(timeout=1)           # prints "100" unless your computer is *very* slow
    print pool.map(f, range(10))          # prints "[0, 1, 4,..., 81]"

rawDescription: Run separate processes in parallel - Python


code:
f1 = open('a', 'r').readlines()
f2 = open('b', 'r').readlines()
out = []
indexa = 0
indexb = 0
out = []
while(1):
    try:
        if f1[indexa][:-1] ==  f2[indexb][:-1]:
            indexa +=1
            indexb +=1
        elif f1[indexa][:-1] > f2[indexb][:-1]:
            indexb += 1
        elif f1[indexa][:-1] < f2[indexb][:-1]:
            out.append(indexa+1)
            indexa += 1
    except IndexError:
        break
for i in out:
    print i

rawDescription: Compare two files in python and save line differences in a new file


code:
import os
import subprocess

line = "perl tilt.pl %s | tee final-%s.txt"

framespdb = os.listdir("prac_frames")

for frames in framespdb:
    cmd = line % (frames, frames)
    print(cmd)
    output = subprocess.check_output(cmd, shell=True)
    print 'output:', output

rawDescription: Linux Command for Perl in Python

description: Linux Command for Perl in Python


code:
from PIL import Image, ImageDraw
from math import pi

RED, GREEN, YELLOW = (255, 0, 0), (0, 255, 0), (127, 127, 0)
SIZE = (500, 500)

def overlap(ellipse1, ellipse2):
    im1 = Image.new("RGB", SIZE)
    ImageDraw.Draw(im1).ellipse(ellipse1, fill=RED)
    im2 = Image.new("RGB", SIZE)
    ImageDraw.Draw(im2).ellipse(ellipse2, fill=GREEN)
    im3 = Image.blend(im1, im2, 0.5)
    im3.show()
    im3.save('test.png', "png")
    return [count for count, color in im3.getcolors() if color == YELLOW][0]

area1 = overlap((0, 50, 500, 450), (50, 50, 450, 450))
area2 = pi * (200**2)
print "overlap calc:" , area1
print "exact area:  " , area2
print "percent diff:" , ((area1 - area2)/area2)*100

rawDescription: Graphical test of the correctness of an implementation


code:
from nltk.corpus import brown
from nltk import word_tokenize, pos_tag, ne_chunk
sent = "The turtles fight Shredder."
pos_tag(word_tokenize(sent))
ne_chunk(pos_tag(word_tokenize(sent)))
for i in ne_chunk(pos_tag(word_tokenize(sent))):
    print i

rawDescription: How do I tag a sentence with the Brown or CoNLL2000 tagger / chunker?

description: Tag a sentence with the Brown or CoNLL2000 tagger / chunker


code:
from matplotlib.tight_layout import get_renderer
import matplotlib.pyplot as plt

FONTSIZE=20

# set up example plots
fig = plt.figure()

ax1 = fig.add_subplot(211)
ax1.plot(range(10,1,-1))
ax1.set_title('ax1',fontsize=FONTSIZE)
ax1.set_xlabel('X axis',fontsize=FONTSIZE)
ax1.set_ylabel('Y axis',fontsize=FONTSIZE)

ax2 = fig.add_subplot(212)
ax2.plot(range(1,10,1))
ax2.set_title('ax1',fontsize=FONTSIZE)
ax2.set_xlabel('X axis',fontsize=FONTSIZE)
ax2.set_ylabel('Y axis',fontsize=FONTSIZE)

# tighten things up in advance
print "Subplots 'bottom' before tight_layout: ",fig.subplotpars.bottom
plt.tight_layout()
print "Subplots 'bottom' after tight_layout: ",fig.subplotpars.bottom
fig.savefig('noFigText.png')

# add and deal with text
bigFigText = plt.figtext(0.5 ,0.05,
                         u'first line\nsecond line\nthird line',
                         ha='center')
# textLimitsDpi is a 2x2 array correspoinding to [[x0,y0],[x1,y1]]
textLimitsDpi = bigFigText.get_window_extent(renderer=get_renderer(fig),
                                   dpi=fig.get_dpi()).get_points()

# we really just need y1
textHeightFig = fig.transFigure.inverted().transform((0,textLimitsDpi[1,1]))[1]

# make adjustment to bottom
fig.subplots_adjust(bottom=fig.subplotpars.bottom+textHeightFig)

print "Subplots 'bottom' after figtext: ",fig.subplotpars.bottom
fig.savefig('withFigText.png')
plt.show()

rawDescription: Automatically expand canvas for long lines


code:
with open("seq2.txt") as lines:
    for l in lines:
        split_list = l.split()

        header = "".join(split_list[0:2])
        seq = split_list[2]
        disorder = split_list[4]

        # Create the new disorder string
        new_disorder = ["Disorder: Posi R"]
        print new_disorder
        for i, x in enumerate(disorder): # nest your for loop to process each line
            if x == "X":
                # Appends of the form: "AminoAcid Position"
                new_disorder.append("{} {}".format(i, seq[i]))

        new_disorder = " ".join(new_disorder)

        with open("seq2.txt", "a+") as f: # write to file after each process
            f.write( "\n".join([header, seq, new_disorder]))

rawDescription: How to align disorder region and sequence in a larger scale (python)

description: Align disorder region and sequence in a larger scale (python)


code:
import clang.cindex
from clang.cindex import *

def method_definitions(cursor):
    for i in cursor.walk_preorder():
        if i.kind != CursorKind.CXX_METHOD:
            continue
        if not i.is_definition():
            continue
        yield i

def extract_definition(cursor):
    filename = cursor.location.file.name
    with open(filename, 'r') as fh:
        contents = fh.read()
    return contents[cursor.extent.start.offset: cursor.extent.end.offset]

idx = Index.create()
tu = idx.parse('method.C', ['-x', 'c++'])
defns = method_definitions(tu.cursor)
for defn in defns:
    print extract_definition(defn)

rawDescription: How to get class method definitions using clang python bindings?

description: Get class method definitions using clang python bindings


code:
class IntermediateObj(object):

    def __init__(self, raw):
        self.raw = raw
        self.sections = []
        self.fields = []
        self.elements = []
        self.recurse(raw)

    def recurse(self, items):
        for k,v in items.iteritems():
            if isinstance(v, list):
                getattr(self, k).append(v)
                [self.recurse(i) for i in v]
            else:
                setattr(self, k, v)

class MyClass(IntermediateObj):

    def __init__(self, intermediate_instance):
        super(MyClass, self).__init__(intermediate_instance.raw)

ii = IntermediateObj({'large': 'nested_dictionary',
                      'sections': [{}, {}, {}]
                    })
print ii.raw
print ii.sections
tada = MyClass(ii)
print tada.sections
print tada.raw

rawDescription: Python class inheritance (multiple) : Why are attributes empty? i.e. doing it right


code:
print df.groupby('one').apply(net_func).ix[[('AAL', 1), ('AAPL', 1)]]
#         one  two  dailyTrue  dailyFalse
#one
#AAL  1   AAL    2          1           0
#AAPL 1  AAPL    2          1           0

rawDescription: Python Pandas, slice rows from group in .groupby().apply()


code:
import Queue
import threading
import os

# we will store all data in a Queue so we can process
# it at a custom speed, without blocking the reading
q = Queue.Queue()

# thread for getting the data from the sensor
# it puts the data in a Queue for processing
def get_data(q):
    for cnt in xrange(20000):
        # assuming readbysensor() is a
        # blocking function
        sens = readbysensor()
        q.put(sens)

# thread for processing the results
def process_data(q):
    for cnt in xrange(20000):
        data = q.get()
        # do something with data here
        q.task_done()

t_get = threading.Thread(target=get_data, args=(q,))
t_process = threading.Thread(target=process_data, args=(q,))
t_get.start()
t_process.start()

# when everything is set and ready, run the raspivid
os.system("raspivid -t 20000 /home/pi/test.h264 &")

# wait for the threads to finish
t_get.join()
t_process.join()

# at this point all processing is completed
print "We are all done!"

rawDescription: Synchronize a Linux system command and a while-loop in Python


code:
def other_function(parameter):
    return parameter + 5

def main_function():
    x = 10
    print x
    x = other_function(x)
    print x

rawDescription: Python - How to make a local variable (inside a function) global


code:
from itertools import product

x = [['a','b'], ['c','d'], ['e','f']]

for _ in product(*x):
    print _

rawDescription: Can't figure out this simple recursion with Python


code:
def dump(e):
    print '<%s>' % e.tag
    print 'text =',repr(e.text)
    for n in e:
        dump(n)
    print '</%s>' % e.tag
    print 'tail =',repr(e.tail)

dump(tree)

rawDescription: How do I get Python XML to stop having wasted Child Nodes

description: Get Python XML to stop having wasted Child Nodes


code:
d = {}
for (value, key) in testdata:
    d.setdefault(key, []).append(value)
print d

rawDescription: Make sets from a list of lists in Python


code:
import re

class cls(object):
    pass

def fn(var):      # function to apply to the strings
    return "[%s mod]" % var

a = "<a>"
b = "<b>"
c = "01234567890"
d = cls()
d.s = "<d.s>"
e = cls()
e.s = "<e.s>"

var_list = "a b c[2:7] d.s e.s".split()

for var in var_list:
    # Modify the variables
    try:
        # exec "%s='Hi there'" % var             # Modify the variables
        exec "%(var)s=fn(%(var)s)" % { "var": var }
    except TypeError:
        # Assume Slice...
        slice_ = re.findall("\[(\d+)\:(\d+)\]", var)[0]   # Get slice
        var_with_slice = var
        var = var.split("[")[0]                 # Remove slice
        # Look ma, I can code in Perl too! :)
        line = \
             "%(var)s=%(var)s[:%(slice1)s]+fn(%(var_with_slice)s)+%(var)s[%(slice2)s+1:]" % \
             { "var": var, "var_with_slice": var_with_slice, "slice1": slice_[0], "slice2": slice_[1] }
        # somewhat like c = c[:2] + fn(c[2:7]) + c[7+1:]
        exec line

print a,b,c,d.s,e.s
# >>> [<a> mod] [<b> mod] 01[23456 mod]890 [<d.s> mod] [<e.s> mod]

rawDescription: Python: modify strings stored in various objects inplace in a loop


code:
import random

#----------------------------------------------#
class MyArrayClass(object):
    def create_list_and_find_max_and_min(self, n):
        self.my_array = []
        n = input("How many numbers do you want in your array?:")
        for i in range(n):
            self.my_array.append(random.randint(1,n))
        print "My array is:", self.my_array
        #----------------------------------------------#
        min = self.my_array[0]
        for number in self.my_array:
            if min > number:
                min = number
        print "The minimum value in the array is:", min
        #----------------------------------------------#
        max = self.my_array[0]
        for number in self.my_array:
            if max < number:
                max = number
        print "The maximum value in the array is:", max
    #----------------------------------------------#
    def the_smart_way(self):
        # "This one uses the built-in Python functions for min/max..."
        min_my_array = min(self.my_array)
        max_my_array = max(self.my_array)
        return min_my_array, max_my_array
#----------------------------------------------#
def main():
    my_array = MyArrayClass()
    my_array.create_list_and_find_max_and_min(10)
    print my_array.the_smart_way()
#----------------------------------------------#
if __name__ == '__main__':
    main()

rawDescription: Python Alternatives to Global Variables

description: Python Alternatives to Global Variables


code:
while turn1:
    print constant - random

rawDescription: how do I create a constant variable that can be modified constantly

description: Create a constant variable that can be modified constantly


code:
translation = []

words = sentence.split(' ')
maxlen = 3
index = 0

while index < len(words):
    for i in range(maxlen, 0, -1):
        phrase = ' '.join(words[index:index+i])
        if phrase in myDict:
            translation.append(myDict[phrase])
            index += i
            break
    else:
        translation.append(words[index])
        index += 1

print ' '.join(translation)

rawDescription: Scanning for two word phrase in Python dictionary


code:
import re

def capitalizer(match):
    return match.group(0).upper()

sentence = 'this is a sentence. isn\'t it a nice sentence? i think it is'
print re.sub(r'(?:^\s*|[.?]\s+)(\w)', capitalizer, sentence)

rawDescription: Title case for a paragraph

description: Title case for a paragraph


code:
import sys

lower_argv = [s.lower() for s in sys.argv]
if 'pyside' in lower_argv:
    from PySide import QtCore, QtGui
    QtCore.pyqtSignal = QtCore.Signal
    QtCore.pyqtSlot = QtCore.Slot
    print 'Using PySide'
else:
    from PyQt4 import QtCore, QtGui
    print 'Using PyQt4'

class MyButtonGroup(QtCore.QObject):
    trigger = QtCore.pyqtSignal((),(bool,))

    def addButton(self, button):
        button.clicked.connect(self.trigger.emit)

    def removeButton(self, button):
        button.clicked.disconnect(self.trigger.emit)

class MyWindow(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self, None)

        self.group = MyButtonGroup()
        button1 = QtGui.QPushButton("button1")
        button2 = QtGui.QPushButton("button2")
        self.group.addButton(button1)
        self.group.addButton(button2)
        self.group.trigger.connect(self.do_something)

        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(button1)
        layout.addWidget(button2)

    def do_something(self, x=False):
        print 'hello'

if __name__ == '__main__':
    app = QtGui.QApplication([])
    window = MyWindow()
    window.show()
    app.exec_()

rawDescription: How to group buttons in pyQT

description: Group buttons in pyQT


code:
import win32com.client
import pythoncom

ProgID = "someProgramID"
com_object = win32com.client.Dispatch(ProgID)

for key in com_object._prop_map_get_:
    method = getattr(com_object,key)
    if str(type(method)) == "<type 'instance'>":
        print key
        for sub_method in dir(method):
            if not sub_method.startswith("_") and not "clsid" in sub_method.lower():
                print "\t"+sub_method
    else:
        print "\t",method

rawDescription: List all methods in COMobject

description: List all methods in COMobject


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


code:
for test, expected in tests:
    result = money.match(test)
    is_match = result is not None
    if is_match == expected:
      status = 'OK'
      if result:
        amt = [x for x in result.groups() if x is not None].pop()
        status += ' (%s)' % amt
    else:
      status = 'Fail'
    print test + '\t' + status

rawDescription: Can somebody explain a money regex that just checks if the value matches some pattern?


code: print etree.tostring(other_function(parent, my_attrib='my value'))

rawDescription: Parsing **kwargs

description: Parsing **kwargs


code:
import time
from contextlib import contextmanager

@contextmanager
def measureTime(title):
    t1 = time.clock()
    yield
    t2 = time.clock()
    print '%s: %0.2f seconds elapsed' % (title, t2-t1)

rawDescription: timing block of code in Python without putting it in a function

description: Timing block of code in Python without putting it in a function


code:
a = 0
b = 0
c = 0

while a <= 5:
    while b <=3:
        while c <= 8:
            print a , b , c
            c += 1
        b += 1
        c = 0 # reset
    a += 1
    b = 0 # reset
    c = 0 # reset

rawDescription: Why is only the innermost of these nested while loops working?


code:
import numpy as np
from scipy.interpolate import interp1d

x = y = np.arange(5)
f = interp1d(x,y, kind="linear", fill_value=0., bounds_error=False)

print f(0)
print f(2)
print f(3)
print f(3.4)

rawDescription: Convert a python list into function

description: Convert a python list into function


code:
import os

files = folders = 0

for _, dirnames, filenames in os.walk(path):
  # ^ this idiom means "we won't be using this value"
    files += len(filenames)
    folders += len(dirnames)

print "{:,} files, {:,} folders".format(files, folders)

rawDescription: Count the number of folders in a directory and subdirectories


code:
for line in output1:
    line = line.replace(' ', '(^_^)')
    line = line.split()
    line = [word.replace('(^_^)', ' ').strip() for word in line]
    line = ','.join([word.strip(',') for word in line])
    print line

rawDescription: Python split('\n') breaks a row midway instead of after end of line


code:
#!python2
ArbSyn = [u'\u0627\u0642\u062a\u0631\u062d', u'\u0627\u062d\u062f\u0627\u062b', u'\u0645\u0648\u0633\u0633', u'\u0631\u0627\u062f', u'\u062a\u0633\u064a\u0633', u'\u0627\u062d\u062f\u0627\u062b']

# Demonstrate the difference printing an item vs. its representation
for item in ArbSyn:
    print item,repr(item)

# Build a Unicode string representation of a list
as_list = u"['" + u"', '".join(ArbSyn) + u"']"
print as_list

rawDescription: Python storing Arabic in an Array?

description: Python storing Arabic in an Array


code:
mystr = "2 aikjhakihaiyhgikjewh"
lst = list(list([item for item in [mystr[0] + mystr[3:5]]])[0])
print lst

rawDescription: Append a portion of a string to a list

description: Append a portion of a string to a list


code:
from collections import defaultdict

listone = [
    {'unit1': {'test1': 10}},
    {'unit1': {'test2': 45}},
    {'unit2': {'test1': 78}},
    {'unit2': {'test2': 2}}
]

listtwo = [
    {'unit1': {'test1': 56}},
    {'unit1': {'test2': 34}},
    {'unit2': {'test1': 23}},
    {'unit2': {'test2': 5}}
]

def dictify(lst):
    res = defaultdict(lambda: defaultdict(int))
    for entry in lst:
        for unit,testentry in entry.iteritems():
            for test,val in testentry.iteritems():
                res[unit][test] = val
    return res
    # returns dict['unitX']['testY'] = val

def genDeltas(dictA, dictB):
    units = dictA.keys()
    units.sort()
    tests = dictA[units[0]].keys()
    tests.sort()
    for unit in units:
        _A = dictA[unit]
        _B = dictB[unit]
        for test in tests:
            yield unit,test,(_B[test]-_A[test])

for unit,test,delta in genDeltas(dictify(listone),dictify(listtwo)):
    print "{0}, {1}, {2}".format(unit,test,delta)

rawDescription: Python: Substracting between list of dictionaries


code:
#!/usr/bin/env python

import csv
reader = csv.reader(open('4956984.csv', 'rb'))

chunk, chunksize = [], 100

def process_chunk(chuck):
    print len(chuck)
    # do something useful ...

for i, line in enumerate(reader):
    if (i % chunksize == 0 and i > 0):
        process_chunk(chunk)
        del chunk[:]
    chunk.append(line)

# process the remainder
process_chunk(chunk)

rawDescription: How do you split a csv file into evenly sized chunks in Python?

description: Split a csv file into evenly sized chunks in Python


code:
from itertools import product

def print_lattice_edges(lattice):
    """prints all edges of a lattice, given as a list of lists of coordinates"""
    for idim, dim_coords in enumerate(lattice):
        for other_coords in product(*lattice[:idim] + lattice[idim+1:]):
            for coord1, coord2 in zip(dim_coords[:-1], dim_coords[1:]):
                edge1 = other_coords[:idim] + (coord1,) + other_coords[idim:]
                edge2 = other_coords[:idim] + (coord2,) + other_coords[idim:]
                print edge1, '->', edge2

rawDescription: Transforming lattice into graph?

description: Transforming lattice into graph


code:
# hello.py
def world():
    print 'hello world!'

rawDescription: How should a global (module) object be created in a Python function?


rawDescription: Filter special chars such as color codes from shell output


code:
import glob
import os

os.chdir('/mydir')
for file in glob.glob('apple*.json.gz'):
    print file

rawDescription: Find files in a directory with a partial string match


code:
def by_veg_sum(record):
    s = sum(record[entry] for entry in ['Cucumber','Carrot','Runner Bean'])
    print s
    return s

rawDescription: Ordered dictionary Sum and Top 3 of the Ordered dictionary sum


code:
#! usr/local/bin/python
import cgi;
import cgitb;
import Cookie;
import os;
import sqlite3;

cgitb.enable()
username= None
form= cgi.FieldStorage()

#open connection
conn= sqlite3.connect("manager.db")
cur= conn.cursor()

pagehead= """
    <html>
        <head> Redirecting </head>
        <body>

            """
pagefoot="""<form method= POST action="http://localhost:8000/cgi-bin/page1.py">
            <p> Validated! <input type="submit" value="Enter"/> </p>
            </form>
        </body>
    </html> """
errorpagefoot= """
<form action="http://localhost:8000/cgi-bin/index.py">
<p> Error! <input type="submit" value="Go Back"/> </p>
</form>
</body>
</html>"""

userName= form.getvalue('usernameLogin')
userPW= form.getvalue('passwordLogin')
userPWDatabase = conn.execute("SELECT username,passwrd FROM login WHERE username=? and passwrd=?",[userName,userPW])
cur.fetchone()
for result in userPWDatabase:
    userDb= result[0]
    pwDb= result[1]
    if userDb == userName and pwDb == userPW:
        #Create Cookie
        C= Cookie.SimpleCookie()
        #take the value of usernameLogin into the variable username
        username= form.getvalue('usernameLogin')
        #Set-Cookie header with the usernameLogin key
        C['usernameLogin'] = username
        print C
    elif userDb != userName and pwDb != userPW:
        print errorpagefoot

print "Content_type: text/html\n\n"
print pagehead
if username:
    print pagefoot
else:
    print errorpagefoot

rawDescription: Redirect python script to another python script for validation of login credentials


code:
vms = server.get_registered_vms()
mylist = []
for vm in vms:
    virtual_machine = server.get_vm_by_path(vm)
    guest_os = virtual_machine.get_property('guest_full_name')
    if server_guest_is_linux(guest_os):
        mylist.append(virtual_machine)
        print vm

def server_guest_is_linux(guest_os):
    if 'linux' in guest_os.lower() \
            or 'ubuntu' in guest_os.lower() \
            or 'centos' in guest_os.lower():
        return True
    return False

rawDescription: Can you get a guest OS using PySphere?

description: Get a guest OS using PySphere


code:
_sentinel = object()

def foo(a, optional=_sentinel):
    if optional is _sentinel:
        optional = 42
        print "1 arg"
    else:
        print "2 args"

rawDescription: Number of actual function arguments

description: Number of actual function arguments


code:
TEXT = u'word=\\u0631\\u064e\\u062c\\u0627'
print TEXT
TEXT = TEXT.decode('unicode-escape')
print TEXT

rawDescription: How to insert arabic script into Tkinter text widget correctly?

description: Insert arabic script into Tkinter text widget correctly


code:
import fabric.api as fab

fab.env.roledefs['staging'] = ['bbs-evolution.ipsw.dt.ept.lu']
fab.env.roledefs['prod'] = ['bbs-arbiter.ipsw.dt.ept.lu']

@fab.task
def testrole():
    print fab.env.roles

rawDescription: How to discover current role in Python Fabric

description: Discover current role in Python Fabric


code:
def proxy(bridge, target):
    def proxyfy(cls):
        for bname, func in inspect.getmembers(target, predicate=inspect.ismethod):
            fname = func.__name__
            if fname in cls.__dict__:
                print 'ignoring %s.%s' % (cls, fname)
                continue
            print 'adding %s.%s' % (cls, fname)
            def proxy_func(self, bname=bname, *args, **kwargs):
                print 'calling %s.%s.%s' % (cls, bridge, bname)
                bridge_member = getattr(self, bridge)
                return getattr(bridge_member, bname)(*args, **kwargs)
            setattr(cls, fname, proxy_func)
        return cls
    return proxyfy

rawDescription: Using closure to decorate a class's methods


code:
for idx, fragment in enumerate(fragments):
    fragment_number = idx + 1
    indent = " " * idx
    print indent + str(fragment_number)
    print indent + " ".join(fragment)

rawDescription: how can I generate a fragment library from a protein sequence file?

description: Generate a fragment library from a protein sequence file


code:
a,b= [1,2,[3,[4,5]]], [4,5]

c,d= [1,2,[3,[4,5]]], [3,4,5]
def isSublist(a,b):
    return any(x if x==b else isSublist(x,b) for x in a if isinstance(x,list) )

print isSublist(a,b) #True
print isSublist(c,d) #False

rawDescription: check if the first list is a sublist of the second one python

description: Check if the first list is a sublist of the second one python


code:
class Animals(object):
    zoo = {}
    def runExpensiveFunction(self):
        print "EXPENSIVE CALLED"
    def __new__(cls, species):
        if species in cls.zoo:
            return cls.zoo[species]
        else:
            animal = object.__new__(Animals)
            animal.species = species
            animal.age = 0
            animal.runExpensiveFunction()
            Animals.zoo[species] = animal
            return animal

rawDescription: Two constructors in a Python Class

description: Two constructors in a Python Class


code:
p=[['a','b','c','d'],
   ['a','c','e','d'],
   ['a','b','z','x']]

for i,item in enumerate(p):
    for j,x in enumerate(item):
        print i,j,x

rawDescription: Python index in nested for loop

description: Python index in nested for loop


code:
print [tuple(sorted(items, key=sls.index)) for items in list_tup]
# [('SF', 'NYC'), ('HOU', 'BOS'), ('DAL', 'NYC')]

rawDescription: sorting tuples in a list according to another self-made order

description: Sorting tuples in a list according to another self-made order


code:
fp = open('test.txt', 'r')
file_contents = fp.read()
result = []
for split in file_contents.split('\n\n'):
    split = ','.join(split.split('\n'))
    split = ''.join(split.split(' '))
    split = split.split(',')
    for x in range(0, len(split)-1, 2):
        if x == 0:
            result.append(split[x])
            result.append((0, int(split[x+1])))
        else:
            result.append((int(split[x]), int(split[x+1])))
print result

rawDescription: Passing textfile and Creating new Tuple when there is space


code:
#!/bin/python
import sys
import os

if len(sys.argv) < 2:
    print 'Usage: ' + sys.argv[0] + ' <filename>'
    sys.exit(1)

print 'This is the name of the python script: ' + sys.argv[0]
print 'This is the 1st argument:              ' + sys.argv[1]

f=open('/home/xxx/scratch/test/' + sys.argv[1],'r').readlines()
print f[1]

rawDescription: How to pass a Bash variable to Python?

description: Pass a Bash variable to Python


code:
for k, g in groupby(enumerate(group_first), lambda (i, x):i-x[0]):
    print sum(v for i, (k, v) in g)

rawDescription: python counting frequency of elements

description: Python counting frequency of elements


code:
chars = frozenset(map(chr, range(ord('a'), ord('z')+1) + range(ord('A'), ord('Z')+1)))
with open(fn) as f:
    print sum(1 for c in f.read() if c in chars)

rawDescription: Python: Number of letters in file, simple yet efficient way


rawDescription: List of numbers

description: List of numbers


code:
import codecs, re

def open_detect(path):
    fin = open(path, 'rb')
    prefix = fin.read(80)
    encs = re.findall('#\s*coding\s*=\s*([\w\d\-]+)\s+', prefix)
    encoding = encs[0] if encs else 'utf-8'
    fin.seek(0)
    return codecs.EncodedFile(fin, 'utf-8', encoding)

for path in ('utf-8.txt','cp1252.txt'):
    fin = open_detect(path)
    print repr(fin.readlines())

rawDescription: Read a unicode file in python which declares its encoding in the same way as python source


code:
o1 = Test()
o2 = Test()

print "o1 static_attr : ", o1.static_attr1
print "o2 static_attr : ", o2.static_attr1

Test.static_method(3)

print "o1 static_attr : ", o1.static_attr1
print "o2 static_attr : ", o2.static_attr1

rawDescription: Java-like static class & method in Python


code:
f = lambda x: 'f({!r})'.format(x)
g = lambda x: 'g({})'.format(x)
h = lambda x: 'h({})'.format(x)

my_composition = compose(f, g, h)
print my_composition('X')

rawDescription: How can I automatically run all the functions in the module?

description: Automatically run all the functions in the module


code:
members = ["skoda","audi","benz","bmw","audi","Rangerover","Hummer"]

print ','.join(sorted(set(members),key=lambda x: members.index(x)))
skoda,audi,benz,bmw,Rangerover,Hummer

rawDescription: python preserving order in set after removing duplicate

description: Python preserving order in set after removing duplicate


code:
from subprocess import PIPE,Popen
sorting = Popen(["sort", field, output, append, new_path], stdout=PIPE)
out, err = sorting.communicate()
print out

rawDescription: How to store output from linux call in Python

description: Store output from linux call in Python


code:
input = [['SE01_inf', 'name', [], 'NA', []],\
         ['SE01_loc', 'NA', 'loc', 'NA', []],\
         ['SE01_id', 'NA', [], '123', []],\
         ['SE01_1_inf', 'name1', [], 'NA', []],\
         ['SE01_1_loc', 'NA', 'loc', 'NA', []]]

output = {}
for row in input:
    id = row[0][:row[0].rfind('_')]
    if id not in output:
        output[id] = [id] + row[1:]
    else:
        output[id] = [new if old in ('NA', []) else old for new, old in zip(row, output[id])]

print output.values()

rawDescription: grouping by rows in python

description: Grouping by rows in python


code:
for row in matrix:
    for x in row:
        print x

rawDescription: How to read Python comprehension with two expressions?

description: Read Python comprehension with two expressions


code:
def gettype(line):
    return line[-1]

S1, S2 = 0, 0
with open(path) as f:
     lines = f.read().splitlines()

lines.sort(key=gettype)
for type, group in itertools.groupby(lines, gettype):
    ids = (line.partition(" ")[0] for line in group)
    if type == "1" or type == "2":
       S1 += len(set(ids))
    elif type == "3" or type == "4":
       S2 += len(set(ids))
    else:
       assert 0, (type, list(ids))

print S1, S2

rawDescription: How to improve performance of this counting program?

description: Improve performance of this counting program


code:
import sys

MY_X = 3
MY_Y = 4
MY_RNG = 2

grid = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
    [0, 0, 1, 1, 1, 1, 0, 0, 1, 0],
    [0, 1, 1, 1, 1, 1, 1, 1, 1, 1],
    [0, 0, 1, 1, 0, 1, 1, 0, 0, 1],
    [0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
    [0, 0, 0, 0, 1, 1, 1, 1, 1, 0],
    [0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
    [0, 1, 1, 1, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
]

def findTileLetter(x, y):
    return grid[y][x]

class Person:
    pass

def showMap():
    for y in range(len(grid)):
        for x in range(len(grid[y])):
            if grid[y][x] == 0:
                sys.stdout.write(' ')
            elif x == MY_X and y == MY_Y:
                sys.stdout.write('x')
            elif (x, y) in ALLOWEDMOVES:
                sys.stdout.write('o')
            else:
                sys.stdout.write('-')
        sys.stdout.write('\n')

me = Person()

ALLOWEDMOVES = []

PLAYERDISTANCE = {}
PLAYERDISTANCE[me] = MY_RNG

PLAYERSPOSITION = {}
PLAYERSPOSITION[me] = (MY_X, MY_Y)

def showPerson(tilex, tiley, personAtTile):
    global ALLOWEDMOVES
    ALLOWEDMOVES = []
    prepare = {k:v for v,k in PLAYERSPOSITION.items()}
    z = PLAYERDISTANCE[personAtTile]
    #get all coords for the possible moves
    currentNewSpots = []
    oldSpots = []
    a = PLAYERSPOSITION[personAtTile][0]
    b = PLAYERSPOSITION[personAtTile][1]
    c = a + 1
    test = findTileLetter(c, b)
    if test:
        currentNewSpots.append((c, b))
        ALLOWEDMOVES.append((c, b))
    c = a -1
    test = findTileLetter(c, b)
    if test:
        currentNewSpots.append((c, b))
        ALLOWEDMOVES.append((c, b))
    c = b + 1
    test = findTileLetter(a, c)
    if test:
        currentNewSpots.append((a, c))
        ALLOWEDMOVES.append((a, c))
    c = b - 1
    test = findTileLetter(a, c)
    if test:
        currentNewSpots.append((a, c))
        ALLOWEDMOVES.append((a, c))

    showMap()

    for x in range(PLAYERDISTANCE[prepare[(tilex, tiley)]]):
        for y in range(len(currentNewSpots)):
            a = currentNewSpots[y][0]
            b = currentNewSpots[y][1]
            c = a + 1
            test = findTileLetter(c, b)
            if test and ((c, b)) not in ALLOWEDMOVES:
                currentNewSpots.append((c, b))
                ALLOWEDMOVES.append((c, b))
            c = a - 1
            test = findTileLetter(c, b)
            if test and ((c, b)) not in ALLOWEDMOVES:
                currentNewSpots.append((c, b))
                ALLOWEDMOVES.append((c, b))
            c = b + 1
            test = findTileLetter(a, c)
            if test and ((a, c)) not in ALLOWEDMOVES:
                currentNewSpots.append((a, c))
                ALLOWEDMOVES.append((a, c))
            c = b - 1
            test = findTileLetter(a, c)
            if test and ((a, c)) not in ALLOWEDMOVES:
                currentNewSpots.append((a, c))
                ALLOWEDMOVES.append((a, c))
        showMap()

showPerson(MY_X, MY_Y, me)
print ALLOWEDMOVES

rawDescription: Turn Based Movement Algorithm

description: Turn Based Movement Algorithm


code:
from jinja2 import Template

items = [
    ['foo', 'bar'],
    ['bax', 'quux', 'ketchup', 'mustard'],
    ['bacon', 'eggs'],
    ]

print Template("""
{% set counter = 0 -%}
{% for group in items -%}
  {% for item in group -%}
    item={{ item }}, count={{ counter + loop.index0 }}
  {% endfor -%}
  {% set counter = counter + group|length %}
{% endfor -%}
""").render(items=items)

rawDescription: How can I make a simple counter with Jinja2 templates?

description: Make a simple counter with Jinja2 templates


code:
import urllib2
import urllib # needed for url-encoding
par = {"text": "He is a good boy"}
headers={"Accept" : "application/rdf+xml"}
request = urllib2.Request(
    "http://wit.istc.cnr.it/stlab-tools/fred/?" + urllib.urlencode(par),
    headers=headers)
contents = urllib2.urlopen(request).read()
print contents

rawDescription: FRED rest API in python

description: FRED rest API in python


code:
import numpy as np

def binnings(n, k, cache={}):
    if n == 0:
        return np.zeros((1, k))
    if k == 0:
        return np.empty((0, 0))
    args = (n, k)
    if args in cache:
        return cache[args]
    a = binnings(n - 1, k, cache)
    a1 = a + (np.arange(k) == 0)
    b = binnings(n, k - 1, cache)
    b1 = np.hstack((np.zeros((b.shape[0], 1)), b))
    result = np.vstack((a1, b1))
    cache[args] = result
    return result

if __name__ == '__main__':
    import timeit
    print timeit.timeit('binnings(20, 5, {})', setup='from __main__ import binnings', number=1)

rawDescription: Efficient item binning algorithm (itertools/numpy)


code:
import pyfits

keys = ['SIMPLE', 'TELESCOP', 'INSTRUME', 'OBJECTS', 'RA_OBJ', 'DEV_OBJ']

hdulist = pyfits.open("data.fits")
header = hdulist[0].header
for k in keys:
    print k, "=", header[k]

rawDescription: Making an Ascii table from a FITS file header


code:
a = UserTest(name='ehsan', family='shirzadi', age=29)
print vars(a)

rawDescription: How to access a class field values in its base class?

description: Access a class field values in its base class


code:
import re
p = re.compile(ur'^(?:by|from) (\S+)', re.MULTILINE)
test_str = u"from mail2.oknotify2.com (mail2.oknotify2.com. [208.83.243.70]) by mx.google.com with ESMTP id dp5si2596299pdb.170.2015.06.03.14.12.03\n\nby 10.66.156.198 with SMTP id wg6mr62843415pab.126.1433365924352;\n\nfrom localhost (localhost [127.0.0.1])"
print [x.group(1) for x in re.finditer(p, test_str)]

rawDescription: Regex: How to leave out string + space before a domain or IP address?


code:
b = 3
from A import *
print "a in B's namespace:", a

rawDescription: passing value to other module python

description: Passing value to other module python


code:
def eq_hash(word):
    return tuple(word.index(c) for c in word)

print eq_hash('mom') # 0 1 0
print eq_hash('dad') # 0 1 0

rawDescription: Find equivalent words in a list through arbitrary mapping


code:
# broadcast.py
from socket import *
import struct

if __name__ == "__main__":
        UDP_IP = '<broadcast>'
        UDP_PORT = 6139
        HEX = 0x2F03F4B2
        I = 0
        V = 0
        C = 0
        PAYLOAD = struct.pack("!L3i", HEX, I, V, C)
        comsocket = socket(AF_INET, SOCK_DGRAM)
        comsocket.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
        comsocket.sendto(PAYLOAD, (UDP_IP, UDP_PORT))
        data, wherefrom = comsocket.recvfrom(1024, 0)
        print data, wherefrom
        comsocket.close()

rawDescription: UDP communication to device that responds to port request comes from, how to get that response


code:
if __name__ == '__main__':
    fs = []
    for j in range(10):
        p = Process(target=f, args=(j,))
        p.start()
        fs.append(p)

    for f in fs:
        f.join()

    print "switch"

    # comment
    gs = []
    for j in range(10):
        q = Process(target=g, args=(j,))
        q.start()
        gs.append(q)

    for g in gs:
        g.join()

    print "I'm done"

rawDescription: How to run two parallel processes subsequently?

description: Run two parallel processes subsequently


code:
from collections import defaultdict
d = defaultdict(int)

s = "hello this is hello this is baby baby baby baby hello"

for w in s.split():
    if len(w)>=4:
        d[w] += 1

print d

rawDescription: Counting the Repeating of words in a list PYTHON


code:
#!/usr/bin/env python

import bisect

def find_lt(a, x):
    'Find rightmost value less than x'
    i = bisect.bisect_left(a, x)
    if i:
        return a[i-1]
    raise ValueError

def find_gt(a, x):
    'Find leftmost value greater than x'
    i = bisect.bisect_right(a, x)
    if i != len(a):
        return a[i]
    raise ValueError

# First create a test-list (49996 items)
i=1.0
R=[1.0]
D={}
while i < 10000:
    i+=0.2
    i=round(i,2)
    D[i]=True
    R.append(i)

# Locate a value, in this case 100.3 which is not in the list
x=100.3
if D.has_key(x):
    print "found", x
else:
    print find_lt(R, x)
    print find_gt(R, x)

rawDescription: search for before and after values in a long sorted list

description: Search for before and after values in a long sorted list


code:
newperson = Person(name="Ben", address='9999 Gotham City, las vegas', phone=['702-000-0000', '111-827-3509'], gender ='male', prefix ='Waiter')
print newperson.userdata

rawDescription: Initializing Python class with array data


code:
s = "orange apple grapes pear"

from itertools import product
l = s.split()
r='/'.join(''.join(k*v for k,v in zip(l, x))
           for x in product(range(2), repeat=len(l))
           if sum(x) > 1)
print r

rawDescription: Combining words in Python (permutations?)


code:
import win32pipe

print win32pipe.CallNamedPipe(r"\\.\pipe\named_pipe_demo", "Hello", 64, 0)

rawDescription: Showing data in a GUI where the data comes from an outside source


code:
#!/usr/bin/env python

team_ids = ('A', 'B')

team_names = (
    ('Fred', 'Bob'),
    ('John', 'Jake'),
)

#Build a dict to get team name from person name
teams = {}
for team_id, names in zip(team_ids, team_names):
    for name in names:
        teams[name] = team_id

#Each block in convo MUST consist of <name>\n<one line of text>\n\n
#Do NOT omit the final blank line at the end
convo = '''Fred
hello

John
hi

Bob
how is it going?

Jake
we are doing fine

'''

lines = convo.splitlines()

#Group lines into <name><text><empty> chunks
#and append the text into the appropriate list in `said`
said = {'A': [], 'B': []}
for name, text, _ in zip(*[iter(lines)]*3):
    team_id = teams[name]
    said[team_id].append(text)

for team_id in team_ids:
    print 'Team %s said: %r' % (team_id, ' '.join(said[team_id]))

rawDescription: disassemble and reassemble strings based on list

description: Disassemble and reassemble strings based on list


code:
list_ = []
for i in range(something):
    dict_ = {}
    get_values_into_dict(dict_)
    list_.append(dict_)
print list_

rawDescription: Python The appended element in the list changes as its original variable changes


code:
#!/usr/bin/env python

import questions

print "question one is,", questions.sports_questions[0]

rawDescription: Having large lists in main scripts, is there anyway to get it out of the main-script and into another module?


rawDescription: Test if two lists of lists are equal

description: Test if two lists of lists are equal


code:
def options(opt):
    opt.load('compiler_c')
    opt.load('compiler_cxx')

def configure(cfg):
    cfg.load('compiler_c')
    cfg.load('compiler_cxx')

def build(bld):
    print "Compiler is CC_NAME  %s  CC  %s"%(bld.env.CC_NAME,bld.env.CC)
    print "Compiler is CXX_NAME %s  CXX %s"%(bld.env.CXX_NAME,bld.env.CXX)

rawDescription: How to determine tools chosen by waf?

description: Determine tools chosen by waf


code:
def btn_click(button_name):
    print button_name

rawDescription: Is it possible to know the button name through function


code:
a = "QWE"

for member in dir(a):
    print getattr(a, member)

rawDescription: How to do string with dot operator extension using a variable

description: Do string with dot operator extension using a variable


code:
seen = set()
print list(set(x for x in myList if x in seen or seen.add(x)))

rawDescription: How to check if two numbers in a list are the same

description: Check if two numbers in a list are the same


code:
levels = map(tuple, frame.index.levels)
index = list(product(*levels))
frame = frame.reindex(levels)
print frame

rawDescription: Transform Pandas DataFrame with n-level hierarchical index into n-D Numpy array


code:
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('abc.txt')

dic = {}

for section in config.sections():
    for option in config.options(section):
        res = config.get(section, option)
        if res == '':
            continue
        dic.update({section: res})

print dic

rawDescription: Parse the file section wise in python

description: Parse the file section wise in python


code:
print db.users.count()
# OR
print db["users"].count()

rawDescription: How do I construct a variable query with pymongo

description: Construct a variable query with pymongo


code:
from collections import defaultdict

class Crosstab(object):

    def __init__(self):
        self.count = defaultdict(lambda: defaultdict(int))
        self.row_tot = defaultdict(int)
        self.col_tot = defaultdict(int)
        self.grand_tot = 0

    def add(self, r, c, n):
        self.count[r][c] += n
        self.row_tot[r] += n
        self.col_tot[c] += n
        self.grand_tot += n

def load_data(line_iterator, conv_funcs):
    ct = Crosstab()
    for line in line_iterator:
        r, c, n = [func(s) for func, s in zip(conv_funcs, line.split(','))]
        ct.add(r, c, n)
    return ct

def display_all_2x2_tables(crosstab):
    for rx in crosstab.row_tot:
        for cx in crosstab.col_tot:
            a = crosstab.count[rx][cx]
            b = crosstab.col_tot[cx] - a
            c = crosstab.row_tot[rx] - a
            d = crosstab.grand_tot - a - b - c
            assert all(x >= 0 for x in (a, b, c, d))
            print ",".join(str(x) for x in (rx, cx, a, b, c, d))

if __name__ == "__main__":

    # inputfile
    # <word, time, frequency>
    lines = """\
    apple, 1, 3
    banana, 1, 2
    apple, 2, 1
    banana, 2, 4
    orange, 3, 1""".splitlines()

    ct = load_data(lines, (str.strip, int, int))
    display_all_2x2_tables(ct)

rawDescription: Python, dictionaries, and chi-square contingency table


code:
#!/usr/bin/python

from collections import defaultdict
import json

def tree():
    return defaultdict(tree)

nested = defaultdict(tree)

words = open("single.txt").read().splitlines()
words_output = open("out.json", "wb")

for word in words:
    node = nested
    for char in word:
        node = node[char.lower()]

def convert(d):
    return dict((key, convert(value)) for (key,value) in d.iteritems()) if isinstance(d, defaultdict) else d

def format(d):
    children = []
    for (key, value) in d.iteritems():
        children += [{"name":key, "children":format(value)}]
    return children

print json.dumps(format(convert(nested)))

rawDescription: Structuring Plain Text to JSON

description: Structuring Plain Text to JSON


code:
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get('https://weedmaps.com/dispensaries/in/united-states/colorado')

wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.subregion a.region-ajax-link")))

for region in driver.find_elements_by_css_selector("div.subregion a.region-ajax-link"):
    print region.get_attribute("href")

driver.close()

rawDescription: Scrapy Xpath construction producing empty brackets on dynamic site


code:
from bs4 import BeautifulSoup

data = """

Market Cap:  10.64 Crores

Current Price:  35.35

Book Value:  53.52

"""
soup = BeautifulSoup(data)

titles = ['Market Cap', 'Current Price', 'Book Value']
for title in titles:
    print soup.find(text=lambda x: x.startswith(title)).next_element.text

rawDescription: how to obtain class contents in html using beautifulsoup?

description: Obtain class contents in html using beautifulsoup


code: print ' '.join(line.split()[:3])

rawDescription: how to retrieve value from text file using python?

description: Retrieve value from text file using python


code:
import regex
result = regex.sub(ur'[^\p{Latin}]', u'', text)

rawDescription: Python Removing Non Latin Characters

description: Python Removing Non Latin Characters


code:
import functools
def valid_for(typelist):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(self, *args):
            if self.genus_type in typelist:
                return func(self, *args)
            else:
                # handle this case
                raise NotImplementedError(
                    '{} not in {}'.format(self.genus_type, typelist))
        return wrapper
    return decorator

class A(object):
    def __init__(self):
        self.genus_type = 'typeA'
    @valid_for(['typeB'])
    def do_something_cool(self):
        print 'blah'

a = A()
try:
    a.do_something_cool()
except NotImplementedError as err:
    print(err)
    # typeA not in ['typeB']

a.genus_type = 'typeB'
a.do_something_cool()
# blah

rawDescription: Python descriptors with arguments?

description: Python descriptors with arguments


code:
def x(t):
    return math.exp(-(t-4)**2)

print diff(x, 0)

rawDescription: Arbitrary functions

description: Arbitrary functions


code:
from pyparsing import *

# parse action -maker
def makeLRlike(numterms):
    if numterms is None:
        # None operator can only by binary op
        initlen = 2
        incr = 1
    else:
        initlen = {0:1,1:2,2:3,3:5}[numterms]
        incr = {0:1,1:1,2:2,3:4}[numterms]

    # define parse action for this number of terms,
    # to convert flat list of tokens into nested list
    def pa(s,l,t):
        t = t[0]
        if len(t) > initlen:
            ret = ParseResults(t[:initlen])
            i = initlen
            while i < len(t):
                ret = ParseResults([ret] + t[i:i+incr])
                i += incr
            return ParseResults([ret])
    return pa

# setup a simple grammar for 4-function arithmetic
varname = oneOf(list(alphas))
integer = Word(nums)
operand = integer | varname

# ordinary opPrec definition
arith1 = operatorPrecedence(operand,
    [
    (None, 2, opAssoc.LEFT),
    (oneOf("* /"), 2, opAssoc.LEFT),
    (oneOf("+ -"), 2, opAssoc.LEFT),
    ])

# opPrec definition with parseAction makeLRlike
arith2 = operatorPrecedence(operand,
    [
    (None, 2, opAssoc.LEFT, makeLRlike(None)),
    (oneOf("* /"), 2, opAssoc.LEFT, makeLRlike(2)),
    (oneOf("+ -"), 2, opAssoc.LEFT, makeLRlike(2)),
    ])

# parse a few test strings, using both parsers
for arith in (arith1, arith2):
    print arith.parseString("A+B+C+D+E")[0]
    print arith.parseString("A+B+C*D+E")[0]
    print arith.parseString("12AX+34BY+C*5DZ+E")[0]

rawDescription: Recursive expressions with pyparsing

description: Recursive expressions with pyparsing


code:
import re

data = """start < some 50 words > End
start < some 50 words >
start < some 50 words > End
start < some 50 words >
< some 50 words > End
"""

print re.sub('start(.*)End', 'start2\g<1>End.', data)

rawDescription: search regex pattern and python function needed

description: Search regex pattern and python function needed


code:
def my_task():
    print 'Currently executing on {0}'.format(env.host)

rawDescription: Retrieve current host from within an executed task


code:
from Tkinter import *
import tkMessageBox

app = Tk()
# Message Window

def messagePop():
    get_data()
    tkMessageBox.showinfo('Results', '100% Very Good')

# Background colour

app.configure(bg='cornflower blue')

COLORS  =['snow', 'ghost white', 'white smoke', 'gainsboro', 'floral white', 'old lace',
    'linen', 'antique white', 'papaya whip', 'blanched almond', 'bisque', 'peach puff',
    'navajo white', 'lemon chiffon', 'mint cream', 'azure', 'alice blue', 'lavender',
    'lavender blush', 'misty rose', 'dark slate gray', 'dim gray', 'slate gray',
    'light slate gray', 'gray', 'light grey', 'midnight blue', 'navy', 'cornflower blue', 'dark slate blue',
    'slate blue', 'medium slate blue', 'light slate blue', 'medium blue', 'royal blue',  'blue',
    'dodger blue', 'deep sky blue', 'sky blue', 'light sky blue', 'steel blue', 'light steel blue',
    'light blue', 'powder blue', 'pale turquoise', 'dark turquoise', 'medium turquoise', 'turquoise',
    'cyan', 'light cyan', 'cadet blue', 'medium aquamarine', 'aquamarine', 'dark green', 'dark olive green',
    'dark sea green', 'sea green', 'medium sea green', 'light sea green', 'pale green', 'spring green',
    'lawn green', 'medium spring green', 'green yellow', 'lime green', 'yellow green',
    'forest green', 'olive drab', 'dark khaki', 'khaki', 'pale goldenrod', 'light goldenrod yellow',
    'light yellow', 'yellow', 'gold', 'light goldenrod', 'goldenrod', 'dark goldenrod', 'rosy brown',
    'indian red', 'saddle brown', 'sandy brown',
    'dark salmon', 'salmon', 'light salmon', 'orange', 'dark orange',
    'coral', 'light coral', 'tomato', 'orange red', 'red', 'hot pink', 'deep pink', 'pink', 'light pink',
    'pale violet red', 'maroon', 'medium violet red', 'violet red',
    'medium orchid', 'dark orchid', 'dark violet', 'blue violet', 'purple', 'medium purple',
    'thistle', 'snow2', 'snow3',
    'snow4', 'seashell2', 'seashell3', 'seashell4', 'AntiqueWhite1', 'AntiqueWhite2',
    'AntiqueWhite3', 'AntiqueWhite4', 'bisque2', 'bisque3', 'bisque4', 'PeachPuff2',
    'PeachPuff3', 'PeachPuff4', 'NavajoWhite2', 'NavajoWhite3', 'NavajoWhite4',
    'LemonChiffon2', 'LemonChiffon3', 'LemonChiffon4', 'cornsilk2', 'cornsilk3',
    'cornsilk4', 'ivory2', 'ivory3', 'ivory4', 'honeydew2', 'honeydew3', 'honeydew4',
    'LavenderBlush2', 'LavenderBlush3', 'LavenderBlush4', 'MistyRose2', 'MistyRose3',
    'MistyRose4', 'azure2', 'azure3', 'azure4', 'SlateBlue1', 'SlateBlue2', 'SlateBlue3',
    'SlateBlue4', 'RoyalBlue1', 'RoyalBlue2', 'RoyalBlue3', 'RoyalBlue4', 'blue2', 'blue4',
    'DodgerBlue2', 'DodgerBlue3', 'DodgerBlue4', 'SteelBlue1', 'SteelBlue2',
    'SteelBlue3', 'SteelBlue4', 'DeepSkyBlue2', 'DeepSkyBlue3', 'DeepSkyBlue4',
    'SkyBlue1', 'SkyBlue2', 'SkyBlue3', 'SkyBlue4', 'LightSkyBlue1', 'LightSkyBlue2',
    'LightSkyBlue3', 'LightSkyBlue4', 'SlateGray1', 'SlateGray2', 'SlateGray3',
    'SlateGray4', 'LightSteelBlue1', 'LightSteelBlue2', 'LightSteelBlue3',
    'LightSteelBlue4', 'LightBlue1', 'LightBlue2', 'LightBlue3', 'LightBlue4',
    'LightCyan2', 'LightCyan3', 'LightCyan4', 'PaleTurquoise1', 'PaleTurquoise2',
    'PaleTurquoise3', 'PaleTurquoise4', 'CadetBlue1', 'CadetBlue2', 'CadetBlue3',
    'CadetBlue4', 'turquoise1', 'turquoise2', 'turquoise3', 'turquoise4', 'cyan2', 'cyan3',
    'cyan4', 'DarkSlateGray1', 'DarkSlateGray2', 'DarkSlateGray3', 'DarkSlateGray4',
    'aquamarine2', 'aquamarine4', 'DarkSeaGreen1', 'DarkSeaGreen2', 'DarkSeaGreen3',
    'DarkSeaGreen4', 'SeaGreen1', 'SeaGreen2', 'SeaGreen3', 'PaleGreen1', 'PaleGreen2',
    'PaleGreen3', 'PaleGreen4', 'SpringGreen2', 'SpringGreen3', 'SpringGreen4',
    'green2', 'green3', 'green4', 'chartreuse2', 'chartreuse3', 'chartreuse4',
    'OliveDrab1', 'OliveDrab2', 'OliveDrab4', 'DarkOliveGreen1', 'DarkOliveGreen2',
    'DarkOliveGreen3', 'DarkOliveGreen4', 'khaki1', 'khaki2', 'khaki3', 'khaki4',
    'LightGoldenrod1', 'LightGoldenrod2', 'LightGoldenrod3', 'LightGoldenrod4',
    'LightYellow2', 'LightYellow3', 'LightYellow4', 'yellow2', 'yellow3', 'yellow4',
    'gold2', 'gold3', 'gold4', 'goldenrod1', 'goldenrod2', 'goldenrod3', 'goldenrod4',
    'DarkGoldenrod1', 'DarkGoldenrod2', 'DarkGoldenrod3', 'DarkGoldenrod4',
    'RosyBrown1', 'RosyBrown2', 'RosyBrown3', 'RosyBrown4', 'IndianRed1', 'IndianRed2',
    'IndianRed3', 'IndianRed4', 'sienna1', 'sienna2', 'sienna3', 'sienna4', 'burlywood1',
    'burlywood2', 'burlywood3', 'burlywood4', 'wheat1', 'wheat2', 'wheat3', 'wheat4', 'tan1',
    'tan2', 'tan4', 'chocolate1', 'chocolate2', 'chocolate3', 'firebrick1', 'firebrick2',
    'firebrick3', 'firebrick4', 'brown1', 'brown2', 'brown3', 'brown4', 'salmon1', 'salmon2',
    'salmon3', 'salmon4', 'LightSalmon2', 'LightSalmon3', 'LightSalmon4', 'orange2',
    'orange3', 'orange4', 'DarkOrange1', 'DarkOrange2', 'DarkOrange3', 'DarkOrange4',
    'coral1', 'coral2', 'coral3', 'coral4', 'tomato2', 'tomato3', 'tomato4', 'OrangeRed2',
    'OrangeRed3', 'OrangeRed4', 'red2', 'red3', 'red4', 'DeepPink2', 'DeepPink3', 'DeepPink4',
    'HotPink1', 'HotPink2', 'HotPink3', 'HotPink4', 'pink1', 'pink2', 'pink3', 'pink4',
    'LightPink1', 'LightPink2', 'LightPink3', 'LightPink4', 'PaleVioletRed1',
    'PaleVioletRed2', 'PaleVioletRed3', 'PaleVioletRed4', 'maroon1', 'maroon2',
    'maroon3', 'maroon4', 'VioletRed1', 'VioletRed2', 'VioletRed3', 'VioletRed4',
    'magenta2', 'magenta3', 'magenta4', 'orchid1', 'orchid2', 'orchid3', 'orchid4', 'plum1',
    'plum2', 'plum3', 'plum4', 'MediumOrchid1', 'MediumOrchid2', 'MediumOrchid3',
    'MediumOrchid4', 'DarkOrchid1', 'DarkOrchid2', 'DarkOrchid3', 'DarkOrchid4',
    'purple1', 'purple2', 'purple3', 'purple4', 'MediumPurple1', 'MediumPurple2',
    'MediumPurple3', 'MediumPurple4', 'thistle1', 'thistle2', 'thistle3', 'thistle4',
    'gray1', 'gray2', 'gray3', 'gray4', 'gray5', 'gray6', 'gray7', 'gray8', 'gray9', 'gray10',
    'gray11', 'gray12', 'gray13', 'gray14', 'gray15', 'gray16', 'gray17', 'gray18', 'gray19',
    'gray20', 'gray21', 'gray22', 'gray23', 'gray24', 'gray25', 'gray26', 'gray27', 'gray28',
    'gray29', 'gray30', 'gray31', 'gray32', 'gray33', 'gray34', 'gray35', 'gray36', 'gray37',
    'gray38', 'gray39', 'gray40', 'gray42', 'gray43', 'gray44', 'gray45', 'gray46', 'gray47',
    'gray48', 'gray49', 'gray50', 'gray51', 'gray52', 'gray53', 'gray54', 'gray55', 'gray56',
    'gray57', 'gray58', 'gray59', 'gray60', 'gray61', 'gray62', 'gray63', 'gray64', 'gray65',
    'gray66', 'gray67', 'gray68', 'gray69', 'gray70', 'gray71', 'gray72', 'gray73', 'gray74',
    'gray75', 'gray76', 'gray77', 'gray78', 'gray79', 'gray80', 'gray81', 'gray82', 'gray83',
    'gray84', 'gray85', 'gray86', 'gray87', 'gray88', 'gray89', 'gray90', 'gray91', 'gray92',
    'gray93', 'gray94', 'gray95', 'gray97', 'gray98', 'gray99']

# The position and size relative to the screen
app.geometry('500x500+450+140')

# The title of the program
app.title('Maths4Primary')

# The icon
app.wm_iconbitmap('MathIcon.ico')

# Object positioning in the program
# def GridPos:

# I might use the place() method for the screen layout.
Label(app, text="Put these prices in order", bg="gold", fg="blue").place(x=100,y=20)
Label(app, text= u"\xA3" + "20.50", bg="gold", fg="blue").place(x=20,y=50)
Label(app, text="Question 3", bg="gold", fg="blue").place(x=20,y=120)

# Entry
def get_data():
    x_data = x.get()
    y_data = y.get()
    z_data = z.get()
    print "x_data = {0} , y_data = {1} , z_data = {2}".format(x_data,y_data,z_data)

x = Entry(app)
y = Entry(app)
z = Entry(app)

x.place(x=150,y=60)
y.place(x=150,y=80)
z.place(x=150,y=100)

# Buttons
B1 = Button(app,text='Marks',bg='gold',fg='blue', command = messagePop ).place(x=425,y=450)

app.mainloop()

rawDescription: How do I store a value entered on a Tk entry widget in a variable

description: Store a value entered on a Tk entry widget in a variable


rawDescription: How to index a DataFrame based on the number of consecutive days

description: Index a DataFrame based on the number of consecutive days


code:
import subprocess
import time
from daemon import runner
import datetime

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/YOUR_PROCESS_NAME.pid'
        self.pidfile_timeout = 5
    def run(self):

        counter1 = 0
        counter_log = 0
        try:
            while True:

                # INSERT YOUR FUNCTIONS HERE

                # SET YOUR LOOP SLEEP TIMER (IN SECONDS) HERE
                time.sleep(60)

        except Exception, e:
            raise

app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

rawDescription: Average network statistics in Python

description: Average network statistics in Python


code:
nos = [4, 4, 1, 1]
for i in range(sum(nos)): print i+1

rawDescription: A simple list simulation in python

description: A simple list simulation in python


code:
firstDictionary = {"firstKey" : "A", "secondKey" : "B"}
secondDictionary = {"firstKey" : 3, "secondKey" : 47}
emptyDictionary = {value : secondDictionary.get(key, None) for key, value in firstDictionary.items()}
print emptyDictionary

rawDescription: new dictionary from existing dictionary values

description: New dictionary from existing dictionary values


code:
import networkx as nx
import matplotlib.pyplot as plt
import itertools

H = nx.DiGraph()

axis_labels = ['p','q','r','s']

D_len_node = {}

#Iterate through axis labels
for i in xrange(0,len(axis_labels)+1):
    #Create edge from empty set
    if i == 0:
        for ax in axis_labels:
            H.add_edge('O',ax)
    else:
        #Create all non-overlapping combinations
        combinations = [c for c in itertools.combinations(axis_labels,i)]
        D_len_node[i] = combinations
    #Create edge from len(i-1) to len(i) #eg. pq >>> pqr, pq >>> pqs
    if i > 1:
        for node in D_len_node[i]:
            for p_node in D_len_node[i-1]:
                if set.intersection(set(p_node),set(node)):
                    H.add_edge(''.join(p_node),''.join(node))

#This is manual two options to project tesseract onto 2D plane
# - many projections are available!!
wikipedia_projection_coords = [(0.5,0),(0.85,0.25),(0.625,0.25),(0.375,0.25),
                                (0.15,0.25),(1,0.5),(0.8,0.5),(0.6,0.5),
                                (0.4,0.5),(0.2,0.5),(0,0.5),(0.85,0.75),
                                (0.625,0.75),(0.375,0.75),(0.15,0.75),(0.5,1)]

#Build the "two cubes" type example projection co-ordinates
half_coords = [(0,0.15),(0,0.6),(0.3,0.15),(0.15,0),
               (0.55,0.6),(0.3,0.6),(0.15,0.4),(0.55,1)]
#make the coords symmetric
example_projection_coords = half_coords + [(1-x,1-y) for (x,y) in half_coords][::-1]

print example_projection_coords

def powerset(s):
    ch = itertools.chain.from_iterable(itertools.combinations(s, r) for r in range(len(s)+1))
    return [''.join(t) for t in ch]

pos={}
for i,label in enumerate(powerset(axis_labels)):
    if label == '':
       label = 'O'
    pos[label]= example_projection_coords[i]

#Show Plot
nx.draw(H,pos,with_labels = True,node_shape = 'o')
plt.show()

rawDescription: How to reshape a networkx graph in Python?

description: Reshape a networkx graph in Python


code:
def save_events_json(request):
    if request.is_ajax():
        if request.method == 'POST':
            print 'Raw Data: "%s"' % request.body
    return HttpResponse("OK")

rawDescription: Where's my JSON data in my incoming Django request?


code:
import random

width = 5
height = 5

class Brain(object):

    def __init__(self):
        self.w = [[1]]
        self.ix = [[1]]

    def mutate(self):
        self.w[0].append(1)

class Animal(object):

    def __init__(self):
        self.brain = Brain()
        self.x = random.randint(0, width)
        self.y = random.randint(0, height)
        self.age = 0
        self.fitness = 10

def reproduce(parent):
    child = Animal()
    child.brain.w= parent.brain.w[:]
    child.brain.ix= parent.brain.ix[:]
    child.x,child.y = random.randint(0,width),random.randint(0,height)
    child.age = 0
    child.fitness= 9 + parent.fitness/10 #parent.fitness/2

    mutation = random.choice([0,1,1,1,1,1,1,1,1,2,3,4,5])
    for b in range(mutation):
      child.brain.mutate()
    animals.append(child)

animals = []
parent = Animal()

animals.append(parent)
print parent.brain.w
#reproduce(parent)
import copy
reproduce(copy.deepcopy(parent))

for each in animals:
    print each.brain.w

rawDescription: applying a function on an object in python

description: Applying a function on an object in python


code:
def f(x):
    return x == 2

if not any(f(k) for k in a):
    print 'no match'

rawDescription: Is there an inverse behavior to the "else" in a for-else loop?


code:
with open("credentials.txt", "r") as infile:
    data = [line.rstrip().split(",") for line in infile]
    usernames, passwords = zip(*data)
    print usernames, passwords
    # ('mcgoga12', 'shelby12') ('password', 'password1')

rawDescription: Parsing a text file with Python and split()


code:
print getstring('(hello)')
print getstring('@hello sdfdsf')

rawDescription: Extract value from string in Python?

description: Extract value from string in Python


code:
posts = []
for url in RSS_URLS:
    posts.extend(feedparser.parse(url).entries)

for post in posts:
    print post.title

rawDescription: How can I parse multiple URLs in feedparser (Python)?

description: Parse multiple URLs in feedparser (Python)


code:
for x in wx.all_synsets('n'):
    print x

rawDescription: Searching through an entire series of synsets (from NLTK) in Python NLP


code:
import time
import threading
import multiprocessing

def fn():
    '''since all 3 functions were identical you can just use one ...'''
    x = 0
    while  x < 100000000:
        x += 1

def TEST_THREADS():
    new_thread1  = threading.Thread(target = fn , args = ())
    new_thread2  = threading.Thread(target = fn, args = ())
    new_thread3  = threading.Thread(target = fn, args = ())
    new_thread1.start()
    new_thread2.start()
    new_thread3.start()
    new_thread1.join()
    new_thread2.join()
    new_thread3.join()

def TEST_NORMAL():
    fn()
    fn()
    fn()

def TEST_MULTIPROCESSING():
    new_thread1  = multiprocessing.Process(target = fn , args = ())
    new_thread2  = multiprocessing.Process(target = fn, args = ())
    new_thread3  = multiprocessing.Process(target = fn, args = ())
    new_thread1.start()
    new_thread2.start()
    new_thread3.start()
    new_thread1.join()
    new_thread2.join()
    new_thread3.join
if __name__ == "__main__":
    '''It is very important to use name == __main__ guard code with threads and multiprocessing'''
    import timeit
    print "Time to Run 1x: %0.2fs"%(timeit.timeit(fn,number=1),)
    print "NORMAL:%0.2fs"%(timeit.timeit(TEST_NORMAL,number=1),)
    print "Threaded: %0.2fs"%(timeit.timeit(TEST_THREADS,number=1),)
    print "Multiprocessing: %0.2fs"%(timeit.timeit(TEST_MULTIPROCESSING,number=1),)

rawDescription: Threading in Python takes longer time instead of making it faster?


code:
class Window(QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.scene = QGraphicsScene()

        item1 = Test_Box(QPointF(0, 0))
        item2 = Test_Box(QPointF(20, 20))
        item11 = Test_Box(QPointF(10, 5), item1)

        self.scene.addItem(item1)
        self.scene.addItem(item2)

        self.view = QGraphicsView(self.scene)

        self.listItems = QPushButton('list')
        self.listItems.clicked.connect(self.printItems)

        layout = QHBoxLayout()
        layout.addWidget(self.view)
        layout.addWidget(self.listItems)
        self.setLayout(layout)

    def printItems(self):
        for item in self.scene.items():
            print item, item.parentItem()

rawDescription: Removing a QGraphicsItem's parent

description: Removing a QGraphicsItem's parent


code:
from collections import defaultdict
A = [
    ('A', 5, 3),
    ('B', 6, 1),
    ('D', 10, 2),
    ('C', 2, 4),
]

B = [
    ('A', 5, 5),
    ('D', 2, 1),
    ('B', 5, 4),
]

# we need to calculate (value, quantity) for each label:
a = {key: [weight * quantity, quantity] for key, weight, quantity in A}
b = {key: [weight * quantity, quantity] for key, weight, quantity in B}

# defaultdict is a dictionary like structure, but able to create
# a new item if key is not found, in our case a new [0, 0] list:
merged = defaultdict(lambda: list((0, 0)))

# let's sum quantities and
for key, pair in a.items() + b.items():
    # add both value and quantity respectively
    quantity, value = map(sum, zip(merged[key], pair))
    merged[key] = [quantity, value]

# now let's calculate means
for key, (quantity, value) in merged.items():
    mean = quantity / float(value)
    merged[key] = [mean, value]

for item in merged.items():
    print item

rawDescription: Merge two tables based on intersection in Python


code:
dic= {}
x = raw_input('Enter line:')
if x.strip():
    p = x.split()
    for x in set(p):   #set(p) contains only unique elements of p
        dic[x]=p.count(x)
    print dic
else:
    print 'you entered nothing'

rawDescription: Cumulative numbers in python dictionaries


code:
import sys
import decimal

d = {
    "int": 0,
    "float": 0.0,
    "dict": dict(),
    "set": set(),
    "tuple": tuple(),
    "list": list(),
    "str": "a",
    "unicode": u"a",
    "decimal": decimal.Decimal(0),
    "object": object(),
}
for k, v in sorted(d.iteritems()):
    print k, sys.getsizeof(v)

rawDescription: In-memory size of a Python structure

description: In-memory size of a Python structure


code: print  ss.norm.cdf(4, 4, 2) - ss.norm.cdf(-100, 4, 2)

rawDescription: Generating a probability from a pdf?

description: Generating a probability from a pdf


code:
#!/usr/bin/python
#
# This program does a Google search for "quick and dirty" and returns
# 200 results.
#

from xgoogle.search import GoogleSearch, SearchError

class give_me(object):
    def __init__(self, query, target):
        self.gs = GoogleSearch(query)
        self.gs.results_per_page = 50
        self.current = 0
        self.target = target
        self.buf_list = []

    def __iter__(self):
        return self

    def next(self):
        if self.current >= self.target:
            raise StopIteration
        else:
            if(not self.buf_list):
                self.buf_list = self.gs.get_results()
            self.current += 1
            return self.buf_list.pop(0)

try:
    sites = {}
    for res in give_me("quick and dirty", 200):
        t_dict = \
        {
            "title" : res.title.encode('utf8'),
            "desc" : res.desc.encode('utf8'),
            "url" : res.url.encode('utf8')
        }
        sites[t_dict["url"]] = t_dict
    print t_dict
except SearchError, e:
    print "Search failed: %s" % e

rawDescription: Updated approach to Google search with python


code:
import sys
import math

class Percentage(float):
    _at_least = 2
    def __init__(self, val):
        self._x = val

    def __format__(self, s):
        #print 's [%s]' % (repr(s))
        at_least = Percentage._at_least
        try:
            at_least = int(s)
        except:
            pass
        return '{1:.{0}%}'.format(max(at_least, int(-math.log10(self._x))-1),
                                  self._x)

for x in (1., .1, .123456, .0123, .00123, .000123, .0000123, .00000123):
    p = Percentage(x)
    print '{0} {1:3} {2}'.format(x, p, 50 * p)

rawDescription: format string syntax: printing percentage with at least one significant digit

description: Format string syntax: printing percentage with at least one significant digit


rawDescription: Delete weird ANSI character and convert accented ones using Python


code:
while file_size > 0:
    work_file = server.recv(1024)
    f.write(work_file)
    file_size -= 1024
    print file_size

rawDescription: Python sending a file over sockets

description: Python sending a file over sockets


code:
for entry in entries:
     print sql + entry

rawDescription: printing a "for i in range" command

description: Printing a "for i in range" command


code:
import matplotlib.pyplot as plt

x = [1,2,4]
y = [1,3,2]

fig1 = plt.figure(figsize=(5,5),dpi=100)
ax = fig1.add_axes([0,0,1,1])

ax.scatter(x,y)

ax.set_xlim(0,5)
ax.set_ylim(0,5)
transDataToFig1 = ax.transData+fig1.transFigure.inverted()
for ix,iy in zip(x,y):
    inDots = ax.transData.transform((ix,iy))
    inFigIndirect = fig1.transFigure.inverted().transform(inDots)
    inFigDirect = transDataToFig1.transform((ix,iy))
    print inDots,"->",inFigIndirect," or ",inFigDirect

fig1.savefig('scatterPos1.png')

rawDescription: Matplotlib: Centroid of Scatter Plot Circles


code:
def test():
    "Time me"
    L = []
    for i in range(100):
        L.append(i)

if __name__=='__main__':
    from timeit import Timer
    t = Timer("test()", "from __main__ import test")
    print t.timeit()

rawDescription: Python question about time spent

description: Python question about time spent


code:
import urllib
import re

html = urllib.urlopen("http://jshawl.com/python-playground/").readlines()
for line in html :
    if "jesseshawl" in line:
        print re.sub("<[^>]*?>","",line)

rawDescription: re.findall printing the full text on a line of tekst

description: Re.findall printing the full text on a line of tekst


code:
import ConfigParser as configparser

parser = configparser.ConfigParser()
parser.read("sample.ini")

section_2 = dict(parser.items("Section2"))
print section_2["name3"]
print section_2["name4"]

rawDescription: Printing contents in particular section of configuration file in Python


code:
my_list = ["these", "should", "be", "separated", "by", "commas"]
print ",".join(my_list)

rawDescription: Combining objects in a list. Python

description: Combining objects in a list. Python


code:
sentences = ("The sun is shiny i like the sun","I have been exposed to sun")
vect = TfidfVectorizer(stop_words="english",lowercase=False)
mat = vect.fit_transform(sentences).toarray()
q = mat / vect.idf_
sums = np.ones((q.shape[0], 1))
lens = np.ones((q.shape[0], 1))
for ix in xrange(q.shape[0]):
    sums[ix] = np.sum(q[ix,:])
    lens[ix] = len([x for x in sentences[ix].split() if unicode(x) in vect.get_feature_names()]) #have to filter out stopwords
sum_to_1 = q / sums
tf = sum_to_1 * lens
print tf

rawDescription: How to get word count from TF*IDF value in sklearn

description: Get word count from TF*IDF value in sklearn


code:
class B (object):
    def b(self):
        return 1
b = lambda self: 42
print id(getattr(B, 'b'))
print id(b)
setattr(B, 'b', b)
print id(getattr(B, 'b'))
print id(getattr(B, 'b').im_func)  # grab function from the descriptor

4424060752
4440057568
4424060752
4440057568   # here's our new lambda

rawDescription: Why does setattr work differently for attributes and methods?


code:
def usewalk():
   for root, dirname, filenames in os.walk("."):
       for filename in filenames:
           print os.path.join(root, filename)

rawDescription: Initial Directory for os.walk()

description: Initial Directory for os.walk()


code:
# Two possible ways of storing your data: a list of tuples, or a list of dictionaries
entries_tuples = []
entries_dictionary = []

soup = BeautifulSoup(text)

div = soup.find('div', {'id': 'object-a'})
ul = div.find('ul', {'id': 'object-a-1'})

for li in ul.findAll('li'):
    title = li.find('a', {'class': 'title'})
    url_href = title.get('href')
    person = title.text
    url_word = li.find('p', {'class': 'url word'}).text
    emails = re.findall(r'\s+(\S+@\S+)(?:\s+|\Z)', li.findAll('p')[1].text, re.M)       # allow for multiple emails

    entries_tuples.append((url_href, person, url_word, emails))
    entries_dictionary.append({'url_href' : url_href, 'person' : person, 'url_word' : url_word, 'emails' : emails})

for url_href, person, url_word, emails in entries_tuples:
    print '{:25} {:10} {:25} {}'.format(url_href, person, url_word, emails)

print

for entry in entries_dictionary:
    print '{:25} {:10} {:25} {}'.format(entry['url_href'], entry['person'], entry['url_word'], entry['emails'])

rawDescription: BeautifulSoup filtering data from list elements on html pages