code:
import os

def get_file_types(directory):
    file_ext = set()
    for root, directories, files in os.walk(directory):
        for filename in files:
            filepath = os.path.join(root, filename)
            fileName, fileExtension = os.path.splitext(filepath)

    return sorted(file_ext)  # Self-explanatory.

file_types = get_file_types("d:\\Development\\")
for ty in file_types:
    print ty

rawDescription: how to get file's type under a directory in Python

description: Get file's type under a directory in Python


code:
import os

pids = [pid for pid in os.listdir('/proc') if pid.isdigit()]

for pid in pids:
    try:
        cmd = open(os.path.join('/proc', pid, 'cmdline'), 'rb').read()
        if cmd.find('smtpd') != -1:
            print "PID: %s; Command: %s" % (pid, cmd)
    # process has already terminated
    except IOError:
        continue

rawDescription: How to find a unix process in Python

description: Find a unix process in Python


code:
if args.words or not arg.lines:
    print "Words in a file: {}" .format(print_words(args.filename))

if args.lines or not arg.words:
    print "Lines in a file: {}" .format(print_lines(args.filename))

rawDescription: Argument parser for a word count and/or line count program


code:
s = 'abc\bde'
print s
len(s)

rawDescription: Python counting zero-length control characters in string formatting width field?


code:
for x in ('asdf', 5, None):
    print x

rawDescription: Does tuple sort itself when looped through


code:
class CustomApp(wx.App):
    def MainLoop(self):
        global HANDLER
        global WM
        global NOTIFIER
        global WDD
        global UPDATE_UI
        global PING_TIMER

        # Create an event loop and make it active.  If you are
        # only going to temporarily have a nested event loop then
        # you should get a reference to the old one and set it as
        # the active event loop when you are done with this one...
        evtloop = wx.EventLoop()
        old = wx.EventLoop.GetActive()
        wx.EventLoop.SetActive(evtloop)

        # This outer loop determines when to exit the application,
        # for this example we let the main frame reset this flag
        # when it closes.
        while self.keepGoing:
            # At this point in the outer loop you could do
            # whatever you implemented your own MainLoop for.  It
            # should be quick and non-blocking, otherwise your GUI
            # will freeze.

            # call_your_code_here()
            if not HANDLER:
                HANDLER = EventHandler()

            if not WM:
                WM = pyinotify.WatchManager() # Watch Manager

            if not NOTIFIER:
                NOTIFIER = pyinotify.ThreadedNotifier(WM, HANDLER)
                NOTIFIER.start()
                print 'notifier started'

            if not WDD:
                WDD = WM.add_watch(WATCH_PATH, WM_MASK, rec=True,quiet=False)

            # This inner loop will process any GUI events
            # until there are no more waiting.
            while evtloop.Pending():
                evtloop.Dispatch()

            # Send idle events to idle handlers.  You may want to
            # throttle this back a bit somehow so there is not too
            # much CPU time spent in the idle handlers.  For this
            # example, I'll just snooze a little...
            time.sleep(0.10)
            self.ProcessIdle()

        wx.EventLoop.SetActive(old)

    def OnInit(self):
        global UPDATE_UI
        if not UPDATE_UI:
            UPDATE_UI = Updater()
            UPDATE_UI.Show()
            self.SetTopWindow(UPDATE_UI)

        self.keepGoing = True
        return True

"--------------------------------------------------------------------------------------"
Watcher()
app = CustomApp(False)

rawDescription: Suspected thread issue with pyinotify

description: Suspected thread issue with pyinotify


rawDescription: Shuffle the records of a list of text files in one single file


code:
from bs4 import BeautifulSoup
import requests

url = "http://backpack.tf/stats/Unique/AWPer%20Hand/Tradable/Craftable"
r = requests.get(url)

soup = BeautifulSoup(r.text)

curPrice = soup.find('h2').findNext('a').text

print 'The current price is: {0}'.format(curPrice)

print 'These are the prices they are being sold at: '
print '\n'.join([item.text for item in soup.find_all('span', attrs={'class': 'label label-black', 'data-tip': 'bottom'})])

rawDescription: how to extract a certain number from a website in python

description: Extract a certain number from a website in python


code:
#!/usr/bin/python
email = "" # Initialize the email
count = 0  # and counter
import fileinput

for line in fileinput.input("word.txt"): # Interator: process a line at a time
  myArr = line.split(",")
  if (email != myArr[0]): # New email; print and reset count, email
    for n in range(0,count):
      print email + "," + str(n+1) + "," + str(count)
    email = myArr[0]
    count = 1
  else: # Same email, increment count
    count = count + 1

# Print the final email
for n in range(0,count):
  print email + "," + str(n+1) + "," + str(count)

rawDescription: Want to print maxm entry of every email against it in another column


code:
line = '"RUn.exe O" "" "   2ne, " two! . " "'
import re
regex = re.compile(r'"[^"]*"|[^\s]+')
matches = [el.strip('"') for el in regex.findall(line)]

print '\n'.join(matches)

rawDescription: Filling a list with regular expression results python


code:
s = "cats \\ dogs"
print s
print s.replace("\\", "\\\\")

rawDescription: replace all "\" with "\\" python

description: Replace all "\" with "\\" python


code:
import win32com
from win32com.client import Dispatch
import getpass

def number_of_steps(name):
    qcServer = "***"
    qcUser = "***"
    qcPassword = getpass.getpass('Password: ')
    qcDomain = "***"
    qcProject = "***"
    td = win32com.client.Dispatch("TDApiOle80.TDConnection.1")

    #Starting to connect
    td.InitConnectionEx(qcServer)
    td.Login(qcUser, qcPassword)
    td.Connect(qcDomain, qcProject)
    if td.Connected is True:
        print "Connected to " + qcProject

    else:
        print "Connection failed"

    mg = td.TreeManager  # Tree manager
    folder = mg.NodeByPath("Subject\Regression")
    testList = folder.FindTests(name)  # Make a list of tests matching name (partial match is accepted)
    if testList is not None:
        if len(testList) > 1:
            print "There are multiple tests matching this name, please check input parameter\nTests matching"
            for test in testList:
                print test.name
                td.Disconnect
                td.Logout
                return False
        if len(testList) == 1:
            print "In test %s there is %d steps" % (testList[0].Name, testList[0].DesStepsNum)
    else:
        print "There are no test with this test name in Quality Center"
        td.Disconnect
        td.Logout
        return False
    td.Disconnect
    td.Logout
    print "Disconnected from " + qcProject
    return testList[0].DesStepsNum  # Return number of steps for given test

rawDescription: Reading specific test steps from Quality Center with python


code:
from multiprocessing import Process, Event
from time import sleep

class Test(Process):
    def __init__(self):
        Process.__init__(self)
        self.stop = Event()

    def run(self):
        while not self.stop.is_set():
            print "running"
            sleep(1.0)

    def end(self):
        print "stop message received"
        self.stop.set()

if __name__ == "__main__":
    test = Test()
    test.start()
    sleep(1.0)
    test.end()
    test.join()

rawDescription: python multiprocessing member variable not set

description: Python multiprocessing member variable not set


code:
import time
import sys
for i in range(10):
    print "\rworking on:", i,
    sys.stdout.flush()
    time.sleep(1)

rawDescription: How to update a number without changing lines or placement of output

description: Update a number without changing lines or placement of output


code:
def process_backspaces(input, token='[BACKSPACE]'):
    """Delete character before an occurence of "token" in a string."""
    output = ''
    for item in (input+' ').split(token):
        output += item
        output = output[:-1]
    return output

def process_shifts(input, token='[SHIFT]'):
    """Replace characters after an occurence of "token" with their uppecase
    equivalent. (Doesn't turn "1" into "!" or "2" into "@", however!)."""
    output = ''
    for item in (' '+input).split(token):
        output += item[0].upper() + item[1:]
    return output

test_string = '[SHIFT]this isrd[BACKSPACE][BACKSPACE] an example file[SHIFT]1'
print process_backspaces(process_shifts(test_string))

rawDescription: Parsing strings in python

description: Parsing strings in python


rawDescription: Faster way to sum a list of numbers than with a for-loop?


code:
string = '123456789'
splitted = []

prev = 0
while True:
    n = random.randint(1,3)
    splitted.append(string[prev:prev+n])
    prev = prev + n
    if prev >= len(string)-1:
        break
print splitted

rawDescription: Split string by n when n is random

description: Split string by n when n is random


code:
import win32gui

def callback(hwnd, extra):
    rect = win32gui.GetWindowRect(hwnd)
    x = rect[0]
    y = rect[1]
    w = rect[2] - x
    h = rect[3] - y
    print "Window %s:" % win32gui.GetWindowText(hwnd)
    print "\tLocation: (%d, %d)" % (x, y)
    print "\t    Size: (%d, %d)" % (w, h)

def main():
    win32gui.EnumWindows(callback, None)

if __name__ == '__main__':
    main()

rawDescription: Get window position & size with python

description: Get window position & size with python


code:
values = 100,101,102,103,104,105

start = 0
stop = len(values)-1

while stop > start:
    for i in range(start, stop):
        print i, "compare", values[i], "with", values[i+1]
    print "moved a large value to index", stop
    print

    stop = stop - 1
    if stop == start:
        break

    for i in range(stop, start, -1):
        print i, "compare", values[i], "with", values[i-1]
    print "moved a small value to index", start
    print

    start = start + 1

rawDescription: Python 3: Optimised Bubble Sort

description: Python 3: Optimised Bubble Sort


code:
import requests
r = requests.post('http://www.boerse-frankfurt.de/en/parts/boxes/history/_tickdata_full.m', data={'component_id':'PREKOP97077bf9dec39f14320bf9d40b636c7c589', 'page':"3", 'page_size':'50', 'boerse_id':'6', 'titel':'Tick-Data', 'lang':'en', 'text':'LOcbaec84ecad1b94ad2fd257897c87361', 'items_per_page':'50', 'template':'0', 'pages_total':'50', 'use_external_secu':'1', 'item_count':'2473', 'include_url':'/parts/boxes/history/_tickdata_full.m', 'ag':'291', 'secu':'291', })
print r.text #here is your data of interest, it still needs to be parsed

rawDescription: Scraping a webpage with python to get onclick values


code:
s={"username":"username",
   "email":"a@b.com",
   "email_error":"email_error",
   "password_error_one":"password_error_1"}

def write_form(username="", email="", username_error="", email_error="",
        password_error_one="", password_error_two = ""):
    print username, email, email_error, password_error_one, password_error_two

write_form(**s)

rawDescription: Can i pass a variable which contains all parameters for a function to a function in python?If yes, then how?

description: Pass a variable which contains all parameters for a function to a function in python?If yes, then how


code:
import fileinput

with open('file2.txt') as fin:
    exclude = set(line.rstrip() for line in fin)

for line in fileinput.input('file1.txt', inplace=True):
    if line.rstrip() not in exclude:
        print line,

rawDescription: How to delete same words from different text file using python?

description: Delete same words from different text file using python


code:
sysLst = str(raw_input('Enter pipe separated list of items [PRIMARY|PRIMARY-HA1|SECONDARY|SECONDARY-HA1|SCALE|ALL]: ')).upper().strip()
if "ALL" in sysLst:
    nsysLst1 = "PRIMARY|PRIMARY-HA1|SECONDARY|SECONDARY-HA1|^SCALE$"
    nsysLst = nsysLst1.replace("^SCALE$", "PRIMARY-SCALE1|PRIMARY-SCALE2|AUXVM-SCALE1|AUXVM-SCALE2")
    output="|".join(["^" + sysList_t + "$" for sysList_t in nsysLst.split('|')])
else:
    nsysLst1="|".join(["^" + sysList_t + "$" for sysList_t in sysLst.split('|')])
    output = nsysLst1.replace("^SCALE$", "PRIMARY-SCALE1|PRIMARY-SCALE2|AUXVM-SCALE1|AUXVM-SCALE2")
print output

rawDescription: Append a variable into a variable

description: Append a variable into a variable


code:
#! /usr/local/bin/python

SMTPserver = 'smtp.att.yahoo.com'
sender =     'me@my_email_domain.net'
destination = ['recipient@her_email_domain.com']

USERNAME = "USER_NAME_FOR_INTERNET_SERVICE_PROVIDER"
PASSWORD = "PASSWORD_INTERNET_SERVICE_PROVIDER"

# typical values for text_subtype are plain, html, xml
text_subtype = 'plain'

content="""\
Test message
"""

subject="Sent from Python"

import sys
import os
import re

from smtplib import SMTP_SSL as SMTP       # this invokes the secure SMTP protocol (port 465, uses SSL)
# from smtplib import SMTP                  # use this for standard SMTP protocol   (port 25, no encryption)

# old version
# from email.MIMEText import MIMEText
from email.mime.text import MIMEText

try:
    msg = MIMEText(content, text_subtype)
    msg['Subject']=       subject
    msg['From']   = sender # some SMTP servers will do this automatically, not all

    conn = SMTP(SMTPserver)
    conn.set_debuglevel(False)
    conn.login(USERNAME, PASSWORD)
    try:
        conn.sendmail(sender, destination, msg.as_string())
    finally:
        conn.quit()

except Exception, exc:
    sys.exit( "mail failed; %s" % str(exc) ) # give a error message

rawDescription: Sending mail from Python using SMTP

description: Sending mail from Python using SMTP


code:
with open("filename_here") as f:
    content = f.readlines()
print content

rawDescription: read the http links from a file and append it to a list

description: Read the http links from a file and append it to a list


code:
scores = [1,2,10,3,4,5,10,1]

ret = [0 for x in (scores)]

for i in xrange(len(scores)):
        ret[i] = sum(scores[i:i+3]) if scores[i] == 10 else scores[i]

print "Final score", sum(ret)

rawDescription: Adding numbers in a list but only after a certain number


code:
f = os.popen (strpath, 'r')
for line in f:
    print line
f.close()

rawDescription: save python output to log

description: Save python output to log


code:
#!/usr/bin/env python
# [SNIPPET_NAME: gtk3 opengl example]
# [SNIPPET_CATEGORIES: opengl]
# [SNIPPET_TAGS: opengl, gtk3]
# [SNIPPET_DESCRIPTION: using gtk3 library lets draw using opengl]
# [SNIPPET_AUTHOR: Oliver Marks ]
# [SNIPPET_LICENSE: GPL]

import sys
from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL import GLX
from OpenGL.raw._GLX import struct__XDisplay
from OpenGL import GL
from ctypes import *

import Xlib
from Xlib.display import Display
from gi.repository import Gtk, GdkX11, Gdk

class gtkgl:
    """ these method do not seem to exist in python x11 library lets exploit the c methods """
    xlib = cdll.LoadLibrary('libX11.so')
    xlib.XOpenDisplay.argtypes = [c_char_p]
    xlib.XOpenDisplay.restype = POINTER(struct__XDisplay)
    xdisplay = xlib.XOpenDisplay("")
    display = Xlib.display.Display()
    attrs = []

    xwindow_id = None
    width = height = 200

    def __init__(self):
        """ lets setup are opengl settings and create the context for our window """
        self.add_attribute(GLX.GLX_RGBA, True)
        self.add_attribute(GLX.GLX_RED_SIZE, 1)
        self.add_attribute(GLX.GLX_GREEN_SIZE, 1)
        self.add_attribute(GLX.GLX_BLUE_SIZE, 1)
        self.add_attribute(GLX.GLX_DOUBLEBUFFER, 0)

        xvinfo = GLX.glXChooseVisual(self.xdisplay, self.display.get_default_screen(), self.get_attributes())
        configs = GLX.glXChooseFBConfig(self.xdisplay, 0, None, byref(c_int()))
        self.context = GLX.glXCreateContext(self.xdisplay, xvinfo, None, True)

    def add_attribute(self, setting, value):
        """just to nicely add opengl parameters"""
        self.attrs.append(setting)
        self.attrs.append(value)

    def get_attributes(self):
        """ return our parameters in the expected structure"""
        attrs = self.attrs + [0, 0]
        return (c_int * len(attrs))(*attrs)

    def configure(self, wid):
        """  """
        self.xwindow_id = GdkX11.X11Window.get_xid(wid)
        if(not GLX.glXMakeCurrent(self.xdisplay, self.xwindow_id, self.context)):
            print 'failed'
        glViewport(0, 0, self.width, self.height)

    def draw_start(self):
        """make cairo context current for drawing"""
        if(not GLX.glXMakeCurrent(self.xdisplay, self.xwindow_id, self.context)):
            print "failed"

    def draw_finish(self):
        """swap buffer when we have finished drawing"""
        GLX.glXSwapBuffers(self.xdisplay, self.xwindow_id)

    def test(self):
        """Test method to draw something so we can make sure opengl is working and we can see something"""
        self.draw_start()

        glClearColor(0.0, 0.0, 0.0, 0.0)
        glClear(GL_COLOR_BUFFER_BIT)
        glBegin(GL_TRIANGLES)
        glIndexi(0)
        glColor3f(1.0, 0.0, 0.0)
        glVertex2i(0, 1)
        glIndexi(0)
        glColor3f(0.0, 1.0, 0.0)
        glVertex2i(-1, -1)
        glIndexi(0)
        glColor3f(0.0, 0.0, 1.0)
        glVertex2i(1, -1)
        glEnd()

        self.draw_finish()

class gui():
    glwrap = gtkgl()

    def __init__(self):
        self.window = Gtk.Window()
        self.window.realize()
        self.window.resize(self.glwrap.width, self.glwrap.height)
        self.window.set_resizable(True)
        self.window.set_reallocate_redraws(True)
        self.window.set_title("GTK3 with opengl")
        self.window.connect('delete_event', Gtk.main_quit)
        self.window.connect('destroy', lambda quit: Gtk.main_quit())

        self.drawing_area = Gtk.DrawingArea()
        self.drawing_area.connect('configure_event', self.on_configure_event)
        self.drawing_area.connect('draw', self.on_draw)
        self.drawing_area.set_double_buffered(False)
        self.drawing_area.set_size_request(self.glwrap.width, self.glwrap.height)

        self.window.add(self.drawing_area)
        self.window.show_all()

    def on_configure_event(self, widget, event):
        self.glwrap.configure(widget.get_window())
        return True

    def on_draw(self, widget, context):
        self.glwrap.test()

def main():
    g = gui()
    Gtk.main()

if __name__ == '__main__':
    main()

rawDescription: How can i use gtk3 and opengl together?

description: Use gtk3 and opengl together


code:
query = users.select().order_by(users.c.id.desc()).limit(5)

print reversed(conn.execute(query).fetchall() )

rawDescription: Sqlalchemy get last X rows in order

description: Sqlalchemy get last X rows in order


code:
from itertools import product
a = xrange(2)
b = xrange(3)

for x, y in product(a, b):
    print x, y

rawDescription: Walk two lists (no zip)

description: Walk two lists (no zip)


code:
import sys

class Logger():
    stdout = sys.stdout
    messages = []

    def start(self):
        sys.stdout = self

    def stop(self):
        sys.stdout = self.stdout

    def write(self, text):
        self.messages.append(text)

log = Logger()

log.start()
print "sys"
log.stop()

print log.messages

rawDescription: Python Get console ouput

description: Python Get console ouput


code:
soup = BeautifulSoup(html)
i = 0
data = []
while True:
    firm1 = soup.find('a', { "id" : "dgrdAcquired_hyplnkacquired_%s" % i})
    if not firm1:
        break
    data.append(''.join(firm1.findAll(text=True)))
    print data[-1]
    i += 1

rawDescription: How can I iterate through tags with different identifiers with BeautifulSoup in Python

description: Iterate through tags with different identifiers with BeautifulSoup in Python


code:
import datetime

# get current local time and utc time
localnow = datetime.datetime.now()
utcnow = datetime.datetime.utcnow()

# compute the time difference in seconds
tzd = localnow - utcnow
secs = tzd.days * 24 * 3600 + tzd.seconds

# get a positive or negative prefix
prefix = '+'
if secs < 0:
    prefix = '-'
    secs = abs(secs)

# print the local time with the difference, correctly formatted
suffix = "%s%02d:%02d" % (prefix, secs/3600, secs/60%60)
now = localnow.replace(microsecond=0)
print "%s%s" % (now.isoformat(' '), suffix)

rawDescription: In Python, how to print FULL ISO 8601 timestamp, including current timezone


code:
if np.isfinite(pcov).all():
    print 'valid'
else:
    print 'invalid'

rawDescription: Discern infinite value from array of floats


code:
import sys

if len(sys.argv)==2: # first entry in sys.argv is script itself...
    print "No second argument"
elif len(sys.argv)==3:
    print "Second argument"

rawDescription: Python script argument conditional

description: Python script argument conditional


code:
import Levenshtein
s = "spam ham and eggs"
t = "ram"
for i,_ in enumerate(s):
  s_ = s[i:i+len(t)]
  if Levenshtein.distance(s_, t) == 1:
    print s_

rawDescription: 1-mismatch regular expression

description: 1-mismatch regular expression


code:
#!/usr/bin/env python

import sys

def hello(variable):
    print variable

data = sys.stdin.read()
hello(data)

rawDescription: Pipe output from shell command to a python script


code:
def passmein(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    wrapper.__doc__ = func.__doc__
    return wrapper

@passmein
def testfunc(me):
    """This is a test function"""

if __name__ == '__main__':
    print testfunc.__doc__

rawDescription: How to print docstring outside a function using wrappers?

description: Print docstring outside a function using wrappers


code:
from PySide import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self, parent = None):
        super(Window, self).__init__(parent)

        # Create a slider
        self.floatSlider = QtGui.QSlider()
        self.floatSlider.setObjectName('floatSlider')
        self.floatSlider.valueChanged.connect(self.myFunction)

        # Create a spinbox
        self.colorSpinBox = QtGui.QSpinBox()
        self.colorSpinBox.setObjectName('colorSlider')
        self.colorSpinBox.valueChanged.connect(self.myFunction)

        # Create widget's layout
        mainLayout = QtGui.QHBoxLayout()
        mainLayout.addWidget(self.floatSlider)
        mainLayout.addWidget(self.colorSpinBox)
        self.setLayout(mainLayout)

        # Resize widget and show it
        self.resize(300, 300)
        self.show()

    def myFunction(self):
        # Getting current control calling this function with self.sender()
        # Print out the control's internal name, its type, and its value
        print "{0}: type {1}, value {2}".format( self.sender().objectName(), type( self.sender() ), self.sender().value() )

win = Window()

rawDescription: How to get the Maya/Qt GUI component that is calling a function?

description: Get the Maya/Qt GUI component that is calling a function


code:
out_edges = G.out_edges(G, data= True)

for edge in out_edges:

    lat = []
    lon = []
    x = edge[0]
    y = edge[1]
    lat.append(x)
    lon.append(y)
    print lat
    print lon

rawDescription: Appending in an empty list all the values of a dict key


code:
import csv
from collections import Counter

calo_hits = Counter()
with open('/Users/willturner/Desktop/caloHits.csv') as f: # 'rb' is not necessary
    reader = csv.reader(f)
    for row in reader:
        calo_hits.update([int(n.strip()) for n in row if n.strip()])

print calo_hits[10]

rawDescription: CSV to list of ints and count occurrence of integers


code:
if "http://" in result[2]:
    print result[2]

rawDescription: loop through results looking for a string using python

description: Loop through results looking for a string using python


code:
import subprocess
proc = subprocess.Popen('cmake', shell=True, stdout=subprocess.PIPE)
while proc.poll() is None:
    output = proc.stdout.readline()
    print output

rawDescription: How to get subprocess' stdout data asynchronously?

description: Get subprocess' stdout data asynchronously


code:
import numpy as np
M,N = 2,2
print np.kron(np.arange(12).reshape(3,4), np.ones((M,N), dtype=int))

rawDescription: how to repeat along two axis

description: Repeat along two axis


code:
import subprocess
res = subprocess.check_output(["/usr/bin/open", "-a", "-W", "/Applications/Mou.app", "p.py"])
print "Finished"

rawDescription: Launching and waiting a GUI app to finish with Python


code:
import re

def find_subs(line):
    match = re.findall(">([aA-zZ\s]*)<",line)
    if len(match) != 0:
        new_line = '
'
        for m in match:
            new_line += "
"+m+"
"
        new_line += "
"
        return new_line
    else:
        return None

line = "<stats>Some line
Other line</stats>"
new = find_subs(line)
print new

rawDescription: How to replace XML with sub-elements

description: Replace XML with sub-elements


code:
import cv2
import time

faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
capture = cv2.VideoCapture(0)
keyPressed = -1
faceFound = []
ts = [0,0,False]

print 'press esc to quit'

while(keyPressed != 27):
    ret, camImage = capture.read()
    cv2.imshow('camImage', camImage)

    try:
        faceRegion = faceCascade.detectMultiScale(camImage)
        if ts[2] == False:
            ts[0] = time.time()
            ts[2] = True
    except TypeError:
        if ts[2] == True:
            ts[1] = time.time()
            ts[2] = False
            faceFound.append([ts[0], ts[1]])
        print 'check if front face is visible to camera'
        pass

    keyPressed = cv2.waitKey(1)
cv2.destroyAllWindows()

for list in faceFound:
    print list[1] - list[0]

rawDescription: python, opencv: duration of time an object is detected on webcam

description: Python, opencv: duration of time an object is detected on webcam


code:
from threading import Thread
import time
import random
from Queue import Queue

queue = Queue(10)

class ProducerThread(Thread):
    def run(self):
        nums = range(5)
        global queue
        while True:
            num = random.choice(nums)
            queue.put(num)
            print "Produced", num
            time.sleep(random.random())

class ConsumerThread(Thread):
    def run(self):
        global queue
        while True:
            num = queue.get()
            queue.task_done()
            print "Consumed", num
            time.sleep(random.random())

ProducerThread().start()
ConsumerThread().start()

rawDescription: Access a Python Code That is Running

description: Access a Python Code That is Running


code:
with arcpy.da.UpdateCursor(fc, ["FEATURE", "FERRY"]) as cursor:
    for row in cursor:
        if row[0] == "ferry crossing": # test the FEATURE field
            row[1] = "FERRY" # set the FERRY field
            print "YES"
        else:
            print "NO"
        cursor.updateRow(row) # commit the changes

rawDescription: Add shp attribute data to column with python


code:
#!/usr/bin/env python
import sys, threading
import gtk, webkit
import time
import gobject

gobject.threads_init()
google = "http://www.google.com"

class WebView(webkit.WebView):
    #return page's content
    def get_html(self):
        self.execute_script('oldtitle=document.title;document.title=document.documentElement.innerHTML;')
        html = self.get_main_frame().get_title()
        self.execute_script('document.title=oldtitle;')
        return html

#wait 5 senconds and send a signal
class TimeSender(gobject.GObject, threading.Thread):
    def __init__(self):
        self.__gobject_init__()
        threading.Thread.__init__(self)

    def myEmit(self):
        window.emit("Sender_signal")

    def run(self):
        print "sleep 5 seconds"
        time.sleep(5)
        gobject.idle_add(self.myEmit)

gobject.type_register(TimeSender)

#PywebkitGTK, open google.com, receive signal
class Window(gtk.Window, gobject.GObject):
    def __init__(self, time_sender, url):
        self.__gobject_init__()
        gtk.Window.__init__(self)
        self.connect('Sender_signal', self._finished_loading)
        self._url = url

    def open_page(self):
        self.view = WebView()
        self.view.get_html()
        self.view.open(self._url)
        self.add(self.view)
        gtk.main()
    #write html to file
    def _finished_loading(self, view1):
        with open("pagehtml.html", 'w') as f:
            f.write(self.view.get_html())
        gtk.main_quit()

'''
def user_callback(object):
    with open("pagehtml2.html", 'w') as f:
        f.write(view.get_html())
    gtk.main_quit()
'''

if __name__ == '__main__':
    gobject.signal_new("Sender_signal", Window, gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())
    time_sender = TimeSender()
    window = Window(time_sender, google)
    #time_sender.connect("Sender_signal", user_callback)
    time_sender.start()
    window.open_page()

rawDescription: PyGTK with threading, gobject, send signal from another thread?


code:
import requests
r = requests.get(
    'https://storkcloud.org/api/stork/ls?uri=ftp://ftp.mozilla.org/',
    cookies=dict(email="EMAIL", password="PASS")
)
print r.text

rawDescription: python pycurl equivalent of curl -b get command

description: Python pycurl equivalent of curl -b get command


code:
import re

def replace_all(text, dic):
    result = ""
    input = re.findall(r"[\w']+|[.,!?;]", text)
    for word in input:
        changed = dic.get(word,word)
        result = result + " " + changed
    return result

my_text = 'Flojo y cargantes. Decepcionantes. Decenté decentó'
my_text_lower= my_text.lower()

lemmatize_list = 'ExampleDictionary'
lemmatize_word_dict = {}
with open(lemmatize_list) as f:
    for line in f:
        kv = line.split()
        lemmatize_word_dict[kv[1]] =kv[0]

    txt = replace_all(my_text_lower, lemmatize_word_dict)
    print txt

rawDescription: Making multiple search and replace more precise in Python for lemmatizer


code:
# Not broken anymore, prints 3.1415559...

from math import sqrt

def get_y(x, r):
    return sqrt((r**2.0)-(x**2.0)) # First mistake: ** is exponentiation, not ^

def get_distance(x1, y1, x2, y2):
    return sqrt( (x2-x1)**2.0 + (y2-y1)**2.0 )

def c(r):
    # def range(b): # redundant
    #     a = 0
    #     while a < b:
    #         yield a
    #         a = a + 1
    circumference = 0.0
    for x1 in range(r):
        x2 = x1 + 1.0
        y1 = get_y(x1, r)
        y2 = get_y(x2, r)
        distance = get_distance(x1, y1, x2, y2) # second mistake, x2, x2 --> x2, y2
        circumference = circumference + distance
    circumference = circumference * 4
    return circumference

print get_y(0, 4)
radius = 400.0
print "%.64f" % (c(radius) / (radius * 2)) # third mistake: / radius * 2 --> / (radius*2)

rawDescription: Calculating pi in Python using geometry

description: Calculating pi in Python using geometry


code:
import urllib2
import json

data = {"text": "Hello world github/linguist#1 **cool**, and #1!"}
json_data = json.dumps(data)

req = urllib2.Request("https://api.github.com/markdown")
result = urllib2.urlopen(req, json_data)

print '\n'.join(result.readlines())

rawDescription: Python JSON call

description: Python JSON call


code:
import ast
import inspect

class NodeTagger(ast.NodeVisitor):
    def __init__(self):
        self.class_attribute_names = {}

    def visit_Assign(self, node):
        for target in node.targets:
            self.class_attribute_names[target.id] = target.lineno

    # Don't visit Assign nodes inside Function Definitions.
    def visit_FunctionDef(self, unused_node):
        return None

def order_properties(model):
    properties = model._properties
    source = inspect.getsource(model)
    tree = ast.parse(source)
    visitor = NodeTagger()
    visitor.visit(tree)
    attributes = visitor.class_attribute_names
    model._ordered_property_list = sorted(properties, key=lambda x:attributes[x])
    return model

@order_properties
class Foo(object):
    c = 1
    b = 2
    a = 3

    # Add a _properties member to simulate an `ndb.Model`.
    _properties = {'a': object, 'b': object, 'c': object}

print Foo._ordered_property_list

rawDescription: ndb Model - retrieve ordered set of property names

description: Ndb Model - retrieve ordered set of property names


code:
data = [{'name': 'Jack'}, {'age': '28'}]

new_dict = {}
for d in data:
    new_dict.update(d)

new_data = [new_dict]

print new_data

rawDescription: How can I merge two or more dictionaries in a list?

description: Merge two or more dictionaries in a list


code:
def openAndSleep():
    with open("fff", 'w') as f:
        print "opened, sleep 10 sec"
        time.sleep(10)
        print "sleep finish"

rawDescription: Will Python close an fd if it's out of a local scope?


code:
x = csr_matrix(np.random.rand(1000) > 0.99).T
print x.shape   # (1000, 1)

rawDescription: Sparse-Dense multiplication in Python

description: Sparse-Dense multiplication in Python


code:
a = range(20)
b = range(5)
for i in range(len(a)):
  if i%4==0:
    print a[i], b[i/4]
  else:
    print a[i]

rawDescription: Looping lists in tandem every nth iteration


code:
class Double:
        def run(self,x):
            return x*2

class Triple:
    def run(self,x):
        return x*3

def createMultiplier(n):
    class Multiply:
        def run(self,x):
            return x*n
    return Multiply

class Library:
    def __init__(self,c):
        self.c = c()
    def Op(self,val):
        return self.c.run(val)

op1 = Double
op2 = Triple
op3 = createMultiplier(5)

lib1 = Library(op1)
lib2 = Library(op2)
lib3 = Library(op3)

print lib1.Op(2)
print lib2.Op(2)
print lib3.Op(2)

rawDescription: Lambda function for classes in python?

description: Lambda function for classes in python


code:
import datetime

print datetime.datetime.now() - datetime.timedelta(minutes=59)

rawDescription: How to minus time with Python

description: Minus time with Python


code:
import unicodedata as ucd
import sys

def dump_encoding(enc):
    for i in xrange(sys.maxunicode):
        u = unichr(i)
        try:
            s = u.encode(enc)
        except UnicodeEncodeError:
            continue
        try:
            name = ucd.name(u)
        except:
            name = '?'
        print "U+%06X %r %s" % (i, s, name)

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

rawDescription: How can I iterate over every character in a given encoding using Python?

description: Iterate over every character in a given encoding using Python


code:
from voronoi import voronoi
import random
from collections import defaultdict

num_points = 50
points = [(random.uniform(0,10), random.uniform(0,10)) for i in xrange(num_points)]
c = voronoi(points)

# For each point find triangles (vertices) of a cell
point_in_triangles = defaultdict(set)
for t_ind, ps in enumerate(c.triangles):
    for p in ps:
        point_in_triangles[p].add(t_ind)

# Vertex connectivity graph
vertex_graph = defaultdict(set)
for e_ind, (_, r, l) in enumerate(c.edges):
    vertex_graph[r].add(l)
    vertex_graph[l].add(r)

def cell(point):
    if point not in point_in_triangles:
        return None
    vertices = set(point_in_triangles[point]) # copy
    v_cell = [vertices.pop()]
    vertices.add(-1)  # Simulate infinity :-)
    while vertices:
        neighbours = vertex_graph[v_cell[-1]] & vertices
        if not neighbours:
            break
        v_cell.append(neighbours.pop())
        vertices.discard(v_cell[-1])
    return v_cell

for p in xrange(num_points):
    print p, cell(p)

rawDescription: Editing voronoi class to return polygon points in python


code:
import wx

########################################################################
class MyForm(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "List Control Tutorial")

        # Add a panel so it looks the correct on all platforms
        panel = wx.Panel(self, wx.ID_ANY)
        self.index = 0

        self.list_ctrl = wx.ListCtrl(panel, size=(-1,100),
                         style=wx.LC_REPORT
                         |wx.BORDER_SUNKEN
                         )
        self.list_ctrl.InsertColumn(0, 'Subject')
        self.list_ctrl.InsertColumn(1, 'Due')
        self.list_ctrl.InsertColumn(2, 'Location', width=125)

        btn = wx.Button(panel, label="Add Line")
        btn2 = wx.Button(panel, label="Get Column 0")
        btn.Bind(wx.EVT_BUTTON, self.add_line)
        btn2.Bind(wx.EVT_BUTTON, self.getColumn)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.list_ctrl, 0, wx.ALL|wx.EXPAND, 5)
        sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
        sizer.Add(btn2, 0, wx.ALL|wx.CENTER, 5)
        panel.SetSizer(sizer)

    #----------------------------------------------------------------------
    def add_line(self, event):
        line = "Line %s" % self.index
        self.list_ctrl.InsertStringItem(self.index, line)
        self.list_ctrl.SetStringItem(self.index, 1, "01/19/2010")
        self.list_ctrl.SetStringItem(self.index, 2, "USA")
        self.index += 1

    #----------------------------------------------------------------------
    def getColumn(self, event):
        """"""
        count = self.list_ctrl.GetItemCount()
        for row in range(count):
            item = self.list_ctrl.GetItem(itemId=row, col=0)
            print item.GetText()

#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

rawDescription: ListCtrl - wxPython get all the values from a column


code:
s =  "110202 132721"
print time.mktime(time.strptime(s, "%y%m%d %H%M%S"))

rawDescription: python convert date and time into linux timestmap

description: Python convert date and time into linux timestmap


code:
def getDataCopy( data ):

    """ Given a piece of data, figure out how to copy it.  If it's a native python type
        like a string or numeric, just return the value.  If it's a rally object, return
        the ref to it.  If it's a list, iterate and call ourself recursively for the
        list members. """

    if isinstance( data, types.ListType ):
        copyData = []
        for entry in data:
            copyData.append( getDataCopy(entry) )

    elif hasattr( data, "ref" ):
        copyData = { "_ref": data.ref }

    else:
        copyData = data

    return copyData

def getArtifactCopy( artifact ):

    """ Build a dictionary based on the values in the specified artifact.  This dictionary
        can then be passed to a rallyConn.put() call to actually create the new entry in
        Rally.  Attachments and Tasks must be copied seperately, since they require creation
        of additional artifacts """

    newArtifact = {}

    for attrName in artifact.attributes():

        # Skip the attributes that we can't or shouldn't handle directly
        if attrName.startswith("_") or attrName == "oid" or attrName == "Iteration" or attrName == "Attachments":
            continue

        attrValue = getattr( artifact, attrName )
        newArtifact[attrName] = getDataCopy( attrValue )

    if getattr( artifact, "Iteration", None ) != None:
        newArtifact["Iteration"] = { "_ref": "iteration/" + artifact.Iteration.oid }

    return newArtifact

def copyAttachments( rallyConn, oldArtifact, newArtifact ):

    """ For each attachment in the old artifact, create new attachments and attach them to the new artifact"""

    # Copy Attachments
    source_attachments = rallyConn.getAttachments(oldArtifact)

    for source_attachment in source_attachments:

        # First copy the content
        source_attachment_content = source_attachment.Content
        target_attachment_content_fields = { "Content": base64.encodestring(source_attachment_content) }

        try:
            target_attachment_content = rallyConn.put( 'AttachmentContent', target_attachment_content_fields )
            print "\t===> Copied AttachmentContent: %s" % target_attachment_content.ref
        except pyral.RallyRESTAPIError, details:
            sys.stderr.write('ERROR: %s \n' % details)
            sys.exit(2)

        # Next copy the attachment object
        target_attachment_fields = {
            "Name": source_attachment.Name,
            "Description": source_attachment.Description,
            "Content": target_attachment_content.ref,
            "ContentType": source_attachment.ContentType,
            "Size": source_attachment.Size,
            "User": source_attachment.User.ref
        }

        # Attach it to the new artifact
        target_attachment_fields["Artifact"] = newArtifact.ref

        try:
            target_attachment = rallyConn.put( source_attachment._type, target_attachment_fields)
            print "\t===> Copied Attachment: '%s'" % target_attachment.Name
        except pyral.RallyRESTAPIError, details:
            sys.stderr.write('ERROR: %s \n' % details)
            sys.exit(2)

def copyTasks( rallyConn, oldArtifact, newArtifact ):

    """ Iterate over the old artifacts tasks and create new ones, attaching them to the new artifact """

    for currentTask in oldArtifact.Tasks:

        newTask = getArtifactCopy( currentTask )

        # Assign the new task to the new artifact
        newTask["WorkProduct"] = newArtifact.ref

        # Push the new task into rally
        newTaskObj = rallyConn.put( currentTask._type, newTask )

        # Copy any attachments the task had
        copyAttachments( rallyConn, currentTask, newTaskObj )

def copyDefect( rallyConn, currentDefect, addlUpdates = {} ):

    """ Copy a defect including its attachments and tasks.  Add the new defect as a
        duplicate to the original """

    newArtifact = getArtifactCopy( currentDefect )

    # Add the current defect as a duplicate for the new one
    newArtifact["Duplicates"].append( { "_ref": currentDefect.ref } )

    # Copy in any updates that might be needed
    for (attrName, attrValue) in addlUpdates.items():
        newArtifact[attrName] = attrValue

    print "Copying %s: %s..." % (currentDefect.Project.Name, currentDefect.FormattedID),
    newDefect = rallyConn.create( currentDefect._type, newArtifact )

    print "done, new item", newDefect.FormattedID

    print "\tCopying attachments"
    copyAttachments( rallyConn, currentDefect, newDefect )

    print "\tCopying tasks"
    copyTasks( rallyConn, currentDefect, newDefect )

rawDescription: Preferred method to copy a defect using Rally REST API in Python


code:
data=open("file").read().split("\n\n")
for rec in data:
    if "have paid" in rec:
         print rec.split("have paid")[0]

rawDescription: Append previous lines of a file based on a condition


code: print repr('some\ttext')

rawDescription: How to accept raw special characters in a function?

description: Accept raw special characters in a function


code:
def foo(func):
    def wrap(s): # I'd call this 'self' instead of 's' to remind us it's a reference to an instance

        func(s) # This is a function, not a method yet - so we need to pass in the reference

        s.ma() # This is a method, because you use attribute lookup on the object s to get it
    return wrap

class A:
    def ma(self):
        print "this is ma"

    @foo     # if the way foo wraps mb doesn't depend on some arg, don't use args here
    def mb(self):
        print "this is mb"

rawDescription: Python member function decorators use instance as a parameter


code:
import numpy as np
import matplotlib.pyplot as plt

s100, s0 = 5, 0

signal = np.concatenate((np.ones((25,)) * s100,
                         s100 + (np.random.rand(25) - 0.5) * (s100-s0),
                         np.linspace(s100, s0, 25),
                         s0 + (np.random.rand(25) - 0.5) * (s100-s0),
                         np.ones((25,)) * s0))

# Interpolate to find crossings with 30% and 70% of signal
# The general linear interpolation formula between (x0, y0) and (x1, y1) is:
# y = y0 + (x-x0) * (y1-y0) / (x1-x0)
# to find the x at which the crossing with y happens:
# x = x0 + (y-y0) * (x1-x0) / (y1-y0)
# Because we are using indices as time, x1-x0 == 1, and if the crossing
# happens within the interval, then 0 <= x <= 1.
# The following code is just a vectorized version of the above
delta_s = np.diff(signal)
t30 = (s0 + (s100-s0)*.3 - signal[:-1]) / delta_s
idx30 = np.where((t30 > 0) & (t30 < 1))[0]
t30 = idx30 + t30[idx30]
t70 = (s0 + (s100-s0)*.7 - signal[:-1]) / delta_s
idx70 = np.where((t70 > 0) & (t70 < 1))[0]
t70 = idx70 + t70[idx70]

# compute all possible transition times, keep the smallest
idx = np.unravel_index(np.argmin(t30[:, None] - t70),
                       (len(t30), len(t70),))

print t30[idx[0]] - t70[idx[1]]
# 9.6

plt. plot(signal)
plt.plot(t30, [s0 + (s100-s0)*.3]*len(t30), 'go')
plt.plot(t30[idx[0]], [s0 + (s100-s0)*.3], 'o', mec='g', mfc='None', ms=10)
plt.plot(t70, [s0 + (s100-s0)*.7]*len(t70), 'ro')
plt.plot(t70[idx[1]], [s0 + (s100-s0)*.7], 'o', mec='r', mfc='None', ms=10 )
plt.show()

rawDescription: Slew rate measuring

description: Slew rate measuring


code:
dom = parseString(data)

xmlTag = dom.getElementsByTagName('items')
for node in xmlTag:
    item = node.getElementsByTagName('item_name')[0]
    print item,
    cat = node.getElementsByTagBane('category')
    for s in cat:
        print s.childNodes[0].data,
    print ""

rawDescription: Concatenate multiple node values when parsing XML


code:
colors = {0:'yellow', 1:'red', 5:'blue'};
fig, ax1 = plt.subplots(figsize=(3.25,3));
print y;
c_arr=[colors[k] for k in y]
ax1.scatter(X[:,0],X[:,1], s=(y+1)*20, c=c_arr);

rawDescription: matplotlib scatter with non-sequential label colors

description: Matplotlib scatter with non-sequential label colors


code: print chr(65) # will print "A"

rawDescription: What is the opposite of python's ord() function?


code:
import sys
import ctypes

def zerome(string):
    location = id(string) + 20
    size     = sys.getsizeof(string) - 20

    memset =  ctypes.cdll.msvcrt.memset
    # For Linux, use the following. Change the 6 to whatever it is on your computer.
    # memset =  ctypes.CDLL("libc.so.6").memset

    print "Clearing 0x%08x size %i bytes" % (location, size)

    memset(location, 0, size)

rawDescription: Mark data as sensitive in python

description: Mark data as sensitive in python


code:
import os
import time

dirname = MEDIA_ROOT+my_folder
filenames = os.listdir(dirname)
filenames = [os.path.join(dirname,filename) for filename in filenames]
for filename in filenames:
    last_access = os.stat(filename).st_mtime #secs since epoch
    timediff = time.gmtime() - last_access
    print filename+'----'+timediff
    if timediff > 24*60*60:
        print 'older than a day'
        # do your thing

rawDescription: deleting unaccessed files using python

description: Deleting unaccessed files using python


rawDescription: Sequence of zeroes

description: Sequence of zeroes


code:
import select
import socket

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(('', 8888))
server_socket.listen(5)
print "Listening on port 8888"

read_list = [server_socket]
while True:
    readable, writable, errored = select.select(read_list, [], [])
    for s in readable:
        if s is server_socket:
            client_socket, address = server_socket.accept()
            read_list.append(client_socket)
            print "Connection from", address
        else:
            data = s.recv(1024)
            if data:
                s.send(data)
            else:
                s.close()
                read_list.remove(s)

rawDescription: Python socket.accept nonblocking?

description: Python socket.accept nonblocking


code:
import fcntl
import contextlib

@contextlib.contextmanager
def lock(fname):
    with open(fname, "w") as f:
        print "Acquiring lock"
        fcntl.lockf(f, fcntl.LOCK_EX)
        print "Acquired lock"

        yield

        print "Releasing lock"
        fcntl.lockf(f, fcntl.LOCK_UN)
        print "Released lock"

if __name__ == "__main__":
    import os
    print "PID:", os.getpid()

    import time
    print "Starting"
    with lock("/tmp/lock-file"):
        time.sleep(100)
    print "Done"

rawDescription: How to properly implement a process based lock in Python?

description: Properly implement a process based lock in Python


code:
import json

from bs4 import BeautifulSoup
import requests
from slimit import ast
from slimit.parser import Parser
from slimit.visitors import nodevisitor

ID = 1042997979

url = 'http://bedbathandbeyond.ugc.bazaarvoice.com/2009-en_us/{id}/reviews.djs?format=embeddedhtml&sort=submissionTime'.format(id=ID)

response = requests.get(url)

parser = Parser()
tree = parser.parse(response.content)
data = ""
for node in nodevisitor.visit(tree):
    if isinstance(node, ast.Object):
        data = json.loads(node.to_ecma())
        if "BVRRSourceID" in data:
            break

soup = BeautifulSoup(data['BVRRSourceID'])
print soup.select('span.BVRRCount span.BVRRNumber')[0].text

rawDescription: Having trouble accessing xpath attribute with scrapy


code:
for name, dtype in d._fields_:
    print name, getattr(d, name)

rawDescription: Python ctypes c_float.value doesn't return value


rawDescription: How to decode this string (it's hex?)?

description: Decode this string (it's hex?)


code:
import time, threading
answer = ""
def user_input():
    answer = raw_input("Hello, how are you doing? ")
    global answer

Thread1 = threading.Thread(target = user_input)
for the_time in range(100): #Example loop
    time.sleep(2)
    print answer

rawDescription: Loop vs asynchronous timer

description: Loop vs asynchronous timer


code:
import wx

########################################################################
class MyFileDropTarget(wx.FileDropTarget):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, window):
        """Constructor"""
        wx.FileDropTarget.__init__(self)
        self.window = window

    #----------------------------------------------------------------------
    def OnDropFiles(self, x, y, filenames):
        """
        When files are dropped, write where they were dropped and then
        the file paths themselves
        """
        self.window.SetInsertionPointEnd()
        self.window.updateText("\n%d file(s) dropped at %d,%d:\n" %
                              (len(filenames), x, y))
        print filenames
        for filepath in filenames:
            self.window.updateText(filepath + '\n')

########################################################################
class DnDPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)

        file_drop_target = MyFileDropTarget(self)
        lbl = wx.StaticText(self, label="Drag some files here:")
        self.fileTextCtrl = wx.TextCtrl(self,
                                        style=wx.TE_MULTILINE|wx.HSCROLL|wx.TE_READONLY)
        self.fileTextCtrl.SetDropTarget(file_drop_target)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(lbl, 0, wx.ALL, 5)
        sizer.Add(self.fileTextCtrl, 1, wx.EXPAND|wx.ALL, 5)
        self.SetSizer(sizer)

    #----------------------------------------------------------------------
    def SetInsertionPointEnd(self):
        """
        Put insertion point at end of text control to prevent overwriting
        """
        self.fileTextCtrl.SetInsertionPointEnd()

    #----------------------------------------------------------------------
    def updateText(self, text):
        """
        Write text to the text control
        """
        self.fileTextCtrl.WriteText(text)

########################################################################
class DnDFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, parent=None, title="DnD Tutorial")
        panel = DnDPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = DnDFrame()
    app.MainLoop()

rawDescription: wxPython: Dragging a file into window to get file path

description: WxPython: Dragging a file into window to get file path


code:
# Download the Python helper library from twilio.com/docs/python/install
from twilio.rest import TwilioRestClient

# Your Account Sid and Auth Token from twilio.com/user/account
account_sid = "AC1ab0bb368322688c3d6cbb1355aeef9b"
auth_token  = "{{ auth_token }}"
client = TwilioRestClient(account_sid, auth_token)

message = client.messages.create(body="Jenny please?! I love you <3",
    to="+15558675309",
    from_="+14158141829",
    media_url="http://www.example.com/hearts.png")
print message.sid

rawDescription: Getting SMS Twilio message sid as it is being created from an outgoing message


code:
#!/usr/bin/env python

import os, os.path
import stat

def traverse_path(start_dir='.'):
    for root, dirs, files in os.walk(start_dir, topdown=False):
        for f in files:
            complete_path = os.path.join(root, f)
            try:
                m = os.stat(complete_path)[stat.ST_MODE]
                if stat.S_ISREG(m):
                    yield complete_path[len(start_dir):]
            except OSError, err:
                print 'Skipping', complete_path
            except IOError, err:
                print 'Skipping', complete_path

if __name__ == '__main__':
    s = set(traverse_path('/home/hughdbrown'))
    t = set(traverse_path('/home.backup/hughdbrown'))
    for e in s - t:
        print e
    print '-' * 25
    for e in t - s:
        print e

rawDescription: Remove differences between two folders

description: Remove differences between two folders


code:
import errno
import socket
import time
import mock

PORT = 50123

def connect_mock(*agrs):
    raise socket.error(errno.WSAECONNREFUSED, "Testing")

def main():
    s = socket.socket()
    s.bind(('127.0.0.1', PORT))
    s.listen(0)
    client = socket.socket()
    client.connect(('127.0.0.1', PORT))

    client2 = socket.socket()
    start = time.time()

    with mock.patch('socket.socket.connect', connect_mock):
        try:
            client2.connect(('127.0.0.1', PORT))
            print "done"
        except socket.error as e:
            assert e.errno == errno.WSAECONNREFUSED
            print 'connection attempt took', time.time() - start
        finally:
            client2.close()
            client.close()
            s.close()

if __name__ == '__main__':
    main()

rawDescription: Fast detection or simulation of WSAECONNREFUSED


code:
def check():
    text = inputfield.get()
    print text.startswith('sag')

rawDescription: First letters of a Tkinter input

description: First letters of a Tkinter input


code:
orig = { 'a' : 'val\ue' }
jstring = json.dumps(orig)
print jstring
extracted = json.loads(jstring)
print extracted
print extracted['a']

rawDescription: Unable to load json containing escape sequences


code:
import pickle

class Example:
    def __init__(self):
        self.list1 = [1]
        self.list2 = [2]

    def __getstate__(self):
        return {'list1': self.list1, 'list2': self.list2}

    def __setstate__(self, state):
        self.list1 = state['list1']
        self.list2 = state['list2']

ex = Example()
s = pickle.dumps(ex)
ex2 = pickle.loads(s)
print ex.list1, ex.list2

rawDescription: How do you pass multiple arguments to __setstate__?

description: Pass multiple arguments to __setstate__


code:
import _winreg

################################################################################

class HKEY:
    'Hive Constants'
    CLASSES_ROOT = -2147483648
    CURRENT_USER = -2147483647
    LOCAL_MACHINE = -2147483646
    USERS = -2147483645
    CURRENT_CONFIG = -2147483643

class KEY:
    'Mode Constants'
    QUERY_VALUE = 1
    SET_VALUE = 2
    CREATE_SUB_KEY = 4
    ENUMERATE_SUB_KEYS = 8
    NOTIFY = 16
    CREATE_LINK = 32
    WRITE = 131078
    EXECUTE = 131097
    READ = 131097
    ALL_ACCESS = 983103

class REG:
    'Type Constants'
    NONE = 0
    SZ = 1
    EXPAND_SZ = 2
    BINARY = 3
    DWORD = 4
    DWORD_BIG_ENDIAN = 5
    LINK = 6
    MULTI_SZ = 7
    RESOURCE_LIST = 8
    FULL_RESOURCE_DESCRIPTOR = 9
    RESOURCE_REQUIREMENTS_LIST = 10
    QWORD = 11

################################################################################

class _Value(object):

    '_Value(value) -> _Value'

    def __init__(self, value):
        'Initialize the _Value object.'
        self.__value = value
        self.__repr = '%s(%r)' % (self.__class__.__name__, value)

    def __repr__(self):
        'Return the object\'s representation.'
        return self.__repr

    def __get_value(self):
        'Private class method.'
        return self.__value

    value = property(__get_value, doc='Value of this object.')

class REG_NONE(_Value): pass
class REG_SZ(_Value): pass
class REG_EXPAND_SZ(_Value): pass
class REG_BINARY(_Value): pass
class REG_DWORD(_Value): pass
class REG_DWORD_BIG_ENDIAN(_Value): pass
class REG_LINK(_Value): pass
class REG_MULTI_SZ(_Value): pass
class REG_RESOURCE_LIST(_Value): pass
class REG_FULL_RESOURCE_DESCRIPTOR(_Value): pass
class REG_RESOURCE_REQUIREMENTS_LIST(_Value): pass
class REG_QWORD(_Value): pass

################################################################################

class Registry(object):

    'Registry([computer]) -> Registry'

    def __init__(self, computer=None):
        'Initialize the Registry object.'
        self.__computer = computer
        self.__repr = 'Registry()' if computer is None else 'Registry(%r)' % computer

    def __repr__(self):
        'Return the object\'s representation.'
        return self.__repr

    def __iter__(self):
        'Iterate over hives defined in HKEY.'
        return (Key(key, computer=self.__computer) for key in map(HKEY.__dict__.__getitem__, filter(str.isupper, dir(HKEY))))

    def __HKEY_CLASSES_ROOT(self):
        'Private class method.'
        return Key(HKEY.CLASSES_ROOT, computer=self.__computer)

    def __HKEY_CURRENT_USER(self):
        'Private class method.'
        return Key(HKEY.CURRENT_USER, computer=self.__computer)

    def __HKEY_LOCAL_MACHINE(self):
        'Private class method.'
        return Key(HKEY.LOCAL_MACHINE, computer=self.__computer)

    def __HKEY_USERS(self):
        'Private class method.'
        return Key(HKEY.USERS, computer=self.__computer)

    def __HKEY_CURRENT_CONFIG(self):
        'Private class method.'
        return Key(HKEY.CURRENT_CONFIG, computer=self.__computer)

    HKEY_CLASSES_ROOT = property(__HKEY_CLASSES_ROOT, doc='The CLASSES_ROOT hive.')
    HKEY_CURRENT_USER = property(__HKEY_CURRENT_USER, doc='The CURRENT_USER hive.')
    HKEY_LOCAL_MACHINE = property(__HKEY_LOCAL_MACHINE, doc='The LOCAL_MACHINE hive.')
    HKEY_USERS = property(__HKEY_USERS, doc='The USERS hive.')
    HKEY_CURRENT_CONFIG = property(__HKEY_CURRENT_CONFIG, doc='The CURRENT_CONFIG hive.')

################################################################################

class Key(object):

    '''Key(key[, subkey][, mode][, computer]) -> Key

    Key(key) -> Key
    Key(key, subkey) -> Key
    Key(key, mode=value) -> Key
    Key(key, subkey, mode) -> Key
    Key(key, computer=value) -> Key
    Key(key, subkey, computer=value) -> Key
    Key(key, mode=value, computer=value) -> Key
    Key(key, subkey, mode, computer) -> Key'''

    def __init__(self, key, subkey=None, mode=None, computer=None):
        'Initialize the Key object.'
        if isinstance(key, (int, _winreg.HKEYType)) and subkey is None and mode is None and computer is None:
            self.__key = _winreg.OpenKey(key, '')
        elif isinstance(key, Key) and subkey is None and mode is None and computer is None:
            self.__key = _winreg.OpenKey(key.__key, '')
        elif isinstance(key, (int, _winreg.HKEYType)) and isinstance(subkey, str) and mode is None and computer is None:
            self.__key = _winreg.OpenKey(key, subkey)
        elif isinstance(key, Key) and isinstance(subkey, str) and mode is None and computer is None:
            self.__key = _winreg.OpenKey(key.__key, subkey)
        elif isinstance(key, (int, _winreg.HKEYType)) and subkey is None and isinstance(mode, int) and computer is None:
            self.__key = _winreg.OpenKey(key, '', 0, mode)
        elif isinstance(key, Key) and subkey is None and isinstance(mode, int) and computer is None:
            self.__key = _winreg.OpenKey(key.__key, '', 0, mode)
        elif isinstance(key, (int, _winreg.HKEYType)) and isinstance(subkey, str) and isinstance(mode, int) and computer is None:
            self.__key = _winreg.OpenKey(key, subkey, 0, mode)
        elif isinstance(key, Key) and isinstance(subkey, str) and isinstance(mode, int) and computer is None:
            self.__key = _winreg.OpenKey(key.__key, subkey, 0, mode)
        elif isinstance(key, int) and subkey is None and mode is None and isinstance(computer, str):
            self.__key = _winreg.ConnectRegistry(computer, key)
        elif isinstance(key, int) and isinstance(subkey, str) and mode is None and isinstance(computer, str):
            self.__key = _winreg.OpenKey(_winreg.ConnectRegistry(computer, key), subkey)
        elif isinstance(key, int) and subkey is None and isinstance(mode, int) and isinstance(computer, str):
            self.__key = _winreg.OpenKey(_winreg.ConnectRegistry(computer, key), '', 0, mode)
        elif isinstance(key, int) and isinstance(subkey, str) and isinstance(mode, int) and isinstance(computer, str):
            self.__key = _winreg.OpenKey(_winreg.ConnectRegistry(computer, key), subkey, 0, mode)
        else:
            raise TypeError, 'Please check documentation.'
        self.__keys = Keys(self.__key)
        self.__values = Values(self.__key)
        self.__info = Info(self.__key)
        self.__repr = 'Key(%s)' % ', '.join([repr(key)] + ['%s=%r' % (key, value) for key, value in zip(('subkey', 'mode', 'computer'), (subkey, mode, computer)) if value is not None])

    def __repr__(self):
        'Return the object\'s representation.'
        return self.__repr

    def save(self, file_name):
        'Save this key to file.'
        _winreg.SaveKey(self.__key, file_name)

    def load(self, subkey, file_name):
        'Load subkey from file.'
        _winreg.LoadKey(self.__key, subkey, file_name)

    def __get_keys(self):
        'Private class method.'
        return self.__keys

    def __set_keys(self, keys):
        'Private class method.'
        if isinstance(keys, str):
            _winreg.CreateKey(self.__key, keys)
        elif isinstance(keys, (list, tuple)):
            for key in keys:
                self.keys = key
        else:
            raise TypeError, 'Key Could Not Be Created'

    def __del_keys(self):
        'Private class method.'
        try:
            while True:
                _winreg.DeleteKey(self.__key, _winreg.EnumKey(self.__key, 0))
        except EnvironmentError:
            pass

    def __get_values(self):
        'Private class method.'
        return self.__values

    def __set_values(self, values):
        'Private class method.'
        if isinstance(values, str):
            _winreg.SetValueEx(self.__key, values, 0, REG.SZ, _winreg.QueryValue(self.__key, ''))
        elif isinstance(values, (list, tuple)):
            for value in values:
                self.values = value
        else:
            raise TypeError, 'Value Could Not Be Created'

    def __del_values(self):
        'Private class method.'
        try:
            while True:
                _winreg.DeleteValue(self.__key, _winreg.EnumValue(self.__key, 0)[0])
        except EnvironmentError:
            pass

    def __get_value(self):
        'Private class method.'
        return _winreg.QueryValue(self.__key, '')

    def __set_value(self, value):
        'Private class method.'
        _winreg.SetValue(self.__key, '', REG.SZ, value)

    def __del_value(self):
        'Private class method.'
        _winreg.DeleteValue(self.__key, '')

    def __get_info(self):
        'Private class method.'
        return self.__info

    keys = property(__get_keys, __set_keys, __del_keys, 'Keys of this key.')
    values = property(__get_values, __set_values, __del_values, 'Values of this key.')
    value = property(__get_value, __set_value, __del_value, 'Value of this key.')
    info = property(__get_info, doc='Information about this key.')

################################################################################

class Keys(object):

    'Keys(key) -> Keys'

    def __init__(self, key):
        'Initialize the Keys object.'
        self.__key = key
        self.__repr = 'Keys(%r)' % key

    def __repr__(self):
        'Return the object\'s representation.'
        return self.__repr

    def __len__(self):
        'Return the number of keys.'
        return _winreg.QueryInfoKey(self.__key)[0]

    def __getitem__(self, key):
        'Return the specified key.'
        return Key(self.__key, key)

    def __setitem__(self, key, value):
        'Assign the item to a key.'
        key = Key(_winreg.CreateKey(self.__key, key), mode=KEY.ALL_ACCESS)
        for name in value.values:
            key.values[name] = value.values[name]
        for name in value.keys:
            key.keys[name] = value.keys[name]

    def __delitem__(self, key):
        'Delete the specified key.'
        _winreg.DeleteKey(self.__key, key)

    def __iter__(self):
        'Iterate over the key names.'
        return iter(tuple(_winreg.EnumKey(self.__key, index) for index in xrange(_winreg.QueryInfoKey(self.__key)[0])))

    def __contains__(self, item):
        'Check for a key\'s existence.'
        item = item.lower()
        for index in xrange(_winreg.QueryInfoKey(self.__key)[0]):
            if _winreg.EnumKey(self.__key, index).lower() == item:
                return True
        return False

################################################################################

class Values(object):

    'Values(key) -> Values'

    TYPES = REG_NONE, REG_SZ, REG_EXPAND_SZ, REG_BINARY, REG_DWORD, REG_DWORD_BIG_ENDIAN, REG_LINK, REG_MULTI_SZ, REG_RESOURCE_LIST, REG_FULL_RESOURCE_DESCRIPTOR, REG_RESOURCE_REQUIREMENTS_LIST, REG_QWORD

    def __init__(self, key):
        'Initialize the Values object.'
        self.__key = key
        self.__repr = 'Values(%r)' % key

    def __repr__(self):
        'Return the object\'s representation.'
        return self.__repr

    def __len__(self):
        'Return the number of values.'
        return _winreg.QueryInfoKey(self.__key)[1]

    def __getitem__(self, key):
        'Return the specified value.'
        item_value, item_type = _winreg.QueryValueEx(self.__key, key)
        return self.TYPES[item_type](item_value)

    def __setitem__(self, key, value):
        'Assign the item to a value.'
        if isinstance(value, self.TYPES):
            _winreg.SetValueEx(self.__key, key, 0, list(self.TYPES).index(value.__class__), value.value)
        else:
            _winreg.SetValueEx(self.__key, key, 0, _winreg.QueryValueEx(self.__key, key)[1], value)

    def __delitem__(self, key):
        'Delete the specified value.'
        _winreg.DeleteValue(self.__key, key)

    def __iter__(self):
        'Iterate over the value names.'
        return iter(tuple(_winreg.EnumValue(self.__key, index)[0] for index in xrange(_winreg.QueryInfoKey(self.__key)[1])))

    def __contains__(self, item):
        'Check for a value\'s existence.'
        item = item.lower()
        for index in xrange(_winreg.QueryInfoKey(self.__key)[1]):
            if _winreg.EnumValue(self.__key, index)[0].lower() == item:
                return True
        return False

################################################################################

class Info(object):

    'Info(key) -> Info'

    def __init__(self, key):
        'Initialize the Info object.'
        self.__key = key
        self.__repr = 'Info(%r)' % key

    def __repr__(self):
        'Return the object\'s representation.'
        return self.__repr

    def __get_keys(self):
        'Private class method.'
        return _winreg.QueryInfoKey(self.__key)[0]

    def __get_values(self):
        'Private class method.'
        return _winreg.QueryInfoKey(self.__key)[1]

    def __get_modified(self):
        'Private class method.'
        return _winreg.QueryInfoKey(self.__key)[2]

    def __get_difference(self):
        'Private class method.'
        return _time.time() + 11644473600.0 - self.modified / 10000000.0

    keys = property(__get_keys, doc='Number of keys.')
    values = property(__get_values, doc='Number of values.')
    modified = property(__get_modified, doc='Time last modified.')
    difference = property(__get_difference, doc='Seconds since modified.')

################################################################################

if __name__ == '__main__':
    def echo(key, prefix=''):
        for name in key.values:
            print '    ' + name + ' = ' + repr(key.values[name])
        for name in key.keys:
            print prefix + '\\' + name
            echo(key.keys[name], prefix + '\\' + name)
    key = '''\
SOFTWARE\\Network Associates\\TVD\\Shared Components\\\
On Access Scanner\\McShield\\Configuration\\Default'''
    server_list = open('server_test.txt')
    for computer in server_list:
        echo(Registry(computer).HKEY_LOCAL_MACHINE.keys[key])
    server_list.close()

rawDescription: Getting registry information using Python


code:
class TheThread(Thread):
    def __init__(self, in_val):

        """Init Worker Thread Class."""
        Thread.__init__(self)

        self.in_val = in_val
        self.start()

    def run(self):
        print self.in_val
        time.sleep(5)

        wx.CallAfter(Publisher.sendMessage, "ctrl")
        """
        threadsafe method to call a pub.subscribe that runs a
        function to re-enable button
        """

rawDescription: How to proper inherit values into thread class with wxPython

description: Proper inherit values into thread class with wxPython


code:
import numpy as np
import pylab as py
from scipy import *  # it is better practice to do: from scipy import module1, module2, etc...
from numpy.fft import fft
import mpl_toolkits.mplot3d.axes3d as p3

def fft2dplot(
    type = 'rect', aperature = 16, method = 'transfer',
    wavelength = 1, distance = 1000000):
    # here you are overwriting the built-in 'dict' suggest using a different variable name
    dict = {
        'rect' : 'Rectangle', 'circ' : 'Circle',
        'transfer' : 'Tranfer Function', 'integral' : 'Integral'}
    #Scale is not correct
    scale = aperature/(distance*wavelength) #in mm
    #Range for aperature,
    x = y = arange(-aperature*8,aperature*8, 1)
    X,Y = np.meshgrid(x,y)
    print len(X)
    # you were losing references to the meshgrid arrays X and Y here.
    # I've provided an alternate method of getting an array of zeros
    # Z = np.zeros(X.shape) works as well
    #X = Y = Z = X*0
    Z = X.copy()
    Z[:,:] = 0

    # Indexing does not work like this.  Indices are unsigned integers 0 and above
    # or a boolean array the same shape as the indexed array.
    #These following statements never enter (type == rect passes, but for loop don't)
##    if type == 'rect':
##        for u in x[-aperature/2:aperature/2]:
##                for w in y[-aperature/2:aperature/2]:
##                    Z[u,w] = 1
##                    print "I'm here"

    # what you need is to define your indices based on your conditions.
    # Here we create a boolean array of indices that indicate where we meet your
    # conditions.
    # Then we use that array to assign those elements of the Z array to the value 1
    idxs = (X>-aperature/2)&(X<aperature/2)&(Y>-aperature/2)&(Y<aperature/2)
    Z[idxs] = 1

    fig = py.figure()
    ax = p3.Axes3D(fig)
    #ax.contour3D(X,Y,Z)
    ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1)
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')
    py.show()

rawDescription: Plotting 3D mesh plot, accessing points in mesh plot array?


code:
from Tkinter import *

# This function will be run every N milliseconds
def get_text(root,val,name):
    # try to open the file and set the value of val to its contents
    try:
        with open(name,"r") as f:
            val.set(f.read())
    except IOError as e:
        print e
    else:
        # schedule the function to be run again after 1000 milliseconds
        root.after(1000,lambda:get_text(root,val,name))

root = Tk()
root.minsize(740,400)
eins = StringVar()
data1 = Label(root, textvariable=eins)
data1.config(font=('times', 37))
data1.pack()
get_text(root,eins,"test.txt")
root.mainloop()

rawDescription: Tkinter label widget not updating when text file changes


code:
import win32gui

MAIN_HWND = 0

def is_win_ok(hwnd, starttext):
    s = win32gui.GetWindowText(hwnd)
    if s.startswith(starttext):
            print s
            global MAIN_HWND
            MAIN_HWND = hwnd
            return None
    return 1

def find_main_window(starttxt):
    global MAIN_HWND
    win32gui.EnumChildWindows(0, is_win_ok, starttxt)
    return MAIN_HWND

def winfun(hwnd, lparam):
    s = win32gui.GetWindowText(hwnd)
    if len(s) > 3:
        print("winfun, child_hwnd: %d   txt: %s" % (hwnd, s))
    return 1

def main():
    main_app = 'EditPlus'
    hwnd = win32gui.FindWindow(None, main_app)
    print hwnd
    if hwnd < 1:
        hwnd = find_main_window(main_app)
    print hwnd
    if hwnd:
        win32gui.EnumChildWindows(hwnd, winfun, None)

main()

rawDescription: python win32gui finding child windows

description: Python win32gui finding child windows


code:
import xml.etree.ElementTree as ET
from collections import Counter,defaultdict

root = ET.ElementTree(file="nwind_medium.xml")

orders = root.findall("./orders")
total = {}
# intalize the default dict here
productdetails=defaultdict(list,{})
for order in orders:
    orderdetails = order.findall("./orderdetails")
    for detail in orderdetails:
        productid = detail.findall("./products/productid")[0].text
        quantity = detail.findall("./quantity")
        supplierid = detail.findall("./suppliers/supplierid")[0].text
        companyname = detail.findall("./suppliers/companyname")[0].text
        productname = detail.findall("./products/productname")[0].text
        #use append to add the details into the product details
        productdetails[productid].append((supplierid,companyname,productname))
        if productid in total.keys():
            total[productid]+=float(quantity[0].text)
        else:

            total[productid]=float(quantity[0].text)

maxprod= Counter(total).most_common(1)[0][0]
print set(productdetails[maxprod])

rawDescription: Elementtree and counter - finding corresponding value


code:
passwd = getpass.getpass()
pid = os.fork()
if pid:
  print 'Parent thinks passwd is', passwd
else:
  print 'Child thinks passwd is', passwd

rawDescription: start python program in the background that can prompt the user for password

description: Start python program in the background that can prompt the user for password


code:
class Parent(object):
    def bar(self):
        print "bar"

class MetaFoo(type):
    def __new__(cls, name, bases, dict):
    	return type(name, (Parent,) + bases, dict)

class Foo(object):
    __metaclass__ = MetaFoo

if __name__ == "__main__":
    f = Foo()
    f.bar()
    print f.bar.func_name

rawDescription: How to add method using metaclass

description: Add method using metaclass


code:
import myModule

import inspect
print inspect.getmembers(myModule, inspect.isclass)

rawDescription: How to get a list of all the classes in one .py file?

description: Get a list of all the classes in one .py file


code:
from tkinter import *
from tkinter import filedialog
guiRoot = Tk()
startDir = "C:\Users\Chidumaga\Music\music"
someFileName = filedialog.askopenfilename(parent=guiRoot,title='Choose a file',initialdir=startDir)
if(someFileName!=""):
    someFile = open(someFileName,'rb')
    #read file contents
    someFile.close()
guiRoot.mainloop()

rawDescription: Manipulating an OS directory with Tkinter


code:
print "Status: 301 Moved",
print "Location:/wherever.com/"

rawDescription: How to redirect to another page in Python in CGIAr

description: Redirect to another page in Python in CGIAr


code:
import wx

class bmpframe(wx.Frame):
    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)

        pnl = wx.Panel(self, -1)
        # lazy way to make two discernable bitmaps
        # Warning: alpha does not work on every platform/version
        bmp1 = wx.EmptyBitmapRGBA(64, 64, alpha=0)
        bmp2 = wx.EmptyBitmapRGBA(64, 64, alpha=1)

        static_bitmap_1 = wx.StaticBitmap(pnl, -1, bitmap=bmp1)
        static_bitmap_2 = wx.StaticBitmap(pnl, -1, bitmap=bmp2)
        self.stbmp1 = static_bitmap_1
        self.stbmp2 = static_bitmap_2

        self.btn_swap = wx.Button(pnl, -1, u'Swap…')

        szmain = wx.BoxSizer(wx.VERTICAL)
        szmain.Add(static_bitmap_1, 0, wx.EXPAND|wx.ALL, 4)
        szmain.Add(static_bitmap_2, 0, wx.EXPAND|wx.ALL, 4)
        szmain.Add(self.btn_swap, 0, wx.EXPAND|wx.ALL, 4)

        pnl.SetSizer(szmain)
        szmain.Fit(self)

        self.btn_swap.Bind(wx.EVT_BUTTON, self.on_swap)

    def on_swap(self, evt):
        print 'EVT_BUTTON'
        bmp1 = self.stbmp1.GetBitmap()
        bmp2 = self.stbmp2.GetBitmap()
        self.stbmp1.SetBitmap(bmp2)
        self.stbmp2.SetBitmap(bmp1)
        self.Refresh()

if __name__ == '__main__':
    app = wx.App(redirect=False)
    frm = bmpframe(None, -1, 'testbmpswap')
    frm.Show()

    app.MainLoop()

rawDescription: wxPython Swap Images

description: WxPython Swap Images


code:
box = [1, 2, 3, 4, 5]

for i in box: #it will go through all elements in the list
    print i, "this is the first loop" #for each different 'i' in box
    for x in box: #it will go through all elements in the list
        print x, "this is the second loop" #you will get all elements from the box
        print (i,x) #this is what you get

rawDescription: How do nested for loops work?

description: How do nested for loops work


code:
from tornado.ioloop import IOLoop
from tornado.web import Application, RequestHandler
import sys

class MainHandler(RequestHandler):

    def get(self):

        self.finish("foo")

application = Application([
    (r"/", MainHandler),
])

def on_stdin(fd, events):

    content = fd.readline()

    print "received: %s" % content

if __name__ == "__main__":

    application.listen(8888)

    IOLoop.instance().add_handler(sys.stdin, on_stdin, IOLoop.READ)

    IOLoop.instance().start()

rawDescription: Handling stdin with tornado

description: Handling stdin with tornado


rawDescription: Beautiful soup and extracting values

description: Beautiful soup and extracting values


code:
import os
p = os.popen('echo '+s+' | ${morphg_res:-./morphg.ix86_linux -t}')
out = p.read()
print out

rawDescription: Correct use of Popen in Python, or something alike


code:
def foo(var):
    print var

s = "foo('This is a test')"

exec s

rawDescription: How can I convert a string to a command in Python?

description: Convert a string to a command in Python


code:
from subprocess import call

while True:
    print call(raw_input("command: "), shell = True)

rawDescription: Command line interface for python

description: Command line interface for python


code:
import time
from datetime import date, timedelta

t=time.strptime('20110531','%Y%m%d')
newdate=date(t.tm_year,t.tm_mon,t.tm_mday)+timedelta(1)
print newdate.strftime('%Y%m%d')

rawDescription: calculating the next day from a "YYYYMMDD" formated string

description: Calculating the next day from a "YYYYMMDD" formated string


code:
def _get_index(self, child):
    """
    Returns the index of the node that the object belongs to.  Returns -1 if the object does not exist in the tree.
    """
    index = -1
    child_position = child.get_position()
    child_radius = child.get_radius()
    if len(child_position) != 2:
        print "Quadtree is only designed to handle two-dimensional objects! Object will not be added."
        return index
    #check if it fits in the top or bottom
    is_in_top_quadrant = child_position[1] - child_radius > self.mid_y and child_position[1] + child_radius < self.max_y
    #check if it fits left
    if child_position[0] + child_radius < self.mid_x and child_position[0] - child_radius > self.min_x:
        if is_in_top_quadrant:
            index = 1
        else:
            index = 2
    #check if it fits right
    if child_position[0] - child_radius > self.mid_x and child_position[0] + child_radius < self.mid_x:
        if is_in_top_quadrant:
            index = 0
        else:
            index = 3
    return index

rawDescription: How to efficiently insert non-point objects into a quadtree

description: Efficiently insert non-point objects into a quadtree


code:
import ast

string1 = "Lorem ipsum dolor sit amet, consectetur adipisicing elit [{'do':'said', 'eiusmod':'tempor', 'incididun':'ut'}]"

string2 = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"

def formatter(content):
    print "content: %s" % content
    if content.find('[') >= 0:
        print "running if"
        attrs = ['do', 'fum']
        ind, indend = content.find('['), content.find(']')
        choice = ast.literal_eval(content[ind+1:indend])
        for attr in attrs:
            for key, value in choice.iteritems():
                if attr == key:
                    new_choice = choice[key]
                    new_string = content[:ind] + new_choice + content[indend+1:]
                    print "calling formatter with: %s" % new_string
                    formatter(new_string)
                    print "back from recursion"
    else:
        print "running else"
        print content
        return content

print "string1"
print formatter(string1)
print "string2"
print formatter(string2)

rawDescription: Having trouble with this recursive function


code:
def abc(hello, hi):
    myli = []
    for i in xrange(len(hello)):
        for j in xrange(len(hi)):
            myli.append([hello[i], hi[j], {"Mydata": str(j)}])
    return myli

hello = ["hello ", "cruel "]
hi = ["hi", "world"]
print abc(hello, hi)

rawDescription: Why the List is not appending the dictionary data into my list?


code:
import wx

class ClassName(wx.Frame):
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, title=title)
        self.panel = wx.Panel(self)
        self.PhotoMaxSize = 240
        self.createWidgets()
        self.Show()

    def createWidgets(self):
        self.palletNumberText = wx.TextCtrl(self.panel, size=(80,-1))

        self.palletNumberText.Bind(wx.EVT_TEXT, self.onPalletNumberText)

    def onPalletNumberText(self, event):
        '''
        save palletNumbertTxt Value when text is entered
        '''
        print self.palletNumberText.GetValue()
        print "This is a test"
        # Store Value

        return

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = ClassName(None, "Test")
    app.MainLoop()

rawDescription: wxpython pass variable to callback event. Lambda land

description: Wxpython pass variable to callback event. Lambda land


code:
import sys
import os
import tkMessageBox
from Tkinter import *
from tkCommonDialog import Dialog
import shutil
import tkFileDialog
import win32com.client

win = Tk()
win.title("Copying the Directory to specified location")
win.geometry("600x600+200+50")
win.resizable()

# force "new" Python class by inheriting from "object"
class Copy(object):

    # use class attributes for shared variables
    src = None
    des = None
    textboxsrc = None
    textboxdes = None

    def srce():
        # access the class attributes via "Copy." syntax
        Copy.src = tkFileDialog.askdirectory(title = "The source folder is ")
        Copy.textboxsrc.delete(0,END)
        Copy.textboxsrc.insert(0,Copy.src)
        print Copy.src
        return Copy.src

    textboxsrc = Entry(win, width="70")
    textboxsrc.insert(0,'Enter master file name')
    textboxsrc.pack()
    textboxsrc.place(relx=0.40, rely=0.06, anchor=CENTER)
    bu = Button(text = "Source",font = "Verdana 12 italic bold",bg = "Purple",fg= "white", command= srce)
    bu.pack(fill =X, expand=YES)
    bu.place(relx=0.85, rely=0.06, anchor=CENTER)

    def dest():
        # access the class attributes via "Copy." syntax
        Copy.des = tkFileDialog.askdirectory(title = "TheDestination folder is ")
        Copy.textboxdes.delete(0,END)
        Copy.textboxdes.insert(0,Copy.des)
        print Copy.des
        return Copy.des

    textboxdes = Entry(win, width="70")
    textboxdes.insert(0,'Enter master file name')
    textboxdes.pack()
    textboxdes.place(relx=0.40, rely=0.13, anchor=CENTER)
    bu1 = Button(text = "Destination",font = "Verdana 12 italic",bg = "Purple",fg= "white", command= dest)
    bu1.pack(fill =X, expand=YES)
    bu1.place(relx=0.85, rely=0.13, anchor=CENTER)

    def start():
        # access the class attributes via "Copy." syntax
        print "copy src(%s) to des(%s)" % (Copy.src,Copy.des)
        try:
            shutil.copy(Copy.src,Copy.des)
        except:
            tkMessageBox.showwarning("Copying file",  "Error while copying\n(%s) to (%s)\n%s\n%s"
            % (Copy.src,Copy.des, sys.exc_info()[0], sys.exc_info()[1]) )

    bn =Button(text = "Copy",font = "Verdana 12 italic", bg = "Purple",fg= "white",command=start)
    bn.pack(fill =X, expand = YES)
    bn.place(relx=0.50, rely=0.25, anchor=CENTER)

obj= Copy()
win.mainloop()

rawDescription: Calling of variable in python

description: Calling of variable in python


code:
import random

counter = 0

while counter < 6:
    oracle = random.randint(6,9)

    if oracle == 6:
       print "__ __~"
    elif oracle == 7:
       print "_____"
    elif oracle == 8:
       print "__ __"
    elif oracle == 9:
       print "_____~"

    counter += 1

rawDescription: Setting loop condition

description: Setting loop condition


code:
from pysnmp.entity.rfc3413.oneliner import cmdgen
from pysnmp.carrier.asynsock.dgram import udp6
import socket

class Udp6TransportTarget(cmdgen.UdpTransportTarget):
    transportDomain = udp6.domainName

    def __init__(self, transportAddr, timeout=1, retries=5):
        self.transportAddr = (
            socket.getaddrinfo(transportAddr[0], transportAddr[1],
                               socket.AF_INET6,
                               socket.SOCK_DGRAM,
                               socket.IPPROTO_UDP)[0][4]
            )
        self.timeout = timeout
        self.retries = retries

    def openClientMode(self):
        self.transport = udp6.Udp6SocketTransport().openClientMode()
        return self.transport

print cmdgen.CommandGenerator().getCmd(
        cmdgen.CommunityData('public'),
        Udp6TransportTarget(('::1', 161)),
        '1.3.6.1.2.1.1.1.0')

rawDescription: ipv6 support in pysnmp

description: Ipv6 support in pysnmp


code:
import sys, os, base64, datetime, hashlib, hmac
import requests
method = 'GET'
service = 's3'
host = 's3-us-west-2.amazonaws.com'
region = 'us-west-2'
endpoint = 'http://s3-us-west-2.amazonaws.com'
request_parameters = ''

def sign(key, msg):
    return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

def getSignatureKey(key, dateStamp, regionName, serviceName):
    kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
    kRegion = sign(kDate, regionName)
    kService = sign(kRegion, serviceName)
    kSigning = sign(kService, 'aws4_request')
    return kSigning

access_key = os.environ.get('AWS_ACCESS_KEY_ID')
secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')
if access_key is None or secret_key is None:
    print 'No access key is available.'
    sys.exit()

t = datetime.datetime.utcnow()
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope

canonical_uri = '/bucket/key'
canonical_querystring = request_parameters
canonical_headers = 'host:' + host + '\n' + 'x-amz-content-sha256:UNSIGNED-PAYLOAD' + '\n' + 'x-amz-date:' + amzdate + '\n'
signed_headers = 'host;x-amz-content-sha256;x-amz-date'
payload_hash = 'UNSIGNED-PAYLOAD'
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + payload_hash
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' +  amzdate + '\n' +  credential_scope + '\n' +  hashlib.sha256(canonical_request).hexdigest()
signing_key = getSignatureKey(secret_key, datestamp, region, service)
signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' +  'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature
headers = {'x-amz-date':amzdate, 'x-amz-content-sha256': 'UNSIGNED-PAYLOAD', 'Authorization':authorization_header}
request_url = endpoint + canonical_uri

print '\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++'
print 'Request URL = ' + request_url
r = requests.get(request_url, headers=headers)

print '\nRESPONSE++++++++++++++++++++++++++++++++++++'
print 'Response code: %d\n' % r.status_code
print r.text

rawDescription: Problems doing a get on a s3 bucket with python


code:
import urllib
import urllib2

url = 'someurl.php'
values = {'site' : 'name1place1', 'size' : '8'}

sites_file = 'path/to/sites_file'
with open(sites_file, 'r') as sites:
    for site_value in sites: # This pulls each line out the file

        # Remove trailing whitespace or '\n' from site and replace value in dict
        values['site'] = site_value.rstrip()
        data = urllib.urlencode(values)
        req = urllib2.Request(url, data)
        response = urllib2.urlopen(req)
        the_page = response.read()
        print the_page

rawDescription: Changing a value in a dictionary to be imported from a list and cycle through, with urllib2


code:
phrasewords = [w.text for w in phrase.findall('V')+phrase.findall('N')+phrase.findall('PREP')]
for words in finalPatterns:
    if all(word in phrasewords for word in words.split()):
         print "found"

rawDescription: Searching for a list of words in XML file in Python?


code:
def get_ref(ref_attr):
    item = f
    for attr in ref_attr.split('.'):
        item = getattr(item, attr)
        print item

rawDescription: What's the best way to get referenced object (variable level)


code:
class counter(object):
    def __init__(self, current=0):
        self.current = current

    def __iter__(self):
        def iter():
            while True:
                yield self.current
                self.current += 1 #
        return iter()

    def set(self,x):
        self.current = x

s = counter()
t = iter(s)
print t.next() # 0
s.set(20)
print t.next() # 21

rawDescription: Can iterator be restored and can its value/status be assigned?


code:
import netsnmp
import binascii

session = netsnmp.Session(Community='public', DestHost='myagentip', Version=1)
vbwithbinarydata = netsnmp.VarBind('oid_to_binary_data')
varlist = netsnmp.Varlist(vbwithbinarydata)
session.get(varlist)
print binascii.b2a_hex(vbwithbinarydata.val)

rawDescription: Printing hex-string format variable in python


rawDescription: Python, simple string ordering by datetime


code:
tk=Tk()
tk.withdraw()

def fileupload():
    while True:
        uploadedfilenames = askopenfilenames(multiple=True)
        if uploadedfilenames == '':
            tkMessageBox.showinfo(message="File Upload has been cancelled program will stop")
            return
        uploadedfiles = tk.splitlist(uploadedfilenames)
        if len(uploadedfiles)!=2:
           tkMessageBox.showinfo(message="2 files have not been selected!")
        else:
            return uploadedfiles

print fileupload()

rawDescription: Python File Upload If statement and user cancelation


code:
import sys, re

expS=re.compile(r'\s*//\s*loopId = (\d+); depth = \d+; \w+')
expE=re.compile(r'\s*//\s*end loop \(loopId = (\d+)\)')
lines, varcnt = [], 0
with open(sys.argv[1]) as f:
    for line in f:
        line = line.rstrip()
        lines += [ line ]
        m = re.match(expS, line)
        if m:
            varcnt += 1
            loopid = int(m.group(1))
            lines += [ 'gettimeofday(&tv[{}], 0);'.format((loopid-1)*2) ]
            continue
        m = re.match(expE, line)
        if m:
            loopid = int(m.group(1))
            sid, eid = (loopid-1)*2, (loopid-1)*2+1
            lines += [ 'gettimeofday(&tv[{}], 0);'.format(eid) ]
            lines += [ 'printf("Id {}: %ld\\n", tdiff_xxx(&tv[{}],&tv[{}]));'.format(
                loopid, sid, eid) ]

print '#include <sys/time.h>'
print 'struct timeval tv[{}];'.format(varcnt*2)
print 'long tdiff_xxx(struct timeval *t0, struct timeval *t1) {'
print '  return (t1->tv_sec-t0->tv_sec)*1000000 + t1->tv_usec-t0->tv_usec;'
print '}'
for l in lines: print l

rawDescription: adding lines in C code using Python script

description: Adding lines in C code using Python script


code:
from mymodule import version, myclass
print version
instance = myclass.MyClassWithCtor(1, 2)

rawDescription: Python: Printing a variable delcared in __init__.py after importing a class


code:
from dateutil.parser import *
import datetime

date1="2016-04-11 19:46:46-04:00"
date2=datetime.datetime.now()
updated_date1=parse(date1, ignoretz=True) #Ignoring TimeZone
updated_date2=parse(str(date2))
result=updated_date2 - updated_date1
print result

rawDescription: Subtracting two time moments specified as strings


code:
corrected
def config(name, description, default=None):
    ComponentMeta.config_items.append((name, description, default))

class ComponentMeta(type):
    config_items = []
    def __init__(cls, clsname, bases, clsdict):
        for options in ComponentMeta.config_items:
                cls.add_config(*options)
        ComponentMeta.config_items = []

class Component(object):
    __metaclass__ = ComponentMeta
    config_items = [] # this is only for testing. you don't need it
    @classmethod
    def add_config(cls, name, description, default=None):
        #also for testing
        cls.config_items.append((name, description, default))

class Model1(Component):
    config('n', 'number of burz to instigate')
    config('skip', 'skip any barz in the data', default=True)

print Model1.config_items

rawDescription: Associating properties to Class objects

description: Associating properties to Class objects


code:
initial_list, temp_list = [], []
for line in open(filename):
    if line.strip() == '':
        initial_list.append(temp_list)
        temp_list = []
    else: temp_list.append(line.strip())
if len(temp_list) > 0: initial_list.append(temp_list)
final_list = [item for item in initial_list if len(item) > 0]
print final_list

rawDescription: for loops on text files

description: For loops on text files


code:
import wx, wx.grid

class GridData(wx.grid.PyGridTableBase):
    _cols = "a b c".split()
    _data = [
        "1 2 3".split(),
        "4 5 6".split(),
        "7 8 9".split()
    ]

    def GetColLabelValue(self, col):
        return self._cols[col]

    def GetNumberRows(self):
        return len(self._data)

    def GetNumberCols(self):
        return len(self._cols)

    def GetValue(self, row, col):
        return self._data[row][col]

    def SetValue(self, row, col, val):
        self._data[row][col] = val

class Test(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        self.data = GridData()
        grid = wx.grid.Grid(self)
        grid.SetTable(self.data)
        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.Show()

    def OnClose(self, event):
        print self.data._data
        event.Skip()

app = wx.PySimpleApp()
app.TopWindow = Test()
app.MainLoop()

rawDescription: wxpython: Updating a dict or other appropriate data type from wx.lib.sheet.CSheet object

description: Wxpython: Updating a dict or other appropriate data type from wx.lib.sheet.CSheet object


code:
while True:
    title_selection = raw_input("Please type in the number of your title and press Enter.\n%s" % (raw_input_string))
    if title_selection:
        break
    print "Sorry, you have to enter something."

rawDescription: Force a raw_input

description: Force a raw_input


code:
import sqlite3
cur = sqlite3.connect('filename.db').cursor()
query = cur.execute('SELECT * FROM A_TABLE')
colname = [ d[0] for d in query.description ]
result_list = [ dict(zip(colname, r)) for r in query.fetchall() ]
cur.close()
cur.connection.close()
print result_list

rawDescription: How to build a list of dicts from a SQLite3 database query in Python?

description: Build a list of dicts from a SQLite3 database query in Python


code:
from fogbugz import FogBugz
import fbSettings

fb = FogBugz(fbSettings.URL, fbSettings.TOKEN)

resp = fb.search(q='project:"Python Testing"',cols='ixBug')

# printing
for case in resp.cases.findAll('case'):
    print case.ixbug.string

# store in a list
l = [case.ixbug.string for case in resp.cases.findAll('case')]

rawDescription: How to parse an XML file with multiple non-specific elements

description: Parse an XML file with multiple non-specific elements


code:
import subprocess

if "SchoolWifiName" in subprocess.check_output("netsh wlan show interfaces"):
    print "I am on school wifi!"

rawDescription: How do I get Python to know what Wifi the user is connected to?

description: Get Python to know what Wifi the user is connected to


code:
def a():
    return "test"

class b:
    def c(self):
        x = a()
        print x

b().c()  # prints "test"

rawDescription: How to access a function defined globaly outside of the class

description: Access a function defined globaly outside of the class


code:
print '{:.{prec}f}'.format(12.345, prec=2)
print '{:.{prec}f}'.format(12.345, prec=1)

rawDescription: Passing precision to python's .format method


code:
total = 0
for line in myfile:
    m = re.findall(pattern, line)
    total += len(m)

print total

rawDescription: Python adding up the length of lists of number


code:
import MySQLdb as mysql
import csv

con = mysql.connect('localhost','user','password','dbname')
cur = con.cursor()

q = "select x, y,z from tablet_vendors where a=%s and b=%s"

with open('somefile.txt') as f:
  rows = csv.reader(f,delimiter='\t')
  for row in rows:
     cur.execute(q,row)
     result = cur.fetchone()
     while result:
        print result
        result = cur.fetchone()

rawDescription: Scripting mysql for retrieving data in a loop