code:
import bugzilla
bz = bugzilla.Bugzilla(url="https://bugzilla.kernel.org")

print bz._proxy.Bug.fields({"names" : ["rep_platform"]})

rawDescription: how to retrieve field values from python-bugzilla xml-rpc

description: Retrieve field values from python-bugzilla xml-rpc


code:
import gzip, subprocess, os
fifo_path = "path/to/fastload-fifo"
os.mkfifo(fifo_path)
fastload_fifo = open(fifo_path)
fastload = subprocess.Popen(["fastload", "--read-from", fifo_path],
                            stdin=subprocess.PIPE)
with gzip.open("/path/to/file/myfile.gz") as f:
    for i, line in enumerate(f):
         fastload_fifo.write(line)
    print "Number of lines", i + 1
os.unlink(fifo_path)

rawDescription: Pythonic way to send contents of a file to a pipe and count # lines in a single step


code:
from itertools import repeat

def insert_and_process((file_to_process,db)):
    db = DAL("path_to_mysql" + db)
    #Table Definations
    db.table.insert(**parse_file(file_to_process))
    return True

if __name__=="__main__":
    file_list=os.listdir(".")
    P = Pool(processes=4)
    P.map(insert_and_process,zip(file_list,repeat(db)))

rawDescription: multiprocessing.pool.map and function with two arguments

description: Multiprocessing.pool.map and function with two arguments


code:
import httplib
import xml.dom.minidom

data = """
<spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="1" ignoreallcaps="1">
    <text> %s </text>
</spellrequest>
"""

word_to_spell = "gooooooogle"

con = httplib.HTTPSConnection("www.google.com")
con.request("POST", "/tbproxy/spell?lang=en", data % word_to_spell)
response = con.getresponse()

dom = xml.dom.minidom.parseString(response.read())
dom_data = dom.getElementsByTagName('spellresult')[0]

for child_node in dom_data.childNodes:
    result = child_node.firstChild.data.split()

print result

rawDescription: Using the RESTful interface to Google's AJAX Search API for "Did you mean"?


rawDescription: Conver integer to cryptocurrency

description: Conver integer to cryptocurrency


code:
from collections import defaultdict
import csv

class PlayerStat(object):
    def __init__(self, yds=0, car=0, td=0, fum=0, ypc=0, count=0):
        self.yds   = float(yds)
        self.car   = float(car)
        self.td    = float(td)
        self.fum   = float(fum)
        self.ypc   = float(ypc)
        self.count = count
    def __iadd__(self, other):
        self.yds   += other.yds
        self.car   += other.car
        self.td    += other.td
        self.fum   += other.fum
        self.ypc   += other.ypc
        self.count += other.count
        return self

filenames = 'NewRush4.csv', 'NewRush5.csv', 'NewRush6.csv',
stats = defaultdict(PlayerStat)
for filename in filenames:
    with open(filename) as f:
        reader = csv.DictReader(f, delimiter=',')
        for row in reader:
            stat = PlayerStat(row['YDS'], row['CAR'], row['TD'], row['FUM'], row['YPC'], count=1)
            stats[row['Player']] += stat

for player in sorted(stats, key=lambda player: stats[player].yds):
    stat = stats[player]
    if stat.count == 1:
        continue
    print '{0:<20}{1.car:>10}{1.yds:>10}{1.td:>10}{1.fum:>10}{1.ypc:>10}'.format(player, stat)

rawDescription: Read and combine data from multiple csv files


code:
import wx

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

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

        self.main_sizer = wx.BoxSizer(wx.VERTICAL)
        add_btn = wx.Button(self, label='Add')
        add_btn.Bind(wx.EVT_BUTTON, self.add_button)

        self.main_sizer.Add(add_btn, 0, wx.CENTER|wx.ALL, 5)
        self.SetSizer(self.main_sizer)

    #----------------------------------------------------------------------
    def add_button(self, event):
        """"""
        new_btn = wx.Button(self, label="Remove %s" % self.btns)
        new_btn.Bind(wx.EVT_BUTTON, self.remove_button)
        self.btns += 1
        self.main_sizer.Add(new_btn, 0, wx.CENTER|wx.ALL, 5)
        self.main_sizer.Layout()

    #----------------------------------------------------------------------
    def remove_button(self, event):
        """"""
        btn = event.GetEventObject()
        print "Deleting %s button" % btn.GetLabel()
        self.main_sizer.Hide(btn)
        self.main_sizer.Remove(btn)
        self.main_sizer.Layout()

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

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Buttons")
        panel = MyPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

rawDescription: A simple example for adding and removing buttons in wxpython


code:
for line in open("file"):
    li=line.strip()
    if not li.startswith("#"):
        print line.rstrip()

rawDescription: Python: How to ignore #comment lines when reading in a file


code:
template = open('/temp/template.txt','r')
new_elements = iter(["movie1","movies2"])

for i in template.readlines():
    if "movie" in i:
        print "replace line with", new_elements.next()

rawDescription: replacing lines with elements from a list

description: Replacing lines with elements from a list


code:
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'):
    """Converts an integer to a base36 string."""
    if not isinstance(number, (int, long)):
        raise TypeError('number must be an integer')

    base36 = ''
    sign = ''

    if number < 0:
        sign = '-'
        number = -number

    if 0 <= number < len(alphabet):
        return sign + alphabet[number]

    while number != 0:
        number, i = divmod(number, len(alphabet))
        base36 = alphabet[i] + base36

    return sign + base36

def base36decode(number):
    return int(number, 36)

print base36encode(1412823931503067241)
print base36decode('AQF8AA0006EH')

rawDescription: Python base 36 encoding

description: Python base 36 encoding


code:
def import_non_local(name, custom_name=None):
    import imp, sys

    custom_name = custom_name or name

    f, pathname, desc = imp.find_module(name, sys.path[1:])
    module = imp.load_module(custom_name, f, pathname, desc)
    f.close()

    return module

# Import non-local module, use a custom name to differentiate it from local
# This name is only used internally for identifying the module. We decide
# the name in the local scope by assigning it to the variable calendar.
calendar = import_non_local('calendar','std_calendar')

# import local module normally, as calendar_local
import calendar as calendar_local

print calendar.Calendar
print calendar_local

rawDescription: Importing from builtin library when module with same name exists


code:
if produce_name in produce2:
    print "Added %s to %s" % (produce_stock, produce_name)

rawDescription: How to get a variable to equal one of the strings within a list in Python

description: Get a variable to equal one of the strings within a list in Python


code:
def my_filter(iterable):
    result=[]
    for i in iterable:
        result.append(i)
        if i==5:
            continue
        yield result
        result=[]

idx = iter(range(0, 10))

for i in my_filter(idx):
    print i

rawDescription: Python: access to iterator-object in for-loops


code: print ''.join([chr(x) for x in range(256)])

rawDescription: Python. Chess symbol in windows cmd

description: Python. Chess symbol in windows cmd


code:
import unittest

class Test(unittest.TestCase):

    def test_one(self):
        print "Foo"

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

rawDescription: Selenium tests - Everything is printed all the time no matter what


code:
r=zip(*Lt)[0]
print Lt

rawDescription: Python: Trim a list

description: Python: Trim a list


code:
def parse_dir_contents(self, response):
 # select xpath here
 print '________________________BEGIN PRODUCT________________________'
 item = detailedItem()
 item['title'] = sites.xpath('//*[@id="product-name"]/text()').extract()

 # get url_2 from this page

 request = scrapy.Request(url_2, callback=self.parse_detailed_contents,dont_filter=True)
 request.meta['item'] = item
 yield request

rawDescription: Scrapy callback function

description: Scrapy callback function


code:
print "nana", "dada %d " % 2,
sys.stderr.write("hey")         # no newline
print                           # print the newline here

rawDescription: Print sys.stderr along normal print in python


code:
import xml.etree.ElementTree as ET

def GetMapData( xmlfile ):
    result = ""
    try:
        tree = ET.parse( xmlfile )
    except IOError, e:
        print "Failure Parsing %s: %s" % (xmlfile, e)
    root = tree.getroot() # root node
    for child in root:
        if ( child.tag == 'LandmarkPointListXml' ):
            result += '|' + loopLandmark(child) + '|'
        elif child.text is not None:
            result += child.text + ','
    return result

def loopLandmark( landmarks ):
    result=""
    for landmark in landmarks:
        if ( landmark.tag == 'anyType' ): # check also xsi:type="LandmarkPointProperty"?
            for child in landmark:
                if ( child.text and child.tag in [ 'LandmarkPointX', 'LandmarkPointY' ] ):
                    result += child.text + ','
    return result

GetMapData( 'xml.in' )

rawDescription: How to extract data from XML using python minidom

description: Extract data from XML using python minidom


code:
#!/usr/bin/python

url = "svn://server/path/to/repo"
path = "/path/to/local/wc"

import pysvn
import threading

# Set to something reasonable
SVN_TIMEOUT = 1000

svn_timer = None
stop_svn = False

def timer_expired():
    # Too long since last SVN event, so do something sensible...
    print "SVN took too long!"
    global stop_svn
    stop_svn = True

def svn_cancel():
    return stop_svn

def notify( event_dict ):
    global svn_timer
    if svn_timer:
        svn_timer.cancel()
    svn_timer = threading.Timer(SVN_TIMEOUT, timer_expired)
    svn_timer.start()

svn_client = pysvn.Client()
svn_client.callback_notify = notify
svn_client.callback_cancel = svn_cancel

svn_timer = threading.Timer(SVN_TIMEOUT, timer_expired)
svn_timer.start()

revision = svn_client.checkout(url,path)

if svn_timer:
    svn_timer.cancel()

rawDescription: Watch over another process (svn)

description: Watch over another process (svn)


rawDescription: Just returning the text of elements in xpath (python / lxml)


code:
from lxml import etree

xml = etree.XML("<root>ABCDoes not existDEFGHI</root>")

print 'Before:'
print etree.tostring(xml)

xp = etree.XPath("/*/*[not(@name)]") # or "//*[not(@name)]" to include the root tag
all_nodes = xp(xml)
for x in all_nodes:
    parent = x.getparent()
    #if parent is None: continue # if the root tag is included, the parent is None
    parent.remove(x)

print 'After:'
print etree.tostring(xml)

rawDescription: Force attribute exists in tags in XML

description: Force attribute exists in tags in XML


code:
import re

import requests
from bs4 import BeautifulSoup

response = requests.get("https://www.sec.gov/Archives/edgar/data/36405/000093247115006447/indexfunds_final.htm")
soup = BeautifulSoup(response.content)

futures = soup.find_all(text=re.compile('C. Futures Contract'))
for future in futures:
    for row in future.find_next("table").find_all("tr"):
        print [cell.get_text(strip=True) for cell in row.find_all("td")]

rawDescription: How to extract table from SEC N-Q doc using BeautifulSoup

description: Extract table from SEC N-Q doc using BeautifulSoup


code:
def update(mylist, row, col, cmprow, cmpcol):
    lo, hi = mylist[row][col]
    low, high = mylist[cmprow][cmpcol]

    # always replace the current value if it's (-1, -1)
    if (lo, hi) == (-1, -1):
        mylist[row][col] = low, high
        print "replacing empty", row, col, "with", cmprow, cmpcol
        return

    # never replace the current value if the ranges don't overlap
    # or the other range is (-1, -1)
    if (low, high) == (-1, -1) or lo >= high or hi <= low:
        print row, col, "doesn't overlap", cmprow, cmpcol
        return

    # set the low to the highest low and the high to the lowest high
    print "updating", row, col, "with", cmprow, cmpcol
    mylist[row][col] = max((lo, low)), min((hi, high))

def update_ranges(oldlist):
    # make a copy of the list as we're going to modify it
    mylist = oldlist[:]
    # we don't need the row titles, they just complicate things
    rowtitles, mylist = zip(*mylist)
    rows = len(mylist)
    columns = range(len(mylist[0]))

    # for each row except the last
    for i in xrange(rows - 1):
        # update it by going down all the rows below it
        for k in xrange(i+1, rows):
            # for both columns
            for j in columns:
                update(mylist, i, j, k, j)

    # put the row titles back in
    mylist = zip(rowtitles, mylist)
    return mylist

def test():
    oldlist = [ ('a', [ (-1, -1), (0.2, 0.4) ] ),
               ('b', [ (0.3, 1.0), (-1, -1) ] ),
               ('c', [ (-1, -1), (-1, -1) ] ),
               ('d', [ (0.15, 0.35), (0.05, 0.15) ] ) ]
    print "Original List"
    print '\n'.join(str(l) for l in oldlist)
    newlist = update_ranges(oldlist)
    print "New List"
    print '\n'.join(str(l) for l in newlist)

if __name__ == '__main__':
    test()

rawDescription: comparing and replacing the elements of a nested list

description: Comparing and replacing the elements of a nested list


code:
from multiprocessing import Process, Manager
from multiprocessing.managers import BaseManager, SyncManager
from time import sleep
import signal

#handle SIGINT from SyncManager object
def mgr_sig_handler(signal, frame):
    print 'not closing the mgr'

#initilizer for SyncManager
def mgr_init():
    signal.signal(signal.SIGINT, mgr_sig_handler)
    #signal.signal(signal.SIGINT, signal.SIG_IGN) # <- OR do this to just ignore the signal
    print 'initialized mananger'

def f(process_number, shared_array):
    try:
        print "starting thread: ", process_number
        shared_array.append(process_number)
        sleep(3)
        shared_array.append(process_number)
    except KeyboardInterrupt:
        print "Keyboard interrupt in process: ", process_number
    finally:
        print "cleaning up thread", process_number

if __name__ == '__main__':

    processes = []

     #using syncmanager directly instead of letting Manager() do it for me
    manager = SyncManager()
    manager.start(mgr_init)  #fire up the child manager process
    shared_array = manager.list()

    for i in xrange(4):
        p = Process(target=f, args=(i, shared_array))
        p.start()
        processes.append(p)

    try:
        for process in processes:
            process.join()
    except KeyboardInterrupt:
        print "Keyboard interrupt in main"

    for item in shared_array:
        print item

rawDescription: Keyboard Interrupt with python's multiprocessing


code:
from random import choice
from itertools import permutations
data = list(permutations([1, 2, 3], 3))[1:]
for _ in range(10):
    print choice(data)

rawDescription: Shuffle a small set of items

description: Shuffle a small set of items


code:
import gc

def foo():
    code = """
class DummyA(object):
    pass
"""
    context = {}
    exec code in context
    exec code in context

    gc.collect()
    print len(gc.garbage), len(gc.get_objects())

gc.enable()
foo(); foo() # amount of objects doesn't increase
gc.set_debug(gc.DEBUG_LEAK)
foo() # leaks

rawDescription: In python, how can you unload generated classes


code:
import sys

def search_func_a(l):
    """
    Called for things that follow `search key A`
    """
    print 'A: %s' % l

def search_func_b(l):
    """
    Called for things that follow `search key B`
    """
    print 'B: %s' % l

def search_key_func(l):
    """
    Returns the associated "search function" for each search string.
    """
    if 'search key A' in l:
        return search_func_a
    if 'search key B' in l:
        return search_func_b
    return None

def main():
    # Start with a default handler.  This changes as `search key` lines are
    # found.
    handler = lambda _: 0

    for line in open('test.txt'):
        # search_key_func returns None for non `search key` lines.  In that
        # case, continue to use the last `search function` found.
        search_func = search_key_func(line)
        if search_func:
            # If a search line is found, don't pass it into the search func.
            handler = search_func
            continue
        handler(line)

if __name__ == '__main__':
    sys.exit(main())

rawDescription: Passing Partial Lists into Python Function


code:
def reverse(num):
  return int(str(num)[::-1])

largest = None
for y in range (100,999):
    for x in range (100,999):
        xy = x*y
        if xy > largest and xy == reverse(xy):
            largest = xy
print largest

rawDescription: Only print max value (python)

description: Only print max value (python)


code:
class Car():

    def __init__(self, mileage=0, mpg=10, tank_capacity=5):
        self.mileage = mileage
        self.mpg = mpg
        self.tank_capacity=tank_capacity
        self.tank_level = 0

    def drive(self, miles):
        gallons_burned = float(miles) / self.mpg
        if self.tank_level < gallons_burned:
            miles_driven = float(self.tank_level) * self.mpg
            self.tank_level = 0
            self.mileage += miles_driven
            print "You ran out of gas after %s miles." % miles_driven
            return
        self.tank_level -= gallons_burned
        self.mileage += miles
        print "You made it to your destination after %s miles." % miles

    def pump_gas(self, gallons):
        self.tank_level += gallons
        if self.tank_level > self.tank_capacity:
            self.tank_level = self.tank_capacity
        print "You now have %s gallons in your tank" % self.tank_level

    def status(self):
        print "Mileage:", self.mileage
        print "Tank level: %s gallons" % self.tank_level

if __name__ == "__main__":
    my_car = Car(mileage=100, mpg=30, tank_capacity=3)
    my_car.pump_gas(4)
    my_car.status()
    my_car.drive(50)
    my_car.status()
    my_car.drive(60)
    my_car.status()

"""
You now have 3 gallons in your tank
Mileage: 100
Tank level: 3 gallons
You made it to your destination after 50 miles.
Mileage: 150
Tank level: 1.33333333333 gallons
You ran out of gas after 40.0 miles.
Mileage: 190.0
Tank level: 0 gallons
"""

rawDescription: python, changing functions into classes and objects

description: Python, changing functions into classes and objects


code:
from random import choice
from words import four_letter_words

print choice(four_letter_words)

rawDescription: Access an array in a separate file?

description: Access an array in a separate file


code:
dblist = [(0, ['word1', 'word2', 'word3', 'word4']), (1, ['word5', 'word6', 'word7', 'word8']), (2, ['word1', 'word9', 'word3', 'word7'])]
dbrow = ['word1', 'word2', 'word10', 'word7', 'word3']

for class_idx, kwords in dblist:
    if len(set(dbrow) & set(kwords)) == 2:
        print kwords  # or do whatever you need

rawDescription: Comparison of two lists in python

description: Comparison of two lists in python


code:
import glib, sys, os, fcntl

class IODriver(object):
    def __init__(self, line_callback):
        self.buffer = ''
        self.line_callback = line_callback
        flags = fcntl.fcntl(sys.stdin.fileno(), fcntl.F_GETFL)
        flags |= os.O_NONBLOCK
        fcntl.fcntl(sys.stdin.fileno(), fcntl.F_SETFL, flags)
        glib.io_add_watch(sys.stdin, glib.IO_IN, self.io_callback)

    def io_callback(self, fd, condition):
        chunk = fd.read()
        for char in chunk:
            self.buffer += char
            if char == '\n':
                self.line_callback(self.buffer)
                self.buffer = ''

        return True

def line_entered(line):
    print "You have typed:", line.strip()

d = IODriver(line_entered)

rawDescription: interactive console for my mainloop app

description: Interactive console for my mainloop app


code:
a_flat = [(i, j, item) for i, sublst in enumerate(a) for j, item in enumerate(sublst)]
choices = random.sample(a_flat, 3)

for c in choices:
    print c

(2, 3, [0.2, 2.1])
(3, 0, [0.4, 1.3])
(1, 0, [0.6, 4.5])

rawDescription: Return random sub-sub-list and its indexes from list


code:
class MaxSpider(CrawlSpider):
    name = "max"
    allowed_domains = ["maxmind.com"]
    start_urls = ["https://www.maxmind.com/en/geoip-demo"]

def __init__(self):
    self.driver = webdriver.Firefox()

def parse(self, response):
    self.driver.get(response.url)
    button = self.driver.find_element_by_id('addresses')
    login_form = self.driver.find_element_by_id('addresses')
    actions = ActionChains(self.driver)
    actions.click(login_form)
    actions.perform()
    login_form.send_keys("62.237.72.200")
    submit = self.driver.find_element_by_xpath('//*[@id="geoip-demo-form"]/button')
    actions.click(submit)
    time.sleep(3)
    for element in self.driver.find_elements_by_id('geoip-demo-results-tbody'):
       print element.text
    self.driver.close()

rawDescription: How to use Python to get elements that do not appear in HTML, but appear in "Inspect Element" tool of Chrome?

description: Use Python to get elements that do not appear in HTML, but appear in "Inspect Element" tool of Chrome


code:
tree = ET.parse('unified.xml')
root = tree.getroot()
for child in root.findall('object'):
    for tag in child.findall('tag'):
        print tag.text

rawDescription: ElementTree parsing the next tag in Python


code:
import subprocess
ls = subprocess.Popen(['ssh','user@xx.xx.xx.xx', 'ls'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err =  ls.communicate()
print out
print err

rawDescription: Remote Directory Listing Python WSGI

description: Remote Directory Listing Python WSGI


code:
dataset = ['Sensor_01', 'Sensor_02', 'Sensor_03']
for i in range(len(dataset)):
    dataset[i] = dataset[i].replace('Sensor_', '')
print dataset

rawDescription: How do I use Regex to remove "Sensor_" from a data set? this is example set, ["Sensor_01", "Sensor_10"}

description: Use Regex to remove "Sensor_" from a data set? this is example set, ["Sensor_01", "Sensor_10"}


code:
my_list = [3, 1, 2]
sorted_list = sorted(my_list)
sorted_list
my_list
print my_list.sort()
my_list

rawDescription: Python sorted() vs .sort() for directory list


code:
with open(os.path.join(dirname, filename), "r") as f:
    for line in f:
        if 'date' in line:
            print line
            break
    else:
        print "no date"

rawDescription: Else statement to print once in python

description: Else statement to print once in python


code:
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

rawDescription: Easier Way to Write Python Console Programs (do args exist)


code:
import artm
batch_vectorizer = artm.BatchVectorizer(data_path=r'D:\Datasets\kos',
                                        data_format='batches')
dictionary = artm.Dictionary(data_path=r'D:\Datasets\kos')
model = artm.ARTM(num_topics=15,
                  num_document_passes=5,
                  dictionary=dictionary,
                  scores=[artm.TopTokensScore(name='top_tokens_score')])

model.fit_offline(batch_vectorizer=batch_vectorizer, num_collection_passes=3)

top_tokens = model.score_tracker['top_tokens_score']
for topic_name in model.topic_names:
    print '\n', topic_name
    for (token, weight) in zip(top_tokens.last_tokens[topic_name],
                               top_tokens.last_weights[topic_name]):
        print token, '-', weight

rawDescription: How to iterate through top words in BigARTM?

description: Iterate through top words in BigARTM


code:
import gdata.gauth

Client_id='xxx';
Client_secret='yyy'
Scope='https://spreadsheets.google.com/feeds/'
User_agent='myself'

token = gdata.gauth.OAuth2Token(client_id=Client_id,client_secret=Client_secret,scope=Scope,user_agent=User_agent)
print token.generate_authorize_url(redirect_uri='urn:ietf:wg:oauth:2.0:oob')
code = raw_input('What is the verification code? ').strip()
token.get_access_token(code)
print "Refresh token\n"
print token.refresh_token
print "Access Token\n"
print token.access_token

rawDescription: Gdata python Google apps authentication

description: Gdata python Google apps authentication


code:
from itertools import groupby
from operator import itemgetter
data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28]
for k, g in groupby(enumerate(data), lambda (i, x): i-x):
    print map(itemgetter(1), g)

rawDescription: Detecting consecutive integers in a list


code:
import urllib
import cv2
from win32api import GetSystemMetrics

#the [x, y] for each right-click event will be stored here
right_clicks = list()

#this function will be called whenever the mouse is right-clicked
def mouse_callback(event, x, y, flags, params):

    #right-click event value is 2
    if event == 2:
        global right_clicks

        #store the coordinates of the right-click event
        right_clicks.append([x, y])

        #this just verifies that the mouse data is being collected
        #you probably want to remove this later
        print right_clicks

path_image = urllib.urlretrieve("http://www.bellazon.com/main/uploads/monthly_06_2013/post-37737-0-06086500-1371727837.jpg", "local-filename.jpg")[0]
img = cv2.imread(path_image,0)
width = GetSystemMetrics(0)
height = GetSystemMetrics(1)
scale_width = 640 / img.shape[1]
scale_height = 480 / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)
cv2.namedWindow('image', cv2.WINDOW_NORMAL)
cv2.resizeWindow('image', window_width, window_height)

#set mouse callback function for window
cv2.setMouseCallback('image', mouse_callback)

cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: Get pixel location using mouse click/events


rawDescription: list with xyz values to dictionary

description: List with xyz values to dictionary


code:
s = 'hello'
print repr(s)

rawDescription: Printing a string with the parentheses attched


code:
try:
 import mymodule
except ImportError, e:
 pass # module doesn't exist, deal with it.

rawDescription: Check if Python Package is installed

description: Check if Python Package is installed


code:
from collections import deque

deque_crc = deque([0,0,0,0,0],maxlen=5)

myID.extend(deque_crc)

for x in myID:
    deque_crc.rotate(-1)
    deque_crc[2] = (deque_crc[2] + deque_crc[4]) % 2
    deque_crc[4] = (deque_crc[4] + x) % 2

myID[-5:] = deque_crc

print myID

rawDescription: Python: CRC implementation using xor and shift registers


code:
class Countable(object):
    counter = 0
    def __new__(cls, *a, **kw):
        instance = super(Countable, cls).__new__(cls, *a, **kw)
        instance.id = cls.counter + 1
        cls.counter = instance.id
        return instance

class A(Countable):
    pass

class B(Countable):
    pass

print A().id, A().id   # 1 2
print B().id           # 1

rawDescription: What is the most Pythonic way of implementing classes with auto-incrementing instance attributes?


code:
#!/usr/bin/python
import os
import time
import urllib2

os.system("gpio mode 6 out && gpio mode 5 out")

while True:
    try:
        urllib2.urlopen("http://www.google.com").close()
    except urllib2.URLError:
        print "Not Connected"
        os.system("gpio write 6 0 && gpio write 5 1")
        time.sleep(1)
    else:
        print "Connected"
        os.system("gpio write 6 1 && gpio write 5 0")
        break

rawDescription: How to detect if Computer is contacted to the internet with Python?

description: Detect if Computer is contacted to the internet with Python


code:
#!/bin/env python

import logging
import logging.handlers
import logging.config

class Test1TimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
    def __init__(self,filename):
        print "init called"
        logging.handlers.TimedRotatingFileHandler.__init__(self,filename, when='S', interval=86400, backupCount=8, encoding=None)

    def __del__(self):
        print "del called"
        if hasattr(logging.handlers.TimedRotatingFileHandler,"__del__"):
            logging.handlers.TimedRotatingFileHandler.__del__(self)

if __name__ == "__main__":
    logging.config.fileConfig('./test1.conf')
    logger = logging.getLogger("test1")

rawDescription: Python logging: Why is __init__ called twice?


code:
def_m = "(logs125 >= 0)&(logs125 <=3)&(loudestonedge==0)&(geocontained==1)"
mask1 = eval(def_m)
print def_m

rawDescription: How to print definition of a variable in python?

description: Print definition of a variable in python


code:
from PIL import Image

def get_num_pixels(filepath):
    width, height = Image.open(open(filepath)).size
    return width*height

print get_num_pixels("/path/to/my/file.jpg")

rawDescription: How can I read how many pixels an image has in Python

description: Read how many pixels an image has in Python


code:
#! /usr/bin/env python
import sys
locals = dict()
for line in sys.stdin:
    saved = locals.copy()
    stmt = compile(line, '<stdin>', 'single')
    eval(stmt, None, locals)
    print line.strip(),
    for (k,v) in locals.iteritems():
        if k not in saved:
            print '=', v,
    print

rawDescription: How to accomplish this in python?

description: Accomplish this in python


code:
class HeroCarousel(unittest.TestCase):

    def setUp(self):
        self.drivers = [] #could make this with list comprehension
        for driver_instance in globes.desired_cap:
            driver = webdriver.Remote(
                command_executor=globes.selenium_server_url,
                desired_capabilities=driver_instance)
            self.drivers.append(driver)

        self.verificationErrors = []

    def test_hero_carousel(self):
        for driver in self.drivers:
            driver.get(globes.base_url)

            hero_carousel = driver.find_element(By.CSS_SELECTOR, 'div.carousel-featured')
            try: self.assertTrue(hero_carousel.is_displayed())
            except AssertionError, e: self.verificationErrors.append("home_test: Hero Carousel was not visible")

    def tearDown(self):
        for driver in self.drivers:
            driver.close()
        self.assertEqual([], self.verificationErrors)

rawDescription: Selenium Hub, Launches 2 browser only runs test in 1 of them (selenium python)


code:
folder = "path/folder/to/read/"
file_names = [fn for fn in listdir(folder) if isfile(join(folder,fn))]
count = -1
for f in file_names:
    count = count + 1
    print "[%s] " % count + f

while True:
    ans_file = input("Select file: ")
    if ans_file > count:
        print "Wrong selection."
        continue
    path = folder + file_names[ans_file]
    print "Selected file: %s " % path
    break

rawDescription: Create dynamic menu from os.listdir

description: Create dynamic menu from os.listdir


code:
def prog_callback(param, current, total):
    pct = 100 - ((total - current ) *100 )/ (total)
    print "Progress: %s " % pct

datagen, headers = multipart_encode({
                                    "post": "1",
                                    "skin": "xmlhttprequest",
                                    "userlogin": "%s" % username,
                                    "password": "%s" % password,
                                    "item_type": "file",
                                    "title": "%s" % title.encode("utf-8"),
                                    "description": "%s" % description.encode("utf-8"),
                                     "file": filename
                                     }, cb=prog_callback)

opener = register_openers()

req = urllib2.Request(UPLOAD_URL, datagen, headers)
response = urllib2.urlopen(req)
return response.read()

rawDescription: Python HTTPConnection file send with httplib, retrieving progress


code:
def depends(*deps):
    def deco(func):
        def __new__(self):
            super(Dependency, self).__new__(self)
            return func()
        Dependency = type('Dependency', deps, {'__new__': __new__})
        return Dependency
    return deco

@depends(object)
def f():
    print 'using f'

@depends(f)
def g():
    print 'using g'

@depends(g, f)
def h():
    print 'using h'

h()
# using f
# using g
# using h

rawDescription: Dependency decorator with no duplictates


code:
your_list = ["Word", "Palabra"]
if "Word" in your_list:
    print "Found!"
    DoSmth()

rawDescription: Python String Parts

description: Python String Parts


code:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class User(Base):
    __tablename__ = 'user'
    id = Column(Integer, primary_key=True)
    name = Column(String, nullable=False, index=True)
    variant = Column(Integer, nullable=False, index=True)

    def __init__(self, name):
        self.name = name
        self.variant = select([func.count(User.id)]).where(User.name == self.name)

e = create_engine("sqlite://", echo=True)

Base.metadata.create_all(e)

s = Session(e)

s.add(User(name='n1'))
s.commit()

s.add(User(name='n1'))
s.commit()

print s.query(User.variant).all()

rawDescription: SqlAlchemy: Self referencing default value as query


code:
import sys
def special_func(x):
    callingframe = sys._getframe(1)
    print 'My caller is the %r function in a %r class' % (
        callingframe.f_code.co_name,
        callingframe.f_locals['self'].__class__.__name__)

rawDescription: Get function callers' information in python


code:
import re
print re.sub(r'(\D+)(\d)$',r'\g<1>0\2','file1')

rawDescription: Python regex reference conflicting with substitution number


code:
import xml.dom.minidom

def parsed_dict(attrs):
    return dict(xml.dom.minidom.parseString('<node {}/>'.format(attrs)).firstChild.attributes.items())

print parsed_dict('level="Information" clientAddr="127.0.0.1" action="GetByName" message="Action completed" url="/customers/foo" method="GET"')

{u'clientAddr': u'127.0.0.1', u'level': u'Information', u'url': u'/customers/foo', u'action': u'GetByName', u'message': u'Action completed', u'method': u'GET'}

rawDescription: Parse log text in Python using Regex

description: Parse log text in Python using Regex


code:
#!/usr/bin/env python

def main():
    entries=[]
    while True:
        entries.append(raw_input('input something: '))
        if not len(entries[-1]):
            entries=entries[:-1]
            break
    counter=len(entries)
    print 'counter %d, entries %s.' % (counter, entries)

if (__name__ == "__main__"):
    main()

rawDescription: Making a Python3 Variable Using a Counter


code:
yourDict = {u'type': u'Point', u'coordinates': [-38.386702, -12.950518]}
latitude, longitude  = yourDict['coordinates']

print latitude
#=> -38.386702

print longitude
#=> -12.950518

rawDescription: Getting the two values from Python

description: Getting the two values from Python


code:
import json

response = requests.get('http://api.appannie.com/v1/accounts/1000/apps/mysuperapp/sales?break_down=application+iap&start_date=2013-10-01&end_date=2013-10-02',
                        auth=('username', 'password'))
data = json.loads(response.json()) # data is a dictionary now

sales_list = data.get('sales_list')
for sales in sales_list:
    print sales['revenue']['app']

rawDescription: Parse this JSON response From App Annie in Python


code:
withDups = "The Quick Brown Fox Jumped Over The Lazy Dog"
withoutDups = ""

for letter in withDups:
    if letter not in withoutDups:
        withoutDups += letter

print withoutDups

rawDescription: Python Removing Duplicates in a String Using in and not in


code:
from subprocess import Popen, PIPE
proc = Popen(["ls", '-la'], stdout=PIPE) # if you want more, add after "-la"
print proc.stdout.readlines()

rawDescription: Calling a command from external software using Popen() function


code:
with open("file.txt", "r") as fh1:
    array = []
    counter = 0
    for line in fh1:
        line = line.rstrip("\n")
        counter +=1
        array.append((line, counter))
for line, counter in (array):
    print line, ":", counter

rawDescription: Python: Print iterates too many times

description: Python: Print iterates too many times


code:
class Test(models.Model):
    class Meta:
        app_label = 'ignore'
        db_table = 'T'
    a = models.IntegerField()
    b = models.IntegerField()
    c = models.IntegerField()
    d = models.IntegerField()

result = Test.objects.values('c', 'd').annotate(Sum('a'), Sum('b'))
print str(result.query)

rawDescription: can django support group by some columns at the same time sum on other columns

description: Can django support group by some columns at the same time sum on other columns


code:
# importing the necessary libraries
import win32com.client
from win32com.client import constants

PowerPoint=win32com.client.Dispatch("PowerPoint.Application")
Excel=win32com.client.Dispatch("Excel.Application")

presentation=PowerPoint.Presentations.Add(True)
workbook=Excel.Workbooks.Open(Filename="C:\\.........\\workbook_with_charts.xlsx",ReadOnly=1,UpdateLinks=False)

for ws in workbook.Worksheets:
    for chart in ws.ChartObjects():
    # Copying all the charts from excel
        chart.Activate()
        chart.Copy()

        Slide=presentation.Slides.Add(presentation.Slides.Count+1,constants.ppLayoutBlank)
        Slide.Shapes.PasteSpecial(constants.ppPasteShape)

    # WE are going to make the title of slide the same chart title
    # This is optional
    textbox=Slide.Shapes.AddTextbox(1,100,100,200,300)
    textbox.TextFrame.TextRange.Text=str(chart.Chart.ChartTitle.Text)

presentation.SaveAs("C:\\...........\\Final_PowerPoint.pptx")
presentation.Close()
workbook.Close()

print 'Charts Finished Copying to Powerpoint Presentation'

Excel.Quit()
PowerPoint.Quit()

rawDescription: Charts from Excel to PowerPoint with Python


code:
import inspect

def print_local_namespace():
    ns = inspect.stack()[1][0].f_locals
    for k, v in ns.iteritems():
        if not k.startswith('__'):
            print '{0} : {1}'.format(k, v)

def test(a, b):
    c = 'Freely'
    print_local_namespace()
    return a + b + c

test('I', 'P')

rawDescription: how to get the current scope in python

description: Get the current scope in python


code:
yahooImport = robjects.r('function(x) as.data.frame(yahooImport(x)@data)')
print type(qqq)
qqq

rawDescription: rpy2 convert Matrix -> DataFrame

description: Rpy2 convert Matrix -> DataFrame


code:
import time
import calendar

current = time.localtime()

dates = ["2011-07-01 09:26:11", "2011-06-07 09:26:11", "2011-03-12 09:26:11", "2010-07-25 09:26:11"]

for date in dates:
    print "%s" % date
    date = time.strptime(date, "%Y-%m-%d %H:%M:%S")

    if date.tm_year == current.tm_year - 1:
        print "Last year"

    elif date.tm_mon == current.tm_mon:
        print "This month"

    else:
        print calendar.month_name[date.tm_mon]

rawDescription: Convert date to months and year

description: Convert date to months and year


code:
from BeautifulSoup import BeautifulSoup
html = '
centerTEXTright MORE TEXT
'
soup = BeautifulSoup(html)
for m in soup.findAll(['a', 'img']):
  if m.parent.name == 'p':
     m.replaceWith('')
print soup

rawDescription: Python remove certain elements in source


rawDescription: Numpy histogram, how to take the maximum value in each bin


code:
import os
import csv

# Open the csv and write headers.
with open("Subject_Task_Count.csv",'wb') as out:
    outwriter = csv.writer(out)
    outwriter.writerow(['Directory','FilesInDir','FilesIncludingSubdirs'])

    # Track total number of files in each subdirectory by absolute path
    totals = {}

    # topdown=False iterates lowest level (leaf) subdirectories first.
    # This way I can collect grand totals of files per subdirectory.
    for path,dirs,files in os.walk('.',topdown=False):
        files_in_current_directory = len(files)

        # Start with the files in the current directory and compute a
        # total for all subdirectories, which will be in the `totals`
        # dictionary already due to topdown=False.
        files_including_subdirs = files_in_current_directory
        for d in dirs:
            fullpath = os.path.abspath(os.path.join(path,d))

            # On my Windows system, Junctions weren't included in os.walk,
            # but would show up in the subdirectory list.  this try skips
            # them because they won't be in the totals dictionary.
            try:
                files_including_subdirs += totals[fullpath]
            except KeyError as e:
                print 'KeyError: {} may be symlink/junction'.format(e)

        totals[os.path.abspath(path)] = files_including_subdirs
        outwriter.writerow([path,files_in_current_directory,files_including_subdirs])

rawDescription: Python output number of files in each sub directory to a csv file


code:
def f():
  print "F called"
  return 1
0 < f() < 100
0 < f() and f() < 100
if (0 < f() and f() < 100):
  print True

rawDescription: Python comparison evaluation

description: Python comparison evaluation


code:
def neighbours(p):
    res = []
    ind = p.index(0)
    if not top(ind):
        res.append(up_neig(p, ind))
    if not bottom(ind):
        res.append(down_neig(p, ind))
    if not left(ind):
        res.append(left_neig(p, ind))
    if not right(ind):
        res.append(right_neig(p, ind))
    return res

def top(ind):
    return ind < 3

def bottom(ind):
    return ind > 5

def left(ind):
    return ind in [0, 3, 6]

def right(ind):
    return ind in [2, 5, 8]

def up_neig(p, ind):
    _p = list(p)
    _p[ind], _p[ind-3] = _p[ind-3], _p[ind]
    return tuple(_p)

def down_neig(p, ind):
    _p = list(p)
    _p[ind], _p[ind+3] = _p[ind+3], _p[ind]
    return tuple(_p)

def left_neig(p, ind):
    _p = list(p)
    _p[ind], _p[ind-1] = _p[ind-1], _p[ind]
    return tuple(_p)

def right_neig(p, ind):
    _p = list(p)
    _p[ind], _p[ind+1] = _p[ind+1], _p[ind]
    return tuple(_p)

p = (1,3,2,5,4,6,0,7,8)
print neighbours(p)  # [(1, 3, 2, 0, 4, 6, 5, 7, 8), (1, 3, 2, 5, 4, 6, 7, 0, 8)]

rawDescription: 8 puzzle compute neighbours python

description: 8 puzzle compute neighbours python


code:
import mechanize
import cookielib
import lxml.html as lh
import time

br = mechanize.Browser()
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

while True:
    r = br.open('https://news.google.com/')
    html = r.read()
    doc=lh.fromstring(html)
    for i in doc.xpath('.//*[@class="esc-lead-article-title"]'):
        print i.text_content()
    time.sleep(1800)

rawDescription: Web scraping using python example

description: Web scraping using python example


code:
import sys, os
_stderr = sys.stderr
_stdout = sys.stdout
null = open(os.devnull,'wb')
sys.stdout = sys.stderr = null
print "Bleh"
sys.stderr = _stderr
sys.stdout = _stdout
print "Bleh"

rawDescription: How to temporary hide stdout or stderr while running a unittest in Python

description: Temporary hide stdout or stderr while running a unittest in Python


code:
for dec in decimals:
   print format(dec, '.2f')

rawDescription: Format Python Decimal object to a specified precision


code:
import imp
module = """
def setup(*args, **kwargs):
    print(args, kwargs)
"""
setuptools = imp.new_module("setuptools")
exec module in setuptools.__dict__
setuptools
setuptools.setup(3)

rawDescription: Parse setup.py without setuptools

description: Parse setup.py without setuptools


code:
import numpy, glumpy
from glumpy.pylab import *

window = glumpy.Window(256,64)
Z = data.astype(numpy.float32)

t0, frames, t = 0,0,0
fig = plt.figure(figsize=(7,7))
ax = plt.subplot(111)
ax = imshow(Z[:,:,0], origin='lower', interpolation='bilinear')
show()
window = glumpy.active_window()

@window.event
def on_idle(dt):
    global Z, t0, frames, t

    t += dt
    frames = frames + 1
    if frames > 248:
        fps = float(frames)/(t-t0)
        print 'FPS: %.2f (%d frames in %.2f seconds)' % (fps, frames, t-t0)
        frames,t0 = 0, t

    for image, axis, alpha in items:
        image.data[...] = Z[:,:,frames]
        image.update()
    window.draw()

window.mainloop()

rawDescription: How can I speed up an animation?

description: Speed up an animation


code:
import subprocess
import threading
import Queue

def read_stdout(stdout, queue):
    while True:
        queue.put(stdout.readline()) #This hangs when there is no IO

process = subprocess.Popen('cmd.exe', shell=False, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
q = Queue.Queue()
t = threading.Thread(target=read_stdout, args=(process.stdout, q))
t.daemon = True # t stops when the main thread stops
t.start()

while True:
    x = raw_input("insert a command \n")
    if x == "x":
        break
    process.stdin.write(x + "\n")
    o = []
    try:
        while True:
            o.append(q.get(timeout=.1))
    except Queue.Empty:
        print ''.join(o)

rawDescription: PYTHON subprocess cmd.exe closes after first command


code:
import subprocess

def run():
    DefaultFFMPEGParam = "-tune animation -keyint_min 12 -sc_threshold 45 -bf 8 -b_strategy 2 -refs 10 -qmin 10 -qmax 51 -qcomp 0.6 -direct-pred auto -me_range 24 -me_method umh -subq 9 -trellis 2 -vcodec libx264" \
        .split(' ')
    crf = ['-crf', '28.0']
    output = "output2.mkv"

    # list concatenation
    args1 = ["ffmpeg", "-i", "my niece.mkv"] + DefaultFFMPEGParam + crf + [output,]

    print args1
    # prints:
    #
    # ['ffmpeg', '-i', 'my niece.mkv', '-tune', 'animation', '-keyint_min', '12',
    #  '-sc_threshold', '45', '-bf', '8', '-b_strategy', '2', '-refs', '10', '-qmin',
    #  '10', '-qmax', '51', '-qcomp', '0.6', '-direct-pred', 'auto', '-me_range', '24',
    #  '-me_method', 'umh', '-subq', '9', '-trellis', '2', '-vcodec', 'libx264',
    #  '-crf', '28.0',
    #  'output2.mkv']

    subprocess.call(args1)

run()

rawDescription: python subprocess.call terminates without notice

description: Python subprocess.call terminates without notice


code:
sum = 0
max = 11
for i in range(1, max, 2): # not including max
    sum += i
print sum

#out:25 (1 + 3 + 5 + 7 + 9)

rawDescription: Having trouble creating a function that takes one argument, and returns a result of adding odd numbers between 1 and argument?


code:
import cv2
import numpy as np
image = cv2.imread("Large.png")
template = cv2.imread("small.png")
result = cv2.matchTemplate(image,template,cv2.TM_CCOEFF_NORMED)
print np.unravel_index(result.argmax(),result.shape)

rawDescription: How to find subimage using the PIL library?

description: Find subimage using the PIL library


code:
from multiprocessing import Process, Pipe

def f(a1):
    print a1.name
    a1.conn2.send('why!?!?!?!?!!?!??')
    a1.conn2.close()

class Test1(object):

    def __init__(self):
        self.name = 'this is name in class'
        self.conn1, self.conn2 = Pipe()

if __name__ == '__main__':
    a1 = Test1()

    p = Process(target=f, args=(a1,))
    p.start()
    print a1.conn1.recv()
    p.join()

rawDescription: How to give Class to child process in python?

description: Give Class to child process in python


code: print df.to_string(index=False)

rawDescription: how to print dataframe without index

description: Print dataframe without index


code:
#!/usr/bin/python

import wx
import wx.lib.scrolledpanel

class SimpleFrame(wx.Frame):
    def __init__(self, parent):
        super(SimpleFrame, self).__init__(parent)

        # add a panel so it looks the correct on all platforms
        self.frame_panel = wx.Panel(self)
        frame_panel = self.frame_panel
        # image panel
        self.image_panel = wx.lib.scrolledpanel.ScrolledPanel(frame_panel, style=wx.SIMPLE_BORDER)
        image_panel = self.image_panel
        image_panel.SetAutoLayout(True)
        image_panel.SetupScrolling()
        # image panel - image control
        self.image_ctrl = wx.StaticBitmap(image_panel)
        self.image_ctrl.Bind(wx.EVT_MOTION, self.ImageCtrl_OnMouseMove)
        self.img = wx.Image("image.jpg", wx.BITMAP_TYPE_ANY)
        self.image_ctrl.SetBitmap(wx.BitmapFromImage(self.img))
        image_panel.Layout()
        image_sizer = wx.BoxSizer(wx.VERTICAL)
        image_sizer.Add(self.image_ctrl)
        image_panel.SetSizer(image_sizer)
        # frame sizer
        frame_sizer = wx.BoxSizer(wx.HORIZONTAL)
        frame_sizer.Add(image_panel, proportion=1, flag=wx.EXPAND | wx.ALL)
        frame_panel.SetSizer(frame_sizer)
        return

    def ImageCtrl_OnMouseMove(self, event):
        # position in control
        ctrl_pos = event.GetPosition()
        print("ctrl_pos: " + str(ctrl_pos.x) + ", " + str(ctrl_pos.y))
        pos = self.image_ctrl.ScreenToClient(ctrl_pos)
        print "pos relative to screen top left = ", pos
        screen_pos = self.frame_panel.GetScreenPosition()
        relative_pos_x = pos[0] + screen_pos[0]
        relative_pos_y = pos[1] + screen_pos[1]
        print "pos relative to image top left = ", relative_pos_x, relative_pos_y

app = wx.PySimpleApp()
frame = SimpleFrame(None)
frame.Show()
app.MainLoop()

rawDescription: In wxPython, how to get the mouse position related to image in ScrolledPanel?


code:
output_adress = []
for i in xrange(len(recent_tx_1["inputs"])):
    output_adress.append(recent_tx_1["inputs"][i]["prev_out"]["addr"])
print output_adress

rawDescription: Bitcoin: parsing Blockchain API JSON in PyQT


code:
try:
    Foo.objects.get(bar1=bar_inst)
    print 'bar1'
except Foo.DoesNotExist:
    try:
        Foo.objects.get(bar2=bar_inst)
        print 'bar2'
    except Foo.DoesNotExist:
        try:
           Foo.objects.get(bar3=bar_inst)
           print 'bar3'
        except Foo.DoesNotExist:
           print 'nothing found'

rawDescription: Django finding which field matched in a multiple OR query


code:
from collections import Counter

string = "hello world"
print ''.join(char[0] for char in Counter(string).most_common())

rawDescription: Python: find most frequent bytes?

description: Python: find most frequent bytes


code:
import urllib2

class HTTPRedirectHandler(urllib2.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        newreq = urllib2.HTTPRedirectHandler.redirect_request(self,
            req, fp, code, msg, headers, newurl)
        if newreq is not None:
            self.redirections.append(newreq.get_full_url())
        return newreq

url = 'http://google.com'

h = HTTPRedirectHandler()
h.max_redirections = 100
h.redirections = [url]
opener = urllib2.build_opener(h)
response = opener.open(url)
print h.redirections
# -> ['http://google.com', 'http://www.google.com/', 'http://google.com.ua/']

rawDescription: Use Mechanize (Python) to get redirection log


code:
from ctypes import *
from ctypes.wintypes import HANDLE

# Example use of WinAPI
windll.user32.MessageBoxW(None, u"Example", u"Example", 0)

x = HANDLE()
print windll.advapi32.LogonUserW(u"Tupteq", None, u"passwd", 4, 0, pointer(x))
print windll.kernel32.GetLastError()
print x

rawDescription: LoginUser API access from Python

description: LoginUser API access from Python


code:
pages = self.stats.get_value('response_received_count')
print pages/((datetime.now() - self.stats.get_value('start_time')).seconds/60.0)

rawDescription: How can I get the scraping speed in scrapy?

description: Get the scraping speed in scrapy


code:
import Tkinter as tk
from Tkinter import TclError

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.text = tk.Text(self, width=40, height=8)
        self.button = tk.Button(self, text="do it!", command=self.doit)
        self.button.pack(side="top")
        self.text.pack(side="bottom", fill="both", expand=True)
        self.doit()

    def doit(self, *args):
        # get the clipboard data, and replace all newlines
        # with the literal string "\n"
        clipboard = self.clipboard_get()
        clipboard = clipboard.replace("\n", "\\n")

        # delete the selected text, if any
        try:
            start = self.text.index("sel.first")
            end = self.text.index("sel.last")
            self.text.delete(start, end)
        except TclError, e:
            # nothing was selected, so paste doesn't need
            # to delete anything
            pass

        # insert the modified clipboard contents
        self.text.insert("insert", clipboard)

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

rawDescription: Pasting in the Tkinter Text widget

description: Pasting in the Tkinter Text widget


code:
from threading import Thread
from time import sleep

def threaded_function(arg):
    for i in range(arg):
        print "running"
        sleep(1)

if __name__ == "__main__":
    thread = Thread(target = threaded_function, args = (10, ))
    thread.start()
    thread.join()
    print "thread finished...exiting"

rawDescription: Creating Threads in python

description: Creating Threads in python


code:
# password prompt
while True:
    mysql_password = getpass('Please enter MySQL root password: ')
    mysql_password_confirmation = getpass('Please confirm your password: ')
    if mysql_password == mysql_password_confirmation:
        break
    else:
        print "Passwords don't match"

# set the value in debconf
with settings(hide('warnings', 'running', 'stdout', 'stderr'),
              warn_only=True):
    if not run('dpkg-query --show mysql-server'):
        sudo('echo "mysql-server-5.1 mysql-server/root_password password '
            '%s" | debconf-set-selections' % mysql_password)
        sudo('echo "mysql-server-5.1 mysql-server/root_password_again '
             'password %s" | debconf-set-selections' % mysql_password)

rawDescription: Automate Install mysql-server and postfix remotely


code:
def depchange(change):
    depchange_status=''
    if change == "23456":
        depchange="33456"
        depchange_status = 'NEW'
    if change == "33456":
        depchange=""
        depchange_status = 'COMPLETED'
    return (depchange,depchange_status)

def main ():
    master_change="23456"
    dep={}
    while True:
        dep_change,depchange_status=depchange(master_change)
        dep[master_change]=[dep_change]
        master_change = dep_change
        if depchange_status != 'NEW':
            break
    print dep

if __name__ == '__main__':
    main()

rawDescription: Print lists in a dictionary based on the status of change/depchanges


code:
class CheckerHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def post(self):
        pi1 = self.get_argument('display')
        do_find_one(self,pi1)
        self.finish()  # Without this the client's request will hang

    def do_find_one(self,live):
        Info = {}
        isAvailable = str
        count=db.userInfo.find( {'Username': live}).count()
        if  count > 0:
            isAvailable = False
            Info['valid']=isAvailable
            print False, count
            print Info
        else:
            isAvailable = True
            print True, count
        self.write(json.dumps(Info, default=json_util.default))

rawDescription: Sending JSON from Tornado to client

description: Sending JSON from Tornado to client


code:
with open('foo.xml', 'rt') as document:
    tree = ElementTree.parse(document)
    for series in tree.findall('.//series'):
        locationId = series.find('./header/locationId').text
        print locationId
        events = series.findall('./event')
        for event in events:
            print '{}, {}, {}'.format(event.attrib.get('date'), event.attrib.get('time'), event.attrib.get('value'))

rawDescription: Parse XML time series data to dat files

description: Parse XML time series data to dat files


code:
import base64
import binascii

print binascii.hexlify(base64.urlsafe_b64decode(md5_base64))

rawDescription: How to convert Google Cloud Storage base64 md5sum to hexadecimal version?

description: Convert Google Cloud Storage base64 md5sum to hexadecimal version


code:
def round_gt_05(x):
    try:
        num = float(x)
        if num > 0.5:
            return str(int(round(num)))
    except ValueError:
        pass
    return x

mylist = ["34.59","0.32","-","39.29","E","0.13","*"]
newlist = map(round_gt_05, mylist)
print newlist

rawDescription: Round list of string/float if greater than x


code:
import smtplib
from Tkinter import *
import tkMessageBox

def Composemail(sender,password,receivers,message):
    try:
        server = smtplib.SMTP()
        server.connect('smtp.gmail.com',587)
        server.ehlo()
        server.starttls()
        server.login(sender, password)
        server.sendmail(sender, receivers, message)
        tkMessageBox.showinfo("Sending Mail information","Mail sent.")
    # Just a tip, "error" isn't defined yet so it will blow up.
    except smtplib.SMTPException, error:
        tkMessageBox.showinfo("Sending Mail information","Sending Mail failed.Try again  later.")

a=Tk()
a.title("MailsNow-A new place for sending emails")
a.geometry("1000x700")
b=Label(a,fg="Purple",text="From")
b.pack()
c=Entry(a,bd=5,width=100)
c.pack()
d=Label(a,fg="Purple",text="Password")
d.pack()
e=Entry(a,bd=5,width=100,show="*")
e.pack()
f=Label(a,fg="Purple",text="To")
f.pack()
g=Entry(a,bd=5,width=100)
g.pack()
h=Label(a,fg="Purple",text="Subject")
h.pack()
i=Entry(a,bd=5,width=100)
i.pack()
j=Label(a,fg="Purple",text="Type your email here")
j.pack()
k=Text(a,bd=5,height=20,width=100)
k.pack()

def getstuff():
    # You can retrieve the text entered into an entrybox using the get method
    sender=c.get()
    password=e.get()
    receivers=g.get()
    subject=i.get()
    # Since textboxes are multiline, I have to tell it what text to get.
    # 0.0,END is saying "get everything from start to finish".
    message=k.get(0.0,END)

    # One thing I noted was that you are not sending the subject to
    # Composemail.  Is this what you want?
    Composemail(sender,password,receivers,message)

l=Button(a, text="Sendmail",bg="Purple",activebackground="Yellow",
command=getstuff)
l.pack()

a.mainloop()

rawDescription: How to retrieve the contents of entry and text widget and assign it to a variable in tkinter using python

description: Retrieve the contents of entry and text widget and assign it to a variable in tkinter using python


code:
# use 'tkinter' instead of 'Tkinter' if using python 3.x
import Tkinter as tk

class CustomCanvas(tk.Canvas):
    def __init__(self, *args, **kwargs):
        '''A custom canvas that generates <<ScrollEvent>> events whenever
           the canvas scrolls by any means (scrollbar, key bindings, etc)
        '''
        tk.Canvas.__init__(self, *args, **kwargs)

        # replace the underlying tcl object with our own function
        # so we can generate virtual events when the object scrolls
        tcl='''
            proc widget_proxy {actual_widget args} {
                set result [$actual_widget {*}$args]
                set command [lindex $args 0]
                set subcommand [lindex $args 1]
                if {$command in {xview yview} && $subcommand in {scroll moveto}} {
                    # widget has been scrolled; generate an event
                    event generate {widget} <<ScrollEvent>>
                }
                return $result
            }

            rename {widget} _{widget}
            interp alias {} ::{widget} {} widget_proxy _{widget}
        '''.replace("{widget}", str(self))
        self.tk.eval(tcl)

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        # create an instance of the custom canvas. Make sure it
        # has a largeish scroll region, for demonstration purposes
        self.canvas = CustomCanvas(self, width=400, height=400,
                                   borderwidth=0, scrollregion=(0,0,1000,1000))
        self.vsb = tk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
        self.hsb = tk.Scrollbar(self, orient="horizontal", command=self.canvas.xview)
        self.canvas.configure(xscrollcommand=self.hsb.set, yscrollcommand=self.vsb.set)

        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.vsb.grid(row=0, column=1, sticky="ns")
        self.hsb.grid(row=1, column=0, sticky="ew")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        # this binds to the virtual event that is sent by the proxy
        self.canvas.bind("<<ScrollEvent>>", self.on_scroll)

        # some data, just so that we can see that the canvas
        # really is scrolling
        for y in range(0, 1000, 100):
            for x in range(0, 1000, 100):
                self.canvas.create_text(x, y, text="%s/%s" % (x,y), anchor="nw")

    def on_scroll(self, event):
        print "widget scrolled..."

if __name__ == "__main__":
    root = tk.Tk()
    view = Example(root)
    view.pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: Tkinter Canvas Scroll / Drag Notification


code:
import sys
import os.path
if len(sys.argv) != 2:
    print "Usage:", sys.argv[0], "<inputfile.lua>"
    exit()
f = open(sys.argv[1], "r")
lines = f.readlines()
f.close()
for line in lines:
    if line.startswith("require "):
        path = line.replace('require "', '').replace('"', '').replace("\n", '').replace(".", "/") + ".lua"
        fName = os.path.basename(path)
        path = path.replace(fName, "")
        print "File: " + fName
        print "Directory: " + path
        #do what you want to each file & path here

rawDescription: How does one parse a .lua file with Python and pull out the require statements?

description: Parse a .lua file with Python and pull out the require statements


code:
# a string that is unicode+raw (escapes \)
path = ur"E:\pub\private\desktop"
print os.listdir(path)
# [u'\xa6.txt', u'\u2560.txt']

rawDescription: Filename formatting in Python under Windows


code:
# these are the modules you want to profile
import foo
import huh

# This is a profiling function
# yours would do something smarter
def profile(f):
    def gotcha(*args, **kwds):
        print "before"
        result = f(*args, **kwds)
        print "after"
        return result
    return gotcha

# these are the functions in those modules that you
# want to profile.  Each one is patched here instead
# of decorated there.
foo.bar = profile(foo.bar)
huh.baz = profile(huh.baz)
huh.hmm = profile(huh.hmm)

rawDescription: python module import question

description: Python module import question


code:
import datetime
def prevMonthEnd(startDate):
   ''' given a datetime object, return another datetime object that
       is set to the last day of the prevoius month '''
   firstOfMonth = startDate.replace(day=1)
   return firstOfMonth - datetime.timedelta(days=1)
theDate = datetime.date.today()
for i in range(60):
   theDate = prevMonthEnd(theDate)
   print theDate

rawDescription: Python last 60 end-of-months

description: Python last 60 end-of-months


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument(
    '-c',
    '--command-type',
    required=True,
    help='The command to run against ElasticSearch',
    choices=('create', 'delete', 'status'),
)
parser.add_argument(
    '-i',
    '--index_name',
    required=True,
    help='Name of ElasticSearch index to run the command against',
)
parser.add_argument(
    '-u',
    '--elastic-search-url',
    required=True,
    help='Base URl of ElasticSearch',
)
parser.add_argument(
    '-f',
    '--file_to_index',
    type=argparse.FileType(),
    help='The file name of the index map',
)

args = parser.parse_args()

print args

rawDescription: Working with argparse need explaination of how to use it properly


code:
file1 = open('file.csv', 'rU')
fileR = csv.reader(file1, delimiter=',')
L=list(fileR)
print set(item[1] for item in L if item[0]=='A').intersection([item[1] for item in L if item[0]=='B'])
print len(set(item[1] for item in L if item[0]=='A').intersection([item[1] for item in L if item[0]=='B']))

#set(['rule2', 'rule1'])
#2

rawDescription: How to find the shared properties of any two elements in a CSV file

description: Find the shared properties of any two elements in a CSV file


code:
word='Banana'

L=[]                           #create an empty list
for letter in word:
    if letter not in L:
        L.append(letter)       #append unique chars to list

print len(L)                   #count the chars in list

rawDescription: Counting number of different characters in a word


code:
from IPython.display import display, HTML

# Assuming that dataframes df1 and df2 are already defined:
print "Dataframe 1:"
display(df1)
print "Dataframe 2:"
HTML(df2.to_html())

rawDescription: Print DataFrame as table in iPython Notebook


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.main = tk.Canvas(self, width=400, height=400,
                              borderwidth=0, highlightthickness=0,
                              background="bisque")
        self.main.pack(side="top", fill="both", expand=True)

        # add a callback for button events on the main canvas
        self.main.bind("<1>", self.on_main_click)

        for x in range(10):
            for y in range(10):
                canvas = tk.Canvas(self.main, width=48, height=48,
                                   borderwidth=1, highlightthickness=0,
                                   relief="raised")
                if ((x+y)%2 == 0):
                    canvas.configure(bg="pink")

                self.main.create_window(x*50, y*50, anchor="nw", window=canvas)

                # adjust the bindtags of the sub-canvas to include
                # the parent canvas
                bindtags = list(canvas.bindtags())
                bindtags.insert(1, self.main)
                canvas.bindtags(tuple(bindtags))

                # add a callback for button events on the inner canvas
                canvas.bind("<1>", self.on_sub_click)

    def on_sub_click(self, event):
        print "sub-canvas binding"
        if event.widget.cget("background") == "pink":
            return "break"

    def on_main_click(self, event):
        print "main widget binding"

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack (fill="both", expand=True)
    root.mainloop()

rawDescription: How to pass an event to parent widget

description: Pass an event to parent widget


code:
import numpy as np

# your example data, with a bad value at [1, 1, 1]
M = np.array([[[    0,     2,     1],
               [    1,     4,     1],
               [    1,     1,     2]],

              [[    4,     2,     0],
               [    3, -9999,     0],
               [    1,     0,     3]],

              [[    2,     0,     3],
               [    1,     3,     4],
               [    2,     4,     3]]])

# create a masked array where all of the values in `M` that are equal to
# -9999 are masked
masked_M = np.ma.masked_equal(M, -9999)

# take the mean over the first axis
masked_mean = masked_M.mean(0)

# `masked_mean` is another `np.ma.masked_array`, whose `.data` attribute
# contains the result you're looking for
print masked_mean.data
# [[ 2.          1.33333333  1.33333333]
#  [ 1.66666667  3.5         1.66666667]
#  [ 1.33333333  1.66666667  2.66666667]]

rawDescription: How to avoid using "no data" in image stacking

description: Avoid using "no data" in image stacking


code:
book = ['Andrea', '21', 'andrea@hotmail.com', 'Brenda', '1211', 'brenda@yahoo.co.uk']
input_name = str(raw_input("Name:"))
updatedBook = [[name, number, email] for name, number, email in zip(book[::3], book[1::3], book[2::3]) if name != input_name]
print updatedBook

rawDescription: How do I delete Address book entry

description: Delete Address book entry


code:
from copy import deepcopy

company_ids = [1,2,3]
seller_ids = [[0, False, { u'company_id': 4}]]
result = []
for company in company_ids:
    for i in xrange(0, len(seller_ids)):
        mycopy = deepcopy(seller_ids[i])
        mycopy[2]['company_id'] = company
        result.append(mycopy)

print result

rawDescription: Insert a value into dict of nested lists


code:
def typeText(text, delay=0.05):
  for character in text:
    print character,
    time.sleep(delay)

typeText("Hello, this is a text")

rawDescription: Python text game

description: Python text game


code:
from datetime import datetime, timedelta
from pytz import timezone
import pytz
utc = pytz.utc
utc.zone
eastern = timezone('US/Eastern')
eastern.zone
amsterdam = timezone('Europe/Amsterdam')
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
print loc_dt.strftime(fmt)
ams_dt = loc_dt.astimezone(amsterdam)
ams_dt.strftime(fmt)

rawDescription: Python: display the time in a different time zone


code:
import time
import curses

# The timer class
class Timer():
    def __init__(self):
        self.target = time.time() + 5
    def add_five(self):
        self.target += 5
    def get_left(self):
        return int(self.target-time.time())

# The main program
t = Timer()
stdscr = curses.initscr()
stdscr.nodelay(True)
curses.noecho()
# This is the main loop done in curses, but you can implement it with
# a GUI toolkit or any other method you wish.
while True:
    left = t.get_left()
    if left <= 0:
        break
    stdscr.addstr(0, 0, 'Seconds left: %s ' % str(left).zfill(3))
    c = stdscr.getch()
    if c == ord('x') :
        t.add_five()
# Final operations start here
stdscr.keypad(0)
curses.echo()
curses.endwin()
print '\nTime is up!\n'

rawDescription: python add time to a countdown already running

description: Python add time to a countdown already running


code:
lst = [-6,-5,-4,4,5,6]

def foo(x):
    return x*x

minmax = min

print minmax((foo(x), x) for x in lst)[1]  # -4

rawDescription: Pythonic way to solve a small task

description: Pythonic way to solve a small task


code:
#! /usr/bin/env python

import os
import cgi
import cgitb
cgitb.enable()
import sys

def check_file_extension(display_file):
    input_file = display_file
    nm,file_extension = os.path.splitext(display_file)
    return file_extension

form = cgi.FieldStorage()

type_of_file =''
file_nm = ''
nm =''
path = '/home/shantala/Documents'
not_found = 0

if form.has_key("file1"):
    file_nm = form["file1"].value

for f in next(os.walk(path))[2]:
    if str(f) == str(file_nm).strip():
        not_found = 0
        absolute_path_of_file = os.path.join(path, f)
        type_of_file = check_file_extension(absolute_path_of_file)
        if type_of_file == '.pdf':
            file_read = file(absolute_path_of_file,'rb').read()
            print  'Content-type: application/pdf\n'
            print file_read
        if type_of_file == '.txt':
            file_read = file(absolute_path_of_file,'rb').read()
            print  'Content-type: text/html\n'
            print file_read
        if type_of_file == '.png':
            file_read = file(absolute_path_of_file,'rb').read()
            print  'Content-type: image/png\n'
            print file_read
        if type_of_file == '.pdf':
            file_read = file(absolute_path_of_file,'rb').read()
            print  'Content-type: application/pdf\n'
            print file_read
        if type_of_file == '.JPG':
            file_read = file(absolute_path_of_file,'rb').read()
            print  'Content-type: image/jpg\n'
            print file_read
        if type_of_file == '.bmp':
            file_read = file(absolute_path_of_file,'rb').read()
            print  'Content-type: image/bmp\n'
            print file_read

        break
    else:
        not_found = 1

if not_found == 1:
    pass
    # print "%s" % str(file_nm) + " not found"

rawDescription: How to invoke webbrowser from cgi script?

description: Invoke webbrowser from cgi script


code:
class TreeView(QtGui.QTreeView):
    def edit(self, index, trigger, event):
        if trigger == QtGui.QAbstractItemView.DoubleClicked:
            print 'DoubleClick Killed!'
            return False
        return QtGui.QTreeView.edit(self, index, trigger, event)

rawDescription: How to disable the double click file renaming behavior on QTreeView and QFileSystemModel in PyQt?

description: Disable the double click file renaming behavior on QTreeView and QFileSystemModel in PyQt


code:
import argparse
parser = argparse.ArgumentParser(description='example')
parser.add_argument('-a', '--add')
options = parser.parse_args(['-a', 'foo', '-a', 'bar'])
print 'add = {}'.format(options.add) # output: add = bar

rawDescription: Python argparse: single-valued argument but allow specified multiple times on command line


code:
def TREE_PRINT(tree, indent=''):
    #is this a leaf node?
    if 'val' in tree:
        print str(tree['val'])
    else:
        #print the criteria
        print 'split: '+ str(tree['spl']) + ' ' + str(tree['go_r'])
        #print the branches
        print indent+'L->',
        TREE_PRINT(tree['l'], indent+'  ')

        print indent+'R->',
        TREE_PRINT(tree['r'], indent+'  ')

rawDescription: Recursive Function to Print a Decision Tree in Python: Suppress 'None's


code:
N = 5 # This way you can test it with 5 or 6 and even 100 if you want to.
visited = [[False for x in range(N)] for y in range(N)]

def move(x,y,m):

    result=False
    if x<0 or x>=N or y<0 or y>=N or visited[x][y]==True: # You may merge these two ifs.
        return False
    visited[x][y]=True
    if m==(N * N - 1):
        print "a solution has been found"
        visited[x][y]=True # Set visited here tot true.
        return True
    else:
        print x,",",y
        if (move(x+2,y+1,m+1) or move(x+2,y-1,m+1)
            or move(x-2,y+1,m+1) or move(x-2,y-1,m+1)
            or move(x+1,y+1,m+1) or move(x+1,y-1,m+1)
            or move(x-1,y+1,m+1) or move(x-1,y-1,m+1)): # Place them in one if.
            print x,",",y

            return True
    return False # If the algorithm comes here it may return false

print move(2,1,0)

rawDescription: Knight's tour backtracking

description: Knight's tour backtracking


code:
import urllib2
import os

os.environ['http_proxy'] = "http://10.8.0.1:8118/"
print urllib2.urlopen("http://twitter.com").read()

rawDescription: How do I add proxy support into my python script? (reddit api wrapper python)

description: Add proxy support into my python script? (reddit api wrapper python)


code:
d = {
    'A' : {
        'C' : {
            'D' : {
                'E' : 4,
            },
            'F' : 5,
        },
    },
    'B' : 2,
}

def DeepDictDel(path, dict):
    for key in path.split('.'):
        owner = dict
        dict = dict[key]

    del owner[key]

print d # prints {'A': {'C': {'D': {'E': 4}, 'F': 5}}, 'B': 2}
DeepDictDel('A.C.D', d)
print d # prints {'A': {'C': {'F': 5}}, 'B': 2}

rawDescription: Subtract dict A from dict B (deep del)?

description: Subtract dict A from dict B (deep del)


code:
import cv2
import numpy as np

ix,iy = -1,-1
# mouse callback function
def draw_circle(event,x,y,flags,param):
    global ix,iy
    if event == cv2.EVENT_LBUTTONDBLCLK:
        cv2.circle(img,(x,y),100,(255,0,0),-1)
        ix,iy = x,y

# Create a black image, a window and bind the function to window
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)

while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(20) & 0xFF
    if k == 27:
        break
    elif k == ord('a'):
        print ix,iy
cv2.destroyAllWindows()

rawDescription: How to save mouse position in variable using OpenCV and Python?

description: Save mouse position in variable using OpenCV and Python


code:
for pow in xrange(2,5):
    sum=0
    for index in xrange(3,3+pow):
        sum+=index ** pow
    if sum==(index+1) ** pow:
        print True

#output is for power 2, 3 it works

rawDescription: Programming a number theory programme

description: Programming a number theory programme


code:
import requests
from requests.auth import HTTPBasicAuth
import json

token = ""

def get_token(username, password, url):
    global token

    #verify=False will not verify the ssl
    resp = requests.post(url, auth=HTTPBasicAuth(username, password), verify=False)

    print "\n", dir(resp)
    print "Status Code:", resp.status_code, "\n"
    print "text:", resp.text, "\n"
    print "json:", resp.json(), "\n"
    print "Content:", resp.content, "\n"
    print "Headers:", resp.headers, "\n"
    print "Header(Content-type:)", resp.headers.get('content-type'), "\n"
    print "Header(Content-length:)", resp.headers.get('content-length'), "\n"
    print "OK:", resp.ok, "\n"
    print "json dump:", json.dumps(resp.json())

    json_dict = json.loads(resp.text)

    token = json_dict['token-id']
    print "\ntoken-id:", json_dict['token-id']

    for key, value in json_dict.items():
        print key, "=>", value

    return token

def get_global_users(token):
    print "\nexecuting get_global_users.."
    print "Token", token
    url = 'https://xxx.xxx.xxx.xxx/api/v1/global/users'
    headers_dict = {'content-type': 'application/json', 'Accept': 'application/json', 'X-Auth-Token': token}
    resp = requests.get(url, headers=headers_dict, verify=False)
    print "Status Code:", resp.status_code, "\n"
    print "text:", resp.text, "\n"
    print "json:", resp.json(), "\n"
    json_users = json.loads(resp.text)
    print "all users:\n", json_users['users']

    print "\n"
    for users in json_users['users']:
        for key, value in users.items():
            print key, "=>", value

def post_global_user(token):
    print "\nexecuting post_global_users.."
    print "Token:", token
    url = 'https://xxx.xxx.xxx.xxx/api/v1/global/users'
    headers_dict = {'content-type': 'application/json', 'Accept': 'application/json', 'X-Auth-Token': token}
    payload = {'username': 'myuser', 'password': 'pas1234', 'pw-type': 0, 'privilege': 15}
    resp = requests.post(url, data=json.dumps(payload), headers=headers_dict, verify=False)
    print "Status Code:", resp.status_code, "\n"

rawDescription: how to implement CURL cli using python to consume REST services

description: Implement CURL cli using python to consume REST services


code:
import datetime as dt
import peewee as pw

# custom sqlite function to reformat our date string
def _sqlite_reformat_date(unfortunate_date_string):
    return dt.datetime \
        .strptime(unfortunate_date_string,'%m/%d/%Y') \
        .strftime('%Y-%m-%d')

# Subclass pw.SqliteDatabase to add our custom sqlite function
class MySqliteDatabase(pw.SqliteDatabase):
    def __init__(self, *args, **kwargs):
        super(MySqliteDatabase, self).__init__(*args, **kwargs)

    def _add_conn_hooks(self, conn):
        conn.create_function('reformat_date', 1, _sqlite_reformat_date)
        super(MySqliteDatabase, self)._add_conn_hooks(conn)

db = MySqliteDatabase('people1.db')

# ...
# Your model definition and data inserts from your example above
# ...

rd = pw.fn.reformat_date # Use our custom sqlite function
for item in Person.select().where(rd(Person.birthday) > rd(base.birthday)):
    print item.name , item.birthday

rawDescription: How to extract correct data from Sqlite database using Python?

description: Extract correct data from Sqlite database using Python


code:
data = [(0, 2.5), (1, 2.1), (2, 1.7), (3, 2.0), (4, 0.3), (5, 0.8), (6, -1.2), (7, -0.5)]
n = 5

t0, x0 = data.pop(0)
outliers = []
up = bool(x0 > 0)

for t, x in data:
    if (x < x0 and up) or (x > x0 and not up):
        if not outliers:
            outliers = [(t0,x0)]
        outliers.append((t,x))
        up = not up
    else:
        if len(outliers) >= n:
            print 'outliers =', outliers
        outliers = []
    t0,x0 = t,x

if len(outliers) >= n:
    print 'outliers =', outliers

rawDescription: Finding a sequence of alternating numbers in a list


code:
import urllib2
import urllib
from lxml import etree

_TARGET_URL = 'https://www.paoilandgasreporting.state.pa.us/publicreports/Modules/DataExports/ExportProductionData.aspx?PERIOD_ID=2013-0'
_AGREEMENT_URL = 'https://www.paoilandgasreporting.state.pa.us/publicreports/Modules/Welcome/Agreement.aspx'
_CSV_OUTPUT = 'urllib2_ProdExport2013-0.csv'

class _MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):

    def http_error_302(self, req, fp, code, msg, headers):
        print 'Follow redirect...'  # Any cookie manipulation in-between redirects should be implemented here.
        return urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)

    http_error_301 = http_error_303 = http_error_307 = http_error_302

cookie_processor = urllib2.HTTPCookieProcessor()

opener = urllib2.build_opener(_MyHTTPRedirectHandler, cookie_processor)
urllib2.install_opener(opener)

response_html = urllib2.urlopen(_TARGET_URL).read()

print 'Cookies collected:', cookie_processor.cookiejar

page_node, submit_form = etree.HTML(response_html), {}  # ElementTree node + dict for storing hidden input fields.
for input_name in ['ctl00$MainContent$AgreeButton', '__EVENTVALIDATION', '__VIEWSTATE']:  # Form `input` fields used on the ``Agreement.aspx`` page.
    submit_form[input_name] = page_node.xpath('//input[@name="%s"][1]' % input_name)[0].attrib['value']
    print 'Form input \'%s\' found (value: \'%s\')' % (input_name, submit_form[input_name])

# Submits the agreement form back to ``_AGREEMENT_URL``, which redirects to the CSV download at ``_TARGET_URL``.
csv_output = opener.open(_AGREEMENT_URL, data=urllib.urlencode(submit_form)).read()
print csv_output

with file(_CSV_OUTPUT, 'wb') as f:  # Dumps the CSV output to ``_CSV_OUTPUT``.
    f.write(csv_output)
    f.close()

rawDescription: Python - downloading a CSV file from a web page with a link


code:
import threading, signal

def huphandler(signum, frame):
    print idle_loop.sig_lock
    if idle_loop.sig_lock:
        idle_loop.continuee = False
    else:
        print 'dont b here'
        os._exit(0)

def loop():
    print 'in lock'
    time.sleep(5)

def idle_loop():
    while True:
        idle_loop.sig_lock = True
        t = multiprocessing.Process(target=loop)
        t.start()
        t.join()
        print 'out lock'
        if idle_loop.continuee:
            idle_loop.sig_lock = False
            time.sleep(5)
        else: return

idle_loop.sig_lock = False
idle_loop.continuee = True
signal.signal(signal.SIGHUP, huphandler)
idle_loop()

rawDescription: Signal program to exit only when it is ready


code:
x = Int('x')
y = Int('y')

def abs(x):
    return If(x >= 0,x,-x)

s=Solver()
s.add(x == abs(y-2))
s.add(x>0)
s.add(y>0)
s.check()
m=s.model()
print m

rawDescription: How to calculate Absolute value in z3 or z3py

description: Calculate Absolute value in z3 or z3py


code:
import csv
with open(name, 'rb') as f:
    for row in csv.reader(f, delimiter=' ', skipinitialspace=True):
            print '|'.join(row)

rawDescription: Can Python remove double quotes from a string, when reading in text file?


code:
my_string = 'qwer123asd!@#$%^'
predef = set('0x#$qi')

if set(my_string).issubset(predef):
    print "only predefined symbols"

rawDescription: How to check if there is only defined symbols in string?

description: Check if there is only defined symbols in string


code:
from BitVector import BitVector
bv = BitVector(intVal = 0x13A5, size = 32)
print bv
bv << 6                            #does a cyclic left shift
print bv
bv[0] = 1
print bv
bv << 3                            #cyclic shift again, should be more apparent
print bv

rawDescription: How Can I limit bit number in the integer variable in Python?

description: Limit bit number in the integer variable in Python


code:
import wmi
c = wmi.WMI ()
drive_letter = "D"
for physical_disk in c.Win32_DiskDrive ():
  for partition in physical_disk.associators ("Win32_DiskDriveToDiskPartition"):
    for logical_disk in partition.associators ("Win32_LogicalDiskToPartition"):
      if logical_disk.Caption == drive_letter:
        print physical_disk.Caption, partition.Caption, logical_disk.Caption

rawDescription: How to find volume Volume serial number or Harddisk number from drive letter

description: Find volume Volume serial number or Harddisk number from drive letter


code:
#! /usr/bin/env python

''' Steganography with PIL (really Pillow)

    Encodes / decodes bits of a binary data file into the LSB of each color
    value of each pixel of a non-palette-mapped image.

    Written by PM 2Ring 2015.02.03
'''

import sys
import getopt
import struct
from PIL import Image

def readbits(bytes):
    ''' Generate single bits from bytearray '''
    r = range(7, -1, -1)
    for n in bytes:
        for m in r:
            yield (n>>m) & 1

def encode(image_bytes, mode, size, dname, oname):
    print 'Encoding...'
    with open(dname, 'rb') as dfile:
        payload = bytearray(dfile.read())

    #Prepend encoded data length to payload
    datalen = len(payload)
    print 'Data length:', datalen

    #datalen = bytearray.fromhex(u'%06x' % datalen)
    datalen = bytearray(struct.pack('>L', datalen)[1:])
    payload = datalen + payload

    databits = readbits(payload)
    for i, b in enumerate(databits):
        image_bytes[i] = (image_bytes[i] & 0xfe) | b

    img = Image.frombytes(mode, size, str(image_bytes))
    img.save(oname)

def bin8(i):
    return bin(i)[2:].zfill(8)

bit_dict = dict((tuple(int(c) for c in bin8(i)), i) for i in xrange(256))

def decode_bytes(data):
    return [bit_dict[t] for t in zip(*[iter(c&1 for c in data)] * 8)]

def decode(image_bytes, dname):
    print 'Decoding...'
    t = decode_bytes(image_bytes[:24])
    datalen = (t[0] << 16) | (t[1] << 8) | t[2]
    print 'Data length:', datalen

    t = decode_bytes(image_bytes[24:24 + 8*datalen])

    with open(dname, 'wb') as dfile:
        dfile.write(str(bytearray(t)))

def process(iname, dname, oname):
    with Image.open(iname) as img:
        mode = img.mode
        if mode == 'P':
            raise ValueError, '%s is a palette-mapped image' % fname
        size = img.size
        image_bytes = bytearray(img.tobytes())
    #del img

    print 'Data capacity:', len(image_bytes) // 8 - 24

    if oname:
        encode(image_bytes, mode, size, dname, oname)
    elif dname:
        decode(image_bytes, dname)

def main():
    #input image filename
    iname = None
    #data filename
    dname = None
    #output image filename
    oname = None

    def usage(msg=None):
        s = msg + '\n\n' if msg else ''
        s += '''Embed data into or extract data from the low-order bits of an image file.

Usage:

%s [-h] -i input_image [-d data_file] [-o output_image]

To encode, you must specify all 3 file names.
To decode, just specify the input image and the data file names.
If only the the input image is given, its capacity will be printed,
i.e., the maximum size (in bytes) of data that it can hold.

Uses PIL (Pillow) to read and write the image data.
Do NOT use lossy image formats for output, eg JPEG, or the data WILL get scrambled.
The program will abort if the input image is palette-mapped, as such images
are not suitable.
'''
        print >>sys.stderr, s % sys.argv[0]
        raise SystemExit, msg!=None

    try:
        opts, args = getopt.getopt(sys.argv[1:], "hi:d:o:")
    except getopt.GetoptError, e:
        usage(e.msg)

    for o, a in opts:
        if o == '-h': usage(None)
        elif o == '-i': iname = a
        elif o == '-d': dname = a
        elif o == '-o': oname = a

    if iname:
        print 'Input image:', iname
    else:
        usage('No input image specified!')

    if dname:
        print 'Data file:', dname

    if oname:
        print 'Output image:', oname

    process(iname, dname, oname)

if __name__ == '__main__':
    main()

rawDescription: Alternative method to compare original image with edited one that may not need the original


code:
print 010 # 8
print 0x10 # 16

rawDescription: Python chr() explain

description: Python chr() explain


code:
import random

HTH = 0
HTT = 0
numberOfTrials = 10000

for t in xrange( numberOfTrials ):
    myList = [ random.randint(0,1), random.randint(0,1), random.randint(0,1) ]
    flips = 3
    HTHflips = HTTflips = 0

    while HTHflips == 0 or HTTflips == 0:
        if HTHflips == 0 and myList[flips-3:flips] == [1,0,1]:
            HTHflips = flips
        if HTTflips == 0 and myList[flips-3:flips] == [1,0,0]:
            HTTflips = flips
        myList.append(random.randint(0,1))
        flips += 1

    HTH += HTHflips
    HTT += HTTflips

print 'HTT :', numberOfTrials, HTT, float(HTT)/numberOfTrials
print 'HTH :', numberOfTrials, HTH, float(HTH)/numberOfTrials

rawDescription: Using python to analyse coin tossing statistics


code:
def MultiplyBy(x):
    def M(y):
        return x * y
    return M

Double = MultiplyBy(2)
Triple = MultiplyBy(3)

print Double(10), Triple(10)

rawDescription: Python self: Do I have to pass self into a function to refer to self?


code:
test1 = int(raw_input("Please write some number:>  "))
print test1 * 100

a = "I will like some candies"
b = "I will like some chocolates"
c = "I will rather die but have fried chicken"
test2 = raw_input("Please write the variable name you want to print ")
print globals()[test2]

rawDescription: Can we make python take variables than strings from raw_input() builtin function?


code:
from StringIO import StringIO
from time import time
import ast

def zip_test():
    # Using StringIO to illustrate using something file-like.
    for row in StringIO('a 1.0 2 True\n' * 32):
        (a, b, c, d) = [f(v) for (f, v) in zip(
                (str, float, int, lambda v: v == 'True'), row.split())]

def ast_test():
    for row in StringIO('"a" 1.0 2 True\n' * 32):
        (a, b, c, d) = [ast.literal_eval(s) for s in row.split()]

for f in (zip_test, ast_test):
    start = time()
    for i in range(100):
        f()
    print '%s: %s' % (f.func_name, time() - start)

 # [ ** Results ** ]
 #
 # zip_test: 0.0131301879883
 # ast_test: 0.0835828781128

rawDescription: Convert list of strings into multiple data types in one line


code:
with open('missing.csv', "wb") as outFile:
    outCsv = csv.writer(outFile)
    outCsv.write(header)
    for missing in missingFromAuthoritative:
        # do your other stuff with inconsistencies, etc., here
        print missing
        outCsv.writerow(missing)

rawDescription: print python and csv row

description: Print python and csv row


code:
# approach 1: pattern for "generic smiley"
eyes, noses, mouths = r":;8BX=", r"-~'^", r")(/\|DP"
pattern1 = "[%s][%s]?[%s]" % tuple(map(re.escape, [eyes, noses, mouths]))

# approach 2: disjunction of a list of smileys
smileys = """:-) :) :o) :] :3 :c) :> =] 8) =) :} :^)
             :D 8-D 8D x-D xD X-D XD =-D =D =-3 =3 B^D""".split()
pattern2 = "|".join(map(re.escape, smileys))

text = "bla bla bla :-/ more text 8^P and another smiley =-D even more text"
print re.findall(pattern1, text)

rawDescription: detect emoticon in a sentence using regex python

description: Detect emoticon in a sentence using regex python


code:
import urlparse
import lxml.html

URL = 'http://example.com'
dom = lxml.html.parse(URL)
url = dom.docinfo.URL
base = dom.find('head/base')
if base:
    url = base.get('href', url)

for link in dom.xpath('//div[@id="right-column"]//a/@href'):
    print urlparse.urljoin(url, link)

rawDescription: How to concatenate lxml string with another string in Python

description: Concatenate lxml string with another string in Python


code:
elements, queries = map(int, raw_input().split())
array = set(raw_input().split())  # not really an array, but...
if len(array) != elements:
    raise ValueError('unexpected number of elements in array')
for _ in range(queries):
    print 'YES' if raw_input() in array else 'NO'

rawDescription: Optimising the program for large inputs

description: Optimising the program for large inputs


code:
month_of_the_year = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dec']

def convert_to_mysql_format(string):
  explode = string.split()
  day_of_the_month = explode[2][:-1]
  if int(explode[2][:-1]) < 10:
    day_of_the_month = "%02d" % (int(explode[2][:-1]),)

  if explode[5] == 'am':
    time_split = explode[4].split(':')
    if time_split[0] == '12':
      time_split[0] = '00'
    elif int(time_split[0]) < 10:
      time_split[0] = "%02d" % int(time_split[0])

  else:
    time_split = explode[4].split(':')
    if int(time_split[0]) in range(1, 12):
      time_split[0] = str(int(time_split[0]) + 12)

  if month_of_the_year.index(explode[1]) < 12:
    explode[1] = "%02d" % (month_of_the_year.index(explode[1])+1)

  return explode[3]+'-'+explode[1]+'-'+day_of_the_month+' '+time_split[0]+':'+time_split[1]+':00'

print convert_to_mysql_format("Lun Ene 27, 2014 9:52 am")
print convert_to_mysql_format("Lun Ene 27, 2014 9:52 pm")

rawDescription: convert python string date to mysql datetime

description: Convert python string date to mysql datetime


code:
eachconfig = [['a', ['blank', ['p1', 'r', 'r'], ['b']]], ['b', ['blank', ['p0'], ['c']]], ['c', ['blank', ['r', 'r'], ['a']]]]
def turingmachine(data):
    a = 0
    tape = []
    finalmc = data[0][0]
    for z in range(1,40):
        tape.append(' ')
    mcName = []
    m = 0
    for emc in range(1,len(data)+1):
        goal = data[m][0]
        mcName.append(goal)
        m+=1
    mcNumber = [h-1 for h in range(1,len(mcName)+1)]
    mcNameNumber = dict(zip(mcName,mcNumber))

    d = 0
    tapeposition = d
    tapescan = tape[d]
    for process in range(1,len(tape) - 8):
        b = 0
        c = 0

        cconfig = data[a][b]
        if cconfig == finalmc:
            b += 1
            scannedsymbol = data[a][b][c]
            if isinstance(scannedsymbol, str):
                if scannedsymbol.lower() in ('any', 'blank'):
                    c += 1
                    operations = data[a][b][c]
                    for cycle in operations:
                        if cycle[0] in ('p','P'):
                            tape[tapeposition] = cycle[1:]
                        elif cycle[0] in ('r', 'R'):
                            tapeposition += 1
                        elif cycle[0] in ('l', 'L'):
                            tapeposition -= 1
                        elif cycle[0] in ('e', 'E'):
                            tape[tapeposition] == ' '
                    finalmc = data[a][b][-1][0]
                    a = mcNameNumber[finalmc]
    return tape

print turingmachine(eachconfig)

rawDescription: Why is my for loop not iterating in this code?


code:
import ssl
import socket
from httplib2 import has_timeout
import httplib2
import socks

class CertificateValidationError(httplib2.HttpLib2Error):
    pass

def validating_sever_factory(ca_cert_file):
    # we need to define a closure here because we don't control
    # the arguments this class is instantiated with
    class ValidatingHTTPSConnection(httplib2.HTTPSConnectionWithTimeout):

        def connect(self):
            # begin copypasta from HTTPSConnectionWithTimeout
            "Connect to a host on a given (SSL) port."

            if self.proxy_info and self.proxy_info.isgood():
                sock = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM)
                sock.setproxy(*self.proxy_info.astuple())
            else:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

            if has_timeout(self.timeout):
                sock.settimeout(self.timeout)
            sock.connect((self.host, self.port))
            # end copypasta

            try:
                self.sock = ssl.wrap_socket(sock,
                            self.key_file,
                            self.cert_file,
                            cert_reqs=ssl.CERT_REQUIRED,
                            ca_certs=ca_cert_file
                            )
            except ssl.SSLError:
                # we have to capture the exception here and raise later because
                # httplib2 tries to ignore exceptions on connect
                import sys
                self._exc_info = sys.exc_info()
                raise
            else:
                self._exc_info = None

                # this might be redundant
                server_cert = self.sock.getpeercert()
                if not server_cert:
                    raise CertificateValidationError(repr(server_cert))

        def getresponse(self):
            if not self._exc_info:
                return httplib2.HTTPSConnectionWithTimeout.getresponse(self)
            else:
                raise self._exc_info[1], None, self._exc_info[2]
    return ValidatingHTTPSConnection

def do_request(url,
        method='GET',
        body=None,
        headers=None,
        keyfile=None,
        certfile=None,
        ca_certs=None,
        proxy_info=None,
        timeout=30):
    """
    makes an http/https request, with optional client certificate and server
    certificate verification.
    returns response, content
    """
    kwargs = {}
    h = httplib2.Http(proxy_info=proxy_info, timeout=timeout)
    is_ssl = url.startswith('https')
    if is_ssl and ca_certs:
        kwargs['connection_type'] = validating_sever_factory(ca_certs)

    if is_ssl and keyfile and certfile:
        h.add_certificate(keyfile, certfile, '')
    return h.request(url, method=method, body=body, headers=headers, **kwargs)

rawDescription: How to do mutual certificate authentication with httplib2

description: Do mutual certificate authentication with httplib2


code:
from email.MIMEMultipart import MIMEMultipart
from email.header import Header
from email.utils import formataddr

author = formataddr((str(Header(u'Alał', 'utf-8')), "somemail@somedomain.com"))
msg = MIMEMultipart('alternative')
msg['From'] = author
print msg

rawDescription: Python email module: form header "From" with some unicode name + email