code:
matches = re.findall(r"(?<!see)(?<!under)\s+(section 7[\s.:-]+(?:deliver(?:ing)?).*?terminal\s+diagnosis(?:'s)?)", s, re.I)
print matches

rawDescription: Negative lookahead - exclude entire match if words are found?


code:
## Broken method definition: def _inputs_changed(self, old, new):
# container event static listeners must be in the form of _foo_items_changed()
def _inputs_items_changed(self, old, new):
    # static event listener for self.inputs
    if len(new.added) > 0:
        print "Check it out, we added %s to self.items" % new.added
    elif len(new.removed) > 0:
        print "Check it out, we removed %s from self.items" % new.removed

rawDescription: How can I fire a Traits static event notification on a List?

description: Fire a Traits static event notification on a List


code:
from lxml import etree

if __name__ == '__main__':
    print """Trying to create xml file like this:
        Hello
World"""

    html_node = etree.Element("html")
    body_node = etree.SubElement(html_node, "body")
    body_node.text = "Hello"

    print "Step1:" + etree.tostring(html_node)

    br_node = etree.SubElement(body_node, "br")
    print "Step2:" + etree.tostring(html_node)

    br_node.tail = "World"
    print "Step3:" + etree.tostring(html_node)

    br_node.text = "Yeah?"
    print "Step4:" + etree.tostring(html_node)

rawDescription: Why lxml.etree.SubElement(body, "br") will create <br />?


code:
from multiprocessing import Process
import nltk
import time

def child_fn():
    print "Fetch URL"
    import urllib2
    print urllib2.urlopen("https://www.google.com").read()[:100]
    print "Done"

while True:
    child_process = Process(target=child_fn)
    child_process.start()
    child_process.join()
    print "Child process returned"
    time.sleep(1)

rawDescription: Python child process silently crashes when issuing an HTTP request


rawDescription: Transform slow pandas iterrows into apply


code:
class Test(object):
    def __init__(self, test_value):
        self.test_value = test_value

    def test(self):
        print "The value I need is", self.test_value
        self._inner_test()

    def _inner_test():
        print "running test"

if __name__ == '__main__':
    args = get_args()
    t = TestClass(args.test_value)
    t.test()

rawDescription: how can I avoid using a global variable as a parameter to a python decorator

description: Avoid using a global variable as a parameter to a python decorator


code:
from mock import patch
import module

def some_function():
    instance = module.Foo()
    print instance.labels
    return instance.method()

some_function()

with patch('module.Foo') as mock:
    instance = mock.return_value
    instance.method.return_value = 'the result'
    instance.labels = [1,2,3,4,5]
    result = some_function()
    assert result == 'the result'

rawDescription: Python mock class instance variable

description: Python mock class instance variable


code:
l1 = []
l2 = object_from_id( id(l1) )
print l1 == l2
l1.append(9)
print l2

rawDescription: Is it possible to access an object via memory address?


code: print client

rawDescription: Soap Client using Suds

description: Soap Client using Suds


code:
#!/usr/bin/env python

i = 0
numbers = []

for j in xrange(6):
    print "At the top i is %d" % i
    numbers.append(i)

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

print "The numbers: "

for num in numbers:
    print num

rawDescription: Using For Loop In stead of While loop in Python


code:
class testclass:
    def __init__(self):
        print "new instance"
        self.myList = []

rawDescription: Puzzling scope behaviour

description: Puzzling scope behaviour


code:
def bar(arg, *args):
    print args

bar(1, 2, 3, 'a', 'b')

rawDescription: what does double star followed by variable name mean in python?

description: What does double star followed by variable name mean in python


code:
from collections import Counter
def counting(self):
    nucleotides = frozenset(('g', 'a', 't', 'c'))
    with open("BRCA1.txt", "r") as gene:
        nucleotide_counts = Counter(char for line in gene for char in line.lower() if char in nucleotides)
    for (nucleotide, count) in nucleotide_counts.most_common():
        print "number of %s's: %d" % (nucleotide, count)

rawDescription: Sorting values (for loop)

description: Sorting values (for loop)


code:
from collections import defaultdict
import re

stop_words = set(['a', 'is', 'and', 'the', 'i'])
text = [ 'This is the first line in my text'
       , 'and this one is the second line in my text'
       , 'I like texts with three lines, so I added that one'
       ]
word_line_dict = defaultdict(list)

for line_no, line in enumerate(text, 1):
    words = set(map(str.lower, re.split('\W+', line)))
    words_ok = words.difference(stop_words)
    for wok in words_ok:
        word_line_dict[wok].append(line_no)

print word_line_dict

rawDescription: Filtering textual data in Python

description: Filtering textual data in Python


code:
x = Counter(3,8)
for i in x:
    print x

rawDescription: Iterator (iter()) function in Python

description: Iterator (iter()) function in Python


code:
H=set()
ans=0
for a in A:
  H.add(a)
for a in A:
  if a-k in H:
    ans+=1
print ans

rawDescription: Fastest algorithm possible to pick number pairs


code:
from itertools import tee, izip_longest
in1, in2 = tee(sys.stdin, 2)
next(in2)
for line, prevline in izip_longest(in1, in2, fillvalue=''):
    if line.startswith('---(more') or prevline.startswith('---(more'):
        continue
    print line

rawDescription: What's an elegant way for one loop iteration to affect another?


code:
bs1 = BeautifulSoup("sometext")
bs1.find('a').string
bs2 = BeautifulSoup("sometext")
bs2.find('a').string
print bs2.find('a').string

rawDescription: Beautifulsoup find element by text using `find_all` no matter if there are elements in it


code:
for sentence in data:
    print ' '.join(sentence.split())

rawDescription: remove blank lines & extra space within lists - python

description: Remove blank lines & extra space within lists - python


code:
import sys
for l in sys.stdin:
    print l

rawDescription: How do I create a python subprocess using a file for stdin starting at a certain line?

description: Create a python subprocess using a file for stdin starting at a certain line


code:
import xml.etree.ElementTree as ET
tree = ET.parse("people.xml")
top = tree.getroot()

for target in top:
     for x in target:
         if x.tag == 'name': print x.text

rawDescription: Python elementree having hard time extracting data


code:
class MyLineEdit(QtGui.QLineEdit):

    def __init__(self, parent):

        super(MyLineEdit, self).__init__(parent)
        self.parentWindow = parent

    def mousePressEvent(self, event):
        print 'forwarding to the main window'
        self.parentWindow.mousePressEvent(event)

rawDescription: Add a click on QLineEdit

description: Add a click on QLineEdit


code:
import json

d = json.loads(r.content)

print d['date']
03-28-2015

type(d)
dict

rawDescription: How to pull information from a Json

description: Pull information from a Json


code:
from datetime import timedelta

delta = timedelta(hours=3457)
print delta

rawDescription: Python convert timedeltas into hours in string format


code:
from itertools import chain

cur1 = con.cursor()
cur1.execute('select something from table1') #1st select
cur2 = con.cursor()
cur2.execute('select something_else from table2') #2nd select

for row in chain(cur1, cur2):
    print row

rawDescription: How print two different select results

description: How print two different select results


code:
seen = set()
dnf = list(itertools.product(*filters))

for item in data:
    keys = set(
        tuple((field, item.get(field, None)) for field in conjunct)
        for conjunct in dnf)
    if keys.isdisjoint(seen):
        seen |= keys
        print item # unique

rawDescription: Comparing dictionaries based on a combination of keys


code:
import numpy
import cairo
import math
data = numpy.zeros((200, 200, 4), dtype=numpy.uint8)
surface = cairo.ImageSurface.create_for_data(
    data, cairo.FORMAT_ARGB32, 200, 200)
cr = cairo.Context(surface)

# fill with solid white
cr.set_source_rgb(1.0, 1.0, 1.0)
cr.paint()

# draw red circle
cr.arc(100, 100, 80, 0, 2*math.pi)
cr.set_line_width(3)
cr.set_source_rgb(1.0, 0.0, 0.0)
cr.stroke()

# write output
print data[38:48, 38:48, 0]
surface.write_to_png("circle.png")

rawDescription: How to write simple geometric shapes into numpy arrays

description: Write simple geometric shapes into numpy arrays


code:
def foo(lst):
    d = {}
    for (k,v) in lst: d[k] = d.get(k,0) + v     # Accumulate
    return max(d.items(), key=lambda x:x[1])[0] # Find max value, return corresponding key

print foo([(1,200),(1,50),(2,275)])             # 2
print foo([(1,100),(2,50),(2,300),(1,1000)])    # 1

rawDescription: Python, in a list of (a,b) pairs find the a value with the largest sum(b values)


code:
df = DataFrame({'event': range(1,4), 'unixtime': [1346617885925, 1346961625305,1347214217566]})
df['day'] = df['unixtime'].apply(lambda x: datetime.fromtimestamp(x/1000).date())
df['arbday']=df['day'].map(lambda x: (x-df.get_value(df[df.event == 1].first_valid_index(), 'day')).days+1)
print df

rawDescription: Compute the nth day from the first event in Pandas


rawDescription: How to copy last X bits?

description: Copy last X bits


code:
def a(name):
    global_variables = globals()
    try:
        name_of_passed_in_variable = [x for x in global_variables if id(global_variables[x]) == id(name)][0]
    except Exception:
        name_of_passed_in_variable = "unknown"
    print name_of_passed_in_variable, name

my_name = "Tom"
a(my_name)

a("Mike")

second_name = my_name
a(second_name)

rawDescription: Actual name of the passed parameter

description: Actual name of the passed parameter


code:
def run():
    print "Everything is ok for now"

rawDescription: is it possible to use import after sys.exit(1)?

description: Is it possible to use import after sys.exit(1)


code: print "I'm global!"

rawDescription: Is it bad to name a Python module "global" or other keyword?


code:
import json, string

def to_json(file):
    data = {}
    for line in open(file):
        fields = map(string.strip, line.split(','))
        categories = data.get(fields[1], {})
        tags = categories.get(fields[2], [])
        tags.append(fields[0])
        categories[fields[2]] = tags
        data[fields[1]] = categories
    return json.dumps(data)

print to_json('data.csv')

rawDescription: How to turn a dataframe of categorical data into a dictionary

description: Turn a dataframe of categorical data into a dictionary


rawDescription: How to create a date range until some date inclusive with python dateutils?

description: Create a date range until some date inclusive with python dateutils


code:
import sys
print sys.stdout.isatty()

rawDescription: Fool python's os.isatty from a bash script


code:
message = ['ffjffjf', 'ddjbgg']
splitmessage = []
for myString in message:
    splitmessage.append(myString[:2])
print splitmessage

rawDescription: How to take the first two letters of a variable in python?

description: Take the first two letters of a variable in python


code:
from StringIO import StringIO as sIO
class DelimitedStringIO(sIO):
    def __init__(self, initial, *args, **kwargs):
            sIO.__init__(self, *args, **kwargs)
            self.write(initial)
    def conc(self, value, delim=" "):
            self.write(delim)
            self.write(value)
    def __str__(self):
            return self.getvalue()
x = DelimitedStringIO("Hello")
x.conc("Alice")
x.conc("Bob", delim=", ")
x.conc("Charlie", delim=", and ")
print x

rawDescription: Modify subclassed string in place

description: Modify subclassed string in place


code:
#! /usr/bin/env python

import sys
import readline

def main():
    count = 1
    while True:
        try:
            line = raw_input()
            print "%3d: [%s]" % (count, line)
            count += 1
        except EOFError:
            break

if __name__ == '__main__':
    main()

rawDescription: Reading from stdin in Python 2.7.6. Sys.stdout.flush() and python -u doesn't work


code:
from PySide import QtCore, QtGui

def Function(arg=None):
    print 'Function.arg: %r'%arg

class button(QtGui.QPushButton):
    def __init__(self, parent=None):
        super(button, self).__init__(parent)
        self.clicked.connect(self.click)
        self.show()

    def click(self):
        self.emit(QtCore.SIGNAL('customSignal'), 'String Arument')

btn = button()

class label(QtGui.QLabel):
    def __init__(self, parent=None):
        super(label, self).__init__(parent)
        self.connect(btn, QtCore.SIGNAL('customSignal'), Function)
        self.show()

lbl = label()

rawDescription: Signals And Slots: When simple example is not working


code: print ''.join([chr(random.randint(32,126)) for _ in xrange(11)])

rawDescription: More efficient for loops in Python (single line?)


code:
data = [['Day','Date','Week'], ['Day','Date','Week'], ['Day','Date','Week']]
print [item[0] for item in data]

rawDescription: Is it possible to display only first list element in for loop?


code: print int("1") + 1

rawDescription: How to convert strings into integers in python?

description: Convert strings into integers in python


code:
import bar

class Data(object):
    def __init__(self):
        self.val = bar.get_data()

if __name__ == '__main__':
    d = Data()
    print d.val    # prints 'bar'

rawDescription: in python, how to manipulate namespace of an instance

description: In python, how to manipulate namespace of an instance


rawDescription: Need help in splitting a fixed-width string with unprintable characters


code:
from collections import Counter

truth      = [1, 2, 1, 2, 1, 1, 1, 2, 1, 3, 4, 1]
prediction = [1, 1, 2, 1, 1, 2, 1, 2, 1, 4, 4, 3]

confusion_matrix = Counter()

#say class 1, 3 are true; all other classes are false
positives = [1, 3]

binary_truth = [x in positives for x in truth]
binary_prediction = [x in positives for x in prediction]
print binary_truth
print binary_prediction

for t, p in zip(binary_truth, binary_prediction):
    confusion_matrix[t,p] += 1

print "TP: {} TN: {} FP: {} FN: {}".format(confusion_matrix[True,True], confusion_matrix[False,False], confusion_matrix[False,True], confusion_matrix[True,False])

rawDescription: How to find true positives, true negatives, false positives, false negatives in Python

description: Find true positives, true negatives, false positives, false negatives in Python


code: print new_dictionary['sequence_3']

rawDescription: Assigning a string from a .txt file into a variable


code:
print [key
          for people in peoples
          for key, value in people.items()
          if value == criteria]

rawDescription: How do I iterate over a dictionary and return the key in Python?

description: Iterate over a dictionary and return the key in Python


code:
bytestring = "vTest\r"
bits = chr(0x7f) + bytestring
checksum = reduce(lambda x,y:chr((ord(x)^ord(y))&0xff),bits)
message = bytestring+checksum
print map(lambda x:hex(ord(x)),message)
#Result:['0x76', '0x54', '0x65', '0x73', '0x74', '0xd', '0x32']
# ser.write(message)

rawDescription: Python XOR on hex and string (parity check function)


code:
build_dep_list = []
for item in mainlist:
    build_dep_list.append(item)
    internal_dep_list = getinternaldep(item)
    external_dep_list = getexternaldep(item)
    build_dep_list.extend(internal_dep_list)
    build_dep_list.extend(external_dep_list)
print build_dep_list

rawDescription: Recursive algorithm for generating a acyclic directed graph


code:
def conjunction(i,j): # conjunction i,j
    return (i and j)

def disjunction(i,j): # dis-junction i,j
    return (i or j)

def exclusive(i,j): # exclusive i,j
    return (i != j)

def conditional(i,j): # conditional i,j
    return j if i else True

def biconditional (i,j): # biconditional i,j
    return (i == j)

output = [[],[],[],[],[]]
titles = ["Conjunction", "Disjunction", "Exclusive", "Conditional", "Biconditional"]

for f1 in [True, False]:
    for f2 in [True, False]:
        output[0].append('{0:8s} | {1:8s} | {2:8s}'.format(str(f1), str(f2), str(conjunction(f1, f2))))
        output[1].append('{0:8s} | {1:8s} | {2:8s}'.format(str(f1), str(f2), str(disjunction(f1, f2))))
        output[2].append('{0:8s} | {1:8s} | {2:8s}'.format(str(f1), str(f2), str(exclusive(f1, f2))))
        output[3].append('{0:8s} | {1:8s} | {2:8s}'.format(str(f1), str(f2), str(conditional(f1, f2))))
        output[4].append('{0:8s} | {1:8s} | {2:8s}'.format(str(f1), str(f2), str(biconditional(f1, f2))))

for i in range(5):
    print "=" * 30
    print titles[i]
    print "-" * 30
    print "\n".join(output[i])
    print "-" * 30

rawDescription: results of two propositions using python

description: Results of two propositions using python


code:
url = 'http://www.zillow.com/homedetails/3728-Balcary-Bay-Champaign-IL-61822/89057727_zpid/'
page = urllib2.urlopen(url)
soup = BeautifulSoup(page)

info = soup.findAll('span',{'itemtype':'http://schema.org/GeoCoordinates'}) #this tag + class combination found 4 matches, 4th one was the required one, just selecting that here
cordinates = [i['content'] for i in info[0].find_all('meta')]

print cordinates

rawDescription: Issue with parsing HTML class elements using beautifulsoup


code:
import numpy

def f(x, a1, a2, a3, a4):
    return a1 + a2*x + a3*x**2 + a4*x**3

data_x = numpy.arange(50)
errors = numpy.random.randn(50) * 0.3
data_y = data_x**3 + errors

chi_squared = make_chi_squared(f, data_x, data_y, errors)
print inspect.getargspec(chi_squared).args

rawDescription: How to define a chi2 value function for arbitrary function?

description: Define a chi2 value function for arbitrary function


code:
import copy
myarray = range(4)
for k, v in iter(copy.copy(locals()).items()):
    if myarray == v:
        print k

rawDescription: Export function that names the export file after the input variable


code:
import requests
site = raw_input("\nEnter the site from which you want to receive data \n\n -> ")
r = requests.get(site, allow_redirects=True)
print r.headers
print r.content

rawDescription: web client in python not working

description: Web client in python not working


code:
import json
import pprint
import sys

import requests

def main(url):
  print 'Reading from {}'.format(url)
  for line in requests.get(url, stream=True).iter_lines(chunk_size=1):
    pprint.pprint(json.loads(line))
  print 'All done.'

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

rawDescription: Imitating Twitter's Streaming API

description: Imitating Twitter's Streaming API


code:
def signal_distance(lat1,lng1,lat2,lng2):
    import simplejson, urllib
    orig_coord = lat1,lng1
    dest_coord =  lat2,lng2
    orig_coord_str = ' ,'.join(map(str, orig_coord))
    dest_coord_str = ' ,'.join(map(str, dest_coord))
    #API request
    url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins={0}&destinations={1}&mode=transit&language=zh-TW&key=AIzaSyBlwZDhGYNTrxXiQblz20v3poJTA7zTVho".format(orig_coord_str,dest_coord_str)
    result = simplejson.load(urllib.urlopen(url))
    print result

rawDescription: why python code for google maps api can not work suddenly

description: Why python code for google maps api can not work suddenly


code:
def reassemble(list_name):
    def inner_iter(head, tail):
        if head[0][0] == '{':
            new_head = [head[0] + ',' + tail[0]]
            if tail[0][-1] == '}':
                return [new_head[0][1:-1]], tail[1:]
            else:
                return inner_iter(new_head, tail[1:])
                #before the change, control reached here upon return
        #control might still reach here, in case 'if' condition was not met
        #implicitly "return None"

    def outer_iter(corrected_list, head, tail):
        if tail == []:
            print corrected_list + head
            return corrected_list + head
        else:
            if head[0][0] == '{':
                head, tail = inner_iter(head, tail)
                return outer_iter(corrected_list + head, [tail[0]], tail[1:])
                #before the change, control reached here upon return
            else:
                return outer_iter(corrected_list + head, [tail[0]], tail[1:])
                #before the change, control reached here upon return
        #before the change, control reached here upon return
        #implicitly "return None"

    return outer_iter([], [list_name[0]], list_name[1:])

rawDescription: Functional programming in Python: returning none instead of correct value


code:
#!/usr/bin/python

import networkx as nx
import random

g = nx.Graph()
g.add_edges_from([(1,2),(2,3),(1,4),(2,5)])

random_edge = random.choice(g.edges())

print 'Randomly selected edge is:', random_edge
print 'Nodes are', random_edge[0], 'and', random_edge[1]

rawDescription: How do I get nodes from the specific edge in the networkx?

description: Get nodes from the specific edge in the networkx


code:
print detect_language_v2(
    ["Python - can I detect unicode string language code?",
     u"матрёшка",
     u"打水"], api_key=open('api_key.txt').read().strip())


code:
from sklearn.datasets import load_files
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
import numpy as np
import scipy

# Load the text data

twenty_train_subset = load_files('datasets/20news-bydate-train/',
    categories=categories, encoding='latin-1')

# Turn the text documents into vectors of word frequencies
vectorizer = TfidfVectorizer(min_df=2)
X_train_only_text_features = vectorizer.fit_transform(twenty_train_subset.data)

print type(X_train_only_text_features)
print "X_train_only_text_features",X_train_only_text_features.shape

size = X_train_only_text_features.shape[0]
print "size",size

ones_column = np.ones(size).reshape(size,1)
print "ones_column",ones_column.shape

new_column = scipy.sparse.csr.csr_matrix(ones_column )
print type(new_column)
print "new_column",new_column.shape

X_train= scipy.sparse.hstack([new_column,X_train_only_text_features])

print "X_train",X_train.shape

rawDescription: Sklearn other inputs in addition to text for text classification


code:
from datetime import date, datetime, time, timedelta

dt = datetime.combine(date.today(), time(23, 55)) + timedelta(minutes=30)
print dt.time()

rawDescription: python time + timedelta equivalent

description: Python time + timedelta equivalent


code:
class Watcher(object):
    def __init__(self, to_watch):
        self.to_watch = to_watch

    def print_current_value(self):
        print self.to_watch

i = 0
watcher = Watcher(i)
watcher.print_current_value()
# prints 0
i += 3
watcher.print_current_value()
# still prints 0

l = [0]
watcher = Watcher(l)
watcher.print_current_value()
# prints [0]
l[0] += 3
watcher.print_current_value()
# prints [3]

rawDescription: Watching a variable in python?

description: Watching a variable in python


code:
import Tkinter as tk

def test(event, extra=None):
    print extra

master = tk.Tk()

b1 = tk.Button(master, text="QUIT", command=master.destroy, width=20, heigh=5)
b1.pack()

b2 = tk.Label(master, text="OK", width=20, heigh=5)
b2.pack()

b2.bind('<Double-Button-1>', lambda event:test(event,101))

b2.bind('<Button-1>', lambda event:test(event,1))
b2.bind('<Button-2>', lambda event:test(event,2))
b2.bind('<Button-3>', lambda event:test(event,3))

master.mainloop()

rawDescription: How would one bind two different button click events to the same label, namely "<Button-1>" and "<Double-Button1>" to same label?


code:
class Person(object):
  def __init__(self,name,age,weight,height):
      self.name = name
      self.age = age
      self.weight = float(weight)
      self.height = float(height)
  def get_bmi_result(self):
      bmi = (self.weight)/float((self.height*30.48)*(self.height*30.48))
      print bmi
      if bmi <= 18.5:
        return "underweight"
      elif bmi>18.5 and bmi<25:
           return "normal"
      elif bmi>30:
           return "obese"

p = Person("hari", "25", "6", "30")
p.get_bmi_result()

rawDescription: Error in BMI caluclator

description: Error in BMI caluclator


code: print eval("[('tupleValueA', 1), 'someString']")

rawDescription: Is there a high-level way to read in lines from an output file and have the types recognized by the structure of the contents?


code:
import lxml.etree as etree
document = etree.parse(open("your.xml"))

secondIdentifier = document.xpath(".//product/identifier[2]")[0]
firstContributor = document.xpath(".//product/contributor[1]")[0]
print secondIdentifier, firstContributor

rawDescription: Targeting specific sub-elements when parsing XML with Python


code:
import urllib2
from bs4 import BeautifulSoup

url = "https://www.google.com.hk/finance?q=0001&ei=yF14VYC4F4Wd0ASb64CoCw"

def WebCrawl(url):
    htmltext = urllib2.urlopen(url).read()
    soup = BeautifulSoup(htmltext)
    p = soup.find("span", attrs={"id": "ref_164573760542896_l"}).text
    print p

WebCrawl(url)

rawDescription: How can I use beautiful soup to get the current price of a stock on Google Finance?

description: Use beautiful soup to get the current price of a stock on Google Finance


code:
from numpy import array, dtype
from h5py import File
from operator import itemgetter

# Dummy data

d = dtype([('a', int),('b', int),('c', int)])
a = array([(1, 6, 4), (5, 7, 1), (9, 7, 8), (3, 1, 2), (2, 1, 6)],dtype=d)

hdf = File('tmp.hdf','a')
hdf.create_dataset('data',data=a)
hdf.flush()

# Extract data

dat = hdf.get('data',default=0)

sub = ['a','c']
get = itemgetter(*sub)

print get(dat)

rawDescription: What is the most elegant way of selecting a subset of columns using pytables?


code:
import os

def listdirs(suffix):
    for dirname, dirnames, filenames in os.walk('.'):
        for subdirname in dirnames:
            subdirpath = os.path.join(dirname, subdirname)
            if subdirpath.endswith(suffix):
                yield subdirpath

if __name__ == "__main__":
    for d in listdirs('inputs'):
        print d

rawDescription: Python subfolder listings

description: Python subfolder listings


code:
sqr = (i**2 for i in xrange(10)) # <generator object <genexpr> at 0x1196acfa0>
list(sqr) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

sqr = (i**2 for i in xrange(10))
for x in sqr:
    print x,
# 0 1 4 9 16 25 36 49 64 81

rawDescription: How to convert generator object into list?

description: Convert generator object into list


code:
class Test:
    def _pub_wrapper(self, verb, obj_type, id_list):
        print "  Called _pub_wrapper(" , verb, ", ", obj_type, ", ", id_list, ")"
        ids = [str(i) for i in id_list]
        self._pub(ids, '{0}.{1}'.format(verb,
                                        obj_type.lower()))

    def _pub(self, ids, something):
        print "    Called _pub( ", self, ", ", ids, ", ", something, ")"

    def __getattr__(self, item):
        verb = item.split('_')[0]
        obj_type = item.split('_')[-1]
        if verb in ['new', 'changed', 'deleted'] and \
           obj_type in ['resources', 'items', 'banks']:

            def wrapper(*args, **kwargs):
                print "Within wrapper: verb=", verb, ", obj_type=", obj_type, ", args=",  args, ", kwargs=", kwargs
                print "Within wrapper: ", verb, ", ", obj_type, ", ",  args
                return self._pub_wrapper(verb, obj_type, args[0])
            return wrapper
        raise AttributeError

    """
    def __getattr__(self, item):
        if item in ['new_resources', 'changed_resources', 'deleted_resources', 'changed_banks']:
            verb = item.split('_')[0]
            obj_type = item.split('_')[-1]
            print verb, " vs ", obj_type
            def wrapper(*args):
                print "Within wrapper: ", verb, ", ", obj_type, ", ",  args[0]
                return self._pub_wrapper(verb, obj_type, args[0])
            return wrapper
        raise AttributeError
    """

    def fake_new_resources(self, id_list):
        self._pub_wrapper('new', 'resources', id_list)

t = Test()
print "Faking it... "
t.fake_new_resources([])

print "New tries"
t.new_resources([])
t.changed_banks([])
t.deleted_items(["hi", "bye"], 4, your=23, mine=42)

rawDescription: Writing a generic getattr() and populate method parameters based on attr name


code:
# import sqlite3
from PyQt4 import QtCore, QtGui

# conn = sqlite3.connect('Contacts')
# c = conn.cursor()

# def tableCreate():
#     c.execute('CREATE TABLE ContactInfo(Name TEXT, Age INT, MobilePhone TEXT, Address TEXT)')

# name = ""
# age = int()
# mobilenum = ""
# Adr = ""

# def dataEntry():
#     c.execute('INSERT INTO CustomerInfo (Name, Age, MobilePhone, Address) VALUES (?,?,?,?)',
#         (Name, Age, MobilePhone, Adr))
#     conn.commit()

# GUI Code ------------------------------------------------------------

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_ContactCreator(object):
    def setupCreateContactUi(self, ContactCreator):
        ContactCreator.setObjectName(_fromUtf8("ContactCreator"))
        ContactCreator.resize(484, 165)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("CClogo.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        ContactCreator.setWindowIcon(icon)
        name = ""
        age = int()
        mobilenum = ""
        address = ""
        self.addcontactBut = QtGui.QPushButton(ContactCreator)
        self.addcontactBut.setGeometry(QtCore.QRect(190, 100, 101, 23))
        self.addcontactBut.setObjectName(_fromUtf8("addcontact"))
        self.addcontactBut.clicked.connect(self.addContact)

        self.nameLe = QtGui.QLineEdit(ContactCreator)
        self.nameLe.setGeometry(QtCore.QRect(10, 60, 171, 20))
        self.nameLe.setAutoFillBackground(False)
        self.nameLe.setObjectName(_fromUtf8("name"))

        self.ageLe = QtGui.QLineEdit(ContactCreator)
        self.ageLe.setGeometry(QtCore.QRect(190, 60, 41, 20))
        self.ageLe.setObjectName(_fromUtf8("age"))
        self.ageLe.setText("")

        self.mobphoLe = QtGui.QLineEdit(ContactCreator)
        self.mobphoLe.setGeometry(QtCore.QRect(240, 60, 113, 20))
        self.mobphoLe.setObjectName(_fromUtf8("mobilephone"))

        self.adrLe = QtGui.QLineEdit(ContactCreator)
        self.adrLe.setGeometry(QtCore.QRect(360, 60, 113, 20))
        self.adrLe.setObjectName(_fromUtf8("address"))

        self.label = QtGui.QLabel(ContactCreator)
        self.label.setGeometry(QtCore.QRect(90, 40, 31, 20))
        self.label.setObjectName(_fromUtf8("label"))

        self.label_2 = QtGui.QLabel(ContactCreator)
        self.label_2.setGeometry(QtCore.QRect(200, 40, 21, 20))
        self.label_2.setObjectName(_fromUtf8("label_2"))

        self.label_3 = QtGui.QLabel(ContactCreator)
        self.label_3.setGeometry(QtCore.QRect(260, 40, 81, 20))
        self.label_3.setObjectName(_fromUtf8("label_3"))

        self.label_4 = QtGui.QLabel(ContactCreator)
        self.label_4.setGeometry(QtCore.QRect(370, 40, 101, 20))
        self.label_4.setObjectName(_fromUtf8("label_4"))
        self.retranslateUi(ContactCreator)
        QtCore.QMetaObject.connectSlotsByName(ContactCreator)

    def addContact(self):
        self.name = str(self.nameLe.text())
        print self.name

    def retranslateUi(self, ContactCreator):
        ContactCreator.setWindowTitle(_translate("ContactCreator", "ContactCreator", None))
        self.addcontactBut.setText(_translate("ContactCreator", "Add New Contact", None))
        self.label.setText(_translate("ContactCreator", "Name", None))
        self.label_2.setText(_translate("ContactCreator", "Age", None))
        self.label_3.setText(_translate("ContactCreator", "  Mobile Phone", None))
        self.label_4.setText(_translate("ContactCreator", "      Address", None))

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    ContactCreator = QtGui.QWidget()
    ui = Ui_ContactCreator()
    ui.setupCreateContactUi(ContactCreator)
    ContactCreator.show()
    sys.exit(app.exec_())

rawDescription: How do I get the input from a PyQt linedit object?

description: Get the input from a PyQt linedit object


code:
from nltk.chunk import *
from nltk.chunk.util import *
from nltk.chunk.regexp import *
from nltk import Tree
from nltk.tag import pos_tag

# Let's say we give it a rule that says anything with a [DT NN] is an NP
chunk_rule = ChunkRule("<DT>?<NN.*>", "DT+NN* or NN* chunk")
chunk_parser = RegexpChunkParser([chunk_rule], chunk_node='NP')

# Let's say our test sentence is:
# "The cat sat on the mat the big dog chewed."
gold = tagstr2tree("[ The/DT cat/NN ] sat/VBD on/IN [ the/DT mat/NN ] [ the/DT big/JJ dog/NN ] chewed/VBD ./.")

# We POS tag the sentence and then chunk with our rule-based chunker.
test = pos_tag('The cat sat on the mat the big dog chewed .'.split())
chunked = chunk_parser.parse(test)

# Then we calculate the score.
chunkscore = ChunkScore()
chunkscore.score(gold, chunked)
chunkscore._updateMeasures()

# Our rule-based chunker says these are chunks.
chunkscore.guessed()

# Total number of tokens from test sentence. i.e.
# The/DT , cat/NN , on/IN , sat/VBD, the/DT , mat/NN ,
# the/DT , big/JJ , dog/NN , chewed/VBD , ./.
total = chunkscore._tags_total
# Number of tokens that are guessed correctly, i.e.
# The/DT , cat/NN , on/IN , the/DT , mat/NN , chewed/VBD , ./.
correct = chunkscore._tags_correct
print "Is correct/total == accuracy ?", chunkscore.accuracy() == (correct/total)
print correct, '/', total, '=', chunkscore.accuracy()
print "##############"

print "Correct chunk(s):" # i.e. True Positive.
correct_chunks = set(chunkscore.correct()).intersection(set(chunkscore.guessed()))
##print correct_chunks
print "Number of correct chunks = tp = ", len(correct_chunks)
assert len(correct_chunks) == chunkscore._tp_num
print

print "Missed chunk(s):" # i.e. False Negative.
##print chunkscore.missed()
print "Number of missed chunks = fn = ", len(chunkscore.missed())
assert len(chunkscore.missed()) == chunkscore._fn_num
print

print "Wrongly guessed chunk(s):" # i.e. False positive.
wrong_chunks = set(chunkscore.guessed()).difference(set(chunkscore.correct()))
##print wrong_chunks
print "Number of wrong chunks = fp =", len(wrong_chunks)
print chunkscore._fp_num
assert len(wrong_chunks) == chunkscore._fp_num
print

print "Recall = ", "tp/fn+tp =", len(correct_chunks), '/', len(correct_chunks)+len(chunkscore.missed()),'=', chunkscore.recall()

print "Precision =", "tp/fp+tp =", len(correct_chunks), '/', len(correct_chunks)+len(wrong_chunks), '=', chunkscore.precision()

rawDescription: IOB Accuracy on NLTK named entity recognition


code:
a = a.lower()
b = b.lower()
print a.endswith(b) or b.endswith(a)

rawDescription: Python - boolean matter

description: Python - boolean matter


rawDescription: Remove one column for a numpy array

description: Remove one column for a numpy array


code:
import xml.etree.ElementTree as ET
import sys

name = str.strip(sys.argv[1])
filename = str.strip(sys.argv[2])

fp = open("sample.xml","r")
tree = ET.parse(fp)
root = tree.getroot()

for offers in root.findall('.//{http://url}Offers'):
    value_found = False
    for amount in offers.findall('.//{http://url}Amount'):
        if amount.text == name:
            value_found = True
            break
    if value_found:
        print ET.tostring(offers)

rawDescription: Python extract nodes containing tag using ElementTree


code:
from lxml import etree

xml_string = """
<response method="switchvox.currentCalls.getList">
    <result>
            <current_calls total_items="3">
                            <current_call id="SIP/6525-b59313c8" from_caller_id_name="user1" from_caller_id_number="user1_ext" to_caller_id_name="callee1" to_caller_id_number="callee1_num"  start_time="2011-06-30 15:44:17" duration="346" state="talking" provider="Internal" format="g722->g722" />
                            <current_call id="SIP/4476-b595a0a0" from_caller_id_name="user2" from_caller_id_number="user1_ext" to_caller_id_name="callee2" to_caller_id_number="callee2_num"  start_time="2011-06-30 15:48:44" duration="79" state="talking" provider="VCG_B" format="g722->ulaw" />
                            <current_call id="SIP/4483-0aa41320" from_caller_id_name="user3" from_caller_id_number="user1_ext" to_caller_id_name="callee3" to_caller_id_number="callee3_num"  start_time="2011-06-30 15:47:54" duration="129" state="talking" provider="VCG_B" format="g722->ulaw" />
            </current_calls>
    </result>
</response>
"""

tree = etree.fromstring(xml_string)

for call in tree.xpath('.//current_call'):
    print call.attrib

rawDescription: Parse XML using lxml

description: Parse XML using lxml


code:
result = []
for x, y in zip(df.one, df.two):
    if x in y.split():
        result.append(True)
        continue
    result.append(False)

print df[result]

rawDescription: With pandas: if, in a row, a word in a column does not occur in string in other column, drop row


code:
for date, data in a.iteritems():
    print date,
    for key, value in data.iteritems():
        print '{}={}'.format(key, value),
    print

rawDescription: how to enumerate OrderedDict in python

description: Enumerate OrderedDict in python


code:
import re
with open(file) as f:
    fil = f.read()
    print re.sub(r'\n(?!\d{4}-\d{2}-\d{2}T\d)', '', s)

rawDescription: python fix multi line log entries

description: Python fix multi line log entries


code:
#!/usr/bin/env python
from contextlib import contextmanager
from StringIO import StringIO
################################################################################
class FakeFile(StringIO):
    def __init__(self):
        StringIO.__init__(self)
        self.count = 0

    def read(self, n=-1):
        return "<empty#1>"

    def readlines(self, sizehint = 0):
        return ["<empty#2>"]

    def next(self):
        if self.count == 0:
            self.count += 1
            return "<empty#3>"
        else:
            raise StopIteration
################################################################################
@contextmanager
def monkey_patched_open():
    global open
    old_open = open

    def new_fake_open(filename, mode="r"):
        try:
            fh = old_open(filename, mode)
        except IOError:
            fh = FakeFile()
        return fh

    open = new_fake_open

    try:
        yield
    finally:
        open = old_open

################################################################################
with monkey_patched_open():
    for line in open("NOSUCHFILE"):
        print "NOSUCHFILE->", line
    print "Other", open("MISSING").read()
    print "OK", open(__file__).read()[:30]

rawDescription: Best way to read file contents of a file and set to empty string if exception happen

description: Read file contents of a file and set to empty string if exception happen


code: print raw_input('?')

rawDescription: Difference between python script output and python console output


code:
import string
exclude = set(string.punctuation +  "\n\t\r")
print ''.join(ch for ch in input_string if ch not in exclude)

rawDescription: reformat unstructured text into single line after removing punctuation

description: Reformat unstructured text into single line after removing punctuation


code:
#create a new function named 'test' in the current (mod2) namespace
#the first time this module is imported.  Note that this function has
#access to the entire namespace where it is defined (mod2).
def test(name):
    print 'loading...'
    countLines(name)
    countChars(name)
    print '-'*10

rawDescription: Some confusion regarding imports in Python


code:
# Imports #
import statsmodels.api as smapi
import statsmodels.graphics as smgraphics
# Make data #
x = range(30)
y = [y*10 for y in x]
# Add outlier #
x.insert(6,15)
y.insert(6,220)
# Make graph #
regression = smapi.OLS(x, y).fit()
figure = smgraphics.regressionplots.plot_fit(regression, 0)
# Find outliers #
test = regression.outlier_test()
outliers = ((x[i],y[i]) for i,t in enumerate(test) if t[2] < 0.5)
print 'Outliers: ', list(outliers)

rawDescription: Can scipy.stats identify and mask obvious outliers?


code:
import maya.cmds as cmds

cmds.polyCube( n="myCube")
print cmds.listAttr( "myCube" )

rawDescription: PYTHON in MAYA: get all attributes

description: PYTHON in MAYA: get all attributes


code:
#!/usr/bin/python

import sys
import os
import zipfile
import StringIO
import zipimport
import time

sys.path.append('/tmp')

class SinEater(object):
    def __init__(self):
        tmp = str(int(time.time()*100)) + '.zip'
        f = open(tmp, 'w')
        f.write(sys.stdin.read(1024*64)) # 64kb limit
        f.close()
        try:
            z = zipimport.zipimporter(tmp)
            z.load_module('foo')

        except:
            pass

if __name__ == '__main__':
    print 'herp derp'
    s = SinEater()

rawDescription: why can't python execute a zip archive passed via stdin?

description: Why can't python execute a zip archive passed via stdin


code:
result = []
for k, g in groupby(enumerate(cycles), lambda (i,x):i-x):
    result.append(map(itemgetter(1), g))

print result

rawDescription: Adding data to an array instead of print?


code:
good = 0
bad = 0
for row_number, row in group.iterrows():
    if row['Quality'] == 'usefulness-useful':
        good += 1
    else:
        bad += 1
print 'good', good, 'bad', bad

rawDescription: How to perform functions over groupby results in pandas in python?

description: Perform functions over groupby results in pandas in python


code:
from bs4 import BeautifulSoup

data = """

Date

    2008

"""

soup = BeautifulSoup(data)
date_field = soup.find('div', class_='detail_date').find('dt', text='Date')
print date_field.find_next_sibling('dd').text.strip()

rawDescription: Use BeautifulSoup to get a value after a specific tag


code:
foo = []

def f(arg):
  arg.append(1)
  arg.append(2)

f(foo)
print foo # output: [1, 2]

rawDescription: Python Access Variables Outside of Function


code:
print (s)       # NOT a tuple, so seems to work
print (s,)      # A 1-tuple
print (s,1,2)   # A 3-tuple
print s,1,2     # prints normally.

rawDescription: what makes a python webscrape output unicode?

description: What makes a python webscrape output unicode


code:
def foo(*args):
   print 'foo',args

def bar(*args):
   print 'bar',args

from operator import methodcaller

map(methodcaller('__call__',1,2,3),[foo,bar])

rawDescription: Python one-liner to call list of functions


code:
p1 = DummyObj(t1, list1, d1)
p2 = DummyObj(t1, list1, d1)
mySet = set()
mySet.add(p1)

print "p1 in set", p1 in mySet
print "p2 in set", p2 in mySet

rawDescription: How to implement __eq__ for set inclusion test?

description: Implement __eq__ for set inclusion test


code:
class Facilities(object):
    def __init__(self):
        self.total_rate = 0
        self.vrates = 0
        self.funrate = 0
        self.rates5 = 0

    def food(self):
        # files are used
        self.rates5 = 1
        # calculate the rate and store the total rate in rates5
        return self.rates5

    def recreation(self):
        # files are used
        self.funrate = 2
        # calculate the rate and store the total rate in funrate
        return self.funrate

    def transport(self):
        # files are used
        self.vrates = 3
        # calculate the rate and store the total rate in vrates
        return self.vrates

    def get_total_rate(self):
        return self.food() + self.recreation() + self.transport()

facilities_obj = Facilities()
total_rate = facilities_obj.food() + facilities_obj.recreation() + facilities_obj.transport()
# another option
total_rate = facilities_obj.get_total_rate()
print "The total amount =", total_rate

rawDescription: Something wrong with this file program?

description: Something wrong with this file program


code:
#!/usr/bin/env python

def joiner(s, token):
    i = 0
    while i < len(s):
        if s[i] == token:
            yield s[i] + ' ' + s[i+1]
            i=i+2
        else:
            yield s[i]
            i=i+1

sentence = ['a','list','with','a','lot','of','strings','in','it']

for i in joiner(sentence, 'a'):
    print i

rawDescription: joining string to next string in list

description: Joining string to next string in list


code:
for k,v in sorted(after_free_skate.items(),key=itemgetter(1)):
    try:
        diff = after_short_program[k]-v
        print "%s (%+d)"%(k,diff)
    except KeyError:
        print "%s (new)"%k

rawDescription: Positional Comparisons in Python

description: Positional Comparisons in Python


rawDescription: Tokenising integers in a string

description: Tokenising integers in a string


code:
#! /usr/bin/env python

import re

token_re = re.compile(r'use\s+([a-z0-9]+)\s+code', re.IGNORECASE)
def find_token(s):
    m = token_re.search(s)
    if m is not None:
        token = m.group(1)
        if token.isupper():
            return token

if __name__ == '__main__':
    for s in ['Use HELLO1 code',
              'USE hello1 CODE',
              'this does not match',
             ]:
        print s, '->',
        print find_token(s)

rawDescription: How to set ignorecase flag for part of regular expression in Python?

description: Set ignorecase flag for part of regular expression in Python


code:
_level = MemoizeMutable(_level)

equirements = {'a': [],
               'b': [],
               'c': ['a'],
               'd': ['a','b'],
               'e': ['c','d'],
               'f': ['e']
                 }

print uses_hierarchy(equirements)

rawDescription: Python - anyone have a memoizing decorator that can handle unhashable arguments?


code:
from numpy import *

amp = 10
length = 100
wavelength = 20

omega = (2*pi)/wavelength
phi   = wavelength*(0.5)
X = arange(1,length)
Y1 = round_(amp*(sin(omega*X) + 1))
Y2 = round_(amp*(sin(omega*X+phi) + 1))

offset = phi/2
Z1 = sin(omega*X + offset)
Z2 = sin(omega*X + phi + offset)

T1 = " ######### "
T2 = " ********* "
clen = len(T1)

H = zeros((length,amp*2+clen),dtype='str')
H[:,:] = " "

for n,(y1,y2,z1,z2) in enumerate(zip(Y1,Y2,Z1,Z2)):
    H[n,y1:y1+clen] = list(T1)
    H[n,y2:y2+clen] = list(T2)

    # Overwrite if first helix is on top
    if z1>z2: H[n,y1:y1+clen] = list(T1)

for line in H:
    print "".join(line)

rawDescription: Double helix generating algorithm

description: Double helix generating algorithm


code:
for title, block in blocks('input.txt'):
    if 'solid' not in block:
        print title, block

rawDescription: Python - reading between parenthesis as a single 'block'


code:
for row in grid:
    for item in row:
        print item,
    print

rawDescription: How to traverse a 2D List in python

description: Traverse a 2D List in python


code:
def count(df):
    count_sessions = lambda t: df[(df.Start<t) & (df.Finish>t)].shape[0]
    df['OpenSessions'] = df['Start'].map(count_sessions)
    return df

print sessions.groupby('Node').apply(count)

rawDescription: Pandas get the index of an element in a map function


code:
def can_detect(self, other):
    for own_coord, other_coord in zip(self.coordinates, other.coordinates):
        if abs(own_coord - other_coord) > self.radar_range:
            return False
    return True

def radar(self):
    for other in Mobilesuits.instances:
        if other is not self and self.can_detect(other):
            print "%s detected at %s" % (other.description, other.coordinates)

rawDescription: How do I automatically pass arguments to a function on certain objects

description: Automatically pass arguments to a function on certain objects


code:
n_s = np.logspace(1, 3.3, 25)
int_1 = np.empty((len(n_s),) * 2)
int_2 = np.empty((len(n_s),) * 2)
z_shape = (5,)

for i, n_i in enumerate(n_s) :
    print int(n_i)
    for j, n_j in enumerate(n_s) :
        x, y, z = sample_data(int(n_i), int(n_j), z_shape)
        int_1[i, j] = min(timeit.repeat('interp_1(x, y, z)',
                                        'from __main__ import interp_1, x, y, z',
                                        repeat=10, number=1))
        int_2[i, j] = min(timeit.repeat('interp_2(x, y, z)',
                                        'from __main__ import interp_2, x, y, z',
                                        repeat=10, number=1))

cs = plt.contour(n_s, n_s, np.transpose(int_1-int_2))
plt.clabel(cs, inline=1, fontsize=10)
plt.xlabel('n_i')
plt.ylabel('n_j')
plt.title('timeit(interp_2) - timeit(interp_1), z.shape=' + str(z_shape))
plt.show()

rawDescription: Scipy Fast 1-D interpolation without any loop


code:
import json

from twisted.internet import reactor
from scrapy.crawler import Crawler
from scrapy import log, signals
from scrapy.utils.project import get_project_settings

class MyPipeline(object):
    def process_item(self, item, spider):
        results.append(dict(item))

results = []
def spider_closed(spider):
    print results

# set up spider
spider = TestSpider(domain='mydomain.org')

# set up settings
settings = get_project_settings()
settings.overrides['ITEM_PIPELINES'] = {'__main__.MyPipeline': 1}

# set up crawler
crawler = Crawler(settings)
crawler.signals.connect(spider_closed, signal=signals.spider_closed)
crawler.configure()
crawler.crawl(spider)

# start crawling
crawler.start()
log.start()
reactor.run()

rawDescription: scrapy from script output in json

description: Scrapy from script output in json


code:
import datetime
import calendar
d = datetime.datetime(2014,03,04,12,00,00)
calendar.timegm(d.timetuple())

rawDescription: Find the epoch of the most recent midnight


code:
bar = [False]

def someFunction(incoming_variable):
    incoming_variable[0] = True

someFunction(bar)

print bar[0]

rawDescription: Change a variable from a function

description: Change a variable from a function


code:
import sys

class Name:

    def __init__(self):
        self.name = 'John'
        self.address = 'Place'
        self.age = '100'

    def printName(self):
        print self.name

    def printAddress(self):
        print self.address

    def printAge(self):
        print self.age

if __name__ == '__main__':

    Person = Name()

    launchOptions = sys.argv[1:]

    if not launchOptions or 'name' in launchOptions:
        Person.printName()

    if not launchOptions or 'address' in launchOptions:
        Person.printAddress()

    if not launchOptions or 'age' in launchOptions:
        Person.printAge()

rawDescription: How to start a Python script several functions in

description: Start a Python script several functions in


code:
from xml.dom.minidom import parseString

document = parseString('''
<?xml version="1.0"?>
<connections>
  <connection name="name_1">
    <parameter name="user" value="user_value_1"/>
    <parameter name="password" value="psw_1"/>
  </connection>

  <connection name="name_2">
    <parameter name="user" value="user_value_2"/>
    <parameter name="password" value="psw_2"/>
  </connection>

  <connection name="name_n">
    <parameter name="user" value="user_value_n"/>
    <parameter name="password" value="psw_n"/>
  </connection>
</connections>''')

names = {'connection names': []}

for connection in document.getElementsByTagName('connection'):
  names['connection names'].append(connection.getAttribute('name'))

print names

rawDescription: Get a json dictionary from xml file

description: Get a json dictionary from xml file


code:
def parse():
  itr = iter(filter(lambda x: x, re.split("\\s+", s.replace('(', ' ( ').replace(')', ' ) '))))

  def _parse():
    stuff = []
    for x in itr:
      if x == ')':
        return stuff
      elif x == '(':
        stuff.append(_parse())
      else:
        stuff.append(x)
    return stuff

  return _parse()[0]

def find(parsed, tag):
  if parsed[0] == tag:
    yield parsed
  for x in parsed[1:]:
    for y in find(x, tag):
      yield y

p = parse()
np = find(p, 'NP')
for x in np:
  print x

rawDescription: Extracting information from context-free phrase structure output from Stanford Parser


code:
import re

text = "Mr. McCONNELL. yadda yadda jon stewart is mean to me. The PRESIDING OFFICER. Suck it up. Mr. McCONNELL. but noooo. Mr. REID. Really dude?"

speakers = ["McCONNELL", "PRESIDING OFFICER", "REID"]

speakers_re = re.compile('(' + '|'.join([re.escape(s) for s in speakers]) + ')')

print speakers_re.split(text)

rawDescription: split by elements of a string, and create a dictionary with {element used to split: that chunk of text}

description: Split by elements of a string, and create a dictionary with {element used to split: that chunk of text}


code:
import re
p = re.compile(ur'Start.*$')
test_str = u"87, 72 Start I am a sentence finish"
result = re.sub(p, "", test_str).strip()
print result

rawDescription: Python regex replace sentence with starting word


code:
# We need to store our value somewhere
total_value = 0
for fruit_name, fruit_list in fruit_stand.items():
    # Ignore fruit_name and iterate over the fruits in fruit_list
    for color, quantity, cost in fruit_list:
        total_value += (quantity * cost)

print total_value

rawDescription: Breaking down instances of classes into lists, or: a better way to sum class variables?


code:
html = """

            menu1

Some data1

Foo1Bar1

            menu2

Some data2

Foo2Bar2

Foo3Bar3

Some data3

"""

import BeautifulSoup as bs

soup = bs.BeautifulSoup(html)

table = soup.findAll('table')[0]

results = {}

th = table.findChildren('th')#,text=['menu1','menu2'])

for x in th:
    #print x
    results_li = []
    li = x.nextSibling.nextSibling.findChildren('li')
    for y in li:
        #print y.next
        results_li.append(y.next)
    results[x.next] = results_li

print results

rawDescription: Parsing html table with BeautifulSoup to python dictionary


code:
import script
print script.airportCode

rawDescription: How to import or include data structures (e.g. a dict) into a Python file from a separate file

description: Import or include data structures (e.g. a dict) into a Python file from a separate file


code:
class Example:
    def print_stuff(self, *args):
        print 'My *self* is {}'.format(self)
        print 'My *args* is {}'.format(args)

Example().print_stuff(1, 2, 3)
# My *self* is <__main__.Example instance at 0x012D4210>
# My *args* is (1, 2, 3)

rawDescription: Function inside of Object generating different print output than stand-alone function in Python 3.5


code:
def hasDigit(w):
   for c in w:
      if c.isdigit():
         return True
   return False

with open("data.txt") as f:
    for line in f:
        digits = [w for w in line.split() if not hasDigit(w)]
        if digits:
            print ' '.join(digits)
#   break  # uncomment the "break" if you ONLY want to process the first line

rawDescription: I need to make the output be in one line


code:
import numpy

a = numpy.linspace(0, 10, num = 101)  # num -> number of elements
print a

rawDescription: Specifying Elements In A Numpy Array

description: Specifying Elements In A Numpy Array


code:
from Tkinter import *
from ttk import *

class App():
  def __init__(self, master):
    frame = Frame(master)
    frame.pack()

    master.title("Just my example")
    self.label = Label(frame, text="Type very long text:")

    self.entry = Entry(frame)

    self.button = Button(frame,
                         text="Quit", width=15,
                         command=frame.quit)

    self.slogan = Button(frame,
                         text="Hello", width=15,
                         command=self.write_slogan)

    self.label.grid(row=0, column=0)
    self.entry.grid(row=0, column=1)
    self.slogan.grid(row=1, column=0, sticky='e')
    self.button.grid(row=1, column=1, sticky='e')

  def write_slogan(self):
    print "Tkinter is easy to use!"

root = Tk()
root.style = Style()
#('clam', 'alt', 'default', 'classic')
root.style.theme_use("clam")

app = App(root)
root.mainloop()

rawDescription: Tkinter look (theme) in Linux

description: Tkinter look (theme) in Linux


code:
if any(block.rect.colliderect(x.rect) for x in blocklist if x is not block):
            x=(int(mse[0]) / 32)*32
            y=(int(mse[1]) / 32)*32
            blockpairs = itertools.combinations(blocklist,2) #2 for pairs
            remlist = frozenset(b2 for b1,b2 in blockpairs if b1.rect.colliderect(b2.rect))
            blocklist = [block for block in blocklist if block not in remlist]
            for block in remlist:
                print 'killed it'
                blocklist.remove(block)

rawDescription: Pygame: Removing an entity from a list

description: Pygame: Removing an entity from a list


code:
tickets = [{"summary" : "a"}, {"summary" : "a"}, {"summary" : "b"}]
issue = {"title" : "a"}
from timeit import timeit
print timeit("[ticket for ticket in tickets if ticket['summary'] == issue['title']]", setup="from __main__ import tickets, issue")
print timeit('filter(lambda ticket: ticket["summary"] == issue["title"], tickets)', setup="from __main__ import tickets, issue")
print timeit("list(ticket for ticket in tickets if ticket['summary'] == issue['title'])", setup="from __main__ import tickets, issue")

rawDescription: Find a dictionary in a list of dictionaries


code:
for itemID, itemName in zip(itemIDs, itemNames):
    print itemID, itemName

rawDescription: How to use a .NET method which modifies in place in Python?

description: Use a .NET method which modifies in place in Python


rawDescription: How should I go about subsampling from a scipy.sparse.csr.csr_matrix and a list


code:
def main():
    t1 = timeit.timeit('MultiRange.in_range(985000)', setup='import MultiRange', number=10000)
    t2 = timeit.timeit('MultiRange.IsInRange(985000)', setup='import MultiRange', number=10000)

    print t1, t2
    print float(t2)/float(t1), 1 - float(t2)/float(t1)

rawDescription: How to check if a number is within a group of non-consecutive ranges?

description: Check if a number is within a group of non-consecutive ranges


code:
from collections import deque

with open('/tmp/lines.txt') as fin:
    trim=6                              # print all but the last X lines
    d=deque(maxlen=trim+1)
    for line in fin:
        d.append(line)
        if len(d)<trim+1: continue
        print d.popleft().strip()

rawDescription: How to not print the last line

description: Not print the last line


code:
def flatten(l):
    """
    Flatten a nested list.
    """
    for i in l:
        if isinstance(i, (list, tuple)):
            for j in flatten(i):
                yield j
        else:
            yield i

def list2csv(l):
    """
    Return CSV-ish text for a nested list.
    """
    lines = []
    for row in l:
        if isinstance(row, (list, tuple)):
            lines.append(",".join(str(i) for i in flatten(row)))
        else:
            lines.append(str(row))
    return "\n".join(lines)

print list2csv(data)

rawDescription: Python save arbitrarily nested list to CSV


code:
import glob,os
mylist=[]
os.chdir("/mydir")
for file in glob.glob("Mod*"):
        mylist.append(file)

print mylist

rawDescription: Filename scanning for certain names Python


code:
[{'distance': 4.1, 'home_id': 1L, 'home_number': 2, 'road_id': 0},
 {'distance': 2.1, 'home_id': 2L, 'home_number': 4, 'road_id': 0},
 {'distance': 4, 'home_id': 3L, 'home_number': 5, 'road_id': 1},
 {'distance': 2.1, 'home_id': 4L, 'home_number': 1, 'road_id': 2},
 {'distance': 6, 'home_id': 5L, 'home_number': 3, 'road_id': 2}]

rawDescription: Sorting and re-numbering values in Python dictionary


code:
alpha = 0.5
assert 0 < alpha <= 1.0
av = sum(alpha**n.days * iq
    for n, iq in map(lambda (day, iq), today=max(days): (today-day, iq),
        sorted(zip(days, IQ), key=lambda p: p[0], reverse=True)))

rawDescription: calculate exponential moving average in python

description: Calculate exponential moving average in python


code:
class MyDetailView(DetailView):
    context = {}

    def get(self, request, *args, **kwargs):
        self._process(request, *args, **kwargs)

        if 'redirect' in self.context:
            return HttpResponseRedirect(self.context['redirect'])

        else:
            return self._render(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self._process(request, *args, **kwargs)

        if 'redirect' in self.context:
            return HttpResponseRedirect(self.context['redirect'])

        elif self.context['form'].is_valid():
            self._get_hook('_pre_save')(request, *args, **kwargs)
            return self._save(request, *args, **kwargs)

        else:
            return self._render(request, *args, **kwargs)

    def _process(self, request, *args, **kwargs):
        form = getattr(app.forms, '%sForm' % self.model.__name__)

        if kwargs['pk'] != 'new':  # READ/UPDATE
            self.object = self.get_object(request, *args, **kwargs)

            self._get_hook('_auth')(request, *args, **kwargs)

            if not self.object:  # user not authorized for this entity
                return {'redirect': reverse(
                    '%s_list' % self.model.__name__.lower())}

        self.context['form'] = form(
            data=request.POST if request.method == 'POST' else None,
            instance=self.object if hasattr(self, 'object') else None)

        self._get_hook('_post_process')(request, *args, **kwargs)

    def _get_hook(self, hook_name):
        try:
            return getattr(self, '%s_hook' % hook_name)
        except AttributeError, e:
            def noop(*args, **kwargs):
                pass
            return noop

rawDescription: DRY views in Django

description: DRY views in Django


code:
import requests
from pprint import pprint
files = {'file1': ('foo.txt', 'foo\ncontents\n','text/plain'),
          'file2': ('bar.txt', 'bar contents', 'text/plain'),
          'file3': ('baz.txt', 'baz contents', 'text/plain')}
headers = {'Content-Disposition': 'attachment'}
params = [('title', 'file1'), ('title', 'file2'), ('title', 'file3')]
r = requests.Request('POST', 'http://example.com',
                     files=files, headers=headers, params=params)
prepared = r.prepare()
prepared.url
pprint(dict(prepared.headers))
print prepared.body

rawDescription: how to POST multipart list of JSON/xml files using python requests


code:
import mysql

x = input()
read = mysql.readinput()
print read
for item in read:
    if str(x) == item[0]:
      print("Hello, #10!")
      break
    else:
      print("bye")

rawDescription: Python MySQL: How to read from database in a module and compare it to input() in main program?


code:
import re

regi = ("[mM]y name [Ii][sS] (\w*)"
        "||Hi {0}!"
        "||You said that your name was {0} !!!",

        "[Ii]n repertory (\w*) I [wW][aA][nN][tT] file (\w*)"
        "||OK here's your file {0}\\{1} :"
        "||I already gave you the file {0}\\{1} !",

        "[Ii] [wW][aA][nN][tT] to ([ \w]*)"
        "||OK, I will do {0}"
        "||You already did {0}. Do yo really want again ?")

direg  = {}
memory = {}
def distr(regi,cnt = 0,di = direg,mem = memory,
          regnb = re.compile('{\d+}')):
    for i,el in enumerate(regi,start=1):
        sp = el.split('||')
        cnt += len(regnb.findall(sp[1]))
        di[cnt] = sp[1]
        mem[cnt] = sp[2]
        yield sp[0]

regx = re.compile('|'.join(distr(regi)))
print 'direg :\n',direg
print
print 'memory :\n',memory
for inp in ('I say that my name is Armano the 1st',
            'In repertory ONE I want file SPACE',
            'I want to record music',
            'In repertory ONE I want file SPACE',
            'I say that my name is Armstrong',
            'But my name IS Armstrong now !!!',
            'In repertory TWO I want file EARTH',
            'Now my name is Helena'):

    print '\ninput  ==',inp

    mat = regx.search(inp)
    if direg[mat.lastindex]:
        print 'output ==',direg[mat.lastindex]\
              .format(*(d for d in mat.groups() if d))
        direg[mat.lastindex] = None
        memory[mat.lastindex] = memory[mat.lastindex]\
                                .format(*(d for d in mat.groups() if d))
    else:
        print 'output ==',memory[mat.lastindex]\
              .format(*(d for d in mat.groups() if d))
        if not memory[mat.lastindex].startswith('Sorry'):
            memory[mat.lastindex] = 'Sorry, ' \
                                    + memory[mat.lastindex][0].lower()\
                                    + memory[mat.lastindex][1:]

rawDescription: How to save a regular expression user input value (Python)

description: Save a regular expression user input value (Python)


code:
a = range(5, 15)
b = range(10, 20)
print sorted(set(a + b))

rawDescription: Given a bunch of ranges of numbers, get all the numbers within those ranges?


code:
class Text(Object, ColourMixin):
    """
    A class for representing text on the screen.

    The reference point of a Text object is the centre of its
    bounding box.
    """

    def __init__(self, screen, x, y, text, size, colour, static=0):

        self.init_text (screen, x, y, text, size, colour, static)

    def init_text (self, screen, x, y, text, size, colour, static=0):
        """
        Arguments:

        screen -- the screen the object is on.
        x -- x-coordinate of centre of bounding box.
        y -- y-coordinate of centre of bounding box.
        text -- the text to display.
        size -- nominal height of the text, in pixels.
        colour -- the colour the text should be.
        """
        if not _have_font:
            raise GameError, "We don't have pygame.font, so can't create text objects"
        self._size = size
        self._colour = colour
        self._text = text
        self._font = pygame.font.Font(None, self._size)
        self._a = 0
        surface = self._create_surface()
        Object.__init__(self, screen, x, y, surface, x_offset=self._x_offset,
                        y_offset=self._y_offset, static=static)
        self.move_to(x,y)

    # There are more methods...

rawDescription: Changing font in a livewires message

description: Changing font in a livewires message


code:
def n_split(iterable, n, fillvalue=None):
    num_extra = len(iterable) % n
    zipped = zip(*[iter(iterable)] * n)
    return zipped if not num_extra else zipped + [iterable[-num_extra:], ]

dblist=['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve']
for group in n_split(dblist, 5):
    print ' '.join(group)

for count, group in enumerate(n_split(dblist, 5), 1):
    print 'env{}: {}'.format(count, ' '.join(group))

rawDescription: Splitting a Python list into groups of 5 and then printing


code:
soup = Soup(html)
text = soup.p.string
soup.p.clear()
print soup

rawDescription: Python BeautifulSoup - Add Tags around found keyword


code:
import numpy as np
import pandas as pd
import itertools

c = list(itertools.repeat(['x','y', 'z'], 3))
col_a = list(itertools.chain(*c))

depths = [5.0, 5.0, 5.0, 10.0, 10.0, 10.0, 20.0, 20.0, 20.0]
names = list("xyzxyzxyz")

df = pd.DataFrame(np.random.rand(8, 9))
df.columns = pd.MultiIndex.from_arrays((depths, names))
print df[10]

rawDescription: Selecting a subset of columns from a dataframe using multi index


code:
print 'Value is "%d"' % value
print 'Value is "%d", but math.pi is %.2f' % (value, math.pi)

rawDescription: How to print variables without spaces between values

description: Print variables without spaces between values


code:
src = {'lblA': (False, True), 'lblB': (False, True), 'lblC': (0, 1, 2)}

labels, terms = zip(*src.items())

print [dict(zip(labels, term)) for term in itertools.product(*terms)]

rawDescription: Best way to enumerate a cartesian product with labels in python?

description: Enumerate a cartesian product with labels in python


code:
text = """[image @alt:alien; @title:reddit alien;]http://www.reddit.com/alien1.png[/image]

But I should have no problem matching:

[image @title:reddit alien; @alt:alien;]http://www.reddit.com/alien2.png[/image]
"""

from pyparsing import Suppress, Group, Word, alphas, SkipTo, Dict, ZeroOrMore

LBRACK,RBRACK,COLON,SEMI,AT = map(Suppress,"[]:;@")
tagAttribute = Group(AT + Word(alphas) + COLON + SkipTo(SEMI) + SEMI)
imageTag = LBRACK + "image" + Dict(ZeroOrMore(tagAttribute)) + RBRACK
imageLink = imageTag + SkipTo("[/image]")("text")

for taginfo in imageLink.searchString(text):
    print taginfo.alt
    print taginfo.title
    print taginfo.text
    print

rawDescription: Is there a way to match a set of groups in any order in a regex?


code:
def createstuff(data):
    t= threading.Thread(target=func, args=(data,))
    t.start()

def func(val):
    time.sleep(2)
    print ('Value: %s, : %s'%(val, threading.currentThread().getName()))

args_list = ThreadSafeList(['x'])
createstuff(args_list)
rn =random.randint(5,50)
print 'random no:', rn
args_list[0] = rn

rawDescription: Threading lock in python not working as desired


code:
df.index = ["row1", "row2", "row3"]
print df

rawDescription: Assigning column names from a list to a table


code:
def main():
  print 'Hello, world.'

main()

rawDescription: Import Python Functions from Auto-Running Script


code:
import numpy as np
import colorsys
mymatrix = np.matrix([[11,12,13],
                      [21,22,23],
                      [31,32,33]])

def to_hsv(x):
    return colorsys.rgb_to_hsv(*x)

#Apply the to_hsv function to each matrix row.
print np.apply_along_axis(to_hsv, axis=1, arr=mymatrix)

rawDescription: Translating Matlab (Octave) group coloring code into python (numpy, pyplot)


code: print '\n\n'.join(('\n'.join(line) for line in ascii))

rawDescription: Printing nested lists in certain directions - Python


code:
def conjoin(gs):
    return [()] if not gs else (
        (val,) + suffix for val in gs[0]() for suffix in conjoin(gs[1:])
    )

def range3():
    return range(3)

print list(conjoin([range3, range3]))

rawDescription: Conjoin function made in functional style


code:
from pkg_resources import load_entry_point
mainfunc = load_entry_point('pelican', 'console_scripts', 'pelican')
print mainfunc.__module__
mainfunc()

rawDescription: which is pelican executable script that user executes from shell?

description: Which is pelican executable script that user executes from shell


code:
import pytz, datetime, time
import os

originalTimeStamp = os.stat("/tmp/file-from-us-west-coast").st_mtime

# prints e.g. 2010-03-31 13:01:18
print "original:",datetime.datetime.fromtimestamp(originalTimeStamp)

# re-interpret
originalTimeZone = "America/Los_Angeles"
targetTimeZone   = "Europe/Paris"

newTimeStamp = pytz.timezone(originalTimeZone).localize(datetime.datetime.fromtimestamp(originalTimeStamp)).astimezone(pytz.timezone(targetTimeZone))

# prints e.g. 2010-03-31 22:01:18+02:00
print "new:     ",newTimeStamp

# convert back to seconds since epoch
newTimeStamp = time.mktime(newTimeStamp.timetuple())

# print time difference in hours
print (newTimeStamp - originalTimeStamp) / 3600.0

rawDescription: Convert Facebook Event start/end times to UTC


code:
def lv1(d):
  exec ""
  locals().update(d)
  print zap

lv1({'zap': 23})

rawDescription: How can I pass my locals and access the variables directly from another function?

description: Pass my locals and access the variables directly from another function


code:
import re

f = open("3HDL.pdb", "r")

for line in f:
  m = re.search(r"REMARK 800 SITE_IDENTIFIER: (.+)", line)
  if m:
    site_id = m.group(1).strip()
  else:
    m = re.search(r"REMARK 800 EVIDENCE_CODE: (.+)", line)
    if m:
      evidence_code = m.group(1).strip()
    else:
      m = re.search(r"REMARK 800 SITE_DESCRIPTION: (.+)", line)
      if m:
        site_descrip = m.group(1).strip()
        print site_id, evidence_code, site_descrip

f.close()

rawDescription: How to collect and gather words from multiple lines in a input text (PDB file) using Python?

description: Collect and gather words from multiple lines in a input text (PDB file) using Python


code:
def twentyone(seq, groups = [], final = []): #default final list
    goal = 21
    s = sum(groups)

    if s == goal:
        final.append(groups)

    if s >= goal:
        return

    for i in range(len(seq)):
        n = seq[i]
        remaining = seq[i+1:]
        twentyone(remaining, groups + [n])

    return final

seq = [1, 5, 6, 7, 10, 2, 11]
print twentyone(seq)

rawDescription: trouble appending lists to another list

description: Trouble appending lists to another list


code:
a = A()
print a.object_property

rawDescription: difference between an object property and type property

description: Difference between an object property and type property


code:
teachers = list(School.getTeachers())
teacher1 = teachers[0]
teacher2 = teachers[1]

diff = set(teacher1.getChildrens()) - set(teacher2.getChildrens())
print "%s are not under %s" % (", ".join(c.getName() for c in diff), teacher2.getName())

rawDescription: Comparison of data in Python

description: Comparison of data in Python


code:
import unicodedata, re, io
from time import time

# This is to generate randomly a file to test the script

from string import lowercase
from random import random

all_chars = (unichr(i) for i in xrange(0x110000))
control_chars = [c for c in all_chars if unicodedata.category(c)[0] == 'C']
chars = (list(u'%s' % lowercase) * 115117) + control_chars

fnam = 'filename.txt'

out=io.open(fnam, 'w')

for line in range(1000000):
    out.write(u''.join(chars[int(random()*len(chars))] for _ in range(600)) + u'\n')
out.close()

# version proposed by alvas
all_chars = (unichr(i) for i in xrange(0x110000))
control_chars = ''.join(c for c in all_chars if unicodedata.category(c)[0] == 'C')
cc_re = re.compile('[%s]' % re.escape(control_chars))
def rm_control_chars(s):
    return cc_re.sub('', s)

t0 = time()
cleanfile = []
with io.open(fnam, 'r', encoding='utf8') as fin:
    for line in fin:
        line =rm_control_chars(line)
        cleanfile.append(line)
out=io.open(fnam + '_out1.txt', 'w')
out.write(''.join(cleanfile))
out.close()
print time() - t0

# using a set and checking character by character
all_chars = (unichr(i) for i in xrange(0x110000))
control_chars = set(c for c in all_chars if unicodedata.category(c)[0] == 'C')
def rm_control_chars_1(s):
    return ''.join(c for c in s if not c in control_chars)

t0 = time()
cleanfile = []
with io.open(fnam, 'r', encoding='utf8') as fin:
    for line in fin:
        line = rm_control_chars_1(line)
        cleanfile.append(line)
out=io.open(fnam + '_out2.txt', 'w')
out.write(''.join(cleanfile))
out.close()
print time() - t0

rawDescription: Is there a faster way to clean out control characters in a file?


code:
import sys
import argparse as ap

def foo(str_, encoding=sys.stdin.encoding):
    return str_.decode(encoding)

parser = ap.ArgumentParser()
parser.add_argument('my_int', type=int)
parser.add_argument('my_arg', type=foo)
args = parser.parse_args()

print repr(args)

rawDescription: Best way to decode command line inputs to Unicode Python 2.7 scripts

description: Decode command line inputs to Unicode Python 2.7 scripts


code:
import os
import time
import serial

# Name of csv file with drawing coordinates
fileName = "coordinates.csv"

# Create serial connection
ser = serial.Serial(port='/dev/tty.usbserial-A9005bDh', baudrate=9600)

wd = os.getcwd()
myFile = open(wd + "/graphics/" + fileName)

#num_lines = sum(1 for line in myFile)

state = '0'
idx = 0

while True: # Exits when there is no more lines to read

    #print "state", state

    while state == '0': # Wait for Arduino to be ready
        ser.flushInput() # Clear input buffer
        state = str(ser.read())

    if state == '1': # Send one more line to Arduino
        line = myFile.readline()
        if not line:
            break
        print "Coordinate", idx
        print line
        ser.flushOutput() # Clear output buffer
        ser.write(line)

        time.sleep(0.1)

        idx = idx + 1
        state = '0' # Set waiting flag – make Arduino wait for next line

ser.close()
myFile.close

rawDescription: How to make data sent by Python (via serial connection) wait for Arduino to finish current task?

description: Make data sent by Python (via serial connection) wait for Arduino to finish current task


code: print dir(response)

rawDescription: Django: How to test for 'HttpResponsePermanentRedirect'


code:
import os
from xml.sax.saxutils import quoteattr as xml_quoteattr

def DirAsLessXML(path):
    result = '<dir name=%s>\n' % xml_quoteattr(os.path.basename(path))
    for item in os.listdir(path):
        itempath = os.path.join(path, item)
        if os.path.isdir(itempath):
            result += '\n'.join('  ' + line for line in
                DirAsLessXML(os.path.join(path, item)).split('\n'))
        elif os.path.isfile(itempath):
            result += '  <file name=%s />\n' % xml_quoteattr(item)
    result += '</dir>'
    return result

if __name__ == '__main__':
    print '<structure>\n' + DirAsLessXML(os.getcwd()) + '\n</structure>'

rawDescription: os.walk() python: xml representation of a directory structure, recursion

description: Os.walk() python: xml representation of a directory structure, recursion


code:
import subprocess
import sys

sys.stdout = open("./out.log", "w")
print "Starting process..."
sys.stdout.flush()
process = subprocess.Popen(["echo", "a"], shell=False, stdout=sys.stdout)
process.wait()
print "Done"

rawDescription: Calling external program through Python and passing the output to stdout


code:
def CRlistToTable(CRlist):
    """ Create HTML table from CRlist data """
    CRstrings = ['
']

    # create table's header row from the first row of CRlist
    BGCOLOR = '#67B0F9' # column header cells background color
    cols = CRlist[0]  # column names given in first row
    CRstrings += ['
', '\n'.join(
                  '    {}	'.format(BGCOLOR, col_name)
                     for col_name in cols),
                  '
']

    # create a template for remaining non-header table rows
    TR_TEMPLATE = ['
',
                   '    ',
                   '      {}',  # for dynamically generated CR links
                   '    	', '\n'.join(
                  ['    {}	'] * (len(cols)-1)), # one per remaining cols
                   '
']
    TR_TEMPLATE = '\n'.join(TR_TEMPLATE) # convert to a string

    # apply the row template created to remaining CRlist rows
    CR_LINK_TEMPLATE = '{0}'
    for row in CRlist[1:]:
        if ',' not in row[0]:  # no comma-delimited items in first column?
            links = CR_LINK_TEMPLATE.format(row[0])
        else:
            CRs = row[0].replace(',', ' ').split()
            links = ',\n      '.join(CR_LINK_TEMPLATE.format(cr) for cr in CRs)
        row[0] = links
        CRstrings += [TR_TEMPLATE.format(*row)]

    CRstrings += ["
"]

    # return string list merged to a single long newline-delimited string
    return '\n'.join(CRstrings) + '\n'

with open('cr_fixes_tabbed.xml') as file:
    xmldata = file.read()  # read entire file into memory

FIXES_START_TAG, FIXES_END_TAG = '<Fixes>, </Fixes>'.replace(',', ' ').split()
# embedded fixes info starts right after the tag itself within the xml data
xmlFixesStart = xmldata.find(FIXES_START_TAG) + len(FIXES_START_TAG)
xmlFixesEnd = xmldata.find(FIXES_END_TAG)

# extract portion of file data within the FIXES tags into a list of lines
info = xmldata[xmlFixesStart:xmlFixesEnd].strip().splitlines()

# split non-blank lines of tab-delimited data into list of rows of column data
CRlist = [line.split('\t') for line in info if line] # skips blank lines

crInfo = CRlistToTable(CRlist) # convert list into html table
print crInfo

rawDescription: Logical issue in generating HTML code

description: Logical issue in generating HTML code


code:
def echo(**kwargs):
    for name, value in kwargs.items():
        print name, value

foo = 7
echo(foo=foo)

rawDescription: Find the name of a Python variable that was passed to a function


rawDescription: Displaying unicode characters using python


code:
from bson.tz_util import utc
cursor = db.collection.find({'$or': [
    {'col1': 1, 'col2': 'foo'},
    {'col3': {'$gt': datetime(2012, 01, 01, tzinfo=utc)}},
    {'col3': {'$lt': datetime(2012, 01, 02, tzinfo=utc)}},
]})

rawDescription: Build mongoDB queries based on JSON from a user using Python


code:
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('a', type=int)
parser.add_argument('b', type=int)
parser.add_argument('c', type=int)

args = parser.parse_args()

def sum(i, j):
      return i+j

def totalsum(k):
      return sum(args.a, args.b) + k

print totalsum(args.c)

rawDescription: Using argparse, how do parse command line arguments to specify variable values?


code:
import pandas as pd
import numpy as np

data = pd.DataFrame({'time': np.arange(1,101), 'mass': np.random.randn(100)})
dm = np.diff(data.mass, n=1)
dmv = np.diff(data.mass.values, n=1)

print 'data.mass: \t\t', dm.shape
print 'min: ', dm.min(), ' max: ', dm.max(), ' mean: ', dm.mean()

print ''
print 'now using data.mass.values in the calculations \n'
print 'data.mass.values: \t', dmv.shape
print 'min: ', dmv.min(), ' max: ', dmv.max(), ' mean: ', dmv.mean()

print ''
dm_p = data.mass.diff()
print 'now based on what @jeff said: '
print 'using .diff() : \t', dm_p.shape
print 'min: ', dm_p.min(), ' max: ', dm_p.max(), ' mean: ', dm_p.mean()

rawDescription: numpy.diff() use with pandas DataFrame error

description: Numpy.diff() use with pandas DataFrame error


code:
a=[{'type':"cccc"}, {'type':"oooo"} , {'type':"xxxx"}, {'type':"cccc"},{'type':"xxxx"}]

xxlist=[]

for index,dix in enumerate(a):
    if dix['type']=='xxxx':
        xxlist.append(a.pop(index))
new=[]
for i in a:
    if i['type']=='cccc':
        new.append(xxlist.pop(0))
        new.append(i)
    else:
        new.append(i)

if len(xxlist)>0:
    for i in xxlist:
       new.append(i)
print new

rawDescription: Python: sort specific pairs of dictionaries in a list of dictionaries based on occurrence of value


code:
a = Vector(1,1)           # There is a Vector object somewhere in memory, e.g. 12345. Then a = 12345
b = a                     # b = a = 12345 (still the address of the same Vector object)
a.subtract(Vector([1,1])) # Change whatever is stored at the address of a = 12345
print a,b                 # both are still the address of the same object you modified in the previous step!

rawDescription: Python object1 = object2

description: Python object1 = object2


code:
import re

regex = re.compile(r'(?=(\w{5}))')
with open('input.txt', 'r') as fh:
    input = fh.read()
print len(set(re.findall(regex, input)))

rawDescription: Faster operation reading file

description: Faster operation reading file


code:
lines = []
for line in url_text:
    if line.startswith('>'):
        lines.append(line) # or whatever else you wanted to add to the list
        print line[line.index(' ') : line.index('OS')]

rawDescription: Adding for-loop elements to a list

description: Adding for-loop elements to a list


code:
for elm in favs.getiterator():
    print elm.items()

rawDescription: Retrieving flickr favorites

description: Retrieving flickr favorites


rawDescription: Python speed up the code for reconstructing lists


code:
import itertools

class Sprocket:
    def __init__(self, x, frame, particle):
        self.x = x
        self.frame = frame
        self.particle = particle

data = [
    Sprocket(0,0,1),
    Sprocket(1,1,1),
    Sprocket(2,2,2),
    Sprocket(3,3,2),
]

#now we arrange them by particle.
arrange_func = lambda item: item.particle
data.sort(key=arrange_func)
for particle, sprockets in itertools.groupby(data, key=arrange_func):
    print "sprockets with particle {}:".format(particle)
    for sprocket in sprockets:
        print sprocket.x, sprocket.frame, sprocket.particle

rawDescription: How to arrange a dict by value, and back again?

description: Arrange a dict by value, and back again


code:
from BeautifulSoup import BeautifulSoup
import re

hello = """

CVE-2010-3718
CVE-2010-3718
CVE-2010-3718

"""

target = re.compile("CVE-\d+-\d+.html")
commentSoup = BeautifulSoup(hello)
atags = commentSoup.findAll(href=target)
for a in atags:
    match = re.findall(target, a['href'])[0]
    print match

rawDescription: Novice Python/Regex: pull strings between <a> tags using regex


code:
lst = [[1L, u'12 sheet', 0],
       [2L, u'4 sheet', 0],
       [3L, u'48 sheet', 0],
       [4L, u'6 sheet', 0],
       [5L, u'Busrear', 0],
       [6L, u'phonebox', 0],
       [7L, u'train', 0]]

def sortby(x):
    try:
        return int(x[1].split(' ')[0])
    except ValueError:
        return float('inf')

lst.sort(key=sortby)
print lst

rawDescription: Python sort list of list containing integer and string with integers inside


code:
for tag in soup.findAll():
    print tag.string

rawDescription: Removing a tag and its contents in xml using BeautifulSoup an lxml in Python


code:
parser.add_argument('--dict', nargs='*', type=str, default = [])
args = parser.parse_args(['--dict', 'name:man', 'address:kac', 'tags:don'])
args.dict = dict([arg.split(':') for arg in args.dict])
print args.dict

rawDescription: Python: Parse multiple datatypes using argparse


code:
class fibber(object):
    def __init__(self):
        self.c = None

    def __call__(self, n):
        result = []
        a, b = 0, 1
        while b < n:
            result.append(b)
            a, b = b, a+b
            self.c = result
        return result

fib = fibber()
f100 = fib(100)
print result
print fib.c

rawDescription: How to access a variable defined inside a function from out side?

description: Access a variable defined inside a function from out side


code:
import re
from bs4 import BeautifulSoup as Soup

soup = Soup("""Society/Project: Sai Sparsh

         Built-up  Area: 1005 Sq.Ft.
             @ Rs.6109/sq.ft""")

print re.sub('(\s{2,})', ' ', soup.text)

rawDescription: Scraping and stripping off child tags python


code:
class FileSystem():

    def __init__(self,filePath=None):
        self.children = []
        if filePath != None:
            try:
                self.name, child = filePath.split("/", 1)
                self.children.append(FileSystem(child))
            except (ValueError):
                self.name = filePath

    def addChild(self, filePath):
        try:
            thisLevel, nextLevel = filePath.split("/", 1)
            try:
                if thisLevel == self.name:
                    thisLevel, nextLevel = nextLevel.split("/", 1)
            except (ValueError):
                self.children.append(FileSystem(nextLevel))
                return
            for child in self.children:
                if thisLevel == child.name:
                    child.addChild(nextLevel)
                    return
            self.children.append(FileSystem(nextLevel))
        except (ValueError):
            self.children.append(FileSystem(filePath))

    def getChildren(self):
        return self.children

    def printAllChildren(self, depth = -1):
        depth += 1
        print "\t"*depth + "Name: "+ self.name
        if len(self.children) > 0:
            print "\t"*depth +"{ Children:"
            for child in self.children:
                child.printAllChildren(depth)
            print "\t"*depth + "}"

    def makeDict(self):
        if len(self.children) > 0:
            dictionary = {self.name:[]}
            for child in self.children:
                dictionary[self.name].append(child.makeDict())
            return dictionary
        else:
            return self.name

records = ["base/images/graphs/one.png", "base/images/tikz/two.png",
"base/refs/images/three.png", "base/one.txt", "base/chapters/two.txt"]

myFiles = FileSystem(records[0])
for record in records[1:]:
    myFiles.addChild(record)

print myFiles.makeDict()

rawDescription: Creating Nested Dictionary from File hierarchy


code:
import yaml
import json

s = "yamlstr"  # your yaml str
data = yaml.load(s)
jsondata = json.dumps(data)
print jsondata

rawDescription: How to parse this special config file in python?

description: Parse this special config file in python


code:
from bs4 import BeautifulSoup
import requests

headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

# initialize session
session = requests.Session()

# getting playlist
response = session.get('http://animedigitalnetwork.fr/video/naruto-shippuden', headers=headers)
soup = BeautifulSoup(response.content)
playlist = soup.find('a', {'data-playlist': True})['data-playlist']

# getting list of videos
url = 'http://animedigitalnetwork.fr/index.php?option=com_vodvideo&view=playlist&format=raw'
response = session.post(url, data={
    'playlist': playlist,
    'season': '',
    'order': 'DESC'
}, headers=headers)

soup = BeautifulSoup(response.content)
for video in soup.select('div.adn-video'):
    print video.a.get('title')

rawDescription: BeautifulSoup passing div

description: BeautifulSoup passing div


code:
from types import ModuleType

with open("A/M.py") as a:
    A = ModuleType('A')
    exec a.read() in A.__dict__

with open("B/M.py") as b:
    B = ModuleType('B')
    exec b.read() in B.__dict__

with open("C/M.py") as c:
    C = ModuleType('C')
    exec c.read() in C.__dict__

rawDescription: Importing a python module by path

description: Importing a python module by path


code:
from nltk.tokenize import word_tokenize
from nltk.tag import pos_tag

sentences = ['alice loves to read crime novels.', 'she also loves to play chess with him']
sentences_with_pronouns = []

for sentence in sentences:
    words = word_tokenize(sentence)
    for word in words:
        word_pos = pos_tag([word])
        if word_pos[0][1] == 'PRP':
            sentences_with_pronouns.append(sentence)
            break

print sentences_with_pronouns

rawDescription: How can I take a few paragraphs of text, see if any sentence has a pronoun and select all those sentences to make a new paragraph?

description: Take a few paragraphs of text, see if any sentence has a pronoun and select all those sentences to make a new paragraph


code:
xmlFile = minidom.parse( FILE_PATH )

for script in SCRIPTS:

    newScript = xmlFile.createElement("script")

    newScript.setAttribute("name"  , script.name)
    newScript.setAttribute("action", script.action)

    newScriptText = xmlFile.createTextNode( script.description )

    newScript.appendChild( newScriptText  )
    xmlFile.childNodes[0].appendChild( newScript )

print xmlFile.toprettyxml()

rawDescription: add element with attributes in minidom python

description: Add element with attributes in minidom python


code:
paragraph = "five hundred to one hundred words separated by spaces"
array_of_strings = set(['hundred', 'spaces', ])  # make a set..
print set(paragraph.split()).intersection(array_of_strings)

rawDescription: rough estimate time it takes to do string comparisons Python

description: Rough estimate time it takes to do string comparisons Python


code:
# make sure these are all lowercase
cursewords = ['javascript', 'php', 'windows']
input_lower = input.lower()
if any(curseword in input_lower for curseword in cursewords):
    print 'onoes'

rawDescription: How to find if part of a list is in str

description: Find if part of a list is in str


code:
#!/usr/bin/env python
import os
import pty
import termios

class Bot:

  def __init__(self, name, program):
    self.name = name

    # Fork a process in a pseudo-terminal
    self._pid, self._fd = pty.fork()

    if self._pid == 0:
      # Child process, replace with program
      os.execvp(program, [program])

    # Turn off echoing for child file descriptor, otherwise it will spew the
    # child's output to the parent's STDOUT.
    attribs = termios.tcgetattr(self._fd)
    attribs[3] = attribs[3] & ~termios.ECHO
    termios.tcsetattr(self._fd, termios.TCSANOW, attribs)

  def speak(self, bot):
    output = self.read()
    bot.write(output)

    print '{} -> {}: {}'.format(self.name, bot.name, output)

  def read(self):
    return os.read(self._fd, 1024).strip()

  def write(self, line):
    os.write(self._fd, line + "\n")

if __name__ == '__main__':

  bot1 = Bot('Bot1', './bot1.py')
  bot2 = Bot('Bot2', './bot2.py')

  # Bot1 -> Bot2: What is your name?
  bot1.speak(bot2)

  # Bot2 -> Bot1: Bot2
  bot2.speak(bot1)

  # Bot1 -> Bot2: Hello Bot2, my name is Bot1
  bot1.speak(bot2)

  # Bot2 -> Bot1: Hello Bot1
  bot2.speak(bot1)

rawDescription: Python: Communicate with always running subprocesses


code:
arrange_func = lambda item: item.particle
data.sort(key=arrange_func)
d = {}
for particle, sprockets in itertools.groupby(data, key=arrange_func):
    d[particle] = {"X":[], "Frame":[]}
    for sprocket in sprockets:
        d[particle]["X"].append(sprocket.x)
        d[particle]["Frame"].append(sprocket.frame)

print d

description: Arrange a dict by value, and back again


code:
for pos_X in program_X:

    #find the position with 375
    if pos_X == '375':
       print program_time
       break

rawDescription: code keep firing like 7 times when using the for loops

description: Code keep firing like 7 times when using the for loops


code:
len(u'à')  # a single code point
len('à')   # by default utf-8 -> takes two bytes
len(u'à'.encode('utf-8'))
len(u'à'.encode('latin1'))  # in latin1 it takes one byte
print u'à'.encode('utf-8')  # terminal encoding is utf-8
print u'à'.encode('latin1') # it cannot understand the latin1 byte

rawDescription: Python str vs unicode types

description: Python str vs unicode types


code:
def test(a):
    b = Person('b')
    print "{a.name} joins {b.name}".format(**locals())

rawDescription: Passing current context to str.format?

description: Passing current context to str.format


code:
def do_task(key):
    try:
        return perform_scan.delay(key)
    except:
        print "failed"

def main():
    executor = concurrent.futures.ProcessPoolExecutor(10)
    futures = [executor.submit(do_task, key) for key in key_list]
    # If you want to do anything with these results, you probably want
    # a loop around concurrent.futures.as_completed or similar here,
    # rather than waiting for them all to finish, ignoring the results,
    # and printing the number of them.
    concurrent.futures.wait(futures)
    print len(futures)

rawDescription: My queue is empty after multiprocessing.Process instances finish


code:
a = "    indented string"
leading_spaces = len(a) - len(a.lstrip())
print leading_spaces

rawDescription: Python check string indentation

description: Python check string indentation


code:
df1 = DataFrame({'a':a})
df2 = DataFrame({'aa':aa})
df3 = DataFrame({'apol':apol})
df=df1.append([df2,df3]).sort_index()
print df.resample('Q-APR',loffset='-1m').T

rawDescription: Using resample to align multiple timeseries in pandas


code:
import  wx

if wx.Platform == '__WXMSW__':
    from wx.lib.flashwin import FlashWindow

class MyPanel(wx.Panel):
    def __init__(self, parent, id):
        wx.Panel.__init__(self, parent, -1)
        self.pdf = None

        sizer = wx.BoxSizer(wx.VERTICAL)
        btnSizer = wx.BoxSizer(wx.HORIZONTAL)

        self.flash = FlashWindow(self, style=wx.SUNKEN_BORDER)
        sizer.Add(self.flash, proportion=1, flag=wx.EXPAND)
        #sizer.Hide(0)

        self.SetSizer(sizer)
        self.SetAutoLayout(True)
        print "Importing Flash..."
        self.flash.LoadMovie(0, raw_input('Copy link for flash: '))
        #Used to load a flash file. You may also give a location of a specific file on disk.
        print "Done."

app = wx.PySimpleApp()
# create window/frame, no parent, -1 is default ID, title, size
# change size as needed
frame = wx.Frame(None, -1, "Flash Stream", size = (500, 400))
# make instance of class, -1 is default ID
MyPanel(frame, -1)
# show frame
frame.Show(True)
#comment if you don't want to see the ui
print "Started"
# start event loop
app.MainLoop()

rawDescription: Generating Links to Youtube Audio

description: Generating Links to Youtube Audio


code:
class Foo(object):
    def __init__(self):
        pass
    def my_method(self):
        print "foobar"

rawDescription: Rewrite a python script, injecting a method in each of the script's classes


code:
import numpy as np
from scipy.sparse import spdiags
from scipy.sparse.linalg import eigs

# create banded matrix
n = 30
A = spdiags((np.ones((n,1))*[-1,2,-1]).T, [-1,0,1], n, n).todense()
A[0,8] = 30

# EIGS: k closest eigenvalues to sigma
k = 10
sigma = 3.6766133
D = eigs(A, k, sigma=sigma, which='LM', return_eigenvectors=False)
D = D[::-1]
for x in D:
    print '{:.16f}'.format(x)

# EIG
ev,_ = np.linalg.eig(A)
idx = np.argsort(np.abs(ev - sigma))
ev = ev[idx[:k]]
for x in ev:
    print '{:.16f}'.format(x)

rawDescription: Using ARPACK solving eigenvalueproblem, but getting inconsistent results with Matlab


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

data = np.random.rand(500,500)

# fig1 will save the contourf as a vector
fig1,ax1 = plt.subplots(1)
ax1.contourf(data)
fig1.savefig('vector.pdf')

# fig2 will save the contourf as a raster
fig2,ax2 = plt.subplots(1)
ax2.contourf(data,zorder=-20)
ax2.set_rasterization_zorder(-10)
fig2.savefig('raster.pdf')

# Show the difference in file size. "os.stat().st_size" gives the file size in bytes.
print os.stat('vector.pdf').st_size
# 15998481
print os.stat('raster.pdf').st_size
# 1186334

rawDescription: Reducing size of vectorized contourplot

description: Reducing size of vectorized contourplot


code:
import inspect, dis, opcode

def check_status():

    try:
        frame = inspect.currentframe().f_back
        next_opcode = opcode.opname[ord(frame.f_code.co_code[frame.f_lasti+3])]
        if next_opcode == "POP_TOP":
            # or next_opcode == "RETURN_VALUE":
            # include the above line in the if statement if you consider "return check_status()" to be assignment
            print "I was not assigned"
            print "Pretty printer status check 0.02v"
            print "NOTE: This is so totally not written for giant robots"
            return
    finally:
        del frame

    # do normal routine

    info = {'cond_op': 1, 't_canoncharge': 1342, 'stage_booster': 5}

    return info

# no assignment
def test1():
    check_status()

# assignment
def test2():
    a = check_status()

# could be assignment (check above for options)
def test3():
    return check_status()

# assignment
def test4():
    a = []
    a.append(check_status())
    return a

rawDescription: Is there a way to check whether function output is assigned to a variable in Python?


code:
#!/usr/bin/env python2.6
from lxml.html import fromstring, tostring
from lxml.html import builder as E
fragment = """\

This is div.

"""

div = fromstring(fragment)
print tostring(div)
#

#
This is div.

#

div.replace(div.get_element_by_id('inner'), E.DIV('Hello ', E.B('world!')))
print tostring(div)
#

#
Hello world!

rawDescription: Python: Injecting HTML content into a tag using `lxml.html`