code:
# importing libraries
import os

# defining location of parent folder
BASE_DIRECTORY = 'E:\Images'
output_file = open('output.txt', 'w')
output = {}
file_list = []

# scanning through sub folders
for (dirpath, dirnames, filenames) in os.walk(BASE_DIRECTORY):
    for f in filenames:
        if 'txt' in str(f):
            e = os.path.join(str(dirpath), str(f))
            file_list.append(e)

for f in file_list:
    print f
    txtfile = open(f, 'r')
    output[f] = []
    for line in txtfile:
        if 'Start Date:' in line:
            output[f].append(line)
        elif 'Format' in line:
            output[f].append(line)
        elif 'Resolution' in line:
            output[f].append(line)
tabs = []
for tab in output:
    tabs.append(tab)

tabs.sort()
for tab in tabs:
    output_file.write(tab + '\n')
    output_file.write('\n')
    for row in output[tab]:
        output_file.write(row + '')
    output_file.write('\n')
    output_file.write('----------------------------------------------------------\n')

raw_input()

rawDescription: Extract certain data from multiple .txt files using Python and RegEx


code:
class CustomWSGIApplication(webapp2.WSGIApplication):

    def __call__(self, environ, start_response):

        routes, settings, ns = get_app(environ)
        namespace_manager.set_namespace(ns)

        environ['PATH_INFO'] = '/%s%s' %(ns, environ.get('PATH_INFO'))

        for route in routes:
            r, h     = route # returns a tuple with mapping and handler
            newroute = ('/%s%s'%(ns, r), h,)
            self.router.add(newroute)

        if settings:
            self.config[ns] = settings

        self.debug  = debug

        with self.request_context_class(self, environ) as (request, response):
            try:
                if request.method not in self.allowed_methods:
                    # 501 Not Implemented.
                    raise exc.HTTPNotImplemented()

                rv = self.router.dispatch(request, response)
                if rv is not None:
                    response = rv
            except Exception, e:
                try:
                    # Try to handle it with a custom error handler.
                    rv = self.handle_exception(request, response, e)
                    if rv is not None:
                        response = rv
                except HTTPException, e:
                    # Use the HTTP exception as response.
                    response = e
                except Exception, e:
                    # Error wasn't handled so we have nothing else to do.
                    response = self._internal_error(e)

            try:
                return response(environ, start_response)
            except Exception, e:
                return self._internal_error(e)(environ, start_response)

rawDescription: serve different wsgiapplications depending on request domain on GAE with threadsafe:true

description: Serve different wsgiapplications depending on request domain on GAE with threadsafe:true


code:
import mechanize

br = mechanize.Browser()
br.open("http://www.example.com/")
# follow second link with element text matching regular expression
response1 = br.follow_link(text_regex=r"cheese\s*shop", nr=1)

print response1.geturl()

rawDescription: How to find the current URL in python mechanize?

description: Find the current URL in python mechanize


code:
processes = {}
for cmd in ['cmd1', 'cmd2', 'cmd3']:
    p = subprocess.Popen('cmd1', stdout=subprocess.PIPE)
    processes[p.stdout] = p

while len(processes):
    rfds, _, _ = select.select(processes.keys(), [], [])
    for fd in rfds:
        process = processses[fd]
        print fd.read()

        if process.returncode is not None:
            print "Process {0} returned with code {1}".format(process.pid, process.returncode)
            del processes[fd]

rawDescription: python run multi command in the same time

description: Python run multi command in the same time


code:
from itertools import izip
a = [1,2,3,4,5]
b = [5,4,3,2,1]
c = izip(a, b)
c
for x, y in c:
    print x, y

rawDescription: Is there a function which can replace "zip" function in Python?


code:
with open("exports.txt",'r') as infile:
    exports = {}
    for line in infile:
        parts = line.partition('\t')
        exports[parts[0]] = parts[-1].strip().split(', ')

for country, exports in exports.iteritems():
    print country
    print exports

rawDescription: How do I print something and then its list?

description: Print something and then its list


code:
from operator import itemgetter

def getPairClusters( l ):

    # first, we just store all possible pairs sequentially
    # clustering will happen later
    pairs = []

    for i in xrange( len( l)  ):
        for j in xrange(i+1, len( l ) ):
            pair = l[i] + l[j]
            pairs.append( ( pair, i, j ) )
    pairs.sort(key=itemgetter(0))

    # pairs = [ (4, 1, 3), (5, 0, 3), (7, 0, 1), (7, 2, 3), (9, 1, 2), (10, 0, 2)]
    # a list item of pairs now contains a tuple (like (4, 1, 3)) with
    # * the sum of two l items: 4
    # * the index of the two l items: 1, 3

    # now clustering starts
    # we want to find neighbouring items as
    # (7, 0, 1), (7, 2, 3)
    # (since 7=7)

    pairClusters = []

    # flag if we are within a cluster
    # while iterating over pairs list
    withinCluster = False

            # iterate over pair list
    for i in xrange(len(pairs)-1):
        if not withinCluster:
            if pairs[i][0] == pairs[i+1][0]:
                # if not within a cluster
                # and found 2 neighbouring same numbers:
                # init new cluster
                pairCluster = [ ( pairs[i][1], pairs[i][2] ) ]
                withinCluster = True
        else:
            # if still within cluster
            if pairs[i][0] == pairs[i+1][0]:
                pairCluster.append( ( pairs[i][1], pairs[i][2] ) )
            # else cluster has ended
            # (next neighbouring item has different number)
            else:
                pairCluster.append( ( pairs[i][1], pairs[i][2] ) )
                pairClusters.append(pairCluster)
                withinCluster = False

    return pairClusters

l = [4,3,6,1]

print getPairClusters(l)

rawDescription: Python: fast dictionary of big int keys

description: Python: fast dictionary of big int keys


code:
T = int(raw_input())
N = [int(raw_input()) for i in range(T)]
N[:] = [x-2 for x in N]
L2 = []
for j in N:
  L1 = [1, 1]
  for k in range(j):
    L1.append(L1[-1]+L1[-2])
  L2.append(L1)
print L2

rawDescription: fibonacci series using lists in python

description: Fibonacci series using lists in python


code:
import itertools

for z, x, c, v in itertools.permutations(lst):
    if z+x-c==v:
        print z,x,c,v

rawDescription: Python: iterate through a list

description: Python: iterate through a list


code:
x = raw_input('How many numbers do you want to play?')
for i in xrange(int(x)):
   print random.randrange(1,81)

rawDescription: print statement in for loop only executes once

description: Print statement in for loop only executes once


code:
def average(data):
    highest = {}
    index = 0
    while True:
        for i in data:
            if i[0] in highest:
                highest[i[0]].append(i[1])
            else:
                highest[i[0]] = [i[1]]
        for i in highest:
            highest[i] = sum(highest[i]) / len(highest[i])
        answer = 0
        for i in highest:
            if highest[i] >= answer:
                answer = i
        return answer
print average(data)

rawDescription: Average based on first element of list of lists python


code:
k = 1 # or 2, or whatever
with open('datafile', 'r') as f:
    since_tag = 0
    for line in f:
        line = line.strip()
        if line == 'tag':
            print('tag found!')
            since_tag = 0
        if since_tag == k:
            print "kth number found: ", line
        since_tag += 1

rawDescription: How to proceed next line while reading specific line?

description: Proceed next line while reading specific line


code:
def myFunc(*args, **kwargs):
  # This function accepts arbitary arguments:
  # Keywords arguments are available in the kwargs dict;
  # Regular arguments are in the args tuple.
  # (This behaviour is dictated by the stars, not by
  #  the name of the formal parameters.)
  print args, kwargs
myFunc()
myFunc(2)
myFunc(2,5)
myFunc(b = 3)
import dis
dis.dis(myFunc)

rawDescription: Is it possible to declare a function without arguments but then pass some arguments to that function without raising exception?


code:
class tps():
    def __init__(self):
        #temperature/pressure sensor setup
        self.bmp = BMP085(0x77)
        self.temp = None
        self.pressure = None
#       If you want to initialize your tps object with sensor data, you can call your updater method here.
        self.updateTempAndPressure()

#   Here's a function that you can call whenever you want updated data from the sensor
    def updateTempAndPressure(self):
        self.temp = self.bmp.readTemperature()*1.8+32
        self.pressure = self.bmp.readPressure()*0.0002953

class data():
    def __init__(self):
        self.tp = tps()
        self.savedata()

    def savedata(self):
#       Call the method that gets updated data from the sensor
        self.tp.updateTempAndPressure()
        print self.tp.temp, self.tp.pressure
        sleep(4)
#       Call the update method again
        self.tp.updateTempAndPressure()
        print self.tp.temp, self.tp.pressure

data()

rawDescription: Python: Update Sensor Data to Variable

description: Python: Update Sensor Data to Variable


code:
from lxml import etree

doc = etree.parse('thisxmlfile.xml')

# There is only one "season" element
season = doc.find('season').get('season')

# XPath query relative to root node
for conference in doc.xpath('conference'):
    # XPath query relative to "conference" node
    for team in conference.xpath('division/team'):
        print season, conference.get('label'),
        print team.get('city'), team.get('name'), team.get('alias')

rawDescription: Parsing XML with LXML and Python

description: Parsing XML with LXML and Python


code:
i = 1240832864000L
i
print i

'<script type="text/javascript"> var num = %s; </script>' % i

rawDescription: Print long integers in python

description: Print long integers in python


code:
import os
found =False
file = open("/home/pi/Desktop/AutoJobs/netdata.py","r")
for line in file:
        if int(float(line.rstrip())) == 7:
                found = True
                os.system('sudo python /home/pi/Desktop/AutoJobs/tvOn.py')
file.close()
if not found:
        print "Add your code here."

rawDescription: Python: File Reader int and if clauses

description: Python: File Reader int and if clauses


code:
import os

try:
    os.symlink("src", "dest")
except OSError:
    print "cant do it :("

rawDescription: Finding out if the current filesystem supports symbolic links


code:
import random
health = 20
enemy_health = 20

def punch():
    global enemy_health
    x = random.randint(1,3)
    enemy_health -= x
    if x == 3:
        print"your hit was very effective enemy lost 3 hp"
    if x == 2:
        print "Your punch was effective enemy lost 2 hp"
    if x == 1:
        print "enemy lost 1 point"
    print "Enemy Health is", enemy_health

def kick():
    global enemy_health
    x = random.randint(1,5)
    enemy_health -= x
    if x > 3:
        print "your kick was very effective enemy lost %d hp" % x
    if x > 1 < 3:
        print "Your kick was effective enemy lost %d hp" % x
    if x == 1:
        print "enemy lost 1 point"
    print "Enemy Health is", enemy_health

def attackChoice(c):
    if c == "punch":
        punch()
    if c == "kick":
        kick()

while True:
    c = raw_input("Choice Attack\nKick Or Punch: ")
    attackChoice(c)

rawDescription: Variable assignment in function

description: Variable assignment in function


code: for url in re.findall('(http://\S+)', someString): print url

rawDescription: Extract All urls from a string in python


code:
# Define the user class - what data do we store about users:

class User(object):
    def __init__(self, user_name, first_pet):
        self.user_name = user_name
        self.first_pet = first_pet

# Now gather the actual list of users

users = []
while someCondition:
    user_name, first_pet = getUserDetails()
    users.append(User(user_name, first_pet))

# Now we can use it

print "The first users name is:"
print users[0].user_name

rawDescription: Converting user input to variable names (python 2.7)


code:
for rule in sg.rules:
  if len(rule.grants) > 1:
    for grant in rule.grants:
      st = sg, sg.id, "inbound:", rule, " source:", [grant]
      print st
  else:
      st = sg, sg.id, "inbound:", rule, " source:", rule.grants
      print st

rawDescription: change loop output to per line instead of a group

description: Change loop output to per line instead of a group


code:
text=['words words','words words words','words words words words']
pyramid(text)
print open("abc").read()

rawDescription: selecting the number of the lines in .txt file to which to write

description: Selecting the number of the lines in .txt file to which to write


code:
for k in frequencies:
    print 'bigram: %r frequency: %s' % (k, frequencies[k])

rawDescription: Odd Python dictionary and string behavior


code:
from random import randint
from time import sleep

f = open("2GB.file", "rb")
linemap = [] # Keeps the start and end position of each line
for x in f:
    linemap.append((f.tell(), len(x)))
    # It is slightly faster to have start and length than only start and then f.readline()
    # But either way will work OK for you

def getline (index):
    line = linemap[index]
    f.seek(line[0])
    return f.read(line[1])

def getslice (start=0, stop=None):
    if stop==None: stop = len(linemap)
    howmany = 0
    for x in xrange(start, stop): howmany += linemap[x][1]
    f.seek(linemap[start][0])
    return f.read(howmany).splitlines(1)

while True:
    print getline(randint(0, len(linemap)-1))
    sleep(2)

rawDescription: Keeping files in memory for long times

description: Keeping files in memory for long times


code:
components = "Set(['LPE', 'CLK'])"
x = components.lstrip("Set([").rstrip("])")
for i in x.split(", "):
    z = i.lstrip("'").rstrip("'")
    print z

rawDescription: Get value inside array?

description: Get value inside array


code:
import requests
from bs4 import BeautifulSoup
from requests.exceptions import InvalidURL, MissingSchema
import re

urlx = "http://www.cvs.com/store-locator/cvs-pharmacy-address/557+South+Atlantic+Avenue-Aberdeen-NJ-07747/storeid=2511"
cookies = requests.get(urlx).cookies
rx = requests.get(urlx, cookies=cookies, headers={'user-agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'})

soupx = BeautifulSoup(rx.content)
lat = soupx.find(attrs={'id':'toLatitude'})['value']
long = soupx.find(attrs={'id':'toLongitude'})['value']
street_address = ", ".join([soupx.find(attrs={'itemprop':'streetAddress'}).text,soupx.find(attrs={'itemprop':'addressLocality'}).text, soupx.find(attrs={'itemprop':'addressRegion'}).text ])
print lat, long, street_address

rawDescription: Can a website know that a request is coming through the "requests" python library?


code:
import re
string
print '\n'.join(re.findall(r'(?<=data-name\=\")[^"]+(?=\")', string))

rawDescription: Searching a string of text and copying following data in Python


code:
import sys

d = {}
for line in sys.stdin:
    parts = line.split("=",2)
    if len(parts) < 2:
        continue
    k = parts[0].strip()
    v = parts[1].strip()
    d[k] = v

print d['CENTRAL_BODY']

rawDescription: Human-readable binary data using Python

description: Human-readable binary data using Python


code:
def getData(i):
    while True:
        print "Sleep for %d"%i
        time.sleep(i)
        myList.append(compareValues())

rawDescription: Reading the results from an infinite loop using threads in python


code:
class DomTreeItem(TreeItem):
   def __init__(self, node):
      self.node = node
   def GetText(self):
      node = self.node
      if node.nodeType == node.ELEMENT_NODE:
         return node.nodeName
      elif node.nodeType == node.TEXT_NODE:
         return node.nodeValue
   def IsExpandable(self):
      node = self.node
      return node.hasChildNodes()
   def GetSubList(self):
      parent = self.node
      children = parent.childNodes
      prelist = [DomTreeItem(node) for node in children]
      itemlist = [item for item in prelist if item.GetText().strip()]
      return itemlist
   def GetSelectedIconName(self):
      print self.node.nodeName
   def OnDoubleClick(self):
      print "double-clicked"

rawDescription: Python Tkinter: obtain tree node information


code:
for var in dir(character):
    if var[:2] != '__':
        print '%s:' % var, getattr(character, var)

rawDescription: Listing all the variables in a Python class


code:
import numpy as np
from scipy.io import wavfile

fs = 44.1e3
t = np.arange(0, 1.0, 1.0/fs)

f1 = 440
f2 = 600

x = 0.5*np.sin(2*np.pi*f1*t) + 0.5*np.sin(2*np.pi*f2*t)

fname = 'output.wav'
wavfile.write( fname, fs, x )

fs, data = wavfile.read( fname )

print fs, data[:10]

rawDescription: looking for reading audio wave values in python

description: Looking for reading audio wave values in python


code:
import sys
li = [2,5,-34,0,389,202,8]
m = sys.maxint
print [e for e in li if e == e%m]

rawDescription: Python remainder operator using list

description: Python remainder operator using list


code:
import pbapi

import webbrowser
import cPickle
import os
import re
import sys
from xml.etree import ElementTree

__author__ = "leoluk"

###############################################
##               CONFIGURATION               ##
###############################################

# File in which the oAuth token will be stored
TOKEN_FILE = "token.txt"

IMAGE_PATH = r"D:\Eigene Dateien\Bilder\SC\foo.png"

IMAGE_RECORD = {
    "type": 'image',
    "uploadfile": '@'+IMAGE_PATH,

    "title": "My title", # <---
    "description": "My description", # <---
}

ALBUM_NAME = None # default album if None

API_KEY = "149[..]"
API_SECRET = "528[...]"

###############################################
##                   SCRIPT                  ##
###############################################

api = pbapi.PbApi(API_KEY, API_SECRET)

api.pb_request.connection.cache = None

# Test if service online
api.reset().ping().post()

result = api.reset().ping().post().response_string

ET = ElementTree.fromstring(result)

if ET.find('status').text != 'OK':
    sys.stderr.write("error: Ping failed \n"+result)
    sys.exit(-1)

try:
    # If there is already a saved oAuth token, no need for a new one
    api.username, api.pb_request.oauth_token = cPickle.load(open(TOKEN_FILE))
except (ValueError, KeyError, IOError, TypeError):
    # If error, there's no valid oAuth token

    # Getting request token
    api.reset().login().request().post().load_token_from_response()

    # Requesting user permission (you have to login with your account)
    webbrowser.open_new_tab(api.login_url)

    raw_input("Press Enter when you finished access permission. ")

    #Getting oAuth token
    api.reset().login().access().post().load_token_from_response()

# This is needed for getting the right subdomain
infos = api.reset().album(api.username).url().get().response_string

ET = ElementTree.fromstring(infos)

if ET.find('status').text != 'OK':
    # Remove the invalid oAuth
    os.remove(TOKEN_FILE)
    # This happend is user deletes the oAuth permission online
    sys.stderr.write("error: Permission deleted. Please re-run.")
    sys.exit(-1)

# Fresh values for username and subdomain
api.username = ET.find('content/username').text
api.set_subdomain(ET.find('content/subdomain/api').text)

# Default album name
if not ALBUM_NAME:
    ALBUM_NAME = api.username

# Debug :-)
print "User: %s" % api.username

# Save the new, valid oAuth token
cPickle.dump((api.username, api.oauth_token), open(TOKEN_FILE, 'w'))

# Posting the image
result = (api.reset().album(ALBUM_NAME).
          upload(IMAGE_RECORD).post().response_string)

ET = ElementTree.fromstring(result)

if ET.find('status').text != 'OK':
    sys.stderr.write("error: File upload failed \n"+result)
    sys.exit(-1)

# Now, as an example what you could do now, open the image in the browser

webbrowser.open_new_tab(ET.find('content/browseurl').text)

rawDescription: Python: Upload a photo to photobucket

description: Python: Upload a photo to photobucket


rawDescription: How does one find the currency value in a string?

description: Find the currency value in a string


code:
def main():
    legislatorsTxtFile = open("names.txt","r").read()
    stateName = raw_input("enter a state abv.")
    districtNum = raw_input("enter district Number")
    lines = legislatorsTxtFile.split('\n')
    matches = []
    for line in lines:
        cols = line.split(',')
        if stateName == cols[5] and districtNum == cols[6]:
            matches.append(line)

    print matches

main()

rawDescription: Searching for filenames containing particular strings


code:
@app.before_first_request
def load_huge_file():
    #Do some things and assign data from a large file to loaded_data
    print "Huge data set loaded!"
    global shared_data
    shared_data = loaded_data

rawDescription: Flask - caching result of data load

description: Flask - caching result of data load


code:
class Basket(object):

  def __init__(self):
    # add all the properties
    setattr(self.__class__, 'Apple', property(lambda s : 'Apple') )
    setattr(self.__class__, 'Pear', property(lambda s : 'Pear') )

  # normal property
  Air = property(lambda s : "Air")

if __name__ == "__main__":
  b = Basket()
  print b.Air # outputs: "Air"
  print b.Apple # outputs: "Apple"
  print b.Pear # outputs: "Pear"

rawDescription: How to define properties in __init__

description: Define properties in __init__


rawDescription: Python join - quoting values

description: Python join - quoting values


code:
from mechanize import Browser
browser = Browser()
response = browser.open('http://www.google.com')
print response.code

rawDescription: Python Mechanize.Browser.Open(url) Status Code


code:
from random import choice

class A(object):
    def __init__(self):
        self.name = 'in A'

class B(object):
    def __init__(self):
        self.name = 'in B'

class C(object):
    def __init__(self):
        self.name = 'in C'

if __name__ == "__main__":
    classes = ['A', 'B', 'C']
    class_name = choice(classes)
    print class_name

    # 1st way
    obj = globals()[class_name]()
    print obj.name

    # 2nd way
    import sys
    obj = getattr(sys.modules['__main__'], class_name)()
    print obj.name

    # 3rd way - not recommended
    obj = eval(class_name)()
    print obj.name

rawDescription: Get class object from string

description: Get class object from string


code:
print '''
<title>My first Python CGI app</title>

Hello, 'world'!

'''

rawDescription: Printing HTML in Python CGI

description: Printing HTML in Python CGI


rawDescription: Minimum of itertools.product in python

description: Minimum of itertools.product in python


code:
from __future__ import with_statement
from hashlib import md5, sha1

filename = 'hash_one-pass.py'

hashes = md5(), sha1()
chunksize = max(4096, max(h.block_size for h in hashes))
with open(filename, 'rb') as f:
    while True:
        chunk = f.read(chunksize)
        if not chunk:
            break
        for h in hashes:
            h.update(chunk)

for h in hashes:
    print h.name, h.hexdigest()

rawDescription: How can I create multiple hashes of a file using only one pass?

description: Create multiple hashes of a file using only one pass


code:
# "images" will contain exactly the same info as "product['image']", but
# keyed by the URL.
images = { d['url']:d for d in product['image'] }

# Print every line implied by the first data set
for url in product['image_urls']:
    # But only if the data is actually in the second data set
    if url in images:
        image = images[url]
        print url, image['url'], image['path'], image['checksum']
        # Or ...
        # Image.objects.create(article=id,
        #                      image_urls=url,
        #                      url=image['url'],
        #                      path=image['path'],
        #                      checksum=image['checksum'])
        # Or fancier,
        # Image.objects.create(article=id, images_urls=url, **image)

rawDescription: python combine lists with order

description: Python combine lists with order


code:
import atexit

@atexit.register
def goodbye():
    print "You are now leaving the Python sector."

rawDescription: Run code at Pyramid shutdown

description: Run code at Pyramid shutdown


code:
f = open("template.file", "r")
t = open("File1").read()

for line in f:
    if line.rstrip() in t:
        print "found " + line
    else:
        print line + " Not found"

rawDescription: Search for string with wildcard in file python


code:
import thread
import time

def main():
    try:
        m = thread.start_new_thread(killable_input, tuple())
        while 1:
            time.sleep(0.1)
    except KeyboardInterrupt:
        print "exception"

def killable_input():
    w = thread.start_new_thread(normal_input, tuple())
    i = thread.start_new_thread(wait_sometime, tuple())

def normal_input():
    s = raw_input("input:")

def wait_sometime():
    time.sleep(4) # or any other condition to kill the thread
    print "too slow, killing imput"
    thread.interrupt_main()

if __name__ == '__main__':
    main()

rawDescription: Python: How to quit CLI when stuck in blocking raw_input?


code:
people = {
    "Paul": [1,2],
    "Joe": [3,4]
}

def myFunc(name):
    return people[name]

print myFunc("Paul")
print myFunc("Joe")

rawDescription: Using variable to access another variable


code:
import os
import webbrowser
import time
import socket
import urllib2
import subprocess
import socket

URL = "http://automation.whatismyip.com/n09230945.asp"
DIR = '/Desktop/hma'
HMA = ['./hma-start', '-r']
WAIT_TIME = 60 * 30 # 30 min
GET_IP = lambda: urllib2.urlopen(URL).read()

if __name__ == '__main__':
    external = internal = GET_IP()
    print "Internal IP Address is %s" % internal
    try:
        os.chdir(DIR)
    except OSError:
        print "%s not found" % DIR

    print "External IP Address is ", external
    while True:
        external = GET_IP()
        if external != internal:
            print "Proxied"
            time.sleep(WAIT_TIME)
        else:
            print "Not Proxied"
            proc = subprocess.Popen(HMA)
            proc.wait()

rawDescription: python subprocess with hma

description: Python subprocess with hma


code:
date = 'Date: April 1st, 2015'
import re
regex = re.search(
    r'Date:\s([A-Z]{1}[a-z]*)\s([0-9]{1,2})[a-z]{2},\s([0-9]{4})',
    date,
)
parsed_date = ' '.join(regex.groups())
from datetime import datetime
date_time = datetime.strptime(parsed_date, '%B %d %Y')

print date_time
#output
'2015-04-01 00:00:00'

rawDescription: Need Regex pattern for this Date

description: Need Regex pattern for this Date


code:
for i in ['a', 'b', 'c', 'd']:
    print i

# The code at this indentation is not part of the above block.
print 42

rawDescription: "Finishing" a for loop in Python

description: "Finishing" a for loop in Python


code:
def on_checkbutton1_toggled(self, widget, data=None):
    global test
    chkbtn1 = self.builder.get_object("checkbutton1")
    print "BUTTON CHECKED -",chkbtn1.get_active()
    if chkbtn1.get_active() == 0:
        test = 0
    if chkbtn1.get_active() == 1:
        test = 1
    print test

def __init__(self):

    global test

rawDescription: manipulate python variable inside a GTK action listener

description: Manipulate python variable inside a GTK action listener


code:
from collections import deque
from itertools import islice, dropwhile
import csv

def iscomment(row): return row[0][0] == '#'

with gzip.open(sys.argv[1], 'r') as f:
    reader = dropwhile(iscomment, csv.reader(f, delimiter="\t"))
    history = deque(islice(reader, 2), maxlen=2)

    for row in reader:
        if history[-1][1] in myHdictionary:
            print history[0]
            print history[-1]
            print row
        history.append(row)

rawDescription: how to read previous and next line if the current line is valid for an IF statement in Python

description: Read previous and next line if the current line is valid for an IF statement in Python


code:
# a.py
some_list = [1,2,3,4]

# b.py
import a
print a.some_list

rawDescription: Referencing another project

description: Referencing another project


code:
class Car(object):

  def __init__(self, make):

      # Set the user-defined 'make' property on the self object
      self.make = make

      # Set the 'horn' property on the 'self' object to 'BEEEEEP'
      self.horn = 'BEEEEEP'

  def honk(self):

      # Now we can make some noise!
      print self.horn

# Create a new object of type Car, and attach it to the name `lambo`.
# `lambo` in the code below refers to the exact same object as 'self' in the code above.

lambo = Car('Lamborghini')
print lambo.make
lambo.honk()

rawDescription: What does self do?

description: What does self do


code:
if line.startswith(">"):
    seqid = re.search('Segment:[(0-9)]',line).group()
    seqID.append(seqid)
    sequence = ""
elif len(line.strip()):
    sequence += line.strip()  # three lines will make a sequence
else: #Find the Length and GC%
    numSeq = len(sequence)
    #print seqid, numSeq
    GCPercent = (( sequence.count('G') + sequence.count('C') ) / (numSeq)*100)
    allGC.append(GCPercent);
    sequences.append(sequence)
    seqLen.append(numSeq)
    print "%s\t%d\t%.2f" % (seqid,numSeq,GCPercent)

rawDescription: Python - Removing whitespace after already stripping lines?


code:
def swap():
    #input files
    infile1 = open(r"Z:\ped_test.txt", 'rb')
    keyfile = open(r"Z:\ruid_respid_test.txt", 'rb')

    #output file
    outfile=open(r"Z:\ped_testRESPID.txt", 'wb')
    # create dictionary of RUID-RESPID
    COLUMN = 1 #Column containing RUID
    RESPID={}
    for k in keyfile:
        kList = k.split('\t', 2)   # minor: jut grab what you need
        if kList[0] and kList[0] not in RESPID: # minor: do the cheap test first
            RESPID[kList[0]]=kList[1]
    #print RESPID
    print "creating RESPID-RUID xwalk dictionary is done"

    print "Start creating new file"
    print str(datetime.datetime.now())
    count=0
    for line in infile1:
     #if not re.match('#', line): #if there is a header
        sline = line.split('\t', 2) # minor: just grab what you need
        #slen = len(sline)
        RUID = sline[COLUMN]
        #print RUID
        C0 = sline[0]
        #print C0
        DAT=sline[2:]

        # the biggie, just use a lookup
        #for key in RESPID:
        #   if key==RUID:
        #       NewID=RESPID[key]
        rows = '\t'.join([sline[0], RESPID.get(RUID, sline[1]), sline[2]])

        #row=str(C0+'\t'+NewID)
        #for a in DAT:
        #   row=row+'\t'+a
        #print row
    outfile.write(row)
    outfile.write('\n')

    infile1.close()
    keyfile.close()
    outfile.close()

    print "All Done: RESPID replacement is complete"
    print str(datetime.datetime.now())

rawDescription: Swapping IDs & Python Performance

description: Swapping IDs & Python Performance


code:
sentence = raw_input("   ")
length = len(sentence)
index = length - 1
reversed_sentence = ''

while index >= 0:
    #letter is the last letter of the original sentence
    letter = sentence[index]
    #make the first letter of the new sentence the last letter of the old sentence
    reversed_sentence += letter
    #update the index so it now points to the second to last letter of the original sentence
    index = index - 1

print reversed_sentence

rawDescription: how to reverse a sentence with a while loop

description: Reverse a sentence with a while loop


code:
def handle_data(self, data):
    tag = self.get_starttag_text().replace("<","").replace(">","")
    tag_words = tag.split(" ")
    if len(tag_words) > 0 and tag_words[0].endswith("title"):
        print data

rawDescription: how to extract specified text in HTML using SGMLParser

description: Extract specified text in HTML using SGMLParser


code:
from urlparse import urlparse

def parse(self, response):
    parsed_uri = urlparse(response.url)
    domain = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri)
    print domain

rawDescription: How can i obtain a domain name with Scrapy?

description: Obtain a domain name with Scrapy


code:
from collections import Counter
def duplicate_encode(word):
  counter = Counter(word)
  return "".join(")" if counter[c] > 1 else "(" for c in word)
print duplicate_encode("attachment") # "))))((((()"

rawDescription: Python 2: substitution of chars in a string


code:
from collections import defaultdict

specific_characters = ['X', 'Y']
counter_dict = defaultdict(lambda: 0)

with open("old.txt", "r") as in_file, open("new.txt","a") as out_file:
  while True:
    c = in_file.read(1)
    if not c:
      break
    if c in specific_characters:
      out_file.write(c)
      counter_dict[c] += 1

# printing just X and Y for your specific case.
# the counter will have count of any characters from the specific_characters list.

print "Count of X: ", counter_dict['X']
print "Count of Y: ", counter_dict['Y']

rawDescription: Keep only specific characters from one text file and write these in a new text file


code:
import time
class something(object):
    def __init__(self,c):
        self.c=c
    def inc(self):
        new = self.c+1
        # if the thread is interrupted by another inc() call its result is wrong
        time.sleep(0.001) # sleep makes the os continue another thread
        self.c = new

x = something(0)
import threading

for _ in range(10000):
    threading.Thread(target=x.inc).start()

print x.c # ~900 here, instead of 10000

rawDescription: Is this simple python code thread safe?

description: Is this simple python code thread safe


code:
import collections

c = collections.Counter()

with open('file.txt') as f:
    for text in f:
        c.update( [int(text.strip())] )

c_sorted = sorted(c.most_common())

for key, val in c_sorted:
    print val, key

rawDescription: Python similar uniq -c command?

description: Python similar uniq -c command


code:
class baseclass(object):
    def __init__(self):
        print 'hey this is the base'

    def _deco(func):
        def wrapper(*arg):
            res = func(*arg)
            print 'I\'m a decorator. This is fabulous, but that colour, so last season sweetiedarling'
            return res
        return wrapper

    @_deco
    def basefunc(self):
        print 'I\'m a base function'

    @_deco
    def basefunc2(self):
        print "I'm another base function"

   #no more uses of _deco in this class
    _deco = staticmethod(_deco)
   # this is the key. it must be executed after all of the uses of _deco in
   # the base class. this way _deco is some sort weird internal function that
   # can be called from within the class namespace while said namespace is being
   # created and a proper static method for subclasses or external callers.

class otherclass(baseclass):
    def __init__(self):
        super(otherclass, self).__init__()
        print 'other class'

    @baseclass._deco
    def meh(self):
        print 'I\'m a function'

rawDescription: Accessing a decorator in a parent class from the child in Python


code:
def fn (a, b, c = 1):
    return a * b + c

print fn (1, 2)                # returns 3, positional and default.
print fn (1, 2, 3)             # returns 5, positional.
print fn (c = 5, b = 2, a = 2) # returns 9, named.
print fn (b = 2, a = 2)        # returns 5, named and default.
print fn (5, c = 2, b = 1)     # returns 7, positional and named.
print fn (8, b = 0)            # returns 1, positional, named and default.

rawDescription: Positional argument v.s. keyword argument


code:
import sys
import getopt

def main(argv):
    try:
        opts, args = getopt.getopt(argv,"hi:",["ifile="])
    except getopt.GetoptError:
      print 'test.py -i <inputfile>'
      sys.exit(2)
    for opt, arg in opts:
        if opt in ("-i", "--ifile"):
            inputfile = arg
    print 'Input file is "', inputfile

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

rawDescription: Running python script with arguments in microsoft visual studio


code:
def handleupload(self, block):
    self.pbar.update(self.pbar.currval+len(block))

def upload(self):
    try:
        if os.path.getsize(self.filename) == 0:
            print "%s 0 bytes passing..." % self.filename
        else:
            print "Uploading %s-%d-bytes" % (self.filename, self.ftp.size(self.filename))
            self.pbar=ProgressBar(widgets=[FileTransferSpeed(),' ', Bar(marker=RotatingMarker()), ' ',
                                                    Percentage(),' ', ETA()],    maxval=os.path.getsize(self.filename)).start()
            self.ftp.storbinary("STOR " + self.filename, open(self.filename),
                                                        callback = s.handleupload, blocksize = 1024)
            self.pbar.finish()
            print "Finished"
    except (error_perm, error_temp, Exception), self.exc:
        print self.exc

rawDescription: Python: ftp and progressbar 2.3

description: Python: ftp and progressbar 2.3


code:
for line in tailer.follow(open('test.txt')):
    print line

rawDescription: python, tailer and logrotate

description: Python, tailer and logrotate


code:
import time

while 1:
    where = file.tell()
    line = file.readline()
    if not line:
        time.sleep(1)
        file.seek(where)
    else:
        print line, # already has newline

rawDescription: Read from a log file as it's being written using python


code:
import urlparse
url = '/citations?view_op=view_citation&hl=en&user=11JgipcAAAAJ&pagesize=100&citation_for_view=11JgipcAAAAJ:j3f4tGmQtD8C'
vals = urlparse.parse_qs(url)
print vals.get('citation_for_view')

rawDescription: Extracting specific psuedo tag inside href element using Beautiful Soup


code:
import sys
import numpy
from scipy.ndimage import morphology, label, find_objects
from PIL import Image

COLORS = range(4)
RED, GREEN, BLUE, BLACK = COLORS

def card_color(img):
    im = img.load()
    width, height = img.size
    black, blue, green, red = 0, 0, 0, 0
    for x in xrange(width):
        for y in xrange(height):
            r, g, b = im[x, y]
            if r > 200 and g > 200 and b > 200:
                # "white", ignore
                continue

            if r > 200 and g < 100 and b < 100:
                red += 1
            elif r < 100 and g < 100 and b > 200:
                blue += 1
            elif r < 50 and g < 50 and b < 50:
                black += 1
            elif r < 100 and g > 120 and b < 50: # dark green
                green += 1
    return max(zip((black, blue, green, red), COLORS))

def euler_number(img, conn=4):
    im = img.load()
    width, height = img.size

    c1, c2, c3 = 0, 0, 0
    for x in xrange(width - 1):
        for y in xrange(height - 1):
            s = (im[x,y] + im[x+1,y] + im[x,y+1] + im[x+1,y+1]) / 255
            if s == 1:
                c1 += 1
            elif s == 2:
                if (im[x+1,y] and im[x,y+1]) or (im[x,y] and im[x+1,y+1]):
                    c3 += 1
            elif s == 3:
                c2 += 1
    if conn == 4:
        return (c1 - c2 + 2 * c3) / 4
    else: # 8
        return (c1 - c2 - 2 * c3) / 4

def carefully_binarize(img, color):
    if color == BLACK:
        img = img.convert('L')
    else:
        img = img.split()[color]
    width, height = img.size
    im = numpy.empty((height + 2, width + 2), dtype=numpy.uint8) # Padding
    im.fill(255)
    im[1:-1, 1:-1] = numpy.array(img)
    threshold = im.mean() - im.std()
    im[im <= threshold] = 1
    im[im > threshold] = 0
    # Discard small components.
    lbl, ncc = label(im)
    for i in xrange(1, ncc + 1):
        py, px = numpy.nonzero(lbl == i)
        if len(py) < 30:
            im[lbl == i] = 0
    return Image.fromarray(im * 255)

def discard_bottom(img, k=0.5):
    width, height = img.size
    im = numpy.array(img)
    limit = height * k
    lbl, ncc = label(im)
    for i, oslice in enumerate(find_objects(lbl)):
        srow, scol = oslice
        if srow.stop > limit:
            ncc -= 1
            im[srow.start:srow.stop, scol.start:scol.stop] = 0
    return Image.fromarray(im), ncc

def signature(img):
    # Assumption: a single connected component is present now.
    im = numpy.array(img)
    im = morphology.binary_fill_holes(im)
    im = morphology.binary_dilation(im) - im

    py, px = numpy.nonzero(im)
    return Image.fromarray(im.astype(numpy.uint8)*255), zip(py, px)

def hausdorff(a, b):
    dist = 0
    for ai in a:
        mindist = float('inf')
        for bi in b:
            chess = max(abs(ai[0]-bi[0]), abs(ai[1]-bi[1]))
            if chess < mindist:
                mindist = chess
        if mindist > dist:
            dist = mindist
    return dist

img1 = Image.open(sys.argv[1]).convert('RGB')
dirpath = sys.argv[2]

img1_color = card_color(img1)[1]
img1 = carefully_binarize(img1, img1_color)
img1_top, img1_top_ncc = discard_bottom(img1)
img1_top_en = euler_number(img1_top)

feature = [img1_color, img1_top_ncc, img1_top_en]

match = []
for fname in os.listdir(dirpath):
    try:
        img2 = Image.open(os.path.join(dirpath, fname)).convert('RGB')
    except IOError:
        print "Ignoring", fname
        continue

    if card_color(img2)[1] != feature[0]:
        continue

    img2 = carefully_binarize(img2, feature[0])
    img2_top, ncc = discard_bottom(img2)
    if ncc != feature[1]:
        continue
    en = euler_number(img2_top)
    if en != feature[2]:
        continue

    match.append((img2_top, os.path.join(dirpath, fname)))

if len(match) == 1:
    print "Here is your best match:", match[0][1]
else:
    img1_sig, sig1 = signature(img1_top)
    best_match = float('inf'), None
    for img2, fname in match:
        img2_sig, sig2 = signature(img2)
        dist = hausdorff(sig1, sig2)
        if dist < best_match[0]:
            best_match = dist, fname

    print "Best match:", best_match[1]

rawDescription: Compare a image with a list Python

description: Compare a image with a list Python


code:
#Modified your above code to generate the required output
import urllib2
import random
from operator import itemgetter

current_word = {}
current_count = 0
story = 'http://sixty-north.com/c/t.txt'
request = urllib2.Request(story)
response = urllib2.urlopen(request)
each_word = []
words = None
count = 1
same_words ={}
word = []
""" looping the entire file """
#Collect All the words into a list
for line in response:
    #print "Line = " , line
    line_words = line.split()
    for word in line_words:  # looping each line and extracting words
        each_word.append(word)

#for every word collected, in dict same_words
#if a key exists, such that key == word then increment Mapping Value by 1
# Else add word as new key with mapped value as 1
for words in each_word:
    if words.lower() not in same_words.keys() :
        same_words[words.lower()]=1
    else:
        same_words[words.lower()]=same_words[words.lower()]+1

for each in same_words.keys():
    print "word = ",each, ", count = ",same_words[each]

rawDescription: How to write a wordcount program using Python without using map reduce

description: Write a wordcount program using Python without using map reduce


code:
import urllib2
from bs4 import BeautifulSoup

url = 'http://192.168.0.184:88/cgi-bin/CGIProxy.fcgi? cmd=snapPicture&usr=USER&pwd=PASS'
html = urllib2.urlopen(url)
soup = BeautifulSoup(html, "html5lib")
imgs = soup.findAll("img")
print imgs
for img in imgs:
   print img["src"].replace("..","http://192.168.0.184:88")

rawDescription: decrease string in python doesn't works

description: Decrease string in python doesn't works


code:
def parsePsycopgSQLArray(input):
    import csv
    import cStringIO

    input = input.strip("{")
    input = input.strip("}")

    buffer = cStringIO.StringIO(input)
    reader = csv.reader(buffer, delimiter=',', quotechar='"')

    return reader.next() #There can only be one row

if __name__ == "__main__":
    text = '{2f5e5fef-1e8c-43a2-9a11-3a39b2cbb45e,"Marc, Dirk en Koen",398547,85.5,-9.2, 62fe6393-00f7-418d-b0b3-7116f6d5cf10}'
    result = parsePsycopgSQLArray(text)
    print result

rawDescription: Python: Regex question / CSV parsing / Psycopg nested arrays


code:
def possibilities(bitcount):
    for i in reversed(xrange(2**bitcount)):
        yield ("{0:0" + str(bitcount) + "b}").format(i)

def prettyprint(bitcount):
    for p in possibilities(bitcount):
        print " ".join(p.replace("0", "F").replace("1", "T") + "/")

rawDescription: How can I find TRUE - FALSE situations in C (2^n situations need to write)

description: Find TRUE - FALSE situations in C (2^n situations need to write)


rawDescription: Python Unicode Output Format

description: Python Unicode Output Format


code:
from itertools import groupby
from operator import itemgetter

with open('somefile.txt') as fin:
    lines = ( line.split() for line in fin )
    for key, values in groupby(lines, itemgetter(0)):
        print 'Key', key, 'has values'
        for value in values:
            print value

rawDescription: How can I iterate over a data file without code duplication in python?

description: Iterate over a data file without code duplication in python


code:
import mechanize
from bs4 import BeautifulSoup

URL = ('http://www.airchina.com.cn/www/jsp/airlines_operating_data/'
       'exlshow_en.jsp')
control_year = ['2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013',
                '2014']
control_month = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10',
                 '11', '12']

br = mechanize.Browser()
r = br.open(URL)

br.select_form("exl")
control_m = br.form.find_control('month')
control_y = br.form.find_control('year')

br[control_m.name] = ['06']
br[control_y.name] = ['2012']
response = br.submit()

soup = BeautifulSoup(response)

div = soup.find('div', class_='mainRight').find_all('div')[1]
table = div.find('table', recursive=False)

for row in table.find_all('tr', recursive=False):
    for cell in row('td', recursive=False):
        print cell.text.split()

rawDescription: Python beautifulsoup not grabbing full table


code:
for i,j in izip( mylistA, mylistB ):
    print i + j

rawDescription: Python - Iterate throuhg 2 lists at the same time


code:
name = None
while not name:
    name = raw_input("Hello, please enter your name?: ")
    if name:
        print "Hello %s I am soandso" % name

rawDescription: Python: looping raw input

description: Python: looping raw input


code:
hdr = "AB_1_15_Oct_2015"
print hdr
locals()[hdr] = {}

print AB_1_15_Oct_2015

rawDescription: How to assign a string value as an empty dictionary in Python?

description: Assign a string value as an empty dictionary in Python


code:
import numpy  as np
import pandas as pd

df = pd.DataFrame(np.random.rand(8,2),columns=['a','b'])

# Every time you call `values` a new array object is created:
print df.a.values is df.a.values # This will be False

# But the data is _not_ copied:
x = df['a'].values
y = df.a.values
print np.may_share_memory(x, y) #This will be True

# And if we modify "x" or "y", we'll modify the original data frame:
x[0] = -9
y[-1] = -8
print df

# However, this only holds for cases where the data can be
# viewed as a numpy array.

# This will modify the original dataframe:
z = df.values
z[0,:] = -5
print df

# But this won't, because the types are different and "values" returns
# a copy:
df['b'] = df['b'].astype(int)
arr = df.values
arr[0,:] = 10
print df

rawDescription: Using a view of columns from pandas?

description: Using a view of columns from pandas


code:
from itertools import product

fruit_dict = {'oranges':['big','small'],'apples':['green','yellow','red']}

keys, values = zip(*fruit_dict.items())
print [dict(zip(keys, value_list)) for value_list in product(*values)]

rawDescription: How do I get all the permutations selecting one item from each value list in a dictionary?

description: Get all the permutations selecting one item from each value list in a dictionary


code:
counts = {
    'A': 14,
    'B': 157,
    'C': 17,
}
lst = counts.items()
lst.sort(key=lambda x: x[1]) # x[1] => count
for key, val in lst:
    print val, key

rawDescription: Sort Python List

description: Sort Python List


code:
import ftplib
import os
import os
import socket

HOST = 'ftp.server.com'
DIRN = 'DirectoryInFTPServer'
filematch = '*.xml'
username = 'username'
password = 'password'
storetodir='DirectoryToStoreFilesIn' ####
def main():
    try:
        f = ftplib.FTP(HOST)
    except (socket.error, socket.gaierror), e:
        print 'ERROR: cannot reach "%s"' % HOST
        return
    print '*** Connected to host "%s"' % HOST

    try:
        f.login(username, password)
    except ftplib.error_perm, e:
        print 'ERROR: cannot login'
        f.quit
        return
    print '*** Logged in successfully'

    try:
        f.cwd(DIRN)
    except ftplib.error_perm, e:
        print 'ERROR: cannot CD to "%s"' % DIRN
        f.quit()
    print '*** Changed to folder: "%s"' % DIRN

    currdir=os.getcwd() ####

    try:
        os.chdir(storetodir)####
        s = 0;

        for filename in f.nlst(filematch):
            fhandle = open(filename, 'wb')
            print 'Getting ' + filename
            f.retrbinary('RETR ' + filename, fhandle.write)
            s = s + 1
    except ftplib.error_perm, e:
        print 'ERROR: cannot read file "%s"' % filename
        os.unlink(filename)
    os.chdir(currdir) ####
    f.quit()
    print 'Files downloaded: ' + str(s)
    return

if __name__ == '__main__':
    main()

rawDescription: how to specify local destination folder when retrieving files from FTP

description: Specify local destination folder when retrieving files from FTP


code:
my = os.path.abspath('/my/self/defined/path')
new = os.path.abspath(path)
if len(new) < len(my) or not new.startswith(my):
   print 'bzzzt'

rawDescription: Secure use of shutil.rmtree / os.path.join and Directory Traversal


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('<option value="BC">BRITISH COLUMBIA</option>')
soup.find('option')['selected'] = ''
print soup

rawDescription: BeautifulSoup - adding attribute to tag

description: BeautifulSoup - adding attribute to tag


code:
import inspect, re

def func(x, noCheck=False):
  if not noCheck:
      #Get the line the function was called on.
      _, _, _, _, lines, _ = inspect.getouterframes(inspect.currentframe())[1]

      #Now we need to search through `line` to see how the function is called.

      line = lines[0].split("#")[0] #Get rid of any comments at the end of the line.

      match = re.search(r"[a-zA-Z0-9]+ *= *func\(.*\)", line) #Search for instances of `func` being called after an equals sign

      try:
        variable, functioncall = match.group(0).split("=")
        print variable, "=", functioncall, "=", eval(functioncall.strip()[:-1] + ", noCheck=True)")

      except:
        pass #print "not assigned to a variable"

  #Actually make the function do something
  return 3*x**2 + 2*x + 1

func(1) # x = func(1)
x = func(1)

rawDescription: Python: can I change function behaviour whether output is assigned or not?


code:
def go_fwd(event):
    areal.focus_set()
    me.configure(me.x, me.y-2)
    check_if_player_enters_region(me)

def go_bwd(event):
    areal.focus_set()
    me.configure(me.x, me.y+2)
    check_if_player_enters_region(me)

def go_left(event):
    areal.focus_set()
    me.configure(me.x-2, me.y)
    check_if_player_enters_region(me)

def go_right(event):
    areal.focus_set()
    me.configure(me.x+2, me.y)
    check_if_player_enters_region(me)

def check_if_player_enters_region(player):
    ## Define your Areas here
    if(is_in_region(player, 20, 20, 10, 10)):
        print "enter region 1, load script xxx"
    if(is_in_region(player, 50, 50, 10, 10)):
        print "enter region 2, load script xxx"

    playarea.create_rectangle(20,20,30,30, fill='blue') ## this is just for visualisation, delete this line
    playarea.create_rectangle(50,50,60,60, fill='blue') ## this is just for visualisation, delete this line

def is_in_region(player, x, y, width, height): # define region boundries
    if((player.x >= x and player.x <= x+width) and  ## check x boundries
       (player.y >= y and player.y-2 <= y+height)): ## check y boundries
        return True
    return False

dw = tk.tk()
dw.title('Erebos')

me = player(0,0)

areal = tk.Frame(master=dw, width=20000, height=600, bg='black')
areal.pack_propagate(0)
areal.pack(fill=tk.BOTH, expand=bool(dw)-100)
areal.bind("<1>", lambda event: areal.focus_set())
dw.bind("<Up>", go_fwd)
dw.bind("<Down>", go_bwd)
dw.bind("<Left>", go_left)
dw.bind("<Right>", go_right)

playarea = tk.Canvas(width=800, height=500, master=areal, bg='white')
playarea.pack()
playarea.create_rectangle(20,20,30,30, fill='blue') ## this is just for visualisation, delete this line
playarea.create_rectangle(50,50,60,60, fill='blue') ## this is just for visualisation, delete this line
me.zeichne(playarea)
dw.mainloop()

rawDescription: Best method to keep checking the state of a variable in tkinter window


code:
if x[3] is x[4]:
    print "What's the difference?"

rawDescription: Python - How do I differentiate between two list elements that point to the same object?


code:
totalReTries = 10
acquiredValue = None
PROMPT_MESSAGE = "Please enter the valid value: "
typeOfInteredData = float
rangeOfData = range(10, 20)

for currentRetry in range(1, totalReTries):

    print "Attempt %d of %d" % (currentRetry, totalReTries)
    try:
        acquiredValue = input(PROMPT_MESSAGE)
    except ValueError:
        print("Incorrect data format. Please try again.")
        continue

    if type(acquiredValue) != typeOfInteredData:
        print "Incorrect data type. Please try again."
        continue
    elif not acquiredValue in rangeOfData:
        print "Incorrect data Range. Please try again."
        continue
    break

if not acquiredValue:
    print "ERROR: Failed to get a correct value"
else:
    print "The acquired value is: " + str(acquiredValue)

rawDescription: Basic Error Capture - for inputs - Python


code:
import urlparse

u = 'http://cve.mitre.org/cgi-bin/cvename.cgi?name=1999-0016'

q = urlparse.urlparse(u).query
values = urlparse.parse_qs(q).get('name')
if values is not None:
    print values[0]
    # prints '1999-0016'

rawDescription: Python - Parsing a specific value from a URL within a line


code:
print 'Content-Type: text/html'
print 'Location: %s' % redirectURL
print # HTTP says you have to have a blank line between headers and content
print ''
print '  '
print '    <meta http-equiv="refresh" content="0;url=%s" />' %redirectURL
print '    <title>You are going to be redirected</title>'
print '  '
print '  '
print '    Redirecting... Click here if you are not redirected' % redirectURL
print '  '
print ''

rawDescription: How to redirect user to a returned URL python

description: Redirect user to a returned URL python


code:
class my_property(object):
    def __init__(self, getter, setter, deleter):
        self.getter  = getter
        self.setter  = setter
        self.deleter = deleter

    def __get__(self, instance, owner):
        return self.getter(instance)

    def __set__(self, instance, value):
        self.setter(instance, value)

    def __delete__(self, instance):
        self.deleter(instance)

class Foo(object):
    def __init__(self):
        self._x = 42

    def get_x(self):
        print 'getter'
        return self._x

    def set_x(self, value):
        print 'setter'
        self._x = value

    def del_x(self):
        print 'deleter'
        del self._x

    x = my_property(get_x, set_x, del_x)

obj = Foo()
print obj.x
obj.x = 69
del obj.x
print obj.x

rawDescription: Python custom property with setter

description: Python custom property with setter


code:
if all(x % k == 0 for k in [1, 2, 3]):
    print 'yay'

rawDescription: How can I condense this simple "if" line of code?

description: Condense this simple "if" line of code


code:
from mock import patch
import src_pkg.person as p

class TestPerson():
    def test_can_do_it(self):
        with patch.object(p.Person, '__init__', lambda self: None):
            person = p.Person()
            print "can he do it? :", person.can_do_it(4)

rawDescription: Mock a class in Python in order to call one of its methods


code:
import glob

class ClassB():
    def myfunction(self):
        print 'hello'

if __name__ == '__main__':
    libs = [item[:-3] for item in glob.glob("*.py")]
    print '***************************************************'
    print '* Menu'
    for item in libs :
      print '** ' + item
    print '***************************************************'

    while True:
        module_name = raw_input(">>> ")
        if module_name != "":
            if module_name == 'exit':
              break
            if module_name in libs:
              lib = __import__(module_name)
              class_ = getattr(lib, 'ClassB')
              theclass = class_()
              theclass.myfunction()
              break
            else:
              print 'Module does not exist'

rawDescription: menu python command line

description: Menu python command line


code:
s = raw_input()
print sum(int(c) for c in s.strip())

rawDescription: How do I add a string of numbers in python

description: Add a string of numbers in python


code:
def Plot_field(field,name):
    vmin = field.mean()-5*field.std()
    vmax = field.mean()+5*field.std()
    v = np.linspace(vmin, vmax, 15, endpoint=True)
    plt.tricontourf(Xnew, Ynew, field, v, cmap=plt.cm.hot)
    x = plt.colorbar(ticks=v)
    print x
    # plt.scatter(Pos_integr_inst_tplus1[:,1], Pos_integr_inst_tplus1[:,2],marker='s',s=20.)
    plt.savefig(name+ str(instant[0]) + ".png")
    # plt.show()

# Plot_field(V)

Plot_field(VM,"VM")

rawDescription: Python - Matplotlib name of save fig with function


code:
def process_all(pf):
   print "PID: ", os.getpid()
   print "Script Dir: ", pf[0]
   print "Script: ", pf[1]
   os.chdir(pf[0])
   call(['postprocessing_saudi', pf[1]])

if __name__ == '__main__':
   pool = Pool(processes=2)
   files, paths = find_sea_files()
   pathfile = [[paths[i],files[i]] for i in range(len(files))]
   pool.map(process_all, pathfile, 1) # Ensure the chunk size is 1
   pool.close()
   pool.join()

rawDescription: Using multiprocessing pool of workers

description: Using multiprocessing pool of workers


code:
server = "rally1.rallydev.com"
user = "user@company.com"
password = "topsecret"
workspace = "My Workspace"
project = "My Project"
rally = Rally(server, user, password, workspace=workspace, project=project)
rally.enableLogging("rally.history.showtasks")

fields    = "FormattedID,State,Name,WorkProduct,Name,LastUpdateDate",
criterion = 'Workproduct.Name = "My Tasks User Story"'

response = rally.get('Task', fetch=fields, query=criterion, order="LastUpdateDate Desc",pagesize=200, limit=400)

most_current_task = response.next()
print "%-8.8s  %-52.52s  %s" % (most_current_task.FormattedID, most_current_task.Name, most_current_task.State)

rawDescription: How to retrieve the latest modified tasks using REST API?

description: Retrieve the latest modified tasks using REST API


code:
#!/usr/bin/env python

import socket

def get_dns_domain():
    return socket.getfqdn().split('.', 1)[1]

print get_dns_domain()

rawDescription: How can I get the default machine domain name in Python using a portable way?

description: Get the default machine domain name in Python using a portable way


code:
column = []
for _ in range(5):
    message = sock.recv(2048)
    column.append(message.split()[0])
print np.average((map(float, column)))

rawDescription: Average and Mean in numpy

description: Average and Mean in numpy


code:
def trace(*args):
    def _trace(func):
        def wrapper(*args, **kwargs):
            print enter_string
            func(*args, **kwargs)
            print exit_string
        return wrapper
    if len(args) == 1 and callable(args[0]):
        # No arguments, this is the decorator
        # Set default values for the arguments
        enter_string = 'entering'
        exit_string = 'exiting'
        return _trace(args[0])
    else:
        # This is just returning the decorator
        enter_string, exit_string = args
        return _trace

rawDescription: How to build a python decorator with optional parameters?

description: Build a python decorator with optional parameters


code:
from selenium import selenium
s = selenium("localhost", 4444, "*chrome", "http://tagger.steve.museum")
s.start()

s.open("/steve/object/141913")

text = s.get_html_source()
print text

rawDescription: Why does text retrieved from pages sometimes look like gibberish?


code:
#!/usr/local/bin/python2.7
import math

lista = [2231, 2240, 2236, 2238, 7]

newlist = []
mean = 0
newmean = 0
variance = 0

for i in lista:
    mean += i
mean = mean/float(len(lista))

for i in lista:
    variance += (i*i)
variance = variance/float(len(lista))
variance = math.sqrt(variance)

minval = variance - mean
maxval = variance + mean

for i in lista:
    if i >= minval and i <= maxval:
        newlist.append(i)
print newlist

for i in newlist:
    newmean += i
newmean = newmean/float(len(newlist))
print newmean

rawDescription: Getting mean and erasing numbers with to much difference


code:
from openpyxl import load_workbook

wb = load_workbook(r"C:\Excel\LOOKUP_TABLES_edited.xlsx")

for sheet in wb.worksheets:
    print sheet

rawDescription: How to iterate over worksheets in workbook, openpyxl

description: Iterate over worksheets in workbook, openpyxl


code:
import sys
import select
import tty
import termios

def isData():
    return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])

old_settings = termios.tcgetattr(sys.stdin)
try:
    tty.setcbreak(sys.stdin.fileno())

    i = 0
    while 1:
        print i
        i += 1

        if isData():
            c = sys.stdin.read(1)
            if c == '\x1b':         # x1b is ESC
                break

finally:
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)

rawDescription: Python: how to tell if input file has input pending without waiting


code:
import requests
import json

payload = {'query': json.dumps({"tags":["test1", "test2"]})}
url = 'http://www.test.com/match'

r = requests.post(url, data=payload)

if __name__=='__main__':
    print r.text

rawDescription: Conversion of curl to python Requests

description: Conversion of curl to python Requests


code:
#!/usr/bin/env python
import os
import sys
from gi.repository import GLib, Gtk, Poppler

class PrintingApp:
    def __init__(self, file_uri):
        self.operation = Gtk.PrintOperation()

        self.operation.connect('begin-print', self.begin_print, None)
        self.operation.connect('draw-page', self.draw_page, None)

        self.doc = Poppler.Document.new_from_file(file_uri)

    def begin_print(self, operation, print_ctx, print_data):
        operation.set_n_pages(self.doc.get_n_pages())

    def draw_page(self, operation, print_ctx, page_num, print_data):
        cr = print_ctx.get_cairo_context()
        page = self.doc.get_page(page_num)
        page.render(cr)

    def run(self, parent=None):
        result = self.operation.run(Gtk.PrintOperationAction.PRINT_DIALOG,
                                    parent)

        if result == Gtk.PrintOperationResult.ERROR:
            message = self.operation.get_error()

            dialog = Gtk.MessageDialog(parent,
                                       0,
                                       Gtk.MessageType.ERROR,
                                       Gtk.ButtonsType.CLOSE,
                                       message)

            dialog.run()
            dialog.destroy()

        Gtk.main_quit()

def main():
    if len(sys.argv) != 2:
        print "%s FILE" % sys.argv[0]
        sys.exit(1)

    file_uri = GLib.filename_to_uri(os.path.abspath(sys.argv[1]))

    main_window = Gtk.OffscreenWindow()
    app = PrintingApp(file_uri)
    GLib.idle_add(app.run, main_window)
    Gtk.main()

if __name__ == '__main__':
    main()

rawDescription: python Gtk.PrintOperation print a pdf

description: Python Gtk.PrintOperation print a pdf


rawDescription: Using list to do mathematics in python

description: Using list to do mathematics in python


code:
global i
i=0

def rabbit():
    global i
    print "rabbit ",i

#main here
if __name__ == '__main__':
    rabbit()

rawDescription: define global variables in a function and pass on to a class

description: Define global variables in a function and pass on to a class


code:
class vis(QtCore.QObject):
    def __init__(self, parent=None):
        super(vis, self).__init__(parent) # you are missing this line
                                          # also the `parent` arg
        self._oreList = []

        self._w = window.window()
        self._w.scanStarted.connect(self._scanOre)

    def _scanOre(self, rawText):
        print "main ->", rawText

rawDescription: connecting pyqt4 signals in a pyqt4 qobject class

description: Connecting pyqt4 signals in a pyqt4 qobject class


code:
def outer():
    a = [1]
    def inner():
        a[0] += 1
        print a[0]

rawDescription: Modify the function variables from inner function in python


code:
c = """(Speaking) (Laughing) Get out of here"""

paren_count = 0
out = []

for char in c:
    if char == "(":
        paren_count += 1
        continue
    elif char == ")":
        paren_count -= 1
        continue
    if paren_count == 0:
        out.append(char)

print "".join(out).strip()

rawDescription: Remove certain string blocks from python string


code:
import wx

class TestFrame(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, id=-1, title=title)
        text = wx.StaticText(self, label=title)

        self.cb1 = wx.CheckBox(self, -1, "pewpew")
        self.Bind(wx.EVT_CHECKBOX, self.lg, self.cb1)

        evt = wx.CommandEvent(wx.EVT_CHECKBOX.typeId, self.cb1.GetId())
        wx.PostEvent(self, evt)

    def lg(self, in_event):
        print in_event
        print 'In lg'

app = wx.App()
frame = TestFrame(None, "Hello, world!")
frame.Show()
app.MainLoop()

rawDescription: python checkbox event trigger

description: Python checkbox event trigger


code:
import re
l = [int(i) for i in re.findall(r'(\d+)', "(1, 89, 67, 23)")]
print l

rawDescription: List in the form of a string into a real list


code:
cur = db.cursor()
cur.execute("SELECT * FROM prototype")
db.commit()
results = cur.fetchall()
for name in results:
    print name[0]

rawDescription: Returning elements from lists within a list


code:
def foo(a,b):
    print a
    print b

foo(b=2,a=1)

rawDescription: Parameter naming convention in Python

description: Parameter naming convention in Python


code:
#!/usr/bin/env python

import re
from os import walk
from os.path import join

def main():
    for (dirpath, _, filenames) in walk('/path/to/root'):
        for filename in filenames:
            # Build the path to the current file.
            path_to_file = join(dirpath, filename)
            content = None
            # Open the file.
            with open(path_to_file, 'r') as myfile:
                print 'Reading {0}'.format(path_to_file)
                # Read the file's contents.
                content = myfile.read()
                content = re.sub(r'.+(?=@.+\.(com|edu))', "xxxx", content)

            with open(path_to_file, 'w') as myfile:
                myfile.write(content)

main()

rawDescription: How to execute a python script across all directories

description: Execute a python script across all directories


code:
import datetime

now = datetime.datetime.now()
holidays = [datetime.date(2013, 8, 14)] # you can add more here
businessdays = 0
for i in range(1, 32):
    try:
        thisdate = datetime.date(now.year, now.month, i)
    except(ValueError):
        break
    if thisdate.weekday() < 5 and thisdate not in holidays: # Monday == 0, Sunday == 6
        businessdays += 1

print businessdays

rawDescription: Using Python to count the number of business days in a month?


code:
from tornado.ioloop import IOLoop
from tornado import gen
from tornado.httpclient import AsyncHTTPClient, HTTPError

client = AsyncHTTPClient()

@gen.coroutine
def fetch():
    try:
        yield client.fetch('http://tornadoweb.org', follow_redirects=False)
    except HTTPError as e:
        print 'response:'
        print e.response
        print
        print 'headers:'
        print e.response.headers

IOLoop.current().run_sync(fetch)

rawDescription: Access header on redirect response with tornado.httpclient.AsyncHTTPClient?


code:
import threading
import time

class TimerClass(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.event = threading.Event()

    def run(self):
        while not self.event.is_set():
            print "do something"
            self.event.wait( 1 )

    def stop(self):
        self.event.set()

tmr = TimerClass()
tmr.start()

time.sleep( 10 )

tmr.stop()

rawDescription: Execute task every so often within a process


code:
def CleanWhiteSpace(theDict) :
    stuff=[]
    for key2 in theDict.keys():  # this is the line I changed
        if theDict[key2] == [' ']:
            print key2
            del theDict[key2]
            print "hi"

    print theDict
    for key, value in theDict.iteritems():
        for d in value:
            print value
            if d != ' ':
                    stuff.append(d)
            theDict[key]=stuff
        stuff=[]

    return theDict
print CleanWhiteSpace({'a':['1','2'],'b':['3',' '],'c':[' ']})

rawDescription: Why did it delete key a and key c, instead of just key c?


code:
class B():
    def __init__(self, someA):
        self.parent = someA
    def C(self):
        self.parent.d()

class A(object):
   def __init__(self):
       self.b = B(self)
   def d(self):
      print "Hi"

rawDescription: python , how to find class object from child entity?

description: Python , how to find class object from child entity


code:
s="Hello"
swap_seq="23014"
swapped=''.join([s[int(i)] for i in swap_seq])
if s[0].isupper(): swapped.capitalize()
print swapped

rawDescription: How do I swap letters around from an input in python?

description: Swap letters around from an input in python


rawDescription: transform an adjacency list into a sparse adjacency matrix using python

description: Transform an adjacency list into a sparse adjacency matrix using python


code: for pizza in orderedpizzas: print standardpizzalist[pizza-1]

rawDescription: Print list, with values from another list


code:
my_string = 'hello world'
l = ['my_string']
for each in l:
    exec 'print ' + each
    exec 'a = ' + each
    print 'a = %s' % a

rawDescription: How to read a variable name which is stored as a string in python?

description: Read a variable name which is stored as a string in python


code:
import Tkinter, tkFileDialog
import csv

#Choose the file that you want to read from
root = Tkinter.Tk()
root.withdraw()

file_path = tkFileDialog.askopenfilename()
with open(file_path , 'rb') as current_file:
    reader = csv.reader(current_file, delimiter= ' ',
                        skipinitialspace=True)
    with open('newdata.txt','wb') as output_file:
        out = csv.writer(output_file)
        for row in reader:
            out.writerow(row)
            print row
            #print row[0::1]

rawDescription: Trouble with using csv on large data set to separate parameters


code:
from django.core.cache import cache
from django.db.models.query import QuerySet
try:
    from cPickle import dumps
except:
    from pickle import dumps
from hashlib import sha1

cache_miss = object()

class CantPickleAQuerySet(Exception): pass

def cache_function(cache_timeout, func_type='generic'):
    def wrapper(fn):
        def decorator(*args, **kwargs):
            try:
                cache_indentifiers = "%s%s%s%s" % (
                                         fn.__module__,
                                         fn.__name__,
                                         dumps(args),
                                         dumps(kwargs)
                                         )
            except Exception, e:
                print "Error: %s\nFailed to generate cache key: %s%s" % (e, fn.__module__, fn.__name__)
                return fn(*args, **kwargs)

            cache_key = sha1(cache_indentifiers).hexdigest()

            value = cache.get(cache_key, cache_miss)

            if value is cache_miss:
                value = fn(*args, **kwargs)

                if isinstance(value, QuerySet):
                    raise CantPickleAQuerySet("You can't cache a queryset. But you CAN cache a list! just convert your Queryset (the value you were returning) to a list like so `return list(queryset)`")

                try:
                    cache.set(cache_key, value, cache_timeout)
                except Exception, e:
                    print "Error: %s\nFailed to cache: %s\nvalue: %s" % (e, cache_indentifiers, value)

            return value

        no_arg2 = object()
        def filter_decorator(arg1, arg2=no_arg2):
            if arg2 is no_arg2:
                return decorator(arg1)
            else:
                return decorator(arg1, arg2)

        if func_type == 'generic':
            return decorator

        elif func_type == 'filter':
            return filter_decorator

    return wrapper

rawDescription: Decorators on Django Template Filters?

description: Decorators on Django Template Filters


code:
import Tkinter
from Tkinter import *

# This program is designed to count up from zero
class CountsUp(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.grid()
        self.widgets()
        self.running = False
        self.timer = [0,0,0]    # [minutes ,seconds, centiseconds]
        self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
        self.update_time()

    def widgets(self):
        self.timeFrame = LabelFrame(root, text='Counts Up')
        self.timeFrame.grid(row=0,column=0, sticky=W)

        self.resetButton = Button(self.timeFrame, text='Reset', command=self.resetTime)
        self.resetButton.grid(row=2,column=1)

        self.pauseButton = Button(self.timeFrame, text='Pause', command=self.pause)
        self.pauseButton.grid(row=1,column=1)

        self.startButton = Button(self.timeFrame, text='Start', command=self.start)
        self.startButton.grid(row=0,column=1)

        self.show = Label(self.timeFrame, text='00:00:00', font=('Helvetica', 30))
        self.show.grid(row=0, column=0)

        self.quit = Button(self.timeFrame, text='QUIT', command=self.quit)
        self.quit.grid(row=3, column=1)

    def update_time(self):

        if (self.running == True):      #Clock is running

            self.timer[2] += 1          #Count Down

            if (self.timer[2] >= 100):  #100 centiseconds --> 1 second
                self.timer[2] = 0       #reset to zero centiseconds
                self.timer[1] += 1      #add 1 second

            if (self.timer[1] >= 60):   #60 seconds --> 1 minute
                self.timer[0] += 1      #add 1 minute
                self.timer[1] = 0       #reset to 0 seconds

            self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
            self.show.config(text=self.timeString)
        root.after(10, self.update_time)

    def start(self):            #Start the clock
        self.running = True
        print 'Clock Running...'

    def pause(self):            #Pause the clock
        self.running = False
        print 'Clock Paused'

    def resetTime(self):        #Reset the clock
        self.running = False
        self.timer = [0,0,0]
        print 'Clock is Reset'
        self.show.config(text='00:00:00')

    def quit(self):             #Quit the program
        root.destroy()

# This program is designed to count down from a starting time
class CountsDown(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)
        self.grid()
        self.widgets()
        self.running = False
        self.timer = [0,0,0]    # [minutes ,seconds, centiseconds]
        self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
        self.update_time()

    def widgets(self):
        self.timeFrame = LabelFrame(root, text='Counts Down')
        self.timeFrame.grid(row=2,column=0, sticky=W)

        self.resetButton = Button(self.timeFrame, text='Reset', command=self.resetTime)
        self.resetButton.grid(row=2,column=1)

        self.pauseButton = Button(self.timeFrame, text='Pause', command=self.pause)
        self.pauseButton.grid(row=1,column=1)

        self.startButton = Button(self.timeFrame, text='Start', command=self.start)
        self.startButton.grid(row=0,column=1)

        self.show = Label(self.timeFrame, text='00:00:00', font=('Helvetica', 30))
        self.show.grid(row=0, column=0)

        self.addMinute = Button(self.timeFrame, text='Add Minute', command=self.addMinute)
        self.addMinute.grid(row=2,column=0)

        self.addSecond = Button(self.timeFrame, text='Add Second', command=self.addSecond)
        self.addSecond.grid(row=3,column=0)

        self.quit = Button(self.timeFrame, text='QUIT', command=self.quit)
        self.quit.grid(row=3, column=1)

    def update_time(self):

        if (self.running == True):      #Clock is running

            self.timer[2] -= 1          #Count Down

            if (self.timer[2] < 0):     #if centiseconds is negative
                self.timer[2] = 100     #reset to 100 centiseconds
                self.timer[1] -= 1      #subtract 1 second

            if (self.timer[1] < 0):     #if seconds is negative
                self.timer[1] = 60      #reset to 60 seconds
                self.timer[1] -= 1      #subtract 1 second
                self.timer[0] -= 1      #subtract 1 minute

            self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
            self.show.config(text=self.timeString)
        root.after(10, self.update_time)

    def addMinute(self):
        self.timer[0] += 1
        self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
        self.show.config(text=self.timeString)

    def addSecond(self):
        self.timer[1] += 1
        self.timeString = str(self.timer[0]) + ':' + str(self.timer[1]) + ':' + str(self.timer[2])
        self.show.config(text=self.timeString)

    def start(self):            #Start the clock
        self.running = True
        print 'Clock Running...'

    def pause(self):            #Pause the clock
        self.running = False
        print 'Clock Paused'

    def resetTime(self):        #Reset the clock
        self.running = False
        self.timer = [0,0,0]
        print 'Clock is Reset'
        self.show.config(text='00:00:00')

    def quit(self):             #Quit the program
        root.destroy()

root = Tkinter.Tk()

up = CountsUp(root)
down = CountsDown(root)

root.mainloop()

rawDescription: StopWatch on Tkinter ...Creating a Class


code:
from ctypes import windll, wintypes, byref

SPI_GETWORKAREA = 48
SM_CYSCREEN = 1

def get_taskbar_size():
    SystemParametersInfo = windll.user32.SystemParametersInfoA
    work_area = wintypes.RECT()
    if (SystemParametersInfo(SPI_GETWORKAREA, 0, byref(work_area), 0)):
        GetSystemMetrics = windll.user32.GetSystemMetrics
        return GetSystemMetrics(SM_CYSCREEN) - work_area.bottom

print get_taskbar_size()  # 30

rawDescription: How to get a ms windows desktop height in pygtk?

description: Get a ms windows desktop height in pygtk


code:
import timeit
import re
s = '0' * 1000 + 'foo' + '0' * 1000
rgx = re.compile(r'foo')
setup = 'from __main__ import s, rgx'
print timeit.timeit('"foo" in s', setup = setup)             # 0.745168924332
print timeit.timeit('rgx.search(s).group(0)', setup = setup) # 1.14249396324

rawDescription: In vs re.search python

description: In vs re.search python


code:
#!/usr/bin/python

import zipfile
f = zipfile.ZipFile('myfile.zip')

for subfile in f.namelist():
    print subfile
    data = f.read(subfile)
    for line in data.split('\n'):
        print line

rawDescription: Is there a python module for regex matching in zip files


code:
import bllipparser

def is_prepreterminal(node):
    """Returns True iff all children of this node are preterminals."""
    subtrees = node.subtrees()
    return len(subtrees) > 0 and \
        all(subtree.is_preterminal() for subtree in subtrees)

# testing code
tree = bllipparser.Tree('(S1 (S (NP (DT This)) (VP (VBZ is) (NP (DT a) (ADJP (RB fairly) (JJ simple)) (NN parse) (NN tree))) (. .)))')
for subtree in tree.all_subtrees():
    print subtree, is_prepreterminal(subtree)

rawDescription: Treebank-style tree parser python

description: Treebank-style tree parser python


rawDescription: Group tuple and list maintaining order python


code:
connection = engine.connect()
result = connection.execute("select username from users")
for row in result:
    print "username:", row['username']
connection.close()

rawDescription: Is there a MySQL database abstraction layer for Python that works like pyodbc on both Linux and Windows?


code:
functions = ['sum', 'id', 'str', 'list']
modules = ['random', 'numpy', 'scipy', 'os']
methods = ['some_other_stuff']

answer = dict()
answer['functions'] = functions
answer['modules'] = modules
answer['methods'] = methods

while True:
    choice = raw_input('Choose between functions, methods, or modules: ')
    if choice in answer.keys(): # ['functions', 'modules', 'methods']
        print answer[choice]

rawDescription: Python raw_input

description: Python raw_input


code:
from datetime import datetime, date, timedelta
dateformat = "%Y-%m-%d"
date1 = datetime.strptime("2015-07-09", dateformat)
date2 = datetime.strptime("2016-08-20", dateformat)
weeks = int((date2-date1).days/7)
print weeks

rawDescription: Python get number of the week by month

description: Python get number of the week by month


code:
import numpy as np
from datetime import datetime
n = 50000000
a = np.random.rand(1, n).ravel()
startTime = datetime.now()
np.array([ x if x >=0 else 0 for x in np.sign(a)])
print datetime.now() - startTime

startTime = datetime.now()
(a > 0).astype(int)
print datetime.now() - startTime
pass

rawDescription: Convert real-valued numpy array to binary array by sign


code:
N = 3 # for 3 lines of output
p = subprocess.Popen(['/path/to/external-app.sh'],
    stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()

if p.returncode != 0:
    print ("ERROR: External app did not complete successfully "
           "(error code is %s)" % p.returncode)
    print "Error/failure details: ", '\n'.join(stderr.splitlines()[-N:])
    status = False
else:
    status = True

rawDescription: How to get the last N lines of a subprocess' stderr stream output?

description: Get the last N lines of a subprocess' stderr stream output


code:
ip = '127.0.0.1'
print '.'.join(format(int(x), '04o') for x in ip.split('.'))

rawDescription: Python Convert IP to octal adress

description: Python Convert IP to octal adress


code:
import Tkinter as tk

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        lb = tk.Listbox(self)
        lb.insert("end", "one")
        lb.insert("end", "two")
        lb.insert("end", "three")
        lb.bind("<Double-Button-1>", self.OnDouble)
        lb.pack(side="top", fill="both", expand=True)

    def OnDouble(self, event):
        widget = event.widget
        selection=widget.curselection()
        value = widget.get(selection[0])
        print "selection:", selection, ": '%s'" % value

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

rawDescription: Get selected item in listbox and call another function storing the selected for it


code:
import xml.etree.cElementTree as ET

txt = """<div1 type="chapter" num="9">

             As they say, A student has usually three maladies:

             poverty, itch, and pride.

         </div1>"""
root = ET.fromstring(txt)
for p in root:
    for s in p:
        print s.attrib['num'], s.tail

rawDescription: How can I associate xml text with a preceding empty element in Python?

description: Associate xml text with a preceding empty element in Python


code:
#!/usr/bin/python2
import os
import random
import subprocess
outputs = []
processes = []
for i in range(4):
    args = ['bash', '-c', 'sleep ' + str(random.randint(0, 3)) + '; whoami']
    p = subprocess.Popen(args, stdout=subprocess.PIPE)
    processes.append(p)
while processes:
    p = processes[0]
    p.wait()
    output = p.stdout.read()
    outputs.append(output)
    print('{p} finished'.format(p=p.pid))
    os.sys.stdout.flush()
    processes.remove(p)
print outputs

rawDescription: Append output of multiple subprocesses to array in Python


code:
NAMES = 'value ref pre'.split()
for key, values in x.iteritems():
    valstrs = ['%s:%s' % (name, value)
               for name, value in zip(NAMES, values)
               if value]
    print ' '.join(valstrs)

rawDescription: while printing how to skip a value which is not in dict

description: While printing how to skip a value which is not in dict


code:
import socket
print socket.getdefaulttimeout()
socket.setdefaulttimeout(60)

rawDescription: python socket object accept time out

description: Python socket object accept time out


code:
dictionary3 = OrderedDict(sorted(x.items(), key=lambda (key, value): int(key.split('_')[1])))
dictionary3

rawDescription: How to sort OrderedDict when keys contains strings and numbers - Python

description: Sort OrderedDict when keys contains strings and numbers - Python


code:
import re
s = 'D08838  Acotiamide hydrochloride hydrate (JAN/BBC); Acotiamide hydrochloride (USAN) Antagonist'
print re.sub('(\s*\(.*?\))', '', s)
#D08838  Acotiamide hydrochloride hydrate; Acotiamide hydrochloride Antagonist

rawDescription: Python - Regex How to replace characters in a string?


code:
def all_addresses():
   ip_is = [i for i in range(256)]
   ports = [i for i in range(1024,49152)]
   # note (...) instead of [...] to create a generator instead of a list;
   # separate |for|s to iterate over the lists individually
   return (str(i1)+"."+str(i2)+"."+str(i3)+"."+str(i4)+":"+str(p)
            for i1 in ip_is
            for i2 in ip_is
            for i3 in ip_is
            for i4 in ip_is
            for p in ports)

for addr in all_addresses():
   print addr

rawDescription: Too many values problem

description: Too many values problem


code:
###########################################################################################
###
def  runFunctionsInParallel(listOf_FuncAndArgLists,kwargs=None,names=None,parallel=None,offsetsSeconds=None,expectNonzeroExit=False,maxAtOnce=None,showFinished=50):
    ###
    #######################################################################################
    """
    Chris Barrington-Leigh, 2011-2014+

    Take a list of lists like [function, args, kwargs]. Run those functions in parallel, wait for them all to finish, and return a tuple of (return codes, return values), each a list in order.

This implements a piecemeal collection of return values from the functions, since otherwise the pipes get stuck (!) and the processes cannot finish.

listOf_FuncAndArgLists: a list of lists like [function, args, kwargs], specifying the set of functions to be launched in parallel.  If an element is just a function, rather than a list, then it is assumed to have no arguments. ie args and kwargs can be filled in where both, or kwargs, are missing.

names: an optional list of names for the processes.

offsetsSeconds: delay some functions' start times

expectNonzeroExit: Normally, we should not proceed if any function exists with a failed exit code? So the functions that get passed here should return nonzero only if they fail.

parallel: If only one function is given or if parallel is False, this will run the functions in serial.

2013 Feb: when there's a change in the statuses, update again immediately rather than sleeping.

2013 Feb: to add: maxAtOnce: if nonzero, it will queue jobs, adding more only when some are finished!

2013July: You can now pass os.system or etc to this as the function, with no need for a wrapper: I made use of hasattr(builtinfunction,'func_name') to check for a name.

showFinished= (int) . : Specifies the maximum number of successfully finished jobs to show in reports (before the last, which should always show them all).

    """

    if parallel is None or parallel is True: # Don't use parallel on my laptop or anything really, other than apollo
        from cpblDefaults import defaults
        parallel=defaults['manycoreCPU']

    if not listOf_FuncAndArgLists:
        return([]) # list of functions to run was empty.

    if offsetsSeconds is None:
        offsetsSeconds=0

    # If no argument list is given, make one:
    listOf_FuncAndArgLists=[faal if isinstance(faal,list) else [faal,[],{}] for faal in listOf_FuncAndArgLists]
    listOf_FuncAndArgLists=[faal+[{}] if len(faal)==2 else faal for faal in listOf_FuncAndArgLists]
    listOf_FuncAndArgLists=[faal+[[],{}] if len(faal)==1 else faal for faal in listOf_FuncAndArgLists]
    kwargs=kwargs if kwargs else [{} for faal in listOf_FuncAndArgLists]

    if len(listOf_FuncAndArgLists)==1:
        parallel=False

    if parallel is False:
        print('++++++++++++++++++++++  DOING FUNCTIONS SEQUENTIALLY ---------------- (parallel=False in runFunctionsInParallel)')
        returnVals=[fffargs[0](*(fffargs[1]),**(fffargs[2]))  for iffargs,fffargs in enumerate(listOf_FuncAndArgLists)]
        assert expectNonzeroExit or not any(returnVals)
        return(returnVals)

    from multiprocessing import Process, Queue, cpu_count

    if names is None:
        names=[None for fff in listOf_FuncAndArgLists]
    assert len(names)==len(listOf_FuncAndArgLists)

    def functionWrapper(fff,que,theArgs=None,kwargs=None,delay=None): #add a argument to function for assigning a queue
        os.nice(10) # Add 10 to the niceness of this process (POSIX only)
        if delay:
            from time import sleep
            sleep(delay)
        if not kwargs:
            kwargs={}
        if not theArgs:
            theArgs=[]
        funcName='(built-in function)' if not hasattr(fff,'func_name') else fff.func_name
        print 'MULTIPROCESSING: Launching %s in parallel '%funcName
        returnVal=que.put(fff(*theArgs,**kwargs))
        print 'MULTIPROCESSING: Finished %s in parallel! '%funcName
        return(returnVal)

    def reportStatus(sjobs,showmax,showsuccessful=np.inf):#jobs):
        djobs= sjobs if showmax>=len(sjobs) else sjobs[:showmax]

        tableFormatString='%s\t%'+str(max([len(job.name) for job in djobs]))+'s:\t%9s\t%s\t%s\t%s'
        print('\n'+'-'*75+'\n'+ tableFormatString%('alive?','Job','exit code','Full','Empty','Func',)+ '\n'+'-'*75)
        # Check that we aren't going to show more *successfully finished* jobs than we're allowed: Find index of nth-last successful one. That is, if the limit binds, we should show the latest N=showsuccessful ones only.
        isucc=[ii for ii,job in enumerate(djobs) if job.exitcode==0]
        earliestSuccess= -1 if len(isucc)<showsuccessful else isucc[::-1][showsuccessful-1]
        print('\n'.join([tableFormatString%(job.is_alive()*'Yes:',job.name,job.exitcode,queues[iii].full(),queues[iii].empty(),'(built-in function)' if not hasattr(listOf_FuncAndArgLists[ii][0],'func_name') else listOf_FuncAndArgLists[ii][0].func_name) for ii,job in enumerate(djobs) if job.exitcode!=0 or ii>=earliestSuccess  ]))

        if len(isucc)>showsuccessful:
            print('%d other jobs finished successfully.'%(len(isucc)-showsuccessful))
        if len(sjobs)>len(djobs):
            print('%d more jobs waiting for their turn to start...'%(len(sjobs)-len(djobs)))
        print('-'*75+'\n')
        return([job.exitcode for ii,job in enumerate(sjobs)])

    def emptyQueues():#jobs,queues,gotQueues):
        for ii,job in enumerate(jobs):
            if not queues[ii].empty():
                if ii in gotQueues:
                    gotQueues[ii]+=queues[ii].get()
                else:
                    gotQueues[ii]=queues[ii].get()

    queues=[Queue() for fff in listOf_FuncAndArgLists] #create a queue object for each function
    delays=list(arange(len(listOf_FuncAndArgLists))*offsetsSeconds)
    jobs = [Process(target=functionWrapper,args=[funcArgs[0],queues[iii]],kwargs={'theArgs':funcArgs[1],'kwargs':funcArgs[2],'delay':delays[iii]},name=names[iii]) for iii,funcArgs in enumerate(listOf_FuncAndArgLists)]

    if maxAtOnce is None:
        maxAtOnce=max(1,cpu_count()-1)  #np.inf
    else:
        maxAtOnce=max(min(cpu_count()-2,maxAtOnce),1)  #np.inf
    istart=maxAtOnce if maxAtOnce<len(jobs) else len(jobs)

    for job in jobs[:istart]: job.start() # Launch them all

    import time
    from math import sqrt
    timeElapsed=0
    ##n=1 # obselete
    gotQueues=dict()

    """ Now, wait for all the jobs to finish.  Allow for everything to finish quickly, at the beginning.
    """
    while any([jj.is_alive() for jj in jobs]) or istart<len(jobs):
        sleepTime=5*(timeElapsed>2) + np.log(1.5+timeElapsed)/2
        if timeElapsed>0:
            time.sleep(1+sleepTime) # Wait a while before next update. Slow down updates for really long runs.
        timeElapsed+=sleepTime
        # Add any extra jobs needed to reach the maximum allowed:
        while istart<len(jobs) and sum([jj.is_alive() for jj in jobs]) < maxAtOnce:
            jobs[istart].start()
            istart+=1
            timeElapse=.01
        reportStatus(jobs,istart,showFinished) #istart)#jobs)
        emptyQueues()#jobs,queues,gotQueues)

    for job in jobs: job.join() # Wait for them all to finish... Hm, Is this needed to get at the Queues?

    # And now, collect any remaining buffered outputs (queues):
    emptyQueues()
    for ii,job in enumerate(jobs):
        if ii not in gotQueues:
            gotQueues[ii]=None

    # Give final report of exit statuses?
    success=reportStatus(jobs,np.inf)
    names=[names[iii] if names[iii] is not None else fff[0].func_name for iii,fff in enumerate(listOf_FuncAndArgLists)]

    if any(success):
        print('MULTIPROCESSING: Parallel processing batch set did not ALL succeed successfully ('+' '.join(names)+')')
        assert expectNonzeroExit  # one of the functions you called failed.
        return(False)
    else:
        print('MULTIPROCESSING: Apparent success of all functions ('+' '.join(names)+')')
    return(success,[gotQueues[ii] for ii in range(len(jobs))])

rawDescription: python multiprocessing: some functions do not return when they are complete (queue material too big)

description: Python multiprocessing: some functions do not return when they are complete (queue material too big)


code:
class FancyCreature( Creature ):

    def __init__(self):
        super( FancyCreature, self ).__init___()

    def rise_hands(self, *args, **kwargs):
        print 'hands rised'
        super( FancyCreature, self ).rise_hands( *args, **kwargs )

    def new_method( self ):
        print "new method"

rawDescription: Redefine or add Methods to class through decorator. Possible?


code:
from collections import namedtuple

HostInfo = namedtuple('HostInfo', 'access_times,bytes,errors')

accs = {}
for i in reqs_host.keys():
    accs[i] = HostInfo(
        reqs_host[i] if reqs_host[i] > max_requests else None,
        bytes_host[i] if bytes_host[i] > max_bytes else None,
        errors_host[i] if errors_host[i] > max_errors else None
    )

for access_times, host in sorted((
            (info.access_times, host)
            for host, info in accs.iteritems()
            if info.access_times is not None
        ), reverse=True):
    print "Host %s accessed %s times"%(host, access_times)

rawDescription: Access dictionary of lists with sorting havin defaults filled


rawDescription: Create a list by combining each index in 2 lists


code:
import sqlite3

def collate_reverse(string1, string2):
    return -cmp(string1, string2)

con = sqlite3.connect(":memory:")
con.create_collation("reverse", collate_reverse)

cur = con.cursor()
cur.execute("create table test(x)")
cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
cur.execute("select x from test order by x collate reverse")
for row in cur:
    print row
con.close()

rawDescription: Can you achieve a case insensitive 'unique' constraint in Sqlite3 (with Django)?

description: Achieve a case insensitive 'unique' constraint in Sqlite3 (with Django)


code:
count = 0
for afile in filelist:
    (head, filename) = os.path.split(afile)
    if afile.endswith(".log") or afile.endswith(".txt"):
        f=ftp.open(afile, 'r')
        for i, line in enumerate(f.readlines()):
            result = regex.search(line)
            if result:
                count += 1
                ln = str(i)
                pathname = os.path.join(afile)
                template = "\nLine: {0}\nFile: {1}\nString Type: {2}\n\n"
                output = template.format(ln, pathname, result.group())
                hold = output
                print output
                ftp.get(afile, 'c:\\Extracted\\' + filename)
                temp.write(output)
                break
        else:
            print "String Not Found in: " + os.path.join(afile)
            temp.write("\nString Not Found: " + os.path.join(afile))

        f.close()
for fnum in filelist:
    print "\nFiles Searched: ", len(filelist)
    print "Files Matched: ", count
    num = len(filelist)

    temp.write("\n\nFiles Searched: " + '%s\n' % (num))
    temp.write("Files Matched: "+str(count)) # here is where I want to show the number of files matched
    break

rawDescription: How can I get a value in the scope of loop and use it outside the loop in Python

description: Get a value in the scope of loop and use it outside the loop in Python


code:
bools = [True, True, False, True, True, False, True]

print ''.join(chr(ord('A') + i) if b else ' ' for i, b in enumerate(bools))

rawDescription: convert a list of booleans to string

description: Convert a list of booleans to string


code:
import random

a = ['a', 'b', 'c']
b = [1, 2, 3]

c = list(zip(a, b))

random.shuffle(c)

a, b = zip(*c)

print a
print b

[OUTPUT]
['a', 'c', 'b']
[1, 3, 2]

rawDescription: Shuffle two list at once with same order