code:
from threading import Timer
import xml.etree.ElementTree as ET
import urllib
import time

datetime = time.strftime('%Y-%m-%d %H.%M')
filename = datetime + ".sql"
url = "localhost/send.cgi"
interval = 0.5
table_name = "0001"
columns = "(time, foo, bar)"
counting = 0

def parser():
    t = Timer(interval, parser)
    global counting
    global filename
    query = open(filename, "a")

    if counting == 0:
        date = int(time.time()*1000)
        web = urllib.urlopen(url)
        tree = ET.parse(web)
        root = tree.getroot()
        foo = root[1].text.replace(" ", "")
        bar = root[2].text.replace(" ", "")
        sql = "INSERT INTO %s %s VALUES ('%s', '%s', '%s');" % (table_name, columns, date, foo, bar)
        counting += 1
        query.write(sql)
        print counting
        t.start()
    elif (counting > 0) and (counting < 59):
        date = int(time.time()*1000)
        web = urllib.urlopen(url)
        tree = ET.parse(web)
        root = tree.getroot()
        foo = root[1].text.replace(" ", "")
        bar = root[2].text.replace(" ", "")
        sql = "\nINSERT INTO %s %s VALUES ('%s', '%s', '%s');" % (table_name, columns, date, foo, bar)
        counting += 1
        query.write(sql)
        print counting
        t.start()
    elif counting == 59:
        date = int(time.time()*1000)
        web = urllib.urlopen(url)
        tree = ET.parse(web)
        root = tree.getroot()
        foo = root[1].text.replace(" ", "")
        bar = root[2].text.replace(" ", "")
        sql = "\nINSERT INTO %s %s VALUES ('%s', '%s', '%s')" % (table_name, columns, date, foo, bar)
        counting += 1
        query.write(sql)
        print counting
        t.start()
    elif counting == 60:
        query.close()
        datetime = time.strftime('%Y-%m-%d %H-%M')
        filename = datetime + ".sql"
        counting = 0
        t.start()
parser()

rawDescription: Run Python Function Every Second for A Minute


code:
from subprocess import Popen, PIPE
p = Popen("c:\users\user\downloads\Application", stdin=PIPE)
p.communicate("000")
p.communicate("#\n")

rawDescription: How to write to console of subprocess in Python?

description: Write to console of subprocess in Python


code:
def data_gen(init_val):
    b = init_val
    while True:
        b += 1
        yield b

gen = data_gen(3)
print next(gen)
print 'starting loop'
for j in gen:
    print j
    if j > 50:
        print "don't want to run forever, breaking"
        break

rawDescription: generator function for matplotlib animation

description: Generator function for matplotlib animation


code:
scores = {}  # Not `dict`. Don't reuse builtin names.

with open('scores.txt', 'r') as f:  # Not "r+" unless you want to write later
    for line in f:
        name, score = line.strip().rsplit(' ', 1)
        score = int(score)
        if name in scores:
            scores[name] = scores[name] + score
        else:
            scores[name] = score

print scores.items()

rawDescription: Python sort text file in dictionary

description: Python sort text file in dictionary


code:
import numpy as np
import cv2

cap = cv2.VideoCapture('videos/kondo2.avi')
w=800
h=600

fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v')
out = cv2.VideoWriter('videos/output.avi',fourcc, 25, (w,h),True)
count = 0
while(cap.isOpened()):
    count = count + 1
    print "processing frame ", count
    ret, frame = cap.read()
    if ret == True:
        frame = cv2.resize(frame,(w,h), interpolation = cv2.INTER_CUBIC)
        y_len,x_len,_ = frame.shape

        scale = 9
        for y in range(scale):
            for x in range(scale):
                cropped_frame=frame[(y*y_len)/scale:((y+1)*y_len)/scale,
                                    (x*x_len)/scale:((x+1)*x_len)/scale]

                mean_val=cv2.mean(cropped_frame)
                mean_val=mean_val[:3]
                cropped_frame[:,:,:] = mean_val

        out.write(frame)

cap.release()
out.release()
cv2.destroyAllWindows()

rawDescription: No video output OpenCV Python

description: No video output OpenCV Python


code:
from collections import deque
from types import StringTypes

s = "A!\nB!\nC!\n<tag>\nD!\nE!\n</tag>\nF!\n<tag>\nG!\n</tag>"

def parse(parts):
    if type(parts) in StringTypes:
        parts = deque(parts.split("\n"))
    ret = []
    while parts:
        part = parts.popleft()
        if part[-1] == "!":
            ret.append(part[:-1])
        elif part == "<tag>":
            ret.append(parse(parts))
        elif part == "</tag>":
            return ret
    return ret

print parse(s)

rawDescription: Regular Expression help

description: Regular Expression help


code:
from pyparsing import col,Word,Optional,alphas,nums,ParseException

table = """\
12345678901234567890
COLOR      S   M   L
RED       10   2   2
BLUE           5  10
GREEN      3       5
PURPLE     8"""

# function to create column-specific parse actions
def mustMatchCols(startloc,endloc):
    def pa(s,l,t):
        if not startloc <= col(l,s) <= endloc:
            raise ParseException(s,l,"text not in expected columns")
    return pa

# helper to define values in a space-delimited table
def tableValue(expr, colstart, colend):
    return Optional(expr.copy().addParseAction(mustMatchCols(colstart,colend)))

# define the grammar for this simple table
colorname = Word(alphas)
integer = Word(nums).setParseAction(lambda t: int(t[0])).setName("integer")
row = (colorname("name") +
        tableValue(integer, 11, 12)("S") +
        tableValue(integer, 15, 16)("M") +
        tableValue(integer, 19, 20)("L"))

# parse the sample text - skip over the header and counter lines
for line in table.splitlines()[2:]:
    print
    print line
    print row.parseString(line).dump()

rawDescription: PyParsing: Parsing Cisco's "show ip bgp"


code:
import urllib2

n = 123

try:
    url = 'http://localhost/%d.jpg' % n
    urllib2.urlopen(url)
except urllib2.HTTPError, e:
    if e.code == 404:
        print '%d.jpg was not found' % n
    else:
        raise  # if the issue wasn't a 404, then re-raise the exception

rawDescription: python checking for files

description: Python checking for files


code:
import evernote.edam.notestore.NoteStore as NoteStore

from evernote.api.client import EvernoteClient
from evernote.api.client import Store
from evernote.edam.notestore.ttypes import NoteFilter, NotesMetadataResultSpec

auth_token = "YOUR TOKEN"

client = EvernoteClient(token=auth_token, sandbox=True)

noteStore = client.get_note_store()

# get linked notebooks
linked_notebooks = noteStore.listLinkedNotebooks(auth_token)

linked_notebook = linked_notebooks[0]

# shareKey for the first notebook
shareKey = linked_notebook.shareKey

# get the right noteStore
note_store_uri = linked_notebook.noteStoreUrl
shared_note_store = Store(auth_token, NoteStore.Client, note_store_uri)

# authenticate to the linked notebook
auth_result = shared_note_store.authenticateToSharedNotebook(shareKey,auth_token)

# get the share token
share_token = auth_result.authenticationToken

updated_filter = NoteFilter(words=' ')
offset = 0
max_notes = 40000
result_spec = NotesMetadataResultSpec(includeTitle=True)

result_list = shared_note_store.findNotesMetadata(share_token, updated_filter, offset,             max_notes, result_spec)

print result_list

rawDescription: How to get shared notes in Evernote Python API?

description: Get shared notes in Evernote Python API


code:
def find_shelter():
    print "Your crew needs to find shelter for the first night.\n"
    print "Do you choose....\n"
    print "The cave, it is near the water. You will be safe from wind, but there may be animals inside the cave.\n"
    print "The beach, it is very comfortable. You can see boats, but we will be exposed to weather.\n"
    print "The jungle, it has many trees. You will be safe from storms.  However, there are many animals.\n"
    print "The mountain, it is very high.  You will be safe from the jungle animals, but you may fall off the mountain.\n"
    choice = raw_input("Select A for cave, B for beach, C for jungle, or D for mountain. ")
    return choice

def oh_no_cave(crew):
    print "OH NO! There was a very big storm in the night! It rained and the wind was very strong."
    print "There was a flood in the cave, one person drowned and is dead."
    crew = crew - 1
    print "There are now %s people left in your crew."% crew
    return crew

def oh_no_beach(crew):
    print "OH NO! There was a very big storm in the night! It rained and the wind was very strong."
    print "The storm rained on you. One person was struck by lightening and is dead."
    crew = crew - 1
    print "There are now %s people left in your crew."% crew
    return crew

def oh_no_jungle(crew):
    print "OH NO! There was a very big storm in the night! It rained and the wind was very strong."
    print "But, you were safe in the jungle from the storm. Everyone is ok."
    print "There are still %s people left in your crew."% crew

def oh_no_mountain(crew):
    print "OH NO! There was a very big storm in the night! It rained and the wind was very strong."
    print "You all get very wet on the mountain, but everyone is ok."
    print "There are still %s people left in your crew."% crew

#choice = []
print "You are going on a cruise with your family and friends.\n"
crew = int(raw_input("Enter the number of people on the cruise, must be at least four: \n"))
print "Oh no! Your crew has just shipwrecked on a desolate island."
print "All food and supplies were lost at sea, and the captain has died too. :( "
print "On the island there is a beach, a river, a jungle, a mountain, and a cave."

while crew != 0:
    choice = find_shelter()
    if choice == "a":
        crew = oh_no_cave(crew)
    elif choice == "b":
        crew = oh_no_beach(crew)
    elif choice == "c":
        crew = oh_no_jungle(crew)
    elif choice == "d":
         crew = oh_no_mountain(crew)
    else:
        print "Please enter a valid choice."
else:
    print "OH NO! Everyone in your crew has died! It's all over...."
    print "Completely over."

rawDescription: can't get more functions running in beginner python code

description: Can't get more functions running in beginner python code


code:
import random
HATE_LAMBDAS = random.choice(True, False)
class TestClass(object):
    def __init__(self):
        self.value = 100
        if HATE_LAMBDAS:
            def x():
                self.value += 100
            self.x = x
        else:
            self.x = lambda: setattr(self, "value", self.value + 100)
        self.run()

    def run(self):
        self.x()
        print self.value

t = TestClass()

#Output: 200

rawDescription: Python Lambda Mutability

description: Python Lambda Mutability


code:
from email.parser import FeedParser
f = FeedParser()
f.feed("<insert mail message here, including all headers>")
rootMessage = f.close()

# Now you can access the message and its submessages (if it's multipart)
print rootMessage.is_multipart()

# Or check for errors
print rootMessage.defects

# If it's a multipart message, you can get the first submessage and then its payload
# (i.e. content) like so:
rootMessage.get_payload(0).get_payload(decode=True)

rawDescription: python email encoding problem

description: Python email encoding problem


code:
import urllib2
from bs4 import BeautifulSoup

url1 = "http://www.salatomatic.com/c/Sydney+168"
content1 = urllib2.urlopen(url1).read()
soup = BeautifulSoup(content1)
for link in soup.findAll('a'):
   print link.get('href')

rawDescription: Strip link from website using Beautifulsoup


code:
import sys
import time
import os

watchdir = '/home/lou/Documents/script/txts/'
contents = os.listdir(watchdir)
count = len(watchdir)
dirmtime = os.stat(watchdir).st_mtime

while True:
    newmtime = os.stat(watchdir).st_mtime
    if newmtime != dirmtime:
        dirmtime = newmtime
        newcontents = os.listdir(watchdir)
        added = set(newcontents).difference(contents)
        if added:
            print "Files added: %s" %(" ".join(added))
        removed = set(contents).difference(newcontents)
        if removed:
            print "Files removed: %s" %(" ".join(removed))

        contents = newcontents
    time.sleep(30)

rawDescription: While loop to monitor folder and run script if conditon is true


code:
for length in sorted(results):
    print length, [t.originalWord for t in results[length]]

rawDescription: How do I print the lists of all the indices within defaultdict in Python 3?

description: Print the lists of all the indices within defaultdict in Python 3


code:
import gdata.docs.service

# Create a client class which will make HTTP requests with Google Docs server.
client = gdata.docs.service.DocsService()
# Authenticate using your Google Docs email address and password.
client.ClientLogin('jo@gmail.com', 'password')

# Query the server for an Atom feed containing a list of your documents.
documents_feed = client.GetDocumentListFeed()
# Loop through the feed and extract each document entry.
for document_entry in documents_feed.entry:
  # Display the title of the document on the command line.
  print document_entry.title.text

rawDescription: How do I authenticate my Python application with Google for the Google Contacts API?

description: Authenticate my Python application with Google for the Google Contacts API


code:
from fractions import *

def returnElement(element):
    if '/' in element and len(element) > 1:
        fraction = element.split('/')
        numerator = fraction[0]
        denominator = fraction[1]
        return 'Fraction(' + numerator + ',' + denominator + ')'
    else:
        return element

class main():
    for i in range(0, 10):
        print "\t\nWRITE YOUR OPERATION"
        code = 'print('
        s = raw_input()
        elements = s.split()

        for element in elements:
            code = code + returnElement(element)

        code = code + ')'

        print code
        exec code

rawDescription: Python - Execute a String Code For Fractions


code:
from cStringIO import StringIO
import os
import webbrowser

from apiclient.discovery import build
from apiclient.http import MediaInMemoryUpload
import httplib2
from oauth2client.client import OAuth2WebServerFlow
import pyPdf

CLIENT_ID = 'client_id'
CLIENT_SECRET = 'client_secret'
OAUTH_SCOPE = 'https://www.googleapis.com/auth/drive'
REDIRECT_URI = 'redirect_url'

class GoogleDriveManager(object):

  def __init__(self):
    # Create new Google Drive credentials.
    flow = OAuth2WebServerFlow(
        CLIENT_ID, CLIENT_SECRET, OAUTH_SCOPE, REDIRECT_URI)
    authorize_url = flow.step1_get_authorize_url()
    webbrowser.open(authorize_url)
    code = raw_input('Enter verification code: ').strip()
    self._credentials = flow.step2_exchange(code)

  def GetFile(self, file_id):
    http = httplib2.Http()
    http = self._credentials.authorize(http)
    drive_service = build('drive', 'v2', http=http)
    url = drive_service.files().get(fileId=file_id).execute()['downloadUrl']
    return http.request(url, "GET")[1]

  def GetFileName(self, file_id):
    http = httplib2.Http()
    http = self._credentials.authorize(http)
    drive_service = build('drive', 'v2', http=http)
    return drive_service.files().get(fileId=file_id).execute()['title']

  def InsertFile(self, file_name, data, mimeType):
    http = httplib2.Http()
    http = self._credentials.authorize(http)
    drive_service = build('drive', 'v2', http=http)
    media_body = MediaInMemoryUpload(
        data, mimetype='text/plain', resumable=True)
    body = {
      'title': file_name,
      'mimeType': mimeType
    }
    drive_service.files().insert(body=body, media_body=media_body).execute()

if __name__ == '__main__':
  # Create a drive manager.
  drive_manager = GoogleDriveManager()
  file_id = raw_input('Enter the file id of the pdf file: ').strip()
  file_name, ext = os.path.splitext(drive_manager.GetFileName(file_id))
  # Download the pdf file.
  pdf_data = drive_manager.GetFile(file_id)
  pdf = pyPdf.PdfFileReader(StringIO(pdf_data))
  print "Number of pages: %d" % pdf.getNumPages()
  for i in xrange(pdf.getNumPages()):
    writer = pyPdf.PdfFileWriter()
    writer.addPage(pdf.getPage(i))
    page_data = StringIO()
    writer.write(page_data)
    drive_manager.InsertFile(
        file_name + '-' + str(i) + ext, page_data.getvalue(), 'application/pdf')

rawDescription: How to manipulate PDF in Google Drive API using Python

description: Manipulate PDF in Google Drive API using Python


code:
from pyparsing import ZeroOrMore, OneOrMore, \
                      Keyword, Literal

test_code = """
class CFGFunctions {
  class ABC {
    class AA {
      file = "abc/aa/functions"
      class myFuncName{ recompile = 1; };
    };
    class BB
    {
      file = "abc/bb/functions"
      class funcName{
        recompile=1;
      }
    }
  };
};
"""

class_tkn       = Keyword('class')
lbrace_tkn      = Literal('{')
rbrace_tkn      = Literal('}')
semicolon_tkn   = Keyword(';')
assign_tkn      = Keyword(';')

class_block     = ( class_tkn + identifier + lbrace_tkn + \
                    OneOrMore(class_block | ZeroOrMore(assignment)) + \
                    rbrace_tkn + semicolon_tkn \
                  )

def test_parser(test):
    try:
        results = class_block.parseString(test)
        print test, ' -> ', results
    except ParseException, s:
        print "Syntax error:", s

def main():
    test_parser(test_code)

    return 0

if __name__ == '__main__':
    main()

rawDescription: Python convert C header file to dict

description: Python convert C header file to dict


code:
import inspect

def foo(non_default_var, a=None, b=1, c='bar'):
    inspector = inspect.getargspec(foo)
    local_vars = inspector.args                      # = ['d', 'a', 'b', 'c']
    default_values = inspector.defaults              # = (None, 1, 'bar')
    default_vars = local_vars[-len(default_values):] # Since default values are at the end
    for var, default_value in zip(default_vars, list(default_values)): # Now iterate and compare
        print locals()[var] == default_value         # True if the variable is default

rawDescription: List function parameters not equal to their default values


code:
from subprocess import check_output
ovol = check_output(['osascript', '-e', 'get volume settings'])
print ovol

rawDescription: Set variable using osascript

description: Set variable using osascript


code:
import networkx as nx

data = '''a,b,201212100401
a,d,201212100403
b,e,201212100511
b,c,201212100518
e,f,201212100610
c,a,201212100720'''.split('\n')

G = nx.DiGraph()
for line in data:
    n1, n2, t1 = line.split(',')
    G.add_edge(n1, n2, time=t1)

def check_sequence(list_of_edges):
    times = []
    # First check if all the edges are in the graph
    # and collect their times in a list
    for e in list_of_edges:
        if e in G.edges():
            times.append(G[e[0]][e[1]]['time'])
        else:
            return "Edge {} not in the graph.".format(str(e))
    # Next check if each successive time in the list
    # is greater than the previous time
    start = times[0]
    for time in times[1:]:
        if time > start:
            start = time
        else:
            return 'Edges not in sequence: {}'.format(str(times))
    # If we have not returned up to now, then we are in sequence
    return 'Edges are in sequence: {}'.format(str(times))

print check_sequence( [('a', 'e'), ('e', 'f'), ('a', 'f') ] )
# Edge ('a', 'e') not in the graph.
print check_sequence( [('a', 'b'), ('b', 'c'), ('c', 'a') ] )
# Edges are in sequence: ['201212100401', '201212100518', '201212100720']
print check_sequence( [('c', 'a'), ('a', 'b'), ('b', 'c') ] )
# Edges not in sequence: ['201212100720', '201212100401', '201212100518']

rawDescription: Python - Logical Tests on Graph Data with NetworkX


code:
import ctypes
from ctypes import wintypes

LPRECT = ctypes.POINTER(wintypes.RECT)

# Callback Factory
MonitorEnumProc = ctypes.WINFUNCTYPE(
    ctypes.c_bool,
    wintypes.HMONITOR,
    wintypes.HDC,
    LPRECT,
    wintypes.LPARAM)

ctypes.windll.user32.EnumDisplayMonitors.restype = wintypes.BOOL
ctypes.windll.user32.EnumDisplayMonitors.argtypes = [
    wintypes.HDC,
    LPRECT,
    MonitorEnumProc,
    wintypes.LPARAM]

def _monitorEnumProc(hMonitor, hdcMonitor, lprcMonitor, dwData):
    print 'call result:', hMonitor, hdcMonitor, lprcMonitor, dwData
    print lprcMonitor[0].right, lprcMonitor[0].bottom
    return True # continue enumeration

# Make the callback function
enum_callback = MonitorEnumProc(_monitorEnumProc)

def enum_mons():
    '''Enumerate the display monitors.'''
    return ctypes.windll.user32.EnumDisplayMonitors(
        None,
        None,
        enum_callback,
        0)

if __name__ == '__main__':
    print 'return code: %d' % enum_mons()

rawDescription: What would cause this code to produce different results when running at the module level versus in the scope of a function?


rawDescription: What is the easiest way to search through a list of dicts in Python?


code:
try:
    from hashlib import sha as hasher
except ImportError:
    # You could probably exclude the try/except bit,
    # but older Python distros dont have hashlib.
    try:
        import sha as hasher
    except ImportError:
        import md5 as hasher

def hash_password(password):
    """Returns the hashed version of a string
    """
    return hasher.new( str(password) ).hexdigest()

def load_auth_file(path):
    """Loads a comma-seperated file.
    Important: make sure the username
    doesn't contain any commas!
    """
    # Open the file, or return an empty auth list.
    try:
        f = open(path)
    except IOError:
        print "Warning: auth file not found"
        return {}

    ret = {}
    for line in f.readlines():
        split_line = line.split(",")
        if len(split_line) > 2:
            print "Warning: Malformed line:"
            print split_line
            continue # skip it..
        else:
            username, password = split_line
            ret[username] = password
        #end if
    #end for
    return ret

def main():
    auth_file = "/home/blah/.myauth.txt"
    u = raw_input("Username:")
    p = raw_input("Password:") # getpass is probably better..
    if auth_file.has_key(u.strip()):
        if auth_file[u] == hash_password(p):
            # The hash matches the stored one
            print "Welcome, sir!"

rawDescription: Python Authentication API

description: Python Authentication API


code:
def SaveToPDF_Function( self, event ):

    NameString = self.NameField.GetValue()

    try:
        c = canvas.Canvas("myFile.pdf", pagesize=landscape(A3))

        c.drawCentredString(600, 800, 'OPENED... Welcome to ReportLab! This is my FIRST App...'  + NameString )

        c.save()

        subprocess.Popen(['myFile.pdf'], shell=True)

    except IOError:
        print 'The file is already OPENED!'

rawDescription: wxPython/ReportLab: How to create and open a .pdf file on button clicked

description: WxPython/ReportLab: How to create and open a .pdf file on button clicked


code:
range = wb.ActiveSheet.Range("A2:A200")
for cell in range:
    if cell.Value is not None:
        f = 'C:\Users\\robertph\Share\ioe\\' + str(cell.Value) + '.txt'
        ol = wb.ActiveSheet.OLEObjects().Add(Filename=f, Link=False)
        ol.Top = cell.GetOffset(0, 3).Top
        ol.Left = cell.GetOffset(0, 3).Left

rawDescription: VBA to Python conversion

description: VBA to Python conversion


code:
import datetime
data1 = datetime.datetime.now()
data2 = datetime.datetime.now()

days, seconds = diff.days, diff.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

print hours,minutes,seconds

rawDescription: How to get the difference between two dates in hours, minutes and seconds.?

description: Get the difference between two dates in hours, minutes and seconds.


code:
import re
import mechanize
import lxml.html as lh

url='hidden'

parr=lh.parse(url).xpath('//p/text()')
elem=parr[2]
op1=int(elem[0:5])
op2=int(elem[6:11])
sum=op1+op2
print sum
sum=str(sum)

br=mechanize.Browser()
br.open(url)

br.select_form(name="loginform")
br["sum"]=sum
resp=br.submit()

br.select_form(name="poll")
br["vote"]=["7"]
resp2=br.submit()

print resp2.read()

rawDescription: Python Web Bot (urllib)

description: Python Web Bot (urllib)


code:
from collections import defaultdict

lst = ['RH', 'CD241', 'C2', 'SCZD9', 'RG59L', 'WNT3A']
ref_dict = {
    '': [''], '6005': ['RH50A, CD241, SLC42A1'], '603': [''],
    '6000': [''], '8787': ['PERRS, RGS9L, MGC26458'],
    '41': ['ACCN2, BNaC2, hBNaC2'], '8490': [''],
    '9628': [''], '5999': ['SCZD9']
}

all_values = defaultdict(list)
for key in ref_dict:
    for value in (map(lambda x: x.strip(), ref_dict[key][0].split(","))):
        all_values[value].append(key)

print all_values['CD241'] # ['6005']

rawDescription: Looping a list through dictionary values python


code:
import os

from fsevents import Observer, Stream

def callback(file_event):
    print file_event.name # the path of the modified file

def main():
    observer = Observer()
    observe_path = os.getcwd() # just for this example
    stream = Stream(callback, observe_path, file_events=True)
    observer.start()
    observer.schedule(stream)

if __name__ == '__main__':
    main()

rawDescription: How to watch directory for file modifications

description: Watch directory for file modifications


code:
import time
import pygame, sys
from pygame.locals import *
pygame.init()
clocks = pygame.time.Clock()
surfaceObject = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Bounce')

mousey,mousex = 0,0
imgx = 10
imgy = 10
pixmove = 5
movement = 'down'

background = pygame.image.load('bg.jpg').convert()
ball = pygame.image.load('ball.jpg').convert_alpha()
pygame.mixer.music.load('yeah.mp3')

while True:
    time.sleep(1)
    if movement == 'down':
        imgx += pixmove
    if imgy < 200:
        movement = 'right'

    elif movement  == 'right':
        imgx += pixmove
    if imgx < 200:
        movement = 'up'

    elif movement == 'up':
        imgy -= pixmove
    if imgy < 30:
        movement = 'left'

    elif movement == 'left':
        imgx -= pixmove
    if imgx < 30:
        movement = 'down'
    print movement
    print imgx
    print imgy

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    surfaceObject.blit(background,(mousex,mousey))
    surfaceObject.blit(ball,(imgx,imgy))
    pygame.mixer.music.play()
    pygame.display.update()
    clocks.tick(50)

rawDescription: Moving the ball with pygame

description: Moving the ball with pygame


code:
import re
import sys
from collections import Counter

#sys.stdout = open("result.txt", 'w+')

def intersect(list1, list2):
  for o in list1:
    if o in list2:
      list1.remove(o)
      list2.remove(o)
  return list1, list2

def read(in_file):
  cases = []
  caselines_index = []
  readlines = []
  readlines_num = []
  with open(in_file, 'r') as file:
    readfile = file.read().strip()
    for line in readfile.split('\n'):
      readlines_num.append(line.strip())
    regex = re.compile("switch\(\$\d\).+?\}", re.DOTALL)
    readfile = re.sub(regex, ' ', readfile)
    for line in readfile.split('\n'):
      readlines.append(line.strip())
    for line in readlines:
      case_search = re.search("case\s\".+?\"\:\s", line)
      if case_search:
        caselines_index.append(readlines.index(line))
    #print caselines_index
    caselines_index_iter = iter(caselines_index)
    try:
      int_line_index = int(next(caselines_index_iter))
    except:
      print "No cases found"
    try:
      int_next_index = int(next(caselines_index_iter))
    except:
      int_next_index = len(readlines) - 1
    while True:
      try:
        case_text = ' '.join(readlines[int_line_index:int_next_index]).strip()
        match1 = re.search("nvp_add", case_text)
        match2 = re.search("details", case_text)
        if match1 or match2:
          case = [readlines[int_line_index].strip(), readlines_num.index(readlines[int_line_index]) + 1, case_text]
          cases.append(case)
        int_line_index = int_next_index
        int_next_index = int(next(caselines_index_iter))
      except StopIteration:
        case_text = ' '.join(readlines[int_line_index:len(readlines) - 1]).strip()
        case = [readlines[int_line_index].strip(), readlines_num.index(readlines[int_line_index]), case_text]
        cases.append(case)
        break
  return cases

def work(cases):
  MATCH = 1
  for case_list in cases:
    details = []
    nvp_add = []
    caseline = case_list[0].strip()
    nvp = re.findall("details\(.+?\)", case_list[2].strip())

    for item in nvp:
      result_list = re.findall("(\$.+?)[\,\)]", item)

      for result in result_list:
        if "$*" not in result:
          details.append(result)

    nvp = re.findall("nvp_add\(.+?\)", case_list[2].strip())

    for item in nvp:
      result_list = re.findall("(\$.+?)[\,\)]", item)

      for result in result_list:
        if "$*" not in result:
          nvp_add.append(result)

    nvp_add_c = Counter(nvp_add)
    details_c = Counter(details)
    missing_from_details = list((nvp_add_c - details_c).elements())
    missing_from_nvp_add = list((details_c - nvp_add_c).elements())
    if missing_from_nvp_add or missing_from_details:
      MATCH = 0
      print caseline + "   LINE - " + str(case_list[1] + 1)
      for mismatch in missing_from_details:
        print "Missing from details:"
        print mismatch
      for mismatch in missing_from_nvp_add:
        print "Missing from nvp_add:"
        print mismatch
      print "\n"
  if MATCH == 1:
    print "MATCH"
  else:
    print "MISMATCHES"

def main():
  in_file = "target1.txt"
  cases = read(in_file)
  work(cases)

if __name__=="__main__":
  main()

rawDescription: Python script couldnt detect mismatch when $instance deleted in only one of the value nvp_add in double if else input statement


rawDescription: Set of dictionary values python

description: Set of dictionary values python


code:
import multiprocessing
import time
import os
from cassandra.cluster import Cluster
from cassandra import ConsistencyLevel
from cassandra.query import SimpleStatement

def mp_worker(inputArg):
        cluster = Cluster(['1.2.1.4'])
        session = cluster.connect('poc')

        with open(inputArg[0]) as f:
            for line in f:
                query = SimpleStatement (
                    "INSERT INTO testTable (cust_id, accts, offers) values (%s)" %(line),
                    consistency_level=ConsistencyLevel.ONE)
                session.execute_async (query)

def mp_handler(inputData, nThreads = 8):
    p = multiprocessing.Pool(nThreads)
    p.map(mp_worker, inputData, chunksize=1)
    p.close()
    p.join()

if __name__ == '__main__':
    temp_in_data = ['/toImport/part-00000', '/toImport/part-00001', '/toImport/part-00002']
    start = time.time()
    N_Proc = 3
    file_data = [(i,) for i in temp_in_data]

    print '----------------------------------Start Working!!!!-----------------------------'
    print 'Number of Processes using: %d' %N_Proc
    mp_handler(file_data, N_Proc)
    end = time.time()
    time_elapsed = end - start
    print '----------------------------------All Done!!!!-----------------------------'
    print "Time elapsed: {} seconds".format(time_elapsed)

rawDescription: python cassandra driver same insert performance as copy

description: Python cassandra driver same insert performance as copy


code:
import msvcrt

def inputemulator():
    buf = []
    while True:
        ch = msvcrt.getch()
        if ch=="\r": #newline
            yield ''.join(buf)
            buf = []
        elif ch=="\x03": #ctrl-c
            raise KeyboardInterrupt
        elif ch=="\x16": #ctrl-v, do paste, ...
            pass
        else:
            buf.append(ch)

for line in inputemulator():
    print line

rawDescription: My script opens a windows cmd prompt, need help pasting into it


code:
n = 45346
output = []
while n:
    output.append(n % 100)
    n //= 100

output = output[::-1]
print output

rawDescription: Python - Split user input integer into list, where each entry is 2 digits


code:
import collections
import heapq

Node = collections.namedtuple('Node', ['v', 'children'])

def min_depth_bfs(root):
    todo = [(1, root)]
    while todo:
        depth, node = heapq.heappop(todo)
        if not node.children: return depth, node
        for c in node.children:
            heapq.heappush(todo, (depth + 1, c))

def min_depth_dfs(node):
    if not node.children: return 1, node
    d, n = min(min_depth_dfs(c) for c in node.children)
    return 1 + d, n

example = Node(8, [Node(3, [Node(1, [])]), Node(10, [])])

print min_depth_dfs(example)
print min_depth_bfs(example)

rawDescription: how to caculate the minimum depth of binary tree

description: Caculate the minimum depth of binary tree


code:
import sys
print '\n'.join(sys.modules)

rawDescription: What is the best way of listing all imported modules in python?


code:
import sqlite3
from collections import defaultdict

downloadsByExtensionCount = defaultdict(int)
# downloadsByExtensionList = []
logFiles = ['file1.log', 'file2.log', 'file3.log', 'file4.log']

conn = sqlite3.connect('c:/temp/example')
c = conn.cursor()
# Create table
c.execute('create table if not exists logs(date, time, c_ip, cs_method, s_port, cs_uri_stem, cs_user_agent)')

for logFile in logFiles:
    try:
        log = open(logFile, 'rb')#, encoding='utf-8')
    except IOError, e:
        continue

    logLines = log.readlines()

    for logLine in logLines:
        date, time, c_ip, cs_method, s_port, cs_uri_stem, cs_user_agent = logLine.split(" ")

        downloadsByExtensionCount[cs_uri_stem] += 1
        c.execute(
            'insert into logs(date, time, c_ip, cs_method, s_port, cs_uri_stem, cs_user_agent) values(?,?,?,?,?,?,?)',
            (date, time, c_ip, cs_method, s_port, cs_uri_stem, cs_user_agent)
            )

conn.commit()
conn.close()

rawDescription: Python memory leak while populating a list - how to fix it?


code:
import csv

def url_escaper(data):
    for line in data:
        yield line.replace('&','&')

with open("adzuna_0.csv", 'r') as file_in, open("adzuna_X.csv", 'w') as file_out:
    csv_in = csv.reader(url_escaper(file_in))
    csv_out = csv.writer(file_out)
    for i, row in enumerate(csv_in):

        if len(row) == num_headers:
            csv_out.writerow(row)
        else:
            print "line %d is malformed" % i

rawDescription: adapt python script to replace/escape particular characters of the input data

description: Adapt python script to replace/escape particular characters of the input data


code:
def kernel_thing(N):
  import numpy as np
  n = N // 2 + 1
  a = np.zeros((N, N), dtype=int)
  for i in xrange(n):
    a[i:N-i, i:N-i] += 1
  return a

def kernel_to_string(a):
  return '{} {}\n'.format(a.shape[0], a.shape[1]) + '\n'.join(' '.join(str(element) for element in row) for row in a)

print kernel_to_string(kernel_thing(5))
print kernel_to_string(kernel_thing(6))
print kernel_to_string(kernel_thing(17))

rawDescription: Using Numpy to generate ASCII kernel

description: Using Numpy to generate ASCII kernel


code:
print u'☃'.encode('unicode_escape')
print repr(u'☃')

rawDescription: How to recognize special eol character when I see it, using Python?

description: Recognize special eol character when I see it, using Python


code:
import math

def five_digits(number):
    ndigits = int(math.log10(number))+1
    try:
        return number//int(10**(ndigits-5))
    except ZeroDivisionError:
        return number

print five_digits(10000000)
print five_digits(12345678)
print five_digits(12345)
print five_digits(1234)  #don't know what you want to do with this one...

rawDescription: python trim number without converting to string first

description: Python trim number without converting to string first


code:
from PyQt4 import QtCore, QtGui

class MainWidget(QtGui.QDialog):

    # Option #3 - Custom signal
    closing = QtCore.pyqtSignal()

    def __init__(self):
        super(MainWidget, self).__init__()

        self.layout = QtGui.QVBoxLayout(self)

        for i in xrange(5):
            label = ResourceLabel('label%02d' % i)
            self.layout.addWidget(label)

            # option #2
            # Let a signal trigger the cleanup on the children
            # self.destroyed.connect(label.close)

            # option #3
            # Use a custom signal emitted from the closeEvent,
            # wired directly to the cleanup slot on the object
            # self.closing.connect(label.close)

    def closeEvent(self, event):
        print "Closing main window"

        # option #1
        # if you want to trigger a cleanup specifically when
        # this widget is closed, as opposed to destroyed
        for i in xrange(self.layout.count()):
            item = self.layout.itemAt(i)
            widget = item.widget()
            if widget:
                try:
                    widget.close()
                except:
                    pass

        # Or Option #3 - emit a custom signal
        self.closing.emit()

        super(MainWidget, self).closeEvent(event)

class ResourceLabel(QtGui.QLabel):

    def __init__(self, *args, **kwargs):
        super(ResourceLabel, self).__init__(*args, **kwargs)
        self.aResource = "FOO"

    def close(self):
        print "Cleaning up", self
        self.aResource = None

if __name__ == "__main__":
    app = QtGui.QApplication([])
    win = MainWidget()
    win.show()
    win.raise_()
    app.exec_()

rawDescription: How to detect parent widget close in PyQT?

description: Detect parent widget close in PyQT


code:
def decorator(fnc):
    def test():
        print "test"
    return test

@decorator
def foo():
    print "foo"

foo() # will print test

rawDescription: Decorator does not work when function is passed as object in a process


code:
c = conv2d(m,np.array([w, w, w]))
f = theano.function([m], c)
print f(numpy.ones([100,100], dtype=numpy.float32)).shape  # outputs (3, 91, 100)

rawDescription: Why does theano conv2d add empty dimension?


code:
@view_config(context='Channels')
def some_view(context, request):
    user = context.__parent__
    userlist = user.__parent__
    print user.__name__  # Prints a, b or c
    print userlist.__name__  # Prints 'users'

rawDescription: How to use the pyramid_traversalwrapper?

description: Use the pyramid_traversalwrapper


code:
class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])')
@register.filter
def add_class(value, css_class):
    string = unicode(value)
    match = class_re.search(string)
    if match:
        m = re.search(r'^%s$|^%s\s|\s%s\s|\s%s$' % (css_class, css_class,
                                                    css_class, css_class),
                                                    match.group(1))
        print match.group(1)
        if not m:
            return mark_safe(class_re.sub(match.group(1) + " " + css_class,
                                          string))
    else:
        return mark_safe(string.replace('>', ' class="%s">' % css_class))
    return value

rawDescription: Django: Adding CSS classes when rendering form fields in a template


code: print woodWOPfile, 'YA="%s"' % xbo.setdefault('Y', xbo_prev['Y'])

rawDescription: Python : simplify try / except code?

description: Python : simplify try / except code


code:
cmnd = ["ffmpeg", "-i", "/your/file.avi", "-acodec", "copy", "-ss", "00:00:00", "-t", "00:00:30", "-f", "avi", "pipe:1"]

p = subprocess.Popen(cmnd, stdout=subprocess.PIPE)

out, err = p.communicate()

print len(out) # print the length of the data received

rawDescription: Assign output to a variable instead to a Output file


code:
import tempfile
temp = tempfile.NamedTemporaryFile()

with open("~/somefile.txt") as inf:
    for line in inf:
        if line==line.lstrip():
            temp.write(line)

temp.seek(0) # <=============== ADDED

line = str(temp.readline()).strip()
print line

rawDescription: temp.readline() empty?

description: Temp.readline() empty


code:
import codecs
try:
    f = codecs.open(filename, encoding='utf-8', errors='strict')
    for line in f:
        pass
    print "Valid utf-8"
except UnicodeDecodeError:
    print "invalid utf-8"

rawDescription: How to write a check in python to see if file is valid UTF-8?

description: Write a check in python to see if file is valid UTF-8


code:
from django.core.cache.backends import locmem
print locmem._caches

rawDescription: Contents of locmem cache in django?

description: Contents of locmem cache in django


code:
input_list = []
with open('input', 'r') as inputfile:
    for line in inputfile.readlines():
        item, val = line.split(':')
        input_list.append((item.strip(), int(val.strip())))
    res_list = sorted(input_list, key=lambda input: input[1], reverse=True)

print res_list  #[('banana', 11), ('cucumber', 10), ('pepper', 9), ('jalapeno', 8), ('okra', 7), ('carrot', 6), ('zucchini', 5), ('kiwi', 4), ('watermelon', 3), ('orange', 2), ('apple', 1)]

rawDescription: I want to organise text file contents by descending score


code:
data = csv.reader(open(alignment_filename,'r'))
data.next()

print all([row[0]<row[1] for row in data])

rawDescription: how to make a function that check if the csv file is valid or not? (python)

description: Make a function that check if the csv file is valid or not? (python)


code:
from pybtex.database.input import bibtex
parser = bibtex.Parser()
bib_data = parser.parse_file('examples/foo.bib')
bib_data.entries.keys()
print bib_data.entries['ruckenstein-diffusion'].fields['title']

rawDescription: Is there a reliable python library for taking a BibTex entry and outputting it into specific formats?


code:
import os
import shutil

srcpath = "C:\Users\joshuarb\Desktop\Python_Test\UnorganizedImages"
srcfiles = os.listdir(srcpath)

destpath = "C:\Users\joshuarb\Desktop\Python_Test\OrganizedImages"

# extract the three letters from filenames and filter out duplicates
destdirs = list(set([filename[0:8] for filename in srcfiles]))

def create(dirname, destpath):
    full_path = os.path.join(destpath, dirname)
    os.mkdir(full_path)
    return full_path

def move(filename, dirpath):
    shutil.move(os.path.join(srcpath, filename)
            ,dirpath)

# create destination directories and store their names along with full  paths
targets = [
    (folder, create(folder, destpath)) for folder in destdirs
]

for dirname, full_path in targets:
    for filename in srcfiles:
        if dirname == filename[0:8]:
           move(filename, full_path)

rawDescription: Organizing and copying files to new folders


code:
#Print out the results
for i in range(nprocs):
    result = result_q.get()
    print result

#Joint the process to wait for all data/process to be finished
for p in procs:
    p.join()

rawDescription: Multiprocessing has cutoff at 992 integers being joined as result


code:
class Widget:
    def __repr__(self):
            return "repr of a Widget"
    def __str__(self):
            return "str of a Widget"
x = Widget()
x
print x
print [x,2,3]
print repr(x)
print str(x)

rawDescription: When I am in the Python or IPython console, what is called when I am returned an output?


code:
import re
from collections import Counter

def getWordListAndCounts(text):
    return Counter(re.split('\s+', str([' '.join(x) for x in text][0])))

text = [['I like Apple' , 'I also like Google']]
print getWordListAndCounts(text)

rawDescription: Shorter way to code in Python

description: Shorter way to code in Python


code:
import random
import struct

main_list = range(100)
random.shuffle(main_list)

# 'I' meaning unsigned int of 4 bytes
bytes = struct.pack("{}I".format(len(main_list)), *main_list)

for send_50 in zip(*[iter(bytes)]*50):
    print len(send_50)

rawDescription: Convert a list of integers to a bytearray in Python


rawDescription: Getting .decode("hex") to display results as normal charcters and escaped hex when run from .py


code:
import Tkinter
import turtle
import sys

def main():
    root = Tkinter.Tk()
    cv = Tkinter.Canvas(root, width = 600, height= 600)
    cv.pack(side = Tkinter.LEFT)
    root.title("Draw")
    t = turtle.RawTurtle(cv)
    screen = t.getscreen()
    screen.setworldcoordinates(0,0,600,600)
    frame = Tkinter.Frame(root)
    frame.pack(side = Tkinter.RIGHT, fill = Tkinter.BOTH)
    quitbutton = Tkinter.Button(frame, text='Quit', command = quithandler)
    quitbutton.pack()
    root.mainloop()

def quithandler():
    print 'Goodbye'
    sys.exit(0)

if __name__ == "__main__":
    main()

rawDescription: Simple Tkinter program is not responding


code:
def ex4(str4):

    someLetter = str4[ :1]
    return str4.count(someLetter)

print ex4("mldtmgm")

rawDescription: python program doesn't work

description: Python program doesn't work


code:
color_list = [
['black', 'maroon', 'maroon', 'maroon', 'maroon']  ,
['purple', 'black', 'maroon', 'maroon', 'maroon']  ,
['maroon', 'purple', 'maroon', 'teal', 'teal']     ,
['maroon', 'maroon', 'purple', 'maroon', 'maroon'] ,
['teal', 'olive', 'teal', 'maroon', 'maroon']
]

from collections import Counter

cnt = [Counter(x) for x in color_list]

for x, y in [('black', 'maroon'), ('teal', 'olive')]:
    print x, y, sum(min(c[x], c[y]) for c in cnt)

rawDescription: efficienty count the elements in the list

description: Efficienty count the elements in the list


code:
def permutation(numberList,array,visited,place):
    if (place==len(numberList)):
        print array
    else:
        i=0
        while (i < len(numberList)):
            if i not in visited:
                visited.add(i)
                array.append(numberList[i])
                permutation(numberList,array,visited,place+1)
                array.pop()
                visited.remove(i)
            i+=1

def scanList():
    numberList=[];
    number=input()
    #keep scanning for numbers for the list
    while(number!=0):
       numberList.append(number)
       number=input()
    return numberList

permutation(scanList(),[],set(), 0)

rawDescription: Permutations in Python without repetitions


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

print 'Please enter one alias per line. Leave blank when finished.'
aliases = [alias for alias in iter (raw_input, '') ]
print (aliases)

rawDescription: How to receive a list of unknown length of strings

description: Receive a list of unknown length of strings


code:
@staticmethod
def deleteProjects():
    #projects = os.listdir(os.path.join(ENGINE_DIR, r"scv\Projects"))
    ENGINE_DIR = r"C:\AutoTest\engine"
    projects = os.listdir(os.path.join(ENGINE_DIR, r"scv\Projects"))
    for project in projects:
        logging.error("Project %s not deleted" % project)
        path = os.path.join(os.path.join(ENGINE_DIR, r"scv\Projects"), project)
        print "*** path ***"
        print path
        shutil.rmtree(path)

rawDescription: Python how to delete all files from a folder. Not to delete the folder


code:
import httplib

NO_WEB_SERVER = 0
WEB_SERVER = 1
GAE_DEV_SERVER_1_0 = 2
def checkServer(host, port, try_only_ssl = False):
    hh = None
    connectionType = httplib.HTTPSConnection if try_only_ssl \
                                             else httplib.HTTPConnection
    try:
        hh = connectionType(host, port)
        hh.request('GET', '/_ah/admin')
        resp = hh.getresponse()
        headers = resp.getheaders()
        if headers:
            if (('server', 'Development/1.0') in headers):
                return GAE_DEV_SERVER_1_0|WEB_SERVER
            return WEB_SERVER
    except httplib.socket.error:
        return NO_WEB_SERVER
    except httplib.BadStatusLine:
        if not try_only_ssl:
            # retry with SSL
            return checkServer(host, port, True)
    finally:
        if hh:
            hh.close()
    return NO_WEB_SERVER

print checkServer('scorpio', 22)   # will print 0 an  ssh server
print checkServer('skiathos', 80)  # will print 1 for an apache web server
print checkServer('skiathos', 8080) # will print 3, a GAE Dev Web server
print checkServer('no-server', 80) # will print 0, no server
print checkServer('www.google.com', 80) # will print 1
print checkServer('www.google.com', 443) # will print 1

rawDescription: Use python to check if dev_appserver is running on localhost


code:
from dragonfly.all import Grammar, CompoundRule

# Voice command rule combining spoken form and recognition processing.
class ExampleRule(CompoundRule):
    spec = "do something computer"                  # Spoken form of command.
    def _process_recognition(self, node, extras):   # Callback when command is spoken.
         print "Voice command spoken."

# Create a grammar which contains and loads the command rule.
grammar = Grammar("example grammar")                # Create a grammar to contain the command    rule.
grammar.add_rule(ExampleRule())                     # Add the command rule to the grammar.
grammar.load()                                      # Load the grammar.

while True:
    pythoncom.PumpWaitingMessages()
    sleep(.1)

rawDescription: How do you recognize speech with the Python module Dragonfly?

description: Recognize speech with the Python module Dragonfly


code:
def time() :
    t_u = 0
    i = 0
    while i < len(tlist) - 1:
        # if the number is in the range
        # do the calculations and move to the next number
        if t_u > tlist[i] and t_u < tlist[i + 1] :
            print "\n The t_u value:", t_u, 'is between',
            print "start:", tlist[i], " and end: ", tlist[i+1]
            poly = poly_coeff(tlist[i], tlist[i + 1], t_u)
            Newton(poly)
            t_u = t_u + 0.04 # regular time interval
        # if the number is at the boundary of the range
        # go to the next number without doing the calculation
        elif t_u == tlist[i] or t_u == tlist[i + 1] :
            print "\n The t_u value:", t_u, 'is on the boundary of',
            print "start:", tlist[i], " and end: ", tlist[i+1]
            t_u = t_u + 0.04 # regular time interval
        # if the number isn't in the range, move to the next range
        else :
            i += 1

rawDescription: getting a boundary of an item from another list

description: Getting a boundary of an item from another list


code:
import socket
import dns.resolver

# Basic query
for rdata in dns.resolver.query('www.yahoo.com', 'CNAME') :
    print rdata.target

# Set the DNS Server
resolver = dns.resolver.Resolver()
resolver.nameservers=[socket.gethostbyname('ns1.cisco.com')]
for rdata in resolver.query('www.yahoo.com', 'CNAME') :
    print rdata.target

rawDescription: Using the dig command in python

description: Using the dig command in python


code:
from gi.repository import Gtk, GdkPixbuf, Gdk
import urllib
import os
TARGET_TYPE_URI_LIST = 80

def get_file_path_from_dnd_dropped_uri(uri):
    # get the path to file
    path = ""
    if uri.startswith('file:\\\\\\'): # windows
        path = uri[8:] # 8 is len('file:///')
    elif uri.startswith('file://'): # nautilus, rox
        path = uri[7:] # 7 is len('file://')
    elif uri.startswith('file:'): # xffm
        path = uri[5:] # 5 is len('file:')

    path = urllib.url2pathname(path) # escape special chars
    path = path.strip('\r\n\x00') # remove \r\n and NULL

    return path

def on_drag_data_received(widget, context, x, y, selection, target_type, timestamp):
    if target_type == TARGET_TYPE_URI_LIST:
        uri = selection.get_data().strip('\r\n\x00')
        print 'uri', uri
        uri_splitted = uri.split() # we may have more than one file dropped
        for uri in uri_splitted:
            path = get_file_path_from_dnd_dropped_uri(uri)
            print 'path to open', path
            if os.path.isfile(path): # is it file?
                data = file(path).read()
                #print data

w = Gtk.Window()
w.connect('drag_data_received', on_drag_data_received)

w.drag_dest_set( Gtk.DestDefaults.MOTION|
                  Gtk.DestDefaults.HIGHLIGHT | Gtk.DestDefaults.DROP,
                  [Gtk.TargetEntry.new("text/uri-list", 0, 80)], Gdk.DragAction.COPY)

w.show_all()
Gtk.main()

rawDescription: Drag and drop file example in pygobject

description: Drag and drop file example in pygobject


code:
foos = doc.find('foos')
for foo in foos:
    for text in foo.itertext():
        print text.strip(),
    print

rawDescription: extract tag inside text element of an xml tag

description: Extract tag inside text element of an xml tag


code:
import json

class MultiDimensionalArrayEncoder(json.JSONEncoder):
    def encode(self, obj):
        def hint_tuples(item):
            if isinstance(item, tuple):
                return {'__tuple__': True, 'items': item}
            if isinstance(item, list):
                return [hint_tuples(e) for e in item]
            else:
                return item

        return super(MultiDimensionalArrayEncoder, self).encode(hint_tuples(obj))

def hinted_tuple_hook(obj):
    if '__tuple__' in obj:
        return tuple(obj['items'])
    else:
        return obj

enc = MultiDimensionalArrayEncoder()
jsonstring =  enc.encode([1, 2, (3, 4), [5, 6, (7, 8)]])

print jsonstring

# [1, 2, {"items": [3, 4], "__tuple__": true}, [5, 6, {"items": [7, 8], "__tuple__": true}]]

print json.loads(jsonstring, object_hook=hinted_tuple_hook)

# [1, 2, (3, 4), [5, 6, (7, 8)]]

rawDescription: Preserve Python tuples with JSON

description: Preserve Python tuples with JSON


code:
print id(df)
df2 = df
print id(df2)
df  = df[df['C']>0]
print id(df)

rawDescription: Re-assignment in Pandas: Copy or view?

description: Re-assignment in Pandas: Copy or view


code:
import Tkinter

class Values(Tkinter.Tk):
    """docstring for Values"""
    def __init__(self, parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()
        stepOne = Tkinter.LabelFrame(self, text=" 1. Enter Values ")
        stepOne.grid(row=0, columnspan=7, sticky='W',padx=5, pady=5, ipadx=5, ipady=5)
        self.Val1Lbl = Tkinter.Label(stepOne,text="Value 1")
        self.Val1Lbl.grid(row=0, column=0, sticky='E', padx=5, pady=2)
        self.Val1Txt = Tkinter.Entry(stepOne)
        self.Val1Txt.grid(row=0, column=1, columnspan=3, pady=2, sticky='WE')
        self.Val2Lbl = Tkinter.Label(stepOne,text="Value 2")
        self.Val2Lbl.grid(row=1, column=0, sticky='E', padx=5, pady=2)
        self.Val2Txt = Tkinter.Entry(stepOne)
        self.Val2Txt.grid(row=1, column=1, columnspan=3, pady=2, sticky='WE')

        self.val1 = None
        self.val2 = None

        SubmitBtn = Tkinter.Button(stepOne, text="Submit",command=self.submit)
        SubmitBtn.grid(row=4, column=3, sticky='W', padx=5, pady=2)

    def submit(self):
        self.val1=self.Val1Txt.get()
        if self.val1=="":
            Win2=Tkinter.Tk()
            Win2.withdraw()

        self.val2=self.Val2Txt.get()
        if self.val2=="":
            Win2=Tkinter.Tk()
            Win2.withdraw()

        self.quit()

if __name__ == '__main__':
    app = Values(None)
    app.title('Values')
    app.mainloop() #this will run until it closes
    #Print the stuff you want.
    print app.val1,app.val2

rawDescription: Return values of Tkinter text entry, close GUI


code:
import io
import re

with io.open('a.csv') as fin:
    for line in fin:
        parts = line.split(';')
        parts[13] = parts[13].replace('¶', ' ')
        print ','.join(parts)

rawDescription: Perl to Python - CSV cleaning

description: Perl to Python - CSV cleaning


code:
import fileinput
for line in fileinput.input():
 for p in line.replace('\\(','EscapeLP').replace('\\)','EscapeRP').split('(')[1:]:
  print p[:p.find(')')].replace('EscapeLP','(').replace('EscapeRP',')')

rawDescription: Extracting text from postscript and/or creating overlays using python


code:
import gevent
import gevent.monkey

gevent.monkey.patch_all()

INTERVAL = 10

def callback():
    # do something
    print "!"

def loop():
    while True:
        gevent.sleep(INTERVAL)
        callback()

gevent.Greenlet.spawn(loop)

rawDescription: somethig like cron (timer) in gevent

description: Somethig like cron (timer) in gevent


code:
"""
Module that provides a class that filters profanities

"""

__author__ = "leoluk"
__version__ = '0.0.1'

import random
import re

class ProfanitiesFilter(object):
    def __init__(self, filterlist, ignore_case=True, replacements="$@%-?!",
                 complete=True, inside_words=False):
        """
        Inits the profanity filter.

        filterlist -- a list of regular expressions that
        matches words that are forbidden
        ignore_case -- ignore capitalization
        replacements -- string with characters to replace the forbidden word
        complete -- completely remove the word or keep the first and last char?
        inside_words -- search inside other words?

        """

        self.badwords = filterlist
        self.ignore_case = ignore_case
        self.replacements = replacements
        self.complete = complete
        self.inside_words = inside_words

    def _make_clean_word(self, length):
        """
        Generates a random replacement string of a given length
        using the chars in self.replacements.

        """
        return ''.join([random.choice(self.replacements) for i in
                  range(length)])

    def __replacer(self, match):
        value = match.group()
        if self.complete:
            return self._make_clean_word(len(value))
        else:
            return value[0]+self._make_clean_word(len(value)-2)+value[-1]

    def clean(self, text):
        """Cleans a string from profanity."""

        regexp_insidewords = {
            True: r'(%s)',
            False: r'\b(%s)\b',
            }

        regexp = (regexp_insidewords[self.inside_words] %
                  '|'.join(self.badwords))

        r = re.compile(regexp, re.IGNORECASE if self.ignore_case else 0)

        return r.sub(self.__replacer, text)

if __name__ == '__main__':

    f = ProfanitiesFilter(['bad', 'un\w+'], replacements="-")
    example = "I am doing bad ungood badlike things."

    print f.clean(example)
    # Returns "I am doing --- ------ badlike things."

    f.inside_words = True
    print f.clean(example)
    # Returns "I am doing --- ------ ---like things."

    f.complete = False
    print f.clean(example)
    # Returns "I am doing b-d u----d b-dlike things."

rawDescription: What’s a good Python profanity filter library?


code:
import httplib

def requester(url):
    host = url.split('/')[0]
    #if urls do contain 'http://' -->  host = url.split('/')[2].replace('http://','')
    req = url[url.find(host)+len(host):]
    conn = httplib.HTTPConnection(host)
    conn.request("HEAD","/"+req)
    response = conn.getresponse()
    print response.status, response.reason

    #if you want data...
    #data = response.read()
    #print data

for url in open(urls.txt):
    try:
        requester(url)
    except Error,e:
        print Error, e

rawDescription: Python HTTP Request

description: Python HTTP Request


code:
import time
a = time.time()

print "Starting time is %s" % str(a)

while True:
    # Clear the screen each iteration to "recycle" the lines
    print chr(27) + "[2J"

    program_time = time.time();
    elapsed      = int(round((program_time - a) * 1000)) * 100

    print "Start time is %s" % a
    print "Elapsed time is %s" % elapsed

    # Simulate some work
    time.sleep(1)

rawDescription: While loop, have two if i in statements

description: While loop, have two if i in statements


code:
def compute_paths(source, dest):
    results = graph_tool.topology.shortest_path(g, source, dest, weights=weight)
    filteredge[results[1][0]] = 0
    g.set_edge_filter(filteredge)
    s_results = graph_tool.topology.shortest_path(g, source, dest, weights=weight)
    print "PRIMARY PATH:   %s" % ([g.vertex_index[x] for x in results[0]])
    print "SECONDARY PATH: %s" % ([g.vertex_index[x] for x in s_results[0]])
    filteredge[results[1][0]] = 1

rawDescription: How to find alternative (redundant) shortest paths with graph-tool

description: Find alternative (redundant) shortest paths with graph-tool


code:
import argparse

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', type='open')
    args = parser.parse_args()

    for line in args.infile:
        print line

if __name__ == '__main__':
    main()

rawDescription: Python command line 'file input stream'

description: Python command line 'file input stream'


code:
import requests

videoId = 'ZSzeFFsKEt4'
results = []
npage = 1
session = requests.session()
while True:
    urlstr = 'http://www.sandracires.com/en/client/youtube/comments.php'
    print "Getting page ", npage
    response = session.get(urlstr, params={'v': videoId, 'page': npage})
    content = response.json()
    if len(content['list']) > 1:
        results.append(content)
    else:
        break
    npage += 1

print results

rawDescription: Using python to take advantage of web page functions


code:
import sqlite3

def getTableDump(db_file, table_to_dump):
    conn = sqlite3.connect(':memory:')
    cu = conn.cursor()
    cu.execute("attach database '" + db_file + "' as attached_db")
    cu.execute("select sql from attached_db.sqlite_master "
               "where type='table' and name='" + table_to_dump + "'")
    sql_create_table = cu.fetchone()[0]
    cu.execute(sql_create_table);
    cu.execute("insert into " + table_to_dump +
               " select * from attached_db." + table_to_dump)
    conn.commit()
    cu.execute("detach database attached_db")
    return "\n".join(conn.iterdump())

TABLE_TO_DUMP = 'table_to_dump'
DB_FILE = 'db_file'

print getTableDump(DB_FILE, TABLE_TO_DUMP)

rawDescription: how do i dump a single sqlite3 table in python?

description: Dump a single sqlite3 table in python


rawDescription: How to find what the next word separated by underscore is

description: Find what the next word separated by underscore is


code:
import os
from subprocess import Popen, PIPE

class CwdKeeper(object):
    def __init__(self):
        self._cwd = os.environ.get("PWD")
        if self._cwd is None: # no environment. fall back to calling pwd on shell
           self._cwd = Popen('pwd', stdout=PIPE).communicate()[0].strip()
        self._os_getcwd = os.getcwd
        self._os_chdir = os.chdir

    def chdir(self, path):
        if not self._cwd:
            return self._os_chdir(path)
        p = os.path.normpath(os.path.join(self._cwd, path))
        result = self._os_chdir(p)
        self._cwd = p
        os.environ["PWD"] = p
        return result

    def getcwd(self):
        if not self._cwd:
            return self._os_getcwd()
        return self._cwd

cwd = CwdKeeper()
print cwd.getcwd()
# use only cwd.chdir and cwd.getcwd from now on.
# monkeypatch os if you want:
os.chdir = cwd.chdir
os.getcwd = cwd.getcwd
# now you can use os.chdir and os.getcwd as normal.

rawDescription: How to get/set logical directory path in python

description: Get/set logical directory path in python


code: print u'My String'

rawDescription: Django Model Objects

description: Django Model Objects


code:
import pandas as pd
import io, datetime

df = pd.read_csv(r'E:\project\test\file1.csv')
df1 = pd.read_csv(r'E:\project\test\file2.csv')

#set column date to datetime
df1["date"] = pd.to_datetime(df1["date"], format="%d/%m/%Y %H:%M")
#set column date to index, stack columns to rows(not drop NaN values), reset index
df1 = df1.set_index("date").stack(dropna=False).reset_index()
#set column names
df1.columns = ['date','Loc_Nu', 'values']
#set column type to int for merging
df1['Loc_Nu'] = df1['Loc_Nu'].astype(int)

#set datetime column to column date, delete these columns
df['date'] = df[['Yr', 'Mth', 'Day', 'Hr', 'Min']].apply(lambda s : datetime.datetime(*s),axis = 1)
df = df.drop(['Yr', 'Mth', 'Day', 'Hr', 'Min'], axis=1)
print df
#   Loc_Nu      Lat      Long Rain                date
#0   12456 -34.9211  138.6216  Yes 2005-01-01 09:30:00
#1   12375 -34.9211  138.6216  Yes 2005-01-01 09:45:00
#2   12376 -34.9211  138.6216   No 1998-12-01 17:05:00
print df1
#                 date  Loc_Nu  values
#0 2005-01-01 09:30:00   12375     NaN
#1 2005-01-01 09:30:00   12376     NaN
#2 2005-01-01 09:30:00   12456     0.2
#3 2005-01-01 10:00:00   12375     NaN
#4 2005-01-01 10:00:00   12376     0.0
#5 2005-01-01 10:00:00   12456     NaN
#6 2005-01-01 10:30:00   12375     0.0
#7 2005-01-01 10:30:00   12376     NaN
#8 2005-01-01 10:30:00   12456     0.6

#intersection df and df1 by columns date and Loc_Nu
df2 = pd.merge(df, df1, on=['date', 'Loc_Nu'])
#if you want, you can reorder columns
df2 = df2[['date','Loc_Nu','Lat','Long','Rain','values']]
print df2
#                 date  Loc_Nu      Lat      Long Rain  values
#0 2005-01-01 09:30:00   12456 -34.9211  138.6216  Yes     0.2

#what are dataframes and count them by matches 0, >0, NaN
print df2.loc[df2['values'] == 0 ]
print len(df2.loc[df2['values'] == 0 ].index)
print df2.loc[df2['values'] > 0 ]
print len(df2.loc[df2['values'] > 0 ].index)
print df2.loc[df2['values'].isnull()]
print len(df2.loc[df2['values'].isnull()].index)

#Empty DataFrame
#Columns: [date, Loc_Nu, Lat, Long, Rain, values]
#Index: []
#0
#                 date  Loc_Nu      Lat      Long Rain  values
#0 2005-01-01 09:30:00   12456 -34.9211  138.6216  Yes     0.2
#1
#Empty DataFrame
#Columns: [date, Loc_Nu, Lat, Long, Rain, values]
#Index: []
#0

rawDescription: Match and count two files by time and column


code:
import time, datetime

d = datetime.datetime.now()
print time.mktime(d.timetuple())

rawDescription: Converting datetime to POSIX time

description: Converting datetime to POSIX time


code:
from random import randint
bob = 6
bob1 = randint(0, 100)
bob2 = randint(0, min(100, 100 + bob - bob1))
bob3 = 100 + bob - bob1 - bob2
print bob1
print bob2
print bob3

rawDescription: How can I create three random integers which sum to a specific value? (Python)

description: Create three random integers which sum to a specific value? (Python)


code:
"""
A generator that yields fib numbers
"""
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# Instantiate the generator
f = fibonacci()

# Some vars to hold stuff
counter = 0
the_sum = 0

# Use our generator and loop
for x in f:
    # Bonus points for printing
    print x

    # If it is an even number
    if x % 2 == 0:
        # Add it up
        the_sum += x

        # Increment counter so we don't go too far
        counter += 1

        # Are we there yet?
        if (counter == 2015): break

# You don't want the final fib you want the sum of each
# number in the final fib
the_answer = 0

# Split the fib number into individual numbers
for n in list(str(the_sum)):
    the_answer += int(n) # Add each number together

# Tada
print the_answer

rawDescription: TypeError: Can't convert 'int' object to str implicitly in Fib


code:
import feedparser
import lxml.html as lh
import urllib2

#Import Feed for Parsing
d = feedparser.parse("http://feeds.boston.com/boston/bigpicture/index")

# Print feed name
print d['feed']['title']

# Determine number of posts and set range maximum
posts = len(d['entries'])

# Collect Post URLs
for post in d['entries']:
    link=post['link']
    print('Parsing {0}'.format(link))
    doc=lh.parse(urllib2.urlopen(link))
    imgs=doc.xpath('//img[@class="bpImage"]')
    for img in imgs:
        print(img.attrib['src'])

rawDescription: Python, BeautifulSoup or LXML - Parsing image URL's from HTML using CSS tags


code:
from Phidgets.Devices.Stepper import Stepper

class Parent(object):
    "Parent Class"

    def stepperAttached(self, event):
        print 'Connected to device ', event.device.getSerialNum()

    def eventHandler (self, event):
        print "Event fired!", event.state

class Child(object):
    "Child class"

    def __init__(self, parent):
        self.parent = parent
        self.stepper =  Stepper()
        self.stepper.setOnAttachHandler(self.parent.StepperAttached)
        self.stepper.setOnInputChangedHandler(self.parent.eventHandler)

p = Parent()
c = Child(p)
c2 = Child(p)
# etc..

rawDescription: Python and Phidgets: want to send event/message from object to its parent


code:
import re

html = '...... your html page .... '
textlist = re.findall(r'OpenWindow\.document\.write\(([^\)]*)\)', html)

print "".join(textlist)

rawDescription: Python Regex to match OpenWindow.document.write( [this] )


code:
import os

var = os.popen('xsel').read()
print var

rawDescription: How to get selected text with xsel - Python

description: Get selected text with xsel - Python


code:
import operator
lst = [(0, 2), (1, 2), (0, 4), (2,6), (23, 2), (22, 6), (26, 2), (26, 2), (26, 2)]
lst.sort(key=operator.itemgetter(1))
for i in reversed(xrange(len(lst)-1)):
    start, length = lst[i]
    for j in xrange(i+1, len(lst)):
        lstart, llength = lst[j]
        if start >= lstart and start + length <= lstart + llength:
            del lst[i]
            break
print lst
#[(0, 4), (2, 6), (22, 6)]

rawDescription: Collapse a list of range tuples into the overlapping ranges


code:
from __future__ import division

import math
height = int(raw_input('Height: '))
weight = int(raw_input('Weight: '))
v = math.sqrt(2)*height*weight
mass = int(raw_input('mass: '))
K_E = 1/2*(mass*v**2)
print K_E

rawDescription: how to calculate physics in python?

description: Calculate physics in python


code:
def solve(A):
    count = 0
    accum = 0
    total = 0
    seen = {0: 1}

    for i, element in enumerate(A):
        if element == 'H':
            count += 1
            accum -= seen.get(count, 0)
        else:
            accum += seen.get(count, 0)
            count -= 1

        seen[count] = seen.get(count, 0) + 1
        total += (i + 1 - accum)

    return total

print solve([ 'H', 'T', 'H', 'T', 'T', 'H' ])

print solve([ 'T', 'H', 'H', 'H', 'T' ])

rawDescription: Count substrings with a minority of tails from a string of coin tosses


code:
for i in product(*lol):
  print i

rawDescription: How to permutate/combinate lists of different sizes? python

description: Permutate/combinate lists of different sizes? python


code:
import html2text
html = open("foobar.html").read()
print html2text.html2text(html)

rawDescription: Rendered HTML to plain text using Python


code:
import os, re
path = 'C:/Temp/Folder1/allTexts'
listing = os.listdir(path)
for infile in listing:
    text = open(path + '/' + infile).read()
    match = re.search('
', text)
    if match is None:
        continue
    start = match.start()
    end = re.search('
', text).start()
    print text[start:end]

rawDescription: How to search multiple files for textblocks and write those textblocks to another file

description: Search multiple files for textblocks and write those textblocks to another file


code:
ct = CourseTemplate.objects.all()[0]
print ct.pk
# some original pk

ct.pk = None
ct.save()
print ct.pk
# will be a new auto-incremented

rawDescription: Copy or clone an object instance in Django/Python


rawDescription: Python - Converting Hex to INT/CHAR

description: Python - Converting Hex to INT/CHAR


code:
import Image

theFile = "foo.png"

img = Image.open(theFile)
resized = img.resize((75,75))
r, g, b, alpha = resized.split()

newImage = Image.new(resized.mode, resized.size, "black")
newImage.paste(resized, mask=alpha)
newImage.save("out.png")

print "Done"

rawDescription: Python Image Library - Create and paste image


code:
import os, itertools

files = os.listdir("/path/to/files")
for file1, file2 in itertools.combinations(files, 2):
  print file1, file2

rawDescription: Comparing files in directory to each other with no repeated comparisons


code:
maxDict = {}
for (eachtest, pattern), counter in counts.iteritems():
    _, prev_max = maxDict.get(eachtest, ('', 0))
    if counter > prev_max:
        maxDict[eachtest] = (pattern, counter)

print maxDict
# prints: {'test1': ('alpha', 2), 'test2': ('gamma', 2)}

rawDescription: Python: Returning max value of a dict by its tupled-key


code:
import wx
from wx.lib.scrolledpanel import ScrolledPanel

class TestWindow(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, 'Accelerator Table Test', size=(600, 400))

        self.panel = ScrolledPanel(parent=self, id=-1)
        self.panel.SetupScrolling()

        #Create IDs to be used in initial acclerator table
        self.functionList = [self.func1, self.func2, self.func3, self.func4, self.func5, self.OnAdd, self.OnDel]
        self.functionListstr = ["self.func1", "self.func2", "self.func3", "self.func4", "self.func5", "self.OnAdd", "self.OnDel"]
        self.IDDict = {i: wx.NewId() for i in range(len(self.functionList))}
        self.IDDictrev = {val:key for key, val in self.IDDict.iteritems()}

        self.aTableList = [(wx.ACCEL_ALT, ord('S'), self.IDDict[0]),(wx.ACCEL_CTRL, ord('Q'), self.IDDict[1])]

        #Set up initial accelerator table
        aTable = wx.AcceleratorTable(self.aTableList)
        self.SetAcceleratorTable(aTable)

        #Bind inital accelerator table IDs to functions
        for i in range(len(self.functionList)):
            self.Bind(wx.EVT_MENU, self.functionList[i], id=self.IDDict[i])

        #Set up control widgets on GUI
        self.flexgrid = wx.FlexGridSizer(cols=3, hgap=10, vgap=5)

        cmdkeylbl = wx.StaticText(self.panel, -1, "Command Key")
        self.cmdkey = wx.ComboBox(self.panel, style=wx.CB_READONLY)
        cmdkeylist = ["Alt", "Control/Command", "Shift", "OSX Control", "None"]
        self.cmdkeyconstants = {"Alt":wx.ACCEL_ALT, "Control/Command":wx.ACCEL_CTRL, "Shift":wx.ACCEL_SHIFT, "None":wx.ACCEL_NORMAL}
        self.cmdkeyconstantsrev = {val:key for key, val in self.cmdkeyconstants.iteritems()}
        self.cmdkey.SetItems(cmdkeylist)

        hotkeylbl = wx.StaticText(self.panel, -1, "HotKey (single letter only)")
        self.hotkey = wx.TextCtrl(self.panel, size=(50,-1))

        funclbl = wx.StaticText(self.panel, -1, "Function")
        self.func = wx.ComboBox(self.panel, style=wx.CB_READONLY)
        self.func.SetItems(self.functionListstr)

        self.hbox = wx.BoxSizer(wx.HORIZONTAL)

        addBtn = wx.Button(self.panel, -1, "Add")
        delBtn = wx.Button(self.panel, -1, "Delete")

        self.Bind(wx.EVT_BUTTON, self.OnAdd, addBtn)
        self.Bind(wx.EVT_BUTTON, self.OnDel, delBtn)

        self.vbox = wx.BoxSizer(wx.VERTICAL)

        self.curATable = wx.StaticText(self.panel, -1, self._DisplayATable())

        self.flexgrid.Add(cmdkeylbl)
        self.flexgrid.Add(hotkeylbl)
        self.flexgrid.Add(funclbl)
        self.flexgrid.Add(self.cmdkey)
        self.flexgrid.Add(self.hotkey)
        self.flexgrid.Add(self.func)

        self.hbox.Add((20, 20), 0)
        self.hbox.Add(addBtn)
        self.hbox.Add((0, 0), 0)
        self.hbox.Add(delBtn)
        self.hbox.Add((20, 20), 0)

        self.vbox.Add(self.flexgrid, flag=wx.TOP|wx.BOTTOM|wx.LEFT|wx.RIGHT|wx.EXPAND, border = 5)
        self.vbox.Add(self.hbox, flag=wx.TOP|wx.BOTTOM|wx.LEFT|wx.RIGHT|wx.EXPAND, border = 5)
        self.vbox.Add(self.curATable, flag=wx.TOP|wx.BOTTOM|wx.LEFT|wx.RIGHT|wx.EXPAND, border = 5)

        self.panel.SetSizer(self.vbox)
        self.panel.Layout()

    #Class Functions
    def _DisplayATable(self):
        aTablelbl = ""
        for cmdKey, hotKey, Func in self.aTableList:
            aTablelbl += "{} + {} calls {}\n".format(self.cmdkeyconstantsrev[cmdKey], chr(hotKey), self.functionListstr[self.IDDictrev[Func]])

        return aTablelbl

    def OnAdd(self, event):
        self.aTableList.append((self.cmdkeyconstants[self.cmdkey.GetValue()], ord(self.hotkey.GetValue()[:1].title()), self.IDDict[self.func.GetSelection()]))
        print "Added {} + {} as a shortcut for {}!".format(self.cmdkey.GetValue(), self.hotkey.GetValue()[:1].title(), self.functionListstr[self.func.GetSelection()])

        aTable = wx.AcceleratorTable(self.aTableList)
        self.SetAcceleratorTable(aTable)
        self.curATable.SetLabel(self._DisplayATable())
        self.panel.Layout()

    def OnDel(self, event):
        if (self.cmdkeyconstants[self.cmdkey.GetValue()], ord(self.hotkey.GetValue()[:1].title()), self.IDDict[self.func.GetSelection()]) in self.aTableList:
            self.aTableList.remove((self.cmdkeyconstants[self.cmdkey.GetValue()], ord(self.hotkey.GetValue()[:1].title()), self.IDDict[self.func.GetSelection()]))

            aTable = wx.AcceleratorTable(self.aTableList)
            self.SetAcceleratorTable(aTable)
            self.curATable.SetLabel(self._DisplayATable())
            self.panel.Layout()

        else:
            dlg = wx.MessageDialog(self, "ERROR: That combination is not in the accelerator table!", "Error", style=wx.OK)
            dlg.ShowModal()
            dlg.Destroy()

    def func1(self, event):
        dlg = wx.MessageDialog(self, "Func1", "Func1", style=wx.OK)
        dlg.ShowModal()
        dlg.Destroy()

    def func2(self, event):
        dlg = wx.MessageDialog(self, "Func2", "Func2", style=wx.OK)
        dlg.ShowModal()
        dlg.Destroy()

    def func3(self, event):
        dlg = wx.MessageDialog(self, "Func3", "Func3", style=wx.OK)
        dlg.ShowModal()
        dlg.Destroy()

    def func4(self, event):
        dlg = wx.MessageDialog(self, "Func4", "Func4", style=wx.OK)
        dlg.ShowModal()
        dlg.Destroy()

    def func5(self, event):
        dlg = wx.MessageDialog(self, "Func5", "Func5", style=wx.OK)
        dlg.ShowModal()
        dlg.Destroy()

app = wx.App(False)
frame = TestWindow()
frame.Show()
app.MainLoop()

rawDescription: wxPython: Getting a EVT_KEY_DOWN event for CMD+[other key] on OSX

description: WxPython: Getting a EVT_KEY_DOWN event for CMD+[other key] on OSX


code:
# untested
from itertools import count
rows = len(csvList)
pctn = rows // 100
perc = count()
for rowno, row in enumerate(csvList):
    if rowno % pctn == 0:
        print '{}%'.format(next(perc))

rawDescription: SQL Insert progress bar

description: SQL Insert progress bar


rawDescription: Python: Find FWHM of curve

description: Python: Find FWHM of curve


code:
import math
origX = 95485
origY = 729380

nextX = 95241
nextY = 729215

distance = 2000.0
bearing = 45

origVec = origX, origY
nextVec = nextX, nextY

#Euclidean distance between vectors (L2 norm)
dist = math.sqrt((nextVec[0] - origVec[0])**2 + (nextVec[1] - origVec[1])**2)

#Get a normalized difference vector
diffVec = (nextVec[0] - origVec[0])/dist, (nextVec[1] - origVec[1])/dist

#rotate our vector by bearing to get a vector from orig towards new point
#also, multiply by distance to get new value
#invert bearing, because +45 in math is counter-clockwise (left), not starboard
angle = math.radians(-bearing)

newVec = origVec[0]+(diffVec[0]*math.cos(angle) - diffVec[1]*math.sin(angle))*distance, \
         origVec[1]+(diffVec[0]*math.sin(angle) + diffVec[1]*math.cos(angle))*distance

print newVec

rawDescription: Move xy coordinates based on a given distance and bearing from transect


code:
#open the file , can be /var/log/messages, /var/log/maillog etc as defined in your system
f=open("mysyslogfile")
count=0
#go through the file
for line in f:
   if "<unique pattern for checking root account login>" in line:
       count+=1
#close the file
f.close()
print "total count: " ,count

rawDescription: Python - retrieving info from a syslog file


code:
import os
this_dir, this_filename = os.path.split(__file__)
DATA_PATH = os.path.join(this_dir, "data", "data.txt")
print open(DATA_PATH).read()

rawDescription: Python Access Data in Package Subdirectory


code:
from functools import partial

def setTable(self):
    for i in range( 0, self.myTable.rowCount() ):
        item = "row " + str(i)
        self.myTable.setItem(i, 0, QtGui.QTableWidgetItem(item))

        box = cBox()
        nameList = ("sss","aaa","qqq")
        box.addItems(nameList)

        self.myTable.setCellWidget(i,1,box)
        # here the 'i' will be the parameter rowIndex in the tmp function
        box.currentIndexChanged.connect(partial(self.tmp, i))

def tmp(self, rowIndex, comboBoxIndex):
    # this print statements are just for explanation
    print "current index of the combobox: " + str(comboBoxIndex)
    print "row index of where the combobox resides: " + str(rowIndex)
    item = "item " + str(comboBoxIndex)
    self.myTable.setItem(rowIndex, 2, QtGui.QTableWidgetItem(item))

rawDescription: PySide QComboBox in QTableWidget (Python)


code:
result = ''
for charc in text:
    if charc != " " :
        charc = ord(charc)
        charc = (charc - 97) + key
        charc = (charc % 26)
        charc = charc + 97
        charc = chr(charc)
    result += charc
print result

rawDescription: How do I print all my results on one line with the spaces

description: Print all my results on one line with the spaces


code:
from bs4 import BeautifulSoup
import urllib2

domain = 'http://www.renderx.com'
url = 'http://www.renderx.com/demos/examples.html'

page = urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
app = soup.find_all('a', text = "Applications")

for aa in app:
    print domain + aa['href']

rawDescription: Python, Limiting search at a specific hyperlink on webpage


rawDescription: Python Unicode string stored as '\u84b8\u6c7d\u5730' in file, how to convert it back to Unicode?


code:
class Order(object):
    def __init__(self, number, amount):
        self.number = number
        self.amount = amount
        print self

    def __str__(self):
        return "Order #%s: amount = %s" % (self.number, self.amount)

    @property
    def order_number(self):
        return self.number

    def cancel(self):
        self.amount = 0
        print "Order is cancelled."
        print self

class PizzaHut(object):

    def __init__(self, price):
        self.price = price

    def order(self):
        return Order(42, self.price)

pizza = PizzaHut(4.99)
order = pizza.order()
print order.order_number
order.cancel()

rawDescription: Returning objects from methods in Python


code:
table = soup.find('table', class_='views-table cols-6')
for row in table.find_all('tr'):
    row_text = list()
    for item in row.find_all('td'):
        text = item.text.strip()
        row_text.append(text.encode('utf8'))
    print row_text

rawDescription: How to use BeautifulSoup to parse a table?

description: Use BeautifulSoup to parse a table


code:
import pygame

pygame.init()
screen = pygame.display.set_mode((400,400))

pygame.event.set_allowed(None)
pygame.event.set_allowed([pygame.QUIT, pygame.KEYDOWN])

while True:
    e = pygame.event.wait()
    print e

rawDescription: Pygame loop only upon keypress

description: Pygame loop only upon keypress


code:
import time
import IPython

try:
    from msvcrt import kbhit
except ImportError:
    import termios, fcntl, sys, os
    def kbfunc():
        fd = sys.stdin.fileno()
        oldterm = termios.tcgetattr(fd)
        newattr = termios.tcgetattr(fd)
        newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSANOW, newattr)
        oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
        try:
            while True:
                try:
                    c = sys.stdin.read(1)
                    return c.decode()
                except IOError:
                    return False
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
            fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
else:
    def kbfunc():
        #this is boolean for whether the keyboard has bene hit
        x = msvcrt.kbhit()
        if x:
            #getch acquires the character encoded in binary ASCII
            ret = msvcrt.getch()
            return ret.decode()
        else:
            return False

def wait_for_interrupt(waitstr=None, exitstr=None, countdown=True, delay=3):
    if waitstr is not None: print waitstr
    for i in range(delay*10):
        if   countdown and i%10 ==0    : print '%d'%(i/10 + 1),
        elif countdown and (i+1)%10 ==0: print '.'
        elif countdown                 : print '.',

        key = kbfunc()
        if key: return key
        time.sleep(0.1)
    if exitstr is not None: print exitstr
    return False

if __name__ == "__main__":
    #wait_for_interrupt example test
    if wait_for_interrupt('wait_for_interrupt() Enter something in the next 3 seconds', '... Sorry too late'):
        IPython.embed()

    #begin the counter
    number = 1

    #interrupt a loop
    while True:

        #acquire the keyboard hit if exists
        x = kbfunc()

        #if we got a keyboard hit
        if x != False and x == 'i':
            #we got the key!
            IPython.embed()
            #break loop
            break
        else:
            #prints the number
            print (number)
            #increment, there's no ++ in python
            number += 1
            #wait half a second
            time.sleep(0.5)

rawDescription: Timeout when invoking IPython embed()

description: Timeout when invoking IPython embed()


rawDescription: Python scientific notation using D instead of E


code:
car_classes = {
'car'     : Car,
'truck'   : Truck,
'compact' : Compact
}

if __name__ == '__main__':
    option = sys.argv[1]
    mCar = car_classes[option]()
    print 'I am a', mCar.__class__.__name__

rawDescription: Python: bind child class at run time

description: Python: bind child class at run time


code:
import urllib2
from threading import Thread

BASE_URL = 'http://farmsubsidy.org/DE/browse?page='
NUM_RANGE = range(0000, 3603)
THREADS = 2

def main():
    for nums in split_seq(NUM_RANGE, THREADS):
        t = Spider(BASE_URL, nums)
        t.start()

def split_seq(seq, num_pieces):
    start = 0
    for i in xrange(num_pieces):
        stop = start + len(seq[i::num_pieces])
        yield seq[start:stop]
        start = stop

class Spider(Thread):
    def __init__(self, base_url, nums):
        Thread.__init__(self)
        self.base_url = base_url
        self.nums = nums
    def run(self):
        for num in self.nums:
            url = '%s%s' % (self.base_url, num)
            data = urllib2.urlopen(url).read()
            print data

if __name__ == '__main__':
    main()

rawDescription: get many pages with pycurl?

description: Get many pages with pycurl


code:
import xlrd
book = xlrd.open_workbook("sample.xls", formatting_info=True)
sheets = book.sheet_names()
print "sheets are:", sheets
for index, sh in enumerate(sheets):
    sheet = book.sheet_by_index(index)
    print "Sheet:", sheet.name
    rows, cols = sheet.nrows, sheet.ncols
    print "Number of rows: %s   Number of cols: %s" % (rows, cols)
    for row in range(rows):
        for col in range(cols):
            print "row, col is:", row+1, col+1,
            thecell = sheet.cell(row, col)
            # could get 'dump', 'value', 'xf_index'
            print thecell.value,
            xfx = sheet.cell_xf_index(row, col)
            xf = book.xf_list[xfx]
            bgx = xf.background.pattern_colour_index
            print bgx

rawDescription: Identifying Excel Sheet cell color code using XLRD package


code:
sortedList = sorted([u'test3',u'test2',u'test5'])
print sortedList

rawDescription: How to sort the list in Python?

description: Sort the list in Python


code:
import csv
from cStringIO import StringIO

# parse the data you're about to filter with
with open('filters.csv', 'rb') as f:
    filters = {(row[0], row[1]) for row in csv.reader(f, delimiter=',')}

out_f = StringIO()  # use e.g. `with open('out.csv', 'wb') as out_f` for real file output
out = csv.writer(out_f, delimiter=',')

# go thru your rows and see if the pair (row[1], row[8]) is
# found in the previously parsed set of filters; if yes, skip the row
with open('data.csv', 'rb') as f:
    for row in csv.reader(f, delimiter=','):
        if (row[1], row[8]) not in filters:
            out.writerow(row)

# for debugging only
print out_f.getvalue()  # prints the resulting filtered CSV data

rawDescription: How to remove rows from csv based on matching data

description: Remove rows from csv based on matching data


code:
import datetime, xlrd
book = xlrd.open_workbook("myfile.xls")
sh = book.sheet_by_index(0)
a1 = sh.cell_value(rowx=0, colx=0)
a1_as_datetime = datetime.datetime(*xlrd.xldate_as_tuple(a1, book.datemode))
print 'datetime: %s' % a1_as_datetime

rawDescription: Reading date as a string not float from excel using python xlrd


code:
import numpy
p = numpy.poly1d([2, 4, 6])
print p
i = p.integ()
i
integrand = i(1) - i(0) # Use call notation to evaluate a poly1d
integrand

rawDescription: Calculating the area underneath a mathematical function


code:
import urllib2,re,os
#import requests

folder = "FailImages"

if not os.path.exists(folder): # Directory that I want to save the image to
    os.mkdir(folder) # If no directory create it

url = "http://www.google.ca"
source = urllib2.urlopen(url).read()

imgs = re.findall(r'(https?:/)?(/?[\w_\-&%?./]*?)\.(jpg|png|gif)',source, re.M) # regex finds files with .jpg extension

for img in imgs:
    remote = url + img[1] + "." + img[2];
    filename = folder + "/" + img[1].split('/')[-1] + "." + img[2]
    print "Copying from " + remote + " to " + filename
    if not os.path.exists(filename):
        f = open(filename, 'wb')
        f.write(urllib2.urlopen(remote).read())
        #f.write(requests.get(remote).content)
        f.close()

rawDescription: Download all the image files found using regex on a website to a specified directory in my computer in python


code:
from numpy import array
a = array((1,0,0,1,1,0,0))
b = 1-a
print a ; print b

rawDescription: Flipping zeroes and ones in one-dimensional NumPy array


code:
import tables
import numpy

fileName = 'carray1.h5'
shape = (200, 300)
atom = tables.UInt8Atom()
filters = tables.Filters(complevel=5, complib='zlib')

h5f = tables.openFile(fileName, 'w')
ca = h5f.createCArray(h5f.root, 'carray', atom, shape, filters=filters)

coord_slice = [slice(10,60,None),slice(20,70,None)]

# attempt to do multi-dimensional indexing with coord_slice as a list
try:
    ca[coord_slice] = numpy.ones((50, 50))
except TypeError:
    print 'TypeError was thrown with list'

# convert coord_slice to a tuple and try again.  This should work.
coord_slice = tuple(coord_slice)
try:
    ca[coord_slice] = numpy.ones((50, 50))
except TypeError:
    print 'TypeError was thrown with tuple'

print ca[coord_slice]
h5f.close()

rawDescription: How to use `slice` objects to read a pytables.CArray?

description: Use `slice` objects to read a pytables.CArray


code:
from scrapy.spider import BaseSpider
from scrapy.selector import Selector
from scrapy.exceptions import CloseSpider
from scrapy.http import Request
from tcgplayer1.items import Tcgplayer1Item

URL = "http://store.tcgplayer.com/magic/journey-into-nyx?pageNumber=%d"

class MySpider(BaseSpider):
    name = "tcg"
    allowed_domains = ["tcgplayer.com"]
    start_urls = [URL % 1]

    def __init__(self):
        self.page_number = 1

    def parse(self, response):
        print self.page_number
        print "----------"

        sel = Selector(response)
        titles = sel.xpath("//div[@class='magicCard']")
        if not titles:
            raise CloseSpider('No more pages')

        for title in titles:
            item = Tcgplayer1Item()
            item["cardname"] = title.xpath(".//li[@class='cardName']/a/text()").extract()[0]

            vendor = title.xpath(".//tr[@class='vendor ']")
            item["price"] = vendor.xpath("normalize-space(.//td[@class='price']/text())").extract()
            item["quantity"] = vendor.xpath("normalize-space(.//td[@class='quantity']/text())").extract()
            item["shipping"] = vendor.xpath("normalize-space(.//span[@class='shippingAmount']/text())").extract()
            item["condition"] = vendor.xpath("normalize-space(.//td[@class='condition']/a/text())").extract()
            item["vendors"] = vendor.xpath("normalize-space(.//td[@class='seller']/a/text())").extract()
            yield item

        self.page_number += 1
        yield Request(URL % self.page_number)

rawDescription: scraping multiple pages with scrapy

description: Scraping multiple pages with scrapy


code:
print 'The Fibonacci series is : ',
for i in xrange(1,10):
    #Calculate the next number 'n' to print
    print n,

rawDescription: Fibonacci series printing horizontally

description: Fibonacci series printing horizontally


code:
textfile = open('a.txt')
replace_dict_list = []

replace_symbol =  raw_input(" Which symbol would you like to replace ")
replace_letter = raw_input(" Which letter would you like to replace it with ")

dict = {replace_symbol:replace_letter}

already_exists = False
for item in replace_dict_list:
    if replace_symbol in item:
        already_exists = True
    else:
        replace_dict_list.append(dict)

if not already_exists:
    print "running"
    words = words.replace(replace_symbol, replace_letter)

rawDescription: How to see whether a symbol has been matched or not?

description: See whether a symbol has been matched or not


code:
class Foo(object):
    def create_new(self):
        return self.__class__()

    def create_new2(self):
        return Foo()

class Bar(Foo):
    pass

b = Bar()
c = b.create_new()
print type(c)  # We got an instance of Bar
d = b.create_new2()
print type(d)  # we got an instance of Foo

rawDescription: Class() vs self.__class__() when creating object?


code:
import sys
import json
import string

def test():
    req = {
        "superObject": {
            "object": {
                "property1": 0,
                "property2": "",
                "property3": False
            }
        },
        "superProperty1": "abcd",
        "superProperty2": 4321
      }

    with open("./log_test.txt", 'r') as log:
        log_string = ''
        for line in log:
            log_string = log_string + line.replace('\n', '').replace(' ', '')
        req_string = str(req).replace('\n', '').replace(' ', '').replace("'", '"')
        log.close()
        if req_string in log_string:
            print str(req) + " It's there!!!"
        else:
            print "It's NOT there!!!"
            raise Exception("String '" + str(req) + "' does not exist")

if __name__ == "__main__":
    test()

rawDescription: Find full JSON body in file

description: Find full JSON body in file


code:
import re
inputs = [r'123,456,789.4533',r'123456789.4533',r'123,456,789,4533',r'123.456.789,4533']
for input in inputs:
    decimal = re.search(r'(?<=[.,])\d+$',input).group()
    integer = re.search(r'.*(?=[.,]\d+$)',input).group()
    checkdigit = lambda x : x.isdigit()
    integer = ''.join([character for character in integer if checkdigit(character)])
    print integer.rjust(17,'0') + decimal.ljust(9,'0')

rawDescription: How do I get Python to intelligently transform dynamic input into a fixed width output?

description: Get Python to intelligently transform dynamic input into a fixed width output


code:
def opt_fun(x1, x2, *positional_parameters, **keyword_parameters):
    if ('optional' in keyword_parameters):
        print 'optional parameter found, it is ', keyword_parameters['optional']
    else:
        print 'no optional parameter, sorry'

opt_fun(1, 2)
opt_fun(1,2, optional="yes")
opt_fun(1,2, another="yes")

rawDescription: Python optional parameter

description: Python optional parameter


code:
import pandas as pd

ser = pd.Series([1,1,1], index=pd.date_range('1/1/2000', periods=3))
print ser

rm1 = pd.rolling_window(ser, window=[2,2,2], mean=False)
rm2 = pd.rolling_window(ser, window=[2,2,2]) #, mean=True

print rm1
#
#2000-01-01   NaN
#2000-01-02   NaN
#2000-01-03     6
#Freq: D, dtype: float64
print rm2
#
#2000-01-01   NaN
#2000-01-02   NaN
#2000-01-03     1
#Freq: D, dtype: float64

rawDescription: How do I calculate a rolling mean with custom weights in pandas?

description: Calculate a rolling mean with custom weights in pandas


code:
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

a = [1,2,3]
b = [4,2,9]

line = ax.plot(a,b)

def onclick(event):
    print "clicked"
    a = [7,8,9]
    b = [1,9,20]
    fig2 = plt.figure()
    ax_single = fig2.add_subplot(111)
    line2 = ax_single.plot(a,b)
    fig2.show()

cid = fig.canvas.mpl_connect('button_press_event',onclick)
plt.show()

rawDescription: Python/Matplotlib 1.0.1 does not open new figure when clicked


code:
import csv
# Create Dictionary structure of csv file 2
with open("dict.csv", "rb") as fp:
    dic_file = csv.reader(fp,)
    dict1 = {}
    for d in dic_file:
        dict1[d[1]] = d[0]

print dict1
found_ = None #not necessary

with open("match_out.csv", "wb") as fw1:
    with open("file.csv", "r") as fr1:
        with open("nomatch_out.csv", "wb") as fw2:
            output = csv.writer(fw1, delimiter=",")
            writer1 = csv.writer(fw2,delimiter=",")
            read = csv.reader(fr1,)
            for row in read:
                found_ = False
                for d in dict1:
                    if d == row[2]:
                        found_ = True
                if found_:
                    output.writerow(row) ## write only the matching ones
                else:
                    writer1.writerow(row) ## if no key/match write to a separate file

rawDescription: python - for nested loop with if

description: Python - for nested loop with if


code:
from collections import defaultdict

l = [('AT', 'TG'), ('GT', 'TG'), ('TG', 'GG'), ('GG', 'GC'), ('GC', 'CG'), ('CG', 'GT'), ('GC', 'CA'), ('TG', 'GC'), ('CA', 'AA'), ('AA', 'AT')]

lookup = defaultdict(set)
for k, v in l:
    lookup[k].add(v)

def sort(l, s):
    k = l[-1][1]
    pairs = set([(k, v) for v in lookup[k]]) - s
    if len(pairs) == 0:
        return [l]
    results = set()
    for k, v in pairs:
        results.update(sort(l + ((k, v), ), s | set([(k, v)])))
    return results

results = sort((('AT', 'TG'), ), set([('AT', 'TG')]))

for result in  results:
    print list(result)

rawDescription: Sort a list of lists

description: Sort a list of lists


code:
read_buff = ctypes.c_uint()
kernel32.ReadProcessMemory(hproc, lpbaseaddr, ctypes.byref(read_buff),
                           ctypes.sizeof(read_buff), ctypes.byref(bytread))
print read_buff.value

description: Python ctypes.create_string_buffer Problem