code:
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write("%s\n%s\n%s\n" % (line1, line2, line3))

print "And finally, we close it."
target.close()

rawDescription: Why does Python's .write cause single quotes around the lines of text?


code:
#!/usr/bin/env python

words = ''

while True:

    # Get input

    new_word = raw_input('Enter a word: ')

    # Stop loop if user entered 'stop'

    if new_word.upper() == 'STOP':
        break

    # Add comma to string if this is not the first word

    if words:
        words += ','

    # Add word to string

    words += new_word

print "Your words are: " + words

rawDescription: Need help prompting strings and adding them to one


code:
import re
from itertools import chain
print list(chain.from_iterable(re.findall('[DGRYy]{3,}', data)))
# ['D', 'G', 'D', 'D', 'D', 'D', 'D', 'R', 'Y', 'D', 'y', 'D', 'G', 'R', 'D', 'D', 'Y', 'G', 'R']

rawDescription: Find specific character with python regex


code:
file1=set(open("file1").readlines())
file2=set(open("file2").readlines())
intersection = file1 & file2 #common lines
non_intersection = file2 - file1  #uncommon lines (in file2 but not file1)
for items in intersection:
    print items
for nitems in non_intersection:
    print nitems

rawDescription: Convert Perl script to Python: dedupe 2 files based on hash keys


code: print func.func_name, args, kwargs

rawDescription: Printing a function and its parameters as a string


code:
for k, v in r.items():
    print k, v

print r[4]

rawDescription: How to map key values using lists?

description: Map key values using lists


code:
import nltk
from nltk.tokenize import word_tokenize

lin = "A frequency distribution for the outcomes of an experiment. A frequency distribution records the number of times each outcome of an experiment has occurred. For example, a frequency distribution could be used to record the frequency of each word type in a document. Formally, a frequency distribution can be defined as a function mapping from each sample to the number of times that sample occurred as an outcome."

tokens = word_tokenize(lin)
fdist = nltk.FreqDist(tokens)

for f in fdist:
    print f, fdist[f]

rawDescription: FreqDist Python ... at the end issue

description: FreqDist Python ... at the end issue


code:
print numpy.amax(numpy.unique(all_data[:, 3]).astype(int))
print numpy.amin(numpy.unique(all_data[:, 3]).astype(int))

rawDescription: numpy.unique doesn't give the expected output

description: Numpy.unique doesn't give the expected output


code:
class A:
   a = 1
print A.a
obj = A()
print obj.a
obj.a = 2
print A.a
print obj.a

rawDescription: How to copy a class variable - Python

description: Copy a class variable - Python


code:
class A(object):
    def __init__(self, name):
        self.name = name
    def f(self, param):
        print self.name, param

# just pass an instance as first parameter to a function or to an unbound method
func = types.FunctionType(A.f.__code__, globals={}, name='f')
func(A('a'), 2)
unbound_method = types.MethodType(func, None, A)
unbound_method(A('b'), 3)
# or bound the function to an instance
bound_method = types.MethodType(func, A('c'), A)
bound_method(4)

rawDescription: code objects in python - passing parameters

description: Code objects in python - passing parameters


code:
if time(10,30) <= now.time() <= time(16,30):
    print "yes, within the interval"

rawDescription: How do I determine if current time is within a specified range using Python's datetime module?

description: Determine if current time is within a specified range using Python's datetime module


code:
def insertion(new_record):
    newRecordDict={r.split('=')[0]:r.split('=')[1] for r in new_record.split('\n')[1:-1]} #first and last line is ignored
    field_names = {'Customer_ID':None,
    'Last_Name':None,
    'First_Name':None,
    'Street_Address':None,
    'City':None,
    'Province':None,
    'Postal_Code':None,
    }
    field_names2 = {'Home_Phone':0,'Business_Phone':0}

    for field in field_names:
        field_names[field] = newRecordDict.get(field,None)
    for field in field_names2:
        field_names2[field] = newRecordDict.get(field,None)

    print field_names
    print field_names2

rawDescription: Replace parts of string that occur within a list


code:
ENCODING = 'utf-8'
print u' '.join((u'1S²',u'2S¹')).encode(ENCODING)

rawDescription: Need help with tuples in python

description: Need help with tuples in python


code:
from Tkinter import *

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

class MainWindow():

    def __init__(self, root):
        self.e1 = Entry(root)
        self.e1.pack()

        self.e2 = Entry(root)
        self.e2.pack()

        self.e1.bind("<FocusOut>", self.test)
        self.e2.bind("<FocusOut>", self.test)
        # or
        # root.bind_class("Entry", "<FocusOut>", self.test)

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

    def test(self, event):
        if event.widget == self.e1:
            #print "e1:", event.widget.get()
            print "e1:", self.e1.get()

        if event.widget == self.e2:
            #print "e2:", event.widget.get()
            print "e2:", self.e2.get()

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

root = Tk()
MainWindow(root)
root.mainloop()

rawDescription: how handle events on every individual entry

description: How handle events on every individual entry


code:
class Grandparent(object):
    def my_method(self):
        print "Grandparent"

class Parent(Grandparent):
    def my_method(self):
        print "Parent"

class Child(Parent):
    def my_method(self):
        print "Hello Grandparent"
        Grandparent.my_method(self)

rawDescription: Python 2.7 : how to call super super class method?


rawDescription: python selenium - print xpath value

description: Python selenium - print xpath value


code:
from PyQt4 import QtGui

clr = QtGui.QColor('yellow')
qtwi = QtGui.QTableWidgetItem()
qtwi.setBackgroundColor(clr)

print 'Colors are the same object: %s' % (clr == qtwi.backgroundColor())

print 'Alpha before is: %s' % clr.alpha()
clr.setAlpha(67)
print 'Alpha after is: %s' % clr.alpha()

qtwibg = qtwi.backgroundColor()
print 'Alpha before is: %s' % qtwibg.alpha()
qtwibg.setAlpha(171)
print 'Alpha after is: %s' % qtwibg.alpha()

print 'Colors are the same object: %s' % (clr == qtwibg)

rawDescription: PyQt QColor setAlpha not working?

description: PyQt QColor setAlpha not working


code:
for name in pdfnames(names):
    print name

rawDescription: Translating regex match groups

description: Translating regex match groups


code:
from abc import ABCMeta, abstractmethod

def enforcedmethod(func):
    func.__enforcedmethod__ = True
    return func

class EditedABCMeta(ABCMeta):

    def __call__(cls, *args, **kwargs):

        enforcedmethods = set()
        for base in cls.__mro__:
            for name, value in base.__dict__.items():
                if getattr(value, "__enforcedmethod__", False) and name not in cls.__dict__:
                    enforcedmethods.add(name)
        if enforcedmethods:
            raise TypeError("Can't instantiate abstract class {} "
                            "with enforced methods {}".format(
                                cls.__name__, ', '.join(enforcedmethods)))
        else:
            return super(EditedABCMeta, cls).__call__(*args, **kwargs)

class A(object):
    __metaclass__ = EditedABCMeta

    @enforcedmethod
    def veryspecificmethod(self):
        pass
    @abstractmethod
    def simplemethod(self):
        pass

class B(A):
    def veryspecificmethod(self):
        print 'doing something in B'
    def simplemethod(self):
        pass

class C(B):
    pass

class D(C):
    def veryspecificmethod(self):
        print 'doing something in D'

rawDescription: Force implementation of a method in all inheriting classes


code:
import json

thres = 0.1
tmp_e3 = 0
tmp_e1 = "-"

lol = [['a', 3, 1.01], ['x',5, 1.00],['k',7, 2.02],
       ['p',8, 3.00], ['b', 10, 1.09], ['f', 12, 2.03]]

# ensure lol is sorted
lol.sort(key = (lambda x: x[1]))
dol = {}

while len(lol) > 0:
    x = lol.pop(0)
    lol2 = []
    dol[x[0]] = [ x[0] ]
    for i in lol:
        if abs(i[2] - x[2]) < thres:
            dol[x[0]].append(i[0])
        else:
            lol2.append(i)
    lol = lol2

print json.dumps(dol, indent=4)

rawDescription: How to cluster list-of-list by distance condition in Python

description: Cluster list-of-list by distance condition in Python


code:
import urllib2, json
response = urllib2.urlopen('https://www.udemy.com/api-2.0/channels/1640/courses?is_angular_app=true&p=2')
data = json.load(response)

print data['results'][0]['url']

rawDescription: extract key value from json python

description: Extract key value from json python


code:
def generator_example():
    yield 1
    print "x"
    yield 2

rawDescription: Questions about Python 'yield' keyword that I have not found answers elsewhere, and its specific use in a code I am working on


code:
for group, items in itertools.groupby('aaAaAAbBbcCdDdDeE'):
    print group, list(items)

rawDescription: Regarding the correct usage of groupby(): Python 3


code:
import sys

class Logger(file):
    def __init__(self,*a,**kw):
        # copy original stdout to instance
        self.stdout = sys.stdout
        return super(Logger,self).__init__(*a,**kw)

    def write(self,data):
        self.stdout.write(data) # to screen
        return super(Logger,self).write(data) #to file

    def writelines(self,lines):
        for line in lines: self.write(line)

    def close(self):
        # return it back
        sys.stdout = self.stdout

some_list = ['elem1', 'elem2']

for elem in some_list:
    with Logger("/tmp/1/{}.log".format(elem), "w") as sys.stdout:
    # Do lots of stuff that print messages.
        print 'lots of stuff for', elem

print 'Code finished'

rawDescription: Store all stdout to file while still displaying it on screen


code: print len(set(str(s)))

rawDescription: Count of different numbers in one long number


code:
for i, sel in enumerate(response.xpath('//div[@class="submission-list"]/div[contains(@class,"submission")]/div[@class="content"]'), start=1):
    startup_name = sel.xpath('.//div[@class="title"]/a/div[@class="name"]/text()').extract()[0].encode('utf-8')
    votes = sel.xpath('.//div[@class="count vote-widget "]/div[@class="vote-count"]/text()').extract()[0]
    print "[{}] {} has {} votes".format(i, startup_name, votes)

rawDescription: Scrape html siblings as individual items?


code:
from numpy import newaxis
xy = x[:,:,newaxis] * y[:,newaxis,:]

# 10th matrix
print xy[10]
print np.outer(x[10,:], y[10,:])

rawDescription: Perform a series of outer products using tracedot in scipy


code:
import time
from functools import wraps

PROF_DATA = {}

def profile(fn):
    @wraps(fn)
    def with_profiling(*args, **kwargs):
        start_time = time.time()

        ret = fn(*args, **kwargs)

        elapsed_time = time.time() - start_time

        if fn.__name__ not in PROF_DATA:
            PROF_DATA[fn.__name__] = [0, []]
        PROF_DATA[fn.__name__][0] += 1
        PROF_DATA[fn.__name__][1].append(elapsed_time)

        return ret

    return with_profiling

def print_prof_data():
    for fname, data in PROF_DATA.items():
        max_time = max(data[1])
        avg_time = sum(data[1]) / len(data[1])
        print "Function %s called %d times. " % (fname, data[0]),
        print 'Execution time max: %.3f, average: %.3f' % (max_time, avg_time)

def clear_prof_data():
    global PROF_DATA
    PROF_DATA = {}

rawDescription: Measuring elapsed time with the Time module


code:
print nounify("created")
print nounify("teach")
print nounify("spoke")

rawDescription: Get noun from verb Wordnet

description: Get noun from verb Wordnet


code:
def logged(func):
    def with_logging(*args, **kwargs):
        print func.__name__ + " was called"
        return func(*args, **kwargs)
    return with_logging

rawDescription: What does functools.wraps do?

description: What does functools.wraps do


code:
result,start,end = next(g1.scanString(msg))
print len(msg),end

rawDescription: getting a grammar to read more than one keyword in the text

description: Getting a grammar to read more than one keyword in the text


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base, declared_attr

Base = declarative_base()

class CommentBase(Base):
    __abstract__ = True

    id = Column(Integer, primary_key=True)
    text = Column(Unicode(500))

    @declared_attr
    def user_id(cls):
        return Column(ForeignKey('user.id'))

    @declared_attr
    def user(cls):
        return relationship('User')

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

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)

class CommentOne(CommentBase):
    __tablename__ = 'comment_one'

class CommentTwo(CommentBase):
    __tablename__ = 'comment_two'

e = create_engine("sqlite://", echo=True)

Base.metadata.create_all(e)

s = Session(e)

u1 = User()
s.add(u1)
s.flush()

s.add_all([CommentOne(user_id=u1.id, text="c1"), CommentTwo(user_id=u1.id, text="c2")])
s.commit()

print s.query(CommentOne).all()

rawDescription: SQLAlchemy UnmappedClassError: Class 'sqlalchemy.ext.declarative.DeclarativeMeta' is not mapped


code:
import sympy
from sympy.core.decorators import call_highest_priority
from sympy import Expr, Matrix, Mul, Add, diff
from sympy.core.numbers import Zero

class D(Expr):
    _op_priority = 11.
    is_commutative = False
    def __init__(self, *variables, **assumptions):
        super(D, self).__init__()
        self.evaluate = False
        self.variables = variables

    def __repr__(self):
        return 'D%s' % str(self.variables)

    def __str__(self):
        return self.__repr__()

    @call_highest_priority('__mul__')
    def __rmul__(self, other):
        return Mul(other, self)

    @call_highest_priority('__rmul__')
    def __mul__(self, other):
        if isinstance(other, D):
            variables = self.variables + other.variables
            return D(*variables)
        if isinstance(other, Matrix):
            other_copy = other.copy()
            for i, elem in enumerate(other):
                other_copy[i] = self * elem
            return other_copy

        if self.evaluate:
            return diff(other, *self.variables)
        else:
            return Mul(self, other)

    def __pow__(self, other):
        variables = self.variables
        for i in range(other-1):
            variables += self.variables
        return D(*variables)

def mydiff(expr, *variables):
    if isinstance(expr, D):
        expr.variables += variables
        return D(*expr.variables)
    if isinstance(expr, Matrix):
        expr_copy = expr.copy()
        for i, elem in enumerate(expr):
            expr_copy[i] = diff(elem, *variables)
        return expr_copy
    return diff(expr, *variables)

def evaluateMul(expr):
    end = 0
    if expr.args <> ():
        if isinstance(expr.args[-1], D):
            if len(expr.args[:-1])==1:
                cte = expr.args[0]
                return Zero()
            end = -1
    for i in range(len(expr.args)-1+end, -1, -1):
        arg = expr.args[i]
        if isinstance(arg, Add):
            arg = evaluateAdd(arg)
        if isinstance(arg, Mul):
            arg = evaluateMul(arg)
        if isinstance(arg, D):
            left = Mul(*expr.args[:i])
            right = Mul(*expr.args[i+1:])
            right = mydiff(right, *arg.variables)
            ans = left * right
            return evaluateMul(ans)
    return expr

def evaluateAdd(expr):
    newargs = []
    for arg in expr.args:
        if isinstance(arg, Mul):
            arg = evaluateMul(arg)
        if isinstance(arg, Add):
            arg = evaluateAdd(arg)
        if isinstance(arg, D):
            arg = Zero()
        newargs.append(arg)
    return Add(*newargs)

def evaluateExpr(expr):
    if isinstance(expr, Matrix):
        for i, elem in enumerate(expr):
            elem = elem.expand()
            expr[i] = evaluateExpr(elem)
        return expr
    expr = expr.expand()
    if isinstance(expr, Mul):
        expr = evaluateMul(expr)
    elif isinstance(expr, Add):
        expr = evaluateAdd(expr)
    elif isinstance(expr, D):
        expr = Zero()
    return expr

rawDescription: Differential Operator usable in Matrix form, in Python module Sympy


code:
from ctypes import *
import threading

lock = threading.Lock()
lib = CDLL('./tmp.so')
callback_t = CFUNCTYPE(c_int)

def f():
  with lock:
    print threading.current_thread()
  return 21

callback = callback_t(f)
lib.registerCallback(callback)

rawDescription: Using threading lock in ctypes callback function


code:
class SimpleConsumer(Consumer):
     def my_func(self, body):
         print body

     _callback = my_func

rawDescription: Register unique callbacks per instance using classmethod


code: print Pdata < 0.05

rawDescription: comparing/extracting data from matrices using python (2.6.1)

description: Comparing/extracting data from matrices using python (2.6.1)


code:
# A bogus game with wins in several directions.
board = (
    [1,1,2,1],
    [0,2,1,1],
    [2,2,2,1],
    [1,0,0,1],
)

# A few convenience variables.
n_rows = len(board)
lft = [ [0] * i for i in range(n_rows) ]  # [[], [0], [0, 0], [0, 0, 0]]
rgt = list(reversed(lft))

# Create transpositions of the board to check for wins in various directions.
transpositions = {
    'horizontal' : board,
    'vertical'   : zip(*board),
    'diag_forw'  : zip(* [lft[i] + board[i] + rgt[i] for i in range(n_rows)] ),
    'diag_back'  : zip(* [rgt[i] + board[i] + lft[i] for i in range(n_rows)] ),
}

# Apply Jonathan's horizontal-win check to all of the transpositions.
for direction, transp in transpositions.iteritems():
    for row in transp:
        s = ''.join( map(str, row) )
        for player in range(1,3):
            if s.find(str(player) * 3) >= 0:
                print 'player={0} direction={1}'.format(player, direction)

rawDescription: Determining three in a row in Python 2d array


code:
from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://www.delyver.com/Partners/partner/HSR%20Layout,%20Bengaluru,%20Karnataka,%20India/12.9081357/77.64760799999999")
for post in browser.find_elements_by_css_selector(".Parwrsp.Parwrsp-Ado"):
    print post.get_attribute('href')

rawDescription: Href values are not being returned

description: Href values are not being returned


code:
import myDict

list_name = raw_input('wallet or numbers? ')
print getattr(myDict, list_name)

rawDescription: Print variable from other file with raw_input


code:
#!/usr/bin/env python

snippet = """

Football

Team A
Team B

Baseball

Team C
Team D

"""

import lxml.html

html = lxml.html.fromstring(snippet)
body = html[1]

results = []
current_category = None

for element in body.xpath('./*'):
    if element.tag == 'div':
        current_category = element.xpath('./a')[0].text
    elif element.tag == 'a':
        results.append({ 'category' : current_category,
            'title' : element.text })

print results

rawDescription: lxml: split at attribute?

description: Lxml: split at attribute


code:
import pickle

def extract_dict(filename):
    try:
        oldInfoFile=open(filename, 'r')
    except:
        print "File could not be opened"
        return {}
    oldInfo=oldInfoFile.read()
    oldInfoFile.close()
    try:
        oldDict=pickle.loads(oldInfo)
    except AttributeError:
        print "Non valid Pickle format"
        return {}
    return oldDict

def append_dict(filename,more_info_dict):
    myDict=extract_dict(filename)
    myDict.update(more_info_dict)
    aFile=open(filename, 'w')
    aFile.write(pickle.dumps(myDict))
    aFile.close()

#Testing what we have in aFile.dat
print(extract_dict("aFile.dat"))

aList = ['useless', 'info']
bList = [1000,5000]
first_info={"aList":aList,"bList":bList}

#Adding data to aFile.dat
append_dict("aFile.dat",first_info)

#Verifying data was written to aFile.dat
print(extract_dict("aFile.dat"))

second_info={"aList2":aList,"bList2":bList}

#Writting more data
append_dict("aFile.dat",second_info)

#Verifying new data was written to aFile.dat
print(extract_dict("aFile.dat"))

rawDescription: How do I write two lists to a dat file using pickle?

description: Write two lists to a dat file using pickle


code:
tmp = 'Fern\xc3\x9fndez'
print tmp.decode('utf-8')  # print formats the string for stdout
print tmp.decode('latin1')

rawDescription: Python unicode decode not working for outlook exported csv


code:
def length(x):
    b = 0
    for i in x:
        b += 1
    return b
print length('foo')

rawDescription: For Loop Count Single Word String Not Work?


code: print tweet['id_str']

rawDescription: Getting a tweet's ID with Twython?

description: Getting a tweet's ID with Twython


code:
import copy

invocation = 0

def chain(numbers, n, all_chains=[], sum=0, this_chain=[]):
    global invocation
    invocation += 1
    local_id = invocation
    indent = "  "

    print indent*local_id, local_id, "ENTER", "\tsum", sum, "\tthis", this_chain, "\tall", all_chains
    for i in range(len(numbers)):
        if numbers[i] not in this_chain:
            sum += numbers[i]
            if sum <= n:
                print indent*local_id, local_id, "append to this", sum, this_chain, numbers[i]
                this_chain.append(numbers[i])
                chain(numbers, n, all_chains, sum, this_chain)
            else:
                if this_chain not in all_chains:
                    print indent*local_id, local_id, "append to all 1", this_chain
                    all_chains.append(copy.copy(this_chain))
                    mocha = numbers[:]
                    mocha.remove(this_chain[-1])
                    chain(mocha, n, all_chains, sum=0, this_chain=[])
    print indent*local_id, local_id, "append to all 2", this_chain
    all_chains.append(copy.copy(this_chain))
    print indent*local_id, local_id, "LEAVE", all_chains
    return all_chains

numma = [1, 2, 3, 4]
result = chain(numma, 7)
print
for x in result:
    print x

rawDescription: Problems with recursion

description: Problems with recursion


code:
for line in html.splitlines():
    cleaned = line.rpartition('@')[0]
    print cleaned

rawDescription: Python - how to delete all characters in all lines after some sign?


code:
import decorator

@decorator.decorator
def no_none(f,*args,**kwargs):
    if None in args:
        raise ValueError("None's aren't welcome here")
    return f(*args,**kwargs)

@no_none
def foo(a,b,c):
    """Docstring"""
    print a,b,c

foo(1,2,3)
print foo.__doc__

try:
    foo(None,'bar','baz')
except ValueError as e:
    print ('Good, raised ValueError')

try:
    foo("bar","baz",c=None)
except ValueError as e:
    print ('Good, raised ValueError')

rawDescription: How do you check if any of the arguments passed to function is None?

description: Check if any of the arguments passed to function is None


code:
import sys
for word in words(sys.stdin):
    print word

rawDescription: manipulating and searching within large files in python

description: Manipulating and searching within large files in python


code:
def tri2(size):
    row = map(str, range(1, size + 1))
    print '\n'.join(map(lambda n: ' '.join(row[n:]), range(size)))

rawDescription: Recursive numeric triangle in python

description: Recursive numeric triangle in python


code:
def lookahead(it):
    it1, it2 = tee(iter(it))
    next(it2)
    return izip_longest(it1, it2)

for (token, lookahead_1) in lookahead(a):
    print token, lookahead_1

rawDescription: Implement lookahead iterator for strings in Python


code:
import sys

for arg in sys.argv[2:]:
    print arg

rawDescription: Writing and documenting a Python script with variable number of arguments


code:
d1= {'a':{'b':{'cs':10},'d':{'cs':20}}}
d2= {'a':{'b':{'cs':30} ,'d':{'cs':20}},'newa':{'q':{'cs':50}}}

def findDiff(d1, d2, path=""):
    for k in d1.keys():
        if not d2.has_key(k):
            print path, ":"
            print k + " as key not in d2", "\n"
        else:
            if type(d1[k]) is dict:
                if path == "":
                    path = k
                else:
                    path = path + "->" + k
                findDiff(d1[k],d2[k], path)
            else:
                if d1[k] != d2[k]:
                    print path, ":"
                    print " - ", k," : ", d1[k]
                    print " + ", k," : ", d2[k]

print "comparing d1 to d2:"
print findDiff(d1,d2)
print "comparing d2 to d1:"
print findDiff(d2,d1)

rawDescription: Comparing Python dictionaries and nested dictionaries


code:
data1 = list(l.rstrip() for l in open(raw_input("Which is list1?")))
data2 = list(l.rstrip() for l in open(raw_input("Which is list2?")))
data = []
for x in data1:
    if not any(x == y for y in data2):
        data.append(x)
for x in data:
    print x

rawDescription: Simple Nested loop with Python

description: Simple Nested loop with Python


rawDescription: Regex: Matching the closest value backwards


code:
from itertools import product
result = []
for col, siz, mat in product(*(data["color"], data["size"], data["material"])):
    result.append({col: {siz: {mat: {'available': True, 'cost': 100}}}})
print result

rawDescription: combine multidementional array into key based dictionary object

description: Combine multidementional array into key based dictionary object


code:
import numpy as np

r = 2 #matrix dimension
maxs = 5 #maximum sum of row/column

def generate(r, maxs):
    # We create an extra row and column for the starting "dummy" values.
    # Filling in the matrix becomes much simpler when we do not have to treat cells with
    # one or two zero indices in special way. Thus, we start iteration from the
    # (1, 1) index.

    m = np.zeros((r + 1, r + 1), dtype = np.int32)
    m[0] = m[:,0] = maxs + 1

    def go(n, i, j):
        # If we completely filled the matrix, yield a copy of the non-dummy parts.
        if (i, j) == (r, r):
            yield m[1:, 1:].copy()
            return

        # We compute the next indices in row major order (the choice is arbitrary).
        (i2, j2) = (i + 1, 1) if j == r else (i, j + 1)

        # Computing the maximum possible value for the current cell.
        max_val = min(
            maxs - m[i, 1:].sum(),
            maxs - m[1:, j].sum(),
            m[i, j-1],
            m[i-1, j])

        for n2 in xrange(max_val, -1, -1):
            m[i, j] = n2
            for matrix in go(n2, i2, j2):
                yield matrix

    return go(maxs, 1, 1) #note that this is a generator object

# testing
for matrix in generate(r, maxs):
    print
    print matrix

rawDescription: Enumeration all possible matrices with constraints


code:
for x in data:
    print x,    # notice the comma at the end of the line

rawDescription: python: printing horizontally rather than current default printing

description: Python: printing horizontally rather than current default printing


code:
class MiThread(threading.Thread):
      def __init__(self, num):
          threading.Thread.__init__(self)
          self.num = num
          self.status = ''

      def run(self):
          while true:
             self.status = "Soy el hilo {0}".format( self.num )

t1 = MiThread(i)
t1.start()
t2 = MiThread(i)  #<-- at this point you get back interpreter
t2.start()
print t1.status

rawDescription: Take control of interpreter in multithreaded program


code:
import operator, itertools

LR = int(raw_input())

L1a = [8, 9, 14, 13, 12]
L2a = [9, 12, 14, 10, 8]
L3a = [26]
L1b = [27, 32, 26]
L2b = [30, 27, 32, 28, 31]
L3b = [31, 30, 26]
OM = [9, 10]

c1 = [(reduce(operator.mul, p), p) for p in itertools.product(L1b, L2b, L3b)]
c2 = [(reduce(operator.mul, p), p) for p in itertools.product(OM, L1a, L2a)]

RPL = [(((p[0][0]) / p[1][0]) * LR, p[0][1], p[1][1])  for p in itertools.product(c1, c2)]

print RPL

rawDescription: For loop, how can i use loop variable outside loop


code: print len(nodes)

rawDescription: using python in maya do for-loop through selected nodes

description: Using python in maya do for-loop through selected nodes


code:
import numpy as np

def rolling_window(a, window):
   """
   Make an ndarray with a rolling window of the last dimension

   Parameters
   ----------
   a : array_like
       Array to add rolling window to
   window : int
       Size of rolling window

   Returns
   -------
   Array that is a view of the original array with a added dimension
   of size w.

   Examples
   --------
   >>> x=np.arange(10).reshape((2,5))
   >>> rolling_window(x, 3)
   array([[[0, 1, 2], [1, 2, 3], [2, 3, 4]],
          [[5, 6, 7], [6, 7, 8], [7, 8, 9]]])

   Calculate rolling mean of last dimension:
   >>> np.mean(rolling_window(x, 3), -1)
   array([[ 1.,  2.,  3.],
          [ 6.,  7.,  8.]])

   """
   if window < 1:
       raise ValueError, "`window` must be at least 1."
   if window > a.shape[-1]:
       raise ValueError, "`window` is too long."
   shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
   strides = a.strides + (a.strides[-1],)
   return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

rawDescription: Efficient Numpy 2D array construction from 1D array


code: print final_result(res)

rawDescription: celery issuing tasks from subtasks

description: Celery issuing tasks from subtasks


code:
import Tkinter as tk

def center(win, width, height):
  win.update_idletasks()
  frm_width = win.winfo_rootx() - win.winfo_x()
  win_width = width + 2 * frm_width
  titlebar_height = win.winfo_rooty() - win.winfo_y()
  win_height = height + titlebar_height + frm_width
  x = win.winfo_screenwidth() // 2 - win_width // 2
  y = win.winfo_screenheight() // 2 - win_height // 2
  win.geometry('{}x{}+{}+{}'.format(width, height, x, y))

def show(root):
    root.update()
    root.deiconify()

def hide(root):
    root.withdraw()

def showDialog():
  print "tkinter"
  root = tk.Tk()
  hide(root)
  root.title("Say Hello")
  label = tk.Label(root, text="Hello World")
  label.pack(side="top", fill="both", expand=True, padx=20, pady=20)
  button = tk.Button(root, text="OK", command=root.destroy)
  button.pack(side="bottom", fill="none", expand=True, padx=10, pady=10)
  center(root, width=200, height=200)
  show(root)
  root.mainloop()

showDialog()

rawDescription: tkinter: how to not display the empty root window when creating it

description: Tkinter: how to not display the empty root window when creating it


code:
from itertools import permutations

s = 'asis:abc'
delimiter = ':'
pre, post = s.split(delimiter)
for p in permutations(post):
    print '{}{}{}'.format(pre, delimiter, ''.join(p))

rawDescription: python 2.7 permutation of string starting from index

description: Python 2.7 permutation of string starting from index


rawDescription: Statistical counting in Python

description: Statistical counting in Python


code:
import difflib

diff = {}
for k, a_value in A.items():
    b_value = B[k]
    matcher = difflib.SequenceMatcher(a=b_value, b=a_value)
    diff[k] = []
    for opcode, b_start, b_end, a_start, a_end in matcher.get_opcodes():
        a_range = a_value[a_start:a_end]
        b_range = b_value[b_start:b_end]
        if opcode == 'replace':
            diff[k].append("%s digit(s) are different (%s)" % (len(b_range), b_range))
        elif opcode == 'delete':
            diff[k].append("has an extra %s digit(s) (%s)" % (len(b_range), b_range))
        elif opcode == 'insert':
            diff[k].append("missing %s digit(s) (%s)" % (len(a_range), a_range))

for k in sorted(diff.keys()):
    print "B[%s] respect A[%s] = %s" % (k, k, diff[k] and " and ".join(diff[k]) or "no differences")

rawDescription: Python regular expression

description: Python regular expression


code:
from functools import wraps

class attr_block_meta(type):
    def __new__(meta, cname, bases, dctry):
        def _setattr(self, name, value):
            if not hasattr(self, name):
                raise AttributeError("'" + name + "' not an attibute of " + cname + " object.")
            object.__setattr__(self, name, value)

        def override_setattr_after(fn):
            @wraps(fn)
            def _wrapper(*args, **kwargs):
                cls.__setattr__ = object.__setattr__
                fn(*args, **kwargs)
                cls.__setattr__ = _setattr
            return _wrapper

        cls = type.__new__(meta, cname, bases, dctry)
        cls.__init__ = override_setattr_after(cls.__init__)
        return cls

class ImPoint(object):
    __metaclass__ = attr_block_meta
    def __init__(self, q, z):
        self.q = q
        self.z = z

point = ImPoint(1, 2)
print point.q, point.z
point.w = 3  # Raises AttributeError

rawDescription: How to write metaclass which would prevent creating new attributes after __init__()?

description: Write metaclass which would prevent creating new attributes after __init__()


code: print cb.solids

rawDescription: colorbar find the width of color segment

description: Colorbar find the width of color segment


code:
def election_observance(dt):
    if dt.year % 2 == 1:
        return None
    else:
        return dt + pd.DateOffset(weekday=TU(1))

class USElectionCalendar(AbstractHolidayCalendar):
    """
    Federal Presidential  and Congressional election day.
    Tuesday following the first Monday, 2 to 8 November every two even numbered years.
    Election Days can only occur from November 2nd through 8th inclusive.
    """

    rules = [
        Holiday('Election Day', month=11, day=2, observance=election_observance)
    ]

cal = USElectionCalendar()

start_date = '20160108'
end_date = '20261231'

print cal.holidays(start_date, end_date, return_name=True)

rawDescription: Pandas Holiday Calendar Rule for US Election day


code:
import re
from StringIO import StringIO

text = """

here is some text 1
I want to print out this line and the following 3 lines only once keyword 2
print this line since it has a keyword2 3
print this line keyword 4
print this line 5
I don't want to print this line but I want to start looking for more text starting at this line 6
Don't print this line 7
Not this line either 8
I want to print out this line again and the following 3 lines only once keyword 9
please print this line keyword 10
please print this line it has the keyword2 11
please print this line 12
Don't print this line 13
Start again searching here 14
etc.
"""

def my_scan(data,search1,search2):
  buffer = []
  for line in data:
    buffer.append(line)
    if len(buffer) > 4:
      buffer.pop(0)
    if len(buffer) == 4: # Valid search block
      if search1.search(buffer[0]) and search2.search("\n".join(buffer[1:3])):
        for item in buffer:
          yield item
        buffer = []

# First search term
s1 = re.compile(r'\bkeyword\b')
s2 = re.compile(r'\bkeyword2\b')

for row in my_scan(StringIO(text),s1,s2):
  print row.rstrip()

rawDescription: How can I move forward to a subsequent portion of text once I've already printed a searched portion of text in Python?

description: Move forward to a subsequent portion of text once I've already printed a searched portion of text in Python


code:
lines = []
for x in range(0, 2):
    line = []
    for item in dic:
        for i,j in enumerate(abst):
            if item == j:
                line.append(data[x][i])
    lines.append(line)

print lines

rawDescription: how to print lists separately instead of merging them?

description: Print lists separately instead of merging them


code:
a=[]  #a references a mutable object
b=a   #b references the same mutable object
b.append(1)  #change b a little bit
print a # [1] -- because a and b still reference the same object
        #        which was changed via b.

rawDescription: python byRef // copy

description: Python byRef // copy


code:
o.attr3 = "test"
print o.attr1, o.attr2, o.attr3

rawDescription: Create an anonymous class instance in python


code:
from copy import deepcopy

def gen_tables(N):
    tables = []
    x = 1
    for i in xrange(N):
        tables.append(range(x, x + N))
        x += N
    return tables

def print_tables(tables):
    for table in tables:
        print " ".join(map(str, table))
    print

def print_table_perms(perms):
    for perm in perms:
        print_tables(perm)

def gen_table_perms(tables):
    perms = []

    N = len(tables[0])

    for table in tables:
        assert(len(table) == N)

    # first, add the "columns", who won't be mixed together
    perms.append(map(list, zip(*tables)))

    current_tables = deepcopy(tables)
    next_tables = deepcopy(tables)

    # next, mix the columns with a diagonal shift (mod N)
    for i in xrange(N):
        perms.append(deepcopy(current_tables))

        for j in xrange(N):
            for k in xrange(N):
                next_tables[j][k] = current_tables[(j + k) % N][k]

        (current_tables, next_tables) = (next_tables, current_tables)

    return perms

def verify_table_perms(perms):
    N = len(perms[0][0])

    expect = set((x for x in xrange(1, N * N + 1)))

    v = {}
    for i in xrange(1, N * N + 1):
        v[i] = set((i,))

    for perm in perms:
        for table in perm:
            for seat in table:
                v[seat].update(table)

    for s in v.values():
        assert s == expect, s

tables = gen_tables(6)
perms = gen_table_perms(tables)
verify_table_perms(perms)
print_table_perms(perms)

rawDescription: python : speed dating & permutation

description: Python : speed dating & permutation


code:
def isPrime(n):
    for i in xrange(2,n-1):
        if n % i == 0:
            return False
    return True

largest = 0
n = 600851475143
for i in xrange(2,n-1):
    print 'Checking whether %d divides %d' % (i,n)
    if isPrime(i) and n % i == 0:
        largest = i
        n = n / i
        continue

print("The largest prime factor is", largest)

rawDescription: Prime factorization: doesn't work with large numbers?


code: print out.dump()

rawDescription: Getting a data structure equivalent to asXML() in pyparsing?


code:
import sys
import lxml.html as LH
import lxml.etree as ET

data = '''
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="ie6"> <![endif]-->
<!--[if IE 7]>    <html class="ie7"> <![endif]-->
<!--[if IE 8]>    <html class="ie8"> <![endif]-->
<!--[if gt IE 8]><!--> <html> <!--<![endif]-->
<head profile="http://gmpg.org/xfn/11">
 <meta charset="UTF-8">
 <title>
     Erased US data shows 1 in 4 missiles in Afghan airstrikes now fired by drone: The Bureau of Investigative Journalism  </title>

 <meta name="description" content="Drone data has been wiped from the Air Force website.">

 <meta name="generator" content="Magicalia 2010" />
 <meta name="google-site-verification" content="bGFVI6kAZGjMNNiS6LGvBDWSGydwyWQI3gogCD4xP50" />

 <link href="http://cdn-images.mailchimp.com/embedcode/slim-081711.css" rel="stylesheet" type="text/css">
 <link rel="stylesheet" href="http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/css/screen.css" type="text/css" media="screen, projection" />
 <link rel="stylesheet" href="http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/css/print.css" type="text/css" media="print" />
 <link rel="stylesheet" href="http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/style.css?3" type="text/css" media="screen, projection" />

 <!--[if IE]>
   <link rel="stylesheet" href="http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/css/lib/ie.css" type="text/css" media="screen, projection" />
 <![endif]-->

 <!--[if lt IE 7]>
   <script defer type="text/javascript" src="http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/js/pngfix.js"></script>
 <![endif]-->

 <!--[if gte IE 5.5]>
   <script language="javaScript" src="http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/js/dhtml.js" type="text/javaScript"></script>
 <![endif]-->

 <link rel="alternate" type="application/rss+xml" title="The Bureau of Investigative Journalism RSS Feed" href="http://www.thebureauinvestigates.com/feed/" />
 <link rel="pingback" href="http://www.thebureauinvestigates.com/xmlrpc.php" />

 <link rel="alternate" type="application/rss+xml" title="The Bureau of Investigative Journalism » Erased US data shows 1 in 4 missiles in Afghan airstrikes now fired by drone Comments Feed" href="http://www.thebureauinvestigates.com/2013/03/12/erased-us-data-shows-1-in-4-missiles-in-afghan-airstrikes-now-fired-by-drone/feed/" />
<link rel='stylesheet' id='mailchimp-css'  href='http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/lib/mailchimp.dev.css?ver=3.5.1' type='text/css' media='all' />
<link rel='stylesheet' id='donate-css'  href='http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/lib/donate.dev.css?ver=3.5.1' type='text/css' media='all' />
<link rel='stylesheet' id='tubepress-css'  href='http://www.thebureauinvestigates.com/wp-content/plugins/tubepress/src/main/web/css/tubepress.css?ver=3.5.1' type='text/css' media='all' />
<link rel='stylesheet' id='NextGEN-css'  href='http://www.thebureauinvestigates.com/wp-content/plugins/nextgen-gallery/css/nggallery.css?ver=1.0.0' type='text/css' media='screen' />
<link rel='stylesheet' id='shutter-css'  href='http://www.thebureauinvestigates.com/wp-content/plugins/nextgen-gallery/shutter/shutter-reloaded.css?ver=1.3.4' type='text/css' media='screen' />
<link rel='stylesheet' id='stbCSS-css'  href='http://www.thebureauinvestigates.com/wp-content/plugins/wp-special-textboxes/css/wp-special-textboxes.css.php?ver=4.3.72' type='text/css' media='all' />
<link rel='stylesheet' id='grid-css'  href='http://www.thebureauinvestigates.com/wp-content/plugins/big-brother/css/grid.css?ver=3.5.1' type='text/css' media='all' />
<link rel='stylesheet' id='reveal-css'  href='http://www.thebureauinvestigates.com/wp-content/plugins/big-brother/css/reveal.css?ver=3.5.1' type='text/css' media='all' />
<link rel='stylesheet' id='app-css'  href='http://www.thebureauinvestigates.com/wp-content/plugins/big-brother/css/app.css?ver=3.5.1' type='text/css' media='all' />
<script type='text/javascript' src='http://www.thebureauinvestigates.com/wp-includes/js/jquery/jquery.js?ver=1.8.3'></script>
<script type='text/javascript' src='http://www.thebureauinvestigates.com/wp-content/plugins/tubepress/src/main/web/js/tubepress.js?ver=3.5.1'></script>
<script type='text/javascript' src='http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/js/jquery.cycle.js?ver=3.5.1'></script>
<script type='text/javascript' src='http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/js/search.js?ver=3.5.1'></script>
<script type='text/javascript' src='http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/js/nav/superfish.js?ver=3.5.1'></script>
<script type='text/javascript' src='http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/js/nav/supersubs.js?ver=3.5.1'></script>
<script type='text/javascript' src='http://www.thebureauinvestigates.com/wp-content/themes/dxw_magicalia/js/home.js?ver=3.5.1'></sc
'''

if __name__ == '__main__':

    print("%-20s: %s" % ('Python',           sys.version_info))
    print("%-20s: %s" % ('lxml.etree',       ET.LXML_VERSION))
    print("%-20s: %s" % ('libxml used',      ET.LIBXML_VERSION))
    print("%-20s: %s" % ('libxml compiled',  ET.LIBXML_COMPILED_VERSION))
    print("%-20s: %s" % ('libxslt used',     ET.LIBXSLT_VERSION))
    print("%-20s: %s" % ('libxslt compiled', ET.LIBXSLT_COMPILED_VERSION))

    n = 0
    while True:
        n += 1
        print '-', n
        parser = LH.HTMLParser()
        parser.feed(data)
        root = parser.close()
        m = root.xpath('//meta[@property]')
        for i in m:
            print(n)

rawDescription: How to prevent lxml.etree.HTML( data ) from crashing on certain type of data?

description: Prevent lxml.etree.HTML( data ) from crashing on certain type of data


code:
import pandas as pd
data = pd.read_csv("http://data.giss.nasa.gov/gistemp/tabledata_v3/GLB.Ts+dSST.csv",
na_values = ["**** ","***  "])
print data.head()

df1 = pd.melt(data, id_vars=[' Year'], value_vars=['Jan','Feb', 'Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'], var_name='Month').rename(columns={' Year':'Year'})

print df1.columns
Index([u'Year', u'Month', u'value'], dtype='object')

print df1

rawDescription: Display monthly columns by year using pandas


code:
import mymodule
print mymodule.__repr__()

rawDescription: Can a python module have a __repr__?

description: Can a python module have a __repr__


code:
from datetime import datetime
from dateutil import rrule
list(rrule.rrule(rrule.MONTHLY, dtstart=datetime(2010,01,01,00,01), count=12))

rawDescription: Python iterate through month, use month in between Query


code:
from random import random

class PointSet(object):
    def __init__(self, numpoints):
        self.points = [Point(random(), random()) for _ in xrange(numpoints)]

    def update(self):
        for point in self.points:
            point.x += random() - 0.5
            point.y += random() - 0.5

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

points = PointSet(100000)
point = points.points[10]

for _ in xrange(1000):
    points.update()
    print 'Position of one point out of 100000:', point.x, point.y

rawDescription: Storing Python objects in a Python list vs. a fixed-length Numpy array


code: for x in (1,2,3,4):print x;exec("for y in (5,6):print x,y;")

rawDescription: How to create a single-line script with two for loops, in the debugger, in python 2.7

description: Create a single-line script with two for loops, in the debugger, in python 2.7


rawDescription: python - possible encoding and decoding values

description: Python - possible encoding and decoding values


code:
import sys, os
print os.dirname(sys.argv[0])

rawDescription: Parse the executing file path

description: Parse the executing file path


code:
import itertools as it
points = ('A', 'B', 'C', 'D', 'E')
for pt1, pt2 in it.combinations(points, 2):
    print '{0}-{1}'.format(pt1, pt2)

rawDescription: Python non-repeat loop

description: Python non-repeat loop


code:
import requests as rq
from bs4 import BeautifulSoup as bsoup

def get_title(url):

    r = rq.get(url)
    soup = bsoup(r.content)
    title = soup.find_all("title")[0].get_text()
    print title.split(" - ")[0]

def main():

    urls = [
    "http://www.wikiart.org/en/henri-rousseau/tiger-in-a-tropical-storm-surprised-1891",
    "http://www.wikiart.org/en/edgar-degas/the-green-dancer-1879",
    "http://www.wikiart.org/en/claude-monet/dandelions",
    "http://www.wikiart.org/en/albrecht-durer/the-little-owl-1506",
    "http://www.wikiart.org/en/gustav-klimt/farmhouse-with-birch-trees-1903",
    "http://www.wikiart.org/en/jean-michel-basquiat/boxer",
    "http://www.wikiart.org/en/fernand-leger/three-women-1921",
    "http://www.wikiart.org/en/alphonse-mucha/flower-1897",
    "http://www.wikiart.org/en/alphonse-mucha/ruby",
    "http://www.wikiart.org/en/georges-braque/musical-instruments-1908",
    "http://www.wikiart.org/en/rene-magritte/the-evening-gown-1954",
    "http://www.wikiart.org/en/m-c-escher/lizard-1",
    "http://www.wikiart.org/en/johannes-vermeer/the-girl-with-a-pearl-earring"
    ]

    for url in urls:
        get_title(url)

if __name__ == "__main__":
    main()

rawDescription: Why am I getting an httplib2.RedirectLimit error?


code:
from decimal import *

getcontext().prec = 6
getcontext().rounding = ROUND_FLOOR

print Decimal(22)/Decimal(7)

rawDescription: Python decimal rounding

description: Python decimal rounding


code:
from sqlalchemy import *
from sqlalchemy.orm import *

metadata = MetaData()

t = Table(
    't', metadata,
    Column('id', Integer, primary_key=True),
    Column('state', String(10)),
)

class Model(object): pass

mapper(Model, t)

engine = create_engine('sqlite://')
metadata.create_all(engine)

session = sessionmaker(bind=engine)()

obj1 = Model()
obj1.state = 'value1'
session.add(obj1)
session.commit()
obj_id = obj1.id

obj2 = Model()
obj2.id = obj_id
obj2.state = 'value2'
obj3 = session.merge(obj2)
session.commit()
print obj3 is obj1, obj3 is obj2
print obj3.state

rawDescription: Can SQLAlchemy's session.merge() update its result with newer data from the database?


code:
quote_1 = ("monkeys rock", "False")
quote_2 = ("donkeys rock",  "True")
q_list = [ quote_1, quote_2]
print cur.mogrify("insert into posts VALUES(%s,%s::quotes[])",
                  ("animals are good", q_list))
#
#                 added explicit cast to quotes[]->^^^^^^^^

rawDescription: psycopg2 mapping Python : "list of dicts" to Postgres : "array of composite type" for an INSERT statement

description: Psycopg2 mapping Python : "list of dicts" to Postgres : "array of composite type" for an INSERT statement


code: print enumerate.__doc__

rawDescription: How can I get the index value of a list comprehension?

description: Get the index value of a list comprehension


code:
import requests
from bs4 import BeautifulSoup

marathon = 'http://www.marathonguide.com/results/browse.cfm?MIDD=472131103'

s = requests.session()
p = s.get(marathon)

race_range = 'M,201,300,50062'
rp = 'http://www.marathonguide.com/results/makelinks.cfm'
data = {'RaceRange':race_range, 'RaceRange_Required':'You must make a selection before viewing results.', 'MIDD':'472131103', 'SubmitButton':'View'}
headers = {
"Referer":"http://www.marathonguide.com/results/browse.cfm?MIDD=472131103",
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36"
}

results = s.post(rp, data=data, headers=headers)
soup = BeautifulSoup(results.content)

rows = soup.find_all("tr", {"bgcolor":"#CCCCCC"})
for row in rows:
  print row.find("td").get_text()

rawDescription: Requests interacting strangely with redirect


code: print "".join([chr(item) for item in a])

rawDescription: Convert Numpy array of ASCII codes to string


code:
import zlib, base64
s='eNoLDnF09lbwD3MNcvPxD1cIHhxcAE9UKaU='
data = zlib.decompress(base64.b64decode(s))
print data

rawDescription: Compressing a file in python and keep the grammar exact when opening it again


code:
bash_history_text = bash_history.read()
print bash_history_text

rawDescription: reading .bash_history file through python script

description: Reading .bash_history file through python script


code:
NumOfN = int(input("What is N? : "))
total = 0
for i in range(NumOfN):
  NextNum = 1.0/(NumOfN)
  total += NextNum
  NumOfN = NumOfN-1
print "the sum is ", total

rawDescription: Python 2 - "For counting loop"

description: Python 2 - "For counting loop"


code:
dic={}
for x in range (1,6):
    level = 'level%d' % x
    dic[level] = {}
    for iteration in range(1, 4):
        value = 'value%d' % iteration
        dic[level][value] = 0

print dic

rawDescription: How do I create multiple dictionaries based on nested for loops?

description: Create multiple dictionaries based on nested for loops


rawDescription: How to rename variables in a loop in Python

description: Rename variables in a loop in Python


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

def get_data(fname):
    with open(fname, 'r') as f:
        return int(f.read())

while True:
    time.sleep(1)
    pyserv = get_data('vardata')
    print pyserv

rawDescription: how can you Import an os variable into PYTHON and have it update?


code: print "RESULT: " + ", ".join(str(float(x.strip()) / 1e4) for x in raw_input("Enter values: ").split(","))

rawDescription: Process multiple input values in Python

description: Process multiple input values in Python


code:
from string import printable, whitespace
from itertools import groupby
pathchars = set(printable) - set(whitespace)
with open("/usr/bin/rawtherapee") as fp:
    data = fp.read()

for k, g in groupby(data, pathchars.__contains__):
    if not k: continue
    g = ''.join(g)
    if len(g) > 3 and g.startswith("/"):
        print g

rawDescription: What is the fastest method of finding a file in Linux and Windows using Python?


code:
import signal
import os
import time

def receive_signal(signum, stack):
    print 'Received:', signum

signal.signal(signal.SIGUSR1, receive_signal)
signal.signal(signal.SIGUSR2, receive_signal)

print 'My PID is:', os.getpid()

rawDescription: How to get id of process from which came signal in Python?

description: Get id of process from which came signal in Python


code:
tests = [Test(1), Test(2), Test(3), Test(2), Test(4)]
for test in tests:
    print test.somevalue, id(test)

rawDescription: How can I memoize a class instantiation in Python?

description: Memoize a class instantiation in Python


code:
class MyTypeOfLength3(object):
    def __len__(self):
        return 3

o = MyTypeOfLength3()
print len(o)
# 3

rawDescription: Proper way to make functions extensible by the user


code:
import re

s = 'hello\xFE\xDCWorld' # our test-string

# read: FE DC or FE DD or FE DE
unstuff   = re.compile('\xFE\xDC|\xFE\xDD|\xFE\xDE')
# read:
#  - use this pattern to match against the string
#  - replace what you have found (m.groups(0), whole match) with
#    char(ord(match[1])^0x20)
unstuffed = unstuff.sub(lambda m: chr(ord(m.group(0)[1])^0x20), s)

# same thing, other way around
stuff   = re.compile('\xFC|\xFD|\xFE')
stuffed = stuff.sub(lambda m: '\xFE' + chr(ord(m.group(0))^0x20), unstuffed)

print s, unstuffed, stuffed

rawDescription: Octet (byte) stuffing and unstuffing, i.e. replacing one byte with two or v.v


code:
JuncSize = JuncSize.groupby('No').size()
JuncSize.name = 'size'
JuncSize = JuncSize.reset_index()
print JuncSize

rawDescription: Manipulate a new column after 'df.size()' function?


code:
import lxml.html

pagesource = """<form method="POST" action="/login/?session=sess">
<input type="text" id="usern" name="username" value="" placeholder="Username"/>
<input type="password" id="passw" name="password" placeholder="Password"/>
<input type="hidden" name="ses_token" value="token"/>
<input id="login" type="submit" name="login" value="Log In"/>
</form>
<form method="POST" action="/login/?session=sess">
<input type="text" id="usern" name="username" value="" placeholder="Username"/>
<input type="password" id="passw" name="password" placeholder="Password"/>
<input type="hidden" name="ses_token" value="token"/>
<input id="login" type="submit" name="login" value="Log In"/>
</form>
"""

tree = lxml.html.fromstring(pagesource)
form = tree.find('.//form')

print "Action:", form.action
print "Token:", form.find('.//input[@name="ses_token"]').value

rawDescription: python - parse html form with lxml.html with xpath syntax

description: Python - parse html form with lxml.html with xpath syntax


code:
import base64

#My buggy SSH account needs this to write unicode output, you hopefully won't
import sys
import codecs
sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

encoded = '=?UTF-8?B?0J/RgNC+0LLQtdGA0LrQsA==?='
prefix = '=?UTF-8?B?'
suffix = '?='

#extract the data part of the string
middle = encoded[len(prefix):len(encoded)-len(suffix)]
print "Middle: %s" % middle

#decode the bytes
decoded = base64.b64decode(middle)
#decode the utf-8
decoded = unicode(decoded, 'utf8')

print "Decoded: %s" % decoded

rawDescription: How convert email subject from "?UTF-8?...?=" to readable string?


code:
import os
import sys

euid = os.geteuid()
if euid != 0:
    print "Script not started as root. Running sudo.."
    args = ['sudo', sys.executable] + sys.argv + [os.environ]
    # the next line replaces the currently-running process with the sudo
    os.execlpe('sudo', *args)

print 'Running. Your euid is', euid

rawDescription: authentication in python script to run as root

description: Authentication in python script to run as root


code:
import dpkt, pcap
pc = pcap.pcap()     # construct pcap object
pc.setfilter('icmp') # filter out unwanted packets
for timestamp, packet in pc:
    print dpkt.ethernet.Ethernet(packet)

rawDescription: Packet sniffing in Python (Windows)

description: Packet sniffing in Python (Windows)


code:
import datetime

def daterange(start, end, delta):
    """ Just like `range`, but for dates! """
    current = start
    while current < end:
        yield current
        current += delta

start = datetime.datetime.now()
end = start + datetime.timedelta(days=20)

for d in daterange(start, end, datetime.timedelta(days=1)):
    print d

rawDescription: Does Python have any for loop equivalent (not foreach)


code:
try:
  print credentials.id_token['email']
except KeyError:
  print 'Unknown email'

rawDescription: Get Google Account email address based on user_id


code:
import sys
def sizeof(lst):
    return sys.getsizeof(lst) + sum(sys.getsizeof(v) for v in lst)

GIG = 1024**3
file_size = 1.5 * GIG
lines = 31164015
num_cols = 4
avg_line_len = int(file_size / float(lines))

val = 'a' * (avg_line_len / num_cols)
lst = [val] * num_cols

line_size = sizeof(lst)
print 'avg line size: %d bytes' % line_size
print 'approx. memory needed: %.1f GB' % ((line_size * lines) / float(GIG))

rawDescription: Why is loading this file taking so much memory?


code:
import itertools
from operator import mul

def totient(n):
    if n == 1:  return 1
    res = list()
    value = int("%d" % n)
    if value > 3:
        for this in itertools.chain(iter([2]), xrange(3,int(value ** 0.5)+1, 2)):
            if this*this > value:  break
            while not (value % this):
                if value == this:  break
                value /= this
                res.append(this)
    res.append(value)
    prime_factors_mult = sorted([fact, res.count(fact)] for fact in set(res))
    return res, reduce(mul, [(p - 1) * p**(m - 1) for p,m in prime_factors_mult]), prime_factors_mult

x = totient(315)

# This would be the returned list from prime_factors(315)
print x[0]
[3, 3, 5, 7]

# This would be the returned value from totient(315)
print x[1]
144

# This would be the returned list from prime_factors_mult(315)
print x[2]
[[3, 2], [5, 1], [7, 1]]

# The 3-tuple:
print x
([3, 3, 5, 7], 144, [[3, 2], [5, 1], [7, 1]])

rawDescription: Combine functions to reduce queries

description: Combine functions to reduce queries


code:
import time

def measure_time(f):

  def timed(*args, **kw):
    ts = time.time()
    result = f(*args, **kw)
    te = time.time()

    print '%r (%r, %r) %2.2f sec' % \
          (f.__name__, args, kw, te-ts)
    return result

return timed

rawDescription: Python: How to measure time spent waiting for I/O?


code:
for items in t.iter_over('c', 'b', 'a'):
    print items[1] # will be b (or 2nd passed above) etc...

rawDescription: Assignment to value returned from list

description: Assignment to value returned from list


code:
import re

s = 'Text Processing. You are tired of seeing lines on your e-mail wrap because people type lines that are too long for your mail reader application. Create a program to scan a text file for all lines longer than 80 characters. For each of the offending lines, find the closest word before 80 characters and break the line there, inserting the remaining text to the next line (and pushing the previous next line down one). When you are done, there should be no lines longer than 80 characters.'
print '\n'.join(line.strip() for line in re.findall(r'.{1,80}(?:\s+|$)', s))

rawDescription: wrapping a text file so that each line contain a maximum of 80 characters

description: Wrapping a text file so that each line contain a maximum of 80 characters


code:
Code
benchmark.py
# vim: set fileencoding=utf-8 :
import timeit
import pyximport
pyximport.install()

def timer(func, mod):
    import_ = 'from %s import mk_value' % mod
    time = timeit.timeit(func, import_, number=100000)
    ms = 1000 * time
    us = 1000 * ms

    if func[40:]:
        func_short = func[:37] + '...'
    else:
        func_short = func

    print '%(mod)s.%(func_short)-40s %(ms)6dms %(us)12dμs' % locals()

for mod in 'abcd':
    timer("mk_value(1234)", mod)
    timer("mk_value(1234.56)", mod)
    timer("mk_value('1234')", mod)
    timer("mk_value('1234.56')", mod)
    timer("mk_value('1,234.56', thousand_sep=',')", mod)
    timer("mk_value('1.234.567,89 EUR', currency_sign='EUR', "
        "thousand_sep='.', decimal_sep=',')", mod)

rawDescription: Fastest and/or most pythonic way to convert string into a number


code:
import re
p = re.compile(r'(?ims)author\s*=\s*[{"]((?:[^{}]+?|{[^}]+?})+?)[}"]')
test_str = "@inproceedings{baz,\n    AUTHOR = {{Baz}, {S}. and Bar, {G}. and\n      Foo, {M}},\n    year={2013}\n}\n@inproceedings{baz,\n    AUTHOR={{%Baz%}, {S!}. and Bar, {^G^}. and\n      Foo, {<M>}},\n    year={2013}\n}\n"
print [x.group(1) for x in re.finditer(p, test_str)]

rawDescription: Python regexp match across lines

description: Python regexp match across lines


code:
def NamedTupleWithDocstring(docstring, *ntargs):
    nt = namedtuple(*ntargs)
    class NT(nt):
        __slots__ = ()
        __doc__ = docstring
    return NT

Point3D = NamedTupleWithDocstring("A point in 3d space", "Point3d", ["x", "y", "z"])

p3 = Point3D(1,2,3)

print p3.__doc__

rawDescription: Adding docstrings to namedtuples?

description: Adding docstrings to namedtuples


code:
import csv
import collections

grades = collections.Counter()
with open('file.csv') as input_file:
    for row in csv.reader(input_file, delimiter=';'):
        grades[row[1]] += 1

print 'Number of A grades: %s' % grades['A']
print grades.most_common()

rawDescription: Python algorithm of counting occurrence of specific word in csv


code:
import httplib
conn = httplib.HTTPConnection('w3.com')
conn.request('OPTIONS', '/')
response = conn.getresponse()
print response.getheader('allow')

rawDescription: Showing allowed HTTP methods

description: Showing allowed HTTP methods


code:
def _wait_for_server(cloud_server, server):
    while True:
        sleep(30)
        s = cloud_server.servers.get(server.id)
        print '%s: %s (%s%%)' % (s.id, s.status, s.progress)
        if s.status == 'ACTIVE':
            break

    return server

rawDescription: Python while loop does not exit, why?

description: Python while loop does not exit, why


code:
from scipy.spatial.distance import pdist, squareform
coordinates = [(0.0, 0), (1.0, 2.0), (-1.0, 0.5), (3.1, 2.1)]
dist = squareform(pdist(coordinates))
print dist

rawDescription: numpy 2D matrix- How to improve performance in this case?

description: Numpy 2D matrix- How to improve performance in this case


code:
from sklearn import svm

X = [[0, 0], [1, 1]]
y = [0, 1]

clf = svm.SVC(kernel='linear')
clf.fit(X, y)
print clf.support_vectors_

rawDescription: scikit-learn, linearsvc - how to get support vectors from the trained SVM?

description: Scikit-learn, linearsvc - how to get support vectors from the trained SVM


code:
import os
import signal
import subprocess
import time
from threading import Thread

process = None

def executeCommand(command, runCommand):
    Thread(target=runCommand, args=(command,)).start()

def runCommand(command):
    global process
    args = command.strip().split()
    process = subprocess.Popen(
        args, shell=False, stdout=subprocess.PIPE, preexec_fn=os.setsid)

    for line in process.communicate():
        if line:
            print "process:", line,

if __name__ == '__main__':
    executeCommand("./ascript.sh", runCommand)
    time.sleep(1)
    os.killpg(process.pid, signal.SIGKILL)

rawDescription: How do I close the stdout-pipe when killing a process started with python subprocess Popen?

description: Close the stdout-pipe when killing a process started with python subprocess Popen


code:
selected_class = None

while True:
    charClass = raw_input('What type of training have you had (Class)? ')
    if charClass in classes:
        selected_class = classes[charClass]
        break
    else:
        print 'That is not a valid class.'

rawDescription: Values from tuples named the same as user input in Python (Hard for me to explain, will update title if I can find a better way to express myself)


code: print d["char12"]+d["char22"]

rawDescription: Spacing when printing values in a python dictionary


code:
from nltk.corpus import wordnet as wn
for ss in wn.all_synsets():
    print ss
    print ss.definition()
    break

rawDescription: How can I print the entire contents of Wordnet (preferably with NLTK)?

description: Print the entire contents of Wordnet (preferably with NLTK)


code:
test_sha1 = hashlib.sha1(raw_input("Enter password: ") + salt).hexdigest()
# Enter password:  password
print encrypted == test_sha1
# True

rawDescription: How to create a user login section in Python with Tkinter module

description: Create a user login section in Python with Tkinter module


code:
from math import sqrt, floor

for a in range(1, 500):
  b = 1000 * (500-a) / (1000-a)
  c = sqrt(a**2 + b**2)
  if int(floor(c)) == c and 0 < a < b < c:
    print a, b, c

rawDescription: Why isn't my solution to Project Euler 9 working?


code:
from urllib2 import urlopen
from BeautifulSoup import BeautifulSoup
import sys

URL = "http://hiscore.runescape.com/hiscorepersonal.ws?user1=" + sys.argv[1]

# Grab page html, create BeatifulSoup object
html = urlopen(URL).read()
soup = BeautifulSoup(html)

# Grab the
 element
scores = soup.find('table', {'id':'mini_player'})

# Get a list of all the
s in the table, skip the header row
rows = scores.findAll('tr')[1:]

# Helper function to return concatenation of all character data in an element
def parse_string(el):
   text = ''.join(el.findAll(text=True))
   return text.strip()

for row in rows:

   # Get all the text from the s
   data = map(parse_string, row.findAll('td'))

   # Skip the first td, which is an image
   data = data[1:]

   # Do something with the data...
   print data

rawDescription: How do I draw out specific data from an opened url in Python using urllib2?

description: Draw out specific data from an opened url in Python using urllib2


code:
tf.reset_default_graph()

queue_dtype = np.int32

# values_queue is a queue that will be filled with 0,1,2,3,4
# range_input_producer creates the queue and registers its queue_runner
value_queue = tf.range_input_producer(limit=5, num_epochs=1, shuffle=False)
value = value_queue.dequeue()

# value_squared_queue will be filled with 0,1,4,9,16
value_squared_queue = tf.FIFOQueue(capacity=50, dtypes=queue_dtype)
value_squared_enqueue = value_squared_queue.enqueue(tf.square(value))
value_squared = value_squared_queue.dequeue()

# value_squared_sum keeps running sum of squares of values
value_squared_sum = tf.Variable(0)
value_squared_sum_update = value_squared_sum.assign_add(value_squared)

# register queue_runner in the global queue runners collection
num_threads = 2
qr = tf.train.QueueRunner(value_squared_queue, [value_squared_enqueue] * num_threads)
tf.train.queue_runner.add_queue_runner(qr)

sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())
tf.start_queue_runners()

for i in range(5):
  sess.run([value_squared_sum_update])
  print sess.run([value_squared_sum])

rawDescription: Tensorflow Race conditions when chaining multiple queues


code:
print [idx for idx, field in enumerate(fieldnames) if values[idx] is not None]
# [1, 3]

rawDescription: Having trouble with pythonic style and list comprehension


code:
for element in makefile_parser.parseString(test):
    if element.getName() == 'task_definition':
        print "TASK:", element.target,
        if element.deps:
            print "DEPS:(" + ','.join(element.deps) + ")"
        else:
            print
        for key in ('des', 'path', 'para'):
            if key in element:
                print " ", key.upper()+":", element[key]

    elif element.getName() == 'symbol_assignment':
        print "SYM:", element.name, "->", element.value

rawDescription: Any python module for customized BNF parser?


code:
import inspect

class copy_argspec(object):
    """
    copy_argspec is a signature modifying decorator.  Specifically, it copies
    the signature from `source_func` to the wrapper, and the wrapper will call
    the original function (which should be using *args, **kwds).  The argspec,
    docstring, and default values are copied from src_func, and __module__ and
    __dict__ from tgt_func.
    """
    def __init__(self, src_func):
        self.argspec = inspect.getargspec(src_func)
        self.src_doc = src_func.__doc__
        self.src_defaults = src_func.func_defaults

    def __call__(self, tgt_func):
        tgt_argspec = inspect.getargspec(tgt_func)
        need_self = False
        if tgt_argspec[0][0] == 'self':
            need_self = True

        name = tgt_func.__name__
        argspec = self.argspec
        if argspec[0][0] == 'self':
            need_self = False
        if need_self:
            newargspec = (['self'] + argspec[0],) + argspec[1:]
        else:
            newargspec = argspec
        signature = inspect.formatargspec(
                formatvalue=lambda val: "",
                *newargspec
                )[1:-1]
        new_func = (
                'def _wrapper_(%(signature)s):\n'
                '    return %(tgt_func)s(%(signature)s)' %
                {'signature':signature, 'tgt_func':'tgt_func'}
                   )
        evaldict = {'tgt_func' : tgt_func}
        exec new_func in evaldict
        wrapped = evaldict['_wrapper_']
        wrapped.__name__ = name
        wrapped.__doc__ = self.src_doc
        wrapped.func_defaults = self.src_defaults
        wrapped.__module__ = tgt_func.__module__
        wrapped.__dict__ = tgt_func.__dict__
        return wrapped

rawDescription: How can I programmatically change the argspec of a function *not* in a python decorator?

description: Programmatically change the argspec of a function *not* in a python decorator


code:
print json.dumps(obj, sort_keys=True,
                 indent=4, separators=(',', ': '))

rawDescription: How to execute a python module (python -m json.tool) programatically?

description: Execute a python module (python -m json.tool) programatically


code:
if hasattr(intvalue, __int__):
    print "Integer"

rawDescription: Type of the positional parameters in python


code:
class MyFunctions():
    def __init__( self):
        self.listOfItems = []

    def displayList( self):
        """Prints all items in listOfItems)"""
        for item in self.listOfItems:
            print item

    def addToList(self):
        """Updates all mlb scores, and places results in a variable."""
        self.listOfItems.append("test")

f = MyFunctions()
f.addToList()
f.displayList()

rawDescription: Understanding python variable scope within class


code:
class Options(object):
    def functionOne(self): # or function1
        print 'one'
    def functionTwo(self): # or function2
        print 'two'
    def functionThree(self): # or function3
        print 'three'

o = Options()
for name in dir(o):
    if 'function' in name:
        getattr(o, name)()

rawDescription: Calling unspecified function from another file and another class


code:
gsm.registerAdapter(AB)
gsm.registerAdapter(AC)
from zope.component import getAdapters
for adapter in getAdapters((a, c), Interface):
    print adapter

rawDescription: Issue with zope.component subscriber adapters adapting multiple objects


code:
from collections import Counter
c = Counter(item[0] for item in l)
print sorted(l, key = lambda x: -c[x[0]])

rawDescription: Python: How to sort a list of lists by the most common first element?


code:
import csv
import urllib2
url = 'http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KMDLAURE4&day=9&month=6&year=2013&graphspan=day&format=1'
response = urllib2.urlopen(url)
cr = csv.reader(response)

for row in cr:
    if len(row) <= 1: continue
    print row

rawDescription: Reading .csv data from URL in python: extra lines


code:
import re
t = u"Great buy w. all amenities! Use on all cars. come on in!"
p = re.compile("(?<! .)([.!](?:\s|$))")
last = None
for m in p.finditer(t):
    last = m

if last is not None:
    print m.start()

rawDescription: regexp, python: index of last occurrence. Has negative look-behind

description: Regexp, python: index of last occurrence. Has negative look-behind


code:
not_seen = members - seen
for member in not_seen: print member

rawDescription: Finding out matches between two dictionaries in Python


rawDescription: How to replace first column in text file?

description: Replace first column in text file


code:
x = "abcdefghi"
x = list(x)
x[0:4] = x[2:6]
print "".join(x)

rawDescription: python replace records in variable

description: Python replace records in variable


code:
def walkDict( aDict, visitor, path=() ):
    for  k in aDict:
        if k == 'attrs':
            visitor( path, aDict[k] )
        elif type(aDict[k]) != dict:
            pass
        else:
            walkDict( aDict[k], visitor, path+(k,) )

def printMe( path, element ):
    print path, element

def filterFor( path, element ):
    if element['id'] == '4130-2-2':
        print path, element

rawDescription: How to do this - python dictionary traverse and search

description: Do this - python dictionary traverse and search


code:
from bs4 import BeautifulSoup as bsoup
import re

ofile = open("test.html", "rb")
soup = bsoup(ofile)
soup.prettify()

categories = ["Type:","Main Type:","Wheel:","Movement type:","Level:","Sport:","Force:"]
for category in categories:
    f = soup.find(text=re.compile(category)).next_sibling
    string = f.get_text()
    ref = f.get("href")
    print "%s %s (%s)" % (category, string, ref)

rawDescription: Parsing links and strings from unstructured HTML data


code:
data = 'Data to buffer'
N = 4
buf = 2*N*['\00']

for i,c in enumerate(data):
    j = i % N
    buf[j] = c
    buf[j+N] = c
    if i >= N-1:
        print ''.join(buf[j+1:j+N+1])

rawDescription: ring buffer with numpy/ctypes

description: Ring buffer with numpy/ctypes


rawDescription: How to read a two digit numbers in CSV file and storying it in a list?

description: Read a two digit numbers in CSV file and storying it in a list


code:
x = 0
while True:
    if x < 9:
        print "this works"
        x = x + 1
    else:
        print "this doesn't work"
        break

rawDescription: Simple "if" statements in Python

description: Simple "if" statements in Python


code:
print [reduce(my_reduce, group)
       for _, group in groupby(sorted(pets), key=itemgetter(0))]

rawDescription: Reduce by key in python

description: Reduce by key in python


code:
def get_all_doc(obj,indent=''):
    for item in filter(lambda x:not x.startswith('__'),dir(obj)):
        o=getattr(obj,item)
        print "{indent}{item} {doc}".format(indent=indent,
                                            item=item,
                                            doc=o.__doc__)
        get_all_doc(o,indent=indent+'   ')

rawDescription: Getting docstrings from Python package __init__ - based imports


code:
class MyFoo(object):
    a = 10
    def bar(self):
        print self.a

rawDescription: Python Suite, Package, Module, TestCase and TestSuite differences


code:
import os

while True:
    for root, dirs, files in os.walk("/home/user/Documents"):
        for file in files:
            print(os.path.join(root, file))
    fname = raw_input('Enter filename to view '
                      '(leave empty to proceed without viewing another file):')

    if not fname:  # Empty strings are 'falsy'.
        break

    # The rest of the while clause will only be executed
    # if above we didn't break out of the loop. If we did
    # break out, the script continues with the code after
    # this loop.
    f = open(fname, 'r')
    print f.read()

rawDescription: How to accept user input multiple times and then execute the rest of the script when they're done?

description: Accept user input multiple times and then execute the rest of the script when they're done


code:
import re

text = u'Und Wenn die Psychoanalytiker, von den d\xfcmmsten bis zu den kl\xfcgsten, im allgemeinen feindselig auf dieses Buch reagiert haben, aber eher defensiv als aggressiv, so liegt das nat\xfcrlich nicht allein am Inhalt, sondern an dieser Str\xf6mung, die noch gr\xf6\xdfer werden wird, denn die Leute haben immer mehr die Nase voll davon, sich sagen zu lassen "Papa, Mama, \xd6dipus, Kastration, Regression" und haben es satt f\xfcr die Sexualit\xe4t im allgemeinen - und ihre im besonderen - ein wirklich bl\xf6dsinniges Bild angeboten zu bekommen. Die Psychoanalytiker sollten, wie man sagt, die "Massen" ber\xfccksichtigen, die kleinen Massen.'

pattern = ur'[A-ZÄÖÜ][a-zäöüß-]*'
result = " ".join(re.findall(pattern, text))

rawDescription: Remove lowercase words from python unicode string


code:
import requests
from bs4 import BeautifulSoup

ADVANCED_URL = "http://www.scoresway.com/b/block.teama_people_match_stat.advanced?has_wrapper=true&match_id=45926&sport=basketball&localization_id=www"

response = requests.get(ADVANCED_URL)
soup = BeautifulSoup(response.text)
print [td.text.strip() for td in soup('td', class_='name')]

rawDescription: Python Beautiful Soup scape page containing Java Script


code:
import datetime
from datetime import timedelta

def find_unique_ids(df, date, daysback=1):

    date_new = date
    date_old = date - timedelta(days = daysback)

    ids_new = df[df['Date'] == date_new]['ID']
    ids_old = df[df['Date'] == date_old]['ID']

    return df.iloc[ids_new[-ids_new.isin(ids_old)]]

date = datetime.date(2015, 1, 2)
daysback = 1

print find_unique_ids(df, date, daysback)

rawDescription: Pandas Dataframe Groupby Determine Values in 1 group vs. another group


code:
offset = 2
aString = raw_input("digit the string to convert: ")
#aString = "abz"
newString = ""

for letter in aString:
    ord_letter = ord(letter)+offset
    ord_letter_rotated = ((ord_letter - 97) % 26) + 97
    newString += chr(ord_letter_rotated)

print newString

rawDescription: Returning the value of an index in a python list based on other values


code:
import re
import urlparse
html = """
<script type='text/javascript' src='http://www.somesite.com/wp-content/themes/Dessa/scripts/jquery.easing.1.3.js?ver=1.3'></script>
<a href="http://www.somesite.com/hard-circuit-editor-double-layout-design-now/">
"""
for attrname, value in re.findall(r'''(href=|src=)["']([^"']*)["']''', html, re.U):
    print value, urlparse.urlparse(value).query

rawDescription: Regex for extracting string with interrogation (?) mark in Python


code:
def triangle():
  res = 0
  inc = 1
  while True:
    res += inc
    inc += 1
    yield res

t = triangle()
print next(t)
print next(t)
print next(t)
print next(t)

rawDescription: Returning values from inside a while loop in python


code:
from bisect import bisect

def age_band(age, upto=[30, 60, 90], desc=['0-30', '31-60', '61-90', '91+']):
    if not age >= 0:
        return '*invalid*'
    return desc[bisect(upto, age)]

for age in [31, 99, 65, 12, -1]:
    print age, age_band(age)

rawDescription: Reformatting a CSV using Python and bucketing the data


code:
from pyparsing import *

and_keyword = CaselessKeyword("and")
or_keyword = CaselessKeyword("or")
in_operation = CaselessKeyword("in")

value = quotedString | Word(alphanums)
comparisonOp = oneOf("= != > < >= <=")
LPAR,RPAR = map(Suppress,"()")
valueList = LPAR + delimitedList(value) + RPAR
comparisonExpr = value + comparisonOp + value | value + in_operation + Group(valueList)
def makePymongoComparison(tokens):
    v1,op,v2 = tokens
    if op != 'in':
        if op != '=':
            op = {
                "!=" : "$ne",
                ">"  : "$gt",
                "<"  : "$lt",
                ">=" : "$gte",
                "<=" : "$lte",
                }[op]
            v2 = "{'%s': '%s'}" % (op, v2)
        return "{'%s': '%s'}" % (v1, v2)
    else:
        return "{'%s': {'$in': [%s]}}" % (v1, ','.join("'%s'"%v for v in v2))
comparisonExpr.setParseAction(makePymongoComparison)

def handleBinaryOp(op):
    def pa(tokens):
        return "{'$%s': %s}" % (op, ', '.join(tokens.asList()[0][::2]))
    return pa
handleAnd = handleBinaryOp("and")
handleOr  = handleBinaryOp("or")
whereOperand = comparisonExpr
where_expr = operatorPrecedence(whereOperand,
    [
    (and_keyword, 2, opAssoc.LEFT, handleAnd),
    (or_keyword, 2, opAssoc.LEFT, handleOr),
    ])

where_condition = Group(CaselessLiteral("where") + where_expr)

print where_expr.parseString("(Sal = 1000 or Sal=5000) AND Car>2")[0]
print where_expr.parseString("(Sal = 1000 or Sal=5000) AND Car in (1,2,3)")[0]

rawDescription: Sql to Pymongo generation using Pyparsing


code:
x = {'both1':1, 'both2':2, 'only_x': 100 }
y = {'both1':10, 'both2': 20, 'only_y':200 }

print { k: x.get(k, 0) + y.get(k, 0) for k in set(x) }
print { k: x.get(k, 0) + y.get(k, 0) for k in set(x) & set(y) }
print { k: x.get(k, 0) + y.get(k, 0) for k in set(x) | set(y) }

rawDescription: Merge and sum of two dictionaries

description: Merge and sum of two dictionaries


code:
regexp = re.compile(("mailto:([a-z0-9!#$%&'*+\/=?^_`{|}~-]+@[a-z0-9]+\.[a-zA-Z0-9-.]+)"))

links = re.findall(regexp, content)

print links

rawDescription: how to Parse emails from mailto urls in Python

description: Parse emails from mailto urls in Python


code:
if re.match('^{0}'.format(x), y):
    print "success"

rawDescription: including a bound string object in regular expression in python

description: Including a bound string object in regular expression in python


code:
Species_IC = {'R1': '2.7109e+02', 'R2': '1.2709e+02', 'R1_I': '2.7109e+03', 'R2_I': '1.2709e+03', 'LR1R2': '1.6913e+00', 'LR1R2_I': '1.6913e+01'}

list_Species_IC = Species_IC.keys()
print list_Species_IC
#['R1', 'R2', 'R1_I', 'R2_I', 'LR1R2', 'LR1R2_I']
out = df[df['Unnamed: 0'].isin(list_Species_IC)].reset_index()
print out
#   Unnamed: 0  Initial_guess  Lower_bound  Upper_bound Estimated_or_Fixed
#4        R1_I              5     0.000001        10000          Estimated
#10    LR1R2_I              5     1.000000        10000          Estimated

rawDescription: Filtering a Pythons Pandas DataFrame based on values from dictionary


code:
last_paragraph = soup.find_all('p', style='clear:both')[-1]
script_tag = last_paragraph.next_sibling.next_sibling
script_text = script_tag.text

lines = script_text.split('\n')
data_text = ''
for line in lines:

    if 'SCREEN_DATA' in line: break
    data_text = data_text + line

data_text = data_text.replace('var VERSION_DATA =', '')
# delete semicolon at the end
data_text = data_text[:-1]

data = json.loads(data_text)
data = data[0]
print data['data']

rawDescription: Scrape a Google Chart script with Scraperwiki (Python)


code:
if any("1" == x.userID for x in self.users):
   print True

rawDescription: Python if Statement not finding value

description: Python if Statement not finding value


code:
class Test1(object):
    def __init__(self):
        d = {}
        d['a'] = 1
        d['b'] = 2
        d['c'] = 3
        self.d = d

class Test2(object):
    def __init__(self):
        self.d = {}
        self.d['a'] = 1
        self.d['b'] = 2
        self.d['c'] = 3

import dis
print "Test1.__init__"
dis.dis(Test1.__init__)

print "Test2.__init__"
dis.dis(Test2.__init__)

rawDescription: Constructing objects in __init__

description: Constructing objects in __init__


code:
for num in x:
    print d.get(num,"not found")

rawDescription: Python a list and a dictionary

description: Python a list and a dictionary


code:
prior = [] # list of prior input sets (only those that weren't redundant)

with open("permission.txt") as in_file:
  for in_line in in_file:
    master = set([])
    cover = set([])
    cover_team = []
    perm_line = set([int(s) for s in in_line.split('P') if len(s)>0])

    # Check each of the shorter (prior) permission strings
    for short in prior:
      # If the prior string has no superfluous permissions, add it to the master set.
      extra = short - perm_line
      if len(extra) == 0:
        master = master.union(short)
        # Does this string add anything new to the coverage?
        ### print "compare", short, cover
        if len(short - cover) > 0:
          cover = cover.union(short)
          cover_team.append(short)
          ### print "Add to cover_team:", short

    # Did the combination of prior strings cover all of the input line permissions?
    print in_line,
    if len(perm_line - master) == 0:
      print "\tPermissions included in prior strings", cover_team
    else:
      print "\tFound New permission combinations; adding to reference list"
      prior.append(perm_line)

rawDescription: Generating different combinations of string in python


code:
import mm

@mm.multimethod(int)
def spam(a):
    print 'Calling the int method'
    print '%s: %r' % (type(a), a)

@mm.multimethod(float)
def spam(a):
    print 'Calling the float method'
    print '%s: %r' % (type(a), a)

spam(5)
spam(5.0)

rawDescription: Force a function parameter type in Python?


code:
import threading

class Dev(threading.Thread):

    def __init__(self, workQueue, queueLock, count):
        super(Dev, self).__init__()   # super() will call Thread.__init__ for you
        self.workQueue = workQueue
        self.queueLock= queueLock
        self.count = count

    def run(self):  # put inside run your loop
        data = ''
        while 1:
            with self.queueLock:
                if not self.workQueue.empty():
                    data = self.workQueue.get()
                    print data
                    print self.count

            if data == 'quit':
                break

rawDescription: Threading and information passing -- how to


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

from matplotlib.widgets import RectangleSelector
from matplotlib.transforms import Bbox

def main():
    # Generate some random data:
    data = []
    for track_id in xrange(100):
        a, b = np.random.random(2)
        x = 100 * a + np.random.random(100).cumsum()
        y = np.cos(x) + b * np.random.random(100).cumsum()
        data.append((track_id, x, y))

    # Plot it, keeping track of the "track_id"
    fig, ax = plt.subplots()
    for track_id, x, y in data:
        line, = ax.plot(x,y)
        line.track_id = track_id

    # Make the selector...
    selector = RectangleSelector(ax, onselect, drawtype='box')
    # We could set up a button or keyboard shortcut to activate this, instead...
    selector.set_active(True)

    plt.show()

def onselect(eclick, erelease):
    """Get the lines in an axis with vertices inside the region selected.
    "eclick" and "erelease" are matplotlib button_click and button_release
    events, respectively."""
    # Make a matplotlib.transforms.Bbox from the selected region so that we
    # can more easily deal with finding if points are inside it, etc...
    left, bottom = min(eclick.x, erelease.x), min(eclick.y, erelease.y)
    right, top = max(eclick.x, erelease.x), max(eclick.y, erelease.y)
    region = Bbox.from_extents(left, bottom, right, top)

    track_ids = []
    ax = eclick.inaxes
    for line in ax.lines:
        bbox = line.get_window_extent(eclick.canvas)
        # Start with a rough overlaps...
        if region.overlaps(bbox):
            # We need the xy data to be in display coords...
            xy = ax.transData.transform(line.get_xydata())

            # Then make sure that at least one vertex is really inside...
            if any(region.contains(x,y) for x,y in xy):
                # Highlight the selected line by making it bold
                line.set_linewidth(3)
                track_ids.append(line.track_id)

    print track_ids
    eclick.canvas.draw()

if __name__ == '__main__':
    main()

rawDescription: limiting the data to the desired values

description: Limiting the data to the desired values


rawDescription: Export pandas DataFrame to LaTeX and apply formatters by row


code:
import os, hashlib
def gen():
    return hashlib.sha1(os.urandom(512)).hexdigest()

test = [gen() for i in range(100000)]
print len(test), len(set(test))

rawDescription: random.choice not random

description: Random.choice not random


code:
for item in mylist:
    print '%0.2f' % item,

rawDescription: Change default float print format

description: Change default float print format


code:
with open('data.txt') as inf:
    for number, line in enumerate(inf, 1):
        if "Internet(R) explorer" in line:
            print 'found "Internet(R) explorer" on line %d.' % number

rawDescription: To search exact word in a file using python


code:
import sys
sys.stdout = open("file.txt", 'w')

for n in xrange(100):
    print n

#I bet you can guess what you're going to see in file.txt

rawDescription: putting python output to text file using cron-job

description: Putting python output to text file using cron-job


code:
import time
print int(time.time() % 10)

rawDescription: does this code generate random numbers?

description: Does this code generate random numbers


code:
doctype = doctypeDefn.parseString(sample)
print doctype.dump()
for elem in doctype.elements:
    print elem.dump()

rawDescription: Parser for xml DTD file

description: Parser for xml DTD file


code:
for sl in lmod:
   for el in sl:
       print el

rawDescription: How to exclude some indexes in a python loop?

description: Exclude some indexes in a python loop


code:
d = datetime.datetime(2013, 8, 15, 12, 0, 0)
print week_start_end(d)

rawDescription: tuple of datetime objects in Python

description: Tuple of datetime objects in Python


code:
from collections import Counter
with open('x.txt') as f1,open('y.txt','w') as f2:
    c=Counter(x.strip() for x in f1)
    for x in c:
        print x,c[x]   #do f2.write() here if you want to write them to f2

rawDescription: How to count word frequencies within a file in python

description: Count word frequencies within a file in python


code:
from random import choice
import xlrd

wb = xlrd.open_workbook("quotes.xlsx")
sh1 = wb.sheet_by_index(0)
column = 2 # or whatever column you want to select from

print choice(sh1.col(column)).value

rawDescription: Randomize search in excel

description: Randomize search in excel


code:
import math

NGRAM = 0
"""Marginals index for the ngram count"""

UNIGRAMS = -2
"""Marginals index for a tuple of each unigram count"""

TOTAL = -1
"""Marginals index for the number of words in the data"""

_product = lambda s: reduce(lambda x, y: x * y, s)
_SMALL = 1e-20

def student_t(*marginals):
    """Scores ngrams using Student's t test with independence hypothesis
    for unigrams, as in Manning and Schutze 5.3.1.
    """
    _n = 2
    return ((marginals[NGRAM] -
                _product(marginals[UNIGRAMS]) /
                float(marginals[TOTAL] ** (_n - 1))) /
              (marginals[NGRAM] + _SMALL) ** .5)

ngram_freq = 2
w1_freq = 2
w2_freq = 4
total_num_words = 24

print student_t(ngram_freq, (w1_freq,w2_freq), total_num_words)

rawDescription: What is the total bigram count returned for NLTK BigramCollocationFinder?


code:
# some toy example data - I understand you want the first 2 sub_list
# to be "merged" because BOTH strings in pos 0 and 2 match
data = [['42x120x1800', 50, '50x90x800', 60],
        ['42x120x1800', 8, '50x90x800', 10],
        ['2x10x800', 5, '5x9x80', 6]]

from collections import defaultdict

# I'm using a lambda to initialize the items of the dict
# to a two-element list of zeros
d = defaultdict(lambda :[0, 0])
for sub_list in data:
    key = (sub_list[0], sub_list[2])
    d[key][0] += sub_list[1]
    d[key][1] += sub_list[3]

for key in d:
    print key, d[key]
# ('2x10x800', '5x9x80') [5, 6]
# ('42x120x1800', '50x90x800') [58, 70]

rawDescription: How to identify all identical lists from a list of lists?

description: Identify all identical lists from a list of lists


code:
product = session.query(Product).filter(Product.barcode == user_input).scalar()
print product.name, product.price

rawDescription: Using user input to find information in a Mysql database


code: print parser.format_help()

rawDescription: Getting the remaining arguments in argparse


rawDescription: Check a phone number with interleaving patterns


code:
def partition(it, item):
    a = []
    for x in it:
        if x == item:
            return a, [item], list(it)
        a.append(x)
    return a, [], []

print partition((x for x in range(10)), 7)
print partition((x for x in range(10)), 17)

rawDescription: More compact way to skip initial list items? (or partition list based on an item)


code:
folder_paths, job_folders = get_filepaths( os.path.expandvars(r"%TEMP%\workorder"), ext_list )

print "folder_paths =", folder_paths
print "job_folders =", job_folders

rawDescription: How to list all directories that do not contain a file type?

description: List all directories that do not contain a file type


code:
lslr = commands.getoutput("ls –lR")
print lslr

rawDescription: Files and directories in Python on linux


code:
#!/usr/bin/env python
# aptinstall.py

import apt
import sys

pkg_name = "libjs-yui-doc"

cache = apt.cache.Cache()
cache.update()

pkg = cache[pkg_name]
if pkg.is_installed:
    print "{pkg_name} already installed".format(pkg_name=pkg_name)
else:
    pkg.mark_install()

    try:
        cache.commit()
    except Exception, arg:
        print >> sys.stderr, "Sorry, package installation failed [{err}]".format(err=str(arg))

rawDescription: How to install a package using the python-apt API

description: Install a package using the python-apt API


code:
import mechanize
br = mechanize.Browser()
response = br.open("default.aspx")
print br.form
br.select_form(nr=0)
print br.form

rawDescription: Py Mechanize submit more data using the auth'ed user


code:
with open('/root/temps', 'w') as f:
    for eip_dict in addresses_dict['Addresses']:
        if 'PrivateIpAddress' in eip_dict:
            print eip_dict['PublicIp']
            f.write(eip_dict['PublicIp'])

rawDescription: How to write the list to file?

description: Write the list to file


code:
l = ['A.', 'Pe\xc3\xb1aloza']
''.join(map(lambda s:s.decode('utf-8'), l))
print ''.join(map(lambda s:s.decode('utf-8'), l))

rawDescription: Making cvs file of facebook friends with python to import in new profile


rawDescription: Drop some Pandas dataframe rows using group based condition


code:
from HTMLParser import HTMLParser
h = HTMLParser()
s = "מפגשי"
print h.unescape(s)

rawDescription: Convert numeric character reference notation to unicode string


code:
def bounce(num):
    print num
    if num:
        bounce(num - 1)
        print num

rawDescription: Count to zero then Count up

description: Count to zero then Count up


code:
#!/usr/bin/python
import argparse

parser = argparse.ArgumentParser(prefix_chars='@')
parser.add_argument('@@xlim', nargs = 2,
                  help = 'X axis limits',
                  action = 'store', type = float,
                  default = [-1.e-3, 1.e-3])
print parser.parse_args()

rawDescription: Python Argparse: Issue with optional arguments which are negative numbers


code: print get_longest(data)

rawDescription: Size of largest sub-dictionary in python


code:
def poll(x):
    regex = re.compile("\+CMTI:.......")
    lst = []
    for l in x:
        for m in [regex.search(l)]:
            if m:
                lst.append(m)
                print "You have received a new message!"

rawDescription: Combining print statements with list comprehension in python


code:
if 'user' in session:
       User=session['user']
       print User # Prints User

if 'nickname' in session:
       Nickname=session['nickname']
       print Nickname # Prints nickname

rawDescription: flask : how to retrieve session data?

description: Flask : how to retrieve session data


code:
def myFunction():
    print "123"

abc = myFunction

rawDescription: Is it possible to use functions before declaring their body in python?


rawDescription: Limited deep copy of an instance with a container of containers as an attribute


code:
from timeit import timeit
print timeit('sorted(["abcd", "abc", "ab", "a"], key=lambda x:len(x))')
print timeit('sorted(["abcd", "abc", "ab", "a"], key=len)')

rawDescription: python callback vs node callback point to point comparisons

description: Python callback vs node callback point to point comparisons


code:
#!/usr/bin/python

import subprocess
import time

print "Parent started"
subprocess.Popen("./child.py")
print "(child started, sleeping)"

time.sleep(5)

print "Parent finished"

rawDescription: "Fire and forget" a process from a Python script


code:
import numpy as np

def mirrored(maxval, inc=1):
    x = np.arange(inc, maxval, inc)
    if x[-1] != maxval:
        x = np.r_[x, maxval]
    return np.r_[-x[::-1], 0, x]

print mirrored(1, 0.3)

rawDescription: Create list of numbers mirrored around zero (python)


code:
for fname in listFiles(r"Your Path"):
        newName=re.match("(^.*?)([A-Za-z\.]*$)",x)
        newName=''.join([newName[0],newName[1].lower()])
        os.rename(fname,newName)
        print "Renamed " + fname + "to" + newName

rawDescription: How to change last letter of filename to lowercase if it is a letter?

description: Change last letter of filename to lowercase if it is a letter


code:
from y import f1

import x

print "reload"

reload(x)

rawDescription: import behaviour with already loaded modules

description: Import behaviour with already loaded modules


code: print text, len(text)

rawDescription: How to understand unicode and utf-8

description: Understand unicode and utf-8


code:
result = json.loads(output)
print result

rawDescription: Python accessing data in JSON object

description: Python accessing data in JSON object


code:
if valid_ip(data):
    print data

rawDescription: Validate IP address from list

description: Validate IP address from list


code:
class UserNode(StructuredNode):
    user_id = IntegerProperty(required=True, index=True)
    following = RelationshipTo('UserNode', 'FOLLOW')
    followers = RelationshipFrom('UserNode', 'FOLLOW')

    def follow_person(self, user_id):
        followed_user = self.index.get(user_id=user_id)
        self.follow.connect(followed_user, {'time': str(datetime.datetime.utcnow())})

print "User 1 follows {}".format(u1.following.all())
print "User 1's followers {}".format(u1.followers.all())

rawDescription: A following models with django neomodel

description: A following models with django neomodel


code:
import os

path, filename = os.path.split(os.path.abspath(__file__))
print path

rawDescription: How to get the path of a file, in an absolut way

description: Get the path of a file, in an absolut way


code:
import urllib
from bs4 import BeautifulSoup, SoupStrainer

baseurl="http://data.10jqka.com.cn/market/yybzjsl/HTZQGFYXGSCDSJLZQYYB"
page = urllib.urlopen(baseurl)
getonly = SoupStrainer('table')
table = BeautifulSoup(page, parse_only=getonly)

for row in table("tr"):
  text = ''.join(row.findAll(text=True))
  data = text.strip()
  print data

rawDescription: Scraping data table from Chinese stock website using Python


code:
from lxml import etree

parent = etree.parse("parent.xml").getroot()
penv = parent.xpath("Environment")

for e in penv:
    child = e.get("{http://www.w3.org/1999/xlink}href")
    c = etree.parse(child).getroot()
    parent.replace(e, c)

print etree.tostring(parent)

rawDescription: How should I process XLink references with lxml in python?