code:
def f1():
  print "hi"

def f2():
  print "bye"

functions = {1: f1, 2: f2}  # dict of functions (Note: no parenthesis)

def options(x):
    return functions[x]()   # Get the function against the index and invoke it

options(1)
# hi

options(2)
# bye

rawDescription: accessing python dict with function values

description: Accessing python dict with function values


code:
for i in [x for x in dir(signal) if x.startswith("SIG")]:
  try:
    signum = getattr(signal,i)
    signal.signal(signum,sighandler)
  except RuntimeError,m:
    print "Skipping %s"%i

rawDescription: Python - Trap all signals

description: Python - Trap all signals


code:
import os
import re
import csv
from bs4 import BeautifulSoup

def driver(folder, input_filename, output_filename1, output_filename2):
    os.chdir(folder)
    with open(input_filename, 'r') as f:
        hearing = f.read()

    Hearing = BeautifulSoup(hearing)
    Hearing = Hearing.get_text()
    Hearing = Hearing.split("erroneous text")

    speakers = re.findall("\\n    Mr. [A-Z][a-z]+\.|\\n    Ms. [A-Z][a-z]+\.|\\n    Congressman [A-Z][a-z]+\.|\\n   Congresswoman [A-Z][a-z]+\.|\\n   Chairwoman [A-Z][a-z]+\.|\\n   Chairman [A-Z][a-z]+\.", hearing)
    speakers = list(set(speakers))

    print speakers

    position = []
    for speaker in speakers:
        x = hearing.find(speaker)
        position.append(x)

    def find_speaker(hearing, speakers):
        position = []
        for speaker in speakers:
            x = hearing.find(speaker)
            if x==-1:
                x += 1000000
            position.append(x)
        first = min(position)
        name = speakers[position.index(min(position))]
        name_length = len(name)
        chunk = [name, hearing[0:first], hearing[first+name_length:]]
        return chunk

    chunks = []

    print hearing
    names = []
    while len(hearing)>10:
        chunk_try = find_speaker(hearing, speakers)
        hearing = chunk_try[2]
        chunks.append(chunk_try[1])
        names.append(chunk_try[0].strip())

    print len(hearing)#0

    #print dialogue[0:5]

    chunks.append(hearing)
    chunks = chunks[1:]
    print len(names) #138
    print len(chunks) #138

    data = zip(names, chunks)

    with open(output_filename1,'wb') as f:
        w=csv.writer(f)
        w.writerow(['Speaker','Speach'])
        for row in data:
            w.writerow(row)

    paragraphs = str(chunks)
    print (paragraphs)

    Paragraphs = paragraphs.split("\\n")

    data1 = zip(Paragraphs)

    with open(output_filename2,'wb') as f:
        w=csv.writer(f)
        w.writerow(['Paragraphs'])
        for row in data1:
            w.writerow(row)

    return True  # success

if __name__ == '__main__':
    driver('path in computer', 'hearing_name.htm', 'filename.csv', 'Paragraphs.csv')

rawDescription: Parse a 90MB data archive in Python

description: Parse a 90MB data archive in Python


code:
import numpy

my_ar = numpy.array((0,5,10))
print my_ar

transformed = numpy.array(map(lambda x:numpy.array((x,x*2,x*3)), my_ar))
print transformed

print transformed.shape

rawDescription: Adding a dimension to every element of a numpy.array


code:
def f():
    def g():
        print myvar
    myvar = 1
    g()

f()

rawDescription: Convention for declaring variables in Python, when required for scope?


code:
import facebook

token = 'your token'

graph = facebook.GraphAPI(token)
profile = graph.get_object("me")
friends = graph.get_connections("me", "friends")

friend_list = [friend['name'] for friend in friends['data']]

print friend_list

rawDescription: Python - Facebook API - Need a working example


code:
from itertools import groupby

print " ".join([k for k, group in groupby(d['key']) if len(list(group)) == 1])
# -> a b d

rawDescription: how to print elements which occur only once in a list, without counting

description: Print elements which occur only once in a list, without counting


code:
#! /usr/bin/env python
import sys
import termios
import copy
from time import sleep

fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = copy.deepcopy(old)
new[3] = new[3] & ~termios.ECHO

try:
  termios.tcsetattr(fd, termios.TCSADRAIN, new)
  sleep(5)
except KeyboardInterrupt, ke:
  pass
finally:
  termios.tcsetattr(fd, termios.TCSADRAIN, old)
  sys.exit(0)

rawDescription: How to avoid ^C getting printed after handling KeyboardInterrupt

description: Avoid ^C getting printed after handling KeyboardInterrupt


code:
count = 0
one_hour = 60 * 60
file = open('logFile.log', 'r')
while 1:
    where = file.tell()
    line = file.readline()
    if not line:
        count = count + 1
        if count >= one_hour:
          break
        time.sleep(1)
        file.seek(where)
    else:
        print line
        count = 0   # Here needs to reset the time couter!

rawDescription: End a sleep loop in Python

description: End a sleep loop in Python


code:
import regex as re
string = 'this is a test of the loss of offsite power'

all_tags = ['offsite power', 'loss of offsite power']
reg_ex = '|'.join(['\\b%s\\b' % t for t in all_tags])

expression = re.compile(reg_ex, re.IGNORECASE)

# mind overlapped=True !
matches = re.findall(expression, string, overlapped=True)
print matches
# ['loss of offsite power', 'offsite power']

rawDescription: How to get all matches in Python using RegEx when the pattern has similar text?

description: Get all matches in Python using RegEx when the pattern has similar text


code:
import os
import sys
import pexpect

def run_server():
    server_dir = '/path/to/server/root'
    current_dir = os.path.abspath(os.curdir)

    os.chdir(server_dir)
    server_call = pexpect.spawn('atlas-run')
    server_response = server_call.expect(['Server Error!', 'Sever is running!'])
    os.chdir(current_dir)
    if server_response:
        return server_call #return server spawn object so we can shutdown later
    else:
        print 'Error starting the server: %s'%server_response.after
        sys.exit(1)

def run_unittests():
    # several ways to do this. either make a unittest.TestSuite or run command line
    # here is the second option
    unittest_dir = '/path/to/tests'
    pexpect.spawn('python -m unittest discover -s %s -p "*test.py"'%unittest_dir)
    test_response = pexpect.expect('Ran [0-9]+ tests in [0-9\.]+s') #catch end
    print test_response.before #print output of unittests before ending.
    return

def main():
    server = run_sever()
    run_unittests()
    server.sendcontrol('d') #shutdown server

if __name__ == "__main__":
    main()

rawDescription: In python, how can I run a command-line program that does not return until I send Ctrl+D to it.


code:
from difflib import Differ
d = Differ()
print ''.join(line for line in d.compare(text1, text2) if not line.startswith(' '))

rawDescription: Python difflib.Differ with Contextual difference


code:
record = False
for line in file:
    if line.startswith('--END--'):  # so you don't catch any extra lines
        break  # this exits the loop
    if record:
        print line  # or whatever code you want to run on each username
    if line.startswith('USERNAME'):
        record = True  # this will be visible in the next loop iteration

rawDescription: Parsing a line in a text file that follows a static line


code:
matrix = open('workfile', 'w')
A = np.array([])
for row in matrix:
    A = numpy.append(A, row)

print A

rawDescription: How to append elements to a numpy array

description: Append elements to a numpy array


code:
from itertools import product, islice

# all values, generator expression
query = ((x['val'], y['val']) for x, y in product(R, S) if x['id'] == y['id'])

# just the first 10
limited = islice(query, 10)

for row in limited:
    print row

rawDescription: mapping sql to python

description: Mapping sql to python


code:
reader = csv.reader(f)
print [i[1] for i in reader]

rawDescription: Python reading specific csv column into list


code:
import urllib2
from StringIO import StringIO

def mock_response(req):
    if req.get_full_url() == "http://example.com":
        resp = urllib2.addinfourl(StringIO("mock file"), "mock message", req.get_full_url())
        resp.code = 200
        resp.msg = "OK"
        return resp

class MyHTTPHandler(urllib2.HTTPHandler):
    def http_open(self, req):
        print "mock opener"
        return mock_response(req)

my_opener = urllib2.build_opener(MyHTTPHandler)
urllib2.install_opener(my_opener)

response=urllib2.urlopen("http://example.com")
print response.read()
print response.code
print response.msg

rawDescription: How do I unit test a module that relies on urllib2?

description: Unit test a module that relies on urllib2


code:
from cStringIO import StringIO
import csv
data = StringIO('name,phone,"addres 1, address 2",foo,bar')
for row in csv.reader(data):
    print row

rawDescription: mixed format CSV

description: Mixed format CSV


code:
#!/usr/bin/env python

import random
import sys

pegs = range(2, 11)

def roll_dice():
    return random.randint(1, 5) + random.randint(1, 5)

while True:
    roll = roll_dice()
    print "You rolled %s" %roll
    available_choices = set(p for p in pegs if p != 'X') - set(range(roll+1, 11))
    if len(available_choices) == 0:
        print "FAIL SAUCE"
        sys.exit()
    while True:
        choice = raw_input("Choose a number %s: " % (", ".join(str(x) for x in sorted(list(available_choices)))))
        if choice == 'q':
            sys.exit()
        choice = int(choice)
        if choice in available_choices:
            break
        print "Nice try buddy... pick a number in range, that hasn't been picked"
    pegs[choice - 2] = 'X'
    print "".join("(%s)" % p for p in pegs)
    if len([x for x in pegs if x == 'X']) == 9:
        print "WINNER!"
        sys.exit()

rawDescription: Creating a python game, dealing with lists


code:
from socket import *
import sys

if len(sys.argv) <= 1:
    print 'Usage: "python ProxyServer.py server_ip"\n[server_ip : It is the IP Address of the Proxy Server'
    sys.exit(2)

# Create a server socket, bind it to a port and start listening
tcpSerPort = 8888
tcpSerSock = socket(AF_INET, SOCK_STREAM)

# Prepare a server socket
tcpSerSock.bind(('', tcpSerPort))
tcpSerSock.listen(5)

while True:
    # Start receiving data from the client
    print 'Ready to serve...'
    tcpCliSock, addr = tcpSerSock.accept()
    print 'Received a connection from: ', addr
    message = tcpCliSock.recv(1024)

    # Extract the filename from the given message
    print message.split()[1]
    filename = message.split()[1].partition("/")[2]
    fileExist = "false"
    filetouse = "/" + filename
    try:
        # Check whether the file exists in the cache
        f = open(filetouse[1:], "r")
        outputdata = f.readlines()
        fileExist = "true"
        print 'File Exists!'

        # ProxyServer finds a cache hit and generates a response message
        tcpCliSock.send("HTTP/1.0 200 OK\r\n")
        tcpCliSock.send("Content-Type:text/html\r\n")

        # Send the content of the requested file to the client
        for i in range(0, len(outputdata)):
            tcpCliSock.send(outputdata[i])
        print 'Read from cache'

        # Error handling for file not found in cache
    except IOError:
        print 'File Exist: ', fileExist
        if fileExist == "false":
            # Create a socket on the proxyserver
            print 'Creating socket on proxyserver'
            c = socket(AF_INET, SOCK_STREAM)

            hostn = filename.replace("www.", "", 1)
            print 'Host Name: ', hostn
            try:
                # Connect to the socket to port 80
                c.connect((hostn, 80))
                print 'Socket connected to port 80 of the host'

                # Create a temporary file on this socket and ask port 80
                # for the file requested by the client
                fileobj = c.makefile('r', 0)
                fileobj.write("GET " + "http://" + filename + " HTTP/1.0\n\n")

                # Read the response into buffer
                buff = fileobj.readlines()

                # Create a new file in the cache for the requested file.
                # Also send the response in the buffer to client socket
                # and the corresponding file in the cache
                tmpFile = open("./" + filename, "wb")
                for i in range(0, len(buff)):
                    tmpFile.write(buff[i])
                    tcpCliSock.send(buff[i])

            except:
                print 'Illegal request'

        else:
            # HTTP response message for file not found
            # Do stuff here
            print 'File Not Found...Stupid Andy'
            a = 2
    # Close the socket and the server sockets
    tcpCliSock.close()

# Do stuff here

rawDescription: Homework - Python Proxy Server

description: Homework - Python Proxy Server


code:
import threading

# Event marking the GUI thread as having imported GTK.  GTK must not
# be imported before this event's flag is set.
gui_ready = threading.Event()

def run_gui_thread():
    import gobject
    gobject.threads_init()
    import gtk
    gui_ready.set()
    gtk.main()

gui_thread = threading.Thread(target=run_gui_thread)
gui_thread.start()

# wait for the GUI thread to initialize GTK
gui_ready.wait()

# it is now safe to import GTK-related stuff
import gobject, gtk

def countdown(maxSec):
    while maxSec > 0:
        print maxSec
        maxSec -= 1

    gobject.idle_add(gtk.main_quit)

worker = threading.Thread(target=countdown, args=(5,))
print 'starting work...'
worker.start()

# When both the worker and gui_thread finish, the main thread
# will exit as well.

rawDescription: PyGtk: Run gtk.main() loop in a seperate thread


code:
#!/usr/bin/env python

from cmd import Cmd
from twisted.internet import reactor

class CommandProcessor(Cmd):
    def do_EOF(self, line):
        return True

    def do_YEP(self, line):
        reactor.callFromThread(on_main_thread, "YEP")

    def do_NOPE(self, line):
        reactor.callFromThread(on_main_thread, "NOPE")

def on_main_thread(item):
    print "doing", item

def heartbeat():
    print "heartbeat"
    reactor.callLater(1.0, heartbeat)

reactor.callLater(1.0, heartbeat)
reactor.callInThread(CommandProcessor().cmdloop)
reactor.run()

rawDescription: Python Twisted integration with Cmd module


code:
import requests
from BeautifulSoup import BeautifulSoup as bs
#grab HTML
r = requests.get(r'http://www.amazon.com/s/ref=sr_pg_1?rh=n:172282,k%3adigital%20camera&keywords=digital%20camera&ie=UTF8&qid=1343600585')
html = r.text
#parse the HTML
soup = bs(html)

results= soup.findAll('div', attrs={'class': 'data'})

print results

rawDescription: Beautifulsoup unable to extract data using attrs=class


code:
list = data_array
string = str(raw_input("Search keyword: "))
print string
for s in list:
    if string in str(s):
        print 'Yes'
        print list.index(s)

rawDescription: Python: if list contains string print all the indexes / elements in the list that contain it


code:
import lxml.etree as et
from lxml.builder import E

xml = """
<text>
    <name>
        <ref>foobar</ref>
    </name>
</text>
"""

tree = et.fromstring(xml)

for name in tree.findall('name'):
    text = name.find('ref').text
    tree.replace(name, E.ref(E.name(text)))

print et.tostring(tree)

rawDescription: reverse the nesting of elements with python lxml.etree

description: Reverse the nesting of elements with python lxml.etree


code:
try:
    key, value = name.split(":")
except ValueError:
    print "Failure"
else:
    print "Success"

rawDescription: Python Check if String split succeeded

description: Python Check if String split succeeded


code:
import boto.ec2

sgs = boto.ec2.connect_to_region('us-east-1').get_all_security_groups()

for sg in sgs:
    for rule in sg.rules:
        print sg, sg.id, "inbound:", rule, " source:", rule.grants

rawDescription: limit nested for loop output

description: Limit nested for loop output


rawDescription: How to re-work this ROT13 Function

description: Re-work this ROT13 Function


code:
word = raw_input("Enter word: ")
lst = []
if "a" in word:
    lst.append(word)
    print lst

rawDescription: How to search for specific letter in a word, then add that word with that letter to a list?

description: Search for specific letter in a word, then add that word with that letter to a list


code:
import time

class wrapper(list):

    def __getattribute__(self, name):
        TO_OVERRIDE = ['append']
        if name in TO_OVERRIDE:
            start = time.clock()
        ret = super(list, self).__getattribute__(name)
        if name in TO_OVERRIDE:
            stop = time.clock()
            print "It took %s seconds to perform %s" % (str(stop-start), name)
        return ret

profiled_list = wrapper('abc')
print profiled_list
profiled_list.append('d')
print profiled_list
profiled_list.pop()
print profiled_list

rawDescription: Python: wrap all functions in a library

description: Python: wrap all functions in a library


code:
notes = ["10.0% higher", "5.0% lower", "Same as", "21.2% lower"]

changes = []
for note in notes:
    m = re.findall("(?:(\d+\.\d+)% )?(higher|lower|Same as)", note)
    if len(m):
       if m[0][1] == 'higher':
          changes += [float(m[0][0])]
       elif m[0][1] == 'lower':
          changes += [-float(m[0][0])]
       else:
          changes += [0.0]

print changes

rawDescription: Python regex String array to float array


code:
import os
import re

class FileSystem(object):
    class NoAccess(Exception): pass
    class Unknown(Exception): pass

    @classmethod
    def _get_all_subclasses(cls):
        """ Recursively generate of all the subclasses of class cls. """
        for subclass in cls.__subclasses__():
            yield subclass
            for subclass in subclass._get_all_subclasses():
                yield subclass

    @staticmethod
    def _get_prefix(s):
        """ Extract any file system prefix at beginning of string s and
            return a lowercase version of it or None when there isn't one.
        """
        match = re.match(r'\s*([^:]+)://', s)  # matches "xxx:" if x is any char
        return match.group(1).lower() if match else None

    def __new__(cls, path):
        path_prefix = cls._get_prefix(path)
        for subclass in cls._get_all_subclasses():
            if subclass.prefix == path_prefix:
                return object.__new__(subclass , path)  # using "object" avoids recursion
        else:  # no subclass with matching prefix found (or with prefix of None)
            raise FileSystem.Unknown(
                'path "{}" has no known file system prefix'.format(path))

    def count_files(self):
        raise NotImplementedError

class Nfs(FileSystem):
    prefix = 'nfs'

    def __init__ (self, path):
        pass

    def count_files(self):
        pass

class LocalDrive(FileSystem):
    prefix = None  # default when no file system prefix is found

    def __init__(self, path):
        if not os.access(path, os.R_OK):
            raise FileSystem.NoAccess('Cannot read directory')
        self.path = path

    def count_files(self):
        return sum(os.path.isfile(os.path.join(self.path, name))
                    for name in os.listdir(self.path))

data1 = FileSystem('nfs://192.168.1.18')
data2 = FileSystem('c:/')  # change as necessary for testing

print type(data1)
print type(data2)

print data2.count_files()

rawDescription: Improper use of __new__ to generate classes in Python?


code:
import httplib
from urlparse import urlparse

def checkUrl(url):
    p = urlparse(url)
    conn = httplib.HTTPConnection(p.netloc)
    conn.request('HEAD', p.path)
    resp = conn.getresponse()
    return resp.status < 400

if __name__ == '__main__':
    print checkUrl('http://www.stackoverflow.com') # True
    print checkUrl('http://stackoverflow.com/notarealpage.html') # False

rawDescription: Python script to see if a web page exists without downloading the whole page?


code:
from cStringIO import StringIO
import xml.etree.ElementTree as ET

NS_MAP = {
    'http://www.red-dove.com/ns/abc' : 'rdc',
    'http://www.adobe.com/2006/mxml' : 'mx',
    'http://www.red-dove.com/ns/def' : 'oth',
}

DATA = '''<?xml version="1.0" encoding="utf-8"?>
<rdc:container xmlns:mx="http://www.adobe.com/2006/mxml"
                 xmlns:rdc="http://www.red-dove.com/ns/abc"
                 xmlns:oth="http://www.red-dove.com/ns/def">
  <mx:Style>
    <oth:style1/>
  </mx:Style>
  <mx:Style>
    <oth:style2/>
  </mx:Style>
  <mx:Style>
    <oth:style3/>
  </mx:Style>
</rdc:container>'''

tree = ET.parse(StringIO(DATA))
some_node = tree.getroot().getchildren()[1]
print ET.fixtag(some_node.tag, NS_MAP)
some_node = some_node.getchildren()[0]
print ET.fixtag(some_node.tag, NS_MAP)

rawDescription: Alter namespace prefixing with ElementTree in Python


code:
import time
from lxml import etree
import urllib
while True:
    time.sleep(60) # for 1 minute time interval
    #time.sleep(86400) # for 1 day time interval
    web = urllib.urlopen("http://www.yoursite.com/")
    html = etree.HTML(web.read())
    tr_nodes = html.xpath('//table/tr')
    td_content = [tr.xpath('td') for tr in tr_nodes  if [td.text for td in tr.xpath('td')][2] == 'Chennai' or [td.text for td in tr.xpath('td')][2] == 'Across India'  or 'Chennai' in [td.text for td in tr.xpath('td')][2].split('/') ]
    main_list = []
    for i in td_content:
        if i[5].text == 'Freshers' or  'Freshers' in i[5].text.split('/') or  '0' in i[5].text.split(' '):
            sub_list = [td.text for td in i]
            sub_list.insert(6,'http://yoursite.com/%s'%i[6].xpath('a')[0].get('href'))
            main_list.append(sub_list)
    print 'main_list',main_list

rawDescription: How to Trace Particular Content in Web Page using Python in Certain Time Period?


code: print "my var's content: %s" %( my_var if my_var != "" else "blank" )

rawDescription: Python Try: Except: inside a function(a, b, c)


code:
def get_ans(index):
    ans = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]
    end = index - 1
    start = end - 4
    if start < 0:
        result = ans[start:] + ans[:end]
    else:
        result = ans[start:end]
    print result

if __name__ == "__main__":
    mm=int(raw_input("enter a number "))
    get_ans(mm)

rawDescription: How can I Display previous 4 value excluding current value in python?


code:
import math

def s(x):
    return 0.298**k/math.factorial(k)

prevSK = 0
for k in range(0,5):
    try:
        print (s(k))
        print (s(k)/prevSK)
        prevSK = s(k)
    except Exception, e:
        print e
        prevSK = s(k)

        continue

rawDescription: Creating loop from another loop values using dividing


code:
def combined_graphs_edges(G, H, weight = 1.0):
    for u,v,hdata in H.edges_iter(data=True):
        # multply attributes of H by weight
        attr = dict( (key, value*weight) for key,value in hdata.items())
        # get data from G or use empty dict if no edge in G
        gdata = G[u].get(v,{})
        # add data from g
        # sum shared items
        shared = set(gdata) & set(hdata)
        attr.update(dict((key, attr[key] + gdata[key]) for key in shared))
        # non shared items
        non_shared = set(gdata) - set(hdata)
        attr.update(dict((key, gdata[key]) for key in non_shared))
        yield u,v,attr
    return

if __name__ == '__main__':
    import networkx as nx
    G = nx.Graph([('a','b', {'a': 1, 'b':2})])
    H = nx.Graph([('a','b', {'a': 3, 'c':4})])
    print list(combined_graphs_edges(G,H,weight=0.5))
    # or to make a new graph
    graph = G.copy()
    graph.add_edges_from(combined_graphs_edges(G,H,weight=0.5))

rawDescription: Combine two weighted graphs in NetworkX

description: Combine two weighted graphs in NetworkX


code:
import csv

def print_friends():
    reader = csv.reader(open("friends.csv", "rb"), delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for row in reader:
        print row

def friend_exists(friend):
    reader = csv.reader(open("friends.csv", "rb"), delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    for row in reader:
        if (row == friend):
            return True
    return False

def add_friend(name, phone, address, birthday):
    friend = [name, phone, address, birthday]
    if friend_exists(friend):
        return False

    writer = csv.writer(open("friends.csv", "ab"), delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
    writer.writerow(friend)
    return True

print "print_friends: "
print_friends()

print "get_friend: "
test_friend = ["barney", "4321 9876", "New York", "2000"]
print friend_exists(test_friend)

print "add_friend: "
print add_friend("barney", "4321 9876", "New York", "2000")

rawDescription: Adding data to a CSV file through Python


code:
import sys
import os
import webbrowser
import gdata.gauth
import oauth2client.client
import oauth2client.file
import oauth2client.tools
import gdata.gauth
import gdata.client
import gdata.apps.groups.client

APICONSOLE = 'https://code.google.com/apis/console'
SCOPES = 'https://apps-apis.google.com/a/feeds/groups/'
OAUTH2FILENAME = 'credentials.oauth2'
OAUTH2JSONFILE = 'client_secrets.json'
OAUTH2USERAGENT = 'GROUPS'
MISSING_OAUTHJSONFILE_MESSAGE = """
You must create or download a client secrets json file (%s)
from the Google APIs console <https://code.google.com/apis/console>.
Attemping to open page with your browser ...
""" % os.path.join(os.path.dirname(__file__), OAUTH2JSONFILE)

# populate with approprate values
DOMAIN = 'your-domain'
GROUP_ID = 'agroup@your.domain'

if not os.path.isfile(OAUTH2JSONFILE):
  message = MISSING_OAUTHJSONFILE_MESSAGE
  print message
  try:
    webbrowser.open(str(APICONSOLE))
  except Exception, e:
    print "Error opening web page"
    sys.exit(1)
  message = 'When %s is created/downloaded press Enter to continue ... ' %(OAUTH2JSONFILE)
  raw_input(message)
oauth2_flow = oauth2client.client.flow_from_clientsecrets(OAUTH2JSONFILE,
  scope=SCOPES,message=MISSING_OAUTHJSONFILE_MESSAGE)
storage = oauth2client.file.Storage(OAUTH2FILENAME)
oauth2_credentials = storage.get()
if oauth2_credentials is None or oauth2_credentials.invalid:
  oauth2_credentials = oauth2client.tools.run(oauth2_flow, storage)
oauth2_token = gdata.gauth.OAuth2Token(
  client_id=oauth2_credentials.client_id,
  client_secret=oauth2_credentials.client_secret,
  scope=SCOPES,
  user_agent=OAUTH2USERAGENT,
  access_token=oauth2_credentials.access_token,
  refresh_token=oauth2_credentials.refresh_token)
# authorize client
groups_client = oauth2_token.authorize(
  gdata.apps.groups.client.GroupsProvisioningClient(domain=DOMAIN))
print 'Authorized domain %s . . .\n' %(DOMAIN)
group_entry = groups_client.RetrieveGroup(group_id=GROUP_ID)
print group_entry.group_id
print group_entry.group_name
print group_entry.description
print group_entry.email_permission

sys.exit(0)

rawDescription: Google App Engine and Group Provisioning


code:
from __future__ import print_function

import sys

def a():
    print('a()')

def comment_1(s):
    lines = s.split('\n')
    return '\n'.join(line.replace(';','#;',1) if line.strip().startswith('1;') else line for line in lines)

_blocked = False

def remove_1(f):
    global _blocked
    if _blocked:
        return f
    import inspect
    source = inspect.getsource(f)
    new_source = comment_1(source)
    env = sys.modules[f.__module__].__dict__
    _blocked = True
    try:
        exec new_source in env
    finally:
        _blocked = False
    return env[f.__name__]

@remove_1
def f():
    1;a()
    print('Some statements 1')
    1;a()
    print('Some statements 2')

f()

def remove_1(f):
    import inspect
    source = inspect.getsource(f)
    new_source = comment_1(source)
    env = sys.modules[f.__module__].__dict__.copy()
    exec new_source in env
    return env[f.__name__]

rawDescription: Preprocessing function text in runtime bofore compilation


code:
def dragEnterEvent(self, event):
    if event.mimeData().hasUrls():
        event.accept()
    else:
        event.ignore()

def dropEvent(self, event):
    for url in event.mimeData().urls():
        path = url.toLocalFile().toLocal8Bit().data()
        if os.path.isfile(path):
            print path
            # do other stuff with path...

rawDescription: PyQt: Getting file name for file dropped in app


code:
import cairo
import rsvg

def convert(data, ofile, maxwidth=0, maxheight=0):

    svg = rsvg.Handle(data=data)

    x = width = svg.props.width
    y = height = svg.props.height
    print "actual dims are " + str((width, height))
    print "converting to " + str((maxwidth, maxheight))

    yscale = xscale = 1

    if (maxheight != 0 and width > maxwidth) or (maxheight != 0 and height > maxheight):
        x = maxwidth
        y = float(maxwidth)/float(width) * height
        print "first resize: " + str((x, y))
        if y > maxheight:
            y = maxheight
            x = float(maxheight)/float(height) * width
            print "second resize: " + str((x, y))
        xscale = float(x)/svg.props.width
        yscale = float(y)/svg.props.height

    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, x, y)
    context = cairo.Context(surface)
    context.scale(xscale, yscale)
    svg.render_cairo(context)
    surface.write_to_png(ofile)

rawDescription: Server-side SVG to PNG (or some other image format) in python


code:
import kivy
import datetime

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.factory import Factory
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.scatter import Scatter

Builder.load_string("""
<MyScatter>:
    id: cool
    #pos: 200, 200
    #size: 300,300
    Image:
        id: img
        source: "cat.png"
        allow_stretch:  True
        size: cool.size
<P>:
    MyScatter:

""")

class MyScatter(Scatter):

    def on_touch_move(self, touch): #magic time!!!!
        res =  super(MyScatter, self).on_touch_move(touch)
        if res: #Yay do something!
            print self.center
        return res
class P(FloatLayout):
    pass

class MyApp(App):

    def build(self):
        return P()

if __name__ == '__main__':
    MyApp().run()

rawDescription: Kivy Get Position of Widget in Scatter while moving it


code:
xls = xlrd.open_workbook(xlsname)
worksheet = xls.sheet_by_name('Accounts') # Use whatever name is on the worksheet tab in excel
max_col = worksheet.ncols - 1 # Cells addressed from 0
max_row = worksheet.nrows - 1 # Cells addressed from 0
account_col = 0 # Assuming it's the first column

for row in xrange(0, max_row):
    value = xlrd.cell_value(row, account_col)
    if value in favorites:
        print "Do something"
        print "I can address other cells in this row if I want"
        for col in xrange(0, max_col):
            new_value = xlrd.cell_value(row, col)

rawDescription: Comparing list to spreadsheet (Python/ xlrd)


code:
from ethereum import tester as t

s = t.state()
code = """contract LogTest {
            event LogMyNumber(uint loggedNumber);

            function LogTest() {
            }

            function logSomething() {
                LogMyNumber(4);
            }
        }"""

c = s.abi_contract(code, language='solidity', sender=t.k0)
o = []
s.block.log_listeners.append(lambda x: o.append(c._translator.listen(x)))

c.logSomething()

assert len(o) == 1
assert o == [{"_event_type": 'LogMyNumber', "loggedNumber": 4}]

number_i_logged = o[0]["loggedNumber"]
print "You logged the number %d" % (number_i_logged)

rawDescription: How do I get event log information from pyethereum?

description: Get event log information from pyethereum


code:
from google.appengine.tools import appengine_rpc
use_production = True
if use_production:
  base_url = 'myapp.appspot.com'
else:
  base_url = 'localhost:8080'

def passwdFunc():
  return ('user@gmail.com','password')

def main(argv):
  rpcServer = appengine_rpc.HttpRpcServer(base_url,
                                          passwdFunc,
                                          None,
                                          'myapp',
                                          save_cookies=True,
                                          secure=use_production)
# Makes the actual call, I guess is the same for POST and GET?
blah = rpcServer.Send('/some_path/')

print blah

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

rawDescription: How to make an authenticated request from a script to appengine?

description: Make an authenticated request from a script to appengine


code:
import numpy as np
m = np.ma.masked_greater(np.random.rand(10), 0.5)
print np.ma.filled(m, 0)

rawDescription: get the data and the masked values as 0?

description: Get the data and the masked values as 0


code:
import re
s = "Dr. Peter is a great man. Dr. med. Lumpert Mercury is a great man."
for m in re.finditer("(?:Dr|med)\.\s*([A-Z][a-z]+(?: [A-Z][a-z]+)?)", s):
    print '%02d-%02d: %s' % (m.start(), m.end(), m.group(1))

rawDescription: simple regex to find two words

description: Simple regex to find two words


code:
layers = []
counter = 0
while True:
    layer = pkt.getlayer(counter)
    if (layer != None):
        print layer.name
        layers.append(layer.name)
    else:
        break
    counter += 1

print "Layers are:\t\t",layers

rawDescription: Get all the layers in a packet

description: Get all the layers in a packet


code:
r = requests.get("http://www.barchart.com/stocks/performance/12month.php")
html = r.text
soup = BeautifulSoup(html, 'html.parser')
tds = soup.find_all("td", {"class": "ds_name"})
for td in tds:
    print td.a.text

rawDescription: Extracting specific Information from a website using BeautifulSoup (Python)


code:
def traverse(o, tree_types=(list, tuple)):
    if isinstance(o, tree_types):
        for value in o:
            for subvalue in traverse(value, tree_types):
                yield subvalue
    else:
        yield o

data = [(1,1,(1,1,(1,"1"))),(1,1,1),(1,),1,(1,(1,("1",)))]
print list(traverse(data))
# prints [1, 1, 1, 1, 1, '1', 1, 1, 1, 1, 1, 1, 1, '1']

for value in traverse(data):
    print repr(value)
# prints
# 1
# 1
# 1
# 1
# 1
# '1'
# 1
# 1
# 1
# 1
# 1
# 1
# 1
# '1'

rawDescription: Python - Iterating through list of list

description: Python - Iterating through list of list


code:
import wx

class ChildWidget(wx.TextCtrl):

    def __init__(self, parent, name, pos):
        super(ChildWidget, self).__init__(parent, name=name, pos=pos)
        self.parent = parent
        self.Bind(wx.EVT_KEY_DOWN, self.keyPressed)

    def keyPressed(self, event):
        wx.PostEvent(self.parent, event)

class MainWidget(wx.Frame):

    def __init__(self, parent, title):
        super(MainWidget, self).__init__(parent, title=title)

        self.child1 = ChildWidget(self, name="Child1", pos=(0,0))
        self.child2 = ChildWidget(self, name="Child2", pos=(100,0))

        self.Bind(wx.EVT_KEY_DOWN, self.ChildKeyPressed)

        self.Layout()

    def ChildKeyPressed(self, event):
        print "Keypress from " + event.GetEventObject().GetName()

if __name__ == '__main__':
    app = wx.App(redirect=False)
    frame = MainWidget(None, "test")
    frame.Show(True)
    app.MainLoop()

rawDescription: Redirecting key events of child widgets to their parent frame widget


code:
def onSelectionChanged(tree_selection) :
    (model, pathlist) = tree_selection.get_selected_rows()
    for path in pathlist :
        tree_iter = model.get_iter(path)
        value = model.get_value(tree_iter,0)
        print value

listStore = gtk.ListStore(int)
treeview = gtk.TreeView()
treeview.set_model(listStore)
tree_selection = treeview.get_selection()
tree_selection.set_mode(gtk.SELECTION_MULTIPLE)
tree_selection.connect("changed", onSelectionChanged)

rawDescription: How to get value from selected item in treeview in PyGTK?

description: Get value from selected item in treeview in PyGTK


code:
class Foo(object):
    _all_names = {}
    def __init__(self, name=None):
        self.name = name
    @property
    def name(self):
        return self._name
    @name.setter
    def name(self, name):
        self._name = name
        self._all_names[name] = self
    @classmethod
    def get_by_name(cls, name):
        return cls._all_names[name]
    def __str__(self):
        return "Foo({0})".format(self.name)

a = Foo("alice")
b = Foo("bob")
print Foo.get_by_name("alice")

rawDescription: Python list, lookup object name, efficiency advice


code:
class class1:
  def greet(self):
    print "hi"

class class2:
  def greet(self):
    print "hello"

maker = class1
obj1 = maker()

maker = class2
obj2 = maker()

obj1.greet() # prints "hi"
obj2.greet() # prints "hello"

rawDescription: Python class factory ... or?

description: Python class factory ... or


code:
items = soup.findAll(id="info")
print items[0].span.b.contents[0]
print items[0].contents[3].strip()
print items[0].contents[5].strip().split(":", 1)[1]

rawDescription: Cleaning up and removing tags with BeautifulSoup


code:
import paramiko

conf = paramiko.SSHConfig()
conf.parse(open('/home/user/.ssh/config'))
host = conf.lookup('host')
print host

proxy = paramiko.ProxyCommand(host['proxycommand'])

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host["hostname"], username=host["user"], password='test', sock=proxy)
client.close()

rawDescription: Python ssh using Tor proxy

description: Python ssh using Tor proxy


code:
from selenium import selenium
import unittest, time, re, csv, logging

class Untitled(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444, "*firefox", "http://example.com")
        self.selenium.start()
        self.selenium.set_timeout("60000")

    def test_untitled(self):
        sel = self.selenium
        spamReader = csv.reader(open('SubDomainList.csv', 'rb'))
        for row in spamReader:
            try:
                sel.open(row[0])
            except Exception, e:
                ofile = open('outputTest.csv', 'ab')
                ofile.write("error on %s: %s" % (row[0],e))
            else:
                time.sleep(5)
                html = sel.get_html_source()
                ofile = open('output4001-5000.csv', 'ab')
                ofile.write(html.encode('utf-8') + '\n')
            ofile.close()

    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
     unittest.main()

rawDescription: Python Selenium handling Timeout Exceptions with a long list of URLs


code:
MESSAGE_FRAME_START = '@'
MESSAGE_FRAME_END = '#'

def process_raw_socket_message_stream(raw_message_stream):
    message_list = []
    cmd = ''
    last_footer_idx = message_string.rfind(MESSAGE_FRAME_END)
    cmd_str_len = len(message_string)
    byte_cnt = 0
    while (byte_cnt <= last_footer_idx):
        cmd_chr = message_string[byte_cnt]
        cmd += cmd_chr
        if cmd_chr == MESSAGE_FRAME_START:
            cmd = MESSAGE_FRAME_START
        elif cmd_chr == MESSAGE_FRAME_END:
            message_list.append(cmd)

        byte_cnt += 1

    # Remove the parsed data
    if last_footer_idx > 0:
        message_string = message_string[last_footer_idx+1:]

    return message_list, message_string

def add_message_frames(unframed_message):
    return MESSAGE_FRAME_START + unframed_message + MESSAGE_FRAME_END

def remove_message_frames(framed_message):
    clean_message = framed_message.lstrip(MESSAGE_FRAME_START)
    clean_message = clean_message.rstrip(MESSAGE_FRAME_END)
    return clean_message

def process_messsage(clean_message):
    # Do what needs to be done
    pass

def send_data(mysocket, payload):
    framed_payload = add_message_frames(payload)
    mysocket.sendall(framed_payload)

def receive_data(mysocket, byte_size=1024):
    data = ''
    while(1):
        try: # Wait for data
            data += mysocket.recv(byte_size)
            if(data != '') and (data != None):
                # Decode all messsages
                message_list, remaining_data = process_raw_socket_message_stream(data)

                # Process all of the messages
                for messsage in message_list:
                    process_messsage(remove_message_frames(message))

                # Store the remaining data
                data = remaining_data
        except:
            print "Unexpected Error"

rawDescription: Implementing "Simplest Protocol" pseudo-code algorithm in python


code:
if dialog.exec_():
    fileNames = dialog.selectedFiles()
    print str(fileNames)
else:
    print "Canceled"

rawDescription: pyside: QFileDialog returns an empty list

description: Pyside: QFileDialog returns an empty list


code:
now = datetime.datetime.now().replace(microsecond=0)
print now

rawDescription: Change time format in Django Views

description: Change time format in Django Views


code:
class First(object):
    def __init__(self, p):
        p = str(p)
        #The decision whether or not to perform default action is done
        #in the following try/except block. In reality this block
        #is more complicated
        #and more checks are performed in order to assure proper work
        try:
            strImport = "__import__('module%s')"%p
            print strImport
            e = eval(strImport, {}, {})
            if not hasattr(e, p):
                raise ImportError()

            self.override_obj = getattr(e, p)(p)
        except ImportError:
            e = None #default behaviour
            self.override_obj = None

        self.p = p

    def act(self):
        if self.override_obj:
            return self.override_obj.act()
        else:
            print 'Default behaviour'

rawDescription: Dynamically loading instance method during object instantiation


code:
import sqlite3

def select(self, attr="*", table="reuters", fetch=None, num=None, tologfile=False, logfile=""):
    if fetch is None:
        fetch=self.fetchone
    output=self.execute("select * from ?;".replace('?',table).replace("select * ", ("select "+attr+' ')))

    output=fetch(num) if num else fetch()

    if tologfile:
        logfile = open(logfile, 'w')
        logfile.write(str(output))
        logfile.close()
    else: return output

if __name__ == '__main__':
    connection = sqlite3.connect('winkwinknudgenudgesaynomore.db')
    cursor = connection.cursor()
    cursor.execute("drop table reuters;")
    cursor.execute("create table reuters (foo text, bar text);")
    connection.commit()
    print select(cursor)
    print select(cursor, 'bar')
    print select(cursor, 'bar', fetch=cursor.fetchmany, num=5)
    cursor.close()

rawDescription: Passing a member function as a function arg?


code:
span = 2
words = "this-is-a-string".split("-")
print ["-".join(words[i:i+span]) for i in range(0, len(words), span)]

rawDescription: Is there a way to split a string by every nth separator in Python?


code:
import cv2
import numpy as np

img_rgb = cv2.imread("four.jpg")

template = cv2.imread('fairy.jpg')
template1 = cv2.imread('sad.jpg')
template2 = cv2.imread('san.jpg')
template3 = cv2.imread('deer.jpg')

res = cv2.matchTemplate(img_rgb,template,cv2.TM_CCOEFF_NORMED)
res1 = cv2.matchTemplate(img_rgb,template1,cv2.TM_CCOEFF_NORMED)
res2 = cv2.matchTemplate(img_rgb,template2,cv2.TM_CCOEFF_NORMED)
res3 = cv2.matchTemplate(img_rgb,template3,cv2.TM_CCOEFF_NORMED)

threshold = 0.99

loc = np.where (res >= threshold)
loc1 = np.where (res1 >= threshold)
loc2 = np.where (res2 >= threshold)
loc3 = np.where (res3 >= threshold)

fairy = list(loc[0])
sandeer = list(loc1[0])
san = list(loc2[0])
deer = list(loc3[0])

x=sorted(fairy+sandeer+san+deer)
out=', '.join(['tooth fairy' if y in fairy else 'santa and deer' if y in sandeer else 'santa' if y in san else 'deer' for y in x])

print out

rawDescription: Python, cv2, numpy to find images in an image


code:
print m.obj_list[0].get_a() # prints 0
m.obj_list[0].set_a(5)
print m.obj_list[0].get_a() # prints 5
# access all the "a"'s
a_s = [o.get_a() for o in m.obj_list]

rawDescription: How to access the methods of an object inside another object

description: Access the methods of an object inside another object


code:
import sys

for line in sys.stdin:
   line = line.strip()
   if line:
      print line

rawDescription: Deleting an empty line in Python

description: Deleting an empty line in Python


code:
from datetime import date, timedelta
yesterday = date.today() - timedelta(1)
print yesterday.strftime('%m%d%y')

rawDescription: Formatting "yesterday's" date in python

description: Formatting "yesterday's" date in python


code:
#!/usr/bin/env python

from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import pygame

ESCAPE = '\033'
window = 0
texture = 0

A_TEX_NUMBER = None
B_TEX_NUMBER = None

def GenTextureForText(text):
    font = pygame.font.Font(None, 64)
    textSurface = font.render(text, True, (255,255,255,255),
                              (0,0,0,255))
    ix, iy = textSurface.get_width(), textSurface.get_height()
    image = pygame.image.tostring(textSurface, "RGBX", True)
    glPixelStorei(GL_UNPACK_ALIGNMENT,1)
    i = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, i)
    glTexImage2D(GL_TEXTURE_2D, 0, 3, ix, iy, 0, GL_RGBA, GL_UNSIGNED_BYTE, image)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL)
    return i

def InitGL(Width, Height):
    global A_TEX_NUMBER, B_TEX_NUMBER
    pygame.init()
    A_TEX_NUMBER = GenTextureForText("a")
    B_TEX_NUMBER = GenTextureForText("b")
    glEnable(GL_TEXTURE_2D)
    glClearColor(0.0, 0.0, 0.0, 0.0)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
    glMatrixMode(GL_MODELVIEW)
    done = 1

def DrawGLScene():

  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
  glLoadIdentity()
  glTranslatef(0.0,0.0,-10.0)
  glBindTexture(GL_TEXTURE_2D, B_TEX_NUMBER)
  glBegin(GL_QUADS)
  glTexCoord2f(0.0, 0.0); glVertex3f(-1.0, -1.0,  1.0)
  glTexCoord2f(1.0, 0.0); glVertex3f( 1.0, -1.0,  1.0)
  glTexCoord2f(1.0, 1.0); glVertex3f( 1.0,  1.0,  1.0)
  glTexCoord2f(0.0, 1.0); glVertex3f(-1.0,  1.0,  1.0)
  glEnd()
  glutSwapBuffers()

def keyPressed(*args):
    if args[0] == ESCAPE:
      glutDestroyWindow(window)
      sys.exit()

def main():
  global window
  glutInit("")
  glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH)
  glutInitWindowSize(640, 480)
  glutInitWindowPosition(0, 0)
  window = glutCreateWindow("Jeff Molofee's GL Code Tutorial ... NeHe '99")
  glutDisplayFunc(DrawGLScene)
  glutIdleFunc(DrawGLScene)
  glutKeyboardFunc(keyPressed)
  InitGL(640, 480)
  glutMainLoop()
print "Hit ESC key to quit."
main()

rawDescription: Pygame + OpenGL - how to draw text after glBegin()?


code:
import sys
def Time_Function(i,rows,counter,start,var):

    if  i==start or i% round(rows/10) ==0 and counter <=100:
        sys.stdout.write(str(counter))
        counter=counter+10
        var=0
    if i% round((rows/10)/3) ==0 and counter <=100 and var<3:
        sys.stdout.write('.')
        var=var+1
    return [counter,var]

def Project(array,rows,cols):
    counter=var=0
    for i in range(0,rows):
        for j in range(0,cols):
            array=3 #just an arbitrary number
        [counter,var]=Time_Function(i,rows,counter,0,var)

array1=1
array2=2
Project(array1,2018,486)
print "\n"
Project(array2,2023,486)

rawDescription: For Loop Timer Function in Python

description: For Loop Timer Function in Python


code:
import re

def rna_strand_count(test_string,sub_string):
    test_string = test_string.replace(' ','').upper()
    sub_string = sub_string.replace(' ','').upper()
    first = sub_string[0]
    second = sub_string[1:]
    return {sub_string:len(re.findall(r'{0}(?={1})'.format(first,second),test_string))}

print rna_strand_count('AAAA','AA')

rawDescription: How to create a strand count?

description: Create a strand count


code:
import subprocess
proc=subprocess.Popen(['tac','-'], shell=True, stdin=subprocess.PIPE,
                      stdout=subprocess.PIPE, )
output,_=proc.communicate('one\ntwo\nthree\n')
print output

rawDescription: Filtering python string through external program


code:
import numpy as np

a = np.array([32.49, -39.96,-3.86])
b = np.array([31.39, -39.28, -4.66])
c = np.array([31.14, -38.09,-4.49])

ba = a - b
bc = c - b

cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc))
angle = np.arccos(cosine_angle)

print np.degrees(angle)

rawDescription: python code to calcualte angle between three point using thier 3D coordinates

description: Python code to calcualte angle between three point using thier 3D coordinates


code:
query = 'What is hello'
stopwords = ['what','who','is','a','at','is','he']
querywords = query.split()

resultwords  = [word for word in querywords if word.lower() not in stopwords]
result = ' '.join(resultwords)

print result

rawDescription: Removing list of words from a string

description: Removing list of words from a string


rawDescription: convert string value to dictionary from pickled

description: Convert string value to dictionary from pickled


code:
def infix_postfix(tokens):
    output = []
    stack = []
    for item in tokens:
        #pop elements while elements have lower precedence
        if item in ops:
            while stack and prec[stack[-1]] >= prec[item]:
                output.append(stack.pop())
            stack.append(item)
        #delay precedence. append to stack
        elif item == "(":
            stack.append("(")
        #flush output until "(" is reached
        elif item == ")":
            while stack and stack[-1] != "(":
                output.append(stack.pop())
            #should be "("
            print stack.pop()
        #operand. append to output stream
        else:
            output.append(item)
    #flush stack to output
    while stack:
        output.append(stack.pop())
    return output

rawDescription: Good Infix to Prefix implementation in Python that covers more operators (e.g. <, <=, etc) of a C program?


code:
class Team:
    def __init__(self, name):
        self.name = name

teams = [Team("Dolphins"), Team("Browns"), Team("Ravens")]

def checkIfNameExists(team_obj_list, the_name):
    for team in team_obj_list:
        if (team.name == the_name):
            return "Name " + the_name + " already exists"

print checkIfNameExists(teams, "Browns")

rawDescription: find if item's variable exists in list using python

description: Find if item's variable exists in list using python


code:
import os

def getSubDirs(dir):
    return [os.path.join(dir,name) for name in os.listdir(dir)
            if os.path.isdir(os.path.join(dir, name))]

def getSubFiles(dir):
    return [os.path.join(dir,name) for name in os.listdir(dir)
            if os.path.isfile(os.path.join(dir, name))]

indir = "/topdir"
subDirArr = []
subSubDirArr = []
subSubFileArr = []

subDirArr.extend(getSubDirs(indir))

for dir in subDirArr:
    subSubDirArr.extend(getSubDirs(dir))

for dir in subSubDirArr:
    subSubFileArr.extend(getSubFiles(dir))

print "Here i am doing operation on level1 dirs"
for dir in subDirArr:
    print os.path.basename(dir)

print "Here i am doing operation on level2 dirs"
for dir in subSubDirArr:
        print os.path.basename(dir)

print "Here i am doing operation on level3 files"
for file in subSubFileArr:
        print os.path.basename(file)

rawDescription: Iterate through subdirectories with os.walk in particular order


code:
f1 = file("file1.txt")
f2 = file("file2.txt")
d = {}
while True:
  line = f1.readline()
  if not line:
    break
  c0,c1,c2,c3,c4,c5 = line.split()
  d[(c0,c3)] = (c0,c1,c2,c3,c4,c5)
while True:
  line = f2.readline()
  if not line:
    break
  c0,c1,c2,c3 = line.split()
  if (c3,c2) in d:
    vals = d[(c3,c2)]
    print c3,vals[1],vals[2],vals[3],vals[4],vals[5],c0,c1

rawDescription: Python - comparing columns in 2 files and returning merged output


code:
question = raw_input("Do you wish to try again? y/n: ")
start_over = 10
if question == "y":
    start_over -= 1
    print start_over
else:
    raise SystemExit

rawDescription: if input equals string, do something... python 2.7

description: If input equals string, do something... python 2.7


code:
D={}
with open("file1.txt","rU") as f1:
    for line in f1:
        line=line.rstrip().rsplit("\t")
        if line[6]=="+" and line[2]=="start_codon":
            D[line[3]] = line[8].rstrip('"')[9]
            keys = D.keys()

count=[]
results=[]
number = 12
with open("file2.txt","rU") as f2:
    for line in f2:
        line=line.rstrip().rsplit("\t")
        if int(line[1]) >= 70:
            count.append(line[1])
            if line[0] in D:
                results.append(D[line[0]])
                if len(count) > number:
                    results.append(str(number))
                else:
                    results.append(str(len(count)-1))
                print "\t".join(results)
                count=[]

        else:
            count=[]

rawDescription: Counting previous lines using information from two files in python


code:
import random
from netaddr import *
import itertools

def subnetOverlap(randomSubnet1, randomSubnet2):
    return (randomSubnet1.first <= randomSubnet2.last and
          randomSubnet2.first <= randomSubnet1.last)

def getRandomIP(networkIp="10.10.127.240"):
    network = networkIp + '/24'
    ip = IPNetwork(network)
    print ip

    while 1:
        chosenSubnets = []
        overlap = False
        #Choose 3 random subnetLists
        for randomNumber in random.sample(range(25,30),3):
            subnetList = list(ip.subnet(randomNumber))

            #For each subnetList choose a subnet
            chosenSubnets.append(random.sample(subnetList,1)[0])

        #Check whether any pairs overlap
        for pair in itertools.combinations(chosenSubnets,2):
            if subnetOverlap(pair[0],pair[1]):
                print "OVERLAP"
                overlap = True
                break

        #No overlaps found
        if overlap==True: continue
        if overlap==False: break

    #print chosenSubnets
    return chosenSubnets

#networkIp = raw_input("Enter the desired network: ")
for i in range(20):
    print "***************************"
    print getRandomIP("10.10.127.240")
    #getRandomIP(networkIp)

rawDescription: How to choose three random, non-overlapping subnets in Python according to a specific range?

description: Choose three random, non-overlapping subnets in Python according to a specific range


code:
# Prepare the list of words
word_file = open('wordfile', 'r', encoding='utf8')
words = [word.strip() for word in word_file.readlines()]
word_file.close()

# Now examine each sentence:
with open('sentencefile') as sentences:
    for sentence in sentences:
        found = False
        for word in words:
            if word in sentence:
                found = True
                break
        if found:
            print sentence

rawDescription: Searching for all sentences containing a string in another document


rawDescription: character encoding in python

description: Character encoding in python


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

driver.find_element_by_xpath("//*[@id='lb_LoadMore_button_text_2']").click()

# waiting
wait = WebDriverWait(driver, 10)
product_titles = wait.until(EC.presence_of_all_elements_located((By.XPATH, "//font[@class='ProductTitle']")))

print [x.text for x in product_titles]

rawDescription: Python Selenium - dynamically generated data not added to DOM


code:
from traits.api import HasTraits, Int
from traitsui.api import TextEditor, View, Item

class LazyEval(HasTraits):
    a = Int
    # Additional 'evaluate' is needed to make an int from a string
    view = View(Item("a", editor=TextEditor(auto_set=False, enter_set=True,
                                            evaluate=int)))

    def _a_changed(self):
        print "New value of a is %s" % self.a

l = LazyEval()
l.configure_traits()

rawDescription: traitsui prevent txt-box from realtime updating

description: Traitsui prevent txt-box from realtime updating


code:
import re

blah = """All Eyez on Me Track Listing # Title Artisttime 1 Ambitionz Az a Ridah 2Pac 4:39 2 All About U 2Pac 4:37       Fatal           Yani Hadati           Dru Down           Snoop Dogg           Nair Dogg           Nate Dogg     3 Skandalouz 2Pac 4:09       Nate Dogg     4 Got My Mind Made Up 2Pac 5:13       Kurupt           Redman           Method Man           Dat N Daz     5 How Do You Want It Jojo the Elf 4:47       2Pac     6 2 of Amerikaz Most Wanted 2Pac 4:07       Snoop Dogg     7 No More Pain 2Pac 6:14 8 Heartz of Men 2Pac 4:43 9 Life Goes On 2Pac 5:02 10 Only God Can Judge Me Rappin' 4-Tay 4:57       2Pac     11 Tradin War Stories Nair Dogg 5:29       The Storm           CPO           C-BO           Outlawz           2Pac     12 California Love [Remix] Dr. Dre 6:25       2Pac           Roger     13 I Ain't Mad at Cha 2Pac 4:53       Danny Boy     14 What'z Ya Phone No. Danny Boy 5:10       2Pac     15 (2) Can't C Me George Clinton 5:30       2Pac     16 (2) Shorty Wanna Be a Thug 2Pac 3:51 17 (2) Holla at Me 2Pac 4:56 18 (2) Wonda Why They Call U B____ 2Pac 4:19 19 (2) When We Ride Nair Dogg 5:09       2Pac     20 (2) Thug Passion Outlawz 5:08       The Storm           Dramarydal           Jewell           2Pac     21 (2) Picture Me Rollin' Danny Boy 5:15       2Pac           CPO           Big Syke     22 (2) Check Out Time Big Syke 4:39       Kurupt           2Pac     23 (2) Ratha Be Ya N____ 2Pac 4:14       Richie Rich     24 (2) All Eyez on Me Big Syke 5:08       2Pac     25 (2) Run tha Streetz The Storm 5:17       Nair Dogg           Michel'le           2Pac     26 (2) Ain't Hard 2 Find B-Legit 4:29       E-40           C-BO           2Pac           Richie Rich     27 (2) Heaven Ain't Hard 2 Find 2Pac 3:58 Extra"""

def extraction2(s):
    s = re.sub(r'\s+', " ", s)
    tracks = []
    trackno = 1
    while 1:
        track = { "trackno" : trackno, "title" : "", "duration": None }
        # start of next track
        from_ = s.find(str(trackno))
        if from_ < 0:
            # last title has additional artists (not the case in the example)
            tracks[trackno-2]["title"] += " " + s.strip()
        else:
            if trackno > 1 and from_ > 0:
                # add "trailing" artists to previous track
                tracks[trackno-2]["title"] += s[:from_].strip()
            # time indicates end of track
            m = re.search(r'\d{1,2}:\d{2}', s[from_:])
            if m:
                line = s[from_:from_+m.end()].split(" ")
                track["title"] = " ".join(line[1:-1]).strip()
                track["duration"] = line[-1:][0]
                tracks.append(track)
        if not track["duration"]:
            break
        s = s[from_+m.end():]
        trackno += 1
    return tracks

tracklist = extraction2(blah)
import json
print json.dumps(tracklist, indent=4)

rawDescription: How to get all text in between two numbers using regular expression in Python?

description: Get all text in between two numbers using regular expression in Python


code:
class A(object):
  def __init__(self):
    print "In __init__"
a = A()
b = A.__new__(A)
type(b)

rawDescription: Instantiate a class but don't call its __init__ method


code:
import time
import urllib2
import socket
import sys
import random
import os
from time import sleep
from random import randint

def cls():
    os.system("clear")

def choices():
    print "1.IDgen\n"
    print "2.socks\n"
    print "3.XatBot (Not working)\n"
    print "4.Calculator (not working)\n"
    print "5.XatRaid(not working) \n"
    print "6.Exit\n"
    choicechoice = int(raw_input("What do you want(The number)\n"))
    if choicechoice == 6: # use `==` not =
        exit()
    elif choicechoice == 5:
        print "Not working yet...\n"
        cls()
        choices()
    elif choicechoice == 4:
        print "Not working yet..\n"
        cls()
        choices()
    elif choicechoice == 3:
        print "Will be done soon...\n"
        cls()
        choices() # choices not  choiches()
    elif choicechoice == 1:
        cls()
        idgen()
    elif choicechoice == 2:
        print "Almost done\n"
        cls()
        time.sleep(2)
        choices()

def main():
    print "Welcome to the main menu!\n"
    time.sleep(3)
    print "Before we start the program, we will ask you a couple of questions\n"
    time.sleep(3)
    cls()
    name = raw_input("What is your name?\n")
    time.sleep(2)
    age = int(raw_input("How old are you?\n")) # missing a closing paren
    time.sleep(2)
    country = raw_input("In what country do you live?\n")
    time.sleep(2)
    print ("Thanks for the info!\n")
    time.sleep(2)
    cls()
    valid = raw_input("Is this info valid? Answer with y or n\n")
    if valid == "y":
        print "Thanks for submitting your real info!\n"
        cls()
        print "Soo, your real name is {} and you live in {} and your real age is {} ? Nice!\n".format(name, country, age)
        choices()
    else:
        exit()

def idgen():
    id = urllib2.urlopen("http://xat.com/web_gear/chat/auser3.php").read()
    if "&UserId" in id:
        file = open("idss.txt", "w")
        file.write(id + "\n")
        file.close()
        print "ID generated!\n"
        time.sleep(2)
    else:
        print "Not an id... um??\n"
        time.sleep(2)
    choices()

main()

rawDescription: Python centOS no output

description: Python centOS no output


code:
class Parser(object):

    def __init__(self, use_messaging=False):
        if use_messaging:
            try:
                self.messages = __import__('django.contrib.messages')
            except ImportError:
                print "dude, you really need to read the help secton"
                sys.exit(1)
        else:
            self.messages = None

    def parse(self):
        if self.messages:
            self.messages.send_message("I am parsing now")

rawDescription: pass a python module to a function

description: Pass a python module to a function


code:
resp = self.session.request(self.method, full_url,
                                                data=self.post_data, timeout=self.api.timeout,
                                                auth=auth, proxies=self.api.proxy)
print resp.url # This is the url you want

rawDescription: understanding python requests session parameters

description: Understanding python requests session parameters


code:
s="Whatever"
print s[::-1]

rawDescription: Read words backwards using python

description: Read words backwards using python


code:
authList = ('jennifer', 35, 20), ('john', 20, 34), ('fred', 34, 89)
rtAuthors = ('larry', 57, 24, 'simon'), ('jeremy', 24, 15, 'john'), ('sandra', 39, 24, 'fred')
authDict = {t[0]: t[1:] for t in authList}
rtAuthList = [t + authDict[t[-1]] for t in rtAuthors if t[-1] in authDict]
print rtAuthList

rawDescription: How do I optimize searching two tuples of tuples for large tsv file in python?

description: Optimize searching two tuples of tuples for large tsv file in python


code:
emptyspace = "                   "
lempty = len(emptyspace)
addS = "Message"
news = "#" + emptyspace + addS + emptyspace + "#"
lnew = len(news)

edge = "# "
mid = "# "
for i in range((lnew / 2 - 1)):
    edge += "# "
    mid += "  "
edge += "#"
mid += "#"

print edge
print mid
print news
print mid
print edge

rawDescription: Create a box with text in center

description: Create a box with text in center


code:
import requests
import lxml.html as lh
from BeautifulSoup import UnicodeDammit

URL = "http://en.wikipedia.org/w/index.php?title=data_mining&printable=yes"
HEADERS = {'User-agent': 'Mozilla/5.0'}

def lhget(*args, **kwargs):
    r = requests.get(*args, **kwargs)
    html = UnicodeDammit(r.content).unicode
    tree = lh.fromstring(html)
    return tree

def remove(el):
    el.getparent().remove(el)

tree = lhget(URL, headers=HEADERS)

el = tree.xpath("//div[@class='mw-content-ltr']/p")[0]

for ref in el.xpath("//sup[@class='reference']"):
    remove(ref)

print lh.tostring(el, pretty_print=True)

print el.text_content()

rawDescription: Removing html tags when crawling wikipedia with python's urllib2 and Beautifulsoup


code:
PkgInfo={}
Tags=['Package', 'Section', 'Name']

for line in reader.readlines():
    entry = line.strip().split(': ', 2)
    if len(entry) != 2:
        continue
    element, value = entry[0], entry[1]
    if element in Tags:
        PkgInfo[element] = value

print PkgInfo

rawDescription: Python: if string starts with a string from a list


code:
import sys as s
mod=s.modules.keys()
mods_seen = list()
for indx,each in enumerate(mod):
    parts = each.split('.')
    if not parts[0] in mods_seen:
        print indx,each
        mods_seen.append(parts[0])

rawDescription: Listing installed modules in Python

description: Listing installed modules in Python


code:
import pickle, os
user_folder = "user_data/"
if not os.path.exists(user_folder):
    os.makedirs(user_folder)
while True:
    RegOrLog = raw_input('[Register/Login]:')
    if RegOrLog not in ('reg', 'register', 'REGISTER','log', 'login', 'LOGIN',\
                        'r','l'):
        print "Please enter 'register' if you dont have account"
        print "Please enter 'login' if you already registered"

    if RegOrLog in ('reg', 'register', 'REGISTER','r','Register'):
        count = 0
        while count < 1:
            regusrnm = raw_input('Enter your desire login name:')
            regusrnm = regusrnm.lower()
            regpswrd = raw_input('Enter your password:')
            while True:
                regage = raw_input('Enter your age:')
                if int(regage) not in range(1, 100):
                    print 'please enter apropriate value'
                else:
                    break

            while True:
                reggender = raw_input('State your gender:')
                if reggender not in ('male', 'female'):
                    print 'Are you an alien?'
                else:
                    break

            data = {"username": regusrnm, "password": regpswrd, "age": regage,\
                    "gender": reggender}
            pickle.dump( data, open( user_folder + regusrnm, "wb" ) )
            RegOrLog = 'login'
            print 'Please login to your account for security purpose'
            break

    if RegOrLog in ('log', 'login', 'LOGIN','l','Login'):
        logusrnm = raw_input('Enter your username:')
        data = pickle.load( open( user_folder + logusrnm, "rb" ) )
        count = 3
        while count >= 1:
            logpswrd = raw_input('Enter your password:')
            count = count - 1
            if logpswrd != data["password"]:
                print "You have",count, "attempt left"
                if count == 0:
                    print "The account doesn't exist or wrong password"
                    print 'Please register a new one'
                    break

            else:
                 print 'Welcome Back',data["username"]
                 break

rawDescription: Change directory of the saved file inside another file. Clean and neat. No mess


code:
css = """
/*
author : name
uri : link
etc
*/

bla bla bla. Blah blah
x: 10;
color: red;

/* header */
/* footer */
"""

import re

pat = r'\/\*([\S\s]*?)\*\/'

print re.findall(pat, css)
print re.search(pat, css).group()

rawDescription: Python: extracting comments from a css file


code:
class MyClass(object): # Use new style classes
    def __init__(self):
        object.__setattr__(self, 'datastore', {}) # This prevents infinite recursion when setting attributes

    def __getattr__(self, key):
        return self.datastore[key]

    def __setattr__(self, key, value):
        self.datastore[key] = value

a = MyClass()
b = MyClass()

a.hello = "err"

print a.hello # Works
print b.hello # Gives an error

rawDescription: Python, how to use __setattr__ on dictionary object that is part of the class that overloads the method?


code:
import threading
import time
import sys

def background():
        while True:
            time.sleep(3)
            print 'disarm me by typing disarm'

def other_function():
    print 'You disarmed me! Dying now.'

# now threading1 runs regardless of user input
threading1 = threading.Thread(target=background)
threading1.daemon = True
threading1.start()

while True:
    if raw_input() == 'disarm':
        other_function()
        sys.exit()
    else:
        print 'not disarmed'

rawDescription: How to use threading to get user input realtime while main still running in python

description: Use threading to get user input realtime while main still running in python


code:
a=np.where(MACD[2]>0.)[0]
b=np.where(MACD[2]<0.)[0]

num=np.array([1])
num1=[]

for x in range (-1,-30,-1):#for MACD above  0
    if(a[x]-a[x-1]>1):
        num=a[x]
        num1.append(num)
        print num1

rawDescription: How to append a empty list within for loop in Python

description: Append a empty list within for loop in Python


code: print re.search("(\w+) vs (\w+) \(\s?(\w+)",my_string).groups()

rawDescription: How do I capture words wrapped in parentheses with a regex in Python?

description: Capture words wrapped in parentheses with a regex in Python


code:
hourlist,minutelist,secondlist=[],[],[]

f = open("newtext.txt", 'r')
for line in f:
    line = line.strip()
    columns = line.split()
    time = columns[0]
    hourlist.append(int(time[0:2]))
    minutelist.append(int(time[2:4]))
    secondlist.append(int(time[4:6]))
f.close()

hour = int(time[0:2])
minute = int(time[2:4])
second = int(time[4:6])

print hourlist, minutelist,secondlist

rawDescription: Convert time strings to integers

description: Convert time strings to integers


code:
lst_lvl1 = [] # Top level list

for i, project in enumerate(root):
    projects[i] = project

    print(project.get('name'))
    lst_lvl1.append(project.get('name')) # Append to the top level list

    lst_lvl2 = [] # Create an empty 2nd level list

    for u, design in enumerate(project):
        designs[u] = design
        print(design.get('name'))
        lst_lvl2.append(design.get('name')) # Append to the 2nd level list

        lst_lvl3 = [] # Create a 3rd level list...
        for x, param in enumerate(design):
            params[x] = param
            print(param.get('name'))
            lst_lvl3.append(param.get('name'))
            lst_lvl4 = []
            for x, info in enumerate(param):
                print(info.text)
                lst_lvl4.append(info.text)
            lst_lvl3.append(lst_lvl4) # At the end of level 4, append what you got to the level-3 list
        lst_lvl2.append(lst_lvl3) # At the end of level 3, append what you got to the level-2 list... etc
    lst_lvl1.append(lst_lvl2)

print lst_lvl1

rawDescription: read data form xml to list

description: Read data form xml to list


code:
for i, j, k in zip(cusip_result, bond_name_result, bond_price_result):
    print i, j, k

rawDescription: Sequentially Combining Three Lists Created with Regular Expressions - Python


code:
import os
import sys

from PyQt4 import QtCore,  QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4 import NavigationToolbar2QT as NavigationToolbar

from matplotlib.figure import Figure
from mpl_toolkits.mplot3d import Axes3D

class QtMplCanvas(FigureCanvas):
    def __init__(self, parent=None, width = 6.5, height = 5.5, dpi = 100, sharex = None, sharey = None, fig = None):
        if fig == None:
            self.fig = Figure(figsize = (width, height), dpi=dpi, facecolor = '#FFFFFF')
            self.ax = self.fig.add_subplot(111, projection='3d')
            self.fig.subplots_adjust(left=0.1, bottom=0.1, right=0.9, top=0.9)
            self.ax.hold(True)
        else:
            self.fig = fig

        FigureCanvas.__init__(self, self.fig)
        FigureCanvas.setSizePolicy(self,
            QtGui.QSizePolicy.Expanding,
            QtGui.QSizePolicy.Expanding)
        FigureCanvas.updateGeometry(self)

    def sizeHint(self):
        w, h = self.get_width_height()
        return QtCore.QSize(w, h)

    def minimumSizeHint(self):
        return QtCore.QSize(10, 10)

    def sizeHint(self):
        w, h = self.get_width_height()
        return QtCore.QSize(w, h)

    def minimumSizeHint(self):
        return QtCore.QSize(10, 10)

class MyNavigationToolbar(NavigationToolbar) :
    def __init__(self, parent, canvas, direction = 'h' ) :

        self.canvas = canvas
        QWidget.__init__( self, parent )

        if direction=='h' :
            self.layout = QHBoxLayout( self )
        else :
            self.layout = QVBoxLayout( self )

        self.layout.setMargin( 2 )
        self.layout.setSpacing( 0 )

        NavigationToolbar2.__init__( self, canvas )

    def set_message( self, s ):
        pass

class MPL_WIDGET_3D(QtGui.QWidget):
    def __init__(self, parent = None, enableAutoScale = False, enableCSV = False, enableEdit = False, fig = None):
        QtGui.QWidget.__init__(self, parent)
        self.canvas = QtMplCanvas(fig)
        self.canvas.ax.mouse_init()
        self.toolbar = NavigationToolbar(self.canvas, self.canvas)
        self.vbox = QtGui.QVBoxLayout()
        self.vbox.addWidget(self.canvas)
        self.vbox.addWidget(self.toolbar)
        self.setLayout(self.vbox)

        ###########SAVING FIGURE TO CLIPBOARD##########
        self.cb = None #will be used for the clipboard
        self.tempPath = getHomeDir()
        self.tempPath = os.path.join(self.tempPath,'tempMPL.png')

        self.mpl2ClipAction = QtGui.QAction("Save to Clipboard",  self)
        self.mpl2ClipAction.setShortcut("Ctrl+C")
        self.addAction(self.mpl2ClipAction)
        QtCore.QObject.connect(self.mpl2ClipAction,QtCore.SIGNAL("triggered()"), self.mpl2Clip)

    def mpl2Clip(self):
        try:
            self.canvas.fig.savefig(self.tempPath)
            tempImg = QtGui.QImage(self.tempPath)
            self.cb = QtGui.QApplication.clipboard()
            self.cb.setImage(tempImg)
        except:
            print 'Error copying figure to clipboard'
            errorMsg = "Sorry: %s\n\n:%s\n"%(sys.exc_type, sys.exc_value)
            print errorMsg

####USED TO GET THE USERS HOME DIRECTORY FOR USE OF A TEMP FILE

def valid(path):
    if path and os.path.isdir(path):
        return True
    return False

def env(name):
    return os.environ.get( name, '' )

def getHomeDir():
    if sys.platform != 'win32':
        return os.path.expanduser( '~' )

    homeDir = env( 'USERPROFILE' )
    if not valid(homeDir):
        homeDir = env( 'HOME' )
        if not valid(homeDir) :
            homeDir = '%s%s' % (env('HOMEDRIVE'),env('HOMEPATH'))
            if not valid(homeDir) :
                homeDir = env( 'SYSTEMDRIVE' )
                if homeDir and (not homeDir.endswith('\\')) :
                    homeDir += '\\'
                if not valid(homeDir) :
                    homeDir = 'C:\\'
    return homeDir

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    mplQt = MPL_WIDGET_3D()
    mplQt.show()
    sys.exit(app.exec_())

rawDescription: Qt4 + mplot3d of matplotlib

description: Qt4 + mplot3d of matplotlib


code:
for x in range(0, 10, 2):
    print str(x)

rawDescription: In Python how do you make a for loop counting by arbitrary increments?


code:
from itertools import groupby
from operator import itemgetter

d = {'year': ['2014', '2014', '2014'], 'week': ['44', '49', '49'], 'value': [15, 20, 30]}
out = {'year': [], 'week': [], 'value': []}

for k, g in groupby(enumerate(d['week']), key=itemgetter(1)):
    total = 0
    for i, x in g:
        total += d['value'][i]
    # Now `i` is the last index of the group and `x` is the last week of the group,
    # We can use these to get values from 'year' and 'week'.
    out['year'].append(d['year'][i])
    out['week'].append(x)
    out['value'].append(total)

print out
#{'week': ['44', '49'], 'value': [15, 50], 'year': ['2014', '2014']}

rawDescription: Merge list values inside a dictionary

description: Merge list values inside a dictionary


code:
clines_dict = {} #open an empty dictionary

with open(smaller_file) as b:
    for line in b:
        clines_dict["\t".join(line.split('\t')[1:5])] = [line.split('\t')[5]]

# clines_dict[key] = [value]

print "dictionary created!"

with open(larger_file) as a:
    with open("scores.txt", "w") as result:
        for line in a:
            line = line.split('\t')
            look_for = "\t".join(line[1:5])
            if look_for in clines_dict: #check if look_for is a key in your dictionary
                result.write("\t".join(line[1:7]) + "\t" + clines_dict[look_for][0] + "\n")

rawDescription: compare multiple columns in two files, replace value in file 2 with value from file 1

description: Compare multiple columns in two files, replace value in file 2 with value from file 1


code:
import re
original = "&\hbox{(1b)}}$$ with the initial condition <2inline-formula>$x(0)$, where the subscript <3inline-formula>$p$ means 'plant’; <4inline-formula>$x_{p}(t) \in \Re^{n}$ is the state, <5inline-formula>$y_{p}(t)\in\Re^{q}$ is the output, and <6inline-formula>$u_{p}(t)\in\Re^{m}$ is the input; <7inline-formula>"
new = re.sub(r"<\d+inline-formula>", "<inline-formula>", original)
print new

rawDescription: Replacing a leading text string with the same string in python


code:
b = '010000010100001001000011'
bin_chunks = [b[8*i:8*(i+1)] for i in xrange(len(b)//8)]
print bin_chunks
ints = [int(x, 2) for x in bin_chunks]
print ints
chars = [chr(x) for x in ints]
print chars
print ''.join(chars)

rawDescription: Python: Need help splitting an input of binary code, with no spaces


rawDescription: What's the easiest way to print seleced key values from dictionary in python


code:
import ifcopenshell

ifc_file = ifcopenshell.open('Example_A.ifc')

materials = ifc_file.by_type('IfcMaterial')

print 'There are ' + str(len(materials)) + ' different types of  materials in the file:' + '\n'

for x in range(0):
    materials = ifc_file.by_type('IfcMaterial')[x]
    colour = ifc_file.by_type('IfcColourRgb')[x]
    styles = ifc_file.by_type('IfcStyledItem')[x]
    surfacestyles = ifc_file.by_type('IfcSurfaceStyleRendering')[x]

    #DECLARING THE VARIABLES FOR RADIANCE DEFINTION
    rad_material = materials.Name
    rad_red = colour.Red
    rad_green = colour.Green
    rad_blue = colour.Blue
    rad_specular = surfacestyles.SpecularColour
    rad_roughness = 0.1 #<- Roughness is not defined in IFC, the value of 0.1 is  merely put there as an example

    print 'RETRIEVES DATA FROM IFC FILE PRINTS THEM ACCORDING TO A RADIANCE READABLE DEFINITION'
    print ''

    print '#material name: ' + rad_material
    print '#material type: ' + 'No definition found in the specified ifc file'
    print 'void ' + ' plastic ' + rad_material
    print '0'
    print '0'
    print rad_red , rad_green, rad_blue,rad_specular[0], rad_roughness

rawDescription: For loop over a range (Python 2.7 + Ifc)


rawDescription: Parsing GPS receiver output via regex in Python


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup("""

1

2

3

4

""")

for tr in soup.find('table').find_all('tr', recursive=False):
    print tr

rawDescription: How to find nodes using Beautiful Soup

description: Find nodes using Beautiful Soup


code:
import datetime
import random
import numpy as np
import datetime
import itertools

dates, allSpillovers, allBins, allDigitised = [], [], [], []
with open("year.dat") as year:
  previousDate = None
  spillovers = []
  for line in year.readlines()[1:]:
    _, strdate, spillover = line.split(",")
    spillover = float(spillover)
    year, month, day = [int(i) for i in strdate.split("-")]

    date = datetime.date(year, month, day)

    if previousDate == date:
      spillovers.append(spillover)
    elif previousDate != None:
      mean = np.mean(spillovers)
      stdev = np.std(spillovers)

      spillovers.sort()
      if len(spillovers) > 70:
          allSpillovers.append([mean, mean-stdev, mean+stdev] + spillovers)
          dates.append(date)
      spillovers = []

    previousDate = date

#itertools.izip_longest(*allSpillovers, fillvalue=0)
allSpillovers = zip(*allSpillovers)

from matplotlib import pyplot

print len(dates), len(allSpillovers[0]), len(allSpillovers[1])

fig = pyplot.figure()
ax = fig.add_subplot(1,1,1)

for i in range(3, len(allSpillovers)-1):
  alpha = 0.5 - abs(i / float(len(allSpillovers)) - 0.5)
  print len(dates), len(allSpillovers[i]), len(allSpillovers[i+1])
  ax.fill_between(dates, allSpillovers[i], allSpillovers[i+1], facecolor='green', interpolate=True, alpha=alpha, linewidth=0)

#ax.fill_between(dates, allSpillovers[1], allSpillovers[2], facecolor='green', interpolate=True, alpha=0.5)

#for b, d in bins, digitised:

ax.plot(dates, allSpillovers[0], color="blue", linewidth=2)
ax.plot(dates, [0 for _ in dates], color="red", linewidth=2)
ax.grid()

fig.autofmt_xdate()

pyplot.show()

rawDescription: Python: Plot a graph with the same x-axis values


code:
class DelList(list):
    def __del__(self):
        print 'Deleted {}'.format(self)

def foo():
    A = DelList([DelList([1, 3, 5, 7]), DelList([2, 4, 6, 8])])
    return A[1]

B = foo()
del B

rawDescription: python garbage collector behavior on compound objects

description: Python garbage collector behavior on compound objects


code:
import xml.etree.ElementTree as ET

data = {}
tree = ET.parse('test.xml')
root = tree.getroot()

for entry in root.iter('entry'):
    term = entry.find('term')
    for opinion in entry.iter('opinion'):
        termDict = data.setdefault(opinion.get('source'), {})
        termDict[term.text] = opinion.get('polarity')

for k,v in data.items():
    print k, v

rawDescription: Iterating over xml document

description: Iterating over xml document


code:
import weakref
import gc

class M:
    pass

w = weakref.WeakKeyDictionary()
key = M()
val = M()
val.keyRef = weakref.ref(val)
w[key] = val
print len(w)   ## prints 1
del key
gc.collect()
print len(w)   ## prints 0

rawDescription: GC Doesn't Delete Circular References in WeakKeyDictionaries?


code:
from Tkinter import *

running = True  # Global flag

def scanning():
    if running:  # Only do this if the Stop button has not been clicked
        print "hello"

    # After 1 second, call scanning again (create a recursive loop)
    root.after(1000, scanning)

def start():
    """Enable scanning by setting the global flag to True."""
    global running
    running = True

def stop():
    """Stop scanning by setting the global flag to False."""
    global running
    running = False

root = Tk()
root.title("Title")
root.geometry("500x500")

app = Frame(root)
app.grid()

start = Button(app, text="Start Scan", command=start)
stop = Button(app, text="Stop", command=stop)

start.grid()
stop.grid()

root.after(1000, scanning)  # After 1 second, call scanning
root.mainloop()

rawDescription: How do you create a Tkinter GUI stop button to break an infinite loop?

description: Create a Tkinter GUI stop button to break an infinite loop


code:
import imaplib

def read(username, password, sender_of_interest):
    # Login to INBOX
    imap = imaplib.IMAP4_SSL("imap.gmail.com", 993)
    imap.login(username, password)
    imap.select('INBOX')

    # Use search(), not status()
    status, response = imap.search('INBOX', '(UNSEEN)')
    unread_msg_nums = response[0].split()

    # Print the count of all unread messages
    print len(unread_msg_nums)

    # Print all unread messages from a certain sender of interest
    status, response = imap.search(None, '(UNSEEN)', '(FROM "%s")' % (sender_of_interest))
    unread_msg_nums = response[0].split()
    da = []
    for e_id in unread_msg_nums:
        _, response = imap.fetch(e_id, '(UID BODY[TEXT])')
        da.append(response[0][1])
    print da

    # Mark them as seen
    for e_id in unread_msg_nums:
        imap.store(e_id, '+FLAGS', '\Seen')

rawDescription: How to get unread messages and set message read flags over IMAP using Python?

description: Get unread messages and set message read flags over IMAP using Python


code:
import csv
from collections import Counter
import operator

def parse_files(dataset_path,f):  # please avoid using reserved words like file
    threads = range(0,16,2)
    dataset = csv.reader(open(dataset_path,'rb'), delimiter=',')
    results = []
    for line in dataset:
        counter = {str(x):[] for x in range(0,8,2)}
        # map(lambda x:counter[line[x+1]].append(line[x]), threads)
        # map(lambda ...) is just a more pythonic way to write the following two lines
        for index in threads:
            counter[line[index+1]].append(line[index])
        # now counter is something like
        #{'0': ['c', 'l'], '2': ['a', 'm'], '4': ['mi', 's'], '6': ['b', 'G']}

        results.extend([','.join(v)+'='+k for k,v in counter.items()])
        # in results, I'm appending something like this:
        # {'c,l=6', 'a,m=0', 'b,mi=2', 'G,s=4'}

    sorted_results = sorted(dict(Counter(results)).iteritems(), key=operator.itemgetter(1), reverse=True)
    print '\n'.join(['The couple %s appears %d times'%el for el in sorted_results])

    # >>> The couple a,b=2 appears 2 times
    # >>> The couple c,m=4 appears 2 times
    # >>> The couple G,s=4 appears 2 times
    # >>> The couple c,mi=6 appears 1 times
    # >>> The couple a,m=2 appears 1 times
    # >>> ...

rawDescription: identify permutations (and count them) in a csv file

description: Identify permutations (and count them) in a csv file


code:
import math
def R(h):
  return 1.02 / math.tan( h + 10.3 / (h + 5.11) )
print R(1)

rawDescription: Bennett atmospheric equation

description: Bennett atmospheric equation


code:
allowed_chars = ['-', '.', ' ', '\n']
with open("textfile.txt", "r") as fp:
    for line in fp:
        line_check = line
        for chars in allowed_chars:
            line_check = line_check.replace(chars, '')
        if line_check.isdigit():
            print "Good line:", line
        else:
            print "Bad line:", line

rawDescription: python, trying to sort out lines from a textfile

description: Python, trying to sort out lines from a textfile


code:
def redirect_stdout():
    print "Redirecting stdout"
    sys.stdout.flush() # <--- important when redirecting to files

    # Duplicate stdout (file descriptor 1)
    # to a different file descriptor number
    newstdout = os.dup(1)

    # /dev/null is used just to discard what is being printed
    devnull = os.open('/dev/null', os.O_WRONLY)

    # Duplicate the file descriptor for /dev/null
    # and overwrite the value for stdout (file descriptor 1)
    os.dup2(devnull, 1)

    # Close devnull after duplication (no longer needed)
    os.close(devnull)

    # Use the original stdout to still be able
    # to print to stdout within python
    sys.stdout = os.fdopen(newstdout, 'w')

rawDescription: Redirect stdout from python for C calls

description: Redirect stdout from python for C calls


code:
import wx

########################################################################
class MyFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Chat")
        panel = wx.Panel(self)

        my_sizer = wx.BoxSizer(wx.VERTICAL)

        lbl = wx.StaticText(panel, label="Input:")
        my_sizer.Add(lbl, 0, wx.ALL, 5)

        self.txt = wx.TextCtrl(panel, style=wx.TE_PROCESS_ENTER)
        self.txt.SetFocus()
        self.txt.Bind(wx.EVT_TEXT_ENTER, self.OnEnter)
        my_sizer.Add(self.txt, 0, wx.ALL, 5)

        panel.SetSizer(my_sizer)
        self.Show()

    #----------------------------------------------------------------------
    def OnEnter(self, event):
        """"""
        text = self.txt.GetValue()
        if text.lower() == "hello":
            print "Hi!"

if __name__ == "__main__":
    app = wx.App(True)
    frame = MyFrame()
    app.MainLoop()

rawDescription: Get user input in WxPython

description: Get user input in WxPython


rawDescription: Finding the max element in an array, sorted ascending first and then descending


code:
import sys
from PyQt4 import QtGui, QtCore, QtWebKit

class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        self.pages = ['http://www.google.com', 'http://www.citrix.com', 'http://yahoo.com', 'http://reddit.com']
        self.index = 0

        self.view = QtWebKit.QWebView()
        self.view.connect(self.view, QtCore.SIGNAL('loadFinished(bool)'), self.loadFinished)
        self.setCentralWidget(self.view)

        self.view.load(QtCore.QUrl(self.pages[self.index]))

    def loadFinished(self, ok):
        self.index += 1
        if self.index < len(self.pages) :
            self.view.load(QtCore.QUrl(self.pages[self.index]))
        else:
            print 'done'

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

rawDescription: Wait until a webpage finished loading to load the next one in a list


code:
from Tkinter import *

def dummy(root):
    root.after(1000, dummy, root)
    print '',

def main():
    root = Tk()
    root.withdraw()
    dummy(root)
    mainloop()

if __name__ == "__main__":
    main()

rawDescription: How to end a Tkinter application which hasn't any window shown

description: End a Tkinter application which hasn't any window shown


code:
import re

matches = re.finditer('<h[1-6]>', your_text)
for match in matches:
    print match.start()

rawDescription: Python Regular expression

description: Python Regular expression


code:
import boto.elasticache

conn = boto.elasticache.connect_to_region(region)
data = conn.describe_cache_clusters()
clusters = data["DescribeCacheClustersResponse"]["DescribeCacheClustersResult"]["CacheClusters"]

for value in clusters:
    print value["CacheClusterId"]

rawDescription: How to get cache_cluster_id from elasticache using boto

description: Get cache_cluster_id from elasticache using boto


code:
#!/usr/bin/env python

# http://www.linuxquestions.org/questions/programming-9/wxwidgets-wxpython-drawing-problems-with-onpaint-event-703946/

import wx

class MainWindowWindow(wx.Window):
    def __init__(self, parent):
        wx.Window.__init__(self, parent)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.circles = list()
        self.displaceX = 30
        self.displaceY = 30

        circlePos = (self.displaceX, self.displaceY)
        self.circles.append(circlePos)

        ## uncommenting either only first, or both of
        ## the commands below, now calls onPaint
        ## (without these panels, OnPaint called once - with them, twice)
        self.panel = wx.Panel(self, wx.ID_ANY)
        self.mpanelA = wx.Panel(self.panel, -1, size=(200,50))

    def OnPaint(self, e):
        print "OnPaint called"
        dc = wx.PaintDC(self)
        dc.SetPen(wx.Pen(wx.BLUE))
        dc.SetBrush(wx.Brush(wx.BLUE))

        # Go through the list of circles to draw all of them
        for circle in self.circles:
            dc.DrawCircle(circle[0], circle[1], 10)

class MainWindow(wx.Frame):
    def __init__(self, parent, title, size=wx.DefaultSize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, title, wx.DefaultPosition, size)
        MainWindowWindow(self)

def main():
    app = wx.App()
    win = MainWindow(None, "Draw delayed circles", size=(620,460))
    win.Show()
    app.MainLoop()

if __name__ == "__main__":
    main()

rawDescription: wxpython: adding panel to wx.Frame disables/conflicts with wx.Frame's OnPaint?

description: Wxpython: adding panel to wx.Frame disables/conflicts with wx.Frame's OnPaint


code:
class Foo: pass
f = Foo()
f.bar = Foo()
f.bar.baz = Foo()
f.bar.baz.quux = "Found me!"

import operator
print operator.attrgetter("bar.baz.quux")(f)     # prints "Found me!"

rawDescription: How to convert string to class sub-attribute with Python

description: Convert string to class sub-attribute with Python


code:
import numpy

print numpy.fromstring('abcd', dtype='u1')
# 8-bit unsigned int: [97,97,97,97]

print numpy.fromstring('abcd', dtype='i2')
# 16-bit signed int [25185, 25699]

print numpy.fromstring('abcd', dtype='<f4')
# 32-bit float (little-endian): 1.67779994e+22

print numpy.fromstring('abcd', ftype='>f4')
# 32-bit float (big-endian): 2.61007876e+20

rawDescription: Read binary files directly with python to use fo statistical analysis


code:
for line in testFile:
    m = re.search(r"\b(\d+)\b", line)
    if m is not None and int(m.group(1)) >= 9:
        print line

rawDescription: Python print a line that contains a number greater than "x" in a file


code:
# example code:
string_with_newlines = """something
someotherthing"""

import re

print re.match('some', string_with_newlines) # matches
print re.match('someother',
               string_with_newlines) # won't match
print re.match('^someother', string_with_newlines,
               re.MULTILINE) # also won't match
print re.search('someother',
                string_with_newlines) # finds something
print re.search('^someother', string_with_newlines,
                re.MULTILINE) # also finds something

m = re.compile('thing$', re.MULTILINE)

print m.match(string_with_newlines) # no match
print m.match(string_with_newlines, pos=4) # matches
print m.search(string_with_newlines,
               re.MULTILINE) # also matches

rawDescription: What is the difference between Python's re.search and re.match?


code:
stop, first = map(int, raw_input().split())
for i in range(stop - 1):
    print '*' * (i + first)

rawDescription: is there possible to resolve this star pyramid

description: Is there possible to resolve this star pyramid


code:
result = (0, 'one\ntwo')
print result
print result[1]

rawDescription: Console o/p data to log file is not formatted (Python script)


code:
print method

ci = proxy.methods.get(method)

for param in ci.inparams:

    print param.name.ljust(20), param.type

print

rawDescription: Python Soap Server for the Quickbooks Webconnector


code:
class Node(object):
    def __init__(self, idx):
        self.idx = idx     # not needed but nice for prints
        self.parent = None # edge to parent or None
        self.childs = []   # list of edges

    def get_deepest(self, k = 2):
        max_value = -1
        max_node = None
        for edge in self.childs:
            r = edge.n2.get_deepest()
            if r is None: continue # leaf
            value, node = r
            value += len(edge.s)
            if value > max_value: # new best result
                max_value = value
                max_node = node
        if max_node is None:
            # we are either a leaf (no edge connected) or
            # the last non-leaf.
            # The number of childs have to be k to be valid.
            return (0, self) if len(self.childs) == k else None
        else:
            return (max_value, max_node)

    def get_string_to_root(self):
        if self.parent is None: return ""
        return self.parent.n1.get_string_to_root() + self.parent.s

class Edge(object):
    # creating the edge also sets the correspondending
    # values in the nodes
    def __init__(self, n1, n2, s):
        #print "Edge %d -> %d [ %s]" % (n1.idx, n2.idx, s)
        self.n1, self.n2, self.s = n1, n2, s
        n1.childs.append(self)
        n2.parent = self

nodes = {1 : Node(1)} # root-node
string = sys.stdin.readline()
k = int(sys.stdin.readline())
for line in sys.stdin:
    parent_idx, child_idx, start, length = [int(x) for x in line.split()]
    s = string[start-1:start-1+length]
    # every edge constructs a Node
    nodes[child_idx] = Node(child_idx)
    Edge(nodes[parent_idx], nodes[child_idx], s)

(depth, node) = nodes[1].get_deepest(k)
print node.get_string_to_root()

rawDescription: Longest repeated (k times) substring

description: Longest repeated (k times) substring


code:
#! /usr/bin/python

import os
import resource
import sys
import time

cmd = ' '.join(sys.argv[1:])
stime = time.time()
os.system(cmd)          # fire off the command
etime = time.time()

# now get the resource utilization
r = resource.getrusage(resource.RUSAGE_CHILDREN)
user_time = r.ru_utime
sys_time = r.ru_stime
# resource doesn't know "clock" time, so we'll just figure that ourselves
real_time = etime - stime

print "real\t" + str(real_time)
print "user\t" + str(user_time)
print "sys\t" + str(sys_time)

rawDescription: Python Shell Wrapper

description: Python Shell Wrapper


code:
def isIntLessThanSeventeen(listlong):
    try:
        listlong = int(listlong) # throws exception if not an int
        if listlong >= 17:
            raise ValueError
        return True
    except:
        return False

print isIntLessThanSeventeen(16) # True
print isIntLessThanSeventeen("abc") # False

rawDescription: python beginner: try two things before exception?

description: Python beginner: try two things before exception


code:
from google.appengine.ext import db
class TestModel(db.Model):
    string_type = db.StringProperty(default='', multiline=True)
    text_type = db.TextProperty()

some_instance = TestModel()
some_instance.text_type = 'foobar'
setattr(some_instance, 'string_type', some_instance.text_type)
some_instance.put()

retrieved_instance = db.get(some_instance.key())

print id(retrieved_instance.string_type) #10166414447674124776
print id(retrieved_instance.text_type) #10166414447721032360

print type(retrieved_instance.string_type) #OOPS: string_type is now Text type!

rawDescription: db.StringProperty but property is occasionally datastore_types.Text?

description: Db.StringProperty but property is occasionally datastore_types.Text


code:
# Python 2.7
import datetime, numpy as np
import calendar

def toTimestamp(d):
  return calendar.timegm(d.timetuple())

arr1 = np.array([toTimestamp(datetime.datetime(2008,1,d)) for d in range(1,10)])
arr2 = np.arange(1,10)

result = np.interp(toTimestamp(datetime.datetime(2008,1,5,12)),arr1,arr2)
print result # Prints 5.5

rawDescription: How do you interpolate from an array containing datetime objects?

description: Interpolate from an array containing datetime objects


code:
def func():
    a = 10
    print a

co = func.func_code
modified_consts = list(co.co_consts)
for idx, val in enumerate(modified_consts):
    if modified_consts[idx] == 10: modified_consts[idx] = 15

modified_consts = tuple(modified_consts)

import types
modified_code = types.CodeType(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, modified_consts, co.co_names, co.co_varnames, co.co_filename, co.co_name, co.co_firstlineno, co.co_lnotab)
modified_func = types.FunctionType(modified_code, func.func_globals)
# 15:
modified_func()

rawDescription: How to get/set local variables of a function (from outside) in Python?

description: Get/set local variables of a function (from outside) in Python