code:
# class for tree nodes
class Node:
    def __init__(self,start):
        self.start = start
        self.children = []
        self.text = ''

# make a tree
def make_tree(s):
    stack = []
    nodes = []
    cur = None
    root = None

    for i, c in enumerate(s):
        if c == '(':
            cur = Node(i)
            if stack:
                stack[-1].children.append(cur)
            stack.append(cur)

            if root is None:
                root = cur

        elif c == ')' and stack:
            topnode = stack.pop()

            text = s[topnode.start + 1: i]
            topnode.text = text

    return root

# list of leaves
def list_of_leaves(node):
    result = []
    for child in node.children:
        result.extend(list_of_leaves(child))
    if not result:
        return [node]

    return result

s = """(ROOT
  (SQ (VBD Did)
    (NP (NNP Matt))
    (VP (VB win)
      (NP (DT the) (NNS men) (NN slalom)))
    (. ?)))"""

root = make_tree(s)

for node in list_of_leaves(root):
    print node.text

rawDescription: How do I reach the leaves of the tree generatod by a stanford parser in python?

description: Reach the leaves of the tree generatod by a stanford parser in python


code:
from BeautifulSoup import BeautifulSoup as soupy
from urllib import urllib
html = urllib.urlopen(YOUR_TWITTER_URL).read()
soup = soupy(html)
for tweet in soup.find('ol',attrs={'class':'stream-items'}).findAll('li'):
     print tweet.find('p').text

rawDescription: crawling twitter using urllib instead of twitter api

description: Crawling twitter using urllib instead of twitter api


code:
html_doc='''

Time

14:00

17:00

Temperature

27.5

27.8

Time

8:00

11:00

Temperature

27.5

27.8

'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc, 'html.parser')
result={}
days_conut=0
for datas in soup.findAll('div', attrs = {'id':'hour3'}):
    for dates in datas('div',{'class':'row first'}):

        for temp in datas('div',{'class':'row wd'}):
            lst_of_time=dates.text.split()[1:]
            lst_of_temp=temp.text.split()[1:]
            count=0
            result['day'+str(days_conut)]=[]
            for i in lst_of_temp:
              result['day'+str(days_conut)].append({'time':lst_of_time[count],'temperature':lst_of_temp[count]})
              count=count+1
        days_conut=days_conut+1

print result

rawDescription: How can I use bs4 to get multiple nested div values and output in a json format?

description: Use bs4 to get multiple nested div values and output in a json format


code:
with open(__file__) as f:
    print "I AM %d LINES LONG"%len(list(f))

rawDescription: count the lines of a program in python

description: Count the lines of a program in python


code:
import logging
import pika
import Queue
import sys
import threading
import time
from functools import partial
from pika.adapters import SelectConnection, BlockingConnection
from pika.exceptions import AMQPConnectionError
from pika.reconnection_strategies import SimpleReconnectionStrategy

log = logging.getLogger(__name__)

DEFAULT_PROPERTIES = pika.BasicProperties(delivery_mode=2)

class Broker(object):

    def __init__(self, parameters, on_channel_open, name='broker'):
        self.parameters = parameters
        self.on_channel_open = on_channel_open
        self.name = name

    def connect(self, forever=False):
        name = self.name
        while True:
            try:
                connection = SelectConnection(
                    self.parameters, self.on_connected)
                log.debug('%s connected', name)
            except Exception:
                if not forever:
                    raise
                log.warning('%s cannot connect', name, exc_info=True)
                time.sleep(10)
                continue

            try:
                connection.ioloop.start()
            finally:
                try:
                    connection.close()
                    connection.ioloop.start() # allow connection to close
                except Exception:
                    pass

            if not forever:
                break

    def on_connected(self, connection):
        connection.channel(self.on_channel_open)

def setup_submitter(channel, data_queue, properties=DEFAULT_PROPERTIES):
    def on_queue_declared(frame):
        # PROBLEM pika does not appear to have a way to detect delivery
        # failure, which means that data could be lost if the connection
        # drops...
        channel.confirm_delivery(on_delivered)
        submit_data()

    def on_delivered(frame):
        if frame.method.NAME in ['Confirm.SelectOk', 'Basic.Ack']:
            log.info('submission confirmed %r', frame)
            # increasing this value seems to cause a higher failure rate
            time.sleep(0)
            submit_data()
        else:
            log.warn('submission failed: %r', frame)
            #data_queue.put(...)

    def submit_data():
        log.info('waiting on data queue')
        data = data_queue.get()
        log.info('got data to submit')
        channel.basic_publish(exchange='',
                    routing_key='sandbox',
                    body=data,
                    properties=properties,
                    mandatory=True)
        log.info('submitted data to broker')

    channel.queue_declare(
        queue='sandbox', durable=True, callback=on_queue_declared)

def blocking_submitter(parameters, data_queue,
        properties=DEFAULT_PROPERTIES):
    while True:
        try:
            connection = BlockingConnection(parameters)
            channel = connection.channel()
            channel.queue_declare(queue='sandbox', durable=True)
        except Exception:
            log.error('connection failure', exc_info=True)
            time.sleep(1)
            continue
        while True:
            log.info('waiting on data queue')
            try:
                data = data_queue.get(timeout=1)
            except Queue.Empty:
                try:
                    connection.process_data_events()
                except AMQPConnectionError:
                    break
                continue
            log.info('got data to submit')
            try:
                channel.basic_publish(exchange='',
                            routing_key='sandbox',
                            body=data,
                            properties=properties,
                            mandatory=True)
            except Exception:
                log.error('submission failed', exc_info=True)
                data_queue.put(data)
                break
            log.info('submitted data to broker')

def setup_receiver(channel, data_queue):
    def process_data(channel, method, properties, body):
        log.info('received data from broker')
        data_queue.put(body)
        channel.basic_ack(delivery_tag=method.delivery_tag)

    def on_queue_declared(frame):
        channel.basic_consume(process_data, queue='sandbox')

    channel.queue_declare(
        queue='sandbox', durable=True, callback=on_queue_declared)

if __name__ == '__main__':
    if len(sys.argv) != 2:
        print 'usage: %s RABBITMQ_HOST' % sys.argv[0]
        sys.exit()

    format=('%(asctime)s %(levelname)s %(name)s %(message)s')
    logging.basicConfig(level=logging.DEBUG, format=format)

    host = sys.argv[1]
    log.info('connecting to host: %s', host)
    parameters = pika.ConnectionParameters(host=host, heartbeat=True)
    data_queue = Queue.Queue(0)
    data_queue.put('message') # prime the pump

    # run submitter in a thread

    setup = partial(setup_submitter, data_queue=data_queue)
    broker = Broker(parameters, setup, 'submitter')
    thread = threading.Thread(target=
         partial(broker.connect, forever=True))

    # uncomment these lines to use the blocking variant of the submitter
    #thread = threading.Thread(target=
    #    partial(blocking_submitter, parameters, data_queue))

    thread.daemon = True
    thread.start()

    # run receiver in main thread
    setup = partial(setup_receiver, data_queue=data_queue)
    broker = Broker(parameters, setup, 'receiver')
    broker.connect(forever=True)

rawDescription: RabbitMQ, Pika and reconnection strategy


code:
import csv
doc= csv.reader(open('file.csv','rb'))

# Build the lists.
first_col = []
second_col = set()
for row in doc:
    first_col.append(row[0])
    second_col.add(row[1])

# Now actually do the comparison.
for item in first_col:
    if item in second_col:
        print item

rawDescription: if row[0] in row[1] print row

description: If row[0] in row[1] print row


code:
def right_justify(s):
    print "%70s" % s

rawDescription: prints the string with enough leading spaces?

description: Prints the string with enough leading spaces


code:
import readline
# I am using Ctrl+K to insert line break
# (dont know what symbol is for shift+enter)
readline.parse_and_bind('C-k: "#\n"')
text = []
line = "#"
while line and line[-1]=='#':
  line = raw_input("> ")
  if line.endswith("#"):
    text.append(line[:-1])
  else:
    text.append(line)

# all lines are in "text" list variable
print "\n".join(text)

rawDescription: Shift + Return to insert linebreak in python


code:
from z3 import *

# Return the first "M" models of formula list of formulas F
def get_models(F, M):
    result = []
    s = Solver()
    s.add(F)
    while len(result) < M and s.check() == sat:
        m = s.model()
        result.append(m)
        # Create a new constraint the blocks the current model
        block = []
        for d in m:
            # d is a declaration
            if d.arity() > 0:
                raise Z3Exception("uninterpreted functions are not supported")
            # create a constant from declaration
            c = d()
            if is_array(c) or c.sort().kind() == Z3_UNINTERPRETED_SORT:
                raise Z3Exception("arrays and uninterpreted sorts are not supported")
            block.append(c != m[d])
        s.add(Or(block))
    return result

# Return True if F has exactly one model.
def exactly_one_model(F):
    return len(get_models(F, 2)) == 1

x, y = Ints('x y')
s = Solver()
F = [x >= 0, x <= 1, y >= 0, y <= 2, y == 2*x]
print get_models(F, 10)
print exactly_one_model(F)
print exactly_one_model([x >= 0, x <= 1, y >= 0, y <= 2, 2*y == x])

# Demonstrate unsupported features
try:
    a = Array('a', IntSort(), IntSort())
    b = Array('b', IntSort(), IntSort())
    print get_models(a==b, 10)
except Z3Exception as ex:
    print "Error: ", ex

try:
    f = Function('f', IntSort(), IntSort())
    print get_models(f(x) == x, 10)
except Z3Exception as ex:
    print "Error: ", ex

rawDescription: (Z3Py) checking all solutions for equation


code:
import os, glob
magic='.log'
for file in glob.glob(os.path.join(mydir, '*%s' % magic)):
    dirname, filename = os.path.split(file)
    base=filename[:-len(magic)] # if you use this very often, it is faster to use a variable "len_magic"
    print dirname, base

rawDescription: python get file folder location and file with glob

description: Python get file folder location and file with glob


code:
import os

searchdir = r'C:\root_dir' # traversal starts in this directory (the root)

for root, dirs, files in os.walk(searchdir):
    for name in files:
        (base, ext) = os.path.splitext(name) # split base and extension
        print base, ext

rawDescription: All Files in Dir & Sub-Dir

description: All Files in Dir & Sub-Dir


code:
def floatToTwosComplementDecimal(intBits,decBits,number):
    if decBits == 0:
        mx = pow(2,intBits-1) - 1 # maximum number
    else:
        mx = pow(2,intBits-1) - pow(2,-1*decBits) # maximum number
    mn = -1*pow(2,intBits-1) # minimum number
    if number > mx:
        print "number:" + str(number) + " has been truncated to: " + str(mx)
        number = mx
    elif number < mn:
        print "number:" + str(number) + " has been truncated to: " + str(mn)
        number = mn
    n = []
    m = 0
    if number < 0:
        n.append(1)
        m = -1*pow(2,intBits-1)
    else:
        n.append(0)
        m = 0
    for i in reversed(range(intBits-1)):
        m1 = m + pow(2,i)
        if number < m1:
            n.append(0)
        else:
            n.append(1)
            m = m1
    for i in range(1,decBits+1):
        m1 = m + pow(2,-1*i)
        if number < m1:
            n.append(0)
        else:
            n.append(1)
            m = m1
    return string.join([str(i) for i in n], '')

def twosComplementDecimalToFloat(intBits,decBits,binString):
    n = 0.0
    if binString[0] == "1":
        n = -1*pow(2,intBits-1)
    for i in range(intBits-1):
        n += int(binString[intBits-1-i])*pow(2,i)
    for i in range(1,decBits+1):
        n += int(binString[intBits-1+i])*pow(2,-1*i)
    return n

rawDescription: How to convert between floats and decimal twos complement numbers in Python?

description: Convert between floats and decimal twos complement numbers in Python


code:
tags = [('album', [u'Singles']), ('artist', [u'Led Zeppelin']), ('title', [u'Kashmir'])]
print ', '.join('{} {}'.format(el[0], el[1][0]) for el in tags)
# album Singles, artist Led Zeppelin, title Kashmir

rawDescription: Cleaning up a varied list that contains strings and tuples with unicode


code:
def leading(a, b):
    # generate digit pairs a=123, b=456 -> [(1, 4), (2, 5), (3, 6)]
    zip_digits = zip(str(a), str(b))
    zip_digits = map(lambda (x,y):(int(x), int(y)), zip_digits)

    # this ignores problems where the last matching digits are 0 and 9
    # leading (12000, 12999) is same as leading(12, 12)
    while(zip_digits[-1] == (0,9)):
        zip_digits.pop()

    # start recursion
    return compute_leading(zip_digits)

def compute_leading(zip_digits):
    if(len(zip_digits) == 1):   # 1 digit case is simple!! :)
        (a,b) = zip_digits.pop()
        return range(a, b+1)

    #now we partition the problem
    # given leading(123,456) we decompose this into 3 problems
    # lows    -> leading(123,129)
    # middle  -> leading(130,449) which we can recurse to leading(13,44)
    # highs   -> leading(450,456)

    last_digits = zip_digits.pop()
    low_prefix  = reduce(lambda x, y : 10 * x + y, [tup[0] for tup in zip_digits]) * 10     # base for lows e.g. 120
    high_prefix = reduce(lambda x, y : 10 * x + y, [tup[1] for tup in zip_digits]) * 10     # base for highs e.g. 450
    lows = range(low_prefix + last_digits[0], low_prefix + 10)
    highs = range(high_prefix + 0, high_prefix + last_digits[1] + 1)

    #check for boundary cases where lows or highs have all ten digits
    (a,b) = zip_digits.pop()    # pop last digits of middle so they can be adjusted
    if len(lows) == 10:
        lows = []
    else:
        a = a + 1

    if len(highs) == 10:
        highs = []
    else:
        b = b - 1

    zip_digits.append((a,b))    # push back last digits of middle after adjustments

    return lows + compute_leading(zip_digits) + highs       # and recurse - woohoo!!

print leading(199,411)

print leading(2169800, 2171194)

print leading(1000, 1452)

rawDescription: leading number groups between two numbers

description: Leading number groups between two numbers


code:
def get_input():
    return raw_input('get file: ')

if __name__ == '__main__':
    print get_input()

rawDescription: How to use 'def' to get an input value

description: Use 'def' to get an input value


code:
emails = browser.find_elements_by_tag_name("a")

for x in range(0,len(emails)):
    code = emails[x].get_attribute("onclick")
    email = code[4:len(code)-17]
    print email

rawDescription: selenium python: How do I find every email on a webpage?

description: Selenium python: How do I find every email on a webpage


code:
with open('test.in', 'r') as f:
    r = []
    map(lambda (a,b): [0, [r.append(0) for i in xrange(a - len(r))]] and r.append(b), sorted([(int(l.split(' ')[0]), float(l.split(' ')[-1])) for l in f], key=lambda (a,b): a))

rawDescription: Python: Create Array from Indexed List

description: Python: Create Array from Indexed List


code:
class ControlPanel(HasTraits):

    keithley3706Asettings = Instance(Keithley3706A_module.Keithley3706ASettings, ())

    k3706A = Instance(Keithley3706A_module.Keithley3706A, ())

    start = Button("Start Measurements")
    clear_3706A_display = Button("Clear K3706A Display")

    view = View(UItem('start'),
                UItem('clear_3706A_display'),
                Item('keithley3706Asettings', style='simple'))

    def _start_fired(self):
        print "hello %s" % self.keithley3706Asettings.display
        self.k3706A.message(self.keithley3706Asettings.display)

    def _clear_3706A_display_fired(self):
        self.k3706A.clear()

rawDescription: Why attribute doesn't update in traitsui on user input


code:
import os
while(1):
    ping = os.popen('ping www.google.com -n 1')
    result = ping.readlines()
    msLine = result[-1].strip()
    print msLine.splot(' = ')[-1]

rawDescription: How to ping an ip and get only the ms in the Tk with Python?

description: Ping an ip and get only the ms in the Tk with Python


code:
from pprint import pprint
import praw

r = praw.Reddit(user_agent='praw_overflow')
user = r.get_redditor('Sariel007')
submissions = user.get_submitted()

self_texts = []
for link in submissions:
    self_texts.append(link.selftext)

print self_texts

rawDescription: How do I use PRAW and python to retrieve reddit post data from a certain user?

description: Use PRAW and python to retrieve reddit post data from a certain user


code:
def uescape(text):
    print repr(text)
    escaped_chars = []
    for c in text:
        if (ord(c) < 32) or (ord(c) > 126):
            c = '&{};'.format(htmlentitydefs.codepoint2name[ord(c)])
        escaped_chars.append(c)
    return ''.join(escaped_chars)

rawDescription: Python throws UnicodeEncodeError although I am doing str.decode(). Why?


code:
for i in range(15):
    print '{}{} {}{}'.format(*format(i, '04x')) #

rawDescription: represent counting variable in 4 digit hex seperated by a space

description: Represent counting variable in 4 digit hex seperated by a space


code:
def preprocess(file):
    #exporting from MySQL query browser adds a weird
    #character to the result set, remove it
    #so the XML parser can read the data
    print "in preprocess"
    lines = map(lambda line: line.replace("\b", ""), file)

    #go to the beginning of the file
    file.seek(0);

    #overwrite with correct data
    file.writelines(lines)
    sys.exit()

'''Entry into the program'''
#test the file to see if processing is needed before parsing
for line in xml_file:
    p = re.compile("\\b")
    if(p.search(line)): ####Changed to p.search here
        processing = True
        break #only one match needed

if processing:
    preprocess(xml_file)

rawDescription: Overwriting XML file

description: Overwriting XML file


code:
jsonlist = ['foo.json', 'bar.json']
print [item.replace(".json", "") for item in jsonlist]
# ['foo', 'bar']

rawDescription: Avoid using two arrays to make a simple string change


code:
from datetime import datetime

startTime = datetime.now()

a=2**1000000-3
b=a/13

elapsedTime = datetime.now() - startTime

print "Elapsed time %s\n Number: %s" % (elapsedTime, b)

rawDescription: Why is it much slower to print an answer to a calculation when compared to just computing it?


code:
def donuts(count):
    if count < 10:
     return 'Number of donuts: ' + str(count)
    else: return 'Number of donuts: many'

print donuts(8)

rawDescription: Why is python shell not printing

description: Why is python shell not printing


code:
my_string = "StopAndSmellTheRoses"
i = 0
result = ""
for c in my_string:
    if c.isupper() and i > 0:
        result += " "
        result += c.lower()
    else:
        result += c
    i += 1

print result

rawDescription: word separator for python coding

description: Word separator for python coding


code: print all(item.x == some_value for item in my_list)

rawDescription: Python - Boolean compare property for all elements in a list of objects


code:
import multiprocessing, time

def task(args):
    count = args[0]
    queue = args[1]
    for i in xrange(count):
        queue.put("%d mississippi" % i)
    return "Done"

def main():
    manager = multiprocessing.Manager()
    q = manager.Queue()
    pool = multiprocessing.Pool()
    result = pool.map_async(task, [(x, q) for x in range(10)])
    time.sleep(1)
    while not q.empty():
        print q.get()
    print result.get()

if __name__ == "__main__":
    main()

rawDescription: How do you pass a Queue reference to a function managed by pool.map_async()?

description: Pass a Queue reference to a function managed by pool.map_async()


code:
import re

regex = '''<item>
<obj1>grab1</obj1>
<obj2>text<obj2>
...
</item>'''

pattern = re.compile(regex)

with open('data.dat') as searchfile:
    filetext = searchfile.read()
    text = pattern.findall(filetext)
    print text

rawDescription: Using regex to grab values from a multi-line string in python


code:
if request.method == "POST":
    image = request.files['myfile'] #myfile is name of input tag
    config ={
            'album':album,
            'name':'Catastrophe!',
            'title':'Catastrophe!'
    }
    print "uploading image..."
    filename = secure_filename(image.filename)
    file.save(os.path.join('/home/suraj/Pictures', filename))
    print os.path.realpath(image.filename)

rawDescription: upload image using image Path in flask

description: Upload image using image Path in flask


code:
class Holding:
    def __init__(self, companyName, numShares, sharePrice):
        self.companyName = companyName
        self.numShares = numShares
        self.sharePrice = sharePrice
    def getValue(self):
        return self.numShares * self.sharePrice

portfolio = {'AMP':Holding('AMP', 1000, 2.5), 'ANZ':Holding('ANZ', 2000, 17.0), 'BHP':Holding('BHP', 500, 54.30)}

print portfolio['BHP'].sharePrice
# 54.3
print portfolio['AMP'].getValue()
# 2500.0

rawDescription: Python object oriented design concepts

description: Python object oriented design concepts


code:
from lxml import etree

def buildXmlUpdate(dfrom, roomId, ldays):
    root = etree.Element("UpdateInventoryRequest")
    root.append(etree.Element("StartDate"))
    root[-1].text = dfrom
    root.append(etree.Element("RoomId"))
    root[-1].text = str(roomId)
    root.append(etree.Element("Data"))
    dataroot = root[-1]

    for item in ldays:
        dataroot.append(etree.Element("Availability"))
        dataroot[-1].text = str(item['avail'])
        dataroot.append(etree.Element("Price"))
        dataroot[-1].text = str(item['price'])

    return root

myroot = buildXmlUpdate('21/12/2015', 1, [{'avail': 1, 'price': 100}, {'avail': 3, 'price': 120}])
print etree.tostring(myroot, pretty_print=True)

rawDescription: Multiple results on a Xml stack with lml (Python)


code:
from bs4 import BeautifulSoup
import re
import requests

base_url = 'http://www.localstore.co.uk'
url = 'http://www.localstore.co.uk/stores/75061/dfs/'
res = requests.get(url)
soup = BeautifulSoup(res.text)

shops = []

links = soup.find_all('a', href=re.compile('.*\/store\/.*'))

for l in links:
    full_link = base_url + l['href']
    town = l['title'].split(',')[1].strip()
    res = requests.get(full_link)
    soup = BeautifulSoup(res.text)
    info = soup.find('span', attrs={"itemprop": "postalCode"})
    postalcode = info.text
    shops.append(dict(town_name=town, postal_code=postalcode))

print shops

rawDescription: Scraping data from href

description: Scraping data from href


code:
for satir in dosya.readlines():
  for o in olasilik:
    if ("%s\n" % o) == satir:
      print o

rawDescription: Text reading and list index out of range in Python


code:
#!/usr/bin/env python

import os
from glob import glob
from subprocess import check_output, CalledProcessError

def get_usb_devices():
    sdb_devices = map(os.path.realpath, glob('/sys/block/sd*'))
    usb_devices = (dev for dev in sdb_devices
        if 'usb' in dev.split('/')[5])
    return dict((os.path.basename(dev), dev) for dev in usb_devices)

def get_mount_points(devices=None):
    devices = devices or get_usb_devices() # if devices are None: get_usb_devices
    output = check_output(['mount']).splitlines()
    is_usb = lambda path: any(dev in path for dev in devices)
    usb_info = (line for line in output if is_usb(line.split()[0]))
    return [(info.split()[0], info.split()[2]) for info in usb_info]

if __name__ == '__main__':
    print get_mount_points()

rawDescription: how can the directory of a usb drive connected to a system be obtained?

description: How can the directory of a usb drive connected to a system be obtained


code:
import re
text ="""
Buffer Usage / Capacity left
100 % / 0 m	"""
result = re.search(r"Buffer Usage.*\n.*?>(\d{1,3}) % .+",text).group(1)
print result # 100

rawDescription: Regex to search HTML and find a number after the occurrence of a string in python


rawDescription: md5 to integer bits in python

description: Md5 to integer bits in python


code:
print "Welcome to the Receipt Program!"
seats = []
while True:
    seat = raw_input('Enter the value for the seat: ["q to quit"] ')
    if seat == 'q':
        break
    try:
        seats.append(float(seat))
    except ValueError:
        print "I'm sorry but {} isn't valid. Please try again.".format(seat)

print "*****"
print '$', sum(seats)

rawDescription: How to make 'seat' in user input returned as a float

description: Make 'seat' in user input returned as a float


code:
def open_file(self, treeview, path, column):
    model = treeview.get_model()
    iter = model.get_iter(path)
    filename = os.path.join(self.dirname, model.get_value(iter, 0))
    filestat = os.stat(filename)
    # print filename
    if stat.S_ISDIR(filestat.st_mode):
        new_model = self.make_list(filename)
        treeview.set_model(new_model)
    else:
        print filename + "is a file!!"
    return

rawDescription: Catch a click in pyGTK

description: Catch a click in pyGTK


code:
import sys
from PyQt4 import QtCore, QtGui

class MyWindow(QtGui.QWidget) :
    def __init__(self):
        QtGui.QWidget.__init__(self)
        tabs = QtGui.QTabWidget()
        tab1 = QtGui.QWidget()
        tab2 = QtGui.QWidget()
        tabs.addTab(tab1, "Tab 1")
        tabs.addTab(tab2, "Tab 2")
        layout = QtGui.QVBoxLayout()
        layout.addWidget(tabs)
        self.setLayout(layout)
        self.setMouseTracking(True)

    def setMouseTracking(self, flag):
        def recursive_set(parent):
            for child in parent.findChildren(QtCore.QObject):
                try:
                    child.setMouseTracking(flag)
                except:
                    pass
                recursive_set(child)
        QtGui.QWidget.setMouseTracking(self, flag)
        recursive_set(self)

    def mouseMoveEvent(self, event):
        print 'mouseMoveEvent: x=%d, y=%d' % (event.x(), event.y())

app = QtGui.QApplication(sys.argv)
window = MyWindow()
window.setFixedSize(640, 480)
window.show()
sys.exit(app.exec_())

rawDescription: QWidget::mouseMoveEvent not firing when cursor over child widget


code:
result = settings_w.configure_traits(kind="livemodal")

if result:
    print "The user pressed OK."
else:
    print "The user pressed Cancel or closed the window."

rawDescription: Reacting to a Button Pressed by the user in a EPD Traits view?


code:
import lxml.etree as et
tree = et.XML(yourxml)
print tree.nsmap

rawDescription: Python ElementTree - print out namespace definitions?


code:
import re

def replacement_func(match, repl_pattern):
    match_str = match.group(0)
    repl = ''.join([r_char if m_char.islower() else r_char.upper()
                   for r_char, m_char in zip(repl_pattern, match_str)])
    repl += repl_pattern[len(match_str):]
    return repl

input_str = "myStrIngFullOfStUfFiWannAReplaCE_StUfFs"
print re.sub('stuff',
             lambda m: replacement_func(m, 'banana'),
             input_str, flags=re.I)

rawDescription: Best way to do a case insensitive replace but match the case of the word to be replaced?

description: Do a case insensitive replace but match the case of the word to be replaced


code:
regex = re.compile("(?:Dresses)|(?:Wallets)|(?:Pumps)")
print regex.findall(c_raw)

rawDescription: Python Regex Search for three terms

description: Python Regex Search for three terms


code:
from collections import deque

class BinaryTree:
    def __init__(self, data, left = None, right = None):
        self.key = data
        self.left = left
        self.right  = right

    def insert_left(self, data):
        self.left = BinaryTree(data, left=self.left)

    def insert_right(self, data):
        self.right = BinaryTree(data, right=self.right)

    def get_left_subtree(self):
        return self.left

    def get_right_subtree(self):
        return self.right

    def set_value(self, val):
        self.key = val

    def get_value(self):
        return self.key

    def create_string(self, indent):
        string = str(self.key) + '---+'
        if self.left:
            string += '\n(l)' + indent + self.left.create_string(indent + '    ')
        if self.right:
            string += '\n(r)' + indent + self.right.create_string(indent + '    ')
        return string

    def __str__(self):
        return self.create_string('  ')

    def return_list(self, templist):
        templist.append(self.key)
        if self.left is None:
            templist.append(None)
        else:
            self.left.return_list(templist)
        if self.right is None:
            templist.append(None)
        else:
            self.right.return_list(templist)

def return_b_list(tree,templist,queue):
    if tree is None:
        return;
    queue.append(tree)
    while len(queue) !=0:
        node = queue.popleft()
        if node is None:
            templist.append(None)
        else:
            templist.append(node.key)
            queue.append(node.left)
            queue.append(node.right)

def main():
    tree = BinaryTree(3)
    tree.insert_left(29)
    tree.insert_right(4)
    right = tree.get_right_subtree()
    left = tree.get_left_subtree()
    left.insert_left(26)
    right.insert_right(2)
    right2 = right.get_right_subtree()
    right2.insert_left(9)
    templist = []
    queue = deque() # you should do a from collections import deque
    return_b_list(tree,templist,queue)
    print tree.create_string(' ')
    print templist

main()

rawDescription: printing out python list from python binary tree

description: Printing out python list from python binary tree


code:
d1={'H':'Z','E':'P','L':'O','O':'J'}
def encrypt(table,string):
    encrypted=""
    for c in string:
        encrypted+=table[c]
    return encrypted

print encrypt(d1,"HELLO")

rawDescription: Missing letter from encryption

description: Missing letter from encryption


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

rawDescription: subprocess ignores bufsize argument

description: Subprocess ignores bufsize argument


code:
import re
p = re.compile(ur'\[description\]:((?:.+\n?)*)')
test_str = u" [type]: mail\n [category]: Values\n [service]: testing\n [description]: Testing out automapping of email\n Line break Testing out automapping of email\n Line break Testing out automapping of email"
subst = u""

result = re.sub(p, subst, test_str)

re.search(p, test_str)

rawDescription: Python/Jython parse e-mail

description: Python/Jython parse e-mail


code:
import os
import time
fileName = 'test'
originalTime = os.path.getmtime(fileName)

while(True):
    if(os.path.getmtime(fileName) > originalTime):
        with open(fileName, 'r') as f:
            print "\n" + f.read(),
        originalTime = os.path.getmtime(fileName)
    time.sleep(0.1)

rawDescription: Read extern file and wait for changes in Python


code:
from Tkinter import *
import battleEngine
import openingSequence
from classes import Pokemon
from classes import movesList

def donothing():
    print "Doesn't do anything."

class gameWindow(Frame):
    def displayMenu(self):
        gameMenu = Menu()
        fileMenu = Menu(gameMenu, tearoff=0)
        fileMenu.add_command(label="New Game", command=donothing)
        fileMenu.add_command(label="Load Game", command=donothing)
        fileMenu.add_command(label="Save Game", command=donothing)
        fileMenu.add_command(label="Save Game as...", command=donothing)
        fileMenu.add_command(label="Exit", command=exit())

    def __init__(self):
        self.displayMenu()

inGame = gameWindow()

inGame.mainloop()

rawDescription: Class has no attribute 'tk'

description: Class has no attribute 'tk'


rawDescription: How can I split a list of lists based on a specific condition in Python?

description: Split a list of lists based on a specific condition in Python


code:
s = "1 2 3 4 5"
print [int(i)+1 for i in s.split()]

rawDescription: Python map each integer within input to int


code:
import _winreg
from _winreg import ConnectRegistry, OpenKey, CloseKey, QueryInfoKey, SetValueEx
print r"*** Reading from SYSTEM\CurrentControlSet\services\NetBT\Parameters ***"
aReg = ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE)
aKey = OpenKey(aReg, "SYSTEM\CurrentControlSet\services\NetBT\Parameters")
for i in range(_winreg.QueryInfoKey(aKey)[1]):
    try:
        n, v, t = _winreg.EnumValue(aKey, i)
        print i, n, v, t
    except EnvironmentError:
        print "Encountered problems reading the Registry..."
        break
_winreg.CloseKey(aKey)
print r"*** WRiting to SYSTEM\CurrentControlSet\services\NetBT\Parameters ***"
aKey = OpenKey(aReg, r"SYSTEM\CurrentControlSet\services\NetBT\Parameters", 0, _winreg.KEY_WRITE)
try:
    SetValueEx(aKey, "SMBDeviceEnabled", 0, _winreg.REG_SZ, "Test")
except EnvironmentError:
    print "Encountered problems writing into the Registry..."
CloseKey(aKey)
CloseKey(aReg)

rawDescription: winreg in python 2.7

description: Winreg in python 2.7


code:
login('USERLOGIN', 'PASSWORD')

def login(username, password):
    loginPayload = {'login' : username}
    passPayload = {'password' : password}
    s = requests.Session()

    # POST the username
    url = 'https://www.card.com/client/factor2UserId.recip'
    postData = loginPayload.copy()
    response = s.post(url, postData)
    if response.status_code != requests.codes.ok:
        raise ValueError("Bad response in first pass %s" % response.status_code)
    postData.update(passPayload)
    tokenParam = token_search(response.text)
    if tokenParam is not None:
        postData.update(tokenParam)
    else:
        raise ValueError("No token value found!")
    # POST with password and the token
    url = 'https://www.card.com/client/siteLogonClient.recip'
    r = s.post(url, postData)
    return r

def token_search(resp_text):
    # uses regex to find the Token from the HTML
    patFinder2 = re.compile(r"name=\"(org.apache.struts.taglib.html.TOKEN)\"\s+value=\"(.+)\"",re.I)
    findPat2 = re.search(patFinder2, resp_text)

    # if the Token in found it turns it into a dictionary. and prints the dictionary
    # if no Token is found it prints "nothing found"
    if findPat2:
        newdict = dict(zip(findPat2.group(1).split(), findPat2.group(2).split()))
        return newdict
    else:
        print "No Token Found"
        return None

rawDescription: Python Request for Post in Secure website.


code:
from tamil import utf8
string = u"எஃகு"
letters = utf8.get_letters(string)
print(len(letters))
# 3. Not 4. 3.
print letters
# [u'\u0b8e', u'\u0b83', u'\u0b95\u0bc1']
for letter in letters:
    print letter
# எ
# ஃ
# கு

rawDescription: how to traverse a unicode tamil word character by charcter in python?

description: Traverse a unicode tamil word character by charcter in python


code:
def unit_disabled(func):
    def wrapper(func):
         func.__test__ = False
         return func

    return wrapper

@unit_disabled
def test_my_sample_test():
    assert 1 <> 1

def test2_my_sample_test():
    assert 1 <> 1

rawDescription: Disabling Python nosetests

description: Disabling Python nosetests


code:
def load_file(self):
    self.file_name = tkFileDialog.askopenfilename(filetypes=([('All files', '*.*'),
                                                           ('Text files', '*.txt'),
                                                           ('CSV files', '*.csv')]))
    print self.file_name

rawDescription: Passing name of file open with Tkinter button to another function


code:
from bs4 import BeautifulSoup
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://eve-central.com/home/quicklook.html?typeid=34')

html = driver.page_source
soup = BeautifulSoup(html)

# check out the docs for the kinds of things you can do with 'find_all'
# this (untested) snippet should find tags with a specific class ID
# see: http://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class
for tag in soup.find_all("a", class_="my_class"):
    print tag.text

rawDescription: How to retrieve the values of dynamic html content using Python

description: Retrieve the values of dynamic html content using Python


code:
firstStr = 'hello'
secondStr = 'world'
print my_str
print secondStr

rawDescription: strings in python

description: Strings in python


code:
import multiprocessing
import os
import time

def work(job):
    time.sleep(1)
    print "I am process", os.getpid(), "processing job", job

class StickyPool:
    def __init__(self, processes):
        self._inqueues = [multiprocessing.Queue() for ii in range(processes)]
        self._pool = [multiprocessing.Process(target=self._run, args=(self._inqueues[ii],)) for ii in range(processes)]
        for process in self._pool:
            process.start()

    def map(self, fn, args):
        for arg in args:
            ii = hash(arg) % len(self._inqueues)
            self._inqueues[ii].put((fn, arg))

    def _run(self, queue):
        while True:
            fn, arg = queue.get()
            fn(arg)

pool = StickyPool(3)
#pool = multiprocessing.Pool(3)

pool.map(work, [1,2,3,4,1,2,3,4,1,2,3,4])
time.sleep(4)

rawDescription: python multiprocessing pool assign object to worker

description: Python multiprocessing pool assign object to worker


code:
irofile = iter(rofile)
for line in irofile:
    print line
    if(line == 'foo'):
        line = next(irofile)  #BEWARE, This could raise StopIteration!
        print line

rawDescription: Python: For loop with files, how to grab the next line within forloop?


code:
import datetime
from email.MIMEText import MIMEText
body = "helloworld"
msg = MIMEText(body, 'plain', _charset='iso-8859-1')
msg['Subject'] = 'asdf'
msg['From'] = 'name <username@example.com>'
msg['Date'] = datetime.datetime.now().strftime('%a, %d %b %Y %H:%M:%S %z')
print msg

rawDescription: How do I change my Content-Transfer-Encoding header in Python?

description: Change my Content-Transfer-Encoding header in Python


code:
import urllib2
from urllib2 import URLError

url_common = 'http://apps.waterconnect.sa.gov.au/SiteInfo/Data/Site_Data/'
site_list=['4260514','4260512','4260519']
parameter_list=['ecrec','ecday','flowrec','flowcday']
for site in site_list:
    for parameter in parameter_list:
        try:
            url = url_common+'A'+site+'/'+'a'+site+'_'+parameter+'.zip'
            name ='A'+site+'_'+parameter+'.zip'
            req = urllib2.urlopen(url)
            with open(name,'wb') as fh:
                fh.write(req.read())
        except URLError,e:
            if e.code==404:
                print name + '  not found. moving on...'
                pass

rawDescription: download files from the internet using urllib issue

description: Download files from the internet using urllib issue


code:
class Foo(object):

    def __init__(self):
        self._dirty = False

    def __setattr__(self, key, value):
        if key != '_dirty':
            if isinstance(value, list):
                self.__dict__[key] = list_observer(value, self.observer(self))
            else:
                self.__dict__[key] = value
            self._make_dirty()

    def _make_dirty(self):
        self._dirty = True
        print('is dirty')

    def _not_dirty(self):
        self._dirty = False
        print('is no more dirty')

    class observer(object):
        """
        If a call to a method is made, this class prints the name of the method
        and all arguments.
        """

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

        def p(self, *args):
            print self.attr, args
            self.instance._make_dirty()

        def __getattr__(self, attr):
            self.attr = attr
            return self.p

class list_observer(list):
    """
    Send all changes to an observer.
    """

    def __init__(self, value, observer):
        list.__init__(self, value)
        self.set_observer(observer)

    def set_observer(self, observer):
        """
        All changes to this list will trigger calls to observer methods.
        """
        self.observer = observer

    def __setitem__(self, key, value):
        """
        Intercept the l[key]=value operations.
        Also covers slice assignment.
        """
        try:
            oldvalue = self.__getitem__(key)
        except KeyError:
            list.__setitem__(self, key, value)
            self.observer.list_create(self, key)
        else:
            list.__setitem__(self, key, value)
            self.observer.list_set(self, key, oldvalue)

    def __delitem__(self, key):
        oldvalue = list.__getitem__(self, key)
        list.__delitem__(self, key)
        self.observer.list_del(self, key, oldvalue)

    def __setslice__(self, i, j, sequence):
        oldvalue = list.__getslice__(self, i, j)
        self.observer.list_setslice(self, i, j, sequence, oldvalue)
        list.__setslice__(self, i, j, sequence)

    def __delslice__(self, i, j):
        oldvalue = list.__getitem__(self, slice(i, j))
        list.__delslice__(self, i, j)
        self.observer.list_delslice(self, i, oldvalue)

    def append(self, value):
        list.append(self, value)
        self.observer.list_append(self)

    def pop(self):
        oldvalue = list.pop(self)
        self.observer.list_pop(self, oldvalue)

    def extend(self, newvalue):
        list.extend(self, newvalue)
        self.observer.list_extend(self, newvalue)

    def insert(self, i, element):
        list.insert(self, i, element)
        self.observer.list_insert(self, i, element)

    def remove(self, element):
        index = list.index(self, element)
        list.remove(self, element)
        self.observer.list_remove(self, index, element)

    def reverse(self):
        list.reverse(self)
        self.observer.list_reverse(self)

    def sort(self, cmpfunc=None):
        oldlist = self[:]
        list.sort(self, cmpfunc)
        self.observer.list_sort(self, oldlist)

if __name__ == '__main__':
    f = Foo()

    #change detected, f is dirty
    f.bar = ['foo']
    f._not_dirty()

    #change detected, f is dirty again
    f.bar.append('bar')

rawDescription: Looking for a solution to detect value change in class attribute with a list and append


code:
class SparseDict(dict):
  def __init__(self, default_value):
    dict.__init__(self)
    self._value = default_value
  def __getitem__(self, key):
    try:
      return dict.__getitem__(self, key)
    except KeyError:
      return self._value
  def __setitem__(self, key, val):
    # I'm sure this can go faster if I were smarter
    if val == self._value:
      if  key in self:
        del self[key]
    else:
      dict.__setitem__(self, key, val)

def test(galaxy):
  import sys
  print len(galaxy), sys.getsizeof(galaxy)

  # test is 1/10th size in each dimension,
  # so 1/1000th of the volume
  for x in range(160):
    for y in range(160):
      for z in range (25):
        import random
        # 90% of space is essentially a vacuum
        if random.random() < .1:
          galaxy[x,y,z] = 1502100
        else:
          galaxy[x,y,z] = 0

  print len(galaxy), sys.getsizeof(galaxy)

test(SparseDict(0))

rawDescription: 3D Array vs Sparse Matrix for Sparse Data


code:
import re
print re.sub(r"u('\w)", r"\1", p)

rawDescription: Regex. How to remove multiple occurence of 'u' if it's befoure some symbol


code:
start = 'item: '
end = 'Other: '
should_append = False
the_list = []
for line in open('file').readlines():
    if line.startswith(start):
        data = line[len(start):]
        the_list.append(data)
        should_append = True
    elif line.startswith(end):
        should_append = False
        break
    elif should_append:
        the_list.append(line)

print the_list

rawDescription: Putting parts of a text file into a list


code:
def classifyInput(n):
    if n == "r":
        return 1
    elif n == "s":
        return 2
    elif n == "p":
        return 3
    else:
        print "Wrong input!"
        # implicit: return None

p1_inp = raw_input("Player 1 ?")
p1 = classifyInput(p1_inp)

rawDescription: Changing string into integers for variables inside function, Python


code:
from datetime import datetime, timedelta

now = datetime.now()
seven_days_from_now = now + timedelta(days=7)
print now, seven_days_from_now

rawDescription: Django equivalent of Rails's x.days.from_now


code:
import types

class Namespace(object):
    pass

class Foo(object):
    def __init__(self, value):
        self.value = value
        self.bar = Namespace()

def function(self, new_value):
    self.value = new_value

a = Foo(1)
b = Foo(2)

b.bar.function = types.MethodType(function, b, Foo)
b.bar.function(6)

print a.value   # prints 1
print b.value   # prints 6

rawDescription: Method namespaces/collections in Python classes


code:
import subprocess
from subprocess import PIPE

def main():
    process = subprocess.Popen('echo %USERNAME%', stdout=PIPE, shell=True)
    username = process.communicate()[0]
    print username #prints the username of the account you're logged in as

if __name__ == '__main__':
    main()

rawDescription: Python script to execute external commands


code:
from twill.commands import go, fv, submit
go('http://lcnitd.com/yearbook/2014/index.php')
fv("2","rollnumber","10/CSE/2")
fv("2","password","myPassword")
submit('0')
go('http://www.lcnitd.com/yearbook/2014/request.php')
n=1
roll="10/CSE/"
while(n<100):
    sleep(2)
    temp=roll+`n`
    print n
    fv("2","requestroll",temp)
    n+=1
    submit('0')

rawDescription: Automating requests on a website

description: Automating requests on a website


code:
def main():
    print "Welcome to my Text Adventure!"
    return raw_input("Press any button to start!")

rawDescription: "None" output after raw_input in Python 2.7 bug


code:
class MyClass(object):
    names_list = []
    _name = None

    def get_name(self):
        return self._name
    def set_name(self, name):
        assert self._name is None
        self._name = name
        self.names_list.append(name)
    name = property(get_name, set_name)

obj1 = MyClass()
obj1.name = 'name1'

obj2 = MyClass()
obj2.name = 'name2'

print obj1.names_list
print len(obj1.names_list)

rawDescription: How to enumerate all objects and get they attribute?

description: Enumerate all objects and get they attribute


code:
inputs = []
search_strings = ['WaveDir', 'WaveHs', 'WaveTp', 'WtrDpth', 'Number of mooring lines', 'Reference height', 'Reference wind speed', 'Grid height', 'Grid width', 'Analysis time']
files = ['input.txt', 'input2.txt']

for filename in files:
    with open(filename) as f_input:
        for line_number, line in enumerate(f_input, start=1):
            for search in search_strings:
                if search in line:
                    first_non_space = line.strip().split(' ')[0]
                    inputs.append((filename, line_number, search, first_non_space))
                    #print filename, line_number, search

for filename, line_number, search_matched, first_non_space in inputs:
    print filename, line_number, search_matched, first_non_space

rawDescription: searching for an array of keywords in an array of files

description: Searching for an array of keywords in an array of files


code:
class Foo:
    def bar(self):
        print "hello bar"

    def haz(self):
        print "hello haz"

    def nothing(self):
        print "None"

    def __init__(self, choose_me):
        {'foo': self.bar,
         'can': self.haz
         }.get(choose_me, self.nothing)()

if __name__ == '__main__':
    Foo('foo')

rawDescription: Python dictionary lookup returning multiple results?


code:
import re

# ...

page_source = driver.page_source

pattern = re.compile(r"var desp_list = \[\['(.*?)',")
match = pattern.search(page_source, re.MULTILINE | re.DOTALL)
print match.group(1) if match else "No match"

rawDescription: Python selenium getting data while hovering


code:
try:
    names = prod['COMPONENTS'][0][1][0][2]
except LookupError:
    print "It failed"
    # Do whatever you need to do in case of failure

rawDescription: check arbitrary list index existence in python

description: Check arbitrary list index existence in python


code:
from django import template
from django.utils.safestring import mark_safe

register = template.Library()

# http://www.soyoucode.com/2011/set-variable-django-template
# http://djangosnippets.org/snippets/861/
# http://stackoverflow.com/questions/4183252/what-django-resolve-variable-do-template-variable
# https://docs.djangoproject.com/en/dev/ref/templates/api/

@register.tag
def allow_tags(parser, token):

    """
    Example: {% allow_tags page.content %}
    """

    try:
        # Splitting by None == splitting by spaces:
        tag_name, var_name = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, '%r tag requires arguments' % token.contents.split()[0]

    return RenderNode(var_name)
allow_tags.is_safe = True

class RenderNode(template.Node):

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

    def render(self, context):
        try:
            content = template.Variable(self.content).resolve(context)
            return template.Template(content).render(template.Context(context, autoescape=False))
        except template.TemplateSyntaxError, e:
            return mark_safe('Template error: There is an error one of this page\'s template tags: <code>%s</code>' % e.message)

rawDescription: Is it possible to process arbitrary content with the Django template processor?


code:
import csv
from collections import defaultdict

# Gather the data from the CSV file
d = defaultdict(list)
with open('data.csv', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter='\t')
    for row in reader:
        d[float(row[0])].append(float(row[1]))

# Print the mean.
for k in d.keys():
    print k, sum(d[k])/len(d[k])

rawDescription: Performing calculations on a tab-delimited file


code:
#!/usr/bin/python

import selenium
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time

browser = webdriver.Firefox() # Get local session of firefox
browser.get("http://news.sina.com.cn/c/2013-07-11/175827642839.shtml ") # Load page
time.sleep(5) # Let the page load
try:
    element = browser.find_element_by_xpath("//span[contains(@class,'f_red')]") # get element on page
    print element.text # get element text
except NoSuchElementException:
    assert 0, "can't find f_red"
browser.close()

rawDescription: How to scrape data generated by javascript using python

description: Scrape data generated by javascript using python


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

followers_per_page = 18

driver = webdriver.Chrome()  # webdriver.Firefox() in your case
driver.get("http://www.quora.com/Andrew-Delikat/followers")

# get the followers count
element = WebDriverWait(driver, 2).until(EC.presence_of_element_located((By.XPATH, '//li[contains(@class, "FollowersNavItem")]//span[@class="profile_count"]')))
followers_count = int(element.text.replace(',', ''))
print followers_count

# scroll down the page iteratively with a delay
for _ in xrange(0, followers_count/followers_per_page + 1):
    driver.execute_script("window.scrollTo(0, 10000);")
    time.sleep(2)

rawDescription: Scrolling web page using selenium python webdriver


code:
import sys
import time
k = 0
try:
    buff = ''
    while True:
        buff += sys.stdin.read(1)
        if buff.endswith('\n'):
            print buff[:-1]
            buff = ''
            k = k + 1
except KeyboardInterrupt:
   sys.stdout.flush()
   pass
print k

rawDescription: How do you read from stdin in python from a pipe which has no ending

description: Read from stdin in python from a pipe which has no ending


code:
diff = difflib.ndiff(foo, bar)
diff = list(diff)
print ''.join(difflib.restore(diff, 2))
''.join(difflib.restore(diff, 2))==''.join(bar)
''.join(difflib.restore(diff, 1))==''.join(foo)

rawDescription: How to apply the output of python's difflib.unified_diff to the original string?

description: Apply the output of python's difflib.unified_diff to the original string


code:
import json
a = ((1,2),(11,22,),(111,222))
print a
message = json.dumps(a)
message
b = json.loads(message)
b

rawDescription: python: send a list/dict over network

description: Python: send a list/dict over network


code:
import os

searchdir = r'C:\blabla'
searchstring = 'import sys'

def found_in_file(fname, searchstring):
    with open(fname) as infp:
        for line in infp:
            if searchstring in line:
                return True
        return False

with open('found.txt', 'w') as outfp:
    count = 0
    search_count = 0
    for root, dirs, files in os.walk(searchdir):
        for name in files:
            (base, ext) = os.path.splitext(name)
            if ext in ('.txt', '.py'):
                count += 1

            full_name = os.path.join(root, name)
            if found_in_file(full_name, searchstring):
               outfp.write(full_name + '\n')
               search_count += 1

print 'total number of files found %d' % count
print 'number of files with search string %d' % search_count

rawDescription: filter directory in python

description: Filter directory in python


code:
import re
def myfilter(x):
    return ' '.join(re.sub(ur'\(\s*[nN][eE][wW]\s*\)','',x).title().split())

wcity = myfilter( raw_input("Please enter a city ==> ") )
print wcity
wtype = myfilter( raw_input("Please enter a restaurant type ==> ") )
print wtype

rawDescription: Need to change capitalize python to interpret 3 different types of inputs the SAME with the raw_input function


code:
import re

class Node:
    def __init__(self, parent, items, repeat):
        self.parent = parent
        self.items = items
        self.repeat = repeat

root = Node(None, [], 1)
node = root

with open('levels.txt') as f:
    for line in f:
        line = line.strip()
        if line == 'NODE':
            new_node = Node(node, [], 1)
            node.items.append(new_node)
            node = new_node

        if line == '}':
            node = node.parent

        res = re.match('REPEAT = (\d+)', line)
        if res:
            node.repeat=int(res.group(1))

        res = re.match('LEVEL (\d+) FOR ([\d.]+)', line)
        if res:
            node.items.append((int(res.group(1)), float(res.group(2))))

def generate(node):
    res = []
    for i in xrange(node.repeat):
        for item in node.items:
            if isinstance(item, Node):
                res.extend(generate(item))
            elif isinstance(item, tuple):
                res.append(item)
    return res

res = generate(root)

for r in res:
    print r

rawDescription: Parsing file that has nested loop structures into list structure using python


code:
import re
rx = r'\(([^)]+)\)'
string = """Name Multiple Words Zero Row* (78.59/0) Name Multiple Words2* (96/24.56) Name Multiple Words3* (0/32.45) Name Multiple Words4* (96/12.58) Name Multiple Words5* (96/0) Name Multiple Words Zero Row6* (0) Name Multiple Words7* (96/95.57) Name Multiple Words Zero Row8* (0) Name Multiple Words9*"""

for match in re.finditer(rx, string):
    parts = match.group(1).split('/')
    First_Num = parts[0]
    try:
        Seg_Length = parts[1]
    except IndexError:
        Seg_Length = None

    print "First_Num, Seg_Length: ", First_Num, Seg_Length

rawDescription: Python RegEx String Parsing with inconsistent data


code:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))

rawDescription: printing list in python properly

description: Printing list in python properly


rawDescription: How to round integers in python

description: Round integers in python


code:
import sys
import select
import tty
import termios

class NonBlockingConsole(object):

    def __enter__(self):
        self.old_settings = termios.tcgetattr(sys.stdin)
        tty.setcbreak(sys.stdin.fileno())
        return self

    def __exit__(self, type, value, traceback):
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)

    def get_data(self):
        if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
            return sys.stdin.read(1)
        return False

if __name__ == '__main__':
    # Use like this
    with NonBlockingConsole() as nbc:
        i = 0
        while 1:
            print i
            i += 1

            if nbc.get_data() == '\x1b':  # x1b is ESC
                break

rawDescription: python non-blocking non-messing-my-tty key press detection

description: Python non-blocking non-messing-my-tty key press detection


code:
print x
print x.append( pandas.Series([8, 9], index=["foo", "bar"]))

rawDescription: Adding individual items and sequences of items to dataframes and series


code:
class flags(object):
    def __init__(self, *opts):
        keys = [t[0] for t in opts]
        words = [t[1] for t in opts]
        nums = [2**i for i in range(len(opts))]
        self.attrs = dict(zip(keys,nums))
        self.choices = zip(nums,words)

    def __getattr__(self, a):
        return self.attrs[a]

    def __iter__(self):
        return iter(self.choices)

Abilities = flags(
    ('FLY', 'Can fly'),
    ('FIREBALL', 'Can shoot fireballs'),
    ('INVISIBLE', 'Can turn invisible'),
)

print Abilities.FLY
for k, v in Abilities:
    print k, v

rawDescription: How to add __iter__ to dynamic type?

description: Add __iter__ to dynamic type


code:
for property, value in vars(theObject).iteritems():
    print property, ": ", value

rawDescription: How to enumerate an object's properties in Python?

description: Enumerate an object's properties in Python


code:
from itertools import islice
with open('filename') as fin:
    for line in islice(fin, 1, 16):
        print line

rawDescription: Python read text file from second line to fifteenth


code:
import png
from StringIO import StringIO

# bitmap data
s = ['110010010011',
     '101011010100',
     '110010110101',
     '100010010011']
s = map(lambda x: map(int, x), s)

f = StringIO()
w = png.Writer(len(s[0]), len(s), greyscale=True, bitdepth=1)
w.write(f, s)

# binary PNG data
print f.getvalue()

rawDescription: Text to a PNG on App Engine (Python)

description: Text to a PNG on App Engine (Python)


code:
class twothreads:
    def t1(self):
        print "Hi"

    def t2(self):
        print "Bye"

t = twothreads()
threading.Thread(target=t.t1).start()
threading.Thread(target=t.t2).start()

rawDescription: multithreading class (python)

description: Multithreading class (python)


code:
for i in range(3):
    print a[:-i or None]

for i in [0, -1, -2]:
    print a[:i or None]

rawDescription: sequentially shorter list from the right via indexing - need [:-0] to act like [:]

description: Sequentially shorter list from the right via indexing - need [:-0] to act like [:]


rawDescription: How can I compute elements from two diferents lists in python?

description: Compute elements from two diferents lists in python


code:
q = "today(Thursday)^05^*07*[2012]"
import re
print re.findall(r'\w+', q) # ['today', 'Thursday', '05', '07', '2012']

rawDescription: Way to extract several substrings from a string?


code:
import pytz
import datetime

tz = pytz.timezone('Asia/Calcutta')
dt = datetime.datetime.utcnow()

offset_seconds = tz.utcoffset(dt).seconds

offset_hours = offset_seconds / 3600.0

print "{:+d}:{:02d}".format(int(offset_hours), int((offset_hours % 1) * 60))
# +5:30

rawDescription: how to get UTC offset value from timezone?

description: Get UTC offset value from timezone


code:
from comtypes import *
import comtypes.client
from ctypes import POINTER
from ctypes.wintypes import DWORD, BOOL

MMDeviceApiLib = \
    GUID('{2FDAAFA3-7523-4F66-9957-9D5E7FE698F6}')
IID_IMMDevice = \
    GUID('{D666063F-1587-4E43-81F1-B948E807363F}')
IID_IMMDeviceEnumerator = \
    GUID('{A95664D2-9614-4F35-A746-DE8DB63617E6}')
CLSID_MMDeviceEnumerator = \
    GUID('{BCDE0395-E52F-467C-8E3D-C4579291692E}')
IID_IMMDeviceCollection = \
    GUID('{0BD7A1BE-7A1A-44DB-8397-CC5392387B5E}')
IID_IAudioEndpointVolume = \
    GUID('{5CDF2C82-841E-4546-9722-0CF74078229A}')

class IMMDeviceCollection(IUnknown):
    _iid_ = GUID('{0BD7A1BE-7A1A-44DB-8397-CC5392387B5E}')
    pass

class IAudioEndpointVolume(IUnknown):
    _iid_ = GUID('{5CDF2C82-841E-4546-9722-0CF74078229A}')
    _methods_ = [
        STDMETHOD(HRESULT, 'RegisterControlChangeNotify', []),
        STDMETHOD(HRESULT, 'UnregisterControlChangeNotify', []),
        STDMETHOD(HRESULT, 'GetChannelCount', []),
        COMMETHOD([], HRESULT, 'SetMasterVolumeLevel',
            (['in'], c_float, 'fLevelDB'),
            (['in'], POINTER(GUID), 'pguidEventContext')
        ),
        COMMETHOD([], HRESULT, 'SetMasterVolumeLevelScalar',
            (['in'], c_float, 'fLevelDB'),
            (['in'], POINTER(GUID), 'pguidEventContext')
        ),
        COMMETHOD([], HRESULT, 'GetMasterVolumeLevel',
            (['out','retval'], POINTER(c_float), 'pfLevelDB')
        ),
        COMMETHOD([], HRESULT, 'GetMasterVolumeLevelScalar',
            (['out','retval'], POINTER(c_float), 'pfLevelDB')
        ),
        COMMETHOD([], HRESULT, 'SetChannelVolumeLevel',
            (['in'], DWORD, 'nChannel'),
            (['in'], c_float, 'fLevelDB'),
            (['in'], POINTER(GUID), 'pguidEventContext')
        ),
        COMMETHOD([], HRESULT, 'SetChannelVolumeLevelScalar',
            (['in'], DWORD, 'nChannel'),
            (['in'], c_float, 'fLevelDB'),
            (['in'], POINTER(GUID), 'pguidEventContext')
        ),
        COMMETHOD([], HRESULT, 'GetChannelVolumeLevel',
            (['in'], DWORD, 'nChannel'),
            (['out','retval'], POINTER(c_float), 'pfLevelDB')
        ),
        COMMETHOD([], HRESULT, 'GetChannelVolumeLevelScalar',
            (['in'], DWORD, 'nChannel'),
            (['out','retval'], POINTER(c_float), 'pfLevelDB')
        ),
        COMMETHOD([], HRESULT, 'SetMute',
            (['in'], BOOL, 'bMute'),
            (['in'], POINTER(GUID), 'pguidEventContext')
        ),
        COMMETHOD([], HRESULT, 'GetMute',
            (['out','retval'], POINTER(BOOL), 'pbMute')
        ),
        COMMETHOD([], HRESULT, 'GetVolumeStepInfo',
            (['out','retval'], POINTER(c_float), 'pnStep'),
            (['out','retval'], POINTER(c_float), 'pnStepCount'),
        ),
        COMMETHOD([], HRESULT, 'VolumeStepUp',
            (['in'], POINTER(GUID), 'pguidEventContext')
        ),
        COMMETHOD([], HRESULT, 'VolumeStepDown',
            (['in'], POINTER(GUID), 'pguidEventContext')
        ),
        COMMETHOD([], HRESULT, 'QueryHardwareSupport',
            (['out','retval'], POINTER(DWORD), 'pdwHardwareSupportMask')
        ),
        COMMETHOD([], HRESULT, 'GetVolumeRange',
            (['out','retval'], POINTER(c_float), 'pfMin'),
            (['out','retval'], POINTER(c_float), 'pfMax'),
            (['out','retval'], POINTER(c_float), 'pfIncr')
        ),

    ]

class IMMDevice(IUnknown):
    _iid_ = GUID('{D666063F-1587-4E43-81F1-B948E807363F}')
    _methods_ = [
        COMMETHOD([], HRESULT, 'Activate',
            (['in'], POINTER(GUID), 'iid'),
            (['in'], DWORD, 'dwClsCtx'),
            (['in'], POINTER(DWORD), 'pActivationParans'),
            (['out','retval'], POINTER(POINTER(IAudioEndpointVolume)), 'ppInterface')
        ),
        STDMETHOD(HRESULT, 'OpenPropertyStore', []),
        STDMETHOD(HRESULT, 'GetId', []),
        STDMETHOD(HRESULT, 'GetState', [])
    ]
    pass

class IMMDeviceEnumerator(comtypes.IUnknown):
    _iid_ = GUID('{A95664D2-9614-4F35-A746-DE8DB63617E6}')

    _methods_ = [
        COMMETHOD([], HRESULT, 'EnumAudioEndpoints',
            (['in'], DWORD, 'dataFlow'),
            (['in'], DWORD, 'dwStateMask'),
            (['out','retval'], POINTER(POINTER(IMMDeviceCollection)), 'ppDevices')
        ),
        COMMETHOD([], HRESULT, 'GetDefaultAudioEndpoint',
            (['in'], DWORD, 'dataFlow'),
            (['in'], DWORD, 'role'),
            (['out','retval'], POINTER(POINTER(IMMDevice)), 'ppDevices')
        )
    ]

enumerator = comtypes.CoCreateInstance(
    CLSID_MMDeviceEnumerator,
    IMMDeviceEnumerator,
    comtypes.CLSCTX_INPROC_SERVER
)

print enumerator
endpoint = enumerator.GetDefaultAudioEndpoint( 0, 1 )
print endpoint
volume = endpoint.Activate( IID_IAudioEndpointVolume, comtypes.CLSCTX_INPROC_SERVER, None )
print volume
print volume.GetMasterVolumeLevel()
print volume.GetVolumeRange()
#volume.SetMasterVolumeLevel(-65, None) uncomment for 0 volume
#volume.SetMasterVolumeLevel(-1, None) uncomment for full volume
volume.SetMasterVolumeLevel(-25, None) #Change the first argument for controlling the volume remember it should be -ve not less than -65

rawDescription: Programmatically changing system-wide speaker balance on Windows 7


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base, declared_attr

Base = declarative_base()

class Parent(Base):
    __tablename__ = 'mytable'

    id = Column(Integer, primary_key = True)
    type = Column(String(32), nullable = False)
    __mapper_args__ = {
        'polymorphic_on' : type,
        'polymorphic_identity' : 'parent'
    }

class Child1(Parent):
    __mapper_args__ = { 'polymorphic_identity' : 'child1' }

    @declared_attr
    def property1(cls):
        return Parent.__table__.c.get('property1', Column(Integer))

class Child2(Parent):
    __mapper_args__ = { 'polymorphic_identity' : 'child2' }

    @declared_attr
    def property1(cls):
        return Parent.__table__.c.get('property1', Column(Integer))

class Child3(Parent):
    __mapper_args__ = { 'polymorphic_identity' : 'child3' }

    other_property = Column(Integer)

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)

s = Session(e)
s.add_all([Child1(property1=1), Child2(property1=2), Child3(other_property=3)])
s.commit()

for p in s.query(Parent):
    if isinstance(p, (Child1, Child2)):
        print p.property1
    elif isinstance(p, Child3):
        print p.other_property

rawDescription: SQLAlchemy: Single Table Inheritance, same column in childs


code:
import itertools

c1 = [10, 45, 50, 75, 90]
c2 = [15, 25, 30, 65, 80]

print c1, c2
for i in range(1, 5):
    for c in itertools.combinations(c1, i):
        mc1 = sorted(list(set(c1).difference(set(c))))
        mc2 = sorted(list(set(c2).union(c)))
        print mc1, mc2

rawDescription: How to move Items from one list to the another list in python?

description: Move Items from one list to the another list in python


code:
intweight = 0
while True:
    try:
        weight = float(input())
    except ValueError:
        print "Please enter a number"
    else:
        break
        intweight = weight

rawDescription: How to make sure that a user inputs a number?

description: Make sure that a user inputs a number


code:
from collections import defaultdict, Counter
stats = defaultdict(Counter)

def add_result_to_stats(result, func_name):
    stats[func_name][result] += 1

add_result_to_stats('foo', 'bar')
print stats # defaultdict(<class 'collections.Counter'>, {'bar': Counter({'foo': 1})})

rawDescription: Clean way of using a python dictionary to hold program statistics


code:
import os

file_name = "test.txt" #file to be searched
cur_dir = os.getcwd() # Dir from where search starts can be replaced with any path

while True:
    file_list = os.listdir(cur_dir)
    parent_dir = os.path.dirname(cur_dir)
    if file_name in file_list:
        print "File Exists in: ", cur_dir
        break
    else:
        if cur_dir == parent_dir: #if dir is root dir
            print "File not found"
            break
        else:
            cur_dir = parent_dir

rawDescription: Python: search for a file in current directory and all it's parents


code:
class B(object):
    def virtual_fn(self):
        print 'in B.virtual_fn() for', id(self)
    def other_virtual_fn(self):
        print 'in B.other_virtual_fn() for', id(self)
    def call_virtual(self):
        print 'in B.call_virtual() for', id(self)

class D(B):
    def virtual_fn(self):
        print 'in D.virtual_fn() for', id(self)

b_obj = B()
d_obj = D()
id(b_obj)
id(d_obj)
b_obj.virtual_fn()
d_obj.virtual_fn()
d_obj.other_virtual_fn()
B.virtual_fn(d_obj)
d_obj.call_virtual()

rawDescription: How can I express base class method calling derived virtual?

description: Express base class method calling derived virtual


code:
import os
os.times()
print os.times.__doc__

rawDescription: CPU Usage Per Process in Python

description: CPU Usage Per Process in Python


rawDescription: Sorting a list of tuples on multiple keys


code:
for td in soup_result:
    print td.getText()

rawDescription: Returning the text from a selection using BeautifulSoup


code:
p = Popen('bash -c "echo \'useful\'; cd ~/dicp/python; nohup sleep 5 &> /tmp/out.txt & echo \'more\';"', shell = True, stdout = PIPE, stderr = PIPE)
print p.communicate()

rawDescription: Python Popen waiting while it shouldn't (bg and output redirected)


code:
class Game(object):

    def __init__ (self, start):
        self.quips = ['You died.you kinda suck at this.', 'Nice job, you died...jackass.',
            "Such a luser.",
            'I have a small puppy that\'s bettr at this.']
        self.start = start

        self.ROOMS = {
            'death' : self.death,
            'central_corridor' : self.central_corridor,
            'laser_weapon_armory' : self.laser_weapon_armory,
            'the_bridge' : self.the_bridge,
            'escape_pod' : self.escape_pod
        }

    def play (self):
        next = self.start

        while True:
            print "\n--------"
            room = self.ROOMS[next]
            next = room()

rawDescription: How to use dictionary in class? it shows the dict is not defined

description: Use dictionary in class? it shows the dict is not defined


code:
import time
print int(time.time())

rawDescription: Python's version of PHP's time() function


code:
from numpy import genfromtxt
from StringIO import StringIO

def read_by_block(filename):
    blocks = []
    data = open(filename).read()
    for blk in data.split('\n\n'): # we assume that blocks are separated by two newlines
        blocks.append(genfromtxt(StringIO(blk), delimiter=';', names=True))
    return blocks

data = read_by_block('data.txt')

print data[0].dtype.names # print fields for first block
print data[0]['StdPhi'] # print column 'Std(Phi)' in 1st block

rawDescription: Python : How to load column from multiblock csv tables?


code:
import datetime
import pymongo
import json
import re

hosts = ["mongodbuat"]

# initialize failures and successes
failures = 0
successes = 0

for host in hosts:
    conn = pymongo.Connection(host)
    mdb = conn['salt']
    collections = set(mdb.collection_names())

    hosts = []
    jids = []

    # for every collection, identify whether it is a host or a job
    for c in collections:
        # if the collection is a host add it to the host array
        if not (len(c) == 20 and int(c)):
            hosts.append(c)
        # otherwise add it to the job array
        else:
            jids.append(c)

    for h in hosts:
        # for every job in a host connect to that collection
        # and search for the job id to see if it exists
        # and what its return was so we can report on that info
        for j in jids:
            coll = conn['salt'][h]

            # search for the json documents returned from mongodb
            # if the jobid exists in that host
            for doc in coll.find({j: {'$exists': True}, "fun": "state.sls"}, {"_id": 0}):

                # if the jobid exists find the host name in a readable format
                c = str(coll)
                thishost = ''
                match = re.search('(\w+)\.spottrading\.com',c)
                if match:
                    thishost = match.group(1)

                # search the document returned in the form of a dictionary for
                # the states you want to report on
                for jobid, states in doc.iteritems():
                    if re.search('\d+', jobid):
                        print '\njob id =', jobid
                        if isinstance(states, list):
                            print states
                            failures += 1
                        elif isinstance(states, dict):
                            for job, data in states.iteritems():
                                print '\tjob: {0}, result: {1}'.format(job, data[u'result'])
                            successes += 1

print "{0} successes, {1} failures".format(successes, failures)

rawDescription: mongodb query data where the key is variable and aggregate results using python

description: Mongodb query data where the key is variable and aggregate results using python


code:
from Tkinter import *

def rClicker(e):
    ''' right click context menu for all Tk Entry and Text widgets
    '''

    try:
        def rClick_Copy(e, apnd=0):
            e.widget.event_generate('<Control-c>')

        def rClick_Cut(e):
            e.widget.event_generate('<Control-x>')

        def rClick_Paste(e):
            e.widget.event_generate('<Control-v>')

        e.widget.focus()

        nclst=[
               (' Cut', lambda e=e: rClick_Cut(e)),
               (' Copy', lambda e=e: rClick_Copy(e)),
               (' Paste', lambda e=e: rClick_Paste(e)),
               ]

        rmenu = Menu(None, tearoff=0, takefocus=0)

        for (txt, cmd) in nclst:
            rmenu.add_command(label=txt, command=cmd)

        rmenu.tk_popup(e.x_root+40, e.y_root+10,entry="0")

    except TclError:
        print ' - rClick menu, something wrong'
        pass

    return "break"

def rClickbinder(r):

    try:
        for b in [ 'Text', 'Entry', 'Listbox', 'Label']: #
            r.bind_class(b, sequence='<Button-3>',
                         func=rClicker, add='')
    except TclError:
        print ' - rClickbinder, something wrong'
        pass

if __name__ == '__main__':
    master = Tk()
    ent = Entry(master, width=50)
    ent.pack(anchor="w")

    #bind context menu to a specific element
    ent.bind('<Button-3>',rClicker, add='')
    #or bind it to any Text/Entry/Listbox/Label element
    #rClickbinder(master)

    master.mainloop()

rawDescription: Stardand context menu in Python TKinter text widget when mouse right button is pressed


rawDescription: text with unicode escape sequences to unicode in python

description: Text with unicode escape sequences to unicode in python


code:
#!/usr/bin/env python
import requests

r = requests.get('https://github.com/timeline.json')
for item in r.json or []:
    print item['repository']['name']

rawDescription: Take a Json object from three webpages and write that in a file?


code:
def recursiveCount(lst,key):
    if lst == []: #base case
        return 0
    if lst[0] == key:
        return 1 + recursiveCount(lst[1:],key)
    else:
        return 0 + recursiveCount(lst[1:],key)

print recursiveCount(['a','b','a'],'a') #prints 2

rawDescription: Recursive Python function to count occurrences of an element in a list


code:
import numpy as np
import mayavi.mlab as ML
import math
import time

def produce_verts(A, t):
    def delta(A, t):
        return A * math.sin(t)
    def verts(d):
        return [(1 + d, 0, 0), (0, 1 + d, 0), (-1 - d, 0, 0), (0, -1 - d, 0),
                (0, 0, 1 + d), (0, 0, -1 - d)]
    return zip(*verts(delta(A, t)))

t = 0.
dt = 0.1
A = 0.5
ML.clf()
nverts = 6
x, y, z = produce_verts(A, t)
# Each triangle is a 3-tuple of indices. The indices are indices of `verts`.
triangles = [(i, (i + 1) % 4, j) for i in range(4) for j in (4, 5)]
colorval = [xi ** 2 + yi ** 2 + zi ** 2 for xi, yi, zi in zip(x, y, z)]
mesh = ML.triangular_mesh(
    x, y, z, triangles, scalars=colorval, opacity=1, representation='mesh')
ms = mesh.mlab_source
while True:
    t = (t + dt) % (2 * math.pi)
    x, y, z = produce_verts(A, t)
    colorval = [xi ** 2 + yi ** 2 + zi ** 2 for xi, yi, zi in zip(x, y, z)]
    ms.set(x=x, y=y, z=z, scalars=colorval)
    # time.sleep(0.1)
    print t, dt
    if t > 4:
        break

ML.show()

rawDescription: Mayavi: animating an octahedron outline without blocking


code:
def main(data):
    total = []
    n = len(data)
    for i in range(n):
        tmp = []
        for j in range(n):
            a = data[i];
            b = data[j]
            tmp.append(dist(data[i],data[j]))
        total.append(tmp)
    return total

def dist(a,b):
    tmp = [pow(a - b,2) for a, b in zip(a, b)]
    return pow(sum(tmp),0.5);

def output(t):#this function is not necessary and is just for tidiness
    n = len(t)
    for i in range(n):
        for j in range(n):
            print t[i][j],"\t\t\t",
        print "\n"

data = [[1,1,1],[1,2,3],[0,0,0]]#just for test
t = main(data)
output(t)

rawDescription: euclidean distance with multiple column of data

description: Euclidean distance with multiple column of data


code:
import re
import requests
import requests.models

# non-standard conform redirect:
requests.Response.is_redirect = property(lambda self: (
    'location' in self.headers and (
        self.status_code in requests.models.REDIRECT_STATI or
        self.headers.get('Ajax-Response', '') == 'redirect'
)))

headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:27.0) Gecko/20100101 Firefox/27.0'
}
payload = {
    "AJAXREQUEST": "loader2",
    "residential": "residential",
    "residential:j_id12": "",
    "residential:firstField": 'a',
    "residential:criteria1": "3",
    "residential:city": "ASIND",
    "residential:button1": "residential:button1",
    "residential:suggestionBoxId_selection": "",
    "javax.faces.ViewState": "j_id1"

}

with requests.Session() as s:
    print s.get('http://dq.ndc.bsnl.co.in/bsnl-web/residentialSearch.seam')
    print s.headers
    print s.cookies
    resp = s.post(
        'http://dq.ndc.bsnl.co.in/bsnl-web/residentialSearch.seam',
        data=payload, headers=headers)

    while True:
        # do data processing
        for l in resp.text.split("subscriber');")[1:]: print l[2:].split('<')[0]

        # look for next page
        current, last = re.search('Page (\d+) of (\d+)', resp.text).groups()
        if int(current) == int(last):
            break

        resp = s.post('http://dq.ndc.bsnl.co.in/bsnl-web/resSrchDtls.seam',
            data={'AJAXREQUEST':'_viewRoot',
                'j_id10':'j_id10',
                'javax.faces.ViewState':'j_id2',
                'j_id10:PGDOWNLink':'j_id10:PGDOWNLink',
            }, headers=headers)

rawDescription: Getting past an AJAX form using Python Requests


code:
from PyQt4.QtGui import QApplication, QPixmap
desktop = QApplication.desktop()
screenRect = desktop.screenGeometry(1)   #2nd monitor
print screenRect.x(), screenRect.y()   #returns the x and y of that screen

rawDescription: Get screen layout of multiple screens on linux/Gnome


code:
from string import Template
import optparse

def main():
    usage = "usage: %prog options outputname"
    p = optparse.OptionParser(usage)
    p.add_option('--optiona', '-a', default="")
    p.add_option('--optionb', '-b', default="")
    options, arguments = p.parse_args()
    t = Template('Option a is ${optiona} option b is ${optionb}')
    print t.substitute(vars(options)) #I'm assuming the uppercase S was a typo.

rawDescription: getopts Values class and Template.Substitute don't (immediately) work together

description: Getopts Values class and Template.Substitute don't (immediately) work together


code:
# Read everything
with open('/path/to/file') as infile:
    data = infile.readlines()
# Replace
try:
    data[63] = 'this is the new text\n' # Do not forget the '\n'!
    with open('/path/to/file', 'w') as newfile:
        newfile.writelines(data)
except IndexError:
    print "Oops, there is no line 63!"

rawDescription: Replacing line in text file with python. How to?


code:
print render_template('/path/to/template.html',
    title = 'My page title',
    more  = 'even more stuff',
    **logged_in
)

rawDescription: Can you combine keyword argument expansion with regular keyword arguments?

description: Combine keyword argument expansion with regular keyword arguments


code:
import numpy as np
import numdifftools

def fun(A, B, C):
    return numpy.sum(numpy.dot(A, B)) + numpy.sum(C)

def fun_A(A, B, C):
    J = numdifftools.Jacobian(lambda z: fun(z.reshape(A.shape), B, C).ravel())
    return J(A.ravel()).reshape(A.shape)

np.random.seed(1234)
A = np.random.rand(30,30)
B = np.random.rand(30,30)
C = np.random.rand(30,30)
print fun_A(A,B,C)[3,5]
# -> 14.9081790839

# Verify result manually
Ap = A.copy()
Ap[3,5] += 1e-6
print (fun(Ap,B,C) - fun(A,B,C)) / 1e-6
# -> 14.908178855

rawDescription: Partial derivative of a function with numpy.array input


code:
from mako.template import Template
t = Template("""
% if key in d:
    key is in dictionary
% else:
    key is not in dictionary
% endif
""")

print t.render(key='a', d={'a': 'A'})  # prints "key is in dictionary"

rawDescription: How to check if a key exists in mako dict?

description: Check if a key exists in mako dict


code:
foo = []

def my_list_creator(n):
    '''Makes the nth value in a list n. If the list is not
    long enough, it extends it, initialised with None.
    '''
    global foo

    if len(foo) < n:
        foo.extend([None] * (n - len(foo)))

    foo[n-1] = n

def access_a_global():
    print foo

def another_func():
    my_list_creator(10)
    access_a_global()
    my_list_creator(20)
    access_a_global()

another_func()

rawDescription: Insert on python list on a particular offset


code:
import pandas as pd
df1 = pd.DataFrame({"ID":[1,2,3,4], "value": ["a","b","c","d"]})
df2 = pd.DataFrame({"Id_a": [1,4,2,3,4,2]})

merged_df = pd.merge(df2, df1, left_on="Id_a", right_on="ID")
print merged_df

rawDescription: How to select column values in a data frame using column values of other data frame

description: Select column values in a data frame using column values of other data frame


code:
from textwrap import dedent
def print_help():
  help = """\
  Specify the hostname or service/hostname you want to connect to
  If specified -f/--hostfile will be ignored
  Some more multiline text here
  and more to demonstrate"""
  print dedent(help)

print_help()

rawDescription: Python optparse help message formatting

description: Python optparse help message formatting


code:
import string, cgi

class Template(string.Formatter):
    def format_field(self, value, spec):
        if spec.endswith('h'):
            value = cgi.escape(value)
            spec = spec[:-1] + 's'
        return super(Template, self).format_field(value, spec)

print Template().format('{0:h} {1:d}', "<hello>", 123)

rawDescription: Add custom conversion types for string formatting


code:
mainProcess = subprocess.Popen(['python', file, param], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
communicateRes = mainProcess.communicate()
stdOutValue, stdErrValue = communicateRes

# you can split by any value, here is by space
my_output_list = stdOutValue.split(" ")

# after the split we have a list of string in my_output_list
for word in my_output_list :
    if word == "myword":
        print "something something"

rawDescription: How do you search subprocess output in Python for a specific word?

description: Search subprocess output in Python for a specific word


code:
# Call this script with:
# cd /usr/lib/mailman/bin/
# withlist -r ackpostforgmail LISTNAME

from Mailman import mm_cfg

def ackpostforgmail(m):
    # m is the maillist object for the list LISTNAME

    # We need to lock the list, since we want to change something...
    m.Lock()

    print "Setting 'AcknowledgePosts' to True for all gmail adresses of the list..."
    for memb in m.members:
        # If the mailadress memb contains 'gmail'...
        if 'gmail' in memb:
            # ...set the ackpost option...
            prev_state = m.getMemberOption(memb, mm_cfg.AcknowledgePosts)
            m.setMemberOption(memb, mm_cfg.AcknowledgePosts,True)
            after_state = m.getMemberOption(memb, mm_cfg.AcknowledgePosts)

            print "%s: %s -> %s" % (memb, prev_state, after_state)

    m.Save()

rawDescription: How do I know if my mailman post was succesful using gmail?

description: Know if my mailman post was succesful using gmail


code:
def sum_up(id, list):
    counted = len(list)
    summed = sum(list)
    avrg = summed/counted
    # print, insert or do whatever needed with the lines:
    print counted, summed, avrg

last_id = None
current = []
for line in file:
    (id, value) = line.split()
    if last_id != id:
        if last_id is not None:
            # evaluate last id
            sum_up(last_id, current)
            current = []
        # remember id
        last_id = id
    # append to current ids entries
    current.append(value)

# do the last id, if there is any:
if len(current) > 0:
    sum_up(last_id, current)

rawDescription: how to iterate over entries in a file making a dictionary with unique values and calculate an average for each value that can occur multiple times?

description: Iterate over entries in a file making a dictionary with unique values and calculate an average for each value that can occur multiple times


code:
# oo is the symbol for infinity
from sympy import Interval, oo, Rational

i1 = Interval(10, 15)
i2 = Interval(0, oo)
i3 = Interval(-5, -1)
# adding intervals
i4 = i1 + i3
i5 = i1 + i2
# interval with open end
i6 = Interval(Rational(1, 2), Rational(45, 3), left_open=True)

print 11 in i1 # True
print -1 in i1 # False
print 0 in i4 # False
print Rational(3, 2) in i6 # True
print oo in i2 # False
print i2.sup # oo (infinity)
print Rational(1, 2) in i6 # False
print i6.inf # 1/2

rawDescription: Is there an implementation of _rational_ interval arithmetic in Python?


code:
width = int(raw_input("How Long?"))

while width <= 7:
    print "Min 7"
    width = int(raw_input())

rawDescription: How to create while loop checking for input

description: Create while loop checking for input


code:
curse=["apple","ball","car"]
fil = ["!","@","#","$","%","^","&","*","(",")"]

word = raw_input(">>")
words = word.split();
for w  in words:
    p = w.lower()
    if p in curse:
        filword=""
        worlen = len(w);
        for i in range(worlen):
            filword += fil[j]
            j = (j + 1)%len(fil)
        word = word.replace(w,filword);

print word

rawDescription: Python: Replacing foul words with characters from a sentence


code:
from bs4 import BeautifulSoup

html_doc = '''

 '''

soup = BeautifulSoup(html_doc)

# Find any tag with a class of "number"
# that is a descendant of a tag with
# a class of "mobile"
mobiles = soup.select(".mobile .number")
print mobiles

# Find a tag with a class of "number"
# that is an immediate descendent
# of a tag with "mobile"
mobiles = soup.select(".mobile > .number")
print mobiles

# Find an  tag that is an immediate
# descendent of a
 tag.
mobiles = soup.select("tr.mobile > a.number")
print mobiles

rawDescription: Python - how do I target a class in another class using BeautifulSoup?


code:
import os
for root, subFolders, files in os.walk('/tmp'):
  for f in files:
    if len(f) < 5: continue
    newf = f[:-5]+f[-5].lower()+f[-4:]
    print "changing",f,"to",newf

rawDescription: How to rename last letter but not the file ending in python

description: Rename last letter but not the file ending in python


code:
import threading

list_of_things = []

class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global list_of_things
        for i in range(0, 10):
            list_of_things.append('hello ' + str(i))

if __name__ == "__main__":
    mythread = MyThread()
    mythread.start()
    mythread.join()
    print list_of_things

rawDescription: Using a global list in a Thread object

description: Using a global list in a Thread object


code:
def print_first_and_last(sentence):
    words = break_words(sentence)

    print sentence, words
    print_first_word(words)
    print sentence, words
    print_last_word(words)
    print sentence, words

rawDescription: Learn Python The Hard Way #25

description: Learn Python The Hard Way #25


code:
from string import digits, ascii_uppercase, ascii_lowercase
from itertools import product

chars = digits + ascii_uppercase + ascii_lowercase

for n in range(1, 4 + 1):
    for comb in product(chars, repeat=n):
        print ''.join(comb)

rawDescription: Generate alphanumeric strings sequentially


code:
low = 0
mid = 50
high = 100
secretnum = "Is your secret number: "
print"Please think of a number between 0 and 100!"
print secretnum + str(mid) + "?"
herp = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
while herp != 'c':
    if herp == 'h':
        high = mid
        mid = int((mid + low)/2)
    elif herp == 'l':
        low = mid
        mid = int((mid + high)/2)
    else:
        print"Sorry, I did not understand your input."
    print secretnum + str(mid) + "?"
    herp = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")
if herp == 'c':
    print "Game over. Your secret number was:", mid

rawDescription: Taking a Python course and learning about bisection search, confused on why my semantics are incorrect


code:
import histogram, numpy
y = range(0, 100) #Except I used real data
Hist = histogram(y, bins=100, range=[0,100])
colors = ['red', 'blue', 'green', ]
ranges = [[0,30], [30,31], [31,100]]
fig = pyplot.figure(figsize=(8,6))
ax, plt, _ = fig.plothist(Hist, alpha=0) # plot for spacing
for c, r in zip(colors, ranges):
    plt = ax.overlay(Hist, range=r, facecolor=c)
print y

CumulativeHist = numpy.cumsum(h6)
colors = ['red', 'blue', 'green', ]
ranges = [[0,30], [30,31], [31,100]]
fig = pyplot.figure(figsize=(8,6))
ax, plt, _ = fig.plothist(CumulativeHist, alpha=0) # plot for spacing
for c, r in zip(colors, ranges):
    plt = ax.overlay(CumulativeHist, range=r, facecolor=c)

pyplot.show()

rawDescription: Modifying Matplotlib multicoloured histogram script to make it cumulative


rawDescription: Is there a way to refer to the entire matched expression in re.sub without the use of a group?


code:
foodmap = {'HotDog': HotDog, 'Burger': Burger}

print [foodmap[f]() for (f, c) in todayOrders for x in range(c)]

rawDescription: Create a list of objects

description: Create a list of objects


code:
code = """
def hello():
    print 'Hello world'
"""
exec code
hello()

rawDescription: How to store Python functions in a SQLite table?

description: Store Python functions in a SQLite table


code:
from multiprocessing.process import Process
import sys
import os

def child(newstdin):
    sys.stdin = newstdin
    print 'test'
    message = raw_input() #this is where this process doesn't fail anymore
    print message

def main():
    newstdin = os.fdopen(os.dup(sys.stdin.fileno()))
    p =  Process(target = child, args=(newstdin,))
    p.start()
    p.join()

if __name__ == '__main__':
    main()

rawDescription: Python user input in child process

description: Python user input in child process


rawDescription: convert number to string in python

description: Convert number to string in python


code:
numberOfSets = 3
test = [set() for _ in xrange(numberOfSets)]
test[0].add("testing")
print test

rawDescription: How do I create a list of independent sets in python?

description: Create a list of independent sets in python


code:
from multiprocessing import Process, Manager

def mysubprocess(shared_dict):
    item = shared_dict['list_item'] = list()
    item.append('test')
    shared_dict['list_item'] = item
    print 'subprocess:', shared_dict

manager = Manager()
shared_dict = manager.dict()
p = Process(target=mysubprocess, args=(shared_dict,))
p.start()
p.join()
print 'main process:', shared_dict

rawDescription: Cannot append items to multiprocessing shared list


code:
from threading import Thread

class WorkerThread(Thread):

    def __init__(self, func):

        Thread.__init__(self)
        self.func = func

    def run(self):

        for i in range(10):
            self.func()

class VolumePanel:

    def __init__(self):

        #self.thread = WorkerThread(self.startStop)
        #self.thread.start() #or elsewhere
        pass

    def startStop(self):

        print "in def startStop()"

vp = VolumePanel()
thread = WorkerThread(vp.startStop)
thread.start()

rawDescription: Calling a Class function from another Class


code:
M = 20
N = 20

a = np.random.normal(0, 1, (N, M))
b = np.random.normal(0, 3, N)[:, None]

print np.var(a + b, axis=0)
print np.var(a + b, axis=1)

rawDescription: How to generate a random gaussian matrix with different variance along each axis

description: Generate a random gaussian matrix with different variance along each axis


code:
def selectst(self):
    try:
          print "S E L E C T"
          self.cursor.execute("SELECT d_id,d_link,d_name FROM `d_details`")
          print  self.cursor.fetchall() # or fetchone() for one record

    except MySQLdb.Error as error:
                        print "---------------------"""
                        print(error)
    #self.cnx.commit() there is no need of commit here since we are not changing the data of the table

rawDescription: Executing Select statement by using mysql-python gives None


code:
import re

def url(x) :
    match = re.search(r"href=\"(.*)\"", x)
    if match:
        return match.group(1)
    else:
        return ""

print url('asdfasdf')

rawDescription: Creating a function that returns the URL of an HTML hyperlink


code:
#Initiating Variables for use by importing functions
module_name = 'mymod'
filename = 'action_file'
source = PossibleMatches[0][1] #the source code from the best matched option

# define module_name somewhere
import types
module = types.ModuleType(module_name)

# source should the code to execute
# filename should be a pseudo-filename that the code's from
# (it doesn't actually have to exist; it's used for error messages)
code_object = compile(source, filename, 'exec')

#execute the code in the context of the module
exec code_object in module.__dict__

#Executing the 'Main' Function from the code
return module.Main()

rawDescription: Dynamically running python code on google app engine


code:
import sys

def userConfirm():
    userChoice = raw_input("Are you happy with results? (Y or N or Q): ")
    if userChoice == 'N':
        return False
    elif userChoice == 'Q':
        sys.exit("You Quit the Program")
    elif userChoice == 'Y':
        print "OK Proceeding"
        return True

while True:
    answer = shuffle(filter3)
    print answer
    if userConfirm():
        break

rawDescription: python how to GOTO/REDO

description: Python how to GOTO/REDO


rawDescription: Format a string with a space between every two digits


code:
from itertools import izip
t = [1,2,3,4,5,6,7,8,9,10,11,12]
for a, b in izip(*[iter(t)]*2):
    print a, b
for a, b, c in izip(*[iter(t)]*3):
    print a, b, c
for a, b, c, d in izip(*[iter(t)]*4):
    print a, b, c, d
for a, b, c, d, e, f in izip(*[iter(t)]*6):
    print a, b, c, d, e, f

rawDescription: how convert list of int to list of tuples

description: How convert list of int to list of tuples


code:
import wx

########################################################################
class Car:
    """"""

    #----------------------------------------------------------------------
    def __init__(self, id, model, make, year):
        """Constructor"""
        self.id = id
        self.model = model
        self.make = make
        self.year = year

########################################################################
class MyForm(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial")

        # Add a panel so it looks the correct on all platforms
        panel = wx.Panel(self, wx.ID_ANY)

        cars = [Car(0, "Ford", "F-150", "2008"),
                Car(1, "Chevrolet", "Camaro", "2010"),
                Car(2, "Nissan", "370Z", "2005")]

        sampleList = []
        self.cb = wx.ComboBox(panel,
                              size=wx.DefaultSize,
                              choices=sampleList)
        self.widgetMaker(self.cb, cars)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.cb, 0, wx.ALL, 5)
        panel.SetSizer(sizer)

    #----------------------------------------------------------------------
    def widgetMaker(self, widget, objects):
        """"""
        for obj in objects:
            widget.Append(obj.make, obj)
        widget.Bind(wx.EVT_COMBOBOX, self.onSelect)

    #----------------------------------------------------------------------
    def onSelect(self, event):
        """"""
        print "You selected: " + self.cb.GetStringSelection()
        obj = self.cb.GetClientData(self.cb.GetSelection())
        text = """
        The object's attributes are:
        %s  %s    %s  %s

        """ % (obj.id, obj.make, obj.model, obj.year)
        print text

# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

rawDescription: How to create dropdown with value and text node - WXPython

description: Create dropdown with value and text node - WXPython


code:
from itertools import product
for i in product(*[range(dim) for dim in a.shape]):
    print i, a[i]

rawDescription: Iterate over nested arrays storing indexes


code:
class SpecialDictionary(dict):
    def __missing__(self, k):
        return 0

words = ['a', 'b', 'c', 'a', 'b']
special_dict = SpecialDictionary()
for w in words:
    special_dict[w] += 1
print special_dict
#{'c': 1, 'a': 2, 'b': 2}

rawDescription: Count words without checking that a word is "in" dictionary