code:
import random

def play(till_jackpot_count):
    game_data_per_jackpot = [{'plays' : 0, 'wins' : 0}]
    wheel_values = xrange(36)
    wheels = [0, 0, 0]
    while till_jackpot_count >= len(game_data_per_jackpot):
        wheels = [random.choice(wheel_values) for wheel in wheels]
        game_data_per_jackpot[-1]['plays'] += 1
        print '%d plays since last jackpot' % game_data_per_jackpot[-1]['plays']
        print '%d wins since last jackpot' % game_data_per_jackpot[-1]['wins']
        print '%d total plays' % sum([data['plays'] for data in game_data_per_jackpot])
        print '%d total wins' % sum([data['wins'] for data in game_data_per_jackpot])
        print '%d total jackpots' % (len(game_data_per_jackpot) - 1)
        print 'this play: {} {} {}'.format(*wheels)
        if len(set(wheels)) == 1:
            if wheels[0] == 7:
                print 'jackpot!'
                game_data_per_jackpot.append({'plays' : 0, 'wins' : 0})
            else:
                print 'win!'
                game_data_per_jackpot[-1]['wins'] += 1
    return game_data_per_jackpot[:-1]

play(10)

rawDescription: wins on average

description: Wins on average


code:
word = raw_input("Enter sequence:")

# build a dictionary to know what letter to switch to
swap_dict = {'A': 'T', 'T': 'A', 'C': 'G', 'G': 'C'}

# find out what each letter in the reversed word maps to and then join them
newword = ''.join(swap_dict[letter] for letter in reversed(word))

print "Reverse complement sequence:", newword

rawDescription: Python structure mistake

description: Python structure mistake


code:
import console
import BaseHTTPServer
import SocketServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
import sys
import threading
import webbrowser
from time import sleep
import ui

original_stdout = sys.stdout
original_stderr = sys.stderr

class BasicServer(SocketServer.TCPServer):
    allow_reuse_address = True

class NullifyOutput():
    def write(self, s):
        pass

class ServerThread(threading.Thread):
    def __init__(self, ip, port):
        super(ServerThread, self).__init__()
        self.ip = ip
        self.port = port
        self.HandlerClass = SimpleHTTPRequestHandler
        self.Protocol = 'HTTP/1.0'
        self.server_address = (self.ip, self.port)
        self.HandlerClass.protocol_version = self.Protocol
        try:
            self.httpd = BasicServer(self.server_address, self.HandlerClass)
        except:
            self.port += 1
            self.server_address = (self.ip, self.port)
            self.httpd = BasicServer(self.server_address, self.HandlerClass)
        self.stoptheserver = threading.Event()

    def run(self):
        while not self.stoptheserver.isSet():
            self.httpd.handle_request()

    def join(self, timeout=None):
        self.stoptheserver.set()
        self.httpd.socket.close()
        super(ServerThread, self).join(timeout)

server = ServerThread('127.0.0.1', 8000)

def start_t(sender):
    print server.isAlive()
    if not server.isAlive():
        server.start()

def visit_t(sender):
    webbrowser.open('http://127.0.0.1:' + str(server.port))
    #webbrowser.open('safari-http://127.0.0.1' + str(server.port))
    # Use the safari- prefix to open in safari. You may need to switch to
    # pythonista then back to safari to get the page to load.

@ui.in_background
def stop_t(sender):
    sys.stdout, sys.stderr = NullifyOutput(), NullifyOutput()
    server.join(3)
    sys.stdout, sys.stderr = original_stdout, original_stderr

ui.load_view('SimpleServer').present('sheet')

rawDescription: Shutting down Python BasicHTTPServer from another thread


rawDescription: Python: raw_unicode_escape doesn't write raw value for "é"


code:
import urllib2
from multiprocessing.dummy import Pool

def generate_urls(): # generate some dummy urls
    for i in range(100):
        yield 'http://example.com?param=%d' % i

def get_url(url):
    try: return url, urllib2.urlopen(url).read(), None
    except EnvironmentError as e:
         return url, None, e

pool = Pool(20) # limit number of concurrent connections
for url, result, error in pool.imap_unordered(get_url, generate_urls()):
    if error is None:
       print result,

rawDescription: Threading in python doesn't happen parallel


code:
def merge(times):
    saved = list(times[0])
    for st, en in sorted([sorted(t) for t in times]):
        if st <= saved[1]:
            saved[1] = max(saved[1], en)
        else:
            yield tuple(saved)
            saved[0] = st
            saved[1] = en
    yield tuple(saved)

data = [
    [(1, 5), (2, 4), (3, 6)],
    [(1, 3), (2, 4), (5, 8)]
    ]

for times in data:
    print list(merge(times))

rawDescription: Merging a list of time-range tuples that have overlapping time-ranges


code:
import xml.etree.cElementTree as ET

s = '''
<Node1>
  <Node11>
    <Node21>
    </Node21>
    <Node22>
    </Node22>
    <Node23>
    </Node23>
  </Node11>
  <Node12>
  </Node12>
  <Node13>
  </Node13>
</Node1>
'''

root = ET.fromstring(s)

print root
print list(root)

rawDescription: Python XML: get direct child nodes

description: Python XML: get direct child nodes


code:
lookup = 'the dog barked'

with open(filename) as myFile:
    for num, line in enumerate(myFile, 1):
        if lookup in line:
            print 'found at line:', num

rawDescription: Get Line Number of certain phrase in file Python


code:
l = [(1,"hi"),(True,False),(3,4)]
for i in l:
    print str(i[0])+str(i[1])

rawDescription: How to convert a tuple to string?

description: Convert a tuple to string


code:
max_length = len(max(words, key=len))
for word in words:
    print "{0:{1}s} 1".format(word, max_length)

rawDescription: python Formatting Code from a list

description: Python Formatting Code from a list


code:
import hashlib

salt = 'F0C020D239062F875C7BD8FB218D8102C9B37656F653E8DF0C655EF2D4A0CB61'.decode('hex')
password = 'pass1'

m = hashlib.sha1()
m.update( salt[::-1] )
m.update( password )

print m.hexdigest()
# output: 4a6eed870e313f68f4d34b73bc5b330b0963b4e5 <- the reversed of the C++ result

rawDescription: Different results in Python and C++ when computing SHA-1 digest


code:
Instrument_Control = __import__("Instrument-Control.audio$pecial")
audiospecial = getattr(Instrument_Control, "audio$pecial")
print audiospecial
# <module 'Instrument-Control.audio$pecial' from 'Instrument-Control/audio$pecial/__init__.py'>
audiospecial.example_func()  # executes example_func() from audio$pecial

rawDescription: How does one import in python if the filename or filepath contains a non-alpha, non-underscore character?

description: Import in python if the filename or filepath contains a non-alpha, non-underscore character


code:
cursor = db.model.find({'time': {'$gte': start, '$lt': end}}).sort('time')

for result in cursor:
    print result['_id']

rawDescription: Pymongo - Cursor Iteration in Script v Shell


code:
import serial

ser = serial.Serial(0)  # open first serial port with 9600,8,N,1
print ser.portstr       # check which port was really used
ser.write('hello')
ser.close()

rawDescription: Writing to the serial port in Vista from Python


code:
import _winreg
import wmi
c = wmi.WMI(computer="10.31.247.8", user="devuser", password="devpass1!",namespace="root/default").StdRegProv

result, imagePath = c.GetStringValue (
hDefKey=_winreg.HKEY_LOCAL_MACHINE,
sSubKeyName="SYSTEM\ControlSet001\Services\MRxDAV",
sValueName="ImagePath"
)
print imagePath

rawDescription: Python WMI _wmireg - retrieving values

description: Python WMI _wmireg - retrieving values


code:
import re

string = """2015-11-27 A1,B3
2015-11-23 A1
2015-11-22 A1,B3,Z6"""

for line in re.split("\n", string):
    date, rest = re.split("\s", line)
    print "Date: " + date + ", Rest: " + rest

    #parts = re.split(",", rest)

rawDescription: Python re to split dates from other data


code:
d = {frozenset((1,2)): "foo"}
print d.get(frozenset((2,1)))

rawDescription: Look up a tuple in a python dictionary matching (x,y) or (y,x)


code:
from sympy.abc import a,b,c,p,q
from sympy import collect, expand
e = p * ( a + b ) + q * ( a + c )

print e
print expand(e)
print collect(expand(e),a)

rawDescription: sympy : expression simplification

description: Sympy : expression simplification


code:
with open('logfile1.txt', 'w') as f1, open('logfile2.txt', 'w') as f2:
    while True:
        volts = adc.readADCDifferential01(256, 8)
        print volts
        sleep(1)
        if volts < 10:
            print >> f1, time(), volts
        else: # volts >= 10
            print >> f2, time(), volts

rawDescription: How to write two separate log files from same python program?

description: Write two separate log files from same python program


code:
import urllib
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
f = urllib.urlopen("http://www.musi-cal.com/cgi-bin/query", params)
print f.read()

rawDescription: Programmatically submitting a form in Python?


code:
firstdict = {"somelist":[]}
seconddict = {"attribute1": "value1", "attribute2": "value2"}
firstdict["somelist"].append(seconddict)
print firstdict["somelist"][0]['attribute1']

rawDescription: How to access attribute within a list of dicts in python?

description: Access attribute within a list of dicts in python


code:
import time
print hex(int(time.mktime(time.strptime('1999-12-31 15:00:00', '%Y-%m-%d %H:%M:%S'))) - time.timezone)

rawDescription: Getting a datetime in this format and converting to 4 byte hex


code:
from instagram.client import InstagramAPI

api = InstagramAPI(client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET')
popular_media = api.media_popular(count=20)
for media in popular_media:
    print media.images['standard_resolution'].url

rawDescription: Instagram and oAuth

description: Instagram and oAuth


code:
from Products.CMFCore.utils import getToolByName

membership = getToolByName(self.context, 'portal_membership')
authenticated_user = membership.getAuthenticatedMember().getProperty('location')
print authenticated_user

rawDescription: get current logged user on Plone

description: Get current logged user on Plone


code:
import subprocess as sp, pandas as pd
# (1) new import
from openpyxl import load_workbook
# (2) new import
from datetime import datetime

ffmpeg = 'C:/FFMPEG/bin/ffmpeg.exe' # on Windows
datafile = r'C:\Users\A_Do\Dropbox\1. Projects\2. Python\TM Creator\tm_creator_test1.xlsx'

# (3) open the file in openpyxl first:
book = load_workbook(datafile)

xl = pd.ExcelFile(datafile,index = False)
df = xl.parse('Sheet1')

def create_tm():
    row_iterator = df.iterrows()
     # take first item from row_iterator
    for i, row in row_iterator:
        infile = row['filename']
        outputfile = row['outputfilename']
        timein = row['timein']
        duration = row['duration']
        decision = row['Create TM?']
        if decision == "Y":
            sp.call(ffmpeg + " -y -i " + infile + " -map 0:0 -map 0:1 -map 0:2 -acodec copy -ss " + str(timein) + " -codec copy -t " + str(duration) + " " + outputfile,shell=True) #this works

        elif decision != decision: #this gets rid of the NaN
            break
        else:
            print "You said you didn't want to make a TM for " + str(infile)

        # (4) Wherever in the code you want to put the timestamp:
        df.loc[i, 'Timestamp'] = str(datetime.now())

    # (5) This saves the sheet back into the original file, without removing
    # any of the old sheets.
    writer = pd.ExcelWriter(datafile)
    writer.book = book
    writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
    df.to_excel(writer)
    writer.save()

create_tm()

rawDescription: How do I timestamp an excel document using Pandas?

description: Timestamp an excel document using Pandas


code:
dirs = collections.defaultdict(set)

for file_path in input:
    file_path = file_path.rjust(8, "0")
    dir, name = file_path[:-3], file_path

    dirs[dir].add(name)

for dir, files in dirs.iteritems():
    for missing_file in files - set(glob.glob("*.tif")):
        print missing_file

rawDescription: Python File System Reader Performance

description: Python File System Reader Performance


code:
import re
filename = 'sliceeverfile3.txt'
pattern  = '\d\d,\d\d,\d\d,\d\d,\d\d,\d\d,\d\d'
new_file = []

# Make sure file gets closed after being iterated
with open(filename, 'r') as f:
   # Read the file contents and generate a list with each line
   lines = f.readlines()

# Iterate each line
for line in lines:

    # Regex applied to each line
    match = re.search(pattern, line)
    if match:
        # Make sure to add \n to display correctly when we write it back
        new_line = match.group() + '\n'
        print new_line
        new_file.append(new_line)

with open(filename, 'w') as f:
     # go to start of file
     f.seek(0)
     # actually write the lines
     f.writelines(new_file)

rawDescription: Python using re module to parse an imported text file


code:
import wx

class APP(wx.Frame):
    def __init__(self,parent,id,title):
        wx.Frame.__init__(self,parent,id,title)
        self.panel=wx.Panel(self)
        self.INPUT = wx.TextCtrl(self.panel,-1,value="")  ############ Here
        self.Bind(wx.EVT_TEXT, self.ONPRESSENTER, self.INPUT)

    def ONPRESSENTER(self,event):
        print self.INPUT.GetValue()

if __name__ == "__main__":
    app = wx.App()
    frame = APP(None,-1,'TextCtrl in a panel - GetValue Test')
    frame.Show(True)
    app.MainLoop()

rawDescription: wxPython - GetValue() and panels

description: WxPython - GetValue() and panels


code:
from bs4 import BeautifulSoup as BS
html = """<li class="li_dataline2">

<b> Expiry date: </b>14/09/2013

</li>"""
soup = BS(html)
print soup.find('li', {'class':'li_dataline2'}).contents[-1].strip()

rawDescription: BeautifulSoup targeting a string between tags


rawDescription: Zipping nested lists in Python

description: Zipping nested lists in Python


code:
db = c.foo
for doc in db.things.find(): print doc

db.command('count', 'things', query={'foo': 'bar'})

rawDescription: Does the PyMongo driver aggregate data

description: Does the PyMongo driver aggregate data


code:
x=[1,3,5,9,2]
alphabet = "abcdefghijklmnopqrstuvwxyz" #the string
r = "" # The string to print out at the end
for i in x:
    r += alphabet[i]
print r

rawDescription: How can I locate position of letters from a list which contains there position?

description: Locate position of letters from a list which contains there position


code:
cur.execute("SELECT status FROM users WHERE id=%s", (clientIDInput, ))
data = cur.fetchone()
if not data:
    print "The ID has not been found in the database"
else:
    status = data[0]
    if status:
        print "This person is already checked in. Checking out now."
        # Update MySQL database and change status from 1 to 0
    else:
        print "This person has not checked in yet. Checking in now."

rawDescription: Python - Multiple SQL queries within code


code:
x = [2,3,5,9,1,0,2,3]

def my_min(sequence):
    """return the minimum element of sequence"""
    low = sequence[0] # need to start with some value
    for i in sequence:
        if i < low:
            low = i
    return low

print my_min(x)

rawDescription: Find the minimum value in a python list

description: Find the minimum value in a python list


code:
thelines = ['hello:3.1 GB', 'world:1.2 MB', 'foo:956.2 KB']

mult = dict(KB=2**10, MB=2**20, GB=2**30)

def getsize(aline):
  fn, size = aline.split(':', 1)
  value, unit = size.split(' ')
  multiplier = mult[unit]
  return float(value) * multiplier

thelines.sort(key=getsize)
print thelines

rawDescription: Order a list of files by size via python


code:
for i in numbers:
    if i % 2 == 0:
        print i
    if i == 980:
        break

rawDescription: Python (loops) with a list

description: Python (loops) with a list


code:
for i in range(1,n+1):
    for j in range(1,n-i+1):
        print' ',
    print'*',
    if 1 < i <= n - 1:
        for k in range(1,2*i - 2):
            print' ',
        print'*',
    elif i == n:
        for k in range(1,2*i - 1):
            print'*',
    print

rawDescription: Draw hollow triangles in Python

description: Draw hollow triangles in Python


code:
#!/usr/bin/evn python
from scapy.all import *
def print_summary(pkt):
    if IP in pkt:
        ip_src=pkt[IP].src
        ip_dst=pkt[IP].dst
    if TCP in pkt:
        tcp_sport=pkt[TCP].sport
        tcp_dport=pkt[TCP].dport

        print " IP src " + str(ip_src) + " TCP sport " + str(tcp_sport)
        print " IP dst " + str(ip_dst) + " TCP dport " + str(tcp_dport)

    # you can filter with something like that
    if ( ( pkt[IP].src == "192.168.0.1") or ( pkt[IP].dst == "192.168.0.1") ):
        print("!")

sniff(filter="ip",prn=print_summary)
# or it possible to filter with filter parameter...!
sniff(filter="ip and host 192.168.0.1",prn=print_summary)

rawDescription: Fetch source address and port number of packet - Scapy script


code:
import json
# This converts from JSON to a python dict
parsed_input = json.loads(input_data)

# Now, all of your static variables are referenceable as keys:
secret = parsed_input['secret']
minutes = parsed_input['minutes']
link = parsed_input['link']

# Plus, you can get your bookmark collection as:
bookmark_collection = parsed_input['bookmark_collection']

# Print a list of names of the bookmark collections...
print bookmark_collection.keys() # Note this contains sublinks, so remove it if needed

# Get the name of the Boarding Pass bookmark:
print bookmark_collection['boarding_pass']['name']

# Print out a list of all bookmark links as:
#  Boarding Pass
#    * 1: http://www.1.com/
#    * 2: http://www.2.com/
#  ...
for bookmark_definition in bookmark_collection.values():
    # Skip sublinks...
    if bookmark_definition['name'] == 'sublinks':
        continue
    print bookmark_definition['name']
    for bookmark in bookmark_definition['bookmarks']:
        print "    * %(name)s: %(link)s" % bookmark

# Get the sublink definition:
sublinks = parsed_input['bookmark_collection']['sublinks']

# .. and print them
print sublinks['name']
for link in sublinks['link']:
    print '  *', link

rawDescription: Parsing muilti dimensional Json array to Python


code:
from bs4 import BeautifulSoup
import requests

url = 'http://alerts.weather.gov/cap/us.php?x=1'

r = requests.get(url)
soup = BeautifulSoup(r.text, 'xml')
entries = soup.find_all('entry')

geocode = {}
k = None
for tag in entries[0].geocode.children:
    if tag.name == 'valueName':
        k = tag.string
    elif tag.name == 'value':
        geocode[k] = tag.string

print 'title: ', entries[0].title.string
print 'cap_geocode: ', str(geocode)
print 'cap_event: ', entries[0].event.string

rawDescription: Python/XML RSS Feedparser - Blank Fields


code:
import csv
with open("pe_ratio.csv", "w") as out_file:
    f = csv.writer(out_file)

    def factorial(n):
        results = 1
        # results are one because that is the minimum number
        while n >= 1:
            results =  results * n
            # results * nth number of n
            n = n - 1
            # n - 1
            # two variables are affected in this program results and n
        return f.writerow([results])  # <---note writerows vs writerow

    print factorial(4)

rawDescription: CSV Python Sequence Error

description: CSV Python Sequence Error


code:
def f(obj):
    for k,v in obj.__dict__.items():
        print k ,v
        if hasattr(v,'__dict__'):
            f(v)

rawDescription: print all python Structure field values

description: Print all python Structure field values


code:
def test_envconfig():
     import inspect
     for frame, filename, line_num, func, source_code, source_index in inspect.stack():
         if 'tests/unittests/capital/' in filename:
             print 'The Test env is activated for %s' % (filename)
     return "user"

rawDescription: How to track the caller details inside callee in python

description: Track the caller details inside callee in python


code:
if __name__ == '__main__':
  with open(r"/tmp/genes.txt","r") as f:
      for line in f.readlines():
          probes_dict = get_probes_from_genes(line.strip())
          expression_values, well_ids, well_coordinates, donor_names =     get_expression_values_from_probe_ids(probes_dict.keys())
          print get_mni_coordinates_from_wells(well_ids)

rawDescription: Creating loop for __main__

description: Creating loop for __main__


code:
for dirName, subdirList, fileList in os.walk(Directory):
    for fname in fileList:
        if fname.endswith('.csv'):
            for line in fileinput.input(os.path.join(dirName, fname), inplace = 1):
                location = line.find(r'GLNext')
                if location > 0:
                    location += len('GLNext')
                    print line.replace(line[:location], ".")
                else:
                    print line

rawDescription: How to remove a specific string common in multiple lines in a CSV file using python script?

description: Remove a specific string common in multiple lines in a CSV file using python script


code:
from collections import defaultdict
def counter(STRING):
  h=defaultdict(int)
  for i in STRING:
    if i in "stn":
       h[i]+=1
  return h
for s in ['description','statements']:
    k=counter(s)
    print k + " for " + s

rawDescription: How many times different letters appear in different words?


code:
from multiprocessing.queues import Queue
import errno

def retry_on_eintr(function, *args, **kw):
    while True:
        try:
            return function(*args, **kw)
        except IOError, e:
            if e.errno == errno.EINTR:
                continue
            else:
                raise

class RetryQueue(Queue):
    """Queue which will retry if interrupted with EINTR."""
    def get(self, block=True, timeout=None):
        return retry_on_eintr(Queue.get, self, block, timeout)

rawDescription: interrupted system call with processing queue

description: Interrupted system call with processing queue


code:
clusters = {}

my_file = open('out.txt', 'r')
for line in my_file:
    columns = line.strip().split('\t')
    name = columns[0]
    species = columns[1]
    if clusters.get(name) is not None:
        if species not in clusters[name]:
            clusters[name].append(species)
    else:
        clusters[name]=[species]

my_file.close()
my_output_file = open('in.txt', 'w')

for each_cluster_key in clusters.keys():
    if len(clusters[each_cluster_key]) < 2:
        clusters.pop(each_cluster_key, None)
    else:
        for each_species in clusters[each_cluster_key]:
            my_output_file.write(each_cluster_key+'\t'+each_species+'\n')

my_output_file.close()

print clusters

rawDescription: Remove dictionary key when the multiple values are the same


code:
from bs4 import BeautifulSoup
import requests

r=requests.get('http://www.virginiaequestrian.com/main.cfm?action=greenpages&GPType=8')
soup=BeautifulSoup(r.content)

tbl = soup.findAll('table')[2]
for tr in tbl.findAll('tr'):
    for td in tr.findAll('td'):
        if td.p:
            print td.p.string

rawDescription: How can I grab the table data for select rows in BeautifulSoup

description: Grab the table data for select rows in BeautifulSoup


code:
print is_func_decl(v.sort().constructor(0))
print is_expr(v.sort().constructor(0))
print is_expr(v.sort().constructor(0)())

rawDescription: retrieving value of an enumerated type in Z3Py

description: Retrieving value of an enumerated type in Z3Py


code:
namespace = dict(foo=5, bar=6)
print eval('foo*bar', namespace)

rawDescription: Evaluating math expression on dictionary variables


code:
r = re.compile('[0-A]')
r.match('0')
print r.match('0')
print r.match('9')
print r.match('A')
print r.match('Z')
print r.match('-')
print r.match(':')

rawDescription: Python RegEx Underlying Character Groups - eg: Can [0-A] be used?


code:
import os

path = "C:\\tmp" #my test path

# See http://stackoverflow.com/q/973473/474189 for other alternatives
dirs = [x[0] for x in os.walk(path) ]

# Print if needed
for d in dirs:
    print "\nThis dir : %s" % (d)

email_text = "\n".join(dirs)

rawDescription: Send for loop output to email in Python

description: Send for loop output to email in Python


code:
from functools import partial
import time
import threading

class aftereffect(object):
    def __init__(self, func):
        self._func = func
        self._aftereffect = lambda instance: None

    def aftereffect(self, func):
        self._aftereffect = func
        return self

    def __get__(self, instance, cls):
        # this is the descriptor protocol, and
        # instance is the actual object

        def delayed_effect(timeout):
            time.sleep(timeout)
            self._aftereffect(instance)

        def caller(*args, **kwargs):
            timeout = kwargs.pop("_timeout", 1.)
            t = threading.Thread(target=partial(delayed_effect, timeout=timeout))
            t.start()
            return self._func(*args, **kwargs)

        return caller.__get__(instance, cls)

class Thing(object):
    @aftereffect
    def something(self):
        print "something", self

    @something.aftereffect
    def something(self):
        print "after_something", self

t = Thing()
t.something()
t.something(_timeout=5)

rawDescription: Creating a property-like solution for complicated and repetitive function calls


code:
font_elements = soup('font', {'size': 3})

if font_elements:
     print font_elements[0].text

rawDescription: Python Web Scrape Index

description: Python Web Scrape Index


code:
import math
import multiprocessing as mp

def pool_init(basePath_):
    global basePath, job_count
    basePath = basePath_
    job_count = 0
    print 'Spawning new process: %d' %os.getpid()

def mpProcessor(basePath, jsonData, num_procs=mp.cpu_count()):
    pool = mp.Pool(processes=num_procs, initializer=pool_init, initargs=(basePath,))
    # could specify a chunksize, but multiprocessing works out the optimal chunksize
    return pool.map(processJSON, jsonData)

# change processJSON to work with single records and
# remove proc and basePath args (as not needed)
def processJSON(record):
    global job_count
    print 'Starting job %d in process: %d' % (job_count, os.getpid())
    valid = False
    idx = 0
    while valid == False:
        jsonObject = json.loads(record[1])['results'][idx]
        if jsonObject['kind'] == 'song':
            valid = True
            break
        else:
            idx += 1
    tunesTrack = Track()
    tunesTrack.setTrackId(jsonObject['trackId'])
    print 'Finished processing job %d with process %d' % (job_count,  os.getpid())
    job_count += 1

rawDescription: Python Apply_async not waiting for other Processes to Finish


code:
res = df.groupby(by=['A','D']).sum()
res.index = res.index.map(lambda x: ' & '.join(map(str, x)))
res.index.name = 'A & D'
res.columns.values[0] = ' & ' + res.columns[0]
print res.to_latex(escape=False)  # the whole point is not to escape the &s

rawDescription: nbconvert multiindex dataframes to latex

description: Nbconvert multiindex dataframes to latex


code:
from selenium import webdriver
from selenium.common.exceptions import TimeoutException

driver = webdriver.Firefox()
driver.set_page_load_timeout(10)
while True:
    try:
        driver.get("https://www.google.com/")
    except TimeoutException:
        print "Timeout, retrying..."
        continue
    else:
        break

rawDescription: Selenium webdriver with python- how to reload page if loading takes too long?


code:
for attr in attrs:
  if ('href', 'http://fls-na.amazon.com') in attr:
    print attr

rawDescription: Find an element in a list of tuples in python


code:
from BeautifulSoup import BeautifulSoup

html = """

        column 1	column 2

value 1	value 2

"""
soup = BeautifulSoup(html)
tables = soup.findChildren('table')
# This will get the first (and only) table. Your page may have more.
my_table = tables[0]
# You can find children with multiple tags by passing a list of strings
rows = my_table.findChildren(['th', 'tr'])
for row in rows:
    cells = row.findChildren('td')
    for cell in cells:
        value = cell.string
        print "The value in this cell is %s" % value

rawDescription: How do you get all the rows from a particular table using BeautifulSoup?

description: Get all the rows from a particular table using BeautifulSoup


code:
rank_from_str = dict(zip("23456789TJQKA",[2,3,4,5,6,7,8,9,10,10,10,10,11]))
print rank_from_str['A']

hand = "TTA"
hand_rank = sum(rank_from_str[card] for card in hand)
if hand_rank > 21: # if our hand is bigger than 21
   for i in range(hand.count("A")): #convert aces'
       hand_rank -= 10 #change 11 to 1 (subtract 10)
       if hand_rank <= 21: break #until we have less than 21
       #or until we run out of aces

print "HAND RANK:",hand_rank

rawDescription: Displaying strings as card values

description: Displaying strings as card values


code:
def distribute2(available, weights):
    distributed_amounts = []
    total_weights = sum(weights)
    for weight in weights:
        weight = float(weight)
        p = weight / total_weights
        distributed_amount = round(p * available)
        distributed_amounts.append(distributed_amount)
        total_weights -= weight
        available -= distributed_amount
    return distributed_amounts
for x in xrange(100):
    d = distribute2(x, (1,2,3))
    if x != sum(d):
        print x, sum(d), d

rawDescription: Distributing integers using weights? How to calculate?


code:
def bub_sort(ol):
    print 'function start'
    s = 0
    for x in range(1, len(ol)):
        print 'in floop'
        if ol[x] > ol[x-1]:
            print 'swap'
            ol[x], ol[x-1] = ol[x-1], ol[x]
            s += 1  # Python has the increment operator.
    if s > 0:
        print 'restart'
        return bub_sort(ol)
    else:
        print 'return'
        return ol

rawDescription: Bubble Sort Not Returning List

description: Bubble Sort Not Returning List


code:
#!/usr/bin/env python
from settings import INSTALLED_APPS
from django.utils.importlib import import_module
import os

app_names = (x for x in INSTALLED_APPS if not x.startswith('django'))
app_paths = (os.path.dirname(os.path.abspath(import_module(x).__file__)) for x in app_names)
print "\n".join(x for x in app_paths if not x.startswith(os.getcwd()))

rawDescription: Get a list of python packages used by a Django Project


code:
from bs4 import BeautifulSoup
import lxml

html_doc = open('bestellingen.html', 'r')
soup = BeautifulSoup(html_doc,'lxml')

orderId = soup.select('.orderId')
customerName = soup.select('.customerName')
orderAmount = soup.select('.orderAmount')

print orderId
print customerName
print orderAmount

rawDescription: Parsing specific information from html source file with BeautifulSoup and saving it to a .csv file


code:
import textwrap
wrapper = textwrap.TextWrapper(width=20)
for line in wrapper.wrap(text):
    print line, len(line)

rawDescription: Split one long string by multiple delimeter in shorter string with max len


code:
from timeit import Timer
from urllib2 import urlopen

def fetch():
    page = urlopen('http://www.google.com')
    return page.info()

timer = Timer(fetch)
print timer.timeit(1)

rawDescription: python page response benchmarking (headers)

description: Python page response benchmarking (headers)


code:
import Xlib.display

screen = Xlib.display.Display().screen()
root_win = screen.root

num_of_fs = 0
for window in root_win.query_tree()._data['children']:
    window_name = window.get_wm_name()
    width = window.get_geometry()._data["width"]
    height = window.get_geometry()._data["height"]

    if width == screen.width_in_pixels and height == screen.height_in_pixels:
        num_of_fs += 1

print num_of_fs

rawDescription: How to tell if a full-screen application is running?

description: Tell if a full-screen application is running


code:
class Class3():

    def printValue(self):
        print self.string1

class Class2(Class3):

    def e(self):
        self.value4 = self.value3 - self.value2
        print self.value4
        self.string1 = 'Hello'
        self.printValue()

class Class1(Class2):

    def __init__(self):
        self.value1 = 10
        self.value2 = 20

    def add(self):
        self.value3 = self.value1 + self.value2

if __name__ == '__main__':
    instance1 = Class1()
    instance1.add()
    instance1.e() # will print "10" and "Hello"
    print instance1.value3 # will print "30"

rawDescription: Class Inheritance through Multiple Classes


code:
def sum3():
    print "Please enter three numbers:"
    a = input()
    b = input()
    c = input()
    return sum((a,b,c)) # a+b+c

print sum3() # asks for input then prints result.

rawDescription: how to ask for user input in a function. Python related

description: Ask for user input in a function. Python related


code:
# classes should have capitalized names ...
class a(str):
    def b(self,*x,**y):
        print 'debugging: ', self, x, y
        print str.decode(self, *x,**y)

if __name__ == '__main__':
    b=a('aaa')
    b.b('utf-8')

    b=a()
    b.b('utf-8')

# => output

# debugging:  aaa ('utf-8',) {}
# aaa
# debugging:   ('utf-8',) {}
#

rawDescription: Why does this Python code print nothing?

description: Why does this Python code print nothing


code:
for detail in response.xpath("//div[@class='detail-all-text']/b"):
    name = detail.xpath("text()").extract()[0]
    value = detail.xpath("following-sibling::text()")[0]

    print name, value

rawDescription: Need help scraping items from a list with Scrapy using ancestor


code:
import re

def _callback(matches):
    id = matches.group(1)
    try:
        return unichr(int(id))
    except:
        return id

def decode_unicode_references(data):
    return re.sub("&#(\d+)(;|(?=\s))", _callback, data)

data = "U.S. Adviser’s Blunt Memo on Iraq: Time ‘to Go Home’"
print decode_unicode_references(data)

rawDescription: Decoding HTML entities with Python

description: Decoding HTML entities with Python


code:
import inspect
inspect.getargspec(inspect.getargspec)
print inspect.getsource(inspect.getsource)

rawDescription: In python, how to check the function form of an imported module method


code:
from collections import defaultdict
names = defaultdict(list)
with open('f.txt') as f:
   lines = [l.split() for l in f.readlines() if l.strip()]
   for l in lines:
     names[l[0]].append([l[1],l[2]])
for i in names.iteritems():
   print i

rawDescription: need help in anayzing a text file using python

description: Need help in anayzing a text file using python


code:
'''

JP

Attempt to get multiple updating of matplotlibs working.
Uses WX to create an 'almost' gui with a mpl in the middle of it.
Data can be queued to this object - or you can directly plot to it.

Probably will have some limitations atm
- only really thinking about 2d plots for now -
but presumably can work around this for other implimentations.
- the working code seems to need to be put into another thread.
Tried to put the wx mainloop into another thread,
but it seemed unhappy. :(

Classes of Interest :
    GraphData - A silly class that holds data to be plotted.
    PlotFigure - Class of wx frame type.
        Holds a mpl figure in it + queue to queue data to.
        The frame will plot the data when it refreshes it's canvas

    ThreadSimulation - This is not to do with the plotting
                        it is a test program.

Modified version of:

Copyright (C) 2003-2005 Jeremy O'Donoghue and others

License: This work is licensed under the PSF. A copy should be included
with this source code, and is also available at
http://www.python.org/psf/license.html

'''
import threading
import collections
import time

import numpy as np

import matplotlib
matplotlib.use('WXAgg')

from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.backends.backend_wx import NavigationToolbar2Wx

from matplotlib.figure import Figure

import wx

class GraphData(object):
    '''
        A silly class that holds data to be plotted.
    '''
    def __init__(self, xdatainit, ydatainit):

        self.xdata = xdatainit
        self.ydata = ydatainit

class PlotFigure(wx.Frame):

    def __init__(self ):
        '''
            Initialises the frame.
        '''
        wx.Frame.__init__(self, None, -1, "Test embedded wxFigure")

        self.timerid = wx.NewId()

        self.fig = Figure((5,4), 75)
        self.canvas = FigureCanvasWxAgg(self, -1, self.fig)
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()

        # On Windows, default frame size behaviour is incorrect
        # you don't need this under Linux
        tw, th = self.toolbar.GetSizeTuple()
        fw, fh = self.canvas.GetSizeTuple()
        self.toolbar.SetSize(wx.Size(fw, th))

        # Now put all into a sizer
        sizer = wx.BoxSizer(wx.VERTICAL)
        # This way of adding to sizer allows resizing
        sizer.Add(self.canvas, 1, wx.LEFT|wx.TOP|wx.GROW)
        # Best to allow the toolbar to resize!
        sizer.Add(self.toolbar, 0, wx.GROW)
        self.SetSizer(sizer)
        self.Fit()
        wx.EVT_TIMER(self, self.timerid, self.onTimer)

        self.dataqueue = collections.deque()

        # Add an axes and a line to the figure.
        self.axes = self.fig.add_subplot(111)
        self.line, = self.axes.plot([],[])

    def GetToolBar(self):
        '''
            returns default toolbar.
        '''
        return self.toolbar

    def onTimer(self, evt):
        '''
            Every timer period this is called.

            Want to redraw the canvas.
        '''
        #print "onTimer"
        if len(self.dataqueue) > 0 :
            data = self.dataqueue.pop()

            x = data.xdata
            y = data.ydata

            xmax = max(x)
            xmin = min(x)

            ymin = round(min(y), 0) - 1
            ymax = round(max(y), 0) + 1

            self.axes.set_xbound(lower=xmin, upper=xmax)
            self.axes.set_ybound(lower=ymin, upper=ymax)

            self.line.set_xdata(x)
            self.line.set_ydata(y)

        # Redraws the canvas - does this even if the data isn't updated...
        self.canvas.draw()

    def onEraseBackground(self, evt):
        '''
        this is supposed to prevent redraw flicker on some X servers...
        '''
        pass

class ThreadSimulation(threading.Thread):
    '''
    Simulation Thread - produces data to be displayed in the other thread.
    '''

    def __init__(self,  nsimloops, datastep, pltframe, slowloop = 0):
        threading.Thread.__init__(self)

        self.nsimloops = nsimloops
        self.datastep = datastep
        self.pltframe = pltframe
        self.slowloop=slowloop

    def run(self):
        '''
        This is the simulation function.
        '''
        nsimloops = self.nsimloops
        datastep = self.datastep
        pltframe = self.pltframe

        print 'Sim Thread: Starting.'
        tstart = time.time()               # for profiling

        # Define Data to share between threads.
        x  = np.arange(0,2*np.pi,datastep)            # x-array
        y  = np.sin(x )

        # Queues up the data and removes previous versions.
        pltframe.dataqueue.append(GraphData(x,y))
        for i in range(len(pltframe.dataqueue)-1):
            pltframe.dataqueue.popleft()
        pltframe.dataqueue

        for i in np.arange(1, nsimloops):

            x = x + datastep
            y = np.sin(x)

            # Queues up the data and removes previous versions.
            pltframe.dataqueue.append(GraphData(x,y))
            for i in range(len(pltframe.dataqueue)-1):
                pltframe.dataqueue.popleft()
            #pltframe.dataqueue

            if self.slowloop > 0 :
                time.sleep(self.slowloop)

        tstop= time.time()
        print 'Sim Thread: Complete.'
        print 'Av Loop Time:' , (tstop-tstart)/ nsimloops

if __name__ == '__main__':

    # Create the wx application.
    app = wx.PySimpleApp()

    # Create a frame with a plot inside it.
    pltframe = PlotFigure()
    pltframe1 = PlotFigure()

    # Initialise the timer - wxPython requires this to be connected to
    # the receiving event handler

    t = wx.Timer(pltframe, pltframe.timerid)
    t.Start(100)

    pltframe.Show()
    pltframe1.Show()

    npoints = 100
    nsimloops = 20000
    datastep = 2 * np.pi/ npoints
    slowloop = .1

    #Define and start application thread
    thrd = ThreadSimulation(nsimloops, datastep, pltframe,slowloop)
    thrd.setDaemon(True)
    thrd.start()

    pltframe1.axes.plot(np.random.rand(10),np.random.rand(10))

    app.MainLoop()

rawDescription: Python Matplotlib interactive plotting - freezes after a few frames


code:
import alpha

alpha.set_bravo()

from alpha import bravo

print "Value of bravo is: %s" % bravo
print "Value of alpha.bravo is: %s" % alpha.bravo

rawDescription: Why does from ... import appear to bind to value at import time in Python?


code:
d = [{'type_id': 6, 'type_name': 'Type 1'}, {'type_id': 12, 'type_name': 'Type 2'}]
print [{'type':x['type_id'],'name':x['type_name']} for x in d]

rawDescription: Remapping key names in a list of dictionaries


code:
import itertools

def check_element(checkpair):
    for pair in checklist:
        if  checkpair != pair and (pair[0] in range(checkpair[0],checkpair[1]) or pair[1] in range(checkpair[0],checkpair[1]) ):
            return bool

checklist = [(2,72), (20,73),(22,70), (25,30)]
print checklist
filtered = itertools.ifilter(check_element, checklist) #returns generator
checklist = list(filtered)                             #exahust iterator to create list
print checklist
_filtered = itertools.ifilter(check_element, checklist)
checklist = list(_filtered)
print checklist

rawDescription: Find non crossing pairs in array and remove iteratively in Python until no pairs are left


code:
import requests
import json

# initial message
message = "if i can't let it go out of my mind"

# split into list
split_message = message.split()

def decrementList(words):
    for w in [ words ] + [ words[:-x] for x in range(1, len(words)) ]:
        url = 'http://ws.spotify.com/search/1/track.json?q='
        request = requests.get(url + "%20".join(w))

        json_dict = json.loads(request.content)
        num_results = json_dict['info']['num_results']

        if num_results > 0:
            num_removed = len(words) - len(w)

            track_title = ' '.join(w)

            for track in json_dict["tracks"]:
                if track["name"].lower().startswith(track_title.lower()):
                    yield num_removed, track, track["name"], w

def quote(s):
   return '"' + ('%r' % ("'"+s.encode('utf-8')))[2:]

for num_words_removed, track, track_name, w in decrementList(split_message):
   print '%2d %s by %s (track %d on %s from %s)' % (
     num_words_removed,
     quote(track_name),
     quote(track['artists'][0]['name']),
     int(track['track-number']),
     quote(track['album']['name']),
     track['album']['released'])

rawDescription: Returning values with an else statement

description: Returning values with an else statement


rawDescription: Indexing a position of value change

description: Indexing a position of value change


code:
#!/usr/bin/env python

import urllib
import re

def main():
    url = ('http://www.metoffice.gov.uk/public/weather/forecast/gcptz5sys')

    htmlfile = urllib.urlopen(url)

    htmltext = htmlfile.read()

    htmltext = str(htmltext).replace('\n', '')
    htmltext = str(htmltext).replace('\t', '')
    htmltext = str(htmltext).replace(' ', '')

    pattern = re.compile('<spantitle="Maximumdaytimetemperature"data-c="7"data-f="45">(?P<temperature>.+?)°C')

    for match in pattern.finditer(htmltext):
        print match.group('temperature')

if __name__ == "__main__":
    main()

rawDescription: WEB SCRAPING: Regex is not returning anything? What am I doing wrong?


code:
import requests
from bs4 import BeautifulSoup

URL="http://www11.davidsonsinc.com/Login/Login.aspx"
headers={"User-Agent":"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36"}

username="username"
password="password"

s=requests.Session()
s.headers.update(headers)
r=s.get(URL)
soup=BeautifulSoup(r.content)

VIEWSTATE=soup.find(id="__VIEWSTATE")['value']
VIEWSTATEGENERATOR=soup.find(id="__VIEWSTATEGENERATOR")['value']
EVENTVALIDATION=soup.find(id="__EVENTVALIDATION")['value']

login_data={"__VIEWSTATE":VIEWSTATE,
"__VIEWSTATEGENERATOR":VIEWSTATEGENERATOR,
"__EVENTVALIDATION":EVENTVALIDATION,
"ctl00$ContentPlaceHolderNavPane$LeftSection$UserLogin$UserName":username,
"ctl00$ContentPlaceHolderNavPane$LeftSection$UserLogin$Password":password,
"ctl00$ContentPlaceHolderNavPane$LeftSection$UserLogin$LoginButton":"Log In"}

r=s.post(URL, data=login_data)
print r.url

rawDescription: Unable to log in to ASP.NET website with requests module of Python


code:
initial_input = [("This doesn't matter", 0),("Gimme 4", 0),("Maybe 8", 0),("Ignore me", 1)]

def how_many(mystring):
    return int(mystring[-1])

def display(yourlist):
    for element in yourlist:
        print element

list_of_lists = [[] for i in range(len(initial_input)-1)]
list_of_lists[0] = [list(initial_input)]

for i in range(1, len(initial_input)):
    for currlist in list_of_lists[i-1]:
        element = currlist[i]
        if element[1] == 0:
            recursions = how_many(element[0])
            additems = [currlist[:i] + [(element[0], tick)] + currlist[i+1:] for tick in range(1, recursions)]
            list_of_lists[i].extend(additems)

for i in range(len(initial_input)-1):
    print "\n"
    display(list_of_lists[i])

rawDescription: Generate range of lists with the same number of tuples and index from list of tuples


code:
with open( "file1.xlsx", "r" ) as ins1, open( "file2.xlsx", "r" ) as ins2, \
        open("output.xlsx",'wb') as resultfile :
    for line in ins1:
        line = line.rstrip() + " " + next(ins2)
        print line.rstrip()
        resultfile.write(line)

rawDescription: Python Combine 2 XLSX files

description: Python Combine 2 XLSX files


code:
list1= [{'outside_key1': [ { 'key1': 'one', 'key2': 'xyz','key3':'three'}]} ,
        {'outside_key2': [ { 'key1': 'one', 'key2': 'abc','key3':'three'}]}]
sort_on = "key2"
decorated = [(dict_.values()[0][0][sort_on], dict_) for dict_ in list1]
decorated.sort()
result = [dict_ for (key, dict_) in decorated]
print result

rawDescription: Accessing list of dictionaries in python and sort it using value (Nested dictionary)


code:
import requests
r = requests.get("http://www.deanclatworthy.com/imdb/?q=The+Green+Mile")
import dict2xml
xml = dict2xml.dict2xml(r.json)
print xml

rawDescription: I want to fetch json data from a given url And that json data i have to convert into xml form


rawDescription: Python split string ignoring \"

description: Python split string ignoring \"


code:
Data = np.zeros(100,dtype=[('time', np.float), ('y',np.float)])
Data['y'] = np.random.uniform(size=100)
Data['time'] = np.random.uniform(size=100)
print Data[ (Data['time'] > 0.6) & (Data['time'] < 0.7) ]

rawDescription: Mask numpy array with a range of values

description: Mask numpy array with a range of values


code:
matrix = [[1,0,1],[1,0,1],[1,0,1]]
print '\t' + '\t'.join('col{}'.format(i) for i in xrange(len(matrix[0])))
for i,row in enumerate(matrix):
    print 'row{}\t'.format(i) + '\t'.join(str(x) for x in row)

rawDescription: Printing row of a list

description: Printing row of a list


code:
def function(a, b=0): print a, b

args = [[1, 1], [1, 2], [1]]
for arg in args: function(*arg)

rawDescription: Looping through a function with two arguments


code:
movieTit = []
movieLink = []

for title in soup.findAll("div", {"class" : "title"}):
    movieTit.append(title.getText())
for a in soup.findAll('a'):
    if 'ploaded' in a.getText():
        movieLink.append(a['href'])

for i in range(0,len(movieTit)/2,2):
    print movieTit[i]
    print movieTit[i+1]
    print movieLink[i]
    print movieLink[i+1]

rawDescription: Extract Title+links from homepage

description: Extract Title+links from homepage


code:
class A1(object):
    pass

class A1Child(A1):
    pass

class A2(object):
    pass

class A2Child(A2):
    pass

class B(object):

    a1_instance = None
    a2_instance = None

    def __init__(self):
        self.a1_instance = A1()
        self.a2_instance = A2()

class BChild(B):

    def __init__(self):
        self.a1_instance = A1Child()
        self.a2_instance = A2Child()

b_instance = B()

print b_instance.a1_instance
print b_instance.a2_instance

bchild_instance = BChild()

print bchild_instance.a1_instance
print bchild_instance.a2_instance

rawDescription: Can inherited class change type of elements in base class


code:
first = 0b01010101
second = 0b11110000
res = (first<<4) | (second>>4)
print bin(res)

rawDescription: How to concatenate bits in Python

description: Concatenate bits in Python


code:
import MA
a = MA.array([1, 2, None], mask = [0, 0, 1])
print "average =", MA.average(a)

rawDescription: How to use numpy with 'None' value in Python?

description: Use numpy with 'None' value in Python


code:
from ast import literal_eval
s = "text: u'\u0644'"
unicode_part = s.split(':')[-1].strip()
unicode_part
unicode_string = literal_eval(unicode_part)
unicode_string
print unicode_string

rawDescription: How to extract a unicode string from a string

description: Extract a unicode string from a string


code:
from itertools import product

def worker1(a, b, c):
    return a + b + c

def worker2(d, e, f):
    return d * e * f

def search(model, *params):
    res = []

    # Loop over one of the parameters and repeatedly append to res
    for current_params in product(*params):
        if model == 1:
            res.append(worker1(*current_params))
        elif model == 2:
            res.append(worker2(*current_params))

    return res

print search(1, [1,2,3,4], [2], [3])

# more complicated combinations are possible:
print search(1, [1,2,3,4], [2,7,9], [3,13,23,43])

rawDescription: Grid search function in Python

description: Grid search function in Python


code:
def approximate_random_effects(data, labels, group):

    correlation_per_donor = {}
    for donor_id in set(data[group]):
        correlation_per_donor[donor_id], _, _, _, _ = linregress(list(data[labels[0]][data[group] == donor_id]),
                                                       list(data[labels[1]][data[group] == donor_id]))
    average_slope = np.array(correlation_per_donor.values()).mean()
    t, p_val = ttest_1samp(correlation_per_donor.values(), 0)
    print "Averaged slope across donors = %g (t=%g, p=%g)"%(average_slope, t, p_val)
    with PdfPages('poopyheadjoe04.pdf') as pdf:
        fig = plt.figure()
        sns.violinplot([correlation_per_donor.values()], inner="points", names=["donors"])
        plt.ylabel("Linear regression slopes between %s and %s"%(labels[0],labels[1]))
        plt.axhline(0, color="red")
        pdf.savefig(fig) ## Saving first figure

        fig = plt.figure()
        sns.lmplot(labels[0], labels[1], data, hue=group, col=group, col_wrap=3)
        pdf.savefig(fig) ## Saving second figure

    return average_slope, t, p_val

rawDescription: Can't save all matlibplots to pdf - missing some graphs (IPython)


code:
content = v_file.read()
for line in content.split('\n'):
    print line
    ## ... or whatever. Should return those numbers

rawDescription: Automatic conversion from file to string after entering in a for loop?


code:
import fileinput
for linenum,line in enumerate( fileinput.FileInput("file",inplace=1) ):
  if linenum==0 :
    print "new line"
    print line.rstrip()
  else:
    print line.rstrip()

rawDescription: How to insert a new line before the first line in a file using python?

description: Insert a new line before the first line in a file using python


code:
class Parent(object):
    x = None  # default value
    def __init__(self):
        print self.x

class someChild(Parent):
    x = 10
    def __init__(self):
        Parent.__init__(self)

class otherChild(Parent):
    x = 20
    def __init__(self):
        Parent.__init__(self)

a = someChild()
# output: 10
b = otherChild()
# output: 20

rawDescription: How to refer to a child class from a parent method?

description: Refer to a child class from a parent method


code:
from spyne.model.complex import ComplexModel
from spyne.model.primitive import Integer

class B(ComplexModel):
    c = Integer

class A(ComplexModel):
    a = Integer
    b = B

from spyne.util.dictdoc import get_object_as_dict
print get_object_as_dict(A(a=4, b=B(c=5)), A)
# prints {'a': 4, 'b': {'c': 5}}

get_object_as_dict(A(a=4, b=B(c=5)), A, ignore_wrappers=False)
# prints {'A': {'a': 4, 'b': {'B': {'c': 5}}}}

rawDescription: From Spyne to Suds

description: From Spyne to Suds


code:
import theano
import theano.tensor as T
import numpy as np

x = T.fmatrix()
y = T.fmatrix()
a = np.asarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=theano.config.floatX)
b = np.asarray([[11, 12, 13], [14, 15, 16], [17, 18, 19]], dtype=theano.config.floatX)
z = T.concatenate([x, y], axis=1)
t = theano.function([x, y], z)
print t(a, b)

rawDescription: column_stack equivalent in Theano

description: Column_stack equivalent in Theano


code:
import subprocess

# ps -ux | grep 1842 (Assuming 1842 is the process id. replace with process id you get)

p1 = subprocess.Popen(["ps", "-ux"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["grep", "1842"], stdin=p1.stdout, stdout=subprocess.PIPE)
p1.stdout.close()  # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
print output

rawDescription: How can I read the memory of a process in python in linux?

description: Read the memory of a process in python in linux


code:
def override_setup(exp, args):
    opts = vars(args)

    for param in ['param1', 'param2']:
        if opts[param] is None:
            continue

        try:
            setattr(exp, param, opts[param])
        except Exception as e:
            print e

rawDescription: How to update pyxb tree-like object in a loop?

description: Update pyxb tree-like object in a loop


code:
import ntpath
filepath = r"c:\ttemp\FILEPA~1.EXE"
print ntpath.basename(filepath)
print ntpath.splitdrive(filepath)

rawDescription: Os.path : can you explain this behavior?

description: Os.path : can you explain this behavior


code:
def transposer(n):
    m = copy.copy(n)
    tm = []
    maxi = 0
    for i in range(0, len(m)):
        maxi = max(maxi, len(m[i]))
        print i, maxi
    for z in range(0, maxi):
        row = []
        for j in range(0, len(m)):
            try:
                row.append(m[j].pop(0))
            except:
                pass
        tm.append(row)
    return(tm)

rawDescription: Custom transposing a list messes up original variable in Python


code:
for vector in matrix:
    print vector

rawDescription: Numpy iterating over 3d vector array

description: Numpy iterating over 3d vector array


code:
dict12 = defaultdict(lambda:defaultdict(list))
for k,v in dict1.items():
    for k1,v1 in v.items():
        dict12[k][k1] = v1
for k,v in dict2.items():
    for k2,v2 in v.items():
        dict12[k][k2] += v2
for k,v in dict12.items():
    for k12,v12 in v.items():
        print "dict12[%r][%r] = %r" % (k,k12,v12)

rawDescription: Merging nested defaultdicts

description: Merging nested defaultdicts


code:
import os

L = ["a", "b", "c"]

for item in L:
    pid = os.fork()
    if pid == 0: break
    else: print "Forked:", pid

if pid != 0: print "Main Execution, Ends"
else: print "Execution:", item

rawDescription: Parallelize a loop in python 2.4

description: Parallelize a loop in python 2.4


code:
a="IGADKYFHARGNYDAA"
b="KGADKYFHARGNYEAA"

u=zip(a,b)
x = 0               # not 1
for i,j in u:       # you don't need a dict here
    print i,j,
    if i != j:      # they differ iff they are not equal to each other
        x = x + 1
        print "  neq"
    else:
        print " eq"
print x

rawDescription: Python Differentiate mistake

description: Python Differentiate mistake


code:
from IPython.testing.globalipapp import get_ipython
from IPython.utils.io import capture_output
ip = get_ipython()

def run_cell(cmd):
    with capture_output() as io:
        res = ip.run_cell(content)
        print 'suc', res.success
        print 'res', res.result
    res_out = io.stdout
    print 'res out', res_out

content = "print (111+222)"
run_cell(content)
content = "alsdkjflajksf"
run_cell(content)

rawDescription: Executing Python Code in IPython Kernel

description: Executing Python Code in IPython Kernel


code: print '{:.2f}'.format(result) # print the float as a string to the second place value

rawDescription: How to print out an answer in decimal using python?

description: Print out an answer in decimal using python


code:
getcontext().prec = 8
print Decimal(7000)/Decimal(9)
getcontext().prec = 4
print Decimal(7000)/Decimal(9)
getcontext().prec = 2
print Decimal(7000)/Decimal(9)

rawDescription: Why Python getcontext().prec = 4 sometimes gives 3 decimals instead of 4?


code:
import re

tests = [
    # Test data in original question.
    ( '',                '""'                ),
    ( 'a',               '"a"'               ),
    ( '"a"',             '"a"'               ), # No change.
    ( '""a" b"',         '""a" b"'           ), # No change.
    ( '"a" b',           '""a" b"'           ),
    ( '"a" "b"',         '""a" "b""'         ),
    ( 'a "b" c',         '"a "b" c"'         ),

    # Test data in latest edits.
    ( 'type',            '"type"'         ),    # Quote these.
    ( '"type" /?',       '""type" /?"'    ),
    ( '"type" "/?"',     '""type" "/?""'  ),
    ( 'type "a a" b',    '"type "a a" b"' ),
    ( 'type "" b',       '"type "" b"'    ),
    ( '"type"',          '"type"'         ),    # Don't quote.
    ( '""type" /?"',     '""type" /?"'    ),

    # Some more tests.
    ( '"a b" "c d"',     '""a b" "c d""'     ),
    ( '" a " foo " b "', '"" a " foo " b ""' ),
]

Q = '"'
re_quoted_items = re.compile(r'" \s* [^"\s] [^"]* \"', re.VERBOSE)

for orig, expected in tests:
    # The orig string w/o the internally quoted items.
    woqi = re_quoted_items.sub('', orig)

    if len(orig) == 0:
        orig_quoted = Q + orig + Q
    elif len(woqi) > 0 and not (woqi[0] == Q and woqi[-1] == Q):
        orig_quoted = Q + orig + Q
    else:
        orig_quoted = orig

    print orig_quoted == expected

rawDescription: How to properly add quotes to a string using python?

description: Properly add quotes to a string using python


code:
class MyCounter(threading.Thread):
  def __init__(self, *args, **kwargs):
    super(MyCounter, self).__init__()
    self.count = 0
    self._running = True

  def run(self):
    while self._running:
      self.count += 1

  def quit(self):
    self._running = False

C = MyCounter()
C.start()

while 1:
    try:
        command = raw_input('Command: ')
        if command == 'quit':
            C.quit()
            sys.exit()
        elif command == 'status':
            print(time.ctime())
            print(C.count + '\n')
        else:
            print('unknown command. [quit] or [satus]')

    except KeyboardInterrupt:
        print "\nKeybord interrupt, exiting gracefully anyway."
        sys.exit()

rawDescription: Return a value from a thread function

description: Return a value from a thread function


code:
import math, random
name1 = ""
name2 = ""
strength1 = 0
strength2 = 0
skill1 = 0
skill2 = 0

def Character1():
    global strength1, skill1, name1
    name1 = raw_input("Please enter a name for the first character : ")
    strength1 = math.floor(random.randint(1,12)/random.randint(1,4))+10
    skill1 = math.floor(random.randint(1,12)/random.randint(1,4))+10

def Character2():
    global strength2, skill2, name2
    name2 = raw_input("Please enter a name for the second character : ")
    strength2 = math.floor(random.randint(1,12)/random.randint(1,4))+10
    skill2 = math.floor(random.randint(1,12)/random.randint(1,4))+10

def printStats():
    print "The first character is called " + name1 + " and has a skill level of " + str(skill1) + " and a strength level of " + str(strength1)
    print "The first character is called " + name2 + " and has a skill level of " + str(skill2) + " and a strength level of " + str(strength2)

Character1()
Character2()
printStats()

rawDescription: What is wrong with this python program? It hangs after asking for the first characters name


code:
from networkx import Graph
from networkx.algorithms.components.connected import connected_components

# see aliases as the edges between nodes in a graph
aliases = [('A', 'B'), ('B', 'C'), ('D','E')]

g = Graph( aliases )

# connected components are alias groups
print connected_components(g) # [['A', 'C', 'B'], ['E', 'D']]

rawDescription: Is there an elegant way to keep track of sets of connected items in Python?


code:
import getpass
import sys
import telnetlib

HOST = "localhost"
user = raw_input("Enter your remote account: ")
password = getpass.getpass()

tn = telnetlib.Telnet(HOST)

tn.read_until("login: ")
tn.write(user + "\n")
if password:
    tn.read_until("Password: ")
    tn.write(password + "\n")

tn.write("ls\n")
tn.write("exit\n")

print tn.read_all()

rawDescription: Telnet automation / scripting

description: Telnet automation / scripting


code:
pattern1 = pattern1.replace("%midinote", r"(?P<midinote>\d+)").replace("%velocity", r"(?P<velocity>\d+)").replace("%notename", r"(?P<notename>[A-Ga-g]#?[0-9])")
for fname in filelist1:
    m = re.match(pattern1, fname)
    if m:
        info = m.groupdict()
        midinote = int(info.get('midinote',0))
        velocity = int(info.get('velocity',0))
        notename = info.get('notename', 'c')
        notenametomidi = NOTES.index(notename[:-1].lower()) + (int(notename[-1])+2) * 12
        print fname, midinote, velocity, notename, notenametomidi

rawDescription: Regex with a variable number of match groups


rawDescription: python / numpy - group matrix elements and build dictionary

description: Python / numpy - group matrix elements and build dictionary


code:
class create_positional_index():
    def __init__(self, lst):
        self.lst = lst
    def __getitem__(self, elm):
        return [[doc_id] + [pos for pos, key  in enumerate(sub_lst) if key==elm] for doc_id, sub_lst in enumerate(self.lst) if elm in sub_lst]

index = create_positional_index([['a', 'b', 'a'], ['a', 'c']])
print index['a']
print index['b']
print index['c']

def create_positional_index2(lst, elm):
    return [[doc_id] + [pos for pos, key  in enumerate(sub_lst) if key==elm] for doc_id, sub_lst in enumerate(lst) if elm in sub_lst]

print create_positional_index2([['a', 'b', 'a'], ['a', 'c']], 'a')
print create_positional_index2([['a', 'b', 'a'], ['a', 'c']], 'b')
print create_positional_index2([['a', 'b', 'a'], ['a', 'c']], 'c')

rawDescription: Positional index of list elements using Python


code:
for radioButton in self.findChildren(QtGui.QRadioButton):
    if radioButton.isChecked():
        radioButtonText = radioButton.text()
        print "Radio Button Selected: ", radioButtonText
        if radioButtonText == "example":
            example(args)

rawDescription: pyqt4 + radiobutton

description: Pyqt4 + radiobutton


code:
def counts(xs):
    d = {}
    for item in xs:
        d[item] = xs.count(item)
    return d

if __name__== "__main__":
   print counts([1,1,1,2,3,3,3,3,5])
   print counts("abracadabra")

rawDescription: Defining a function with counts(xs)

description: Defining a function with counts(xs)


rawDescription: Delete rows from numpy array depending on a condition on a single cell


rawDescription: python - extracting tags and attributes from HTML - the hard way

description: Python - extracting tags and attributes from HTML - the hard way


code:
from datetime import datetime
a = datetime.fromtimestamp(1317365200)
print a

rawDescription: Time and date on the basis of seconds elapsed since 1970 year


code:
class USBclient(Protocol):
    def connectionMade(self):
        global serServ
        serServ = self
        print 'Arduino device: ', serServ, ' is connected.'

    def cmdReceived(self, cmd):
        serServ.transport.write(cmd)
        print cmd, ' - sent to Arduino.'
        pass

    def dataReceived(self,data):
        print 'USBclient.dataReceived called with:'
        print str(data)

rawDescription: Twisted Python script on Raspberry Pi (Debian) to communicate with Arduino via USB


code:
for line in p.stdout:
    if "Number of" in line:
        print line

rawDescription: How to print part of output from a subprocess

description: Print part of output from a subprocess


code:
import requests
import bs4

proxy = {"http": "115.227.195.213"}
response = requests.get('http://www.whatsmyip.de/', proxies=proxy)
soup = bs4.BeautifulSoup(response.text)

print soup.h3.text

rawDescription: Requests Proxy not Working

description: Requests Proxy not Working


code:
import re
yourString = "JAIDK392**8'^+%&7JDJ0204İŞÇéS29487"
numberOnlyString = re.sub('[^0-9]', '', yourString)
print numberOnlyString

rawDescription: Remove Everything from a string .. Only Leave Numbers in it


code:
import os
print os.environ["REMOTE_USER"]

rawDescription: How to get the authenticated user name under apache while in python code?

description: Get the authenticated user name under apache while in python code


code:
import os
import subprocess
import time
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/your-pid-name.pid'
        self.pidfile_timeout = 5
    def run(self):

        try:
            while True:

                ### PUT YOUR SCRIPT HERE ###

                time.sleep(300)

        except Exception, e:
            raise

app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

rawDescription: How can I run my python script in the background on a schedule?

description: Run my python script in the background on a schedule


code:
import functools
def foo(number):
    print number

bar = functools.partial(foo, 1)
bar()

rawDescription: How to pass predefined arguments when storing a function

description: Pass predefined arguments when storing a function


code:
import random

index = random.randint(0, len(yourstring)-1)
yourstring = yourstring[:index] + yourstring[index+1:]

print yourstring[index]

rawDescription: Remove one char from a string

description: Remove one char from a string


code:
import os
import heapq

def iterfiles(root):
    for base, dirs, files in os.walk(root):
        for filename in files:
            fullname = os.path.join(base, filename)
            yield os.stat(fullname).st_ctime, fullname

print heapq.nlargest(10, iterfiles('some path here'))

rawDescription: Use Python to Optimally find Top 10 recently created files


code:
if __name__ == '__main__':
    text = str(raw_input("Enter text to word-wrap: "))
    lineLength = int(raw_input("Enter number of characters per line: "))
    print
    print insertNewlines(text, lineLength)
    raw_input()

rawDescription: How to prevent command window from closing when a program finishes executing

description: Prevent command window from closing when a program finishes executing


rawDescription: How to: Compare dictionaries within lists


code:
class Employee:

    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "Name: {0}, age: {1}".format(self.name, self.age)

t = Employee("uday", 25)
print t

rawDescription: TypeError: this constructor takes no arguments in python


code:
#!/usr/bin/python

"""myjson.py: Command-line tool to validate and pretty-print JSON

Usage::
     1)     $ echo '{"json":"obj"}' | python myjson.py
        {
            "json": "obj"
        }
     2)     $ echo '{ 1.2:3.4}' | python myjson.py
        Expecting property name enclosed in double quotes: line 1 column 2 (char 2)

     3) printing a file with multiple lines where each line is a JSON message:
            e.g. msgs.json:
                    [1,,{"6":7,"4":5}]
                    [2,{"6":7,"4":5}]
            python myjson.py msgs.json
                    [
                        1,
                        {
                            "4": 5,
                            "6": 7
                        }
                    ]
                    [
                        2,
                        {
                            "4": 5,
                            "6": 7
                        }
                    ]
"""
import sys
import json
def main():
        data = []
        if len(sys.argv) == 1:
            infile = sys.stdin
            outfile = sys.stdout
        elif len(sys.argv) == 2:
            infile = open(sys.argv[1], 'rb')
            outfile = sys.stdout
        elif len(sys.argv) == 3:
            infile = open(sys.argv[1], 'rb')
            outfile = open(sys.argv[2], 'wb')
        else:
            raise SystemExit(sys.argv[0] + " [infile [outfile]]")
        with infile:
            try:
                  for line in infile:
                            data.append(json.loads(line))
            except ValueError, e:
                raise SystemExit(e)
        with outfile:
            for d in data:
                    json.dump(d, outfile, sort_keys=True,
                             indent=4, separators=(',', ': '))
                    outfile.write('\n')
if __name__ == '__main__':
        main()

rawDescription: JSON pretty print multiple lines

description: JSON pretty print multiple lines


code:
data = json.loads(json_data)

def iterate_item(item):
    result_str = ""
    if type(item) == dict:
        for key in item:
            result_str = result_str + key + ": " + iterate_item(item[key])
    elif type(item) == list:
        for i in item:
            result_str = result_str + iterate_item(i) + ", "
    else:
        if not item:
            item = "None"
        result_str = result_str + str(item) + ". "

    return result_str

for sighting in data["results"]["features"]:
    print iterate_item(sighting) + "\n\n"

rawDescription: iterating through json with python

description: Iterating through json with python


code:
for x in range(10):
    print '{0}\r'.format(x),
print

rawDescription: How to overwrite the previous print to stdout in python?

description: Overwrite the previous print to stdout in python


code:
for d in students:
    print d["name"],d["homework"],d["quizzes"],d["tests"]

rawDescription: Python: For loop in a for loop?

description: Python: For loop in a for loop


code:
import numpy as np
import itertools
with open('test.dat') as f_in:
    x = np.genfromtxt(itertools.islice(f_in, 1, 12, None), dtype=float)
    print x[0,:]

rawDescription: How to read only specific rows from a text file?

description: Read only specific rows from a text file


code:
class AutoRegister(type):
    def __new__(mcs, name, bases, classdict):
        new_cls = type.__new__(mcs, name, bases, classdict)
        #print mcs, name, bases, classdict
        for b in bases:
            if hasattr(b, 'register_subclass'):
                b.register_subclass(new_cls)
        return new_cls

class AbstractClassA(object):
    __metaclass__ = AutoRegister
    _subclasses = []

    @classmethod
    def register_subclass(klass, cls):
        klass._subclasses.append(cls)

    @classmethod
    def get_concrete_classes(klass):
        return klass._subclasses

class ConcreteClassA1(AbstractClassA):
    pass

class ConcreteClassA2(AbstractClassA):
    pass

class ConcreteClassA3(ConcreteClassA2):
    pass

print AbstractClassA.get_concrete_classes()

rawDescription: Python: How to register all child classes with the father class upon creation


code:
import Image
import sys

def processImage(infile):
    try:
        im = Image.open(infile)
    except IOError:
        print "Cant load", infile
        sys.exit(1)
    i = 0
    mypalette = im.getpalette()

    try:
        while 1:
            im.putpalette(mypalette)
            new_im = Image.new("RGBA", im.size)
            new_im.paste(im)
            new_im.save('foo'+str(i)+'.png')

            i += 1
            im.seek(im.tell() + 1)

    except EOFError:
        pass # end of sequence

processImage('gif_example.gif')

rawDescription: PIL - Convert GIF Frames to JPG

description: PIL - Convert GIF Frames to JPG


code:
def myLen(l):
  for i in range(3):
    print "Hello"

  return 1 + myLen(l[1:]) if l else 0

rawDescription: Python recursion with iterators

description: Python recursion with iterators


code:
entries = {}
with open('no_dup.txt', 'r') as fh_in:
    for line in fg_in:
        entry = line.split()[0]
        if entry in entries:
            entries[entry].append(line)
        else:
            entries[entry] = [line]
for matches in entries.iteritems():
    if len(matches) == 1:
        print matches[0]

rawDescription: How can i compare two columns in two different rows in python

description: Compare two columns in two different rows in python


code:
from urlparse import urlparse

url = 'http://www.gurlge.com:80/path/file.html;params?a=1#fragment'
o = urlparse(url)

print o.params

rawDescription: How can I decode python-requests URL?

description: Decode python-requests URL


code:
def mon_fonction(une_formation, TYPE_RECHERCHE):
    tot = 0
    liste = []
    for quel, val in une_formation:
        if quel == TYPE_RECHERCHE:
            tot += val
            liste.append(val)
    print "Les vals sont:", liste
    print "en tout:", tot
    return tot

rawDescription: Definition of a function with a list in python


code:
import operator
class Comparator:
     def __init__(self,fieldName,compareToValue,my_operator):
         self.op = my_operator
         self.field = fieldName
         self.comparedTo = compareToValue
     def __call__(self,row):
         my_row_val = getattr(row,self.field)
         return self.op(my_row_val,self.comparedTo)
class row_obj:
    class RowItem:
         def __init__(self,name):
              self.name = name
         def __eq__(self,other):
             return Comparator(self.name,other,operator.eq)
    val1 = RowItem("val1")
    val2 = RowItem("val2")
    val3 = RowItem("val3")
    val4 = RowItem("val4")

    def __init__(self, val1, val2, val3, val4):
        self.val1 = val1
        self.val2 = val2
        self.val3 = val3
        self.val4 = val4
    def __str__(self):
        return str([self.val1,self.val2,self.val3,self.val4])
    def __repr__(self):
        return str(self)

class MyTable:
    def __init__(self,rows):
        self.rows = rows
    def filter(self,condition):
        for row in self.rows:
            if condition(row):
               yield row

rows = [row_obj(1,2,3,4),row_obj(1,2,7,4),row_obj(1,2,3,4),row_obj(7,7,7,7)]
mytable = MyTable(rows)
print list(mytable.filter(row_obj.val3 == 7))

rawDescription: Pass in logical operators (and partial expressions) into a function argument Python


code:
import socket
import os

SOCKET_FILENAME = 'lock.sock'

def server():
    print 'I\'m the server, creating the socket'
    s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    s.bind(SOCKET_FILENAME)

    try:
        while True:
            print 'Got a URL: %s' % s.recv(65536)
    except KeyboardInterrupt, exc:
        print 'Quitting, removing the socket file'
        s.close
        os.remove(SOCKET_FILENAME)

def client():
    print 'I\'m the client, opening the socket'
    s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
    s.connect(SOCKET_FILENAME)
    s.send('http://stackoverflow.com')
    s.close()

def main():
    if os.path.exists(SOCKET_FILENAME):
        try:
            client()
        except (socket.error):
            print "Bad socket file, program closed unexpectedly?"
            os.remove(SOCKET_FILENAME)
            server()
    else:
        server()

main()

rawDescription: Only one python program running (like Firefox)?


code:
import threading
from java.util import Timer, TimerTask

class MyTimerTask(TimerTask):
    def run(self):
        print 'Getting Realtime Data'

class IBTHXHandler(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self, name='IBTHX Handler Thread')
        self.start()

    def run(self):
        print 'ibthx thread running'
        timer = Timer()
        timer.schedule(MyTimerTask(), 0, 1000)

IBTHXHandler()

rawDescription: How can I use a Java timer from within a jython class to schedule one of the classes methods?

description: Use a Java timer from within a jython class to schedule one of the classes methods


rawDescription: Simple Python variable scope

description: Simple Python variable scope


code:
def db_default(field, db_default):
    """
    Set attribute __db_default for signal to set default values with.
    """
    field.__db_default = db_default
    return field

class OrderShipLog(models.Model):
    date = db_default(models.DateTimeField(), 'now()')

def generate_default_sql(model):
    """
    Generate SQL for postgresql_psycopg2 default values because the shipping
    database post doesn't guarantee posting certain fields but id like them all to be strings.
    """
    db_fields = filter(lambda x: hasattr(x, '__db_default'), model._meta.fields)
    db_table = model._meta.db_table
    modelname = model._meta.object_name

    sql_dir = os.path.join(os.path.dirname(__file__), 'sql/')
    sql_filename = os.path.join(sql_dir, '{modelname}.postgresql_psycopg2.sql'.format(
        modelname=modelname.lower()))

    from django.db import connection
    if not db_table in connection.introspection.table_names():
        print >> sys.stderr, "{0} not in introspected table list; creating db default sql file : {1}".format(db_table, sql_filename)
        try:
            if not os.path.exists(sql_dir):
                os.makedirs(sql_dir)

            with open(sql_filename, 'w+') as f:
                for field in db_fields:
                    attname, db_column = field.get_attname_column()
                    if not field.__db_default:
                        raise Exception("Must enter value for field {modelname}.{field}.__db_default".format(
                            modelname=modelname,
                            field=attname))
                    f.write('ALTER TABLE {db_table} ALTER COLUMN {db_column} SET DEFAULT {default};\n'.format(
                        db_table=db_table,
                        db_column=db_column,
                        default=field.__db_default,
                        ))
        except Exception, e:
            print >> sys.stderr, "Could not generate SQL file. Manually set the defaults! {0}\n".format(e) * 10

generate_default_sql(OrderShipLog)

rawDescription: Setting database level defaults for fields in django?


code:
def foo():
    """
    >>> foo() # doctest: +ELLIPSIS
    [...] world
    """
    print "hello world"

if __name__ == "__main__":
    import doctest

    OC = doctest.OutputChecker
    class AEOutputChecker(OC):
        def check_output(self, want, got, optionflags):
            from re import sub
            if optionflags & doctest.ELLIPSIS:
                want = sub(r'\[\.\.\.\]', '...', want)
            return OC.check_output(self, want, got, optionflags)

    doctest.OutputChecker = AEOutputChecker
    doctest.testmod()

rawDescription: Can I have an ellipsis at the beginning of the line in a Python doctest?

description: Have an ellipsis at the beginning of the line in a Python doctest


code:
from pubnub import Pubnub

class PubnubHeartbeat(Pubnub):
    def __init__(self, heartbeat=300, **kwargs):
        self.heartbeat = heartbeat
        super(PubnubHeartbeat, self).__init__(**kwargs)

    def getUrl(self, request):
        if "subscribe" in request['urlcomponents'][:2]:
            if "urlparams" not in request:
                request['urlparams'] = {}
            request['urlparams']['heartbeat'] = self.heartbeat

        return super(PubnubHeartbeat, self).getUrl(request)

p = PubnubHeartbeat(
    subscribe_key="demo",
    publish_key="demo",
    heartbeat=60
)

def recv(msg):
    print msg

p.subscribe(channels="heartbeat_test", callback=recv)

rawDescription: Modifying Pubnub presence heartbeat for Python


code:
import signal

class TimeoutException(Exception):
    pass

def alarm_handler(*args):
    raise TimeoutException()

def tryrun(func, timeout=30):
    oldhandler = signal.signal(signal.SIGALRM, alarm_handler)
    try:
        signal.alarm(timeout)
        func()
    except TimeoutException:
        print "Timeout"
    else:
        print "Success"
    finally:
        signal.alarm(0) # disarm alarm
        signal.signal(signal.SIGALRM, oldhandler)

import time
tryrun(lambda: time.sleep(10), 5) # prints Timeout
tryrun(lambda: time.sleep(2), 5)  # prints Success

rawDescription: Python, anticipating an endless loop

description: Python, anticipating an endless loop


code:
x = 4
print x
import sys
sys.stdout.write(str(x)) # you have to str() your variables

rawDescription: Print variable in python without space or newline


code:
condition = True

if condition:
    class C(object):
        os = __import__('os')
        def __init__(self):
            print self.os.listdir

    C.os
    c = C()

rawDescription: Importing modules inside python class

description: Importing modules inside python class


code:
#!/usr/bin/env python

import gtk

def on_addName_destroy(gtkobject, data=None):
    print "This is called later after delete-event callback has been called"
    print "Indication that the reference of this object should be destroyed"
    print "============================================"

def on_addName_delete(widget, event, data=None):
    print "This is called on delete request"
    print "Propagation of this event further can be controlled by return value"
    print "--------------------------------------------"
    return False

def show_popup(widget, data=None):
    dialog = gtk.Window(gtk.WINDOW_TOPLEVEL)
    dialog.set_size_request(100, 100)
    label = gtk.Label("Hello!")
    dialog.add(label)
    dialog.connect("delete-event", on_addName_delete)
    dialog.connect("destroy", on_addName_destroy)
    dialog.show_all()

window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_size_request(100, 100)
button = gtk.Button("Popup")
button.connect("clicked", show_popup)
window.add(button)
window.connect("destroy", lambda x: gtk.main_quit())
window.show_all()

gtk.main()

rawDescription: Connect a method for window destroy

description: Connect a method for window destroy


code:
for i in range(1,15):
   print str(i).zfill(10),

rawDescription: Printing number pattern using python

description: Printing number pattern using python


code:
# import libraries
import urllib2
from collections import defaultdict
from collections import Counter
from matplotlib import pylab as plt

#function for inputing words
def load_dictionary(word_dictionary):
    for word in word_dictionary:
        yield word.strip()

#function for making anagrams
def make_anagrams(source):
    d = defaultdict(list)
    for word in source:
        key = "".join(sorted(word))
        d[key].append(word)
    return d

#function for printing anagrams
def print_anagrams(word_input):
    count=0
    n=0
    k=''
    d = make_anagrams(word_input)
    anagramLens =Counter()
    for key, anagrams in d.iteritems():
        anagramLens[len(anagrams)] += 1
        if len(anagrams) > 1:
            count+= 1
            if n < len(anagrams):
                n=len(anagrams)
                k=key
    print 'The number of unique anagrams is: %d:' % count
    print 'The largest group of anagrams for a word is: %d; and the original word is: %s' % ( n , k)
    print 'The anagrams for the largest anagram word is: %s ' % d[k]
    #print list(anagramLens.elements())
    plt.figure()
    n, bins, patches = plt.hist(list(anagramLens.elements()), histtype='bar', rwidth=0.8)
    plt.show()
#input dictionary from puzzlers.org
word_dictionary = urllib2.urlopen('http://www.puzzlers.org/pub/wordlists/ospd.txt')
word_input = load_dictionary(word_dictionary)
#print answer
print_anagrams(word_input)

rawDescription: How to make a histogram of showing number of items for on the x axis with matplotlib?

description: Make a histogram of showing number of items for on the x axis with matplotlib


code:
#!/usr/bin/env python

import os

def walklevel(some_dir, level):
    some_dir = some_dir.rstrip(os.path.sep)
    num_sep = some_dir.count(os.path.sep)
    for root, dirs, files in os.walk(some_dir):
        yield root, dirs, files
        num_sep_this = root.count(os.path.sep)
        if num_sep + level <= num_sep_this:
            del dirs[:]

for root,dirs,files in walklevel('.',3):
    for dir in dirs:
        tabs='\t'*root.count(os.path.sep)
        print tabs,dir

rawDescription: Pass through the file system from a given directory and print all subfolders and file names (Python)


code:
import re

text = '''public function getVersion() {
    # SomeComment
    some_function()
    return '1.0.0';
}'''

regex_comp = re.compile("public function getVersion\\(\\)\\s*?{\\s*.*return\\s*'(.+)';", re.DOTALL)

print regex_comp.search(text).group(1)

rawDescription: Non-Greedy Regex Does Not Terminate

description: Non-Greedy Regex Does Not Terminate


code:
import sys

def example():
    x = 1
    # Wrap in a try/except loop to catch the interrupt
    try:
        while True:
            x = x + 1
            print x
    except KeyboardInterrupt:
        # On interrupt, write to a simple file and exit
        with open('myvar', 'w') as f:
            f.write(str(x))
            sys.exit(0)

# Not sure of your implementation (probably not this :) ), but
# prompt to run the function
resp = raw_input('Run example (y/n)? ')
if resp.lower() == 'y':
    example()
else:
  # If the function isn't to be run, read the variable
  # Note that this will fail if you haven't already written
  # it, so you will have to make adjustments if necessary
  with open('myvar', 'r') as f:
      myvar = f.read()

  print int(myvar)

rawDescription: Python - Change variable value on exit for next session


code:
import sys
print >> sys.stderr, "Starting..."
print "Done!"

rawDescription: Piped sdt output with notification Python


code:
review1 = {"Google": [10, "Google is the best website to search"], "MSN": [8, "MSN is old, old."]}
review2 = {"Yahoo": [8, "Yahoo?"], "Google": [9, "Google is good to search things"]}
tr = {}

for keys in (review1.viewkeys() | review2.keys()):
    if keys in review1 and keys in review2:
        tr[keys] = [float(review1[keys][0] + review2[keys][0]) / 2, 2, [review1[keys][1], review2[keys][1]]]
    elif keys in review1:
        tr[keys] = [review1[keys][0], review1[keys][1]]
    elif keys in review2:
        tr[keys] = [review2[keys][0], review2[keys][1]]

print tr

rawDescription: Collecting same names and averaging the value in two dictionaries


code:
i=9
while (i<len(headerRow)):
    # Attempt to retrieve an entry's corresponding primary key.
    row = cursor.fetchone()

    if row == None: # New Entry
        # Add entry to database
        print "New Entry Added!"
    else: # Entry already exists
        print "Existing Entry"
        qpID = row[0]
        i += 1
        # ...

rawDescription: Decrement a variable in an incrementing for loop


code:
import numpy as np

x = np.array(["A", "B"])
print np.repeat(x, [2, 3], axis=0)

['A' 'A' 'B' 'B' 'B']

rawDescription: R function rep() in Python (replicates elements of a list/vector)


code:
class _static_property(object):
    """ Descriptor class used for declaring computed properties that
        don't require a class instance. """
    def __init__(self, getter, setter):
        self.getter = getter
        self.setter = setter

    def __get__(self, obj, objtype=None):
        print "In the getter function"
        return self.getter(obj)

    def __set__(self, obj, value):
        print "In setter function"
        self.setter(obj, value)

class _MyMetaClass(type):
    def getX(self):
        return self._x

    def setX(self, v):
        self._x = v

    X = _static_property(getX, setX)

class MyTest(object):
    __metaclass__ = _MyMetaClass
    _x = 42

print MyTest.__dict__
print MyTest.X
MyTest.X = 12
print MyTest.X
print MyTest.__dict__

rawDescription: Why does the Python descriptor __set__ not get called


code:
#!/usr/bin/env python

import os
import time
import datetime

# Targeted filename
filename = 'test.py'

# File creation date UNIX timestamp
created_at = int(os.path.getctime(filename))

# Get hour and minutes
new_name = datetime.datetime.fromtimestamp(created_at).strftime('%H%M')

# Get file extension
name, extension = os.path.splitext(filename)

# New filename
new_filename = new_name + extension

# Rename file
os.rename(filename, new_filename)

print '[+] File successfully renamed'

rawDescription: Write date modified to filename

description: Write date modified to filename


code:
from subprocess import Popen, PIPE

with open("test.avi", "rb") as infile:
    p=Popen(["ffmpeg", "-i", "-", "-f", "matroska", "-vcodec", "mpeg4",
        "-acodec", "aac", "-strict", "experimental", "-"],
           stdin=infile, stdout=PIPE)
    while True:
        data = p.stdout.read(1024)
        if len(data) == 0:
            break
        # do something with data...
        print(data)
    print p.wait() # should have finisted anyway

rawDescription: How do I use ffmpeg with Python by passing File Objects (instead of locations to files on disk)

description: Use ffmpeg with Python by passing File Objects (instead of locations to files on disk)


code:
import re
sentence="warhol's art used many types of media, including hand drawing, painting, printmaking, photography, silk screening, sculpture, film, and music."
print re.sub(ur"[^\w\d'\s]+",'',sentence)

rawDescription: Python removing punctuation from unicode string except apostrophe


code:
files = os.listdir(".")
files.sort(key=os.path.getmtime, reverse=True)
for name in files:
    with open(name) as f:
        if search_string in f.read():
            print name
            break

rawDescription: How do I read the last modified file that contains a certain string?

description: Read the last modified file that contains a certain string


code:
import os
PIs = []
for root, dirs, files in os.walk("/rootDir/"):
  for fname in files:
    if fname.endswith('sum.txt'):
      print fname  #Here, the wanted file name is printed
      with open(os.path.join(root,fname), 'r') as fh_in:
        for line in fh_in:
          print line # here I only get 's' printed, which I believe is the first letter in 'sum.txt'
          line = line.rstrip()
          line = line.split('\t')
          PIs.append(line[2])
print PIs #nothing is collected so nothing is printed

rawDescription: how do I access information from files in subdirectories with os.walk?

description: Access information from files in subdirectories with os.walk


code:
import xml.etree.ElementTree as ET

data = """<article>
<MainText>
    <Big> HDhsdjdsd </Big>
    <Small> jdhdhksdj </Small>
    <Big><text> jsdhjsadh </text> <footnote> 1 </footnote>  <text> hsdhsdh </text> </Big>
</MainText>
</article>"""

tree = ET.fromstring(data)

print tree.find('.//MainText//footnote').text.strip()

rawDescription: Find tag in XML-File

description: Find tag in XML-File


code:
def now():
    print "Hello World!"

class NowGlobals(dict):
    def __init__(self, now, globals):
        self["now"] = now
        self.globals = globals
    def __missing__(self, key):
        return self.globals[key]

class Sim(object):
    def __init__(self, func):
        func = self.patch(func)
        self.func = func
    def now(self):
        print "Hello locals!"
    def patch(self, func):
        funcname   = func.__name__
        nowglobals = NowGlobals(self.now, func.func_globals)
        func = type(func)(func.func_code, nowglobals)
        globals()[funcname] = func
        return func

def myfunc():
    now()

sim = Sim(myfunc)
myfunc()

rawDescription: Change reference to function in run-time in Python


code:
import urllib
from bs4 import *
url = raw_input('Enter - ')
position=int(raw_input('Enter Position'))
count=int(raw_input('Enter Count'))

#perform the loop "count" times.
for _ in xrange(0,count):
    html = urllib.urlopen(url).read()
    soup = BeautifulSoup(html)
    tags=soup.findAll('a')
    for tag in tags:
        url= tag.get('href')
        tags=soup.findAll('a')
        # if the link does not exist at that position, show error.
        if not tags[position-1]:
            print "A link does not exist at that position."
        # if the link at that position exist, overwrite it so the next search will use it.
        url = tags[position-1].get('href')
print url

rawDescription: Having problems following links with webcrawler


code:
# follow.py
#
# Follow a file like tail -f.

import time
def follow(thefile):
    thefile.seek(0,2)
    while True:
        line = thefile.readline()
        if not line:
            time.sleep(0.1)
            continue
        yield line

if __name__ == '__main__':
    logfile = open("run/foo/access-log","r")
    loglines = follow(logfile)
    for line in loglines:
        print line,

rawDescription: Reading from a frequently updated file

description: Reading from a frequently updated file


code:
import poplib
from email import parser

pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('username')
pop_conn.pass_('password')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
    print message['subject']
pop_conn.quit()

rawDescription: Checking email with Python

description: Checking email with Python


code:
#!/usr/bin/env python
import csv
import operator
import pprint

inputfilename = 'input.csv'
outputfilename = 'output.csv'

values = []
with open(inputfilename, 'rb') as csvfile: #Open file
    reader = csv.DictReader(filter(lambda row: row[0]!='#', csvfile)) #Skip rows with #
    header = reader.next().values()[0] #Gives a list of field names
    for rows in reader:
        row = rows.values()[0]
        values.append({header[i]: row[i] for i in range(len(header))}) #Creates list of csv data in a dictionary

report = {} #Define empty dictionary to aggregate data into

for value in values:
    browserstring = value["Operating System"] + " - " + value["Browser"] + " - " + value["Browser Version"].split('.')[0] #Split browser version by '.' to get major version release
    if value["Browser"] <> '': #Skip to next to avoid GA column totals in output (i.e. those with a blank browser value)
        if browserstring in report:
            report [browserstring] += int(value["Sessions"].replace(',','')) #Remove number comma formatting, sum data
        else:
            report [browserstring] = int(value["Sessions"].replace(',','')) #Remove number formatting and add new reecord (if it does not exist already already)
    else:
        next

sorted_report = sorted(report.items(), reverse=True, key=operator.itemgetter(1)) #Convert dictionary to tuple to sort values in descending order

#pprint.pprint(sorted_report) #for debugging

with open(outputfilename,'w') as out: #Let's print this to file
    csv_out=csv.writer(out)
    csv_out.writerow(['Aggregated Browser Version - Major']) #Title
    csv_out.writerow(['Browser','Sessions']) #Column headers
    for row in sorted_report: #Data from ordered tuple list
        csv_out.writerow(row)

rawDescription: Parse and Aggregate Google Analytics Browser Version CSV Data


code:
a = ['adam', 'home', 'wednesday', '17th']
b = ['Tiffany', 'office', 'monday', '9th']

for x in [a, b]:
    working_line = ' '.join(map(lambda s: s.ljust(10, ' '), x))
    print working_line

rawDescription: python string aligning format

description: Python string aligning format


code:
try:
    os.close(rpipe)
    os.dup2(wpipe, sys.stdout.fileno())
    os.dup2(wpipe, sys.stderr.fileno())
    os.close(wpipe)

    print 'aaaaaaaaa'
except:
    traceback.print_exc(20, sys.stderr)
finally:
    sys.stdout.flush()
    sys.stderr.flush()
    os._exit(1)

rawDescription: Redirect output of forked python process to pipe


code:
from bs4 import BeautifulSoup
from urllib2 import urlopen

response = urlopen('http://goldratenepal.com')
html = response.read()
soap = BeautifulSoup(html)
result = soap.find_all('td' ,{'class': 'stones'})

print result[0].text

rawDescription: using beautifulsoup to parse data from table

description: Using beautifulsoup to parse data from table


code:
import regex
p = regex.compile(ur'(?<=\p{Ll})(?=\p{Lu})')
test_str = u"Tina Turner\nMarieM\u00FCller\nJacek\u0104cki"
result = p.sub(u" ", test_str)
result

rawDescription: Split stacked entities using regex re.split in python