code:
import socket

class TestClient(object):
    _buffer = ""

    def __init__(self, host, port):
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.connect((host, port))

    def writable(self):
        return (len(self._buffer) > 0)

    def write(self):
        while self.writable():
            sent = self.send(self._buffer)
            self.buffer = self._buffer[sent:]

    def link(self, name):
        return name.replace(' ', '%20')

    def sendArtist(self, artist):
        print "here"
        self._buffer = self.link(artist)
        self.write()

rawDescription: Python's asyncore client send only last element from list inside a thread


code:
def decorator(func):
    def _decorator(self, *args, **kwargs):
        # access a from TestSample
        print 'self is %s' % self
        func(self, *args, **kwargs)
    return _decorator

rawDescription: Access self from decorator

description: Access self from decorator


code:
def difference(after, before):
    return tuple(before.index(x) for x in after)

print difference('ijk', 'ikj') # (0, 2, 1)
print difference('jik', 'ikj') # (2, 0, 1)

rawDescription: Python permutation difference

description: Python permutation difference


code:
import collections

def move_element(odict, thekey, newpos):
    odict[thekey] = odict.pop(thekey)
    i = 0
    for key, value in odict.items():
        if key != thekey and i >= newpos:
            odict[key] = odict.pop(key)
        i += 1
    return odict

queue = collections.OrderedDict()

queue["animals"] = ["cat", "dog", "fish"]
queue["food"] = ["cake", "cheese", "bread"]
queue["people"] = ["john", "henry", "mike"]
queue["drinks"] = ["water", "coke", "juice"]
queue["cars"] = ["astra", "focus", "fiesta"]

print queue

queue = move_element(queue, "people", 1)

print queue

rawDescription: Changing order of ordered dictionary in python


code:
import os

for item in os.listdir(path):
    if not os.path.isfile(os.path.join(path, item)):
        print "Folder"
    else:
        print "File"

rawDescription: Search Program using python

description: Search Program using python


code:
bk = conn.get_bucket('my_bucket_name')
key = bk.lookup('my_key_name')
print key.size

rawDescription: How do I get the file / key size in boto S3?

description: Get the file / key size in boto S3


code:
if len(sys.argv) == 2 and str(sys.argv[1]).isdigit():
    for i in xrange(0,200000):
        print "%s%05d"%(str(sys.argv[1]), i)
elif len(sys.argv) == 2 and not str(sys.argv[1]).isdigit():
    print ("Given argument must be digit!")
else:
    print ("Wrong number of arguments")

rawDescription: Generating numbers in python loop with specific number


rawDescription: Tuples and nested lists

description: Tuples and nested lists


code:
import pandas as pd
import numpy as np
import io

#test data
temp=u"""id,col1,col2,col3
1,13,15,14
1,13,15,14
1,12,15,13
2,18,15,13
2,18,15,13
2,18,15,13
2,18,15,13
2,18,15,13
2,18,15,13
3,14,15,13
3,14,15,13
3,14,185,213"""
df = pd.read_csv(io.StringIO(temp), sep=",", usecols=['id', 'col1'])
#drop duplicities, from out you can choose constant
df = df.drop_duplicates()
print df
#   id  col1
#0   1    13
#2   1    12
#3   2    18
#9   3    14

#for example list of constants
constants = [1,2,3]
#or column id to list of unique values
constants = df['id'].unique().tolist()
print constants
#[1L, 2L, 3L]

for i in constants:
    iter_csv = pd.read_csv(io.StringIO(temp), delimiter=",", chunksize=10)
    #concat subset with rows id == constant
    df = pd.concat([chunk[chunk['id'] == i] for chunk in iter_csv])
    #your groupby function
    data = df.reset_index(drop=True).groupby(["id","col1"], as_index=False).sum()
    print data.to_csv(index=False)

    #id,col1,col2,col3
    #1,12,15,13
    #1,13,30,28
    #
    #id,col1,col2,col3
    #2,18,90,78
    #
    #id,col1,col2,col3
    #3,14,215,239

rawDescription: pandas groupby with sum() on large csv file?

description: Pandas groupby with sum() on large csv file


code:
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('conf.ini')

try:
    val = config.get('section1', 'var1')
except:
    sys.exit(1)

print val

rawDescription: How to parse ini files and choose appropriate function with python

description: Parse ini files and choose appropriate function with python


code:
import time, re
if True:
    s = time.time()
    "aaaa" in "bbbaaaaaabbb"
    print time.time()-s

if True:
    s = time.time()
    pattern = re.compile("aaaa")
    pattern.search("bbbaaaaaabbb")
    print time.time()-s

rawDescription: Python: speed for "in" vs regular expression


code:
out = open('/tmp/result.txt', 'a+')
with open('/tmp/file.txt', 'r+') as f:
        for line in f:
                i = 1
                line=line.strip('\r\n ')
                while True:
                        work = 'word1' + line + 'word2' + line + 'counter=' + str(i) + 'test'
                        print work
                        result = Function()
                        if "statement" in result:
                                out.write(result)
                                i += 10
                        else:
                                break
out.close()

rawDescription: while true loop in python can't be stopped

description: While true loop in python can't be stopped


code:
for line in codecs.open("data.txt", "r", encoding="utf-8"):
    tup = ast.literal_eval(line)
    print tup[1]

rawDescription: Reading tuples stored in textfile

description: Reading tuples stored in textfile


code:
from openpyxl import load_workbook
wb2 = load_workbook('email_contacts.xlsx')
print wb2.get_sheet_names()

rawDescription: How to get information from an xlsx file in Python?

description: Get information from an xlsx file in Python


code:
x = np.array([1L, 2L, 3L], dtype=object)
x
x[0]
type(x[0])

rawDescription: numpy array using python's long type

description: Numpy array using python's long type


code:
class Value(object):
    """ Generic container of values. """
    def __init__(self, type_, val):
        self.type = type_   # using 'type_' to avoid hiding built-in
        self.val = val

def myfunc(val):
    # Look ma, no type-checking!
    cmdline = 'magicprogram {obj.type} {obj.val}'.format(obj=val)
    print 'Popen({!r}, ... blah blah)'.format(cmdline)
    # ...

val1 = Value('i', 42)
val2 = Value('s', 'foobar')

myfunc(val1)  # Popen('magicprogram i 42', ... blah blah)
myfunc(val2)  # Popen('magicprogram s foobar', ... blah blah)

rawDescription: What is the canonical way of handling different types in Python?


code:
while True:
     result = raw_input("Enter results file: ")

     try:
         result = get_marks_from_file(result)
         break
     except IOError:
         print 'Please supply correct file. '

rawDescription: Python: Print just once in raw_function

description: Python: Print just once in raw_function


code:
class incidenceMatrix:
    def __init__(self, vertexNumber):
        self.matrix = [[] for k in range(vertexNumber)]

    def showGraph(self):
        for i, row in enumerate(self.matrix, 1):
            print i, row

    def isEdge(self, v1, v2):
        return any(x and y for x, y in zip(self.matrix[v1-1], self.matrix[v2-1]))

    def addEdge(self, v1, v2):
        for i, row in enumerate(self.matrix, 1):
            row.append(int(v1==i or v2==i))

    def removeEdge(self, v1, v2):
        num_edges = len(self.matrix[0])
        for j in range(num_edges):
            if self.matrix[v1-1][j] and self.matrix[v2-1][j]:
                for row in self.matrix:
                    del row[j]
                return
        raise Exception('Edge(%d, %d) not found' % (v1, v2))

    def removeVertex(self, v):
        targetrow = self.matrix.pop(v-1)    # fetch and delete the target vertex
        for col, selector in reversed(list(enumerate(targetrow))):
            if selector:                    # find columns that had an edge on the target row
                for row in self.matrix:
                    del row[col]            # remove that column (because the edge is gone)

if __name__ == '__main__':
    GrafIM = incidenceMatrix(5) #verticesNumber
    GrafIM.addEdge(2,3)
    GrafIM.addEdge(1,3)
    GrafIM.addEdge(2,1)
    GrafIM.addEdge(5,2)
    print GrafIM.isEdge(2,4)
    for pair in [(2,3), (1,3), (2,1), (5,2)]:
        print GrafIM.isEdge(*pair)
    GrafIM.showGraph()
    print "-------"
    GrafIM.removeEdge(2,5)
    GrafIM.showGraph()
    print "-------"
    GrafIM.removeVertex(2)
    GrafIM.showGraph()

rawDescription: :Python incidence matrix - How to remove Vertex?


code:
import json
import requests
from bs4 import BeautifulSoup

URL = 'http://data.10jqka.com.cn/interface/market/longhuyyb/stocknum/desc/%d/20'
# config end_page as needed, or parse http://data.10jqka.com.cn/market/longhu/yyb/ to make it auto adapted
end_page = 2

result = []
for page_idx in range(1, end_page + 1):
    print 'Extracting page', page_idx
    raw_response = requests.get(URL % page_idx)
    page_content = json.loads(raw_response.text)['data']
    html = BeautifulSoup(page_content, 'lxml')
    for row in html.tbody.find_all('tr'):
        company = row.find(class_='tl').text
        detail_link = row.find(class_='tl').a['href']
        buy = float(row.find(class_='c_rise').text)
        sell = float(row.find(class_='c_fall').text)
        stock_cnt = int(row.find(class_='cur').text)
        stocks = []
        for a in row.find(class_='lhb_stocklist_box hide').p.find_all('a'):
            stocks.append((a.text, a['href']))
        result.append({
            'company': company,
            'detail_link': detail_link,
            'buy': buy,
            'sell': sell,
            'stock_cnt': stock_cnt,
            'stocks': stocks,
        })

print 'Company number:', len(result)

rawDescription: How to scrape the web table with multiple pages using R or Python

description: Scrape the web table with multiple pages using R or Python


code:
req = grequests.get('http://www.codehenge.net/blog', hooks=dict(response=print_res))
job = grequests.send(req, grequests.Pool(1))

for i in range(10):
    print i

rawDescription: In what way is grequests asynchronous?

description: In what way is grequests asynchronous


code:
x = """NetConn_msa[0].time=0.0

NetConn_msa[1].time=0.0 etc for 60 elements. """

print re.sub("(\]\.\w+)=0.0","\\1=0.5",x)

#NetConn_msa[0].time=0.5

#NetConn_msa[1].time=0.5 etc for 60 elements.

rawDescription: Newbie python - replace in an array

description: Newbie python - replace in an array


code:
s = u'\u0103'
print s.encode('raw_unicode_escape')

rawDescription: How does one print a Unicode character code in Python?

description: Print a Unicode character code in Python


code:
import random
def main():
    wordsf = open('words.txt', 'r')
    words = [line.rstrip('\n') for line in wordsf]
    wordsf.close()

    random_number = random.randint(0, len(words)-1)
    random_word = words[random_number]
    print random_word

rawDescription: how can i randomly print an element from a list in python

description: Randomly print an element from a list in python


code:
import re

rx = r'\beggs?\b'
# looks for egg or eggs as a word

while True:
    response = input()
    if re.search(rx, response):
        print "Yummy eggs in here!"
    if response == 'scrambled eggs':
        print('2 eggs, 1 teaspoon mayonnaise or salad dressing, 1 teaspoon water (optional), 1 teaspoon butter, salt and pepper to taste. In a cup or small bowl, whisk together the eggs, mayonnaise and water using a fork. Melt margarine in a skillet over low heat. Pour in the eggs, and stir constantly as they cook. Remove the eggs to a plate when they are set, but still moist. Do not over cook. Never add salt or pepper until eggs are on plate, but these are also good without ')
    if response == 'rice patties':
        print('1 cup cooked rice, chopped 1/4 cup shredded Cheddar cheese, 1 egg beaten, 1 teaspoon minced garlic, 1/4 teaspoon salt, 1/4 teaspoon ground black pepper, 1/4 teaspoon chopped fresh parsley, 1 tablespoon vegetable oil. Step one: Mix rice, onion, Cheddar cheese, egg, garlic, salt, black pepper, and parsley in a bowl. Step two: Cover bowl with plastic wrap and refrigerate at least 30 minutes. Step three: Form rice mixture into 4 small patties. Step four: Heat vegetable oil in a large skillet over medium-high heat. Fry patties in hot oil until lightly browned, about 5 minutes per side.')
    if response == 'french toast':
        print('bread, eggs, milk, vanilla, syrup, butter, cinnamon')
    if response == 'scrambled eggs':
        print('eggs, cheese')
    if response == 'close':
        break

rawDescription: how do I search recipes for everything that has the word 'egg' or 'eggs' and print recipes with the variable included?

description: Search recipes for everything that has the word 'egg' or 'eggs' and print recipes with the variable included


code:
a=10
b=10
c=10

def D():
    return a+b+c

print D()

a=1

print D()

rawDescription: How to make a variable interactively dependent to its assigned formula

description: Make a variable interactively dependent to its assigned formula


rawDescription: Elliptic curve brute forcing

description: Elliptic curve brute forcing


code:
keyword_list = ['motorcycle', 'bike', 'cycle', 'dirtbike']

if any(word in all_text for word in keyword_list):
    print 'found one of em'

rawDescription: Find matching words in a list and a string


code:
from collections import defaultdict

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

result = collections.defaultdict(int) # new keys are auto-added and initialized as 0
for item in data:
    a, b, value = item
    result[(a,b)] += value
print result
# defaultdict(<type 'int'>, {('a', 'b'): 3, ('a', 'c'): 1})
print dict(result)
# {('a', 'b'): 3, ('a', 'c'): 1}
print [[a, b, total] for (a, b), total in result.items()]
# [['a', 'b', 3], ['a', 'c', 1]]

rawDescription: Identify duplicates in a list of lists and sum up their last items


code:
import dbus
import dbus.service
import gobject
from dbus.mainloop.glib import DBusGMainLoop

def event_factory(event_name):
    class Event(dbus.service.Object):
        def __init__(self):
            self.busName = dbus.service.BusName('com.acme.EventManager',
                                                bus=dbus.SessionBus())
            dbus.service.Object.__init__(self,
                                         self.busName,
                                         '/com/acme/EventManager/'+event_name)

        @dbus.service.signal(dbus_interface='com.acme.EventManager.'+event_name,
                             signature='v')
        def emit(self, data):
            print "In %s event, got: %s " % (event_name, data)

    return Event() # return an instance of the class

if __name__ == "__main__":
    DBusGMainLoop(set_as_default=True)
    bus = dbus.SessionBus()
    loop = gobject.MainLoop()
    connect = event_factory('Connect')
    disconnect = event_factory('Disconnect')
    loop.run()

rawDescription: How can I manually invoke dbus.service.signal decorator?

description: Manually invoke dbus.service.signal decorator


rawDescription: Extracting strings from a list of dictionaries


code:
def model_saved(sender, **kwargs):
    send_mail('Subject here', 'Here is the message.', 'from@example.com',
    ['ndhiman08@gmail.com'], fail_silently=False)
    abc_obj = kwargs['instance']
    #can use fields as
    #abc_obj.somefield
    print "SAVED",sender,kwargs

rawDescription: Issues with signals in django

description: Issues with signals in django


code:
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta

# inputs (cannot change)
from_time_str = '13:45'
from_offset = '-0700'
to_offset = '-0100'

if from_offset[0]=='-':
    non_offset = parse(from_time_str)+relativedelta(hours=int(from_offset[1:3]), minutes=int(from_offset[3:]))
else:
    non_offset = parse(from_time_str)-relativedelta(hours=int(from_offset[1:3]), minutes=int(from_offset[3:]))

if to_offset[0]=='-':
    to_offset_time = non_offset-relativedelta(hours=int(to_offset[1:3]), minutes=int(to_offset[3:]))
else:
    to_offset_time = non_offset+relativedelta(hours=int(to_offset[1:3]), minutes=int(to_offset[3:]))

print to_offset_time.strftime('%H:%M')

rawDescription: Python 2.7 - Time offset conversion

description: Python 2.7 - Time offset conversion


code:
pdfs = ['a.pdf', 'b.pdf', 'c.pdf', 'd.pdf']
xmls = ['a.xml', 'd.xml', 'b.xml']

xml_set = set(xmls)

result = []
for pdf in pdfs:
    xml = pdf.replace('.pdf', '.xml')
    if xml in xml_set:
        result.append('Matched %s to %s' % (pdf, xml))
    else:
        result.append("%s doesn't have a corresponding XML file" % (pdf,))

print result

rawDescription: Matching Items in Lists - Python

description: Matching Items in Lists - Python


code:
import gevent
from gevent.queue import *
import time
import random

q = JoinableQueue()
workers = []

def do_work(wid, value):
    gevent.sleep(random.randint(0,2))
    print 'Task', value, 'done', wid

def worker(wid):
    while True:
        item = q.get()
        try:
            do_work(wid, item)
        finally:
            q.task_done()

def producer():
    for i in range(4):
        workers.append(gevent.spawn(worker, random.randint(1, 100000)))

    for item in range(1, 9):
         q.put(item)

producer()
q.join()

rawDescription: Gevent threads don't finish even though all the Queue items are exhausted


code:
import zipfile

zf = zipfile.ZipFile('example.zip', 'r')
print zf.namelist()

rawDescription: search within an unextracted .zip file

description: Search within an unextracted .zip file


code:
import sys
import re

chars = r"A-Za-z0-9/\-:.,_$%'()[\]<> "
shortest_run = 4

regexp = '[%s]{%d,}' % (chars, shortest_run)
pattern = re.compile(regexp)

def process(stream):
    data = stream.read()
    return pattern.findall(data)

if __name__ == "__main__":
    for found_str in process(sys.stdin):
        print found_str

rawDescription: extract strings from a binary file in python

description: Extract strings from a binary file in python


code:
import networkx as nx
import matplotlib.pyplot as plt
import matplotlib as mpl
Dict = {"Alice": 0, "Bob": 1, "Carol": 2}
cmap = plt.cm.Accent
norm = mpl.colors.Normalize(vmin=0, vmax=2)
m = plt.cm.ScalarMappable(norm=norm, cmap=cmap)
for key, value in Dict.iteritems():
    print key, value, m.to_rgba(value)
plt.hlines(1, 1, 5, m.to_rgba(Dict["Alice"]), linewidth=50)
plt.hlines(2, 1, 5, m.to_rgba(Dict["Bob"]),   linewidth=50)
plt.hlines(3, 1, 5, m.to_rgba(Dict["Carol"]), linewidth=50)
G = nx.Graph()
G.add_nodes_from(Dict.keys())

nodelist,node_color = zip(*Dict.items())
nx.draw_networkx(G, nodelist=nodelist, node_size=1000, node_color=node_color,vmin=0.0,vmax=2.0, cmap=cmap)
plt.show()

rawDescription: Setting colors in draw_networkx and in matplotlib


code:
# Create example data and heapify
a = range(10)
a.reverse()
heapq.heapify(a)
print a

# remove an element and heapify again
a.remove(5)
heapq.heapify(a)
print a

rawDescription: Removing an item from a priority queue

description: Removing an item from a priority queue


code:
import dis
def foo():
  a = b + 2
  print bar
  baz()

dis.dis(foo)

rawDescription: Getting Assembly code for Python programs


code:
for row in rows:
    rec={}
    for k in range(len(row)):
        print k
        rec[columns[k]]=row[k]
    rtn.append(rec)

rawDescription: Python + psycopg: type '23' for column when in fact 'double precision' in postgresql database


code:
import csv

f1 = open("test1.txt", 'rb')
reader1 = csv.reader(f1)
f2 = open("test2.txt", 'rb')
reader2 = csv.reader(f2)
result = []

for entry in reader1:
    print entry
    for row in reader2:
        print row
        if entry[0].strip() == row[1].strip():
            del row[1]
            load = entry + row
            result.append(load)

for line in result:
    print line

rawDescription: Writing empty columns in python

description: Writing empty columns in python


code:
from selenium.webdriver.support.ui import Select, WebDriverWait

select = self.br.find_element_by_name( field )  #get the select element
options = select.find_elements_by_tag_name("option") #get all the options into a list

optionsList = []

for option in options: #iterate over the options, place attribute value in list
    optionsList.append(option.get_attribute("value"))

for optionValue in optionsList:
    print "starting loop on option %s" % optionValue

    select = Select(self.br.find_element_by_name( field ))
    select.select_by_value(optionValue)

    source = self.br.page_source #get the new page source

    #now check to see if some required data is on the navigated page, and print some stuff if so
    if "There is no summary data available." not in source:
         print "the new page is good! Here are the original args: ", optionValue
    #time to go back to the main page and click the next option element
    self.br.back()
    print "went backwards" #for debugging

rawDescription: python selenium site spider from page option list

description: Python selenium site spider from page option list


code:
from HTMLParser import HTMLParser

inTD = False

# create a subclass and override the handler methods
class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        global inTD
        if tag.upper() == "TD":
            inTD = True
    def handle_endtag(self, tag):
        global inTD
        if tag.upper() == "TD":
            inTD = False
    def handle_data(self, data):
        global inTD
        if inTD:
            print data

rawDescription: How to extract HTML tag content with python HTMLParser

description: Extract HTML tag content with python HTMLParser


code:
import gtk
import gobject
import cairo
import sys

class PyApp(gtk.Window):

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

        self.set_title("Fade In")
        self.resize(300, 350)
        self.set_position(gtk.WIN_POS_CENTER)

        ## alpha is starting transparency
        self.alpha = 0
        ## delta is amount to increase alpha
        self.delta = 0.01

        self.connect("destroy", gtk.main_quit)

        self.darea = gtk.DrawingArea()
        self.darea.connect("expose-event", self.expose)
        self.add(self.darea)

        try:
            self.surface = cairo.ImageSurface.create_from_png("/usr/share/icons/gnome/256x256/emotes/face-angel.png")
        except Exception, e:
            print e.message
            sys.exit(1)

        self.show_all()

    def fadeImage(self):
        self.darea.queue_draw()

    def expose(self, widget, event):

        cr = widget.window.cairo_create()

        cr.set_source_surface(self.surface, 10, 10)
        cr.paint_with_alpha(self.alpha)

        self.alpha += self.delta

        if self.alpha >= 1: return False
        else: gobject.timeout_add(50,self.fadeImage)

PyApp()
gtk.main()

rawDescription: pygtk image fadein

description: Pygtk image fadein


code:
import random

class DNA(object):
    score = 0

    def __init__(self, bits):
        self.bits = bits
        self.length = len(bits)

    # https://en.wikipedia.org/wiki/Crossover_%28genetic_algorithm%29#Two-point_crossover
    def two_point_crossover(self, other):
        start = random.randint(0, self.length - 1)
        end = random.randint(start, self.length - 1)

        child_1 = DNA(self.bits[:start] + other.bits[start:end] + self.bits[end:])
        child_2 = DNA(other.bits[:start] + self.bits[start:end] + other.bits[end:])
        return child_1, child_2

    # https://en.wikipedia.org/wiki/Mutation_%28genetic_algorithm%29
    def mutate(self, probability):
        self.bits = [bit if random.random() > probability else not bit for bit in self.bits]

    # Allow us to 'breed' two strings by doing dna_1 * dna_2
    def __mul__(self, other):
        return self.two_point_crossover(other)

    @staticmethod
    def decode_byte(bits):
        out = 0
        for bit in reversed(bits):
            out = out << 1
            out += bit

        return out

    def as_bytes(self):
        return [DNA.decode_byte(self.bits[start:start+8]) for start in xrange(0, self.length, 8)]

class Population(object):
    cumulative_scores = None
    total_score = 0
    best_score = 0
    best_member = None

    def __init__(self, members):
        self.members = members
        self.length = len(members)

    def rate(self, fitness_function):
        self.cumulative_scores = []
        self.total_scores = 0

        for member in self.members:
            score = fitness_function(member)
            member.score = score
            self.total_score += score
            self.cumulative_scores.append((self.total_score, member))

            if score > self.best_score:
                self.best_score = score
                self.best_member = member

    # https://en.wikipedia.org/wiki/Fitness_proportionate_selection
    def roulette_wheel_selection(self):
        pick = random.uniform(0, self.total_score)

        current = 0
        pos = 0

        while current < pick:
            (score, member) = self.cumulative_scores[pos]
            pos += 1
            current = score

        return member

    def mutate(self, mutation_rate):
        for member in self.members:
            member.mutate(mutation_rate)

class GeneticAlgorithm(object):
    def __init__(self, fitness_function, population, mutation_rate=0.01):
        self.population = population
        self.fitness_function = fitness_function
        self.mutation_rate=0.01

    def mutate(self):
        self.population.mutate(self.mutation_rate)

    def rate(self):
        self.population.rate(self.fitness_function)

    def breed(self):
        new_members = []
        while len(new_members) < self.population.length:
            parent_1 = self.population.roulette_wheel_selection()
            parent_2 = self.population.roulette_wheel_selection()

            new_members += parent_1 * parent_2

        self.population = Population(new_members[:self.population.length])

#----------------------------------------#
# My problem here

def my_fitness(dna):
    angry, legs, smelly, loyalty = dna.as_bytes()

    score = float((510 - angry - smelly) * loyalty * legs) / float(510*255*255)
    return score

pop = Population([DNA([0] * 8 * 4) for _ in range(1000)])
pop.mutate(0.5)     # Totally randomise our starting set
ga = GeneticAlgorithm(my_fitness, pop)

for _ in range(100):
    ga.mutate()
    ga.rate()
    print "Best so far:", ga.population.best_score
    ga.breed()

# Finished!

ga.rate()
angry, legs, smelly, loyalty = ga.population.best_member.as_bytes()

print "Best score: ", ga.population.best_score
print "Angry", angry, "Legs", legs, "Smelly", smelly, "Loyalty", loyalty

rawDescription: Finding the optimum combination of parameters for stock backtesting python


code:
import tempfile
import win32api
import win32con
import win32security

f = tempfile.NamedTemporaryFile ()
FILENAME = f.name
try:
  sd = win32security.GetFileSecurity (FILENAME,win32security.OWNER_SECURITY_INFORMATION)
  owner_sid = sd.GetSecurityDescriptorOwner ()
  name, domain, type = win32security.LookupAccountSid (None, owner_sid)

  print "I am", win32api.GetUserNameEx (win32con.NameSamCompatible)
  print "File owned by %s\\%s" % (domain, name)
finally:
  f.close ()

rawDescription: View Windows file metadata in Python

description: View Windows file metadata in Python


code:
def add_list_attributes(klass):
    def new(cls, *args, **kwargs):
        result = super(cls, cls).__new__(cls)
        for attribute in klass.list_attributes:
            setattr(result, attribute, [])
        return result
    klass.__new__ = staticmethod(new)
    return klass

@add_list_attributes
class Person(object):
    list_attributes = [
        'phone_numbers'
    ]
    def __init__(self):
        pass

p1 = Person()
p2 = Person()
p1.phone_numbers.append('01234')

print p1.phone_numbers, p2.phone_numbers

rawDescription: Dynamically add instance variables via decorator to a class in Python


code:
def spam():
  print "spam and", eggs

exec(spam.__code__, {'eggs':'pasta'})

rawDescription: Python: How to pass arguments to the __code__ of a function?


code:
import bisect

bins = range(0, 100, 15)

print bisect.bisect_left(bins, 35)

rawDescription: Finding if a number falls within a certain range python


code:
logfile = open('ip.log', 'r')
loglist = logfile.readlines()
logfile.close()
found = False
for line in loglist:
    if str(self.CLIENT_HOST) in line:
        print "Found it"
        found = True

if not found:
    logfile = open('ip.log', 'a')
    logfile.write(str(self.CLIENT_HOST)+"\n")
    logfile.close()

rawDescription: check if a line exists in a file python

description: Check if a line exists in a file python


code:
import os, time, sys
import watchdog.events
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer

class LatexCompiler(FileSystemEventHandler):
    def __init__(self, files, *args, **kwargs):
        super(LatexCompiler, self).__init__(*args, **kwargs)
        self._files = files
        print "LatexCompiler(): monitoring files %r" % self._files

    def on_modified(self, event):
        if (isinstance(event, watchdog.events.FileModifiedEvent) and
                event.src_path in self._files):
            print event
            os.system("pdflatex %s" % event.src_path)

if __name__ == "__main__":
    path = sys.argv[1] if len(sys.argv) > 1 else '.'

    observer = Observer()
    files = [os.path.join(path, f) for f in ['Thesis.tex', 'Resume.tex']]
    observer.schedule(LatexCompiler(files), path, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()

rawDescription: Python watchdog loops forever on os.system()


code:
page = requests.get('http://feeds.bbci.co.uk/news/rss.xml')
links = bs4.BeautifulSoup(page.text).find_all('link')
print links[0].text
webbrowser.open(links[0].text)

rawDescription: Differentiating between relevant and irrelevant URLs


code:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, BigInteger, ForeignKey, Integer
from sqlalchemy.orm import relationship, sessionmaker

Base = declarative_base()
engine = create_engine('sqlite://') ## In Memory.
Session = sessionmaker()
Session.configure(bind=engine)
session = Session()

class Post(Base):
    __tablename__ = 'post'
    id = Column(Integer, primary_key=True)
    last_editor_id = Column(BigInteger, ForeignKey('users.id'), nullable=True)
    last_editor = relationship('User', backref='editor_posts', foreign_keys=[last_editor_id])
    owner_id = Column(BigInteger, ForeignKey('users.id'), nullable=False, index=True)
    owner = relationship('User', backref='owner_posts', foreign_keys=[owner_id])

    def __repr__(self):
        return '<Post: {}>'.format(self.id)

class User(Base):
    '''This represents a user on the site'''
    __tablename__ = 'users'
    id = Column(BigInteger, primary_key=True, unique=True)
    name = Column(BigInteger, nullable=False)

    def __repr__(self):
        return '<User: {}>'.format(self.name)

Base.metadata.create_all(engine)

bob = User(name='Bob', id=1)
alice = User(name='Alice', id=2)
post = Post(owner=alice, last_editor=bob, id=1)

session.add(post)
session.commit()

bob = session.query(User).get(1)
print bob
# <User: Bob>
print bob.editor_posts
# [<Post: 1>]
print bob.owner_posts
# []

post = session.query(Post).get(1)
print post.owner
# <User: Alice>
print post.last_editor
# <User: Bob>

rawDescription: sqlalchemy Error creating backref on relationship

description: Sqlalchemy Error creating backref on relationship


code:
fp = urllib2.urlopen("http://www.example.com/index.cfm")

response = ""
while 1:
    data = fp.read()
    if not data:         # This might need to be    if data == "":   -- can't remember
        break
    response += data

print response

rawDescription: urllib2 not retrieving entire HTTP response

description: Urllib2 not retrieving entire HTTP response


code:
def submerge(d, e, f):
    for g in d[:-1]:
        yield g
    yield e
    yield f
    yield d[-1] # if you want to remove the last element just remove this line

def merge(a, b, c):
    for d, e, f in zip(a, b, c):
        yield tuple(submerge(d, e, f))

a = [(12,3,1),(12,3,5)]
b = [4,2]
c = ['A','B']

print list(merge(a, b, c))

rawDescription: adding 2 lists to a list of tuples

description: Adding 2 lists to a list of tuples


code:
import httplib
conn = httplib.HTTPConnection("www.google.com")
conn.request("HEAD", "/index.html")
res = conn.getresponse()
print res.status, res.reason
print res.getheaders()

rawDescription: How do you send a HEAD HTTP request in Python?

description: Send a HEAD HTTP request in Python


rawDescription: Picking largest number form a list not working


code:
import subprocess
from subprocess import PIPE

def main():
    process = subprocess.Popen('echo %USERNAME%', stdout=PIPE, shell=True)
    username = process.communicate()[0]
    print username #prints the username of the account you're logged in as

    process = subprocess.call('python py1.py --help', shell=True)
    process = subprocess.call('python py2.py --help', shell=True)
    process = subprocess.call('python py3.py --help', shell=True)

if __name__ == '__main__':
    main()

rawDescription: Run a python script from another python script and pass variables to it


code:
l = range(0, 40)
seen = set()
x = 0
while len(seen) < len(l):
    r = random.choice(l)
    if r not in seen:
        seen.add(r)
    x = x + 1
print x

rawDescription: Using python pick a random element from a list with replacement


code:
from freezegun import freeze_time

@freeze_time("2012-01-14")
def test():
    assert datetime.datetime.now() == datetime.datetime(2012, 01, 14)

rawDescription: advance time artificially in pytest

description: Advance time artificially in pytest


rawDescription: How to print container object with unicode-containing values?

description: Print container object with unicode-containing values


code:
from collections import defaultdict
import re

variables = ['VariableA', 'VariableB', 'VariableC']
regexes = [re.compile(r'(%s)[:|=|\(](-?\d+(?:\.\d+)?)(?:\))?' % (variable,))
           for variable in variables]
d = defaultdict(list)

with open("temp.txt") as f:
    for line in f:
        results = [regex.search(line) for regex in regexes]
        if all(results):
            for m in results:
                k, v = m.groups()
                d[k].append(v)

print d

rawDescription: Find multiple regex in each line and skip result if one of the regex doesn't match


code:
def loop(d1):
    for k, v in d1.iteritems():
        if isinstance(v['r'], list):
            for l in v['r']:
                if url1.find(l):
                    yield l
                else:
                    continue
        else:
            if url1.find(v['r']):
                yield v['r']
            else:
                continue

for item in loop(d1):
    print "do something"

rawDescription: Solving nested dict iteration by list comprehension or any other method


rawDescription: How to remove lines from a large file

description: Remove lines from a large file


code:
from struct import unpack
s = "abcdefgty"
int_char, my_str = unpack("b8s", s)
print int_char
print my_str

rawDescription: Unpack value into multiple variable in python


code: print result['results'][0]['name']

rawDescription: python: I want to find the first record in google place result but getting first character

description: Python: I want to find the first record in google place result but getting first character


code:
#! /usr/bin/env python

from Tkinter import *
#import requests
import base64

def build_payload(var1, var2, var3):
    var4 = "31039888252154&31039888252154&0&X168&1411869345&IQSAXYOS&" \
        + var2 + "&" + var3 \
        + "&&1&3&1&ubugg@zetmail.com&goohoo&1411603529&&2&"

    print 'var4 = [%s]\n' % var4

    var5 = base64.b64encode(var4)

    payload = {
        'X1': '218',
        'X127': 'X325',
        'X171': var1,
        'X677': '1420103258',
        'X678': '208180484',
        'X691': var5,
        'X763': '1'
    }
    return payload

class my_GUI(object):
    def __init__(self):
        #Build GUI
        root = Tk()

        root.title("Spam Project")
        root.geometry("200x200")

        app = Frame(root)
        app.grid()

        button = Button(app, text = "Send")
        button.grid()
        button.bind('<Button-1>', self.send_data)

        self.e1 = Entry(root)
        self.e1.grid()
        self.e1.insert(0, "Message")

        self.e2 = Entry(root)
        self.e2.grid()
        self.e2.insert(0, "Name")

        self.e3 = Entry(root)
        self.e3.grid()
        self.e3.insert(0, "Color in Hex")

        button = Button(app, text = "Print")
        button.grid()
        button.bind('<Button-1>', self.print_data)

        #Start tkinter event loop
        root.mainloop()

    def print_data(self, e):
        var1 = self.e1.get()
        var2 = self.e2.get()
        var3 = self.e3.get()
        print var1, var2, var3

    def send_data(self,e):
        var1 = self.e1.get()
        var2 = self.e2.get()
        var3 = self.e3.get()
        print var1, var2, var3

        payload = build_payload(var1, var2, var3)
        print 'Sending payload', payload
        #requests.post("http://us23.chatzy.com/", data=payload)

def main():
    my_GUI()

if __name__ == '__main__':
    main()

rawDescription: Why won't my program read input from entry?


code:
def function2():
    print 'function2 has been called'

def function3():
    pass

def function1():
    # call the other functions
    function2()
    function3()

rawDescription: Call function that has been defined within a function


code:
import wx
import wx.grid as gridlib

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

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        self.s=parent
        self.txt = wx.TextCtrl(self)
        button =wx.Button(self, label="Save", pos=(200, 0))
        button.Bind(wx.EVT_BUTTON, self.Check)

    def Check(self,event):
        passw=self.txt.GetValue()
        if  passw=="1":
            print "true"
            self.s.onSwitchPanels(self)

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

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

        grid = gridlib.Grid(self)
        grid.CreateGrid(25,12)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(grid, 0, wx.EXPAND)
        self.SetSizer(sizer)
        button =wx.Button(self, label="Save", pos=(0, 500))
        button.Bind(wx.EVT_BUTTON, parent.onSwitchPanels)
class PanelThree(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        txt = wx.TextCtrl(self)
        button =wx.Button(self, label="Save", pos=(200, 325))
        button.Bind(wx.EVT_BUTTON, parent.onSwitchPanels)

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

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY,
                          "Panel Switcher Tutorial",
                          size=(800,600))

        self.panel_one = PanelOne(self)
        self.panel_two = PanelTwo(self)
        self.panel_three = PanelThree(self)
        self.panel_two.Hide()
        self.panel_three.Hide()

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.panel_one, 1, wx.EXPAND)
        self.sizer.Add(self.panel_two, 1, wx.EXPAND)
        self.SetSizer(self.sizer)

        menubar = wx.MenuBar()
        fileMenu = wx.Menu()
        switch_panels_menu_item = fileMenu.Append(wx.ID_ANY,
                                                  "Switch Panels",
                                                  "Some text")
        self.Bind(wx.EVT_MENU, self.onSwitchPanels,
                  switch_panels_menu_item)
        menubar.Append(fileMenu, '&File')
        self.SetMenuBar(menubar)

    #----------------------------------------------------------------------
    def onSwitchPanels(self, event):

        if self.panel_one.IsShown():
           self.SetTitle("Panel Two Showing")
           self.panel_one.Hide()
           self.panel_two.Show()
           self.panel_three.Hide()
        elif self.panel_two.IsShown() or self.panel_three.IsShown():

           self.SetTitle("Panel One Showing")
           self.panel_one.Show()
           self.panel_two.Hide()
           self.panel_three.Hide()
        else:
             self.SetTitle("Panel Three Showing")
             self.panel_one.Hide()
             self.panel_two.Hide()
             self.panel_three.Show()

        self.Layout()

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

rawDescription: Error with multiple panels in one frame WXPYTHON


code:
import urllib
import sys
import xml.dom.minidom

#The url of the feed
address = 'http://www.vg.no/export/Alle/rdf.hbs?kat=nyheter'

f = open('lawl.txt','w')

#Our actual xml document
document = xml.dom.minidom.parse(urllib.urlopen(address))
for item in document.getElementsByTagName('item'):
    title = item.getElementsByTagName('title')[0].firstChild.data
    link = item.getElementsByTagName('link')[0].firstChild.data
    description = item.getElementsByTagName('description')[0].firstChild.data

    str = link.strip("http://go.vg.no/cgi-bin/go.cgi/rssart/")
    print "\n"
    print "------------------------------------------------------------------"
    print '''"%s"\n\n%s\n\n(%s)''' % (title.encode('UTF8', 'replace'),
                                            description.encode('UTF8','replace'),
                                            str.encode('UTF8','replace'))
    print "------------------------------------------------------------------"
    print "\n"

    print >>f, "----------------------Nyeste paa VG-------------------------------"
    print >>f, title.encode('UTF8','replace')
    print >>f, description.encode('UTF8','replace')
    print >>f, str.encode('UTF8','replace')
    print >>f, "------------------------------------------------------------------"
    print >>f, "\n"

rawDescription: Why does this Python script only read the last RSS post into the file?


code:
from six.moves.urllib import parse
o=parse.urlparse('http://me:me1234%23@localhost:8080/')
print o

rawDescription: urllib does not handle # character properly

description: Urllib does not handle # character properly


rawDescription: have a url that accepts all characters

description: Have a url that accepts all characters


code:
def pagetext(text_lined, num_lines=25):
   for index,line in enumerate(text_lined):
       if index % num_lines == 0 and index:
           input=raw_input("Hit any key to continue press q to quit")
           if input.lower() == 'q':
               break
       else:
           print line

rawDescription: Paging output from print statement

description: Paging output from print statement


code:
a = np.arange(10)
print a.base
None

b = a[2:9]
print b.base is a
True

c = b[:2]
print c.base is b
True
print c.base is a
False

rawDescription: Can you tell if an array is a view of another?

description: Tell if an array is a view of another


code:
def recursiveadd(x,sum1):
    if x > 0:
        sum1 += x
        return recursiveadd(x-1,sum1)
    else:
        return sum1

print recursiveadd(100,0)

rawDescription: Why does this recursive summation function return None?


code:
class Server(QObject):
    def __init__(self, parent=None):
        QObject.__init__(self)

    def incomingConnection(self, handle):
        print "incoming"
        self.client = Client(self)
        self.client.SetSocket(handle)

    def StartServer(self):
        self.server = QTcpServer()
        self.server.incomingConnection = self.incomingConnection
        if self.server.listen(QHostAddress("0.0.0.0"), 8888):
            print "Server is awake"
        else:
            print "Server couldn't wake up"

rawDescription: PyQT4 Asynchronous QTcpServer (How to create event loop)


code:
my_string = '''

    helloworld

'''
root = html.fromstring(my_string)
print root.text_content()
for text in root.itertext():
    text = text.strip()
    if text: # to skip empty(or space-only) string
        print text
print ' '.join(root.itertext())

rawDescription: Robust way to avoid run-on words when using text_content() on html elements


code:
from inspect import getframeinfo
from logging import currentframe
from datetime import datetime

def callingFrame():
    return getframeinfo(currentframe())

def gTime():
    position = "%s [%s] - " % (str(datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f").rstrip('0')), callingFrame().lineno)
    return position

print gTime()

rawDescription: Python - add a dynamic debug logger style line number and time function


code:
with open('homosapiens.txt', 'r') as f:
    for line in f:
        if line == 'human, Homo sapiens':
            print line  # this will print and go to a newline
        elif line:
            print line,  # the comma after line suppresses the newline

rawDescription: How to write multiple lines in a single line?

description: Write multiple lines in a single line


code:
import re

PHONE_RE = re.compile('([(]{0,1}[2-9]\d{2}[)]{0,1}[-_. ]{0,1}[2-9]\d{2}[-_.  ]{0,1}\d{4})')
NON_NUMERIC = re.compile('\D')

def numbers2links(s):

   def makelink(mo):
      raw_number = mo.group()
      number = NON_NUMERIC.sub("", raw_number)
      return '%s' % (number, raw_number)

   return PHONE_RE.sub(makelink, s)

print numbers2links("Ghost Busters at (555) 423-2368! How about this one: 555 456 7890! 555-456-7893 is where its at.")

rawDescription: Phone numbers to links in Python

description: Phone numbers to links in Python


code:
import random
import xchat

def callback(word, world_eol, userdata):
    number = word[1]
    if random_chance(number):
        print "Success"
    else:
        print "Failure"

def random_chance(percent_chance):
    return random.randrange(1, 101) > (100 - int(percent_chance))

xchat.hook_command("random", callback, help="/random <number>")

rawDescription: Randomizing script for HexChat IRC Client, in Python or Perl


code:
MaxAmount = 100
TotalAmount = 0

while TotalAmount < MaxAmount:
    #Here if you want it to be more precise on decimals change int(raw_input("Amount: ")) to float(raw_input("Amount: "))
    EnteredAmount = float(raw_input("Amount: "))
    if EnteredAmount > MaxAmount:
        print "You can not go over 100"
    elif TotalAmount > MaxAmount:
        #You can go two ways here either just set TotalAmount to MaxAmount or just cancel the input
        print "You can not go over 100"
    elif EnteredAmount <= MaxAmount:
        TotalAmount = TotalAmount + EnteredAmount
        print TotalAmount
print "You have reached the total amount of ", MaxAmount

rawDescription: Write a Python program that repeatedly asks the user to input coin values until the total amount matches a target value


code:
import networkx
X = networkx.read_dot('_t.dot')

def navigate_through_model(model, start_node, end_node, typex):
    path = []
    actual_node = start_node
    visited_nodes = []
    status = True
    while actual_node != end_node:
        u = networkx.all_neighbors(model, actual_node)
        for line in u:
            target_node = line
            print target_node
            try:
                comm = model[actual_node][target_node][0]['comment']
                if (comm == typex and target_node not in visited_nodes):
                    path.append((actual_node, target_node))
                    actual_node = target_node
                    visited_nodes.append(target_node)
                    print path
                    print '\n'
                    print visited_nodes
                    status = True
                else:
                    status = False
            except Exception as err:
                pass
        if not status:
            return "not found"
    return path

print navigate_through_model(X, 'start', 'end', 'regression')

rawDescription: Networkx: find way according to .dot file attribute


code:
tag = getTag(connection, instanceId.split(':')[1])
if tag is not None:
    print "Port %s Open for 0.0.0.0/0, SecurityGroupName: %s  Instance Details --> : %s " % (rule.to_port, securityGroup.name,  tag)

rawDescription: If a function returns None, then don't print anything condition Python


code:
from random import randrange

def choose(colors, numselections, maxrun):
    'Repeatedly choose colors.  Gradually reduce selection probability to avoid runs.'
    colors = list(colors)
    n = len(colors)
    total = n * maxrun
    current_run = 0
    for _ in range(numselections):
        i = randrange(total - current_run) // maxrun
        yield colors[i]
        colors[i], colors[-1] = colors[-1], colors[i]
        current_run = current_run + 1 if i==n-1 else 1

if __name__ == '__main__':
    colors = ['red', 'blue', 'green', 'yellow']
    for color in choose(colors, 100, maxrun=4):
        print color

rawDescription: Sorting algorithm to keep equal values separated


code:
import urllib2
data = urllib2.urlopen("some_url")
html_data = data.read()
soup = BeautifulSoup(html_data)

for a in soup.findAll('a',href=True):
    print a['href']

rawDescription: How to extract a href link from anchor tags in beautiful soup

description: Extract a href link from anchor tags in beautiful soup


code:
import flask
import serial
from time import sleep

app = flask.Flask(__name__)
app.debug = True

def event_barcode():
    messageid = 0
    ser = serial.Serial()
    ser.port = 0
    ser.baudrate = 9600
    ser.bytesize = 8
    ser.parity = serial.PARITY_NONE
    ser.stopbits = serial.STOPBITS_ONE
    ser.timeout = 0
    try:
        ser.open()
    except serial.SerialException, e:
         yield 'event:error\n' + 'data:' + 'Serial port error({0}): {1}\n\n'.format(e.errno, e.strerror)
         messageid = messageid + 1
    str_list = []
    while True:
        sleep(0.01)
        nextchar = ser.read()
        if nextchar:
            str_list.append(nextchar)
        else:
            if len(str_list) > 0:
                yield 'id:' + str(messageid) + '\n' + 'data:' + ''.join(str_list) + '\n\n'
                messageid = messageid + 1
                str_list = []

@app.route('/barcode')
def barcode():
    newresponse = flask.Response(event_barcode(), mimetype="text/event-stream")
    newresponse.headers.add('Access-Control-Allow-Origin', '*')
    newresponse.headers.add('Cache-Control', 'no-cache')
    return newresponse

if __name__ == '__main__':
    app.run(port=8080, threaded=True)

rawDescription: pyserial reading serial port in flask (maybe using gevent)

description: Pyserial reading serial port in flask (maybe using gevent)


code:
def text_file():
    return 'text.txt'

def show_log():  ##  Main log function,
    filename = text_file()
    if os.path.exists(filename) and os.path.getsize(filename): # if text.txt is not empty show the menu
        log_menu()
    else: # no textfile there or its empty
        print
        print "  You have not draw anything yet!"
        print
        raw_input('  Press Enter to continue ')
    return

rawDescription: how to call a function in another function?

description: Call a function in another function


code:
#!/usr/bin/python
import tweepy
import csv #Import csv
auth = tweepy.auth.OAuthHandler('XXXXXX', 'XXXXXXX')
auth.set_access_token('XXX-XXX', 'XXX')

api = tweepy.API(auth)
# Open/Create a file to append data
csvFile = open('result.csv', 'a')
#Use csv Writer
csvWriter = csv.writer(csvFile)

for tweet in tweepy.Cursor(api.search,
                    q="google",
                    since="2014-02-14",
                    until="2014-02-15",
                    lang="en").items():
    #Write a row to the csv file/ I use encode utf-8
    csvWriter.writerow([tweet.created_at, tweet.text.encode('utf-8')])
    print tweet.created_at, tweet.text
csvFile.close()

rawDescription: Get data from Twitter using Tweepy and store in csv file


code:
a = int(10)
b = a
print id(a), id(b)
a += 1
print id(a), id(b)
print a, b

rawDescription: Why is there no "++" operation in Python?


code:
#lines = open ('E:\Python\Assessment\dracula.txt', 'r'). readlines ()

#stripped_list = [item.strip() for item in lines]

with open('/home/facundo/tmp/words.txt') as i:
    stripped_list = [x.strip() for x in i.readlines()]

#tally = [] #empty set of lengths
#for lengths in range(1,20):
#    tally.append(0)

tally = [0] * 20

print tally #original tally

for i in stripped_list:
    #length_word = int(len(i))
    word_length = len(i)
    #tally[length_word] = tally[length_word] + 1
    if word_length > 0:
        tally[word_length - 1] += 1

print tally

rawDescription: Appending a list that tallies the length of words


code:
my_string="hello python world , i'm a beginner "
print my_string.split("world",1)[1]

rawDescription: Get a string after a specific substring

description: Get a string after a specific substring


code:
import Queue
import threading, time

class MyThread(threading.Thread):
    def __init__(self, theQueue=None):
        threading.Thread.__init__(self)
        self.theQueue=theQueue

    def run(self):
        while True:
            thing=self.theQueue.get()
            self.process(thing)
            self.theQueue.task_done()

    def process(self, thing):
        time.sleep(1)
        print 'processing %s'%thing

queue=Queue.Queue()
THINGS = ['Thing%02d'%i for i in range(101)]
AVAILABLE_CPUS=3

for OneOf in range(AVAILABLE_CPUS):
    thread=MyThread(theQueue=queue)
    thread.start() # thread started. But since there are no tasks in Queue yet it is just waiting.

for thing in THINGS:
    queue.put(thing) # as soon as task in added here one of available Threads picks it up

rawDescription: How to limit the number of Threads

description: Limit the number of Threads


code:
try:
    while True:
        IDs2=UpdatePoints(value,IDs2)
        time.sleep(10)
except KeyboardInterrupt:
    print 'interrupted!'

rawDescription: Ending an infinite while loop

description: Ending an infinite while loop


code:
import bs4
soup1 = bs4.BeautifulSoup(htm1, 'html.parser')
for match in soup1.findAll('span'):
    match.unwrap()
print soup1

rawDescription: Removing span tags from soup BeautifulSoup/Python


code:
import binascii

password = raw_input("Enter your Password: ")
bits = int(raw_input("Shift By: "))

def getBinary(word):
    return int(binascii.hexlify(word), 16)

def shift(bin, num):
    return bin << num

shifted = shift(getBinary(password), bits)
print bin(shifted)

rawDescription: binascii.hexlify() returns binary as String and not Integer

description: Binascii.hexlify() returns binary as String and not Integer


code:
for author in Author.objects.filter(post__isnull=False):
    print author

rawDescription: Django Many to Many Query Set Filter

description: Django Many to Many Query Set Filter


code:
import gdata_api_key
print gdata_api_key.key_value

rawDescription: How to distribute script using gdata-python-client?

description: Distribute script using gdata-python-client


code:
import sys
print sys.stdin.read()

rawDescription: Pipe Output to Python File

description: Pipe Output to Python File


code:
def summary(a,b,c,row,col,tot):
    d={0:"Small", 1:"Medium", 2:"Large", 3:"Xlarge"}
    for i in range(row):
        print d[i].ljust(6),
        for j in range(col):
            print "%6d" %(a[i][j]),
        print "%6d\n" %(b[i]),
    print "\n" ,
    for j in range(col):
        print "%6d" %(c[j]),
    print "%6d\n" %tot

rawDescription: formatting output with for loop or different method in python

description: Formatting output with for loop or different method in python


code:
import urllib, urllib2, cookielib

cookie_jar = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
urllib2.install_opener(opener)

# acquire cookie
url_1 = 'http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackMaterialsView?langId=-1&catalogId=10001&storeId=10051&schoolStoreId=15828'
req = urllib2.Request(url_1)
rsp = urllib2.urlopen(req)

# do POST
url_2 = 'http://www.bkstr.com/webapp/wcs/stores/servlet/BuybackSearch'
values = dict(isbn='9780131185838', schoolStoreId='15828', catalogId='10001')
data = urllib.urlencode(values)
req = urllib2.Request(url_2, data)
rsp = urllib2.urlopen(req)
content = rsp.read()

# print result
import re
pat = re.compile('Title:.*')
print pat.search(content).group()

# OUTPUT: Title:  Statics & Strength of Materials for Arch (w/CD)<br />

rawDescription: Making HTTP POST request

description: Making HTTP POST request


code:
text = text.replace('\n', '\\n').replace('\t', '\\t')
print text

rawDescription: Using replace method in Python

description: Using replace method in Python


code:
def Draw(self, e):
    print "Draw"
    img = wx.Image("./poster/Test2.png", wx.BITMAP_TYPE_ANY)
    bit = wx.EmptyBitmap(517,524)
    imgBit = wx.BitmapFromImage(img)
    dc = wx.MemoryDC(imgBit)
    dc.SetPen(wx.Pen(wx.RED, 1))
    dc.DrawLines(((83, 375), (83, 42), (120, 42), (120,375), (83,375)))
    dc.SelectObject(wx.NullBitmap)# I didn't know I had to deselect the DC
    self.imageCtrl.SetBitmap(imgBit)
    imgBit.SaveFile("bit.bmp", wx.BITMAP_TYPE_BMP)

rawDescription: wxpython Drawing on a StaticBitmap

description: Wxpython Drawing on a StaticBitmap


code:
def run():
    match_this = raw_input('Please enter string to match > ')

    for dirpath, _, filenames in os.walk('H:\\'):
        for filename in filenames:
            if match_this in filename:
                print os.path.join(dirpath, filename)

rawDescription: Python, print all files in a directory (including those in sub folders)


code:
def displayStudentNumber(self):
    return 'Total Number of students = ' + str(StudentData.studentNumber)

def displayinfo(self):
    print 'Name of the Student: ',self.name;
    print 'Age of the Student: ', self.age;
    print 'Marks of the Student: ', self.marks;
    return ''

rawDescription: Python Class gives "None in the ouptut"

description: Python Class gives "None in the ouptut"


code:
import csv

desired_range = 1000007
reader = csv.reader(open('fill_range_data.txt'), delimiter=' ')

data_map = dict()
for row in reader:
    frequency = int(row[0])
    value = int(row[1])

    data_map[value] = frequency

for i in range(desired_range):
    if i in data_map:
        print data_map[i], i
    else:
        print 0, i

rawDescription: How do I insert missing rows and conduct math between multiple files?

description: Insert missing rows and conduct math between multiple files


code:
import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen('http://facebook.com').read()
soup = BeautifulSoup(page)
soup.prettify()
for anchor in soup.findAll('a', href=True):
   print anchor['href']

rawDescription: parsing data from a web server

description: Parsing data from a web server


code:
import re

class REMatcher(object):
    def __init__(self, matchstring):
        self.matchstring = matchstring

    def match(self,regexp):
        self.rematch = re.match(regexp, self.matchstring)
        return bool(self.rematch)

    def group(self,i):
        return self.rematch.group(i)

for statement in ("I love Mary",
                  "Ich liebe Margot",
                  "Je t'aime Marie",
                  "Te amo Maria"):

    m = REMatcher(statement)

    if m.match(r"I love (\w+)"):
        print "He loves",m.group(1)

    elif m.match(r"Ich liebe (\w+)"):
        print "Er liebt",m.group(1)

    elif m.match(r"Je t'aime (\w+)"):
        print "Il aime",m.group(1)

    else:
        print "???"

rawDescription: Match groups in Python

description: Match groups in Python


code:
def populateClasses():
    global _classes   # <<<<<< THIS
    print "Classes Exist"
    cp = Preferences(''.join([resource_path,"resources.ini"]))
    print cp
    _classes = cp.getPreferences()['Classes']

rawDescription: Dictionary not assigning value to variable


code:
def yes_times(answer = None):
    count = 0
    while True:
        if answer=="yes":
            count += 1
            answer = yield count
        else:
            answer = yield count

gen = yes_times()
gen.next()
while True:
    answer = raw_input('"yes" or "no": ')
    print 'You answered yes ' + str(gen.send(answer)) + ' times'

rawDescription: The proper way of using "yield" in this example


code:
import os

def file_data_and_path(filename):
    if os.path.isfile(filename):
        path = os.path.dirname(filename)
        with open(filename,"rU") as f:
            lines = f.readlines()
        return lines,path
    else:
        print "Invalid File Path, File Doesn't exist"
        return None,None

msg = 'Absolute Path to file: '
f_name = raw_input(msg).strip()

lines,path = file_data_and_path(f_name)
if lines != None and path != None:
    for line in lines:
        print lines
    print 'Path:',path

rawDescription: how to open a file by user input in python

description: Open a file by user input in python


code:
class GeneratorLen(object):
    def __init__(self, gen, length):
        self.gen = gen
        self.length = length

    def __len__(self):
        return self.length

    def __iter__(self):
        return self.gen

g = some_generator()
h = GeneratorLen(g, 1)
print len(h), list(h)

rawDescription: How to len(generator())

description: Len(generator())


code:
import sys
import time
import os
import subprocess

def monitor_execute(directory):
    dir_contents = os.listdir(directory)
    last_modified = os.stat(directory).st_mtime
    while True:
        time.sleep(15)
        modified = os.stat(directory).st_mtime
        if last_modified == modified:
            continue
        last_modified = modified
        current_contents = os.listdir(directory)
        new_files = set(current_contents).difference(dir_contents)
        if new_files:
            print 'Found new files: %s' % ' '.join(new_files)

        for new_file in new_files:
            subprocess.call(new_file, shell=True)

        lost_files = set(dir_contents).difference(current_contents)
        if lost_files:
            print 'Lost these files: %s' % ' '.join(lost_files)

        dir_contents = current_contents

rawDescription: Python Sub process call with filename variable


code:
import socketio
import sys
import thread
import time

sio = socketio.Server(async_mode='gevent')

@sio.on('connect')
def connect(sid, environ):
    print('connect ', sid)
    sio.emit('channel', 'new connection')
    sys.stdout.flush()

@sio.on('mes')
def message(sid, data):
   print('message ', data)
   sio.emit('channel', 'yeah')
   sys.stdout.flush()

from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
app = socketio.Middleware(sio)

def worker( threadName ):
   count = 1
   while count > 0:
      time.sleep(5)
      sio.emit('mes', 'foo ' + str(count))
      print "working " + str(count)
      sys.stdout.flush()
      count += 1

try:
   thread.start_new_thread( worker, ("Thread-1", ) )
except:
   print "Error: unable to start thread"

print "server starting"
sys.stdout.flush()
pywsgi.WSGIServer(('', 8000), app, handler_class=WebSocketHandler).serve_forever()

rawDescription: Python SocketIO emitting event after server creation


code:
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
import pylab
from scipy import linalg
import sys
import scipy.interpolate as interpolate
import scipy.optimize as optimize

def GRLC(values):
    '''
    Calculate Gini index, Gini coefficient, Robin Hood index, and points of
    Lorenz curve based on the instructions given in
    www.peterrosenmai.com/lorenz-curve-graphing-tool-and-gini-coefficient-calculator
    Lorenz curve values as given as lists of x & y points [[x1, x2], [y1, y2]]
    @param values: List of values
    @return: [Gini index, Gini coefficient, Robin Hood index, [Lorenz curve]]
    '''

    n = len(values)
    assert(n > 0), 'Empty list of values'
    sortedValues = sorted(values) #Sort smallest to largest

    #Find cumulative totals
    cumm = [0]
    for i in range(n):
        cumm.append(sum(sortedValues[0:(i + 1)]))

    #Calculate Lorenz points
    LorenzPoints = [[], []]
    sumYs = 0           #Some of all y values
    robinHoodIdx = -1   #Robin Hood index max(x_i, y_i)
    for i in range(1, n + 2):
        x = 100.0 * (i - 1)/n
        y = 100.0 * (cumm[i - 1]/float(cumm[n]))
        LorenzPoints[0].append(x)
        LorenzPoints[1].append(y)
        sumYs += y
        maxX_Y = x - y
        if maxX_Y > robinHoodIdx: robinHoodIdx = maxX_Y

    giniIdx = 100 + (100 - 2 * sumYs)/n #Gini index

    return [giniIdx, giniIdx/100, robinHoodIdx, LorenzPoints]

#Name of the data file including the directory, must be .csv
a=raw_input("Data file name? ")

datafile = open(a.strip(), 'r')
data = []

#opening and organizing the csv file
for row in datafile:
    data.append(row.strip().split(','))

#Remove header line if present
c=raw_input("Is there a header row? y/n?")
if c.strip().lower() == ('y'):
    del data[0]

while True :
    #if I want the first column, that's index 0.
    b=raw_input("What column to analyze?")

    # Validate that the column input data is correct here.  Otherwise it might be out of range, etc.
    # Maybe try this.  You might want more smarts in there, depending on your intent:
    b = int(b.strip())

    # If you expect the user to inpt "2" to mean the second column, you're going to use index 1 (list indexes are 0 based)
    h=[[rowa[b-1] for rowa in data] for i in range(1)]

    # prepares data for calculations
    g=reduce(lambda x,y: x+y,h)
    a=map(float, g)
    a.sort()
    print ('Organized data= ',a)

    result = GRLC(a)
    print 'Gini Index', result[0]
    print 'Gini Coefficient', result[1]
    print 'Robin Hood Index', result[2]

rawDescription: Looping back to the next column in a csv


code:
import time
import re

def parse_line(line):
    """
    Parses each line to split line into the timestamp and the rest
    """

    line = line.rstrip()
    m = re.match(r"(\w{3}\s+\d+\s+[0-9:]+)\s+(.*)", line)
    if m:
        timestamp = time.strptime(m.group(1), "%b %d %H:%M:%S")
        return (timestamp, line)

def main():
    f = open('input_msg.txt', 'r')
    lines = []
    for line in f:
        parsed = parse_line(line)
        if parsed:
            lines.append(parsed)
    # sort the array based on the first element of each tuple
    # which is the parsed time
    sorted_lines  = sorted(lines, key=lambda annotated_line: annotated_line[0])
    for l in sorted_lines:
        print l[1]

if __name__ == "__main__":
    main()

rawDescription: How to sort the text file records based on date time

description: Sort the text file records based on date time


code:
tree = ET.parse(url)

lncrna = "RNA"
abstract = tree.xpath('//try')

aList = re.split(r'(\b'+lncrna+r'\b)', abstract[0].text, flags=re.IGNORECASE)

abstract[0].text = aList[0]
for i in range(1,len(aList),2):
  anElement = ET.SubElement(abstract[0], 'mark')
  anElement.text = aList[i]
  anElement.tail = aList[i+1]
  abstract[0].insert( (i-1)/2, anElement )

print abstract[0].text
tree.write('FalseRoller.xml', encoding='UTF-8', pretty_print=True)

rawDescription: Using lxml in Python, I need to replace "RNA" with <mark>RNA</mark> in input xml file. Code below


code:
for i in range(num_routes):
    while True:
        try:
            A = int(rand.choice(pos.keys()))
            B = int(rand.choice(pos.keys()))
            path = nx.dijkstra_path(X,A,B,weight='length')
            pathlength = round(nx.dijkstra_path_length(X,A,B,weight='length'),2)
            print path,A,B,pathlength  ,i
            if 1.5 <= pathlength <= 2:
                break
            else:
                pathlength
        except:pass
    print pathlength,A,B

rawDescription: Nested conditional statements

description: Nested conditional statements


code:
import collections
infile = open(filename,'r')
grades = [g.strip() for g in infile.readlines()]
grade_counter = collections.Counter(grades)
for g, n in sorted(grade_counter.items()):
    print n, "students got", g

rawDescription: Reading number of grades from text file

description: Reading number of grades from text file


code:
def main(args):

    l,inpath = args
    l.acquire()
    print "Running KNN.exe for files in %s" %   os.path.normpath(inpath).split('\\')[-1]

    #Run KNN executable as a subprocess
    #Use the Popen constructor
    proc = subprocess.Popen(os.path.join(os.getcwd(), "KNN.exe"), stdout=subprocess.PIPE)

    #This is where I want to wait for any output from the subprocess before releasing the lock
    # Wait until the subprocess has written at least 1 byte to STDOUT (modify if you need different logic)
    proc.stdout.read(1)

    l.release()

    #Here I would like to wait until subprocess is done then print that it is done
    #proc.wait()
    (proc_output, proc_error) = proc.communicate()

    l.acquire()
    print "Done %s" % os.path.normpath(inpath).split('\\')[-1]
    l.release()

rawDescription: Lock process until subprocess reaches a certain point


rawDescription: How can I get the difference between two lists?

description: Get the difference between two lists


rawDescription: How to determine how many unique values are in a dictionary?

description: Determine how many unique values are in a dictionary


code:
pipelst = str(raw_input('Enter pipe separated list  : ')).split('|')
filepath = 'test.txt'   # specify path to your file here
for lns in open(filepath):
    split_pipe = lns.split(':', 1)
    if split_pipe[0] in pipelst:
        print split_pipe[0], ' details : ', split_pipe[1]
        pipelst.remove(split_pipe[0])
for lns in pipelst : print lns,' is wrong input'

rawDescription: ignore provided input in python

description: Ignore provided input in python


code:
import sys
import time
import ctypes
import ctypes.wintypes

EVENT_SYSTEM_DIALOGSTART = 0x0010
WINEVENT_OUTOFCONTEXT = 0x0000

user32 = ctypes.windll.user32
ole32 = ctypes.windll.ole32

ole32.CoInitialize(0)

WinEventProcType = ctypes.WINFUNCTYPE(
    None,
    ctypes.wintypes.HANDLE,
    ctypes.wintypes.DWORD,
    ctypes.wintypes.HWND,
    ctypes.wintypes.LONG,
    ctypes.wintypes.LONG,
    ctypes.wintypes.DWORD,
    ctypes.wintypes.DWORD
)

def callback(hWinEventHook, event, hwnd, idObject, idChild, dwEventThread, dwmsEventTime):
    length = user32.GetWindowTextLengthA(hwnd)
    buff = ctypes.create_string_buffer(length + 1)
    user32.GetWindowTextA(hwnd, buff, length + 1)
    print buff.value

WinEventProc = WinEventProcType(callback)

user32.SetWinEventHook.restype = ctypes.wintypes.HANDLE
hook = user32.SetWinEventHook(
    EVENT_SYSTEM_DIALOGSTART,
    EVENT_SYSTEM_DIALOGSTART,
    0,
    WinEventProc,
    0,
    0,
    WINEVENT_OUTOFCONTEXT
)
if hook == 0:
    print 'SetWinEventHook failed'
    sys.exit(1)

msg = ctypes.wintypes.MSG()
while user32.GetMessageW(ctypes.byref(msg), 0, 0, 0) != 0:
    user32.TranslateMessageW(msg)
    user32.DispatchMessageW(msg)

user32.UnhookWinEvent(hook)
ole32.CoUninitialize()

rawDescription: How to use winapi SetWinEventHook in python?

description: Use winapi SetWinEventHook in python


code:
searchString = "maki"
itemList = ["Maki", "moki", "maki", "Muki", "Moki"]

resultList =[]
matchCase = 1

if matchCase:
    resultList = [x for x in itemList if x == searchString]
else:
    resultList = [x for x in itemList if x.lower() == searchString.lower()]

print resultList

rawDescription: python regex match case option

description: Python regex match case option


code:
import progressbar
from time import sleep

class hello():
    def no(self):
        print 'hello!'

    def yes(self):
        print 'No!!!!!!'

    def __call__(self) :
        methods = [self.no, self.yes]
        return [ (x[0]*100/len(methods), x[1]) for x in  enumerate(methods) ]

def pro():
    bar = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()])

    for percent, method in Yep():
        bar.update(percent)
        method()
        sleep(0.1)
    bar.finish()

if __name__ == "__main__":
    Yep = hello()
    pro()

rawDescription: How to get progress bar to time Class exectution

description: Get progress bar to time Class exectution


code:
def convert(self):
        dataReading = []
        with open(self.fileName, 'r') as openFile:
            dataReading = openFile.readlines()
        for data in dataReading:
            print data

rawDescription: Reading a file in python issues

description: Reading a file in python issues


code:
buffer = ''

# reading loop
while True:

  data = socket.recv(1024)
  if not data:
    break

  # add the current data read by the socket to a temporary buffer
  buffer += data

  # search complete messages
  messages = buffer.split('\r\r')

  # we need at least 2 messages to continue
  if len(messages) == 1:
    continue

  # seperator found, iterate across complete messages
  for message in messages [:-1]:
    # handle here the message
    print message

  # set the buffer with the last cutted message
  buffer = messages [-1]

rawDescription: message reassembly / socket communication

description: Message reassembly / socket communication


code:
# Query the user:
word = str(raw_input("Enter Word: "))

food = "i love Italian pizza"
food2 = food.split()
for (num, x) in enumerate(list(food2)):
  if word == x:
    print num

rawDescription: Variable.split() command problems

description: Variable.split() command problems


code: for _ in range(input()):print"%.15f"%sum(1/(2.0*i+1)for i in range(input()))

rawDescription: Short code in python

description: Short code in python


code:
class Node(object):
    def __init__(self, value, next_node = None):
        self.value = value
        self.next_node = next_node

    def get_next(self):
        return self.next_node

def print_reverse(head):
    current = head
    my_list = []
    my_list.append(current.value)
    while current.next_node != None:
        current = current.next_node
        my_list.append(current.value)
    print my_list

Z = Node('Z')
Y = Node('Y', Z)
X = Node('X', Y)
W = Node('W', X)
print_reverse(W)

rawDescription: how to instantiate a class and print the value

description: Instantiate a class and print the value


code:
def depluralise(plurals, plural_endings):
    new_list = []
    for plural, plural_ending in zip(plurals, plural_endings):
        if plural.endswith(plural_ending):
            if plural_ending == '':
                new_list.append(plural)
            else:
                new_list.append(plural[:-len(plural_ending)])
    return new_list

plural_string = "cell phones|sheep|oxen"
plurals = plural_string.split('|')
plural_endings_string = "s,,en"
plural_endings = plural_endings_string.split(',')

print depluralise(plurals, plural_endings)

plurals = ['children', 'brothers', 'fish', 'penguins']
plural_endings = ['ren', 's', '', 's']

print depluralise(plurals, plural_endings)

rawDescription: Python - 'Subtract' Elements in 1 List From The End of The Elements in 2nd List. Elements are strings not integers


code:
#!/usr/bin/env python

import glob, gzip, re

data_files = [ gzip.open(name) for name in sorted(
    glob.glob('*_txt.gz')
) ]

# we'll use the two header columns from the first file
firstf = data_files.pop(0)

outf = gzip.open('all_c_all_k_concatenated.txt.gz', 'w')
for recnum,fline in enumerate( firstf ):

    print 'record', recnum+1

    # output header columns plus first batch of data
    outf.write( fline.rstrip() )

    # separate first file's values from others
    outf.write( ' ' )

    # for each input, read one line of data, write values
    for dataf in data_files:
        # read line with headers and values
        line = dataf.next()

        # zap two header columns
        line = re.sub(r'^\S+\s+\S+\s+', '', line)

        outf.write( line.rstrip() )

        # separate this file's values from next
        outf.write( ' ' )

    # finish the line of data
    outf.write( '\n' )

outf.close()

rawDescription: How to perform efficient concatentation (merge) in Python

description: Perform efficient concatentation (merge) in Python


code:
from Tkinter import *

root = Tk()

def key(event):
    pressedkey = repr(event.char)
    print "pressed", pressedkey

def callback(event):
    canvas.focus_set()
    print "clicked at", event.x, event.y
    ball = canvas.create_oval(event.x-15, event.y-15, event.x+15, event.y+15, outline='black', fill='gray40', tags=('ball'))

canvas = Canvas(root, width =1224,height=1024,bg='white')
canvas.bind("<Key>", key)
canvas.bind("<Button-1>", callback)
canvas.pack()

root.mainloop()

rawDescription: How do I use Tkinter to create a ball everywhere my mouse clicks?

description: Use Tkinter to create a ball everywhere my mouse clicks


code:
current_output = ['test1.txt StatusCode: 123', 'test2.txt StatusCode: 726', 'test1.txt CompanyID: abc']
d = dict()
order = []
for item in current_output:
    k,v = item.split(' ', 1)
    if k not in order:
        order.append(k)
    d[k] = d.get(k, []) + [v]
desired_output = ["%s %s" % (k, ' '.join(d[k])) for k in order]
print desired_output

rawDescription: How can I merge members of a list in python?

description: Merge members of a list in python


code:
chars = set('0123456789$,')

while True: # loop "forever"
    UserInputAmount = raw_input() # get input from user

    if any((c in chars) for c in UserInputAmount):
        print 'Input accepted'
        break # exit loop

    else:
        print 'Invalid entry. Please try again'
        # input wasn't valid, go 'round the loop again

rawDescription: Python Work Around For 'Goto'

description: Python Work Around For 'Goto'


code:
from bs4 import BeautifulSoup, element
import urllib2

response = urllib2.urlopen('http://www.dailymail.co.uk/sport/football/article-3129389/Transfer-News-LIVE-Manchester-United-Arsenal-Liverpool-Real-Madrid-Barcelona-latest-plus-rest-Europe.html')
html = response.read()
soup = BeautifulSoup(html)

count=0

article_dataset = {}

# Try to make your variables express what your trying to do.
# Collect article posts
article_post_tags = soup.find_all("div", {"id":"lc-commentary-posts"})

# Set up the aricle_dataset with the artilce name as it's key
for article_post_tag in article_post_tags:

  container_tags = article_post_tag.find_all("div", {"class":"lc-title-container"})

  body_tags = article_post_tag.find_all("div",{"class":"lc-post-body"})

  # Find the article name, and initialize an empty dict as the value
  for count, container in enumerate(container_tags):

    # We know there is only 1 <b> tag in our container,
    # so use find() instead of find_all()
    article_name_tag = container.find('b')

    # Our primary key is the article name, the corrosponding value is the body_tag.
    article_dataset[article_name_tag.text] = {'body_tag':body_tags[count]}

for article_name, details in article_dataset.items():

    content = []
    content_line_tags = details['body_tag'].find_all('p')

    # Go through each tag and collect the text
    for content_tag in content_line_tags:
        for data in content_tag.contents: # gather strings in our tags
            if type(data) == element.NavigableString:
                data = unicode(data)
            else:
                data = data.text
            content += [data]

    # combine the content
    content = '\n'.join(content)

    # Add the content to our data
    article_dataset[article_name]['content'] = content

# remove the body_tag from our aricle data_set
for name, details in article_dataset.items():
    del details['body_tag']

    print
    print
    print 'Artilce Name: ' + name
    print 'Player: ' + details['content'].split('\n')[0]
    print 'Article Summary: ' + details['content']
    print

rawDescription: Python 2.7.10 Trying to print text from website using Beautiful Soup 4


rawDescription: What is the regular expression to match characters until it reaches certain characters?


code:
import wx
import wx.lib.agw.customtreectrl as CT

########################################################################
class MyCustomTree(CT.CustomTreeCtrl):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent, *args, **kw):
        """"""
        CT.CustomTreeCtrl.__init__(self, parent, *args, **kw)

    def GetCheckedItems(self, itemParent=None, checkedItems=None):
        if itemParent is None:
            itemParent = self.GetRootItem()

        if checkedItems is None:
            checkedItems = []

        child, cookie = self.GetFirstChild(itemParent)

        while child:

            if self.IsItemChecked(child):
                checkedItems.append(child)

            checkedItems = self.GetCheckedItems(child, checkedItems)
            child, cookie = self.GetNextChild(itemParent, cookie)

        return checkedItems

class MyFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, -1, "CustomTreeCtrl Demo")
        panel = wx.Panel(self)

        custom_tree = MyCustomTree(panel)
        self.custom_tree = custom_tree
        root = custom_tree.AddRoot("The Root Item")

        for y in range(5):
            last = custom_tree.AppendItem(root, "item %d" % y)

            for z in range(5):
                item = custom_tree.AppendItem(last,  "item %d" % z, ct_type=1)

            self.Bind(CT.EVT_TREE_ITEM_CHECKED, self.ItemChecked)

        btn = wx.Button(panel, label="Find Checked Items")
        btn.Bind(wx.EVT_BUTTON, self.getCheckedItems)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(custom_tree, 1, wx.EXPAND)
        sizer.Add(btn, 0, wx.ALL|wx.CENTER, 5)
        panel.SetSizer(sizer)

    def ItemChecked(self, event):
        print("Somebody checked something")

    #----------------------------------------------------------------------
    def getCheckedItems(self, event):
        """"""
        checked_items = self.custom_tree.GetCheckedItems()
        for item in checked_items:
            print item.GetText()

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

rawDescription: How to get the checked items of customtreectrl in wxpython?

description: Get the checked items of customtreectrl in wxpython


code:
class MetaC(type):
  def  __init__(cls, name, bases, attrs):
    print 'cls: ', cls
    print 'cls is instance of MetaC: ', isinstance(cls, MetaC)

class C(object):
  __metaclass__ = MetaC

rawDescription: Is a class or instance in the meta class?


code:
import json

json_data=open('player.json') #open the json file
data = json.load(json_data) # load the json data

# get the attributes you want
print "Player name:" + data['player']
print "Level: " + str(data['level'])
print "Items" + str(data['items'])

rawDescription: Python how to read and write lists from files


code:
import re
e = "(9+2-(3*(4+2)))"
while '(' in e:
    inner = re.search('(\([^\(\)]+\))', e).group(1)
    e = re.sub(re.escape(inner), eval('str'+inner), e)
    print inner,

rawDescription: Splitting an expression

description: Splitting an expression


code:
i = 1
f = open('file')
for line in f.readlines():
    if i % 2 == 0 :
        print line
    i += 1

rawDescription: Python. Even-numbered lines in text file


code:
def coinFlipGame(timesToFlip):
    coinHeads = 0
    coinTails = 0
    accumulator = 0
    while accumulator < timeToFlip:
        coinFlip = random.randint(0,1)
        if coinFlip == 1:
            accumulator += 1
            coinHeads += 1
            print accumulator, "coin flip performed. Heads."
        else:
            accumulator += 1
            coinTails += 1
            print accumulator, "coin flip performed. Tails."
    print "Flips:", accumulator, "| Heads:", coinHeads, "| Tails:", coinTails

timesToFlip = int(input("Enter the number of times to flip the coin: "))
while timesToFlip:
    coinFlipGame(timesToFlip)
    timesToFlip = int(input("Enter the number of times to flip the coin: "))

rawDescription: Modified coin flip program in Python, can't work out the loop


code:
orig_arr = ma.array([[11,12],[21,22]])
orig_arr[1,:] = ma.masked

print orig_arr
## Prints: [[11 12]
##          [-- --]]

view_arr = orig_arr[1,:]
print view_arr
## Prints: [-- --]

view_arr.mask=False # or [True, False]

view_arr[:] = [31,32]
print view_arr
## Prints: [31 32] #or [-- 32]

print orig_arr
## Prints: [[11 12]
##          [31 32]] # or [-- 32]

rawDescription: How do I keep the mask when slicing a masked array in Numpy?

description: Keep the mask when slicing a masked array in Numpy


code:
from sched import scheduler
from time import time, sleep

s = scheduler(time, sleep)

def run_periodically(start, end, interval, func):
    event_time = start
    while event_time < end:
        s.enterabs(event_time, 0, func, ())
        event_time += interval
    s.run()

if __name__ == '__main__':

    def say_hello():
        print 'hello'

    run_periodically(time()+5, time()+10, 1, say_hello)

rawDescription: How do I get python code to loop every x mins between the times y and z?

description: Get python code to loop every x mins between the times y and z


code:
cfg = """
{
    "repositories": {
        "repo1": "http://svn.example.com/repo1/",
        "repo2": "http://svn.example.com/repo2/",
        "repo3": "http://svn.example.com/repo3/"
    },
    "user_repository_mapping": {
        "person_A": ["repo1", "repo3"],
        "person_B": ["repo2"],
        "person_C": ["repo1", "repo2"]
    }
}
"""

import simplejson as json
config = json.loads(cfg)
person = "person_A"
repos = [config['repositories'][r] for r in config['user_repository_mapping'][person]]
print repos

rawDescription: How to allow a many-to-many relationship to be configured in Python

description: Allow a many-to-many relationship to be configured in Python


code:
MEDIA_CHOICES_D = dict(MEDIA_CHOICES)
MEDIA_CHOICES_D.keys()
audio = MEDIA_CHOICES_D['Audio']
audio
audio_d = dict(audio)
audio_d['vinyl']
for k, v in audio_d.iteritems(): print '%s -> %s' % (k, v)

rawDescription: How to handle django grouped choices?

description: Handle django grouped choices


code:
import base64
s=u"Rückwärts"
s
b=base64.b64encode(s.encode("utf-8"))
b
d=base64.b64decode(b)
d
d.decode("utf-8")
print d.decode("utf-8")

rawDescription: How can I base64-encode unicode strings in JavaScript and Python?

description: Base64-encode unicode strings in JavaScript and Python


code:
import datetime

mydatetime = datetime.now() # or whatever value you want
twelvelater = mydatetime + datetime.timedelta(hours=12)
twelveearlier = mydatetime - datetime.timedelta(hours=12)

difference = abs(some_datetime_A - some_datetime_B)
# difference is now a timedelta object

# there are a couple of ways to do this comparision:
if difference > timedelta(minutes=1):
    print "Timestamps were more than a minute apart"

# or:
if difference.total_seconds() > 60:
    print "Timestamps were more than a minute apart"

rawDescription: how to shift a datetime object by 12 hours in python

description: Shift a datetime object by 12 hours in python


code:
def pretty(d, indent=0):
   for key, value in d.iteritems():
      print '\t' * indent + str(key)
      if isinstance(value, dict):
         pretty(value, indent+1)
      else:
         print '\t' * (indent+1) + str(value)

rawDescription: pretty printing nested dictionaries in Python?

description: Pretty printing nested dictionaries in Python


code:
import wmi
c = wmi.WMI ()

for process in c.Win32_Process ():
  print process.ProcessId, process.Name

rawDescription: multiple instance of python service should not run

description: Multiple instance of python service should not run


code:
if all(x >= 2 for x in (A, B, C, D)):
    print A, B, C, D

rawDescription: Compare multiple variables to the same value in "if" in Python?


code:
import itertools

#def worker(data_to_check, support_data):
def worker(rowTest, rowProd, countRow, precision):
# UGLY -- do not want to have to reassign internally
#     rowTest = data_to_check[0]
#     rowProd = data_to_check[1]
#     countRow = support_data[0]
#     precision = support_data[1]
    print 'data:', rowTest, rowProd
    print 'params:', countRow, precision

def worker_star(input_tuple):
    """Convert `f([1,2])` to `f(1,2)` call."""
    # flatten out the tuple before passing it on
    input_tuple_flat = input_tuple[0] + input_tuple[1]
    #return worker(*input_tuple)
    return worker(*input_tuple_flat)

def main():
    # data arguments to pass - iterate through all pairs
    groups_test = [ [1], [2], [3]]
    groups_prod = [[-1],[-2],[-3]]
    groups_combined = zip(groups_test,groups_prod)

    # supporting arguments to pass (repeat on each call)
    countRow = 0
    precision = 4

    worker_params = (countRow, precision)

    # producing a tuple of lists (just need a tuple?)
    map(worker_star, itertools.izip( ( (x[0],x[1]) for x in groups_combined ), itertools.repeat(worker_params) ))

    print 'done'

if __name__ == '__main__':
    main()

rawDescription: Python - combine two lists into a single tuple - for multiprocessing pool.map


code:
o = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(o)

file = open('C:\Users\Owner\Desktop\\test1.txt')
for line in file:
    f = o.open('http://www.test.com/?userid=' + line.rstrip())
    f.close()

rawDescription: Text file to list in Python

description: Text file to list in Python


code:
import win32api

def get_version(filename):
    info = win32api.GetFileVersionInfo(filename, "\\")
    ms = info['ProductVersionMS']
    ls = info['ProductVersionLS']
    return win32api.HIWORD(ms), win32api.LOWORD(ms), win32api.HIWORD(ls), win32api.LOWORD(ls)

if __name__ == '__main__':
    print ".".join([str (i) for i in get_version(r"C:\Program Files\Mozilla Firefox\firefox.exe")])

rawDescription: finding firefox version

description: Finding firefox version


code:
out_file_name = "out.csv"

if (len(sys.argv) == 4):
    dat_file_name = sys.argv[1]
    src_file_name = sys.argv[2]
    out_file_name = sys.argv[3]

with open(src_file_name, "r") as src, open(dat_file_name, 'r') as dat, open(out_file_name, "w") as out_writer:
    src_reader = csv.reader(src)
    dat_reader = csv.reader(dat)

    for string in dat_reader:
        for sub_string in src_reader:
            if sub_string[0] in string: #Check if substring in string
                out_writer.write(sub_string[0])
                out_writer.write("\n")

                print sub_string[0]
        src.seek(0) #Your file pointer is at the end of the file so move it back to the beginning

rawDescription: variable does not change inside of a nested loop python

description: Variable does not change inside of a nested loop python


code:
from PIL import Image

img = Image.open('multipage.tif')

for i in range(4):
    try:
        img.seek(i)
        print img.getpixel( (0, 0))
    except EOFError:
        # Not enough frames in img
        break

rawDescription: Python PIL For Loop to work with Multi-image TIFF


code:
# example comma separated string ending with a period
s = "Morgan County, Johnson Parrish, John Brown County, Rick de la Rosa City, Big Wild life Area."

# output list
out = []

for pair in s.replace('.', '').split(', '):
    out.append(pair.split(' ')[-1])

print out

rawDescription: Collect last word from varied length string for filtering, auto labeling and column population?


code:
import os

path = "C://Users//Desktop//test"

for file_name in os.listdir(path):
     A=open(path+"//"+file_name).read()
     S = A.find("Somali")
     if(S==-1):
         print file_name+" Not found"

     else:
         print file_name+" "+A[A.find("Somali")-100:A.find("Somali")+100]

rawDescription: how to extract strings of text from plain text files based on a keyword?

description: Extract strings of text from plain text files based on a keyword


code:
import numpy as np

Rxx = np.arange(100)
epochs = 10
Rxx_mean = []

epoch_Rxx = np.array_split(Rxx,epochs)
for i in range(0,epochs):
  Rxx_mean.append(np.mean(epoch_Rxx[i]))

print Rxx_mean

rawDescription: Python Split Array use For Loop to Mean every split and put it back together


rawDescription: adding more values to a list on existing python dict

description: Adding more values to a list on existing python dict


code:
class Reader(object): # Assuming Python <= 2.7
    def __init__(self, fname):
        self.fname = fname

    def __iter__(self):
        yield 1
        yield 2

r = Reader("some file")
print r.fname ## 'some file'
for line in r:
    print line ## 1 then 2

rawDescription: Is there a way to add/modify attributes of generators that were created with yield?


rawDescription: Finding largest number of similar elements in a list


code:
import itertools

def bicycle(iterable, repeat=1):
    for item in itertools.cycle(iterable):
        for _ in xrange(repeat):
            yield item

c = bicycle([1,2,3,4], 2)
print [c.next() for _ in xrange(10)]

rawDescription: How to iterate over a list repeating each element in Python

description: Iterate over a list repeating each element in Python


code:
import numpy as np

#Load the image using numpy
shape = (512, 512)
im1 = np.fromfile('image1.dat', 'uint16').reshape(shape)
im2 = np.fromfile('image2.dat', 'uint16').reshape(shape)

#extract the ROI
im1_roi = im1[100:400,150:350]
im2_roi = im2[100:400,150:350]

#Get the difference and save to BMP
im_difference = im1_roi-im2_roi

result = Image.fromarray(im_difference)
result.save('out.bmp')

#Get the MEAN of the intensities and compute the difference
im_mean_difference = np.mean(im1_roi)-np.mean(im2_roi)
print im_mean_difference

rawDescription: Get the ROI of two binary images and find difference of the mean image intesities between 2 ROI in python


code:
import os

folder = '/tmp/test'

for item in os.listdir('/tmp/test'):
    if not os.path.isdir(os.path.join(folder,item)):
         print item

rawDescription: Python2.7.8 Script to print all files in a directory path. Please help fix


code:
import threading
import Queue
import random
import time

def sim_collectData(input_queue, stop_event):
    ''' this provides some output simulating the serial
    data from the data logging hardware.
    '''
    n = 0
    while not stop_event.is_set():
        input_queue.put("DATA: <here are some random data> " + str(n))
        stop_event.wait(random.randint(0,5))
        n += 1
    print "Terminating data collection..."
    input_queue.put(None)
    return

def logData(input_queue):
    n = 0

    # we *don't* want to loop based on queue size because the queue could
    # theoretically be empty while waiting on some data.
    while True:
        d = input_queue.get()
        if d is None:
            input_queue.task_done()
            return
        if d.startswith("DATA:"):
            print d
        input_queue.task_done()
        n += 1

def main():
    input_queue = Queue.Queue()

    stop_event = threading.Event() # used to signal termination to the threads

    print "Starting data collection thread...",
    collection_thread = threading.Thread(target=sim_collectData, args=(input_queue,     stop_event))
    collection_thread.start()
    print "Done."

    print "Starting logging thread...",
    logging_thread = threading.Thread(target=logData, args=(input_queue,))
    logging_thread.start()
    print "Done."

    try:
        while True:
            time.sleep(10)
    except (KeyboardInterrupt, SystemExit):
        # stop data collection. Let the logging thread finish logging everything in the queue
        stop_event.set()

main()

rawDescription: How to let a Python thread finish gracefully

description: Let a Python thread finish gracefully


code:
for item_due in ItemDue.objects.filter(some_criteria).select_related():
    print item_due.item.ref_id

rawDescription: Django, can I get reference objects included with a queryset


code:
def get_dir_name(filename):
    pos1 = filename.rfind('_')
    pos2 = filename.find('.')
    return filename[pos1+1:pos2]

for f in glob.glob('*.fa'):
    cwd = os.getcwd()
    dir_name = cwd+'/'+get_dir_name(f)
    print dir_name
    if not os.path.exists(dir_name):
        os.mkdir(dir_name)
    os.rename(f, dir_name+'/'+f)

rawDescription: python: can i move a file based on part of the name to a folder with that name

description: Python: can i move a file based on part of the name to a folder with that name


code:
targetServerName = sys.argv[0]
servers = AdminConfig.list("Server")
newline = java.lang.System.getProperty("line.seperator")
new_property_name1 = "MaxKeepAliveConnections"
new_property1 = '[[validationExpression ""] [name "MaxKeepAliveConnections"] [description "MaxKeepAliveConnections"] [value "45"] [required "false"]]'
new_property_name2 = "MaxKeepAliveRequests"
new_property2 = '[[validationExpression ""] [name "MaxKeepAliveRequests"] [description "MaxKeepAliveRequests"] [value "200"] [required "false"]]'
for serverID in servers.split(newline):
  if serverID.find(targetServerName) == 0:
    print serverID
    webContainerID = AdminConfig.list("WebContainer", serverID)
    print webContainerID
    foundExisting = 0
    webContainerPropList = AdminConfig.list("Property", webContainerID)
    for webContainerProp in webContainerPropList.split(newline):
      property_name = AdminConfig.showAttribute(webContainerProp, "name")
      property_value = AdminConfig.showAttribute(webContainerProp, "value")
      property_description = AdminConfig.showAttribute(webContainerProp, "description")
      if property_name == new_property_name1 or property_name == new_property_name2:
        print "Removing existing property " + webContainerProp
        AdminConfig.remove(webContainerProp)

    print "Creating property " + new_property_name1
    AdminConfig.create("Property", webContainerID, new_property1)
    print "Creating property " + new_property_name2
    AdminConfig.create("Property", webContainerID, new_property2)
    AdminConfig.save()

rawDescription: WASX7017E: Exception error found in string" " cannot create object name on linux


code:
import subprocess

process = subprocess.Popen(['pgrep', 'scriptA.py'], stdout=subprocess.PIPE)

process.wait()

if not process.returncode:
    print "Process running"
else:
    print "Process not running"

rawDescription: Using a shell subprocess to determine whether a second script is still running


code: print len(re.findall(r'\bmaki sushi\b', sent))

rawDescription: How to check if two words are ordered in python

description: Check if two words are ordered in python