code:
blat_src = """00000001 taaaagatgaagtttctatcatccaaaaaatgggctacagaaacc 00000045
<<<<<<<< |||||||||||||||||||||||||||  |||||||||||||||| <<<<<<<<
41629392 taaaagatgaagtttctatcatccaaagtatgggctacagaaacc 41629348"""

def find_mismatch(blat):
    #break the blat input into lines
    lines = blat.split("\n")

    #give some firendly names to the different lines
    seq_a = lines[0]
    seq_b = lines[2]

    #We're not interested in the '<' and '>' so we strip them out with a slice
    matchstr = lines[1][9:-9]

    #Get the integer values of the starts of each sequence segment
    pos_a = int(seq_a[:8])
    pos_b = int(seq_b[:8])

    results = []

    #find the index of first space character, mmpos = mismatch position
    mmpos = matchstr.find(" ")
    #if a space exists (-1 if none found)
    while mmpos != -1:
        #the position of the mismatch is the start position of the
        #sequence plus the index within the segment
        results.append((posa+mmpos, posb+mmpos))
        #search the rest of the string (from mmpos+1 onwards)
        mmpos = matchstr.find(" ", mmpos+1)
    return results

print find_mismatch(blat_src)

rawDescription: UCSC BLAT output python

description: UCSC BLAT output python


code:
for vendor, description, product in read_data(get_nic_data()):
    print vendor, description, product

rawDescription: Python iterate a subprocess that returns json?


code:
from guppy import hpy
h = hpy()
print h.heap()

rawDescription: Which Python memory profiler is recommended?


code:
centers = np.array([cx,cy,cz])
print centers.shape

rawDescription: Python, from matrix to array

description: Python, from matrix to array


code: print ["{0}: {1}".format(field.name, getattr(request.user, field.name)) for field in request.user._meta.fields]

rawDescription: In Django, how can I view all the properties of my user?


code:
def getline():
    try:
        x = raw_input ("Enter text (or eof): ")
    except EOFError:
        return ""
    return x + "\n"

text = ""
line = getline()
while line != "":
    text = text + line;
    line = getline()
print "\n===\n" + text

rawDescription: Python script dies when I paste multiline text into input prompt


code:
print "foo bar"
print 5

rawDescription: How to return multiple variables from python to bash

description: Return multiple variables from python to bash


code: print clusters['bob']

rawDescription: Python Relating k-means cluster to instance


code:
import tarfile
tar = tarfile.open('tarfile.tar')
for member in tar.getmembers():
    print member.name, member.mtime

rawDescription: Extracting tar file with original time stamp


code:
def numero():
    return int(raw_input("Enter a number: "))

x = numero()
y = 0
while x != 0:
    y += x
    x = numero()
else:
    print 'Total y:', y

rawDescription: Why isn't my while loop, looping?

description: Why isn't my while loop, looping


code:
import re
splitter = re.compile(r":|,,?")
for line in ("literature,general education,,note: see approved list",
             "social-cultural elective,general education,,note: see approved"):
    print splitter.split(line)

rawDescription: Splitting with different delimiters

description: Splitting with different delimiters


code:
#!/usr/bin/python

import sys

directory =  sys.argv[1]

# do something interesting to manipulate directory...

print directory + "tmp"

rawDescription: Change caller's current working directory in Python


rawDescription: How to compute integrals dependent upon two variables with SciPy?

description: Compute integrals dependent upon two variables with SciPy


code: print open('out.txt').read()

rawDescription: modifying a text file containing array with python

description: Modifying a text file containing array with python


code:
import fileinput

def removeLine():
    inputfile = fileinput.input(path, inplace=True, mode='rU')
    next(inputfile, None)  # skip a line *if present*
    for line in inputfile:
        print line,  # write out again, but without an extra newline
    inputfile.close()

rawDescription: Most efficient way to "nibble" the first line of text from a text document then resave it in python


code:
for index,line in zip(key, result):
    print line[:index]+line[index].upper()+line[index+1:]

rawDescription: Load text file into single string and table


code:
original_foo = Foo.foo
with patch.object(Foo, 'foo', autospec=True) as mock_foo:
    def side_effect(self, a):
        print "mock foo", a
        return original_foo(self, a*2)
    mock_foo.side_effect = side_effect

    f.foo(3)

rawDescription: How to call mocked method in Python mock

description: Call mocked method in Python mock


code:
def KSA(key):
    keylength = len(key)

    S = range(256)

    j = 0
    for i in range(256):
        j = (j + S[i] + key[i % keylength]) % 256
        S[i], S[j] = S[j], S[i]  # swap

    return S

def PRGA(S):
    i = 0
    j = 0
    while True:
        i = (i + 1) % 256
        j = (j + S[i]) % 256
        S[i], S[j] = S[j], S[i]  # swap

        K = S[(S[i] + S[j]) % 256]
        yield K

def RC4(key):
    S = KSA(key)
    return PRGA(S)

if __name__ == '__main__':

    # ciphertext should be 9D5AB375EC
    key = 'secret'
    plaintext = 'plain'

    def convert_key(s):
        return [ord(c) for c in s]
    key = convert_key(key)

    keystream = RC4(key)

    ciphertext = ''.join([("%02X" % (ord(c) ^ keystream.next())) for c in plaintext])
    print ciphertext

    keystream = RC4(key)

    def convert_ct(s):
        import binascii
        return [ord(ch) for ch in binascii.unhexlify(s)]

    ciphertext = convert_ct(ciphertext)

    plaintext = ''.join([chr(c ^ keystream.next()) for c in ciphertext])
    print plaintext

rawDescription: RC4 decryption in python hexadecimal inputs


code:
import requests
print "ID\tName"
r = requests.auth.HTTPBasicAuth('x', '00000000000000000000000000000000-us4')
interest_categories_raw = requests.get('http://us4.api.mailchimp.com/3.0/lists/0000000000/interest-categories/', auth=r)
interest_categories = json.loads(interest_categories_raw.content)

# List of all the interest IDs. Can be found from any user
# https://us4.api.mailchimp.com/3.0/lists/0000000000/members/000000000000000000000000
interest_ids = ["00000000000", "0000000000"]

for i_id in interest_ids:
    for category in interest_categories['categories']:
        url = 'http://us4.api.mailchimp.com/3.0/lists/0000000000/interest-categories/{0}/interests/{1}'.format(str(category['id']), str(i_id))
        raw_response = requests.get(url, auth=r)
        if raw_response.status_code != 404:
            interest = json.loads(raw_response.content)
            print interest['id'] + "\t" + interest['name']

rawDescription: Mailchimp API 3.0 How do I get more than 10 entries from Users or Interests


code:
the_list = [1,2,3,4,5,2]
print lstIndex(the_list, 2)
print lstIndex(the_list, 1)
print lstIndex(the_list, 3)
print lstIndex(the_list, 4)
print lstIndex(the_list, 5)
print lstIndex(the_list, 6)
print lstIndex(the_list, 0)

rawDescription: How to return that last index of a list Python

description: Return that last index of a list Python


rawDescription: How to remove white space characters from string in Python

description: Remove white space characters from string in Python


code:
import threading, signal, time

should_restart = False
cond = threading.Event()
exit = threading.Event()
threads = []

def start(num=3):
    for i in range(num):
        t = threading.Thread(target=foo, args=[cond])
        threads.append(t)
        t.daemon = True
        print 'hello, I am', t.name
        t.start()

def restart(signum, frame):
    global should_restart
    should_restart = False
    cond.set()
    for thread in threads:
        thread.join()
        print 'bye bye', thread.name
    cond.clear()
    start()

def foo(should_exit):
    while not should_exit.is_set():
        time.sleep(0.2)

signal.signal(signal.SIGHUP, restart)
signal.signal(signal.SIGINT, lambda n, f: exit.set())
start()

while not exit.is_set():
    time.sleep(0.2)

rawDescription: Python: close all daemon threads

description: Python: close all daemon threads


code:
from collections import defaultdict, namedtuple
import csv

class DataBase(object):
    def __init__(self, csv_filename, recordname):
        # read data from csv format file into a list of namedtuples
        with open(csv_filename, 'rb') as inputfile:
            csv_reader = csv.reader(inputfile, delimiter=',')
            self.fields = csv_reader.next()  # read header row
            self.Record = namedtuple(recordname, self.fields)
            self.records = [self.Record(*row) for row in csv_reader]
            self.valid_fieldnames = set(self.fields)
        # create an empty table of lookup tables for each field name that maps
        # each unique field value to a list of record-list indices of the ones
        # that contain it
        self.lookup_tables = defaultdict(lambda: defaultdict(list))

    def retrieve(self, **kwargs):
        """ Fetch a list of records with a field name with the value supplied
            as a keyword arg (or return None if there aren't any). """
        if len(kwargs) != 1: raise ValueError(
            'Exactly one fieldname/keyword argument required for function '
            '(%s specified)' % ', '.join([repr(k) for k in kwargs.keys()]))
        field, value = kwargs.items()[0]  # get only keyword arg and value
        if field not in self.valid_fieldnames:
            raise ValueError('keyword arg "%s" isn\'t a valid field name' % field)
        if field not in self.lookup_tables:  # must create field look up table
            for index, record in enumerate(self.records):
                value = getattr(record, field)
                self.lookup_tables[field][value].append(index)
        matches = [self.records[index]
                    for index in self.lookup_tables[field].get(value, [])]
        return matches if matches else None

if __name__ == '__main__':
    empdb = DataBase('employees.csv', 'Person')
    print "retrieve(name='Ted Kingston'):", empdb.retrieve(name='Ted Kingston')
    print "retrieve(age='27'):", empdb.retrieve(age='27')
    print "retrieve(weight='150'):", empdb.retrieve(weight='150')
    try:
        print "retrieve(hight='5ft 6in'):", empdb.retrieve(hight='5ft 6in')
    except ValueError as e:
        print "ValueError('{}') raised as expected".format(e)
    else:
        raise type('NoExceptionError', (Exception,), {})(
            'No exception raised from "retrieve(hight=\'5ft\')" call.')

rawDescription: What is the best data structure in Python for storing a set of four (or more) values?


code:
import urllib2
from bs4 import BeautifulSoup

url = urllib2.urlopen("http://link").read()
soup = BeautifulSoup(url)
file = open("parseddata.txt", "wb")
for line in soup.find_all('a', attrs={'class': 'book-title-link'}):
    href = line.get('href')
    print href
    if href:
        file.write(href + '\n')
file.close()

rawDescription: How do i get my Beautiful soup output data to a text file?

description: Get my Beautiful soup output data to a text file


code:
a = np.random.random(size=(100, 100))
above_thr = len(a[a > thr])
print above_thr

rawDescription: In Python: the center of mass of specific regions of values in a 2D numpy array


code: print keywords

rawDescription: compute tf-idf with corpus

description: Compute tf-idf with corpus


code:
import urllib2

from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://www.premierleague.com/en-gb/matchday/league-table.html'))

for row in soup.select("table.leagueTable tr.club-row"):
    cells = [cell.get_text(strip=True) for cell in row.find_all('td')]
    print cells

rawDescription: Python HTML table scrape (Print)

description: Python HTML table scrape (Print)


code:
import os
import sys
import cv2
import numpy as np

def read_images(path, sz=None):
    """Reads the images in a given folder, resizes images on the fly if size is given.

    Args:
        path: Path to a folder with subfolders representing the subjects (persons).
        sz: A tuple with the size Resizes

    Returns:
        A list [X,y]

            X: The images, which is a Python list of numpy arrays.
            y: The corresponding labels (the unique number of the subject, person) in a Python list.
    """
    c = 0
    X,y = [], []
    for dirname, dirnames, filenames in os.walk(path):
        for subdirname in dirnames:
            subject_path = os.path.join(dirname, subdirname)
            for filename in os.listdir(subject_path):
                try:
                    im = cv2.imread(os.path.join(subject_path, filename), cv2.IMREAD_GRAYSCALE)
                    # resize to given size (if given)
                    if (sz is not None):
                        im = cv2.resize(im, sz)
                    X.append(np.asarray(im, dtype=np.uint8))
                    y.append(c)
                except IOError, (errno, strerror):
                    print "I/O error({0}): {1}".format(errno, strerror)
                except:
                    print "Unexpected error:", sys.exc_info()[0]
                    raise
            c = c+1
    return [X,y]

rawDescription: Face recognition in OpenCV Python FAR/FRR


code:
def indent(thing, current_indentation=""):
    print current_indentation + str(thing)
    try:
        for item in thing:
            indent(item, " " * 4 + current_indentation)
    except TypeError:  # thing is not iterable
        pass

xl = [[[0,0], [-1,1], [-2,2]], [[-3,3], [-4, 4], [-5,5]]]
indent(xl)

rawDescription: Python: printing with knowledge of current level of indentation


code:
def next_one(i,n):
    while i < n:
        yield i
        i += 1

def main(variable):
    print next(variable)

variable = next_one(1,10)
main(variable)
main(variable)
main(variable)

[OUTPUT]
1
2
3

rawDescription: Return multiple variables in a loop using dict()


code:
#!/usr/bin/env python

def nifty_thing(*names):
    d = globals()
    for name in names:
        d[name] = None

nifty_thing("foo", "bar", "baz")

print foo, bar, bar

rawDescription: Is there a Python 'shortcut' to define a class variable equal to a string version of its own name?


code:
import re

p = re.compile('"totalPages":([0-9]*),')
print p.findall('"totalPages":15,"bloodhoundHtml"')

rawDescription: Regex to grab number in line

description: Regex to grab number in line


code:
import httplib2
from BeautifulSoup import BeautifulSoup, SoupStrainer

http = httplib2.Http()
status, response = http.request('http://www.mywebsite.com')

for link in BeautifulSoup(response, parseOnlyThese=SoupStrainer('a')):
    if link.has_key('href'):
        if '/website-builder' in link['href']:
          print link['href']

rawDescription: how do you get links with certain words using beautifulsoup

description: Get links with certain words using beautifulsoup


code: print '\n'.join(['line1', 'line2'])

rawDescription: how to join various bits of string and data together using python

description: Join various bits of string and data together using python


code:
codepoints = '\xd3\xd3'
print codepoints.decode("latin-1")

rawDescription: Convert from hex character to Unicode character in python


code:
soup = BeautifulSoup(data)
for p in soup.find('div', attrs={'class':'InternaTesto'}).find_all("p"):
    print p.text
    for sibling in p.next_siblings:
        if sibling.name == 'ul':
            print [li.text for li in sibling.find_all('li')]
        if sibling.name == 'p':
            break

rawDescription: Parse bullet list in correct order with beautifulsoup


code:
class Enemy(object):
  def __init__(self, difficulty, power, MaxHP, magic, MaxMP, speed, name):
    self.power = power + 2*difficulty
    self.HP = self.MaxHP = MaxHP + 5*difficulty
    self.magic = magic + 2* difficulty
    self.MP = self.MaxMP = MaxMP + 5*difficulty
    print 'Raaarghh!! I am the formidable {}.'.format(name)

class Goblin(Enemy):
  def __init__(self, difficulty=1, power=1, MaxHP=5, magic=1, MaxMP=5, speed=5, name="Goblin"):
    super(Goblin, self).__init__(difficulty, power, MaxHP, magic, MaxMP, speed, name)

if __name__ == '__main__':
  g = Goblin(name='user1038783 goblin')

rawDescription: Python: Inheritance and default values in __init__


code:
from Bio.Seq import Seq

seq = Seq("CCTCAGCGAGGACAGCAAGGGACTAGCCAGGAGGGAGAACAGAAACTCCAGAACATCTTGGAAATAGCTCCCAGAAAAGCAAGCAGCCAACCAGGCAGGTTCTGTCCCTTTCACTCACTGGCCCAAGGCGCCACATCTCCCTCCAGAAAAGACACCATGAGCACAGAAAGCATGATCCGCGACGTGGAACTGGCAGAAGAGGCACTCCCCCAAAAGATGGGGGGCTTCCAGAACTCCAGGCGGTGCCTATGTCTCAGCCTCTTCTCATTCCTGCTTGTGGCAGGGGCCACCACGCTCTTCTGTCTACTGAACTTCGGGGTGATCGGTCCCCAAAGGGATGAGAAGTTCCCAAATGGCCTCCCTCTCATCAGTTCTATGGCCCAGACCCTCACACTCAGATCATCTTCTCAAAATTCGAGTGACAAGCCTGTAGCCCACGTCGTAGCAAACCACCAAGTGGAGGAGCAGCTGGAGTGGCTGAGCCAGCGCGCCAACGCCCTCCTGGCCAACGGCATGGATCTCAAAGACAACCAACTAGTGGTGCCAGCCGATGGGTTGTACCTTGTCTACTCCCAGGTTCTCTTCAAGGGACAAGGCTGCCCCGACTACGTGCTCCTCACCCACACCGTCAGCCGATTTGCTATCTCATACCAGGAGAAAGTCAACCTCCTCTCTGCCGTCAAGAGCCCCTGCCCCAAGGACACCCCTGAGGGGGCTGAGCTCAAACCCTGGTATGAGCCCATATACCTGGGAGGAGTCTTCCAGCTGGAGAAGGGGGACCAACTCAGCGCTGAGGTCAATCTGCCCAAGTACTTAGACTTTGCGGAGTCCGGGCAGGTCTACTTTGGAGTCATTGCTCTGTGAAGGGAATGGGTGTTCATCCATTCTCTACCCAGCCCCCACTCTGACCCCTTTACTCTGACCCCTTTATTGTCTACTCCTCAGAGCCCCCAGTCTGTATCCTTCTAACTTAGAAAGGGGATTATGGCTCAGGGTCCAACTCTGTGCTCAGAGCTTTCAACAACTACTCAGAAACACAAGATGCTGGGACAGTGACCTGGACTGTGGGCCTCTCATGCACCACCATCAAGGACTCAAATGGGCTTTCCGAATTCACTGGAGCCTCGAATGTCCATTCCTGAGTTCTGCAAAGGGAGAGTGGTCAGGTTGCCTCTGTCTCAGAATGAGGCTGGATAAGATCTCAGGCCTTCCTACCTTCAGACCTTTCCAGATTCTTCCCTGAGGTGCAATGCACAGCCTTCCTCACAGAGCCAGCCCCCCTCTATTTATATTTGCACTTATTATTTATTATTTATTTATTATTTATTTATTTGCTTATGAATGTATTTATTTGGAAGGCCGGGGTGTCCTGGAGGACCCAGTGTGGGAAGCTGTCTTCAGACAGACATGTTTTCTGTGAAAACGGAGCTGAGCTGTCCCCACCTGGCCTCTCTACCTTGTTGCCTCCTCTTTTGCTTATGTTTAAAACAAAATATTTATCTAACCCAATTGTCTTAATAACGCTGATTTGGTGACCAGGCTGTCGCTACATCACTGAACCTCTGCTCCCCACGGGAGCCGTGACTGTAATCGCCCTACGGGTCATTGAGAGAAATAA")

table = 1
min_pro_len = 100

for strand, nuc in [(+1, seq), (-1, seq.reverse_complement())]:
    for frame in range(3):
        for pro in nuc[frame:].translate(table).split("*"):
            if len(pro) >= min_pro_len:
                print "%s...%s - length %i, strand %i, frame %i" % (pro[:30], pro[-3:], len(pro), strand, frame)

rawDescription: How to find a open reading frame in Python

description: Find a open reading frame in Python


code:
#!/usr/bin/python

from ctypes import *

class Message(Structure):

    MSG_MAX_SIZE=128
    CLT_MAX_SIZE=64

    _fields_ = [
        ("m_level", c_int),
        ("m_text",  type(create_string_buffer(MSG_MAX_SIZE))),
        ("m_client", type(create_string_buffer(CLT_MAX_SIZE)))
    ]

print Message.m_text
print Message.m_client

t = Message(100, 'abcdef' ,'flurp')

print t
print t.m_text

rawDescription: initializing ctypes string object

description: Initializing ctypes string object


code:
myList = [25,3,26,27,56]
myList[3], myList[4] = myList[4], myList[3]
print myList

rawDescription: How to swap one value with next value in Python?

description: Swap one value with next value in Python


code: print sorted(ListB)

rawDescription: How to sort integer list in python descending order

description: Sort integer list in python descending order


code:
table = soup.find('table', id='ctl00_MainContent_GridView1')
for row in table.find_all('tr'):
    cells = row.find_all('td')
    if not cells or len(cells) < 4:
        continue
    if cells[3].string.startswith('http://'):
        print cells[3].string

rawDescription: Searching for strings with BeautifulSoup


code:
x = '\xff\x00'
y = ['%02x' % ord(c) for c in x]
print y

rawDescription: How to treat a returned/stored string like a raw string in Python?

description: Treat a returned/stored string like a raw string in Python


rawDescription: mpi4py append value id to list for each communicator instance

description: Mpi4py append value id to list for each communicator instance


code:
from scipy import linalg
w1 = linalg.lstsq(X, y)[0]
print w1

rawDescription: Understanding scipy's least square function with IRLS


code:
x = 2
epsilon = 0.01
step = 0.1
guess = 0.0
while abs(guess**2-x) >= epsilon:
    print format(guess, '.20'), guess <= x
    if guess <= x:
        guess += step
    else:
        break

if abs(guess**2 - x) >= epsilon:
    print "outside"
    print guess
else:
    print 'succeeded: ' + str(guess)

rawDescription: A confusion in Python's If else logic

description: A confusion in Python's If else logic


code:
import re
from bs4 import BeautifulSoup

data = """

    link1
    link2
    link3
    link4
    link5

"""

soup = BeautifulSoup(data)
links = soup.find_all('a', href=re.compile(r'/d2l/lp/ouHome/home\.d2l\?ou=\d+'))
for link in links:
    print link.text

rawDescription: BeautifulSoup find links that meet criteria


code:
value = "addr = &myvariable;"
findVar = "myvariable"
m = re.findall("[&]{0};".format(findVar), value)
print m
# prints: ['&myvariable;']

rawDescription: Regex for finding variable references in a C file using Python


code:
def foo(a,t=([0]*len(a))):
  print t

a = [1, 2]
def foo(a,t=([0]*len(a))):
  print t

rawDescription: List building in Python function definition


code:
print Derived.flag()
print Base.flag()

rawDescription: Python - Redefining class attribute in a derived class


code:
def expressions(s):
    stack = []
    for n, c in enumerate(s):
        if c == '(':
            stack.append(n+1)
        elif c == ')':
            yield s[stack.pop():n]

for x in expressions(s):
    print x

rawDescription: Regular Expression to match string inside parentheses


code:
class Card:
    def __init__(self,cardval,suitval):
       self.cardval = cardval
       self.suitval = suitval
    def __str__(self):
       return "%s of %s"%(rankName[self.cardval],suitName[self.suitval])
    def __repr__(self):
       return "Card <%s>"%self

print Card(0,2) #prints "ace of Spades"
deck = [Card(cardval,suitval) for suitval in range(4) for cardval in range(13)]
print deck

rawDescription: Card game framework Python 2.6 help/guidance


code:
from socket import *
message = '\xab\xcd\x00\x12\xf6\xbe'
clientSocket = socket(AF_INET, SOCK_DGRAM)
clientSocket.sendto(message, ('127.0.0.1', 12000))
data, server = clientSocket.recvfrom(1024)
print 'client received:', repr(data)

rawDescription: Send Null Byte?

description: Send Null Byte


code:
from datetime import date, timedelta

coll = [['Bill', date(2011,1,1)],
        ['Bill', date(2011,1,2)],
        ['Bill', date(2011,1,3)],
        ['Bill', date(2011,1,5)],
        ['Bill', date(2011,1,7)]]

res = []
group = [coll[0]]
i = 1

while i < len(coll):
    row = coll[i]
    last_in_group = group[-1]

    # use your isBeside() function here...
    if row[1] - last_in_group[1] == timedelta(days=1):
        # consecutive, append to current group..
        group.append(row)
    else:
        # not consecutive, start new group.
        res.append(group)
        group = [row]
    i += 1

res.append(group)

for group in res:
    for row in group:
        for item in row:
            print item,
        print len(group)

rawDescription: Date comparion/consecutive date grouping


code:
from xml.etree import ElementTree
xmldata = '''<?xml version="1.0" encoding="utf-8"?>
<upload>
    <image>
        <name/>
        <title/>
        <caption/>
        <hash>dxPGi</hash>
        <deletehash>kj2XOt4DC13juUW</deletehash>
        <datetime>2011-06-10 02:59:26</datetime>
        <type>image/png</type>
        <animated>false</animated>
        <width>1024</width>
        <height>768</height>
        <size>172863</size>
        <views>0</views>
        <bandwidth>0</bandwidth>
</image>
<links>
    <original>http://i.stack.imgur.com/dxPGi.png</original>
    <imgur_page>http://imgur.com/dxPGi</imgur_page>
    <delete_page>http://imgur.com/delete/kj2XOt4DC13juUW</delete_page>
    <small_square>http://i.stack.imgur.com/dxPGis.jpg</small_square>
    <large_thumbnail>http://i.stack.imgur.com/dxPGil.jpg</large_thumbnail>
</links>
</upload>'''
tree = ElementTree.fromstring(xmldata)
print tree.find('.//original').text

rawDescription: Get specifics elements of a xml output in python


code:
p = subprocess.Popen('ps ax | grep [b]ash | wc -l', stdout=subprocess.PIPE, shell=True)

count = int(p.stdout.read())

if count == 2: # Or maybe 3?
   print count
   print "yes"
else:
   print "fail"

rawDescription: How can I combine three subprocess.popen into one line?

description: Combine three subprocess.popen into one line


code:
for k in d:
    print k

rawDescription: Python: Finding the keys in an unfamiliar json object


code:
b = set([])
[b.add(x) for c in list for x in c if x not in b]
print b

rawDescription: intersection of multiple sets in a list

description: Intersection of multiple sets in a list


code:
from collections import defaultdict

grid = defaultdict(list)
p = Point((10, 13))
grid[(10, 13)] = [2, 3, 4]
print grid[p]                  # prints [2, 3, 4]
print grid[p.r_neighbor]       # no KeyError; prints []

rawDescription: python: representing square grid that wraps on itself (cylinder)

description: Python: representing square grid that wraps on itself (cylinder)


code:
import re
import lxml.html
import lxml.html.clean

url_regexp = re.compile(r"""(?i)\b(?P<body>(?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|(?P<host>[a-z0-9.\-]+[.][a-z]{2,4}/))(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""")

DOC = """<html><body>
    http://foo.com/blah_blah
    http://foo.com/blah_blah/.
    http://www.extinguishedscholar.com/wpglob/?p=364.
    http://✪df.ws/1234
    rdar://1234
    rdar:/1234
    message://%3c330e7f840905021726r6a4ba78dkf1fd71420c1bf6ff@mail.gmail.com%3e
    What about <mailto:gruber@daringfireball.net?subject=TEST> (including brokets).
    bit.ly/foo
</body></html>"""

tree = lxml.html.fromstring(DOC)
body = tree.find('body')
lxml.html.clean.autolink(body, [url_regexp], avoid_hosts=[])
print lxml.html.tostring(tree)

rawDescription: How to modify lxml autolink to be more liberal?

description: Modify lxml autolink to be more liberal


code:
muts={'YES': ['rice','bread','pasta'],
       'NO': ['sweets', 'fat', 'milk', 'choco']}
muts
sql = "UPDATE test2 g SET accept='%s' WHERE g.food IN (%s)"
for k in muts:
    to_add = ', '.join(muts[k])
    ex_sql = sql % (k, to_add)
    print ex_sql
    # cursor.execute(ex_sql) here

rawDescription: Python MySQLdb update table from dictionary of lists


code:
def fun(arg):
    import pdb; pdb.set_trace()
    print arg

rawDescription: save variable to interactive namespace from python debugger

description: Save variable to interactive namespace from python debugger


code:
while True:

    # this reads from your GPIO to set a variable
    Current_State = GPIO.input(GPIO_PIR)

    # if it detected motion or if there wasn't motion last time we checked..
    if Current_State==1 and Previous_State==0:
        print " Mouvement detecte !"

        # wait five seconds so we're not checking as fast as the cpu
        # will allow!
        time.sleep(5)
        Previous_State=1

    # this block has the same logic as above, but in reverse!
    elif Current_State==0 and Previous_State==1:
        # if we don't detect motion on gpio, print ready
        # this is where we need to keep track of how many times we didn't
        # detect motion.
        print " Pret "
        Previous_State=0

        time.sleep(1)

rawDescription: a trivial Presence detector with raspberry using python

description: A trivial Presence detector with raspberry using python


code:
def _compile(*key):
    # internal: compile pattern
    cachekey = (type(key[0]),) + key
    p = _cache.get(cachekey)            #_cache is a dict.
    if p is not None:
        return p
    pattern, flags = key
    if isinstance(pattern, _pattern_type):
        if flags:
            raise ValueError('Cannot process flags argument with a compiled pattern')
        return pattern
    if not sre_compile.isstring(pattern):
        raise TypeError, "first argument must be string or compiled pattern"
    try:
        p = sre_compile.compile(pattern, flags)
    except error, v:
        raise error, v # invalid expression
    if len(_cache) >= _MAXCACHE:
        _cache.clear()
    _cache[cachekey] = p
    return p

rawDescription: How does Python's regex pattern caching work?


code:
x = 123
y = "x"
z = eval(y)

print z

rawDescription: How to pass string as variable name assignment

description: Pass string as variable name assignment


code:
class Worker(QtCore.QObject):
    def __init__(self):
        QtCore.QObject.__init__(self)

    def process(self):
        # dummy worker process
        self.flag = False
        for n in range(0, 10):
            if self.flag:
                print 'stop'
                break
            print 'process {}'.format(n)
            time.sleep(0.5)
        self.finished.emit()

    finished = QtCore.pyqtSignal()

class Dialog(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self.init_ui()

    def init_ui(self):
        self.layout = QtGui.QVBoxLayout(self)
        self.btn_run = QtGui.QPushButton('Run', self)
        self.layout.addWidget(self.btn_run)
        self.btn_cancel = QtGui.QPushButton('Cancel', self)
        self.layout.addWidget(self.btn_cancel)

        QtCore.QObject.connect(self.btn_run, QtCore.SIGNAL('clicked()'), self.run)
        QtCore.QObject.connect(self.btn_cancel, QtCore.SIGNAL('clicked()'), self.reject)

        QtCore.QObject.connect(self, QtCore.SIGNAL('rejected()'), self.stop_worker)

        self.show()
        self.raise_()

    def stop_worker(self):
        print 'stop'
        self.worker.flag = True

    def run(self):
        # start the worker thread
        self.thread = QtCore.QThread(self)
        self.worker = Worker()
        self.worker.moveToThread(self.thread)
        QtCore.QObject.connect(self.thread, QtCore.SIGNAL('started()'), self.worker.process)
        QtCore.QObject.connect(self.worker, QtCore.SIGNAL('finished()'), self.thread.quit)
        QtCore.QObject.connect(self.worker, QtCore.SIGNAL('finished()'), self.worker.deleteLater)
        QtCore.QObject.connect(self.thread, QtCore.SIGNAL('finished()'), self.thread.deleteLater)
        self.thread.start()

rawDescription: Terminating QThread gracefully on QDialog reject()


code:
import os
import sys
import unittest

STDOUT_FD = os.dup(sys.stdout.fileno())
STDERR_FD = os.dup(sys.stderr.fileno())

with open('stdout.txt', 'w') as f, open('stderr.txt', 'w') as g:
    os.dup2(f.fileno(), sys.stdout.fileno())
    os.dup2(g.fileno(), sys.stderr.fileno())

class MyTest(unittest.TestCase):
    def test_print(self):
        print 'some output'
        self.assertEqual('', '')

    def test_some_moar(self):
        print 'some other cool output'
        self.assertTrue(True)

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

print 'I am printing to stdout.txt'
print >> sys.stderr, 'I am printing to stderr.txt'

# revert the File Descriptors
os.dup2(STDOUT_FD, sys.stdout.fileno())
os.dup2(STDERR_FD, sys.stderr.fileno())

print "Yay! Back to printing in the console"

rawDescription: Python unittest print logging works on Linux but not on Windows


code:
for result in results:
    print "Rank: %s Id: %s Author: %s" % (result.rank, result['id'], result['author'])
    print "Content:"
    print result['content']

rawDescription: Whoosh index viewer

description: Whoosh index viewer


code:
from copy import *

a=range(1000)

def cop():
    b=copy(a)

def func1():
    b=list(a)

def slice():
    b=a[:]

def slice_len():
    b=a[0:len(a)]

if __name__=="__main__":
    import timeit
    print "copy(a)",timeit.timeit("cop()", setup="from __main__ import cop")
    print "list(a)",timeit.timeit("func1()", setup="from __main__ import func1")
    print "a[:]",timeit.timeit("slice()", setup="from __main__ import slice")
    print "a[0:len(a)]",timeit.timeit("slice_len()", setup="from __main__ import slice_len")

rawDescription: Efficient ways to duplicate array/list in Python


code:
from pymongo import Connection
from bson.code import Code

db = Connection().mr_test
for i in xrange(10):
    db.things.insert({"x" : i})

map = Code("function(number) {"
    "emit({"
        "ts : number"
    "}, 1);"
"}")

reduce = Code("function(key, vals) {"
    "var sum = 0;"
    "for (var i in vals) {"
        "sum += vals[i]"
    "}"
    "return sum;"
"}")

result = db.things.map_reduce(map, reduce, "test_results")
for doc in result.find():
    print doc

rawDescription: MongoDB MapReduce, Date and % operator

description: MongoDB MapReduce, Date and % operator


code:
def func(a,b,c):
    for a in range(3,500):
        for b in range(a+1,500):
            c = (a**2 + b**2)**0.5
            if a + b + c == 1000:
                print a, b, c
                print a*b*c
                return # causes your function to exit, and return a value to caller

func(3,4,5)

rawDescription: Exit while loop in Python

description: Exit while loop in Python


code:
class Child(BaseClass):
    def Method1(self):
        print 'BAR'
        super(Child, self).Method1()  # will call BaseClass.Method1

rawDescription: Overridden vs. virtual class methods in Python


code:
#!/usr/bin/env python
def make_function(x):
    my_var = [x]
    def my_function(a):
            print a + my_var[0]
            my_var[0] += 1
    return my_function

fct = make_function(15)
for i in xrange(10):
    fct(10)

rawDescription: Recalling/remembering variables after they have been returned within a function in Python


code:
def find_adjacent(message, pairs, k):
  if k == len(message) - 1: #subtract one to avoid getting a string index out of range error
    return("Number of pairs:", pairs)
  else:
    return find_adjacent(message, pairs+1 if message[k]==message[k+1] else pairs, k+1)

if __name__ == "__main__":
  message = "message" # change to input("Enter a message:\n")
  pairs = 0
  k = 0
  m, p = find_adjacent(message, pairs, k)
  print m, p

rawDescription: Finding adjacent pairs of characters in a string using recursion


code:
db = conn.cursor()
db.execute('SELECT 1; SELECT 2;')

more = True
while more:
    print db.fetchall()
    more = db.nextset()

rawDescription: Execute .sql file in Python with MySQLdb


code:
from subprocess import Popen, PIPE
# Set up the process
p = Popen("yourprogram", stdout=PIPE, close_fds=True)
count = 0
while True:
    count += 1
    print '%s: %s' % (count, p.stdout.readline().strip())

rawDescription: python read from shell command output

description: Python read from shell command output


code:
class MutInt(object):
    def __init__(self, v):
        self.v = v

    def __str__(self):
        return str(self.v)

    def inc(self):
        self.v += 1

a = MutInt(7)
print a
a.inc()
print a

rawDescription: Python procedure for changing an object

description: Python procedure for changing an object


code:
import re
with open('source.txt') as x:
    for line in x:
        if line.startswith('<chapter'):
                id = re.findall('"([^"]*)"', line) #Grabs string between matching quotations
        if line.startswith('<text'):
                line = line.replace('lol',id[0])
        print line[:-1]

rawDescription: python negative look behind

description: Python negative look behind


code:
with capturinglines() as output:
    print "foo"
    print "bar"

print output
['foo', 'bar']

with capturinglines(output):   # append to existing list
    print "baz"

print output
['foo', 'bar', 'baz']

rawDescription: How to make a class that acts like a string?

description: Make a class that acts like a string


rawDescription: list of ints into a list of tuples python

description: List of ints into a list of tuples python


code:
if not s.strip():
    print "It was all whitespace!"

rawDescription: check if a string has only white characters in python

description: Check if a string has only white characters in python


rawDescription: Meaning of the following syntax if T <> (None, None) in Python 2


code:
import urllib2
import cookielib

cookieJar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))

setmetar = 'http://www.wunderground.com/cgi-bin/findweather/getForecast?setpref=SHOWMETAR&value=1'
request = urllib2.Request(setmetar)
response = opener.open(request)

url = "http://www.wunderground.com/history/airport/KBUF/2011/1/1/DailyHistory.html?theprefset=SHOWMETAR&theprefvalue=1&format=1"
request = urllib2.Request(url)
page = opener.open(request)
# print(page.info())
dailyData = page.read()
print dailyData

rawDescription: Parsing HTML data from Wunderground

description: Parsing HTML data from Wunderground


code:
name = 'Якета'
asterisks = '****************************'
price = 1250.23
padding = 17
print '{0}: {1} {2} €'.format(name.ljust(padding), asterisks, price)

rawDescription: String alignment when printing in python


code:
s = "i'm Brian, and so's my wife!"
print s[0].upper() + s[1:]

rawDescription: What is the Python equivalent of Perl's ucfirst() or s///e?


code:
import urllib2
from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('https://www.zomato.com/srijata'))
for div in soup.find_all('div', class_='rev-text'):
    print div.div.next_sibling

rawDescription: Printing all occurence of certain document elements of a webpage


code:
RE = r'''
    (?:(\d) \s day.*?)?        # this should match "n day" if it's there
    \s(\d{1,2}):(\d{1,2}) # this should match a space followed by "hh:mm"
'''
print re.search(RE, s1, re.VERBOSE).groups()
print re.search(RE, s2, re.VERBOSE).groups()

rawDescription: Regular Expressions in Python - strange behaviour


code:
letters = {}

for letter in string_lower_as_list(argv[1]):
    if "a" <= letter <= "z":
        letters[letter] = letters.get(letter, 0) + 1

for letter in sorted(letters):
    print letter, letters[letter]

rawDescription: Rm duplication in list comprehension

description: Rm duplication in list comprehension


code:
@app.route("/client")
def initial_template():
    return render_template('client.html')

@app.route("/client/<state>")
def get_change(state):
    print state

rawDescription: flask receiving url changes from pushstate

description: Flask receiving url changes from pushstate


code:
import zmq, time
from datetime import datetime

context = zmq.Context()

#create this node as publisher
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:25647")

for i in range(300):
   message = ("%d, %d" % (1, i))
   print str(datetime.now().time()) + "> sending: " + message
   socket.send(message)
   time.sleep(1)

rawDescription: Python: sharing message between processes


code:
def _compare_keys(x, y):
    try:
        x = int(x)
    except ValueError:
        xint = False
    else:
        xint = True
    try:
        y = int(y)
    except ValueError:
        if xint:
            return -1
        return cmp(x.lower(), y.lower())
        # or cmp(x, y) if you want case sensitivity.
    else:
        if xint:
            return cmp(x, y)
        return 1

for k in sorted(a, cmp=_compare_keys):
    print k, a[k] # or whatever.

rawDescription: Sorting a dictionary having keys as string of numbers in python


code:
import functools
import unittest

FUNCTIONS_TO_LOG = ('setUp', 'tearDown')

def log_start_and_end(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
        print '********** start {}'.format(f.__name__)
        f(*args, **kwargs)
        print '********** end {}'.format(f.__name__)
    return wrapper

class LoggingMeta(type):
    def __new__(cls, name, bases, namespace):
        for attr, obj in namespace.items():
            if attr in FUNCTIONS_TO_LOG:
                namespace[attr] = log_start_and_end(obj)
        return super(LoggingMeta, cls).__new__(cls, name, bases, namespace)

class BaseTest(unittest.TestCase):
    __metaclass__ = LoggingMeta

    def setUp(self):
        print 'inside setup'

    def tearDown(self):
        print 'inside teardown'

    def test_test(self):
        print 'inside test'

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

rawDescription: Add log separators to all fixtures in unittests


code:
a = "text"
b = "text"
print a is b # <-- this will print True

rawDescription: Are strings pooled in Python

description: Are strings pooled in Python


code:
from bs4 import BeautifulSoup
html = '''

            Female

	'''
soup = BeautifulSoup(html)
print ' '.join(soup.find('div', {'class': 'clearfix'}).stripped_strings)
print ' '.join(soup.find('td', {'class': '_480u'}).stripped_strings)

rawDescription: How to extract values with BeautifulSoup with no class

description: Extract values with BeautifulSoup with no class


code:
def get_selected_block_entries(lines, block_name,
                               block_prefix='#####', selected_entry_prefix='* [x]'):
    selected_lines = []

    block_marker = '{} {}'.format(block_prefix, block_name)
    for line in lines:
        if line.startswith(block_prefix):
            in_block = line.startswith(block_marker)
            if in_block:
                selected_lines.append(line)
        else:
            if in_block and line.startswith(selected_entry_prefix):
                selected_lines.append(line)

    return selected_lines

with open('file1.txt') as infile, open('file2.txt', 'w') as outfile:
    selected = get_selected_block_entries(infile, 'Bar:')
    print selected    # a list of selected entries within a Bar: block
    outfile.writelines(selected)

rawDescription: Read and Write the specific content

description: Read and Write the specific content


rawDescription: Sorting csv column by date

description: Sorting csv column by date


rawDescription: Adding the product of an element of a list to an existing list in Python


code:
from HTMLParser import HTMLParser

class AllLanguages(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.inLink = False
        self.dataArray = []
        self.countLanguages = 0
        self.lasttag = None
        self.lastname = None
        self.lastvalue = None

    def handle_starttag(self, tag, attrs):
        self.inLink = False
        if tag == 'a':
            for name, value in attrs:
                if name == 'class' and value == 'Vocabulary':
                    self.countLanguages += 1
                    self.inLink = True
                    self.lasttag = tag

    def handle_endtag(self, tag):
        if tag == "a":
            self.inlink = False

    def handle_data(self, data):
        if self.lasttag == 'a' and self.inLink and data.strip():
            print data

parser = AllLanguages()
parser.feed("""

<title>Test</title>

Swahili
Thilo Schadeberg
English
Russian

""")

rawDescription: Python: Extracting specific data with html parser


code:
a=['a','b','c','d','e']
d=[]
for i,v in enumerate(a[:-1]):
    if a[i+1]=='b':
        d.append('replacement')
    else:
        d.append(v)
d.append(a[-1])
print d

rawDescription: Increment the next element based on previous element


code: print " ".join(colored(element,"cyan") if element != "[S]" else (colored(element,"green") if element != "[X]" else (colored(element,"red") if element != "[H]" else colored(element,"magenta"))) for element in row)

rawDescription: Printing certain strings different colour with termcolor.colored?


code:
std_delete = raw_input("Student To Delete")
for std in students:
    if std.studentID == std_delete:
        print "Student ID %d has been deleted " % std.studentID
        students.remove(std)
        break

rawDescription: OOP - creating class adding to list then deleting


rawDescription: Displaying unicode characters in Python 3


rawDescription: Interpret "plain text" as utf-8 text in python


code:
class RunMonitor(threading.Thread):
    def __init__(self, quit_event):
        threading.Thread.__init__(self)
        self.quit_event = quit_event
    def run(self):
        print 'Invoking the command prompt .....'
        subprocess.call(["start", "/DC:\\Scripts", "scripts_to_execute.bat"], shell=True)
        self.quit_event.set()

def runscript(self):
    print 'Complete_file_Path inside Run script is : ' , self.complete_file_path
    file_operation.Generate_Bat_File(self.complete_file_path)

    quit_event = threading.Event()
    run_monitor_object = RunMonitor(quit_event).start()

    while True:
        if not quit_event.is_set():
             print 'The thread is still alive....'
        else:
             print 'The Thread is not alive anymore'
             self.run_button.setEnabled(True)
             break

rawDescription: Need Assistance in Python Thread programming


code:
my_dict = {1L: (1L, "bar", "foo/bar"),
           2L: (2L, "app", "some/app")}

rawDescription: Retrieving an item from a 2D list

description: Retrieving an item from a 2D list


code:
import numpy as np
import cv2

framebuffer = cv2.imread('pic.jpg',cv2.IMREAD_COLOR)

def IMP(p):
  print "I am here!"
  print "image.shape h,w,d=",p.shape
  cv2.imshow("picture",p)
  cv2.waitKey(0)
  cv2.destroyAllWindows()

rawDescription: how to pass a frame buffer from C to Python using OpenCV

description: Pass a frame buffer from C to Python using OpenCV


code:
def f(name):
    print 'hello', name

rawDescription: Why import specific sub-packages in Python when the entire package has already been imported?


code:
import cPickle
with open( 'big_pickled_list.pkl' ) as p:
    try:
        while True:
            print cPickle.load(p)
    except EOFError:
        pass

rawDescription: Can I stream a Python pickle list, tuple, or other iterable data type?

description: Stream a Python pickle list, tuple, or other iterable data type


code:
reciever.py
delim = "\x00"
recvd = "".join(iter(lambda:ser.read(1),delim))
print recvd

rawDescription: pySerial : Can't read data more than 8 characters

description: PySerial : Can't read data more than 8 characters


code:
#!/usr/bin/env python

from scapy.all import *

def PacketHandler(pkt):
    if pkt.haslayer(Dot11) and pkt.type == 0 and pkt.subtype == 0xC:
        print "Deauth packet sniffed: %s" % (pkt.summary())

sniff(iface="mon0", prn = PacketHandler)

rawDescription: How to sniff specific packets using python module Scapy?

description: Sniff specific packets using python module Scapy


code:
from bs4 import BeautifulSoup
import csv
import urllib2
import os # added this import to process files/dirs

# ** define our data processing function
def processData( pageFile ):
    ''' take the data from an html file and append to our csv file '''
    f = open(pageFile, "r")
    page = f.read()
    f.close()
    soup = BeautifulSoup(page)

    # if you look at the HTML all the titles, dates,
    # and authors are stored inside of <dt ...> tags
    metaData = soup.find_all("dt")

    # likewise the post data is stored
    # under <dd ...>
    postData = soup.find_all("dd")

    # define where we will store info
    titles = []
    authors = []
    times = []
    posts = []

    # now we iterate through the metaData and parse it
    # into titles, authors, and dates
    for html in metaData:
        text = BeautifulSoup(str(html).strip()).get_text().encode("utf-8").replace("\n", "") # convert the html to text
        titles.append(text.split("Title:")[1].split("Post by:")[0].strip()) # get Title:
        authors.append(text.split("Post by:")[1].split(" on ")[0].strip()) # get Post by:
        times.append(text.split(" on ")[1].strip()) # get date

    # now we go through the actual post data and extract it
    for post in postData:
        posts.append(BeautifulSoup(str(post)).get_text().encode("utf-8").strip())

    # now we write data to csv file
    # ***csv files MUST be opened with the 'b' flag***
    csvfile = open('silkroad.csv', 'ab')
    writer = csv.writer(csvfile)

    # iterate through and write all the data
    for time, author, title, post in zip(times, authors, titles, posts):
        writer.writerow([time, author, title, post])

    # close file
    csvfile.close()
# ** start our process of going through files

# the directory where we have all our HTML files
dir = "myDir"

# our csv file
csvFile = "silkroad.csv"

# insert the column titles to csv
csvfile = open(csvFile, 'wb')
writer = csv.writer(csvfile)
writer.writerow(["Time", "Author", "Title", "Post"])
csvfile.close()

# get a list of files in the directory
fileList = os.listdir(dir)

# define variables we need for status text
totalLen = len(fileList)
count = 1

# iterate through files and read all of them into the csv file
for htmlFile in fileList:
    path = os.path.join(dir, htmlFile) # get the file path
    processData(path) # process the data in the file
    print "Processed '" + path + "'(" + str(count) + "/" + str(totalLen) + ")..." # display status
    count = count + 1 # incriment counter

rawDescription: BeautifulSoup - scraping a forum page

description: BeautifulSoup - scraping a forum page


code:
topic_text_sets= {topic:set(text) for topic,(text,_) in data}
topic_related= {}
for topic1, text1 in topic_text_sets.iteritems():
    related= [topic2 for topic2, text2 in topic_text_sets.iteritems() if topic1!=topic2 and len(text1.intersection(text2))>0]
    print related

rawDescription: Advanced grouping in Python

description: Advanced grouping in Python


code:
from pydub import AudioSegment
from pydub.utils import make_chunks

myaudio = AudioSegment.from_file("myAudio.wav" , "wav")
chunk_length_ms = 1000 # pydub calculates in millisec
chunks = make_chunks(myaudio, chunk_length_ms) #Make chunks of one sec

#Export all of the individual chunks as wav files

for i, chunk in enumerate(chunks):
    chunk_name = "chunk{0}.wav".format(i)
    print "exporting", chunk_name
    chunk.export(chunk_name, format="wav")

rawDescription: How to splice an audio file (wav format) into 1 sec splices in pyhton?

description: Splice an audio file (wav format) into 1 sec splices in pyhton


code:
from itertools import permutations
s = 'pet'
print [''.join(p) for i in range(1, len(s)+1) for p in permutations(s, i)]

rawDescription: How to get every single permutation of a string?

description: Get every single permutation of a string


code:
def merge(**extra_kws):
    def _decorator(function):
        def _wrapper(*args, **kws):
            kws.update(_wrapper.extra_kws)
            return function(*args, **kws)
        _wrapper.extra_kws = extra_kws
        return _wrapper
    return _decorator

@merge(foo='bar')
def test(*args, **kws):
    print 'kws:', kws

test(sun='dock')
test.extra_kws['trog'] = 'cube'
test(sun='dock')

rawDescription: Merge decorator function as class

description: Merge decorator function as class


code:
abcedario='abcdefghijklmnopqrstvuxwyz'
v = {}
count = 0
for c in abcedario:
    count = 0
    for char in text:
        if c == char:
            count = count +1
            v[c] = count
print sorted(v.items(), key=lambda x:x[1])

rawDescription: Sort value in dictionary by value in Python


code:
def question(question, answerq, answere):
    user_answer = raw_input(question)
    if user_answer in [str(answerq), str(answere)]:
        print "Correct!"
        return True
    else:
        print "False!"
        return False

x = 0
if question(question1, answer1, answer1_5):
    x += 1
if question(question2, answer2, answer2):
    x += 1

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


code:
#Initialize a running total. For some reason you asked to initialize it to one, but note that that will give you a final total that is 1 greater than the number of
running_total = 1
#Query will select the sum of
query = "SELECT Channel, COUNT(*) AS number_of_programs FROM Programs GROUP BY Channel"
cursor = con.cursor()
cursor.execute(query)
for result in cursor.fetchall():
    print running_total
    #Add the number of programs for the channel to your running total. You access it as the second element of the returned record, because we selected number_of_programs second in our query.
    print 'Channel {0} has {1} programs. Current program count is {2}'.format(result[0],result[1],running_total)
    running_total += result[1]

rawDescription: How to count the values of rows in a database

description: Count the values of rows in a database


code:
#!/usr/local/bin/python

# You can encode the python instructions on this webpage:
# http://www.string-functions.com/string-hex.aspx
#
#
# The following hex string encodes this:
# for i in xrage(0,10):
#     print i
thestring = "\x66\x6f\x72\x20\x69\x20\x69\x6e\x20\x78\x72\x61\x6e\x67\x65\x28\x30\x2c\x31\x30\x29\x3a\x0d\x0a\x20\x20\x20\x20\x70\x72\x69\x6e\x74\x20\x69"

# Demonstration of possible code injection
# in the function:
thehack = "import os;os.system('echo foobar')"

def hex2string(myhexstring):
    """be carefull with this function possible codeinjection"""
    myhexcmd = bytes("%s" % myhexstring)
    exec myhexcmd

hex2string(thestring)

rawDescription: How can I "start" a bytearray in python?

description: "start" a bytearray in python


code:
import time

t = 1360454400
print time.strftime("%m/%d/%y", time.gmtime(t))

rawDescription: Reading a DWORD Date From Registry Using Python & _winreg


code:
import re
D = {u'excerpt':u'...where we\xe2\x80\x99ll just have to wait and see, I\xe2\x80\x99m sure official announcements with start flowing in the coming months \u2013special\u2013...'}
s = D[u'excerpt']
print s
print re.sub(ur'[\xc2-\xf4][\x80-\xbf]+',lambda m: m.group(0).encode('latin1').decode('utf8'),s)

rawDescription: converting a string which contains both utf-8 encoded bytestrings and codepoints to utf-8 encoded string

description: Converting a string which contains both utf-8 encoded bytestrings and codepoints to utf-8 encoded string


code:
d={}
f = open('a.txt', 'r')
for line in f:
     if 'drops' in line:
         data=line.split()
         d[data[1]]=d.setdefault(data[1], 0)+ int(data[3])
print d

rawDescription: Python script to generate report of packet drop


code:
import aaa
print aaa.AA # Or print(aaa.AA) for Python 3
# Prints Foo

rawDescription: I want to refer to a variable in another python script


code:
import pylab
import time
import random
import matplotlib.pyplot as plt

dat=[0,1]
fig = plt.figure()
ax = fig.add_subplot(111)
Ln, = ax.plot(dat)
ax.set_xlim([0,20])
plt.ion()
plt.show()
for i in range (18):
    dat.append(random.uniform(0,1))
    Ln.set_ydata(dat)
    Ln.set_xdata(range(len(dat)))
    plt.pause(1)

    print 'done with loop'

rawDescription: pylab.ion() in python 2, matplotlib 1.1.1 and updating of the plot while the program runs

description: Pylab.ion() in python 2, matplotlib 1.1.1 and updating of the plot while the program runs


code:
import numpy as np

def findclosest(c1, c2, c3):
   c1 = np.asarray(c1)
   c2 = np.asarray(c2)
   c3 = np.asarray(c3)

   for arr in (c1, c2, c3):
       if not (arr.ndim == 2 and arr.shape[1] == 2):
           raise ValueError("expected arrays of 2D coordinates")

   min_val = np.inf
   min_pos = None

   for a, i in enumerate(c1):
       d = xy3dist(i, c2.T[:,:,np.newaxis], c3.T[:,np.newaxis,:])
       k = np.argmin(d)

       if d.flat[k] < min_val:
           min_val = d.flat[k]
           b, c = np.unravel_index(k, d.shape)
           min_pos = (a, b, c)

       print a, min_val, d.min()

   return min_val, min_pos

def xy3dist(a, b, c):
   l1 = np.sqrt((a[0]-b[0]) ** 2 + (a[1]-b[1]) ** 2 )
   l2 = np.sqrt((b[0]-c[0]) ** 2 + (b[1]-c[1]) ** 2 )
   l3 = np.sqrt((a[0]-c[0]) ** 2 + (a[1]-c[1]) ** 2 )
   return l1+l2+l3

np.random.seed(1234)
c1 = np.random.rand(5, 2)
c2 = np.random.rand(9, 2)
c3 = np.random.rand(7, 2)

val, pos = findclosest(c1, c2, c3)

a, b, c = pos
print val, xy3dist(c1[a], c2[b], c3[c])

rawDescription: Finding closest three x,y points in three arrays


code:
import mechanize
from bs4 import BeautifulSoup

SEARCH_URL = "http://www.rcsb.org/pdb/home/home.do"

l = ["YGL130W", "YDL159W", "YOR181W"]
browser = mechanize.Browser()

for item in l:
    browser.open(SEARCH_URL)
    browser.select_form(nr=0)
    browser["q"] = item
    html = browser.submit()

    soup = BeautifulSoup(html)
    table = soup.find("table", {"class":"queryBlue"})
    if table:
        link = table.find("a", {"class":"tooltip"}).get("href")
        browser.retrieve("http://www.rcsb.org/" + str(link), str(link.split("=")[-1]) + ".pdb")[0]
        print "Downloaded " + item + " as " + str(link.split("=")[-1]) + ".pdb"
    else:
        print item + " was not found"

rawDescription: download file using python beautifulsoup and selenium

description: Download file using python beautifulsoup and selenium


code:
def f(l1,l2,i,j, path=None):
    path = [] if path is None else path[:]
    path += [(i,j)]
    if i > 0 and j > 0:
        sub, subpath = f(l1,l2,i-1,j-1)
        sub += s[l1[i]][l2[j]]
        lag1, lag1path = f(l1,l2,i,j-1)
        lag1 += n
        lag2, lag2path = f(l1,l2,i-1,j)
        lag2 += n
        fval = min(sub,lag1,lag2)
        if fval == sub:
            path.extend(subpath)
        elif fval == lag1:
            path.extend(lag1path)
        else:
            path.extend(lag2path)
    elif i > 0:
        fval, ipath = f(l1,l2,i-1,j)
        fval += n
        path.extend(ipath)
    elif j > 0:
        fval, jpath = f(l1,l2,i,j-1)
        fval += n
        path.extend(jpath)
    else:
        fval = s[l1[0]][l2[0]]
    return fval, path

def align(l1,l2):
    score, path = f(l1,l2,len(l1)-1,len(l2)-1)
    print '{} : {}'.format(score, path)

rawDescription: Python: Recursion: Output optimal path

description: Python: Recursion: Output optimal path


code: sorted(d.items(), key=lambda (name, num): (name.rsplit(None, 1)[0], num))

rawDescription: Python: sorting items in a dictionary by a part of a key?


code:
from StringIO import StringIO
import sys
orig_out = sys.stdout
print 'give me input: ',
sys.stdout = StringIO()
a = raw_input('')
sys.stdout = orig_out
a
'string I type'

rawDescription: Prevent Python from showing entered input


code:
f = Foo(bar = "test", lulz = "only for the")
print to_json(f)

rawDescription: Easier way to create a JSON object from an SQLObject


code:
import numpy as np

matrix = np.array(
    [
        [0, 1 ,0 ,0],
        [0, 0, 1, 0],
        [0, 1, 1, 0],
        [1, 0, 0, 1]
    ])

lambdas, V =  np.linalg.eig(matrix.T)
# The linearly dependent row vectors
print matrix[lambdas == 0,:]

rawDescription: How to find linearly independent rows from a matrix

description: Find linearly independent rows from a matrix


code:
def find_people_by_number(d, prefix):
    for v in d.values():
        if v[0].startswith(prefix):
            print ', '.join(v[1])

find_people_by_number(sampleDict, '654')  # Jones, Jennifer

rawDescription: How to iterate through a list in a dictionary in python

description: Iterate through a list in a dictionary in python


code:
import re
import subprocess
device_re = re.compile("Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I)
df = subprocess.check_output("lsusb", shell=True)
devices = []
for i in df.split('\n'):
    if i:
        info = device_re.match(i)
        if info:
            dinfo = info.groupdict()
            dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'), dinfo.pop('device'))
            devices.append(dinfo)
print devices

rawDescription: Simple way to query connected USB devices info in Python?


code:
from bs4 import BeautifulSoup

data = """

        text1
        link text
        text2

"""
soup = BeautifulSoup(data)
p = soup.find("td", {"id": "overview-top"}).find("p", {"itemprop": "description"})
print p.text
print ''.join(text for text in p.find_all(text=True) if text.parent.name != "a")

rawDescription: BeautifulSoup exclude content within a certain tag(s)


code: print 'cat new.txt | tr -d "s/,[]''*//g" >meantenbri.txt2'

rawDescription: writing python code to execute command in main terminal however i need to include ' ' and its not workig

description: Writing python code to execute command in main terminal however i need to include ' ' and its not workig


code:
def get_images_to_compare():
    images_to_compare = []
    while True:
        comp_img = raw_input("Path of image to compare to: ")
        if len(comp_img) <= 1:
            # break if someone just hits enter
            break
        images_to_compare.append(comp_img)
    return images_to_compare

def main():
    #capture_img = "/Users/Me/home1.png"
    capture_img = input('enter path of the file from database')
    #img_to_compare = "/Users/Me/Documents/python programs/compare/img2.jpg"
    take_and_save_picture(capture_img)
    #### you have some odd var names here, basic gist, add a for loop
    for comp_image in get_images_to_compare():
        diff = compute_edges_diff(im1, im2)
        print "Difference (percentage):", diff
        if diff > 0.5:
            print im1
        else:
            print im2

rawDescription: compare a single image with 10 or more images and find the matching one

description: Compare a single image with 10 or more images and find the matching one


code:
from collections import Counter
print Counter(ngrams("abbabcbabbabr"))

rawDescription: Getting next variable in a for loop

description: Getting next variable in a for loop


code:
def better():
  d = {}
  exec "x=23" in d
  return d['x']

print better()

rawDescription: Running exec inside function

description: Running exec inside function


code:
class Interval(object):
     def __init__(self, s=0, e=0):
         self.start = s
         self.end = e

class Solution(object):
    def canAttendMeetings(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: bool
        """
        print type(intervals)

        return True

B = Solution()
print B.canAttendMeetings([Interval(20,30),Interval(25,30)])

rawDescription: Something about python class

description: Something about python class


code: print result['z']

rawDescription: How do I turn a list of tuples into a dictionary while keeping redundant values?

description: Turn a list of tuples into a dictionary while keeping redundant values


code:
#!/usr/bin/python

import csv
import json

with open('csv', 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',', quotechar='"')
    for row in reader:
        single_json = row[6]
        single_json = single_json.replace("u'", "'")
        single_json = single_json.replace("'", '"')
        data = json.loads(single_json)
        print json.dumps(data, indent=4)

rawDescription: How can I extract a JSON object from a CSV file in Python?

description: Extract a JSON object from a CSV file in Python


code:
class Person(object):
    def drive(self, f, t):
        raise NotImplementedError

class RandomPersonABC():
    __metaclass__ = abc.ABCMeta
    @classmethod
    def __subclasshook__(cls, C):
        if C.identity is cls:
            return True
        return NotImplemented

class John(Person, RandomPersonABC):
    def drive(self, f, t):
        print "John drove from %s to %s" % (f,t)

class Kyle(Person, RandomPersonABC):
    def drive(self, f, t):
        print "Kyle drove from %s to %s" % (f,t)

class RandomPerson(Person):
    identity = None
    def __new__(cls):
        cls.identity = random.choice((John,Kyle))
        new = super().__new__(cls)
        new.__dict__.update(cls.identity.__dict__)
        return new

rawDescription: python class factory inherit random parent

description: Python class factory inherit random parent


code:
from collections import Counter
import requests  # external library but much more convenient than urllib2

r = requests.get('http://www.pythonchallenge.com/pc/def/ocr.html')
text = r.text.rsplit('<!--', 1)[-1].rsplit('-->', 1)[0]  # extract comment
counts = Counter(text)
rare = {c for c in counts if counts[c] < 5}
print ''.join([c for c in text if c in rare])

rawDescription: Something wrong in interpreting my solution to python challenge?


code:
import socket
import select
import Queue
import time

TIMEOUT = 0.1   # 100ms

def process_queue_item(item):
    print 'Got queue item: %r' % item

def process_socket_data(data):
    print 'Got socket data: %r' % data

def main():

    # Build queue
    queue = Queue.Queue()
    for i in range(10):
        queue.put(i)
    queue.put(None)   # Using None to indicate no more data on queue
    queue_active = True

    # Build socket
    sock = socket.socket()
    sock.connect(('www.google.com', 80))
    sock.send('GET / HTTP/1.0\r\n\r\n')
    socket_active = True

    # Main event loop
    while 1:

        # If there's nothing to read, bail out
        if not (socket_active or queue_active):
            break

        # By default, sleep at the end of the loop
        do_sleep = True

        # Get data from socket without blocking if possible
        if socket_active:
            r, w, x = select.select([sock], [], [], TIMEOUT)
            if r:
                data = sock.recv(64)
                if not data:    # Hit EOF
                    socket_active = False
                else:
                    do_sleep = False
                    process_socket_data(data)

        # Get item from queue without blocking if possible
        if queue_active:
            try:
                item = queue.get_nowait()
                if item is None:  # Hit end of queue
                    queue_active = False
                else:
                    do_sleep = False
                    process_queue_item(item)
            except Queue.Empty:
                pass

        # If we didn't get anything on this loop, sleep for a bit so we
        # don't max out CPU time
        if do_sleep:
            time.sleep(TIMEOUT)

if __name__ == '__main__':
    main()

rawDescription: Python - How to wait on both queue and a socket on same time


code:
from collections import OrderedDict
cols = ['userid', 'cid', 'mid', 'did', 'msid']
data = (29L, 35L, None, '', None)
result = OrderedDict(zip(cols, data))
result
result['userid']
result['cid']
list(result)

rawDescription: Preserve ordering when consolidating two lists into a dict


code:
variable = "stuff"
print "I would like to print {}".format(variable)
mapping = {'answer': 42, 'interest': 0.815}
print '''\
The answer to the ultimate question: {m[answer]:>10d}
Rate: {m[interest]:03.2%}!'''.format(m=mapping)

rawDescription: In Python what is it called when you use enclose a variable between 2 plus signs?


code:
list_y = []
for i in range(0,5):
   print i
   list_y.append(i)

print list_y

rawDescription: How would I use a attribute or a element that will split my data from adding with each other


code: print [{'newurl': d['url'], 'newtitle': d['content'], 'sumvalue': sum(d.get(item, 0) for item in ['a', 'z', 'd'])} for d in dictlist]

rawDescription: get keys value's from dictionary in python

description: Get keys value's from dictionary in python


code:
inst = MyClass()
inst.foo = 'Some value'
print inst.foo

rawDescription: How do I do get/set method in Python (specifically Trac)

description: Do get/set method in Python (specifically Trac)


code:
@wrapper
def say_hello():
    print 'Hello'

say_hello()

rawDescription: Python Method Definition Using Decorators


code:
from Twython import Twython

TWITTER_APP_KEY = 'xxxxx' #supply the appropriate value
TWITTER_APP_KEY_SECRET = 'xxxxx'
TWITTER_ACCESS_TOKEN = 'xxxxxx'
TWITTER_ACCESS_TOKEN_SECRET = 'xxxxx'

t = Twython(app_key=TWITTER_APP_KEY,
            app_secret=TWITTER_APP_KEY_SECRET,
            oauth_token=TWITTER_ACCESS_TOKEN,
            oauth_token_secret=TWITTER_ACCESS_TOKEN_SECRET)

search = t.search(q='#omg',   #**supply whatever query you want here**
                  count=100)

tweets = search['statuses']

for tweet in tweets:
  print tweet['id_str'], '\n', tweet['text'], '\n\n\n'

rawDescription: Fetching tweets with hashtag from Twitter using Python


code: print [p[:2] for p in (i.partition('.suffix') for i in l)]

rawDescription: Python Regex: How to match filenames with optional suffix? Why '(.*?)(\.suffix)?' doesn't work?


code:
import csv
with open('some.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        print row

rawDescription: Converting columns in a file into separate lists using python


code:
import re

myfile = open('inputfile.txt', 'r')
regex  = re.compile(r'(?<=data-start=\\").*?(?=\\" data-end)')

for line in myfile:
    matches = regex.findall(line)
    for m in matches:
        print m

rawDescription: Extracting text between two markers and handling Backslashes in Regex for Python


code: print data[0]['update_date']

rawDescription: Display Specific Fields (Through Parse) from JSON response in Python


code:
for i,line in enumerate(content.splitlines(True)):
    print str(i)+' '+repr(line)

print '\n\n'

import re

regx = re.compile('\t\t\t\t\t\t(\d\d:\d\d:\d\d)	\r\n'
                  '\t\t\t\t\t\t([\d.]+)	\r\n'
                  '\t\t\t\t\t\t(\d+)	\r\n')

print regx.findall(content)

rawDescription: Web scraping urlopen in python

description: Web scraping urlopen in python


code:
for list1_dict in list1:
    for k, v in list1_dict.iteritems():
        if k in dict1:
            resultDict = {v: dict1[k]}
            print resultDict

rawDescription: combining a list of dictionaries with another dictionary

description: Combining a list of dictionaries with another dictionary


code:
from urllib import urlopen
from bs4 import BeautifulSoup
import re

webpage = urlopen('http://talkingpointsmemo.com/feed/livewire').read()

patFinderTitle = re.compile('<title>(.*)</title>')
patFinderLink = re.compile('<link rel.*href="(.*)"/>')

findPatTitle = re.findall(patFinderTitle, webpage)[0:4]
findPatLink = re.findall(patFinderLink, webpage)[0:4]

listIterator = []
listIterator[:] = range(len(findPatTitle))
paraStringList = []

for i in listIterator:

    print findPatTitle[i]

    articlePage = urlopen(findPatLink[i]).read()

    divBegin = articlePage.find("<div class='story-teaser'>")
    divEnd = articlePage.find("<footer class='article-footer'>")

    article = articlePage[divBegin:divEnd]

    soup = BeautifulSoup(article)

    paragList = soup.findAll('p')

    para_string = ''

    for i in paragList:
        para_string += str(i)

    paraStringList.append(para_string)

for i, var in enumerate(paraStringList):
    with open("{0}.txt".format(i), 'w') as writer:
        writer.write(var)

rawDescription: Python Blog RSS Feed Scraping BeautifulSoup Output to .txt Files


code:
import colorsys

DEG30 = 30/360.
def adjacent_colors((r, g, b), d=DEG30): # Assumption: r, g, b in [0, 255]
    r, g, b = map(lambda x: x/255., [r, g, b]) # Convert to [0, 1]
    h, l, s = colorsys.rgb_to_hls(r, g, b)     # RGB -> HLS
    h = [(h+d) % 1 for d in (-d, d)]           # Rotation by d
    adjacent = [map(lambda x: int(round(x*255)), colorsys.hls_to_rgb(hi, l, s))
            for hi in h] # H'LS -> new RGB
    return adjacent

rawDescription: Calculating the analogous color with python


code:
class ClassRegistry(object):

    def __init__(self):
        self.classes = {}

    def add_file_classes(self, fname, class_list):
        globals = {}
        exec open(fname) in globals
        for class_name in class_list:
            self.classes[class_name] = getattr(globals, class_name)

    def get_class(self, class_name):
        return self.classes[class_name]

rawDescription: Dynamic module import of class list from module given its full path


code:
if sums[i-1] != sums[i] and sums[i] == sums[i+1]:
    if sums[i]<t:
        print "%10d"%(sums[i])
    else:
        break

rawDescription: How to fix Python If Statement for finding Taxicab numbers?

description: Fix Python If Statement for finding Taxicab numbers


code:
import xmlrpclib

proxy = xmlrpclib.ServerProxy('http://localhost:9000')
print 'os.listdir():', proxy.listdir('.')

rawDescription: xmlrpcserver implementation in python capable of registering an entire module?

description: Xmlrpcserver implementation in python capable of registering an entire module


code:
import Tkinter as tk
import xmlrpclib
import socket

class SampleApp(tk.Tk):
    # url of the server
    url = "http://localhost:8000"

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        # initialize connection to server
        self.server = xmlrpclib.ServerProxy(self.url)

        # create GUI
        self.status = tk.Label(text="", anchor="w")
        self.label = tk.Label(text="current score: ?")
        self.status.pack(side="bottom", fill="x")
        self.label.pack(side="top", fill="both", expand=True)
        self.wm_geometry("400x200")

        # wait a second to give the GUI a chance to
        # display, then start fetching the scores
        # every 5 seconds
        self.after(1000, self.get_latest_scores, 2000)

    def update_status(self, message=""):
        '''Update the statusbar with the given message'''
        self.status.configure(text=message)
        self.update_idletasks()

    def get_latest_scores(self, interval):
        '''Retrieve latest scores and update the UI'''
        try:
            self.update_status("connecting...")
            score = self.server.get_scores()
            self.label.configure(text="current score: %s" % score)
            self.update_status()
        except socket.error, e:
            self.update_status("error: %s" % str(e))
        self.after(interval, self.get_latest_scores, interval)

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

rawDescription: How to create a simple network connection in Python?

description: Create a simple network connection in Python


code:
import difflib

lines1 = '''
dog
cat
bird
buffalo
gophers
hound
horse
'''.strip().splitlines()

lines2 = '''
cat
dog
bird
buffalo
gopher
horse
mouse
'''.strip().splitlines()

# Changes:
# swapped positions of cat and dog
# changed gophers to gopher
# removed hound
# added mouse

for line in difflib.unified_diff(lines1, lines2, fromfile='file1', tofile='file2', lineterm=''):
    print line

rawDescription: Compare two files report difference in python


code:
class MyMeta(type):
    def __new__(mcs, name, bases, kwargs):
        print "I'm the metaclass, just checking in."
        return type.__new__(mcs, name, bases, kwargs)

class Foo(object):
    __metaclass__ = MyMeta

    print "I'm the Foo class"

rawDescription: What code is executed when a class is being defined?


code:
import re

l = ['',
     'q//Attachments/Swoop_coverletter_311386_20120103.doc',
     'q//Attachments/Swoop_RESUME_311386_20091012.doc',
     'q//Attachments/Swoop_Resume_311386_20100901.doc',
     'q//Attachments/Swoop_reSume_311386_20120103.doc',
     'q//Attachments/Swoop_coverletter_311386_20100901.doc',
     'q//Attachments/Swoop_coverletter_311386_20091012.doc']

def get_date(line):
    pattern = '.*_(\d{8}).doc'
    m = re.match(pattern, line)
    if m:
        return int(m.group(1))
    else:
        return -1 # or do something else with lines that contain no date

print sorted(l, key=get_date, reverse=True)

rawDescription: Python sorting array according to date

description: Python sorting array according to date


code: print time.ctime(max(os.path.getmtime(root) for root,_,_ in os.walk('/tmp/x')))

rawDescription: Get the last modified date of a directory (including subdirectories) using Python?


code:
#!/usr/bin/env python
import fileinput
from collections import defaultdict, Counter

# count guids
perfile = defaultdict(Counter)
total = Counter()
for line in fileinput.input():
    fname, guid = map(str.strip, line.split(':'))
    perfile[guid][fname] += 1
    total[guid] += 1

# print most common guid first
for guid, count in total.most_common():
    if count < 2: continue # skip printing if count is below threshold
    print '{:>3} {}'.format(count, guid)
    # sorting by filename counts
    for fname, fname_cnt in perfile[guid].most_common():
        print '{:>8} {}'.format(fname_cnt, fname)

rawDescription: Working with dictionaries, how would you find/track duplicate GUIDs given this list?


code: print cubiod[x1,y1,z1]

rawDescription: Python : fill cuboid with spheres

description: Python : fill cuboid with spheres


code:
count = {}
for s in check_string:
  if count.has_key(s):
    count[s] += 1
  else:
    count[s] = 1

for key in count:
  if count[key] > 1:
    print key, count[key]

rawDescription: Counting repeated characters in a string in Python


code:
gender= "male"
print "At least, that's what %s told me." %("he" if gender == "male" else "she")

rawDescription: Python conditional string formatting

description: Python conditional string formatting


code:
class no_share(object):
    def __init__(self, arg1):
        self.arg1 = arg1

    def __call__(self, f):
        """Don't let them in if it's shared"""

        # Do something with the argument passed to the decorator.
        print 'Decorator arguments:', self.arg1

        def wrapped_f(request, *args, **kwargs):
            if kwargs.get('shared', True):
                from django.http import Http404
                raise Http404('not availiable for sharing')
            f(request, *args, **kwargs)
        return wrapped_f

rawDescription: Adding an argument to a decorator

description: Adding an argument to a decorator


code:
for i in tree.xpath('//div[@class="class1"]/div/text()'):
    print i

rawDescription: How do I parse with LXML recursively in an elegant way?

description: Parse with LXML recursively in an elegant way


code:
sample = open('cs_go_sample.txt').read()
config = parser.parseString(sample)

print config.keys()
for k in config.items_game.keys():
    print '-', k

config.items_game.pprint()

rawDescription: Parsing a CS:GO script file in Python

description: Parsing a CS:GO script file in Python


code:
from selenium import webdriver
import time
driver = webdriver.PhantomJS(executable_path=r"C:\Users\Desktop\phantomjs.exe")

driver.set_window_size(1120, 550)
url = 'http://www.stance.com/shop/product/paint-trap'
print "Driver Made"
driver.get(url)
print "URL got"
driver.implicitly_wait(5)
price = driver.find_elements_by_xpath("(//*[@id='h1--title-price']/span)[2]")
for i in price:
    print i.text
driver.close()

rawDescription: Selenium basic opening a url

description: Selenium basic opening a url


rawDescription: Python/Sympy trigonometric solution of cubic equation


code:
from django.core.urlresolvers import RegexURLPattern, RegexURLResolver

def urlpatterns_iterator(patterns):
    """Recursively iterate through `pattern`s.
    """
    _patterns = patterns[:]  # create a copy

    while _patterns:
        cur = _patterns.pop()
        if isinstance(cur, RegexURLPattern):
            yield cur
        elif isinstance(cur, RegexURLResolver):
            _patterns += cur.url_patterns
        else:
            raise ValueError("I don't know how to handle %r." % cur)

def decorate(fn, (urlconf_module, app_name, namespace)):
    """Iterate through all the urls reachable from the call to include and
       wrap the views in `fn` (which should most likely be a decorator).

       (the second argument is the return value of Django's `include`).
    """
    # if the include has a list of patterns, ie.:  url(<regex>, include([ url(..), url(..) ]))
    # then urlconf_module doesn't have 'urlpatterns' (since it's already a list).
    patterns = getattr(urlconf_module, 'urlpatterns', urlconf_module)
    for pattern in urlpatterns_iterator(patterns):
        # the .callback property will set ._callback potentially from a string representing the path to the view.
        if pattern.callback:
            # the .callback property doesn't have a setter, so access ._callback directly
            pattern._callback = fn(pattern._callback)
    return urlconf_module, app_name, namespace

rawDescription: reusable apps and access control

description: Reusable apps and access control


code:
import pandas as pd

df = pd.read_csv("flu.csv")
top = df.head(1)
bottom = df.tail(1)
concatenated = pd.concat([top,bottom])

print concatenated

rawDescription: Python pandas DataFrame from first and last row of csv


code:
import json
import os
from time import sleep
import requests

url = 'http://api.opencorporates.com/v0.2/companies/search'
token = 'ab123cd45'
rate = 20  # seconds to wait after rate limited

with open('codes') as f:
    codes = [l.strip('\n') for l in f]

def get_page(code, page, **kwargs):
    params = {
        # 'api_token': token,
        'jurisdiction_code': code,
        'page': page,
    }
    params.update(kwargs)

    while True:
        r = requests.get(url, params=params)

        try:
            data = r.json()
        except ValueError:
            return None

        if 'error' in data:
            print data['error']['message']
            sleep(rate)
            continue

        return data['results']

def dump_page(code, page, data):
    with open(os.path.join(code, str(page) + '.json'), 'w') as f:
        json.dump(data, f)

for code in codes:
    try:
        os.makedirs(code)
    except os.error:
        pass

    data = get_page(code, 1)
    if data is None:
        continue

    dump_page(code, 1, data['companies'])

    for page in xrange(1, int(data.get('total_pages', 1))):
        data = get_page(code, page)
        if data is None:
            break

        dump_page(code, page, data['companies'])

rawDescription: Check response using urllib2

description: Check response using urllib2


code:
def add(a,b):
    return a + b

print "The first number you want to add?"
a = int(raw_input("First no: "))
print "What's the second number you want to add?"
b = int(raw_input("Second no: "))

result = add(a, b)

print "The result is: %r." % result

rawDescription: Python 'add' function issue: why won't this work?


code:
d = range(0,9)  # build an arbitrary list here
                # this creates a list of numbers: [0,1,2,3,4,5,6,7,8]
e = len(d)
print list(itertools.permutations(d, e))

rawDescription: Python Itertools Permutations

description: Python Itertools Permutations


code:
import socket, struct

host,port = 'baystation12.net', 8000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

senddata = "?status"
query  = '\x00\x83' + struct.pack(">H", len(senddata)+6) + '\x00'*5 + senddata + '\x00'
s.send(query)

data = s.recv(1024)
print `data`

rawDescription: PHP and Python unpack return different results from same source


code:
heads = [i.text.strip() for i in table.select('thead th')]
for tr in table.select('tbody tr'):
    datas = [i.text.strip() for i in tr.select('td')]
    print dict(zip(heads, datas))

rawDescription: Scraping with Beautiful Soup

description: Scraping with Beautiful Soup


code:
import sys

def redirect_output(file_name):

    def decorator(func):
        def wrapper(*args):
            with open(file_name, 'w') as f:
                original_stdout = sys.stdout
                sys.stdout = f
                func(*args)
            sys.stdout = original_stdout
        return wrapper
    return decorator

@redirect_output('file.txt')
def somefunc(x):
  print "Hello World", x**x

somefunc(2)

print 'Hello to console.'

rawDescription: Pipe console outputs from a specific function into a file - python


code:
# define func
dll = ctypes.WinDLL(imagehlp)
mapfileandchecksuma = dll.MapFileAndCheckSumA
mapfileandchecksuma.restype = ctypes.wintypes.DWORD
mapfileandchecksuma.argtypes = [c_char_p,
                                POINTER(ctypes.wintypes.DWORD),
                                POINTER(ctypes.wintypes.DWORD)]

# call func
filename = 'ntkr128g.exe'
headersum  = ctypes.wintypes.DWORD()
checksum = ctypes.wintypes.DWORD()
if mapfileandchecksuma(filename,
                       byref(headersum),
                       byref(checksum)) == 0:
    print headersum.value, checksum.value

rawDescription: python ctypes how to map PTSTR

description: Python ctypes how to map PTSTR


code:
def rotatePoint(centerPoint,point,angle):
    """Rotates a point around another centerPoint. Angle is in degrees.
    Rotation is counter-clockwise"""
    angle = math.radians(angle)
    temp_point = point[0]-centerPoint[0] , point[1]-centerPoint[1]
    temp_point = ( temp_point[0]*math.cos(angle)-temp_point[1]*math.sin(angle) , temp_point[0]*math.sin(angle)+temp_point[1]*math.cos(angle))
    temp_point = temp_point[0]+centerPoint[0] , temp_point[1]+centerPoint[1]
    return temp_point

print rotatePoint((1,1),(2,2),45)

rawDescription: Python function for rotating 2d objects

description: Python function for rotating 2d objects


code:
import re
import csv
from pygoogle import pygoogle

names = []

with open('parse2.txt') as fin:
   names = [x.strip() for x in fin.read().strip('\'"[]').split(' '*6)]

with open("output.txt") as fout:
  for name in names:
    g = pygoogle(name)
    g.pages = 1
    if (g.get_result_count()) == 0:
      print "[Error]: could find no result for '{}'".format(name)
    else:
      fout.write("{}    {} results\n".format(name, g.get_result_count()) )

rawDescription: Writing a results to a .txt file using csv


code:
from lxml import etree

ns_bldg = "http://www.opengis.net/citygml/building/2.0"
nsmap = {
    'bldg': ns_bldg,
}

cityModel = etree.Element("cityModel", nsmap=nsmap)
cityObject = etree.SubElement(cityModel, "cityObjectMember")
bldg = etree.SubElement(cityObject, "{%s}Building" % ns_bldg)
function = etree.SubElement(bldg, "{%s}function" % ns_bldg)
function.text = "1000"
print etree.tostring(cityModel, pretty_print=True)

rawDescription: lxml use namespace instead of ns0, ns1,

description: Lxml use namespace instead of ns0, ns1,


code:
import theano
import theano.tensor as tt

x = tt.matrix()
y = tt.matrix()
z = tt.stack([x, y], axis=2)
f = theano.function([x, y], z)
print f([[1, 2, 3]], [[4, 5, 6]])

rawDescription: How to combine two tensor in theano

description: Combine two tensor in theano


code:
from script1 import gh
from global_var import user
print user
print gh

rawDescription: Use input variables across Python scripts


code:
class BaseHandler(tornado.web.RequestHandler):
    @property
    def prepare(self):
        self.set_header('P3P', 'CP="HONK"')

    def initialize(self):
        if self.request.full_url() == "http://mydomain/a/facebook/":
            self.request.protocol = "https"
        self.init_facebook()

    def init_facebook(self):
        """Sets up the request specific Facebook and User instance"""

        # initial facebook request comes in as a POST with a signed_request
        signed_request = self.get_argument('signed_request', None)
        if signed_request and self.request.method == u'POST':
            app_secret = options.facebook_app_secret
            data = load_signed_request(signed_request, app_secret)
            user_id = data.get(u"user_id")
            if user_id:
                self.set_secure_cookie("uid", user_id)
            self.request.method = u'GET'

class FacebookCanvasHandler(HomeHandler):
    def get(self, *args, **kwds):
        logging.info("Facebook Canvas called.")
        if not self.current_user:
            logging.info("Need user grant permission, redirect to oauth dialog.")
            logging.info(self.settings.get("facebook_canvas_id"))
            oauth_url = self.get_login_url(self.settings.get("facebook_canvas_id"))
            logging.info(oauth_url)
            self.render("canvas_oauth.html", oauth_url=oauth_url)
        else:
            super(FacebookCanvasHandler, self).get(*args, **kwds)

def load_signed_request(signed_request, app_secret):
    try:
        sig, payload = signed_request.split(u'.', 1)
        sig = base64_url_decode(sig)
        data = json.loads(base64_url_decode(payload))

        expected_sig = hmac.new(app_secret, msg=payload, digestmod=hashlib.sha256).digest()

        if sig == expected_sig and data[u'issued_at'] > (time.time() - 86400):
            return data
        else:
            return None
    except ValueError, ex:
        return None

def base64_url_decode(data):
    data = data.encode(u'ascii')
    data += '=' * (4 - (len(data) % 4))
    return base64.urlsafe_b64decode(data)

rawDescription: Facebook Canvas App - Circular Login Redirect


code:
import multiprocessing as mp
import multiprocessing.util as util
util.log_to_stderr(util.SUBDEBUG)
pool=mp.Pool(1)
print list(pool.imap(abs, range(3)))

rawDescription: multiprocessing Pool.imap broken?

description: Multiprocessing Pool.imap broken


code:
string = "Hi how are you"
reversedString = []
mysplit = string.split(" ")

for i in mysplit:
    reverse = i[::-1]
    reversedString.append(reverse)

print  reversedString

rawDescription: How to append an empty list in a for loop in Python and i got "None" when try to append the reversed string.Why its showing None?

description: Append an empty list in a for loop in Python and i got "None" when try to append the reversed string.Why its showing None


code:
# from http://docs.python.org/2/library/os.html
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print root, "consumes",
    print sum(getsize(join(root, name)) for name in files),
    print "bytes in", len(files), "non-directory files"
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

rawDescription: Fast calculation of the size and counting all files in a directory and subdirectories using python (cross platform)


code:
class A(object):
    def __init__(self, s):
        self.s = s
    def replace(self, x):
        self.s = self.s.replace(self.x, x)
    def __getattr__(self, name):
        self.x = name
        return self

a = A('abc')
a.b.replace('X')
print a.s

rawDescription: Python List methods

description: Python List methods


rawDescription: How to format an array of floats into a string

description: Format an array of floats into a string


code:
print "Hello, " + "world".ljust(10) + "!"
print "Hello, " + "world".center(10) + "!"
print "Hello, " + "world".rjust(10) + "!"

rawDescription: Pad outgoing messages

description: Pad outgoing messages


code:
infile = open("temp.txt")
for line in infile:
    if len(line) > 2:
        (A, B) = line.split(':')
        As = [eval(a).strip() for a in A.split(',')]
        Bs = [eval(b).strip() for b in B.split(',')]
        Com = [A for A in As if A in Bs]
        print As, ':', Bs, '::', Com

rawDescription: Python Print common values into column

description: Python Print common values into column


code:
df['binned_strike'] = ind
for grp in df.groupby(['symbol', 'serie', 'binned_strike']):
    print "group key"
    print grp[0]
    print "group content"
    print grp[1]
    print "============="

rawDescription: How to group by a range of values in pandas?

description: Group by a range of values in pandas


code:
data = {
    'a': 1,
    'b': 2,
    'c': 3,
    'd': 4
}
print max(data, key=data.get)

rawDescription: Choose Variable With Highest Value (Python)


code:
EDIT
from difflib import SequenceMatcher

li = [\
 ([u'Liberty', u'Toledo'], #######
 [u'LIBERTY', u'TOLEDO']),

([u'Chattanooga', u'Arkansas'], ################
 [u'UTC', u'AR']),

([u'Texas Tech', u'Iowa State'], ###########
 [u'TT', u'ISU'])  ]

def comp(N,D,sq = SequenceMatcher(None)):
    sq.set_seqs(N[0],D[0])
    a = sq.ratio()
    sq.set_seqs(N[1],D[1])
    b = sq.ratio()

    sq.set_seqs(N[0],D[1])
    x = sq.ratio()
    sq.set_seqs(N[1],D[0])
    y = sq.ratio()

    sq.set_seqs(N[0].lower(),D[0].lower())
    al = sq.ratio()
    sq.set_seqs(N[1].lower(),D[1].lower())
    bl = sq.ratio()

    sq.set_seqs(N[0].lower(),D[1].lower())
    xl = sq.ratio()
    sq.set_seqs(N[1].lower(),D[0].lower())
    yl = sq.ratio()

    return ((N[0],D[0]), (N[1],D[1]),
            a,b,a*b,a+b,
            (N[0].lower(),D[0].lower()), (N[1].lower(),D[1].lower()),
            al,bl,al*bl,al+bl,
            (N[0],D[1]),(N[1],D[0]),
            x,y,x*y,x+y,
            (N[0].lower(),D[1].lower()),(N[1].lower(),D[0].lower()),
            xl,yl,xl*yl,xl+yl)

print '\n'.join(('====='*14)+ '\n'
                '%-25s   %s\n'
                '    %-10f                  %f       -->   x%f  +%f\n'
                '%-25s   %s\n'
                '    %-10f                  %f       -->   x%f  +%f\n\n'
                '%-25s   %s\n'
                '    %-10f                  %f       -->   x%f  +%f\n'
                '%-25s   %s\n'
                '    %-10f                  %f       -->   x%f  +%f\n'
                % comp(N,D) for N,D in li)

rawDescription: Pythonic Name Matching

description: Pythonic Name Matching


code:
import pysvn

url='http://svn.apache.org/repos/asf/httpd/httpd/trunk/README'

epoch = pysvn.Revision(pysvn.opt_revision_kind.number, 0)
head = pysvn.Revision(pysvn.opt_revision_kind.head)

client = pysvn.Client()

# Get all entries
l = client.log(url)
print len(l), l[0].revision, l[-1].revision

# Get most recent entry:
l = client.log(url, limit=1)
print len(l), l[0].revision

# Get most recent entry, again:
l = client.log(url, revision_start=head, revision_end=epoch, limit=1)
print len(l), l[0].revision

# Get least recent entry
l = client.log(url, revision_start=epoch, revision_end=head, limit=1)
print len(l), l[0].revision

rawDescription: Does pysvn let you limit log messages in reverse order?


code: print [100 * (b - a) / a for a, b in zip(prices[::1], prices[1::1])]

rawDescription: Calculating change in percentage between two numbers (Python)


code:
print vars(def_3)
# create a new instance of Word ...
a_separate_instance = Word("dissemble", [def_3])
print vars(def_3)

rawDescription: Interfering objects (or something less sinister?)


code:
def get_count_for_row(row=1):
    with open("so_cnt_file.txt") as infile:
        for i in range(0, row + 2):
            next(infile)
        cnt = 0
        for line in infile:
            row, col = [int(val) for val in line.strip().split(" ") if val]
            if col == 0:
                return cnt
            cnt += 1
print get_count_for_row(1)
print get_count_for_row(6)

rawDescription: Python counting lines in files using exact locations


code:
import urllib
import csv
import StringIO

url = 'http://137.205.144.34/services/unload.cmd?format=csvx&sched=&start=-240:00:00&id=75631&step=864'
f = urllib.urlopen(url)
data = f.read()

reader = csv.reader(StringIO.StringIO(data))
for row in reader:
    if row: print row[0]

rawDescription: searching beautiful soup output without html tags

description: Searching beautiful soup output without html tags


code:
import os
import random

# Draw point, with check if the point is in the image area
def drawPoint(pic, col, x, y):
   if (x >= 0) and (x < getWidth(pic)) and (y >= 0) and (y < getHeight(pic)):
     px = getPixel(pic, x, y)
     setColor(px, col)

# Draw line segment, given two points
# From Bresenham's line algorithm
# http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm
def drawLine(pic, col, x0, y0, x1, y1):

   dx = abs(x1-x0)
   dy = abs(y1-y0)
   sx = sy = 0

   #sx = 1 if x0 < x1 else -1
   #sy = 1 if y0 < y1 else -1

   if (x0 < x1):
     sx = 1
   else:
     sx = -1
   if (y0 < y1):
     sy = 1
   else:
     sy = -1

   err = dx - dy

   while (True):

     drawPoint(pic, col, x0, y0)

     if (x0 == x1) and (y0 == y1):
       break

     e2 = 2 * err
     if (e2 > -dy):
       err = err - dy
       x0 = x0 + sx

     if (x0 == x1) and (y0 == y1):
       drawPoint(pic, col, x0, y0)
       break

     if (e2 <  dx):
       err = err + dx
       y0 = y0 + sy

# Draw infinite line from segment
def drawInfiniteLine(pic, col, x0, y0, x1, y1):
   # y = m * x + b
   m = (y0-y1) / (x0-x1)
   if (abs(m) > 100.0):
     m = 100.0

   # y0 = m * x0 + b   =>   b = y0 - m * x0
   b = y0 - m * x0

   x0 = 0
   y0 = int(m*x0 + b)
   # get a 2nd point far away from the 1st one
   x1 = getWidth(pic)
   y1 = int(m*x1 + b)

   drawLine(pic, col, x0, y0, x1, y1)

# Draw infinite line from origin point and angle
# Angle 'theta' expressed in degres
def drawInfiniteLineA(pic, col, x, y, theta):

   # y = m * x + b
   dx = y * tan(theta * pi / 180.0)  # (need radians)
   dy = y

   if (dx == 0):
     dx += 0.000000001 # Avoid to divide by zero

   m = dy / dx

   # y = m * x + b   =>   b = y - m * x
   b = y - m * x

   # get a 2nd point far away from the 1st one
   x1 = 2 * getWidth(pic)
   y1 = m*x1 + b

   drawInfiniteLine(pic, col, x, y, x1, y1)

def synthesizeFrameAndCreateMovie(folder):

  # Create an empty movie to receive the frames
  movie = makeMovie()

  # Compute & save the frames
  w = 40
  h = 25
  nb_frames = 120       # Will give 120 frames at 30 fps => movie duration : 4 sec.
  for z in range(0, nb_frames):
    pic = makeEmptyPicture(w, h)
    addRectFilled(pic, 0, 0, w-1, h-1)
    #makeColor() takes red, green, and blue (in that order) between 0 and 255
    r = random.randint(0, 255)
    g = random.randint(0, 255)
    b = random.randint(0, 255)
    col = makeColor(r,g,b)
    theta = z * 360 / nb_frames
    if (theta != 180.0) and (theta != 0.0):
      drawInfiniteLineA(pic, col, w//2, h//2, theta)

    # Create one frame and inject in the movie object
    filename = os.path.join(folder, 'pic%03d.png' % z)
    writePictureTo(pic, filename)
    addFrameToMovie(filename, movie)

  # return the movie
  return movie

movie = synthesizeFrameAndCreateMovie("/home/FOLDER")
print movie
#writeQuicktime(movie,"/home/golgauth/Desktop/FOLDER/movie.mov", 30)
#writeAVI(movie,"/home/golgauth/Desktop/FOLDER/movie.avi")
playMovie(movie)

rawDescription: Creating a movie in Jython/Python

description: Creating a movie in Jython/Python


code:
def str_to_list(x):
    return x.split(', ')

print str_to_list("a, b, c, d, e")

rawDescription: Python 2.7 how to turn the string into a list outside the function with str.split()?


code:
for x in range(20):
    if not (x % 5):
        print "Got it: {}".format(x)

rawDescription: Modulo function in python to group an encrypted text in to chunks of 5


code:
# read keys
with open('file1', 'r') as fd:
    keys = fd.read().splitlines()

# output keys
print '\t'.join(keys)

# read data file, with header line and content
with open('file2', 'r') as fd:
    headers = fd.readline().split()
    while True:
        line = fd.readline().split()
        if len(line) == 0:
            break
        print '\t'.join([line[headers.index(x)] for x in keys if x in headers])

rawDescription: extracting data from a dictionary

description: Extracting data from a dictionary


rawDescription: initialize python dictionary containing a strings and lists

description: Initialize python dictionary containing a strings and lists


code:
def next_dow(d,days):
    while d.weekday() not in days:
        d+=dt.timedelta(1)

    return d

d1=next_dow(dt.datetime(2013,4,1),(dow['Tue'],dow['Thu']))
d2=next_dow(dt.datetime(2013,4,2),(dow['Mon'],dow['Wed'],dow['Fri']))

for d in d1,d2:
    print d.strftime('%Y-%m-%d')

rawDescription: Find next date by day of week

description: Find next date by day of week


code:
a = set(listA)
print a.intersection(listB)

rawDescription: List Comparison Algorithm: How can it be made better?