code:
print 'one: %r' % _exec(None, '"foo"', 'range', 7)
print 'two: %r' % allowed_builtins['result']

rawDescription: Python Eval executing enviroment

description: Python Eval executing enviroment


code:
import re
import itertools
import textwrap

if __name__=='__main__':
    print "{0:^78}".format("King James Bible")

    books=iter(['Genesis', 'Exodus', 'Leviticus', 'Numbers', 'Deuteronomy', 'Joshua',
           'Judges', 'Ruth', 'I Samuel', 'II Samuel', 'I Kings', 'II Kings',
           'I Chronicles', 'II Chronicles', 'Ezra', 'Nehemiah', 'Esther', 'Job', 'Psalms',
           'Proverbs', 'Ecclesiastes', 'Song of Solomon', 'Isaiah', 'Jeremiah',
           'Lamentations', 'Ezekiel', 'Daniel', 'Hosea', 'Joel', 'Amos', 'Obadiah',
           'Jonah', 'Micah', 'Nahum', 'Habakkuk', 'Zephaniah', 'Haggai', 'Zechariah',
           'Malachi', 'Matthew', 'Mark', 'Luke', 'John', 'Acts', 'Romans', 'I Corinthians',
           'II Corinthians', 'Galatians', 'Ephesians', 'Philippians',
           'Colossians', 'I Thessalonians', 'II Thessalonians', 'I Timothy', 'II Timothy',
           'Titus', 'Philemon', 'Hebrews', 'James', 'I Peter', 'II Peter', 'I John',
           'II John', 'III John', 'Jude', 'Revelation'])

    with open("KJV.txt", "rb") as book:
        contents=book.read()
        data=re.split(r'(\d+:\d+)',contents)[1:]
        del contents

    word_search = raw_input(r'Enter a word to search: ')

    for chapter_verse, line in itertools.izip(*[iter(data)]*2):
        if chapter_verse=='1:1':
            book=next(books)
        line=' '.join(line.split())
        if word_search in line:
            line=textwrap.fill(line,width=78)
            print('''\
{b} {c}
{l}
'''.format(b=book,c=chapter_verse,l=line))

rawDescription: How can I search a file for all text lines prefaced with numbers in a certain format and move them to a new line

description: Search a file for all text lines prefaced with numbers in a certain format and move them to a new line


code:
data = [
    ('a', 15),
    ('c', 10),
    ('b', 2),
]
data.sort() # Sorts the list in-place
print data
# Output: [('a', 15), ('b', 2), ('c', 10)]
print [x[1] for x in data]
# Output [15, 2, 10]
# Sort by value:
from operator import itemgetter
data = sorted(data, key = itemgetter(1))
print data
# Output [('b', 2), ('c', 10), ('a', 15)]
print [x[1] for x in data]
# Output [2, 10, 15]

rawDescription: How does one insert a key value pair into a python list?

description: Insert a key value pair into a python list


code:
from lxml import etree

content = '''
YOUR XML HERE
'''

root = etree.fromstring(content)

# search for all "top level" resources
resources = root.xpath("//Resource[not(ancestor::Resource)]")
for resource in resources:
    # copy resource attributes in a dict
    mashup = dict(resource.attrib)
    # find child resource elements
    subresources = resource.xpath("./Resource")
    # if we find only one resource, add it to the mashup
    if len(subresources) == 1:
        mashup['resource'] = dict(subresources[0].attrib)
    # else... not idea what the OP wants...

    print mashup

rawDescription: XML Parsing issue in python using xml.etree.ElementTree


code:
with open("stuff.py", "r") as f:
    print "\n".join(f.readlines())

rawDescription: Print script content (Python)

description: Print script content (Python)


code:
from optparse import OptionParser

parser = OptionParser()
parser.disable_interspersed_args()
parser.add_option("-f", "--file", dest="filename")
parser.add_option("-z", "--film", dest="filmname")

(options, args) = parser.parse_args()
print options

rawDescription: optparse - why the last char of the option can be ignored? With `--file` it behaves same as `--fil`

description: Optparse - why the last char of the option can be ignored? With `--file` it behaves same as `--fil`


code:
from bs4 import BeautifulSoup
import requests

page = 'http://www.airchina.com.cn/www/jsp/airlines_operating_data/exlshow_en.jsp'

r = requests.get(page)

soup = BeautifulSoup(r.text)

div = soup.find('div', class_='mainRight').find_all('div')[1]
table = div.find('table', recursive=False)
for row in table.find_all('tr', recursive=False):
    for cell in row('td', recursive=False):
        print cell.text.strip()

rawDescription: Python beautifulsoup grab table

description: Python beautifulsoup grab table


code:
class Base(object):

    def union(self, other):
        return Union(self, other)

    def intersection(self, other):
        return Intersection(self, other)

class RangeSet(Base):

    def __init__(self, low, high):
        self.low = low
        self.high = high

    def __contains__(self, value):
        return value >= self.low and value < self.high

class Union(Base):
    def __init__(self, *sets):
        self.sets = sets

    def __contains__(self, value):
        return any(value in x for x in self.sets)

class Intersection(Base):

    def __init__(self, *sets):
        self.sets = sets

    def __contains__(self, value):
        return all(value in x for x in self.sets)

a = RangeSet(0, 10)
b = RangeSet(5, 15)

u = a.union(b)
i = a.intersection(b)

print 3 in u
print 7 in u
print 12 in u

print 3 in i
print 7 in i
print 12 in i

rawDescription: Is there code out there to subclass set in Python for big xranges?


code:
Example
urls = ['http://www.test.tw/in/15',
        'http://www.test.tw/in/15?page=2',
        'http://www.test.tw/in/15/#/?page=3',
        'http://www.test.tw/in/20/#/?page=2',
        'http://www.test.tw/in/3/?page=5']

print [(url, getcategory(url)) for url in urls]

rawDescription: Url parsing with regex

description: Url parsing with regex


code:
import maya.cmds as cmds
if cmds.window("RyanWindow", exists=True):
    cmds.deleteUI("RyanWindow")

myWindow = cmds.window(t="Ryan Window", w=300, h=300)
form = cmds.formLayout()

print cmds.createDisplayLayer (name='Head_Control_Shapes', empty=True)
cmds.createDisplayLayer (name='Torso_Control_Shapes', empty=True)
cmds.createDisplayLayer (name='Arms_Control_Shapes', empty=True)
cmds.createDisplayLayer (name='Legs_Control_Shapes', empty=True)
cmds.createDisplayLayer (name='Other_Control_Shapes', empty=True)

cmds.setAttr ('Head_Control_Shapes.color', 4)
cmds.setAttr ('Torso_Control_Shapes.color', 12)
cmds.setAttr ('Arms_Control_Shapes.color', 13)
cmds.setAttr ('Legs_Control_Shapes.color', 31)
cmds.setAttr ('Other_Control_Shapes.color', 2)

cmds.columnLayout(adj=True)
cmds.text("                         Custom Control Shape Creator v1                         ")
cmds.separator(height = 15, style='double' )
cmds.separator(height = 15, style='double' )
cmds.setParent( '..' )

tabs = cmds.tabLayout(innerMarginWidth=5, innerMarginHeight=5)
cmds.formLayout( form, edit=True, attachForm=((tabs, 'top', 40), (tabs, 'left', 0), (tabs, 'bottom', 0), (tabs, 'right', 0)) )

tab1 = cmds.rowColumnLayout(numberOfColumns=3)
cmds.button(label='Circle', command="makeCircle()")
cmds.button(label='Square', command="makeSquare()")
cmds.button(label='Oval')
cmds.setParent( '..' )

def makeCircle():
    cmds.circle( nr=(0, 90, 1), c=(0, 0, 0) )

def makeSquare():
    cmds.circle( nr=(0, 90, 1), c=(0, 0, 0) )

cmds.showWindow(myWindow)

rawDescription: Place object within a layer in Python - Maya


code:
import csv

class ContactDetails():
    def __init__(self, filename):
        with open(filename, "r") as f_input:
            csv_input = csv.reader(f_input)
            self.details = list(csv_input)

    def get_col_row(self, col, row):
        return self.details[row-1][col-1]

data = ContactDetails("input.csv")

phone_number = data.get_col_row(5, 4)
name = data.get_col_row(2,4)
last_name = data.get_col_row(3,4)

print "%s %s: %s" % (name, last_name, phone_number)

rawDescription: Python 3: How to read a csv file and store specific values as variables


code:
#!/usr/bin/env python2.7

# see http://www.cis.upenn.edu/~bcpierce/unison/download/releases/stable/unison-manual.html#merge

import sys, os, datetime, os, stat, subprocess, filecmp

# log = open("/Users/neal/unison_merge.log", "a")
# sys.stdout = log
# sys.stderr = log

# work around bug in unison adds quotes incorrectly
# something to do with blanks in filenames

def clean(x):
    if len(x) < 3: return x
    if x[0] == "'": x = x[1:]
    if x[-1] == "'": x = x[:-1]
    return x

sys.argv = [clean(x) for x in sys.argv]

try:
    PATH, CURRENT1, CURRENT2, NEW = sys.argv[1:]
except:
    print "usage: ", " ".join("[%s]" % x for x in sys.argv)
    raise

backup_file_color = 'red'  # for mac
promote_remote = False

def is_suffix(a, b): return b[-len(a):] == a

def mac_color_file(file, color):
    if not os.path.exists("/usr/bin/osascript"): return
    color_map = {
        "none":0,
        "orange":1,
        "red":2,
        "yellow":3,
        "blue":4,
        "purple":5,
        "green":6,
        "gray":7,
        }
    assert color in color_map
    assert file[0] == '/', 'absolute path required'
    assert os.path.exists(file)
    #see http://stackoverflow.com/questions/2435580/tagging-files-with-colors-in-os-x-finder-from-shell-scripts
    #osascript -e "tell application \"Finder\" to set label index of alias POSIX file \"$filename\" to $label"
    cmd = '''/usr/bin/osascript -e 'tell application "Finder" to set label index of alias POSIX file "%s" to %d' > /dev/null ''' % (file, color_map[color])
    try:
        retcode = subprocess.call(cmd, shell=True)
        if retcode < 0:
            print >>sys.stderr, "mac_color_file child was terminated by signal", -retcode
        elif retcode > 0:
            print >>sys.stderr, "mac_color_file child returned", retcode
    except OSError, e:
        print >>sys.stderr, "mac_color_file child failed:", e

def merge(PATH, CURRENT1, CURRENT2, NEW, promote_remote):
    # CURRENT1 is copy of local, CURRENT2 is copy of remote

    # PATH is relative to unison root.
    # We need to know absolute path.
    # We get it, assuming CURRENT1 is an absolute path
    # referring to a file in the same subdirectory as PATH.

    if filecmp.cmp(CURRENT1, CURRENT2, shallow = False):
        # special case -- files have same contents
        # not a real conflict.  just use local copy, no backup
        print "merge of identical files"
        os.link(CURRENT1, NEW)
        return

    assert CURRENT1[0] == '/', "CURRENT1 (%s) is not absolute path" % CURRENT1

    PATH_dir, PATH_tail = os.path.split(PATH)
    ABS_dir = os.path.dirname(CURRENT1)

    assert is_suffix(PATH_dir, ABS_dir), "%s not suffix of %s!" % (PATH_dir, ABS_dir)

    ABS_PATH = os.path.join(ABS_dir, PATH_tail)

    timestamp = datetime.datetime.now().strftime("%y%m%d_%H%M")
    (root, ext) = os.path.splitext(PATH_tail)
    for counter in range(100):
        counter = " %d" % counter if counter else ""
        filename = "%s @%s%s%s" % (root, timestamp, counter, ext)
        BACKUP = os.path.join(ABS_dir, filename)
        if not os.path.exists(BACKUP): break
    else:
        assert False, "too many existing backups %s" % BACKUP

    # promote_remote = False
    # seems to retain file props, saving update in next sync?

    print "CONFLICT:", ABS_PATH

    if promote_remote:
        # resolve conflict by using remote copy, while backing up local to BACKUP
        CURRENT1, CURRENT2 = CURRENT2, CURRENT1
        print "CONFLICT remote saved as", filename
    else:
        print "CONFLICT local saved as", filename

    assert os.path.isfile(CURRENT1)
    assert not os.path.exists(NEW)
    assert not os.path.exists(BACKUP)

    os.link(CURRENT1, BACKUP)
    os.link(CURRENT2, NEW)

    if backup_file_color and backup_file_color != 'none':
        mac_color_file(BACKUP, backup_file_color)

    # note: coloring the tmp file NEW is useless - not propagated
    # coloring the current file ABS_PATH causes UNISON to complain

    # chmod -w BACKUP
    # os.chmod(BACKUP, stat.S_IRUSR)

### main ###

try:
    merge(PATH, CURRENT1, CURRENT2, NEW, promote_remote)
except Exception as e:
    print >>sys.stderr, "ERROR in unison_merge.py"
    print >>sys.stderr, "ERROR:", str(e)

rawDescription: Getting a SyntaxError on the last line of code in a Unison Merge script


code:
import csv
with open('names.txt','rb') as f:
    for line in csv.reader(f):
        print line

rawDescription: Importing .txt data in a particular format


rawDescription: how to get name of a file in directory using python

description: Get name of a file in directory using python


code:
import time
import threading

class Worker(threading.Thread):
    def __init__(self, callback, period=0.5, finished_callback = None):
        threading.Thread.__init__(self)
        self.callback = callback
        self.period = period
        self._stop_requested = False
        self._finished_callback = finished_callback

    def run(self):
        t0 = time.time()
        while not self._stop_requested:
            if time.time()-t0>2:
                self.callback()
                t0 = time.time()
            time.sleep(self.period)
        if self._finished_callback:
            self._finished_callback(self)

    def request_stop(self):
        self._stop_requested = True

    @property
    def stopping(self):
        return self._stop_requested

class CoolThing(object):

    def __init__(self):
        self.workers = []
        self.workers_lock = threading.Lock()

    def run_in_background(self, callback, period=0.5):
        if len([w for w in self.workers if not w.stopping])>0:
            raise RuntimeError()
        worker = Worker(callback, period, finished_callback=self.dispose)
        with self.workers_lock:
            self.workers.append(worker)
        worker.start()

    def stop_background(self, join=False):
        if len(self.workers) == 0:
            raise RuntimeError()
        for worker in self.workers:
            worker.request_stop()
        if join:
            for worker in self.workers:
                worker.join()

    def dispose(self, worker):
        with self.workers_lock:
            self.workers.remove(worker)

def my_callback():
    print "Beep"

if __name__=="__main__":
    cool_thing = CoolThing()
    cool_thing.run_in_background(my_callback, 0.5)
    time.sleep(10)
    print cool_thing.workers
    cool_thing.stop_background()
    # Immediatley restart process
    cool_thing.run_in_background(my_callback, 0.5)
    print cool_thing.workers
    time.sleep(5)
    print cool_thing.workers
    time.sleep(5)
    cool_thing.stop_background()
    print cool_thing.workers
    time.sleep(3)
    print cool_thing.workers

rawDescription: What to do with thread being about to terminate?


code:
o = list()
for k in vars(opt):
    o.append(k)
    o.append(getattr(opt, k))
print "List Opt:", o

rawDescription: How do I use optparse to just split the command-line arguments into options and positional args?

description: Use optparse to just split the command-line arguments into options and positional args


code:
class Zombie:
    def __init__(self):
        self.hp = 100

def attack(target):
    target.hp -= DAMAGE
    print "Zombie health %s/100"%target.hp
    if target.hp <= 0:
        print "Zombie dies"

DAMAGE = 50
zombie1 = Zombie()

print "You see a zombie in the distance."
while zombie1.hp > 0:
    user_input = raw_input("What will you do?: ")
    if user_input == 'shoot':
        attack(zombie1)

rawDescription: Having trouble saving items

description: Having trouble saving items


code:
class ForUseInWith(object):

    def test(self):
        print 'works!'

    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        pass

rawDescription: Is there a way to use the Python "with" statement like the "using" of C#


code:
old_reverse = {v: k for k, v in old.items()}
for k, v in new.iteritems():
    try:
        old_k = old_reverse[v]
        print "%s\t%s\t%s\t%s" % (old_k, repr(v), k, repr(v),)
    except KeyError:
        print "[]\t[]\t%s\t%s" % (k, repr(v),)

rawDescription: Python: find differences in two dicts

description: Python: find differences in two dicts


code:
import sys
print "BEGIN;"
for line in sys.stdin:
    escaped = line.rstrip().replace("'", "''")
    print "INSERT OR IGNORE INTO MyTable VALUES('%s');" % escaped
print "COMMIT;"

rawDescription: Efficient way to aggregate and remove duplicates from very large (password) lists (SOLVED)


code:
# ---------- Imports ------------------------------------- #
from Tkinter import *
import matplotlib
import numpy as np
# ---------- Settings ------------------------------------ #
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
# ---------- Classes  ------------------------------------ #
class App(Frame):
    def __init__(self,master=None):
        Frame.__init__(self, master)
        self._job = None
        self.canvas = None
        self.Flag_Zoom = False
        self.pack()
        self._GUI_Design()
        self._GenData()
        self._Figure(self.Arm)
        # Load the figure Window
        # Send to TK
        self.canvas = FigureCanvasTkAgg(self.f, master=self.LF_Graph)

    def _GUI_Design(self):
        # Initial Frames
        self.LF_Control = LabelFrame(self, text='Angle Controls', width=400, height=100, )
        self.LF_Graph = LabelFrame(self, text='Figure', width=400, height=400)
        self.LF_Control.grid(row=0, column=1, padx=5,pady=1)
        self.LF_Graph.grid(row=1, column=0,columnspan=2,padx=5,pady=3)

        # Insert Controls
        # Labels
        self.LB_Info = Label(self,text="Reduced Code", justify=LEFT)
        self.LB_SP = Label(self.LF_Control, text="Spoiler:")

        #   Slider
        self.SpScale = Scale(self.LF_Control, from_=0, to=120, orient=HORIZONTAL, length=300, resolution=1, command=self._UpdateCanvas, tickinterval=10)

        #   Buttons
        self.Zoomb = Button(self.LF_Control, text="Zoom", command=self._Zoom)
        self.Quit = Button(self.LF_Control, text="Quit", command=self.quit)

        # Grid Layout
        self.LB_Info.grid(row=0, column=0,padx=5,pady=1)
        self.LB_SP.grid(row=0, column=0,padx=10,pady=1)
        self.SpScale.grid(row=0, column=1,padx=10,pady=1)
        self.Zoomb.grid(row=0, column=3 ,padx=10,pady=1)
        self.Quit.grid(row=1, column=3 ,padx=10,pady=1)

    def _GenData(self):
        self.Arm     = [[0,10,184.533],[0,153.734,164.932]]

    def _UpdateCanvas(self, event):
        self._job = self.after(100, self._Execute(self.Flag_Zoom))  #miliseconds
        if self._job:
            self.after_cancel(self._job)

    def _Figure(self,Arm):
        # Gen Figure
        self.f = plt.figure(1,figsize=(10,10))
        self.f.frame = False
        plt.clf()
        if not self.Flag_Zoom:
            print 'no zoom'
            plt.axis([-500,2000,-1500,1000])
        else:
            print 'zoom'
            plt.axis([-100,500,-100,500])
        plt.axes().set_aspect('equal', 'datalim')
        plt.plot(Arm[0],Arm[1],"g")

    def _Zoom(self):
        if self.Flag_Zoom:
            self.Flag_Zoom = False
        else:
            self.Flag_Zoom = True
        self._UpdateCanvas
        RotA = self.RotateNO(self.Arm,self.SpScale.get(),[0,0])
        self._Figure(RotA)
        self.canvas.draw()
        self.canvas.show()

    def RotateNO(self,List,Angle,Orig):
        # Angle: deg2rad
        th = -1.*float(Angle)/180*np.pi
        Rot = [[],[]]
        # Loop through
        for i in xrange(0,len(List[0])):
            X1 = (List[0][i]-Orig[0])*np.cos(th) - (List[1][i]-Orig[1])*np.sin(th)+Orig[0]
            Y1 = (List[0][i]-Orig[0])*np.sin(th) + (List[1][i]-Orig[1])*np.cos(th)+Orig[1]
            Rot[0].append(X1)
            Rot[1].append(Y1)
        return Rot

    def _Execute(self,Zoom):
        RotA = self.RotateNO(self.Arm,self.SpScale.get(),[0,0])
        self._Figure(RotA)
        self.canvas.draw()
        self.canvas.show()
        if self.canvas:
            self.canvas.get_tk_widget().grid(row=0, column=0)

# ---------- Execute Application ------------------------- #
root = Tk()
root.title("Rotation")
Exe = App(master=root)
Exe.mainloop()
Exe.destroy()

rawDescription: Python Tkinter Crashing, every run but program continues? Final polishing of Tkinter


code:
def get_sub_strings(s):
    words = s.split()
    for i in xrange(len(words)+1, 0, -1):
        for n in xrange(0, len(words)+1-i):
            yield ' '.join(words[n:n+i])

out = []
for word in c:
    for sub in get_sub_strings(word.lower()):
        if any(sub in s.lower() for s in isl):
            out.append(sub)
            break

print out
#['john', 'query 989877', 'tamm']

rawDescription: Python: Check for partial match of strings between two lists


code:
import requests
from bs4 import BeautifulSoup
import argparse

parser = argparse.ArgumentParser(description='Get Google Count.')
parser.add_argument('word', help='word to count')
args = parser.parse_args()

r = requests.get('http://www.google.com/search',
                 params={'q':'"'+args.word+'"',
                         "tbs":"li:1"}
                )

soup = BeautifulSoup(r.text)
print soup.find('div',{'id':'resultStats'}).text

rawDescription: perform a google search and return the number of results

description: Perform a google search and return the number of results


code:
import multiprocessing
from multiprocessing.managers import BaseManager

class MyManager(BaseManager): pass

def Manager():
    m = MyManager()
    m.start()
    return m

class Counter(object):
  def __init__(self):
    self._value = 0

  def update(self, value):
    self._value += value

  def get_value(self):
      return self._value

MyManager.register('Counter', Counter)

def update(counter_proxy, thread_id):
  counter_proxy.update(1)
  print counter_proxy.get_value(), 't%s' % thread_id, \
    multiprocessing.current_process().name
  return counter_proxy

def main():
  manager = Manager()
  counter = manager.Counter()
  pool = multiprocessing.Pool(multiprocessing.cpu_count())
  for i in range(10):
    pool.apply(func=update, args=(counter, i))
  pool.close()
  pool.join()

  print 'Should be 10 but is %s.' % counter.get_value()

if __name__ == '__main__':
  main()

rawDescription: How can I share a class between processes in Python?

description: Share a class between processes in Python


code:
import os
print 'set FOO=foo'
print 'set PATH=%s;%s' % ('C:\\my_path_dir', os.environ['PATH'])

rawDescription: Launch configured cmd from Python

description: Launch configured cmd from Python


code:
import sys, StringIO
oldout = sys.stdout
sys.stdout = newout = StringIO.StringIO()
for line in 'this', 'that', 'the other': print line

sys.stdout = oldout
print newout.getvalue().replace('\n', '<br />\n')

rawDescription: Python CGI: Translate from stdout to html (e.g. replace \n with <BR>)


code: print repr(a)[1:-1]

rawDescription: storing chr(3) to variable in python output showing junk values

description: Storing chr(3) to variable in python output showing junk values


code:
isbn = raw_input()
for pos, ch in enumerate(reversed(isbn)):
    print "%d * %d is %d" % pos + 2, int(ch), int(ch) * (pos + 2)

rawDescription: Split an integer into digits to compute an ISBN checksum


code:
a = np.array([1,2,3,4,5,20],dtype=np.float32)
b = np.std(a)
c = np.mean(a)
print b
print c
ok = a > (c - b)
a[~ok] = c - b
ok = a < (c + b)
a[~ok] = c + b
print a

rawDescription: changing the values of a list if they are more than a certain value

description: Changing the values of a list if they are more than a certain value


code: for item in varulista: print item

rawDescription: function and classes, usage of __str__

description: Function and classes, usage of __str__


code:
import asyncore
import socket

class EchoHandler(asyncore.dispatcher_with_send):

    def handle_read(self):
        data = self.recv(8192)
        if data:
            self.send(data)

class EchoServer(asyncore.dispatcher):

    def __init__(self, host, port):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.set_reuse_addr()
        self.bind((host, port))
        self.listen(5)

    def handle_accept(self):
        pair = self.accept()
        if pair is None:
            pass
        else:
            sock, addr = pair
            print 'Incoming connection from %s' % repr(addr)
            handler = EchoHandler(sock)

server = EchoServer('localhost', 8080)
# Note that here loop is infinite (count is not given)
asyncore.loop()

rawDescription: Running separate code while a socket server is running?


code:
import time

def application(environ, start_response):
    start_response('200 OK', [('content-type', 'text/plain')])
    while True:
        time.sleep(1.0)
        yield time.ctime() + '\n'

if __name__ == '__main__':
    from wsgiref.simple_server import make_server
    print "Serving on http://localhost:4000..."
    make_server('localhost', 4000, application).serve_forever()

rawDescription: Basic Comet in Python using just std lib


code:
Example
import heapq

heap = []
element1 = Element('A', 1)
element2 = Element('B', 2)
element3 = Element('C', 3)
heapq.heappush(heap, element1)
heapq.heappush(heap, element2)
heapq.heappush(heap, element3)

print Element('A', 1) in heap      # True
print Element('A', 100) in heap    # True
print Element('D', 1) in heap      # False

rawDescription: Check if heapq contains value

description: Check if heapq contains value


code:
import timeit
import types

N = 10000
R = 3
SUFFIX = '_test'
SUFFIX_LEN = len(SUFFIX)

def setup():
    import random
    global s, i, j
    s = 'abcdefghijklmnopqrstuvwxyz'
    i = random.randrange(len(s))
    while True:
        j = random.randrange(len(s))
        if i != j: break

def swapchars_martineau(s, i, j):
    i, j = (i, j) if i < j else (j, i) # make sure i < j
    return s[:i] + s[j] + s[i+1:j] + s[i] + s[j+1:]

def swapchars_martineau_test():
    global s, i, j
    swapchars_martineau(s, i, j)

def swapchars_clements(text, fst, snd):
    ba = bytearray(text)
    ba[fst], ba[snd] = ba[snd], ba[fst]
    return str(ba)

def swapchars_clements_test():
    global s, i, j
    swapchars_clements(s, i, j)

# find all the functions named *SUFFIX in the global namespace
funcs = tuple(value for id,value in globals().items()
            if id.endswith(SUFFIX) and type(value) is types.FunctionType)

# run the timing tests and collect results
timings = [(f.func_name[:-SUFFIX_LEN],
            min(timeit.repeat(f, setup=setup, repeat=R, number=N))
           ) for f in funcs]
timings.sort(key=lambda x: x[1])  # sort by speed
fastest = timings[0][1]  # time fastest one took to run
longest = max(len(t[0]) for t in timings) # len of longest func name (w/o suffix)

print 'fastest to slowest *_test() function timings:\n' \
      ' {:,d} chars, {:,d} timeit calls, best of {:d}\n'.format(len(s), N, R)

def times_slower(speed, fastest):
    return speed/fastest - 1.0

for i in timings:
    print "{0:>{width}}{suffix}() : {1:.4f} ({2:.2f} times slower)".format(
                i[0], i[1], times_slower(i[1], fastest), width=longest, suffix=SUFFIX)

rawDescription: Python Swap two digits in a number?

description: Python Swap two digits in a number


code:
import re

file_info = ['{file:file1, directory:dir1}', '{file:file2, directory:directory2}']

pattern = re.compile(r'\w+:(\w+)')
for item in file_info:
    print re.findall(pattern, item)

rawDescription: Extract values from within strings in a list - python


code:
for i in range(10):
    print i, '\r',
    time.sleep(1)

rawDescription: Python Shell How to Update Status in Shell Without Newline


code: print hex (-1 & 0xffffffff)

rawDescription: How to get hex string from signed integer

description: Get hex string from signed integer


code:
lindex = SimpleFSDirectory(File(indexdir))
ireader = IndexReader.open(lindex, True)
# Query the lucene index for the terms starting at a term named "field_name"
terms = ireader.terms(Term("field_name", "")) #Start at the field "field_name"
facets = {'other': 0}
while terms.next():
    if terms.term().field() != "field_name":  #We've got every value
        break
    print "Field Name:", terms.term().field()
    print "Field Value:", terms.term().text()
    print "Matching Docs:", int(ireader.docFreq(term))

rawDescription: Finding a single fields terms with Lucene (PyLucene)


code:
s = "{{Hello|Hi|Hey} {world|earth} | {Goodbye|farewell} {noobs|n3wbz|n00blets}}"
print spinner(s)

rawDescription: How to make article spinner regex?

description: Make article spinner regex


code:
import ast

modName = "undefined"
modAttr = []
user_ns = {}
class MyTransformer(ast.NodeTransformer):
    def visit_Name(self, node):
        if node.id in modAttr and not node.id in user_ns:
          return self.getName(node)
        return node
    def getName(self, NameNode):
        return ast.Attribute(value=ast.Name(id=modName, ctx=ast.Load()),
                             attr = NameNode.id,
                             ctx  = NameNode.ctx)
def magic_import(self, line):
    global modName, modAttr, user_ns
    modName = str(line)
    if not self.shell.run_code( compile('import {0}'.format(line), '<string>', 'exec') ):
       user_ns = self.shell.user_ns
       modAttr = user_ns[line.strip()].__dict__
       self.shell.ast_transformers.append(MyTransformer())
       print modName, 'imported'

def load_ipython_extension(ip):
    ip.define_magic('magic_import', magic_import)

rawDescription: Hook the global name lookup in a python interpreter


code:
#The results class
class results:
    def __init__(self, results):
        #textIDDict is a generated dict to speed up the lookup
        self.textIDDict={row["TextID"]: row["RecID"] for row in results}
        self.results=results

    def lookup(self, textID):
        try:
            return self.textIDDict[textID]
        except KeyError:
            return "---"

#Two functions to create the (random) data:
def randStr():
    return str(int(random.random()*60000))

def genRes(n):
    return results([{"TextID":randStr(), "RecID": int(random.random()*10000)} for i in range(n)])

#Test it:
results1=genRes(60000)
results2=genRes(15000)

cursor=[[randStr(), randStr()] for i in range(50000)]

for row in cursor:
    row.append(results1.lookup(row[0]))
    row.append(results2.lookup(row[0]))
    print row

rawDescription: Python lookup list of values in list of dictionaries


code:
import matplotlib.cm as cm

print cm.hot(0.3)

rawDescription: How to map number to color using matplotlib's colormap?

description: Map number to color using matplotlib's colormap


code:
import heapq
from operator import itemgetter

def dict_nlargest_items(d,n):
    return heapq.nlargest(n, d.iteritems(), key=itemgetter(1))

mydict = {'a': 1, 'b': 2, 'c': 3}

print dict_nlargest_items(mydict, 2) # [('c', 3), ('b', 2)]

rawDescription: How can I print the values of keys returned by heapq?

description: Print the values of keys returned by heapq


code:
while True :
    print "Poo"

rawDescription: Python - How to make program go back to the top of the code instead of closing


code:
q = "What is the third letter of the alphabet?"
w = [c for c in "abdefghij"] ; c = ["c"]
print "Correct!" if ask(q, w, c) else "No way..."
print "Correct!" if ask(q, w, c) else "No way..."

rawDescription: Python: How to track "correct" answer in randomized multiple choice


code:
def key(event):
    print "pressed", repr(event.keysym)

rawDescription: tkinter shortcuts impossible to enable

description: Tkinter shortcuts impossible to enable


rawDescription: Way of using sorted function in a different manner?


code: print '\033[' + str(code) + 'm'

rawDescription: How can I highlight regex matches in Python?

description: Highlight regex matches in Python


code:
# New loop keeping track of the previous ("old") input states:
old_input_states = [None] * 3
while True:
    input_states = [GPIO.input(n) for n in (37, 32, 29)]
    for n, name in enumerate(['One', 'Two', 'Three']):
        if input_states[n] != old_input_states[n] and input_states[n] == False:
            print name
    old_input_states = input_states

rawDescription: Python Don't Repeat Consecutive Lines

description: Python Don't Repeat Consecutive Lines


code:
from functools import wraps

def mydecorator(val):
    def myrealdecorator(function):
        @wraps(function)
        def decorator(request, *args, **kwargs):
            # do something with request with respect to val
            print 'I know about', val
            return function(request, *args, **kwargs)
        return decorator
    return myrealdecorator

@mydecorator('VALUE')
def foo(request, param):
    print 'inside foo'

foo('arg1', 'arg2')

rawDescription: Decorator Which Returns a function and Accepts a Parameter


code:
profile = Profile.objects.get(user=someone)
print profile.medias.all()
print profile.roles.all()

rawDescription: How to describe m2m triple-join table in model (Django)

description: Describe m2m triple-join table in model (Django)


code:
def car_brand_choice():
    time.sleep(1.5)
    car_brands = car_dict.keys()
    print "These are the car brands I can provide to you.\n"
    print "\n".join(car_brands) # Show brands options
    selection = raw_input("\nNow is your chance to pick which brand you want. ").title()
    print "You selected %s \n" %selection
    print "I have to verify your selection is valid.\n"
    time.sleep(10)
    selection = selection.lower()
    if selection in car_brands:
        print "Valid selection. You may continue.\n"
        #Display brand models after verification
        car_model_choice(selection)
    else:
        print "Not valid selection."
        print "Go back and select a valid brand.\n"
        car_brand_choice()

def car_model_choice(brand):
   print "Select your model."
   for model in car_dict[brand]: # Show model options
       print model
   model_selection = raw_input("\nNow is your chance to pick which model you want. ").title()
   print "You selected a " + brand + " model " + model_selection + " by " + str(price_dict[model_selection])

rawDescription: Based on user selection, display brand models python


code:
class BaseMeta(type):
    def __init__(cls, name, bases, classdict):
        if classdict.get('__metaclass__') is not BaseMeta:  # subclass?
            # replace any occurrences of this subclass name
            # in Base class 'subs' list with the subclass itself
            while name in cls.subs:
                cls.subs[cls.subs.index(name)] = cls
        type.__init__(cls, name, bases, classdict)

class Base:
    __metaclass__ = BaseMeta
    subs = ['Sub3','Sub1']  # some subclass names in some special order

class Sub1(Base): pass
class Sub2(Base): pass
class Sub3(Base): pass

print Base.subs
# [<class '__main__.Sub3'>, <class '__main__.Sub1'>]

rawDescription: Forward declaration of class in Python

description: Forward declaration of class in Python


code:
for tpl in sorted(z_counts, reverse=True)[:5]:
    print lines[tpl[1]]

rawDescription: python: How to compare values in a list by row?

description: Python: How to compare values in a list by row


code:
for i in xrange(2500,7000):
    try:
        page = urllib2.urlopen("http://bvet.bytix.com/plus/trainer/default.aspx?id={}".format(i))
    except:
        continue
    else:
        soup = BeautifulSoup(page.read())
        for eachuniversity in soup.findAll('fieldset',{'id':'ctl00_step2'}):
            print re.sub(r'\s+',' ',','.join(eachuniversity.findAll(text=True)).encode('utf-8'))
            print '\n'
            number = number + 1

rawDescription: Loop URL to scrape using beautiful soup python


code: print np.sum(f(k))

rawDescription: Filling a numpy array using an arbitrary function


code:
#!/usr/bin/python
from subprocess import check_output as co

co("ss -tp > ss.out", shell=True)
rtts = co("cat ss.out | grep ESTAB | awk '{print $4}' | xargs -I {} ss -i 'src {}' | grep \"rtt:\" | awk '{print $4}' | cut -d : -f 2 | cut -d / -f 1", shell=True)
pids = co("cat ss.out | grep ESTAB | awk '{print $6}' | cut -d , -f 2", shell=True)

print zip(rtts.split('\n'), pids.split('\n'))

rawDescription: with root, open other process socket and get tcp_info with python?

description: With root, open other process socket and get tcp_info with python


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup(open('test.html'))
posts = []
for post in soup.find_all('div', class_='post'):
    title = post.find('h3', class_='post-title').text.strip()
    author = post.find('span', class_='post-author').text.replace('Posted by', '').strip()
    content = post.find('div', class_='post-body').p.text.strip()
    date = post.find_previous_sibling('h2', class_='date-header').text.strip()

    posts.append({'title': title,
                  'author': author,
                  'content': content,
                  'date': date})
print posts

rawDescription: Using BeautifulSoup to pull multiple posts from a single blog archive page, without scripts


code:
timer = timeit.default_timer
start = timer()
print lfactor(number)
time_taken = timer() - start

rawDescription: What is the logic behind the <statement, setup> design for timeit?


rawDescription: Store business days according to week in Python (2.7)?


code:
s1 = 'ATAAGGATAAGGATAAGGATAAGGATAAGGATAAGGATAAGGATAAGGATAAGGATAAGG'
s2 = 'A-AAGGA-AAGGA-AAGGA-AAGGA-AAGGA-AAGGA-AAGGA-AAGGA-AAGGA-AAGG'

#assumes both sequences are of same length (post-alignment)
def print_align(seq1, seq2, length):
    while len(seq1) > 0:
        print "seq1: " + seq1[:length-6]
        print "      " + '|'*len(seq1[:length-6])
        print "seq2: " + seq2[:length-6] + "\n"
        seq1 = seq1[length-6:]
        seq2 = seq2[length-6:]

print_align(s1, s2, 30)

rawDescription: Python - Print horizontally two strings, with |


rawDescription: Looping through nested list that contains dictionary


code:
print '\n '.join(movie)
print ' '+'\n '.join(movie)
print '\n'.join([' ' +i for i in movie])

rawDescription: Beginner not sure how to join lists while scraping


code:
import pickle, datetime

test_file = "two_dict_pkl_file"

# store two dicts in a list
MyFirstDict = { 1: 'a' }
MySecondDict = { 2:'b' }
two_dict = [MyFirstDict, MySecondDict]

print "first pickle test"
print "this python list gets pickled:"
print two_dict
print
print "this is the pickle file"
pickle.dump( two_dict, open( test_file, "wb" ) )
print open(test_file, "rb").read()
print

print "update pickle test"
pickle_list = pickle.load(open(test_file, "rb"))
print "this python object is read back:"
print pickle_list
print
d1, d2 = pickle_list
two_dict = [d1, d2]
d1['time'] = d2['time'] = datetime.datetime.now().time()
pickle.dump( two_dict, open( test_file, "wb" ) )
print "this is the updated pickle:"
print open(test_file, "rb").read()
print

print "and this is the updated python:"
print pickle.load(open(test_file, "rb"))

rawDescription: Working with two dictionaries in one pickle file


code:
import numpy as np

dtype = [('name', object), ('address', object), ('famous', bool)]
people = np.array([
        ("Charles Lindberg", "123 St.", True),
        ("Me", "456 St.", False),
        ], dtype)

charlie = people[people['name'] == 'Charles Lindberg'][0]
print charlie['address']

rawDescription: Pythonic alternative to (nested) dictionaries with the same keys?


code:
import re
from functools import partial

replacements = (
    partial(re.compile(r'\s*#define ([A-Z_]+) (.*)').sub, r'\1 = \2'),
    partial(re.compile(r'\s*/\*\s*(.*?)\s*\*/').sub, r'# \1'),
)

for line in inputsequence:
    for transform in replacements:
        line = transform(line)
    print line

rawDescription: converting include file in C to python

description: Converting include file in C to python


code:
foo=Foo()
print type(foo).__name__
# Foo

rawDescription: How to get class name when there is attribute attached?

description: Get class name when there is attribute attached


code:
for i in range(10):
    print "{} -> {}".format(i+.5, round(i+.5))

rawDescription: Rounding numeric output with str.format

description: Rounding numeric output with str.format


code:
results = {}
for root, dirs, files in os.walk(home):
    dirs[:] = [d for d in dirs if not d == '.Trash']
    if name in files:
        path = os.path.join(root, name)
        results[path] = os.stat(path).m_time

sorted_by_mtime = OrderedDict(sorted(results.items(), key=lambda kv: kv[1]))
for path, time in sorted_by_mtime.items():
    print time, path

rawDescription: Some trouble when sorting a dictionary

description: Some trouble when sorting a dictionary


code:
from itertools import islice
for s in islice(gen_subsets_special(set(range(5)), 1), 10):
   print s
for s in islice(gen_subsets_special(set(range(10, 20)), 3), 10):
   print s

rawDescription: Deterministic python generator for K disparate M-sized subsets of a set


code:
import sys
import clang.cindex

def srcrangestr(x):
    return '%s:%d:%d - %s:%d:%d' % (x.start.file, x.start.line, x.start.column, x.end.file, x.end.line, x.end.column)

def main():
    index = clang.cindex.Index.create()
    tu = index.parse(sys.argv[1], args=['-x', 'c++'])

    for x in tu.cursor.get_tokens():
        print x.kind
        print "  " + srcrangestr(x.extent)
        print "  '" + str(x.spelling) + "'"

if __name__ == '__main__':
    main()

rawDescription: Retrieving comments using python libclang


code:
import time
from threading import Thread, Event

def child(quit):
    for _ in xrange(10):
        if quit.isSet():
            print "Parent is dead. Leaving child."
            return

        print "Child alive"
        time.sleep(.5)

def parent():
    quitEvent = Event()
    t = Thread(target=child, args=(quitEvent,))
    t.start()

    try:
        time.sleep(2)
        raise Exception("Parent thread raises exception")
    finally:
        quitEvent.set()

    t.join()

if __name__ == "__main__":
    t = Thread(target=parent, args=())
    t.start()
    t.join()

rawDescription: Check if parent thread is running

description: Check if parent thread is running


code:
def test_any(data, expected):
    return any( x in expected for x in data )

print df_list['b'].apply(lambda x:test_any(x,[2,3,8]) )
print df_list[ df_list['b'].apply(lambda x:test_any(x,[2,3,8]) ) ]

rawDescription: Selecting rows by members of a list contained in a cell


code:
rooms = soup.findAll("li", {"class":"first"})
for room in rooms:
    if room.span:
        print room.span.text

rawDescription: Get House Price data

description: Get House Price data


code:
#!/usr/bin/python

from sphero_driver import sphero_driver
import time

sphero = sphero_driver.Sphero()

while True:
    try:
        sphero.connect()
        break
    except:
        print '\nTrying to connect again!'
        pass

time.sleep(2)

sphero.set_rgb_led(255, 0, 0, 0, False)
time.sleep(1)
sphero.set_rgb_led(0, 255, 0, 0, False)
time.sleep(1)
sphero.set_rgb_led(0, 0, 255, 0, False)
time.sleep(1)

rawDescription: How to use the sphero_ros Python API?

description: Use the sphero_ros Python API


code:
class Foobar(object):
    def __init__(self, a):
        self.a = a

    def __call__(self, b):
        return a + b

f = Foobar(3)
print f(4)  # returns 7

rawDescription: Can someone help me understand special methods vs normal methods?


code:
from scrapy.selector import Selector
sel = Selector(text=open('page.html').read())

container = sel.xpath('//div[@id="results-list"]')
items = container.xpath('.//div[@class="item paid-featured-item"]')
for item in items:
    # *extracted* is a single-item list containing the title.
    extracted = item.xpath('.//div[@class="title"]/text()').extract()
    title = extracted[0]
    print title

rawDescription: xpath works for just one item when add // in it

description: Xpath works for just one item when add // in it


rawDescription: get the max of R,G,B of one image by using programming

description: Get the max of R,G,B of one image by using programming


code:
cmd = "sudo twidge update \"{0}\"".format(tweet)
print cmd
os.system(cmd)

rawDescription: How to add a string to os.system() command? (Python)

description: Add a string to os.system() command? (Python)


code:
import cmd, time

def run():
  while 1:
    print cmd.dothis()
    reload(cmd)
    time.sleep(1)

rawDescription: Reload self-made module

description: Reload self-made module


code:
def file():
  myfile = pickAFile()
  with open(myfile) as f: # with closes your files automatically
       contents = f.readlines()  # creates a list
       print contents[0] # print first element

rawDescription: Need help reading data from input files and displaying it


code:
for n in os.listdir(directoryChosen):
    print n + "   made it here"
    self.listWidget.addItem(n)
    if os.path.isdir(n):

        print directoryChosen + "   almost there"
        newname =  n.replace('$', '#')
        print newname + "    this is newname"
        if newname != n:
            print newname
            print n
            path = os.path.join(directoryChosen, n)
            print path
            target = os.path.join(directoryChosen, newname)
            print target
            os.rename(path, target)

rawDescription: Renaming a folder in Python

description: Renaming a folder in Python


code:
def get_other_players(player):
    for pair in similarities.keys():
        try:
            other_player = pair[(pair.index(player)+1)%2]
            print other_player, "=", similarities[pair]
        except ValueError:
            pass

rawDescription: How to make array of array of dictionaries in python

description: Make array of array of dictionaries in python


code:
print re.findall ('[^\d ]+', "my t0kens");
print re.findall ('[\d]+', "my t0kens");

rawDescription: Separate number/letter tokens in Python

description: Separate number/letter tokens in Python


code:
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import s3config

conn    = S3Connection(s3config.passwd, s3config.secret)
bucket  = conn.get_bucket(s3config.bucket)
s3_path = '/some/path/in/your/bucket'
keys    = bucket.list(s3_path)
# or if you want all keys:
# keys   = bucket.get_all_keys()

for key in keys:
  print key
  # here you can download or do other stuff
  # with the keys like get some metadata
  print key.name
  print key.etag
  print key.size
  print key.last_modified

rawDescription: How can I store URLs from Amazon S3 bucket in Django sqlite db to display & comment on?

description: Store URLs from Amazon S3 bucket in Django sqlite db to display & comment on


code:
y2 = {k:v for l in y for k, v in l.iteritems()}
for k, v in y2.iteritems():
    print k, v

rawDescription: Iterate over a list of objects getting ke/value pairs


code:
#! /usr/bin/python

import pygame
from pygame import *

WIN_WIDTH = 800
WIN_HEIGHT = 640
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)

DISPLAY = (WIN_WIDTH, WIN_HEIGHT)
DEPTH = 32
FLAGS = 0
CAMERA_SLACK = 30

def main():
    global cameraX, cameraY
    pygame.init()
    screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH)
    pygame.display.set_caption("Use arrows to move!")
    timer = pygame.time.Clock()

    up = down = left = right = running = False
    bg = Surface((32,32))
    bg.convert()
    bg.fill(Color("#000000"))
    entities = pygame.sprite.Group()
    player = Player(32, 32)
    platforms = []

    x = y = 0
    level = [
        "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "P                    PPPPPPPPPPP           P",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "P    PPPPPPPP                              P",
        "P                                          P",
        "P                          PPPPPPP         P",
        "P                 PPPPPP                   P",
        "P                                          P",
        "P         PPPPPPP                          P",
        "P                                          P",
        "P                     PPPPPP               P",
        "P                                          P",
        "P   PPPPPPPPPPP                            P",
        "P                                          P",
        "P                 PPPPPPPPPPP              P",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "P                                          P",
        "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",]
    # build the level
    for row in level:
        for col in row:
            if col == "P":
                p = Platform(x, y)
                platforms.append(p)
                entities.add(p)
            if col == "E":
                e = ExitBlock(x, y)
                platforms.append(e)
                entities.add(e)
            x += 32
        y += 32
        x = 0

    total_level_width  = len(level[0])*32
    total_level_height = len(level)*32
    camera = Camera(complex_camera, total_level_width, total_level_height)
    entities.add(player)

    while 1:
        timer.tick(60)

        for e in pygame.event.get():
            if e.type == QUIT: raise SystemExit, "QUIT"
            if e.type == KEYDOWN and e.key == K_ESCAPE:
                raise SystemExit, "ESCAPE"
            if e.type == KEYDOWN and e.key == K_UP:
                up = True
            if e.type == KEYDOWN and e.key == K_DOWN:
                down = True
            if e.type == KEYDOWN and e.key == K_LEFT:
                left = True
            if e.type == KEYDOWN and e.key == K_RIGHT:
                right = True
            if e.type == KEYDOWN and e.key == K_SPACE:
                running = True

            if e.type == KEYUP and e.key == K_UP:
                up = False
            if e.type == KEYUP and e.key == K_DOWN:
                down = False
            if e.type == KEYUP and e.key == K_RIGHT:
                right = False
            if e.type == KEYUP and e.key == K_LEFT:
                left = False

        # draw background
        for y in range(32):
            for x in range(32):
                screen.blit(bg, (x * 32, y * 32))

        camera.update(player)

        # update player, draw everything else
        player.update(up, down, left, right, running, platforms)
        for e in entities:
            screen.blit(e.image, camera.apply(e))

        pygame.display.update()

class Camera(object):
    def __init__(self, camera_func, width, height):
        self.camera_func = camera_func
        self.state = Rect(0, 0, width, height)

    def apply(self, target):
        return target.rect.move(self.state.topleft)

    def update(self, target):
        self.state = self.camera_func(self.state, target.rect)

def simple_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    return Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h)

def complex_camera(camera, target_rect):
    l, t, _, _ = target_rect
    _, _, w, h = camera
    l, t, _, _ = -l+HALF_WIDTH, -t+HALF_HEIGHT, w, h

    l = min(0, l)                           # stop scrolling at the left edge
    l = max(-(camera.width-WIN_WIDTH), l)   # stop scrolling at the right edge
    t = max(-(camera.height-WIN_HEIGHT), t) # stop scrolling at the bottom
    t = min(0, t)                           # stop scrolling at the top
    return Rect(l, t, w, h)

class Entity(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

class Player(Entity):
    def __init__(self, x, y):
        Entity.__init__(self)
        self.xvel = 0
        self.yvel = 0
        self.onGround = False
        self.image = Surface((32,32))
        self.image.fill(Color("#0000FF"))
        self.image.convert()
        self.rect = Rect(x, y, 32, 32)

    def update(self, up, down, left, right, running, platforms):
        if up:
            # only jump if on the ground
            if self.onGround: self.yvel -= 10
        if down:
            pass
        if running:
            self.xvel = 12
        if left:
            self.xvel = -8
        if right:
            self.xvel = 8
        if not self.onGround:
            # only accelerate with gravity if in the air
            self.yvel += 0.3
            # max falling speed
            if self.yvel > 100: self.yvel = 100
        if not(left or right):
            self.xvel = 0
        # increment in x direction
        self.rect.left += self.xvel
        # do x-axis collisions
        self.collide(self.xvel, 0, platforms)
        # increment in y direction
        self.rect.top += self.yvel
        # assuming we're in the air
        self.onGround = False;
        # do y-axis collisions
        self.collide(0, self.yvel, platforms)

    def collide(self, xvel, yvel, platforms):
        for p in platforms:
            if pygame.sprite.collide_rect(self, p):
                if isinstance(p, ExitBlock):
                    pygame.event.post(pygame.event.Event(QUIT))
                if xvel > 0:
                    self.rect.right = p.rect.left
                    print "collide right"
                if xvel < 0:
                    self.rect.left = p.rect.right
                    print "collide left"
                if yvel > 0:
                    self.rect.bottom = p.rect.top
                    self.onGround = True
                    self.yvel = 0
                if yvel < 0:
                    self.rect.top = p.rect.bottom

class Platform(Entity):
    def __init__(self, x, y):
        Entity.__init__(self)
        self.image = Surface((32, 32))
        self.image.convert()
        self.image.fill(Color("#DDDDDD"))
        self.rect = Rect(x, y, 32, 32)

    def update(self):
        pass

class ExitBlock(Platform):
    def __init__(self, x, y):
        Platform.__init__(self, x, y)
        self.image.fill(Color("#0033FF"))

if __name__ == "__main__":
    main()

rawDescription: Add scrolling to a platformer in pygame

description: Add scrolling to a platformer in pygame


code:
numList = [1,4,10]
total = 0
for i in numList:
   total += i

print total

rawDescription: Input to list and operate on it

description: Input to list and operate on it


code:
with open("pages_Romance") as in_file, open("pages_Romance_temp", "w") as out_file:
   for line in in_file:
      print "Page: " + line
      #Do something with the line
      if delete_this_line == False:
          out_file.write(line)

rawDescription: Deleting a line just after reading it

description: Deleting a line just after reading it


code: models_matrix=[[pd.ols(y=df[ref_col],x=df[col]) for col in df if col<>ref_col] for ref_col in df]

rawDescription: Pairwise regressions in Pandas

description: Pairwise regressions in Pandas


code:
d = {
    "stephane": {},
    "philippe": {},
    "helene": {
        "hugo": {},
        "jean-michel": {},
        "fernand": {},
    },
    "gustave": {},
}

def sort_dict_as_list(d):
    sorted_list = []
    for k, v in sorted(d.items()):
        if k:
            sorted_list.append(k)
        if v:
            sorted_list.append(v)
    return sorted_list

def sort_recursive(d):
    if d:
        for k, v in d.items():
            d[k] = sort_recursive(v)
        return sort_dict_as_list(d)
    else:
        return d

if __name__ == "__main__":
    print sort_recursive(d)

rawDescription: Python - Order nested list in alphabetical way


code:
import re

class RegExConcordanceIndex(object):
    "Class to mimic nltk's ConcordanceIndex.print_concordance."

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

    def print_concordance(self, regex, width=80, lines=25, demarcation=''):
        """
        Prints n <= @lines contexts for @regex with a context <= @width".
        Make @lines 0 to display all matches.
        Designate @demarcation to enclose matches in demarcating characters.
        """
        concordance = []
        matches = re.finditer(regex, self._text, flags=re.M)
        if matches:
            for match in matches:
                start, end = match.start(), match.end()
                match_width = end - start
                remaining = (width - match_width) // 2
                if start - remaining > 0:
                    context_start = self._text[start - remaining:start]
                    #  cut the string short if it contains a newline character
                    context_start = context_start.split('\n')[-1]
                else:
                    context_start = self._text[0:start + 1].split('\n')[-1]
                context_end = self._text[end:end + remaining].split('\n')[0]
                concordance.append(context_start + demarcation + self._text
                                   [start:end] + demarcation + context_end)
                if lines and len(concordance) >= lines:
                    break
            print("Displaying %s matches:" % (len(concordance)))
            print '\n'.join(concordance)
        else:
            print "No matches"

rawDescription: Can you do regex with concordance?

description: Do regex with concordance


code:
import re

p = ur'([،;؛¿!"\])}»›”؟%٪°±©®।॥…])'
text = u"this, is a sentence with weird» symbols… appearing everywhere¿"

print re.sub(p, ur' \1 ', text)

rawDescription: Padding multiple character with space - python


code:
from itertools import groupby, count
from operator import itemgetter

a = [1,2,3,5,55,56]

def consc(b, step):
  for k, g in groupby(zip(count(step=step), b), lambda (i, x): i-x):
     print map(itemgetter(1), g)

consc(a, 2)

rawDescription: Finding Deltas - Difference between elements in a Python list


code:
import subprocess

cmd = ('example1.py', 'any', 'more', 'arguments')

expected_out = """Your expected output of the script"""

exampleP = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = exampleP.communicate() # out and err are stdout and stderr, respectively

if out != expected_out:
    print "Output does not match"

rawDescription: Running a set of Python scripts in a list


code:
from collections import defaultdict

def do_it(source):
  dd = defaultdict(lambda: [])
  for item in sum(source, []): # just use your favourite flattening method here
    if is_name(item):
      name = item
    else:
      dd[name].append(item)
  return [[k]+v for k,v in dd.items()]

for s in do_it(l):
  print s

rawDescription: Python: Linking Lists Together

description: Python: Linking Lists Together


code:
# Determine and draw main axis
length = 300
(x,y),(MA,ma),angle = cv2.fitEllipse(cnt)
print  np.pi , angle
print angle * np.pi / 180.0
print np.cos(angle * np.pi / 180.0)
x2 =  int(round(x + length * np.cos((angle-90) * np.pi / 180.0)))
y2 =  int(round(y + length * np.sin((angle-90) * np.pi / 180.0)))
cv2.line(vis2, (int(x), int(y)), (x2,y2), (0,255,0),5)
print x,y,x2,y2

rawDescription: Longest line detection - python - opencv


code:
import copy_reg
import types
from itertools import product
import multiprocessing as mp

def _pickle_method(method):
    """
    Author: Steven Bethard (author of argparse)
    http://bytes.com/topic/python/answers/552476-why-cant-you-pickle-instancemethods
    """
    func_name = method.im_func.__name__
    obj = method.im_self
    cls = method.im_class
    cls_name = ''
    if func_name.startswith('__') and not func_name.endswith('__'):
        cls_name = cls.__name__.lstrip('_')
    if cls_name:
        func_name = '_' + cls_name + func_name
    return _unpickle_method, (func_name, obj, cls)

def _unpickle_method(func_name, obj, cls):
    """
    Author: Steven Bethard
    http://bytes.com/topic/python/answers/552476-why-cant-you-pickle-instancemethods
    """
    for cls in cls.mro():
        try:
            func = cls.__dict__[func_name]
        except KeyError:
            pass
        else:
            break
    return func.__get__(obj, cls)

copy_reg.pickle(types.MethodType, _pickle_method, _unpickle_method)

class ImageData(object):

    def __init__(self, width=60, height=60):
        self.width = width
        self.height = height
        self.data = []
        for i in range(width):
            self.data.append([0] * height)

    def shepard_interpolation(self, seeds=20):
        print "ImD - Success"

def aux():
    return "VoG - Sucess"

class VariabilityOfGradients(object):
    aux = staticmethod(aux)

    @staticmethod
    def calculate_orientation_uncertainty():
        pool = mp.Pool()
        results = []
        for x, y in product(range(1, 5), range(1, 5)):
            # result = pool.apply_async(aux) # this works too
            result = pool.apply_async(VariabilityOfGradients.aux, callback=results.append)
        pool.close()
        pool.join()
        print(results)

if __name__ == '__main__':
    results = []
    pool = mp.Pool()
    for _ in range(3):
        result = pool.apply_async(ImageData.shepard_interpolation, args=[ImageData()])
        results.append(result.get())
    pool.close()
    pool.join()

    VariabilityOfGradients.calculate_orientation_uncertainty()

rawDescription: Can't pickle static method - Multiprocessing - Python


code:
mystring = "abcdefghijklmnopqrstuvwxyz"

for i1 in range(len(mystring)):
    for i2 in range(i1, len(mystring)):
        for i3 in range(i2, len(mystring)):
            for i4 in range(i3, len(mystring)):
                for i5 in range(i4, len(mystring)):
                    for i6 in range(i5, len(mystring)):
                        for i7 in range (i6, len(mystring)):
                            for i8 in range (i7, len(mystring)):
                                for i9 in range (i8, len(mystring)):
                                    for i10 in range (i9, len(mystring)):
                                        strr = "".join([mystring[i3], mystring[i7], mystring[i2], mystring[i1], mystring[i4], mystring[i5], mystring[i6], mystring[i10], mystring[i8], mystring[i9]])
                                        if hashlib.md5(strr).hexdigest() == md5:
                                            print "key = " ,strr
                                            break

rawDescription: Key Bruteforcing

description: Key Bruteforcing


code:
class A(object):

  def __getattr__(self, attr):
    print attr

rawDescription: __getattr__ equivalent for methods

description: __getattr__ equivalent for methods


code:
import time
res = Pool().amap(simFunction, x,y)
while not res.ready():
  print "waiting..."
  time.sleep(5)

res.get()

rawDescription: Python multiprocessing - tracking the process of pool.map operation


code:
raw = raw_input("Enter values: ")
inputs = raw.split(",")
results = []
for i in inputs:
    num = float(i.strip())
    converted = num / 1e4
    results.append(converted)

outputs = []
for i in results:
    outputs.append(str(i))  # convert to string

print "RESULT: " + ", ".join(outputs)

rawDescription: Process multiple input values in Python

description: Process multiple input values in Python


code:
pg = "Hello world, how you doing?\nFoo bar!"
print pg
lines = pg.splitlines()
lines
for line in lines:
    for splt in line.split():
            if "Foo" in splt:
                    print splt

rawDescription: How can I strip the first 14 characters in an list element using python?

description: Strip the first 14 characters in an list element using python


code:
samples = [
    ['pt=media:song','class=song', 'object=mp3'],
    ['class=text','pt=transaction:email', 'object=email'],
    ['category=where','pt=text:where','class:question'],
    ['object:mp4','class=movie', 'pt=media:movie'],
]
for sample in samples:
    print sorted(sample, key=lambda x: (not x.startswith('pt='), x))

rawDescription: Sort lists in python based on a rule

description: Sort lists in python based on a rule


code:
#stack df1 by level 0
df1 = df1.stack(0).reset_index(name='values').rename(columns={'level_3':'dates'})

#column bool from bool1 and bool2 by dates
df1['bool'] = df1.bool1.where(df1['dates'].str.contains('15/12/2015'), df1.bool2)
df1 = df1.drop(['bool1', 'bool2'], axis = 1)
#change order
print df1[['Stock', 'dates', 'bool', 'values']]
#  Stock       dates   bool  values
#0    AA  15/12/2015   True       2
#1    AA  15/11/2015  False      11
#2    BB  15/12/2015  False       4
#3    BB  15/11/2015  False      14
#4    CC  15/12/2015   True       3
#5    CC  15/11/2015  False      12
#6    DD  15/12/2015   True       5
#7    DD  15/11/2015  False      16

rawDescription: Pandas loop for take row and add data back


code:
import numpy as np
import timeit

nmin = 2000 # number of the smallest values to find in a matrix with unique row and column indexes
nrows = 2000 # number of rows
ncols = 2000 # number of columns
print "Select {} smallest values from {} x {} matrix".format(nmin, nrows, ncols)

matrix = np.random.uniform(0, 1, size = nrows * ncols).reshape(nrows, ncols) # sample 2D array
#print matrix

# ALTERNATIVE: sort once and track-and-skip visited rows and columns
startedat = timeit.default_timer()
seenrows = set()
seencols = set()
order = (divmod(index, ncols) for index in np.argsort(matrix, None))
for iter in xrange(nmin):
    while True:
        try:
            current = order.next()
        except:
            break
        if current[0] not in seenrows and current[1] not in seencols:
            #print iter, current, matrix[current[0]][current[1]]
            seenrows.add(current[0])
            seencols.add(current[1])
            break
alternative = timeit.default_timer() - startedat
print "Alternative approach took: ", alternative

# ORIGINAL: repeatedly find minimum and update matrix
startedat = timeit.default_timer()
for k in xrange(nmin):
    index = np.argmin(matrix)
    i, j = divmod(index, np.shape(matrix)[1])
    #print k, (i, j), matrix[i][j]
    matrix = np.delete(np.delete(matrix, i, 0), j, 1)
    if matrix.size == 0: break
original = timeit.default_timer() - startedat
print "   Original approach took: ", original, "WINNER" if original < alternative else "TIE" if original == alternative else "LOOSER"

rawDescription: Find m "smallest" elements from m by n np.array


code:
if __name__ == '__main__':
    print get_os_major_version()

rawDescription: Python ctypes - Getting 0 with GetVersionEx function


code:
stringA = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus aliquam leo odio, ut posuere dui rutrum ac. Nulla facilisi."
stringB = "ut posuere dui rutrum ac"

print stringA.replace(stringB, '')
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus aliquam leo odio, . Nulla facilisi."

rawDescription: how to change index value in python lists

description: Change index value in python lists


code:
for rpl, p1, p2 in RPL:
    print "%8d  %15s  %15s" % (rpl, str(p1), str(p2))

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


code:
def my_loop(self):
    if (time.time() - self.start_time) < self.game_time:
       print "listening"
       root.after(5000, self.my_loop) # run my_loop again after 5000 milliseconds

def start_game(self):
        global p2score

        # use self. to get access in other function
        self.start_time = time.time()
        self.game_time = 30      #length of game

        P1PIN = 23
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(P1PIN, GPIO.IN)
        GPIO.add_event_detect(P1PIN, GPIO.FALLING, callback=self.p2ScoreEvent)

        try:
            GPIO.add_event_detect(P1PIN, GPIO.FALLING, callback=self.p2ScoreEvent)
            self.my_loop() # run my_loop first time
        except:
            print "Something went wrong..."
            GPIO.cleanup()

rawDescription: Python RaspberryPi GPIO Event Detection in Tkinter Failing


code:
import pandas as pd

df = {'most_exhibitions' : pd.Series(['USA (1) Netherlands (5)' ,
'United Kingdom (2)','China (3) India (5) Pakistan (8)','USA (11) India (4)'], index=['a', 'b', 'c','d']),
              'name' : pd.Series(['Bob', 'Joe', 'Alex', 'Bill'], index=['a', 'b', 'c','d'])}

df = pd.DataFrame(df)
#cange ordering of columns
df = df[['name', 'most_exhibitions']]
print df
#   name                  most_exhibitions
#a   Bob           USA (1) Netherlands (5)
#b   Joe                United Kingdom (2)
#c  Alex  China (3) India (5) Pakistan (8)
#d  Bill                USA (11) India (4)

#copy original to new dataframe for joining original df
df1 = df.reset_index().copy()

#remove '(' and last ')'
df['most_exhibitions'] = df['most_exhibitions'].str.replace('(', '')
df['most_exhibitions'] = df['most_exhibitions'].str.strip(')')

#http://stackoverflow.com/a/34065937/2901002
s = df['most_exhibitions'].str.split(')').apply(pd.Series, 1).stack()
s.index = s.index.droplevel(-1)
s.name = 'most_exhibitions'
print s
#a               USA 1
#a       Netherlands 5
#b    United Kingdom 2
#c             China 3
#c             India 5
#c          Pakistan 8
#d              USA 11
#d             India 4
#Name: most_exhibitions, dtype: object

df = df.drop( ['most_exhibitions'], axis=1)
df = df.join(s)
print df
#   name  most_exhibitions
#a   Bob             USA 1
#a   Bob     Netherlands 5
#b   Joe  United Kingdom 2
#c  Alex           China 3
#c  Alex           India 5
#c  Alex        Pakistan 8
#d  Bill            USA 11
#d  Bill           India 4

#exctract numbers and convert them to integer
df['numbers'] = df['most_exhibitions'].str.extract("(\d+)").astype('int')
#exctract text of most_exhibitions
df['most_exhibitions'] = df['most_exhibitions'].str.rsplit(' ', n=1).str[0]
print df
#   name most_exhibitions  numbers
#a   Bob              USA        1
#a   Bob      Netherlands        5
#b   Joe   United Kingdom        2
#c  Alex            China        3
#c  Alex            India        5
#c  Alex         Pakistan        8
#d  Bill              USA       11
#d  Bill            India        4

#pivot dataframe
df = df.pivot(index='name', columns='most_exhibitions', values='numbers')
#NaN to empty string
df = df.fillna('')
df = df.reset_index()

rawDescription: How do I make new columns in dataframe from a row of a different column?

description: Make new columns in dataframe from a row of a different column


code:
for i in bigrams:
    print ' '.join(i),':',bigrams[i]

rawDescription: Bigram Counter Almost Complete Python

description: Bigram Counter Almost Complete Python


code:
import re

regexp = re.compile(r"(.)\1")
data = ["parrot","follia","carrot","mattia","rettoo","melone"]

for str in data:
    match = re.search(regexp, str)
    if match:
        print str, "<- match for double", match.group(1)
    else:
        print str, "<- doesn't match"

rawDescription: It is possible to match a character repetition with regex? How?


code:
def somecode():
   try:
      import cStringIO as StringIO
      print 'got cStringIO'
   except ImportError:
      import StringIO
      print 'got StringIO'
somecode()

rawDescription: Trigger ImportError to test Coverage of Fallback Code


code:
class XmlRPCApi:
    def do_something(self):
        print "doing something"

server = SimpleXMLRPCServer(("localhost", 8000))
server.register_instance(XMLRpcAPI())
server.timeout = 0

while True:
    sleep(0.016)
    do_normal_thing()
    x.handle_request()

rawDescription: Building an HTTP API for continuously running python process


code:
#!/usr/bin/python
from twisted.internet import protocol, reactor, utils, defer
from twisted.web.server import Site
from twisted.web.static import File

from autobahn.websocket import WebSocketServerFactory, WebSocketServerProtocol
from autobahn.util import newid
from autobahn.resource import WebSocketResource

class ModbusThing(object):
  def __init__(self,clientAddress):
    self.clientAddress = clientAddress
    self.client = None
  def start(self):
    pass
    ## Create client connection to modbus server
    ## Start Looping Call of pollForData with suitable interval
  def pollForData(self):
    pass
    ## Call read methods on ModbusClient object, add call backs to process the results
    ## Add errorBacks to notify of errors
  def resultCallback(self,result):
    pass
    ## Process the data from a read request
    ## Assumes that your websocket clients expect json like {"event":"update","data":[0,1,2]}
    message = dict(event="update",data=processedResults)
    self.broadcast(json.dumps(message))
  def broadcast(self,msg):
    """Override me"""
    pass

class TrackingWebSocketProtocol(WebSocketServerProtocol):
  def onOpen(self):
    self.session_id = newid()
    self.factory._addSession(self,self.session_id)
    print "Socket Open %s" % (self.peerstr,)

  def onMessage(self,payload,isBinary):
    print "Message received from %s\n\t: %r" % (self.peerstr,payload)

  def onClose(self,wasClean,code,reason):
    self.factory._removeSession(self)
    print "Socket Closed %s" % (self.peerstr,)

class TrackingWebSocketFactory(WebSocketServerFactory):
  def __init__(self,*args,**kwargs):
    WebSocketServerFactory.__init__(self,*args,**kwargs)
    self.proto2session = {}
    self.session2proto = {}
  def _addSession(self,proto,session_id):
    if not self.proto2session.has_key(proto):
       self.proto2session[proto] = session_id
    else:
       raise Exception("logic error - dublicate _addSession for protoToSessions")
    if not self.session2proto.has_key(session_id):
       self.session2proto[session_id] = proto
    else:
       raise Exception("logic error - dublicate _addSession for sessionsToProto")
  def _removeSession(self,proto):
    if proto in self.proto2session:
      session_id = self.proto2session[proto]
      del self.proto2session[proto]
      if session_id in self.session2proto:
        del self.session2proto[session_id]
  def sendToAll(self,message,binary=False):
    prepped = self.prepareMessage(message,binary)
    for proto in self.proto2session.keys():
      proto.sendPreparedMessage(prepped)

def run():
  ## WebSocket Factory
  wsfactory = TrackingWebSocketFactory('ws://yourhostname:80')
  wsfactory.protocol = TrackingWebSocketProtocol
  wsresource = WebSocketResource(wsfactory)
  ## Modbus handler
  modbus_thing = ModbusThing((addressofserver,portofserver))
  modbus_thing.broadcast = wsfactory.sendToAll
  modbus_thing.start()
  ## WebServer Site
  # "static" subdirectory, containing http served resources, e.g. index.html, javascript and css
  root = File("static")
  # Your websocket service as 'ws://yourhostname/ws'
  root.putChild("ws", wsresource)
  site = Site(root)
  reactor.listenTCP(80,site)

def main():
  reactor.callWhenRunning(run)
  reactor.run()

if __name__=='__main__':
  main()

rawDescription: How to asynchronously read data via modbus/TCP and send them to web

description: Asynchronously read data via modbus/TCP and send them to web


code: print "      it is python testing"

rawDescription: Why the variable in shell script from the result of python works strange?


code:
s='caabcdab'
sub =''
test =s[0]

for i in range(1,len(s)+1):
    n = i%len(s)
    if len(test) > len(sub):
        sub = test
        if i >= len(s):
            break
    if s[n] >= s[n-1]:
        test += s[n]
    else:
        test = s[n]

print 'Logest substring in alphabetic order is: ' + str(sub)

rawDescription: Longest string in alphabetic order

description: Longest string in alphabetic order


code:
from Tkinter import *
import time

def foo(m):
    for i in xrange(m):
        i * 2
        pbar_f.step(1)
        master.update()
        time.sleep(0.1)
    return i

def start_ind():
    for i in xrange(500):
        pbar_ind.step(1)
        master.update()
        # Busy-wait
        time.sleep(0.1)

def start_det():
    for i in xrange(500):
        pbar_det.step(1)
        master.update()
        # Busy-wait
        time.sleep(0.1)

def start_fun(self):
    res = foo(500)
    print 'res:', res

master = Tk()

master.title("ProgressBar example")
master.minsize(200, 100)
#grid(sticky=E+W+N+S)

#top = winfo_toplevel()
master.rowconfigure(0, weight=1)
master.columnconfigure(0, weight=1)

start_ind = Button(master, text='Start indeterminate', command=start_ind, activeforeground="red")
start_ind.grid(row=0, column=0, pady=2, padx=2, sticky=E+W+N+S)

pbar_ind = ttk.Progressbar(master, orient="horizontal", length=300, mode="indeterminate")
pbar_ind.grid(row=1, column=0, pady=2, padx=2, sticky=E+W+N+S)

start_det = Button(master, text='Start determinate', command=start_det, activeforeground="red")
start_det.grid(row=2, column=0, pady=2, padx=2, sticky=E+W+N+S)

pbar_det = ttk.Progressbar(master, orient="horizontal", length=300, mode="determinate")
pbar_det.grid(row=3, column=0, pady=2, padx=2, sticky=E+W+N+S)

inside_f = Button(master, text='Start function', command=start_fun, activeforeground="red")
inside_f.grid(row=4, column=0, pady=2, padx=2, sticky=E+W+N+S)

pbar_f = ttk.Progressbar(master, orient="horizontal", length=300, mode="determinate")
pbar_f.grid(row=5, column=0, pady=2, padx=2, sticky=E+W+N+S)

master.mainloop()

rawDescription: how to embed a Tkinter progressbar in a function in Python

description: Embed a Tkinter progressbar in a function in Python


code:
from collections import Counter

l = {'users': [{'photos': [{'tags': [1,2,3,4,5]}, {'tags': [3,4,5]}]},
               {'photos': [{'tags': [1]}, {'tags': [2,3,4,5]}]}]}

tags = Counter(t for u in l['users'] for p in u['photos'] for t in p['tags'])
print tags  # prints Counter({3: 3, 4: 3, 5: 3, 1: 2, 2: 2})

rawDescription: Python dictionary add in value / optimize


code:
x = []
y = []
with open("C:/Users/Martinez/Documents/Diego/Python/SampleData.txt") as read_file:
    for line in read_file:
        print line
        a, b = line.split(',')
        x.append(int(a))
        y.append(int(b))

print x
print y

rawDescription: ValueError: invalid literal for int() with base 10: ' '


code:
a_parser = Parser("(%D)%U_%P_%S")
print a_parser.parse("(2005-04-12)Jamie_123_Server1")

b_parser = Parser("%S - %P - %D")
print b_parser.parse("Server1 - 123 - 2005-04-12")

rawDescription: Python Emulate strptime behavor

description: Python Emulate strptime behavor


code:
import lxml.html
from lxml.html import tostring

source = """

blablabla bla prprpr  jj

blalbla ttt sskkss  aa

"""

h = lxml.html.document_fromstring(source)

print ""
print tostring(h, pretty_print=True)
print

for span in h.xpath('//span[@id]'):
    span_id = span.attrib.get('id', None)
    parent_class = span.getparent().attrib.get('class', None)
    if parent_class is None:
        continue
    if redundant_span(span_id, parent_class):
        unwrap(span)

print ""
print tostring(h, pretty_print=True)

rawDescription: lxml strip_tags results in AttributeError

description: Lxml strip_tags results in AttributeError


code:
import json
delete1 = { "id":"ID" }
delete2 = { "query":"QUERY" }
delete3 = { "query":"QUERY", 'commitWithin':'500' }
data = []
data.append(('delete', delete1))
data.append(('delete', delete2))
data.append(('delete', delete3))
'{%s}' % ',\n'.join(['"{}": {}'.format(action, json.dumps(dictionary)) for action, dictionary in data])
print '{%s}' % ',\n'.join(['"{}": {}'.format(action, json.dumps(dictionary)) for action, dictionary in data])

rawDescription: Python json encode with same keys (solr)


code:
class B:
    def __init__(self, a):
        self.a = a
    def temp(self):
        return self.a.temp()

class A:
    def __init__(self):
        self._temp = 10
        self.counter = 0

    def temp(self):
        return self.counter < self._temp

if __name__ == "__main__":
    obj = B(A())
    print obj.temp()

rawDescription: Python Class Objects Attribute Referencing


code:
print vars(r)
print vars(Test)

rawDescription: How to get all attribute in class?

description: Get all attribute in class


code:
Example
counters = [1,6,3,8,4,6]

print [b-a for a,b in zip(counters,counters[1:])]

[OUTPUT]
[5, -3, 5, -4, 2]

rawDescription: Operating on pairs of value in an array

description: Operating on pairs of value in an array


code:
print d.entries[i].title, # <- comma here
print d.entries[i].date

rawDescription: combine lines from 2 prints to single line and insert into mysql database

description: Combine lines from 2 prints to single line and insert into mysql database


code:
try:
    obj2 = ref_to_obj(ref)
    print 'obj != obj2  : ',obj != obj2
    if obj != obj2:
        raise ValueError
except Exception:
    raise ValueError('Cannot determine the reference to %s' % repr(obj))
return ref

rawDescription: Textual reference of a method

description: Textual reference of a method


code:
import urllib2
from bs4 import BeautifulSoup

profile = ['Tweets', 'Followers']

link = "https://twitter.com/iamjericho"
r = urllib2.urlopen(link)
src = r.read()
res = BeautifulSoup(src)
followers = ''
for p, d in zip(profile, res.find_all('span', { 'data-is-compact': "true"})):
    print p, d.text

rawDescription: BeautifulSoup: Scraping different data sets having same set of attributes in the source code


code:
print "client loop started"
while True:
    m = q.get()
    print "waiting for start, got:", m
    if m == "start":
      while True:
        try:
          m = q.get(False)
        except:
          m = None
        print "waiting for stop, got:", m
        if m == "stop":
          break

rawDescription: Handle multiple messages with Queue get()


code:
from bs4 import BeautifulSoup
import requests

respond = requests.get("http://physics.nist.gov/PhysRefData/XrayMassCoef/ElemTab/z30.html")
soup = BeautifulSoup(respond.text)
l = soup.find('table').find('table').find_all('tr')
for i in range(3 , len(l)):
    print l[i].get_text()

rawDescription: Accessing web table using Python - NIST website


code:
listword = ['foo', 'bar', 'baz']
sentence = 'The quick fox jumped over the barred door'
if any(re.search(r'\b{}\b'.format(re.escape(word)), sentence) for word in listword):
    print 'yes'

sentence = 'The tradition to use fake names like foo, bar or baz originated at MIT'
if any(re.search(r'\b{}\b'.format(re.escape(word)), sentence) for word in listword):
    print 'yes'

rawDescription: Finding whether a word exist in a string in python


code:
one = ['hell','good','bad']
two = ['hello', 'goodbye', 'goodness', 'badly', 'baddest']

for a in one:
    print a,'=',
    for b in two:
        if a in b:
            print b,
    print

rawDescription: Python - Loop Through List A and Match Words Contained in List B


code:
app_config = dict(sql="""\
SELECT DISTINCT p.id_product,
                p.price AS price,
                sp.reduction AS discount,
                sp.reduction_type AS discount_type,
                pl.description_short AS description
    FROM ....""")
print yaml.dump(app_config)

rawDescription: Save SQL to YAML as is

description: Save SQL to YAML as is


code:
with open(filename) as myfile:
    for line in myfile:
        line = line.strip() # get rid of leading and trailing whitespace

        h1 = line[-8:-6]
        h2 = line[-6:-4]
        h3 = line[-4:-2]
        h4 = line[-2:]

        print h1,h2,h3,h4

rawDescription: Slice only working on the last line in a file using 'with open' and 'readline'


code: print result

rawDescription: Regex search and replace pattern with modified pattern - Python


code:
import site
print site.PREFIXES

rawDescription: prevent python from loading a pth file

description: Prevent python from loading a pth file


code: print "{} Modified: {}".format(keyword,  method, ", ".join( [str(v) for v in (value, limit, parameter) if not v is None]))

rawDescription: Print parameters passed to the function

description: Print parameters passed to the function


code: print df.groupby('letters').apply(lambda x: x.fillna(method='ffill'))

rawDescription: Apply function to pandas sorting by a unique value in a column


code:
from numpy import mean

for d in set(key):
    print d, mean([dist[i] for i in range(len(key)) if key[i] == d])

rawDescription: average of certain values of an array

description: Average of certain values of an array


code:
import itertools
components = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
statuses = ['Up', 'Down']

for state in itertools.product(statuses, repeat=len(components)):
    for c,s in zip(components, state):
        print '{}:{}'.format(c,s),
    print

rawDescription: Making a decision tree

description: Making a decision tree


rawDescription: How to make matrices in Python?

description: Make matrices in Python


code: print len(self.bitmap2.GetChildren())

rawDescription: Avoiding unnecessary memory consumption in Python and wxPython


code:
f1 = open("superset.txt","r")
f2 = open("subset.txt","r")
l1 = list(f1)
l2 = list(f2)
l3 = []
for li in l1:
    if li in l2:
        l3.append(li.strip())
    else:
        l3.append(None)

print l3     # or you can save this to a file.

rawDescription: Sorting a list and adding None values in the right positions


code: print json.dumps(somedict)

rawDescription: Python Tuple to JSON output

description: Python Tuple to JSON output


code:
class State(object):
    @property
    def population(self):
        return self._population
    @population.setter
    def population(self,value):
        if value < 0:
            raise ValueError("Population must not be negative")
        else:
            self._population = value

class Town(object):
    def __init__(self, population):
        self._population = population

    @property
    def population(self):
        return self._population

s = State()
s.population = 30
print s.population

t = Town(s.population)
print t.population

rawDescription: Properties and inheriting from instances


code:
class Programs:

    def ask(self):
        while 1: # infinite loop
            name = raw_input("Name: ")
            if name == "":
                print "Ops! Retry"
            else:
                print "Hello", name
                break  # this will break the loop

rawDescription: How to get user input within a Method (python)

description: Get user input within a Method (python)


code:
for spec in soup.select('div.product-specs dl.product-specs--list > dt.product-specs--item-title span.product-specs--help-title'):
    print spec.get_text(strip=True)

rawDescription: Python Crawler Beatifulsoup decompose() function


code:
import random
print "WELCOME TO LOTTERY HACK MACHINE!!!\n"
today = int(raw_input( "Please enter today's date: " ))
if today<=31:
    print "Please enter the 4-digit prize winning lottery number for the last 7 days"
    y = raw_input( "Enter 7 numbers separated by commas: " )
    input_list = y.split(',')
    numbers = [float(x.strip()) for x in input_list]
    random.shuffle(numbers)
    print numbers

elif today>31:
    print "A month has only 31 days ;P"

rawDescription: How to choose a random input from 7 given input?

description: Choose a random input from 7 given input


code:
def TestWithAssignment(value):
    def innerFunc(value):
        print value
        # Immediate local **and assigned now**.
        value = "Changed value"
        # If you need to keep the changed value
        # return value
    innerFunc(value)
    # If you need to keep the changed value use:
    # value = innerFunc(value)

rawDescription: Confusing change of scope - what's going on?


code:
data = [['hoose', 200],
        ["Bananphone", 10],
        ['House', 200],
        ["Bonerphone", 10],
        ['UniqueValue', 777]]

already_merged = []

for word, score in data:
    added_to_existing = False
    for merged in already_merged:
        for potentially_similar in merged[0]:
            if levenshtein(word, potentially_similar) < 5:
                merged[0].add(word)
                merged[1] += score
                added_to_existing = True
                break
        if added_to_existing:
            break
    if not added_to_existing:
        already_merged.append([set([word]),score])

print already_merged

rawDescription: How to merge similar items in a list

description: Merge similar items in a list


code:
my_list = [1, 2, 3]
for counter, value in enumerate(my_list):
    exec 'a{} = {}'.format(counter, value)
print a0, a1, a2

rawDescription: How to use sequence unpacking with a sequence of variable length?

description: Use sequence unpacking with a sequence of variable length


code:
import fileinput
import sys

inpfile = 'actualdata.txt'
replacement_file = 'replace.txt'

replacement_data = {}

with open(replacement_file) as f:
    for line in f:
        key = line.split(',')[0].strip()
        replacement_data[key] = line

for line in fileinput.input(inpfile, inplace = 1):
    first_char = line.split(',')[0].strip()
    try:
        int(first_char)
        line = replacement_data[first_char]
        print line,
    except (ValueError, KeyError):
        print line,
        continue

rawDescription: replace lines in a text file from another text file

description: Replace lines in a text file from another text file


code:
import os

def any_p(iterable):
    for element in iterable:
        if element:
            return True
    return False

include_dirs = ['Dir4/SubDir4.2', 'Dir1/SubDir4.2', 'Dir3', 'Dir2'] # List all your included folder names in that

for root, dirs, files in os.walk( '.' ):
    dirs[:] = [d for d in dirs if any_p(d in os.path.join(root, q_inc) for q_inc in include_dirs)]

    for file in files:
        print file

rawDescription: Excluding all but a single subdirectory from a file search


code:
for x in range(1, 100, 2):
    print x

rawDescription: How to count by twos with Python's 'range'

description: Count by twos with Python's 'range'


rawDescription: how to change 39.54484700000000 to 39.54 and using python

description: Change 39.54484700000000 to 39.54 and using python


code:
a = Foo()
print a['bar']
# barbar

print a.keys()
# ['bar']

rawDescription: Why does overriding __contains__ break OrderedDict.keys?


code:
def factors(n):
    while n > 1:
        for i in range(2, n + 1):
            if n % i == 0:
                n /= i
                yield i
                break

for factor in factors(360):
    print factor

rawDescription: Factorizing a number in python

description: Factorizing a number in python


code:
def fsm(self, event):
    old_state = self.state #only for logging
    if self.state == "idle":
        if event == "focus_entry":
            self.createPopup()
            self.state = "virtualkeyboard"
    elif self.state == "virtualkeyboard":
        if event == "focus_entry":
            self.destroyPopup()
            self.state = "typing"
        if event == "focus_out_entry":
            self.destroyPopup()
            self.state = "idle"
        elif event == "key_entry":
            self.destroyPopup()
            self.state = "typing"
    elif self.state == "typing":
        if event == "focus_out_entry":
            self.state = "idle"
    print "{} --{}--> {}".format(old_state, event, self.state)

rawDescription: Making a pop-up keyboard in Tkinter with Toplevel


code:
fd = open('data.txt')
lines = [line.strip() for line in fd]
adict = {}
num_list = []
last_key = None
print lines
for line in lines:
  try:
    num = int(line)
    num_list.append(line)
  except ValueError, error:
    adict[last_key] = num_list
    last_key = line
    num_list = []
    adict[last_key] = []

adict[last_key] = num_list
print adict

rawDescription: Creating dictionaries from a text file

description: Creating dictionaries from a text file


code:
group_counts = Counter({f: len(items) for f, items in food_groups.iteritems()})
for food, count in group_counts.most_common(2):
    print '{} ({}):'.format(food, count)
    print '  items {}\n'.format(', '.join(food_groups[food]))

rawDescription: Using counter on array for one value while keeping index of other values


code:
import urllib2
import json
from bs4 import BeautifulSoup

url = ('https://ajax.googleapis.com/ajax/services/search/patent?' +
       'v=1.0&q=barack%20obama')
request = urllib2.Request(url, None, {})
response = urllib2.urlopen(request)
jsonResponse = json.load(response)
responseData=jsonResponse['responseData']
results = responseData["results"]

print "This doesn't work, no assignee data..."
for result in results:
    print "patent no.: ", result["patentNumber"]
    print "assignee: ", result["assignee"]
    print " "

print "...but this seems to."
for result in results:
    URL = "https://www.google.com/patents/"+result["patentNumber"]
    req = urllib2.Request(URL, headers={'User-Agent' : "python"})
    _file = urllib2.urlopen(req)
    patent_html = _file.read()
    soup = BeautifulSoup(patent_html, 'html.parser')
    patentNumber = soup.find("span", { "class" : "patent-number" }).text
    assigneeMetaTag = soup.find("meta", { "scheme" : "assignee"})
    patentAssignee = assigneeMetaTag.attrs["content"]
    print "patent no.: ", patentNumber
    print "assignee: ", patentAssignee
    print " "

rawDescription: Using Google patent api

description: Using Google patent api


code:
field = list({ random.randint(-10, 30) for i in range(30) })
field.sort()
upper = binsearch(field, lower=False)
lower = binsearch(field, b=upper+1)
for i, f in enumerate(field):
  print lower <= i <= upper, i == f, i, f

rawDescription: dificulty solving a code in O(logn)

description: Dificulty solving a code in O(logn)


rawDescription: Finding Median in 13 rows in CSV

description: Finding Median in 13 rows in CSV


code:
import numpy as np
slice_at = [3, 5]
group_sizes = np.diff([0] + slice_at + [len(df)])
mapping = dict(zip(df.index, np.repeat(range(len(group_sizes)), group_sizes)))
for _, df_k in df.groupby(mapping):
    print df_k.reset_index(drop=True)

rawDescription: Subsetting Data Frame into Multiple Data Frames in Pandas


code:
from itertools import product

text = 'value1 value2 value3_0,value3_1 value4 value5_0,value5_1,value5_2,value5_3 value6'
items = [el.split(',') for el in text.split()]
for item in product(*items):
    print item # use ' '.join(item) to get a string back

rawDescription: Spliting a string containing many values into many strings with one value for each


code: print d.viewkeys() > {"from", "to"}

rawDescription: python dictionary check if any key other than given keys exist

description: Python dictionary check if any key other than given keys exist


code:
string ='I love traveling all over the world'
word_list =['I love','traveling','all over the world']

for x in word_list:
    if x in string:
        print x

rawDescription: how to test if there is any word matched the string in Python

description: Test if there is any word matched the string in Python


code:
@coroutine
def someroutine():
    with open('test.txt', 'a') as f:
        yield
        f.write('A')
    while True:
        yield
    yield 0

routine = someroutine()
print 'I am working in parallel!'
routine.send()
print 'But only cooperatively...'
routine.send()

rawDescription: Python loop in a coroutine

description: Python loop in a coroutine


code:
from pytz import timezone
tz = timezone("Europe/Paris")
print tz._utc_transition_times

rawDescription: How to determine when DST starts or ends in a specific location in Python?

description: Determine when DST starts or ends in a specific location in Python


code:
for module, grade in person.getModules():
       print "Module: " + module
       print "Grades: " + grade

rawDescription: Saving Raw_input to a list when used in a While Loop


code:
import numpy as np
from blas_multiply import blas_multiply
import time

#np.__config__.show()
n_rows, n_cols = 1e6, 100
np.random.seed(seed = 0)

#initialize data matrix X and label vector Y
X = np.random.random(size=(n_rows, n_cols))
Y = np.random.randint(low=0, high=2, size=(n_rows, 1))
Y[Y==0] = -1
Z = X*Y
Z.flags
Z = np.require(Z, requirements = ['F'])

rho_test = np.random.randint(low=-10, high=10, size= n_cols)
set_to_zero = np.random.choice(range(0, n_cols), size =(np.floor(n_cols/2), 1), replace=False)
rho_test[set_to_zero] = 0.0
rho_test = np.require(rho_test, dtype=Z.dtype, requirements = ['F'])

start_time = time.time()
scores = blas_multiply(Z, rho_test)
print "Cython runtime = %1.5f seconds" % (time.time() - start_time)

Z = np.require(Z, requirements = ['C'])
rho_test = np.require(rho_test, requirements = ['C'])
start_time = time.time()
py_scores = np.exp(Z.dot(rho_test))
print "Python runtime = %1.5f seconds" % (time.time() - start_time)

rawDescription: What is causing the 2x slowdown in my Cython implementation of matrix vector multiplication?


code:
import fileinput
for iLine in filinput.input(r'c:\testfile.xml',inplace = True):
    if iLine.find("musicStyle") >= 0:
         mpr = re.search(r'(.*>)(.*?)(<.*)', iLine, re.M|re.I)
         #modify iLine here
    print iLine     #write the line to  the file

rawDescription: Replace text in a file

description: Replace text in a file


code:
projects = [  row + [x[1] for x in emails if x[0] == row[1]] for row in projects ]
print projects

rawDescription: How to combine two lists

description: Combine two lists


code:
ser = df['col'].value_counts()

def somecalulation(s, x):
    return s[x]

print somecalulation(ser, 1)
5
print somecalulation(ser, 2)
3

rawDescription: Pandas, Get count of a single value in a Column of a Dataframe


code:
#!/usr/bin/env python2.7

import re

data = [u'$760,507,625 (USA) (18 November 2010)',
        u'$760,505,847 (USA) (14 November 2010)',
        u'$760,462,559 (USA) (7 November 2010)',
        u'$760,410,799 (USA) (31 October 2010)',
       'blah']

RE_DATA = re.compile(r'^\$([0-9,]+) \(([A-Z]+)\) \(([0-9]+) ([A-Za-z]+) ([0-9]+)\)$')

MONTHS = {
    'January': 1,
    'February': 2,
    'March': 3,
    'April': 4,
    'May': 5,
    'June': 6,
    'July': 7,
    'August': 8,
    'September': 9,
    'October': 10,
    'November': 11,
    'December': 12
}

for entry in data:
    match = RE_DATA.match(entry)
    if match is None:
        print 'Error! %r did not match pattern' % entry
        continue

    amount, country, day, month, year = match.groups()
    amount = int(amount.replace(',', ''))
    country = str(country)
    day = int(day)
    month = MONTHS[month]
    year = int(year)

    print [amount, month, day, year, country]

rawDescription: How to parser this unicode string list

description: Parser this unicode string list


code:
def function(*args):
    print args
function(1, 2, 3)

rawDescription: How to take any number of inputs in python without defining any limit?

description: Take any number of inputs in python without defining any limit


rawDescription: How to find index of a given Fibonacci number

description: Find index of a given Fibonacci number


code:
#!/usr/bin/env python
import urllib2
from contextlib import closing

import regex # pip install regex
from BeautifulSoup import BeautifulSoup

with closing(urllib2.urlopen(URL)) as page:
     soup = BeautifulSoup(page)
     print soup(text=regex.compile(ur'(?fi)\L<keywords>',
                                   keywords=['your', 'keywords', 'go', 'here']))

rawDescription: Returning a lower case ASCII string from a (possibly encoded) string fetched using urllib2 or BeautifulSoup


code:
dfd = pd.melt(dfd, value_vars=dfd.columns.difference([value_col]).tolist(), id_vars=value_col)
dfd['variable'] = dfd.variable.str.replace(r'\d_', '')
print dfd.head()

rawDescription: Pandas Groupby : group **by** a column containing tuples