code:
def the_function(filename):
    """
    returns tuple of list of independent values and list of sparsed arrays as dicts
    e.g. ( [1,2,0.5], [{(0.0):1,(0,1):2},...] )
    on fail prints the reason and returns None:
    e.g. 'failed on text.txt: invalid literal for int() with base 10: '0.0', line: 5'
    """

    # open file and read content
    try:
        with open(filename, "r") as f:
            data_txt = [line.split() for line in f]
    # no such file
    except IOError, e:
        print 'fail on open ' + str(e)

    # try to get the first 3 variables
    try:
        vars =[int(data_txt[0][0]), int(data_txt[1][0]), float(data_txt[2][0])]
    except ValueError,e:
        print 'failed on '+filename+': '+str(e)+', somewhere on lines 1-3'
        return

    # now get arrays
    arrays =[dict()]
    for lineidx, item in enumerate(data_txt[3:]):
        try:
            # for 2d array data
            if len(item) == 3:
                i, j = map(int, item[:2])
                val = float(item[-1])
                # check for 'block separator'
                if (i,j,val) == (-1,-1,0.0):
                    # make new array
                    arrays.append(dict())
                else:
                    # update last, existing
                    arrays[-1][(i,j)] = val
            # almost the same for 4d array data
            if len(item) == 5:
                i, j, k, m = map(int, item[:4])
                val = float(item[-1])
                arrays[-1][(i,j,k,m)] = val
        # if value is unparsable like '0.00' for int or 'text'
        except ValueError,e:
            print 'failed on '+filename+': '+str(e)+', line: '+str(lineidx+3)
            return
    return vars, arrays

rawDescription: Read in file contents to Arrays

description: Read in file contents to Arrays


code:
import mechanize
import cookielib
br = mechanize.Browser()

# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

# Browser options
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

# Follows refresh 0 but not hangs on refresh > 0
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)

# User-Agent
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

url = 'http://site25.way2sms.com/content/index.html?'

#Opening WEbsite
op = br.open(url)

#Selection form
br.select_form(nr=0)

username = 'mobilenumberhere'
password = 'passwordhere'

#Give username and password
br.form['username'] = username
br.form['password'] = password

br.submit()

#To check whether log in Successful or not
if username in br.geturl():
     print "Login Failed" # Go to way2sms and enter wrong details. You will understand this.
else:
     print "Login Successful. You are at ", br.geturl()

rawDescription: scraping way2sms with mechanize

description: Scraping way2sms with mechanize


code:
c = get_config()
# use DOS style path, C:/PROGRA~2 on my 64-bit system points to C:/Program Files (x86)
c.TerminalInteractiveShell.editor = 'C:\PROGRA~2\NOTEPA~1\NOTEPA~1.exe'
# set editor for Qt Console, if you wish to use that
c.IPythonWidget.editor = 'C:\PROGRA~2\NOTEPA~1\NOTEPA~1.exe'

rawDescription: notepad++ run selected code in python console seamlessly

description: Notepad++ run selected code in python console seamlessly


code:
fruit = ['apples', 'bananas', 'pears']
inputs = []

index = 0
while index < len(fruit):
    answer = raw_input('Do you like %s? ' % fruit[index])
    if index > 0 and answer == 'back':
        inputs.pop()
        index -= 1
    else:
        inputs.append(answer)
        index += 1

print inputs

rawDescription: Go to previous user input is user inputs specified string


code:
print user_alias
for user in user_alias:
    for row in Dict_list:
        if user in row.values():
            print row

UserIDs = [] # This is the change.
for user in user_alias:
    for row in Dict_list:
        if row.has_key('_akq6p') and row.has_key('_cn6ca'):
            if user == row['_akq6p'] or user == row['_chk2m']:
                UserID = row['_cn6ca']
                print UserID
                UserIDs.append(UserID)

print UserIDs

rawDescription: How to change for loop to store items in a list for writing

description: Change for loop to store items in a list for writing


code: print timeit.timeit(stmt='offset_back(10000,1000,1000)',setup='from offset_back import offset_back',number=1000)

rawDescription: Using timeit on a cython function

description: Using timeit on a cython function


code:
count = 0
myAuthlog=open('auth.log', 'r')
for line in myAuthlog:
    if re.match("(.*)(B|b)in(.*)", line):
        count+=1
print count

rawDescription: How can I count the occurrences of a word in Python

description: Count the occurrences of a word in Python


code:
import subprocess
from serial import Serial
port = Serial("/dev/ttyAMA0",115200,timeout=3)

subp = subprocess.Popen("./test",stdout=subprocess.PIPE)

for line in iter(subp.stdout.readline, ''):
    port.write(line,)
    print line,

rawDescription: Transmitting stdout via serial not working


code:
with open("myfile.txt") as myfile:
    # Get only numbers
    read = myfile.readlines()[2:-2]

# Remove newlines
read = [number.strip() for number in read]
print read

rawDescription: Read Up Until a Point Python

description: Read Up Until a Point Python


code:
combinations = []
for a in xrange(11):
    for b in xrange(11-a):
        for c in xrange(11-a-b):
            for d in xrange(11-a-b-c):
                for e in xrange(11-a-b-c-d):
                    for f in xrange(11-a-b-c-d-e):
                        for g in xrange(11-a-b-c-d-e-f):
                            for h in xrange(11-a-b-c-d-e-f-g):
                                for i in xrange(11-a-b-c-d-e-f-g-h):
                                    j = 10-a-b-c-d-e-f-g-h-i
                                    combinations.append((a,b,c,d,e,f,g,h,i,j))
print len(combinations)

rawDescription: Is there a more efficient way to find all combinations of 10 items in 10% increments?


code:
from subprocess import Popen, STDOUT
stdout, stderr = Popen('echo ' + cmd, shell=True, stderr=STDOUT).communicate()
print stdout

rawDescription: Python and if statement

description: Python and if statement


code:
#!/usr/bin/python

from os import listdir
from os.path import isfile, join

def readWrite():
    mypath = 'D:\\'
    files = [f for f in listdir(mypath) if isfile(join(mypath, f))]
    for file in files:
        if file.split('.')[1] == 'txt':
            outputFileName = 'out-' + file
            with open(mypath+outputFileName, 'w') as w:
                with open(mypath+file) as f:
                    for l in f:
                        print l
                        w.write(l)

if __name__== "__main__":
    readWrite()

rawDescription: copy content of file to another file using python script

description: Copy content of file to another file using python script


code:
c = range(a, b)
print [d * e for d in c for e in c]

rawDescription: Transforming nested Python loops into list comprehensions


code:
import Tkinter as tk

class App():
    def __init__(self, parent):
        self.parent = parent
        self.options = ['one', 'two', 'three']

        self.om_variable = tk.StringVar(self.parent)
        self.om_variable.set(self.options[0])
        self.om_variable.trace('w', self.option_select)

        self.om = tk.OptionMenu(self.parent, self.om_variable, *self.options)
        self.om.grid(column=0, row=0)

        self.label = tk.Label(self.parent, text='Enter new option')
        self.entry = tk.Entry(self.parent)
        self.button = tk.Button(self.parent, text='Add option to list', command=self.add_option)

        self.label.grid(column=1, row=0)
        self.entry.grid(column=1, row=1)
        self.button.grid(column=1, row=2)

        self.update_button = tk.Button(self.parent, text='Update option menu', command=self.update_option_menu)
        self.update_button.grid(column=0, row=2)

    def update_option_menu(self):
        menu = self.om["menu"]
        menu.delete(0, "end")
        for string in self.options:
            menu.add_command(label=string,
                             command=lambda value=string: self.om_variable.set(value))

    def add_option(self):
         self.options.append(self.entry.get())
         self.entry.delete(0, 'end')
         print self.options

    def option_select(self, *args):
        print self.om_variable.get()

root = tk.Tk()
App(root)
root.mainloop()

rawDescription: Updating OptionMenu from List

description: Updating OptionMenu from List


code:
class Inherit2(Inherit1):
    def __init__(self, a=5, b=5):
        print "INHERIT2"
        super(Inherit1, self).__init__(a=a, b=b)

rawDescription: Bypassing constructor in Python 2.7

description: Bypassing constructor in Python 2.7


code:
import multiprocessing
import os.path
import hashlib
import sys

VALID_EXTENSIONS = ('.JPG', '.GIF', '.JPEG')
MAX_FILE_SZ = 1000000

def md5_file(fname):
    try:
        with open(fname) as fo:
            m = hashlib.md5()
            chunk_sz = m.block_size * 128
            data = fo.read(chunk_sz)
            while data:
                m.update(data)
                data = fo.read(chunk_sz)
        md5_file.queue.put((fname, m.hexdigest()))
    except IOError:
        md5_file.queue.put((fname, None))

def is_valid_file(fname):
    ext = os.path.splitext(fname)[1].upper()
    fsz = os.path.getsize(fname)
    return ext in VALID_EXTENSIONS and fsz <= MAX_FILE_SZ

def init(queue):
    md5_file.queue = queue

def main():
    # Holds tuple (fname, md5sum) / md5sum will be none if an IOError occurs
    queue = multiprocessing.Queue()
    pool = multiprocessing.Pool(None, init, [queue])

    for dirpath, dirnames, filenames in os.walk(sys.argv[1]):
        # Convert filenames to full paths...
        full_path_fnames = map(lambda fn: os.path.join(dirpath, fn),
                               filenames)
        full_path_fnames = filter(is_valid_file, full_path_fnames)
        pool.map(md5_file, full_path_fnames)

    # Dump the queue
    while not queue.empty():
        print queue.get()
    return 0

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

rawDescription: Efficiently recurse through directory of files while minimizing memory usage in Python


code:
import pyglet

key = pyglet.window.key

win = pyglet.window.Window()
keyboard = key.KeyStateHandler()
win.push_handlers(keyboard)

print keyboard[key.UP] and keyboard[key.LEFT]

rawDescription: detecting two simultaneous keys in pyglet (python)

description: Detecting two simultaneous keys in pyglet (python)


code:
import httplib
from cStringIO import StringIO

h = httplib.HTTPMessage(StringIO(""))
h["Content-Type"] = "text/plain"
h["Content-Length"] = "1234"

print h.items()

rawDescription: Python: issue in displaying as a list httplib.HTTPMessage


code:
import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from dmoz.items import DmozItem
from scrapy.selector import HtmlXPathSelector

class DmozSpider(CrawlSpider):
    name = "dmoz"
    allowed_domains = ["dmoz.org"]
    start_urls = [
        "http://www.dmoz.org/Computers/Programming/Languages/Python"
    ]
    rules = [Rule(SgmlLinkExtractor(allow=[r'Books']), callback='parse_item')]

    def parse_item(self, response):
        hxs = HtmlXPathSelector(response)
        item = DmozItem()

        # Extract links
        item['link'] = hxs.select("//li/a/text()").extract()  # Xpath selector for tag(s)

        print item['link']

        for cont, i in enumerate(item['link']):
            print "link: ", cont, i

rawDescription: Scrapy extracting from Link

description: Scrapy extracting from Link


code:
result = [[e-1 for e in i] for i in n]
print result

rawDescription: How to substract multidimensional array in Python?

description: Substract multidimensional array in Python


code:
amount_to_fill = .5
current_fill = 0
loops = 10
for i in range(loops):
    current_fill += amount_to_fill
    amount_to_fill /= 2
print "cup is {}% full".format(current_fill*100)

rawDescription: Halving each continuous number looping

description: Halving each continuous number looping


code:
import json

with open('python.json') as fp:
    ds = json.load(fp) #this file contains the json

    mem = {}

    for record in ds:
        name = record["name"]
        if name not in mem:
            mem[name] = record

    print mem.values()

rawDescription: removing json items from array if value is duplicate python

description: Removing json items from array if value is duplicate python


code:
regex = re.compile(r'\+CMTI: "SM",(\d+)')

def poll(x):
    myRegexableString = "".join(x)
    print "Printing myRegexableString"
    pprint(myRegexableString)
    lst = regex.findall(myRegexableString)

rawDescription: Parsing strings using regular expressions received by a GSM modem connected to a laptop via a serial port in python


code:
import time
import threading

def otherdef(num1, num2, num3):
    #Inside of otherdef we use an event to loop on,
    #we do this so we can have a convent way to stop the process.

    stopped = threading.Event()
    #set a timer, after 10 seconds.. kill this loop
    threading.Timer(10, stopped.set).start()
    #while the event has not been triggered, do something useless
    while(not stopped.is_set()):
        print 'doing ', num1, num2, num3
        stopped.wait(1)

    print 'otherdef exiting'

print 'Running'
#create a thread, when I call start call the target and pass args
p = threading.Thread(target=otherdef, args=(1,2,3))
p.start()
#wait for the threadto finish
p.join(11)

print 'Done'

rawDescription: Python Multi-threading Help

description: Python Multi-threading Help


code:
from lxml import etree

fname = 'output/so-help.html'

# parse
hparser = etree.HTMLParser(encoding='utf-8')
htree   = etree.parse(fname, hparser)

# garbled
htree.write('so-dumpu.html')

# targets
demo_name = htree.xpath("//span[@id='demo']")

# garbled
print 'name: "' + demo_name[0].text

rawDescription: lxml unicode characters

description: Lxml unicode characters


code:
import operator

RecordsByTeam = {}
for r in TeamDict['TeamRecords']:
    RecordsByTeam[r['Team']] = r

for team, rank in sorted(RankDict.items(), key=operator.itemgetter(1)):
    print team
    print rank
    try:
        print RecordsByTeam[team]
    except KeyError:
        print 'No details could be found for team', team

rawDescription: Comparing 2 dictionaries in python

description: Comparing 2 dictionaries in python


code:
class IterStreamer(object):
    """
    File-like streaming iterator.
    """
    def __init__(self, generator):
        self.generator = generator
        self.iterator = iter(generator)
        self.leftover = ''

    def __len__(self):
        return self.generator.__len__()

    def __iter__(self):
        return self.iterator

    def next(self):
        return self.iterator.next()

    def read(self, size):
        data = self.leftover
        count = len(self.leftover)
        try:
            while count < size:
                chunk = self.next()
                data += chunk
                count += len(chunk)
        except StopIteration, e:
            self.leftover = ''
            return data

        if count > size:
            self.leftover = data[size:]

        return data[:size]

rawDescription: Python: Convert an iterable to a stream?

description: Python: Convert an iterable to a stream


code:
from twisted.internet import reactor, protocol
from twisted.protocols.basic import LineReceiver

class MyHandler(LineReceiver):

    def lineReceived(self, line):
        print "Got line:", line

f = protocol.ClientFactory()
f.protocol = MyHandler
reactor.connectTCP("127.0.0.1", 4711, f)
reactor.run()

rawDescription: Reading socket buffer using asyncore

description: Reading socket buffer using asyncore


code:
import urllib2, datetime, sys, string
import lxml.etree

for i in range(414,416):
    num_string = '{:03d}'.format(i)
    print num_string, datetime.datetime.now()
    url = "http://clerk.house.gov/evs/2001/roll"+num_string+".xml"
    xml = lxml.etree.parse(urllib2.urlopen(url))
    root = xml.getroot()
    actdate = root.xpath('//action-date')[0]
    dte = actdate.text.strip()
    print dte

rawDescription: Python Regex Match Dates

description: Python Regex Match Dates


code:
import boto3
client = boto3.client('ec2')
addresses_dict = client.describe_addresses()
for eip_dict in addresses_dict['Addresses']:
    print eip_dict['PublicIp']

rawDescription: How to obtain all available Elastic IP addresses in boto3

description: Obtain all available Elastic IP addresses in boto3


code:
import thread
import threading
import urllib2
def download_file():
    response = urllib2.urlopen("http://website.com/file.f")
    print "Res: " + str(response.read())
    raw_input("Press any key to exit...")

if __name__ == "__main__":
    t = threading.Thread(target=download_file)
    t.start()
    t.join()
    # The below prints before "Res: ..." which makes me think the script exits before the thread has completed
    print("script exit")

rawDescription: Make Exe Continue Till A Thread Has Completed


code:
import cookielib
import urllib2

cookies = cookielib.LWPCookieJar()
handlers = [
    urllib2.HTTPHandler(),
    urllib2.HTTPSHandler(),
    urllib2.HTTPCookieProcessor(cookies)
    ]
opener = urllib2.build_opener(*handlers)

def fetch(uri):
    req = urllib2.Request(uri)
    return opener.open(req)

def dump():
    for cookie in cookies:
        print cookie.name, cookie.value

uri = 'http://www.google.com/'
res = fetch(uri)
dump()

res = fetch(uri)
dump()

# save cookies to disk. you can load them with cookies.load() as well.
cookies.save('mycookies.txt')

rawDescription: How to set and retrieve cookie in HTTP header in Python?

description: Set and retrieve cookie in HTTP header in Python


rawDescription: Adding newlines in a list of lists

description: Adding newlines in a list of lists


code:
#!/usr/bin/env python

import time
import memcache
import hashlib

def memoize(f):

    def newfn(*args, **kwargs):
        mc = memcache.Client(['127.0.0.1:11211'], debug=0)
        # generate md5 out of args and function
        m = hashlib.md5()
        margs = [x.__repr__() for x in args]
        mkwargs = [x.__repr__() for x in kwargs.values()]
        map(m.update, margs + mkwargs)
        m.update(f.__name__)
        m.update(f.__class__.__name__)
        key = m.hexdigest()

        value = mc.get(key)
        if value:
            return value
        else:
            value = f(*args, **kwargs)
            mc.set(key, value, 60)
            return value
        return f(*args)

    return newfn

@memoize
def expensive_function(x):
    time.sleep(5)
    return x

if __name__ == '__main__':
    print expensive_function('abc')
    print expensive_function('abc')

rawDescription: Using python dictionary as a temporary in-memory key-value database?


code:
import csv

reader = csv.reader(open('data.csv', 'rb'))
header = reader.next()
data = {}

for row in reader:
    key = tuple([int(v) for v in row[:-1]])
    val = row[-1]
    data[key] = float(val)

# Retrieve a value
print data[1, 1961, 3]

rawDescription: Most appropriate data structure (Python)


code:
from robobrowser import RoboBrowser

the_url = 'the_url'
login = the_url + '/login'
content = the_url + '/content'
username = 'username'
password = 'password'

browser = RoboBrowser(parser='lxml')

browser.open(login)
form = browser.get_forms()

# You can use '.get_form()' for a specific form but I'm finding it easier to
# using '.get_forms()' to get all the forms and then I'm just interested
# in the first one:

form = form[0]
print form     # this will give you the information you need to
               # now enter your password details:

form['the_user'].value = username
form['the_pass'].value = password

browser.submit_form(form)

# and then because I'm after the html of certain content pages:

browser.open(content)
source = str(browser.parsed)
return source

rawDescription: python, authentication not recognised - urllib2, requests, asp.net

description: Python, authentication not recognised - urllib2, requests, asp.net


code:
from sys import argv
from os.path import exists
# since we want to have a somewhat standardized format
# and dicts are unordered by default
try:
    from collections import OrderedDict
except ImportError:
    # python 2.6 or earlier, use backport
    from ordereddict import OrderedDict

def get_time_and_date(time):
    date, time = time.split(",")
    time, time_indic = time.split()

    date = pad_time(date)
    time = "{0:} {1:}".format(pad_time(time), time_indic)

    return time, date
"""
   Make all the time values look the same, ex turn 5:30 AM into 05:30 AM
"""
def pad_time(time):
    # if its time
    if ":" in time:
        separator = ":"
    # if its a date
    else:
        separator = "/"

    time = time.split(separator)
    for index, num in enumerate(time):
        if len(num) < 2:
            time[index] = "0" + time[index]

    return separator.join(time)

def filework():
    from_file, to_file = argv[1:]
    data = OrderedDict()

    print "copying from %s to %s" % (from_file, to_file)
    # by using open(...) the file closes automatically
    with open(from_file, "r") as inputfile:
        indata = inputfile.readlines()
        entries = []

        print "the input file is %d bytes long" % len(indata)
        print "does the output file exist? %r" % exists(to_file)
        print "ready, hit RETURN to continue, CTRL-C to abort."
        raw_input()

        for line_num in xrange(len(indata)):
            # make the entire string lowercase to be more flexible,
            # and then remove whitespace
            line_lowered = indata[line_num].lower().strip()

            if "start time" == line_lowered:
                time, date = get_time_and_date(indata[line_num+1].strip())
                data["StartTime"] = time
                data["StartDate"] = date
            elif "duration" == line_lowered:
                duration = indata[line_num+1].strip().split()
                # only keep the amount of minutes
                data["Duration"] = duration[0]
            elif "start side" == line_lowered:
                data["StartSide"] = indata[line_num+1].strip()
            elif "fed on both sides" == line_lowered:
                data["FedOnBothSides"] = indata[line_num+1].strip()
            elif line_lowered == "":
                # if a blank line is found, prepare for reading a new entry
                entries.append(data)
                data = OrderedDict()

        entries.append(data)

    # create the outfile if it does not exist
    with open(to_file, "w+") as outfile:
        headers = entries[0].keys()
        outfile.write(", ".join(headers) + "\n")
        for entry in entries:
            outfile.write(", ".join(entry.values()) + "\n")

filework()

rawDescription: Copy pieces of data from a .txt into another file for a spreadsheet


code:
import selenium.webdriver
from selenium.webdriver.common.keys import Keys
import sched, time

driver = selenium.webdriver.Firefox()
url = 'http://www.cic.gc.ca/english/work/iec/index.asp'
driver.get(url)

html_content = ''
# construct a scheduler
s = sched.scheduler(time.time, time.sleep)

def crawl_me():
    global html_content
    driver.refresh()
    time.sleep(5) # wait 5s for page to be loaded

    country_name = driver.find_element_by_name('country-name')
    country_name.send_keys('United Kingdom')
    # trick's here to send a TAB key to trigger the change event
    country_name.send_keys(Keys.TAB)

    # make sure the second Option Select is active (none not in style)
    assert "none" not in driver.find_element_by_id('category_dropdown').get_attribute('style')

    cateogory_name = driver.find_element_by_name('category-name')
    cateogory_name.send_keys('Working Holiday')

    btn_go = driver.find_element_by_id('submit')
    btn_go.send_keys(Keys.RETURN)

    # again, check if the content has been loaded
    assert "United Kingdom - Working Holiday" not in driver.page_source

    compared_content = driver.find_element_by_id('stats').text
    # here we will end this script if content has changed already
    if html_content != '' and html_content != compared_content:
        # do whatever you want to play the beep sound
        # at the end exit the loop
        driver.close()
        exit(-1)
    # if no changes are found, trigger the schedule_crawl() function, like recursively
    html_content = compared_content
    print html_content
    return schedule_crawl()

def schedule_crawl():
    # set your time interval here, 15*60 = 15 minutes
    s.enter(15*60, 1, crawl_me, ())
    s.run() # and run it of course

crawl_me()

rawDescription: Web Scraping w/Mechanize and/or BeautifulSoup4 on ASP pages


code:
byState_df = pd.DataFrame(states.items())
byState_df['Deaths'] = 0
df['Deaths'] = df['Deaths'].convert_objects(convert_numeric=True)
print byState_df
for index, row in df.iterrows():
    if row['Area'] in states:
           byState_df.loc[byState_df[0] == row['Area'], 'Deaths'] = row['Deaths']

print byState_df

rawDescription: Setting values when iterating through a DataFrame


rawDescription: How come my full circle isn't 360 degrees?


code:
def print_method_module(method):
    def printer(self):
        name = self.__module__
        if name == '__main__':
            filename = sys.modules[self.__module__].__file__
            name = os.path.splitext(os.path.basename(filename))[0]
        print name
        return method(self)
    return printer

rawDescription: How Do I Get the Module Name of an Object's Class Definition Rather Than the Module Name of the Object's Instantiation?


code:
import module

print dir(module) # Find functions of interest.

# For each function of interest:
help(module.interesting_function)
print module.interesting_function.func_defaults

rawDescription: How can I list the methods in a Python 2.5 module?

description: List the methods in a Python 2.5 module


code:
for i, each in enumerate(test_text):
    print each, test_text[i-5]

rawDescription: How to address an earlier element in a list/string with for?

description: Address an earlier element in a list/string with for


code:
import random

def main():
    pick_list = ["Rock","Paper","Scissors"]
    player_pick = str(raw_input("Rock, Scissors, Paper! Make your Pick! "))
    pc_pick = random.choice(pick_list)
    if player_pick not in pick_list:
        print "Oops, looks like you didn't pick correctly. Try again!"
        main()
    else:
        print "Your pick was " + player_pick
        print "My pick was " + pc_pick
    results(pc_pick,player_pick)
    table_score(results,pc_pick,player_pick)
    print "The score so far is... You: ",Score.player_score ,"Me", Score.pc_score
    rematch()

def results(pc_pick,player_pick):
    if pc_pick == player_pick:
        print "It's a tie!"
    elif pc_pick == "Rock" and player_pick == "Paper":
        print "You win!"
        return "Victory"
    elif pc_pick == "Rock" and player_pick == "Scissors":
        print "Sorry, I win"
        return "Loss"
    elif pc_pick == "Scissors" and player_pick == "Rock":
        print "You win!"
        return "Victory"
    elif pc_pick == "Scissors" and player_pick == "Paper":
        print "Sorry, I win"
        return "Loss"
    elif pc_pick == "Paper" and player_pick == "Scissors":
        print "You win!"
        return "Victory"
    elif pc_pick == "Paper" and player_pick == "Rock":
        print "Sorry, I win"
        return "Loss"

def rematch():
    challenge = str(raw_input('Wanna go again? [Y/n]'))
    positive_answers =['Y','y', 'yes','Yes']
    negative_answers = ['N','n','No','no']
    if challenge in positive_answers:
        main()
    elif challenge in negative_answers:
        print "Goodbye!"
        raw_input("Press any key to exit")
    else:
        print "Sorry I didn't get that, try again"
        rematch()

def table_score(results, pc_pick, player_pick):
    pc_score = 0
    player_score = 0
    if results(pc_pick, player_pick) == "Victory":
        Score.player_score += 1
    elif results(pc_pick,player_pick) == "Loss":
        Score.pc_score += 1
    else:
        Score.player_score += 0
        Score.pc_score += 0
    print "Player:" + str(player_score)
    print "Pc:" + str(pc_score)

class Score:
    def __init__(self):
        self.pc_score = 0
        self.player_score = 0
Score = Score()

main()

rawDescription: How to give concatenate function results to a class in python 2.7

description: Give concatenate function results to a class in python 2.7


rawDescription: map degrees to 0 - 360 in python

description: Map degrees to 0 - 360 in python


code:
def vanderpol(y, t, mu=1000.):
    return [y[1], mu*(1. - y[0]**2)*y[1] - y[0]]

def vanderpol_jac(y, t, mu=1000.):
    return [[0, 1], [-2*y[0]*y[1]*mu - 1, mu*(1 - y[0]**2)]]

y0 = [2, 0]
t = arange(0, 5000, 1)
y,info = odeint(vanderpol, y0, t, Dfun=vanderpol_jac, full_output=True)

print info['mused'] # method used (1=adams, 2=bdf)
print info['nje']   # cumulative number of jacobian evaluations
plot(t, y[:,0])

rawDescription: Why isn't the Dfunc(gradient) never called while using integrate.odeint in SciPy?


code:
if(isinstance(x, tweepy.models.Relationship)):
    print x

rawDescription: Determine twitter relationship via tweepy


code:
#!/usr/bin/python
import private
import spynner
from spynner import browser
import pyquery
import urlparse
import urllib

b = browser.Browser()
b.load("http://structures.com/cgi-bin/index.cgi")
#browser.debug_level = spynner.DEBUG

def fill_login_form():
    b.fill("input[name=login]",private.uname)
    b.fill("input[name=password]",private.password)
    b.click("input[type=submit]")

def click_download():
    pass

#b.create_webview(True)
b.fill("input[name=login]",private.uname)
b.fill("input[name=password]",private.password)
b.click("input[type=submit]")

b.wait_load()
d = pyquery.PyQuery(b.html)
print str(d('a[href$="ftpquota"]'))
# Test Downloading by clicking a link which will download file called .ftpquota
# Jquery pattern $= indicates a pattern that ends with "ftpquota"

#b.click('a[href$="ftpquota"]')

raw_href = d('a[href$="ftpquota"]').attr("href")
href = urllib.unquote(raw_href)
print "HREF" , raw_href
print "Unquted" , href
print "urlparse.urlsplit()", urlparse.urlsplit(href)
print  "Current URL", b.url
print "Synthesized url" , urlparse.urljoin(b.url, href)
#d.make_links_absolute(base_url=b.url)
filename = raw_href.split("%2F")[-1]
b.download(href, open(filename, "w"))

rawDescription: Spynner programmatic python browser to download files from cgi file-server: jquery selector for browser.click()?


code:
for line in linelist:
    print line.rstrip('\n')

rawDescription: why python print an empty line from a file

description: Why python print an empty line from a file


code:
dic = ["goodmorning", "wakeup"]
test = raw_input("test: ")
if test in dic:
    print "hello"
else:
    print "testf"

rawDescription: Check for individual words in a string

description: Check for individual words in a string


code:
d = {'0': ['Pyrobaculum'], '1': ['Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium', 'Mycobacterium'], '3': ['Thermoanaerobacter', 'Thermoanaerobacter'], '2': ['Helicobacter', 'Mycobacterium'], '5': ['Thermoanaerobacter', 'Thermoanaerobacter'], '4': ['Helicobacter'], '7': ['Syntrophomonas'], '6': ['Gelria'], '9': ['Campylobacter', 'Campylobacter'], '8': ['Syntrophomonas'], '10': ['Desulfitobacterium', 'Mycobacterium']}

# Iterate through and find out how many times each key occurs
vals = {}                       # A dictonary to store how often each value occurs.
for i in d.values():
  for j in set(i):              # Convert to a set to remove duplicates
    vals[j] = 1 + vals.get(j,0) # If we've seen this value iterate the count
                                # Otherwise we get the default of 0 and iterate it
print vals

# Iterate through each possible freqency and find how many values have that count.
counts = {}                     # A dictonary to store the final frequencies.
# We will iterate from 0 (which is a valid count) to the maximum count
for i in range(0,max(vals.values())+1):
    # Find all values that have the current frequency, count them
    #and add them to the frequency dictionary
    counts[i] = len([x for x in vals.values() if x == i])

for key in sorted(counts.keys()):
  if counts[key] > 0:
     print key,":",counts[key]

rawDescription: Count how many times a dictionary value is found with more than one key


code:
from bs4 import BeautifulSoup
import urllib
from urlparse import urljoin

urlInput = raw_input('enter - ')
html = urllib.urlopen(urlInput).read()
soup = BeautifulSoup(html)
tags = soup('a')
urls = set()

for tag in tags:
     urls.add(urljoin(url, tag.get('href')))

for url in urls:
     print url

rawDescription: How To Get All Link On Html Document Using Beautiful Soup?


code:
def not_none(f):
    def func(*args, **kwargs):
        if any(arg is None for arg in args):
            raise ValueError('function {}: does not take arguments of None'.format(f.__name__))
        return f(*args, **kwargs)
    return func

@not_none
def test(a, b):
    print a, b

rawDescription: Python/Django: Are there any decorators to tell that input is not none?


code:
# fake setup
PASS = ["foo.exe", "bar.exe", "really_long_filename.exe"]
FAILED = ["failed.exe"]
types = ["32-bit", "64-bit", "64-bit"]
arch64 = '64'
arch32 = '32'

# your code
def print_row(filename, status, file_type):
    print " %-45s %-15s %15s" % (filename, status, file_type)

print_row('FileName', 'Status', 'Binary Type')

for files in PASS:
    log = types.pop()
    if arch64 in log:
        print_row(files, 'PASSED', '64-bit')
    elif arch32 in log:
        print_row(files, 'PASSED', '32-bit')
print"\n"

for files in FAILED:
        print_row(files, 'FAILED', '')

print "\n\n"

rawDescription: Formatting console Output

description: Formatting console Output


code:
class Number_Guesser(object):
    def __init__(self,lower_bound,upper_bound):
        self.lower_bound = lower_bound
        self.upper_bound = upper_bound
        self.number_of_guesses = 1

    def guess_and_adjust(self):
        while True:
            self.anticheat()
            my_guess = self.make_guess()
            answer = raw_input('Enter 1 if your number is higher, 2 if it\'s lower, or 3 if I was correct!')
            if answer=='1':
                self.lower_bound = my_guess + 1
                self.number_of_guesses += 1
            elif answer=='2':
                self.upper_bound = my_guess - 1
                self.number_of_guesses += 1
            elif answer=='3':
                print 'Woohoooo! I guessed your number in {0} guesses!'.format(self.number_of_guesses)
                quit()
            else:
                print 'Hey, that input is invalid!'

    def anticheat(self):
        if self.lower_bound > self.upper_bound:
            print 'You cheated! We\'re done here!'
            quit()

    def make_guess(self):
        self.current_guess = (self.upper_bound + self.lower_bound) / 2
        print 'My guess is {0}.'.format(self.current_guess)
        return self.current_guess

n = Number_Guesser(1, 100)
n.guess_and_adjust()

rawDescription: Having trouble keeping a persistent variable in a class


code:
import wx
import wx.grid as grid

class MainPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent = parent)

        self.txtOne = wx.StaticText(self, -1, label = "piradoba", pos = (20,10))
        self.txtPlace = wx.TextCtrl(self, pos = (20,30))
        self.txtTwo = wx.StaticText(self, -1, label = "", pos = (20,40))

        button = wx.Button(self, label = "search", pos = (20,70))
        button.Bind(wx.EVT_BUTTON, self.onButton)

    def onButton(self, event):
        var=self.txtPlace.GetValue()
        if len(var) == 9 or len(var) == 11:
            print "???"
        # MainPanel->SplitterWindow->MainFrame ( 2x GetParent() )
        self.GetParent().GetParent().AddPanel()

class SecondPanel(wx.Panel):

    def __init__(self, parent,a,b):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)

        MyGrid=grid.Grid(self)
        MyGrid.CreateGrid(a, b)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(MyGrid, 0, wx.EXPAND)
        self.SetSizer(sizer)

class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="test", size=(800,600))

        self.splitter = wx.SplitterWindow(self)

        self.panelOne = MainPanel(self.splitter)
        self.panelTwo = SecondPanel(self.splitter, 1, 1)

        self.splitter.SplitHorizontally(self.panelOne, self.panelTwo)
        self.splitter.SetMinimumPaneSize(20)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.splitter, 2, wx.EXPAND)

        self.SetSizer(self.sizer)

    def AddPanel(self):
        self.newPanel = SecondPanel(self, 1, 1)
        self.sizer.Add(self.newPanel, 1, wx.EXPAND)
        self.sizer.Layout()

if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    frame.Show()
    app.MainLoop()

rawDescription: How to add panel with event button in wxpython?

description: Add panel with event button in wxpython


code:
import re, ast
data = 'IN.Tags.Share.handleCount({"count":17737,"fCnt":"17K","fCntPlusOne":"17K","url":"www.test.com\/"});'
m = re.match('.*({.*})', data)
d = ast.literal_eval(m.group(1))
print d['count']

rawDescription: How to get a dicitionary key value from a string that contains dictionary?

description: Get a dicitionary key value from a string that contains dictionary


code:
print "Welcome to the receipt program"

total = 0
while True:
    value = raw_input('Enter the value for the seat [Press q to quit]: ')

    if value == 'q':
        break

    if value.isdigit():
        total += int(value)
    else:
        print "I'm sorry, but {} isn't valid.".format(value)

print 'total is {}'.format(total)

rawDescription: Problems with infinite-loop and adding raw_input results


code:
def fence(lst, numrails):
    fence = [[None] * len(lst) for n in range(numrails)]
    rails = range(numrails - 1) + range(numrails - 1, 0, -1)
    for n, x in enumerate(lst):
        fence[rails[n % len(rails)]][n] = x

    if 0: # debug
        for rail in fence:
            print ''.join('.' if c is None else str(c) for c in rail)

    return [c for rail in fence for c in rail if c is not None]

def encode(text, n):
    return ''.join(fence(text, n))

def decode(text, n):
    rng = range(len(text))
    pos = fence(rng, n)
    return ''.join(text[pos.index(n)] for n in rng)

z = encode('ATTACK.AT.DAWN', 3)
print z # ACTWTAKA.ANT.D
y = decode(z, 3)
print y # ATTACK.AT.DAWN

rawDescription: Rail Fence Cipher- Looking for a better solution


code:
from ftplib import FTP

ftp = FTP(host, user, passwd)
for r in ftp.dir():
    if r.upper().startswith('D'):
        print r[58:]  # Starting point

rawDescription: Determine if a listing is a directory or file in Python over FTP


code:
def read_csv(csvfile):
    with open(csvfile, 'rb') as file:
        columns = 4
        reader = csv.reader(file, delimiter=';')
        # i will count the rows, starting at 1
        for i, row in enumerate(reader, start=1):
            for column in range(0, columns):
                 print row[column], ' ====== ', 'column ', column+1, ' and row ', i

rawDescription: How to index rows in my output

description: Index rows in my output


code:
from elixir import *

metadata.bind = "sqlite:///"

class Regions(Entity):
    regionname = Field(String(255))

class Location(Entity):
    region = ManyToOne('Regions')

setup_all()
create_all()

#Create the region names:
na_temp = Regions(regionname="North America")
sa_temp = Regions(regionname="South America")
ca_temp = Regions(regionname="Central America")
ap_temp = Regions(regionname="Asia/Pacific Islands")
session.commit()

#Create links to each region in the location table:
northamerica = Location(region=na_temp)
southamerica = Location(region=sa_temp)
centamerica = Location(region=ca_temp)
asiapacific = Location(region=ap_temp)
anotherarea = Location(region=sa_temp)
yetanotherarea = Location(region=na_temp)
session.commit()

#Get all items from the Location table:
locations = Location.query.all()

#Display the contents of the Location table, and lookup the name from the Regions table
for place in locations:
    print "Location table id: {}".format(place.region_id)
    print "Lookup region name: {}".format(Regions.get_by(id=place.region_id).regionname)
    print

rawDescription: How do you make codes/lookup tables in Elixir?

description: Make codes/lookup tables in Elixir


code:
import os, sys, commands
from subprocess import Popen, PIPE

var1 = sys.argv[1]
var2 = sys.argv[2]
(var3, tError) = Popen(['osascript', '/Setup.scpt', var1, var2], stdout=PIPE).communicate()
print var1
print var2
print var3

rawDescription: pass and receive values between python script and applescript

description: Pass and receive values between python script and applescript


code:
from scrapy.xlib.pydispatch import dispatcher
from scrapy import signals
from scrapy.stats import stats
from datetime import datetime

def handle_spider_closed(spider, reason):
    print 'Spider closed:', spider.name, stats.get_stats(spider)
    print 'Work time:', datetime.now() - stats.get_stats(spider)['start_time']

dispatcher.connect(handle_spider_closed, signals.spider_closed)

rawDescription: Recording the total time taken for running a spider in scrapy


code:
for field in self.Reg_Fields:
    field.returnPressed.connect(lambda field=field: self.reg_change(field))

def reg_change(self, field):
    print field.text(), field.objectName()

rawDescription: How to get the position of a Widget in an array - python

description: Get the position of a Widget in an array - python


code:
def countedSubWords(word, dictionary):
  fragments = set(
    word[i:j]
    for i in range(len(word)) for j in range(i+3, len(word)+1)
  )
  subWords = fragments.intersection(dictionary)
  return (len(subWords), subWords)

def main():
  with open('wordlist.txt') as words:
    dictionary = set(word.strip() for word in words if len(word.strip()) > 2)
    print max(countedSubWords(word, dictionary) for word in dictionary)

rawDescription: Python- find all subwords that can be found inside of a word


code:
import threading

class MetaA(type):
  def __new__(self, name, bases, clsDict):
    # change <type> behavior
    clsDict['_lock'] = threading.Lock()
    return super(MetaA, self).__new__(self, name, bases, clsDict)

class A(object):
  __metaclass__ = MetaA

  @classmethod
  def getLock(cls):
    return cls._lock

class B(A):
  pass

print 'id(A.getLock())', id(A.getLock())
print 'id(B.getLock())', id(B.getLock())
print A.getLock() == B.getLock()

rawDescription: How to avoid deadlock with class attributes initialization with locks, inheritance and threading in Python?

description: Avoid deadlock with class attributes initialization with locks, inheritance and threading in Python


code:
import os
import re
from collections import Counter

def pairs(text):
    ans = re.findall(r'[A-Za-z]+', text)
    return (tuple(ans[i:i+2]) for i in xrange(len(ans)-1))

mypairs = tuple([ tuple(line.split()[-2:]) for line in open('results.txt')])

c = Counter()
folderpath = 'path/to/directory'
for dirpath, dnames, fnames in os.walk(folderpath):
    for f in fnames:
        if not '.txt' in f: continue
        for line in open(os.path.join(dirpath, f)):
            c += Counter(p for p in pairs(line) if p in mypairs)

for item in c.most_common():
    print item

rawDescription: Finding and counting the frequency of known pairs of words in multiple files


code:
from threading import Thread
import time
import sys

def myfn(test, callback):

    while not test():  # check if the first function passed in evaluates to True
        time.sleep(.001)  # we need to wait to give the other thread time to run.
    callback() # test() is True, so call callback.

nums = []

t = Thread(target=myfn, args=(lambda: len(nums) > 5,
           lambda: sys.stdout.write('condition met')))
t.start() # start the thread to monitor for nums length changing

for n in range(10):
    nums.append(n)
    print nums  # just to show you the progress
    time.sleep(1)

rawDescription: Condition testing/callback mechanism

description: Condition testing/callback mechanism


code:
def wrap(Class, method):
    def wrapper(self, *args, **kwargs):
        print Class
        return method(self, *args, **kwargs)
    return method.__class__(wrapper, None, Class)

def rate_limit(*methods):
    def decorator(Class):
        for method_name in methods:
            method = getattr(Class, method_name)
            setattr(Class, method_name, wrap(Class, method))
        return Class
    return decorator

@rate_limit('post')
class SomeEndpoint(object):

    def post(self):
        pass

class Subclass(SomeEndpoint):
    pass

a = Subclass()
a.post()
# prints <class 'SomeEndpoint'>

rawDescription: How to determine the class defining a method through introspection

description: Determine the class defining a method through introspection


code:
list("ō")
print list(set(asa) & set(["ō"]))
print list(set(asa) & set(["ō"]))[0]

rawDescription: python intersection of utf-8 list and utf-8 string

description: Python intersection of utf-8 list and utf-8 string


code:
import sys
for line in iter(sys.stdin.readline,""):
    print line

rawDescription: Piping iostat -d 1 to python sys.stdin

description: Piping iostat -d 1 to python sys.stdin


code:
import tarfile
import glob
import re

reT = re.compile(r'.*?_sl_H.*?')

for tar_filename in glob.glob(r'\my_source_folder\*.tar'):
    try:
        t = tarfile.open(tar_filename, 'r')
    except IOError as e:
        print e
    else:
        t.extractall('outdir', members=[m for m in t.getmembers() if reT.search(m.name)])

rawDescription: Python: Extracting specific files with pattern from tar.gz without extracting the complete file


code:
import xlrd

workbook = xlrd.open_workbook("input.xls")
worksheet = workbook.sheet_by_name("Sheet1")

for row in xrange(worksheet.nrows):
    value_first = worksheet.cell_value(row, 0)
    value_second = worksheet.cell_value(row, 1)
    if value_first in value_second:
        print row
    else:
        print 'no'

rawDescription: Difficulty with using Lists to search in xlrd


code:
def justify(s, pos):
    if len(s)<=70:
        if pos == l:
            print 30*' ' + s
        elif pos == c:
            print ((70 - len(s))/2)*' ' + s
        elif pos == r:
            #you missed it here...
            print (40 - len(s))*' ' + s
        else:
            print('You entered invalid argument-(use either r, c or l)')
    else:
        print("The entered string is more than 70 character long. Couldn't be justified.")

rawDescription: Function in python that justifies string (to either left, center or right)


code:
for element in driver.find_elements_by_css_selector("locator"):
   height = element.get_attribute('height')
   print height

rawDescription: Looping through a set of webelements using selenium in python


code:
import ntpath
print ntpath.basename(filename)

rawDescription: Dealing with BACKSLASH character in non-string literals in Python


code:
import cffi

ffi = cffi.FFI()
code = """
    void* malloc(size_t);
    void* mymalloc(size_t);
"""
ffi.cdef(code)
api = ffi.verify(code, libraries=['foo'])
result = api.malloc(4)
print "malloc", result
result = api.mymalloc(4)
print "mymalloc", result

rawDescription: How to support 64 bits pointers in cffi?

description: Support 64 bits pointers in cffi


code:
a = ['dog','gate','venue','dig']
a.sort(key=lambda x:min(x))
print a
['gate', 'dog', 'dig', 'venue']

rawDescription: list strings alphabetically, but not from first character

description: List strings alphabetically, but not from first character


code:
from itertools import groupby, count

numberlist = [1,2,3,4,5,8,9,10,11,200,201,202]

def as_range(g):
    l = list(g)
    return l[0], l[-1]

print [as_range(g) for _, g in groupby(numberlist, key=lambda n, c=count(): n-next(c))]

rawDescription: group list of ints by continuous sequence

description: Group list of ints by continuous sequence


code:
imie=raw_input('Podaj swoje imię: ').decode('utf8') #Give your name
dl=len(imie)
print dl

rawDescription: Counting UTF8 characters with Python

description: Counting UTF8 characters with Python


code:
from itertools import count, starmap

class Node(object):
    nextid = count(1).next
    nodes = {}
    def __init__(self, lat, lon):
        self.lat, self.lon = lat, lon
        self.id = self.nextid()
        self.nodes[self.id] = self

    @classmethod
    def all(cls):
        return cls.nodes.values()

    def __repr__(self):
        return '<Node %s>' % self.id

    @classmethod
    def byid(cls, id):
        return cls.nodes[id]

class Way(object):
    nextid = count(1).next
    def __init__(self, nodes):
        self.nodes = nodes[:]
        self.id = self.nextid()

node = Node(lat='X',lon='Y')
print node.id
print Node.all()
print Node.byid(1)

way_nodes = list(starmap(Node, (('X', 'Y'), ('Z', 'W'))))
way = Way(way_nodes)
print way.nodes
print way.id

rawDescription: Is there a typed collection tool in Python?


code:
import fileinput
import re

fn = "test.txt" # your filename

r = re.compile('a(.+?)a')
for line in fileinput.input(fn, inplace=1):
  match = r.match(line)
  print match.group() if match else line.replace('\n', '')

rawDescription: Replace all regex matches in a file

description: Replace all regex matches in a file


rawDescription: Adding together the elements of list in nested dictionary - python


code:
f = int(raw_input("Enter height: "))
s = ''
for i in xrange(f):
    for j in xrange(f-i-1):
        s += ' '
    for j in xrange(2*i+1):
        s += '*'
    s += '\n'
print s

rawDescription: python asterisk triangle without using y* "*"

description: Python asterisk triangle without using y* "*"


code:
class BabyNames():
    def baby_namer(self, gender):
        if 'b' not in gender and 'g' not in gender:
            return self.start_wrong_input()
        elif 'b' in gender:
            test = raw_input("What round are you on? (1-{}) \n".format(str(len(boy_rounds))))
            return boy(boy_rounds[test])
        elif 'g' in gender:
            test = raw_input("What round are you on? (1-{}) \n".format(str(len(girl_rounds))))
            return girl(girl_rounds[test])
        else:
            pass

    def start_wrong_input(self):
        print "You need to put boy or girl to move on!"
        re_try = raw_input("Do you want boy or girl names? \n").lower()
        if 'g' in re_try:
            return self.baby_namer('girl') # use self.baby_namer, you don't need to use x = BabyNames()
        elif 'b' in re_try:
            return self.baby_namer('boy')
        else:
            print "You need to put boy or girl to move on!"

rawDescription: Program keeps looping without calling function


code:
import Tkinter

def save_data(form):
    for widget in form:
        print widget.get()

def load_data(id_value, form):
    for i, widget in enumerate(form):
        widget.delete(0, 'end')
        widget.insert(0, id_value * (i + 2))

root = Tkinter.Tk()

lbl_id = Tkinter.Label(text=u'ID')
entry_id = Tkinter.Entry()
entry_load = Tkinter.Button(text=u'Load')
lbl_field1 = Tkinter.Label(text=u'Field 1')
entry_field1 = Tkinter.Entry()
entry_save = Tkinter.Button(text=u'Save')

lbl_id.grid(row=0, column=0)
entry_id.grid(row=0, column=1)
entry_load.grid(row=0, column=2)
lbl_field1.grid(row=1, column=0)
entry_field1.grid(row=1, column=1)
entry_save.grid(row=2, column=2)

form = [entry_field1]
entry_load['command'] = lambda: load_data(entry_id.get(), form)
entry_save['command'] = lambda: save_data(form)

root.mainloop()

rawDescription: Text fields in Python with tkinter

description: Text fields in Python with tkinter


code:
import oauth2 as oauth

# Create your consumer with the proper key/secret.
consumer = oauth.Consumer(key="your-twitter-consumer-key",
    secret="your-twitter-consumer-secret")

# Request token URL for Twitter.
request_token_url = "http://twitter.com/oauth/request_token"

# Create our client.
client = oauth.Client(consumer)

# The OAuth Client request works just like httplib2 for the most part.
resp, content = client.request(request_token_url, "GET")
print resp
print content

rawDescription: OAuth2 client that works on App Engine

description: OAuth2 client that works on App Engine


code:
a = "Ceci est un text avec beuacuop d'ereurs et pas snychro"
chkr = enchant.checker.SpellChecker("fr_FR")
chkr.set_text(a)
for err in chkr:
    print err.word
    sug = err.suggest()[0]
    err.replace(sug)

c = chkr.get_text()#returns corrected text
print c

rawDescription: How to correct text and return the corrected text automatically with PyEnchant

description: Correct text and return the corrected text automatically with PyEnchant


code:
ss = [(0,'bb','jj'), (1,'aa','mm'), (2,'aa','kk'),(3,'bb','ee'),(4,'gg','ff')]

l = []

def insert_sort(l, e, compare):
    lo = 0
    hi = len(l)
    while lo < hi:
        mid = (lo+hi) / 2
        if compare(e, l[mid]):
            lo = mid + 1
        else:
            hi = mid
    l.insert(lo, e)

ascend_list = []
descend_list = []

for i in ss:
    insert_sort(ascend_list, i, lambda x, y: x[1:] >= y[1:])

for i in ss:
    insert_sort(descend_list, i, lambda x, y: x[1:] < y[1:])

print ascend_list
print descend_list

rawDescription: Maintain a list sorted by multiple attributes?


code:
def get_block(data_rows):
    samples = []

    for cell in data_rows[0]:
        samples.append('')

    # add one row at a time to each sample and see if all are unique
    for row_index, row in enumerate(data_rows):
        for cell_index, cell in enumerate(row):
            samples[cell_index] = '%s%s' % (samples[cell_index], cell)

        are_all_unique = True
        sample_dict = {} # use dictionary keys to find repeats
        for sample in samples:
            if sample_dict.get(sample):
                # already there, so another row needed
                are_all_unique = False
                break
            sample_dict[sample] = True # add the key to the dictionary
        if are_all_unique:
            return True, row_index

    return False, None

def get_all_blocks(all_rows):
    remaining_rows = all_rows[:] # make a copy
    blocks = []

    while True:
        found_block, block_end_index = get_block(remaining_rows)
        if found_block:
            blocks.append(remaining_rows[:block_end_index+1])
            remaining_rows = remaining_rows[block_end_index+1:]
            if not remaining_rows:
                break
        else:
            blocks.append(remaining_rows[:])
            break

    return blocks

if __name__ == "__main__":
    v1 = ['00', '00', '11', '01']
    v2 = ['00', '00', '00', '00']
    v3 = ['01', '11', '00', '00']
    v4 = ['00', '00', '00', '00']

    all_rows = [v1, v2, v3, v4]

    blocks = get_all_blocks(all_rows)

    for index, block in enumerate(blocks):
        print "This is block %s." % index
        for row in block:
            print row
        print

rawDescription: A pythonic way for values comparison in an array?


code:
from collections import OrderedDict

with open('/home/jon/testdata.txt') as fin:
    lines = (line.rstrip() for line in fin)
    unique_lines = OrderedDict.fromkeys( (line for line in lines if line) )

print unique_lines.keys()
# ['None_None', 'ConfigHandler_56663624', 'ColumnConverter_56963312',PredicatesFactory_56963424', 'PredicateConverter_56963648', 'ConfigHandler_80134888']

rawDescription: Remove Duplicates from Text File

description: Remove Duplicates from Text File


code:
def start_reqests():
    yield Request('http://checkip.dyndns.org/', callback=self.check_ip)
    # yield other requests from start_urls here if needed

def check_ip(self, response):
    pub_ip = response.xpath('//body/text()').re('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')[0]
    print "My public IP is: " + pub_ip

    # yield other requests here if needed

rawDescription: Get proxy ip address scrapy using to crawl


code:
import re
from xml.etree import ElementTree

with open('films.xml') as f:
    xml = ElementTree.parse(f)

for t in xml.findall('.//{http://www.mediawiki.org/xml/export-0.5/}text'):
    print '===================='
    m = re.search(r'(?s).*?{{(Infobox film.*?)}}', t.text)
    if m:
        print m.group(1)

rawDescription: Extract information from XML

description: Extract information from XML


code:
from StringIO import StringIO
import unittest
import urllib

import cherrypy

local = cherrypy.lib.httputil.Host('127.0.0.1', 50000, "")
remote = cherrypy.lib.httputil.Host('127.0.0.1', 50001, "")

class Root(object):
    @cherrypy.expose
    def index(self):
        return "hello world"

    @cherrypy.expose
    def echo(self, msg):
        return msg

def setUpModule():
    cherrypy.config.update({'environment': "test_suite"})

    # prevent the HTTP server from ever starting
    cherrypy.server.unsubscribe()

    cherrypy.tree.mount(Root(), '/')
    cherrypy.engine.start()
setup_module = setUpModule

def tearDownModule():
    cherrypy.engine.exit()
teardown_module = tearDownModule

class BaseCherryPyTestCase(unittest.TestCase):
    def webapp_request(self, path='/', method='GET', **kwargs):
        headers = [('Host', '127.0.0.1')]
        qs = fd = None

        if method in ['POST', 'PUT']:
            qs = urllib.urlencode(kwargs)
            headers.append(('content-type', 'application/x-www-form-urlencoded'))
            headers.append(('content-length', '%d' % len(qs)))
            fd = StringIO(qs)
            qs = None
        elif kwargs:
            qs = urllib.urlencode(kwargs)

        # Get our application and run the request against it
        app = cherrypy.tree.apps['']
        # Let's fake the local and remote addresses
        # Let's also use a non-secure scheme: 'http'
        request, response = app.get_serving(local, remote, 'http', 'HTTP/1.1')
        try:
            response = request.run(method, path, qs, 'HTTP/1.1', headers, fd)
        finally:
            if fd:
                fd.close()
                fd = None

        if response.output_status.startswith('500'):
            print response.body
            raise AssertionError("Unexpected error")

        # collapse the response into a bytestring
        response.collapse_body()
        return response

class TestCherryPyApp(BaseCherryPyTestCase):
    def test_index(self):
        response = self.webapp_request('/')
        self.assertEqual(response.output_status, '200 OK')
        # response body is wrapped into a list internally by CherryPy
        self.assertEqual(response.body, ['hello world'])

    def test_echo(self):
        response = self.webapp_request('/echo', msg="hey there")
        self.assertEqual(response.output_status, '200 OK')
        self.assertEqual(response.body, ["hey there"])

        response = self.webapp_request('/echo', method='POST', msg="hey there")
        self.assertEqual(response.output_status, '200 OK')
        self.assertEqual(response.body, ["hey there"])

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

rawDescription: Unittesting cherrypy webapp

description: Unittesting cherrypy webapp


code:
string = '<iframe width="420" height="315" src="https://www.youtube-nocookie.com/embed/jc8zayasOB8" frameborder="0" allowfullscreen></iframe>'
start_src = string.find('src="')
first_quote = string.find('"', start_src)
end_quote = string.find('"', first_quote+1)

print string[first_quote+1:end_quote]

rawDescription: How to get a part of a substring from a particular string in python

description: Get a part of a substring from a particular string in python


code:
selection = view.get_selection()
model, iter = selection.get_selected()
if iter is None:
    print "Nothing selected"
else:
    if model.iter_next(iter) is not None:
        print "Selected item was not last"
    else:
        print "Selected item was last"

rawDescription: How to identify if the current selected row is the last on a gtk.TreeView?

description: Identify if the current selected row is the last on a gtk.TreeView


code:
from datetime import datetime, timedelta
from glob import glob
from os import path

DATE_FORMAT = '%Y-%m-%d'
SUBFOLDER_PATH_FORMAT = r'%Y\%Y_%m\%Y-%m-%d\Folder'
pathDir = r'\\10.81.67.162\DLCx Logs\DLCx02'
dateStart = '2015-08-01'
dateEnd = '2015-09-01'
start_date = datetime.strptime(dateStart, DATE_FORMAT).date()
end_date = datetime.strptime(dateEnd, DATE_FORMAT).date()
delta_one_day = timedelta(days=1)

date = start_date
while date <= end_date:
    subfolder_path = date.strftime(SUBFOLDER_PATH_FORMAT)
    data_folder = path.join(pathDir, subfolder_path)
    if path.isdir(data_folder):
        for filename in glob(os.path.join(data_folder, '*.txt')):
            print filename
    date += delta_one_day

rawDescription: getting file from date range of the current directory

description: Getting file from date range of the current directory


code:
print '%s' % '"Hello, you\'re"'
print '%r' % '"Hello, you\'re"'

rawDescription: The last line of this python program uses both " and ' but I don't know why


code:
from Tkinter import *
import webbrowser
import tkMessageBox
import Tkinter as Tk

def actionDirectory():
    webbrowser.open('C:\AgmPlots')

def actionOpenFile():
    print "Done"

win = Tk.Tk()  #Open up connection and declare button and label
master=win

Lb1 = Listbox(win)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")
Lb1.pack()
button = Tk.Button(text='Open Folder', command=actionDirectory)
button1 = Tk.Button(text='Open Text', command=actionOpenFile)
button.pack()
button1.pack()
win.mainloop()

rawDescription: GUI Label, ListBox,Button appear in different frame


code:
recs = db.GqlQuery('select content from FileHistory')
for rec in recs:
  print rec.key(), rec.content

rawDescription: Get Key in property List using GQL

description: Get Key in property List using GQL


code:
# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

rawDescription: How to add trendline in python matplotlib dot (scatter) graphs?

description: Add trendline in python matplotlib dot (scatter) graphs


code:
from gi.repository import Gtk
from gi.repository import GObject

class MyWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Hello World")
        vbox = Gtk.VBox()
        self.add(vbox)
        self.connect("destroy", lambda x: Gtk.main_quit())
        button = Gtk.Button(label="Click Here")
        vbox.pack_start(button, True, True, 0)
        button = Gtk.Button(label="Or There")
        vbox.pack_start(button, True, True, 0)
        self.show_all()

class Foo:
    def __init__(self):
        self.hook_id = GObject.add_emission_hook(Gtk.Button, "button-press-event", self.on_button_press)
        GObject.add_emission_hook(Gtk.Button, "button-release-event", self.on_button_rel)

    def on_button_press(self, *args):
        print "Press signal received"
        return False # Hook is removed

    def on_button_rel(self, *args):
        print "Release signal received"
        # This will result in a warning
        GObject.remove_emission_hook(Gtk.Button, "button-press-event",self.hook_id)
        return True

win = MyWindow()
foo = Foo()
Gtk.main()

rawDescription: GObject.add_emission_hook only works once


code:
import anydbm
def p(initial):
    d = anydbm.open('cache', 'c')
    d.update(initial)
    return d

d1 = p({}) # create a persistent dictionary
d1['k1'] = 'v1' # add

# add another, maybe 1 billion more, entries on to the dictionary
for i in xrange(100000):
    d1['k{}'.format(i)] = 'v{}'.format(i)

print d1.has_key('k9999999999') # entry that is not in memory, prints False

d1.close() # You have to close it yourself

rawDescription: Persistent Python Set, List and Dictionary?


code:
d = {u'channel': {u'item': {u'condition': {u'date': u'Sun, 17 Jan 2016 3:50 am CET', u'text': u'Light Snow', u'code': u'14', u'temp': u'+6'}}}}
temp = d['channel']['item']['condition']['temp']
print temp

rawDescription: How to get a JSON result into a Python variable?

description: Get a JSON result into a Python variable


code:
import os, shutil

path = os.path.expanduser('~/Drive/Company/images/')
src = os.listdir(os.path.join(path, 'full_res'))

for filename in src:
    if filename.endswith('.jpg'):
        basename = os.path.splitext(filename)[0]
        print basename #log to console so I can see it's at least doing something (it's not)
        dest = os.path.join(path, basename)
        if not os.path.exists(dest):
            os.makedirs(dest) #create the folder if it doesn't exist
        shutil.copyfile(os.path.join(path, 'full_res', filename), os.path.join(dest, 'export.jpg'))

rawDescription: Recursively move files from subdirectory to folders in parent directory


code:
#!/usr/bin/python
## This is an example of a simple sound capture script.
##
## The script opens an ALSA pcm for sound capture. Set
## various attributes of the capture, and reads in a loop,
## Then prints the volume.
##
## To test it out, run it and shout at your microphone:

import alsaaudio, time, audioop

# Open the device in nonblocking capture mode. The last argument could
# just as well have been zero for blocking mode. Then we could have
# left out the sleep call in the bottom of the loop
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)

# Set attributes: Mono, 8000 Hz, 16 bit little endian samples
inp.setchannels(1)
inp.setrate(8000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)

# The period size controls the internal number of frames per period.
# The significance of this parameter is documented in the ALSA api.
# For our purposes, it is suficcient to know that reads from the device
# will return this many frames. Each frame being 2 bytes long.
# This means that the reads below will return either 320 bytes of data
# or 0 bytes of data. The latter is possible because we are in nonblocking
# mode.
inp.setperiodsize(160)

while True:
    # Read data from device
    l,data = inp.read()
    if l:
        # Return the maximum of the absolute value of all samples in a fragment.
        print audioop.max(data, 2)
    time.sleep(.001)

rawDescription: How get sound input from microphone in python, and process it on the fly?


code:
from collections import OrderedDict

ret = OrderedDict()
for order in correct_order:
    for key, value in dict_with_nested_list[order]:
        if key not in ret:
            ret[key] = []
        ret[key].append(value)

print [[key] + value for key, value in ret.items()]

rawDescription: How to simplify a dictionary of nested lists in python?

description: Simplify a dictionary of nested lists in python


code:
import imaplib
import email
import quopri
import HTMLParser

class parseLinks(HTMLParser.HTMLParser):
    def handle_starttag(self, tag, attrs):
        global global_futures_fair_value
        if tag == 'a':
            for name, value in attrs:
                if name == 'href':
                    print name
                    print value

M = imaplib.IMAP4_SSL('imap.gmail.com')
M.login('email@email.com','password123')

M.select('Inbox/Test1')

rv, data = M.search(None, 'ALL')
typ, msg_data = M.fetch('1', '(RFC822)')

msg = email.message_from_string(msg_data[0][1])

url_name = 'Click Here'
html_text = msg.get_payload(0)

msg = str(msg.get_payload()[0])
msg = quopri.decodestring(msg)

linkParser = parseLinks()
linkParser.feed(msg)

rawDescription: How do I retrieve a hyperlink URL from email within python?

description: Retrieve a hyperlink URL from email within python


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

if __name__ == "__main__":
    fig, ax = plt.subplots(1, 1)
    theta = np.linspace(0, 2*np.pi, 1024)
    ln, = ax.plot(theta, np.sin(theta))

    plt.ion()
    plt.show(block=False)
    while True:
        w = raw_input("enter omega: ")
        try:
            w = float(w)
        except ValueError:
            print "you did not enter a valid float, try again"
            continue
        y = np.sin(w * theta)
        ln.set_ydata(y)
        plt.draw()

rawDescription: Matplotlib multiProcessing

description: Matplotlib multiProcessing


code: print tuple(x*y for x,y in zip(t,t[1:]))

rawDescription: Multiply Adjacent Elements

description: Multiply Adjacent Elements


code:
class Annotate(object):
    def __init__(self):
        print "Annotate is runing"
        # rest of your code

root = Tk()
my_object = Annotate()

root.mainloop()

rawDescription: Drawing a selection area with mouse in Tkinter


code:
import thread

class PrtArg(object):
    @staticmethod
    def print_name1(tname,*args):
        cnt = 0
        print "Inside print_name1"
        while cnt < 10:
            cnt += 1
            print "%s : %s\n" % (tname, cnt)

    @staticmethod
    def print_name(tname,*args):
        cnt = 0
        print "Inside print_name"
        while cnt < 10:
            cnt += 1
            print "%s : %s\n" % (tname, cnt)

    def m_prt(self,*args):
        thread.start_new_thread(PrtArg.print_name, (args[0],))
        thread.start_new_thread(PrtArg.print_name1, (args[1],))

rawDescription: Multi-threading using python in robot framework, involving nested function calls


rawDescription: Finding partial-match to item in list-of-lists


code:
user_choice_port = "23, 80, 44"
print map(int, user_choice_port.split(","))
print [int(n) for n in user_choice_port.split(",")]

rawDescription: How to turn users input into a list in Python?

description: Turn users input into a list in Python


code:
import Tkinter as tk

class App():
    def __init__(self):
        self.root = tk.Tk()

        # this works

        self.root.attributes('-fullscreen', True)

        # this doesn't work

        #self.root.overrideredirect(True)
        #self.root.geometry("800x600+100+100") # to see console behind
        #self.root.after(5000, self.appexit) # to kill program after 5s

        self.root.bind('q', self.q_pressed)

        tk.Label(text="some text here").grid()
        e = tk.Entry(self.root)
        e.grid()
        e.focus() # focus doesn't work with overrideredirect

        tk.Button(self.root, text='Quit', command=self.appexit).grid()

        self.root.mainloop()

    def q_pressed(self, event):
        print "q_pressed"
        self.root.destroy()

    def appexit(self):
        print "appexit"
        self.root.destroy()

App()

rawDescription: How to bind Tkinter destroy() to a key in Debian?

description: Bind Tkinter destroy() to a key in Debian


code:
import re

lines = response.readlines()

r = re.compile(r'MMa')
for i in range(len(lines)):
    if r.search(lines[i]):
        print lines[max(0, i-14)]

rawDescription: python grep look for a pattern and then a number of lines before

description: Python grep look for a pattern and then a number of lines before


code:
from fabric.api import *

mylist = run("ls -al").rsplit("\n")
for item in mylist:
    print item

rawDescription: Save output of a Fabric command in a list, where each row is a list element


rawDescription: Sklearn linear regression X and Y input format


code:
mydict = {'d': [0, 1], 'e': [1, 2, 3], 'f': [4]}
mylist = [['d', 'e', 'f', 'c'], ['c', 'v', 'd', 'n']]

def convert_to_set(mylist, result_set=None):
    if result_set is None:
        result_set = []
    for item in mylist:
        if isinstance(item, str):
            result_set.append(item)
        if isinstance(item, list):
            convert_to_set(item, result_set)
    return set(result_set)

def list_to_set(f):
    def wrapper(mylist, mydict):
        myset = convert_to_set(mylist)
        result = f(myset, mydict)
        return result
    return wrapper

@list_to_set
def findit(mylist, mydict):
    gen = ((k, mydict[k]) for k in mylist if k in mydict)
    return [k for k, v in sorted(gen, key=lambda p: len(p[1]))]

print findit(mylist, mydict)

rawDescription: Sort a dictionary by list of lists

description: Sort a dictionary by list of lists


rawDescription: Detecting first 20 chars in string in mark_safe()


code:
import fractions

def gcd(L):
    return reduce(fractions.gcd, L)

print gcd([4,8,12,24])

rawDescription: Computing greatest common denominator in python


code:
import ctypes
BUFSIZE = 1024

class my_struct(ctypes.Structure):
    _fields_ = [ ("_buffer", ctypes.c_byte * BUFSIZE),
                 ("size", ctypes.c_int )]

    def buffer():
        def fget(self):
            return ctypes.string_at(self._buffer, self.size)
        def fset(self, value):
            size = len(value)
            if size > BUFSIZE:
                raise ValueError("value %s too large for buffer",
                                 repr(value))
            self.size = size
            ctypes.memmove(self._buffer, value, size)
        return property(fget, fset)
    buffer = buffer()

proto = my_struct()
proto.buffer = "here\0are\0some\0NULs"
print proto.buffer.replace("\0", " ")

rawDescription: How do I build a python string from a ctype struct?

description: Build a python string from a ctype struct


code:
import numpy as np
import scipy.ndimage as ndimage
from matplotlib import pyplot as plt
import cv2

img= ndimage.imread('image.png')

# Label digfferentz original regions
labels, n_regions = ndimage.label(img)
print "Original number of regions found: ", n_regions
# count the number of pixels in each region
ulabels, sizes = np.unique(labels, return_counts=True)
print sizes

# Delete all regions with size < 2 and relabel
mask_size = sizes < 2
remove_pixel = mask_size[labels]
labels[remove_pixel] = 0
labels, n_regions = ndimage.label(labels) #,s)
print "Number of regions found (region size >1): ", n_regions
# count the number of pixels in each region
ulabels, sizes = np.unique(labels, return_counts=True)
print ulabels
print sizes

# Determine large "first level" regions
first_level_regions=np.where(labels ==1, 0, 1)
labeled_first_level_regions, n_fl_regions = ndimage.label(first_level_regions)
print "Number of first level regions found: ", n_fl_regions

# Plot regions and first level regions
fig = plt.figure()
a=fig.add_subplot(2,3,1)
a.set_title('All regions')
plt.imshow(labels, cmap='Paired', vmin=0, vmax=n_regions)
plt.xticks([]), plt.yticks([]), plt.colorbar()
a=fig.add_subplot(2,3,2)
a.set_title('First level regions')
plt.imshow(labeled_first_level_regions,  cmap='Paired', vmin=0, vmax=n_fl_regions)
plt.xticks([]), plt.yticks([]), plt.colorbar()

for region_label in range(1,n_fl_regions):
    mask= labeled_first_level_regions!=region_label
    result = np.copy(labels)
    result[mask]=0
    subregions = np.unique(result).tolist()[1:]
    print region_label, ": ", subregions

    if len(subregions) >1:
        print "   Element 4 is a critical element: ",  region_label
        print "   Subregions: ", subregions

        #Critical first level region
        crit_first_level_region=np.ones(labels.shape)
        crit_first_level_region[mask]=0

        a=fig.add_subplot(2,3,4)
        a.set_title('Crit. first level region')
        plt.imshow(crit_first_level_region, cmap='Paired', vmin=0, vmax=n_regions)
        plt.xticks([]), plt.yticks([])

        #Critical Region Contour
        im = np.array(crit_first_level_region * 255, dtype = np.uint8)
        _, contours0, hierarchy = cv2.findContours( im.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
        crit_reg_contour = [contours0[0].flatten().tolist()[i:i+2] for i in range(0, len(contours0[0].flatten().tolist()), 2)]
        print crit_reg_contour
        print len(crit_reg_contour)

        #First Subregion
        mask2= labels!=subregions[1]
        first_subreg=np.ones(labels.shape)
        first_subreg[mask2]=0

        a=fig.add_subplot(2,3,5)
        a.set_title('First subregion: '+str(subregions[0]))
        plt.imshow(first_subreg, cmap='Paired', vmin=0, vmax=n_regions)
        plt.xticks([]), plt.yticks([])

        #First Subregion Contour
        im = np.array(first_subreg * 255, dtype = np.uint8)
        _, contours0, hierarchy = cv2.findContours( im.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
        first_sub_contour = [contours0[0].flatten().tolist()[i:i+2] for i in range(0, len(contours0[0].flatten().tolist()), 2)]
        print first_sub_contour
        print len(first_sub_contour)

        #Second Subregion
        mask3= labels!=subregions[0]
        second_subreg=np.ones(labels.shape)
        second_subreg[mask3]=0

        a=fig.add_subplot(2,3,6)
        a.set_title('Second subregion: '+str(subregions[1]))
        plt.imshow(second_subreg, cmap='Paired', vmin=0, vmax=n_regions)
        plt.xticks([]), plt.yticks([])

        #Second Subregion Contour
        im = np.array(second_subreg * 255, dtype = np.uint8)
        _, contours0, hierarchy = cv2.findContours( im.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
        second_sub_contour = [contours0[0].flatten().tolist()[i:i+2] for i in range(0, len(contours0[0].flatten().tolist()), 2)]
        print second_sub_contour
        print len(second_sub_contour)

        maxdist=6
        print "Points in first subregion close to first level contour:"
        close_1=[]
        for p1 in first_sub_contour:
            for p2 in crit_reg_contour:
                if (abs(p1[0]-p2[0])+abs(p1[1]-p2[1]))<maxdist:
                    close_1.append(p1)
                    break

        print close_1
        print len(close_1)

        print "Points in second subregion close to first level contour:"
        close_2=[]
        for p1 in second_sub_contour:
            for p2 in crit_reg_contour:
                if (abs(p1[0]-p2[0])+abs(p1[1]-p2[1]))<maxdist:
                    close_2.append(p1)
                    break

        print close_2
        print len(close_2)

        for p in close_1:
            result[p[1],p[0]]=1

        for p in close_2:
            result[p[1],p[0]]=2

        if len(close_1)>len(close_2):
            print "first subregion is considered a hole:", subregions[0]
            hole=subregions[0]
        else:
            print "second subregion is considered a hole:", subregions[1]
            hole=subregions[1]

        #Plot Critical region with subregions
        a=fig.add_subplot(2,3,3)
        a.set_title('Critical first level region with subregions')
        plt.imshow(result, cmap='Paired', vmin=0, vmax=n_regions)
        plt.xticks([]), plt.yticks([])

        result2=result.copy()

#Plot result
fig2 = plt.figure()
a=fig2.add_subplot(1,1,1)
a.set_title('Critical first level region with subregions and bordering contour segments')
plt.imshow(result2, cmap='flag', vmin=0, vmax=n_regions)
plt.xticks([]), plt.yticks([])

#Plot result
mask_hole=np.where(labels ==hole, True, False)
labels[mask_hole]=1
labels=np.where(labels > 1, 2, 1)

# [Edit] Next two lines include black borders into final result
mask_borders=np.where(img ==0, True, False)
labels[mask_borders]=2

fig3 = plt.figure()
a=fig3.add_subplot(1,1,1)
a.set_title('Final result')
plt.imshow(labels, cmap='flag', vmin=0, vmax=n_regions)
plt.xticks([]), plt.yticks([])

plt.show()

rawDescription: Tricky filling holes in an image

description: Tricky filling holes in an image


code:
def main(argv):
    filename = None
    outfile = None
    call_maininfo = False
    try:
        opts, args = getopt.getopt(argv, 'hi:o:t', ['help', 'input=', 'output='])
        if not opts:
            print 'No options supplied'
            usage()
    except getopt.GetoptError, e:
        print e
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit(2)
        elif opt in ('-i', '--input'):
            filename = arg
        elif opt in ('-o', '--output'):
            outfile = arg
        elif opt == '-t':
            call_maininfo = True
        else:
            usage()
            sys.exit(2)

    print 'Processed options [{0}] and found filename [{1}] and outfile [{2}]'.format(
            ', '.join(argv),
            filename,
            outfile,
            )

    if call_maininfo:
        print 'Calling maininfo()'
        maininfo(filename, outfile)

rawDescription: Cannot handle parameters with getopt python


code:
def compute_root(poly, x_0, epsilon, iter=None): ##Using Newton's method
    if iter is None:
        iter = 0
    try:
        if abs(evalpoly(poly,x_0)) < epsilon:
            return '%s is the root. Took %s iterations.'%(x_0,iter)
        else:
            iter += 1
            x_1 = x_0 - (evalpoly(poly,x_0)/evalderiv(poly,x_0))
            return compute_root(poly, x_1, epsilon, iter=iter)

    except ZeroDivisionError:
        print 'No root.'

rawDescription: Counting Iterations in recursion

description: Counting Iterations in recursion


code:
from collections import Counter
tweets = ['RT Find out how AZ is targeting escape pathways to further personalise breastcancer treatment SABCS14',
    'Did you know Ontario has a special screening program for women considered high risk for BreastCancer',
    'Article Foods That Prevent BreastCancer',
    'PRETTY Infinity Faith Hope Breast Cancer RIBBON SIGN Leather Braided Bracelet breastcancer BreastCancerAwareness']

count = Counter(tweets)
for key in Count:
    print key, Count[key]

rawDescription: How to get count of item repetition in a list?

description: Get count of item repetition in a list


code:
for x in itertools.izip_longest(*l, fillvalue="."):
    print " ".join(str(i) for i in x)

rawDescription: Python - write list list of lists in columns


code:
def answer():
    choice = raw_input("> ") # store the input first
    if "1" in choice:
        print "Hermione\'s advice was terrible! Now you\'re dead and Voldemort wins."
    elif "2" in choice:
        print "You\'re a little drunk. Try again."
    elif "3" in choice:
        print "Congratulations! Now go find Professor Quirrel."
    elif "4" in choice:
        print "Hermione\'s advice was terrible! Now you\'re dead and Voldemort wins."
    elif "5" in choice:
        print "Hermione\'s advice was terrible! Now you\'re dead and Voldemort wins."
    elif "6" in choice:
        print "You\'re a little drunk. Try again."
    elif "7" in choice:
        print "What the hell are you doing back in the Chess Room?"
    else:
        print "No, you cannot use a spell to get out of this. Try a number."

rawDescription: python asks for multiple inputs to navigate single if/elif/else

description: Python asks for multiple inputs to navigate single if/elif/else


code:
T = int(raw_input())

for t in xrange(T):
    s = raw_input()
    length = len(s)
    for i in xrange(length / 2):
        if s[i] != s[length - i - 1]:
            if s[i + 1:length - i] == s[length - i - 1:i:-1]:
                print i
            else:
                print length - i - 1
            break
    else:
        print -1

rawDescription: Finding the index at which upon removing element string becomes palindrome


code:
from collections import OrderedDict

mydict = OrderedDict()

for i in xrange(18, 0, -1):
    mydict['d{0}'.format(i)] = 'item {0}'.format(i)

regroupped_dict = [OrderedDict(mydict.items()[i: i + 2])
                   for i in xrange(0, len(mydict), 3)]

print regroupped_dict

# Result: [OrderedDict([('d18', 'item 18'), ('d17', 'item 17')]), OrderedDict([('d15', 'item 15'), ('d14', 'item 14')]), OrderedDict([('d12', 'item 12'), ('d11', 'item 11')]), OrderedDict([('d9', 'item 9'), ('d8', 'item 8')]), OrderedDict([('d6', 'item 6'), ('d5', 'item 5')]), OrderedDict([('d3', 'item 3'), ('d2', 'item 2')])]

rawDescription: How can I loop through subgroups of an OrderedDict in ZPT?

description: Loop through subgroups of an OrderedDict in ZPT


code:
import socks
import socket
def create_connection(address, timeout=None, source_address=None):
    sock = socks.socksocket()
    sock.connect(address)
    return sock

socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)

# patch the socket module
socket.socket = socks.socksocket
socket.create_connection = create_connection

import urllib2

print urllib2.urlopen('http://icanhazip.com').read()

import mechanize
from mechanize import Browser

br = Browser()
print br.open('http://icanhazip.com').read()

rawDescription: using polipo and tor with python mechanize browser reveals ip on one site and not another

description: Using polipo and tor with python mechanize browser reveals ip on one site and not another


code:
from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString

txt = \
'''
<bold>Name of instructor</bold>:
Dr. A. B. C

Professor, Dept. of Alphabet

Office hours: M, T 8:00am-10:00am

Course Name
:
Introduction to Alphabet

Course timings

Monday 4:00-6:00 pm
Tuesday 5:00-6:00 pm

'''

pool = BeautifulStoneSoup(txt, selfClosingTags=['br'])
found_txt = []
for x in pool.find("bold").nextSiblingGenerator():
    if isinstance(x, Tag) and not x.isSelfClosing:
        break
    elif isinstance(x, NavigableString):
        found_txt.append(x)
print found_txt

rawDescription: Get the text present after a HTML tag using BeautifulSoup


code:
import wx
import os

def bindXterm(win):
    winID = win.GetHandle()
    print "binding xterm to window %d(%x)"%(winID,winID)
    os.system("xterm -inot %d"%winID)

app = wx.PySimpleApp()
xtermFrame = wx.Frame(None)
xtermPanel = wx.Panel(xtermFrame)
xtermPanel.SetBackgroundColour((255,0,0))
app.SetTopWindow(xtermFrame)
xtermFrame.Show()
wx.CallLater(1000, bindXterm, xtermPanel)
app.MainLoop()

rawDescription: example of embeddeding xterm in wxPython panel

description: Example of embeddeding xterm in wxPython panel


code:
import pandas as pd

df = pd.read_excel("c:\\tmp\\book1.xlsx", "Sheet1")
mask = df["ID"] == "ID"
nmask = ~mask
s = mask.astype(int).cumsum()
dfs = [x.dropna() for _,x in df[nmask].groupby(s[nmask])]

for df in dfs:
    print df

rawDescription: From Excel to splitted Python structures


code:
messages = """
<alarm-dictionary source="DDD" type="ProxyComponent">

    <alarm code="402" severity="Alarm" name="DDM_Alarm_402">
    <message>Database memory usage low threshold crossed</message>
    <description>dnKinds = database
    type = quality_of_service
    perceived_severity = minor
    probable_cause = thresholdCrossed
    additional_text = Database memory usage low threshold crossed
    </description>
    </alarm>

        ...
</alarm-dictionary>
"""

import xml.etree.ElementTree as ET

# Parse XML
tree = ET.fromstring(messages)

for alarm in tree.getchildren():
    # Get code and severity
    print alarm.get("code")
    print alarm.get("severity")

    # Grab description text
    descr = alarm.find("description").text

    # Parse "thing=other" into dict like {'thing': 'other'}
    info = {}
    for dl in descr.splitlines():
        if len(dl.strip()) > 0:
            key, _, value = dl.partition("=")
            info[key.strip()] = value.strip()
    print info

rawDescription: parse a special xml in python

description: Parse a special xml in python


code:
for i, x in enumerate(SomeArray):
    print i, x

rawDescription: Accessing elements with offsets in Python's for .. in loops


code:
import win32gui

def enumHandlerrr(hwnd, lParam):
   global x
   if win32gui.IsWindowVisible(hwnd):
       if 'Python' in win32gui.GetWindowText(hwnd):
           x = 10

x = ()
win32gui.EnumWindows(enumHandlerrr, None)
print x

rawDescription: Why I get that x is not equal to 10?

description: Why I get that x is not equal to 10


code:
class Group(models.Model):
    name = models.CharField(max_length=64)

class User(models.Model):
    name = models.CharField(max_length=64)
    group = models.ForeignKey(Group)

g = Group.objects.get(id=1)
print g.user_set.all()  # prints list of all users in the group

rawDescription: ManyToOneField in Django

description: ManyToOneField in Django


code:
a = 5
for i in range(12):
    a = (a*2)-3

print a

rawDescription: Python from Coursera - For Loop with a little math


code:
import threading
import time

def doit1():
    for i in range(10):
        time.sleep(.1)
        print 'doit1(%d)' % i

def doit2():
    for i in range(10):
        time.sleep(.2)
        print 'doit2(%d)' % i

t = threading.Thread(target=doit2)
t.start()
doit1()
t.join()
print 'All done.'

rawDescription: Asynchronous api for obtaining GPS position in python for S60


code:
import re
sample = "javascript:ColdFusion.Window.show('theformats');ColdFusion.navigate('exportformats.cfm?id=1900067&expformat=bibtex','theformats');"
regex = r"javascript:ColdFusion\.Window\.show\('theformats'\);ColdFusion.navigate\('([^']+)','theformats'\);"
print re.match(regex, sample).group(1)

rawDescription: Python RegEx: Extract link

description: Python RegEx: Extract link


code:
# your code goes here
import re
line = "something with space . dot";
line = re.sub(r'[. \n]+', ",", line);
print line;

rawDescription: Regex for dot, space and newline

description: Regex for dot, space and newline


code:
from dateutil.relativedelta import relativedelta
rdelta = relativedelta(now, birthdate)
print 'Age in years - ', rdelta.years
print 'Age in months - ', rdelta.months
print 'Age in days - ', rdelta.days

rawDescription: How do I convert days into years and months in python?

description: Convert days into years and months in python


code:
#Get the html
import urllib2
response = urllib2.urlopen('http://en.wikipedia.org/wiki/List_of_programming_languages')
html = response.read()

#Parse it with beautifulsoup
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)

langs = []

#Parse all the links.
for link in soup.find_all('a'):
    #Last link after ZPL, the last language.
    if link.get_text() == u'Top':
        break
    if link.get_text() == u'edit':
        pass
    else:
        langs.append(link.get_text())

# find u'See also'
see_also_index_ = langs.index(u'See also')
# strip out headers
langs = langs[see_also_index_+1:]

print langs

rawDescription: List of all programming languages in Select Field


code:
import csv
from collections import defaultdict

def generateGraph(fileName):
    heroDict = defaultdict(list)

    with open(fileName, 'rb') as inFile:
        reader = csv.reader(inFile, delimiter='\t')
        for row in reader:
            name, comic = row[:2]
            heroDict[comic].append(name)

    graph = defaultdict(list)
    for names in heroDict.itervalues():
        for name in names:
            graph[name].extend(n for n in names if n != name)
    print graph
    return graph

rawDescription: Python: Use sets in conjunction with dictionaries


code:
class A(object):
  @classmethod
  def cfun(cls):
    print 'I am in %r' % (cls,)

class AA(A):
  pass

rawDescription: static method in Python

description: Static method in Python


code:
list = ['State start_ping_3\n{\n   \t// send ping\n\n\tAssign addr Ping_RemoteAddr3;\n\tAssign pingParams Ping_Parameters3;\n\n\tBuild Out GUE_startCommand;\n\tAssign Out.ref\t11;\n\t//Assign Out.command\t"/ercom/bundles/startPing.sh -I %pdn_add% %pingParams% %addr%";\n\tCase(PDNType = 2) // IPv6\n\t{\n\t\tAssign Out.command\t"$BUNDLE_BIN_PATH/ping6 -I %pdn_add% %pingParams% %addr%";\n\t}\n\tDefaultCase(PDNType)\n\t{\n\t\tAssign Out.command\t"$BUNDLE_BIN_PATH/ping -I %pdn_add% %pingParams% %addr%"; // -w 8: 8sec timeout then exit ping\n\t}\n\tSend Out To\tUE;\n\tAdd ping_traffic3 1;\n\t\n\tIf (_ActivateEvents>=1) {Log "Start Ping 3";}\n\tReturn;\n}']
print list[0]

rawDescription: Display a raw string from a "regex-like" string


code:
total = 0

for store_sale in store_week_sales:
    total += store_sale

print "Total week sales: %.2f" % total

rawDescription: Adding a for loop to the list

description: Adding a for loop to the list


code:
#!/usr/bin/env python

def get_settings(variable0, variable1):
    return {
        'general': {
            variable0+'s': [variable0+'1', variable0+'2'],
        },
        variable1+'al': [variable1+'1', variable1+'2'],
    }

print get_settings('car', 'loc')

rawDescription: Best pythonic way to template dictionary


code:
words = ["mama", "papa", "sister", "brother"]
pairs = list(itertools.permutations(words, 2))
print pairs

rawDescription: How to create a list of word pairs

description: Create a list of word pairs


code:
import numpy as np
import time
from numba import jit

def fun1(Fu, Fv, Fx, Fy, P, B):
    Nu = Fu.shape[0]
    Nv = Fv.shape[0]
    Nx = Fx.shape[0]
    Ny = Fy.shape[0]
    Nk = Fu.shape[1]
    Nl = Fv.shape[1]
    I1 = np.zeros([Nu, Nv])
    for iu in range(Nu):
        for iv in range(Nv):
            for ix in range(Nx):
                for iy in range(Ny):
                    S = 0.
                    for ik in range(Nk):
                        for il in range(Nl):
                            S += Fu[iu,ik]*Fv[iv,il]*Fx[ix,ik]*Fy[iy,il]*P[ix,iy]*B[ik,il]
                    I1[iu, iv] += S
    return I1

def fun2(Fu, Fv, Fx, Fy, P, B):
    Nu = Fu.shape[0]
    Nv = Fv.shape[0]
    Nx = Fx.shape[0]
    Ny = Fy.shape[0]
    Nk = Fu.shape[1]
    Nl = Fv.shape[1]
    I2 = np.zeros([Nu, Nv])
    for iu in range(Nu):
        for iv in range(Nv):
            for ix in range(Nx):
                for iy in range(Ny):
                    S = 0.
                    for ik in range(Nk):
                        for il in range(Nl):
                            S += Fu[iu,ik]*Fv[iv,il]*Fx[ix,ik]*Fy[iy,il]*P[ix,iy]*B[ik,il]
                    I2[iu, iv] += S**2.
    return I2

if __name__ == '__main__':

    Nx = 30
    Ny = 40
    Nk = 50
    Nl = 60
    Nu = 70
    Nv = 8
    Fx = np.random.rand(Nx, Nk)
    Fy = np.random.rand(Ny, Nl)
    Fu = np.random.rand(Nu, Nk)
    Fv = np.random.rand(Nv, Nl)
    P = np.random.rand(Nx, Ny)
    B = np.random.rand(Nk, Nl)
    fjit1 = jit(fun1)
    fjit2 = jit(fun2)

    # For loop - becomes too slow so commented out
    # t = time.time()
    # I1 = fun1(Fu, Fv, Fx, Fy, P, B)
    # print 'fun1    :', time.time() - t

    # JIT compiled for loop - After a certain point beats einsum
    t = time.time()
    I1jit = fjit1(Fu, Fv, Fx, Fy, P, B)
    print 'jit1    :', time.time() - t

    # einsum great solution when no squaring is needed
    t = time.time()
    I1_ = np.einsum('uk, vl, xk, yl, xy, kl->uv', Fu, Fv, Fx, Fy, P, B)
    print '1 einsum:', time.time() - t

    # For loop - becomes too slow so commented out
    # t = time.time()
    # I2 = fun2(Fu, Fv, Fx, Fy, P, B)
    # print 'fun2    :', time.time() - t

    # JIT compiled for loop - After a certain point beats einsum
    t = time.time()
    I2jit = fjit2(Fu, Fv, Fx, Fy, P, B)
    print 'jit2    :', time.time() - t

    # Expanded einsum - As the size increases becomes very very slow
    # t = time.time()
    # I2_ = np.einsum('uk,vl,xk,yl,um,vn,xm,yn,kl,mn,xy->uv', Fu,Fv,Fx,Fy,Fu,Fv,Fx,Fy,B,B,P**2)
    # print '2 einsum:', time.time() - t

    # Intermediate einsum - As the sizes increase memory can become an issue
    t = time.time()
    temp = np.einsum('uk, vl, xk, yl, xy, kl->uvxy', Fu, Fv, Fx, Fy, P, B)
    I2__ = np.einsum('uvxy->uv', np.square(temp))
    print '2 einsum:', time.time() - t

    # print 'I1 == I1_   :', np.allclose(I1, I1_)
    print 'I1_ == Ijit1_:', np.allclose(I1_, I1jit)
    # print 'I2 == I2_   :', np.allclose(I2, I2_)
    print 'I2_ == Ijit2_:', np.allclose(I2__, I2jit)

rawDescription: How to sum of squares of sum with memory limitations?

description: Sum of squares of sum with memory limitations


code:
p1 = subprocess.Popen(["/usr/bin/java", "MyClass"], stdout=subprocess.PIPE)
print p1.stdout.read()

rawDescription: Reading Java system.out.print via Python subprocess


code:
import sys
import win32com.client

olFolderTodo = 28

outlook = win32com.client.Dispatch("Outlook.Application")
ns = outlook.GetNamespace("MAPI")
todo_folder = ns.GetDefaultFolder(olFolderTodo)
todo_items = todo_folder.Items

def print_encoded(s):
    print s.encode(sys.stdout.encoding, 'replace')

for i in range(1, 1 + len(todo_items)):
    item = todo_items[i]
    if item.__class__.__name__ == '_MailItem':
        print_encoded(u'Email: {0}. Due: {1}'.format(item.Subject, item.TaskDueDate))
    elif item.__class__.__name__ == '_ContactItem':
        print_encoded(u'Contact: {0}. Due: {1}'.format(item.FullName, item.TaskDueDate))
    elif item.__class__.__name__ == '_TaskItem':
        print_encoded(u'Task: {0}. Due: {1}'.format(item.Subject, item.DueDate))
    else:
        print_encoded(u'Unknown Item type: {0}'.format(item))

rawDescription: Get Outlook To-Do-list using Python

description: Get Outlook To-Do-list using Python


code:
json_string = '[{"product": "car", "months": 12}, {"product": "bike", "months": "12"}]'

import json
data = json.loads(json_string)
print data[0], len(data)

rawDescription: Parsing string containing possibly two json objects


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

driver = webdriver.Chrome()
driver.get("http://www.sigmaaldrich.com/united-states.html")

print driver.title
inputElement = driver.find_element_by_name("Query")

# type in the search
inputElement.send_keys("1300746-79-5")
inputElement.submit()

pricing_link = driver.find_element_by_css_selector("li.priceValue a")
print pricing_link.text
pricing_link.click()

# then deal with the data you want
price_table = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".priceAvailContainer tbody"))
)
print 'price_table.text: ' + price_table.text

driver.quit()

rawDescription: python dynamic webscraping javascript content

description: Python dynamic webscraping javascript content


code:
import os
import zipfile

with zipfile.ZipFile('archive.zip') as z:
    for filename in z.namelist():
        if not os.path.isdir(filename):
            # read the file
            with z.open(filename) as f:
                for line in f:
                    print line

rawDescription: How to read text files in a zipped folder in Python

description: Read text files in a zipped folder in Python