code:
import datetime
import time

class Timer(object):
    def __init__(self, *args, **kwargs):
        self.StartTime = datetime.datetime.now()
        self.TimeElapsed = self.timedif(datetime.datetime.now(), self.StartTime)

    def hms_string(self, sec_elapsed):
        h = int(sec_elapsed / (60 * 60))
        m = int((sec_elapsed % (60 * 60)) / 60)
        s = sec_elapsed % 60
        return "{}:{:>02}:{:>05.2f}".format(h, m, s)

    def timedif(self, end_datetime, start_datetime):
        seconds_elapsed = (end_datetime - start_datetime).total_seconds()
        return self.hms_string(seconds_elapsed)

    def time_elapsed(self):
        return self.timedif(datetime.datetime.now(), self.StartTime)

t = Timer()
print "time elapsed from variable: {}".format(t.TimeElapsed)
time.sleep(1)
print "time elapsed from variable: {}".format(t.TimeElapsed)

t = Timer()
print "time elapsed from method: {}".format(t.time_elapsed())
time.sleep(1)
print "time elapsed from method: {}".format(t.time_elapsed())

rawDescription: Python Classes: update value of instance when it's called on


code: print '\n'.join(parts)

rawDescription: Splitting a string by list of indices

description: Splitting a string by list of indices


code:
for item in chunks({i:i for i in xrange(10)}, 3):
    print item

rawDescription: How to split dictionary into multiple dictionaries fast

description: Split dictionary into multiple dictionaries fast


code:
variables= {}
execfile( "someFile.py", variables )
print variables # globals from the someFile module

rawDescription: How to execute a file within the python interpreter?

description: Execute a file within the python interpreter


code:
some_string = '(laughter flower)'
keys = some_string[1:-1].lower().split()
print somefunc(keys, some_dict)

rawDescription: Using list comprehension

description: Using list comprehension


code:
def find():
    num = 1
    f = open('Customerlist.txt', 'r') #Open file
    search = f.readlines() #read data into memory (list of strings)
    f.close() #close file again
    for line in search:
        lst = line.split(", ") #split on the seperator - in this case a comma and space
        if str(num) == lst[0]: #Check if the string representation of your number equals the first parameter in your lst.
            print "ID: %s" % lst[0]
            print "Name: %s" % lst[1]
            print "Surname: %s" % lst[2]
            print "DOB: %s" % lst[3]
            print "hnumber: %s" % lst[4]
            print "Postcode: %s" % lst[5]
            print "Gender: %s" % lst[6]

rawDescription: How to read a line in a .txt file and create a list?

description: Read a line in a .txt file and create a list


code:
grouped = df.groupby(1)
for k,g in grouped:
    print k
    print g

rawDescription: Indexing column values in pandas

description: Indexing column values in pandas


code:
def hints(before=None, after=None, around=None):
    """A decorator that implements function hints to be run before, after or
    around another function, sort of like in the CLOS."""

    # Make sure all of our hints are callable
    default = lambda *args, **kwargs: None
    before = before if callable(before) else default
    after = after if callable(after) else default
    around = around if callable(around) else default

    # The actual decorator function.  The "real" function to be called will be
    # pased to this as `fn`
    def decorator(fn):

        # The decorated function.  This is where the work is done.  The before
        # and around functions are called, then the "real" function is called
        # and its results are stored, then the around and after functions are
        # called.
        def decorated(*args, **kwargs):
            around(*args, **kwargs)
            before(*args, **kwargs)
            result = fn(*args, **kwargs)
            after(*args, **kwargs)
            around(*args, **kwargs)
            return result
        return decorated
    return decorator

# Shortcuts for defining just one kind of hint
def before(hint):
    return hints(before=hint)

def after(hint):
    return hints(after=hint)

def around(hint):
    return hints(around=hint)

# The actual functions to run before, after, around
def beforefn():
    print 'before'

def afterfn():
    print 'after'

def aroundfn():
    print 'around'

# The function around which the other functions should run
@before(beforefn)
@after(afterfn)
@around(aroundfn)
def fn():
    print 'Hello World!'

# Or use the single @hints decorator
@hints(before=beforefn, after=afterfn, around=aroundfn)
def fn2():
    print 'Goodbye World!'

rawDescription: Python decorators compared to CLOS "around" method


rawDescription: Concatenating numpy arrays vertically and horizontally


code:
# FWHM...
half_max = xs[index_of_peak]/2

# This finds where in the data we cross over the halfway point to our peak. Note
# that this is global, so we need an extra step to refine these results to find
# the closest crossovers to our peak.

# Same sign-change-in-first-diff technique as above
hm_left_indices = (np.diff(np.sign(np.diff(np.abs(xs[:index_of_peak] - half_max)))) > 0).nonzero()[0] + 1
# Add "index_of_peak" to result because we cut off the left side of the data!
hm_right_indices = (np.diff(np.sign(np.diff(np.abs(xs[index_of_peak:] - half_max)))) > 0).nonzero()[0] + 1 + index_of_peak

# Find closest half-max index to peak
hm_left_index = hm_left_indices[np.argmin(np.abs(hm_left_indices - index_of_peak))]
hm_right_index = hm_right_indices[np.argmin(np.abs(hm_right_indices - index_of_peak))]

# And the width is...
fwhm = ts[hm_right_index] - ts[hm_left_index]

print "Width: %.3f" % fwhm

# Plot to illustrate FWHM: blue line is data, red circle is peak, red line
# shows FWHM
plt.plot(ts, xs, '-b')
plt.plot(ts[index_of_peak], xs[index_of_peak], 'or')
plt.plot(
    [ts[hm_left_index], ts[hm_right_index]],
    [xs[hm_left_index], xs[hm_right_index]], '-r')
plt.show()

rawDescription: These spectrum bands used to be judged by eye, how to do it programmatically?


code:
import random

a = ['apple','banana']
probability = [0.1,0.9]

def biase(lst,probability):
    zipped = zip(lst,probability)
    lst = [[i[0]] * int(i[1]*100) for i in zipped]
    new = [b for i in lst for b in i]
    return new

biased_list = biase(a,probability)
random_word = random.choice(biased_list)
print random_word

rawDescription: How to implement biased random function?

description: Implement biased random function


code:
from decimal import *

getcontext().prec = 103

def precision(context, prec=100):

    return Decimal(context).quantize(Decimal('.'+'0'*(prec-1)+'1'), rounding=ROUND_DOWN)

print precision(Decimal(10).log10() / Decimal(2).log10())

rawDescription: Is there a way to inhibit rounding in python?


code:
from lxml.html import fromstring

l = [
    """Carson Daly: Ben Schwartz, Soko, Jacob Escobedo (R 2/28/14)
'""",
    """Carson Daly: Wil Wheaton, the Birds of Satan, Courtney Kemp Agboh
"""
]

for html in l:
    tree = fromstring(html)
    results = ''
    for element in tree.xpath('//node()[preceding-sibling::b="Carson Daly" and following-sibling::br]'):
        if not isinstance(element, str):
            results += element.text.strip()
        else:
            text = element.strip(':')
            if text:
                results += text.strip()

    print results.split(', ')

rawDescription: Regular Expressions: Find Names in String using Python


code:
li = ['sea','mountain','desert',
      'Emma','Cathy','Kate',
      'HH','VVVVVVV','AAA',
      'round','flat','sharp',
      'nut','banana','apple',
      'red','purple','white',
      'hen','tiger']

maxel0 = max(len(li[i]) for i in xrange(0,len(li),3))
maxel1 = max(len(li[i]) for i in xrange(1,len(li),3))
maxel2 = max(len(li[i]) for i in xrange(2,len(li),3))
a,b = divmod(len(li),3)
itn = iter(li).next
form = '%%-%ds\t%%-%ds\t%%-%ds\n' % (maxel0,maxel1,maxel2)
print ''.join(form % (itn(),itn(),itn())
              for i in xrange(a))\
      + ('%%-%ds\t%%-%ds\t\n' %(maxel0,maxel1) % (itn(),itn()) if b==2
         else '%%-%ds\t\n' % maxel0 % itn() if b==1
         else '')

rawDescription: Print python list in groups of 3

description: Print python list in groups of 3


code:
from multiprocessing import Process
import threading
import time
import urllib
import urllib2

class Post:

    def __init__(self, website, data, mode):
        self.website = website
        self.data = data

        #mode is either "Simple"(Simple POST) or "Multiple"(Multi-thread POST)
        self.mode = mode

    def post(self):

        #post data
        req = urllib2.Request(self.website)
        open_url = urllib2.urlopen(req, self.data)

        if self.mode == "Multiple":
            time.sleep(0.001)

        #read HTMLData
        HTMLData = open_url.read()

        print "OK"

if __name__ == "__main__":

    current_post = Post("http://forum.xda-developers.com/login.php", "vb_login_username=test&vb_login_password&securitytoken=guest&do=login", \
                        "Process")
    #save the time before post data
    origin_time = time.time()

    if(current_post.mode == "Multiple"):

        #multithreading POST
        threads = list()
        for i in range(0, 10):
           thread = threading.Thread(target = current_post.post)
           thread.start()
           threads.append(thread)
        for thread in threads:
           thread.join()
        #calculate the time interval
        time_interval = time.time() - origin_time
        print time_interval

    if(current_post.mode == "Process"):

        #multiprocessing POST
        processes = list()
        for i in range(0, 10):
           process = Process(target=current_post.post)
           process.start()
           processes.append(process)
        for process in processes:
           process.join()
        #calculate the time interval
        time_interval = time.time() - origin_time
        print time_interval

    if(current_post.mode == "Simple"):

        #simple POST
        for i in range(0, 10):
            current_post.post()
        #calculate the time interval
        time_interval = time.time() - origin_time
        print time_interval

rawDescription: How to get a faster speed when using multi-threading in python

description: Get a faster speed when using multi-threading in python


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

rawDescription: Sorting values (for loop)

description: Sorting values (for loop)


code:
class A:
    l =[]

class B:
    l =[]

x = A()
y = A()
x.l.append(1)
print 'class A ', A.l, x.l, y.l

x = B()
y = B()
x.l = [1]
print 'class B ', B.l, x.l, y.l

rawDescription: Python inherited base class variables

description: Python inherited base class variables


code:
l = [
    {"key1": "yes", "key2": "yes", "key3": "yes"},
    {"key1": "yes", "key2": "no", "key3": "yes"},
    {"key1": "yes", "key2": "null", "key3": "yes"}
]

f = filter(lambda x: x['key2']!='yes', l)
print f
print len(f)

rawDescription: Json count elements depending on value of another using Python


code:
from timeout import timeout
import re

@timeout(0.01)
def match_re(regex,line):
    return re.match(regex,line)
try:
    print match_re('^tra.+$','tralalalalallalalal')
except Exception, e:
    print 'timeout!'

rawDescription: How to timeout function in python, timeout less than a second

description: Timeout function in python, timeout less than a second


code:
a='.'.join(x.encode('hex') for x in 'Hellö Wörld!')
a
print "".join(e.decode('hex') for e in a.split('.'))

rawDescription: Python: convert a dot separated hex values to string?


code:
import re
infile = open("input", "r")
for line in infile:
    m = re.match("going to the ((?:\w+\s*(?!to try)){1,3})", line)
    if m:
        print m.group(1).rstrip()

rawDescription: Regular Expressions: Match up to a word or a maximum number of words


code:
import os
from os.path import join
from datetime import datetime, timedelta
from operator import itemgetter

def list_user_files(username):
    for root, dirs, files in os.walk(username):
        for name in files:
            fullname = join(root, name)
            try:
                yield fullname, os.stat(fullname).st_mtime
            except (IOError, OSError) as e: # will catch WindowsError but more generic
                pass # Do something here...

ROOT = '/home'
CUTOFF = timedelta(days=30)
for userdir in os.listdir(ROOT):
    most_recent = max(list_user_files(join(ROOT, userdir)), key=itemgetter(1))
    print '{}: most recent file and timestamp is {}'.format(userdir, most_recent)
    if (datetime.now() - datetime.fromtimestamp(most_recent[1])) > CUTOFF:
        print '{} has not used their folder during cutoff period'.format(userdir)

rawDescription: How to find the most recently modified folder in a directory of directories (python)?

description: Find the most recently modified folder in a directory of directories (python)


code:
def questor_file():
    global nodes
    try:
        questor = open(questfile,'rb')
        try:
            nodes= pickle.load(questor)
            quest = nodes[0]
            questor.close()
            return quest
        except:
            print 'P.load failed'
            nodes = []

    except:
        print 'File did not open'
        nodes = []
    return Qnode('python')

rawDescription: Saving dict with nested class instances in Python 2.7


code:
def is_power(a,b):
    if a<b:
        return is_power(b,a)
    elif a==b:
        return True
    else:
        if a%b !=0:
            return False
        else:
            return is_power((a/b),b)

print is_power(2,32)

rawDescription: Why does this iteration didn't return anything out?


code:
for name in root.attrib:
    print '{0}="{1}"'.format(name, root.attrib[name])

rawDescription: Get root's attributes - elementtree

description: Get root's attributes - elementtree


code:
sql = ''' ... as above ... '''
places = Place.objects.raw(sql, [team.id])
for p in places:
    print p.id, bool(p.done)

rawDescription: Optimise two SQL queries and a list comprehension


code:
df
for name, gr in df.groupby("uid"):
    print name
    print gr

rawDescription: python pandas: diff by user in a DataFrame containing multiple users

description: Python pandas: diff by user in a DataFrame containing multiple users


code:
from collections import Counter

ages = [23,23,43,54,34,22,43,23]

histogram = Counter(ages)

for age,count in sorted(histogram.items()):
    print "Age: %d Number of people: %d"%(age,count)

rawDescription: Python setdefault not lvalue, any work-arounds?


code:
#!/usr/bin/env python

#Get the ranks for a list of (class, score) tuples sorted by score
#and return them in a dict
def get_ranks(sd):
    #The first class in the list has rank 1
    k, val = sd[0]
    r = 1
    rank = {k: r}

    for k, v in sd[1:]:
        #Only update the rank number if this value is
        #greater than the previous
        if v > val:
            val = v
            r += 1
        rank[k] = r
    return rank

def weighted_mean(a, b):
    return (0.50*a + 0.25*b) / 0.75

sorted_dict1 = [('class1', 15.17), ('class2', 15.95), ('class3', 15.95)]
sorted_dict2 = [('class2', 9.10), ('class3', 9.22), ('class1', 10.60)]

print sorted_dict1
print sorted_dict2

ranks1 = get_ranks(sorted_dict1)
ranks2 = get_ranks(sorted_dict2)

print ranks1
print ranks2

keys = sorted(k for k,v in sorted_dict1)

print [(k, weighted_mean(ranks1[k], ranks2[k])) for k in keys]

rawDescription: Retrieve the ranking of elements in various list to compute the weighted average of their ranking scores Python


code:
def print_value(row, col):
    print find_in_grid(root, row, col).get()

#...

height = 5
width = 1
for i in range(height): #Rows
    for j in range(width): #Columns
        b = Button(root, text="print value", command=lambda i=i,j=j: print_value(i,j), width=10)
        b.grid(row=i, column=j+1)

rawDescription: Getting the row of a tkinter button in grid on click


code:
import json
import urllib2

with open('urls.txt') as f:
    urls = [line.rstrip() for line in f]
with open('proxies.txt') as proxies:
    for line in proxies:
        proxy = json.loads(line)
        proxy_handler = urllib2.ProxyHandler(proxy)
        opener = urllib2.build_opener(proxy_handler)
        urllib2.install_opener(opener)
        for url in urls:
            try:
                data = urllib2.urlopen(url).read()
                print proxy, "-", data
            except:
                print proxy, "- not working"

rawDescription: How can I test this script that accesses urls through several different proxy servers?

description: Test this script that accesses urls through several different proxy servers


code:
regex.findall(ur"[^[:punct:] ]+|[[:punct:]]", u"""A \N{ARABIC SEMICOLON} B""")
regex.findall(ur"[^[:punct:] ]+|[[:punct:]]", u"""He said, "I don't!" """)

rawDescription: How to split string by space and treat special characters as a separate word in Python?

description: Split string by space and treat special characters as a separate word in Python


code:
import os

class View:
    def __init__(self, f, offset, length):
        self.f = f
        self.f_offset = offset
        self.offset = 0
        self.length = length

    def seek(self, offset, whence=0):
        if whence == os.SEEK_SET:
            self.offset = offset
        elif whence == os.SEEK_CUR:
            self.offset += offset
        elif whence == os.SEEK_END:
            self.offset = self.length+offset
        else:
            # Other values of whence should raise an IOError
            return self.f.seek(offset, whence)
        return self.f.seek(self.offset+self.f_offset, os.SEEK_SET)

    def tell(self):
        return self.offset

    def read(self, size=-1):
        self.seek(self.offset)
        if size<0:
            size = self.length-self.offset
        size = max(0, min(size, self.length-self.offset))
        self.offset += size
        return self.f.read(size)

if __name__ == "__main__":
    f = open('test.txt', 'r')

    views = []
    offsets = [i*11 for i in range(10)]

    for o in offsets:
        f.seek(o+1)
        length = int(f.read(1))
        views.append(View(f, o+2, length))

    f.seek(0)

    completes = {}
    for v in views:
        completes[v.f_offset] = v.read()
        v.seek(0)

    import collections
    strs = collections.defaultdict(str)
    for i in range(3):
        for v in views:
            strs[v.f_offset] += v.read(3)
    strs = dict(strs) # We want it to raise KeyErrors after that.

    for offset, s in completes.iteritems():
        print offset, strs[offset], completes[offset]
        assert strs[offset] == completes[offset], "Something went wrong!"

rawDescription: How can I treat a section of a file as though it's a file itself?

description: Treat a section of a file as though it's a file itself


code: print "The user's password is",password

rawDescription: Use ssh key to encrypt and decrypt a password


code:
with open(filename, 'rb') as searchfile:
    for line in searchfile:
        if 'searchphrase' in line:
            print line

rawDescription: Python--Need to Read and find data, and copy a file to another location (beginner)


code:
df
arr2D = np.column_stack((df['col1'],df['col2'],df['col1'],df['col3']))
out_list = np.vsplit(arr2D.reshape(-1,2),arr2D.shape[0])
print out_list

rawDescription: convert separate 1D np.arrays into a list of 2D np.arrays

description: Convert separate 1D np.arrays into a list of 2D np.arrays


code:
def busy_add(x,y, delay=0.01):
    for n in range(x):
       x += n
    for n in range(y):
       y -= n
    import time
    time.sleep(delay)
    return x + y

def busy_squared(x):
    import time, random
    time.sleep(2*random.random())
    return x*x

def squared(x):
    return x*x

def quad_factory(a=1, b=1, c=0):
    def quad(x):
        return a*x**2 + b*x + c
    return quad

square_plus_one = quad_factory(2,0,1)

def test1(pool):
    print pool
    print "x: %s\n" % str(x)
    print pool.map.__name__
    start = time.time()
    res = pool.map(squared, x)
    print "time to results:", time.time() - start
    print "y: %s\n" % str(res)
    print pool.imap.__name__
    start = time.time()
    res = pool.imap(squared, x)
    print "time to queue:", time.time() - start
    start = time.time()
    res = list(res)
    print "time to results:", time.time() - start
    print "y: %s\n" % str(res)
    print pool.amap.__name__
    start = time.time()
    res = pool.amap(squared, x)
    print "time to queue:", time.time() - start
    start = time.time()
    res = res.get()
    print "time to results:", time.time() - start
    print "y: %s\n" % str(res)

def test2(pool, items=4, delay=0):
    _x = range(-items/2,items/2,2)
    _y = range(len(_x))
    _d = [delay]*len(_x)
    print map
    res1 = map(busy_squared, _x)
    res2 = map(busy_add, _x, _y, _d)
    print pool.map
    _res1 = pool.map(busy_squared, _x)
    _res2 = pool.map(busy_add, _x, _y, _d)
    assert _res1 == res1
    assert _res2 == res2
    print pool.imap
    _res1 = pool.imap(busy_squared, _x)
    _res2 = pool.imap(busy_add, _x, _y, _d)
    assert list(_res1) == res1
    assert list(_res2) == res2
    print pool.amap
    _res1 = pool.amap(busy_squared, _x)
    _res2 = pool.amap(busy_add, _x, _y, _d)
    assert _res1.get() == res1
    assert _res2.get() == res2
    print ""

def test3(pool): # test against a function that should fail in pickle
    print pool
    print "x: %s\n" % str(x)
    print pool.map.__name__
    start = time.time()
    res = pool.map(square_plus_one, x)
    print "time to results:", time.time() - start
    print "y: %s\n" % str(res)

def test4(pool, maxtries, delay):
    print pool
    m = pool.amap(busy_add, x, x)
    tries = 0
    while not m.ready():
        time.sleep(delay)
        tries += 1
        print "TRY: %s" % tries
        if tries >= maxtries:
            print "TIMEOUT"
            break
    print m.get()

import time
x = range(18)
delay = 0.01
items = 20
maxtries = 20
from pathos.multiprocessing import ProcessingPool as Pool
pool = Pool(nodes=4)
test1(pool)
test2(pool, items, delay)
test3(pool)
test4(pool, maxtries, delay)

rawDescription: What can multiprocessing and dill do together?


code:
@CaptainHook
def sum(a, b):
    return a+b
sum(1, 2)
def aHook(*args, **kwargs):
    print "I am a hook!"
sum.hooks.append(aHook)
sum(1, 2)

rawDescription: How to mix *args, **kwargs and named arguments in decorator

description: Mix *args, **kwargs and named arguments in decorator


code:
def fill_rows(mtrx):

    # length of the sub array (= 4)
    sub_n = len(mtrx)

    # From 1 because 0 = head
    # Until sub_n -1 because the sub_n - 1 is = tail (remember, range is exclusive)
    for current_row in xrange(1, sub_n - 1):
        print "Current row: " + str(current_row)

        # -- it gets messy here --
        # get values of inner columns and filter out the zeros (matrix[row][n / 2] == 0 evaluates to False)
        col_vals_1 = [mtrx[row][n / 2] for row in xrange(0, sub_n) if mtrx[row][(n / 2)]]
        col_vals_2 = [mtrx[row][(n / 2) - 1] for row in xrange(0, sub_n) if mtrx[row][(n / 2) - 1]]

        col_vals = col_vals_1 + col_vals_2
        # print "Column Values = " + str(col_vals)

        row_vals = [mtrx[current_row][col] for col in xrange(0, n) if mtrx[current_row][col]]
        # print "Row Values = " + str(row_vals)

        # Find the possible values by getting the difference of the joined set of column + row values
        # with the range from (1 - 6).
        possible_values = list(set(xrange(1, n + 1)) - set(row_vals + col_vals))

        print "Possible acceptable values: " + str(possible_values)

        # Add values to matrix (pop to remove them)
        # After removing add to the list of row_values in order to check for the other columns.
        mtrx[current_row][(n-1)/2] = possible_values.pop()
        row_vals.append(mtrx[current_row][(n - 1) / 2])
        mtrx[current_row][(n-1)/2 + 1] = possible_values.pop()
        row_vals.append(mtrx[current_row][(n-1) / 2 + 1])

        # New possible values for remaining columns of the current row.
        possible_values = list(set(xrange(1, n + 1)) - set(row_vals))
        print "Possible acceptable values: " + str(possible_values)

        # Add values to the cells.
        mtrx[current_row][(n - 2)] = possible_values.pop()
        mtrx[current_row][1] = possible_values.pop()

    # return updated sub-matrix.
    return mtrx

rawDescription: Numbers in a Matrix

description: Numbers in a Matrix


code:
#!/usr/bin/env python
import subprocess
import re

def parse_arpline(line, hosts):
    match = re.search(r'\((\S+?)\)\s+at\s+(\S+)', line)
    if match is not None:
        ipaddr = match.group(1)
        mac = match.group(2)
        hosts.append((ipaddr, mac))
    return hosts

SUBNET = '192.168.1.0/24'  # Insert your subnet here
subprocess.Popen([r"nmap","-sP", SUBNET],stdout=subprocess.PIPE).communicate()
p = subprocess.Popen([r"arp","-an"],stdout=subprocess.PIPE).communicate()[0].split('\n')
hosts = []
ii = 0
for line in p:
    hosts = parse_arpline(line, hosts)
    ii +=1
# Iterate and do something with the hosts list
print hosts

rawDescription: Resolve mac address by host name

description: Resolve mac address by host name


code:
from Tkinter import *

root = Tk()
opt_list = ['opt1','opt2','opt3','opt4','opt5']
sel_list = []

def get_sel():
    sel_list.append(Lb1.curselection())
    root.destroy()

def cancel():
    root.destroy()

B = Button(root, text ="Submit", command = get_sel)
C = Button(root, text ="Cancel", command = cancel)
Lb1 = Listbox(root, selectmode=MULTIPLE)

for i,j in enumerate(opt_list):
    Lb1.insert(i,j)

Lb1.pack()
B.pack()
C.pack()

root.mainloop()

for i in sel_list[0]:
    print opt_list[int(i)]

rawDescription: Python: How to get multiple entries from listbox?


code:
from gpio import GPIO

def Relay():
    print "Relay: %s" % GPIO.__name__
    # Do stuff with GPIO

rawDescription: Python: How to use variables acros modules


code:
for para in soup.find_all('p'):
    if para.strong is not None:
        print para.strong.get_text()
        lines = filter(None, (t.strip() for t in para.find_all(text=True)))[1:]
        print '\n'.join(lines)
        print

rawDescription: Beautiful Soup (Python)

description: Beautiful Soup (Python)


code:
import pygame

#----------------------------------------------------------------------

class Player(object):

    def __init__(self, surface_rect):

        self.surface_rect = surface_rect

        self.image = pygame.image.load("player_one.png").convert()
        self.image.set_colorkey( (255,255,255) )

        self.rect = self.image.get_rect() # you get image width, height

        self.move_x = 15
        self.move_y = 15

        self.restart()

    #------------

    def restart(self):

        self.rect.x = 940
        self.rect.y = 240

    #------------

    def handle_events(self, event):
        player_moves = False

        if event.type == pygame.KEYDOWN:

            if event.key == pygame.K_DOWN:
                if self.rect.bottom < self.surface_rect.bottom: #470
                    self.rect.y += self.move_y
                    player_moves = True

            elif event.key == pygame.K_UP:
                if self.rect.top > self.surface_rect.top:
                    self.rect.y -= self.move_y
                    player_moves = True

            elif event.key == pygame.K_RIGHT:
                if self.rect.right < self.surface_rect.right:
                    self.rect.x += self.move_x
                    player_moves = True

            elif event.key == pygame.K_LEFT:
                if self.rect.left > self.surface_rect.left:
                    self.rect.x -= self.move_x
                    player_moves = True

            print "(debug): player: x, y:", self.rect.x, self.rect.y

        return player_moves
    #------------

    def draw(self, surface):
        surface.blit(self.image, self.rect)

#----------------------------------------------------------------------

rawDescription: Pygame enemy display random when player moves by keyboard


code:
def is_reverse(word1, word2):
   if len(word1) == len(word2):
     if word1 == word2[::-1]:
       return True
return False

file1 = open('List.txt')
for word1 in file1:
    word1 = word1.strip()
    word1 = word1.lower()
    file2 = open('List.txt')
    for word2 in file2:
      word2 = word2.strip()
      word2 = word2.lower()
      print word1 + word2
      if is_reverse(word1, word2):
             print word1 + ' is the opposite of ' + word2

rawDescription: Finding words that are the reverse of each other in a file


code:
aDict = {'a':[1,2,3],'b':[2,3,4],'c':[3,3,6]}
aList = [max(aDict[k]) for k in sorted(aDict.keys())]
print aList

rawDescription: How to iterate over a dictionary and find the max values python?

description: Iterate over a dictionary and find the max values python


code:
import urlparse
parsed = urlparse.urlparse("https://www.google.dk:80/barbaz")
replaced = parsed._replace(netloc="www.foo.dk:80")
print replaced

rawDescription: Changing hostname in a url

description: Changing hostname in a url


code:
import re

test = '''
BadLine
      property1=a
      property2=b
BadLine2
      property1=c
      property2=d
GOODLINE1
      property1=e
      property2=f
BadLine
      property1=a
      property2=b
BadLine2
      property1=c
      property2=d
GOODLINE2
      property1=e
      property2=f
'''

pattern = r'^(GOODLINE(?:[^\n]|\n )*)'

print re.compile(pattern, re.MULTILINE).findall(test)

rawDescription: Python RegEx: How to deal with lines

description: Python RegEx: How to deal with lines


code:
import sys

one, two, three = sys.argv[1:4] # grab indicies 1, 2, and 3
four = sys.argv[4:]
print one
print two
print three
print four

rawDescription: How to pass a list and other values as command line arguments?

description: Pass a list and other values as command line arguments


code:
import os, fnmatch

def get_all_files(path, pattern):
    datafiles = []

    for root,dirs,files in os.walk(path):
        for file in fnmatch.filter(files, pattern):
            pathname = os.path.join(root, file)
            filesize = os.stat(pathname).st_size
            datafiles.append([file, pathname, filesize])

    return datafiles

print get_all_files('.', 'something.*') # all files named 'something'

rawDescription: Getting files with same name irrespective of their extension


code:
from PySide import QtCore, QtGui

def function(arg=None):
    print 'function arg: %r'%arg

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

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

btn = button()

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

lbl = label()

rawDescription: When Signal Does Not Find its Slot

description: When Signal Does Not Find its Slot


code:
getClassDef("RootObj")
for x in _classdefs.keys():
  print _classdefs[x]

rawDescription: using dynamic python class definition and amfast dynamic class mapping and code generation to generate ActionScript class

description: Using dynamic python class definition and amfast dynamic class mapping and code generation to generate ActionScript class


code:
import csv
sample = '''\
Victoria's Regions,2004,2005,2006,2007
Gippsland,63354,47083,51517,54872
Goldfields,42625,36358,30358,36486
Grampians,64092,41773,29102,38058
Great Ocean Road,185456,153925,150268,167458
Melbourne,1236417,1263118,1357800,1377291
'''.splitlines(True)
maximum_value = None
reader = csv.DictReader(sample)
for row in reader:
    count, year = max((int(row[year]), year) for year in reader.fieldnames[1:])  # skip the first column
    if not maximum_value or count > maximum_value[0]:
        maximum_value = (count, row[reader.fieldnames[0]], year)

print "The greatest visitornumber was {} in {} in the year {}.".format(
    *maximum_value)

rawDescription: How to find maximum number from csv-read data in Python 2.7?

description: Find maximum number from csv-read data in Python 2.7


rawDescription: Generating all unique pair permutations

description: Generating all unique pair permutations


code:
import ast

class Visit(ast.NodeVisitor):
    def __init__(self):
        ast.NodeVisitor.__init__(self)
        self.s = set()
    def visit_Name(self,node):
        self.s.add(node.id)

with open('x.py') as f:
    a=ast.parse(f.read())
v = Visit()
v.visit(a)
print v.s

rawDescription: Using python to remove all strings and comments from python code


code:
from datetime import timedelta

# get closest match from "df2" to row from "df1" (as long as it's below the threshold)
def closest(row):
    matches = df2.loc[(df2.employee_id == row.employee_id) &
                      (df2.session_id == row.session_id)]

    deltas = matches.date_start_time - row.date_start_time
    deltas = deltas.loc[deltas <= timedelta(minutes=threshold)]

    try:
        return matches.loc[deltas.idxmin()]
    except ValueError:  # no items
        return row

# replace timestamps in "df1" with closest timestamps in "df2"
df1 = df1.apply(closest, axis=1)

# join
cols = ['date_start_time', 'employee_id', 'session_id']
print df1.merge(df2, on=cols, how='outer')[cols]

rawDescription: pandas merging based on a timestamp which do not match exactly

description: Pandas merging based on a timestamp which do not match exactly


code:
print list(WEEKDAYS)
print WEEKDAYS.fri
print WEEKDAYS.get_selected_values(52)

rawDescription: Representing a multi-select field for weekdays in a Django model


code:
x = next((dict_elem for dict_elem in list_above if dict_elem['name'] == reded), None)
if not x:
    print "No match found"

rawDescription: Concise Way of Get Matching Element in List


code:
seq = [['String1', 4], ['String2', 8], ['String3', 15], ['String4', 8]]
result = [s for s, i in seq if i == 8]
print result

rawDescription: Python Get row in a list by one of its attributes


code:
data = [['cups', 'cusp', 'cpus', 'cpsu', 'csup', 'cspu',],
        ['pups', 'pusp','upsp', 'upps', 'upsp', 'uspp']]

result = {each[0]:each[1:] for each in data}
print result

rawDescription: Python: Create Dictionary From List with [0] = Key and [1:]= Values


code:
from bs4 import BeautifulSoup as Soup

html = """

    sometext

            link1

            link2

            link3

    sometext2

            link4

            link5

"""
soup = Soup(html)

for span in soup.find_all('span', {'class': 'title'}):
    print span.text
    for li in span.next_sibling.next_sibling.find_all('li', {'class': 'bar'}):
        print "- %s % s" % (li.find('a').text, li.find('img').attrs['src'])

rawDescription: foreach group of elements in html page?

description: Foreach group of elements in html page


code:
intervals = [[100,200],[150,250],[300,400]]
intervalsSorted = sorted(intervals, key=lambda x: x[0]) # sort by start time
for x in range(1,len(intervalsSorted)):
    if intervalsSorted[x-1][1] > intervalsSorted[x][0]:
        print "{0} overlaps with {1}".format( intervals[x-1], intervals[x] )

# result: [100, 200] overlaps with [150, 250]

rawDescription: Checking for overlap between time spans

description: Checking for overlap between time spans


code:
for i in range(10):
    shuffle(A)
    print A

rawDescription: Itertools.permutations create n random solutions to the TSP


code:
print np.hstack((a, b)).shape
# (3, 4)

rawDescription: understanding numpy's dstack function

description: Understanding numpy's dstack function


code:
def format_rows(rows, gap, limit):
    split_rows = [row.split(',') for row in rows]
    # Splits each row up, by comma
    column_lengths = [max(col_len) for col_len in zip(*[map(len, row) for row in split_rows])]
    # Finds the maximum size of each column

    for row in split_rows:
        col_lengths = zip(row, column_lengths)[:limit]
        # Prints out only the first `limit` columns

        print ''.join(col.ljust(col_length + gap, ' ') for (col, col_length) in col_lengths)
        # Prints out the data, making sure there's a minimum of "gap" spaces
        # between each column

rawDescription: python yahoo finance format

description: Python yahoo finance format


code:
from collections import OrderedDict

out = []

for r in apts:
    row = OrderedDict([('id',''), ('price',''), ('sqft',''),
                       ('amenities',''),('ac',''),('pets','')])
    row['id']=r[0]
    for sr in r[1]:
        row[sr[0].lower().translate(None," ./")]=sr[1]
    out.append(row)

#print result
for o in out:
    s = ",".join(map(str, o.values()))
    print s

rawDescription: Converting nested python lists to database


code:
from django.db import connection
MyModel.objects.latest()
print connection.queries[-1]['sql']

rawDescription: Django Query using .order_by() and .latest()


code:
vars = {}
execfile('./vars.py',vars)
print vars['git_branch']

rawDescription: Getting variables from another python file WITHOUT importing


code:
import codecs

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB

trainfile = 'train.txt'
testfile = 'test.txt'

# Vectorizing data.
train = []
word_vectorizer = CountVectorizer(analyzer='word')
trainset = word_vectorizer.fit_transform(codecs.open(trainfile,'r','utf8'))
tags = ['bs','pt','es','sr']
print word_vectorizer.get_feature_names()

rawDescription: How to vectorize bigrams with the hashing-trick in scikit-learn?

description: Vectorize bigrams with the hashing-trick in scikit-learn


code:
nd = {}
nd['john'] = 109090
nd['albert'] = 1900
nd['Tim'] = 18000

print sorted(nd.items(), key=lambda x: x[1])

rawDescription: dictionary help for python writing a code

description: Dictionary help for python writing a code


code: print sum(i for i in fibo() if not i%2)

rawDescription: Python program to find fibonacci series. More Pythonic way


code:
print "1 = addition"
print "2 = subtraction"
print "3 = multiplication"
print "4 = division"
print "5 = Exit program\n"

def maths(choice):
    if choice == 1: #if operation chose is addition then this line will exacute
       int1 = input("Enter first integer:")
       int2 = input ("Enter second integer: ")
       sum = int1 + int2
       print "Sum is:", sum

    elif choice == 2: #if operation chose is subtraction then this line will exacute
       int1 = input("Enter first integer: ")
       int2 = input("Enter second integer: ")
       dif = int1 - int2
       print "Difference is:", dif

    elif choice == 3: #if operation chose is multiplication then this line will exacute
       int1 = input("Enter first integer: ")
       int2 = input("Enter second integer: ")
       mult = int1 * int2
       print "Multiplication is:", mult

    elif choice == 4: #if operation chose is division then this line will exacute
       int1 = input("Enter first integer: ")
       int2 = input ("Enter second integer: ")
       div = int1 / int2
       print "Division is: %.2f" % div

    elif choice == 5:
       print "goodbye"
       quit()

while True: # "While True, repeat everything below":
    maths(input("What operation would you like to perform?: "))

rawDescription: How do I repeat my initial input code?

description: Repeat my initial input code


code:
import networkx as nx

g = Graph()
g.add_edges_from([(1, 2), (2, 3), (4,5), (1, 5), (2, 4)])
# Nodes are automatically added

for edge in g.edges_iter():
    print edge
    print 'Node 1:', edge[0]
    print 'Node 2:', edge[1]

rawDescription: Getting the nodes at the end of an edge g.edge_iter


code:
min([3, 5, 2, 1, 5])
d = {'a': 1, 'b': 2, 'c': 3}
for i in d:
    print i
d.get('b')
d.get('d')  # Nothing is returned
min(d, key=d.get)

rawDescription: how does the python min function works

description: How does the python min function works


code:
def functionl(*args):
    return list(set(args))

print functionl(1)                # [1]
print functionl(1, 2, 3, 1)       # [1, 2, 3]

rawDescription: making a function that takes a list of any size as an argument Python 3

description: Making a function that takes a list of any size as an argument Python 3


code:
import subprocess
import os

for file_item in os.listdir('scripts'):
   script = os.sep.join(['scripts', file_item])
   return_value = subprocess.call(['python', script])
   print "OUTPUT: " + str(return_value)

rawDescription: teminate subprocess.call( 'python script") and continure with next test script query

description: Teminate subprocess.call( 'python script") and continure with next test script query


code:
x = Booking.objects.filter(date_select='2011-12-3')
print x.count()

rawDescription: how to specify values in objects in django: is [] not equal to None?

description: Specify values in objects in django: is [] not equal to None


code:
import serial
ser = serial.Serial('COM7', 9600)

try:
    result=ser.readline()
    pieces=result.split(" \t")
    pieces = map(float, pieces)
    print pieces
    if pieces[0] == 5.0:
        print "Yes"
    else:
        print "No"
except:
    print "Failed to get data from Arduino!"

rawDescription: Map serial port data into integer

description: Map serial port data into integer


rawDescription: Average tuple of tuples

description: Average tuple of tuples


code:
from xml.etree import ElementTree
import re

def proper_SN(elem):
    if re.search('\d{6}', elem.text):
        return True
    return False

tree = ElementTree.parse('data.xml')
serial = tree.find('DeviceData/Info/SerialNumber').text
engine = tree.find('DeviceData/Info/EngineVersion').text
media = tree.find('DeviceData/Info/MediaType').text

if proper_SN:
    serstr = "good"
else:
    serstr = "bad"

print "Found a %s serial number (%s), with engine %s and media %s" % (serstr, serial, engine, media)

rawDescription: Checking XML Nodes with Script using REGEX


code:
class Object(object):
    speed = 0

a = Object()
b = Object()
c = Object()

Object.speed = 5
print a.speed

rawDescription: Changing variables in multiple Python instances


code:
def flush():
    import sys, tty, termios, fcntl, os
    fd = sys.stdin.fileno()
    old_attr = termios.tcgetattr(fd)
    old_fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    try:
        tty.setraw(fd)
        fcntl.fcntl(fd, fcntl.F_SETFL, old_fl | os.O_NONBLOCK)
        inp = sys.stdin.read()
    except IOError, ex1:  #if no chars available generates exception
        try: #need to catch correct exception
            errno = ex1.args[0] #if args not sequence get TypeError
            if errno == 35:
                return '' #No characters available
            else:
                raise #re-raise exception ex1
        except TypeError, ex2:  #catch args[0] mismatch above
            raise ex1 #ignore TypeError, re-raise exception ex1
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_attr)
        fcntl.fcntl(fd, fcntl.F_SETFL, old_fl)
    return inp

rawDescription: Need character-by-character keyboard input that interacts well with paste and ANSI escape sequences


code:
from itertools import chain
from collections import defaultdict

import nltk
from nltk.classify import MaxentClassifier, accuracy
from nltk.corpus import movie_reviews

def bag_of_words(words):
    """
    Change a document into a BOW feature vector represented by a dict object.
    """
    return dict([(word, True) for word in words])

def label_feats_from_corpus(corp, feature_detector=bag_of_words):
    """
    Change the corpus into a feature matrix. Sometimes the proceess is
    known as vectorization. The default is the use BOW features.
    """
    label_feats = defaultdict(list)
    for label in corp.categories():
        for fileid in corp.fileids(categories=[label]):
            feats = feature_detector(corp.words(fileids=[fileid]))
            label_feats[label].append(feats)
    return label_feats

def split_label_feats(lfeats, split=0.75):
    """
    Splits corpus into train and test portion.
    This module is used after using `label_feats_from_corpus`.
    """
    train_feats = []
    test_feats = []
    for label, feats in lfeats.iteritems():
        cutoff = int(len(feats) * split)
        train_feats.extend([(feat, label) for feat in feats[:cutoff]])
        test_feats.extend([(feat, label) for feat in feats[cutoff:]])
    return train_feats, test_feats

# Extract features from corpus and for each document label it with the appropriate labels.
label_feats = label_feats_from_corpus(movie_reviews)
'''
for label in label_feats:
    for document in label_feats[label]:
        print label, document
        break
    break
'''

# Let's split the data up into train and test.
train_documents, test_documents = split_label_feats(label_feats)
'''
# Now we see that the `split_label_feats` change the key value structure such that each iteration of train_feats gives us a document with a tuple of the (features, label)
for features, label in train_documents:
    print label, features
    break

print len(train_documents)
print len(test_documents)
# Get the number of documents in movie_review corpus
num_docs_in_corpus = len(list(chain(*[movie_reviews.fileids(categories=[cat]) for cat in movie_reviews.categories()])))
print len(train_documents) + len(test_documents) == num_docs_in_corpus
'''

# To train the tagger.
me_classifier = nltk.MaxentClassifier.train(train_documents, algorithm='iis', trace=0, max_iter=3)
print accuracy(me_classifier, test_feats)

rawDescription: My Maxent Classifier works fine with gis algorithm but does not work with iis algorithm. It is not throwing any error, just some warnings


rawDescription: PHP list() equivalent in Python

description: PHP list() equivalent in Python


code:
import re
import numpy

def pbm2numpy(filename):
    """
    Read a PBM into a numpy array.  Only supports ASCII PBM for now.
    """
    fin = None
    debug = True

    try:
        fin = open(filename, 'r')

        while True:
            header = fin.readline().strip()
            if header.startswith('#'):
                continue
            elif header == 'P1':
                break
            elif header == 'P4':
                assert False, 'Raw PBM reading not implemented yet'
            else:
                #
                # Unexpected header.
                #
                if debug:
                    print 'Bad mode:', header
                return None

        rows, cols = 0, 0
        while True:
            header = fin.readline().strip()
            if header.startswith('#'):
                continue

            match = re.match('^(\d+) (\d+)$', header)
            if match == None:
                if debug:
                    print 'Bad size:', repr(header)
                return None

            cols, rows = match.groups()
            break

        rows = int(rows)
        cols = int(cols)

        assert (rows, cols) != (0, 0)

        if debug:
            print 'Rows: %d, cols: %d' % (rows, cols)

        #
        # Initialise a 2D numpy array
        #
        result = numpy.zeros((rows, cols), numpy.int8)

        pxs = []

        #
        # Read to EOF.
        #
        while True:
            line = fin.readline().strip()
            if line == '':
                break

            for c in line:
                if c == ' ':
                    continue

                pxs.append(int(c))

        if len(pxs) != rows*cols:
            if debug:
                print 'Insufficient image data:', len(pxs)
            return None

        for r in range(rows):
            for c in range(cols):
                #
                # Index into the numpy array and set the pixel value.
                #
                result[r, c] = pxs[r*cols + c]

        return result

    finally:
        if fin != None:
            fin.close()
        fin = None

    return None

rawDescription: How to write PIL image filter for plain pgm format?

description: Write PIL image filter for plain pgm format


code:
import sympy as sy

x = sy.symbols('x')
fx = x**3 - x - 1

def NewtonRaphson(fx,p0,tolerancia,iteracionesMaximas):

    for i in xrange(iteracionesMaximas):

        y = fx.subs(x, p0)
        yy = sy.diff(fx,x).subs(x, p0)
        p = p0 - (y / yy)

        if sy.Abs(p-p0) < tolerancia:
            print "Se encontró la raíz y={raiz} luego de {n} iteraciones".format(raiz=p, n=i-1)
            return

        print "{i}\t{p}\t{p0}".format(i=i+1,p=p,p0=p0)
        p0 = p

    print "El método falló luego de {i} iteraciones".format(i=i-1)

NewtonRaphson(fx,1.7,10**(-4),17)

rawDescription: Evaluation of symbolic Differentiation with Sympy in Python


code:
from collections import defaultdict

lod = [
    {"US": {"Intial0": 12.515}},
    {"GE": {"Intial0": 11.861}},
    {"US": {"Final0": 81.159}},
    {"GE": {"Final0": 12.9835}}]

output = defaultdict(dict)

for d in lod:
    output[d.keys()[0]].update(d.values()[0])

print output

rawDescription: Merge list of dict into one dict in python


code:
from ephem import *
import datetime
import itertools
import math

zodiac = 'AR TA GE CN LE VI LI SC SG CP AQ PI'.split()

def format_zodiacal_longitude(longitude):
    "Format longitude in zodiacal form (like '00AR00') and return as a string."
    l = math.degrees(longitude.norm)
    degrees = int(l % 30)
    sign = zodiac[int(l / 30)]
    minutes = int(round((l % 1) * 60))
    return '{0:02}{1}{2:02}'.format(degrees, sign, minutes)

def format_angle_as_time(a):
    """Format angle as hours:minutes:seconds and return it as a string."""
    a = math.degrees(a) / 15.0
    hours = int(a)
    minutes = int((a % 1) * 60)
    seconds = int(((a * 60) % 1) * 60)
    return '{0:02}:{1:02}:{2:02}'.format(hours, minutes, seconds)

def print_ephemeris_for_date(date, bodies):
    date = Date(date)
    print datetime.datetime(*date.tuple()[:3]).strftime('%A')[:2],
    print '{0:02}'.format(date.tuple()[2]),
    greenwich = Observer()
    greenwich.date = date
    print format_angle_as_time(greenwich.sidereal_time()),
    for b in bodies:
        b.compute(date, date)
        print format_zodiacal_longitude(Ecliptic(b).long),
    print

def print_ephemeris_for_month(year, month, bodies):
    print
    print (datetime.date(year, month, 1).strftime('%B %Y').upper()
           .center(14 + len(bodies) * 7))
    print
    print 'DATE  SID.TIME',
    for b in bodies:
        print '{0: <6}'.format(b.name[:6].upper()),
    print
    for day in itertools.count(1):
        try:
            datetuple = (year, month, day)
            datetime.date(*datetuple)
            print_ephemeris_for_date(datetuple, bodies)
        except ValueError:
            break

def print_ephemeris_for_year(year):
    bodies = [Sun(), Moon(), Mercury(), Venus(), Mars(), Jupiter(),
              Saturn(), Uranus(), Neptune(), Pluto()]
    for month in xrange(1, 13):
        print_ephemeris_for_month(year, month, bodies)
        print

rawDescription: How to calculate longitude using PyEphem

description: Calculate longitude using PyEphem


code:
d = {'apple': 'red',
'orange': 'orange',
'lemon': 'yellow',
'milk': 'white',
'coffee': 'brown'}

d['fruits'] = [d['apple'], d['orange'], d['lemon']]

print d['fruits']

rawDescription: dict of internal keys

description: Dict of internal keys


code:
fh  = open('Documents/import.txt').read()
the_list = []
for line in fh.split('\n'):
    print line.strip()
    splits = line.split()
    if  len(splits) ==1 and splits[0]== line.strip():
        splits = line.strip().split(',')
    if splits:the_list.append(splits)

for i in range(len(the_list)):
    print the_list[i]
    if  the_list[i][-1]=='':
        the_list[i].pop(-1)
        the_list[i].extend(the_list[i+1])
        i += 1

print the_list

rawDescription: Python Data Import

description: Python Data Import


code:
def get_function_arg_data(func):
    import inspect
    func = getattr(func, '_original_f', func) # use saved original if decorated
    func_data = inspect.getargspec(func)
    args_name = func_data.args #func argument list
    args_default = func_data.defaults #funcargument default data list
    return args_name, args_default

def showduration(user_function):
    '''show time duration decorator'''
    import time
    def wrapped_f(*args, **kwargs):
        t1 = time.clock()
        result = user_function(*args, **kwargs)
        print "%s()_Time: %0.5f"%(user_function.__name__, time.clock()-t1)
        return result
    wrapped_f._original_f = user_function  # save original function
    return wrapped_f

def foo(para1, para2=5, para3=7):
    for i in range(1000):
        s = para1+para2+para3
    return s

@showduration
def bar(para1, para2, para3):
    for i in range(1000):
        s=para1+para2+para3
    return s

print 'get_function_arg_data(foo):', get_function_arg_data(foo)
print 'get_function_arg_data(bar):', get_function_arg_data(bar)

rawDescription: How to get through decorator to get the underlying function arguments information?

description: Get through decorator to get the underlying function arguments information


code:
import nltk, collections
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures

def bag_of_words(words):
    return dict([(word, True) for word in words])

def bag_of_bigrams_words(words, score_fn=BigramAssocMeasures.chi_sq, n=200):
    bigram_finder = BigramCollocationFinder.from_words(words)
    bigrams = bigram_finder.nbest(score_fn, n)
    words = [i for i in words]
    return bag_of_words(words + bigrams)

def label_feats_from_corpus(corp, feature_detector=bag_of_bigrams_words):
    label_feats = collections.defaultdict(list)
    for label in corp.categories():
        for fileid in corp.fileids(categories=[label]):
            feats = feature_detector(corp.words(fileids=[fileid]))
            label_feats[label].append(feats)
    return label_feats

from nltk.corpus import movie_reviews
lfeats = label_feats_from_corpus(movie_reviews)
print lfeats

rawDescription: NLTK bag of bigrams words function raises "Don't know how to concatenate types" error - python


code:
item = Item.objects.get(pk=1)
item_old = Item.objects.get(pk=1)
print item.my_attribute
item.my_attribute = 'bar'
get_changes_between_objects(item, item_old)

rawDescription: Compare old and updated fields in Django model


code:
def test_var_args_call(*args):
    print ' '.join(map(str, args))

rawDescription: Function with extensive arguments

description: Function with extensive arguments


code:
packet = event.parsed
tcp_found = packet.find('tcp')
if tcp_found:
  if tcp_found.ACK:
    print "ACK found"
    # do your things

rawDescription: Identify ACK packets from wget in Mininet


code:
import asyncio
import multiprocessing
from concurrent.futures import ProcessPoolExecutor
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from datetime import datetime
import time

def day_limits():
        variable.value = 90
        print ('Day Variable: ',variable.value)

def night_limits():
        variable.value = 65
        print ('Night Variable: ',variable.value)

def thread_2():
    while True:
        c_hour = int(datetime.now().strftime("%H"))
        c_min = int(datetime.now().strftime("%M"))
        c_sec = int(datetime.now().strftime("%S"))

        print ('%02d:%02d:%02d - Variable: %d ' % (c_hour,c_min,c_sec,variable.value))

        time.sleep(2)

if __name__ == "__main__":
    variable = multiprocessing.Value('i', 60)

    scheduler = AsyncIOScheduler()
    scheduler.add_job(day_limits, 'cron', hour=7,misfire_grace_time=3600,timezone='GB')
    scheduler.add_job(night_limits, 'cron', hour=19, minute=32,misfire_grace_time=3600,timezone='GB')
    scheduler.start()

    scheduler.print_jobs()

    executor = ProcessPoolExecutor(1)
    loop = asyncio.get_event_loop()
    baa = asyncio.async(loop.run_in_executor(executor, thread_2))

    try:
        loop.run_forever()

    except (KeyboardInterrupt, Exception):
        loop.stop()
        scheduler.shutdown()

rawDescription: Python 3 - Global Variables with AsyncIO/APScheduler


code: print s % (x)

rawDescription: Using Python String Formatting with Lists


code:
import socket
import sys

HOST, PORT = "localhost", 12345
data = 'da bomb'

# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# As you can see, there is no connect() call; UDP has no connections.
# Instead, data is directly sent to the recipient via sendto().
sock.sendto(data + "\n", (HOST, PORT))
received = sock.recv(1024)

print "Sent:     %s" % data
print "Received: %s" % received

rawDescription: python listen 2 port same file

description: Python listen 2 port same file


code:
import requests

r = requests.get(url, stream=True)

for line in r.iter_lines():
    if line: print line

rawDescription: Python read website data line by line when available


code:
for col in a.dtype.names:
    print col, np.all(a[col] == b[col])

# Prints:
# a True
# b True
# c True

rawDescription: Reading a binary file with numpy structured array


rawDescription: Format float with padding and justification


code:
import re

s1 = """abc 5895 kilimandjaro 81 little"""

s2 = """abc 145 abcdefghuj 87 short
kim 1498 witgenstein 893 sun
oh 142 stackoverflow 89 kol  871 kutr"""

print '========= 1 ============'
for s in (s1,s2,'75 moon 56 mars 10 pluto'):
    print s
    m = re.findall(r'(\d+)\s([a-z]{7,})',s)
    print m
    for i,j in m:     ##separate the two elemnts
        if m == [(i,j)]:   ## if the total match result was equivalent to the i,j result
                      ## then that is fine
          print  '===> ',(i,j)
        else:         ## if the total match result is not the same as i,j then I only want the
                      ##final result to be returned
          print '===> ',m[-1]    ## Not sure what to put here to only return the final result
          break
    else:
        print '===>  No match'
    print

print '========= 2 ============'
for s in (s1,s2,'75 moon 56 mars 10 pluto'):
    print s
    m = re.findall(r'(\d+)\s([a-z]{7,})',s)
    print m
    if m:
        print '===> ',m[-1]
    else:
        print '===>  No match'
    print

print '========= 3 ============'
for s in (s1,s2,'75 moon 56 mars 10 pluto'):
    print s
    for m in re.finditer(r'(\d+)\s([a-z]{7,})|^',s):
        pass
    print m.groups()
    print

print '========= 4 ============'
for s in (s1,s2,'75 moon 56 mars 10 pluto'):
    print s
    print re.search(r'(\d+)\s([a-z]{7,})(?!.*?\d+\s[a-z]{7,})|$',s).groups()
    print

rawDescription: Return only the final result in python re.findall command


code:
# Retry utility
# set logging for `retry` channel
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('retry')

# Define Exception class for retry
class RetryException(Exception):
    u_str = "Exception ({}) raised after {} tries."

    def __init__(self, exp, max_retry):
        self.exp = exp
        self.max_retry = max_retry
    def __unicode__(self):
        return self.u_str.format(self.exp, self.max_retry)
    def __str__(self):
        return self.__unicode__()

# Define retry util function
def retry_func(func, max_retry=10):
    """
    @param func: The function that needs to be retry
    @param max_retry: Maximum retry of `func` function, default is `10`
    @return: func
    @raise: RetryException if retries exceeded than max_retry
    """
    for retry in range(1, max_retry + 1):
        try:
            return func()
        except Exception, e:
            logger.info('Failed to call {}, in retry({}/{})'.format(func.func,
                                                           retry, max_retry))
    else:
        raise RetryException(e, max_retry)

rawDescription: Pythonic way of retry running a function


rawDescription: Python regular expression grouping?

description: Python regular expression grouping


code:
content = u'\xe5\xb1\x82\xe5\x8f\xa0\xe6\xa0\xb7\xe5\xbc\x8f\xe8\xa1\xa8'
content.encode('latin1')
content.encode('latin1').decode('utf8')
print content.encode('latin1').decode('utf8')

rawDescription: Convert unicode with utf-8 string as content to str


code:
import argparse

parser = argparse.ArgumentParser()

class DefaultListAction(argparse.Action):
    CHOICES = ['clear','copy','dump','lock']
    def __call__(self, parser, namespace, values, option_string=None):
        if values:
            for value in values:
                if value not in self.CHOICES:
                    message = ("invalid choice: {0!r} (choose from {1})"
                               .format(value,
                                       ', '.join([repr(action)
                                                  for action in self.CHOICES])))

                    raise argparse.ArgumentError(self, message)
            setattr(namespace, self.dest, values)

parser.add_argument('actions', nargs='*', action=DefaultListAction,
                    default = ['dump', 'clear'],
                    metavar='ACTION')

print parser.parse_args([])
print parser.parse_args(['lock'])

rawDescription: python argparse - optional append argument with choices

description: Python argparse - optional append argument with choices


code:
# get input and join all converted char from generator
while True:
    phone = raw_input('enter phone number in the format xxxxxxx, or enter "end" for termination ').lower()

    if phone == 'end':
        break

    print ''.join(list(alph_to_num(phone)))

rawDescription: Python 2.7 Convert Letters to Phone Numbers


code:
import sys
import time
from urllib2 import URLError
from httplib import BadStatusLine
import json
import twitter

def oauth_login():
    CONSUMER_KEY = ''
    CONSUMER_SECRET = ''
    OAUTH_TOKEN = ''
    OAUTH_TOKEN_SECRET = ''
    auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET,
                               CONSUMER_KEY, CONSUMER_SECRET)
    twitter_api = twitter.Twitter(auth=auth)
    return twitter_api

def make_twitter_request(twitter_api_func, max_errors=10, *args, **kw):
# A nested helper function that handles common HTTPErrors. Return an updated
# value for wait_period if the problem is a 500 level error. Block until the
# rate limit is reset if it's a rate limiting issue (429 error). Returns None
# for 401 and 404 errors, which requires special handling by the caller.
    def handle_twitter_http_error(e, wait_period=2, sleep_when_rate_limited=True):
        if wait_period > 3600: # Seconds
            print >> sys.stderr, 'Too many retries. Quitting.'
            raise e
# See https://dev.twitter.com/docs/error-codes-responses for common codes
        if e.e.code == 401:

            print >> sys.stderr, 'Encountered 401 Error (Not Authorized)'
            return None
        elif e.e.code == 404:
            print >> sys.stderr, 'Encountered 404 Error (Not Found)'
            return None
        elif e.e.code == 429:
            print >> sys.stderr, 'Encountered 429 Error (Rate Limit Exceeded)'
            if sleep_when_rate_limited:
                print >> sys.stderr, "Retrying in 15 minutes...ZzZ..."
                sys.stderr.flush()
                time.sleep(60*15 + 5)
                print >> sys.stderr, '...ZzZ...Awake now and trying again.'
                return 2
            else:
                raise e # Caller must handle the rate limiting issue
        elif e.e.code in (500, 502, 503, 504):
            print >> sys.stderr, 'Encountered %iError. Retrying in %iseconds' %\
            (e.e.code, wait_period)
            time.sleep(wait_period)
            wait_period *= 1.5
            return wait_period
        else:
            raise e
# End of nested helper function
    wait_period = 2
    error_count = 0
    while True:
        try:
            return twitter_api_func(*args, **kw)
        except twitter.api.TwitterHTTPError, e:
            error_count = 0
            wait_period = handle_twitter_http_error(e, wait_period)
            if wait_period is None:
                return
        except URLError, e:
            error_count += 1
            print >> sys.stderr, "URLError encountered. Continuing."
            if error_count > max_errors:
                print >> sys.stderr, "Too many consecutive errors...bailing out."
                raise
        except BadStatusLine, e:
            error_count += 1
            print >> sys.stderr, "BadStatusLine encountered. Continuing."
            if error_count > max_errors:
                print >> sys.stderr, "Too many consecutive errors...bailing out."
                raise

rawDescription: How to get follower count using tweepy

description: Get follower count using tweepy


code:
for name, score in sorted(names.iteritems(), key=lambda (k, v): (-v, k))[:10]:
    print name, score

rawDescription: How to get the top 10 students in the class using Python dict

description: Get the top 10 students in the class using Python dict


code: print ["".join(a) for a in combinations(["hel", "lo", "bye"], 2)]

rawDescription: Generate all possible strings from a list of token


code:
response = urllib.urlopen(URL, parameter)
print response.read()

rawDescription: send xml file to http using python

description: Send xml file to http using python


code:
class Foo(object):
    properties = []
    def __new__(cls, *args):
        instance = object.__new__(cls, *args)
        for p in cls.properties:
            setattr(instance, p, 0)
        return instance

class MyFoo(Foo):
    properties = ['bar', 'baz']

    def __init__(self):
        pass

f=MyFoo()
print dir(f)

rawDescription: Common practice of __new__ constructor?

description: Common practice of __new__ constructor


code:
for name in files:
    with open(name, 'r') as f:
        matches = re.findall("\d{2}-\d{8}", f.read())
        for mt in matches:
            print mt

rawDescription: Python Regex And encode

description: Python Regex And encode


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

header_counter = defaultdict(Counter)

with open('filename.csv') as input_file:
    r = csv.reader(input_file, delimiter=',')
    # read headers
    headers = next(r)
    for row in r:
        # count values for each row to add in header context
        row_val = sum([w.isdigit() for w in row])
        # zip each row with headers to know where to count
        for header, val in zip(headers, row):
            # count only non-digits
            if not any(map(str.isdigit, val)):
                header_counter[header].update({val: row_val})

for k, v in header_counter.iteritems():
    print k, v

rawDescription: Get counts of strings in each CSV column using Python


code:
list = [{1,2,3},{2,3,4},{3,4,5},{4,5,6}]
b = []
[b.append(x) for c in list for x in c if x not in b]
print b # or set(b)

rawDescription: intersection of multiple sets in a list

description: Intersection of multiple sets in a list


code:
p = Popen(['cat'], stdin=PIPE, stdout=PIPE, stderr=STDOUT)
stdout, stderr = p.communicate(input='passed_string')
print stdout

rawDescription: How to get the output from .jar execution in python codes?

description: Get the output from .jar execution in python codes


code:
import numpy as np
x = np.arange(16).reshape(4, 4)

xx = x.reshape(len(x) // 2, 2, x.shape[1] // 2, 2).transpose(0, 2, 1, 3).reshape(len(x) // 2, x.shape[1] // 2, -1).mean(-1)

print xx

rawDescription: Interpolation of values when zooming down


code:
hb = plt.hexbin(x, y)
print hb.norm.vmin, hb.norm.vmax

rawDescription: How do I normalize a hexbin plot?

description: Normalize a hexbin plot


code:
print matching_link.string
print matching_link['href']

rawDescription: Beautiful Soup and searching in results

description: Beautiful Soup and searching in results


code:
proc = subprocess.Popen(['scp', '-o BatchMode=yes',
                                'user@server:/location/file.txt',
                                '/someplace/file.txt'],
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
proc.wait()
print 'result: %s' % repr(proc.stderr.readline())

rawDescription: Python subprocess + scp - can't read all output


code:
from collections import Counter, defaultdict

def test_counter(s):
    return Counter(s)

def test_get(s):
    res = {}
    for char in s:
        res[char] = res.get(char, 0) + 1
    return res

def test_in(s):
    res = {}
    for char in s:
        if char in res:
            res[char] += 1
        else:
            res[char] = 1
    return res

def test_defaultdict(s):
    res = defaultdict(int)
    for char in s:
        res[char] += 1
    return res

s = open('/usr/share/dict/words').read()
#eof

import timeit

test = lambda f: timeit.timeit(f + '(s)', setup, number=10)
setup = open(__file__).read().split("#eof")[0]
results = ['%.4f %s' % (test(f), f) for f in dir() if f.startswith('test_')]
print  '\n'.join(sorted(results))

rawDescription: Python: no. of occurences of each character in a string


code:
def foo():
  print "Foo"

def bar(x):
  print x

args = ()
func = foo
func(*args)

func = bar
args = ('a',)
func(*args)

rawDescription: Python function as a variable - different number of arguments


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

pattern = r"^([A-Za-z]+)"

text = """A  AH0
A'S  EY1 Z
A(2)  EY1
A.  EY1
A.'S  EY1 Z
A.S  EY1 Z
A42128  EY1 F AO1 R T UW1 W AH1 N T UW1 EY1 T
AAA  T R IH2 P AH0 L EY1
AABERG  AA1 B ER0 G
AACHEN  AA1 K AH0 N
AAKER  AA1 K ER0
AALSETH  AA1 L S EH0 TH
AAMODT  AA1 M AH0 T
AANCOR  AA1 N K AO2 R
AARDEMA  AA0 R D EH1 M AH0"""

def main():
    print re.findall(pattern, text, re.MULTILINE)

if __name__ == '__main__':
    main()

rawDescription: Python: A good regular expression for text parsing in this example


code:
from lxml import html
import requests

page = requests.get("http://www.farozon.se/lunchmeny-20207064")
tree = html.fromstring(page.text)

days = tree.cssselect("#block_82470858 table tr")[1:-1]
for item in days:
    cells = item.findall('td')
    day = cells[0].text_content().strip()
    dishes = cells[-1].text_content().strip()

    print day
    print dishes
    print "----"

rawDescription: Output of lxml in Python 2.7

description: Output of lxml in Python 2.7


code:
import pyperclip
print pyperclip.paste().split(" ")

rawDescription: Is there a way to convert the clipboard content into list in the run in Python?


code:
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from mixer.backend.flask import mixer

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'

db = SQLAlchemy(app)
mixer.init_app(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    def __repr__(self):
        return '<User %r>' % self.username

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
        user = mixer.blend(User)
        print user.id, user.username

        # Prints: 1 collins1995

rawDescription: Receiving null values from python mixer

description: Receiving null values from python mixer


code: print sorted(l, key=lambda item: item[1])

rawDescription: Most pythonic way to reorder repeating list


code:
from collections import defaultdict
from bisect import bisect_left

def count_intervals(sequence, intervals):
    count = defaultdict(int)
    intervals.sort()
    for item in sequence:
        pos = bisect_left(intervals, item)
        if pos == len(intervals):
            count[None] += 1
        else:
            count[intervals[pos]] += 1
    return count

data = [4,4,1,18,2,15,6,14,2,16,2,17,12,3,12,4,15,5,17]
print count_intervals(data, [10, 20])

rawDescription: Counting number of values between interval


rawDescription: Python - Extract Main Language Code from HTTP / Browser


code:
def generator(howmany):
    for x in xrange(howmany):
        yield x

g = generator(10)

with open('output.txt', 'w') as f:
    for x in g:
        f.write(str(x))

with open('output.txt', 'r') as f:
    print f.readlines()

rawDescription: Python: How do I save generator output into text file?


code:
import re
pattern = re.compile('(?P<prefix>.*)RESPOND(?P<middle>.*?)=(?P<postfix>.*)')

msg = 'MFS: *CFSRES INC0020 01/12/14 07:51 RESPOND TEST ONLY, ALARM LEVEL: 1, 123 TESTSTREET TESTTOWN ,MAP: ,TG 100, == TESTING : UNIT HERE'

match = pattern.match(msg)

if match:
    print '[PREFIX]', match.group('prefix')
    print '[MIDDLE]', match.group('middle')
    print '[POSTFIX]', match.group('postfix')
else:
    print 'NO MATCH!!'

rawDescription: need to Spilt srting twice

description: Need to Spilt srting twice


code:
for person in a.pList:
    if person.num == 123:
        break
else:
    print "Not found."
dave = person

rawDescription: how to select an object from a list of objects by its attribute in python

description: Select an object from a list of objects by its attribute in python


code:
def pearsonr2(a,b):
    # stats.pearsonr adapted for
    # x and y are (N,2) arrays
    n = x.shape[1]
    mx = x.mean(1)
    my = y.mean(1)
    xm, ym = x-mx[:,None], y-my[:,None]
    r_num = np.add.reduce(xm * ym, 1)
    r_den = np.sqrt(stats.ss(xm,1) * stats.ss(ym,1))
    r = r_num / r_den
    r = np.clip(r, -1.0, 1.0)
    return r

print pearsonr2(xx,yy)

rawDescription: Any faster way to get the same results?

description: Any faster way to get the same results


code:
d={}
for i in main_list:
    d.setdefault(len(i),[]).append(i)

print d.values()

rawDescription: Making Sub Lists Based on Lengths of Items


code:
# assume that your data rows are tuples
template = "{0:8}|{1:10}|{2:15}|{3:7}|{4:10}" # column widths: 8, 10, 15, 7, 10
print template.format("CLASSID", "DEPT", "COURSE NUMBER", "AREA", "TITLE") # header
for rec in your_data_source:
  print template.format(*rec)

rawDescription: How to Print "Pretty" String Output in Python

description: Print "Pretty" String Output in Python


code:
import csv
from collections import Counter

def average_column (csv_filepath):
    column_totals = Counter()
    with open(csv_filepath,"rb") as f:
        reader = csv.reader(f)
        row_count = 0.0
        for row in reader:
            for column_idx, column_value in enumerate(row):
                try:
                    n = float(column_value)
                    column_totals[column_idx] += n
                except ValueError:
                    print "Error -- ({}) Column({}) could not be converted to float!".format(column_value, column_idx)
            row_count += 1.0

    # row_count is now 1 too many so decrement it back down
    row_count -= 1.0

    # make sure column index keys are in order
    column_indexes = column_totals.keys()
    column_indexes.sort()

    # calculate per column averages using a list comprehension
    averages = [column_totals[idx]/row_count for idx in column_indexes]
    return averages

rawDescription: Python - Calculate average for every column in a csv file


code:
import example
c1 = example.C()
print 'init:', c1
c2 = None
def func(c):
    global c2
    print 'func:', c
    c2 = c
example.register_callback(func)
assert(c1 is c2)

rawDescription: boost python return same instance with make_constructor

description: Boost python return same instance with make_constructor


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup(htmlsource)
for link in soup.select('li > a[href^=http://www.amazon.ca/Best-Sellers]'):
    print link['href'], link.get_text()

rawDescription: Python RE does not return anything after /ref=


code:
import sys, pygame,time

FPS=30
fpsClock=pygame.time.Clock()

screen = pygame.display.set_mode((650,650))
screen.fill(255,255,255)
done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        if event.type == pygame.MOUSEMOTION:
            print pygame.mouse.get_rel()

    pygame.display.update()
    fpsClock.tick(FPS)

rawDescription: how to check mousemotion in an undefined direction in pygame?

description: Check mousemotion in an undefined direction in pygame


code:
noOfline=int(raw_input('Enter The Number of Lines'))
listOfInput=[]
for x in range(noOfline):
    inputString=str(raw_input('Enter The String To reverse'))
    listOfInput.append(inputString)
for value in listOfInput:
    print value[::-1]

rawDescription: enter n numbers to control the enter of the map or array

description: Enter n numbers to control the enter of the map or array


code:
#!/usr/local/bin/python2.6

import suds
#import logging
from suds.client import Client
from suds.sax.element import Element
from suds.sax.attribute import Attribute
from suds.xsd.sxbasic import Import

def absoluteMove():

    # connects to WSDL file and stores location in variable 'client'
    client = Client('http://10.10.10.10/p.wsdl')
    client.options.location = 'http://10.10.10.10:32963'

    # Create the header
    wsans = ('wsa', 'http://schemas.xmlsoap.org/ws/2004/08/addressing')
    mustAttribute = Attribute('SOAP-ENV:mustUnderstand', 'true')
    n1s = ('SOAP-ENC', 'http://www.w3.org/2003/05/soap-encoding')
    msgId = Element('Element').addPrefix(p='SOAP-ENC', u='http://www.w3.org/2003/05/soap-encoding')

    msgId2 = Element('Address', ns=wsans).setText('http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous')
    msgId1 = Element('ReplyTo', ns=wsans).insert(msgId2)
    msgId1.append(mustAttribute)

    msgId3 = Element('To', ns=wsans).setText('http://10.10.10.10:32954')
    msgId3.append(mustAttribute)

    client.set_options(soapheaders=[msgId, msgId1, msgId3, msgId2])

    # Create 'token' object to pass as an argument using the 'factory' namespace
    token = client.factory.create('ns4:ReferenceToken')

    # Create 'dest' object to pass as an argument and values passed to this object
    dest = client.factory.create('ns4:PTZVector')
    dest.PanTilt._x=1
    dest.PanTilt._y=4.9
    dest.Zoom._x=1

    # Create 'speed' object to pass as an argument and values passed to this object
    speed = client.factory.create('ns4:PTZSpeed')
    speed.PanTilt._x=0
    speed.PanTilt._y=0
    speed.Zoom._x=1

    # 'AbsoluteMove' method invoked passing in the new values entered in the above objects

    try:
        result = client.service.AbsoluteMove(token, dest, speed)
        print "absoluteMove result ", result
        return result
    except suds.WebFault, e:
        print "suds.WebFaults caught: "
        print e

if __name__ == '__main__': result = absoluteMove()

rawDescription: How to pass SOAP headers into python SUDS that are not defined in WSDL file

description: Pass SOAP headers into python SUDS that are not defined in WSDL file


code:
html = """

   CME Globex

   Some text
   View Rollover Dates

"""

import lxml.html

tree = lxml.html.fromstring(html)
print tree.xpath('//tr/td[@colspan="4"]/text()')

rawDescription: Beautifulsoup Python nested text

description: Beautifulsoup Python nested text


code:
curr = target
while (curr != None):
  print curr
  curr = parentMap[curr]

rawDescription: Tracing and Returning a Path in Depth First Search


code:
for theme in Theme.objects.only('name'):
    print theme.name
    print theme.other_attribute

rawDescription: Model.objects.only("columnname") doesn't work. It shows me everything


code:
import zerorpc
import gevent

class HelloRPC(object):
    def hello(self, name):
        print "this is server"
        return "Hello"

s = zerorpc.Server(HelloRPC())
s.bind("tcp://127.0.0.1:5001")

s1 = zerorpc.Server(HelloRPC())
s1.bind("tcp://127.0.0.1:5002")

gevent.joinall([gevent.spawn(s.run), gevent.spawn(s1.run)])

rawDescription: ZeroRPC bind multi-port for process

description: ZeroRPC bind multi-port for process


code:
soup = BeautifulSoup(page)
for td in soup.findAll('td', {'class': 'prodSpecAtribute'}):
    print td.contents[0]

rawDescription: Regex in Python for html

description: Regex in Python for html


code:
from operator import itemgetter
from itertools import groupby
from csv import reader

def min_z(iterable):
    # the data converted from strings to numbers
    floats = [[float(n) for n in row] for row in iterable]
    # the data sorted by x, y, z
    floats.sort(key=lambda (x, y, z, e): (x, y, z))
    # group the data by x, y
    grouped_floats = groupby(floats, key=itemgetter(slice(0, 2)))
    # return the first item from each group
    # because the data is sorted
    # the first item is the smallest z for the x, y group
    return [next(rowgroup) for xy, rowgroup in grouped_floats]

data = """-2.800000,-1.000000,5.470000,-0.26488315
-3.000000,1.000000,4.070000,-0.81185718
-2.800000,-1.000000,3.270000,1.29303723
-2.800000,-0.400000,4.870000,-0.51165026""".splitlines()

print min_z(reader(data))

rawDescription: How do you sort multiple columns of a CSV file using python?

description: Sort multiple columns of a CSV file using python


code:
x = "Hello World"
print 3

rawDescription: IPython workflow (edit, run)

description: IPython workflow (edit, run)


code:
def setValue(derived, Input):
    if len(Input) == 0:
        print 'Error, LIST HAS NO ENTRY'
        return None
    elif len(Input) == 1:
        derived.value = 1
        return derived
    else:
        derived.value = sum(x.value for x in Input)
        return derived

rawDescription: Assigning classes as variables

description: Assigning classes as variables


code: print "File Path: {} ------ File Hash: {}".format(file_path,file_hash)

rawDescription: filter list of values in a dictionary

description: Filter list of values in a dictionary


code:
import yaml

def constructor(loader, node) :
    fields = loader.construct_mapping(node)
    return Test(**fields)

yaml.add_constructor('!Test', constructor)

class Test(object) :
    def __init__(self, foo, bar=3) :
        self.foo = foo
        self.bar = bar
    def __repr__(self):
        return "%s(foo=%r, bar=%r)" % (self.__class__.__name__, self.foo, self.bar)

print yaml.load("""
- !Test { foo: 1 }
- !Test { foo: 10, bar: 20 }""")

rawDescription: Default constructor parameters in pyyaml


code:
def clearaltbits(v):
    if not v:
        return 0
    L, R = 16, 0
    # Find an upper bound on # bits
    while (-1<<L) & v:
        R, L = L, 2*L
    # Binary search for top bit #
    while not (-1<<L) & v:
        m = (L+R)/2
        if (-1<<m) & v:
            R = m
        else:
            L = m
        if L==R+1: break
    print bin(v),'has',len(bin(v))-2,'bits.'
    # Make big-enough alternate-bits mask
    k, b = 0b0101010101010101, 16
    while not (-1<<L) & k:
        k = (k<<b)|k
        b += b
    if L & 1:
        k = k<<1
    k = k & ((1<<L)-1)
    print bin(k^v),'fin'

clearaltbits(3**3)
clearaltbits(5**6)
clearaltbits(7**17)
clearaltbits(13**19)

rawDescription: How to invert alternate bits of a number

description: Invert alternate bits of a number


code:
# Get the filename from the user
filename = raw_input("Enter file name: ")

# An empty list to contain all our floats
spamflts = []

# Open the file to read ('r'), and loop through each line
for line in open(filename, 'r'):

    # If the line starts with the text we want (with all whitespace stripped)
    if line.strip().startswith('X-DSPAM-Confidence'):

        # Then extract the number from the second half of the line
        # "text:number".split(':') will give you ['text', 'number']
        # So you use [1] to get the second half
        # Then we use .strip() to remove whitespace, and convert to a float
        flt = float(line.split(':')[1].strip())

        print flt

        # We then add the number to our list
        spamflts.append(flt)

print spamflts
# At the end of the loop, we work out the average - the sum divided by the length
average = sum(spamflts)/len(spamflts)

print average

rawDescription: Python parsing through a line using for loop?


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-A', action = 'store_true')
parser.add_argument('-B', action = 'store_true')
args, unk = parser.parse_known_args()

file_parser = argparse.ArgumentParser()
file_parser.add_argument('-C', action = 'store_true')
file_parser.add_argument('-D', action = 'store_true')
file_parser.add_argument('-V', "--variable-list")
file_parser.add_argument('file')

fargs=[]
n=len(unk)
while True:
        i=0
        for i in  range(n): # finding longest fully parsable tail
            Parsed, unkf = file_parser.parse_known_args(unk[i:n])
            if not unkf: break
        if i==n: # did not found parsable tail
            file_parser.parse_args(unk[0:n]) # cause error
        else:
            fargs.append(Parsed)
            n=i
        if (n<=0): break
fargs.reverse()

print args
for argl in fargs:
        print argl

rawDescription: Python argparse: separate options for positional arguments


code:
import ConfigParser
from optparse import OptionParser

CONFIG_FILENAME = 'defaults.cfg'

def main():
    config = ConfigParser.ConfigParser()
    config.read(CONFIG_FILENAME)

    parser = OptionParser()
    parser.add_option("-l",
                      "--language",
                      dest="language",
                      help="The UI language",
                      default=config.get("Localization", "language"))
    parser.add_option("-f",
                      "--flag",
                      dest="flag",
                      help="The country flag",
                      default=config.get("Localization", "flag"))

    print parser.parse_args()

if __name__ == "__main__":
    main()

rawDescription: Using a file to store optparse arguments


code:
class ParagraphTagFixed(object):

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

    def __str__(self):
        return unicode(self).encode("utf-8")

    def __unicode__(self):
        return mark_safe(u'<p>{}</p>'.format(self.text + u'baz'))

print unicode(ParagraphTagFixed("foo")).__class__
print unicode(ParagraphTagFixed("foo"))
print str(ParagraphTagFixed("foo")).__class__
print str(ParagraphTagFixed("foo"))

rawDescription: Marking a class as "safe" for rendering in templates


code:
class pair(object):
    def __init__(self, *a):
        self.a = a
    def __add__(self, t):
        return map(sum, zip(self.a, t))

x, y = (5, 0)
x, y = pair(x, y) + (8, 1)
print x,y

rawDescription: Using python's in-place addition with unpacked tuples


code:
for type_tuple in FEED_TYPES:
    kind, name = type_tuple
    def make_notify(kind):
        def notify(self, **kwargs):
            print "notifying %s" % kind
            self.create(kind, **kwargs)
        return notify
    notify = make_notify(kind)
    notify.__name__ = "notify_%s" % kind
    setattr(cls, notify.__name__, classmethod(notify))

rawDescription: Dynamically adding class methods to a class


code:
html = BeautifulSoup(html1, features="xml")
print html.prettify()

rawDescription: Beautifulsoup removing HTML tags when parsing XML


code:
def testMyXRange(testsize=10):
    def normexcept(f,args):
        try:
            r = [f(args)]
        except Exception, e:
            r = type(e)
        return r

    for i in range(-testsize,testsize+1):
        for j in range(-testsize,testsize+1):
            print i, j
            for k in range(-9, 10, 2):
                r, mr = range(i,j,k), MyXRange(i,j,k)

                if r != list(mr):
                    print "iter fail: %d, %d, %d" % (i,j,k)

                if list(reversed(r)) != list(reversed(mr)):
                    print "reversed fail: %d, %d, %d" % (i,j,k)

                if len(r) != len(mr):
                    print "len fail: %d, %d, %d" % (i,j,k)

                z = [m for m in range(-testsize*2,testsize*2+1)
                      if (m in r) != (m in mr)]
                if z != []:
                    print "contains fail: %d, %d, %d, %s" % (i,j,k,(z+["..."])[:10])

                z = [m for m in range(-testsize*2, testsize*2+1)
                      if normexcept(r.__getitem__, m) != normexcept(mr.__getitem__, m)]
                if z != []:
                    print "getitem fail: %d, %d, %d, %s" % (i,j,k,(z+["..."])[:10])

rawDescription: `xrange(2**100)` -> OverflowError: long int too large to convert to int


code: print self.RadIPAddressInfo.GetSelection()  #returns selected index

rawDescription: How do I determine which button in a RadioBox is selected in wxPython?

description: Determine which button in a RadioBox is selected in wxPython


code:
fileList = ['DataLogs_20141125_AP.CSV', 'DataLogs_20141125_UK_EARLY.CSV',  'DataLogs_20141125_CAN.CSV',  'DataLogs_20141125_US.CSV', 'DataLogs_20141125_EUR.CSV',  'DataLogs_20141125_US_2.CSV', 'DataLogs_20141126_AP.CSV',
    'DataLogs_20141126_UK_EARLY.CSV','DataLogs_20141126_CAN.CSV',  'DataLogs_20141126_US.CSV','DataLogs_20141126_EUR.CSV',  'DataLogs_20141126_US_2.CSV']
latest = sorted(map(lambda x:x.split('_')[1],fileList), reverse=True)[1]
print filter(lambda x:x.find(latest)!=-1, fileList)

rawDescription: Get the latest files from Location using Python


code:
bounds = zip(*[iter(map(int, line.split()))]*2)
for lo, hi in bounds: print 'lo:', lo, '\thi:', hi, '\tdelta:', hi-lo+1

rawDescription: How to select two elements from list and do math on them in Python?

description: Select two elements from list and do math on them in Python


code:
from bs4 import BeautifulSoup

data = """

This is the first paragraph

This is the second paragraph

"""

soup = BeautifulSoup(data)
for span in soup.select('span[id]'):
    # insert sup tag after the span
    sup = soup.new_tag('sup')
    sup.string = span['id']
    span.insert_after(sup)

    # replace the span tag with it's contents
    span.unwrap()

print soup

rawDescription: Beautiful Soup 4: How to replace a tag with text and another tag?


code:
for numb in range(1):
    params = {
        'cg_multi': [3020, 3100, 3120, 3060, 3070],
        'save_search': 1, 'l': 0, 'md': 'th', 'ca': 11, 'w': 3,
        'f': ['p', 'c', 'b'],
        'o': numb + 1,
    }
    url = "http://www.blocket.se/bostad/uthyres"
    r = requests.get(url, params=params)
    soup = BeautifulSoup(r.content, 'html.parser')

    # All your entries live in the itemOffered div
    data = soup.select('div[itemtype=http://schema.org/Offer] div[itemprop=itemOffered]')

    out = StringIO.StringIO()
    fields = ('category', 'address', 'size', 'monthly_rent', 'rooms', 'time', 'weekly_rent_offseason')
    csv_writer = csv.DictWriter(out, fieldnames=fields)

    for entry in data:
        row = {}
        for field in fields:
            if field == 'time':
                time_elem = entry.find('time')
                value = (time_elem or {}).get('datetime', 'NaN')
            else:
                span_elem = entry.find(class_=field)
                value = span_elem.text.strip() if span_elem else 'NaN'
            row[field] = value
        csv_writer.writerow(row)

    print out.getvalue()

rawDescription: How to fix my csv output to make it useable?

description: Fix my csv output to make it useable


code:
import re
lines = "I like bananasAnd this is a new line.And another one."
print re.sub(r"([a-z\.!?])([A-Z])", r"\1 \2", lines)
# I like bananas And this is a new line. And another one.

rawDescription: splitting merged words in python

description: Splitting merged words in python


code:
list_of_strings = [
"Netall_Low_Lin_kor_110_180",
"Netall_Low_Lin_cer_110_181",
"Netall_Low_Lin_asa_110_182",
"Netall_Low_Lin_row_110_183",
"Netall_Low_Lin_psq_182_42",
"Netall_Low_Lin_vyt_182_41"
]

import re
pattern = re.compile("_(?=\d+_\d+)")
for current_string in list_of_strings:
    print pattern.split(current_string)

rawDescription: How can i create substrings from given strings in python?

description: Create substrings from given strings in python


code:
def findit2(fruits,color):
    return [(x['name'],x['weight']) for x in fruits if color in x['color']]

print findit2(fruits,"green")

rawDescription: How to retrieve a variable from a list located in a dictionary, located in a list? two

description: Retrieve a variable from a list located in a dictionary, located in a list? two


code:
for i in inp:
    if largest is None or i > largest:
        largest = i
print 'Largest',largest
# Gets smallest number
for i in inp:
    if smallest is None or i < smallest:
        smallest = i
print 'Smallest', smallest

rawDescription: Iterative Comparison of raw_input

description: Iterative Comparison of raw_input


code:
class ParseCall(ast.NodeVisitor):
    def __init__(self):
        self.ls = []
    def visit_Attribute(self, node):
        ast.NodeVisitor.generic_visit(self, node)
        self.ls.append(node.attr)
    def visit_Name(self, node):
        self.ls.append(node.id)

class FindFuncs(ast.NodeVisitor):
    def visit_Call(self, node):
        p = ParseCall()
        p.visit(node.func)
        print ".".join(p.ls)
        ast.NodeVisitor.generic_visit(self, node)

code = 'something = a.b.method(foo() + xtime.time(), var=1) + q.y(x.m())'
tree = ast.parse(code)
FindFuncs().visit(tree)

rawDescription: Regex matching Python function calls

description: Regex matching Python function calls


code:
for i,j in zip(list1, list2):
    print '%s%d' %(i,j)

rawDescription: Print two presorted lists into one output file in python


code:
text = 'Hello JJ'
counter = 0
for i in range(len(text)):
    if counter:
        counter -= 1
        continue
    for j in range(i + 1, len(text)):
        if text[j] != text[i]: break
        else: counter += 1
    print text[0:i + counter + 1]

rawDescription: How to print two or more identical letter in a string?

description: Print two or more identical letter in a string


code:
from nltk.corpus import wordnet as wn
from itertools import product

def compare(word1, word2):
    ss1 = wn.synsets(word1)
    ss2 = wn.synsets(word2)
    return max(s1.path_similarity(s2) for (s1, s2) in product(ss1, ss2))

for word1, word2 in (('game', 'leonardo'), ('game', 'chess')):
    print "Path similarity of %-10s and %-10s is %.2f" % (word1,
                                                          word2,
                                                          compare(word1, word2))

rawDescription: python nltk returning odd result for wordnet similarity measure

description: Python nltk returning odd result for wordnet similarity measure


code:
import matplotlib
from pylab import *

val = 3-6*rand(5)    # the bar lengths        # changed your data slightly
pos = arange(5)+.5    # the bar centers on the y axis
print pos
figure(1)
barh(pos,val, align='center',height=0.1)    # notice the 'height' argument
yticks(pos, ('Tom', 'Dick', 'Harry', 'Slim', 'Jim'))

gca().axvline(0,color='k',lw=3)   # poor man's zero level

xlabel('Performance')
title('horizontal bar chart using matplotlib')
grid(True)
show()

rawDescription: matplotlib chart - creating horizontal bar chart

description: Matplotlib chart - creating horizontal bar chart


code:
files = urllib2.urlopen('ftp://ftp2.census.gov/geo/tiger/TIGER2008/01_ALABAMA/').read().splitlines()
for l in files[:4]: print l

rawDescription: Python and urllib

description: Python and urllib


code:
def _complements(complements, str):
    return ''.join([complements[i] for i in str])

def matching_codons(complements, poolA, poolB):
    final = []
    for i in poolA:
        if _complements(complements, i) in poolB:
            final.append((i, _complements(complements, i)))
    return final
complements = {'A':'T', 'C':'G', 'T':'A', 'G':'C'}
poolA = ['AAG', 'TAC', 'CGG', 'GAT', 'TTG', 'GTG', 'CAT', 'GGC', 'ATT', 'TCT']
poolB = ['TAA', 'CTA', 'AAC', 'TTC', 'AGA', 'CCC', 'CCG', 'GTA']
print matching_codons(complements, poolA, poolB)

rawDescription: Matching codons

description: Matching codons


code:
info = ['processor_1_info', 'processor_2_info']
processors_info = "\n\t\t\t".join(info)
print "Processor(s):\t{}".format(processors_info)

rawDescription: Python printing Formatted text with lists nested in dict


code:
from PyQt4.QtSql import QSqlDatabase,QSqlQuery
from PyQt4.QtCore import QCoreApplication
import sys

app = QCoreApplication(sys.argv)

db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("sqlitedb.rdb")
db.open()

query = QSqlQuery()
query.exec_("select * from info")
while (query.next()):
    id = query.value(0).toInt()
    name = query.value(1).toString()
    country = query.value(2).toString()
    age = query.value(3).toInt()

    print "name = %s \ncountry = %s" % (name,country)

app.exec_()

rawDescription: Getting data from selected item in QListView


code:
lines = open('file.txt')
for line in lines:
   as_list = line.split()
   result = [as_list[0], as_list[1], as_list[2:]]
   print result

rawDescription: Help with Python strings

description: Help with Python strings


code:
import textwrap
print textwrap.fill('This is a cool sentence... How about eating it??? Whats more?? pepper is available all for free!!!', 15)

rawDescription: Include full words in string slicing

description: Include full words in string slicing


code:
import pkg_resources
print pkg_resources.resource_filename('os.path', 'static/favicon.ico')
# 'C:\\Python27\\lib\\static\\favicon.ico'

rawDescription: How to get file path of a add_static_view() in Pyramid

description: Get file path of a add_static_view() in Pyramid


code:
class MyProtocol(basic.LineReceiver):

    #def makeConnection(self, transport):
    #    print transport

    def connectionLost(self, reason):
        print reason
        self.sendData = False

    def connectionMade(self):
        print "connection made"
        self.delimiter = "\n"
        self.sendData = True
        print self.transport
        self.sendFromQueue()

    def sendFromQueue(self):
        while self.sendData:
            msg = dataQueue.get()
            self.sendLine(msg)
            # you need to handle empty queue
            # Have another function to resume

rawDescription: Twisted client for a send only protocol that is tolerant of disconnects


code:
import StringIO, csv

with open('file.txt', 'r') as f_input:
    begin = False
    rows = []

    for line in f_input:
        if line.startswith("end of file"):
            break
        elif begin:
            rows.append(next(csv.reader(StringIO.StringIO(line))))
        elif line.startswith("begin of file"):
            begin = True

    print rows

rawDescription: Find values in file, between keywords, using python


code:
inp = """
D : A/B/C/D, -
A : A, 3 PM
B : A/B, -
Z : A/B/C/D/Z,
E : E, 4 PM
F : E/r/f, -
G : G, 5 PM """

trans_1 = [ele.split(":")[1].strip().split(",") for ele in inp.splitlines() if ele]

trans_2 = [(ele[0].strip().replace("/", "->"), ele[1].strip()) for ele in trans_1]

#_dict = {}

for ele in trans_2:
    if ele[1] != "-":
        #_dict[ele[1]] = []
        print ele[1], "->", ele[0]
        for inner_ele in trans_2:
            if ele[0] == inner_ele[0][0]:
                #_dict[ele[1]].append(inner_ele[0])
                print "\t", inner_ele[0]

# print _dict

rawDescription: Python to figure out all paths via parsing


code:
for entry in sorted_data[:10]:
    for key in ['Competitor Number', 'Competitor Name', 'sum']:
        print entry[key]
    print

rawDescription: Ordered dictionary Sum and Top 3 of the Ordered dictionary sum