code:
print [['Point %i' % (i) for i, e in enumerate(sl, 1)] for sl in li]
# [['Point 1', 'Point 2', 'Point 3', 'Point 4'], ['Point 1', 'Point 2', 'Point 3']]

rawDescription: list length + list concatenate on uneven lists

description: List length + list concatenate on uneven lists


code:
import numpy as np

def intersected_points(x0, x1, y0, y1):
    # slope
    m = (y1 - y0) / (x1 - x0)
    # Boundary of the selected points
    x_ceil = np.ceil(min(x0, x1))
    x_floor = np.floor(max(x0, x1))
    y_ceil = np.ceil(min(y0, y1))
    y_floor = np.floor(max(y0, y1))

    # calculate all intersected x coordinate
    x = np.arange(x_ceil, x_floor + 1)
    y = m * (x - x0) + y0
    ax = zip(x, y)
    # calculate all intersected y coordinate
    y = np.arange(y_ceil, y_floor + 1)
    x = (y - y0) / m + x0
    ax.extend(zip(x, y))
    ax.append((x0, y0))
    ax.append((x1, y1))
    ax.sort()
    return np.array(ax)

if __name__ == "__main__":
    import matplotlib.pyplot as plt

    x0, y0 = 1.5, 0.5
    x1, y1 = 4.4, 4.1

    points = intersected_points(x0, x1, y0, y1)
    print points

    rect = plt.Rectangle((x0, y0), x1 - x0, y1 - y0,
                         facecolor="#60ff60", alpha=0.2)
    plt.gca().add_patch(rect)
    plt.plot([x0, x1], [y0, y1], 'b-')
    plt.plot(points[:, 0], points[:, 1], 'bo')
    plt.grid(True)
    plt.xticks(np.arange(np.floor(x0), np.ceil(x1)))
    plt.yticks(np.arange(np.floor(y0), np.ceil(y1)))
    plt.show()

rawDescription: Distance for each intersected points of a line in increased order in 2D coordinate


code:
from SubPackage import TestWithGlobals
print TestWithGlobals.__name__
import sys

def MakeStringBall():
    print "In MakeStringBall", id(TestWithGlobals)
    print "In MakeStringBall Subpackage.TestWithGlobals", id(sys.modules['SubPackage.TestWithGlobals'])
    print "In MakeStringBall OuterPackage.SubPackage.TestWithGlobals", id(sys.modules['OuterPackage.SubPackage.TestWithGlobals'])
    TestWithGlobals.global_string = "ball"

rawDescription: Import from subpackage or full path difference


code:
def _is_instance_method(var):
    if not hasattr(var, '__call__'): # It's not a callable
        return False
    if not hasattr(var, 'im_self'): # It's a callable, but it's not a bound method
        return False
    if getattr(var, 'im_self') is not None: # At this point, if it's a class method,
                                            # it will be bound to the class, while
                                            # the instance method is still unbound
                                            # return False if it's bound (i.e. a class method)
        return False
    return True # All that remains is a callable, that's boundable, but not yet -- an instance method!

def func_decorator(func):
    def func_wrapper(self, *args, **kwargs):
        print "Inside %s!" % (func.__name__,)
        return func(self, *args, **kwargs)
    return func_wrapper

def class_decorator(cls):
    for attr in cls.__dict__:
        var = getattr(cls, attr)
        if _is_instance_method(var): # Determine whether the attribute is an instance method
            setattr(cls, attr, func_decorator(var)) # Replace the function with a decorated one
    return cls # Return the class with its new decorated instance methods

@class_decorator
class B(object):

    @staticmethod
    def static_method():
        return "static method"

    @classmethod
    def cls_method(cls):
       return "cls method"

    def instance_method(self):
       return "instance method"

print B.static_method()
print B.cls_method()
b = B()
print b.instance_method()

rawDescription: decorate specific methods of a class

description: Decorate specific methods of a class


code:
s = "40001#World Music#Mike Oldfield#Tubular Bells#   53# # #"
s2 = "#".join([i if i != " " else "" for i in s.split("#")])
print s2

rawDescription: Trim or remove single white space char from delimited text


code:
import os, os.path, sys

rootdir = 'q:'

documentedcount = 0

for root, subFolders, files in os.walk(rootdir):
    filecount = len(files)
    print "Filecount = %s" % filecount
    if filecount >= 3:
        documentedcount =+1
        print "Documented in the loop is %s" % documentedcount

print "Documented = %s" % documentedcount

rawDescription: Counting files and incrementing variable Python


code:
from lxml import etree
from lxml.html import parse

schema_root = etree.XML('''\
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="a">
 <xs:complexType>
  <xs:sequence>
   <xs:element name="b" maxOccurs="unbounded">
    <xs:complexType>
     <xs:attribute name="c" default="1" type="xs:string"/>
    </xs:complexType>
   </xs:element>
  </xs:sequence>
 </xs:complexType>
</xs:element>
</xs:schema>''')

xmls = '''<a>
 <b/>
 <b c="2"/>
</a>'''

schema = etree.XMLSchema(schema_root)
parser = etree.XMLParser(schema = schema, attribute_defaults = True)

root = etree.fromstring(xmls, parser)
result = etree.tostring(root, pretty_print=True, method="xml")

print result

rawDescription: Validating and filling default values in XML based on XSD in Python


code:
ts12_rlm_fit = sm.RLM(ts12.values+ 1e-4*np.random.randn(5), x).fit()
print ts12_rlm_fit.summary()

rawDescription: Fitting downward trends (negative slope) with statsmodels linear regression


code:
from BmpAlphaImagePlugin import BmpAlphaImageFile

x = BmpAlphaImageFile('gearscolor.bmp')
print x.mode
x.save('abc1.png')

rawDescription: Load RGBA bitmap with PIL

description: Load RGBA bitmap with PIL


rawDescription: date_range not accepting the variable I want to use?

description: Date_range not accepting the variable I want to use


code:
indent = []
for action, elem in etree.iterwalk(root, events=('start', 'end')):
    if action == 'start':
        print '{}<{}{}>'.format(''.join(indent), elem.tag, '/' if not len(elem) else '')
        indent.append('  ')
    else:
        indent.pop()
        if len(elem):
            print '{}</{}>'.format(''.join(indent), elem.tag)

rawDescription: Analogue to lxml's tostring(method='text') to return xml without text content?


code:
foo = 'appleorangepearbanana '
dict = {'apple':'x','pear':'x','banana':'x','orange':'y'}
for original,replacewith in dict.items():
    foo = foo.replace(original, replacewith)
print foo

rawDescription: Replace multiple strings in pile of text python


code:
import pandas as pd
import numpy as np

data = {
'exchange' : ['JSE', 'JSE', 'CME', 'CME'],
'symbol'   : ['MTN', 'OML',  'ES',  'YM'],
'abc'      : [ 123 ,  674 ,  235 ,  453 ],
'xyz'      : [ 546 ,  235 ,  563 ,  365 ]
}

df = pd.DataFrame(data).set_index(['exchange', 'symbol'])

# apply fancy calculation
df.loc['JSE', 'OML'] = df.loc['JSE', 'OML'].apply(np.sqrt)
print df

rawDescription: Update dataframe row from a series

description: Update dataframe row from a series


code:
import time
import multiprocessing
from multiprocessing import Pool
import datetime

def f(values):
    now = str(datetime.datetime.now())
    proc_id = str(multiprocessing.current_process())
    print(proc_id+' '+now)
    a=values**2
    time.sleep(4)
    return a

if __name__ == '__main__':
    p = Pool(4) #number of processes
    processed_values= p.map( f, range(28), chunksize=1)
    p.close()
    p.join()
    print processed_values

rawDescription: python multiprocessing map mishandling of last processes

description: Python multiprocessing map mishandling of last processes


code: print elem.tag.split('}')[-1]

rawDescription: lxml parse xsd file without Schema URL

description: Lxml parse xsd file without Schema URL


code:
import numpy
from timeit import timeit
stat = '''
import numpy
a1 = range(4000)
a2 = numpy.array(a1)
i = 0
'''
if __name__ == "__main__":
    test_times = 1000
    print '1. {0:.8f}'.format(timeit('a1[i]', setup = stat, number = test_times))
    print '2. {0:.8f}'.format(timeit('a2[i]', setup = stat, number = test_times))
    print '3. {0:.8f}'.format(timeit('i += a1[i]; ++i', setup = stat, number = test_times))
    print '4. {0:.8f}'.format(timeit('i += a2[i]; ++i', setup = stat, number = test_times))
    print '5. {0:.8f}'.format(timeit('a = a1[i:len(a1)]; ++i', setup = stat, number = test_times))
    print '6. {0:.8f}'.format(timeit('a = a2[i:len(a2)]; ++i', setup = stat, number = test_times))

rawDescription: Why Numpy.array is slower than build-in list for fetching sub list


code:
for cell in grid:
    print grid[cell]

rawDescription: How to make a grid from a dictionary?

description: Make a grid from a dictionary


code:
from collections import Counter

base = [1, 2, 3]
missing = [4, 5, 6]
extra = [7, 8, 9]
a = base + missing
b = base * 4 + extra

result = Counter(b) - Counter(a)
print result
assert result == dict([(k, 3) for k in base] + [(k, 1) for k in extra])

rawDescription: Removing Elements in A from B

description: Removing Elements in A from B


code:
from datetime import datetime
from datetime import timedelta

times = ['00:00:12.00', '00:00:12.5', '00:00:18.00', '00:00:58.00',
         '23:59:57.51', '03:59:52.49999']

def round_seconds(dt, precision):
    # Max value for microseconds in `datetime` is 999999 (6 digits).
    # We need to pad the free space with zeros if `dt.microsecond`
    # has less than 6 digits
    msfloat = '0.{0}{1}'.format(''.zfill(6 - len(str(dt.microsecond))),
                                dt.microsecond)
    mod = dt.second % precision + float(msfloat)
    diff = precision - mod
    if diff == mod:
        # Ambiguous (xxxxxxx.5), gotta ceil it
        delta = mod
    else:
        # Choose the closest bound
        delta = min(diff, mod)
        if delta == mod:
            # Negate if need to floor it
            delta = -mod

    return dt + timedelta(seconds=delta)

for time in times:
    obj = datetime.strptime(time, '%H:%M:%S.%f')
    print datetime.strftime(round_seconds(obj, 5), '%H:%M:%S')+',',

rawDescription: Round datetime object data with ±5 sec precision


code:
from itertools import groupby
for lname, persons in groupby(persons, keyfun):
    print ' - '.join(p.name for p in persons)

rawDescription: Group related objects in Django

description: Group related objects in Django


code:
def remove_nodes(treeFile,idFile):

    t= Tree(treeFile,format=8)
    print t
    removed=[]
    for node in t:
        # print node.name
        if not find_id(idFile,'^'+node.name+'\s'):
            node.delete(prevent_nondicotomic=False)
            removed.append(node)

    print [n.name for n in removed]
    print t
    t.write(format=1, outfile="newtree.nw")

rawDescription: python ete2 delete node from tree

description: Python ete2 delete node from tree


rawDescription: Python CSV transpose data in one column to rows


code:
import fileinput
seen = set() # set for fast O(1) amortized lookup
for line in fileinput.FileInput('1.csv', inplace=1):
    if line in seen: continue # skip duplicate

    seen.add(line)
    print line, # standard output is now redirected to the file

rawDescription: Removing duplicate rows from a csv file using a python script


code:
import re
p = re.compile(ur'(?P<permissions>[d-][rwx-]{9})\s{1,20}(?P<links>\d{1,8})\s{1,20}(?P<owner>[\w-]{1,16})\s{1,20}(?P<group>[\w-]{1,16})\s{1,20}(?P<size>[0-9]{1,16})\s{1,20}(?P<month>[A-Za-z]{0,3})\s{1,20}(?P<date>[0-9]{1,2})\s{1,20}(?P<timeyear>[\d:]{4,5})\s{1,20}(?P<filename>[\s\w.-]+?)(?=[drwx-]{10}|$)')
test_str = u"-rw-r--r--   1 owner    group        75148624 Jan  6  2015 somename.csv-rw-r--r--   1 owner    group       223259072 Feb 26  2015 somename.csv-rw-r--r--   1 owner    group         4041411 Jun  5  2015 somename-adjusted.csv-rw-r--r--   1 owner    group         2879228 May 13  2015 somename.csv-rw-r--r--   1 owner    group        11832668 Feb 13  2015 somename.csv-rw-r--r--   1 owner    group         1510522 Feb 19  2015 somename.csv-rw-r--r--   1 owner    group         2826664 Feb 25  2015 somename.csv-rw-r--r--   1 owner    group          582985 Feb 26  2015 somename.csv-rw-r--r--   1 owner    group          212427 Feb 26  2015 somename.csv-rw-r--r--   1 owner    group         3015592 Feb 27  2015 somename.csv-rw-r--r--   1 owner    group          103576 Feb 27  2015 somename-corrected.csv"

re.findall(p, test_str)

rawDescription: Python Regular expression Lookahead overshooting pattern


code:
import subprocess as s
names = "bla blub moep"
cmd = ['awk', '-f', 'sth.awk', 'vars="' + names + '"', 'file']
print s.check_output(cmd)

rawDescription: Python subprocess with vars

description: Python subprocess with vars


code:
mylist=[(u'computer', 1592), (u'student', 1113), (u'university', 1080), (u'raspberry', 1000), (u'science', 814), (u'$5', 770), (u'pi', 688), (u'exam', 571), (u'just', 544), (u'intelligence', 495), (u'solution', 475), (u'costs', 423), (u'exam:', 411), (u'latest', 402), (u"pi's", 366), (u'be', 311), (u'can', 268), (u'what', 268), (u'way', 257), (u'students', 238)]

with open('test1.txt', 'w') as fp:
    # write line by line without python 2 style string encoding marker
    for item in mylist:
        fp.write(u"('{}', {})\n".format(*item).encode('utf-8'))
    fp.write('\n')

    # write python 2 representation of a dict
    mydict = dict(mylist)
    fp.write(repr(mydict).encode('utf-8'))
    fp.write('\n')

print open('test1.txt').read().decode('utf-8')

rawDescription: how can i write a list of tuples (include unicode) on a txt file?

description: Write a list of tuples (include unicode) on a txt file


rawDescription: How to turn a Dataframe into an Array with certain specifications on Python Pandas

description: Turn a Dataframe into an Array with certain specifications on Python Pandas


code:
for dataset in datasets:
    for field in dataset:
        print "{0:<16}: {1}".format(field[0], field[1])

rawDescription: Extracting data from HTML table

description: Extracting data from HTML table


code:
# Dialog
class Calendar(wx.Dialog):
    def __init__(self, parent, id, title):
        wx.Dialog.__init__(self, parent, id, title)

        self.date = wx.DateTime_Now() #create global variable 'self.date'

        vbox = wx.BoxSizer(wx.VERTICAL)
        self.calend = cal.CalendarCtrl(self, -1, self.date, #from wx.DateTime_Now()
            style = cal.CAL_SHOW_HOLIDAYS|cal.CAL_SEQUENTIAL_MONTH_SELECTION)
        vbox.Add(self.calend, 0, wx.EXPAND | wx.ALL, 20)

        vbox.Add((-1, 20))

        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        btn = wx.Button(self, wx.ID_OK, 'Ok') #changed id to wx.ID_OK
        cancelBtn = wx.Button(self, wx.ID_CANCEL, 'Cancel') #id to wx.ID_CANCEL
        hbox2.Add(btn, 1)
        hbox2.Add(cancelBtn, 1)
        vbox.Add(hbox2, 0, wx.ALIGN_CENTER | wx.TOP | wx.BOTTOM, 20)

        btn.Bind(wx.EVT_BUTTON, self.okClicked)
        cancelBtn.Bind(wx.EVT_BUTTON, self.OnQuit)

        self.SetSizerAndFit(vbox)

        self.Show(True)
        self.Centre()

    def okClicked(self, event):
        self.date = self.calend.GetDate() #set global value 'date' to selection
        print self.date
        return self.date

#Frame function
def calClick1(self, event):
    calObj = Calendar(None, -1, 'test cal')
    #if you clicked ok, continue...
    if calObj.ShowModal() == wx.ID_OK:
        # Set the TextCtrl by calling the global variable 'calObj.date'
        self.MyTextCtrl.SetValue(calObj.date)

rawDescription: wxpython event handling between multiple classes

description: Wxpython event handling between multiple classes


code:
type(1L)
long(1)
int(1L)

rawDescription: Trouble with a simple query PyODBC

description: Trouble with a simple query PyODBC


code:
import re
from bs4 import BeautifulSoup
soup = BeautifulSoup('''\

The quick brown fox jumps over the lazy dog

''')
the = re.compile(r'the', flags=re.I)
text = soup.p.string
while True:
    match = the.search(unicode(text))
    if not match: break
    start, stop = match.span()
    text = inject_tag(text, start, stop, 'b')

print soup.prettify()

rawDescription: How do you replace specific characters in beautifulSoup?

description: Replace specific characters in beautifulSoup


rawDescription: Basic string manipulation to make correct date formatting


code:
for dict_elem in (d['a'] for d in dict_lst):
    print dict_elem

rawDescription: Refer to dictionary element in 'for' loop


rawDescription: Convert 2 lists into a dictionary without having to loop


code:
d = {'a':7}
exec "def f(x): return x + a" in d

rawDescription: creating a function object from a string

description: Creating a function object from a string


code:
def func1(x):
   x.append('foo')
def func2(x):
   x = 'foo'

a = []
func1(a)
print a #['foo']  #mutated a in func1
func2(a)
print a #['foo']  #didn't change a in func2, only created a new local variable named `x` and assigned it to the string 'foo'

rawDescription: python 3: Class function member to modify a class data member

description: Python 3: Class function member to modify a class data member


code:
board=[]
ar_row=[]
for i in range(15):
    ar_row.append(str(i)+"  ")
board.append(ar_row)

for j in range(12):
   row = ((".  " + ",") * 10) + ((".   " + ",") * 5)
   ar_row = row.split(',')
   ar_row.append(str(j))
   board.append(ar_row)

for element in board:
    print ' '.join(element)

rawDescription: Trouble getting the right appearance of an array (Python3)


code:
import numpy as np
from nltk import ngrams

def everygrams(sequence):
    """
    This function returns all possible ngrams for n
    ranging from 1 to len(sequence).
    >>> list(everygrams('a b c'.split()))
    [('a',), ('b',), ('c',), ('a', 'b'), ('b', 'c'), ('a', 'b', 'c')]
    """
    for n in range(1, len(sequence)+1):
        for ng in ngrams(sequence, n):
            yield ng

doc1 = "Singularity is still a confusing phenomenon in physics".split()
doc2 = "Quantum theory still wins over String theory".split()
_vec1 = list(everygrams(doc1))
_vec2 = list(everygrams(doc2))
# Create a full dictionary of all possible ngrams.
vec_dict = list(set(_vec1).union(_vec2))
print 'Vector Dict:', vec_dict, '\n'
# Now vectorize the documents
vec1 = [1/float(len(_vec1)) if ng in _vec1 else 0 for ng in vec_dict]
vec2 = [1/float(len(_vec2)) if ng in _vec2 else 0 for ng in vec_dict]
print 'Vectorzied:', vec1, vec2, '\n'
print 'Similarity:', np.dot(vec1, vec2), '\n'

rawDescription: Normalize ranking score with weights

description: Normalize ranking score with weights


code:
class MyList(list):
    def __setslice__(self, *args):
        print '__setslice__ called with args:', args
        list.__setslice__(self, *args)
    def __setitem__(self, *args):
        print '__setitem__ called with args:', args
        list.__setitem__(self, *args)

rawDescription: How does python do list slices and modification on the LHS?


code:
# Python 2.7

import urllib

url = 'http://www.boursorama.com/includes/cours/last_transactions.phtml?symbole=1xEURUS'
sock = urllib.urlopen(url)
content = sock.read()
sock.close()

print content

rawDescription: Web scraping urlopen in python

description: Web scraping urlopen in python


code:
for key in crucial:
    if key in dishes:
        print dishes[key]

rawDescription: Comparing Two Dictionaries Key Values and Returning the Value If Match


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

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

description: Fix Python If Statement for finding Taxicab numbers


code:
tup = ('08:01: Woke Up\n08:05: Took Shower\n08:20: Ate Breakfast\n08:45: Left for work',)
print tup[0]

rawDescription: split a string in python on linebreaks

description: Split a string in python on linebreaks


code:
import imp
import sys

def find_module(fullname, path=None):
    try:
        # 1. Try imp.find_module(), which searches sys.path, but does
        # not respect PEP 302 import hooks.
        result = imp.find_module(fullname, path)
        if result:
            return result
    except ImportError:
        pass
    if path is None:
        path = sys.path
    for item in path:
        # 2. Scan path for import hooks. sys.path_importer_cache maps
        # path items to optional "importer" objects, that implement
        # find_module() etc.  Note that path must be a subset of
        # sys.path for this to work.
        importer = sys.path_importer_cache.get(item)
        if importer:
            try:
                result = importer.find_module(fullname, [item])
                if result:
                    return result
            except ImportError:
                pass
    raise ImportError("%s not found" % fullname)

if __name__ == "__main__":
    # Provide a simple CLI for `find_module` above.
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", "--path", action="append")
    parser.add_argument("modname", nargs='+')
    args = parser.parse_args()
    for name in args.modname:
        print find_module(name, args.path)

rawDescription: imp.find_module() which supports zipped eggs

description: Imp.find_module() which supports zipped eggs


code: print "hello world"

rawDescription: Python 2.7: What print() does to the string inside of it


rawDescription: Neat way of popping key, value PAIR from dictionary?


code:
from itertools import product, combinations
n = 3 # 3x3
m = 2 # 2 tents
for i in combinations(range(n*n), m):
   print [[0 if x*n+y in i else 1 for x in range(n)] for y in range(n)]

rawDescription: Python generate all possible configurations of numbers on a "board"


code:
boys = ["b1", "b2", "b3"]
girls = ["g1", "g2", "g3"]
for girls_perm in itertools.permutations(girls):
    for b, g in zip(boys, girls_perm):
        print b + g,
    print

rawDescription: All possible (monogamous) pairings of two lists (of boys and girls)


code:
import sys

def is_abundant():
    try:
        n = int(raw_input("Enter a number: "))
    except ValueError:
        print "Invalid number"
        sys.exit(1)
    max_divisor = int(n / 2) + 1
    sum = 0
    for x in range(1, max_divisor):
        if n % x == 0:
            sum += x
    if sum > n:
        print ("Your number is abundant")
    else:
        print ("Your number isn't abundant")

is_abundant()

rawDescription: Determining a Abundant Number when user inputs a nmber


code: print "".join([d.get(c, c) for c in s])

rawDescription: Attributes of Python module `this`

description: Attributes of Python module `this`


code:
# Always import at the top of your script
from random import choice
print "1 stands for paper, 2 stands for rock, 3 stand for scissors"
# Using a tuple here is actually faster than using a list
signs = 1, 2, 3
def game():
    i = int(raw_input("pick a sign, use the numbers shown above "))
    cc = choice(signs)
    if i - cc == 0:
        print "it's a draw"
    elif i - cc == 1:
        print "you lose"
    elif  i - cc == 2:
        print "you win"
    elif i - cc == -1:
        print "you win"
    elif i - cc == -2:
        print "you lose"
    return int(raw_input("if you want to play again, press 1"))
# Have the script loop until the return value of game != 1
while game() == 1:
    # pass is a do-nothing placeholder
    pass

rawDescription: Python Rock Paper Scissors function

description: Python Rock Paper Scissors function


rawDescription: Create Tab Separated File with Iterative Values Python


code:
k = db.Key('agNiYXpyDAsSA2ZvbyIDYmFyDA')
_app = k.app()
path = k.to_path()
print 'app=%r, path=%r' % (_app, path)

rawDescription: How to decode a Google App Engine entity Key path str in Python?

description: Decode a Google App Engine entity Key path str in Python


code:
#! /usr/bin/env python

''' From
http://stackoverflow.com/questions/26153937/given-a-large-dataset-in-file-a-how-can-i-reference-it-in-a-simulation-in-file/26161074#26161074
'''

input_name = "file.dat"

# Lines in file.dat have this format:
# Time [s]    forward velocity [m/s]    angular velocity[rad/s]
# Eg
#1248297556.211    0.075      0.240

def runFunction(timestamp, fwd_vel, ang_vel):
    print "Time %f, Forward velocity %f, Angular velocity %f" % (timestamp, fwd_vel, ang_vel)

def main():
    with open(input_name, "r") as data:
        for line in data:
            #Split line on whitespace into a list of strings
            params = line.split()

            #Convert parameters from strings to floats
            params = [float(s) for s in params]

            #Pass the parameter list
            runFunction(*params)

if __name__ == '__main__':
    main()

rawDescription: Given a large dataset in file A, how can I reference it in a simulation in file B?


code:
import pandas as pd
from StringIO import StringIO

data='''ATG12 Norm     ATG5 Norm    ATG7 Norm    Cancer Stage    Text
5.55           4.99         8.99         IIA    ABC
4.87           5.77         8.88         IIA    ABC
5.98           7.88         8.34         IIC    ABC'''

df = pd.DataFrame.from_csv(StringIO(data), index_col=None, sep='\s{2,}')

print df
print df.groupby('Cancer Stage')['ATG12 Norm','ATG5 Norm'].mean()
print df.groupby('Cancer Stage').mean()

rawDescription: Pandas Building a subtable based on means


code:
rectangles = {}
with open("sample.txt", "r") as rects:
    for rect in rects:
      rectangles[int(rect.split()[0])] = [map(int, rect.split()[1:][i:i+4]) for i in range(0, len(rect.split()[1:]), 4)]

    print rectangles

rawDescription: Load rectangle data from txt file with Python?


code:
print raw_input('abc')[::-1]
raw_input('press enter to exit')

rawDescription: How do I get all of the output from my .exe using subprocess and Popen?

description: Get all of the output from my .exe using subprocess and Popen


code:
class EnumMeta(type):
    def __new__(typ, name, bases, attrs):
        cls_attrs = {}
        cls_choices = {}

        for attr_name, value in attrs.items():
            cls_attrs[attr_name] = attr_name.lower()
            if not attr_name.startswith("__"):
                cls_choices[attr_name.lower()] = value

        ordering = attrs.get('__ordering__')
        if ordering == None:
            ordering = sorted(cls_choices.keys())

        def choices(cls):
            return dict(cls_choices)

        def values(cls, value=None):
            if value is None:
                return [ (k, cls_choices[k] ) for k in ordering ]
            elif not isinstance(value, basestring):
                return [ (k, cls_choices[k] ) for k in value ]
            else:
                return unicode(cls_choices.get(value))

        def keys(cls, nil=False):
            items = list(ordering)
            if nil:
                items.append('')

            return items

        def combined_length(cls):
            return len(",".join(cls.values().keys()))

        def max_length(cls):
            return max(map(len, cls.values().keys()))

        cls_attrs['choices'] = classmethod(choices)
        cls_attrs['values'] = classmethod(values)
        cls_attrs['keys'] = classmethod(keys)
        cls_attrs['combined_length'] = classmethod(combined_length)
        cls_attrs['max_length'] = classmethod(max_length)

        return type(name, bases, cls_attrs)

class SideHemType:
    __ordering__ = ['double', 'single']
    __metaclass__ = EnumMeta

    Single = "Single side hem for opaque fabrics"
    Double = "Double side hem for transparent fabrics"

print SideHemType.keys()
print SideHemType.values()

rawDescription: Ordering enum value in python

description: Ordering enum value in python


code:
import fileinput

for line in fileinput.input('.htaccess', inplace=True):
    if line.strip() == '</IfModule>':
        print 'some stuff before the line'
    print line,

rawDescription: Python: How to add a line just before my matched pattern


code:
import pandas as pd
df = pd.read_csv('timesheet.csv', header=None)
for xx in pd.DatetimeIndex(df[0]):
    print xx.strftime('%d/%m/%Y')

rawDescription: Slicing a list from csv.reader

description: Slicing a list from csv.reader


rawDescription: Using regex for mutliple lines

description: Using regex for mutliple lines


code:
from cStringIO import StringIO
fobj = StringIO('file\ncontent')
for line in fobj:
  print line

rawDescription: reconstituting a class full of data from MySQL BLOB object in python

description: Reconstituting a class full of data from MySQL BLOB object in python


rawDescription: python time interval algorithm sum

description: Python time interval algorithm sum


code:
def run(self):
        while True:
            customer=Customer()
            self.mutex.acquire()

            if self.queue.full():
                print "Queue is full : Cant Enter Critical Section"

            elif not self.queue.full():
                # NOTE 2: other threads can enter after releasing the lock
                print self.mutex.release()

                self.mutex.acquire()
                #Critical Section
                self.queue.put(customer)
                print "Customer %d Enters the Queue with %d service " %(
                    customer.id,customer.serviceTime
                )
            # Note 1 alternative - release mutex (cancel 'if' branching effect)
            self.mutex.release()

rawDescription: Lock variable in python in a loop

description: Lock variable in python in a loop


code:
import numpy as np

A = np.array([2,2,2,-2])
B = np.array([2,3,-2,-3])
C = np.array([2,-2,-4,-2])
D = np.array([2,5,2,-2])

M = abs(A*B*C*D)
S = np.sign(A) + np.sign(B) + np.sign(C) + np.sign(D)
M = np.where( (S==4) + (S==-4) ,M,-M)

print M

rawDescription: Unconventional vector multiplication with numpy


code:
print next(combos) # next combination
print list(islice(combos, 3, 13)) # skip 3 and take another 10

rawDescription: Storing First X Items of a Large List (Python)


code:
import re
pattern = ur'(.*?)(\d+)(.*)'
s = u"ரூ.100"
match = re.match(pattern, s, re.UNICODE)
print match.group(1)
print match.group(2)

rawDescription: identifying if the character is a digit or Unicode character within a word in python

description: Identifying if the character is a digit or Unicode character within a word in python


code:
class Country(object):
    def __init__(self, continent='Europe', country='Great Britain'):
        print 'Continent: {}, Country: {}'.format(continent, country)

dictionary = {'continent': 'Africa', 'country': 'Zimbabwe'}
Country(**dictionary)
Country(**{'country': 'France'})

rawDescription: Assign default arguments to Python class members


code:
import bs4
from bs4 import BeautifulSoup

htmls = """
Background
x0

x1

Innovation
x2

x3

x4

Activities
x5

x6
"""
html = BeautifulSoup(htmls)

for n in html.find_all('b'):
    title_name = n.next_element
    title_content = n.nextSibling.nextSibling

    results = [title_content]
    for f in n.parent.find_next_siblings():
        el = f.next_element
        if isinstance(el, bs4.element.Tag) and el.name == 'b':
            break
        results.append(el)

    print title_name, results

rawDescription: Using BeautifulSoup to parse multiple paragraphs in Python


code:
import pickle
class A(object):
 def z(self): print "hi"

a = A()
pickle.dumps(a.z)

rawDescription: Why can I pass an instance method to multiprocessing.Process, but not a multiprocessing.Pool?


code:
min_pmt, final_balance = min_payment(balance, annualInterestRate)
print 'minimum payment', min_pmt
print 'final balance', final_balance

rawDescription: Get my search to solve only if solution is negative (MIT6.00)


code:
f = open('test.txt','rU')
for line in f:
    print line

rawDescription: Unable to read huge (20GB) file from CPython


code:
from xml.etree import ElementTree as ET

data = """<Faculty>
    <facultyMember>
        <FirstName>A</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>B</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>C</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>D</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>E</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>F</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>G</FirstName>
    </facultyMember>
    <facultyMember>
        <FirstName>H</FirstName>
    </facultyMember>

</Faculty>"""

tree = ET.fromstring(data)
begin, end = 3, 6

for element in tree.findall('.//facultyMember')[begin - 1: end]:
    print ET.tostring(element).strip()

rawDescription: Get Nodes from xml by specifying limit

description: Get Nodes from xml by specifying limit


code:
import sys

for fn in sys.argv[1:]:

    with open(fn,'r') as file:
        prev = 0
        for line in file:
            line = line.strip()
            if line[21:22] != prev:
                # new line separator for each group
                print ''
            print line
            prev = line[21:22]

rawDescription: file separation on the basis of matching character

description: File separation on the basis of matching character


code:
def getTotals():
    result = defaultdict(int)
    regexp = re.compile(r'(?:ttp_ws_sm|ttpv1)_(\d+)_')

    with open(os.path.join(source, 'ttp_13_08.csv'), 'r') as f:
        rows = csv.reader(f)

        #adds total values for each club code (from csv file)
        for row in rows:
            match = regexp.search(row[1])
            if match:
                result[match.group(1)] += int(row[13])
        data.update(result)

        for key in clubDict.viewkeys() & data:
            club_value, data_value = clubDict[key], data[key]
            if club_value == data_value:
                print 'match'
            else:
                print '{0}, {1}, {2}'.format(key, club_value, data_value)

rawDescription: Pull from two dictionaires based on keys, sometimes key isn't in one dictionary in python 2.7


code:
from bs4 import BeautifulSoup
html = '
 foo hi bar
'
soup = BeautifulSoup(html)
original_tag = soup.ul
new_tag = soup.new_tag('a', href='http://www.example.com')
new_tag.insert(0, 'Text!')
original_tag.append(new_tag)
print original_tag
# Prints:
#
 foo hi barText!

# If you don't want it to go to the last bit of the tag all the time,
# use original_tag.insert(). Here's a link to the documentation about it:
# http://www.crummy.com/software/BeautifulSoup/bs4/doc/#insert

rawDescription: How to add html attributes using python and BeautifulSoup

description: Add html attributes using python and BeautifulSoup


code:
d1 = {'one':1, 'both':3, 'falsey_one':False, 'falsey_both':None}
d2 = {'two':2, 'both':30, 'falsey_two':None, 'falsey_both':False}

print "d1 - d2:", {k:d1[k] for k in d1 if k not in d2}                  # 0
print "d2 - d1:", {k:d2[k] for k in d2 if k not in d1}                  # 1
print "intersection:", {k:d1[k] for k in d1 if k in d2}                      # 2
print "union:", {k:d1.get(k, k in d1 or d2[k]) for k in set(d1) | set(d2)}   # 3

rawDescription: How can I perform set operations on Python dictionaries?

description: Perform set operations on Python dictionaries


code:
def deltaC(r, s, sol):
    delta = 0
    sol_r, sol_s = sol[r], sol[s]
    for k in xrange(n):
        if k != r and k != s:
            delta += \
                stream_matrix[r][k] \
                * (distance_matrix[sol_s][sol[k]] - distance_matrix[sol_r][sol[k]]) + \
                stream_matrix[s][k] \
                * (distance_matrix[sol_r][sol[k]] - distance_matrix[sol_s][sol[k]]) + \
                stream_matrix[k][r] \
                * (distance_matrix[sol[k]][sol_s] - distance_matrix[sol[k]][sol_r]) + \
                stream_matrix[k][s] \
                * (distance_matrix[sol[k]][sol_r] - distance_matrix[sol[k]][sol_s])
    return delta

import numpy as np

def deltaC_np(r, s, sol):
    delta = 0
    sol_r, sol_s = sol[r], sol[s]

    if r==s:
        K=np.arange(n-1)
        K[r:] += 1
    else:
        K=np.arange(n-2)
        if r<s:
            K[r:] += 1
            K[s-1:] += 1
        else:
            K[s:] += 1
            K[r-1:] += 1
    #K = np.array([i for i in xrange(n) if i!=r and i!=s]) #TOO SLOW

    return np.sum(
        (stream_matrix_np[r,K] - stream_matrix_np[s,K]) \
        *  (distance_matrix_np[sol_s,sol[K]] - distance_matrix_np[sol_r,sol[K]]) + \
        (stream_matrix_np[K,r] - stream_matrix_np[K,s]) \
        * (distance_matrix_np[sol[K],sol_s] - distance_matrix_np[sol[K],sol_r]))

def deltaC2(r, s, sol):
    delta = 0
    sol_r, sol_s = sol[r], sol[s]
    for k in xrange(n):
        if k != r and k != s:
            sol_k = sol[k]
            delta += \
                (stream_matrix[r][k] - stream_matrix[s][k]) \
                * (distance_matrix[sol_s][sol_k] - distance_matrix[sol_r][sol_k]) \
                + \
                (stream_matrix[k][r] - stream_matrix[k][s]) \
                * (distance_matrix[sol_k][sol_s] - distance_matrix[sol_k][sol_r])
    return delta

import time

N=200

elapsed1s = []
elapsed2s = []
elapsed3s = []
ns = range(10,410,10)
for n in ns:
    distance_matrix_np=np.random.uniform(0,n**2,size=(n,n))
    stream_matrix_np=np.random.uniform(0,n**2,size=(n,n))
    distance_matrix=distance_matrix_np.tolist()
    stream_matrix=stream_matrix_np.tolist()
    sol  = range(n-1,-1,-1)
    sol_np  = np.array(range(n-1,-1,-1))

    Is = np.random.randint(0,n-1,4)
    Js = np.random.randint(0,n-1,4)

    total1 = 0
    start = time.clock()
    for reps in xrange(N):
        for i in Is:
            for j in Js:
                total1 += deltaC(i,j, sol)
    elapsed1 = (time.clock() - start)
    start = time.clock()

    total2 = 0
    start = time.clock()
    for reps in xrange(N):
        for i in Is:
            for j in Js:
                total2 += deltaC_np(i,j, sol_np)
    elapsed2 = (time.clock() - start)

    total3 = 0
    start = time.clock()
    for reps in xrange(N):
        for i in Is:
            for j in Js:
                total3 += deltaC2(i,j, sol_np)
    elapsed3 = (time.clock() - start)

    print n, elapsed1, elapsed2, elapsed3, total1, total2, total3
    elapsed1s.append(elapsed1)
    elapsed2s.append(elapsed2)
    elapsed3s.append(elapsed3)

    #Check errors of one method against another
    #err = 0
    #for i in range(min(n,50)):
    #    for j in range(min(n,50)):
    #        err += np.abs(deltaC(i,j,sol)-deltaC_np(i,j,sol_np))
    #print err
import matplotlib.pyplot as plt

plt.plot(ns, elapsed1s, label='Original',lw=2)
plt.plot(ns, elapsed3s, label='Optimized',lw=2)
plt.plot(ns, elapsed2s, label='numpy',lw=2)
plt.legend(loc='upper left', prop={'size':16})
plt.xlabel('matrix size')
plt.ylabel('time')
plt.show()

rawDescription: How to optimize math operations on matrix in python

description: Optimize math operations on matrix in python


code:
import gdal

def ReadBilFile(bil):

    gdal.GetDriverByName('EHdr').Register()
    img = gdal.Open(bil)
    band = img.GetRasterBand(1)
    data = band.ReadAsArray()
    return data

if __name__ == '__main__':
    a = ReadBilFile(r'G:\truncated\ppt\1950\PRISM_ppt_stable_4kmM2_1950_bil.bil')
    print a[44, 565]

rawDescription: Reading zipped ESRI BIL files with Python


code:
class TestClass:
    def __init__(self):
        self.myValue = 0
    def myMethod(self):
        pass
    def __dir__(self):
        return []

class TestClass1:
    def __init__(self):
        self.myValue = 0
    def myMethod(self):
        pass

print dir(TestClass())
print dir(TestClass1())

print dir(TestClass())
print dir(TestClass1())

rawDescription: dir and help not showing all attributes of an object in python?

description: Dir and help not showing all attributes of an object in python


code:
import sys
for arg in sys.argv:
    print arg

rawDescription: Passing command line parameters to IronPython from C# application?


code:
def do_raw_request(url, token, json_data=None, mode="get"):
    """Uploads a file. """
    header_collection = {"X-Auth-Token": token}
    if json_data is not None:
        header_collection['Content-Type'] = 'application/json'
    try:
        if mode == "delete":
            # this looks ugly, but there is absolutely no way to
            # get requests to do DELETE when there is a blank JSON
            # included
            r = requests.delete(url, headers=header_collection, timeout=10)
        else:
            r = getattr(requests, mode)(url, data=json.dumps(json_data),
                                        headers=header_collection, timeout=10)

        if r.status_code == 200:
                return r, r.status_code
        return r.text, r.status_code

    except requests.exceptions.ConnectionError:
        print "Connection Error! Http status Code {}".format(r.status_code)
        sys.exit()
    except (requests.exceptions.RequestException,
            requests.exceptions.HTTPError):
        print "Ambiguous Error! Http status Code {}".format(r.status_code)
        sys.exit()

rawDescription: Better way to write this Python function because of If conditions


rawDescription: finding longest path in a graph

description: Finding longest path in a graph


code:
class printobserver( CardObserver ):
    def update( self, observable, (addedcards, removedcards) ):
        for card in addedcards:
         if addedcards:
            hresult, hcontext = SCardEstablishContext(SCARD_SCOPE_USER)
            assert hresult==SCARD_S_SUCCESS
            hresult, readers = SCardListReaders(hcontext, [])
            assert len(readers)>0
            reader = readers[0]
            hresult, hcard, dwActiveProtocol = SCardConnect(
             hcontext,
             reader,
             SCARD_SHARE_SHARED,
             SCARD_PROTOCOL_T0 | SCARD_PROTOCOL_T1)
            hresult, response = SCardTransmit(hcard,dwActiveProtocol,[0xFF,0xCA,0x00,0x00,0x04])
            uid = toHexString(response, format=0)
            print response #cards ATR
            print uid #Cards UID

print "place card on reader"
while 1:
    cardmonitor = CardMonitor()
    cardobserver = printobserver()
    cardmonitor.addObserver( cardobserver )
    cardmonitor.deleteObserver( cardobserver )
    time.sleep( 2 )

rawDescription: Python ACR122U Poll

description: Python ACR122U Poll


code:
import re
import urllib2

opener = urllib2.build_opener()
page = opener.open("<the target URL>").read()
code = re.search('website\|([^|]+)\|',page).group(1)

opener.addheaders.append(('Cookie', 'website='+code+'; max-age=1600; path=/'))
r = opener.open("<the target URL>")
print r.read()

rawDescription: using urlopen to access a page with a javascript packer

description: Using urlopen to access a page with a javascript packer


code:
wordCounts = {}
word = wordEncountered
wordCounts[wordEncountered] = wordCounts.get(wordEncountered,default=0) + 1
print wordCounts

rawDescription: Running Total - Python

description: Running Total - Python


code:
class MySerial:
    def __init__(self,port,baudrate):
       self.ser = serial.Serial(port,baudrate)
    def query(cmd,terminal_char="\r"):
       self.ser.write(cmd)
       return ''.join(iter(ser.read,terminal_char))

s = MySerial("COM9",11200)
result = s.query("get -temp\r")
print result

rawDescription: Raspberry Pi is stuck when no char is received on the serial port


code:
import re
text= "I want to go to New York from Atlanta, business class, on 25th July."
destination= re.findall(r'.to.([A-Z][a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)',text)
source= re.findall(r'.from.([A-Z][a-zA-Z]+?[\s-]*[A-Z]*[a-zA-Z]*)',text)

print source,destination

rawDescription: Python NLTK interpret a fixed pattern of sentence and tokenize it


code:
def get_continuous_chunks(tagged_sent):
    continuous_chunk = []
    current_chunk = []

    for token, tag in tagged_sent:
        if tag != "O":
            current_chunk.append((token, tag))
        else:
            if current_chunk: # if the current chunk is not empty
                continuous_chunk.append(current_chunk)
                current_chunk = []
    # Flush the final current_chunk into the continuous_chunk, if any.
    if current_chunk:
        continuous_chunk.append(current_chunk)
    return continuous_chunk

ne_tagged_sent = [('Rami', 'PERSON'), ('Eid', 'PERSON'), ('is', 'O'), ('studying', 'O'), ('at', 'O'), ('Stony', 'ORGANIZATION'), ('Brook', 'ORGANIZATION'), ('University', 'ORGANIZATION'), ('in', 'O'), ('NY', 'LOCATION')]

named_entities = get_continuous_chunks(ne_tagged_sent)
named_entities = get_continuous_chunks(ne_tagged_sent)
named_entities_str = [" ".join([token for token, tag in ne]) for ne in named_entities]
named_entities_str_tag = [(" ".join([token for token, tag in ne]), ne[0][1]) for ne in named_entities]

print named_entities
print
print named_entities_str
print
print named_entities_str_tag
print

rawDescription: Extract list of Persons and Organizations using Stanford NER Tagger in NLTK


code:
class FactorFloat(float):
    def _factor_scale(f):
        def wrapper(self, *args, **kwargs):
            scaled = float.__mul__(self, FACTOR)
            result = f(scaled, *args, **kwargs)
            # if you want to return FactorFloats when possible:
            if isinstance(result, float):
                result = type(self)(result/FACTOR)
            return result
        return wrapper

    def __repr__(self):
        return '%s(%s)' % (type(self).__name__, float.__repr__(self))

    __str__ = _factor_scale(float.__str__)
    __mul__ = _factor_scale(float.__mul__)
    __div__ = _factor_scale(float.__div__)
    __add__ = _factor_scale(float.__add__)
    __sub__ = _factor_scale(float.__sub__)

f = FactorFloat(3.)
FACTOR = 10.
print f   # 30.0
print f-1 # 29.0
FACTOR = 2.
print f   # 6.0
print f-1 # 5.0
print repr(f)

rawDescription: An inheritance example in Python

description: An inheritance example in Python


code:
import sys

if len(sys.argv) > 1:
    print "First argument:", sys.argv[1]

rawDescription: How to get input from user when connecting to remote servers? [Python]

description: Get input from user when connecting to remote servers? [Python]


code:
import time

def do_a_little_work():
    time.sleep(0.1)

print "about to do work..."

icons = ["-", "/", "|", "\\"]
icon_idx = 0

while True:
    do_a_little_work()
    #todo: check if work is done, and break out of the loop.
    print "\r" + icons[icon_idx],
    icon_idx = (icon_idx+1)%len(icons)

print "\rdone."

rawDescription: Common practice for sub processes Python


code:
def regex():
    global text
    for paragraph in text.split('\n\n'):
        lines = paragraph.split('\n', 1)
        #personal modifier to choose certain output only
        if lines[0].startswith('C:\\:') or lines[0].startswith('C:\\WINDOWS\system32:') or lines[0].startswith('C:\\WINDOWS\\security:'):
            print lines[0]
            iterables = re.finditer(r".*Special Permissions: \n(\s+[a-zA-Z ]+\n)*", lines[1])
            for items in iterables:
                #cosmetic fix
                parsedText = re.sub(r"\n$", "", items.group(0))
                parsedText = re.sub(r"^\s+", "", parsedText)
                parsedText = re.sub(r"\n\s+", "\n", parsedText)
                print parsedText
            print

rawDescription: Regex for multiple lines checking

description: Regex for multiple lines checking


code:
class sentimentTweet:
    def __init__(self,d={}):
        sentiment_words = d

    def getTweetSentiment(self,tweet_text):
        sentiment = 0
        words = extractWordsFromTweet(tweet_text)
        for word in words:
            if word in self.sentiments_words:
                sentiment += self.sentiments_words[word] #sentiment_words is empty
        return sentiment

sTwitter= sentimentTweet(loadSentiments(open(sys.argv[1]))) #u r creating an instance of the class and loading it
print sTwitter.sentiment_words #Check, Try to print sentiment_words values

rawDescription: Assigning to global variable inside a function doesn't work


code:
from rdflib import Graph, URIRef, RDF
uri = URIRef('http://dbpedia.org/resource/Richard_Nixon')
person = URIRef('http://dbpedia.org/ontology/Person')

g = Graph()
g.parse(uri)

for obj in g.objects(subject=uri, predicate=RDF.type):
    if obj == person:
        print uri, "is a", person

rawDescription: Test for a resource type of a dbpedia page using rdflib and python


code:
import collections
instance = collections.defaultdict(lambda : None, {'city':'New York', 'year':2014})
print instance['id'], instance['year']

rawDescription: How to define default dictionary keys for sub-classed from built-in dictionary class

description: Define default dictionary keys for sub-classed from built-in dictionary class


code:
from itertools import groupby

with open('input.txt') as f1, open('f_out', 'w') as f2:
    #Firstly group the data by the first column
    for k, g in groupby(f1, key=lambda x:x.split()[0]):
        # Now during the iteration over each group, we need to store only
        # those lines that have unique 3rd and 4th column. For that we can
        # use a `set()`, we store all the seen columns in the set as tuples and
        # ignore the repeated columns.

        seen = set()
        for line in g:
            columns = tuple(line.rsplit(None, 2)[-2:])
            if columns not in seen:
                #The 3rd and 4th column were unique here, so
                # store this as seen column and also write it to the file.
                seen.add(columns)
                f2.write(line.rstrip() + '\n')
                print line.rstrip()

rawDescription: Printing unique elements in lines in a separate .txt file


code:
r = rrule(WEEKLY, byweekday=SA, count=10, dtstart=datetime.datetime(2008,10,01))
r2 = rrule(WEEKLY, byweekday=SA, count=r.count(), dtstart=r[-1] + datetime.timedelta(days=1))
print list(r)
print list(r2)

rawDescription: using existing rrule to generate a further set of occurrences

description: Using existing rrule to generate a further set of occurrences


code:
from functools import partial

clean = partial(filter, None)

def _apply(mols, fn, *args, **kwargs):
    f = partial(fn, *args, **kwargs)
    return map(f, clean(mols))

def foo(m, a, b, c=123):
    return [m, a, b, c]

print _apply([11,22,'',33], foo, 'aa', 'bb', c=475)

rawDescription: Applying function to iterable in python?

description: Applying function to iterable in python


code:
import numpy as np
from scipy import stats
from sklearn.neighbors import KernelDensity
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# Generate random data.
n = 1000
m1, m2 = np.random.normal(-3., 3., size=n), np.random.normal(-3., 3., size=n)
# Define limits.
xmin, xmax = min(m1), max(m1)
ymin, ymax = min(m2), max(m2)
ext_range = [xmin, xmax, ymin, ymax]
# Format data.
x, y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
positions = np.vstack([x.ravel(), y.ravel()])
values = np.vstack([m1, m2])

# Define some point to evaluate the KDEs.
x1, y1 = 0.5, 0.5
# Bandwidth value.
bw = 0.15

# -------------------------------------------------------
# Perform a kernel density estimate on the data using scipy.
# **Bandwidth needs to be scaled to match Sklearn results**
kernel = stats.gaussian_kde(
    values, bw_method=bw/np.asarray(values).std(ddof=1))
# Get KDE value for the point.
iso1 = kernel((x1, y1))
print 'iso1 = ', iso1[0]

# -------------------------------------------------------
# Perform a kernel density estimate on the data using sklearn.
kernel_sk = KernelDensity(kernel='gaussian', bandwidth=bw).fit(zip(*values))
# Get KDE value for the point. Use exponential since sklearn returns the
# log values
iso2 = np.exp(kernel_sk.score_samples([[x1, y1]]))
print 'iso2 = ', iso2[0]

# Plot
fig = plt.figure(figsize=(10, 10))
gs = gridspec.GridSpec(1, 2)

# Scipy
plt.subplot(gs[0])
plt.title("Scipy", x=0.5, y=0.92, fontsize=10)
# Evaluate kernel in grid positions.
k_pos = kernel(positions)
kde = np.reshape(k_pos.T, x.shape)
plt.imshow(np.rot90(kde), cmap=plt.cm.YlOrBr, extent=ext_range)
plt.contour(x, y, kde, 5, colors='k', linewidths=0.6)

# Sklearn
plt.subplot(gs[1])
plt.title("Sklearn", x=0.5, y=0.92, fontsize=10)
# Evaluate kernel in grid positions.
k_pos2 = np.exp(kernel_sk.score_samples(zip(*positions)))
kde2 = np.reshape(k_pos2.T, x.shape)
plt.imshow(np.rot90(kde2), cmap=plt.cm.YlOrBr, extent=ext_range)
plt.contour(x, y, kde2, 5, colors='k', linewidths=0.6)

fig.tight_layout()
plt.savefig('KDEs', dpi=300, bbox_inches='tight')

rawDescription: Relation between 2D KDE bandwidth in sklearn vs bandwidth in scipy


code:
import collections as c
lst = [7,7,7,7,3,1,5,5,1,4]
result = c.OrderedDict()
for el in lst:
    if el not in result.keys():
        result[el] = 1
    else:
        result[el] = result[el] + 1

print result

rawDescription: Duplicates counting with order order preserving in Python lists


rawDescription: Numpy sorting by increasing datetime

description: Numpy sorting by increasing datetime


rawDescription: Regex - Python: Capture three (3) words after a specific word


rawDescription: Why is numpy slower than python? How to make code perform better


code:
def pprint_multilines(linelen=80, separator=' ', line_separator=None,
                      align='left', align_char=' ', lists=[]):
    maxlen = max(len(lst) for lst in lists)
    printed_lines = ['']*len(lists)
    empty = True
    printed = False
    for i in xrange(maxlen):
        max_item_len = max(len(str(lst[i])) for lst in lists)
        if max_item_len + len(printed_lines[0]) + 1 > linelen:
            if printed and line_separator is not None:
                if len(line_separator) > 0:
                    print line_separator*(linelen/len(line_separator))
                else:
                    print
            for printed_line in printed_lines:
                print printed_line
            printed = True
            printed_lines = ['']*len(lists)
            empty = True
        for lst_idx, lst in enumerate(lists):
            if not empty:
                printed_lines[lst_idx] += separator
            if align == 'left':
                printed_lines[lst_idx] += str(lst[i]).ljust(max_item_len, align_char)
            else: # align == 'right'
                printed_lines[lst_idx] += str(lst[i]).rjust(max_item_len, align_char)
        else:
            empty = False
    if not empty:
        if printed and line_separator is not None:
            if len(line_separator) > 0:
                print line_separator*(linelen/len(line_separator))
            else:
                print
        for printed_line in printed_lines:
            print printed_line

rawDescription: In python, how can I print all the values for the same key from different dictionaries on top of one another?


code:
def my_func(choice_pattern, input):
    choice_iterator = choice_pattern.finditer(input, re.M)
    if choice_iterator:
        for choice in choice_iterator:
            print choice
            if get_yes_no_answer():
                return choice
    # If there is no choices or no matches, you end up here:
    print "No matches. Exiting..."
    sys.exit()

rawDescription: Testing for an empty iterator in a Python for... loop


code:
import pandas as pd
HashTable = {"chr1" : 1, "chr2" : 2, "chr3" : 3, "chr4" : 4, "chr5" : 5, "chr6" : 6, "chr7" : 7, "chr8" : 8, "chr9" : 9, "chr10" : 10, "chr11" : 11, "chr12" : 12, "chr13" : 13, "chr14" : 14, "chr15" : 15, "chr16" : 16, "chr17" : 17, "chr18" : 18, "chr19" : 19, "chrX" : 20, "chrY" : 21, "chrM" : 22, 'chrMT': 23}
# A dummy DataFrame with all the valid chromosomes and one unknown chromosome
df = pd.DataFrame({"Chrom": HashTable.keys() + ["unknown_chr"]})
# Filter for valid rows
df = df[df["Chrom"].isin(HashTable.keys())]
# Replace the values according to dict
df["Chrom"].replace(HashTable, inplace=True)
print df

rawDescription: Pandas: Change dataframe values based on dictionary and remove rows with no match


code:
class Tee(object):
    def __init__(self, *files):
        self.files = files
    def write(self, obj):
        for f in self.files:
            f.write(obj)

f = open('logfile', 'w')
backup = sys.stdout
sys.stdout = Tee(sys.stdout, f)

print "hello world"  # this should appear in stdout and in file

rawDescription: Python, logging print statements while having them print to stdout


code:
def gcd(a, b):
    while b > 0:
        a, b = b, a%b
    return a

class rational(object):
    def __init__(self, num, den=1):
        if isinstance(num, rational):
            self.copy(num)
        else:
            self.num = num
            self.den = den

    def copy(self, other):
        self.num = other.num
        self.den = other.den

    def __str__(self):
        return '{0} / {1}'.format(self.num, self.den)

    def lowest_terms(self):
        g = gcd(self.num, self.den)
        return rational(self.num // g, self.den // g)

    def __add__(self, other):
        other = rational(other)
        y = rational(self.num*other.den + other.num*self.den, other.den*self.den)
        return y.lowest_terms()

    def __radd__(self, other):
        return rational(other) + self

    def __iadd__(self, other):
        self.copy(self + rational(other))
        return self

a = rational(1, 4)
b = rational(2, 5)
c = a + b
print a
print b
print c
print c + 5
print 10 + c
c += 10
print c

rawDescription: how to tell Python that we always want to interpret an object of type Foo as an object of type Bar when there are conflicts?

description: Tell Python that we always want to interpret an object of type Foo as an object of type Bar when there are conflicts


code: print clear_screen_seq

rawDescription: Python - Clearing the terminal screen more elegantly


code:
import pandas
df = pandas.DataFrame({'col':['bbb','aaa','aaa','ccc']})
print df
print '-------------'

df2 = df.drop_duplicates()
df2['ranked'] = df2.rank(method='min')
print df.merge(df2, on='col')

rawDescription: How to get ranked values of a pandas column without gaps?

description: Get ranked values of a pandas column without gaps


code:
#-------------------------------------------------------------------------------

import pprint
import Library_SympyExpressionToPythonFunction
import Library_SympyExpressionToStringExpression
import sympy
import sympy.core

def Main(
    ApproximationSymbol = sympy.Symbol('x'),
    ResultType = 'sympy',
    Kind= None,
    Order= None,
    ReturnAll = False,
    CheckArguments = True,
    PrintExtra = False,
    ):

    Result = None

    if (CheckArguments):
        ArgumentErrorMessage = ""

        if (len(ArgumentErrorMessage) > 0 ):
            if(PrintExtra):
                print "ArgumentErrorMessage:\n", ArgumentErrorMessage
            raise Exception(ArgumentErrorMessage)

    ChebyChevPolynomials = []
    ChebyChevPolynomials.append(sympy.sympify(1.))
    ChebyChevPolynomials.append(ApproximationSymbol)

    #Generate the polynomial with sympy:
    for Term in range(Order + 1)[2:]:
        Tn = ChebyChevPolynomials[Term - 1]
        Tnminus1 = ChebyChevPolynomials[Term - 2]
        Tnplus1 = 2*ApproximationSymbol*Tn - Tnminus1

        ChebyChevPolynomials.append(Tnplus1.simplify().expand().trigsimp())

    if(PrintExtra): print 'ChebyChevPolynomials'
    if(PrintExtra): pprint.pprint(ChebyChevPolynomials)

    if (ReturnAll):
        Result = []
        for SympyChebyChevPolynomial in ChebyChevPolynomials:
            if (ResultType == 'python'):
                Result.append(Library_SympyExpressionToPythonFunction.Main(SympyChebyChevPolynomial))
            elif (ResultType == 'string'):
                Result.append(Library_SympyExpressionToStringExpression.Main(SympyChebyChevPolynomial))
            else:
                Result.append(SympyChebyChevPolynomial)

    else:
        SympyExpression = ChebyChevPolynomials[Order] #the last one

        #If the result type is something other than sympy, we can cast it into that type here:
        if (ResultType == 'python'):
            Result = Library_SympyExpressionToPythonFunction.Main(SympyExpression)
        elif (ResultType == 'string'):
            Result = Library_SympyExpressionToStringExpression.Main(SympyExpression)
        else:
            Result = SympyExpression

    return Result

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

rawDescription: Python Sympy Arbitrary Approximation to Arbitrary Sympy Expression?


code: print CreateTable(Model.__table__)

rawDescription: SQLAlchemy printing raw SQL from create()


code:
import pandas as pd

df = pd.read_csv('so.csv')
df_ = df.groupby(['D'])
# Result of above line is a tuple.
for g, v in df_:
    # Get max C of each group. Then get column B.
    x = v[v['C'] == v['C'].max()]['B'].iat[0]
    df.loc[df['D'] == g,'newval'] = x
print df

rawDescription: Pandas Adding new column from result of groupby


code:
from itertools import product

for a, b in product(list1, list2):
    if a + b == x:
        print a, b

rawDescription: How to create a function that uses 2 integers from 2 different lists and adding the pair to a certain integer?

description: Create a function that uses 2 integers from 2 different lists and adding the pair to a certain integer


code:
import timeit

def append2x(foo):
    foo.append(1)
    foo.append(1)

def extend_lst(foo):
    foo.extend([1,1])

def extend_tup(foo):
    foo.extend((1,1))

l1 = []
l2 = []
l3 = []

print timeit.timeit('append2x(l1)',setup = 'from __main__ import append2x,l1')
print timeit.timeit('extend_lst(l2)',setup = 'from __main__ import extend_lst,l2')
print timeit.timeit('extend_tup(l3)',setup = 'from __main__ import extend_tup,l3')

rawDescription: Python - append VS extend efficiency

description: Python - append VS extend efficiency


code:
name1 = "naveen"; name2 = "darshana"

count1={}
count2={}

for x in name1:
    count1[x]=count1.get(x,0)+1

for x in name2:
    count2[x]=count2.get(x,0)+1

def remove_dups(name,count,null):
    clean=[]
    for x in name:
        if count.get(x,0):
            count[x]-=1
        else:
            clean.append(x)
    clean.extend([null]*(len(name)-len(clean)))
    return clean

clean1=remove_dups(name1,count2,'0')
clean2=remove_dups(name2,count1,'1')

print clean1,clean2

rawDescription: Python Iteration Problem!

description: Python Iteration Problem!


code:
from lxml import etree

XML= """
<tag attrib1='I'>
  <subtag1 subattrib1='1'>
    <subtext>text1</subtext>
  </subtag1>
  <subtag3 subattrib3='3'>
    <subtext>text3</subtext>
  </subtag3>
</tag>"""

parser = etree.XMLParser(remove_blank_text=True)
tag = etree.fromstring(XML, parser)

subtag1 = doc.find("subtag1")
subtag2 = etree.Element("subtag2", subattrib2="2")
subtext = etree.SubElement(subtag2, "subtext")
subtext.text = "text2"
subtag1.addnext(subtag2)   # Add subtag2 as a following sibling of subtag1

print etree.tostring(tag, pretty_print=True)

rawDescription: lxml: insert tag at a given position

description: Lxml: insert tag at a given position


code:
for n in morris_generator(10):
    print n

rawDescription: Can anyone provide a more pythonic way of generating the morris sequence?


code:
data = """
Name         At time Last  Inter\ Max    Logfile Location               Status
                     time   val   log
                           (mins) files
------------ ------- ----- ------ ------ ------------------------------ -------
foo1           now   16:00   60   100    flash:/schedule/foo1/          Job under progress
foo2           now     -     60   100    -                              Waiting
tech-support   now   16:00   60   100    flash:/schedule/tech-support/  Job under progress
"""

print sum(1 for line in data.split("\n") if "Job under progress" in line)

rawDescription: Finding a pattern inside a string in Python


code:
def similarity(a,b):
    return sum(1 for p,q in zip(a,b) if p==q)

def pick(seq, superset, match):
    subset = []
    for item in superset:
        if similarity(item, seq) <= match and all(similarity(item, x) <= match for x in subset):
            subset.append(item)
    return subset

superset = [
    'GGG', 'GGC', 'GGA', 'GGT', 'GCG', 'GCC', 'GCA', 'GCT', 'GAG', 'GAC', 'GAA', 'GAT', 'GTG', 'GTC', 'GTA', 'GTT',
    'CGG', 'CGC', 'CGA', 'CGT', 'CCG', 'CCC', 'CCA', 'CCT', 'CAG', 'CAC', 'CAA', 'CAT', 'CTG', 'CTC', 'CTA', 'CTT',
    'AGG', 'AGC', 'AGA', 'AGT', 'ACG', 'ACC', 'ACA', 'ACT', 'AAG', 'AAC', 'AAA', 'AAT', 'ATG', 'ATC', 'ATA', 'ATT',
    'TGG', 'TGC', 'TGA', 'TGT', 'TCG', 'TCC', 'TCA', 'TCT', 'TAG', 'TAC', 'TAA', 'TAT', 'TTG', 'TTC', 'TTA', 'TTT'
]

seq = "AAA"

print pick(seq, superset, 1)

rawDescription: python: iterate through dynamic list

description: Python: iterate through dynamic list


code:
ls = ['a', 'b', 'c']
def abc():

    k= ls.pop(0)
    ls.append(k)
    return k

print abc()
print abc()
print abc()
print abc()
print abc()

rawDescription: How to make a function that will return items in a list one at a time?

description: Make a function that will return items in a list one at a time


code:
with open("f1") as f1,open("f2") as f2:
    if f1.read().strip() in f2.read():
         print 'found'

rawDescription: Comparing some data of a file with another file in python


code:
l = ['A','B','C','D']
for index, item in enumerate(l):
    print index
    print item

rawDescription: How do I get the key of an item when doing a FOR loop through a dictionary or list in Python?

description: Get the key of an item when doing a FOR loop through a dictionary or list in Python


code:
x = 4
y = 4
w = 9999
v = 9999
a = 12345678
b = 12345678
print hex(id(x))
print hex(id(y))
print hex(id(w))
print hex(id(v))
print hex(id(a))
print hex(id(b))

rawDescription: print memory address of Python variable

description: Print memory address of Python variable


code:
from lxml import etree
from StringIO import StringIO
xmlFile = '''
<xml>
<maintag>
<content> lorem ipsum <strong> dolor sit </strong> and so on </content>
</maintag>
</xml>
'''
parser = etree.XMLParser(remove_blank_text=False)
tree = etree.parse(StringIO(xmlFile), parser)
for my_content in tree.xpath('maintag/content//text()'):
      print my_content

rawDescription: lxml Xml Parsing

description: Lxml Xml Parsing


code:
import textwrap

class Interpreter:
    acc = 0
    defined = {}

    def read(self, cmd):
        cmd = textwrap.dedent(cmd).strip()
        lines = cmd.split("\n")
        for line in lines:
            print '==> parsing:', line
            self.parse(line)

    def parse(self, cmd):
        if cmd.startswith("def(") and cmd.endswith(")"):
            print '::found def',
            name, code = cmd[4:-1].split('|')  # def( is 4 characters..
            self.defined[name] = code.replace(';', '\n')  # read() expects commands divided by \n, so replace ; before storing in self.defined
            print self.defined

        elif cmd in self.defined:
            print '::found defined name', cmd, '=>', `self.defined[cmd]`
            self.read(self.defined[cmd])

        elif cmd == "i":
            self.acc = int(input(">> "))

        elif cmd == "p":
            print(self.acc)

        else:
            self.acc += int(cmd)

intp = Interpreter()
intp.read("""
    def(c|i;2)
    c
    p
""")

rawDescription: Interpreter written in Python not working properly


rawDescription: Smallest permutation of given number

description: Smallest permutation of given number


code:
for row in tree.xpath('//div[@id="mw-content-text"]/table[1]/tr')[1:]:
  st = row[0][0].text
  cap = row[3][0].text
  print 'The capital of %s is %s' % (st, cap)

rawDescription: Webscraping with Xpath in Python

description: Webscraping with Xpath in Python


code:
for element in L:
    print element

rawDescription: How does this program in python work?

description: How does this program in python work


code:
from threading import Timer
import thread

def run_with_timeout( timeout, func, *args, **kwargs ):
    """ Function to execute a func for the maximal time of timeout.
    [IN]timeout        Max execution time for the func
    [IN]func           Reference of the function/method to be executed
    [IN]args & kwargs  Will be passed to the func call
    """
    try:
        # Raises a KeyboardInterrupt if timer triggers
        timeout_timer = Timer( timeout, thread.interrupt_main )
        timeout_timer.start()
        return func( *args, **kwargs )
    except KeyboardInterrupt:
        print "run_with_timeout timed out, when running '%s'" %  func.__name__
        #Normally I raise here my own exception
    finally:
        timeout_timer.cancel()

rawDescription: How to see if section of python code completes within a given time

description: See if section of python code completes within a given time


code:
import re
import time
t = time.time()
obj = re.compile('{.*?: (\d*?)}')
with open('datafile.txt', 'r') as f:
    data = f.read()
s = set(m.group(1) for m in obj.finditer(data))
s = set(map(int, s))
print time.time() - t

rawDescription: Python- find the unique values from a large json file efficienctly


code:
import boto.ec2
conn = boto.ec2.connect_to_region("eu-west-1")
groups = conn.get_all_security_groups()
for group in groups:
    print group.name
    for rule in group.rules:
        print rule.ip_protocol, rule.from_port, rule.to_port, rule.grants

rawDescription: BOTO : How to retrieve ipRanges from a security group object?


code:
unique_blocks_template = remove_duplicate_blocks(template)
print unique_blocks_template
string.Template(unique_blocks_template).safe_substitute(blocks)

rawDescription: How to build a regular expression from predefined blocks

description: Build a regular expression from predefined blocks


code:
'''
1. We only need to test for factors up to the square root of num.
2. Unless we are at the end, we only care about the number of numbers,
   not storing them in a list.
3. xrange is better than range in this case.
4. Since 501 is odd, the number must be a perfect square.
'''

def divisors_count(sqrt):
    num = sqrt * sqrt
    return sum(2 for item in xrange(1, sqrt) if num % item == 0) + 1

def divisors(sqrt):
    num = sqrt * sqrt
    for item in xrange(1, sqrt):
        if num % item == 0:
            numbers.append(item)
            numbers.append(item / sqrt)
    numbers.append(sqrt)
    return sorted(numbers)

sqrt = 1
while divisors_count(sqrt) != 501:
    if sqrt % 500 == 0:
        print sqrt * sqrt
    sqrt += 1
print triangle_numbers(sqrt)
print sqrt * sqrt

rawDescription: Make sure python script is still running


code:
S = pd.DataFrame(
    np.array([[1.2,3.4],[1.1,3.5],[1.4,3.3],[1.2,1.6]]),
    columns=["Stock A","Stock B"],
    index=pd.date_range("2014-01-01","2014-01-04",freq="D")
)

indicator = S > S.mean()
binary = indicator.astype("int")
print S
print indicator
print binary

rawDescription: Pandas / Numpy: Issues with np.where

description: Pandas / Numpy: Issues with np.where


code:
for i, a in enumerate(A):
    print fmt % ((i, ) + tuple(a))

rawDescription: Elegant way to print formatted list together with index values in python?


code:
def statement_constructor(list_type, list_size):
    template_string = ""
    input_string = ""
    for z in range(list_size):
        string_part = "{" + str(z) + ":<8} "
        template_string += string_part
        if list_type == "signs_list":
            input_part = "'x' if len(signs_list[" \
                + str(z) + "]) >= i else '',"
        else:
            input_part = list_type + "[" + str(z) + "],"
        input_string += input_part
    statement = "('" + template_string + "')"
    statement += ".format"
    statement += "(" + input_string[:-1] + ")"
    return statement

length = len(test_string_list)
for i in range(len(max(signs_list)), 0, -1):
    print eval(statement_constructor('signs_list', length))
print eval(statement_constructor('test_list', length))
print eval(statement_constructor('test_string_list', length))

rawDescription: Basic Python List Excercise

description: Basic Python List Excercise


code:
for dict in a:
    for key,list in dict.iteritems():
        print '{} : {}'.format(key,list)

rawDescription: iterating through a list of dictionary names

description: Iterating through a list of dictionary names


code:
import numpy as np
from sets import Set

with open('maze.txt') as buffer:
    M = np.matrix(list(map(int, line.strip()) for line in buffer))

print M

def encontra_inicio(matriz):  # retorna (x,y) do inicio
    foo = np.where(M == 2)
    return foo[0][0], foo[1][0]

def freePath(M, xy, visited):
    print str(xy) + '->',
    x = xy[0]
    y = xy[1]
    if M[x+1, y] == 3 or M[x-1, y] == 3 or M[x, y+1] == 3 or M[x, y-1] == 3:
        print 'FINISHED!'
        return
    if M[x+1, y] == 0 and not (x+1, y) in visited:
        visited.add((x+1, y))
        freePath(M, (x+1, y), visited)
    if M[x-1, y] == 0 and not (x-1, y) in visited:
        visited.add((x-1, y))
        freePath(M, (x-1, y), visited)
    if M[x, y+1] == 0 and not (x, y+1) in visited:
        visited.add((x, y+1))
        freePath(M, (x, y+1), visited)
    if M[x, y-1] == 0 and not (x, y-1) in visited:
        visited.add((x, y-1))
        freePath(M, (x, y-1), visited)
    return

visited = Set([])
xy = encontra_inicio(M)
freePath(M, xy, visited)

rawDescription: Creating GRAPH, making the link of the elements only if a IF test = TRUE


code:
source
# adapted from http://stackoverflow.com/questions/3485428/creating-multiple-ssh-connections-at-a-time-using-paramiko

import signal, sys, threading
import paramiko

CMD = 'tail -f /var/log/syslog'

def signal_cleanup(_signum, _frame):
    print '\nCLEANUP\n'
    sys.exit(0)

def workon(host):

    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(host)
    _stdin, stdout, _stderr = ssh.exec_command(CMD)

    for line in stdout:
        print threading.current_thread().name, line,

def main():
    hosts = ['localhost', 'localhost']

    # exit after a few seconds (see WARNINGs)
    signal.signal(signal.SIGALRM, signal_cleanup)
    signal.alarm(3)

    threads = [
        threading.Thread(
            target=workon,
            args=(host,),
            name='host #{}'.format(num+1)
            )
        for num,host in enumerate(hosts)
        ]

    print 'starting'
    for t in threads:
        # WARNING: daemon=True allows program to exit when main proc
        # does; otherwise we'll wait until all threads complete.
        t.daemon = True
        t.start()

    print 'joining'
    for t in threads:
        # WARNING: t.join() is uninterruptible; this while loop allows
        # signals
        # see: http://snakesthatbite.blogspot.com/2010/09/cpython-threading-interrupting.html
        while t.is_alive():
            t.join(timeout=0.1)

    print 'done!'

if __name__=='__main__':
    main()

rawDescription: Python process hanging due to open Paramiko ssh connections


code:
alt = Cmd("Alt")
alt.left = Cmd("Left", alt)
alt.left.up = Cmd("Up", alt.left)

print alt()
print alt.left()
print alt.left.up()

rawDescription: Hierarchical option tree in python

description: Hierarchical option tree in python


code:
cur.execute("SELECT * FROM bar WHERE thing = 'bar'; SELECT * FROM bar")
print cur.fetchall()

# output
(('bar',),)

rawDescription: How do you change the SQL isolation level from Python using MySQLdb?

description: Change the SQL isolation level from Python using MySQLdb


code:
import mock

def foo():
    for line in open('myfile'):
        print line

def test_foo():
    open_mock = mock.MagicMock()
    with mock.patch('__builtin__.open', open_mock):
        foo()
        assert open_mock.called

rawDescription: Mocking file objects or iterables in python


code:
for c in chunks(l, 4):
    print c

rawDescription: How do I interpret this Python Code?

description: Interpret this Python Code


rawDescription: is it possible to convert this loop into a list comprehension in python

description: Is it possible to convert this loop into a list comprehension in python


code:
with open(filename, 'r') as f:
    for line in f:
        value = mydict.get(line.strip())
        if value is not None:
            print value

rawDescription: Reading a text file and matching it to a dictionary key in python


code:
a = [{'entity': 'first entity', 'place': ['first', 'second', 'abc']}, {'entity': 'second entity', 'place': ['awe', 'ert']}]
for x in a:
    print '-', x['entity']
    print '-', ','.join(x['place'])

rawDescription: How to iterate through a python list of dictionaries

description: Iterate through a python list of dictionaries


code:
results = []
while True:
    try:
        wait.until(wait_for_more_than_n_elements((By.CSS_SELECTOR, "div.flightbox"), len(results)))
    except TimeoutException:
        break

    results = self.driver.find_elements_by_css_selector("div.flightbox")
    print len(results)

    # scroll
    for _ in xrange(5):
        try:
            self.driver.execute_script("""
                arguments[0].scrollIntoView();
                window.document.body.scrollTop = 0;
                window.document.body.scrollTop = document.body.scrollHeight;
                arguments[1].scrollIntoView();
            """, results[0], results[-1])
        except StaleElementReferenceException:
            break  # here it means more results were loaded

print "DONE. Result count: %d" % len(results)

rawDescription: PhantomJS acts differently than Firefox webdriver


code:
#Snippet taken from http://stackoverflow.com/a/526450/846892
try:
    offset = int(strs[-5:])
except:
    print "Error"

delta = timedelta(hours = offset / 100)

rawDescription: Convert timestamps of "yyyy-MM-dd'T'HH:mm:ss.SSSZ" format in Python


code:
#!/usr/bin/env python
"""Start process; wait 2 seconds; kill the process; print all process output."""
import subprocess
import tempfile
import time

def main():
    # open temporary file (it automatically deleted when it is closed)
    #  `Popen` requires `f.fileno()` so `SpooledTemporaryFile` adds nothing here
    f = tempfile.TemporaryFile()

    # start process, redirect stdout
    p = subprocess.Popen(["top"], stdout=f)

    # wait 2 seconds
    time.sleep(2)

    # kill process
    #NOTE: if it doesn't kill the process then `p.wait()` blocks forever
    p.terminate()
    p.wait() # wait for the process to terminate otherwise the output is garbled

    # print saved output
    f.seek(0) # rewind to the beginning of the file
    print f.read(),
    f.close()

if __name__=="__main__":
    main()

rawDescription: Stop reading process output in Python without hang?


code:
noun_1 = ""
noun_2 = ""
verb = ""
adjective = ""

def ask():
    global noun_1, noun_2, verb, adjective
    noun_1=raw_input("Enter a noun:")
    verb=raw_input("Enter a verb:")
    adjective=raw_input("Enter a adjective:")
    noun_2=raw_input("Enter another noun:")

def main():
    ask()
    print noun_1,verb,adjective,noun_2

main()

rawDescription: In python I am trying to make a simple english sentence. Please help:


code:
import collections

d={    'k1': [1,2,3],
       'k2': 2,
       'k3': [10],
       'k4': [3,2],
       'k5': 'string',
       'k6': ['string',2]
    }

com_keys={}
for k, v in d.items():
    if not isinstance(v, basestring) and isinstance(v, collections.Iterable):
        for e in v:
            com_keys.setdefault(e, set()).add(k)
    else:
        com_keys.setdefault(v, set()).add(k)

print com_keys
# {1: set(['k1']), 10: set(['k3']), 3: set(['k1', 'k4']), 2: set(['k2', 'k1', 'k6', 'k4']), 'string': set(['k6', 'k5'])}
print {k:v for k,v in com_keys.items() if len(v)>1 }
# {2: set(['k2', 'k1', 'k6', 'k4']), 3: set(['k1', 'k4']), 'string': set(['k6', 'k5'])}

rawDescription: Common items between all the keys of a dictionary


code:
elements = []
for letter in list1:
    elements.append([''.join(c) for c in product(letter, list2)])
    for combo in product(*elements):
        print combo

rawDescription: lists permutation in python

description: Lists permutation in python


code:
from twisted.conch.ssh import transport, connection, userauth, channel, common
from twisted.internet import defer, protocol, reactor
import sys, struct

USER = 'username'
PASS = 'thisisforpersonalusesoicanstoreit!'
CMD  = 'echo "merely this and nothing more"'

from twisted.python import log
import sys
log.startLogging(sys.stdout)

class ClientCommandTransport(transport.SSHClientTransport):
    def __init__(self, username, password, command, factory):
        self.username = username
        self.password = password
        self.command  = command
        self.factory = factory

    def verifyHostKey(self, pubKey, fingerprint):
        print fingerprint
        return defer.succeed(True)

    def connectionSecure(self):
        self.requestService(
            PasswordAuth(self.username, self.password,
                         ClientConnection(self.command, self.factory)))

class PasswordAuth(userauth.SSHUserAuthClient):
    def __init__(self, user, password, connection):
        userauth.SSHUserAuthClient.__init__(self, user, connection)
        self.password = password

    def getPassword(self, prompt=None):
        return defer.succeed(self.password)

class ClientConnection(connection.SSHConnection):
    def __init__(self, cmd, *args, **kwargs):
        connection.SSHConnection.__init__(self)
        self.command = cmd
        self.factory = factory

    def serviceStarted(self):
        self.openChannel(CommandChannel(self.command, self.factory, conn=self))

class CommandChannel(channel.SSHChannel):
    name = 'session'

    def __init__(self, command, factory, *args, **kwargs):
        channel.SSHChannel.__init__(self, *args, **kwargs)
        self.command = command
        self.data = ''
        self.factory = factory
        self.factory.num_connections += 1
        self.factory.connections.append(self)

    def channelOpen(self, data):
        self.conn.sendRequest(
            self, 'exec', common.NS(self.command), wantReply=True).addCallback(
                                                            self._gotResponse)

    def _gotResponse(self, _):
        self.conn.sendEOF(self)
        self.loseConnection()
        self.factory.num_connections -= 1
        self.factory.connections.remove(self)
        if self.factory.num_connections == 0:
            reactor.stop()

    def dataReceived(self, data):
        #self.data += data
        print data

    def request_exit_status(self, data):
        (status,) = struct.unpack('>L', data)
        # print 'exit status = ', status

class ClientCommandFactory(protocol.ClientFactory):
    def __init__(self, command=CMD):
        self.username = USER
        self.password = PASS
        self.command  = command
        self.connections = []
        self.num_connections = 0

    def buildProtocol(self, addr):
        protocol = ClientCommandTransport(
            self.username, self.password, self.command, self)
        return protocol

masters = ['server1','server2','server3','server4','server5']

factory = ClientCommandFactory()

for server in masters:
    print server
    reactor.connectTCP(server, 22, factory)

reactor.run()

rawDescription: Python Twisted Conch - How to stop Reactor with multiple Connections?


code:
import itertools as it
res = list(''.join(p) for p in it.permutations('Mick'))
print res

rawDescription: visualisation of recursion in a for loop in Python

description: Visualisation of recursion in a for loop in Python


code:
for key,value in mydict:
    if element in value:
        print "Element in %s " %(key)

rawDescription: How to print the variables represent instead of the variable?

description: Print the variables represent instead of the variable


code:
import subprocess, threading
import os,signal
class Command(object):
    def __init__(self, cmd):
        self.cmd = cmd
        self.process = None

    def run(self, timeout):
        def target():
            print 'Thread started'
            self.process = subprocess.Popen(self.cmd, shell=True, preexec_fn=os.setsid)
            self.process.communicate()
            print 'Thread finished'

        thread = threading.Thread(target=target)
        thread.start()

        thread.join(timeout)
        if thread.is_alive():
            print 'Terminating process'
            os.killpg(self.process.pid, signal.SIGTERM)
            thread.join()
        print self.process.returncode

command = Command("echo 'Process started'; sleep 2; echo 'Process finished'")
command.run(timeout=3)
command.run(timeout=1)

rawDescription: How to call a system command with specified time limit in Python?

description: Call a system command with specified time limit in Python


code:
PrefilledDict = NewDict()
print PrefilledDict.Key1

rawDescription: I want to subclass dict and set default values


code:
import re
fabric = ['Combed Cotton', 'Polyester', 'Organic Cotton', 'Certified Organic Cotton', 'Bamboo Viscose']
fabric_type = ['Brushed 3-ply', 'Fine Jersey']

test_cases = [
    "80% Combed Cotton 20% Polyester Brushed 3-ply 320 g/m2",
    "70% Bamboo Viscose 30% Organic Cotton Fine Jersey 115g / 3.4 oz"]

fabric_rx = re.sub("\s+","\s+","|".join(fabric))
fabric_type_rx = re.sub("\s+","\s+","|".join(fabric_type))

expr = "(?:\d{1,3}\%\s(?:"+ fabric_rx +")(?:\s+))|(?:"+ fabric_type_rx +"(?:\s+))|(?:.{2,})"
rx = re.compile(expr)

for test in test_cases:
    results = re.findall(rx, test)
    for idx, item in enumerate(results):
        results[idx] = item.strip()
    print results

rawDescription: python split using re and a lookup to a list

description: Python split using re and a lookup to a list


code:
#!/usr/bin/env python

''' Convert Unix Epoch seconds to (proleptic) Gregorian date

    Algorithm by E. G. Richards, https://en.wikipedia.org/wiki/Julian_day

    See http://stackoverflow.com/q/35796786/4014959

    Python implementation by PM 2Ring 2016.03.07
'''

from time import time, gmtime
from random import randint
import sys

def epoch_seconds_to_gregorian_date(eseconds):
    # Algorithm parameters for Gregorian calendar
    y = 4716; j = 1401; m = 2; n = 12; r = 4; p = 1461
    v = 3; u = 5; s = 153; w = 2; B = 274277; C = -38

    #Julian day, rounded
    J = int(0.5 + eseconds / 86400.0 + 2440587.5)

    #Date calculation
    f = J + j + (((4 * J + B) // 146097) * 3) // 4 + C
    e = r * f + v
    g = (e % p) // r
    h = u * g + w
    D = (h % s) // u + 1
    M = (h // s + m) % n + 1
    Y = (e // p) - y + (n + m - M) // n

    #Time calculation
    seconds = eseconds % 86400
    t = int(seconds)
    hr, t = divmod(t, 3600)
    mn = t // 60
    seconds -= 3600 * hr + 60 * mn

    return Y, M, D, hr, mn, seconds

# Tests
def test(s):
    t = gmtime(s)
    gmdate = t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec
    e2gdate = epoch_seconds_to_gregorian_date(s)
    assert gmdate == e2gdate, (s, gmdate, e2gdate)
    return '%d.%02d.%02d %02d:%02d:%06.3f' % e2gdate

print 'now'
s = time()
print s, epoch_seconds_to_gregorian_date(s), gmtime(s)

print '\nhours'
for i in xrange(25):
    s = 3600 * i
    print i, test(s)

print '\ndays'
for i in xrange(32):
    s = 86400 * i
    print i, test(s)

print '\n2 days by seconds...'
for i in xrange(86400 * 2):
    test(i)
    if i % 10000 == 0:
        sys.stderr.write('.')
sys.stderr.write('\n')

n = 50
print '\n%d years by days...' % n
for i in xrange(365 * n):
    s = 86400 * i
    test(s)

n = 500000
print '\nRandom seconds'
for i in xrange(n):
    s = randint(0, 2147483647)
    test(s)
    if i % 10000 == 0:
        sys.stderr.write('.')
sys.stderr.write('\n')

print 'Ok'

rawDescription: How to calculate the current month from python time.time()

description: Calculate the current month from python time.time()


code:
with open('text.txt', 'r') as theOpenFile:
    highest = 0
    for myCurrentString in theOpenFile:
        stringArray = myCurrentString.split()

        try:
            series = float(stringArray[0].split('.')[0])
        except ValueError:
            # The input wasn't a number, so we just skip it and go on
            # to the next one
            continue

        if series > highest:
            highest = series
            print "Highest = " + series

        print series

rawDescription: Simple Python headache with number comparison


code:
d = {
  'dev': {
    'dev1': {
      'mod': {
        'mod1': {'port': [1, 2, 3]},
      },
    },
    'dev2': {
      'mod': {
        'mod3': {'port': []},
      },
    },
  },
}

print list(find_parent_keys(d, 'mod'))
print list(find_parent_keys(d, 'dev'))

rawDescription: Finding a parent key from a dict given an intermediate key using python


code:
for s in inputtext.splitlines(True):
    print ri.match(s).groups()

rawDescription: Python regex format

description: Python regex format


code:
from banyan import SortedSet, OverlappingIntervalsUpdator # pip install banyan

def maximize_nonoverlapping_count(intervals):
    # sort by the end-point O(n log n)
    sorted_intervals = SortedSet(intervals,
                                 key=lambda (start, end): (end, (end - start)))
    # build "interval" tree O(n log n)
    tree = SortedSet(intervals, updator=OverlappingIntervalsUpdator)
    result = []
    while sorted_intervals: # until there are intervals left to consider
        # pop the interval with the smallest end-point, keep it in the result
        result.append(sorted_intervals.pop()) # O(log n)

        # remove intervals that overlap with the popped interval
        overlapping_intervals = tree.overlap(result[-1]) # O(m log n)
        tree -= overlapping_intervals # O(m log n)
        sorted_intervals -= overlapping_intervals # O(m log n)
    return result

rawDescription: Python - Removing overlapping lists

description: Python - Removing overlapping lists


code: print '%*s : %*s' % (20, "Python", 20, "Very Good")

rawDescription: Format string dynamically

description: Format string dynamically


code:
#!/usr/bin/python
# Alternative Implementation with ElementTree XML Parser

xml = '''\
<Emps>
    <Emp>
        <Name>Raja</Name>
        <Location>
            <city>ABC</city>
            <geocode>123</geocode>
            <state>XYZ</state>
        </Location>
        <sal>100</sal>
        <type>temp</type>
    </Emp>
    <Emp>
        <Name>GsusRecovery</Name>
        <Location>
            <city>Torino</city>
            <geocode>456</geocode>
            <state>UVW</state>
        </Location>
        <sal>120</sal>
        <type>perm</type>
    </Emp>
</Emps>
'''

from xml.etree import ElementTree as ET
# tree = ET.parse('input.xml')  # decomment to parse xml from file
tree = ET.ElementTree(ET.fromstring(xml))
root = tree.getroot()

for location in root.iter('Location'):
    if location.find('city').text == 'Torino':
        location.set("isupdated", "1")
        location.find('city').text = 'MyCity'
        location.find('geocode').text = '10.12'
        location.find('state').text = 'MyState'

print ET.tostring(root, encoding='utf8', method='xml')
# tree.write('output.xml') # decomment if you want to write to file

rawDescription: Replace xml tag contents using python

description: Replace xml tag contents using python


code:
myfile = [line.rstrip('\n') for line in open('path/to/myfile')]
for element in myarray:
    elementstring=''.join(element)
    for line in myfile:
        if elementstring in line:
            print line

rawDescription: Python nested for loop to match strings in array elements to a file


code:
import pandas

data = [
    [1975,'a','b'],
    [1976,'b','c'],
    [1977,'b','a'],
    [1977,'a','b'],
    [1978,'c','d'],
    [1979,'e','f'],
    [1980,'a','f'],
]

birthdate = [
    [1975,'a'],
    [1975,'b'],
    [1976,'c'],
    [1978,'d'],
    [1979,'f'],
    [1979,'e']
]

df1 = pandas.DataFrame(data, columns = ['Date', 'Item1', 'Item2'])
df2 = pandas.DataFrame(birthdate, columns = ['Birthdate', 'Item'])

#print df1
#print df2

newdf = pandas.merge(left=df1, right=df2, left_on='Item1', right_on='Item')

print newdf

print newdf[ newdf['Birthdate'] > 1975 ]

rawDescription: Selecting rows in one dataframe based on data in another dataframe in Python Pandas


code:
import pandas as pd

########### Setup some test data: #############
s = """id|Country|Year|Export|Macro|Code|Codename|Value
1|China|2012|1|69|6996700|Articles,of iron or steel wire,n.e.s.|0.0
2|Germany|2012|1|69|6996700|Articles,of iron or steel wire,n.e.s.|59.9
3|Germany|2013|1|69|6996700|Articles,of iron or steel wire,n.e.s.|80.0
4|Germany|2013|1|69|6996700|Articles,of iron or steel wire,n.e.s.|40.0
5|Italy|2012|1|69|6996700|Articles,of iron or steel wire,n.e.s.|33.2"""

from StringIO import StringIO
df = pd.read_csv(StringIO(s), sep='|')

pd.Series.__unicode__ = pd.Series.to_string # suppress meta-data when printing

########### The real stuff happens here: #############
macro = 69
group_by = df[df.Macro == macro].groupby(['Country', 'Year'])['Value'].sum()

for country in df.Country.unique():
    print '---', country, '---'
    print group_by[country]
    print

rawDescription: Pandas stats plain table

description: Pandas stats plain table


code:
string1 = "Sony Xperia Z2 m/Smartwatch 2"
print re.split(" m/| \+ ", string1)[1]
# output: Smartwatch 2

rawDescription: Python Regex to match and exclude certain content


code:
def main():
    a = float(raw_input("Enter the first number: "))
    b = float(raw_input("Enter the second number: "))

    print "Your answer is: ",(a*b)

main()

rawDescription: How to turn a script into a function

description: Turn a script into a function


rawDescription: Python: Calculate all values of dictionary to z-scores


code:
track = 0
hash = int(size/80)
while True:
    r, w, x = select.select([chan], [], [])
    if chan in r:
        data = chan.recv(1024)
        if len(data) == 0:
            break
        os.write(fp[0], data)
        track = track + len(data)
        if transport.packetizer.need_rekey():
            sys.stdout.write('Z')
            sys.stdout.flush()
            time.sleep(1)
        if track > hash:
            sys.stdout.write('.')
            sys.stdout.flush()
            track = 0
print ''

rawDescription: How to compensate for Paramiko rekey failures?

description: Compensate for Paramiko rekey failures


rawDescription: Tokenization using regexp in Python

description: Tokenization using regexp in Python


code:
def static_var(varname, value):
    def decorate(func):
        setattr(func, varname, value)
        return func
    return decorate

@static_var("counter", 0)
def foo():
    foo.counter += 1
    print "Counter is %d" % foo.counter

rawDescription: static variable in a function with Python Decorator

description: Static variable in a function with Python Decorator


code:
import operator
sorted_return_message = sorted(return_message.iteritems(), key=operator.itemgetter(0))
for k,v in sorted_return_message: print k

rawDescription: Sort nodes after using getElementsByTagName by the nodes attributes


code:
import random

def main():
  def process(data):
     return data + [0]
  def process1(data):
     return data + [9]
  def process2(data):
     return data + [7]
  def run(data):
     test = random.choice([process,process1,process2])
     print test(data)
  for i in range(7):
    run([1, 2, 3])

main()

rawDescription: use random functions (python)

description: Use random functions (python)


rawDescription: Convert binary string to int

description: Convert binary string to int


code:
print df

#            Prediction  MAPE  Score
#
#2015-11-01        7.93  1.83      1

print df.index

#DatetimeIndex(['2015-11-01'], dtype='datetime64[ns]', name=u'', freq=None)

df.index = df.index.to_period('M')
print df

#         Prediction  MAPE  Score
#
#2015-11        7.93  1.83      1

rawDescription: Python/Datetime/Pandas - Changing datetime format


code:
def foo(L = []):
  print id(L)
  L.append(1)
  print id(L)
  print L

foo()
foo()
foo()

rawDescription: Default values for arguments

description: Default values for arguments


code:
options = {0 : zero,
                1 : sqr,
                4 : sqr,
                9 : sqr,
                2 : even,
                3 : prime,
                5 : prime,
                7 : prime,
}

def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

rawDescription: How to use switch in Python?

description: Use switch in Python


code:
from random import randint
from Tkinter import *

class GUI:
    def __init__(self, master):

        frame = Frame(master)
        frame.pack()

        self.rooms = Button(frame, text = "All Rooms", fg = "blue",
                            command=self.allrooms)
        self.rooms.pack(side=LEFT)

        self.alsoquit = Button(frame, text = "Quit", fg = "green",
                               command=frame.quit)
        self.alsoquit.pack(side=LEFT)

        self.displaytext = StringVar()
        self.displaytext.set("hello")
        self.displaytext.trace("w", self.callback)  # <---
        self.display = Label(master, textvariable=self.displaytext)  # <---
        self.display.pack(side=LEFT)

    def callback(*args):
        print "variable changed!"

    def roomselect(self, random):
        if random == 1:
            self.displaytext.set("The Chest!")
        elif random == 2:
            self.displaytext.set("Dark Chest")
        elif random == 3:
            self.displaytext.set("Hush")
        else:
            quit()

    def allrooms(self):
        random = randint(1,3)
        self.roomselect(random)

root = Tk()
app = GUI(root)
root.mainloop()

rawDescription: tkinter labels, or "updating variables in a loop"

description: Tkinter labels, or "updating variables in a loop"


code:
import xmlrpclib

s = xmlrpclib.ServerProxy('http://localhost:8000')
print s.pow(2,3)  # Returns 2**3 = 8
print s.add(2,3)  # Returns 5
print s.div(5,2)  # Returns 5//2 = 2

# Print list of available methods
print s.system.listMethods()

rawDescription: Create a SimpleHTTPServer to use the python code as API


code:
d = {}
exec "def f(x): return x" in d

rawDescription: creating a function object from a string

description: Creating a function object from a string


code:
import re
x = open("logssss.txt")

dic={}

for line in x:
    m = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b",line).group().split()
    c = re.search(r"\[(.+)\]",line).group().split()
    for i in range(len(m)):
        try:
            dic[m[i]] += 1
        except:
            dic[m[i]] = 1

for k,v in dic.iteritems(): #or items if Python 3.X
    print k, v

rawDescription: Counting number of unique items from a dictionary


code:
for t in range(150):
    QRAIN1 = [1000*np.mean(QC[t,z,:,:]) for z in range(279)]
    print len(QRAIN1)
    QRAIN.append(QRAIN1)
QR = np.array(QRAIN)

rawDescription: Separate the first loop append and the second loop append while doing double loop in Python


code:
def test_str(mystring):
    try:
        return all( (0 <= int(i) <= 10000) for i in mystring.split() )
    except ValueError:
        return False

print test_str("123 345 456 567 abc 789")
print test_str("123 345 456 567 -300 789")
print test_str("123 345 456 567 300 789")

rawDescription: Validating integers in Python strings

description: Validating integers in Python strings


code:
import pymel.core as pm
print pm.modelEditor(pm.getPanel(wf=True), q=True, rnm=True)

rawDescription: How to query current viewport renderer in maya

description: Query current viewport renderer in maya