code:
def trywordp(x, foundA, foundB):
  if foundA and foundB: return True # Positive base case: Both found!
  if x == "": return False # Negative base case: String exhausted
  if x[0] == 'a': return trywordp(x[1:], True, foundB) # First character in string is 'a', continue checking next character
  if x[0] == 'b': return trywordp(x[1:], foundA, True) # Ditto for 'b'
  return trywordp(x[1:], foundA, foundB) # Neither 'a' nor 'b', continue looking

def tryword(x):
  return trywordp(x, False, False) # We have not found any of them yet so start with foundA and foundB as False

if tryword("stringwithaandb"):
  print "inside"
else:
  print "not inside"

rawDescription: Check 2 characters in a recursion

description: Check 2 characters in a recursion


code:
doc1=['the boy is sleeping', 'in the class', 'not at home']
doc2=['the girl is reading', 'in the class', 'a serious student']

temp=''.join(list(set(doc1) & set(doc2)))
resultDoc1 = ''.join(doc1).find(temp)
resultDoc2 = ''.join(doc2).find(temp)

print "Position of starting character for matching string in doc1=%d" % (resultDoc1 + 1)
print "Position of starting character for matching string in doc2=%d" % (resultDoc2 + 1)

rawDescription: How to find character offsets in texts using python

description: Find character offsets in texts using python


code:
#!/usr/bin/python

import subprocess
import sys
import os
import signal

U_LOG_FILE_PATH = "u.log"
K_LOG_FILE_PATH = "k.log"
U_COMMAND = "adb logcat > " + U_LOG_FILE_PATH
K_COMMAND = "adb shell cat /proc/kmsg > " + K_LOG_FILE_PATH

LOG_PID_PATH="log-pid"

def start_log():
    if(os.path.isfile(LOG_PID_PATH) == True):
        print "log process already started, found file: ", LOG_PID_PATH
        return
    file = open(LOG_PID_PATH, "w")
    print "starting log process: ", U_COMMAND
    proc = subprocess.Popen(U_COMMAND,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        shell=True, preexec_fn=os.setsid)
    print "log process1 id = ", proc.pid
    file.write(str(proc.pid) + "\n")
    print "starting log process: ", K_COMMAND
    proc = subprocess.Popen(K_COMMAND,
        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
        shell=True, preexec_fn=os.setsid)
    print "log process2 id = ", proc.pid
    file.write(str(proc.pid) + "\n")
    file.close()

def stop_log():
    if(os.path.isfile(LOG_PID_PATH) != True):
        print "log process not started, can not find file: ", LOG_PID_PATH
        return
    print "terminating log processes"
    file = open(LOG_PID_PATH, "r")
    log_pid1 = int(file.readline())
    log_pid2 = int(file.readline())
    file.close()
    print "log-pid1 = ", log_pid1
    print "log-pid2 = ", log_pid2
    os.killpg(log_pid1, signal.SIGTERM)
    print "logprocess1 killed"
    os.killpg(log_pid2, signal.SIGTERM)
    print "logprocess2 killed"
    subprocess.call("rm " + LOG_PID_PATH, shell=True)

def print_usage(str):
    print "usage: ", str, "[start|stop]"

# Main script
if(len(sys.argv) != 2):
    print_usage(sys.argv[0])
    sys.exit(1)

if(sys.argv[1] == "start"):
    start_log()
elif(sys.argv[1] == "stop"):
    stop_log()
else:
    print_usage(sys.argv[0])
    sys.exit(1)

sys.exit(0)

rawDescription: How to control background process in linux

description: Control background process in linux


code:
server = request.META.get('wsgi.file_wrapper', None)
if server is not None and server.__module__ == 'django.core.servers.basehttp':
    print 'inside dev'

rawDescription: How can I tell whether my Django application is running on development server or not?

description: Tell whether my Django application is running on development server or not


code:
from theano import function, sandbox, shared
import theano.tensor as T
import numpy as np

reservoirSize = 2
samples       = 5

# To initialize _mat first column
_vec      = np.asarray([1 for i in range(reservoirSize)], np.float32)

# Random matrix, first column will be initialized correctly (_vec)
_mat      = np.asarray(np.random.rand(reservoirSize, samples), np.float32)
_mat[:,0] = _vec

print "Init:\n",_mat

_mat      = shared(_mat)

idx  = T.iscalar()
test = function([idx], updates= {
            # -> instead of
            #_mat[:,idx]:sandbox.cuda.basic_ops.gpu_from_host(_mat[:,idx-1] * 2)
            # -> do this:
            _mat:T.set_subtensor(_mat[:,idx], _mat[:,idx-1]*2)
            })

for i in range(1, samples):
    test(i)

print "Done:\n",_mat.get_value()  # use get_value() here to retrieve the data

rawDescription: Theano: Indexing inside a compiled function (GPU)


code:
import random

def rolldice(sides, rolls):
  for i in xrange(0, rolls):
    yield random.randint(1, sides)

for item in rolldice(6,3):
  print item

rawDescription: How to return when looped variable amount of times

description: Return when looped variable amount of times


code:
import urlparse
url = "http://www.domain.com/img?res=high&refurl=http://www.ahother_domain.com/page/&imgurl=http://www.one_more.com/static/images/mercedes.jpg&w=640&h=480"
urlParams = urlparse.parse_qs(urlparse.urlparse(url).query)
urlInUrl = urlParams['imgurl']
print urlInUrl

rawDescription: How to find URL in another URL?

description: Find URL in another URL


code:
import collections

def handle_vertex(v, vs):
  if v in vs[0]:
    vs[0].remove(v)
  elif v in vs[1]:
    vs[0].add(v)
    vs[1].remove(v)

def follow(edgemap, start, vs):
  """Follow a path in the graph, yielding the edges."""
  v0 = start
  last = None
  while True:
    # All vertices that we can go to next.
    next_v = [v for v in edgemap[v0] if v != last]
    if not next_v:
      # We've reached the end (we must have been a line).
      return
    assert len(next_v) == 1 or (v0 == start and len(next_v) == 2)
    next_v = next_v[0]
    # Remove the endpoints from the vertex-degree sets.
    handle_vertex(v0, vs)
    handle_vertex(next_v, vs)
    yield v0, next_v
    if next_v == start:
      # We've got back to the start (we must have been a cycle).
      return
    v0, last = next_v, v0

def pairsort(edges):
  edgemap = collections.defaultdict(list)
  original_edges = {}
  for a, b in edges:
    # Build the adjacency table.
    edgemap[a].append(b)
    edgemap[b].append(a)
    # Keep a map to remember the original order pairs appeared in
    # so we can output edges correctly no matter which way round
    # we store them.
    original_edges[a, b] = [a, b]
    original_edges[b, a] = [a, b]
  # Build sets of degree 1 and degree 2 vertices.
  vs = [set(), set()]
  for k, v in edgemap.iteritems():
    vs[len(v) - 1].add(k)
  # Find all components that are lines.
  while vs[0]:
    v0 = vs[0].pop()
    for e in follow(edgemap, v0, vs):
      yield original_edges[e]
  # Find all components that are cycles.
  while vs[1]:
    v0 = vs[1].pop()
    for e in follow(edgemap, v0, vs):
      yield original_edges[e]

input = [
    [ 4, 10],
    [ 4,  2],
    [ 0,  7],
    [ 5, 11],
    [ 6,  8],
    [ 3,  6],
    [ 9,  7],
    [ 2, 11],
    [ 9,  5],
    [ 8,  1]]

print list(pairsort(input))

rawDescription: Ordering an array for maximal pairwise matches


code:
for x in d.get("kids", ()):
    print "kid:", x

rawDescription: Python: Combine "if 'x' in dict" and "for i in dict['x']"


code:
class Int(object):

  def __init__(self, init_val=0):
    self.val = init_val

obj = Int(42)
print Int, type(Int), obj, type(obj)

rawDescription: Does Python assume a symbol is a type before trying to see if it is a function?


code:
if attivo[0][0] == 1:
    print "1"

rawDescription: Fetch array after SELECT statement

description: Fetch array after SELECT statement


code:
import signal, sys
def handler(signal, frame):
    print "Canceled!"
    sys.exit(1)
signal.signal(signal.SIGINT, handler)
for x in large_list:
    function_that_catches_KeyboardInterrupt(x)

rawDescription: In Python, can I prevent a function from catching KeyboardInterrupt and SystemExit?


code:
def size(lst):
    if type(lst) == int:
        return 1
    else:
        return 1 + sum(size(e) for e in lst)

print size([[[14],[23,[14]]]])

rawDescription: List structure size function, difficulty with code


code:
for k in dir(__builtins__):
    print str(k) + " : :\n" + str(dir(eval(k))) + "\n\n"
    try:
        a = input("type enter for next:")
    except(SyntaxError):
        continue

rawDescription: Which classes do Python intrinsic methods belong to?


code:
s = "Welcome to !+SO!"
try:
    print s[s.index("+"):s.rindex("!")+1]
    # +SO!
except ValueError:
    print "Either + or ! not found in the string"

rawDescription: searching for python substring without regex

description: Searching for python substring without regex


code:
if os.path.exists('C:/Program Files'): print 'yes'
if os.path.exists(r'C:\Program Files'): print 'yes'
if os.path.exists('C:\\Program Files'): print 'yes'

rawDescription: Python (and possibly others) - What is the escape character for a space?


code:
import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port, username=username, password=password)

stdin, stdout, stderr = client.exec_command('ls -l')
print stdout.read()

rawDescription: Is it possible to run a shell command onto a different device?


code:
import random

def newfunc(string1, string2):
    if string1 == string2:
        print "You selected",string1,"and the computer selected",string2,"you win!"
    else:
        print "You selected",string1,"and the computer selected",string2,"you lose!"

def AceDiamondSpade():
    #Set up a list which contains Ace, Diamond and Spade so that the computer can randomly choose one of them.
    myList = ["Ace", "Diamond", "Spade"]
    #
    while(True):
        choice = raw_input("Ace, Diamond, or Spade? ")
        computerChoice = random.choice(myList)
        if choice not in myList:
            print "That was not a valid choice."
            break
        newfunc(choice,computerChoice)

AceDiamondSpade()

rawDescription: Using a while loop in a Rock, Paper, Scissors Type game. (Python)


code:
root = etree.fromstring("""
<root>
    <articles>

             <content>some text</content>

             <content>some text</content>

             <content>some text</content>

    </articles>
</root>
""")

print root.xpath("//article[@type='news']/content/text()")

rawDescription: finding elements by attribute with lxml

description: Finding elements by attribute with lxml


code:
# =============================================================================
# Plot central cross-section of sphere under steady-state conditions
# where the temperature on upper hemisphere is T=T_0 and the lower
# hemisphere is held at T=0.  This is an expansion in Legendre polynomials.
#
# Author:           Max Graves
# Last Revised:     8-OCT-2013
# =============================================================================

import pylab as pl

from scipy.special import eval_legendre as Leg
import math,sys

def sumTerm(a,r,theta,l):
    """
    Compute term of sum given radius of sphere (a),
    y and z coordinates, and the current index of the
    Legendre polynomials (l) over the entire range
    where these polynomials are orthogonal [-1,1].
    """
    xRange = pl.arange(-0.99,1.0,0.01)
    x = pl.cos(theta)
    # correct for scipy handling negative indices incorrectly
    lLow = l-1
    lHigh = l+1
    if lLow < 0:
        lLow = -lLow-1
    return 0.5*((r/a)**l)*Leg(l,x)*(Leg(lLow,0)-Leg(lHigh,0))

def main():

    n = 20      # number of l terms to expand to
    a = 1.0     # radius of sphere

    # generate r, theta values
    aBins = pl.linspace(0, 2*pl.pi, 360)      # 0 to 360 in steps of 360/N.
    rBins = pl.linspace(0, 1, 50)
    theta,r = pl.meshgrid(aBins, rBins)

    tempProfile = pl.zeros([50,360])
    for nr,ri in enumerate(rBins):
        print nr
        for nt,ti in enumerate(aBins):
            temp = 0.0
            for l in range(n):
                temp += sumTerm(a, ri, ti, l)
            tempProfile[nr,nt] = temp

    # plot the Temperature profile
    fig, ax = pl.subplots(subplot_kw=dict(projection='polar'))
    pax = ax.pcolormesh(theta, r, tempProfile)
    ax.set_theta_zero_location("N") # 'north' location for theta=0
    ax.set_theta_direction(-1)      # angles increase clockwise
    fig.colorbar(pax)

    pl.show()

if __name__=='__main__':
    main()

rawDescription: Build up and plot Matplotlib 2d histogram in polar coordinates using the Legendre Polynomials


code:
from mailbox import mbox
import re

PAT_EMAIL = re.compile(r"[0-9A-Za-z._-]+\@[0-9A-Za-z._-]+")

mymbox = mbox("demo.txt")
for email in mymbox.values():
    from_address = PAT_EMAIL.findall(email["from"])
    to_address = PAT_EMAIL.findall(email["to"])
    date = [ email["date"], ]
    print ";".join(from_address + to_address + date)

rawDescription: Parsing email headers with regular expressions in python


code:
import urllib2
import csv

class GoogleFinanceAPI:
    def __init__(self):
        self.url = "http://finance.google.com/finance/historical?client=ig&q={0}:{1}&output=csv"
    def get(self,symbol,exchange):
        page = urllib2.urlopen(self.url.format(exchange,symbol))
        content = page.readlines()
        page.close()
        reader = csv.reader(content)
        for row in reader:
            print row

c = GoogleFinanceAPI()
c.get("MSFT","NASDAQ")

rawDescription: Python- Get Stock Information for a company for a range of dates


code:
import csv
import glob
import ast
from os.path import isfile
from lxml import etree

def look_for_speaker_in_files(speakerAttrib):
    speakerDict = ast.literal_eval(speakerAttrib)
    l_file_exists = False
    if isfile("allspeakers.csv"):
        l_file_exists = True
    c = csv.writer(open("allspeakers.csv","a"))
    if not l_file_exists:
        c.writerow(["Name", "Filename", "Text"])
    lparser = etree.XMLParser(recover=True)
    for cr_file in glob.iglob('parsed/*.xml'):
        try:
          tree = etree.parse(cr_file,parser=lparser)
          for node in tree.iter('speaking'):
             if node.keys() == speakerDict.keys():
                c.writerow([node.attrib, cr_file, node.text])
             else:
                 continue
        except:
          print "bad string " + cr_file
          raise

def main():
    with open("UAS_speakers.txt","r") as speaker_list:
        for x in speaker_list:
            print x
            look_for_speaker_in_files(x)
if __name__ == "__main__":
    main()

rawDescription: How do I apply a function to all items in a list in a text or csv file with Python?

description: Apply a function to all items in a list in a text or csv file with Python


code:
# Create a range that does not contain 50
for i in [x for x in xrange(100) if x != 50]:
    print i

# Create 2 ranges [0,49] and [51, 100]
for i in range(50) + range(51, 100):
    print i

# Create a iterator and skip 50
xr = iter(xrange(100))
for i in xr:
    print i
    if i == 49:
        next(xr)

# Simply continue in the loop if the number is 50
for i in range(100):
    if i == 50:
        continue
    print i

rawDescription: Skip over a value in the range function in python


code:
cl = g.community_fastgreedy().as_clustering()
comm1 = cl[0]
comm2 = cl[1]
edges_between = g.es.select(_between=(comm1, comm2))
print 2.0 * len(edges_between) / len(comm1) * len(comm2)

rawDescription: iGraph in Python: Relation between a VertexDendrogram object and VertexClustering object

description: IGraph in Python: Relation between a VertexDendrogram object and VertexClustering object


rawDescription: Convert IP address string to binary in Python


code:
import xmlrpclib
import time

client = xmlrpclib.ServerProxy("https://pypi.python.org/pypi")

interval = 86400*2
for package, version in client.updated_releases(int(time.time()) - interval):
    print "%s %s" % (package, version)

rawDescription: how to see less recent packages on pypi

description: See less recent packages on pypi


code:
from urllib2 import urlopen
from bs4 import BeautifulSoup
url = 'http://www.emploi.ma/offre-emploi-maroc/commerciaux-en-emission-appels-1019077'
soup = BeautifulSoup(urlopen(url), "html5lib")
print soup.body
soup = BeautifulSoup(urlopen(url), "html.parser")
print soup.body

soup = BeautifulSoup(urlopen(url), "lxml")
print soup.body

rawDescription: Beautifulsoup soup.body return None

description: Beautifulsoup soup.body return None


rawDescription: Have I reached some limit of a scipy calculation?


code:
class Promise(object):
    def fulfill(self, result):
        self.result = result
    def __iter__(self):
        return iter(self.result)

def scaleit(g, k):
  for item in g:
    yield item*k

promise = Promise()
f = scaleit(promise, 3)
promise.fulfill(range(10))
print list(f)

rawDescription: updating a python generator after it has been created

description: Updating a python generator after it has been created


code:
data = ['VERB', 'SUBJ', 'OBJ']
for n, i in enumerate(data):
    print n, i

rawDescription: Using the index of items in a list to compare the order they come in the list


code:
from settings import INSTALLED_APPS
if 'appname' in INSTALLED_APPS:
    print 'we have app'

rawDescription: Is there a quick way to tell if an app is in Django's installed_apps?


code:
import requests
import time
class BaseCheck():
    def __init__(self, url):
        self.http_proxy  = "http://user:pw@proxy:8080"
        self.https_proxy = "http://user:pw@proxy:8080"
        self.ftp_proxy   = "http://user:pw@proxy:8080"
        self.proxyDict = {
                      "http"  : self.http_proxy,
                      "https" : self.https_proxy,
                      "ftp"   : self.ftp_proxy
                    }
        self.url = url
        def makearr(tsteps):
            global stemps
            global steps
            stemps = {}
            for step in tsteps:
                stemps[step] = { 'start': 0, 'end': 0 }
            steps = tsteps
        makearr(['init','check'])
        def starttime(typ = ""):
            for stemp in stemps:
                if typ == "":
                    stemps[stemp]['start'] = time.time()
                else:
                    stemps[stemp][typ] = time.time()
        starttime()
    def __str__(self):
        return str(self.url)
    def getrequests(self):
        g=requests.get(self.url,proxies=self.proxyDict)
        print g.status_code
        print g.content
        print self.url
        stemps['init']['end'] = time.time()
        #print stemps['init']['end'] - stemps['init']['start']
        x= stemps['init']['end'] - stemps['init']['start']
        print x

test=BaseCheck(url='http://google.com')
test.getrequests()

rawDescription: Diagnosing proxy issue with python

description: Diagnosing proxy issue with python


code:
import csv
foo_in = open('bar.csv', 'rU')
readfoo = csv.reader(foo_in)

for row in readfoo:
    spam = row[0]
    eggs = row[1]
    foobar = row[2]
    new_data = dict()
    new_data.setdefault(spam, {})
    new_data[spam].setdefault(eggs, []).append(foobar)
    print new_data

rawDescription: Creating either 2 dictionaries from CSV or creating dictionary from 3 rows


code:
import serial
port,baud = "/dev/ttyUSB0",9600 #just an example (linux)
port,baud = "COM5",9600 #just an example (win)
ser = serial.serial(port,baud,timeout=1)
ser.write("1")
print "RESP 1:",ser.read(10000)
ser.write("2")
print "RESP 2:",ser.read(10000)

rawDescription: Implement serialPort.write in Python

description: Implement serialPort.write in Python


code:
phrases = ["I'm so happy with myself lately!", "Johnny, im so sad, so very sad, call me", "i feel like crap. SO ANGRY!!!!"]
words = ["happy", "sad", "angry", "jumpy"]

for phrase in phrases:
    print phrase
    print {word: phrase.count(word) for word in words}

rawDescription: Two lists, one of words, one of phrases

description: Two lists, one of words, one of phrases


code:
import cv2, Image, os

name = raw_input('Video File (With Extension): ')
x_res = int(raw_input('Image Width (Pixels): '))
y_res = int(raw_input('Image Height (Pixels): '))
rows = int(raw_input('Number of Rows: '))
columns = int(raw_input('Number of Columns: '))

vidcap = cv2.VideoCapture(name)
success,im = vidcap.read()
frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
print frames
new_im = Image.new('RGB', (x_res, y_res))
x_cntr = 0
y_cntr = 0

if not os.path.exists('./' + name + ' Output/'):
    os.makedirs('./' + name + ' Output/')

for x in xrange(0,frames,1):
    if x%(rows*columns) == 0:
        new_im.save('./' + name + ' Output/' + str(x) + '.jpg')
        new_im = Image.new('RGB', (x_res,y_res))
        y_cntr = 0
        x_cntr = 0
        print str(round(100*(float(x)/frames), 1)) + "% Complete"
    elif x%rows == 0:
        x_cntr = 0
        y_cntr = y_cntr + y_res/columns
    elif x%1 == 0:
        x_cntr = x_cntr + x_res/rows
    success,cv2_im = vidcap.read()
    if success == True:
        cv2_im = cv2.cvtColor(cv2_im,cv2.COLOR_BGR2RGB)
        im = Image.fromarray(cv2_im)
        im = im.resize((x_res/rows + x_res%rows, y_res/columns + y_res%columns), Image.ANTIALIAS)
        new_im.paste(im, (x_cntr, y_cntr))
    elif success == False:
        new_im.save('./' + name + ' Output/' + str(x) + '.jpg')

rawDescription: Python OpenCV / PIL COLOR_BGR2RGB Error

description: Python OpenCV / PIL COLOR_BGR2RGB Error


code:
#!/usr/bin/env python

import re

if __name__ == "__main__":
    lines = {' foo      (bar)    '}
    parens_regex = re.compile(r'\(.*?\)')  # Non-greedy
    space_regex =  re.compile(r'\s+')

    for line in lines:
        print 'Before: "%s"' % line
        line_tmp = parens_regex.sub('', line)  # Before space-regex so we also collapse space around parens
        line_tmp = space_regex.sub(' ', line_tmp)
        line_tmp = line_tmp.strip()
        print 'After: "%s"' % line_tmp  # Prints: "foo"

rawDescription: Removal of whitespace and text in brackets - make my working code more elegant


code:
from multiprocessing import Process, Manager

def f(d):
    for i in range(10000):
        d['blah'] += 1

if __name__ == '__main__':
    manager = Manager()

    d = manager.dict()
    d['blah'] = 0
    procs = [ Process(target=f, args=(d,)) for _ in range(10) ]
    for p in procs:
        p.start()
    for p in procs:
        p.join()

    print d

rawDescription: how can I share a dictionary across multiple processes?

description: Share a dictionary across multiple processes


code:
#!/usr/bin/python
# URL that generated this code:
# http://txt2re.com/index-python.php3?s=$%2055%20326&2&1

import re

txt='$ 55 326'
re1='.*?'   # Non-greedy match on filler
re2='(\\d+)'    # Integer Number 1
re3='.*?'   # Non-greedy match on filler
re4='(\\d+)'    # Integer Number 2

rg = re.compile(re1+re2+re3+re4,re.IGNORECASE|re.DOTALL)
m = rg.search(txt)
if m:
    int1=m.group(1)
    int2=m.group(2)
    print "("+int1+")"+"("+int2+")"+"\n"

rawDescription: python enconding regex issue

description: Python enconding regex issue


code:
import re
pattern = r"""
          \b(?P<first_part>\w*(?P<splitter>\w))   # matches starting at a word boundary
          (?P<last_part>(?P=splitter)er\b)        # matches the last letter of the first group
                                                  # plus 'er' if followed by a word boundary
          """
matcher = re.compile(pattern, re.X)
print matcher.search('letter').groupdict()
# out: {'first_part': 'let', 'last_part': 'ter', 'splitter': 't'}

rawDescription: Refer to group inside group with Regex

description: Refer to group inside group with Regex


code:
from datetime import timedelta
tm1 = [map(int, x.split(':')) for x in times]
tm2 = [timedelta(hours=x[0], minutes=x[1], seconds=x[2]) for x in tm1]
print sum(tm2, timedelta())

rawDescription: Working with time values greater than 24 hours


code:
# Solve square puzzle
import operator

class Node:
# Here is how the squares are defined
    def __init__(self, ID, base):
        self.posx = ID % base
        self.posy = ID / base
        self.base = base
    def isValidNode(self, posx, posy):
        return (0<=posx<self.base and 0<=posy<self.base)

    def getNeighbors(self):
        neighbors = []
        if self.isValidNode(self.posx + 3, self.posy): neighbors.append(self.posx + 3 + self.posy*self.base)
        if self.isValidNode(self.posx + 2, self.posy + 2): neighbors.append(self.posx + 2 + (self.posy+2)*self.base)
        if self.isValidNode(self.posx, self.posy + 3): neighbors.append(self.posx + (self.posy+3)*self.base)
        if self.isValidNode(self.posx - 2, self.posy + 2): neighbors.append(self.posx - 2 + (self.posy+2)*self.base)
        if self.isValidNode(self.posx - 3, self.posy): neighbors.append(self.posx - 3 + self.posy*self.base)
        if self.isValidNode(self.posx - 2, self.posy - 2): neighbors.append(self.posx - 2 + (self.posy-2)*self.base)
        if self.isValidNode(self.posx, self.posy - 3): neighbors.append(self.posx + (self.posy-3)*self.base)
        if self.isValidNode(self.posx + 2, self.posy - 2): neighbors.append(self.posx + 2 + (self.posy-2)*self.base)
        return neighbors

# the nodes go like this:
# 0 => bottom left
# (base-1) => bottom right
# base*(base-1) => top left
# base**2 -1 => top right
def solve(start_nodeID, base):
    all_nodes = []
    #Traverse list is the list to keep track of which moves are made (the id numbers of nodes in a list)
    traverse_list = [start_nodeID]
    for i in range(0, base**2): all_nodes.append(Node(i, base))
    togo = dict()
    #Togo is a dictionary with (nodeID:[list of neighbors]) tuples
    togo[start_nodeID] = all_nodes[start_nodeID].getNeighbors()
    solution_count = 0

    while(True):
        # The search is exhausted
        if not traverse_list:
            print "Somehow, the search tree is exhausted and you have reached the divine salvation."
            print "Number of solutions:" + str(solution_count)
            break

        # Get the next node to hop
        try:
            current_node_ID = togo[traverse_list[-1]].pop(0)
        except IndexError:
            del togo[traverse_list.pop()]
            continue

        # end condition check
        traverse_list.append(current_node_ID)
        if(len(traverse_list) == base**2):
            #OMG, a solution is found
            #print traverse_list
            solution_count += 1
            #Print solution count at a steady rate
            if(solution_count%100 == 0):
                print solution_count
                # The solution list can be returned (to visualize the solution in a simple GUI)
                #return traverse_list

        # get valid neighbors
        valid_neighbor_IDs = []
        candidate_neighbor_IDs = all_nodes[current_node_ID].getNeighbors()
        valid_neighbor_IDs = filter(lambda id: not id in traverse_list, candidate_neighbor_IDs)

        # if no valid neighbors, take a step back
        if not valid_neighbor_IDs:
            traverse_list.pop()
            continue

        # if there exists a neighbor which is accessible only through the current node (island)
        # and it is not the last one to go, the situation is not promising; so just eliminate that
        stuck_check = True
        if len(traverse_list) != base**2-1 and any(not filter(lambda id: not id in traverse_list, all_nodes[n].getNeighbors()) for n in valid_neighbor_IDs): stuck_check = False

        # if stuck
        if not stuck_check:
            traverse_list.pop()
            continue

        # sort the neighbors according to accessibility (the least accessible first)
        neighbors_ncount = []
        for neighbor in valid_neighbor_IDs:
            candidate_nn = all_nodes[neighbor].getNeighbors()
            valid_nn = [id for id in candidate_nn if not id in traverse_list]
            neighbors_ncount.append(len(valid_nn))
        n_dic = dict(zip(valid_neighbor_IDs, neighbors_ncount))
        sorted_ndic = sorted(n_dic.items(), key=operator.itemgetter(1))

        sorted_valid_neighbor_IDs = []
        for (node, ncount) in sorted_ndic: sorted_valid_neighbor_IDs.append(node)

        # if current node does have valid neighbors, add them to the front of togo list
        # in a sorted way
        togo[current_node_ID] = sorted_valid_neighbor_IDs

# To display a solution simply
def drawGUI(size, solution):
    # GUI Code (If you can call it a GUI, though)
    import Tkinter
    root = Tkinter.Tk()
    canvas = Tkinter.Canvas(root, width=size*20, height=size*20)
    #canvas.create_rectangle(0, 0, size*20, size*20)
    canvas.pack()

    for x in range(0, size*20, 20):
        canvas.create_line(x, 0, x, size*20)
        canvas.create_line(0, x, size*20, x)

    cnt = 1
    for el in solution:
        canvas.create_text((el % size)*20 + 4,(el / size)*20 + 4,text=str(cnt), anchor=Tkinter.NW)
        cnt += 1
    root.mainloop()

print('Start of run')

# it is the moment
solve(0, 10)

#Optional, to draw a returned solution
#drawGUI(10, solve(0, 10))

raw_input('End of Run...')

rawDescription: Riddle: The Square Puzzle

description: Riddle: The Square Puzzle


code:
import sys, pkgutil
mods = set()

#You may not need this part if you don't care about the builtin modules
print sys.builtin_module_names
for m in sys.builtin_module_names:
    if m != '__main__':
        mods.add(m)
        #mods.add(m)

for loader, name, ispkg in pkgutil.walk_packages():
    if name.find('.') == -1:
        mods.add(name)

print mods

rawDescription: How can I find the module(s) provided by a given Python distribution?

description: Find the module(s) provided by a given Python distribution


code:
class MyClass(object):
     def __init__(self,arg):
         self.arg = arg

     @classmethod
     def from_sum(cls,*args):
         return cls(sum(args))

inst = MyClass.from_sum(1,2,3,4)
print inst.arg  #10

rawDescription: CapWords conventions: get_MyClass or get_my_class


code:
x = [1,2,3,4,4,5,6,7,7]
y = [3,4,5,6,7,8,9,10]
# you can leave out bad and just compare against
# x at the end if memory is more important than speed
newx, bad, newy = [], [], []
for i in x:
    if i in y:
        callsomefunction(i)
        bad.append(i)
    else:
        newx.append(i)

for i in y:
    if i not in bad:
        newy.append(i)

print newx
print newy

rawDescription: python iterate over the two lists while comparing items

description: Python iterate over the two lists while comparing items


code:
import subprocess

text = raw_input("Enter text to be classified: ")
p1 = subprocess.Popen('bin/stupidfilter', 'data/c_trbf')
stupid = float(p1.communicate(text)[0])

if stupid:
    print "Text is likely to be stupid"
else:
    print "Text is not likely to be stupid"

rawDescription: Calling an external program from python

description: Calling an external program from python


code:
out = ['<cookies>.facebook.com:%s:%s' % (k,v)
       for d in L for k,v in d.iteritems()]
print ''.join(out) + '<cookies>'

rawDescription: Python list of dictionaries representation


code: print blah[0].json()

rawDescription: <class 'requests.models.Response'> to Json


code:
for node in tree.iter('{http://uniprot.org/uniprot}dbReference'):
   if node.attrib.get('type') == 'GO':
       for child in node:
           value = child.attrib.get('value');
           print value
           if value.startswith('C:'):
               goterm = node.attrib.get('id')
               print goterm
               break

rawDescription: Python: Extract XML element value when children attribute meet criteria


rawDescription: Split delimited values in excel using jupyter python


code:
from pymongo import MongoClient
uri = "mongodb://test1:test1@ds051990.mongolab.com:51990/joran1"
my_db_cli = MongoClient(uri)
db = my_db_cli.joran1 #select the database ...

my_scores = db.scores #this will be created if it doesnt exist!
#add a new score
my_scores.insert({"user_name":"Leeeeroy Jenkins","score":124,"time":"11/24/2014 13:43:22"})
my_scores.insert({"user_name":"bob smith","score":88,"time":"11/24/2014 13:43:22"})
from pymongo import DESCENDING
#get a list of high scores (from best to worst)
print list(my_scores.find().sort("score",DESCENDING))

rawDescription: Creating a leaderboard for offline game in Python


code:
def multigen(gen_func):
    class _multigen(object):
        def __init__(self, *args, **kwargs):
            self.__args = args
            self.__kwargs = kwargs
        def __iter__(self):
            return gen_func(*self.__args, **self.__kwargs)
    return _multigen

@multigen
def myxrange(n):
   i = 0
   while i < n:
     yield i
     i += 1
m = myxrange(5)
print list(m)
print list(m)

rawDescription: How to make a repeating generator in Python

description: Make a repeating generator in Python


code:
import numpy as np
import pylab as P

def binner(LB, UB, step=1):
    N = int((UB-LB+1)/float(step) + 1)
    return [LB + step * (i - 1/float(2)) for i in xrange(N)]

def f_hist(x, bins=None, param=20, h_type='bar', barwidth=0.8,filename=None):
    P.figure()
    if bins is None:
        if hasattr(param, "__iter__"):
            if len(param) == 2:
                LB, UB = param
                step = 1
            elif len(param) == 3:
                LB, UB, step = param
            else:
                raise Exception
            bins = binner(LB, UB, step)
            n, bins, patches = P.hist(x,bins,histtype=h_type,rwidth=barwidth)
        else:
            n, bins, patches = P.hist(x,param,histtype=h_type,rwidth=barwidth)
    else:
        n, bins, patches = P.hist(x, bins, histtype=h_type, rwidth=barwidth)
    if filename is None:
        P.show()
    else:
        P.savefig(filename)
        print "Histogram saved as {}".format(filename)
        return filename

if __name__ == '__main__':
    mu, sigma = 200, 25
    LB, UB, step = 100, 300, 10
    x = mu + sigma*P.randn(10000)
    f_hist(x, param = (LB, UB, step))
    f_hist(x)

rawDescription: Ask for a way to plot histogram for a 1D array within python


code:
from multiprocessing import Process, Queue
import time

def reader(queue):
    ## Read from the queue
    while True:
        msg = queue.get()         # Read from the queue and do nothing
        if (msg == 'DONE'):
            break

def writer(count, queue):
    ## Write to the queue
    for ii in xrange(0, count):
        queue.put(ii)             # Write 'count' numbers into the queue
    queue.put('DONE')

if __name__=='__main__':
    for count in [10**4, 10**5, 10**6]:
        queue = Queue()   # reader() reads from queue
                          # writer() writes to queue
        reader_p = Process(target=reader, args=((queue),))
        reader_p.daemon = True
        reader_p.start()        # Launch reader() as a separate python process

        _start = time.time()
        writer(count, queue)    # Send a lot of stuff to reader()
        reader_p.join()         # Wait for the reader to finish
        print "Sending %s numbers to Queue() took %s seconds" % (count,
            (time.time() - _start))

rawDescription: How to use multiprocessing queue in Python?

description: Use multiprocessing queue in Python


code:
import matplotlib.pyplot as plt

def on_pick(event):
    print event.artist.get_facecolor()

fig, ax = plt.subplots()
bars = ax.bar(range(10), range(10), picker=5)

fig.canvas.mpl_connect('pick_event', on_pick)

plt.show()

rawDescription: Getting the colour of bar chart matplotlib


code:
import csv
try :
    fr = open("mycsv.csv")
except:
    print "Couldn't open the file"
reader = csv.reader(fr)
base={}
for row in reader :
     if len(row) > 0:
            if row[1] in base: #Check if that season is in dict.
                    base[row[1]].append(row[0]) # If so add the number to the list already there.
            else:
                    base[row[1]]=[row[0]] # Else create new list and add the number
print base

rawDescription: How to find a string that is repeated in a csv file and formatting the result in python?

description: Find a string that is repeated in a csv file and formatting the result in python


code:
import numpy as np
import cv2
from matplotlib import pyplot as plt

img = cv2.imread('simple.jpg',0)

# Initiate FAST object with default values
fast = cv2.FastFeatureDetector_create()

# find and draw the keypoints
kp = fast.detect(img,None)
img2 = cv2.drawKeypoints(img, kp, color=(255,0,0))

# Print all default params
print "Threshold: ", fast.getInt('threshold')
print "nonmaxSuppression: ", fast.getBool('nonmaxSuppression')
print "neighborhood: ", fast.getInt('type')
print "Total Keypoints with nonmaxSuppression: ", len(kp)

cv2.imwrite('fast_true.png',img2)

# Disable nonmaxSuppression
fast.setBool('nonmaxSuppression',0)
kp = fast.detect(img,None)

print "Total Keypoints without nonmaxSuppression: ", len(kp)

img3 = cv2.drawKeypoints(img, kp, color=(255,0,0))

cv2.imwrite('fast_false.png',img3)

rawDescription: Where is the FAST algorithm in OpenCV?

description: Where is the FAST algorithm in OpenCV


code:
yplot = 0 #added

#do the simulation
total_time = 0.0
dt = 0.04
times=[]
yvals=[]
while total_time<2.0:
    x,y,z = body.getPosition()
    u,v,w = body.getLinearVel()
    print "%1.2fsec: pos=(%6.3f,%6.3f,%6.3f) vel=(%6.3f,%6.3f,%6.3f)" % \
        (total_time, x,y,z,u,v,w)
    world.step(dt)
    total_time += dt
    yplot += y
    times.append(total_time)
    yvals.append(yplot)
plot(times, yvals,'r-')
xlabel('Time') #added
ylabel('Height') #added
show() #added

rawDescription: Plotting graph in python

description: Plotting graph in python


code:
from xml.dom import minidom
from xml.dom.minidom import parse
import xml.etree.ElementTree as ET

xml_file = "dummy.xml"
xmlFile = ET.parse(xml_file)

root = xmlFile.getroot()
root.keys()

newroot = ET.Element("languages")

for child in root:
    if child.tag == "language":
        newroot.insert(1, child)
        root.remove(child)
        root.insert(1, newroot)
        xmlFile.write("newdummy.xml")
    else:
        print "no"

rawDescription: Adding a container element to an XML using Python


code:
from subprocess import Popen, PIPE

gitproc = Popen(['git', 'show-ref'], stdout = PIPE)
(stdout, stderr) = gitproc.communicate()

for row in stdout.split('\n'):
    if row.find('HEAD') != -1:
        hash = row.split()[0]
        break

print hash

rawDescription: Possible to extract the git repo revision hash via Python code?


code:
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save)
def do_your_thing(sender, **kwargs):
    if sender is User:
        if kwargs["created"]:
            print kwargs["instance"].password
            # do your thing

rawDescription: Django check when user created

description: Django check when user created


code:
def merge(a,b):
    for ax, (first, bx) in zip(a,b):
        if ax[0] != first:
            raise ValueError("Items don't match")
        yield ax + (bx,)

print list(merge(a,b))
print list(merge(merge(a,b),c))

rawDescription: how to zip two lists of tuples in python

description: Zip two lists of tuples in python


code:
import os
import select
import subprocess
from cStringIO import StringIO

target = 'Engine'
PIPE = subprocess.PIPE
engine = subprocess.Popen(target, bufsize=0, stdin=PIPE, stdout=PIPE, stderr=PIPE)
engine.stdin.write(b"go\n")
engine.stdin.flush()

class LineReader(object):

    def __init__(self, fd):
        self._fd = fd
        self._buf = ''

    def fileno(self):
        return self._fd

    def readlines(self):
        data = os.read(self._fd, 4096)
        if not data:
            # EOF
            return None
        self._buf += data
        if '\n' not in data:
            return []
        tmp = self._buf.split('\n')
        lines, self._buf = tmp[:-1], tmp[-1]
        return lines

proc_stdout = LineReader(engine.stdout.fileno())
proc_stderr = LineReader(engine.stderr.fileno())
readable = [proc_stdout, proc_stderr]

while readable:
    ready = select.select(readable, [], [], 10.0)[0]
    if not ready:
        continue
    for stream in ready:
        lines = stream.readlines()
        if lines is None:
            # got EOF on this stream
            readable.remove(stream)
            continue
        for line in lines:
            print line

rawDescription: Python: select() doesn't signal all input from pipe


code:
import win32com.client
import pythoncom
import re

class Handler_Class(object):
    def OnNewMailEx(self, receivedItemsIDs):
        # RecrivedItemIDs is a collection of mail IDs separated by a ",".
        # You know, sometimes more than 1 mail is received at the same moment.
        for ID in receivedItemsIDs.split(","):
            mail = outlook.Session.GetItemFromID(ID)
            subject = mail.Subject
            try:
                # Taking all the "BLAHBLAH" which is enclosed by two "%".
                command = re.search(r"%(.*?)%", subject).group(1)

                print command # Or whatever code you wish to execute.
            except:
                pass

outlook = win32com.client.DispatchWithEvents("Outlook.Application", Handler_Class)

#and then an infinit loop that waits from events.
pythoncom.PumpMessages()

rawDescription: Write to a csv using Python from Microsoft Outlook 2010


code:
it = np.nditer(a, flags=['multi_index'], order='F')
while not it.finished:
    print it.multi_index, it[0]
    it.iternext()

rawDescription: numpy.ndenumerate to return indices in Fortran order?

description: Numpy.ndenumerate to return indices in Fortran order


code:
def starttoend(it):
  for line in it:
    if 'START' in line:
      yield line
      break
  for line in it:
    yield line
    if 'END' in line:
      break

l = ['asd', 'zxc', 'START123', '456789', 'qwertyEND', 'fgh', 'cvb']

i = iter(l)
for line in starttoend(i):
  print line

rawDescription: Any push back like function in python?

description: Any push back like function in python


code:
var_1 = 'I have lots of text'
var_2 = 'I have even more text'
var_3 = 'but wait there is more'

my_list = [var_1, var_2, var_3]

for var in my_list:
    x = package.function(var)
    print x

rawDescription: how to retrieve text from a variable stored in a list python

description: Retrieve text from a variable stored in a list python


code:
from pyparsing import Suppress, Word, nums, oneOf, Regex, ZeroOrMore, Optional

# define basic punctuation
EQ,LPAR,RPAR,LBRACK,RBRACK = map(Suppress,"=()[]")

# numeric values
integer = Word(nums).setParseAction(lambda t : int(t[0]))
real = Regex(r"[+-]?\d+\.\d*").setParseAction(lambda t : float(t[0]))

# id and assignment fields
idRef = LBRACK + integer("id") + RBRACK
typesep = LPAR + oneOf("D G") + RPAR
lExpr = 'L' + EQ + integer("Lint")
rExpr = 'R' + EQ + integer("Rint")
pExpr = 'p' + EQ + real("pFloat")
eExpr = 'e' + EQ + integer("Eint")
nExpr = 'n' + EQ + integer("Nint")

# accept assignments in any order, with or without leading (D) or (G)
assignment = lExpr | rExpr | pExpr | eExpr | nExpr
line = idRef + lExpr + ZeroOrMore(Optional(typesep) + assignment)

# test the parser
text = "[ 0 ] L= 9 (D) R= 14 (D) p= 0.0347222 e= 10 n= 34"
data = line.parseString(text)
print data.dump()

# prints
# [0, 'L', 9, 'D', 'R', 14, 'D', 'p', 0.034722200000000002, 'e', 10, 'n', 34]
# - Eint: 10
# - Lint: 9
# - Nint: 34
# - Rint: 14
# - id: 0
# - pFloat: 0.0347222

rawDescription: How to match a text format to a string without regex in python?

description: Match a text format to a string without regex in python


code:
import socket
print socket.gethostbyname('google.com')

rawDescription: Get IP address of url in python?

description: Get IP address of url in python


code:
import sqlite3
from PIL import Image

size = 120, 120
file = "/tmp/a.jpg"
imgobj = Image.open(file)
imgobj.thumbnail(size)

con = sqlite3.connect("/tmp/imagesdb")
cur = con.cursor()
cur.execute("create table img (x blob)")
cur.execute("insert into img(x) values(?)", [ buffer(imgobj.tostring()) ] )
con.commit()
cur.close()
con.close()

# read it back.
con = sqlite3.connect("/tmp/imagesdb")
cur = con.cursor()
row = cur.execute('SELECT * FROM img')
for item in row:
    print item #dont worry just pointers to files...
    #print item[0] # has actually binary contents.

rawDescription: Create thumbnail from image and insert in SQLite as blob


code:
from collections import defaultdict
from itertools import product

pointPairA = [(2,1), (4,8)]
pointPairB = [(3,2), (10,2), (4,2)]
tolerance = 2

dA = defaultdict(list)
tolrange = range(-tolerance, tolerance+1)
for pA, dx, dy in product(pointPairA, tolrange, tolrange):
    dA[pA[0]+dx,pA[1]+dy].append(pA)

# you would have a loop here though the 20k lists
matchedPairs = [(pA, pB) for pB in pointPairB for pA in dA[pB]]

print matchedPairs

rawDescription: A faster way of comparing two lists of point-tuples?


rawDescription: Parsing desired fields from output using regex


code:
ret = ""
string = "hello"

for i in range(len(string)):
    ret+=str(i+1) + " "

print ret

rawDescription: Print the length of strings as numbers

description: Print the length of strings as numbers


code:
print "This is a simple text editor"
from sys import argv
script, name = argv
print "You have selected the file : %s" %name
print "Opening the file...."
t = open(name, 'r+')
print "The contents of the file are"
print t.read()
t.close()  ##########
f = open(name, 'w+')
print "Now we will truncate the file and empty it of it's contents"
f.truncate()
print "Now let us write something into our file\n"
x = raw_input('What do you want to write\n') #Works fine till here
f.write(x)
f.close()  ##########
f = open(name, 'r+')  ##########
print "Now we read our file again"
print f.read()
print "And finally we close the file"
f.close()

rawDescription: Error: Getting symbols in python output

description: Error: Getting symbols in python output


code:
reportTypes = {}

for id, value in DBSession.query(TDeviceType.ixDeviceType, TDeviceType.sDeviceType):
    reportTypes.setdefault(value, []).append(id)

print reportTypes  # looks like {'test': [1, 2], 'somevalue': [3, 4]}

rawDescription: Query table for id of distinct value

description: Query table for id of distinct value


code:
import xlrd
from lxml import etree

root = etree.Element('network')
root.set('name', 'Network')
tree = etree.ElementTree(root)
name = etree.Element('nodes')
root.append(name)
wb = xlrd.open_workbook("emme_nodes1.xls")
sh = wb.sheet_by_index(0)

for row in range(1, sh.nrows):
    val = sh.row_values(row)
    element = etree.SubElement(name, 'node')
    element.set('id', str(int(val[0])))
    element.set('x', str(val[1]))
    element.set('y', str(val[2]))
print etree.tostring(root,pretty_print=True)

rawDescription: xml file from excel sheet data

description: Xml file from excel sheet data


code:
number = int(raw_input("How many numbers?"))
tot = 0

for x in range(number):
    tot += int(raw_input("Enter next number:"))
print tot

rawDescription: Python 2: adding integers in a FOR loop

description: Python 2: adding integers in a FOR loop


code:
aStr = "abcdef"
char = "e"
if aStr == '':
    return False
elif len(aStr) != 1:
    if char == aStr:
        return True
    else:
        print "Python is stupid"
        return False

rawDescription: Is it possible to put an if else statement inside an if else statement?


code:
import itertools
import random

def weighted_random(weights):
    number = random.random() * sum(weights.values())
    for k,v in weights.iteritems():
        if number < v:
            break
        number -= v
    return k

weights_a = {'1': 48,
             '0': 52}
weights_b = {'1': 53,
             '0': 50}

print "a", "b"

for i in itertools.count(5):
    print weighted_random(weights_a), weighted_random(weights_a)

rawDescription: Display (Print) with columns Python

description: Display (Print) with columns Python


code:
print "\x11"
print ["\x11"]
print repr("\x11")

rawDescription: view hexadecimal strings on python shell

description: View hexadecimal strings on python shell


code:
process = subprocess.Popen(
    cmd,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE,
    close_fds=True,
    **kw
)

while True:
    reads, _, _ = select(
        [process.stdout.fileno(), process.stderr.fileno()],
        [], []
    )

    for descriptor in reads:
        if descriptor == process.stdout.fileno():
            read = process.stdout.readline()
            if read:
                print 'stdout: %s' % read

        if descriptor == process.stderr.fileno():
            read = process.stderr.readline()
            if read:
                print 'stderr: %s' % read
        sys.stdout.flush()

    if process.poll() is not None:
        break

rawDescription: subprocess.Popen handling stdout and stderr as they come

description: Subprocess.Popen handling stdout and stderr as they come


code:
import sys
print sys.argv
module = __import__(sys.argv[1])
print module.__file__

rawDescription: python search module path script with arguments not working

description: Python search module path script with arguments not working


code:
def spawnDaemon(func):
    # do the UNIX double-fork magic, see Stevens' "Advanced
    # Programming in the UNIX Environment" for details (ISBN 0201563177)
    try:
        pid = os.fork()
        if pid > 0:
            # parent process, return and keep running
            return
    except OSError, e:
        print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    os.setsid()

    # do second fork
    try:
        pid = os.fork()
        if pid > 0:
            # exit from second parent
            sys.exit(0)
    except OSError, e:
        print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    # do stuff
    func()

    # all done
    os._exit(os.EX_OK)

rawDescription: Run a program from python, and have it continue to run after the script is killed


code:
import os
filename = "/etc/fstab"
statbuf = os.stat(filename)
print "Modification time:",statbuf.st_mtime

rawDescription: How do I get the time a file was last modified in Python?

description: Get the time a file was last modified in Python


code:
a = input("Enter the first number: ")
b = input("Enter the second number: ")
# if a is b: - Compares id's, and can cause inconsistencies. Use == instead.
if a == b:
  print "Both inputs are equal"
else:
  print "Your input is not equal."

rawDescription: Writing a program that compares 2 numbers in Python


code:
import functools
def add(x,y):
    return x + y

inc2 = functools.partial(add, 2)
print inc2(3)

rawDescription: Creating Python function with partial parameters


code:
with open(path_to_encoded_file) as encoded_file:
    print base64.b64decode(encoded_file.read().strip())

rawDescription: Decode base64 encoded file and print results to the console


code:
h = int(input("Enter height"))
b = int(input("Enter Number of Bounces"))
bounce1 = 0
bounce2 = 0
d = h * 0.6
for eachPass in range(b):
    if eachPass == 1:
        bounce1 = h + d
    if eachPass == 2:
        bounce2 = bounce1 + h + d

print str(bounce2)

rawDescription: Bouncing Ball Distance

description: Bouncing Ball Distance


code:
import csv
from collections import defaultdict

matrixDict=defaultdict(list)
with open("m.csv", "r") as confusion_data:
    reader = csv.reader(confusion_data, dialect = csv.excel, delimiter = ',')
    headers = reader.next()

    for row in reader:
        for i in range(1,len(headers)):
            matrixDict[headers[i]+row[0]] = row[i]

print matrixDict

rawDescription: create a dict or list from a matrix(csv) in python using standard libraries/modules

description: Create a dict or list from a matrix(csv) in python using standard libraries/modules


code:
import matplotlib.pyplot as plt

def handle_mouse_press( event ):
    if event.dblclick:
        print "Can haz dblclikz???"

fig = plt.figure()
fig.add_subplot(111)
fig.canvas.mpl_connect('button_press_event', handle_mouse_press)

plt.show()

rawDescription: python: how can I double left click to get a point in python

description: Python: how can I double left click to get a point in python


code:
a = (base * tax / 100)
b = (base*license /100)
c = a + b + base
d = c + dealer_prep
e = d + destination_charge

print "\nAfter taxes the price is: ", a + base
print "\nAfter taxes and license fee the price is: ", c
print "\nAfter taxes and license fee and dealer prep the price is: ", d
print "\nAfter taxes, license fees, dealer prep, and destination charge, the total price is: ", e

raw_input("\nPress the enter key to close the window.")

rawDescription: in Python how do I print the result of a calculation and then save the result to a variable?

description: In Python how do I print the result of a calculation and then save the result to a variable


code:
#!/usr/bin/env python
import Queue
import threading
import urllib2
import time

input_file = 'proxylist.txt'
threads = 10

queue = Queue.Queue()
output = []

class ThreadUrl(threading.Thread):
    """Threaded Url Grab"""
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue

    def run(self):
        while True:
            #grabs host from queue
            proxy_info = self.queue.get()

            try:
                proxy_handler = urllib2.ProxyHandler({'http':proxy_info})
                opener = urllib2.build_opener(proxy_handler)
                opener.addheaders = [('User-agent','Mozilla/5.0')]
                urllib2.install_opener(opener)
                req = urllib2.Request("http://www.google.com")
                sock=urllib2.urlopen(req, timeout= 7)
                rs = sock.read(1000)
                if '<title>Google</title>' in rs:
                    output.append(('0',proxy_info))
                else:
                    raise "Not Google"
            except:
                output.append(('x',proxy_info))
            #signals to queue job is done
            self.queue.task_done()

start = time.time()
def main():

    #spawn a pool of threads, and pass them queue instance
    for i in range(5):
        t = ThreadUrl(queue)
        t.setDaemon(True)
        t.start()
    hosts = [host.strip() for host in open(input_file).readlines()]
    #populate queue with data
    for host in hosts:
        queue.put(host)

    #wait on the queue until everything has been processed
    queue.join()

main()
for proxy,host in output:
    print proxy,host

print "Elapsed Time: %s" % (time.time() - start)

rawDescription: python proxy list check

description: Python proxy list check


code:
def ix(self, dic, n): #don't use dict as  a variable name
   try:
       return list(dic)[n] # or sorted(dic)[n] if you want the keys to be sorted
   except IndexError:
       print 'not enough keys'

rawDescription: How to extract nth key in a python dictionary?

description: Extract nth key in a python dictionary


code:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig1 = plt.figure()
ax = plt.subplot(1,1,1)
times = [0, 1, 2, 3, 4]
handle = {}
for t in times:
    if t % 2 == 0:
        color="blue"
    else:
        color="green"
    handle[color] = ax.add_patch(patches.Rectangle((t, 0.5), 0.1, 0.1,
                                   facecolor=color,
                                   label=color))
plt.xlim(times[0], times[-1] + 0.1)
print handle
plt.legend([handle['blue'],handle['green']],['MyBlue','MyGreen'])
plt.show()

rawDescription: Customizing legend in matplotlib

description: Customizing legend in matplotlib


code: print time.strftime("%a %b %d %H:%M:%S %Z %Y")

rawDescription: date format with timezone

description: Date format with timezone


code:
import dbus
import subprocess
import os
import sys
import time

SYSTEMD_BUSNAME = 'org.freedesktop.systemd1'
SYSTEMD_PATH = '/org/freedesktop/systemd1'
SYSTEMD_MANAGER_INTERFACE = 'org.freedesktop.systemd1.Manager'
SYSTEMD_UNIT_INTERFACE = 'org.freedesktop.systemd1.Unit'

bus = dbus.SystemBus()

proxy = bus.get_object('org.freedesktop.PolicyKit1', '/org/freedesktop/PolicyKit1/Authority')
authority = dbus.Interface(proxy, dbus_interface='org.freedesktop.PolicyKit1.Authority')
system_bus_name = bus.get_unique_name()

subject = ('system-bus-name', {'name' : system_bus_name})
action_id = 'org.freedesktop.systemd1.manage-units'
details = {}
flags = 1            # AllowUserInteraction flag
cancellation_id = '' # No cancellation id

result = authority.CheckAuthorization(subject, action_id, details, flags, cancellation_id)

if result[1] != 0:
    sys.exit("Need administrative privilege")

systemd_object = bus.get_object(SYSTEMD_BUSNAME, SYSTEMD_PATH)
systemd_manager = dbus.Interface(systemd_object, SYSTEMD_MANAGER_INTERFACE)

unit = systemd_manager.GetUnit('cups.service')
unit_object = bus.get_object(SYSTEMD_BUSNAME, unit)
#unit_interface = dbus.Interface(unit_object, SYSTEMD_UNIT_INTERFACE)

#unit_interface.Stop('replace')
systemd_manager.StartUnit('cups.service', 'replace')

while list(systemd_manager.ListJobs()):
    time.sleep(2)
    print 'there are pending jobs, lets wait for them to finish.'

prop_unit = dbus.Interface(unit_object, 'org.freedesktop.DBus.Properties')

active_state = prop_unit.Get('org.freedesktop.systemd1.Unit', 'ActiveState')

sub_state = prop_unit.Get('org.freedesktop.systemd1.Unit', 'SubState')

print active_state, sub_state

rawDescription: process management with python: execute service or systemd or init.d script

description: Process management with python: execute service or systemd or init.d script


code:
import avl

class Item(object):
    def __init__(self, value, id):
        self.value = value
        self.id = id

item1 = Item(1,'b42b00d6-76c8-4d68-b22e-ff4653bb01c8')
item2 = Item(2,'60eda62f-f05d-4134-9e92-9bb9a1f52daf')
item3 = Item(2,'77d9a028-bd4b-4634-b230-234f88ff010a')
item4 = Item(3,'7e7118cd-7145-41c8-8413-79670bdc81dc')

myList = avl.new()
myList.insert(item2)
myList.insert(item1)
myList.insert(item3)
myList.insert(item4)

# Correctly ordered by the first element
for item in myList:
    print "%s %s" % (item.value, item.id)

# But I also need to index by the second element.
# So:

listIndexedBySecondElement = {}
listIndexedBySecondElement[item1.id] = item1
listIndexedBySecondElement[item2.id] = item2
listIndexedBySecondElement[item3.id] = item3
listIndexedBySecondElement[item4.id] = item4

item = listIndexedBySecondElement['7e7118cd-7145-41c8-8413-79670bdc81dc']
print item.value # correctly prints 3

# Now I need to delete an element.

itm = listIndexedBySecondElement['60eda62f-f05d-4134-9e92-9bb9a1f52daf']
del listIndexedBySecondElement['60eda62f-f05d-4134-9e92-9bb9a1f52daf']
myList.remove(itm)

rawDescription: In python, how do I make a collection that is sorted by one value, and indexable by another


rawDescription: Old style python formatting issues

description: Old style python formatting issues


code:
import pytz
def utctime(self,times):
        '''
        transform local time to utc time
        :param times:
        :return:
        '''
        try:
            utc = pytz.utc
            cmd = "cat /etc/sysconfig/clock|cut -d = -f 2"
            out,err,stat = exec_shell(cmd)
            now_utc = out.read().strip()
            fmt = '%Y-%m-%d %H:%M:%S'
            amsterdam = pytz.timezone(now_utc)
            dt = datetime.datetime.strptime(times, fmt)
            am_dt = amsterdam.localize(dt)
            utc_time = am_dt.astimezone(utc).strftime(fmt)
        except Exception,err:
            utc_time = 1
            dlog("utctime err:%s"%err)
        return utc_time

rawDescription: why I can not find out the data which insert in influxdb within 5 hours

description: Why I can not find out the data which insert in influxdb within 5 hours


code:
class A(object):
    def __new__(cls, param):
        return B.__new__(cls, param + 100)
class B(A):
    def __new__(cls, param):
        b = object.__new__(B)
        b.__init__(param)
        return b
    def __init__(self, param):
        if hasattr(self, 'param'):
            print "skipping __init__", self
            return
        self.param = param
print A(5).param

rawDescription: Python inspect iterable in __new__ method


code:
class Test(object):

    def __init__(self, x, y, z):
        self.x = x
        self.y = y
        self.z = z

@jit(float(float))
def runTest(z):
    N = 1000000
    z = 0
    for i in xrange(N):
        z = z + np.sin(i)
    return z

if __name__ == '__main__':
    a = Test(4,5,6)

    start_time = time()
    z = runTest(a.z)
    end_time = time() # Get the CPU end time
    print("Math Time: {0} s".format(end_time - start_time))
    print z

rawDescription: NumbaPro JIT a class constructor

description: NumbaPro JIT a class constructor


code:
import subprocess

with open("hostlist.txt", "r") as hostlist, open("results.txt", "a") as output:
    for host in hostlist:
        host = host.strip()

        print "Tracing", host

        trace = subprocess.Popen(["tracert", "-w", "100", host], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

        while True:
            hop = trace.stdout.readline()

            if not hop: break

            print '-->', hop.strip()
            output.write(hop)

        # When you pipe stdout, the doc recommends that you use .communicate()
        # instead of wait()
        # see: http://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait
        trace.communicate()

rawDescription: traceroute multiple hos python. (reading .txt line by line)

description: Traceroute multiple hos python. (reading .txt line by line)


code:
import uwsgi, os
from flask import Flask
app = Flask('demo')

@app.route('/')
def index():
    return "Hello World"

def callback():
    print "Worker %i exinting" % os.getpid()
uwsgi.atexit = callback

rawDescription: flask\werkzeug: intercept a worker termination

description: Flask\werkzeug: intercept a worker termination


code:
from threading import Thread
import time
import sys

usb_device = 0

def usb_dump():
    for i in range(100):
        time.sleep(0.001)
        print "dumping usb"

class DumpThread(Thread):
    def run(self):
        usb_dump()

t = DumpThread()
t.start()
print "Sleep 1"
time.sleep(1)
print "End"
sys.exit(0)

rawDescription: Scheduling issues in python

description: Scheduling issues in python


code:
import sys

class Tree:
    def __init__(self, v, l=None, r=None):
        self.v = v
        self.l = l
        self.r = r

    def get_inorder_tree(self):
        if not self:
            return

        if self.l:
            for node in self.l.get_inorder_tree():
                yield node
        yield self
        if self.r:
            for node in self.r.get_inorder_tree():
                yield node

    def convert_to_doubly_ll(self):
        prev = None

        for node in self.get_inorder_tree():
            node.l = prev
            if prev is None:
                head = node
            else:
                prev.r = node
            prev = node
        return head

    def print_doubly_ll(self):
        print self.v
        if self.r is not None:
            self.r.print_doubly_ll()

def main():
    a = Tree(1)
    b = Tree(4)
    c = Tree(6)
    d = Tree(8)
    e = Tree(2, a)
    f = Tree(3, e, b)
    g = Tree(7, c, d)
    h = Tree(5, f, g)

    head = h.convert_to_doubly_ll()
    head.print_doubly_ll()

if __name__ == "__main__":
    main()

rawDescription: Static Variable issue in python when converting Binary tree to doubly linked list


code:
import urllib2
from bs4 import BeautifulSoup # latest version bs4

soup = BeautifulSoup(urllib2.urlopen("http://music.cbc.ca/The-Signal").read(), 'lxml')

song = soup.find_all("span", {'class': 'logTrackTitle'})

print song

rawDescription: Scraping music playlist info from a website


code:
def destruct_directed_run(num_set, start, direction):
  while start in num_set:
    num_set.remove(start)
    start += direction
  return start

def destruct_single_run(num_set):
  arbitrary_member = iter(num_set).next()
  bottom = destruct_directed_run(num_set, arbitrary_member, -1)
  top = destruct_directed_run(num_set, arbitrary_member + 1, 1)
  return range(bottom + 1, top)

def max_run(data_set):
  nums = set(data_set)
  best_run = []
  while nums:
    cur_run = destruct_single_run(nums)
    if len(cur_run) > len(best_run):
      best_run = cur_run
  return best_run

def test_max_run(data_set, expected):
  actual = max_run(data_set)
  print data_set, actual, expected, 'Pass' if expected == actual else 'Fail'

print test_max_run([10,21,45,22,7,2,67,19,13,45,12,11,18,16,17,100,201,20,101], range(16, 23))
print test_max_run([1,2,3], range(1, 4))
print max_run([1,3,5]), 'any singleton output fine'

rawDescription: Longest Consecutive Sequence in an Unsorted Array


code:
dll.myfunction.restype = c_char_p
str_p = dll.myfunction(42)
print str_p

rawDescription: How to display a string at a certain address with ctypes

description: Display a string at a certain address with ctypes


code:
import math

x_station = range(1,100)
y_station = range(1,100)
xpt_grid = range(1,23)
ypt_grid = range(1,29)

stat_to_grid_dist = []
for a in xrange(99):
    stat_to_grid_dist_colm = []
    for k in xrange(22):
        stat_to_grid_dist_row = []
        for l in xrange(28):
            stat_to_grid_dist_row.append(
            math.sqrt(math.pow(x_station[a]-xpt_grid[k],2) +
            math.pow(y_station[a]-ypt_grid[l],2)))
        stat_to_grid_dist_colm.append(stat_to_grid_dist_row)
    stat_to_grid_dist.append(stat_to_grid_dist_colm)
    print a

rawDescription: For loop only goes through one iteration in python


code:
from nltk.util import ngrams
sentence = 'this is a foo bar sentences and i want to ngramize it'
n = 6
sixgrams = ngrams(sentence.split(), n)
for grams in sixgrams:
  print grams

rawDescription: n-grams in python, four, five, six grams?

description: N-grams in python, four, five, six grams


code:
class A(object):
    @classmethod
    def do_your_stuff(cls):
        print 'This is A'

class B(A):
    @classmethod
    def do_your_stuff(cls):
        super(B, cls).do_your_stuff()

B.do_your_stuff()

rawDescription: Using super with a class method

description: Using super with a class method


code:
import code

class PythonInterpreter(code.InteractiveInterpreter):
    def __init__(self, localVars):
        self.runResult = ''
        print 'init called'
        code.InteractiveInterpreter.__init__(self, localVars)

    def write(self, data):
        # since sys.stdout is probably redirected,
        # we can't use print
        sys.__stdout__.write('write called\n')
        self.runResult = data

    def runcode(cd):
        # redirecting stdout to our method write before calling code cd
        sys.stdout = self
        code.InteractiveInterpreter.runcode(self,cd)
        # redirecting back to normal stdout
        sys.stdout = sys.__stdout__

rawDescription: write() not called when subclassing code.InteractiveInterpreter

description: Write() not called when subclassing code.InteractiveInterpreter


code:
for i in range(1, 10):
    for j in "abcdefghijklmnopqrstuvwxyz":
        print j * i

rawDescription: Python, print a letter n times on an nth iteration


code:
if myword in listeWord:
    print myword

rawDescription: python find exact string

description: Python find exact string


code:
def check(n):
  s=0
  for i in xrange(1,n/2+1):
    if n%i==0:
      s+=i
  return s>n

l=28123 # upper bound of a number that is not the sum of 2 abundant numbers
sieve=[False]*l # sieve[i] == True means i IS the sum of 2 abundant numbers

abundant=[]
for i in xrange(12,l):
  if check(i):
    abundant.append(i)

for i in xrange(len(abundant)): # ranges here are such that you don't forget something like 2*abundant[-1]
  for j in xrange(i,len(abundant)):
    if abundant[i]+abundant[j]<l:
      sieve[abundant[i]+abundant[j]]=True

print sum([i for i in xrange(len(sieve)) if not(sieve[i])])

rawDescription: logical error project euler 23?

description: Logical error project euler 23


code:
subject = []
for word in result:
    print word
    if isinstance(word, nltk.tree.Tree):
        if word.label() == 'Subject':
            subject.append(word)

# Sentence returned multiple subjects, including direct object, so draw first one
subject[0].draw()

rawDescription: How can I print the subject of a text

description: Print the subject of a text


code:
from bs4 import BeautifulSoup
import requests

url = 'http://financials.morningstar.com/ratios/r.html?t=AMD'
keystat_url = 'http://financials.morningstar.com/financials/getKeyStatPart.html'

with requests.Session() as session:
    session.headers = {'User-Agent': 'Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'}

    # visit the target url
    session.get(url)

    params = {
        'callback': '',
        't': 'XNAS:AMD',
        'region': 'usa',
        'culture': 'en-US',
        'cur': '',
        'order': 'asc',
        '_': '1426047023943'
    }
    response = session.get(keystat_url, params=params)

    # get the HTML part from the JSON response
    soup = BeautifulSoup(response.json()['componentData'])

    # grab the data
    for row in soup.select('div#tab-growth table tr'):
        print row.text

rawDescription: Scraping a website with clickable content in Python


code:
d = {'s1':'before','s2':'before'}

for k in d.keys():
    print d[k]

for k in d.keys():
    d[k] = 'after'
    print d[k]

rawDescription: best way to update values of outer-scope variables from within a for-loop?

description: Update values of outer-scope variables from within a for-loop


code:
variable = sys.argv
print variable

rawDescription: Parse command line argument

description: Parse command line argument


code:
lastLocation = None
lastTime = None
skip = False

bestLocation = None
bestTime = None

for line in text.split('\n'):
    line.find('Location')
    if line.find('Location') == 0:
        # Build Location
        skip = False
        print "  Found Build location"
        lastLocation = line.split(":")[1].lstrip()
    elif line.find('Status') == 0:
        # Status
        print "  Found Status"
        status = line.split(":")
        status1 = status[1].strip()
        if status1 != "Approved":
            skip = True
    elif line.find('BuildDate') == 0 and not skip:
        # Main Make
        print "  Found BuildDate"
        timeStr = line.split(":", 1)[1].lstrip()
        lastTime = datetime.datetime.strptime(timeStr, "%m/%d/%Y %H:%M:%S")
        if bestTime == None or bestTime < lastTime:
            bestTime = lastTime
            bestLocation = lastLocation
print lastLocation

rawDescription: Python:How to implement getting the latest location


code:
n = 600851475143
i = 2
while i * i < n:
    while n % i == 0:
        n = n / i
    i = i + 1
print n

rawDescription: Project Euler #3 with python - MOST EFFICIENT METHOD


code:
import urllib
import urllib2

def latex2svg(latexcode):
    """
    Turn LaTeX string to an SVG formatted string using the online SVGKit
    found at: http://svgkit.sourceforge.net/tests/latex_tests.html
    """
    txdata = urllib.urlencode({"latex": latexcode})
    url = "http://svgkit.sourceforge.net/cgi-bin/latex2svg.py"
    req = urllib2.Request(url, txdata)
    return urllib2.urlopen(req).read()

print latex2svg("2+2=4")
print latex2svg("\\frac{1}{2\\pi}")

rawDescription: converting a latex code to mathml or svg code in python

description: Converting a latex code to mathml or svg code in python


code:
import socket    # used for TCP/IP communication

# Prepare for transmission
TCP_IP = 'ip.com'
TCP_PORT = 10000
BUFFER_SIZE = 1024

#Log in as user "test" password "test" and run "/stats"
MESSAGE = '\r\n'

# Open socket, send message, close socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
print "Connected\n"
s.send(MESSAGE)
print "Message Sent\n"
data = s.recv(BUFFER_SIZE)
print "Data Recvd:\n"
print data
#ADDED THESE LINES AS WELL
s.send("test\r\n")
data = s.recv(BUFFER_SIZE)
print "Data Recvd:\n"
print data
s.close()
print "Socket closed"

rawDescription: Simple Python TCP IP script but won't return data


code:
def hide_word(word, letters=[]):
    letters = map(str.lower, letters)
    word = word.lower()
    print ''.join((letter if letter in letters else '_ ' for letter in word))

hide_word('hiddenword', ['i','d','n']) #_ idd_ n_ _ _ d

rawDescription: How to replace an '_' in a list with a letter corresponding to an earlier list

description: Replace an '_' in a list with a letter corresponding to an earlier list


rawDescription: Converting a raw input in python to a list of lists


code:
df=pd.read_csv("f.csv")
df['DATE']=pd.to_datetime(df['DATE'])
print df.dtypes

rawDescription: pandas read csv normalizing dates with python3

description: Pandas read csv normalizing dates with python3


code:
import sys, time

for i in xrange(0, 101, 10):
  print '\r>> You have finished %d%%' % i,
  sys.stdout.flush()
  time.sleep(2)
print

rawDescription: How to reset cursor to the beginning of the same line in Python

description: Reset cursor to the beginning of the same line in Python


code:
repeats = int(raw_input("How many repetitions? "))
for i in range(repeats):
    print "I will read a Python tutorial!"

rawDescription: Repeating a line in Python

description: Repeating a line in Python


code:
s = "abbcddeeffffcccddddggggghhhiaajjjkk"
for x in sorted(set(s)):
  i = 1;
  while x * i in s:
    i += 1
  print x, "-", i - 1

rawDescription: Given a string, find out the highest repeated characters count in python


code:
import numpy
from scipy.signal import fftconvolve

def ssim(im1, im2, window, k=(0.01, 0.03), l=255):
    """See https://ece.uwaterloo.ca/~z70wang/research/ssim/"""
    # Check if the window is smaller than the images.
    for a, b in zip(window.shape, im1.shape):
        if a > b:
            return None, None
    # Values in k must be positive according to the base implementation.
    for ki in k:
        if ki < 0:
            return None, None

    c1 = (k[0] * l) ** 2
    c2 = (k[1] * l) ** 2
    window = window/numpy.sum(window)

    mu1 = fftconvolve(im1, window, mode='valid')
    mu2 = fftconvolve(im2, window, mode='valid')
    mu1_sq = mu1 * mu1
    mu2_sq = mu2 * mu2
    mu1_mu2 = mu1 * mu2
    sigma1_sq = fftconvolve(im1 * im1, window, mode='valid') - mu1_sq
    sigma2_sq = fftconvolve(im2 * im2, window, mode='valid') - mu2_sq
    sigma12 = fftconvolve(im1 * im2, window, mode='valid') - mu1_mu2

    if c1 > 0 and c2 > 0:
        num = (2 * mu1_mu2 + c1) * (2 * sigma12 + c2)
        den = (mu1_sq + mu2_sq + c1) * (sigma1_sq + sigma2_sq + c2)
        ssim_map = num / den
    else:
        num1 = 2 * mu1_mu2 + c1
        num2 = 2 * sigma12 + c2
        den1 = mu1_sq + mu2_sq + c1
        den2 = sigma1_sq + sigma2_sq + c2
        ssim_map = numpy.ones(numpy.shape(mu1))
        index = (den1 * den2) > 0
        ssim_map[index] = (num1[index] * num2[index]) / (den1[index] * den2[index])
        index = (den1 != 0) & (den2 == 0)
        ssim_map[index] = num1[index] / den1[index]

    mssim = ssim_map.mean()
    return mssim, ssim_map

def nrmse(im1, im2):
    a, b = im1.shape
    rmse = numpy.sqrt(numpy.sum((im2 - im1) ** 2) / float(a * b))
    max_val = max(numpy.max(im1), numpy.max(im2))
    min_val = min(numpy.min(im1), numpy.min(im2))
    return 1 - (rmse / (max_val - min_val))

if __name__ == "__main__":
    import sys
    from scipy.signal import gaussian
    from PIL import Image

    img1 = Image.open(sys.argv[1])
    img2 = Image.open(sys.argv[2])

    if img1.size != img2.size:
        print "Error: images size differ"
        raise SystemExit

    # Create a 2d gaussian for the window parameter
    win = numpy.array([gaussian(11, 1.5)])
    win2d = win * (win.T)

    num_metrics = 2
    sim_index = [2 for _ in xrange(num_metrics)]
    for band1, band2 in zip(img1.split(), img2.split()):
        b1 = numpy.asarray(band1, dtype=numpy.double)
        b2 = numpy.asarray(band2, dtype=numpy.double)
        # SSIM
        res, smap = ssim(b1, b2, win2d)

        m = [res, nrmse(b1, b2)]
        for i in xrange(num_metrics):
            sim_index[i] = min(m[i], sim_index[i])

    print "Result:", sim_index

rawDescription: Comparing image in url to image in filesystem in python


code:
from random import randrange

fruits = ['banana', 'apple',  'mango']
randomOffset = randrange(0,len(fruits))
for i in range(len(fruits)):
   print fruits[i - randomOffset]

rawDescription: Array index start random in Python

description: Array index start random in Python


code:
from collections import Counter
from itertools import groupby

l = [1,2,3,3,3,4,4,4,5,5,6,6,6]

# group most_common output by frequency
freqs = groupby(Counter(l).most_common(), lambda x:x[1])
# pick off the first group (highest frequency)
print [val for val,count in freqs.next()[1]]
# prints [3, 4, 6]

rawDescription: How to produce multiple modes in Python?

description: Produce multiple modes in Python


code:
import sys, subprocess

# Note the 0 here (unbuffered file)
sys.stdout = open("mylog","w",0)

print "Hello"
print "-----"

subprocess.call(["./prog"],stdout=sys.stdout, stderr=sys.stdout)
print "-----"
subprocess.call(["./prog"],stdout=sys.stdout, stderr=sys.stdout)
print "-----"

print "End"

rawDescription: python script using subprocess, redirect ALL output to file

description: Python script using subprocess, redirect ALL output to file


code:
class change_mro_meta(type):
    def __new__(cls, cls_name, cls_bases, cls_dict):
        out_cls = super(change_mro_meta, cls).__new__(cls, cls_name, cls_bases, cls_dict)
        out_cls.change_mro = False
        out_cls.hack_mro   = classmethod(cls.hack_mro)
        out_cls.fix_mro    = classmethod(cls.fix_mro)
        out_cls.recalc_mro = classmethod(cls.recalc_mro)
        return out_cls

    @staticmethod
    def hack_mro(cls):
        cls.change_mro = True
        cls.recalc_mro()

    @staticmethod
    def fix_mro(cls):
        cls.change_mro = False
        cls.recalc_mro()

    @staticmethod
    def recalc_mro(cls):
        # Changing a class' base causes __mro__ recalculation
        cls.__bases__  = cls.__bases__ + tuple()

    def mro(cls):
        default_mro = super(change_mro_meta, cls).mro()
        if hasattr(cls, "change_mro") and cls.change_mro:
            return default_mro[1:2] + default_mro
        else:
            return default_mro

class A(object):
    def __init__(self):
        print "__init__ A"
        self.hello()

    def hello(self):
        print "A hello"

class B(A):
    __metaclass__ = change_mro_meta
    def __init__(self):
        self.hack_mro()
        super(B, self).__init__()
        self.fix_mro()
        print "__init__ B"
        self.msg_str = "B"
        self.hello()

    def hello(self):
        print "%s hello" % self.msg_str

a = A()
b = B()

rawDescription: Change python mro at runtime

description: Change python mro at runtime


code:
import time
pf = False   #check if pixel was found
start_time = time.time()

def game_one():
    box = (x_pad+1, y_pad+1, x_pad+1179, y_pad+474)
    im = ImageGrab.grab(box)
    # return im
    rgb_im = im.convert('RGB')
    while (pf == False) and ((time.time()-start_time) < 120):
        for x in range(1055, 1120, 1):
            if pf == True:
                break
            for y in range(20, 464, 1):
                pix = rgb_im.getpixel((x, y))
                if pix != (255,0,255):
                    startPlaying()
                    time.sleep(.2)
                    clickbuttonone()
                    print "Pixel Found!"
                    pf = True
                    break
                else:
                    print "Waiting for pixel to appear"

rawDescription: How can I look for a certain pixel colour on my screen, in a specific area using Python's PIL?

description: Look for a certain pixel colour on my screen, in a specific area using Python's PIL


code:
csv_f = pd.read_csv('test.csv', header=None)
print csv_f

rawDescription: Python Pandas read_csv reads only single line from CSV file


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

rawDescription: Printing array of strings without delimiters (brackets, quotes and commas)


code:
fileName = '[abc][def]Real Name[!].exe'
name = re.search('(\[[^]]*\])*([\w\s]+)', fileName).group(2)
print name

rawDescription: Regex to not match anything in brackets, only letters, numbers and spaces, and nothing after a dot


code:
PATH_CELL = 'the path you individuate in document.xml'

docbody = document.xpath('/w:document/w:body'+PATH_CELL,
namespaces=nsprefixes)[0]

print 'Replacing ...',
docbody = replace(docbody,'Welcome','Hello')

rawDescription: How change table contents and style using python-docx?


code:
class MyDecorator(object):
    def __init__(self, *args, **kwargs):
        if kwargs:
            # arguments
            print 'got %r as arguments'
        else:
            callable, = args

@MyDecorator(some_function=lambda x:2*x)
def foo():
    pass

rawDescription: Python decorator with optional callable argument


rawDescription: Python print skip arguments

description: Python print skip arguments


code:
import sys, argparse

def main(argv=None):

    if argv is None:
        argv=sys.argv[1:]

    p = argparse.ArgumentParser(description="Example of using argparse")

    p.add_argument('--arg1', action='store', default='hello', help="first word")
    p.add_argument('--arg2', action='store', default='world', help="second word")

    # Parse command line arguments
    args = p.parse_args(argv)

    print args.arg1, args.arg2

    return 0

if __name__=="__main__":
    sys.exit(main(sys.argv[1:]))

rawDescription: groking command line parameters in a python script

description: Groking command line parameters in a python script


code:
from collections import namedtuple
SomeClass = namedtuple('Name of class', ['variableX', 'variableY'], verbose=True)
myObject = SomeClass("value", 120)

print myObject.variableX

rawDescription: Object initializer syntax (c#) in python?


code: print lxml.html.tostring(el)

rawDescription: python, lxml and how to get html code from subset

description: Python, lxml and how to get html code from subset


code:
import urllib2

def get_anon_content(url):
    anon_url = 'http://anonymouse.org/cgi-bin/anon-www.cgi/%s' % url
    req = urllib2.Request(anon_url)
    response = urllib2.urlopen(req)
    content = response.read()
    return content

url = 'http://www.google.ca'
print get_anon_content(url)

rawDescription: Can't post to proxy form

description: Can't post to proxy form


code:
h = response.hits[0]
print h['@timestamp']

rawDescription: python elasticsearch-dsl @timestamp in response

description: Python elasticsearch-dsl @timestamp in response


code:
import Queue
import threading
import time
import urllib2

my_sites = [
    'http://news.ycombinator.com',
    'http://news.google.com',
    'http://news.yahoo.com',
    'http://www.cnn.com'
    ]

# Create a queue for our processing
queue = Queue.Queue()

class MyThread(threading.Thread):
  """Create a thread to make the url call."""

  def __init__(self, queue):
    super(MyThread, self).__init__()
    self.queue = queue

  def run(self):
    while True:
      # Grab a url from our queue and make the call.
      my_site = self.queue.get()
      url = urllib2.urlopen(my_site)

      # Grab a little data to make sure it is working
      print url.read(1024)

      # Send the signal to indicate the task has completed
      self.queue.task_done()

def main():

  # This will create a 'pool' of threads to use in our calls
  for _ in range(4):
    t = MyThread(queue)

    # A daemon thread runs but does not block our main function from exiting
    t.setDaemon(True)

    # Start the thread
    t.start()

  # Now go through our site list and add each url to the queue
  for site in my_sites:
    queue.put(site)

  # join() ensures that we wait until our queue is empty before exiting
  queue.join()

if __name__ == '__main__':
  start = time.time()
  main()
  print 'Total Time: {0}'.format(time.time() - start)

rawDescription: scan websites for content (fast)

description: Scan websites for content (fast)


code:
from django.template import Context, Template

template = Template("this is a template string! {{ foo }}")
c = Context({"foo": "barbarbar"})
print template.render(c)

rawDescription: Invoke Django template renderer in memory without any files from strings?


code:
import struct
import os
import hashlib

def png(fh):
    hash = hashlib.md5()
    assert fh.read(8)[1:4] == "PNG"
    while True:
        try:
            length, = struct.unpack(">i",fh.read(4))
        except struct.error:
            break
        if fh.read(4) == "IDAT":
            hash.update(fh.read(length))
            fh.read(4) # CRC
        else:
            fh.seek(length+4,os.SEEK_CUR)
    print "Hash: %r" % hash.digest()

def jpeg(fh):
    hash = hashlib.md5()
    assert fh.read(2) == "\xff\xd8"
    while True:
        marker,length = struct.unpack(">2H", fh.read(4))
        assert marker & 0xff00 == 0xff00
        if marker == 0xFFDA: # Start of stream
            hash.update(fh.read())
            break
        else:
            fh.seek(length-2, os.SEEK_CUR)
    print "Hash: %r" % hash.digest()

if __name__ == '__main__':
    png(file("sample.png"))
    jpeg(file("sample.jpg"))

rawDescription: Compute hash of only the core image data (excluding metadata) for an image


code:
class _401(HTTPUnauthorized):

    @classmethod
    def basic_jwt_header(cls):
        ret = cls()
        ret.headers.add('WWW-Authenticate','JWT')
        ret.headers.add('WWW-Authenticate', 'Basic realm="Please log in"')
        return ret

    @classmethod
    def jwt_header(cls):
        ret = cls()
        ret.headers.add('WWW-Authenticate','JWT')
        return ret

resp = _401.basic_jwt_header()
print resp.headers

rawDescription: Best practice for repeatedly initializing a class with identical parameters (Pyramid)?


code:
def calculateFathersDayPrice(price, isMember):
    if isMember:
        return price * 0.85
    return price * 0.95

price = float(raw_input("Please Enter Price of Item: "))
isMember = raw_input("Are you a member?: ").lower() in ['true', '1', 't', 'y', 'yes']

print 'Member Status: %s' % isMember
print 'Price: %.2f' % calculateFathersDayPrice(price, isMember)

rawDescription: Python function that calculates membership price


code:
with open('data.txt','rb') as f1:
    reader = csv.reader(f1, delimiter='\t')
    for group, rows in groupby(reader, itemgetter(0)):
        best = max(rows, key=lambda r: (float(r[4]), float(r[2])))
        print best

rawDescription: How to sort by two lines and print the line with the highest value

description: Sort by two lines and print the line with the highest value


code:
f = csv.reader(open('genotypes.csv','rbU'))
key_index = 22  # assuming that this column contains something like 'CASE156'
for rownum, row in enumerate(f):
    if row[key_index] == 'CASE156':
         print row[16]

rawDescription: Python csv - match a specific row and column, and pipe to new file


code:
from PIL import Image, ImageOps
import math

src = Image.open('arched.jpg')

ampl = step = 10

img = ImageOps.expand(src, border=ampl*4, fill='white')
size = img.size

straight_mesh = {}
distorted_mesh = {}
for y in range(size[1]//step-1):
    py = step*(y+1)
    dx = -int(round(ampl*math.sin(py*math.pi/size[1])))
    print dx
    for x in range(size[0]//step-1):
        px = step*(x+1)
        straight_mesh[x, y] = (px, py)
        distorted_mesh[x, y] = (px+dx, py)
transform = []
for x in range(size[0]//step-2):
    for y in range(size[1]//step-2):
        transform.append((
            map(int, straight_mesh[x, y] + straight_mesh[x+1, y+1]),
            map(int, distorted_mesh[x, y] + distorted_mesh[x, y+1] + \
                    distorted_mesh[x+1, y+1] + distorted_mesh[x+1, y])
        ))
img = img.transform(size, Image.MESH, transform, Image.BICUBIC)
img = ImageOps.crop(img, border=ampl*2)
img.save('result.jpg')

rawDescription: How to iterate over columns of an image?

description: Iterate over columns of an image


code:
import random
import pygame

WHITE = (255,255,255)
BLACK = (0  ,0  ,0  )
RED = (255,0,0)

PLAYERS = []

class Player():

    def __init__(self, image, x=0, y=0):

        self.image = pygame.image.load(image).convert_alpha() #.convert()
        #self.image.set_colorkey(WHITE)
        self.rect = self.image.get_rect()

        self.rect.centerx = x
        self.rect.centery = y

        #self.image.set_colorkey(BLACK)

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

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

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

    def update(self):
        #randomly rotate
        angle = random.randint(0,360)
        #self.image = pygame.transform.rotate(self.image, angle)
        self.image = pygame.transform.rotozoom(self.image, angle, 1)

        # here change randomly positon
        self.rect.topleft = random.randint(60,220+1), random.randint( 0, 475+1)
        searchAgain = 0
        while (searchAgain < 1):
            self.rect.topleft = random.randint(60,220+1), random.randint( 0, 475+1)
            searchAgain = 1

            for p in PLAYERS:
                # creating masks for the images
                myImage_mask = pygame.mask.from_surface(self.image)
                myOtherImage_mask = pygame.mask.from_surface(p.image)

                # this is where the images are
                myImage_rect = self.rect
                myOtherImage_rect = p.rect

                # this is where we check for pixel perfect collision
                # observe the order mask variables are used in calculating offset and in overlap method
                offset_x, offset_y = (myOtherImage_rect.left - myImage_rect.left), (myOtherImage_rect.top - myImage_rect.top)
                print (offset_x, offset_y )
                if (myImage_mask.overlap(myOtherImage_mask, (offset_x, offset_y)) != None):
                    print 'Collision Detected!'

                    #if we detect collision of players stay in the loop so that we get another pair of coordinates for the new player
                    searchAgain = 0
                else:
                    print 'None'

class Game():

    def __init__(self):

        pygame.init()

        self.screen = pygame.display.set_mode((800,600))

        self.background = pygame.image.load("background.jpg").convert()
        self.multi_players = []

        # create stimuli

        for i in range(1,10):
            player = Player("stim"+str(i)+".png")
            #player = Player("stim6.gif")
            player.update() # set random position on start
            PLAYERS.append(player)

            self.multi_players.append(player)

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

    def run(self):

        clock = pygame.time.Clock()
        RUNNING = True

        while RUNNING:

            # --- events ---

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    RUNNING = False

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        RUNNING = False

                    # changes position when key is pressed

                    for player in self.multi_players:
                        player.update()

            # --- updates ----

            # place for updates

            # --- draws ---

            self.screen.fill(WHITE)

            self.screen.blit(self.background, self.background.get_rect())

            for player in self.multi_players:
                player.draw(self.screen)

            pygame.display.flip()

            # --- FPS ---

            clock.tick(20)

        # --- quit ---

        pygame.quit()

Game().run()

rawDescription: Creating random patterns of image objects with specified minimum distance between them and random orientation


code:
import pandas as pd

#Read from Excel
xl= pd.ExcelFile("test.xls")

dfs = xl.parse(xl.sheet_names[0])
df1 = dfs[dfs['Sal'] == 1000]
df1 = df1[df1['Message']=="abc"]

ph_no = df1['Number']

print df1

rawDescription: Deleting Entire blank row in an existing Excel Sheet using Python


code:
with open("textfile.txt", "r") as f:
    searchInLines = f.readlines()
    for i, line in enumerate(searchInLines):
        if "VIRGINIA" in line:
            print searchInLines[i-3]

rawDescription: Python - Search for Keyword and Print line above


code:
def forums(d):
    dict_list = [('Subforums', 'Created by')]
    for i, (k, v) in enumerate(d.items(), 1):
        k = '{0}. {1}'.format(i, k)
        dict_list.append((k, v))

    col_width = max(len(word) for row in dict_list for word in row) + 2 # padding

    for row in dict_list:
            print ''.join(word.ljust(col_width) for word in row)

rawDescription: Python Print Formatting

description: Python Print Formatting


code:
from twisted.internet import wxreactor
from twisted.internet.protocol import DatagramProtocol

wxreactor.install()

class MyProtocol(DatagramProtocol):
    def datagramReceived(self, data, (host, port)):
        print "received %r from %s:%d" % (data, host, port)
        self.transport.write(data, (host, port))

# <GUI code>
# to start listening do port = reactor.listenUDP(<port>, MyProtocol())
# to stop do self.transport.stopListening() in MyProtocol
# or port.stopListening() from outside

from twisted.internet import reactor
reactor.registerWxApp(app)
reactor.run()

rawDescription: wxPython threaded UDP server

description: WxPython threaded UDP server


code:
class A:

    def x(self):
        #do stuff and call Class B
        n = 1
        n += B().y() #Instance B and call y method
        print n

class B:
    def y(self):
        #do stuff get results and pass results to Class A
        x = 10
        return x

a = A() #create a object with type A
a.x() #call x method of A class

rawDescription: How to use method results from one class in another

description: Use method results from one class in another


code:
def inplace(seq):
    seq[0] = 5

a = [1,2,3]
print a
inplace(a)
a

rawDescription: What does the def line do in python

description: What does the def line do in python