code:
import cv2
import numpy as np
from numpy import unravel_index
import time

img = cv2.imread('ducks.jpg')

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

print hsv.shape
hue = hsv[:, :, 0]
sat = hsv[:, :, 1]

start = time.time()
max_index = unravel_index(sat.argmax(), sat.shape)
end = time.time()
print 'argmax time:', end - start
print sat[max_index]
print hue[max_index]

start = time.time()
hist, xbins, ybins = np.histogram2d(hue.ravel(), sat.ravel(), [180, 256], [[0, 180], [0, 256]])
end = time.time()
print 'histogram2d time:', end - start

rawDescription: Fast 2d histogram in OpenCL with PyOpenCL


code:
import threading
import datetime

class ThreadClass(threading.Thread):
    def run(self):
        now = datetime.datetime.now()
        print "%s says hello, World! at time: %s"  % (self.getName(),now)

for i in range(10):
        t = ThreadClass()
        t.start()

rawDescription: synchronization across multiple processes in python

description: Synchronization across multiple processes in python


code: print zip.__doc__

rawDescription: writing multiple out files from for loop

description: Writing multiple out files from for loop


code:
#!/usr/bin/python
import collections
Job = collections.namedtuple('Job', ['title', 'salary'])
all_jobs = []
with open("jobs.txt", "r") as job_file:
    headers = job_file.readline()
    for line in job_file:
        (title, fsal) = line.rstrip().split('\t')
        fsal = float(fsal.replace('"', '').replace(',', ''))
        all_jobs.append(Job(title, fsal))
avg_salary = sum(
    job.salary for job in all_jobs) / len(all_jobs)
print "Average salary for all titles = ", avg_salary
sorted_jobs = sorted(
    all_jobs, key=lambda job: job.salary, reverse=True)
for i, j in enumerate(sorted_jobs):
    print '%i. %s \t%g' % (i + 1, j.title, j.salary)

rawDescription: Finding and sorting average in list

description: Finding and sorting average in list


code: print 'this works:', re.sub('START.*END', 'NEWTEXT', text, 0, re.DOTALL)

rawDescription: Regular expression multi-line replacement in Python


code: print "hello world"

rawDescription: In Ipython, does return statement works as Print?


code:
import urllib
import requests
import lxml
from bs4 import BeautifulSoup

def find_notes():

    data_file = open(r"C:\Users\USER_NAME\Desktop\output.txt", 'ab')

    f = requests.get('http://fullthrottleauto.tumblr.com/post/132323884114/treunenthibault-ferrari-599xx-evo-as-i-love')

    soup = BeautifulSoup(f.text, "lxml")

    for post_note in soup.find_all('a', {'rel':'nofollow'}):
        if post_note['href'].endswith('.tumblr.com/') and post_note['href'].startswith('http') :
            print post_note['href']
            data_file.write(post_note['href']+'\n')
    data_file.close()

find_notes()

rawDescription: How do I match Tumblr urls from a text file with Regex and Python

description: Match Tumblr urls from a text file with Regex and Python


code:
from bs4 import BeautifulSoup
import requests

html = requests.get('http://nz.sports.search.yahoo.com/search?p=basketball&fr=sports-nz-ss&age=1w&focuslim=age').text
soup = BeautifulSoup(html)
web_p = soup.find_all('span',class_='url')
for web in web_p:
    print web

rawDescription: Python BeautifulSoup picking webpages, same codes working on and off


code:
for k in sorted(by_categories):
    print 'category', k, 'contains:'
    for v in by_categories[k]:
        print v

rawDescription: How to use a list item to address a dictionary key and append the respective value

description: Use a list item to address a dictionary key and append the respective value


code:
class DecoratorClass(object):
    def __init__(self):
        self.thread = None
        self.lock = threading.Lock()

    def __call__(self, func, *args, **kwargs):
        def wrapped_func(*args, **kwargs):

            self.lock.acquire()

            curr_thread = threading.currentThread().getName()
            self.thread = curr_thread

            print '\nthread name before running func:', self.thread
            ret_val = func()
            print '\nthread name after running func:', self.thread
            self.lock.release()
            return ret_val

        return wrapped_func

@DecoratorClass()
def decorated_with_class():
    print 'running decorated w class'
    time.sleep(1)
    return

threads = []
for i in range(5):
    t = threading.Thread(target=decorated_with_class)
    threads.append(t)
    t.start()

rawDescription: creating a thread safe decorator class

description: Creating a thread safe decorator class


code:
print clf.get_support(indices=True)
#prints [1 2 3]

rawDescription: Find selected features by RandomizedLogisticRegression


code:
import numpy as np

# Alter dimensions as needed
x,y = 3,4

# create a default array of specified dimensions
a = np.arange(x*y).reshape(x,y)
print a
print

# a.diagonal returns the top-left-to-lower-right diagonal "i"
# according to this diagram:
#
#  0  1  2  3  4 ...
# -1  0  1  2  3
# -2 -1  0  1  2
# -3 -2 -1  0  1
#  :
#
# You wanted lower-left-to-upper-right and upper-left-to-lower-right diagonals.
#
# The syntax a[slice,slice] returns a new array with elements from the sliced ranges,
# where "slice" is Python's [start[:stop[:step]] format.

# "::-1" returns the rows in reverse. ":" returns the columns as is,
# effectively vertically mirroring the original array so the wanted diagonals are
# lower-right-to-uppper-left.
#
# Then a list comprehension is used to collect all the diagonals.  The range
# is -x+1 to y (exclusive of y), so for a matrix like the example above
# (x,y) = (4,5) = -3 to 4.
diags = [a[::-1,:].diagonal(i) for i in range(-a.shape[0]+1,a.shape[1])]

# Now back to the original array to get the upper-left-to-lower-right diagonals,
# starting from the right, so the range needed for shape (x,y) was y-1 to -x+1 descending.
diags.extend(a.diagonal(i) for i in range(a.shape[1]-1,-a.shape[0],-1))

# Another list comp to convert back to Python lists from numpy arrays,
# so it prints what you requested.
print [n.tolist() for n in diags]

rawDescription: Get all the diagonals in a matrix/list of lists in Python


code:
rx = re.compile('version\s+([\d.]+)\s+')
rxx = rx.search(results)
if rxx:
    print rxx.group(1)

rawDescription: How to match info from a string

description: Match info from a string


code:
#!/usr/bin/env python
import hashlib
import random

password = str(random.getrandbits(8000))
print hashlib.sha512(password).hexdigest()

rawDescription: bcrypt in python

description: Bcrypt in python


code:
for trans in translation['translations']:
    print trans['translatedText']

rawDescription: How to access JSON translation from Google Translate API with Python

description: Access JSON translation from Google Translate API with Python


code:
for eni in enis:
  if hasattr(eni, 'publicIp') and eni.publicIp:
    print eni.id, eni.publicIp

rawDescription: How to tell if AWS Elastic Network Interface (ENI) has a public IP address using Python boto?

description: Tell if AWS Elastic Network Interface (ENI) has a public IP address using Python boto


code:
i=0
while i < 10:
    print "This should be reprinted only ten times"
    i+=1

rawDescription: Limiting loop repetition in python

description: Limiting loop repetition in python


code:
from selenium import webdriver

case_url = "http://na.leagueoflegends.com/tribunal/en/case/5555631/#nogo"
browser = webdriver.Firefox()
browser.get(case_url)

game_tabs = browser.find_elements_by_xpath('//a[contains(@id, "tab-")]')
for index, tab in enumerate(game_tabs, start=1):
    tab.click()
    game = browser.find_element_by_id('game%d' % index)
    game_type = game.find_element_by_id('stat-type-fill').text
    game_length = game.find_element_by_id('stat-length-fill').text
    game_outcome = game.find_element_by_id('stat-outcome-fill').text

    game_chat = game.find_element_by_class_name('chat-log')
    enemy_chat = [msg.text for msg in game_chat.find_elements_by_class_name('enemy') if msg.text]
    ally_chat = [msg.text for msg in game_chat.find_elements_by_class_name('ally') if msg.text]

    print game_type, game_length, game_outcome
    print "Enemy chat: ", enemy_chat
    print "Ally chat: ", ally_chat
    print "------"

rawDescription: Getting html source when some html is generated by javascript


code:
from calendar import day_abbr
from datetime import datetime, timedelta

def solve(start, end, data):
    days = list(day_abbr)
    output = dict.fromkeys(days, 0)

    while start <= end:
        day = days[start.weekday()]
        if start.hour in data[day]:
            output[day] += 1
        start = start + timedelta(minutes=60)

    return output

data = {
 'Mon': [9, 23],
 'Thu': [12, 13, 14],
 'Tue': [11, 12, 14],
 'Wed': [11, 12, 13, 14],
 'Fri': [13],
 'Sat': [],
 'Sun': [],
}

start = datetime(2015, 7, 22, 17, 58, 54, 746784)
end = datetime(2015, 8, 30, 10, 22, 36, 363912)

print solve(start, end, data)
# {'Wed': 20, 'Sun': 0, 'Fri': 6, 'Tue': 15, 'Mon': 10, 'Thu': 18, 'Sat': 0}

rawDescription: Counting day-of-week-hour pairs between two dates


code:
import random
a_list = ['a', 'b', 'c']
b_list = ['1', '2', '3']
print [(a,random.choice(b_list)) for a in a_list]

rawDescription: Python randomly delegating values from one list to another


rawDescription: Python output complex line with floats colored by value


code:
import csv, itertools
column_names = ['id','name','amount']
source_data = csv.reader(open('foo1.csv'))
target_data = csv.reader(open('foo2.csv'))
counter = 1
def rowElementCompare(sourceRow, targetRow):
    row_length = min(len(sourceRow), len(targetRow))
    for i in range(row_length):
        if sourceRow[i] != targetRow[i]:
            print i
            yield i # UPDATED
    return # UPDATED
for source_row,target_row in itertools.izip(source_data,target_data):
    comparison_result = None
    for comparison_result in rowElementCompare(source_row, target_row): # UPDATED
        print "Mismatch in column %s on row number %d , source value %s, target value %s" % (column_names[comparison_result], counter, source_row[comparison_result], target_row[comparison_result])
    counter += 1

rawDescription: Compare two CSV files field by field and list all mismatches


code:
for line in data:
    print line

rawDescription: Python read website data line by line when available


code:
def foo(): print 'foo here!'
def bar(): print 'bar here!'

rawDescription: How do I iterate over all imported functions

description: Iterate over all imported functions


rawDescription: SQLAlchemy printing raw SQL from create()


code:
import requests

url = "http://geocoding.geo.census.gov/geocoder/locations/addressbatch"
data = {'benchmark': 'Public_AR_Census2010'}
files = {'addressFile': open('t.csv')}

response = requests.post(url, data=data, files=files)
print response.content

rawDescription: Mimic curl in python

description: Mimic curl in python


code: print dict(zip( query_as_dict['static_labels'][0].split(','), query_as_dict['static_xvalues'][0].split(',')))

rawDescription: Having trouble parsing HTML

description: Having trouble parsing HTML


code:
#!/usr/bin/python
import csv
def printresults(results):
    print ("Information Requested:\n" + results)

file = open("/tmp/csvfile.txt", "r")
reader = csv.DictReader(file, skipinitialspace=True, dialect='excel', delimiter=',')

totalfields = (len(reader.fieldnames))
result={}

for row in reader:
    resultfields = ""
    for i in range(1,totalfields):
        resultfields = resultfields + reader.fieldnames[i] + ": " + row[reader.fieldnames[i]] + "\n"
    result[row['id']] = resultfields

idvalues = ["exit", "4"]
while 1:
    idvalue = idvalues.pop() #eg.enterbox(msg=message,title='Print Results', default='', strip=True)

    if idvalue == "":
        message = "Enter id Number"

    elif idvalue =="exit":
        print "done"
        exit()

    else:
        message = result[idvalue]
        print(message)

rawDescription: Searching Python Dictionary by key value is returning multiple, consecutive results, not just 1


code:
import example
assert(6 == example.times_two(3))
print help(example.times_two)

rawDescription: Define a boost::function with a docstring (Boost::Python)


code:
def columnize(mylists, maxcolumns):
    for i in mylists:
        while len(i) < maxcolumns:
            i.insert(-1,None)

mylists = [["author1","author2","author3","this is the title of the article"],
           ["author1","author2","this is the title of the article"],
           ["author1","author2","author3","author4","this is the title of the article"]]

columnize(mylists,5)
print mylists

[['author1', 'author2', 'author3', None, 'this is the title of the article'], ['author1', 'author2', None, None, 'this is the title of the article'], ['author1', 'author2', 'author3', 'author4', 'this is the title of the article']]

rawDescription: Inserting values in a Python list

description: Inserting values in a Python list


code:
s=[{u'task': {u'url': u'http://192.168.1.1/job/f1111111111/', u'color': u'aborted', u'name': u'f1111111111'}, u'stuck': False, u'url': u'queue/item/37/', u'inQueueSince': 1397554800875L, u'actions': [{u'causes': [{u'userName': u'admin', u'userId': u'admin', u'shortDescription': u'Started by user admin'}]}], u'why': u'Waiting for next available executor on NODE_1', u'buildable': True, u'params': u'', u'buildableStartMilliseconds': 1397554800878L, u'id': 37, u'pending': False, u'blocked': False}, {u'task': {u'url': u'http://192.168.1.1/job/1234/', u'color': u'aborted', u'name': u'1234'}, u'stuck': False, u'url': u'queue/item/36/', u'inQueueSince': 1397554797741L, u'actions': [{u'causes': [{u'userName': u'admin', u'userId': u'admin', u'shortDescription': u'Started by user admin'}]}], u'why': u'Waiting for next available executor on NODE_1', u'buildable': True, u'params': u'', u'buildableStartMilliseconds': 1397554797744L, u'id': 36, u'pending': False, u'blocked': False}]
for i in s:
    print i['task']['name']

rawDescription: How to make grep using Python

description: Make grep using Python


code: print movies.data

rawDescription: How to load the datset using scikits

description: Load the datset using scikits


code:
import re
import requests

data = requests.get("http://xkcd.com/").content
pattern = re.compile(r'Permanent link to this comic: http://xkcd.com/(\d+)/')
print pattern.search(data).group(1)

rawDescription: How can I dependably web-scrape a largely unattached line effectively?

description: Dependably web-scrape a largely unattached line effectively


code:
import bisect

places = [
    (501, 'ASIA'),
    (1262, 'EUROPE'),
    (3389, 'LATAM'),
    (5409, 'US'),
]
places.sort() # list must be sorted

for to_find in (389, 1300, 5400):
    pos = bisect.bisect_right(places, (to_find,))
    print '%s -> %s' % (to_find, places[pos])

rawDescription: Find value within a range in lookup table


code: listOfPlayers.sort(key=lambda (name, pos, cost, pts): float(cost)/pts, reverse=True)

rawDescription: Python Sorting lists by value

description: Python Sorting lists by value


code:
while True:
    try:
        time.sleep(3)
        print "Zzzz"
        time.sleep(3)
        print("gong!")
    except KeyboardInterrupt as e:
        print "Closed by an Interrupt"
        break

rawDescription: Keyboard interrupt in debug mode PyCharm


code:
def binary(n):
  if n < 2:
    print n
  else:
    binary(n / 2)
    print n % 2

binary(0)
binary(1)
binary(3)
binary(9)
binary(10)

rawDescription: Recursive function that prints the binary representation of the integer


code:
NUM_COLUMN = 4
NUM_ROW = 2
NUM_MATRIX = 3
mtx = [[0.0 for x in range(NUM_COLUMN)] for x in range(NUM_ROW)]
arrMtx = [mtx for x in range(NUM_MATRIX)]
print arrMtx

rawDescription: Declare array of matrix in python

description: Declare array of matrix in python


code:
import difflib

list_1 = ['J. Payne', 'George Bush', 'Billy Idol', 'M Stuart', 'Luc van den Bergen']
list_2 = ['John Payne', 'George W. Bush', 'Billy Idol', 'M. Stuart', 'Luc Bergen']

mymap = {}
for elem in list_1:
    closest = difflib.get_close_matches(elem, list_2)
    if closest:
        mymap[elem] = closest[0]

print mymap

rawDescription: Given two python lists of same length. How to return the best matches of similar values?


code:
tokens = {
    'Apple': 1,
    'Orange': 2,
    'Pear': 3,
    'Banana': 4,
}

for t in sorted(tokens.keys()):
    print t, 'corresponds to', tokens[t]

rawDescription: Using a for loop to print entries within a dictionary


code:
import random
import re
import string
import sys

def main(args):
    words = []
    letters_and_digits = "%s%s" % (string.letters, string.digits)
    for i in range(2000):
        chars = []
        for j in range(10):
            chars.append(random.choice(letters_and_digits))
        words.append(("%s"*10) % tuple(chars))
    search_for = re.compile("|".join(words))
    first, middle, last = words[0], words[len(words) / 2], words[-1]
    search_string = "%s, %s, %s" % (last, middle, first)
    match_obj = search_for.search(search_string)
    if match_obj is None:
        print "Ahhhg"
        return
    index = match_obj.start()
    which = match_obj.group()
    if index != 0:
        print "ahhhg"
        return
    if words[-1] != which:
        print "ahhg"
        return

    print "success!!! Generated 2000 random words, compiled re, and was able to perform matches."

if __name__ == "__main__":
    main(sys.argv)

rawDescription: What's the most efficient way to find one of several substrings in Python?


code:
for filename in listfiles('/etc/'):
    print filename

rawDescription: Simplest way to get the equivalent of "find ." in python?


code:
for index, item in enumerate(stats):
    print item
    print "index: %s" % index

rawDescription: How do I create a python list with unique indexes from a comma delimited string with duplicate values?

description: Create a python list with unique indexes from a comma delimited string with duplicate values


code:
cntr = df.Column2.str.get_dummies(',').groupby(df.Column1).sum()
print cntr

rawDescription: How to count through several lists contained in a groupby object and add counts together for every value in the lists of that group

description: Count through several lists contained in a groupby object and add counts together for every value in the lists of that group


code:
def initIPythonKernel():
  # You can remotely connect to this kernel. See the output on stdout.
  try:
    import IPython.kernel.zmq.ipkernel
    from IPython.kernel.zmq.ipkernel import Kernel
    from IPython.kernel.zmq.heartbeat import Heartbeat
    from IPython.kernel.zmq.session import Session
    from IPython.kernel import write_connection_file
    import zmq
    from zmq.eventloop import ioloop
    from zmq.eventloop.zmqstream import ZMQStream
    IPython.kernel.zmq.ipkernel.signal = lambda sig, f: None  # Overwrite.
  except ImportError, e:
    print "IPython import error, cannot start IPython kernel. %s" % e
    return
  import atexit
  import socket
  import logging
  import threading

  # Do in mainthread to avoid history sqlite DB errors at exit.
  # https://github.com/ipython/ipython/issues/680
  assert isinstance(threading.currentThread(), threading._MainThread)
  try:
    connection_file = "kernel-%s.json" % os.getpid()
    def cleanup_connection_file():
      try:
        os.remove(connection_file)
      except (IOError, OSError):
        pass
    atexit.register(cleanup_connection_file)

    logger = logging.Logger("IPython")
    logger.addHandler(logging.NullHandler())
    session = Session(username=u'kernel')

    context = zmq.Context.instance()
    ip = socket.gethostbyname(socket.gethostname())
    transport = "tcp"
    addr = "%s://%s" % (transport, ip)
    shell_socket = context.socket(zmq.ROUTER)
    shell_port = shell_socket.bind_to_random_port(addr)
    iopub_socket = context.socket(zmq.PUB)
    iopub_port = iopub_socket.bind_to_random_port(addr)
    control_socket = context.socket(zmq.ROUTER)
    control_port = control_socket.bind_to_random_port(addr)

    hb_ctx = zmq.Context()
    heartbeat = Heartbeat(hb_ctx, (transport, ip, 0))
    hb_port = heartbeat.port
    heartbeat.start()

    shell_stream = ZMQStream(shell_socket)
    control_stream = ZMQStream(control_socket)

    kernel = Kernel(session=session,
                    shell_streams=[shell_stream, control_stream],
                    iopub_socket=iopub_socket,
                    log=logger)

    write_connection_file(connection_file,
                          shell_port=shell_port, iopub_port=iopub_port, control_port=control_port, hb_port=hb_port,
                          ip=ip)

    print "To connect another client to this IPython kernel, use:", \
          "ipython console --existing %s" % connection_file
  except Exception, e:
    print "Exception while initializing IPython ZMQ kernel. %s" % e
    return

  def ipython_thread():
    kernel.start()
    try:
      ioloop.IOLoop.instance().start()
    except KeyboardInterrupt:
      pass

  thread = threading.Thread(target=ipython_thread, name="IPython kernel")
  thread.daemon = True
  thread.start()

rawDescription: Provide remote shell for Python script

description: Provide remote shell for Python script


code:
import c

container = c.Container()
b = container.GetBase()
d = c.CastToDerived(b)
d.f()
print "ok"

rawDescription: How do I down-cast a c++ object from a python SWIG wrapper?

description: Down-cast a c++ object from a python SWIG wrapper


code:
import pandas as pd
import matplotlib.pyplot as plt
import datetime

data = pd.read_csv('data.csv', sep='\t', header=None)
print data

rawDescription: Python 3.4 reading from CSV formats

description: Python 3.4 reading from CSV formats


code:
import pyparsing as pp

word = pp.Word(pp.alphas + ',.')('word*')
number = pp.Word(pp.nums + ',.')('number*')
direct_speech = pp.Suppress('“') + pp.Group(pp.OneOrMore(word | number))('direct_speech*') + pp.Suppress('”')
sentence = pp.Group(pp.OneOrMore(word | number | direct_speech))('sentence')

test_string = 'Lorem 14 ipsum “dolor 22 sit” amet, consectetur.'
r = sentence.parseString(test_string)

from lxml import etree
xml = etree.fromstring(r.sentence.asXML('sentence'))
for el in xml:
    if len(el):
        print el.tag
        for sub_el in el:
            print '  ', sub_el.tag, ':', sub_el.text
    else:
        print el.tag, ':',  el.text

rawDescription: `pyparsing`: iterating over `ParsedResults`


code:
i = 1
for line in sample:
    print i, line
    i = i + 1

rawDescription: Cant get __import__() to dynamically import a module in python - I know this cause it doesn't show up in sys.modules


code:
def append_path(root, paths):
    if paths:
        child = root.setdefault(paths[0], {})
        append_path(child, paths[1:])

# Example usage
root = {}
for p in [(1,2,3,4,5),(1,2,7),(2,3,5),(3,4,5,6)]:
    append_path(root, p)

# Print results
import json
print json.dumps(root,  indent=4)

rawDescription: Nested list into a hierarchical dict

description: Nested list into a hierarchical dict


code:
def halved_loop(sequence):
    n = -1
    while True:
        try:
            yield sequence[n]
        except IndexError:
            return
        n *= 2

for elem in halved_loop(['foo', 'bar', 'baz', 'quu', 'spam', 'ham', 'monty', 'python']):
    print elem

rawDescription: For loop with custom steps in python

description: For loop with custom steps in python


code:
text = 'user = bob'
a = re.match(r'(?P<key>.*?) ?(?P<operator>NOT LIKE|LIKE|<=>|>=|<=|!=|<>|=|>|<) ?(?P<values>.*)',text)
print a.group()

rawDescription: Python Regex: Optional White Space Around Matching Group


rawDescription: paramiko stdout show nothing with regular expression?

description: Paramiko stdout show nothing with regular expression


code:
from itertools import combinations
for x,y in combinations(row1, 2):
    print x,y

rawDescription: pythonic way for nested loops checking items against two or more list

description: Pythonic way for nested loops checking items against two or more list


rawDescription: append value in ith list of list

description: Append value in ith list of list


code:
source
import re

m = re.finditer( 'beer', open('zfind.py').read() ).next()
print m and m.group(0)

rawDescription: Python: find if a given regular expression is present in a file


code:
SCRIPTS = [
    'app/js/libs/EventSource.js',
    'app/js/libs/Hash.js',
    'app/js/libs/JSON.js',
    'app/js/libs/ServiceClient.js',
    'app/js/libs/jquery.hash.js',
    'app/js/libs/Application.js',
    'app/js/intro.js',
    'app/js/jquery-extras.js',
    'app/js/settings.js',
    'app/js/api.js',
    'app/js/game.js',
    'app/js/user.js',
    'app/js/pages.intro.js',
    'app/js/pages.home.js',
    'app/js/pages.log-in.js',
    'app/js/pages.log-out.js',
    'app/js/pages.new-command.js',
    'app/js/pages.new-frame.js',
    'app/js/pages.not-found.js',
    'app/js/pages.register.js',
    'app/js/pages.outro.js',
    'app/js/outro.js',
    ]
SCRIPTS_OUT_DEBUG = 'app/js/multifarce.js'
SCRIPTS_OUT = 'app/js/multifarce.min.js'

STYLESHEETS = [
    'app/media/style.css',
    ]
STYLESHEETS_OUT = 'app/media/style.min.css'

def main():
    print 'Compressing JavaScript...'
    compress(SCRIPTS, SCRIPTS_OUT, 'js', False, SCRIPTS_OUT_DEBUG)

    print 'Compressing CSS...'
    compress(STYLESHEETS, STYLESHEETS_OUT, 'css')

if __name__ == '__main__':
    main()

rawDescription: combine javascript files at deployment in python

description: Combine javascript files at deployment in python


code:
n = 4

# construct a
diag = [-1]*n + [1]*2
lowdiag = [0.5]*(n-1) + [0]*2
updiag = [0.5]*n
a=numpy.diag(diag) + numpy.diag(lowdiag, -1) + numpy.diag(updiag, 2)

# solve ax=b
b=numpy.array([0]*n + [1]*2)
x = numpy.linalg.solve(a, b)

print a
print x[:n]

rawDescription: How to solve recurrence relations in python

description: Solve recurrence relations in python


code:
for row in curs1.tables():
    print row.table_name

rawDescription: Python: Adding excel file to an access database


rawDescription: What does this parameter in numpy.zeros method mean?


code:
x = 0   # The initial value of x, with global scope

def other_function():
    global x
    x = x + 5

def main_function():
    print x    # Just printing - no need to declare global yet
    global x   # So we can change the global x
    x = 10
    print x
    other_function()
    print x

rawDescription: Python - How to make a local variable (inside a function) global


code:
for item in data['clubs']:
    print item['id']

rawDescription: Can't encode content of keys from json

description: Can't encode content of keys from json


code:
def run():
  print 'run'

def walk():
  print 'walk'

def talk():
   print 'talk'
switch={'run':run,'walk':walk,'talk':talk}
switch['run']()

rawDescription: Is this a "pythonic" method of executing functions as a python switch statement for tuple values?


code:
CodeNumber=(raw_input("Please enter 4 digit number: "))
print "Code_A: %r%r%r" %(int(CodeNumber[3]), int(CodeNumber[1]), int(CodeNumber[0]))
print "Code_A: %r%r%r" %(int(CodeNumber[2]), int(CodeNumber[3]), int(CodeNumber[1]))

rawDescription: Python 2 - printing raw input into an array, formatting output


code:
def get_data_for_date(dateStr):
    text = data
    return data.split('\n')

dateStr = raw_input('Date? ')
data = get_data_for_date(dateStr)
print data

rawDescription: Beginner Python, splitting data

description: Beginner Python, splitting data


code: print max(Counter([0, 0, 1, 2, 3, 0]).itervalues())

rawDescription: How to find the maximum number of times that the most common item in a list appears?

description: Find the maximum number of times that the most common item in a list appears


code:
from wand.image import Image
from wand.display import display
from wand.color import Color

with Image(filename='mona-lisa.png') as image:
    for row in image:
        for col in row:
            assert isinstance(col, Color)
            print str(col) + "R:"+str(col.red)+"|"+"G:"+str(col.green)+"|"+"B:"+str(col.blue)

rawDescription: getting the average rgb value of an image in wand

description: Getting the average rgb value of an image in wand


code:
class myParent( object ):
    def __init__( self ):
        self.parentNumber = 5

class Child( myParent ):
    def __init__( self ):
        myParent.__init__( self )
        self.childNumber = 4

    def multiplyNumbers( self ):
        print self.parentNumber * self.childNumber

p = Child()
p.multiplyNumbers()

rawDescription: Python: Getting baseclass values from derived class


code:
def decorator_creator(*args):
    class Decorator(object):
        def __init__(self, func):
            print args
            print func
            self.func = func
        def __call__(self):
            return self.func()
    return Decorator

@decorator_creator(1, 2, 3)
def foo():
    pass

rawDescription: Pass method to decorator with arguments?

description: Pass method to decorator with arguments


code:
x = arange(0,10)
y = exp(-x/3.0)
f_i = interp1d(x, y)
f_x = extrap1d(f_i)

print f_x([9,10])

rawDescription: How to make scipy.interpolate give an extrapolated result beyond the input range?

description: Make scipy.interpolate give an extrapolated result beyond the input range


code:
import pygame
import time
import random

pygame.init()

WHITE = (pygame.Color("white"))
BLACK = (  0,   0,  0)
RED   = (245,   0,  0)
TURQ  = (pygame.Color("turquoise"))
GREEN = (  0, 155,  0)
GREY  = ( 90,  90, 90)
SCREEN = (800, 600)
gameDisplay = pygame.display.set_mode(SCREEN)
#Set the window title and picture
pygame.display.set_caption('Block Worm')
ICON = pygame.Surface((10,10)) #pygame.image.load("apple10pix.png")

pygame.display.set_icon(ICON)
CLOCK = pygame.time.Clock()
FPS = 20
FONT = pygame.font.SysFont("arial", 25)
APPLE_SIZE = 10
TINY_FONT = pygame.font.SysFont("candara", 15)
SMALL_FONT = pygame.font.SysFont("candara", 25)
MED_FONT = pygame.font.SysFont("candara", 50)
LARGE_FONT = pygame.font.SysFont("krabbypatty", 75)
HUGE_FONT = pygame.font.SysFont("krabbypatty", 150)
IMG = pygame.Surface((10,10)) #pygame.image.load("snakehead.png")
APPLE_IMG = pygame.Surface((10,10)) #pygame.image.load("apple10pix.png")
DIRECTION = "up"

def pause():
    paused = True
    message_to_screen("Paused",
                      BLACK,
                      Y_DISPLACE = -100,
                      size = "huge")
    message_to_screen("Press C to continue or Q to quit.",
                      BLACK,
                      Y_DISPLACE = 25)
    pygame.display.update()
    while paused:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key in (pygame.K_c, pygame.K_p):
                    paused = False
                elif event.key in(pygame.K_q, pygame.K_ESCAPE):
                    pygame.quit()
                    quit()
        CLOCK.tick(5)

def score(score):
    text = SMALL_FONT.render("Score: " + str(score), True, BLACK)
    gameDisplay.blit(text, [0, 0])

def game_intro():
    intro = True
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_c:
                    intro = False
                if event.key in (pygame.K_q, pygame.K_ESCAPE):
                    pygame.quit()
                    quit()
        gameDisplay.fill(WHITE)
        message_to_screen("Welcome to",
                          GREEN,
                          Y_DISPLACE = -170,
                          size = "large")
        message_to_screen("Block Worm",
                          GREEN,
                          Y_DISPLACE = -50,
                          size = "huge")
        message_to_screen("The objective of the game is to eat apples.",
                          BLACK,
                          Y_DISPLACE = 36,
                          size = "tiny")
        message_to_screen("The more apples you eat the longer you get.",
                          BLACK,
                          Y_DISPLACE = 68,
                          size = "tiny")
        message_to_screen("If you run into yourself or the edges, you die.",
                          BLACK,
                          Y_DISPLACE = 100,
                          size = "tiny")
        message_to_screen("Press C to play or Q to quit.",
                          GREY,
                          Y_DISPLACE = 210,)
        pygame.display.update()
        CLOCK.tick(FPS)

def text_objects(text, color, size):
    if size == "tiny":
        TEXT_SURFACE = TINY_FONT.render(text, True, color)
    elif size == "small":
        TEXT_SURFACE = SMALL_FONT.render(text, True, color)
    elif size == "medium":
        TEXT_SURFACE = MED_FONT.render(text, True, color)
    elif size == "large":
        TEXT_SURFACE = LARGE_FONT.render(text, True, color)
    elif size == "huge":
        TEXT_SURFACE = HUGE_FONT.render(text, True, color)
    return TEXT_SURFACE, TEXT_SURFACE.get_rect()

def message_to_screen(msg, color, Y_DISPLACE = 0, size = "small"):
    TEXT_SURF, TEXT_RECT = text_objects(msg, color, size)
    TEXT_RECT.center = (SCREEN[0] / 2), (SCREEN[1] / 2) + Y_DISPLACE
    gameDisplay.blit(TEXT_SURF, TEXT_RECT)

class Snake(pygame.sprite.Sprite):
    def __init__(self, image, size, trail, start_size):
        pygame.sprite.Sprite.__init__(self)
        self.image = image
        self.size = size
        self.trail = trail
        self.start_size = start_size
        self.rect = self.image.get_rect()
        if DIRECTION == "right":
            HEAD = pygame.transform.rotate(self.image, 270)
        elif DIRECTION == "left":
            HEAD = pygame.transform.rotate(self.image, 90)
        elif DIRECTION == "down":
            HEAD = pygame.transform.rotate(self.image, 180)
        else:
            HEAD = image
        gameDisplay.blit(HEAD, (self.trail[-1][0], self.trail[-1][1]))
        for XnY in self.trail[:-1]:
            pygame.draw.rect(gameDisplay, GREEN, [XnY[0], XnY[1], self.size, self.size])

    def set_rect(self, rect):
        self.rect = rect

class Apple(pygame.sprite.Sprite):
    def __init__(self, image):
        pygame.sprite.Sprite.__init__(self)
        self.image = image
        self.random_location()
        self.size = self.rect.width
        gameDisplay.blit(self.image, (100, 100))

    def random_location(self):

        x = random.randrange(0, (SCREEN[0] - 10), 10)
        y = random.randrange(0, (SCREEN[1]- 10), 10)
        self.rect = pygame.Rect(x,y, 10, 10)
        print "apple rect =",
        print self.rect

    def draw(self):
        gameDisplay.blit(self.image, (self.rect.x, self.rect.y))

def gameLoop():
    global DIRECTION
    DIRECTION = "up"
    gameExit = False
    gameOver = False
    SCORE = 0

    player_snake_trail = [] # Where the snake head has been.
    enemy_snake_trail = [] # If I create an AI snake.
    start_length = 1

    lead_x = (SCREEN[0] / 2)
    lead_y = (SCREEN[1] - (SCREEN[1] / 5))
    move_speed = 10
    move_speed_neg = move_speed * -1
    lead_x_change = 0
    lead_y_change = -move_speed

    red_apple = Apple(APPLE_IMG)

    while not gameExit:
        if gameOver == True:
            message_to_screen("Game over",
                              RED,
                              Y_DISPLACE = -50,
                              size = "huge")
            message_to_screen("Press C to play again or Q to quit.",
                              BLACK,
                              Y_DISPLACE = 50,
                              size = "small")
            pygame.display.update()
        while gameOver == True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    gameExit = True
                    gameOver = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        gameOver = False
                        gameExit = True
                    elif event.key == pygame.K_c:
                        gameLoop()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                gameExit = True
            elif event.type == pygame.KEYDOWN:
                if event.key in (pygame.K_LEFT, pygame.K_a):
                    lead_x_change = move_speed_neg
                    lead_y_change = 0
                    DIRECTION = "left"
                elif event.key in (pygame.K_RIGHT, pygame.K_d):
                    lead_x_change = move_speed
                    lead_y_change = 0
                    DIRECTION = "right"
                elif event.key in (pygame.K_UP, pygame.K_w):
                    lead_y_change = move_speed_neg
                    lead_x_change = 0
                    DIRECTION = "up"
                elif event.key in (pygame.K_DOWN, pygame.K_s):
                    lead_y_change = move_speed
                    lead_x_change = 0
                    DIRECTION = "down"
                elif event.key in (pygame.K_p, pygame.K_ESCAPE):
                    pause()

        # If the snake goes beyond the screen borders the game will end.
        if lead_x >= SCREEN[0] or lead_x < 0 or lead_y >= SCREEN[1] or lead_y <0:
            gameOver = True

        lead_x += lead_x_change
        lead_y += lead_y_change

        gameDisplay.fill(WHITE)

        # Draw the snake on screen
        SNAKE_HEAD = []
        SNAKE_HEAD.append(lead_x)
        SNAKE_HEAD.append(lead_y)
        player_snake_trail.append(SNAKE_HEAD)

        # draw the apple on the screen
        red_apple.draw()

        # If you hit yourself, game over.
        if SNAKE_HEAD in player_snake_trail[:-1]:
           gameOver = True
        if len(player_snake_trail) > start_length:
            del player_snake_trail[0]

        player_snake = Snake(IMG, 10, player_snake_trail, start_length)
        player_snake.set_rect(pygame.Rect(lead_x, lead_y, 10, 10))

        if pygame.sprite.collide_rect(player_snake, red_apple) == True:
           print("Collided!")

           start_length += 1
           SCORE += 1
           red_apple.random_location()

        # If the snake eats the apple
        # Old code below, needs to be rewritten. Disregard.
##        if APPLE_RECT.collidepoint(lead_x, lead_y) == True:
##            randAppleX, randAppleY = randAppleGen()
##            start_length += 1
##            SCORE += 1

        score(SCORE)

        pygame.display.update()
        CLOCK.tick(FPS)
    pygame.quit()
    quit()

game_intro()
gameLoop()

rawDescription: Why wont collide_rect work in this scenario? The game keeps printing "Collided!" even when the two sprites aren't touching?


code:
import re

inputs = ['{a}text{b}test', 'text', 'text{b}text', 'text{b}', 'text{a}text']
p = re.compile(r"^(.*(?={a})|.*?)({a})?(.*(?={b})|.*)({b})?(.*?)$")
for input in inputs:
    print p.match(input).groups()

rawDescription: Python Regular Expression with optional but greedy groups


rawDescription: Print a nested list line by line - Python


code:
#!/usr/bin/env python

import errno
import os

f1 = "test1"
f2 = "test2"

path = "."
for dirpath, dirnames, _ in os.walk(path):
    for subdir in dirnames:
        filepath1, filepath2 = [os.path.join(dirpath, subdir, f + ".txt") for f in f1, f2]
        try:
            with open(filepath1, 'r') as fin1, open(filepath2, 'r') as fin2:
                print("do something with " + str(fin1) + " and " + str(fin2))
        except IOError as e:
            # ignore directiories that don't contain the 2 files
            if e.errno != errno.ENOENT:
                # reraise exception if different from "file or directory doesn't exist"
                raise

    # comment the next line out if you want to traverse all subsubdirectories
    dirnames[:] = []

rawDescription: Iterate over 2 files in each folder and compare them


code:
from collections import defaultdict
from turtle import *

class MyTurtle(Turtle):
    def __init__(self, *args, **kwds):
        super(MyTurtle, self).__init__(*args, **kwds)  # initialize base
        self.dots = defaultdict(int)

    def dot(self, *args, **kwds):
        super(MyTurtle, self).dot(*args, **kwds)
        self.dots[self.position()] += 1

    def print_count(self):
        """ print number of dots drawn, if any, at current position """
        print self.dots.get(self.position(), 0) # avoid creating counts of zero

def main(turtle):
    turtle.forward(100)
    turtle.dot("blue")
    turtle.left(90)
    turtle.forward(50)
    turtle.dot("green")
    # go back to the start point
    turtle.right(180) # turn completely around
    turtle.forward(50)
    turtle.dot("red")  # put second one in same spot
    turtle.right(90)
    turtle.forward(100)

if __name__ == '__main__':
    turtle1 = MyTurtle()
    main(turtle1)
    mainloop()

    for posn, count in turtle1.dots.iteritems():
        print('({x:5.2f}, {y:5.2f}): '
              '{cnt:n}'.format(x=posn[0], y=posn[1], cnt=count))

rawDescription: Determine How Many Times a Turtle Has Made a Dot in a Certain Location


code:
import itertools
for a,b,c in itertools.product(xrange(5+1),xrange(3+1),xrange(8+1)):
    print a,b,c

rawDescription: Why is only the innermost of these nested while loops working?


code:
import sqlite3, csv, time
from datetime import datetime, date

conn = sqlite3.connect('mynewtable.sqlite3')
conn.text_factory = str
c = conn.cursor()
c.execute('drop table if exists mynewtable')
c.execute('create table mynewtable('
          'id integer primary key autoincrement, '
          'rank integer, '
          'placename text, '
          'information text, '
          'nooftimes integer, '
          'visit text, '
          'fav integer, '
          'year integer)')

sql_insert = "insert into mynewtable values(NULL, ?, ?, ?, ?, ?, ?, ?)"
csv_reader = csv.reader(open('mynewtable.csv', 'rb'))
csv_reader.next() # skip headers
for csv_row in csv_reader:
    print "Inserting %s..." % (csv_row)
    c.execute(sql_insert, csv_row)

conn.commit()

rawDescription: Incorrect number of bindings supplied for CSV Sqlite Python script


code:
import re
p = re.compile(r'([\w ]*#\d\d?,)\1*')
test_str = "Run #1,Run #1,Run #1,Run #1,Run #1,Run #1,Run #1,Run #2,Run #2,Run #2,Run #2,Run #2,Run #2,Run #2,Run #3,Run #3,Run #3,Run #3,Run #3,Run #3,Run #3, (..."
print [x.group() for x in p.finditer(test_str)]

rawDescription: Python's regex module: repeating 'backreferences' does not appear to work correctly


code:
file=open("out1.txt","r+")
wordcount={}
for word in file.read().split():
    word = word.lower()
    if word.isalpha == True:
        if word not in wordcount:
            wordcount[word] = 1
        else:
            wordcount[word] += 1
copy = []
for k,v in wordcount.items():
    copy.append((v, k))

copy = sorted(copy, reverse=True)

for k in copy:
        print '%s: %d' %(k[1], k[0])

rawDescription: Python descending order of wordcount

description: Python descending order of wordcount


code:
from mock import patch
import unittest

from test_app import app

def not_a_db_hit():
    print 'I did not hit the db'

class FlaskTest(unittest.TestCase):

    @patch('test_app.connect_db')
    def test_root(self, mock_connect_db):
        mock_connect_db.side_effect = not_a_db_hit
        response = app.test_client().get('/')
        self.assertEqual(response.status_code, 200)

if __name__ == '__main__':
    unittest.main()

rawDescription: in a Flask unit-test, how can I mock objects on the request-global `g` object?

description: In a Flask unit-test, how can I mock objects on the request-global `g` object


code:
import string

input_list = ['hi', 'how', 'are', 'you']
filename="hi.txt"
count = 0
with open(filename, "rb") as fp:
    data = fp.read()
    data = data.translate(string.maketrans("",""), string.punctuation)
    for word in data.split():
        if word in input_list:
            count += 1

print "Total number of word present in file from the list are %d"%(count)

rawDescription: How to check for words in a list and then return a count?

description: Check for words in a list and then return a count


code:
def menu(choice):
    def add():
        print 6+6
    def sub():
        print 6-3

    if choice == 'add':
        add() # call add here
    elif choice == 'sub':
        sub() # call sub here

rawDescription: How to call upon a function within a function?

description: Call upon a function within a function


code:
from itertools import ifilter

def f(d, func, l):
    if l == 0:
        return {k: d[k] for k in ifilter(func, d)}
    tmp = {k: f(v, func, l - 1) for k, v in d.iteritems()}
    return {k: v for k, v in tmp.iteritems() if v}

d = {'fruit': {'sweet': {'green': 'apple', 'red': 'tomato'}, 'bitter': {'green': 'cucumber'}, 'x': {'a': 'z'}}}

print f(d, lambda k: k == 'green', 2)

rawDescription: How can I filter a nested dictionary at a certain nested level?

description: Filter a nested dictionary at a certain nested level


code:
from basemodule import *
import basemodule

def makeBalls(a,b):
    foo = makeBall(a)
    bar = makeBall(b)
    print foo,bar

def override():
    print "OVERRIDE TWO"

def dontoverride():
    basemodule.dontoverride()
    print "THIS WAS PRESERVED"

rawDescription: How do I extend a python module? (python-twitter)

description: Extend a python module? (python-twitter)


code:
import re

text="sdfsfsdfdsfsdfsd #.split.#style=background: black\nsdfsfsdfdsfsdfsd #.split.#style=background: red"
matches =  re.findall('.*#.split.#.*', text)
final = ""
for m in matches:
    parts = re.search("(.*)#.split.#style=(.*)", m)
    new = '{}

'.format(parts.group(1), parts.group(2))
    final += new + "\n"
print final

rawDescription: Python - get string part from another string


code:
import subprocess

args=[  'gst-launch-0.10',
        '-v',
        'gstrtpbin',
        'name=rtpbin',
        'latency=100',
        'udpsrc',
        'caps="application/x-rtp, media=(string)audio, clock-rate=(int)48000, encoding-name=(string)X-GST-OPUS-DRAFT-SPITTKA-00, caps=(string)audio/x-opus, multistream=(boolean)false, streamheader=(buffer)<4f707573486561640101000080bb0000000000,4f707573546167731e000000456e636f6465642077697468204753747265616d6572204f707573656e63010000001a0000004445534352495054494f4e3d617564696f74657374207761766501>, ssrc=(uint)3090172512, payload=(int)96, clock-base=(uint)4268257583, seqnum-base=(uint)10001"',
        'port=5002',
        '!',
        'rtpbin.recv_rtp_sink_1',
        'rtpbin.',
        '!',
        'rtpopusdepay',
        '!',
        'opusdec',
        '!',
        'audioconvert',
        '!',
        'audioresample',
        '!',
        'alsasink',
        'device=2',
        'name=uudpsink0',
        'udpsrc',
        'port=5003',
        '!',
        'rtpbin.recv_rtcp_sink_1',
        'rtpbin.send_rtcp_src_1',
        '!',
        'udpsink',
        'port=5007',
        'host=%s',
        'sync=false',
        'async=false',

        ]

child = subprocess.Popen(args, stdout=subprocess.PIPE)
streamdata = child.communicate()[0] # streamdata will contain output of gst-launch-0.10
rc = child.returncode # rc will contain the returncode of gst-launch-0.10

print streamdata
print "\nprocess returned %d" %(rc)

rawDescription: Gstreamer - opus caps parsing error, anyone know how to fix it?


code:
from itertools import product
def randString(istr):
    l = [(c, c.upper()) if not c.isdigit() else (c,) for c in istr.lower()]
    return ["".join(item) for item in product(*l)]

print randString("aBC1")
print randString("A1b2c3")

rawDescription: String manipulation in Python (All upper and lower case derivatives of a word)


code:
from myapp.settings import *

def print_foo():
    print FOO

rawDescription: Django default settings convention for pluggable app?


code:
def weakness(self):
    if poketype == 'fire':
        print 'strong against grass'
        print 'weak against water'

    elif poketype == 'water':
        print 'strong against first'
        print 'weak against grass'

    elif poketype == 'grass':
        print 'strong against water'
        print 'weak against fire'

rawDescription: Error with a simple program, printing error (python)


code:
foo = Foo()
print foo.x
foo.add()
print foo.x
foo.redefine()
print foo.x

rawDescription: self variables not being stored in python?

description: Self variables not being stored in python


code:
rv = "command"
rv_args = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

def get_arguments(rv, rv_args):
    arguments = [rv]
    for i in xrange(0, len(rv_args), 2):
        arguments += ["["] + rv_args[i:i+2] + ["]"]

    return arguments

print get_arguments(rv, rv_args)

rawDescription: generating subprocess.call arguments from a list

description: Generating subprocess.call arguments from a list


code:
s = "Lorem ipsum foo bar foobar stuff etc"
start = 0
for i in range(4): # number of words
    start = s.find(" ", start+1)
print s[:start]

rawDescription: How to strip a string after a certain amount of words in python

description: Strip a string after a certain amount of words in python


code:
@staticmethod
def impWords():

    with open('import.txt','r+') as tempFile:
        #re
        tempFile1 = re.findall(r'\w+', tempFile.read())
        # using enumerate here is cleaner
        for i, w in enumerate(tempFile1):
            word = Word() # here you're creating a new Word instance for each item in tempFile1
            word.ID = i
            word.data = w
            word.points = 0
            Repo.words.append(word)
            word.prt(word) # here it would be better to implement Word.__str__() and do print word

    print Repo.words # print automatically calls __str__()
    UI.Controller.adminMenu()

rawDescription: Create from list of strings list of class instances py2.7


code:
print pattern.findall(file.read())
print re.findall(r'>(\w+ing<', file.read())

rawDescription: TypeError: findall() takes at least 2 arguments (1 given)


code:
class A(object):
    def __init__(self):
        self.b_list = []

class B(object):
    def __init__(self):
        self.x = 'X'
        self.y = 'Y'

a = A()
a.b_list.append(B())

print dumps(a.__dict__)

rawDescription: Python serialize objects list to JSON

description: Python serialize objects list to JSON


code:
for key in dd[0]:
    for combination in product(*(d[key] for d in dd)):
        print ' '.join(combination)

rawDescription: Getting the values of many defaultdicts that contains a certain key


code:
l1= ['alpha','beta']
l2= ['alpha','beta','gama','theta']
l3= ['AnotherWord']

print len(list(set(l2)-set(l1)))==len(l2) #Case where l1 is a sublist of l2
print len(list(set(l2)-set(l3)))==len(l2) #case where l3 is not a sublist of l2

rawDescription: check if the first list is a sublist of the second one python

description: Check if the first list is a sublist of the second one python


code:
import numpy as np

a = np.array([[[1,2,3],4],[[4,5,6],5]])
b = a[:,0]

c = np.vstack(b)
print c.shape # (2,3)

rawDescription: numpy array in array resize

description: Numpy array in array resize


code:
r = open('t.txt', 'r')
sentence_List = r.readlines()
for line in sentence_List:
    print line,

rawDescription: readlines() function and unicodes

description: Readlines() function and unicodes


code:
import Tkinter
import random

class simpleapp_tk(Tkinter.Tk):

    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()
        self.started = False # True when timer is running

    def initialize(self):
        self.grid()

        self.infoVariable = Tkinter.StringVar()
        self.labelInfo = Tkinter.Label(self, textvariable=self.infoVariable, anchor="w", fg="blue", bg="gold")
        self.labelInfo.grid(column=0, row=0, sticky='EW')
        self.infoVariable.set(u"Press button to begin!")

        self.buttonStart = Tkinter.Button(self, text=u"Start", command=self.on_buttonStart, fg="black", bg="green")
        self.buttonStart.grid(column=2, row=0)

        self.timeVariable = Tkinter.StringVar()
        self.labelTime = Tkinter.Label(self, textvariable=self.timeVariable, anchor="w", fg="blue", bg="gold")
        self.labelTime.grid(column=1, row=0, sticky='EW')
        self.timeVariable.set(u'Time')

        self.entryVariable = Tkinter.StringVar()
        self.entry = Tkinter.Entry(self, textvariable=self.entryVariable, fg="black", bg="white")
        self.entry.grid(column=0, row=1, columnspan=2, sticky='EW')
        self.entryVariable.set(u"")
        self.entry.bind('<Key>', self.on_key) # event

        self.grid_columnconfigure(0,weight=1)
        self.grid_rowconfigure(0,weight=1)
        self.resizable(True,True)

    def on_buttonStart(self):
        if not self.started:
            # reset values
            self.started = True
            self.number_of_letters = 20
            self.score = 0
            self.time = 0.0
            # select first letter
            self.randletter = random.choice('qwer')
            # show first letter and score
            self.infoVariable.set('Score:' + str(self.score)+' | Press ' + self.randletter)
            # start timer
            self.after(100, self.timer)

    def on_key(self, event):
        if not self.started:
            self.entryVariable.set('')
        else:
            if event.char == self.randletter:
                print 'Correct', event.char
                self.score += 5
            else:
                print 'Incorrect', event.char
                self.score -= 2

            self.number_of_letters -= 1

            if self.number_of_letters == 0:
                self.started = False
                self.entryVariable.set('')
                self.infoVariable.set('Score:' + str(self.score))
            else:
                self.randletter = random.choice('qwer')
                self.infoVariable.set('Score:' + str(self.score)+' | Press ' + self.randletter)

    def timer(self):
        if self.started:
            self.time += .1
            self.timeVariable.set('Time: ' + str(round(self.time,1)) )
            self.after(100, self.timer)

if __name__ == "__main__":
    app = simpleapp_tk(None)
    app.title('LoL Practice')
    app.geometry("700x50")
    app.configure(background='black')
    app.mainloop()

rawDescription: Python Tkinter attribute error entry in random letter typing test


code:
import re
rex = re.compile('py2\d+-(\S+)')
modules = {}
for line in sys.stdin:
    match = rex.match(line)
    if match:
        modules[match.group(1)] = match.group(0)
    else:
        modules[line] = line
print '\n'.join(sorted(modules.values()))

rawDescription: Python filtering: only keep most recent python MacPort


code:
i = 5
def f(arg = i): print arg
i = 6
f()

rawDescription: Python method defaults based off of class __init__ args


code:
myPolyObject = IntPoly([4, 3, 2], [1, 2, 3])
print myPolyObject.multiply()

rawDescription: How do variables get passed in and out of methods in Python?


code:
with open('yourfile.txt') as f:
    print len( filter(lambda x: ('a' <= x <= 'z') or ('A' <= x <= 'Z'), f.read()) )

rawDescription: Python: Number of letters in file, simple yet efficient way


code:
import csv
import datetime

min_date = None

row_list = []
date_list = []

with open('output_file.csv', 'rb') as inf:
    incsv = csv.reader(inf)
    row = next(incsv)
    for row in incsv:
        # Create a time string
        time_str = row[1].strip() + " " + row[2].strip()
        # Convert the time string to a datetime
        cur_date = datetime.datetime.strptime(time_str, "%m/%d/%Y %H:%M:%S")
        # Update the min_date
        if min_date is None:
            min_date = cur_date
        else:
            min_date = min(min_date, cur_date)
        # Append the datetime to the list
        date_list.append(cur_date)
        # Get a copy of the row with whitespace removed
        new_row = [ col.strip() for col in row]
        # Get a copy of the row with the date and time replaced by a
        # placeholder
        new_row = [ new_row[0], "" ] + new_row[3:]
        # Append the row to the list
        row_list.append(new_row)

index = 0
# For each datetime in the list
for cur_date in date_list:
    # Calculate the time delta
    delta_date = cur_date - min_date
    # Store it in the placeholder
    row_list[index][1] = str(delta_date)
    index += 1

for row in row_list:
    print "%s" % row

rawDescription: Converting data and time columns in csv to relative time


code:
import re

email_address = "email_address_you_know@somewhere.com"

for data in j['items']:
    match = re.search(email_address, data['message'])
    if match:
        print data['message']

rawDescription: Search JSON response with python

description: Search JSON response with python


code:
# load map

mymap = []

with open('data.txt') as f:
    for line in f:
        mymap.append( line.strip() )

# show map

for line in mymap:
    print line

# find sprites on map

for y, line in enumerate(mymap):
    for x, char in enumerate(line):
        if char == 'p':
            print 'sprite at', x, y

rawDescription: How to create sprites using ConfigParser in Pygame

description: Create sprites using ConfigParser in Pygame


code:
import unittest

class TestClass(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print "setup"

    def test_01_create_acc(self):
        print id(self)

    def test_02_check_account(self):
        print id(self)

unittest.main()

rawDescription: Are unittest attributes mutable in Python?


code:
import pyaudio

def getaudiodevices():
    p = pyaudio.PyAudio()
    for i in range(p.get_device_count()):
        print p.get_device_info_by_index(i).get('name')

rawDescription: Getting list of audio Input devices in Python


code:
import re
mystr = 'on the'
unWanted = re.findall(r'\(.*'+mystr+'.*\)|\)'+mystr, data) # <- here you put the un-wanted string series, which is easy to define with regex
# delete un-wanted strings
for line in mylist:
    for item in unWanted:
        if item in line:
            mylist.remove(line)
# look for what you want
for line in mylist:
    if mystr in line:
        print line

rawDescription: Do not match word boundary beetwen parenthesis with python regex


code:
import os
import glob
import operator
os.chdir("/mypath")
for file in glob.glob("*.csv"):
    data=open(file).readlines()
    data=[i.strip().split(";") for i in data if i[:3] in ["637","638","639"]]
    # data=[i.strip().split(";") for i in data if i[:3] in ["637","638","639"] and isinstance(float(i[:6]),float) ]
    sortedlist = sorted(data, key=operator.itemgetter(1), reverse=True)
    print "Highest for file %s: %s" % (file,sortedlist[0])

rawDescription: Sorting csv columns in bash, reading bash output into python variables


code:
for host in root.iter('host'):
    print host.attrib['name']

rawDescription: How do you walk an Element tree parsed using Python's elmenttree module?

description: Walk an Element tree parsed using Python's elmenttree module


code:
#!/usr/bin/env python
import paramiko
from contextlib import contextmanager
host = '192.168.10.142'
username = 'slacker'
password = 'password'
def create_ssh(host=host, username=username, password=password):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
       print "creating connection"
       ssh.connect(host, username=username, password=password)
       print "connected"
       yield ssh
    finally:
       print "closing connection"
       ssh.close()
       print "closed"

rawDescription: python libraries for ssh handling

description: Python libraries for ssh handling


code:
import heapq
letters = 'axuebizjmf'
heap = map(ReverseCompare, letters)
heapq.heapify(heap)
print heapq.heappop(heap) # prints z

rawDescription: Pop max value from a heapq python, Is there a max-heap in Python?


code:
list1=[3,2,1,6,5,4]
n_list1 = len(list1)
for position1, item1 in enumerate(list1):
    for position2 in range(position1,n_list1):
        if list1[position1]>list1[position2]:
            list1[position1] , list1[position2] = list1[position2], list1[position1]
print list1

rawDescription: Wrong output in Python - as per my logic


rawDescription: Cannot convert ascii to utf-8 in python

description: Cannot convert ascii to utf-8 in python


code:
class Foo(object):

  def __init__(self):
    self.my_attrs = {
      'frontend': ['name','ip_address','mode','port','max_conn'],
      'backend': ['name','balance_method','balance_mode'],
    }

  def sanity_check_data(self):
    self.check_section('frontend')
    self.check_section('backend')

  def check_section(self, section):
    # maybe use self.my_attrs.get(section) and add some error handling?
    my_attrs = self.my_attrs[section]
    for attr in my_attrs:
      print attr

rawDescription: How can I dynamically refer to a variable in Python

description: Dynamically refer to a variable in Python


code:
import re
p = re.compile(ur'(#+[^\\\n]*)')
test_str = u"..."

re.findall(p, test_str)

rawDescription: Python regular expression for a comment in a long string


code:
import socket,struct

def addressInNetwork(ip,net):
   "Is an address in a network"
   ipaddr = struct.unpack('L',socket.inet_aton(ip))[0]
   netaddr,bits = net.split('/')
   netmask = struct.unpack('L',socket.inet_aton(netaddr))[0] & ((2L<<int(bits)-1) - 1)
   return ipaddr & netmask == netmask

rawDescription: How can I check if an ip is in a network in python

description: Check if an ip is in a network in python


code:
import cgi, cgitb
print "Content-type: text/html\n\n"    #for showing print on HTML
data = cgi.FieldStorage()
argument = data["webArguments"].value    #argument = name of PLC i need to fetch
#some script for connecting to PLC and reading current value of
#variable  with name "argument", in this example "aiTemperature"
print plcVar

rawDescription: Run python script and display printed value on a website


code:
input = map(set, [ [1,5,7], [2,6], [3,4,5], [1,2], [4], [1] ])

def eachCombination(input):
  if input:
    for combination, rest in eachCombination(input[1:]):
      yield combination, input[0:1] + rest
      if not (input[0] & combination):  # fits?
        yield input[0] | combination, rest
  else:
    yield set(), []

def eachPacked(input):
  for combination, rest in eachCombination(input):
    for restPart in rest:
      if not (combination & restPart):  # not densely packed?
        break
    else:
      yield combination, rest

def eachSolution(input):
  for packed, rest in eachPacked(input):
    if rest:
      for subsolution in eachSolution(rest):
        yield [ packed ] + subsolution
    else:
      yield [ packed ]

for solution in eachSolution(input):
  print '   '.join('-'.join('%d' % n for n in set) for set in solution)

rawDescription: What is a good way to merge non intersecting sets in a list to end up with denseley packed sets?


code:
# read text from web page
import urllib
page = urllib.urlopen("https://sites.google.com/site/iminside1/paste")
html = page.read()
page.close()

start = html.index("<pre>")+len("<pre>")+3 #skip over 3-byte header
end = html.index("</pre>")
text = html[start:end]
print text

# parse dict-like syntax
from pyparsing import (Suppress, Regex, quotedString, Word, alphas,
alphanums, oneOf, Forward, Optional, dictOf, delimitedList, Group, removeQuotes)

LBRACK,RBRACK,LBRACE,RBRACE,COLON,COMMA = map(Suppress,"[]{}:,")
integer = Regex(r"[+-]?\d+").setParseAction(lambda t:int(t[0]))
real = Regex(r"[+-]?\d+\.\d*").setParseAction(lambda t:float(t[0]))
string_ = Word(alphas,alphanums+"_") | quotedString.setParseAction(removeQuotes)
bool_ = oneOf("true false").setParseAction(lambda t: t[0]=="true")
item = Forward()

key = string_
dict_ = LBRACE - Optional(dictOf(key+COLON, item+Optional(COMMA))) + RBRACE
list_ = LBRACK - Optional(delimitedList(item)) + RBRACK
item << (real | integer | string_ | bool_ | Group(list_ | dict_ ))

result = item.parseString(text,parseAll=True)[0]
print result.data[0].dump()
print result.data[0].segments[0].dump(indent="  ")
print result.data[0].segments[0].flights[0].dump(indent="  -  ")
print result.data[0].segments[0].flights[0].flightLegs[0].dump(indent="  -  -  ")
for seg in result.data[6].segments:
    for flt in seg.flights:
        fltleg = flt.flightLegs[0]
        print "%(airline)s %(airlineCode)s %(flightNo)s" % fltleg,
        print "%s -> %s" % (fltleg["from"].code, fltleg["to"].code)

rawDescription: Python: load text as python object

description: Python: load text as python object


rawDescription: How do I shift rows of consecutive numbers. Python 3.3.2

description: Shift rows of consecutive numbers. Python 3.3.2


code:
from binascii import hexlify
from construct import BitStruct, BitField, Padding, Array, Octet, Adapter

class BitStringAdapter(Adapter):
  def _encode(self, obj, context):
    return list(ord(b) for b in obj)
  def _decode(self, obj, context):
    return "".join(chr(b) for b in obj)

struct = BitStruct("foo",
  BitField("bar", 8),
  BitStringAdapter(Array(2, Octet("baz"))),
  Padding(4),
  BitField("bat", 4)
)

data = "\x01AB\xCD"

out = struct.parse(data)
print hexlify(struct.build(out))

rawDescription: Obtaining strings from BitStruct in Python's construct module


rawDescription: averaging list of lists python

description: Averaging list of lists python


code:
from collections import defaultdict

d = defaultdict(list)

for k, v in zip(key, data):
    d[k].append(v)

print [(k, ' '.join(v)) for k, v in d.items()]

rawDescription: Concatenate strings by groups python

description: Concatenate strings by groups python


code:
#since items() is a tUple list, you can go as follows :
for attrName, attrValue in element.attributes.items():
    #do whatever you'd like
    print "attribute %s = %s" % (attrName, attrValue)

rawDescription: Python Minidom - how to iterate through attributes, and get their name and value


code:
with open('myfile') as f:
    for line in f:
        x = int(line)
        print x+3

rawDescription: Text file number to Python number how?

description: Text file number to Python number how


code: print [x.split(' ')[1] for x in open(file).readlines()]

rawDescription: Reading specific columns from a text file in python


code: print '{x} {z} {y}'.format(**foo._asdict())

rawDescription: Can I express named Python string arguments more succintly?

description: Express named Python string arguments more succintly


code:
import math
pixels = 500
offset = math.log(10)
for x in range(10, 71, 10):
    print x, int(pixels * (math.log(x) - offset) / (math.log(70) - offset))

rawDescription: Calculate values in logarithmic scale

description: Calculate values in logarithmic scale


code:
s = '''Joe, 21142 21143 21909 24125
Mary, 22650 23127
John, 24325
Mike, 24683 24684 26973
'''
from StringIO import StringIO
from contextlib import closing
with closing(StringIO(s)) as f:
    for line in f:
            x, y = line.split(',')
            x = x.strip()
            y = y.strip().split()
            leader = 'http://example/{}'.format(x)
            print '\n'.join('{}/{}'.format(leader, z) for z in y)

rawDescription: Variables while reading a file with multiple rows in a list - python or shell


code:
output = r'\author{{email}}'.format(email='user@example.org')
print output

rawDescription: How to format a LaTeX string in python?

description: Format a LaTeX string in python


code:
import lxml.html

node = """

        Hello foo, I like foo, because foo is the best.

Foo said: foo foo!

Smurfs ate the last foo and turned blue. Foo!

Foo foo.

"""

node = lxml.html.fromstring(node)

def suitability(node, word):
    mx = [0.0, None]
    _suitability(node, word, mx)
    return mx[1]

def _suitability(node, word, mx):

    children = node.getchildren()
    sparsity = 1
    result = float(node.text_content().lower().count(word))
    for child in children:
        res, spars = _suitability(child, word, mx)
        result += res
        sparsity += spars
    result /= sparsity
    current_max, max_node = mx
    if current_max < result:
        mx[0] = result
        mx[1] = node
    return result, sparsity

print suitability(node, 'foo')

rawDescription: Find an HTML element which contains the largest number of mentions of given word


code:
import sys
import os
import win32file
from win32con import *

# dictionary of [mtime, module] tuple;  uses file path as key
loadedPages = {}

def request_handler(env, start_response):
    '''Demo app from wsgiref'''
    cr = lambda s='': s + '\n'
    if hasattr(sys, "isapidllhandle"):
        h = None
        # get the path of the ISAPI Extension DLL
        hDll = getattr(sys, "isapidllhandle", None)
        import win32api
        dllName = win32api.GetModuleFileName(hDll)
        p1 = repr(dllName).split('?\\\\')
        p2 = p1[1].split('\\\\')
        sep = '\\'
        homedir = sep.join(p2[:-1])

        # the name of the Python module is in the PATH_INFO
        moduleToImport = env['PATH_INFO'].split('/')[1]

        pyFile = homedir + sep + moduleToImport + '.py'

        fd = None
        try:
            fd = win32file.CreateFile(pyFile, GENERIC_READ, FILE_SHARE_DELETE, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)
        except Exception as exc1:
            fd = None

        if fd is not None:
            # file exists, get mtime
            fd.close()
            mt = os.path.getmtime(pyFile)
        else:
            mt = None

        if mt is not None:
            h = None
            if not pyFile in loadedPages:
                # need a new import
                if homedir not in sys.path:
                    sys.path.insert(0, homedir)

                h = __import__(moduleToImport, globals(), locals(), [])
                # remember
                loadedPages[pyFile] = [mt, h]
            else:
                # retrieve handle to module
                h = loadedPages[pyFile][1]
                if mt != loadedPages[pyFile][0]:
                    # need to reload the page
                    reload(h)
                    loadedPages[pyFile][0] = mt

            if h is not None:
                if 'handler' in h.__dict__:
                    for x in h.handler(env, start_response):
                        yield x
                else:
                    start_response("400 Bad Request", [('Content-Type', 'text/html')])
            else:
                start_response("404 Not Found", [('Content-Type', 'text/html')])
                yield cr()
                yield cr("<title>Module not found</title>" \
                             "")
                yield cr("
404 Not Found
")
                yield cr("
No handle
")

        else:
            start_response("404 Not Found", [('Content-Type', 'text/html')])
            yield cr()
            yield cr("<title>Module not found</title>" \
                 "")
            yield cr("
404 Not Found
")
            yield cr("
That module (" + moduleToImport + ") was not found.
")

    else:
        start_response("500 Internal Server Error", [('Content-Type', 'text/html')])
        yield cr()
        yield cr("<title>Server Error</title>" \
                 "
Server Error - No ISAPI Found
")

# def test(environ, start_response):
#     '''Simple app as per PEP 333'''
#     status = '200 OK'
#     start_response(status, [('Content-type', 'text/plain')])
#     return ['Hello world from isapi!']

import isapi_wsgi
# The entry point(s) for the ISAPI extension.
def __ExtensionFactory__():
    return isapi_wsgi.ISAPISimpleHandler(request_handler)

def PostInstall(params, options):
    print "The Extension has been installed"

# Handler for our custom 'status' argument.
def status_handler(options, log, arg):
    "Query the status of the ISAPI?"
    print "Everything seems to be fine..."

if __name__=='__main__':
    # This logic gets invoked when the script is run from the command-line.
    # In that case, it installs this module as an ISAPI.

    #
    # The API provided by isapi_wsgi for this is a bit confusing.  There
    # is an ISAPIParameters object. Within that object there is a
    # VirtualDirs property, which itself is a list of
    # VirtualDirParameters objects, one per vdir.  Each vdir has a set
    # of scriptmaps, usually this set of script maps will be a wildcard
    # (*) so that all URLs in the vdir will be served through the ISAPI.
    #
    # To configure a single vdir to serve Python scripts through an
    # ISAPI, create a scriptmap, and stuff it into the
    # VirtualDirParameters object. Specify the vdir path and other
    # things in the VirtualDirParameters object.  Stuff that vdp object
    # into a sequence and set it into the ISAPIParameters thing, then
    # call the vaguely named "HandleCommandLine" function, passing that
    # ISAPIParameters thing.
    #
    # Clear as mud?
    #
    # Seriously, this thing could be so much simpler, if it had
    # reasonable defaults and a reasonable model, but I guess it will
    # work as is.

    from isapi.install import *

    # Setup the virtual directories -
    # To serve from root, set Name="/"
    sm = [ ScriptMapParams(Extension="*", Flags=0) ]
    vdp = VirtualDirParameters(Name="wsgi", # name of vdir/IIS app
                              Description = "ISAPI-WSGI Demo",
                              ScriptMaps = sm,
                              ScriptMapUpdate = "replace"
                              )

    params = ISAPIParameters(PostInstall = PostInstall)
    params.VirtualDirs = [vdp]
    cah = {"status": status_handler}

    # from isapi.install, part of pywin32
    HandleCommandLine(params, custom_arg_handlers = cah)

rawDescription: How to properly install isapi_wsgi on IIS for Python2.7?

description: Properly install isapi_wsgi on IIS for Python2.7


code:
import numpy as np
import pandas as pd
import os

fname = 'groupby.h5'

# create a frame
df = pd.DataFrame({'A': ['foo', 'foo', 'foo', 'foo',
                         'bar', 'bar', 'bar', 'bar',
                         'foo', 'foo', 'foo'],
                   'B': ['one', 'one', 'one', 'two',
                         'one', 'one', 'one', 'two',
                         'two', 'two', 'one'],
                   'C': ['dull', 'dull', 'shiny', 'dull',
                         'dull', 'shiny', 'shiny', 'dull',
                         'shiny', 'shiny', 'shiny'],
                   'D': np.random.randn(11),
                   'E': np.random.randn(11),
                   'F': np.random.randn(11)})

# create the store and append, using data_columns where I possibily
# could aggregate
with pd.get_store(fname) as store:
    store.append('df',df,data_columns=['A','B','C'])
    print "store:\n%s" % store

    print "\ndf:\n%s" % store['df']

    # get the groups
    groups = store.select_column('df','A').unique()
    print "\ngroups:%s" % groups

    # iterate over the groups and apply my operations
    l = []
    for g in groups:

        grp = store.select('df',where = [ 'A=%s' % g ])

        # this is a regular frame, aggregate however you would like
        l.append(grp[['D','E','F']].sum())

    print "\nresult:\n%s" % pd.concat(l, keys = groups)

os.remove(fname)

rawDescription: Pandas "Group By" Query on Large Data in HDFStore?


code:
for i, c1 in enumerate(cList[:-1]):
    for c2 in cList[i + 1:]:
        o = overlap(c1,c2)
        if not o is None:
            print "left: %s, right: %s, length: %s" % o

rawDescription: Python: optimizing pairwise overlaps between intervals


code:
import sys
import cgi
sys.stdout.write("Content-Type: application/x-www-form-urlencoded")
sys.stdout.write("\n")
sys.stdout.write("\n")
form = cgi.FieldStorage()
name = form.getvalue('name')
print name

rawDescription: Access Ajax data in python

description: Access Ajax data in python


code:
def p(x):
 print "Hello",x
say=lambda x:p

rawDescription: Interesting "Hello World" Interview

description: Interesting "Hello World" Interview


code:
import nltk
print nltk.__version__

rawDescription: FreqDist in NLTK not sorting output

description: FreqDist in NLTK not sorting output


code:
print '\"'
print '\\"'
print r'\"'

rawDescription: Python breaks parsing json with characters \"


code:
seen = []
for number in myList:
    if number in seen:
        print "Number repeated!"
    else:
        seen.append(number)

rawDescription: How to check if two numbers in a list are the same

description: Check if two numbers in a list are the same


code:
from pandas import DataFrame, MultiIndex
from itertools import product

index = range(2), range(2), range(2)
value = range(2 * 2 * 2)
frame = DataFrame(value, columns=['value'],
                  index=MultiIndex.from_product(index)).drop((1, 0, 1))
print frame

rawDescription: Transform Pandas DataFrame with n-level hierarchical index into n-D Numpy array


code:
import re
name = "old_#####"
fmt = re.sub(r'#+',lambda m: r'{{:0{}d}}'.format(len(m.group(0))),name)
print name
print fmt
for i in range(5):
    print fmt.format(i)

rawDescription: How do I add serial number by replacing character in string in Python?

description: Add serial number by replacing character in string in Python


code:
from bs4 import BeautifulSoup as bsoup

xml = """[<temperature time-layout="k-p24h-n7-1" type="maximum" units="Fahrenheit">
      <name>Daily Maximum Temperature</name>
        <value>65</value>
        <value>75</value>
        <value>88</value>
        <value>92</value>
        <value>92</value>
        <value>89</value>
        <value>83</value>
    </temperature>, <temperature time-layout="k-p24h-n6-2" type="minimum" units="Fahrenheit">
      <name>Daily Minimum Temperature</name>
        <value>38</value>
        <value>47</value>
        <value>53</value>
        <value>55</value>
        <value>56</value>
        <value>56</value>
    </temperature>, <temperature time-layout="k-p1h-n1-1" type="apparent" units="Fahrenheit">   <value>53</value>       </temperature>]"""

soup = bsoup(xml)
temps = soup.find_all("temperature")
max_temp = temps[0].find_all("value")[0].get_text()
print "Max temp: ", max_temp
min_temp = temps[1].find_all("value")[0].get_text()
print "Min temp: ", min_temp

rawDescription: overuse of lists and string formating

description: Overuse of lists and string formating


code:
max_y = max(y_av)  # Find the maximum y value
max_x = x[y_av.index(max_y)]  # Find the x value corresponding to the maximum y value
print max_x, max_y

rawDescription: Python find x value to corresponding max y value in plot


rawDescription: Assigning columns to a pandas dataframe constructed from a string


code:
import module

print module.__file__

rawDescription: How can you find where python imported a particular module from?

description: Find where python imported a particular module from


rawDescription: Structuring Plain Text to JSON

description: Structuring Plain Text to JSON


code:
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.dispensary div.name a")))

for dispensary in driver.find_elements_by_css_selector("div.dispensary div.name a"):
    print dispensary.get_attribute("href")

rawDescription: Scrapy Xpath construction producing empty brackets on dynamic site


code:
p=""
q=""
for line in open("file"):
    line=line.rstrip()
    if "Work Phone" in line:
       p="|"+p
    if p: print p
    p,q=q,line
print p
print q

rawDescription: Python - go to two lines above match

description: Python - go to two lines above match


rawDescription: Python Pandas Dataframe - Groupby and Average based on Condition


rawDescription: Python Removing Non Latin Characters

description: Python Removing Non Latin Characters


code:
#!/usr/bin/python2.6

import exceptions
import sys
from Foundation import NSObject, NSLog
from AppKit import NSApplication, NSApp, NSWorkspace
from Cocoa import *
from Quartz import CGWindowListCopyWindowInfo, kCGWindowListOptionOnScreenOnly, kCGNullWindowID
from PyObjCTools import AppHelper
import keycode

evtypes = dict(
    NSLeftMouseDown     = 1,
    NSLeftMouseUp       = 2,
    NSRightMouseDown    = 3,
    NSRightMouseUp      = 4,
    NSMouseMoved        = 5,
    NSLeftMouseDragged  = 6,
    NSRightMouseDragged = 7,
    NSMouseEntered      = 8,
    NSMouseExited       = 9,
    NSKeyDown           = 10,
    NSKeyUp             = 11,
    NSFlagsChanged      = 12,
    NSAppKitDefined     = 13,
    NSSystemDefined     = 14,
    NSApplicationDefined = 15,
    NSPeriodic          = 16,
    NSCursorUpdate      = 17,
    NSScrollWheel       = 22,
    NSTabletPoint       = 23,
    NSTabletProximity   = 24,
    NSOtherMouseDown    = 25,
    NSOtherMouseUp      = 26,
    NSOtherMouseDragged = 27
)

evtypes_rev = dict([[v,k] for k,v in evtypes.items()])

class Hooker(object):
    def __call__(self, *args, **kwargs):
        try:
            evt = kwargs.get('event')
            del kwargs['event']
            items = ' '.join( [ x[0]+"="+unicode(x[1]) for x in kwargs.iteritems()] )
            print "%20s | %22s | %s" % ( self.__class__.__name__, evtypes_rev[evt.type()], items)
        except Exception as e:
            print 'Horrific error!', e
            AppHelper.stopEventLoop()
            sys.exit(0)

class KeyHooker(Hooker): pass
class MouseButtonHooker(Hooker): pass
class MouseMoveHooker(Hooker): pass
class ScreenHooker(Hooker): pass

class SniffCocoa:

    def __init__(self):

        self.key_hook = KeyHooker()
        self.mouse_button_hook = MouseButtonHooker()
        self.mouse_move_hook = MouseMoveHooker()
        self.screen_hook = ScreenHooker()
        self.currentApp = None

    def createAppDelegate (self) :

        sc = self
        class AppDelegate(NSObject):
            def applicationDidFinishLaunching_(self, notification):
                mask = (
                          NSKeyDownMask
                        | NSKeyUpMask
                        | NSLeftMouseDownMask
                        | NSLeftMouseUpMask
                        | NSRightMouseDownMask
                        | NSRightMouseUpMask
                        | NSMouseMovedMask
                        | NSScrollWheelMask
                       )
                NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask, sc.handler)
        return AppDelegate

    def run(self):
        NSApplication.sharedApplication()
        delegate = self.createAppDelegate().alloc().init()
        NSApp().setDelegate_(delegate)
        self.workspace = NSWorkspace.sharedWorkspace()
        AppHelper.runEventLoop()

    def cancel(self):
        AppHelper.stopEventLoop()

    def handler(self, event):

        try:
            activeApps = self.workspace.runningApplications()
            for app in activeApps:
                if app.isActive():
                    if app.localizedName() != self.currentApp:
                        self.currentApp = app.localizedName()
                        options = kCGWindowListOptionOnScreenOnly
                        windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID)

                        for window in windowList:
                            if window['kCGWindowOwnerName'] == self.currentApp:
                                geom = window['kCGWindowBounds']
                                self.screen_hook( event=event,
                                                name = window['kCGWindowName'],
                                                owner = window['kCGWindowOwnerName'],
                                                x = geom['X'],
                                                y = geom['Y'],
                                                w = geom['Width'],
                                                h = geom['Height'])
                                break
                    break

            loc = NSEvent.mouseLocation()

            # mouse clicky buttons
            if event.type() in ( NSLeftMouseDown, NSRightMouseDown, NSLeftMouseUp, NSRightMouseUp):
                self.mouse_button_hook(event=event, x=loc.x, y=loc.y)

            # mouse scrolly buttons
            elif event.type() == NSScrollWheel:
                if event.deltaY() > 0 and event.deltaY() < 0:
                    self.mouse_button_hook(event=event, x=loc.x, y=loc.y)
                if event.deltaX() > 0 and event.deltaX() < 0:
                    self.mouse_button_hook(event=event, x=loc.x, y=loc.y)

            # keys down
            elif event.type() in ( NSKeyDown, NSKeyUp ):

                flags = event.modifierFlags()
                modifiers = [] # OS X api doesn't care it if is left or right
                if (flags & NSControlKeyMask):
                    modifiers.append('CONTROL')
                if (flags & NSAlternateKeyMask):
                    modifiers.append('ALTERNATE')
                if (flags & NSCommandKeyMask):
                    modifiers.append('COMMAND')

                self.key_hook(event=event, key=event.keyCode(), char=keycode.tostring( event.keyCode() ), mods=modifiers, is_repeat=event.isARepeat())

            # Mouse moved
            elif event.type() == NSMouseMoved:
                self.mouse_move_hook(event=event, x=loc.x, y=loc.y)
            else:
                pass

        except ( KeyboardInterrupt ) as e:
            print 'handler', e
            AppHelper.stopEventLoop()

if __name__ == '__main__':
    sc = SniffCocoa()
    sc.run()

rawDescription: Python capture Keystrokes values in text file on OS X


code:
while True:
    if getch() == "w":
        print "forward"

rawDescription: if statement including raw_input just prints whatever i type in to the keyboard

description: If statement including raw_input just prints whatever i type in to the keyboard


code:
sin = lambda x: math.sin(math.radians(x))
print sin (my_number_in_degrees)

rawDescription: Assign multiple functions to a single variable?


code:
from sklearn.decomposition import PCA
from sklearn.svm import SVC
from sklearn import cross_validation

Data=[list1,list2]
X = Data[0]
y = Data[1]
X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.4, random_state=0)
pca = PCA(n_components=2)# adjust yourself
pca.fit(X_train)
X_t_train = pca.transform(X_train)
X_t_test = pca.transform(X_test)
clf = SVC()
clf.fit(X_t_train, y_train)
print 'score', clf.score(X_t_test, y_test)
print 'pred label', clf.predict(X_t_test)

rawDescription: How to do PCA and SVM for classification in python

description: Do PCA and SVM for classification in python


code: print '\n'.join(' '.join(str(n) for n in row) for row in triangle)

rawDescription: getting pascals to print in multiple rows

description: Getting pascals to print in multiple rows


code:
print a
print b
print mask
print res

rawDescription: bounded sum or difference of arrays in numpy

description: Bounded sum or difference of arrays in numpy


code:
while response[0] != 'quit':
    response = raw_input("Please enter who you're looking for, or type 'exit' to quit the program: ").split()
    try:
        print "%s's %s is %s" % (response[0].capitalize(), response[1].lower(), people[response[0].capitalize()][response[1].lower()])
    except KeyError:
        print wrong,

rawDescription: Able to use any case in input to generate the same dict values in output


code:
print interpolate.bisplev(3.5,15,tck)

7.88671875

rawDescription: 2 dimensional interpolation problem

description: 2 dimensional interpolation problem


code:
import Tkinter as tk

# --- functions ---

def check():
    if status != 1:
        print 'check:', status

    # check again after 100ms
    master.after(100, check) # filename without ()

def callback():
    global status # because you use `=`

    status = 0

    print 'callback:', status

# --- main ---

status = 1

master = tk.Tk()

myB = tk.Button(master, text="Enter", command=callback)
myB.pack()

# check after 100ms
master.after(100, check) # filename without ()
# or call immediately
# check()

tk.mainloop()

rawDescription: While loop after tkraise?

description: While loop after tkraise


code:
a = [4,2]

def subseqs(x):
    def go(x, n):
        return zip(*(x[i:] for i in range(n))) + go(x, n-1) if n else []
    return go(x, len(x))

print subseqs(a)   # [(4, 2), (4,), (2,)]

rawDescription: Generate partial subsets in Python

description: Generate partial subsets in Python


code:
filtered = list(itertools.takewhile(lambda item: item%a != 0, array))
if len(filtered) != len(array):
    print array[len(filtered)]

rawDescription: In python how do I compare an array/list to a number


code:
for name in crawler.settings.attributes:
    value = crawler.settings.get(name)
    print name, '=', repr(value)

rawDescription: How do I log Scrapy settings?

description: Log Scrapy settings


code:
s = r"""u'\u2016'"""
print s
print ast.literal_eval(s)

rawDescription: How to specify a unicode and other escaped literals to Python 2.x ConfigParser

description: Specify a unicode and other escaped literals to Python 2.x ConfigParser


rawDescription: Is there a way to extract a dict in Python into the local namespace?


code:
x=[list('ABCD')]

def rotate(l,n):
    return l[n:] + l[:n]

while True:
    rl=rotate(x[-1], 1)
    if len(x)>1 and x[0]==rl:
        break
    else:
        x.append(rl)

print x
# [['A', 'B', 'C', 'D'], ['B', 'C', 'D', 'A'], ['C', 'D', 'A', 'B'], ['D', 'A', 'B', 'C']]

rawDescription: Create an offset list python

description: Create an offset list python


code:
lists = ['A', 'B', 'C', 'D']
nos = [4, 4, 1, 1]

a = 0

for idx, ln in enumerate(zip(lists,nos)):
    l, n = ln[0], ln[1]
    in_nos = range(1, n+1)
    for indx, in_no in enumerate(in_nos):
        out_no = a+indx+1
        print out_no   ##The result should be HERE
    a += n

rawDescription: A simple list simulation in python

description: A simple list simulation in python


code: print f.read()  # this calls the function

rawDescription: Python file.read() function output?

description: Python file.read() function output


code:
import lxml.html as lh

desiredvars = ['Street 1','Street 2','City', 'State', 'Zip']

doc=open('test.htm', 'r')
outhtml=lh.parse(doc)
doc.close()

myresultset = ((var, outhtml.xpath('//tr/td[contains(text(), "%s")]/span[@class="boldred"]/text()'%(var))[0]) for var in desiredvars)

for each in myresultset:
    print each

rawDescription: How to parse HTML table against a list of variables using lxml?

description: Parse HTML table against a list of variables using lxml


code:
import string

for test in ['name1', 'name2', 'name45', 'name1231231']:
    print int(test.strip(string.ascii_letters))

rawDescription: Python parse int from string

description: Python parse int from string


code: print eval(raw_input(), {"__builtins__":None}, {'pi':math.pi})

rawDescription: Regex include the negative lookbehind

description: Regex include the negative lookbehind


code:
from lxml.html import fromstring

html_data = """ <meta content="auth" name="param" />
 <meta content="I_WANT_THIS" name="token" />"""

tree = fromstring(html_data)
print tree.xpath('//meta[@name="token"]/@content')

rawDescription: How to parse HTML using the lxml.html library

description: Parse HTML using the lxml.html library


code:
from collections import Counter
x=raw_input('enter line\n')
if x.strip():
    x=x.split()
    count=Counter(x)
    dic=dict(count)
    print dic
else:
    print 'you entered nothing'

rawDescription: Cumulative numbers in python dictionaries


code:
my_dict = {(1, 1):'2345', (1, 2):'234', (1, 3):'5678', (1, 4):'2387'}

from collections import defaultdict
d = defaultdict(list)
for k, v in my_dict.items():
    for char in v:
        d[char].append(k)
print {v[0]:k for k, v in d.items() if len(v) == 1}

rawDescription: Python - Find characters in list of strings that are not duplicates


code:
def get_how_many_match(value_to_match, list_of_dice):
    return list_of_dice.count(value_to_match)

num_1 = get_how_many_match(2, [5, 2, 2, 5, 2])
num_2 = get_how_many_match(5, [5, 2, 2, 5, 2])
num_3 = get_how_many_match(4, [5, 2, 2, 5, 2])
num_4 = get_how_many_match(3, [5, 3, 4, 3, 3])
num_5 = get_how_many_match(6, [5, 2, 2, 6, 2])

print num_1, num_2, num_3, num_4, num_5

rawDescription: check if two values of lists have the same numbers return how many are same

description: Check if two values of lists have the same numbers return how many are same


code:
from dateutil.tz import tzoffset
from datetime import datetime
now = datetime.now(tzoffset('EDT', +4*60*60))
print now.isoformat()

rawDescription: Timestamp YYYY-MM-DDThh:mm:ss.sssTZD in Python


code:
if args.client:
    while True:
        msg = raw_input('> ')
        sock = gsocket.socket(gsocket.AF_INET, gsocket.SOCK_STREAM)
        sock.connect(('127.0.0.1', 4040))
        sock.sendall(msg)
        text = sock.recv(1024)
        sock.close()
        print text

rawDescription: How could a distributed queue-like-thing be implemented on top of a RBDMS or NOSQL datastore or other messaging system (e.g., rabbitmq)?


code:
import re
text = open('test.txt').read() # contains your string

urls = re.findall(r'href\s*=\s*(.+?)\s+onclick\s*=', text)
for url in urls:
    print url.replace('\\','')

rawDescription: Pattern match in file

description: Pattern match in file


rawDescription: Selenium/Python: Find <label for=""> element with no other attributes


code:
class Fred:
    def __repr__(self):
        return "value returned by repr"
    def __str__(self):
        return "value returned by str"
d = {1: Fred()}
print d
print d[1]

rawDescription: python output different when printed to std out than stored in dict

description: Python output different when printed to std out than stored in dict


code:
import os, urllib2
from cStringIO import StringIO

class Progress(object):
    def __init__(self):
        self._seen = 0.0

    def update(self, total, size, name):
        self._seen += size
        pct = (self._seen / total) * 100.0
        print '%s progress: %.2f' % (name, pct)

class file_with_callback(file):
    def __init__(self, path, mode, callback, *args):
        file.__init__(self, path, mode)
        self.seek(0, os.SEEK_END)
        self._total = self.tell()
        self.seek(0)
        self._callback = callback
        self._args = args

    def __len__(self):
        return self._total

    def read(self, size):
        data = file.read(self, size)
        self._callback(self._total, len(data), *self._args)
        return data

path = 'large_file.txt'
progress = Progress()
stream = file_with_callback(path, 'rb', progress.update, path)
req = urllib2.Request(url, stream)
res = urllib2.urlopen(req)

rawDescription: urllib2 POST progress monitoring

description: Urllib2 POST progress monitoring


code:
from math import floor, log10
class snumber(float):
        def powerise10(x):
            if x == 0: return 0 , 0
            Neg = x <0
            if Neg : x = -x
            a = 1.0 * x / 10**(floor(log10(x)))
            b = int(floor(log10(x)))
            if Neg : a = -a
            return a ,b

        def __str__(x):
            a , b = snumber.powerise10(x)
            if -3<b<3: return "%.4g" % x
            a = a * 10**(b%3)
            b = b - b%3
            return "%.4g*10^%s" %(a,b)

print "{}".format(snumber(100000))

rawDescription: How to define a new string formatter

description: Define a new string formatter


code:
#!/usr/bin/env python
from subprocess import Popen, PIPE
from threading import Thread

def pump_input(pipe):
    try:
       for i in xrange(1000000000): # generate large input
           print >>pipe, i
    finally:
       pipe.close()

p = Popen("/script1.pl | /script2.pl", shell=True, stdin=PIPE, stdout=PIPE,
          bufsize=1)
Thread(target=pump_input, args=[p.stdin]).start()
try: # read output line by line as soon as the child flushes its stdout buffer
    for line in iter(p.stdout.readline, b''):
        print line.strip()[::-1] # print reversed lines
finally:
    p.stdout.close()
    p.wait()

rawDescription: Using POpen to send a variable to Stdin and to send Stdout to a variable


code:
class loginForm(forms.Form):
    email = forms.CharField(label='Email')
    password = forms.CharField(widget=forms.PasswordInput(),label = "Password")

def login(request):
    if request.method == 'POST':
        form = loginForm(request.POST)
        if form.is_valid():
            entered_email = form.cleaned_data['email']
            entered_pass = form.cleaned_data['password']
            try:
                _user = user.objects.get(email=entered_email)
                stored_password = _user.password
                if stored_password == entered_pass:
                    session = get_current_session()
                    if session.is_active():
                        session.terminate()
                    session['email'] = entered_email
                    return  'REDIRECT AS REQUIRED'
                else:
                    print "INCORRECT PASSWORD"
                    form = loginForm()
                    return render(request, 'login.html',{ 'form': form })
            except:
                print "EMAIL NOT REGISTERED"
                form = loginForm()
                return render(request, 'login.html',{ 'form': form })
    else:
        form = loginForm()
        return render(request, 'login.html',{ 'form': form })

rawDescription: Session handling in Django Python with Google App Engine


code:
for entry in entries:
    print sql + entry.get()

rawDescription: printing a "for i in range" command

description: Printing a "for i in range" command


code:
class Globals:
    __master = None
    somevar = 1
    othervar = 2

    @staticmethod
    def get_master():
        if Globals.__master is None:
            Globals.__master = Globals()

        return Globals.__master

g1 = Globals.get_master()
g2 = Globals.get_master()
g1.somevar += 1

print g1.somevar
print g2.somevar

rawDescription: IPython with own scope?

description: IPython with own scope


code:
import glob
def main():
   args = sys.argv[1:]
   for file in glob.glob(args):
       print i

rawDescription: How to extract filenames from cmd input in python

description: Extract filenames from cmd input in python


code:
s = "Montréal"
print s
print repr(s)
ord(s[5])
hex(233)
s == "Montr\xe9al"
`s` == repr(s)

rawDescription: How to use csv.reader in python with french character like é,à,ç,ê,ë,

description: Use csv.reader in python with french character like é,à,ç,ê,ë,


code:
import urllib
import re

html = urllib.urlopen("http://jshawl.com/python-playground/").readlines()
for line in html :
    if "jesseshawl" in line:
        print line

rawDescription: re.findall printing the full text on a line of tekst

description: Re.findall printing the full text on a line of tekst


code:
for fruit_name, fruit_list in fruit_stand.items():
    # Ignore fruit_name and iterate over the fruits in fruit_list
    for color, quantity, cost in fruit_list:
        print color, quantity, cost

rawDescription: Breaking down instances of classes into lists, or: a better way to sum class variables?