code:
# A sample context menu handler.
# Adds a menu item with sub menu to all files and folders, different options inside specified folder.
# When clicked a list of selected items is displayed.
#
# To demostrate:
# * Execute this script to register the context menu. `python context_menu.py --register`
# * Restart explorer.exe- in the task manager end process on explorer.exe. Then file > new task, then type explorer.exe
# * Open Windows Explorer, and browse to a file/directory.
# * Right-Click file/folder - locate and click on an option under 'Menu options'.

import os
import pythoncom
from win32com.shell import shell, shellcon
import win32gui
import win32con
import win32api

class ShellExtension:
    _reg_progid_ = "Python.ShellExtension.ContextMenu"
    _reg_desc_ = "Python Sample Shell Extension (context menu)"
    _reg_clsid_ = "{CED0336C-C9EE-4a7f-8D7F-C660393C381F}"
    _com_interfaces_ = [shell.IID_IShellExtInit, shell.IID_IContextMenu]
    _public_methods_ = shellcon.IContextMenu_Methods + shellcon.IShellExtInit_Methods

    def Initialize(self, folder, dataobj, hkey):
        print "Init", folder, dataobj, hkey
        win32gui.InitCommonControls()
        self.brand= "Menu options"
        self.folder= "C:\\Users\\Paul\\"
        self.dataobj = dataobj
        self.hicon= self.prep_menu_icon(r"C:\path\to\icon.ico")

    def QueryContextMenu(self, hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags):
        print "QCM", hMenu, indexMenu, idCmdFirst, idCmdLast, uFlags

        # Query the items clicked on
        files= self.getFilesSelected()

        fname = files[0]
        idCmd = idCmdFirst

        isdir= os.path.isdir(fname)
        in_folder= all([f_path.startswith(self.folder) for f_path in files])

        win32gui.InsertMenu(hMenu, indexMenu,
            win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
            0, None)
        indexMenu += 1

        menu= win32gui.CreatePopupMenu()
        win32gui.InsertMenu(hMenu,indexMenu,win32con.MF_STRING|win32con.MF_BYPOSITION|win32con.MF_POPUP,menu,self.brand)
        win32gui.SetMenuItemBitmaps(hMenu,menu,0,self.hicon,self.hicon)
#        idCmd+=1
        indexMenu+=1

        if in_folder:
            if len(files) == 1:
                if isdir:
                    win32gui.InsertMenu(menu,0,win32con.MF_STRING,idCmd,"Item 1"); idCmd+=1
                else:
                    win32gui.InsertMenu(menu,0,win32con.MF_STRING,idCmd,"Item 2")
                    win32gui.SetMenuItemBitmaps(menu,idCmd,0,self.hicon,self.hicon)
                    idCmd+=1
        else:
            win32gui.InsertMenu(menu,0,win32con.MF_STRING,idCmd,"Item 3")
            win32gui.SetMenuItemBitmaps(menu,idCmd,0,self.hicon,self.hicon)
            idCmd+=1

        if idCmd > idCmdFirst:
            win32gui.InsertMenu(menu,1,win32con.MF_SEPARATOR,0,None)

        win32gui.InsertMenu(menu,2,win32con.MF_STRING,idCmd,"Item 4")
        win32gui.SetMenuItemBitmaps(menu,idCmd,0,self.hicon,self.hicon)
        idCmd+=1
        win32gui.InsertMenu(menu,3,win32con.MF_STRING,idCmd,"Item 5")
        win32gui.SetMenuItemBitmaps(menu,idCmd,0,self.hicon,self.hicon)
        idCmd+=1

        win32gui.InsertMenu(menu,4,win32con.MF_SEPARATOR,0,None)

        win32gui.InsertMenu(menu,5,win32con.MF_STRING|win32con.MF_DISABLED,idCmd,"Item 6")
        win32gui.SetMenuItemBitmaps(menu,idCmd,0,self.hicon,self.hicon)
        idCmd+=1

        win32gui.InsertMenu(hMenu, indexMenu,
                            win32con.MF_SEPARATOR|win32con.MF_BYPOSITION,
                            0, None)
        indexMenu += 1
        return idCmd-idCmdFirst # Must return number of menu items we added.

    def getFilesSelected(self):
        format_etc = win32con.CF_HDROP, None, 1, -1, pythoncom.TYMED_HGLOBAL
        sm = self.dataobj.GetData(format_etc)
        num_files = shell.DragQueryFile(sm.data_handle, -1)
        files= []
        for i in xrange(num_files):
            fpath= shell.DragQueryFile(sm.data_handle,i)
            files.append(fpath)
        return files

    def prep_menu_icon(self, icon): #Couldn't get this to work with pngs, only ico
        # First load the icon.
        ico_x = win32api.GetSystemMetrics(win32con.SM_CXSMICON)
        ico_y = win32api.GetSystemMetrics(win32con.SM_CYSMICON)
        hicon = win32gui.LoadImage(0, icon, win32con.IMAGE_ICON, ico_x, ico_y, win32con.LR_LOADFROMFILE)

        hdcBitmap = win32gui.CreateCompatibleDC(0)
        hdcScreen = win32gui.GetDC(0)
        hbm = win32gui.CreateCompatibleBitmap(hdcScreen, ico_x, ico_y)
        hbmOld = win32gui.SelectObject(hdcBitmap, hbm)
        # Fill the background.
        brush = win32gui.GetSysColorBrush(win32con.COLOR_MENU)
        win32gui.FillRect(hdcBitmap, (0, 0, 16, 16), brush)
        # unclear if brush needs to be feed.  Best clue I can find is:
        # "GetSysColorBrush returns a cached brush instead of allocating a new
        # one." - implies no DeleteObject
        # draw the icon
        win32gui.DrawIconEx(hdcBitmap, 0, 0, hicon, ico_x, ico_y, 0, 0, win32con.DI_NORMAL)
        win32gui.SelectObject(hdcBitmap, hbmOld)
        win32gui.DeleteDC(hdcBitmap)

        return hbm

    def InvokeCommand(self, ci):
        mask, hwnd, verb, params, dir, nShow, hotkey, hicon = ci
        win32gui.MessageBox(hwnd, str(self.getFilesSelected()), "Wow", win32con.MB_OK)

    def GetCommandString(self, cmd, typ):
        # If GetCommandString returns the same string for all items then
        # the shell seems to ignore all but one.  This is even true in
        # Win7 etc where there is no status bar (and hence this string seems
        # ignored)
        return "Hello from Python (cmd=%d)!!" % (cmd,)

def DllRegisterServer():
    import _winreg
    folder_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT,
    "Folder\\shellex")
    folder_subkey = _winreg.CreateKey(folder_key, "ContextMenuHandlers")
    folder_subkey2 = _winreg.CreateKey(folder_subkey, "PythonSample")
    _winreg.SetValueEx(folder_subkey2, None, 0, _winreg.REG_SZ,
    ShellExtension._reg_clsid_)

    file_key = _winreg.CreateKey(_winreg.HKEY_CLASSES_ROOT,
    "*\\shellex")
    file_subkey = _winreg.CreateKey(file_key, "ContextMenuHandlers")
    file_subkey2 = _winreg.CreateKey(file_subkey, "PythonSample")
    _winreg.SetValueEx(file_subkey2, None, 0, _winreg.REG_SZ,
    ShellExtension._reg_clsid_)

    print ShellExtension._reg_desc_, "registration complete."

def DllUnregisterServer():
    import _winreg
    try:
        folder_key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,

        "Folder\\shellex\\ContextMenuHandlers\\PythonSample")
        file_key = _winreg.DeleteKey(_winreg.HKEY_CLASSES_ROOT,

        "*\\shellex\\ContextMenuHandlers\\PythonSample")
    except WindowsError, details:
        import errno
        if details.errno != errno.ENOENT:
            raise
    print ShellExtension._reg_desc_, "unregistration complete."

if __name__=='__main__':
    from win32com.server import register
    register.UseCommandLine(ShellExtension,
                   finalize_register = DllRegisterServer,
                   finalize_unregister = DllUnregisterServer)

rawDescription: Windows explorer context menus with sub-menus using pywin32


code:
a = np.array([123, 412, 444])
b = np.array([123, 321])
diff = np.setdiff1d(b, a)
print diff
if diff.size:
   print "Not passed"

rawDescription: Numpy: How to check if array contains certain numbers?


code:
def f():
    e=int(raw_input('enter number'))
    if e in range (12):
        print 'co'
    elif e in range (12,20):
        print 'co2'
    elif e in range (-10,0,1):
        print 'co3'

f()

rawDescription: Python input does not compare properly

description: Python input does not compare properly


code:
import pandas as pd
import numpy as np
import multiprocessing as mp
import time

def compute(start, end):
    sub = df.iloc[start:end]
    return start, end, np.abs(sub['column_01']+sub['column_01']) / 2

def collate(retval):
    start, end, arr = retval
    df.ix[start:end, 'new_column'] = arr

def window(seq, n=2):
    """
    Returns a sliding window (of width n) over data from the sequence
    s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...
    """
    for i in range(len(seq)-n+1):
        yield tuple(seq[i:i+n])

if __name__ == "__main__":
    result = []
    # the record count of the real data is over 1 billion with about 10 columns.
    N = 10**3
    df = pd.DataFrame(np.random.randn(N, 4),
                      columns=['column_01', 'column_02', 'column_03', 'column_04'])

    pool = mp.Pool()
    df['new_column'] = np.empty(N, dtype='float')

    start_time = time.time()
    idx = np.linspace(0, N, 5+1).astype('int')
    for start, end in window(idx, 2):
        # print(start, end)
        pool.apply_async(compute, args=[start, end], callback=collate)

    pool.close()
    pool.join()
    print 'elapsed time  : ', np.round(time.time() - start_time,3)
    print(df.head())

rawDescription: Is there a good way to avoid memory deep copy or to reduce time spent in multiprocessing?


code:
import threading
import random
import time
import Queue
import urllib2
import sys
import simplejson, pycurl
import sys, signal

queue = Queue.Queue()
keep_running = True
user = "" # username
pswd = "" # password
headers = [ "Content-Type: text/xml; charset: UTF-8; "]

class MyThread(threading.Thread):

    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
        self.buffer = ""
        self.streaming_url = "https://stream.twitter.com/1/statuses/filter.json?track=justinbieber"

    def start_crawl(self, user, pswd):
        self.conn = pycurl.Curl()
        self.conn.setopt(pycurl.USERPWD, "%s:%s" % (user, pswd))
        self.conn.setopt(pycurl.URL, self.streaming_url)
        #self.conn.setopt(pycurl.POST, 1)
        self.conn.setopt(pycurl.HTTPHEADER, headers)
        self.conn.setopt(pycurl.READFUNCTION, self.storage)
        self.conn.setopt(pycurl.VERBOSE, 1)
        self.conn.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
        self.conn.perform()

    def storage(self, data):
        self.buffer += str(data)
        if isinstance(self.buffer, str):
            if self.buffer.endswith("\r\n") and self.buffer.strip():
                content = json.loads(self.buffer)
                self.buffer = ""
                self.queue.put(content)
                self.queue.task_done()
                #if "text" in content:
                    #print u"{0[user][name]}: {0[text]}".format(content)
        else:
            return data

    def run(self):
        while keep_running:
            self.start_crawl(user,pswd)
            if signal.signal(signal.SIGINT, signal.SIG_DFL):
                sys.exit()
            #line = self.names[random.randint(0,len(self.names)-1)]
            #queue.put(line)

class Starter():
    def __init__(self):
        self.queue = queue
        t = MyThread(self.queue)
        t.daemon = True
        t.start()
        self.next()

    def next(self):
        while True:
            time.sleep(0.1)
            if not self.queue.empty():
                line = self.queue.get(timeout=0.2)
                print line, self.queue.qsize()
            else:
                print 'waiting for queue'

def main():
    try:
        Starter()
        queue.join()
    except KeyboardInterrupt, e:
        print 'Stopping'
        raise

main()

rawDescription: Still can't stop the Thread

description: Still can't stop the Thread


code:
N = 6
a = range(N)
for i in xrange(N-1):
    print zip(a[:N/2], reversed(a[N/2:]))
    a = a[:1] + a[-1:] + a[1:-1]

rawDescription: python matching up items in a list to create new lists

description: Python matching up items in a list to create new lists


code:
class Me(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        #flag to pause thread
        self.paused = False
        # Explicitly using Lock over RLock since the use of self.paused
        # break reentrancy anyway, and I believe using Lock could allow
        # one thread to pause the worker, while another resumes; haven't
        # checked if Condition imposes additional limitations that would
        # prevent that. In Python 2, use of Lock instead of RLock also
        # boosts performance.
        self.pause_cond = threading.Condition(threading.Lock())

    def run(self):
        while True:
            with self.pause_cond:
                while self.paused:
                    self.pause_cond.wait()

                #thread should do the thing if
                #not paused
                print 'do the thing'
            time.sleep(5)

    def pause(self):
        self.paused = True
        # If in sleep, we acquire immediately, otherwise we wait for thread
        # to release condition. In race, worker will still see self.paused
        # and begin waiting until it's set back to False
        self.pause_cond.acquire()

    #should just resume the thread
    def resume(self):
        self.paused = False
        # Notify so thread will wake after lock released
        self.pause_cond.notify()
        # Now release the lock
        self.pause_cond.release()

rawDescription: Python - Thread that I can pause and resume


code:
def dup_pkt(pkt):
    pprint.pprint(pkt)
    if pkt[IP].dst == '10.0.0.1':
        pkts = []
        for ip in ips:
            pkt2 = pkt.copy() # use the copy method rather than copy.deepcopy
            pkt2[IP].dst = ip
            pkts.append(pkt2)
            print "Packet1: ", pkt[IP].dst, " Packet2: ", pkt2[IP].dst
        send(pkts) # send all packets at once

rawDescription: What is the best way to fork scapy in order to duplicate packets


code:
from splinter import Browser

browser = Browser('firefox', wait_time=10)
browser.visit("http://databases.lovd.nl/shared/variants")

# move over the menu "Variant"
browser.find_by_id('tab_variants').mouse_over()
# move over the sub menu
browser.find_by_id('menu_tab_variants').mouse_over()

# print the menu items visibility
print browser.find_link_by_text("View all genomic variants").visible
print browser.find_link_by_text("View all variants affecting transcripts").visible

# move the mouse out of the sub menu
browser.find_by_id('menu_tab_variants').mouse_out()

# print the menu items visibility
print browser.find_link_by_text("View all genomic variants").visible
print browser.find_link_by_text("View all variants affecting transcripts").visible

rawDescription: Using Splinter to select from a dynamic menu


code:
print part
print "Filename:", dir_entry_path
print "Start line of file:", list(my_file)[0]
if len(list(my_file)) > 1:
    print "End line of file:", list(my_file)[-1]

rawDescription: python open directory,read and print filename

description: Python open directory,read and print filename


rawDescription: How to retrieve my unicode from the unicode byte representation

description: Retrieve my unicode from the unicode byte representation


code:
def removeDots (x):
    p = []
    for i in x:
        p.append((i[0],i[1].replace(":","\\:")))
    return p

x = [('Hello:bye','Hello:bye'),
    ('Bye:Hello','Bye:Hello')]

print x
print removeDots(x)

rawDescription: Append to a tuple of a array

description: Append to a tuple of a array


code:
class calc:

    def add (self, a,b):
        add = a + b
        print add

    def sub (self, a,b):
        sub = a-b
        print sub

rawDescription: Calling method from a class in different file


code:
import datetime
import matplotlib.mlab

print matplotlib.mlab.csv2rec('data.csv', converterd={
    0: lambda x: datetime.datetime.strptime(x, '%d.%m.%Y %H:%M'),
})

rawDescription: How to specify date-format using csv2rec-method

description: Specify date-format using csv2rec-method


code:
#!/usr/bin/python

import threading
import time

def target1():
    time.sleep(0.1)
    print "target1 running"
    time.sleep(4)

def target2():
    time.sleep(0.1)
    print "target2 running"
    time.sleep(2)

def launch_thread_with_message(target, message, args=[], kwargs={}):
    def target_with_msg(*args, **kwargs):
        target(*args, **kwargs)
        print message
    thread = threading.Thread(target=target_with_msg, args=args, kwargs=kwargs)
    thread.start()
    return thread

if __name__ == '__main__':
    thread1 = launch_thread_with_message(target1, "finished target1")
    thread2 = launch_thread_with_message(target2, "finished target2")

    print "main: launched all threads"

    thread1.join()
    thread2.join()

    print "main: finished all threads"

rawDescription: In Python threading, how I can I track a thread's completion?


code:
b2=bin[:-1]
print mean(a), var(a), scipy.stats.skew(a)
dist = scipy.stats.rv_discrete(values=(b2,n))
print dist.stats(moments='mvsk')

rawDescription: Get original data array from probability density values and bins of numpy histogram


code:
import random
sampleMassDist = (0.2, 0.1, 0.15, 0.15, 0.25, 0.15)

# assume sum of bias is 1
def roll(massDist):
    randRoll = random.random() # in [0,1)
    sum = 0
    result = 1
    for mass in massDist:
        sum += mass
        if randRoll < sum:
            return result
        result+=1

print roll(sampleMassDist)

rawDescription: How do I simulate biased die in python?

description: Simulate biased die in python


code:
import pygame
import pygame.locals

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

# one image -> 7 subsurfaces

sheet = pygame.image.load('explosed-sprite.png').convert_alpha()

imgs = []

for x in range(7):
    imgs.append( sheet.subsurface((20*x,0,20,20)) )

current_img = 0

# clock - FPS

clock = pygame.time.Clock()

# mainloop

running = True

while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False

    # next image modulo 7
    current_img = ( current_img + 1 ) % 7

    screen.fill( (0,0,0) )
    screen.blit( imgs[current_img], (150-10,150-10) )
    pygame.display.flip()

    clock.tick(12)

# save subsurfaces as separated images

for x in range(7):
    name = 'frame_' + str(x) + '.png'
    pygame.image.save( imgs[x], 'frame_' + str(x) + '.png' )
    print name, 'saved'

# the end
pygame.quit()

rawDescription: What is the best thing to use to seperate images on sprite sheets?


code:
print "paste quote:"
emptycount = 0
lines = []

while emptycount < 2:
    t = raw_input()
    if len(t) == 0:
        emptycount +=1
    else:
        emptycount=0
        lines.append(t)
        lines.append("\n")

print " ".join(lines[:-1])

rawDescription: Problem with reading pasted text in terminal


code:
CLName = raw_input ("\n\nEnter 7 digits CL number !")

if os.path.isdir("/abc/Compiler_Builds/something/%s" % CLName):
              print  "CL Exists"

rawDescription: If a location exist with os.path.isdir by passing a user input variable


code:
data = range(10)

chunk_size = 10

while data:
    sublist, data = data[:chunk_size], data[chunk_size:]

    # Handle subplit
    print sublist

rawDescription: splitting a tuple to use values as filter in sql query

description: Splitting a tuple to use values as filter in sql query


code:
#!/usr/bin/env python

import re, fnmatch, glob

def pat_translate(pat):
    """Translate a shell PATTERN to a regular expression.

    There is no way to quote meta-characters.
    Hacked to add capture groups
    """
    i, n = 0, len(pat)
    res = ''
    while i < n:
        c = pat[i]
        i = i+1
        if c == '*':
            res = res + '(.*)'
        elif c == '?':
            res = res + '(.)'
        elif c == '[':
            j = i
            if j < n and pat[j] == '!':
                j = j+1
            if j < n and pat[j] == ']':
                j = j+1
            while j < n and pat[j] != ']':
                j = j+1
            if j >= n:
                res = res + '\\['
            else:
                stuff = pat[i:j].replace('\\','\\\\')
                i = j+1
                if stuff[0] == '!':
                    stuff = '^' + stuff[1:]
                elif stuff[0] == '^':
                    stuff = '\\' + stuff
                res = '%s([%s])' % (res, stuff)
        else:
            res = res + re.escape(c)
    return res + '\Z(?ms)'

def test(shell_pat):
    print 'Shell pattern %r' % shell_pat
    names = glob.glob(shell_pat)
    print 'Found', names
    regex = pat_translate(shell_pat)
    print 'Regex %r' % regex
    pat = re.compile(regex)
    groups = [pat.match(name).groups() for name in names]
    print 'name, groups'
    for name, row in zip(names, groups):
        print name, row

rawDescription: extracting all expansions from python's glob

description: Extracting all expansions from python's glob


code:
from time import time
import numpy as np

# Create 100 images of the same dimention 256x512 (8-bit).
# In reality, each image comes from a different file
img = np.random.randint(0,255,(100, 256, 512))

# counter-intuitive but preallocation is slightly slower
stacked = np.empty((100, 256, 512))
t0 = time()
for n in range(100):
    stacked[n] = img[n]
print time()-t0
print stacked.shape

rawDescription: stack images as numpy array faster (than preallocation)?

description: Stack images as numpy array faster (than preallocation)


code:
with open("data1.txt") as f:
    lines=f.read()
    spl=lines.split("<NEW ARTICLE>")[1:]
    dic=dict((i,x.strip()) for i,x in enumerate(spl))
    print dic

rawDescription: Creating a Dictionary from File

description: Creating a Dictionary from File


code:
import urllib2, httplib
from BeautifulSoup import BeautifulSoup

def append_log(message):
    print message

def get_web_page(address):
    try:
        user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
        headers = { 'User-Agent' : user_agent }
        request = urllib2.Request(address, None, headers)
        response = urllib2.urlopen(request, timeout=20)
        try:
            return response.read()
        finally:
            response.close()
    except urllib2.HTTPError as e:
        error_desc = httplib.responses.get(e.code, '')
        append_log('HTTP Error: ' + str(e.code) + ': ' +
                  error_desc + ': ' + address)
    except urllib2.URLError as e:
        append_log('URL Error: ' + e.reason[1] + ': ' + address)
    except Exception as e:
        append_log('Unknown Error: ' + str(e) + address)

def process_web_page(data):
    if data is not None:
        print BeautifulSoup(data)
    else:
        pass # do something else

data = get_web_page('http://doesnotexistblah.com/')
process_web_page(data)

data = get_web_page('http://docs.python.org/copyright.html')
process_web_page(data)

rawDescription: How to handle when webpage does not load on BeautifulSoup

description: Handle when webpage does not load on BeautifulSoup


code: print filter(isPrime, range(200))

rawDescription: Python: Getting the Sum of a Lambda Function


code:
with open('1.csv') as file:
    reader = csv.reader(file)
    col1s = []; col2s = []
    for row in reader:
            if "$GPGGA" in row:
                    col1s.append((row[0], row[1], row[2], row[5]))
            elif "$GPVTG" in row:
                    col2s.append((row[0], row[1], row[2]))
    for each in zip(col1s, col2s):
            print each[0] + each[1]

rawDescription: combine selected lines/rows within a csv file

description: Combine selected lines/rows within a csv file


code:
#!/usr/bin/python

x={'123':[[1,3,2015],[2,5,2014],[1,5,2015]],'987':[[3,55,2014]],'456':[[1,37,2015]]}

#Set query dates
query_month = 1 #jan
query_year = 2015 #year

#Set a counter
jan_counts = 0
for list_of_dates in x.values():
    for date in list_of_dates:
        if (date[0] == query_month) and (date[2] == query_year):
            jan_counts += 1
print jan_counts
#3

rawDescription: Counting particular item in defaultdict list


code:
import random

print "\tWelcome to 'Guess My Number'!"
print "\nI'm thinking of a number between 1 and 100."
print "Try to guess it in as few attempts as possible.\n"

# set the initial values
the_number = random.randrange(100) + 1

limit = 5
tries = 0

# guessing loop
while True: # we will test the conditions separately in the loop, not here
    # take a guess
    guess = int(raw_input("Take a guess: "))
    tries += 1

    # first check the number
    if (guess > the_number):
        print "Lower..."
    elif (guess < the_number):
        print "Higher..."
    else: # it can only be equal here
        print "You guessed it!  The number was", the_number
        print "And it only took you", tries, "tries!\n"
        break # exit the while loop

    # now the tries:
    if tries == limit:
        print "You've used all %d of your attempts \
and didn't get the right answer. Shame on You!" % limit
        break

raw_input("\n\nPress the enter key to exit.")

rawDescription: Python Programming for the Absolute Beginner


code:
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons

class Example:

    def onColor(self,label):
        self.cstates[label] = not self.cstates[label]
        print 'un'*(not self.cstates[label]) + 'checked %s' %label
        self.updateChart()

    def onMeasurement(self,label):
        self.mstates[label] = not self.mstates[label]
        print 'un'*(not self.mstates[label]) + 'checked %s' %label
        self.updateChart()

    def updateChart(self, event=None):
        """do something here using self.cstates and self.mstates?"""
        pass

    def __init__(self):
        colourax = plt.axes([0.5, 0.4, 0.09, 0.2])
        measurementax = plt.axes([0.5, 0.6, 0.09, 0.2])
        clabels, cvals = ('Red', 'Green', 'Blue'), (False,)*3
        mlabels, mvals = ('1', '2', '3'), (False,)*3
        self.cstates = dict(zip(clabels,cvals))
        self.mstates = dict(zip(mlabels,mvals))
        self.colours = CheckButtons(colourax, clabels, cvals)
        self.colours.on_clicked(self.onColor)
        self.measurements = CheckButtons(measurementax, mlabels, mvals)
        self.measurements.on_clicked(self.onMeasurement)

    def run(self):
        plt.show()

ex = Example()
ex.run()

rawDescription: Retrieving the selected values from a CheckButtons object in matplotlib


code:
import sys

lists = {
    "list1": ["A", "B", "C"],
    "list2": [1, 2, 3],
}

myarg = sys.argv[1]
print len(lists[myarg])

rawDescription: Python - Use a variable as a list name

description: Python - Use a variable as a list name


code:
from pyquery import PyQuery as pq
html = pq("""<div class='head'> Article TExt <div> <tag> Some ather text </tag>""")
print html('div.head').text()

rawDescription: How can I find tag with regular expression. Python

description: Find tag with regular expression. Python


code:
from sqlalchemy.sql.expression import ColumnElement, _literal_as_column
from sqlalchemy.dialects import postgresql
from sqlalchemy.ext.compiler import compiles

class string_agg(ColumnElement):
    def __init__(self, expr, separator, order_by=None):
        self.type = Text()
        self.expr = _literal_as_column(expr)
        self.separator = literal(separator)
        self.order_by = _literal_as_column(order_by)

    @property
    def _from_objects(self):
        return self.expr._from_objects

@compiles(string_agg, 'postgresql')
def compile_string_agg(element, compiler, **kwargs):
    head = 'string_agg(%s, %s' % (
        compiler.process(element.expr),
        compiler.process(element.separator)
    )
    if element.order_by is not None:
        tail = ' ORDER BY %s)' % compiler.process(element.order_by)
    else:
        tail = ')'
    return head + tail

query = session.query(string_agg(Foo.bar, ', ', order_by=Foo.bar.desc()))
# Print compiled SQL query.
print query.statement.compile(dialect=postgresql.dialect())
# Run the query and print result.
print query.scalar()

rawDescription: Using PostgreSQL Aggregate ORDER BY with sqlalchemy


code:
from P4 import P4, P4Exception
p4 = P4()
p4.port = "1"
p4.user = "User"
p4.client = "Client"

try:
    p4.connect()
    changelist = p4.run_filelog('//server/folder/...@yyyy/mm/dd,@now')
    for r in changelist:
      print r.depotFile
      print r.revisions[0].time

except P4Exception:
    for e in p4.errors:
        print e

finally:
    p4.disconnect()

rawDescription: How to retrieve submitted changelists in a day using Perforce Python API

description: Retrieve submitted changelists in a day using Perforce Python API


code:
import random

fileamount = int(raw_input("How many files should I make? > "))
amount = int(raw_input("How many characters in the files? > "))
print "I will now make %r files with %r characters in them!\n" % (fileamount, amount)

for s2 in range(fileamount):
    with open('a'+str(s2), 'wt') as textfile:
        for s1 in range(amount):
            textfile.write(str(random.randint(0,1)))

rawDescription: Nested loop and File io

description: Nested loop and File io


code:
a=[['1','2'],['1','3']]
for i in range(3):
    for j in range(3):
        if [str(i), str(j)] in a: # Note str
            print a

rawDescription: How to check whether a tuple exists in a Python list?

description: Check whether a tuple exists in a Python list


code:
for state in ('Michigan', 'Florida'):
   print '%s has: %s' % (state, cities[states[state]])

rawDescription: Python Dictionaries Print Options

description: Python Dictionaries Print Options


code:
def appendDict(list1, list2, resultDict):
    for idx, val in enumerate(list1):
        if isinstance(val, list):
            appendDict(val, list2[idx], resultDict)
        else:
            resultDict[val] = list2[idx]

list1=['k1','k2','k3',['k4','k5',['k6','k7']]]
list2=['v1','v2','v3',['v4','v5',['v6','v7']]]
resultDict = {}
appendDict(list1, list2, resultDict)
print resultDict

{'k3': 'v3', 'k2': 'v2', 'k1': 'v1', 'k7': 'v7', 'k6': 'v6', 'k5': 'v5', 'k4': 'v4'}

rawDescription: What's the most efficient way to zip two nested list to a single level dictionary


code:
import csv

STOCKS = ['JPM', 'PG', 'GOOG', 'KO']

for stock in STOCKS:
    with open('{}Min.csv'.format(stock)) as csvin:
        for row in csv.reader(csvin):
            if any(col > 731 for col in map(float, row)):
                print '{} minimum'.format(stock)
                break

rawDescription: Python repeating CSV file

description: Python repeating CSV file


code:
from IPython.core.debugger import Tracer

def my_function():
    x = 5
    Tracer()()
    print 5

rawDescription: Breakpoint-induced interactive debugging of Python with IPython


code:
assert len(A) == len(B) == len(C)
for a, b, c in zip(A, B, C):
    print a, b, c    # replace with file write

rawDescription: Writing data from python list?

description: Writing data from python list


code: print entry.id.text

rawDescription: Extracting ID string from GDataEntry

description: Extracting ID string from GDataEntry


code:
str = "What $noun$ is $verb$?"
print str.replace("$noun$", "the heck")

rawDescription: Replacing specific words in a string (Python)


rawDescription: Compare elements of list and dictionary and store as list of lists


code:
def bits(f):
    bytes = (ord(b) for b in f.read())
    for b in bytes:
        for i in xrange(8):
            yield (b >> i) & 1

for b in bits(open('binary-file.bin', 'r')):
    print b

rawDescription: Using Python How can I read the bits in a byte?


code:
for index in range(len(s)/8):
    substring = s[index * 8: index*8 + 8]
    byteval = int(substring, base=2)
    print chr(byteval)

rawDescription: How to output string of bits as a binary file in python

description: Output string of bits as a binary file in python


code:
import numpy as np
membership = np.random.randint(0, 2, 100)
d = np.diff(np.r_[0, membership, 0])
start = np.where(d == 1)[0]
end = np.where(d == -1)[0]
mask = (end - start) >= 3
start = start[mask]
end = end[mask]

for s, e in zip(start, end):
    print s, e, membership[s:e]

rawDescription: Numpy: split array into parts according to sequence of values


code:
from itertools import product
def fringe8((px, py), (x1, y1, x2, y2)):
    f = [(px+dx, py+dy) for (dx, dy) in product((-1,0,1),(-1,0,1)) if (dx, dy) != (0, 0)]
    f_inrange = [(fx, fy) for (fx, fy) in f if x1 <= fx < x2 and y1 <= fy < y2]
    return f_inrange

fringe8((2, 2), (1, 1, 3, 3))

rawDescription: How can this verbose, unpythonic routine be improved?


code:
precision = 2
number_to_convert = 10000
print "%0.*e"%(precision,number_to_convert)

rawDescription: Convert number to string scientific notation fixed length


code:
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from cStringIO import StringIO

def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec,laparams=laparams)
    fp = file(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()

    for pagenumber, page in enumerate(PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True)):
        print pagenumber
        if pagenumber % 2 == 0:
            print("even page number")
            interpreter.process_page(page)
        else:
            print("odd page number")
        if 5 <= pagenumber <= 10:
            print("pages 5 to 10")

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    return text

rawDescription: Working with singe pages with PDFMiner

description: Working with singe pages with PDFMiner


code:
import calendar
import time

# Time in GMT
x = 'Sat Jul 14 22:05:54 2012'
y = time.strptime(x)
z = calendar.timegm(y)
print z # 1342303554 - the number of seconds since epoch

rawDescription: Python: Number of seconds since midnight 1970.01.01 GMT to arbitrary time GMT?


code:
#!/usr/bin/env python

from multiprocessing.connection import Listener, Client
import socket
from array import array
from sys import argv

def myloop(address):
    try:
        listener = Listener(*address)
        conn = listener.accept()
        serve(conn)
    except socket.error, e:
        conn = Client(*address)
        conn.send('this is a client')
        conn.send('close')

def serve(conn):
    while True:
        msg = conn.recv()
        if msg.upper() == 'CLOSE':
            break
        print msg
    conn.close()

if __name__ == '__main__':
    address = ('/tmp/testipc', 'AF_UNIX')
    myloop(address)

rawDescription: can a python script know that another instance of the same script is running... and then talk to it?

description: Can a python script know that another instance of the same script is running... and then talk to it


code:
word_list = ['love','does','not','make','the','world','go','round','love',
             'is','what','makes','the','ride','worthwhile']
#your code:
from nltk.corpus import stopwords
for word in word_list:
    #print word
    if word in stopwords.words('english'):
       #print word #print out stopword for checking
       word_list.remove(word)
    else:
       print word
#now put:
print word_list
#output:
['love', 'not', 'make', 'world', 'go', 'round', 'love', 'what',
 'makes', 'ride', 'worthwhile']

rawDescription: NLTK error not show some word

description: NLTK error not show some word


code:
with open(filename) as f:
  while True:
    c = f.read(1)
    if not c:
      print "End of file"
      break
    print "Read a character:", c

rawDescription: How to read a single character at a time from a file in Python?

description: Read a single character at a time from a file in Python


code:
# the passing scenario
if all(i in a for i in b):
    print 'PASS'
else:
    print 'FAIL'

# the failing scenario
if all(i in a for i in c):
    print 'PASS'
else:
    print 'FAIL'

rawDescription: Simple if-else statement in Python

description: Simple if-else statement in Python


code:
should_run = True
print "Let's do some Pig Latin!"
while should_run:
    pyg = 'ay'

    original = raw_input('Enter a word:')

    word = original.lower()
    first = word[0]
    new_word = word + first + pyg

    if len(original) > 0 and original.isalpha():
        print new_word [1:]
        again = raw_input('Would you like to play again? [Y/N] \n').upper()
        while again not in "NY":
            again = raw_input("Invalid input. Play again? [Y/N] ").upper()

        should_run = "NY".index(again) # If again is Y, should_run is 1 (True).  Otherwise, it is 0 (False)
    else:
        print 'You were supposed to enter a word!,Try again'

rawDescription: Python: keep game running after converting in py2exe


code:
import email, getpass, imaplib, os

detach_dir = '.' # directory where to save attachments (default: current)
user = raw_input("Enter your GMail username:")
pwd = getpass.getpass("Enter your password: ")

# connecting to the gmail imap server
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user,pwd)
m.select("[Gmail]/All Mail") # here you a can choose a mail box like INBOX instead
# use m.list() to get all the mailboxes

resp, items = m.search(None, "ALL") # you could filter using the IMAP rules here (check http://www.example-code.com/csharp/imap-search-critera.asp)
items = items[0].split() # getting the mails id

for emailid in items:
    resp, data = m.fetch(emailid, "(RFC822)") # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc
    email_body = data[0][1] # getting the mail content
    mail = email.message_from_string(email_body) # parsing the mail content to get a mail object

    #Check if any attachments at all
    if mail.get_content_maintype() != 'multipart':
        continue

    print "["+mail["From"]+"] :" + mail["Subject"]

    # we use walk to create a generator so we can iterate on the parts and forget about the recursive headach
    for part in mail.walk():
        # multipart are just containers, so we skip them
        if part.get_content_maintype() == 'multipart':
            continue

        # is this part an attachment ?
        if part.get('Content-Disposition') is None:
            continue

        filename = part.get_filename()
        counter = 1

        # if there is no filename, we create one with a counter to avoid duplicates
        if not filename:
            filename = 'part-%03d%s' % (counter, 'bin')
            counter += 1

        att_path = os.path.join(detach_dir, filename)

        #Check if its already there
        if not os.path.isfile(att_path) :
            # finally write the stuff
            fp = open(att_path, 'wb')
            fp.write(part.get_payload(decode=True))
            fp.close()

rawDescription: How can I download all emails with attachments from Gmail?

description: Download all emails with attachments from Gmail


code:
import re
line = '[123:456]othertext'
print re.sub(r'^\[\d*:\d*\]','',line)
#               ^        ^
# => othertext

rawDescription: Regular Expressions: Removing this [##### : #####] from a string


code:
import Tkinter as tk

root = tk.Tk()

tk.Label(root, text='Number of Sides').grid(row=0)
tk.Label(root, text='Length of Sides').grid(row=1)

num_of_sides = tk.Entry(root, name = "numOfSides")
num_of_sides.grid(row=0, column=1)

length_of_sides = tk.Entry(root, name = "lenOfSides")
length_of_sides.grid(row=1, column=1)

def draw_polygon():
    ns = num_of_sides.get()
    ls = length_of_sides.get()

    print ns, ls
    print num_of_sides, length_of_sides

draw_button = tk.Button(root, text='Draw', command=draw_polygon)
draw_button.grid(row=3, column=1)

tk.mainloop()

rawDescription: Tkinter .get() from entry gives weird values


code:
import socket
import select

sockets = []

for port in range(33,128):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    server_socket.bind(('0.0.0.0', port))
    sockets.append(server_socket)

empty = []
while True:
    readable, writable, exceptional = select.select(sockets, empty, empty)
    for s in readable:
         (client_data, client_address) = s.recvfrom(1024)
         print client_address, client_data
for s in sockets:
   s.close()

rawDescription: how to create a UDP server that will listen on multiple ports in python?

description: Create a UDP server that will listen on multiple ports in python


code:
import socket

UDP_IP = "127.0.0.1"
UDP_PORT = 5005

sock = socket.socket(socket.AF_INET, # Internet
                 socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))

while True:
    data, addr = sock.recvfrom(1024) # buffer size is 1024 bytes
    print "received message:", data

rawDescription: Using netcat redirection in python to get data, after sending Ctrl C command


code:
print 'Word is',     #Notice the trailing comma. This will not print a newline char
faultyPrint()

rawDescription: Python printing from non returning functions


code:
from PyQt4.QtGui import QMainWindow
from PyQt4 import QtGui
from pyQt4 import QtCore

from MyDialog import MyDialog

class MyMainWindow(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.setWindowTitle("Close App Test")

        self.centralwidget = QtGui.QWidget(self)
        self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)

        self.closeButton = QtGui.QPushButton(self.centralwidget)
        self.closeButton.setText("Close")

        self.closeButton.clicked.connect(self.exit)

    def login(self):
        myDialog = MyDialog(self)
        res = myDialog.exec_()

        if res == 0:
            self.exit()
        else:
            print "Continue"

    def show(self):
        QMainWindow.show(self)
        QtCore.QTimer.singleShot(0, self.login)

    def exit(self):
        self.close()

rawDescription: Close PyQt App via a Modal Dialog

description: Close PyQt App via a Modal Dialog


code:
def generate_data():
    print "Generating"
    return [1,2,3]

class coo:
    data_member = generate_data()
    def modify(self):
        self.data_member.append(4)

    def display(self):
        print self.data_member

x = coo()
y = coo()
y.modify()
x.display()

# Output:
# Generating
# [1, 2, 3, 4]

rawDescription: Pythonic Way to Initialize (Complex) Static Data Members


code:
from httplib import HTTPResponse
from StringIO import StringIO

http_response_str = """HTTP/1.1 200 OK
Date: Thu, Jul  3 15:27:54 2014
Content-Type: text/xml; charset="utf-8"
Connection: close
Content-Length: 626"""

class FakeSocket():
    def __init__(self, response_str):
        self._file = StringIO(response_str)
    def makefile(self, *args, **kwargs):
        return self._file

source = FakeSocket(http_response_str)
response = HTTPResponse(source)
response.begin()
print "status:", response.status
print "single header:", response.getheader('Content-Type')
print "content:", response.read(len(http_response_str)) # the len here will give a 'big enough' value to read the whole content

rawDescription: python parse http response (string)

description: Python parse http response (string)


code:
from Tkinter import *
from time import time

start_time = end_time = 0
master = Tk()
e = Entry(master)
e.pack()
e.focus_set()

def key(event):
    if event.char == '\r':
        e.unbind("<Key>")
        return

    print "pressed", repr(event.char)
    end_time = time()
    print "measured time:", end_time-start_time

e.bind("<Key>", key)

start_time = time()
mainloop()

rawDescription: Implementing a keystroke time measurement function in python


code:
def getstr(s):
    a = [x for x in s]
    res = None
    for x in a:
        if not res: res = x
        else: res = " > ".join([res, x])
        yield res
print " | ".join(getstr("ABCD"))

rawDescription: recursive list in python

description: Recursive list in python


code:
import socket

def scan_port(port_num, host):
  s = socket.socket()
  socket.setdefaulttimeout(2)
  try:
      s = s.connect((host, port_num))
      print port_num, "[+] connection successful"

  except Exception, e:
      print port_num, "[+] Port closed"

host = 'localhost'

for i in xrange(1024):
  scan_port(i, host)

rawDescription: Port Scanner python script

description: Port Scanner python script


code:
pattern= r'^([^,]*),([^,]*),([^,]*),(.*),(\d+)\s*$'
string= 'time,ip,user,H4ck3r,,h4cker,,2015 ,1'
match= re.match(pattern, string)
print match.groups()

rawDescription: Python split delimiter issue

description: Python split delimiter issue


code:
for i in range(1,n):
    print i*(10**i-1)/9

rawDescription: Print integer number multiple times using single for loop and without using string in Python


code:
for divtag in div_Blocks:
    print divtag.find_previous_sibling('img')

rawDescription: position of tags in a html page using python 2.7 with beautifulsoup

description: Position of tags in a html page using python 2.7 with beautifulsoup


code:
import os

def fcount(path, map = {}):
  count = 0
  for f in os.listdir(path):
    child = os.path.join(path, f)
    if os.path.isdir(child):
      child_count = fcount(child, map)
      count += child_count + 1 # unless include self
  map[path] = count
  return count

path = "/Desktop/lay"
map = {}
print fcount(path, map)

rawDescription: How get number of subfolders and folders using Python os walks?


code:
from subprocess import Popen, PIPE

def os_system(command):
    process = Popen(command, stdout=PIPE, shell=True)
    while True:
        line = process.stdout.readline()
        if not line:
            break
        yield line

if __name__ == "__main__":
    for path in os_system("find /tmp"):
        print path

rawDescription: Python iterate over linux command output, line by line in real-time


code:
if 'Word' in myfile:
    print myfile

rawDescription: Modify python string with contain method


code:
result = dict()

for key in d:
    if 'id' in d[key]:
        current_id = d[key]['id']
        if current_id not in result:
            result[current_id] = dict() #init dict
        else:
            for sub_key in d[key]:
                if sub_key != 'id':
                    result[current_id][sub_key] =d[key][sub_key]

#Lastly Map back into the numbers

num_result = {}
result_key = [k for k in result]
# You can sort result key by some criteria if you want

for key_num in xrange(0,len(result_keys)):
    result[result_key[key_num]]['id'] = result_key[key_num] #Adds the id back
    num_result[key_num] = result[result_key[key_num]]

print num_result

rawDescription: Merge nested dictionaries by nested values


code:
from collections import defaultdict
from itertools import izip

add = lambda (sum_, count), value: (sum_+value, count+1)
unique = defaultdict(lambda:(0,0))
for ref, value in izip(reference_array.flat, given_array.flat):
    unique[ref] = add(unique[ref], float(value))

with open('file.out', 'w') as out:
    for ref, (sum_, count) in unique.iteritems():
        out.write('%f,%f\n' % (ref, sum_ / count))

rawDescription: Fastest way of calculating mean values for each indices


code:
import re

s = "hello_from_adele[this_is_the_string_i_am_looking_for]this_is_not_it"
match = re.search(r"\[([A-Za-z0-9_]+)\]", s)
print match.group(1)

rawDescription: From list of strings, extract only characters within brackets


code:
element = webdriver.find_element_by_css_selector("#organic-jobs .organic-job:nth-child("+str(Line)+") .title .lk-job-title")
print element.get_attribute('onclick')

rawDescription: How do I get the onclick "action" of a link using Python and Selenium?

description: Get the onclick "action" of a link using Python and Selenium


code:
import sys

def hello():
    print "Hello world"

def goodbye():
    print "Goodbye, cruel world!"

if __name__ == "__main__":
    func_name = sys.argv[1]
    func = globals()[func_name]
    func()

rawDescription: Python: Call functions out of a script

description: Python: Call functions out of a script


code:
data = json.loads(output.text)
print data['id']  # prints http://goo.gl/O5MIi

rawDescription: Parse requests.post object

description: Parse requests.post object


code:
s = 'abcdefgh'
# s = 'abcdefghi'

# pad
if len(s) % 2:
    s += 'x'

l = []
# split
for i in range(0,len(s),2):
    l.append(s[i:i+2])

# switch
for i in range(0,len(l),2):
    if i+1 < len(l):
        l[i+1], l[i] = l[i:i+2]

# reverse each
l = [x[::-1] for x in l]

print l

rawDescription: python exchange position for pair of characters and reverse 2 characters

description: Python exchange position for pair of characters and reverse 2 characters


code:
import time

from twisted.web import server, resource
from twisted.internet import reactor

class Simple(resource.Resource):
    isLeaf = True
    def render_GET(self, request):
        return "<html>%s Iterations!</html>"%n

def main():
    global n
    site = server.Site(Simple())
    reactor.listenTCP(8080, site)
    reactor.startRunning(False)
    n=0
    while True:
        n+=1
        if n%1000==0:
            print n
        time.sleep(0.001)
        reactor.iterate()

if __name__=="__main__":
    main()

rawDescription: Integrating a simple web server into a custom main loop in python?


code:
class A(object):
    def __init__(self):
        self.hello = "Hello"
        # + some huge misguided crap that I do not control
    def f1(self):
        self.f2()
    def f2(self):
        print self.hello

class B(object):
    class __metaclass__(type):
        A_METHODS = ['f{}'.format(i) for i in xrange(1, 11)] # 'f1'...'f10'

        def __new__(mcls, classname, bases, classdict):
            classobj = type.__new__(mcls, classname, bases, classdict)
            classobj.hello = A().hello
            for fn in mcls.A_METHODS:
                if fn in A.__dict__:
                    setattr(classobj, fn, A.__dict__[fn].__get__(classobj, A))
            return classobj

    def __init__(self):
        pass

a = B()
a.f2()  # --> Hello

rawDescription: Access Python class `__dict__` within class initializer?


code:
for id in IDlines:
    print"ID submitted to findgtf: "+id
    gtf.seek(0) # seek to the start of the file
    fg = findgtf(id, gtf)

rawDescription: python functions and for loops

description: Python functions and for loops


code:
import bcrypt

# Hash a password for the first time
hashed = bcrypt.hashpw(password, bcrypt.gensalt())

# gensalt's log_rounds parameter determines the complexity
# the work factor is 2**log_rounds, and the default is 12
hashed = bcrypt.hashpw(password, bcrypt.gensalt(10))

# Check that an unencrypted password matches one that has
# previously been hashed
if bcrypt.hashpw(plaintext, hashed) == hashed:
    print "It matches"
else:
    print "It does not match"

rawDescription: Best hashing method before saving password into database table for django


code:
for match in responser:
    for num_events, team, events in match:

        for y in events[0]:
            for sub in y:
                if isinstance(sub[0], list):
                    print sub

rawDescription: For loops and nested lists issue

description: For loops and nested lists issue


code:
import inspect
def printname(x):
    print inspect.stack()[1][4]

a = 1.3
printname(a)

rawDescription: Python: How to get argument's name runtime


code:
tmp = self.field.toPlainText()
print 'field.toPlainText: ', tmp

codec0 = QtCore.QTextCodec.codecForName("UTF-16");
codec1 = QtCore.QTextCodec.codecForName("ISO 8859-2");

print 'UTF-16: ', unicode(codec0.fromUnicode(tmp), 'UTF-16')
print 'ISO 8859-2: ', unicode(codec1.fromUnicode(tmp), 'ISO 8859-2')

rawDescription: Make unicode from variable containing QString


code:
import sys
import datetime
import time
from PyQt4 import QtCore, QtGui

class Main(QtGui.QMainWindow):
  def __init__(self, parent=None):
    super(Main, self).__init__(parent)
    self.b = QtGui.QPushButton("exit", self, clicked=self.close)

  def myRun(self):
    while True:
      time.sleep(2)
      print "Print this + Show the Window???!!!"

if __name__ == "__main__":
  app=QtGui.QApplication(sys.argv)
  myapp=Main()
  myapp.show()

  thread = QtCore.QThread()
  thread.run = lambda myapp=myapp: myapp.myRun()
  thread.start()

  app.connect(app, QtCore.SIGNAL("lastWindowClosed()"), app, QtCore.SLOT("quit()"))

  sys.exit(app.exec_())

  while thread.isAlive():
    #Make sure the rest of the GUI is responsive
    app.processEvents()

rawDescription: Python - How to show the window + print the text? Where its only printing but not showing the window


code:
import xmmsclient
import xmmsclient.glib
import os
import sys
import gobject

def cb(result):
    if not result.is_error():
        print "Current: %(artist)s - %(title)s" % result.value()

ml = gobject.MainLoop(None, False)

xc = xmmsclient.XMMS("stackoverflow")
xc.connect()

conn = xmmsclient.glib.GLibConnector(xc)
xc.broadcast_playback_current_id(lambda r: xc.medialib_get_info(r.value(), cb))
ml.run()

rawDescription: xmms2 track change detection for pynotify?

description: Xmms2 track change detection for pynotify


code:
range_sorted_list = sorted(zip(start_list, end_list))
range_sorted_iter = iter(range_sorted_list)
pos_sorted_list = sorted(pos_list)

start, end = next(range_sorted_iter)

try:
    for pos in pos_sorted_list:
        while pos >= end:
            start, end = next(range_sorted_iter)
        if start <= pos < end:
            print "True", pos
        elif pos < start:
            print "False", pos
except StopIteration:
    pass

rawDescription: Alternative to nested for loop

description: Alternative to nested for loop


code:
for s in strings:
    for t in tlds:
        print s + '.' + t

rawDescription: concatenate all items from two lists in Python

description: Concatenate all items from two lists in Python


code:
import os
import ogr
import sys
import numpy as np

#Driver
driver = ogr.GetDriverByName('ESRI Shapefile')

#Working Directory Path
ws = 'C:/data/'

#Make ws the working directory
os.chdir(ws)

#vector path
in_data = 'data.shp'

#user inputs; how many splits per axis
xSplit = 2
ySplit = 2

#This is a three dimensional array (In numpy Z,Y,X values)
dCoords = np.ones((2,ySplit+1,xSplit+1))

#Input polygons
source_ds = ogr.Open(in_data,0)
source_layer = source_ds.GetLayer(0)
source_features = source_layer.GetFeatureCount()

#Output polygons
target_ds = driver.CreateDataSource('split.shp')

if target_ds is None:
    print 'Creation of output file failed.\n'
    sys.exit(1)

geom_type = ogr.wkbPolygon
target_layer = target_ds.CreateLayer('split',None,geom_type)

if target_layer is None:
    print 'Creating of layer failed.\n'
    sys.exit(1)

field_defn = ogr.FieldDefn('parcel_no',ogr.OFTInteger)
field_defn.SetWidth(30)

if target_layer.CreateField(field_defn) !=0:
    print 'Creating plot_num field failed.\n'
    sys.exit(1)

featureDefn = target_layer.GetLayerDefn()

#Get the polygons from the layer
for i in xrange(0,source_features):
    source_poly = source_layer.GetFeature(i)
    source_plot = source_poly.GetField('id')
    source_geom = source_poly.GetGeometryRef()

    #Get the corner coords of the quad
    cx = []
    cy = []

    pts = source_geom.GetGeometryRef(0)
    points = []

    for p in xrange(pts.GetPointCount()):
        cx.append(pts.GetX(p))
        cy.append(pts.GetY(p))

    dx0 = (cx[1] - cx[0]) / xSplit
    dx1 = (cx[1] - cx[2]) / ySplit
    dx2 = (cx[2] - cx[3]) / xSplit
    dx3 = (cx[0] - cx[3]) / ySplit
    dy0 = (cy[1] - cy[0]) / xSplit
    dy1 = (cy[1] - cy[2]) / ySplit
    dy2 = (cy[2] - cy[3]) / xSplit
    dy3 = (cy[0] - cy[3]) / ySplit

    for ys in xrange(0,ySplit):
        x1 = cx[3] + dx3 * ys
        y1 = cy[3] + dy3 * ys
        x2 = cx[2] + dx1 * ys
        y2 = cy[2] + dy1 * ys
        dx2 = ( x2 - x1 )  / xSplit
        dy2 = ( y2 - y1 )  / xSplit

        for xs in xrange(0,xSplit):
            x3 = x1 + dx2 * xs
            y3 = y1 + dy2 * xs

            #Calculate Grid Coordinates
            dCoords[0][xs][ys] = x3
            dCoords[1][xs][ys] = y3

    #Build Grid
    for i in xrange(0,ySplit - 1):
        for j in xrange(0,xSplit - 1):

            #Create an empty ring geometry
            ring = ogr.Geometry(ogr.wkbLinearRing)

            ring.AddPoint(dCoords[0][j][i],dCoords[1][j][i])
            ring.AddPoint(dCoords[0][j][i+1],dCoords[1][j][i+1])
            ring.AddPoint(dCoords[0][j + 1][i + 1],dCoords[1][j + 1][i + 1])
            ring.AddPoint(dCoords[0][j + 1][i],dCoords[1][j + 1][i])
            ring.AddPoint(dCoords[0][j][i], dCoords[1][j][i])

            target_poly = ogr.Geometry(ogr.wkbPolygon)
            target_poly.AddGeometry(ring)

            target_feature = ogr.Feature(featureDefn)
            target_feature.SetGeometry(target_poly)
            target_feature.SetField('id',source_plot)
            target_layer.CreateFeature(target_feature)

rawDescription: Convex Quadrilateral Polygons subdivision in equal parts using Python / OGR


code:
import random
import csv

class Weapon:
    def __init__ (self, name, value, weight, description):
        self.name = name
        self.value = value
        self.weight = weight
        self.description = description

with open('weapon.csv', 'r') as csvfile:
  weaponscsv = list(csv.reader(csvfile))

lengthofcsv = len(weaponscsv)
position = random.randrange(0, lengthofcsv)

aweapon = Weapon(*weaponscsv[position])

print aweapon.name
print aweapon.value
print aweapon.weight
print aweapon.description

rawDescription: How do I pull a random line from a CSV file and assign to a class? Python3

description: Pull a random line from a CSV file and assign to a class? Python3


code:
import sys
import tty

# Back up previous tty settings
stdin_fileno = sys.stdin.fileno()
old_ttyattr = tty.tcgetattr(stdin_fileno)

try:
    print 'Reassigning ctrl-c to ctrl-x'

    # Enter raw mode on local tty
    tty.setraw(stdin_fileno)
    raw_ta = tty.tcgetattr(stdin_fileno)
    raw_ta[tty.LFLAG] |= tty.ISIG
    raw_ta[tty.OFLAG] |= tty.OPOST | tty.ONLCR

    # ^X is the new ^C, set this to 0 to disable it entirely
    raw_ta[tty.CC][tty.VINTR] = '\x18'

    # Set raw tty as active tty
    tty.tcsetattr(stdin_fileno, tty.TCSANOW, raw_ta)

    # Dummy program loop
    import time
    for _ in range(5):
        print 'doing stuff'
        time.sleep(1)

finally:
    print 'Resetting ctrl-c'
    # Restore previous tty no matter what
    tty.tcsetattr(stdin_fileno, tty.TCSANOW, old_ttyattr)

rawDescription: How to stop SIGINT being passed to subprocess in python?

description: Stop SIGINT being passed to subprocess in python


code:
# http://stackoverflow.com/questions/6849600/does-anyone-have-a-categorized-xml-corpus-reader-for-nltk
from CatXMLReader import CategorizedXMLCorpusReader

from nltk.corpus import cicero
from nltk import Text

fileids = cicero.abspaths()
reader = CategorizedXMLCorpusReader('/', fileids, cat_file='cats.txt')
words = Text(reader.words(fileids))
print words.concordance('et')

rawDescription: How to load multiple XML files of corpora with NLTK and use it as a whole with Text class?

description: Load multiple XML files of corpora with NLTK and use it as a whole with Text class


code:
def do_menu(menu,error="Invalid Choice Try Again!"):
    while True:
        for k,(msg,action) in menu.items():
            print msg
        resp = raw_input("Make a Choice:")
        if resp in menu:
            return menu[resp][1]()
        print error

import random,sys

#####JUST SOME GENERIC MENU ACTIONS
something = []

def add_something():
    something.append(random.randint(1,10))
    print "ADDED %d"%something[-1]

def print_something():
    print something

#DEFINE THE MENU
menu = {
'A':("[A]dd Something",add_something),
'P':("[P]rint Something",print_something),
'Q':("[Q]uit",sys.exit)
}
while True:
    #print menu and get user response and act upon it
    print "\n#####[ MENU ]####"
    result = do_menu(menu)

rawDescription: Define a function that will perform various tasks, but terminates with a certain input


code:
import paramiko

# Define connection info
host_ip = 'xx.xx.xx.xx'
user = 'xxxxxxxx'
pw = 'xxxxxxxx'

# Paths
input_loc = '/nfs_home/appers/extracts/*/*.xml'
output_loc = '/user/lcmsprod/output/cnielsen/'
python_path = "/usr/lib/python_2.7.3/bin/python"
hdfs_home = '/nfs_home/appers/cnielsen/'
output_log = r'C:\Users\cnielsen\Desktop\MR_Test\MRtest011316_0.txt'

# File names
xml_lookup_file = 'product_lookups.xml'
mapper = 'Mapper.py'
reducer = 'Reducer.py'
helper_script = 'Process.py'
product_name = 'test1'
output_ref = 'test65'

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

def buildMRcommand(product_name):
    space = " "
    mr_command_list = [ 'hadoop', 'jar', '/share/hadoop/tools/lib/hadoop-streaming.jar',
                        '-files', hdfs_home+xml_lookup_file,
                        '-file', hdfs_home+mapper,
                        '-file', hdfs_home+reducer,
                        '-mapper', "'"+python_path, mapper, product_name+"'",
                        '-file', hdfs_home+helper_script,
                        '-reducer', "'"+python_path, reducer+"'",
                        '-input', input_loc,
                        '-output', output_loc+output_ref]

    MR_command = space.join(mr_command_list)
    print MR_command
    return MR_command

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

def unbuffered_lines(f):
    line_buf = ""
    while not f.channel.exit_status_ready():
        line_buf += f.read(1)
        if line_buf.endswith('\n'):
            yield line_buf
            line_buf = ''

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

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host_ip, username=user, password=pw)

# Build Commands
list_dir = "ls "+hdfs_home+" -l"
getmerge = "hadoop fs -getmerge "+output_loc+output_ref+" "+hdfs_home+"test_011216_0.txt"

# Run Command
stdin, stdout, stderr = client.exec_command(list_dir)
##stdin, stdout, stderr = client.exec_command(buildMRcommand(product_name))
##stdin, stdout, stderr = client.exec_command(getmerge)

print "Executing command..."
writer = open(output_log, 'w')

for l in unbuffered_lines(stderr):
    e = '[stderr] ' + l
    print '[stderr] ' + l.strip('\n')
    writer.write(e)

for line in stdout:
    r = '[stdout]' + line
    print '[stdout]' + line.strip('\n')
    writer.write(r)

client.close()
writer.close()

rawDescription: Launch Hadoop MapReduce job via Python without PuTTy/SSH


code:
import re

for style_tag in soup.find_all('style', text=re.compile('@import\s+url')):
    style_text = style_tag.get_text()
    urls = re.findall(r'@import url\("([^"]+)"\)', style_text)
    print urls

rawDescription: BeautifulSoup take the url of imported moduls


code:
class SortedDict(dict):
    def __iter__(self):
        return iter(sorted(super(SortedDict, self).__iter__()))

    def items(self):
        return iter((k, self[k]) for k in self)

fruits = SortedDict({3: "banana",
          4: "grapes",
          1: "apple",
          2: "cherry"})

for each in fruits:
    print each, fruits[each]

rawDescription: Are sorted keys guaranteed by a Python dictionary?


code:
def rec_increment(p):
    if len(p) == 0:
        return ""                    #If you return an empty string, you don't get the "None" printing at the end.
    else:
        #r = list(p)                 This is not necessary now.
        print p[0]+1                 #r.pop(0) + 1   Rather than pop, just index.
        return rec_increment(p[1:])  # Only recurse on the 2nd-nth part of the list

print rec_increment([1,2,3,4])       # Note that you don't need to both "print" in the function *and* print the result of the function - you can pick which you want to do.

rawDescription: Printing lists recursively in Python without mutating a list


code:
import collections

def is_anagram(w1, w2):
    return collections.Counter(w1) == collections.Counter(w2)

def get_signature(word):
    return ''.join(sorted(word))

def find_anagrams(infilepath):
    answer = {}
    with open(infilepath) as infile:
        for line in infile:
            word = line.strip().lower()
            sig = get_signature(word)
            if sig not in answer:
                answer[sig] = set()
            answer[sig].add(word)
    return answer

def find_most_anagrams(infilepath):
    anagrams = find_anagrams(infilepath)
    most = max(anagrams, key=lambda k:len(anagrams[k]))
    print "The maximum number of anagrams are made with the letters", most, '.'
    print "The anagrams are:",
    print '\n\t'.join(anagrams[most])

rawDescription: finding_anagrams function is not creating dictionary of anagrams

description: Finding_anagrams function is not creating dictionary of anagrams


code:
from PyQt4.QtNetwork import QNetworkCookie, QNetworkCookieJar
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
import sys

class Render(QWebPage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        QWebPage.__init__(self)
        self.loadFinished.connect(self._loadFinished)
        self.mainFrame().load(QUrl(url))
        self.cookie = QNetworkCookie()
        self.cookie.setDomain('.nowgoal.com')
        self.cookie.setName('enurl_bak')
        self.cookiejar = QNetworkCookieJar()
        self.cookiejar.setAllCookies([self.cookie])
        self.networkAccessManager().setCookieJar(self.cookiejar)
        self.app.exec_()

    def _loadFinished(self, result):
        self.frame = self.mainFrame()
        print"loadfinished"
        self.app.quit()

url = 'http://www.nowgoal.com'
Render(url)

rawDescription: PyQT4 Javascript Alert

description: PyQT4 Javascript Alert


code:
class Test(object):
    def check(self):
        print self.one # here it really refers to Test.one

    def test(self):
        Test.one = 1
        yield self.check

rawDescription: Nosetest Generator Method Behavior

description: Nosetest Generator Method Behavior


code:
import asyncore, socket

class Client(asyncore.dispatcher_with_send):
    def __init__(self, host, port, message):
        asyncore.dispatcher.__init__(self)
        self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((host, port))
        self.out_buffer = message

    def handle_close(self):
        self.close()

    def handle_read(self):
        print 'Received', self.recv(1024)
        self.close()

c = Client('', 5007, 'Hello, world')
asyncore.loop()

rawDescription: python asyncore connectivity

description: Python asyncore connectivity


code:
for index, w in enumerate(loopme):
    print "CURRENT WORD IS", w, "AT CHARACTER", index

rawDescription: Python For loop get index

description: Python For loop get index


code:
def my_func(foo):
    foo.append(3)  # now the source list also has the number 3
    foo = [3]      # we've re-bound 'foo' to something else, severing the relationship
    foo.append(4)  # the source list is unaffected
    return foo

original = [1, 2]
new = my_func(original)

print original     # [1, 2, 3]
print new          # [3, 4]

rawDescription: Without pointers, can I pass references as arguments in Python?


code:
class Unusable:
    def __init__(self):
        self.alive = True

    def notcleanedup(func):
        def operation(self, *args, **kwargs):
            if self.alive:
                func(self, *args, **kwargs)
            else:
                raise Exception("Use after cleanup")

        return operation

    @notcleanedup
    def sensitive(self, a, b):
        print a, b

    def cleanup(self):
        self.alive = False

rawDescription: making a python object unsable after a finalize-type call

description: Making a python object unsable after a finalize-type call


code:
import string
trans = string.maketrans('ae', 'bx') # a->b and e->x
text = 'abcdef'
print text.translate(trans)
# bbcdxf

rawDescription: i need to know exactly how to use string.maketrans

description: I need to know exactly how to use string.maketrans


code:
i = 0
while i < len(finalgrid1):
    print finalgrid1[i]
    i += 1

rawDescription: Printing list as table (row, col)

description: Printing list as table (row, col)


code:
class Base(object):
  def __new__(cls):
    if cls is Base:
      raise NotImplementedError()
    super(Base, cls).__new__(cls)

class Derived(Base):
  pass

try:
  o = Base()
except NotImplementedError:
  print 'Should happen!'
else:
  print 'Should not happen!'

try:
  o = Derived()
except NotImplementedError:
  print 'Should not happen!'
else:
  print 'Should happen!'

rawDescription: Best way in python to make a class that is uninitializable but whose child classes are initializable


code:
with file('bla.txt') as input:
  for count, line in enumerate(input):
    if count > 10000:
      break
    if re.search('foo bar', line):
      print line

rawDescription: What is the pythonic way to os.system('grep "word" file.txt')?


code:
for n, m in zip(results, settings):
    if m - 0.1 <= n <= m + 0.1:
        print 'ok'
    else:
        print 'fail'
print 'Done'

rawDescription: Python - Less than or Equal To Compare with two lists?


code:
def character_namer():
    return raw_input("please enter your name: ")

character_name = character_namer()

print character_name

rawDescription: How do I create a variable outside a function in Python

description: Create a variable outside a function in Python


code:
# When run as a cgi script, this will print the client's IP address.

import cgi
import os

print "Content-type: text/html"
print ""

print cgi.escape(os.environ["REMOTE_ADDR"])

rawDescription: Python: CGI program wants to know the IP address of the calling web page


code:
import matplotlib.pyplot as plt

def close_event():
    plt.close() #timer calls this function after 3 seconds and closes the window

fig = plt.figure()
timer = fig.canvas.new_timer(interval = 3000) #creating a timer object and setting an interval of 3000 milliseconds
timer.add_callback(close_event)

plt.plot([1,2,3,4])
plt.ylabel('some numbers')

timer.start()
plt.show()
print "Am doing something else"

rawDescription: How to set timeout to pyplot.show() in matplotlib?

description: Set timeout to pyplot.show() in matplotlib


code:
import json

foo ={"country":"canada",
   "tours":"[{\"title\":\"Canadian Rockies Trail\",\"price\":\"$2249\"},{\"title\":\"2-Day Fantasy Island Getaway\",\"price\":\"$269\"}]"}

foo['tours'] = json.loads(foo['tours']) # turn tours into dict

for tour in foo['tours']:
    print "tour name : {} :::: tour price: {}".format(tour['title'],tour['price']) # tour is a dict now.

rawDescription: Getting the json object of a json object in python?


code:
d1 = {'a' : 1.001, 'b' : 2.0002, 'c' : 3}
d2 = {'a' : 1.002, 'b' : 2,      'c' : 3, 'd' : 4}
tol = 0.001
equals = lambda a, b: abs(a-b) < tol

# For loop with print
for key in set(d1.keys()) & set(d2.keys()):
    print '{} == {} is {} (tolerance: {})'.format(
        d1[key], d2[key], equals(d1[key], d2[key]), tol
    )

# 1.001 == 1.002 is False (tolerance: 0.001)
# 3 == 3 is True (tolerance: 0.001)
# 2.0002 == 2 is True (tolerance: 0.001)

# List comprehension with bools
print [equals(d1[key], d2[key]) for key in set(d1.keys()) & set(d2.keys())]

# [False, True, True]

rawDescription: Elegant comparison of elements in two dictionaries within tolerance in python


code:
number = 343703  # Replace ??? with a value of your choice.
sequence_len = 3  # Replace ??? with a value of your choice.
numbstr = str(number)
digitlist = []

# Appending all the numbers to a list
for digit in numbstr:
    digitlist.append(int(digit))

# Looping over all the variables in digitlist, i is the index
for i, _ in enumerate(digitlist):
    # If the index, i is 2 less than the length of the list
    if i < len(digitlist) - 2:
        # Adding the term and the next two terms after that
        if digitlist[i] + digitlist[i+1] + digitlist[i+2] == 10:
            # Printing the list
            print digitlist[i:i+3]

rawDescription: Sum of following digits

description: Sum of following digits


code:
import re

x = '''LINE: 1
TOKENKIND: somedata
TOKENKIND: somedata
LINE: 2
TOKENKIND: somedata
LINE: 3'''

junkre = re.compile(r'(\s*LINE:\s*\d*\s*)|(\s*TOKENKIND:)', re.DOTALL)

print junkre.sub('', x)

rawDescription: Matching multiple regex groups and removing them


code:
from multiprocessing import Process, Queue
import time
q = Queue()

def some_func1(arg1, arg2, q):
    #this one will take longer, so we'll kill it after the other finishes
    time.sleep(20)
    q.put('some_func1 finished!')

def some_func2(arg1, arg2, q):
    q.put('some_func2 finished!')

proc1 = Process(target=some_func1,
                           args = ('arga', 'argb', q))
proc2 = Process(target=some_func2,
                           args = ('arg1', 'arg2', q))
proc1.start()
proc2.start()

#this will be the result from the first thread that finishes.
#At this point you can wait for the other threads or kill them, or whatever you want.
result = q.get()
print result
#if you want to kill all the procs now:
proc1.terminate()
proc2.terminate()

rawDescription: Python performing multiple tasks

description: Python performing multiple tasks


code:
class ClassDict(object):
  def __init__(self):
    self.classes = {}

  def add(self, cls):
    self.classes[cls.__name__] = cls

  def remove(self, cls):
    if self.classes[cls.__name__] == cls:
      del self.classes[cls.__name__]
    else:
      raise KeyError('%r' % cls)

  def __getitem__(self, key):
    return self.classes[key]

  def __repr__(self):
    return 'ClassDict(%s)' % (', '.join(self.classes),)

class C(object):
  pass

class D(object):
  pass

cd = ClassDict()
cd.add(C)
cd.add(D)

print cd

print cd['C']

rawDescription: Python - Access a class from a list using a key


code:
inst = session.query(Model).first()
session.expunge(inst)

make_transient(inst)
inst.id = None
session.add(inst)
session.flush()
print inst.id #New ID

rawDescription: SQLAlchemy: Modification of detached object


code:
for cdate, path in sorted(entries):
    # compare by timestamp
    #if cdate < time.mktime(datetime.date(2015,03,13).timetuple()) and \
    #    cdate > time.mktime(datetime.date(2014,02,17).timetuple()):

    # compare by datetime
    filedate = datetime.datetime.fromtimestamp(cdate)
    if filedate < datetime.datetime(2015,03,13) and \
            filedate > datetime.datetime(2014,02,17):
        print time.ctime(cdate)
        print os.path.basename(path)

rawDescription: Comparing File Dates in a Directory

description: Comparing File Dates in a Directory


code:
extra = 0
values = (random_list[number] for i,number in enumerate(my_numbers))
for v in values:
    extra += sum(v < x for x in [3000,300,30,3])
    if v < 3:break;

print i+extra

rawDescription: Counter through embedded if statements inside for loop


code:
for li, lj, lk in itertools.product(cntr1, cntr2, cntr3):
    print li, lj, lk

rawDescription: Python: Nesting counters

description: Python: Nesting counters


code:
N=4             #matrix size
a=random((N,N)) #input

#--window size
wl=1            #left
wr=1            #right
wt=1            #top
wb=1            #bottom
#---

H=np.zeros((N,N))   #output

def h(k,l):         #individual cell function
   #--- checks to not run out of array
    k1=max(k-wt,0)
    k2=min(k+wb+1,N)
    l1=max(l-wl,0)
    l2=min(l+wr,N)
   #---
    return a[k,l]-np.amin(a[k1:k2,l1:l2])

H=array([[h(k,l) for l in range(N)] for k in range(N)]) #running over all matrix elements

print a
print H

rawDescription: Loop and extract window

description: Loop and extract window


code:
import Tkinter as tk

def key_press(event):
    print event.char
    return event.char
    # Or whatever processing you might want.

tk_app = tk.Tk()
tk_app.bind('<KeyPress>', key_press)
tk_app.mainloop()

rawDescription: How do you map a keyboard key in Python 2.7?

description: Map a keyboard key in Python 2.7


code:
import collections
from itertools import chain

#input list called l
l = [1,2,[3,4],[5,6],7,[8,9,10]]

#if an item in the list is not already a list (iterable) then put it in one.
a = [i if isinstance(i, collections.Iterable) else [i,] for i in l]

#flattens out a list of iterators
b = list(chain.from_iterable(a))

print b
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

description: How transform list=[1,2,[3,4],[5,6],7,[8,9,10]] in list1=[1,2,3,4,5,6,7,8,9,10] in python


code:
from operator import add, sub, mul, floordiv
import random

number1 = 9
number2 = 3

operators = {'+':add, '-':sub, '*':mul, '/':floordiv}
operator_name = random.choice(operators.keys())
op = operators[operator_name]
answer = op(number1, number2)
question = "What is {}{}{}?".format(number1, operator_name, number2)
print question
print answer

rawDescription: TypeError: 'bool' object is not callable - python


code:
teststr = "a   v w   ef sdv   \n   wef"
print teststr
teststr.split()
teststr.split(" ")

rawDescription: Python split string by space and strip newline char


code:
import ctypes

def show_float(x):
    asdouble = ctypes.c_double(x)
    xpointer = ctypes.addressof(asdouble)
    xdata = ctypes.string_at(xpointer, 8)
    print "".join([bin(ord(i))[2:] for i in xdata])

x = 3.14
show_float(x) # prints 1111110000101111010111010001101110001111010011000000

rawDescription: Is there a python equivalent of the octave command `format bit`?


code:
csvfile = open('dump.csv', 'w')
for file in glob.glob('*.html'):
    print 'Processing', file
    soup = BeautifulSoup(open(file).read())
    for tr in soup.findAll('tr'):
        print >>csvfile, ' '.join(tr.findAll('td'))

rawDescription: Best method of extracting text from multiple html files into one CSV file


code:
lowest, highest = a, b
if b < a: lowest, highest = b, a
total = 0
for _ in range(lowest):
    total += highest
print "a x b = %s" % total

rawDescription: Multiplication without using the times or division symbol in python


code:
import re

rgx = re.compile('ElapsedTime(\d*\.\d*)s: (\S*)')

from collections import defaultdict
d = defaultdict(list)

with open('data1.txt','r') as f:
    for m in rgx.finditer(f.read()):
        d[m.group(2)].append(float(m.group(1)))

lapi = max(map(len,d.iterkeys()))

print '{: ^{width}}   min    max    average   total occurences'.format('api',width=lapi)
pat = '{0:%d}   {1:.2f}   {2:.2f}   {3:.3f}     {4}' % lapi
print '\n'.join(pat.format(api,min(li),max(li),sum(li)/len(li),len(li))
                for api,li in d.iteritems())

rawDescription: python RE and list processing

description: Python RE and list processing


code:
from BeautifulSoup import BeautifulSoup
import requests

r  = requests.get("http://twitter.com/CarolinaPadron/status/456540908368842752")
data = r.text
soup = BeautifulSoup(data)
print soup.findAll("p", "tweet-text")[0].text

rawDescription: How to obtain the text from a web site knowing it's contained within a <p> with certain CSS classes using Python?

description: Obtain the text from a web site knowing it's contained within a <p> with certain CSS classes using Python


code:
import MySQLdb
db = MySQLdb.connect("host", "user", "password", "dbname")
cursor = db.cursor()
sql = """SELECT count(*) as tot FROM simpletable"""
cursor.execute(sql)
data = cursor.fetchone()
db.close()
print data

rawDescription: How to check with python if a table is empty?

description: Check with python if a table is empty


code:
def testFunc(arg1, arg2, arg3, additional='test'):
    print arg1

import inspect
inspect.getargspec(testFunc)

rawDescription: Python function parameter count

description: Python function parameter count


code:
x = range(9)
x
print numpy.random.shuffle(x)
x

rawDescription: NumPy: numpy.random.shuffle does not exist


code:
import os
import datetime
import cPickle

# just a constants we can use to define our score file location
SCORES_FILE = "scores.pickle"

def get_user_data():
    time1 = datetime.datetime.now()
    print "Current time:", time1.strftime("%d.%m.%Y, %H:%M")

    a = None
    while True:
        a = raw_input("Enter weight: ")
        try:
            a = float(a)
        except:
            continue
        else:
            break

    b = None
    while True:
        b = raw_input("Enter height: ")
        try:
            b = float(b)
        except:
            continue
        else:
            break

    c = a/b

    return ['', a, b, c, time1]

def read_high_scores():
    # initialize an empty score file if it does
    # not exist already, and return an empty list
    if not os.path.isfile(SCORES_FILE):
        write_high_scores([])
        return []

    with open(SCORES_FILE, 'r') as f:
        scores = cPickle.load(f)
    return scores

def write_high_scores(scores):
    with open(SCORES_FILE, 'w') as f:
        cPickle.dump(scores, f)

def update_scores(newScore, highScores):
    # reuse an anonymous function for looking
    # up the `c` (4th item) score from the object
    key = lambda item: item[3]

    # make a local copy of the scores
    highScores = highScores[:]

    lowest = None
    if highScores:
        lowest = min(highScores, key=key)

    # only add the new score if the high scores
    # are empty, or it beats the lowest one
    if lowest is None or (newScore[3] > lowest[3]):
        newScore[0] = raw_input("Enter name: ")
        highScores.append(newScore)

    # take only the highest 5 scores and return them
    highScores.sort(key=key, reverse=True)
    return highScores[:5]

def print_high_scores(scores):
    # loop over scores using enumerate to also
    # get an int counter for printing
    for i, score in enumerate(scores):
        name, a, b, c, time1 = score
        # #1    50.0    jdi    (20.12.2012, 15:02)
        print "#%d\t%s\t%s\t(%s)" % \
            (i+1, c, name, time1.strftime("%d.%m.%Y, %H:%M"))

def main():
    score = get_user_data()
    highScores = read_high_scores()

    highScores = update_scores(score, highScores)

    write_high_scores(highScores)
    print_high_scores(highScores)

if __name__ == "__main__":
    main()

rawDescription: Python: creating a dictionary that writes high scores to a file


rawDescription: Find index of string in list

description: Find index of string in list


code:
if count[0] == '0':
    removed = ' ==> %s removed' % (fc)
else:
    removed = ''
print '%s records in %s%s' % ('{0:>9}'.format(count), fc, removed)

rawDescription: python: join print with previous printed line

description: Python: join print with previous printed line


code:
print 'Preall test works!'
from twisted.internet import reactor, protocol, defer
from twisted.python import log
import sys
print 'Imports done'

class PrgShell(protocol.Protocol):
    data = ''
    class PrgProto(protocol.ProcessProtocol):
        def __init__(self, out):
            print 'Prgproto instance made'
            self.transportout = out.transport
            self.out = out
        def outReceived(self, data):
            """Called when process sends data. We send it on to transport, however if it's 'I want input', we need to activate input."""
            print 'Sub said: '+data
            if data == "input":
                print 'Sub wants input'
                self.transportout.write("input")
                d = self.out.getWrit() # getWrit returns a deferred. We store it in d to make the code more readable
                d.addCallback(self.sendInput) # Here we add self.sendInput to the callback chain.
                                              # This way self.sendInput gets called with the user input.
            else:
                self.transportout.write(data)

        def sendInput(self, data):
            self.transport.write(data)

    def getWrit(self):
        print 'Proto gave input to prg'
        self.deferred = defer.deferred()
        self.data = ''
        return self.deferred

    def connectionMade(self):
        print 'Connected'
        proto = self.PrgProto(self)
        addr = "C:\\Documents and Settings\\papa\\My Documents\\Python\\Files\\Maze\\exe\\maze.exe"
        reactor.spawnProcess(proto, addr, ['maze'], {})
        print 'Procces spawned!'

    def dataReceived(self, data):
        print 'Data recived: '+data
        self.data+=data

        if self.data.endswith('\n'):
            if self.deferred:
                # We got a newline character, and there is a deferred to call, so lets call it
                d, self.deferred = self.deferred, None # This will set self.deferred to none to stop mistakes later

                d.callback(self.data) # Call the deferred with data. This will send the data to sendInput above.

                self.data = '' # Clear the buffer

print 'About to do stuff'
factory = protocol.ServerFactory()
factory.protocol = PrgShell
#f = open("errors.txt", 'w')
#log.startLogging(f)
#print 'Logging started'
reactor.listenTCP(8000,factory)
print 'Runing'
reactor.run()

rawDescription: What's wrong with my twisted server that's supposed to take a .exe and send its stdio to anyone who asks. Instead, it doesn't send anything


code:
s = "some string toc remainder of string"

s = s[:s.find('toc')]

print s  # some string

rawDescription: Chop off text when it reaches certain word in Python


code: print dict((s.split('=')+[1])[:2] for s in l)

rawDescription: How to create a dictionary from a list with a list of keys only and key-value pairs (Python)?

description: Create a dictionary from a list with a list of keys only and key-value pairs (Python)


code:
import subprocess
import locale

encoding = locale.getdefaultlocale()[1]
proc = subprocess.Popen(["ping", "123.123.123.123"], stdout=subprocess.PIPE)
out = proc.communicate()[0]
if 'Request timed out' in out.decode(encoding):
    print 'the host is down'
else:
    print 'the host is up'

rawDescription: How to detect what output is and do if statement from it?

description: Detect what output is and do if statement from it


code:
def add_name():
    if len(parent.curselection()) != 0:
        x = parent.get(parent.curselection())
        child.insert(END, x)
    else:
        print "select an element first"

def remove_name():
    if len(parent.curselection()) != 0:
        child.delete(child.curselection())
    else:
        print "select an element first"

rawDescription: Adding items from one tkinter listbox to another


code:
import caffe
import lmdb

lmdb_env = lmdb.open('directory_containing_mdb')
lmdb_txn = lmdb_env.begin()
lmdb_cursor = lmdb_txn.cursor()
datum = caffe.proto.caffe_pb2.Datum()

for key, value in lmdb_cursor:
    datum.ParseFromString(value)
    label = datum.label
    data = caffe.io.datum_to_array(datum)
    for l, d in zip(label, data):
            print l, d

rawDescription: Caffe: Reading LMDB from Python

description: Caffe: Reading LMDB from Python


code:
import struct

# Read all of the data
with open('data_ch04.dat', 'rb') as input_file:
    data = input_file.read()

# Convert to list of floats
format = '{:d}f'.format(len(data)//4)
data = struct.unpack(format, data)

# Display some of the data
print len(data), "entries"
print data[0], data[1], data[2], "..."

rawDescription: Unpacking a binary file with Python only returns one value


code:
def main():
  while True:
      print "*******Welcome to the MACRONUTRIENT CALCULATOR********"
      calorie_deficit = float(input("Enter your calorie deficit: "))
      Percent_protein = float(input("Percentage of Protein: "))
      Percent_carb = float(input("Percent of Carbohydrates: "))
      Percent_fat = float(input("Percentage of Fats: "))
      Macro_dict = {'Protein': Percent_protein, 'Carbohydrate': Percent_carb, 'Fats': Percent_fat}
      Macro_sum = Percent_protein + Percent_carb + Percent_fat
      if not Total_Macro_Check(Macro_sum):
          continue
      Macro_percentage_to_calorie(calorie_deficit, Percent_protein, Percent_carb, Percent_fat)

def Total_Macro_Check(total_val):
  if total_val > 100:
    print "Total percentages surpassed 100! Please reenter percentages."
    return False
  if total_val < 100:
    print "Total precentages is less than 100! Please reenter precentages."
    return False
  return True

rawDescription: restarting to main function

description: Restarting to main function


code:
from django.db.models.signals import post_save
from myapp.models import Car

def do_something(sender, **kwargs):
    print 'the object is now saved.'
    car = kwargs['instance'] #now i have access to the object

post_save.connect(do_something, sender=Car)

rawDescription: Cant get post_save to work in Django

description: Cant get post_save to work in Django


code:
def maybe_skip_member(app, what, name, obj, skip, options):
    print app, what, name, obj, skip, options
    return True

def setup(app):
    app.connect('autodoc-skip-member', maybe_skip_member)

rawDescription: Connect Sphinx autodoc-skip-member to my function


code:
response = requests.get('http://server/stream-forever', stream=True)
for data in response.iter_content(chunk_size=10):
    print data

rawDescription: Automate Streaming API with Python?

description: Automate Streaming API with Python


code:
import signal

RUN = True

def handle(a, b):
    global RUN
    print "handled"
    RUN = False

signal.signal(signal.SIGTERM, handle)
while RUN:
    signal.pause()
print "Stopping"

rawDescription: Why does using threading.Event result in SIGTERM not being caught?


code:
code=[1,2,4,7,2,6,8]
print [val for i,val in enumerate(code) if i%2==0]

rawDescription: how to extract from list python, element with index multiple of 2

description: Extract from list python, element with index multiple of 2


code:
author_A = [['book_x',1,10],['book_y',2,20],['book_z',3,30]]
author_B = [['book_s',5,10],['book_t',2,20],['book_z',3,30]]

def present(A, B):
  Aset = set(tuple(x) for x in A)
  Bset = set(tuple(x) for x in B)
  both = Aset & Bset
  justA = Aset - both
  justB = Bset - both
  totals = [0, 0]
  print "%-12s %-12s %12s" % ('author', 'quantity', 'Amount($)')
  for subset, name in zip((both, justA, justB), ('A*B', 'A', 'B')):
    tq = sum(x[1] for x in subset)
    ta = sum(x[2] for x in subset)
    totals[0] += tq
    totals[1] += ta
    print ' %-11s  %-11d    %-11d' % (name, tq, ta)
  print ' %-11s  %-11d    %-11d' % ('total', totals[0], totals[1])

present(author_A, author_B)

rawDescription: Help to solve my problems with python LIST?


code:
import time
import random
from Tkinter import *

class GetClicktime():
    def __init__(self):
        self.j=0
        self.t=[]
        self.mgui=Tk()
        self.mgui.geometry('200x200')
        self.mgui.title('Queue System')
        self.st = Button(self.mgui, text="Next Customer", command = self.PrintNumber)
        self.st.pack()
        #self.st.bind('<Button-1>',callback)
        self.label = Label(self.mgui, text=str(self.j))
        self.label.pack()
        self.mgui.mainloop()

    def PrintNumber(self):
       self.j+=1
       self.label.config(text=str(self.j))
       print self.j
       t = (time.strftime("%H:%M:%S"))
       d = time.strftime("%d/%m/%Y")
       self.t.append(int(t.replace(':','')))
       print self.t
       if self.j >2:
           print 'the time between clicks is:',self.t[self.j-1]-self.t[self.j-2],'seconds'
       print t,d
       return

if __name__ == "__main__":
    GetClicktime()

rawDescription: Count time intervals (secs) between 2 button clicks


code:
def searchWord(letters, word):
    count = 0
    for l in letters:
        count += word.count(l)

    return count

words = ['hello', 'world'];
letters = ['l', 'o']

currentWord  = None
currentCount = 0

for w in words:
    n = searchWord(letters, w)

    print "word:\t", w, " count:\t", n

    if n > currentCount:
        currentWord = w
        currentCount = n

print "highest word count:", currentWord

rawDescription: How do i search a list of words using a list of letters in python

description: Search a list of words using a list of letters in python


code:
# create two calendars
one = models.Calendar.objects.create(title='calendar one')
two = models.Calendar.objects.create(title='calendar two')

# attach event 1 to both calendars
event = models.Event.objects.create(title='event 1', start_date='2011-11-11')
one.event_set.add(event)
two.event_set.add(event)

# attach event 2 to calendar 2
two.event_set.add(models.Event.objects.create(title='event 2', start_date='2011-11-11'))

# get and print all events from calendar one
events_one = models.Calendar.objects.get(title='calendar one').event_set.all()
print [ event.title for event in events_one ]
# will print: [u'event 1']

# get and print all events from calendar two
events_two = models.Calendar.objects.get(title='calendar two').event_set.all()
print [ event.title for event in events_two ]
# will print: [u'event 1', u'event 2']

rawDescription: Queryset from a ManyToMany relation

description: Queryset from a ManyToMany relation


code:
class myClass():
    def __init__(self, member1 = 5):
        self.member1 = member1

def myFunction(x):
    var1 = myClass().member1
    print x, var1

myFunction(2)

rawDescription: Calling class members from function Definition


code:
from rauth.service import OAuth1Service

class TwitterClient:

    KNOWN_USERS = { # (access_token, access_token_secret)
        'user1' : ("xxx", "yyy")
    }

    def __init__(self):
        # Get a real consumer key & secret from https://dev.twitter.com/apps/new
        self.twitter = OAuth1Service(
            name='twitter',
            consumer_key=TWITTER_CONSUMER_KEY,
            consumer_secret=TWITTER_CONSUMER_SECRET,
            request_token_url='https://api.twitter.com/oauth/request_token',
            access_token_url='https://api.twitter.com/oauth/access_token',
            authorize_url='https://api.twitter.com/oauth/authorize',
            base_url='https://api.twitter.com/1/')

    def new_session(self):
        request_token, request_token_secret = self.twitter.get_request_token()
        authorize_url = self.twitter.get_authorize_url(request_token)
        print 'Visit this URL in your browser: ' + authorize_url
        pin = raw_input('Enter PIN from browser: ')
        session = self.twitter.get_auth_session(request_token,
                                                request_token_secret,
                                                method='POST',
                                                data={'oauth_verifier': pin})
        print session.access_token, session.access_token_secret # Save this to database
        return session

    def reuse_session(self, user):
        access_token, access_token_secret = self.KNOWN_USERS[user]
        session = self.twitter.get_session((access_token, access_token_secret))
        return session

    def init_session(self, user):
        if user in self.KNOWN_USERS : session = self.reuse_session(user)
        else                        : session = self.new_session()
        return session

    def list_tweets(self, user):
        session = self.init_session(user)
        params = {'include_rts': 1,  # Include retweets
                  'count': 10}       # 10 tweets

        r = session.get('statuses/home_timeline.json', params=params)

        for i, tweet in enumerate(r.json(), 1):
            handle = tweet['user']['screen_name'].encode('utf-8')
            text = tweet['text'].encode('utf-8')
            print '{0}. @{1} - {2}'.format(i, handle, text)

tc = TwitterClient()

tc.list_tweets('user1')

rawDescription: Reuse OAuth1 authorization tokens with rauth


code:
areas_to_print = ["Upper Bukit Timah", "West Coast", "Woodlands", "Yishun"]

for prop in sorted(prop_list):
    if prop["area"] in areas_to_print:
        print "Area: %(area)s\nSummary: %(summary)s\nLatitude: %(latitude)s\nLongitude: %(longitude)s\n" % prop

rawDescription: python pretty printing simple if

description: Python pretty printing simple if


code:
with open("filename.txt") as f:
    for line in f:
        if "Smith" in line:
             print line

rawDescription: Python: search file for a string and print the full line


code: print '\n'.join([str(factorial(x)) for x in range(0, 6)])

rawDescription: Printing every item on a new line in Python


code:
import sys
def f(task_list):
    results = []
    for task_id in task_list:
        results.append(work(task_id))
        print len(results) # show the progress
        sys.stdout.flush()  # this will force the system to display what is in the stdout queue
    return results

rawDescription: What is wrong with this way of showing the progress of the function?


code:
x="Hello there <something>, this is more text <tagged content>"
print re.sub(r"<([^>]*)>",r"\1added",x)

rawDescription: regex search and replace with modified result

description: Regex search and replace with modified result


code:
import xml.dom.minidom

DOMTree = xml.dom.minidom.parse("C:/Users/Desktop/PythonXMLproject/Smallfile.xml")
collection = DOMTree.documentElement

instrumentDatas = collection.getElementsByTagName("instrumentData")

for instrumentData in instrumentDatas:
    idx = instrumentData.getElementsByTagName("id")[0].firstChild.data
    print "ID: %s" % idx
    datas = instrumentData.getElementsByTagName("data")
    for data in datas:
        if data.hasAttribute('value'):
            value = data.getAttribute('value')
            print "Value: %s" % value

rawDescription: XML reading Data with Python

description: XML reading Data with Python


code:
arr = np.array(a)
xa, ya, val = arr.T
pts = (xa >= start) & (ya <= end)
print arr[pts]

rawDescription: Subset of a python list

description: Subset of a python list