code:
from collections import Counter
from itertools import chain
from string import punctuation

from nltk.corpus import brown, stopwords

# Let's say the training/testing data is a list of words and POS
sentences = brown.sents()[:2]

# Extract the content words as features, i.e. columns.
vocabulary = list(chain(*sentences))
stops = stopwords.words('english') + list(punctuation)
vocab_nostop = [i.lower() for i in vocabulary if i not in stops]

# Create a matrix from the sentences
matrix = [Counter([w for w in words if w in vocab_nostop]) for words in sentences]

print matrix

rawDescription: How to vectorize bigrams with the hashing-trick in scikit-learn?

description: Vectorize bigrams with the hashing-trick in scikit-learn


code:
with open('/tmp/test', 'rb') as f:
    reader = csv.DictReader(f, delimiter='\t', quoting=csv.QUOTE_NONE)
    print reader.fieldnames

rawDescription: DictReader, No quotes, tabbed file

description: DictReader, No quotes, tabbed file


code:
line = 'date time info junk1 junk2 name'
parts = line.split()
del parts[4]  # junk2
del parts[3]  # junk1
print ' '.join(parts)

rawDescription: Only writing to a file certain columns of a line (seperated by spaces)


code:
def do_something(arg):
    x=arg[:]
    x[0] = 9
    return x

y = [1,2]

print "before: ", y
print "result of do_something(): ", do_something(y)
print "after: ", y

rawDescription: Function in python changes the input variables, why is that?


code:
import xml.etree.ElementTree as ET

data = '<Sets X="s"><B s="1" e="2176" t="-2.0774E4" r="1" /><B s="2177" e="8982" t="-1.8597E4" r="1" /><B s="8983" e="10393" t="-150.22" r="1" /></Sets>'

tree = ET.fromstring(data)
for b in tree.findall('.//B'):
     print map(float, itemgetter(*'setr')(b.attrib))

rawDescription: Parsing a string for data sets

description: Parsing a string for data sets


code:
for item in json.loads(info['plan']):
    print item['Food']
    print item['Grams']
    print item['Pro']
    #etc

rawDescription: Retrive data from jquery-json to python

description: Retrive data from jquery-json to python


code:
import broken

def brokenfunc():
    print "patched"

    broken.dependency()

broken.brokenfunc = brokenfunc

rawDescription: Monkey patching a module function depending on another function inside the module


code:
for row in a:
    print row[0]

rawDescription: Python: Picking a certain element from an array


code:
import requests
from bs4 import BeautifulSoup

url = 'http://atlasgal.mpifr-bonn.mpg.de/cgi-bin/ATLASGAL_SEARCH_RESULTS.cgi?text_field_1=AGAL010.472%2B00.027&catalogue_field=Sextractor&gc_flag='
response = requests.get(url)
soup = BeautifulSoup(response.content, 'html5lib')

table = soup.find(text='Fitted Parameters for Observed Molecular Transitions').find_parent('table')
for row in table.find_all('tr'):
    print row

rawDescription: Table with missing <tr> around a row: can I parse it?


code:
extractedLines = []
extract = False
with open("./log.txt") as f:
    for line in f:
        if "Cell's that didn't clear in the past 2 days" in line:
            extract = False
        if extract:
            extractedLines.append(line)
        if "Cell's that didn't call in" in line:
            extract = True

print extractedLines

rawDescription: How to return all rows between 2 sections in a string in python 3.X?

description: Return all rows between 2 sections in a string in python 3.X


code:
def dump(self):
    print type(self).__dict__['a'].describe()

rawDescription: In Python, how can I call an instance method on a descriptor?


code:
pdd = 1   # number of node i
r = 2     # number of commodity type c
e = 1     # number of period t
dem = []

for i in range(pdd):
    dem2 = []
    for c in range(r):
        dem1 = []
        for t in range(e):
            dem0 = 1000
            dem1.append (dem0)
        dem2.append (dem1)
dem.append(dem2)

print dem

rawDescription: how i Can create this matrix with 3 for?

description: How i Can create this matrix with 3 for


code:
from collections import defaultdict
import csv
import re
import os

def main():
    result = defaultdict(int)
    regexp = re.compile('ttp_ws_sm_(\d+)_')

    source = '\\\\Isfs\\data$\\GIS Carto\TTP_Draw_Count'
    with open(os.path.join(source, 'TTP_13_08.csv'), 'r') as f:
        rows = csv.reader(f)

        for row in rows:
            match = regexp.search(row[1])
            if match:
                result[match.group(1)] += int(row[13])

    for key, value in result.iteritems():
        print "club %s %s" % (key, value)

if __name__ == '__main__':
    main()

rawDescription: Increment string(numbers) to total and print


code:
import sys, time
import zmq

port = "5556"
if len(sys.argv) > 1:
    port =  sys.argv[1]
    int(port)

# Socket to talk to server
context = zmq.Context()
socket = context.socket(zmq.SUB)

print "Collecting updates from weather server..."
socket.connect ("tcp://localhost:%s" % port)

# Subscribe to zipcode, default is NYC, 10001
topicfilter = "10001"
socket.setsockopt(zmq.SUBSCRIBE, topicfilter)

# Process 5 updates
total_value = 0
received_value_count = 0
do_receive_loop = True
while do_receive_loop:
    try:
        #process all messages waiting on subscribe socket
        while True:
            #check for a message, this will not block
            string = socket.recv(flags=zmq.NOBLOCK)

            #message received, process it
            topic, messagedata = string.split()
            total_value += int(messagedata)
            print ('{} {}'.format(topic, messagedata))

            #check if we have all the messages we want
            received_value_count += 1
            if received_value_count > 4:
                do_receive_loop = False
                break

    except zmq.Again as e:
        #No messages waiting to be processed
        pass

    #Here we can do other stuff while waiting for messages
    #contemplate answer to 'The Last Question'
    time.sleep(15)
    print "INSUFFICIENT DATA FOR MEANINGFUL ANSWER"

print('Avg data value for topic {} was {}'.format(topicfilter, (total_value/5)))

rawDescription: zero-mq: socket.recv() call is blocking

description: Zero-mq: socket.recv() call is blocking


rawDescription: why do I keep getting the same answer with this conditional, python pandas

description: Why do I keep getting the same answer with this conditional, python pandas


code:
import win32com.client
from pythoncom import PumpWaitingMessages
from time import time, strftime
import constants

class EventHandler:
    def OnProcessEvent(self, result):
        event = win32com.client.gencache.EnsureDispatch(result)
        if event.EventType == constants.SUBSCRIPTION_DATA:
            self.getData(event)
        elif event.EventType == constants.SUBSCRIPTION_STATUS:
            self.getStatus(event)
        else:
            self.getMisc(event)
    def getData(self, event):
        iterator = event.CreateMessageIterator()
        while iterator.Next():
            message = iterator.Message
            dataString = ''
            for fieldIndex, field in enumerate(constants.fields):
                if message.AsElement.HasElement(field):
                    element = message.GetElement(field)
                    if element.IsNull:
                        theValue = ''
                    else:
                        theValue = ', Value: ' + str(element.Value)
                    dataString = dataString + ', (Type: ' + element.Name + theValue + ')'
            print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + dataString
    def getMisc(self, event):
        iterator = event.CreateMessageIterator()
        while iterator.Next():
            message = iterator.Message
            print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString
    def getStatus(self, event):
        iterator = event.CreateMessageIterator()
        while iterator.Next():
            message = iterator.Message
            if message.AsElement.HasElement('reason'):
                element = message.AsElement.GetElement('reason')
                print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + ', Category: ' + element.GetElement('category').Value + ', Description: ' + element.GetElement('description').Value
            if message.AsElement.HasElement('exceptions'):
                element = message.AsElement.GetElement('exceptions')
                exceptionString = ''
                for n in range(element.NumValues):
                    exceptionInfo = element.GetValue(n)
                    fieldId = exceptionInfo.GetElement('fieldId')
                    reason = exceptionInfo.GetElement('reason')
                    exceptionString = exceptionString + ', (Field: ' + fieldId.Value + ', Category: ' + reason.GetElement('category').Value + ', Description: ' + reason.GetElement('description').Value + ') '
                print strftime('%m/%d/%y %H:%M:%S') + ', MessageType: ' + message.MessageTypeAsString + ', CorrelationId: ' + str(message.CorrelationId) + exceptionString

class bloombergSource:
    def __init__(self):
        session = win32com.client.DispatchWithEvents('blpapicom.Session' , EventHandler)
        session.Start()
        started = session.OpenService('//blp/mktdata')
        subscriptions = session.CreateSubscriptionList()
        for tickerIndex, ticker in enumerate(constants.tickers):
            if len(constants.interval) > 0:
                subscriptions.AddEx(ticker, constants.fields, constants.interval, session.CreateCorrelationId(tickerIndex))
            else:
                subscriptions.Add(ticker, constants.fields, session.CreateCorrelationId(tickerIndex))
        session.Subscribe(subscriptions)
        endTime = time() + 2
        while True:
            PumpWaitingMessages()
            if endTime < time():
                break

if __name__ == "__main__":
    aBloombergSource = bloombergSource()

rawDescription: Asynchronous data through Bloomberg's new data API (COM v3) with Python?


code:
import sys
from  itertools import izip

filehandles = [ open(fn) for fn in sys.argv[1:] ]
for i, rows in enumerate(izip(*filehandles)):
    if i<25: continue

    cols = [ map(float, row.split()) for row in rows ]
    print cols

rawDescription: Simultaneous line-by-line reading of n-number of files in python


code:
from copy import deepcopy

state=[[0, 0, 2, 2],
   [2, 2, 2, 2],
   [2, 2, 2, 2],
   [2, 2, 2, 2]]

def all_rand_tiles(state):
    states = []
    changed = []
    old_states = [None]
    while old_states != states:
        old_states = states
        new_state = deepcopy(state)
        for row in range(4):
            for tile in range(4):
                if state[row][tile] == 0:

                    if [row, tile] not in changed:
                        new_state[row][tile] = 2
                        states.append(new_state)
                        new_state = deepcopy(state)

                        new_state[row][tile] = 4
                        states.append(new_state)
                        new_state = deepcopy(state)
                        changed.append([row, tile])

    return states

print all_rand_tiles(state)

rawDescription: All possible random tiles in 2048(Stupid issue)


code:
from collections import defaultdict
tags=[
        { "id": 1, "post_id": 155, "term": 'python'},
        { "id": 2, "post_id": 155, "term": 'c'},
        { "id": 3, "post_id": 155, "term": 'php'},
        { "id": 4, "post_id": 145, "term": 'php'},
        { "id": 5, "post_id": 145, "term": 'python'},
        { "id": 7, "post_id": 145, "term": 'c'},
        { "id": 9, "post_id": 145, "term": 'java'},
        { "id": 12, "post_id": 166, "term": 'python'},
        { "id": 15, "post_id": 166, "term": 'php'}
        ]

formatted_tags = defaultdict(list)
for tag in tags:
    formatted_tags[tag["post_id"]].append(tag["term"])

print dict(formatted_tags)
intersection = set(formatted_tags[formatted_tags.keys()[0]])
for tag in formatted_tags:
    intersection = intersection & set(formatted_tags[tag])

intersection_tags = {}
intersection = list(intersection)
for tag in formatted_tags:
    intersection_tags[tag] = intersection
print intersection_tags

rawDescription: convert flat dict to nested list and dict and intersect this

description: Convert flat dict to nested list and dict and intersect this


code:
from nltk.corpus import movie_reviews
first_fileid =  movie_reviews.fileids(categories=["pos"])[0]
print first_fileid
print type(movie_reviews.words(first_fileid))
print type(movie_reviews.words())

rawDescription: NLTK bag of bigrams words function raises "Don't know how to concatenate types" error - python


code:
number = 2

var1 = 0
var2 = 1
var3 = 2

for output in (var1, var2, var3):
    print output * number

rawDescription: How do I multiply more the one variable by a number simultaneously

description: Multiply more the one variable by a number simultaneously


code:
import enchant

b = enchant.Broker()
b.set_ordering("en_US","myspell,aspell")
print b.describe()
d=b.request_dict("en_US")
print d.provider
s = '50'
print d.suggest(s)

b = enchant.Broker()
b.set_ordering("en_US","aspell,myspell")
print b.describe()
d=b.request_dict("en_US")
print d.provider
s = '50'
print d.suggest(s)

rawDescription: PyEnchant weird behavior for numbers

description: PyEnchant weird behavior for numbers


code:
def get_time_deltas(infile):
    entries = (line.split() for line in open(INFILE, "r"))
    ts = {}
    for e in entries:
        if " ".join(e[2:5]) == "OuchMsg out: [O]":
            ts[e[8]] = e[0]   # store timestamp for id
        elif " ".join(e[2:5]) == "OuchMsg in: [A]":
            in_ts, ref_id = e[0], e[7]
            out_ts = ts.pop(ref_id, None)   # get ts for this id
            # TODO: handle case where out_ts = None (no id found)
            yield (ref_id[1:-1], float(in_ts) - float(out_ts))

INFILE = 'C:/Users/kdalton/Documents/Minicomm.txt'
print list(get_time_deltas(INFILE))

rawDescription: How do I create a list of timedeltas in python?

description: Create a list of timedeltas in python


code:
n, m = 2, 4
dt1 = np.dtype([('R','u1'), ('G','u1'), ('B','u1'), ('A','u1')])
dt0 = np.dtype([('R','u1'), ('G','u1'), ('B','u1')])
X = np.arange(n*m*3,dtype='u1').reshape(n,m,3)
print repr(X)
X0 = np.zeros((n,m), dtype=dt0)
X0.data = X.data
print repr(X0)
X0.strides # (12, 3)

X1 = np.zeros((n,m), dtype=dt1)
F = np.zeros((n,m,1), dtype='u1')
X01 = np.concatenate([X, F], axis=2)
X1.data = X01.data
print repr(X1)
X1.strides # (12, 4)

rawDescription: Change stride of numpy array (altering data)


rawDescription: how to handle this string in python

description: Handle this string in python


code:
def enter(self):
    print Death.quips[randint(0, len(self.quips)-1)]
    exit(1)

rawDescription: Can somebody explain this short python method


code:
from random import randint

board = [['O' for i in range(5)] for j in range(5)]

def print_board(board):
    for row in board:
        print " ".join(row)

print "Let's play Battleship!"
print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col

# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
for turn in range(4):
    print "Turn", turn + 1# Print (turn + 1) here!
    try:
        guess_row = int(raw_input("Guess Row:"))
        guess_col = int(raw_input("Guess Col:"))
    except ValueError:
        print "Your gunners were asleep on the job!"
        if turn == 3:
            print "Game Over"
        continue
    if guess_row == ship_row and guess_col == ship_col:
        print "Congratulations! You sunk my battleship!"
        break
    else:
        if guess_row not in range(5) or guess_col not in range(5):
            print "Oops, that's not even in the ocean."
        elif(board[guess_row][guess_col] == "X"):
            print "You guessed that one already."
        else:
            print "You missed my battleship!"
            board[guess_row-1][guess_col-1] = "X"
            print_board(board)
    if turn == 3:
        print "Game Over"

rawDescription: Сodecademy 18/19 Battleship

description: Сodecademy 18/19 Battleship


code:
def kill_proc_kidnapper(self, child_pid, kidnapper_name='WerFault.exe'):
    """
    Look among all instances of 'WerFault.exe' process for an specific one
    that took control of another faulting process.
    When 'WerFault.exe' is launched it is specified the PID using -p argument:

    'C:\\Windows\\SysWOW64\\WerFault.exe -u -p 5012 -s 68'
                             |               |
                             +-> kidnapper   +-> child_pid

    Function uses `argparse` to properly decode process command line and get
    PID. If PID matches `child_pid` then we have found the correct parent
    process and can kill it.
    """
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', action='store_false', help='User name')
    parser.add_argument('-p', type=int, help='Process ID')
    parser.add_argument('-s', help='??')

    kidnapper_p = None
    child_p = None

    for proc in psutil.get_pid_list():
        if kidnapper_name in proc.name:
            args, unknown_args = parser.parse_known_args(proc.cmdline)
            print proc.name, proc.cmdline

            if args.p == child_pid:
                # We found the kidnapper, aim.
                print 'kidnapper found: {0}'.format(proc.pid)
                kidnapper_p = proc

    if psutil.pid_exists(child_pid):
        child_p = psutil.Process(child_pid)

    if kidnapper_p and child_pid:
        print 'Killing "{0}" ({1}) that kidnapped "{2}" ({3})'.format(
            kidnapper_p.name, kidnapper_p.pid, child_p.name, child_p.pid)
        self.taskkill(kidnapper_p.pid)
        return 1
    else:
        if not kidnapper_p:
            print 'Kidnapper process "{0}" not found'.format(kidnapper_name)
        if not child_p:
            print 'Child process "({0})" not found'.format(child_pid)

    return 0

rawDescription: How to launch crashing (rarely) application in subprocess

description: Launch crashing (rarely) application in subprocess


code:
import re

if any(re.search(r'\b{}\b'.format(re.escape(word)), sentence) for word in listword):
    print 'yes'

rawDescription: Finding whether a word exist in a string in python


code:
import threading
from multiprocessing.pool import ThreadPool

def test_thread(elem):
    return elem ** 2

a = [1,2,3,4,5,6,7,8]
pool = ThreadPool(2) # 2 worker threads
results = []
for x in range(8):
    print x
    results.append(pool.apply_async(test_thread, args=(a[x],)))

results = [result.get() for result in results]
# You can also replace this for loop altogether using pool.map
# and get the same result:
# results = pool.map(test_thread, range(8))
print(results)

rawDescription: python threads - always have x active threads when iterating over n tasks

description: Python threads - always have x active threads when iterating over n tasks


code:
aw, T, h2o = [float(v) for v in out.split() if not v.strip('0123456789.')]
print aw, T, h2o

rawDescription: Cut a Substring of a String which was read by serial in Python


rawDescription: Pythonic way to compare two lists and print out the differences


code:
from mako.template import Template
template = Template(filename='index.tpl')
print template.render(title='My Title', header='My Header')

rawDescription: Is there a recommended way to procedurally build up an html report


code:
def my_func(a, b='abc', c='def'):
    print a, b, c

rawDescription: Python newbie: What does this code do?

description: Python newbie: What does this code do


code:
from threading import Timer
from time import sleep

def foo():
    print "timer went off!"
t = Timer(4, foo)
t.start()
for i in range(11):
    print i
    sleep(.5)

rawDescription: Postponing functions in python

description: Postponing functions in python


code:
for r in results:
    r_idx = r[0]
    print "Prev", sentence[r_idx-1]
    print "Next", sentence[r_idx+1]

rawDescription: Searching for Unicode characters in Python


code:
import re
def get_attr(str, attr):
    m = re.search(attr + r'=(\w+)', str)
    return None if not m else m.group(1)

str = 'type=weaksubj len=1 word1=wrestle pos1=verb stemmed1=y priorpolarity=negative'

print get_attr(str, 'word1')  # wrestle
print get_attr(str, 'type')   # weaksubj
print get_attr(str, 'foo')    # None

rawDescription: Regular Expressions

description: Regular Expressions


code:
class Animal(object):
  def __init__(self, talk):
    print '__init__ Animal: ', talk

class Cat(Animal):
  def __init__(self, talk='meow'):
    print '__init__ Cat'
    super(Cat, self).__init__(talk)

if __name__ == '__main__':
  tom = Cat()

rawDescription: Python: Inheritance and default values in __init__


code:
import StringIO
import sys

def foo(inStr):
    print "hi"+inStr

def test_foo():
    capturedOutput = StringIO.StringIO()          # Create StringIO object
    sys.stdout = capturedOutput                   #  and redirect stdout.
    foo('test')                                   # Call unchanged function.
    sys.stdout = sys.__stdout__                   # Reset redirect.
    print 'Captured', capturedOutput.getvalue()   # Now works as before.

test_foo()

rawDescription: How to write a unittest for console print

description: Write a unittest for console print


code:
for section, values in result:
    print section, ':'
    for k, v in values.items():
        print '\t', k, '=', v

rawDescription: Parsing specific contents in a file

description: Parsing specific contents in a file


code:
class Person(object):
    def __init__(self, name, sex, parents=None, children=None):
        """
        Create a Person
        """
        self.name = name
        self.sex = sex    # 'M' or 'F'

        self.parents = set()
        if parents is not None:
            for p in parents:
                self.add_parent(p)

        self.children = set()
        if children is not None:
            for c in children:
                self.add_child(c)

    def add_parent(self, p):
        self.parents.add(p)
        p.children.add(self)

    def add_child(self, c):
        self.children.add(c)
        c.parents.add(self)

    def __str__(self):
        return self.name

    def __repr__(self):
        return "Person('{}', '{}')".format(self.name, self.sex)

    #
    # Immediate relationships
    #
    # Each fn returns a set of people who fulfill the stated relationship
    #

    def _parent(self):
        return self.parents

    def _sibling(self):
        return set().union(*(p.children for p in self.parents)) - set([self])

    def _child(self):
        return self.children

    def _female(self):
        if self.sex=='F':
            return set([self])
        else:
            return set()

    def _male(self):
        if self.sex=='M':
            return set([self])
        else:
            return set()

    def relation(self, *rels):
        """
        Find the set of all people who fulfill the stated relationship

        Ex:
            self.relation("parent", "siblings")     # returns all aunts and uncles of self
        """
        # start with the current person
        ps = set([self])

        for rel in rels:
            # each argument is either a function or a string
            if callable(rel):
                # run the function against all people in the current set
                #   and collect the results to a new set
                ps = set().union(*(rel(p) for p in ps))
            else:
                # recurse to evaluate the string
                do = Person._relations[rel]
                ps = set().union(*(p.relation(*do) for p in ps))

        return ps

    def print_relation(self, *rels):
        print ', '.join(str(p) for p in self.relation(*rels))

#
# Extended relationships
#
# Supplies the necessary information for Person.relation() to do its job -
# Each key refers to a recursive function tree (nodes are string values, leaves are functions)
#
# (Unfortunately this table cannot be created until the Person class is finalized)
#
Person._relations = {
    "parent":        (Person._parent,),
    "mother":        (Person._parent, Person._female),
    "father":        (Person._parent, Person._male),
    "sibling":       (Person._sibling,),
    "sister":        (Person._sibling, Person._female),
    "brother":       (Person._sibling, Person._male),
    "child":         (Person._child,),
    "daughter":      (Person._child, Person._female),
    "son":           (Person._child, Person._male),
    "grandparent":   ("parent", "parent"),
    "grandmother":   ("parent", "mother"),
    "grandfather":   ("parent", "father"),
    "aunt":          ("parent", "sister"),
    "uncle":         ("parent", "brother"),
    "cousin":        ("parent", "sibling", "child"),
    "niece":         ("sibling", "daughter"),
    "nephew":        ("sibling", "son"),
    "grandchild":    ("child", "child"),
    "grandson":      ("child", "son"),
    "granddaughter": ("child", "daughter")
}

rawDescription: How do I init a class, Class.__init__(self), from inside this recursive function?

description: Init a class, Class.__init__(self), from inside this recursive function


code:
rango = range(1,n)
for i in rango:
    for j in rango:
        print rango[j-1] * i,
    print

rawDescription: how to make a multiplication table in python

description: Make a multiplication table in python


code: print results.split(' ')[5]

rawDescription: How to match info from a string

description: Match info from a string


code:
my_list = ['a', 'b', 'c', 'd', 'e', 'f']

choices = {'remove': my_list.remove,
           'append': my_list.append}

print my_list
while True:
    try:
        choice, item = raw_input('append <x> OR remove <x>\n').split()
        choices[choice](item)
    except (KeyError, ValueError):
        print('something went wrong...')
    print my_list

rawDescription: Make a function to call while the program is running


rawDescription: Python: comparing list to a string

description: Python: comparing list to a string


code:
from bs4 import BeautifulSoup

html = """

"""

soup = BeautifulSoup(html)
div = soup.find("div", id="here")

html2 = """

           <link rel="stylesheet" type="text/css"  href="//cdn.ss  tatic.net/stackoverflow/all.css?   v=71d362e7c10c">
           """

soup1 = BeautifulSoup(html2)
value = soup1.body.extract()

div.append(value)
print div

rawDescription: How do I use BeautifulSoup to move tag contents from one soup to a template soup

description: Use BeautifulSoup to move tag contents from one soup to a template soup


code: print '\w+(query)\w+'

rawDescription: Regex search find before and after query. Python


code:
command = "cat /sys/class/net/eth1/address"
print "%s" %(getmac(command))

rawDescription: Using console commands in python

description: Using console commands in python


code:
key2values = (v for lst in my_dicts.itervalues()
                    for dct in lst
                        for k, v in dct.iteritems()
                            if 'key2' in k)
for value in key2values:
    print value

rawDescription: Operation on value of a particular key in a dictionary stored as a list in Python


code:
f()
f()

print global_list

rawDescription: is TensorSharedVariable in theano initilized twice in function?

description: Is TensorSharedVariable in theano initilized twice in function


code:
try:
    state = 0
    for line in cmLines:
        if state == 0:
            if "INFERNAL1/a" in line or "HMMER3/f" in line:
                title = line
                state = 1
        elif state == 1:
            if word2(line) in NamesList:
                output.write(title)
                output.write(line)
                state = 2
            else:
                state = 0
        elif state == 2:
            output.write(line)
            if '//' in line:
                state = 0
except Exception as e:
    print "Loop exited becuase:"
    print type(e)
    print "at " + line
finally:
    output.close()

rawDescription: python loop exception

description: Python loop exception


code:
for period, df in d.items():
    print period
    print df

rawDescription: generate multiple pandas data frames

description: Generate multiple pandas data frames


code: print 'Words in paragraph', para_type, ':', para_count

rawDescription: How to count the number of words in a paragraph and exclude some words (from file)?

description: Count the number of words in a paragraph and exclude some words (from file)


code:
ret = []                                 #return value
with open('data.txt', 'r') as f:         #open file
    curArray = []                        #start current array
    for line in f:                       #loop through the lines
        line = line.rstrip()             #get rid of \n
        if len(line) == 0:               #if its an empty line
            ret.append(curArray)         #  append curArray to ret
            curArray = []                #  reset curArray
        else:
            numbers = line.split(' ')    #split array on spaces
            curArray.append(numbers)     #append new array to the curArray
print ret

rawDescription: reading data file into multidimensional array in python

description: Reading data file into multidimensional array in python


code:
import datetime
import doctest
import os

def parseOptions():

    import optparse
    parser = optparse.OptionParser(usage= '-h')
    parser.add_option('-d', '--difference', \
                      type= 'int')
    (options, args) = parser.parse_args()
    return options
now = datetime.datetime.now()

def subtime(a,b):
    """ (datetime,int) -> datetime
    Subtract b hours from a datetime.datetime and return the new datetime object

    >>> subtime(datetime.datetime(2013,11,11,11,0),10)
    datetime.datetime(2013, 11, 11, 1, 0)

    >>> subtime(datetime.datetime(2013,11,11,11,0),24)
    datetime.datetime(2013, 11, 10, 11, 0)

    >>> subtime(datetime.datetime(2013,11,11,11,0),30)
    datetime.datetime(2013, 11, 10, 5, 0)

    >>> subtime(datetime.datetime(2013,11,11,11,0),0)
    datetime.datetime(2013, 11, 11, 11, 0)

    >>> subtime(datetime.datetime(2013,11,11,11,0),-5)
    datetime.datetime(2013, 11, 11, 16, 0)

    """
    subtract = datetime.timedelta(hours=b)
    difference = a - subtract
    return difference

if __name__== "__main__":
    doctest.testmod()

print
print 'This is the time now -', now.strftime("%I:%M:%S %p %a, %B %d %Y")
difference=subtime(now,10)
print 'This is the time minus the difference -', difference.strftime("%I:%M:%S %p %a, %B %d %Y")
print

rawDescription: Doctest with datetime

description: Doctest with datetime


code:
import sys
sys.stdout = open('file', 'w')
print 'test' # prints test to file

rawDescription: How to automatically direct print statements' outputs to a file in python?

description: Automatically direct print statements' outputs to a file in python


rawDescription: Variable always gets rounded to 2 decimal places - Python


code:
import csv
import glob
from datetime import datetime, timedelta, date

days = 2
since = datetime.combine(date.today(), datetime.min.time()) - timedelta(days = days)
required_fields = ['A', 'B', 'C', 'D']

path = "."
newdict = {}

output = {}

for filename in glob.glob(path):
    with open(filename) as csv_file:
        for row in csv.DictReader(csv_file):
            if datetime.strptime(row['Date'], '%m/%d/%Y') >= since:
                name = row['Name']

                try:
                    cur_entry = output[name]
                    entry = {field : cur_entry[field] + float(row[field]) for field in required_fields}
                except KeyError as e:
                    entry = {field : float(row[field]) for field in required_fields}
                    entry['Date'] = days

                output[name] = entry

for name, entry in output.items():
    print name, entry

rawDescription: Sum Multiple Values for Same Key in Different Dictionaries Python


code:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from numpy import arange, sin, pi
import threading

class Dummy():

    def plotme(self, iteration = 1):

        print "%ix plotting... " % iteration,
        t = arange(0.0, 2.0, 0.01)
        s = sin(2*pi*t)
        plt.plot(t, s)
        plt.xlabel('time (s)')
        plt.ylabel('voltage (mV)')
        plt.title('About as simple as it gets, folks')
        plt.savefig("19110942_%i_test.png" % iteration) # irrelevant here
        plt.clf()

    def threadme(self, iteration = 1):

        thread_plot = threading.Thread(target=self.plotme,
                                      args=(iteration,))
        thread_plot.start()
        thread_plot.join()

dummy = Dummy()
dummy.threadme(1)
dummy.threadme(2)

rawDescription: matplotlib plotting freezing in simple thread

description: Matplotlib plotting freezing in simple thread


code:
dict1 = {}
for eachKey in list(set(",".join(each.keys()) for each in result["themes"]))[0].split(","):
    dict1[eachKey] = [each[eachKey] for each in result["themes"]]
print dict1

rawDescription: Unpack dictionary that contains a list of dictionaries and insert in columns


code:
def countpos(lsts):
    return sum(1 for lst in lsts
                 for val in lst
                 if val > 0)

print countpos([[0, 0, 0, 0], [1, 0, 6, 0]])  # 2

rawDescription: how to count a list within a function

description: Count a list within a function


code:
list_patterns = [': error:', ': warning:', 'cc1plus:', 'undefine reference to']
string = 'there is an : error: and a cc1plus: in this string'
print re.findall('|'.join(list_patterns), string)

rawDescription: Python: defining a union of regular expressions


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup("Some text")
wrap(soup.a, soup.new_tag("b"))
print soup.body
# Some text

rawDescription: Add parent tags with beautiful soup

description: Add parent tags with beautiful soup


code:
def resultgiver():
    if result in [7,11]:
        print('You won! You got ' ,result,'.')

    elif result in [2, 3, 12]:
        print('You lost! You got ' ,result,'.')

    elif result in [5, 6, 8, 9, 10]:
        print('Roll again! You got ' ,result,'.')

    else:
        print "default case for result =", result

rawDescription: What is going wrong? Nothing is printing in Python


code:
AA = np.array([[1,2],[3, myVar]])
print AA

rawDescription: How to send Python script to IPython or run Python script in IPython without importing numpy

description: Send Python script to IPython or run Python script in IPython without importing numpy


rawDescription: Summing objects in recursive python function


code:
if result.orderByColumns:
    for ocol in result.orderByColumns:
        print "Order by %(order)s (%(order_dir)s)" % ocol

rawDescription: pyparsing optional subfield

description: Pyparsing optional subfield


code:
T = t[1]-t[0]
print T*np.min(np.where(envelope < limit))

rawDescription: Determining the event location on an oscillatory signal


code:
d = {"a":1}
def p(val):
  print val

def func1():
  p(d["a"])

def call_it(func):
  func()

call_it(func1)
d["a"] = 111
call_it(func1)

rawDescription: Passing objects around an event queue in Python


code:
for quote in quotes:
    print 'ticker: %s' % quote['t'], 'current price: %s' %    quote['l_cur'], 'last trade: %s' % quote['lt']
    outfile.write(''.join(['ticker: %s ' % quote['t'], 'current price: %s ' % quote['l_cur'], 'last trade: %s ' % quote['lt']]) + '\n')

rawDescription: Python - Write multiple lists to file

description: Python - Write multiple lists to file


code:
for x in sorted(d, key=lambda x:d[x][2]):
    print x

rawDescription: Iteration over python dictionary sorted by an element


code:
import requests
import lxml.html

url = 'http://pro-161-70.ib.unicamp.br/~itaraju/cgi-bin/itaraju/bioinf/pimw.cgi'
payload = {
    'arquivo': '',
    'opShowTitle': 'ON',
    'opShowSeq': 'ON',
    'opShowStat': 'ON',
    'opShowpimw': 'ON',
    'opGelVirtual': 'ON',
    'opMap': 'gel0.def',
    'opPK': 'Default',
    'tbCt': 3.55,
    'tbNt': 7,
    'tbArg': 12.01,
    'tbAsp': 4.06,
    'tbCys': 9,
    'tbGlu': 4.45,
    'tbHis': 5.985,
    'tbLys': 10.01,
    'tbTyr': 10.01,
    'tbSeq': '''>gi|532319|pir|TVFV2E|TVFV2E envelope protein
ELRLRYCAPAGFALLKCNDADYDGFKTNCSNVSVVH
CTNLMNTTVTTGLLLNGSYSENRTQIWQKHRTSNDS
ALILLNKHYNLTVTCKRPGNKTVLPVTIMAGLVFHSQ
KYNLRLRQAWCHFPSNWKGAWKEVKEEIVNLPKER
YRGTNDPKRIFFQRQWGDPETANLWFNCHGEFFYCK
MDWFLNYLNNLTVDADHNECKNTSGTKSGNKRAPG
PCVQRTYVACHIRSVIIWLETISKKTYAPPREGHLECT
STVTGMTVELNYIPKNRTNVTLSPQIESIWAAELDRY
KLVEITPIGFAPTEVRRYTGGHERQKRVPFVXXXXXX
XXXXXXXXXXXXXXXXVQSQHLLAGILQQQKNL
LAAVEAQQQMLKLTIWGVK''',
}

# send POST
r = requests.post(url, data=payload)

#print r.text

# convert HTML string into HTML tree
html = lxml.html.fromstring(r.text)

# get all images
imgs = html.cssselect('img')

# get second image
if len(imgs) > 1:
    url = 'http://pro-161-70.ib.unicamp.br/~itaraju/cgi-bin/itaraju/bioinf/' + imgs[1].attrib['src'].strip()

    print "Downloading ...",  url

    with open('output.gif', 'wb') as handle:
        r = requests.get(url, stream=True)

        if not r.ok:
            # Something went wrong
            pass

        for block in r.iter_content(1024):
            if not block:
                break

            handle.write(block)
            print '.',

        print

# get data
for tr in html.cssselect('tr'):
    for td in tr.cssselect('tr'):
        print td.text_content().strip().replace('\n', ' | '),
    print

rawDescription: Trying to post to a form that uses frames and retrieve the data using python


code:
for row in S.iterrows():
    print pdist([row[1]['x'], row[1]['center']], 'euclidean')

rawDescription: Measure distance between data set of 5D

description: Measure distance between data set of 5D


code:
total = -10; print "Total:" + ["", "+"][total > 0] + str(total)
total = 0; print "Total:" + ["", "+"][total > 0] + str(total)
total = 10; print "Total:" + ["", "+"][total > 0] + str(total)

rawDescription: How to print the sign + of a digit for positive numbers in Python

description: Print the sign + of a digit for positive numbers in Python


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

Base = declarative_base()

class Transaction(Base):
    __tablename__ = 'transaction'

    id = Column(Integer, primary_key=True)
    discriminator = Column('origin', String(50))
    __mapper_args__ = {'polymorphic_on': discriminator}
    amount = Column(Integer)

class StudentTransaction(Transaction):
    __mapper_args__ = {'polymorphic_identity': 'student'}

    student_id = Column(Integer, ForeignKey('student.id'))
    student = relationship(
        'Student',
        primaryjoin='and_(StudentTransaction.student_id==Student.id)'
    )

class Student(Base):
    __tablename__ = 'student'

    id = Column(Integer, primary_key=True)

    transactions = relationship(
        'StudentTransaction',
        primaryjoin='and_(Student.id==StudentTransaction.student_id)',
        back_populates='student'
    )

    @hybrid_property
    def balance(self):
        return sum([transaction.amount for transaction in self.transactions])

    @balance.expression
    def balance(cls):
        return select([
                    func.sum(StudentTransaction.amount)
                ]).where(StudentTransaction.student_id==cls.id).as_scalar()

e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)
s = Session(e)

s.add_all([
    Student(transactions=[StudentTransaction(amount=50), StudentTransaction(amount=180)]),
    Student(transactions=[StudentTransaction(amount=600), StudentTransaction(amount=180)]),
    Student(transactions=[StudentTransaction(amount=25), StudentTransaction(amount=400)]),
])

print s.query(Student).filter(Student.balance > 400).all()

rawDescription: SQLAlchemy Relationships with Single Table Inheritance


code:
def fn(*args):
    # args is now a tuple of the non-keyworded arguments
    print args

fn(1, 2, 3, 4, 5)

rawDescription: Passing functions which have multiple return values as arguments in Python


code:
import re
elem = browser.find_elements_by_tag_name("option")
for ele in elem:
  m = re.search(r'(Red,.+wooly,.+small,.+UK)', ele.get_attribute("innerHTML"))
  if m:
    print m.group(1)

rawDescription: Python selenium and fuzzy matching

description: Python selenium and fuzzy matching


code:
Example
from xml.etree import ElementTree as et

data = '''\
<?xml version="1.0" encoding="utf-8"?>
<HeaderLookup>
    <Header>
        <Reserved>2</Reserved>
        <CPU>1</CPU>
        <Flag>1</Flag>
        <VQI>12</VQI>
        <Group_ID>16</Group_ID>
        <DI>2</DI>
        <DE>1</DE>
        <ACOSS>5</ACOSS>
        <RGH>8</RGH>
    </Header>
</HeaderLookup>
'''

tree = et.fromstring(data)
for n in tree.find('Header'):
    print n.tag,'=',n.text

rawDescription: How do I get Python XML to stop having wasted Child Nodes

description: Get Python XML to stop having wasted Child Nodes


code:
matches = driver.find_elements_by_xpath("//td[@class='match-centre']/a")
print [match.get_attribute("href") for match in matches]

rawDescription: Parsing HTML Content using BeautifulSoup & Selenium


code:
with open('test.txt') as x:
    for line in x:
        print line.rstrip()

rawDescription: Reading from a text file with python - first line being missed


code:
v = curs.var(cx_Oracle.FIXED_CHAR, 15)
v.setvalue(0, '1')
print v
result = curs.execute("select name from people where sin = :sin", sin=v)
for r in result: print r

rawDescription: cx_Oracle returns empty query when using bindings

description: Cx_Oracle returns empty query when using bindings


code:
import inspect

def proxy(bridge, target):
    def proxyfy(cls):
        for bname, func in inspect.getmembers(target, predicate=inspect.ismethod):
            fname = func.__name__
            if fname in cls.__dict__:
                print 'ignoring %s.%s' % (cls, fname)
                continue
            print 'adding %s.%s' % (cls, fname)
            def proxy_func(self, bname=bname, *args, **kwargs):
                print 'calling %s.%s.%s' % (cls, bridge, bname)
                bridge_member = getattr(self, bridge)
                return getattr(bridge_member, bname)(*args, **kwargs)
            setattr(cls, fname, proxy_func)
        return cls
    return proxyfy

def proxy(bridge):
    def proxyfy(cls):
        def __getattr__(self, attr):
            target = getattr(self, bridge)
            if attr.startswith('__') and not attr.endswith('__'):
                # unmangle
                attr = '_{}{}'.format(type(target).__name__, attr)
            return getattr(target, attr)
        setattr(cls, '__getattr__', __getattr__)
        return cls
    return proxyfy

class Base(object):
    def __init__(self, i):
        self._i = i

    def __bar(self):
        print 0

    def foo(self):
        print self._i

    def foo2(self):
        print 2 * self._i

# @proxy('_proxy', Base)
@proxy('_proxy')
class Delegate(object):
    def __init__(self, base):
        self._proxy = base

    def foo2(self):
        print 4 * self._proxy._i

d = Delegate(Base(1))
d.__bar() # d._proxy.__bar()
d.foo()   # d._proxy.foo()
d.foo2()  # d.foo2()

rawDescription: Using closure to decorate a class's methods


rawDescription: python list modification to list of lists

description: Python list modification to list of lists


code:
genA = (a for a in [2,3,5,7,11,13,17,19])
genB = (b for b in [2,3,5,7,11,13,17,19])
for pair in gen_weird_sequence(genA, genB): print pair

rawDescription: Generate ordered tuples of infinite sequences


code:
rs = db.query('select max(id) as max_value from tablename')
print rs[0].max_value

rawDescription: How can I get int result from web python sql query?

description: Get int result from web python sql query


code:
import calendar
print calendar.monthrange(2012, 2)[1]

rawDescription: Python function that takes an input and spits out a month and how many days it has


rawDescription: Parse the executing file path

description: Parse the executing file path


code:
import re
from collections import OrderedDict

ch = '>AB0012xxxxaaaaaaaaaaaa'\
     '>CD00192aaabbbllyybbbaaayyyuubbbaaaggggaaabbb'\
     '>ZP0199000012mmmm3m4mmmxxxxaaabbbaaaaaaaaaaaaa'\
     '>QD1547zzzzzzzzjjjiii'\
     '>SE457895ffffaaabbbbbbbgjhgjgjhgjhgbbbbbaaa'

print ch,'\n'

regx = re.compile('((?<=>)(.{7})[^>]*(?:aaabbb|bbbaaa)[^>]*?)(?=>|\Z)')
rag = re.compile('aaabbb|bbbaaa')

dic = OrderedDict()

# Finding the result
for mat in regx.finditer(ch):
    chunk,head = mat.groups()
    headstart = mat.start()
    dic[(headstart,head)] = [(headstart+six.start(),six.start(),six.group())
                             for six in rag.finditer(chunk)]

# Diplaying the result
for (headstart,head),li in dic.iteritems():
    print '{:>10} {}'.format(headstart,head)
    for x in li:
        print '{0[0]:>10} {0[1]:>6} {0[2]}'.format(x)

rawDescription: Regular expression help

description: Regular expression help


code:
def check(self):
    self.original = t.get_gravity()
    print "Original gravity from the function:", self.original
    my_gravity = 9.888
    t.set_gravity(my_gravity)

rawDescription: Accessing the variable from another function of the same class


code:
class myProtocolFactory(ReconnectingClientFactory):
    protocol = MyProtocol

    def buildProtocol(self, address):
        print address
        return self.protocol()

rawDescription: Twisted client for a send only protocol that is tolerant of disconnects


code: print '&\x8cj\xbay\x93\xb9'

rawDescription: Accessing individual elements of an encrypted list in python


code:
try:
     # global webversion we don't need it
     webversion = urllib2.urlopen("http://www." + server + "/version").read().rstrip()
     if webversion > version:
          update_files(webversion, version)
     elif version >= webversion:
          print "[SYSTEM] You have the latest version: v." + version
#And be careful to add except, with try!
except:
    print("Error!")

rawDescription: Pyton take variables into next function

description: Pyton take variables into next function


code:
a=1.2
b='hi'
print "The number is %d and the text is %s" %(a, b)

rawDescription: printing variables in python using % and variable name

description: Printing variables in python using % and variable name


code:
i = struct.unpack('>l', s)[0]
print hex(i)

rawDescription: Python: obtain & manipulate (as integers) bit patterns of floats


code:
from StringIO import StringIO
data = StringIO()
pygame.image.save(surf, x)
print x.getvalue()

rawDescription: How to save pygame Surface as an image to memory (and not to disk)

description: Save pygame Surface as an image to memory (and not to disk)


code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys

class MyTableModel(QAbstractTableModel):
    def __init__(self, parent=None, *args):
        QAbstractTableModel.__init__(self, parent, *args)
        self.items = [i for i in range(10000)]

    def rowCount(self, parent):
        return len(self.items)
    def columnCount(self, parent):
        return 1

    def data(self, index, role):
        if not index.isValid():
            return QVariant()
        elif role != Qt.DisplayRole:
            return QVariant()

        row=index.row()
        column=index.column()
        if row<len(self.items):
            return QVariant(self.items[row])
        else:
            return QVariant()

class Proxy01(QSortFilterProxyModel):
    def __init__(self):
        super(Proxy01, self).__init__()
    def filterAcceptsRow(self, row, parent):
        sourceModel=self.sourceModel()
        index=sourceModel.index(row, 0, parent)
        name=sourceModel.data(index, Qt.DisplayRole).toString()

        if name and not int(name)%10:
            return True
        return False

class Proxy02(QSortFilterProxyModel):
    def __init__(self):
        super(Proxy02, self).__init__()
        self.keyword=None

    def setKeyword(self, arg):
        if arg: self.keyword=str(arg)
        self.reset()

    def filterAcceptsRow(self, row, parent):
        sourceModel=self.sourceModel().sourceModel()
        index=sourceModel.index(row, 0, parent)
        name=sourceModel.data(index, Qt.DisplayRole).toString()

        if self.keyword and name and not self.keyword.lower() in str(name).lower():
            return False
        return True

class MyWindow(QWidget):
    def __init__(self, *args):
        QWidget.__init__(self, *args)

        self.tablemodel=MyTableModel(self)

        self.proxy1=Proxy01()
        self.proxy1.setSourceModel(self.tablemodel)

        self.proxy2=Proxy02()
        self.proxy2.setSourceModel(self.proxy1)

        tableviewA=QTableView()
        tableviewA.setModel(self.proxy2)

        searchEdit=QLineEdit()
        searchEdit.textChanged.connect(self.proxy2.setKeyword)

        layout = QVBoxLayout(self)
        layout.addWidget(tableviewA)
        layout.addWidget(searchEdit)
        self.setLayout(layout)

    def test(self, arg):
        print arg

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = MyWindow()
    w.show()
    sys.exit(app.exec_())

rawDescription: Chained QSortFilterProxyModels

description: Chained QSortFilterProxyModels


code:
import requests
image_url = "http://recipes.thetasteofaussie.netdna-cdn.com/wp-content/uploads/2015/07/Leek-and-Sweet-Potato-Gratin.jpg"
headers = {
    'User-agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36',
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Encoding' : 'gzip,deflate,sdch',
    'Referer' : 'http://aussietaste.recipes/vegetables/leek-vegetables/leek-and-sweet-potato-gratin/'
}
r = requests.get(image_url, headers=headers)
print r

rawDescription: Image url does not return an image. Using Python requests


code:
import wx
import time

class SettingsFrame(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, None, wx.ID_ANY, size=(100, 200))
        self.parent = parent
        self.CenterOnParent()
        self.SetBackgroundColour('#e4e4e4')

        self.radio1 = wx.RadioButton(self, label="1 sec", pos=(40, 45))
        self.radio1.Bind(wx.EVT_RADIOBUTTON, self.SetLab1)

        self.radio2 = wx.RadioButton(self, label="5 sec", pos=(40, 65))
        self.radio2.Bind(wx.EVT_RADIOBUTTON, self.SetLab2)

        self.radio3 = wx.RadioButton(self, label="10 sec", pos=(40, 85))
        self.radio3.Bind(wx.EVT_RADIOBUTTON, self.SetLab3)

        extBtn = wx.Button(self, label="Exit", pos=(20, 110))
        extBtn.Bind(wx.EVT_BUTTON, self.extFrame)

    def SetLab1(self, event):
        self.parent.change_timer(1000)

    def SetLab2(self, event):
        self.parent.change_timer(5000)

    def SetLab3(self, event):
        self.parent.change_timer(10000)

    def extFrame(self, event):
        self.Close()

class MainPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent=parent)
        self.frame = parent
        self.CenterOnParent()

        setBtn = wx.Button(self, label="Set", pos=(45, 10))
        setBtn.Bind(wx.EVT_BUTTON, self.setFrame)

        self.redraw_timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.on_redraw_timer, self.redraw_timer)
        self.redraw_timer.Start(milliseconds=1000)

    def setFrame(self, event):
        SettingsFrame(self).Show()

    def on_redraw_timer(self, event):
        print "Test: " + time.ctime()

    def change_timer(self, value):
        print 'Changing timer to:', value
        self.redraw_timer.Start(value)

class MainFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, size=(200, 200))
        panel = MainPanel(self)
        self.CenterOnParent()

if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    frame.Show()
    app.MainLoop()

rawDescription: wx.lib.pubsub: How to change the value in a timer

description: Wx.lib.pubsub: How to change the value in a timer


code:
if my_func(x) == some_value:
    # do anything with the value returned by my_func, saved in my_func.last
    # such as
    print my_func.last
    return my_func.last

rawDescription: How to avoid defining a variable to hold a function result which might be needed only once

description: Avoid defining a variable to hold a function result which might be needed only once


rawDescription: I am trying to print some list containing '\t' and '\n' . But as python is not printing it because it is thinking it as a special character


code:
expr = Literal("A").setParseAction(replaceWith("Z")) + "B"
print expr.parseString("A B").asList()

rawDescription: change string during pyparsing

description: Change string during pyparsing


code:
from dateutil.relativedelta import relativedelta
from dateutil.rrule import rrule, WEEKLY, MO, SU
from datetime import datetime, timedelta

def four_weeks(year, week):
    end = datetime(year, 1, 1) + relativedelta(weeks=week-1, weekday=SU)
    start = end - relativedelta(weeks=4, weekday=MO)
    mint, maxt = datetime.min.time(), datetime.max.time()
    for dt in rrule(WEEKLY, start, count=4):
        yield dt.combine(dt, mint), dt.combine(dt + timedelta(days=6), maxt)

for start, end in four_weeks(2013, 44):
    print start, '->', end

rawDescription: countdown 4 weeks (week by week) back with python/django

description: Countdown 4 weeks (week by week) back with python/django


code:
import itertools

k = [[1, 2], [4], [5, 6, 2], [1, 2], [3], [4]]

def doset(k, map=map, list=list, set=set, tuple=tuple):
  return map(list, set(map(tuple, k)))

def dosort(k, sorted=sorted, xrange=xrange, len=len):
  ks = sorted(k)
  return [ks[i] for i in xrange(len(ks)) if i == 0 or ks[i] != ks[i-1]]

def dogroupby(k, sorted=sorted, groupby=itertools.groupby, list=list):
  ks = sorted(k)
  return [i for i, _ in itertools.groupby(ks)]

def donewk(k):
  newk = []
  for i in k:
    if i not in newk:
      newk.append(i)
  return newk

# sanity check that all functions compute the same result and don't alter k
if __name__ == '__main__':
  savek = list(k)
  for f in doset, dosort, dogroupby, donewk:
    resk = f(k)
    assert k == savek
    print '%10s %s' % (f.__name__, sorted(resk))

rawDescription: Python: removing duplicates from a list of lists


code:
from functools import wraps

class FakeModule(object):
    def __init__(self):
        self.module = __import__("module_to_fake")

    @staticmethod
    def __testWrapper(fn):
        @wraps(fn)
        def wrapped(*args):
            print "%s called with args %s" % (fn.__name__, args)
            result = fn(*args)
            print "    Result was %s" % (result,)
            return result
        return wrapped

    def __getattr__(self, name):
        try:
            result = getattr(module, name)
        except AttributeError:
            print "tried to get %s, which does not exist" % name
            result = None

        if hasattr(result, "__call__"):
            result = self.__testWrapper(result)

        return result

rawDescription: Fake out module including attributes

description: Fake out module including attributes


code:
import datetime
s = "31/12/9999"
date = datetime.datetime.strptime(s, '%d/%m/%Y')
print date.strftime('%Y/%m/%d')

rawDescription: Invert the order of a string, while preserving the original contents of the string


code:
import re

regexp = re.compile(r'Max Tsai-Wu.*?([0-9.-]+)')
with open('input.txt') as f:
    for line in f:
        match = regexp.match(line)
        if match:
            print match.group(1)

rawDescription: Python: Finding values after searching for a string in a text files


code:
import binascii
import itertools

iconfile = 'stackoverflow.ico'
STR_LENGTH = 60
VARIABLE = 'iconhexdata ='
INDENT = ' ' * (len(VARIABLE)+1)

def grouper(n, iterable):
    "s -> (s0,s1,...sn-1), (sn,sn+1,...s2n-1), (s2n,s2n+1,...s3n-1), ..."
    return itertools.izip_longest(*[iter(iterable)]*n, fillvalue='')

with open(iconfile, 'rb') as imgfile:
    imgdata = imgfile.read()
    hexstr = binascii.b2a_hex(imgdata)

hexlines = (''.join(group) for group in grouper(STR_LENGTH, hexstr))

print VARIABLE,
print (' \\\n' + INDENT).join((repr(line) for line in hexlines))

rawDescription: Python Tkinter use string for icon bitmap


code:
xml_lang = qname('xml', 'lang')

def set_xml_lang(root, defaultlang=''):
    xml_lang = qname('xml', 'lang')
    for item in root:
        try:
            lang = item.attrib[xml_lang]
        except KeyError, err:
            item.set(xml_lang, defaultlang)
            lang = defaultlang
        set_xml_lang(item, lang)

set_xml_lang(root)

namespaces = {'xml':'http://www.w3.org/XML/1998/namespace'}
# Every element in root now has an xml:lang attribute
# so XPath is easy now:
alts_with_no_lang = root.findall('alt[@{{{xml}}}lang=""]'.format(**namespaces))

rawDescription: How do I find an xml node that does not have an attribute

description: Find an xml node that does not have an attribute


code: [[v for i, v in g] for k, g in itertools.groupby(enumerate(date_list), key=lambda (i, x): i-x.day)]

rawDescription: Python splitting a datetime list based on missing days


code:
import optparse, sys
parser = optparse.OptionParser(usage='python %prog -t -b -q',
                           prog=sys.argv[0],
                                                      )
parser.add_option('-t','--tt', action="store_true", help="Blah",dest="t")
parser.add_option('-b','--bb', action="store_true", help="Blah",dest="b")
parser.add_option('-q','--qq', action="store_true", help="Blah",dest="q")
options, args = parser.parse_args()

print options

rawDescription: Python OptParse combine multiple options


code:
# Testing (change the constructor for timedelta to test other cases)
firstDelta = datetime.timedelta(seconds=-1,microseconds=999999, days=-1)
print "--------"
print firstDelta
firstDeltaStr = strfdelta(firstDelta)
print "--------"
print firstDeltaStr;
secondDelta = deltafstr(firstDeltaStr)
print "--------"
print secondDelta
secondDeltaStr = strfdelta(secondDelta)
print "--------"
print secondDelta
print "--------"

rawDescription: Python timedelta object - strfdelta and deltafstr functions for conversion of timedelta -> string -> timedelta


code:
def largest():
    f = pickAFile()
    sound = makeSound(f)
    print max(getSampleValueAt(sound, i) for i in range(1, getLength(sound)))

rawDescription: Max() function using python from loop

description: Max() function using python from loop


code:
for root, dirs, files in os.walk(search_folder):
    for f in sorted(files, key=lambda x: tuple(reversed(os.path.splitext(x)))):
        pathname = os.path.join(root, f)
        print pathname
        print os.path.getsize(pathname)

rawDescription: python sort on extension / Name of the file

description: Python sort on extension / Name of the file


code:
size = raw_input("File size in KB: ")
speed = raw_input("Speed in KB/sec: ")
est = float(size) / float(speed)
print "It will take %f seconds." % est

rawDescription: Data and time conversion - PyMathematics


code:
from bs4 import BeautifulSoup

data = """

Like this

Hello, world

"""

soup = BeautifulSoup(data)
for strong in soup.find_all('strong'):
    if len(strong.parent) == 1:
        strong.name = 'h1'
print soup

rawDescription: Replace <strong> tag with h2 tag

description: Replace <strong> tag with h2 tag


code:
if (int(one[1]) == solution) and (int(two[1]) == solution):
    print "Hello, world"

rawDescription: Quick question regarding format of if-elif statements


code:
import re

someList = ['python', 'ppython', 'ython', 'cython', '.python', '.ythop', 'zython', 'cpython', 'www.python.org', 'xyzthon', 'perl', 'javap', 'c++']

pattern = re.compile('p')
result = []
for word in someList:
    if not pattern.search(word):
        result.append(word)
print result

rawDescription: negating with re.search (find strings that don't contain a specific character)

description: Negating with re.search (find strings that don't contain a specific character)


code:
exec SP_TEST('hello',1,2,3)
exec SP_TEST('hi',2,3,NULL)

rawDescription: iterate over function arguments and retain sort order in python

description: Iterate over function arguments and retain sort order in python


code:
tree = etree.ElementTree(root)
# this will print XPath of all
# elements in 'root'
for e in root.iter():
    print tree.getpath(e)

rawDescription: XPath for sub-element's text value in lxml


code:
import Foo
global total_count # Adding this line made it work.
total_count = 0

def delegate(index):
    global total_count # You need to keep this line, too.
    total_count += 3
    return True

unrelated_count = Foo.FooIt(Foo.Del(delegate))

print total_count # prints 6

rawDescription: Externally scoped variables in IronPython delegates


code:
def count():
    # ... create data variable
    mydata = "Database version : %s " % data
    # print data in console
    print mydata
    # return the datato caller (and then to user...)
    return mydata

rawDescription: connecting with database and showing result on localhost

description: Connecting with database and showing result on localhost


code:
from datetime import datetime, timedelta
s = '2013-08-11 09:48:49'
mytime = datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
mytime += timedelta(hours=6)
print mytime.strftime("%Y.%m.%d %H:%M:%S")

rawDescription: Python datetime add

description: Python datetime add


code:
import time
from datetime import datetime

interval = 3  # nr of seconds
events = {
    'Game Night': '14:00 2013-06-23',
    '3CB vs ST3 Match': '18:45 2013-07-02',
    'Website Maintainance': '13:00 2013-07-16',
}

def myAlertCheck(events):
    for title, event_date in events.iteritems():
        ed = datetime.strptime(event_date, '%H:%M %Y-%m-%d')
        delta_s = (datetime.now() - ed).seconds
        if delta_s < (15 * 60):
            print 'within 15 minutes %s starts' % title
            return True

while True:
    stop_looping = myAlertCheck(events)
    if stop_looping:
        break
    time.sleep(interval)

rawDescription: Python - Do (something) when event is near


code:
def is_function(rel):
    return len(set(rel)) == len(set(x for x, y in rel))

print is_function(['ab', 'cd', 'xd']) # yes
print is_function(['ab', 'cd', 'ad']) # no

rawDescription: Find equivalent words in a list through arbitrary mapping


code:
x = int(str(9663676416),16)
print x
print hex(x)

rawDescription: How to convince python that an int type is actually a hex type?

description: Convince python that an int type is actually a hex type


code:
variables = {}
for name, colour, shape in Applist:
    variables[name] = {"name": name, "colour": colour, "shape": shape}

print "Apple shape: " + variables["Apple"]["shape"]

rawDescription: Python List as variable name

description: Python List as variable name


code:
t = ['is', 'are', 'was', 'the', 'he', 'she', 'fox', 'jumped']
s = "He was walking down the road."
new = []
for word in phrase.split():
    if word.lower() in filters:
            new.append(word)
    else:
            new.extend(word)
    new.append(' ')

print new[:-1] # We slice the last element because it is ' '.

rawDescription: Filtering through a list of Words (Python)


code:
#!/usr/bin/python

def square(z):
    return z * z

def doMath(x, y):
    return square(x + y)

print doMath(5,4)

rawDescription: Python: Calling Methods from a Method

description: Python: Calling Methods from a Method


code:
d = {}
for i in 'a=b,a=c,a=d,b=e'.split(","):
    k,v = i.split("=")
    d.setdefault(k,[]).append(v)
print d

rawDescription: create a dict of lists from a string

description: Create a dict of lists from a string


code:
import ConfigParser

class Test:
  def __init__(self):
      self.post = TestPost(5)
  def getPost(self):
      config = ConfigParser.ConfigParser()
      config.read('/path/to/test.ini')
      newvar = config.get('head', 'var')
      print eval(newvar)

class TestPost:
  def __init__(self, id):
      self.id = id

test = Test()
test.getPost()   # prints 5

rawDescription: Inplace substitution from ConfigParser

description: Inplace substitution from ConfigParser


code:
from lxml import etree
import requests

xmlDict = {}

r = requests.get("http://www.site.co.uk/sitemap.xml")
root = etree.fromstring(r.content)
print "The number of sitemap tags are {0}".format(len(root))
for sitemap in root:
    children = sitemap.getchildren()
    xmlDict[children[0].text] = children[1].text
print xmlDict

rawDescription: Parse XML Sitemap with Python

description: Parse XML Sitemap with Python


code: print r, g, b

rawDescription: Python: How to convert a rgb or hex value to single color values


code:
import datetime

dict_list = [
    {'date': datetime.datetime(2016, 1, 31, 0, 0), 'title': 'Entry'},
    {'date': datetime.datetime(2016, 1, 11, 0, 0), 'title': 'Something'},
    {'date': datetime.datetime(2016, 1, 01, 0, 0), 'title': 'Entry'}
]

dict_keys = set(map(lambda x: x["title"], dict_list))

earliest_entries = {k:min(x["date"] for x in dict_list if x["title"] == k) for k in dict_keys}

rawDescription: Get only first duplicates in list of dicts with python


code:
myPerms = sorted( getPermutations("ABC") )
for p in myPerms: print p

rawDescription: how to print sorted permutation of a string with recursion in python

description: Print sorted permutation of a string with recursion in python


code:
df
print df.to_string()

rawDescription: Disabling DataFrame dimensions printing

description: Disabling DataFrame dimensions printing


code:
from BeautifulSoup import BeautifulStoneSoup
import urllib2
import sys

url = sys.argv[1]
with  open("dirlist.txt",'r') as f:
    for dir in f:
        uri = url + "/" + dir.rstrip()
        try:
            response = urllib2.urlopen(uri)
            if response.getcode() == 200:
                    soup = BeautifulStoneSoup(response.read())
                    viewstate = soup.find("input", {"type": "submit"})
                    if viewstate and viewstate.get("value") == "Send":
                        print("Shell is found!! Yay!!!")
                    else:
                        print("There's nothing here")
        except urllib2.HTTPError, e:
                if e.code == 401:
                    print "[!] Authorization Required %s " % (uri)
                elif e.code == 403:
                    print "[!] Forbidden %s " % (uri)
                elif e.code == 404:
                    print "[-] Not Found %s " % (uri)
                elif e.code == 503:
                    print "[!] Service Unavailable %s " % (uri)
                else:
                    print "[?] Unknwon"

    print "\n:. FINISH :.\n"

rawDescription: Python Beautiful Soup Error : list index out of range


code:
data = np.array([[1,2,3], [4,5,np.NaN], [np.NaN,6,np.NaN], [0,0,0]])
cleaned_data = np.ma.masked_array(data,np.isnan(dat))
#calculate your weighted average here instead
weights=[1,1,1]
average = np.ma.average(cleaned_data,axis=1,weights=weights)
#this gives you the result
print average.filled(np.nan)

rawDescription: Taking np.average while ignoring NaN's?

description: Taking np.average while ignoring NaN's


code:
from pyparsing import *

openEmphasis = (LineStart() | White()) + Suppress('*')
openEmphasis.setParseAction(lambda x: ''.join(x.asList()+['<em>']))
closeEmphasis = '*' + FollowedBy(White() | LineEnd())
closeEmphasis.setParseAction(lambda x: '</em>')

emphasis = (openEmphasis | closeEmphasis).leaveWhitespace()

test = """
*foo *bar* bar*
"""
print test
print emphasis.transformString(test)

rawDescription: Pyparsing: nested Markdown emphasis

description: Pyparsing: nested Markdown emphasis


code:
for group in random_group(your_dictionary):
    print group

rawDescription: Random groups of elements of a dictionary


code:
shape = map(len, frame.index.levels)
print frame.values.reshape(shape)

rawDescription: Transform Pandas DataFrame with n-level hierarchical index into n-D Numpy array


code:
import fcntl
import os

with open("/tmp/out", "r") as f:
    fd = f.fileno()
    flag = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)
    flag = fcntl.fcntl(fd, fcntl.F_GETFL)
    if flag & os.O_NONBLOCK:
        print "O_NONBLOCK!!"

rawDescription: python Non-block read file

description: Python Non-block read file


code:
if(sum(not isinstance(strD, datetime.datetime) for strD in data.ts_placed) > 0):
    print 'Dates not converted correctly'

rawDescription: how to import dates in python

description: Import dates in python


code:
s = "able#1"

for line in open("pro.txt").readlines():
    if s == line.split()[3].strip():
        print line.rsplit(' ',1)[0].strip()

rawDescription: how to retrieve value from text file using python?

description: Retrieve value from text file using python


code:
for itm in db.doctors.find({"email":doc_mail}):
   print itm.get('_id')

rawDescription: How do i get id of an object in pymongo?

description: Get id of an object in pymongo


code:
class Node:
    def __init__(self, name, weight, children):
        self.children = children
        self.weight = weight
        self.weight_plus_children = weight

    def get_all_weight(self):
        if self.children is None:
          return self.weight_plus_children
        else:
          for child in self.children:
            print "child.get_all_weight()", child.get_weigth_with_children()
            self.weight_plus_children += child.get_weigth_with_children()

        return self.weight_plus_children

    def get_weigth_with_children(self):
        return self.weight_plus_children

leaf1 = Node('C1', 58, None)
leaf2 = Node('C2', 7, None)
leaf3 = Node('C3', 10, None)
leaf4 = Node('C4', 20, None)

subroot = Node('B1', 50, [leaf1, leaf2])
subroot1 = Node('B2', 50, [leaf3, leaf4])

root = Node('A', 100, [subroot, subroot1])

print subroot.get_all_weight()
print
print subroot1.get_all_weight()
print
print root.get_all_weight()

rawDescription: How to recursively sum and store all child values in a tree

description: Recursively sum and store all child values in a tree


code:
from bs4 import BeautifulSoup
import requests

url = 'https://zkillboard.com/kill/44998359/'
involved_url = 'https://zkillboard.com/kill/44998359/involved/'

with requests.Session() as session:
    session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'}

    session.get(url)

    response = session.get(involved_url)
    soup = BeautifulSoup(response.content)

    for row in soup.select('table.table tr.attacker'):
        name, corp, alliance = row.select('td.pilot > a')
        print name.text, corp.text, alliance.text

rawDescription: Unsure how to web-scrape a specific value that could be in several different places


code:
import numpy as np
import pandas as pl
np.random.seed(0)

people2 = pd.DataFrame(np.random.randn(5, 5),
                      columns=['a', 'b', 'c', 'd', 'e'],
                      index=['Joe', 'Steve', 'Wes', 'Jim', 'Travis'])
key = ['one', 'two', 'one', 'two', 'one']

Grouped = people2.groupby(key)

def f(df):
    df["f"] = (df.a.mean() - df.b.mean())*df.c
    return df

people2 = Grouped.apply(f)
print people2

rawDescription: Pass Multiple Columns to groupby.transform


code:
import yaml

class folded_unicode(unicode): pass
class literal_unicode(unicode): pass

def folded_unicode_representer(dumper, data):
    return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='>')
def literal_unicode_representer(dumper, data):
    return dumper.represent_scalar(u'tag:yaml.org,2002:str', data, style='|')

yaml.add_representer(folded_unicode, folded_unicode_representer)
yaml.add_representer(literal_unicode, literal_unicode_representer)

data = {
    'literal':literal_unicode(
        u'by hjw              ___\n'
         '   __              /.-.\\\n'
         '  /  )_____________\\\\  Y\n'
         ' /_ /=== == === === =\\ _\\_\n'
         '( /)=== == === === == Y   \\\n'
         ' `-------------------(  o  )\n'
         '                      \\___/\n'),
    'folded': folded_unicode(
        u'It removes all ordinary curses from all equipped items. '
        'Heavy or permanent curses are unaffected.\n')}

print yaml.dump(data)

rawDescription: Any yaml libraries in Python that support dumping of long strings as block literals or folded blocks?


code:
import csv
from collections import defaultdict

def build_dict(source_file):
    projects = defaultdict(dict)
    headers = ['Product', 'Price', 'Cost', 'Brand']
    with open(source_file, 'rb') as fp:
        reader = csv.DictReader(fp, fieldnames=headers, dialect='excel',
                                skipinitialspace=True)
        for rowdict in reader:
            if None in rowdict:
                del rowdict[None]
            brand = rowdict.pop("Brand")
            product = rowdict.pop("Product")
            projects[brand][product] = rowdict
    return dict(projects)

source_file = 'merged.csv'
print build_dict(source_file)

rawDescription: Using Python CSV DictReader to create multi-level nested dictionary


code:
def separator(string):
    if ',' in string:
        sep_strings = string.split(',')
        limits = [i.split('-') for i in sep_strings]
    else:
        limits = [string.split('-')]
    return limits

def ranger(string):
    results = []
    ranges = separator(string)
    for element in ranges:
        start = int(element[0])
        stop = int(element[1]) + 1
        results += [range(start,stop)]
    return results

print ranger(raw_input("Enter a range: "))

rawDescription: How to get 1-100, 110-130 between numbers in python

description: Get 1-100, 110-130 between numbers in python


code:
replacement = {"n't": " not", "book":"notebook"}
string = raw_input("Enter your sentence: ")

for rplc in replacement:
    string = string.replace(rplc, replacement[rplc])

print string

rawDescription: Handling negation in words

description: Handling negation in words


code:
G=(list(x) for _,x in groupby(enumerate(L), lambda (i,x):i-x))
print ",".join("-".join(map(str,(g[0][1],g[-1][1])[:len(g)])) for g in G)

rawDescription: Pythonic way to convert a list of integers into a string of comma-separated ranges


code:
namespaces = {
  "dc":"http://purl.org/dc/elements/1.1/",
  "cc": "http://creativecommons.org/ns#",
  "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
  "svg": "http://www.w3.org/2000/svg",
  "myns": "http://www.w3.org/2000/svg"
}

tree = ET.fromstring(data)
for rect in tree.xpath("//myns:rect", namespaces=namespaces):
    print rect.attrib.get("id")

rawDescription: Get rect tag from this XML file

description: Get rect tag from this XML file


code:
import numpy as np

# Max-Min Composition given by Zadeh
def maxMin(x, y):
    z = []
    for x1 in x:
        for y1 in y.T:
            z.append(max(np.minimum(x1, y1)))
    return np.array(z).reshape((x.shape[0], y.shape[1]))

# Max-Product Composition given by Rosenfeld
def maxProduct(x, y):
    z = []
    for x1 in x:
        for y1 in y.T:
            z.append(max(np.multiply(x1, y1)))
    return np.array(z).reshape((x.shape[0], y.shape[1]))

# 3 arrays for the example
r1 = np.array([[1, 0, .7], [.3, .2, 0], [0, .5, 1]])
r2 = np.array([[.6, .6, 0], [0, .6, .1], [0, .1, 0]])
r3 = np.array([[1, 0, .7], [0, 1, 0], [.7, 0, 1]])

print "R1oR2 => Max-Min :\n" + str(maxMin(r1, r2)) + "\n"
print "R1oR2 => Max-Product :\n" + str(maxProduct(r1, r2)) + "\n\n"

print "R1oR3 => Max-Min :\n" + str(maxMin(r1, r3)) + "\n"
print "R1oR3 => Max-Product :\n" + str(maxProduct(r1, r3)) + "\n\n"

print "R1oR2oR3 => Max-Min :\n" + str(maxMin(r1, maxMin(r2, r3))) + "\n"
print "R1oR2oR3 => Max-Product :\n" + str(maxProduct(r1, maxProduct(r2, r3))) + "\n\n"

rawDescription: Compositions in Fuzzy Relations - MATLAB/Python


code:
text = raw_input("please give 2 numbers to multiply separated with a comma:")
split_text = text.split(',')
a = int(split_text[0])
b = int(split_text[1])
# The last three lines could be written: a, b = map(int, text.split(','))
# but you may find the code I used a bit easier to understand for now.

if b > 0:
    num_times = b
else:
    num_times = -b

total = 0
# While loops with counters basically should not be used, so I replaced the loop
# with a for loop. Using a while loop at all is rare.
for i in xrange(num_times):
    total += a
    # We do this a times, giving us total == a * abs(b)

if b < 0:
    # If b is negative, adjust the total to reflect this.
    total = -total

print total

rawDescription: working with negative numbers in python

description: Working with negative numbers in python


code:
for row in soup.select('table#table_prefixes4 tr'):
    cells = row.find_all('td')
    if not cells:
        continue
    print [cell.get_text(strip=True) for cell in cells]

rawDescription: How to extract td HTML tags with Python BeautifulSoup?

description: Extract td HTML tags with Python BeautifulSoup


code:
from pyparsing import Word, alphas
greet = Word( alphas ) + "," + Word( alphas ) + "!" # <-- grammar defined here
hello = "Hello, World!"
print "Content-type: text/plain\n"
print hello, "->", greet.parseString( hello )

rawDescription: How do I get PyParsing set up on the Google App Engine?

description: Get PyParsing set up on the Google App Engine


code:
with My_Context(mode=0):
    print 'Executing block of code ... '

rawDescription: Skipping execution of -with- block

description: Skipping execution of -with- block


code:
primes = [2,3,5,7,11,17,19,23,29]

def sum_except(l):
    numprimes = 0
    for item in l:
        if item in primes:
            numprimes = numprimes + 1
    if numprimes==0:
        return sum(l)
    elif numprimes==1:
        for (i,item) in enumerate(l):
            if item in primes:
                if i<len(l)-1:
                    l[i+1] = 2*l[i+1]
                else:
                    l[0] = 2*l[0]
                break
        del l[i]
        print l
        return sum(l)
    else: #numprimes >= 2
        numprimes_sofar = 1
        dropped = []
        for (i,item) in enumerate(l):
            if item in primes:
                numprimes_sofar = numprimes_sofar + 1
                dropped.append(i)
            else:
                l[i] = l[i]*numprimes_sofar
        l = [x for (i,x) in enumerate(l) if i not in dropped]
        print l
        return sum(l)

print sum_except([7 , 4 , 11 , 4 , 4 , 4])
print sum_except([ 4 ,  4 ,5, 4 , 4])

rawDescription: Calculator that excludes primes up to 10th prime


code:
x=u'\u0413\u043b\u0430\u0432\u043d\u043e\u0435'
print x.encode('utf-8')
x in ucontent
ucontent.find(x)

rawDescription: urllib2 read to Unicode

description: Urllib2 read to Unicode


code:
import site
print site.getusersitepackages()

rawDescription: Conjugate transpose operator ".H" in numpy


code: print [list(x) for x in itertools.combinations(range(1, y+1), x)]

rawDescription: List All Combinations (Python)

description: List All Combinations (Python)


code:
import csv

with open('data.csv') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print row

rawDescription: How to create dict using csv file with first row as keys

description: Create dict using csv file with first row as keys


code:
def my_lin(lb, ub, steps, spacing=1.1):
    span = (ub-lb)
    dx = 1.0 / (steps-1)
    return [lb + (i*dx)**spacing*span for i in range(steps)]

lin = my_lin(0, 10, 11)
print lin
# visualize the spacing
print ''.join(' '*int(2*a)+'*' for a in lin)

rawDescription: python: generate unevenly spaced array

description: Python: generate unevenly spaced array


code:
class AdjustmentTracker(object):
    def __init__(self, base):
        print("Attribute initialized to %s" % base)
        self.base = base
        self.adjustments = []

    def compute(self):
        return self.base + sum(self.adjustments)

    def update(self, value):
        delta = (value - self.compute())
        print("Adjustment added: %s" % delta)
        self.adjustments.append(delta)

class Creature(object):
    @property
    def health(self):         return self._health.compute()
    @health.setter
    def health(self, value):  self._health.update(value)

    @property
    def armor(self):          return self._armor.compute()
    @armor.setter
    def armor(self, value):   self._armor.update(value)

    def __init__(self, health=100, armor=0):
        self._health = AdjustmentTracker(health)
        self._armor =  AdjustmentTracker(armor)

c1 = Creature(50)
c1.health = 60      # Adds a +10 adjustment
print c1.health     # 60
c1.health += 10     # Add a +10 adjustment
print c1.health     # 70
print c1._health.adjustments     # [10, 10]

rawDescription: Creating an Attribute class that allows adjusting a base value?


code: print initial_grid(3, 0, 0)

rawDescription: How to make a grid from a dictionary?

description: Make a grid from a dictionary


code:
import wx
import wx.richtext

app = wx.App(False)
f=wx.Frame(None, title="Test")
f.Show()
rt = wx.richtext.RichTextCtrl(f, size=(200,200))
def onEvent(evt):
    import cStringIO
    buf = cStringIO.StringIO()
    handler = wx.richtext.RichTextXMLHandler()
    handler.SetFlags(wx.richtext.RICHTEXT_HANDLER_INCLUDE_STYLESHEET)
    handler.SaveStream(rt.GetBuffer(), buf)
    print buf.getvalue()

f.Bind(wx.EVT_LEFT_DOWN, onEvent)
app.MainLoop()

rawDescription: save data in wxRichTextCtrl

description: Save data in wxRichTextCtrl


code:
import string

max_lens = [max([len(str(r[i])) for r in my_matrix])
                for i in range(len(my_matrix[0]))]

print "\n".join(["".join([string.ljust(str(e), l + 2)
                for e, l in zip(r, max_lens)]) for r in my_matrix])

rawDescription: Python's pretty printing of matrix

description: Python's pretty printing of matrix


code:
class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False

members = [attr for attr in dir(Example()) if not callable(attr) and not attr.startswith("__")]
print members

rawDescription: looping over all member variables of a class in python

description: Looping over all member variables of a class in python


rawDescription: Format number using LaTeX notation in Python


code:
from example import *
d = Derived.create_base()
print d
test_basedirect(d)
test_basepointer(d)
test_deriveddirect(d)
test_derivedpointer(d)

o = OtherDerived.create_base()
print o
test_basedirect(o)
test_basepointer(o)
test_derivedpointer(o)

rawDescription: Smart Pointer casting in Boost::Python

description: Smart Pointer casting in Boost::Python


code:
def iam(result):
 # Pretend this is expensive.
 print "iam(%r)" % result
 return result

any((iam(x) for x in [False, True, False]))
reduce(lambda x,y: x or y, (iam(x) for x in [False, True, False]))

rawDescription: How do you apply 'or' to all values of a list in Python?

description: Apply 'or' to all values of a list in Python


code:
import pandas as pd
from cStringIO import StringIO

text_file = '''
     0     1     2
02  en    it  None
03  en  None  None
01  nl    en   fil
'''

# Read in tabular data
df = pd.read_table(StringIO(text_file), sep='\s+')
print 'Original Data:'
print df
print

# Create boolean index based on text comparison
boolIndx = df.isin(['nl']).any(axis=1) & df.isin(['fil']).any(axis=1)
print 'Example Boolean index:'
print boolIndx
print

# Replace string based on boolean assignment
df.loc[boolIndx] = df.loc[boolIndx].replace('nl', '')
print 'Filtered Data:'
print df
print

rawDescription: pandas - apply replace function with condition row-wise

description: Pandas - apply replace function with condition row-wise


code:
import numpy as np
import re

PAT = re.compile(r"""id:\s*(?P<id>\d+)\s*
                     Name:\s*(?P<name>[0-9A-Za-z ]+?)\s+time:.*
                     processing_time:\s*(?P<ptime>\d+)""", re.VERBOSE)

values = []
fp = open("proba.txt", "r")
for line in fp:
    match = PAT.match(line)
    if match:
        values.append(( int(match.group("id")),
                        match.group("name"),
                        int(match.group("ptime"))))
fp.close()
print values

rawDescription: Read txt file for specific fields and store them in a numpy array


code:
from bs4 import BeautifulSoup

html = "	"
soup = BeautifulSoup(html, 'html.parser')
tag = soup.find("span")
tag.string = ' '

print soup.prettify(formatter=None)

rawDescription: How to insert a blank space(&nbsp) into a Beautifulsoup tag?

description: Insert a blank space(&nbsp) into a Beautifulsoup tag


code:
freq = raw_input("Enter freq values separated by spaces ").strip().split(" ")
flux = raw_input("Enter flux values separated by spaces ").strip().split(" ")
print freq, flux

rawDescription: Enter many numbers using raw_input()

description: Enter many numbers using raw_input()


code:
change(dik['dir2']['dir3'], "file", "Some text")
print dik

rawDescription: How make reference to keys in dictionary in Python


code:
# a 2D array
D = np.arange(4).reshape(2, 2)

print D
# [[0 1]
#  [2 3]]

# tile it 3 times in the first dimension
x = np.repeat(D[None, :], 3, axis=0)

print x.shape
# (3, 2, 2)

print x
# [[[0 1]
#   [2 3]]

#  [[0 1]
#   [2 3]]

#  [[0 1]
#   [2 3]]]

rawDescription: How to intialise a Numpy array of numpy arrays

description: Intialise a Numpy array of numpy arrays


code:
import timeit

setup = """
import random
random.seed(0)
item_count = 100000
# divide key range by 5 to ensure lots of duplicates
items = [(random.randint(0, item_count/5), 0) for i in xrange(item_count)]
"""
in_dict = """
d = {}
for k, v in items:
    if k not in d:
        d[k] = v
"""
set_default = """
d = {}
for k, v in items:
    d.setdefault(k, v)
"""
straight_add = """
d = {}
for k, v in items:
    d[k] = v
"""
print 'in_dict      ', timeit.Timer(in_dict, setup).timeit(1000)
print 'set_default  ', timeit.Timer(set_default, setup).timeit(1000)
print 'straight_add ', timeit.Timer(straight_add, setup).timeit(1000)

rawDescription: Fastest way to update a dictionary in python


code:
from functools import wraps

def prints_invocation(f):
    @wraps(f)
    def wrapped(*args):
        print "%s(%s)" % (f.__name__, ', '.join(repr(a) for a in args))
        return f(*args)
    return wrapped

rawDescription: print arguments on function invocation

description: Print arguments on function invocation


code:
import gio
import os

def directory_changed(monitor, file1, file2, evt_type):
    if os.path.isdir(file2):    #maybe this needs to be file1?
        add_monitor(file2)
    print "Changed:", file1, file2, evt_type

def add_monitor(dir):
    gfile = gio.File(dir)
    monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None)
    monitor.connect("changed", directory_changed)

add_monitor('.')

import glib
ml = glib.MainLoop()
ml.run()

rawDescription: PyGTK/GIO: monitor directory for changes recursively


code:
for fruit_name, fruits in fruit_stand.items():
    print fruit_name, "=>", fruits

# Lemon => [(Yellow, 5, 2.99)]
# Apple => [(Red, 10, 0.99), (Green, 9, 0.69)]
# Cherry => [(White, 2, 5.99),(Red, 5, 5.99)]

rawDescription: Breaking down instances of classes into lists, or: a better way to sum class variables?


code:
import datetime
import time

now = datetime.datetime.now()

print now
print now.ctime()
print now.isoformat()
print now.strftime("%Y%m%dT%H%M%S")

rawDescription: Python: creating list of timestamps by minute


code:
from PIL import Image, ImageChops
import math

def image_entropy(img):
    """calculate the entropy of an image"""
    # this could be made more efficient using numpy
    histogram = img.histogram()
    histogram_length = sum(histogram)
    samples_probability = [float(h) / histogram_length for h in histogram]
    return -sum([p * math.log(p, 2) for p in samples_probability if p != 0])

# testing..

img1 = Image.open('SnowCam_main1.jpg')
img2 = Image.open('SnowCam_main2.jpg')
img3 = Image.open('SnowCam_main3.jpg')

# No Difference
img = ImageChops.difference(img1,img1)
img.save('test_diff1.png')
print image_entropy(img) # 1.58496250072

# Small Difference
img = ImageChops.difference(img1,img2)
img.save('test_diff2.png')
print image_entropy(img) # 5.76452986917

# Large Difference
img = ImageChops.difference(img1,img3)
img.save('test_diff3.png')
print image_entropy(img) # 8.15698432026

rawDescription: How to detect motion between two PIL images? (wxPython webcam integration example included)

description: Detect motion between two PIL images? (wxPython webcam integration example included)


code:
x = "Apple iPhone 6(Silver, 16 GB)"
y = "Apple iPhone 6 64 GB GSM Mobile Phone (Silver)"

set_x = set([item.lower() for item in re.findall("([a-zA-Z0-9]+)", x)])
set_y = set([item.lower() for item in re.findall("([a-zA-Z0-9]+)", y)])

print set_x
print set_y

print set_x.issubset(set_y)

rawDescription: How to perform pattern matching between two strings?

description: Perform pattern matching between two strings


code: print profile.user.email ## Won't execute second query

rawDescription: Fetch data from models related with foreign key


code:
o = open
print repr(open)
print repr(o)
o('file.txt')

rawDescription: what exactly are built-in types in Python?

description: What exactly are built-in types in Python


code:
import argparse
parser = argparse.ArgumentParser(description="""This script will clean the old component files.""")
p1 = argparse.ArgumentParser(add_help=False)
p1.add_argument("path", help="path to clean", choices = ["remote", "projects"])
p2 = argparse.ArgumentParser(add_help=False)
p2.add_argument("-d", "--delete", help="parameter for deleting the files from the filesystem", nargs='*', default=True)
sp = parser.add_subparsers(dest='component',description="component to clean")
sp.add_parser('hos', parents=[p1,p2])
sp.add_parser('hcr', parents=[p1,p2])
sp.add_parser('mdw', parents=[p2])
sp.add_parser('gui', parents=[p2])
print parser.parse_args()

rawDescription: Argument parsing python using ArgParse

description: Argument parsing python using ArgParse


code:
def m(x,y):
    x = 2
    y = [3,5]
    return x,y

a = 1
b = [0,26]
a,b = m(a,b)
print a,b

rawDescription: Changing values in a function, but not able to print them outside of the function


code:
for row in data:
    if counter[row[0]] >= 4:
        print row

rawDescription: python csv: getting subset

description: Python csv: getting subset


code:
def longestSubstringFinder(string1, string2):
    answer = ""
    len1, len2 = len(string1), len(string2)
    for i in range(len1):
        match = ""
        for j in range(len2):
            if (i + j < len1 and string1[i + j] == string2[j]):
                match += string2[j]
            else:
                if (len(match) > len(answer)): answer = match
                match = ""
    return answer

print longestSubstringFinder("apple pie available", "apple pies")
print longestSubstringFinder("apples", "appleses")
print longestSubstringFinder("bapples", "cappleses")

rawDescription: Find common substring between two strings


code:
import itertools
max_vals = [3, 2]
for I in itertools.product(*[range(m) for m in max_vals]):
    print I

rawDescription: Next level of abstraction up from a for loop?


code:
from itertools import groupby
from operator import itemgetter

cursor.execute('''select eventid, timestamp, value from table
                  where type="VALUE" order by eventid''')
for eventid, rows in groupby(cursor, itemgetter(0)):
    print eventid
    for _, timestamp, value in rows:
        print timestamp, value

rawDescription: Converting database query results from strings to tuples efficiently


code:
dict = {}
infile = open("in", 'r')
for line in infile:
    line = line.strip()
    line = line.split(',')
    print "line:  ", line
    for field in line:
        field = field.strip()
        print "field:", field
        if field.startswith('Filename: '):
            key = field.split(':')[1]
            value = None

        elif field.startswith('Version: '):
            value = field.split(':')[1]
            if key is not None:
                dict[key] = value
                value = None
                key = None

print dict

rawDescription: Can I pass two conditionals to build a key/value pair in the same dictionary?

description: Pass two conditionals to build a key/value pair in the same dictionary


code:
newMinR = 50.0
newMaxR = 240.0

factor = (newMaxR - newMinR) / (img[:, :, 0].max() - img[:, :, 0].min())
shift = newMinR - factor * img[:, :, 0].min()

img[:, :, 0] = factor * img[:, :, 0].astype('float') + shift
print "new R:", img[:, :, 0].min(), img[:, :, 0].max()

rawDescription: get the max of R,G,B of one image by using programming

description: Get the max of R,G,B of one image by using programming


code:
name='a'

import re
p = re.compile('^'+re.escape(name)+ '$')

with open('test.txt') as inpfile:
    for num, line in enumerate(inpfile):
        if p.search(line.rstrip(r'\n')):
            print num

rawDescription: python regex with variable input

description: Python regex with variable input


code:
n = 10
array = [[False for _ in range(n)] for _ in range(n)]
for row in array:
  print row

rawDescription: How to create a 2D list in python where all elements are the same?

description: Create a 2D list in python where all elements are the same


code:
class a(object):
    b = 'a'
    c = 'd'

print dir(a)

rawDescription: How can I get a full list of class members without instantiating a class?

description: Get a full list of class members without instantiating a class


code: print prompt_user('Are you sure?', 'Y', 'N', 'A', 'Q')

rawDescription: raw_input placeholder?

description: Raw_input placeholder


code:
#!/usr/bin/env python

import json, collections

foo = json.loads('{"123": null, "234": null, "456": null}', object_pairs_hook=collections.OrderedDict)
print map(int, foo.keys())

rawDescription: Python get JSON object by index

description: Python get JSON object by index


code:
test_list=['x10','x50','x100']
text='this text has x100 only'
for i in test_list:
    if  i in text.split():
        print "found "+i

rawDescription: python to find sub string inside string

description: Python to find sub string inside string


code:
import pandas as pd
df = pd.DataFrame({'A_agriculture': [1,2,3],
                   'B_agriculture': [11,22,33],
                   'C': [4,5,6]})
df.columns = df.columns.str.replace('agriculture', 'agri')
print df

rawDescription: pandas rename column if contains string

description: Pandas rename column if contains string


rawDescription: Return matching strings from different txt files containing lists. Each item on new line


code:
listm = soup.findAll('td',{'class':'thumb'})
for elem in listm:
    imgs = elem('img')
    if imgs:
        print imgs['alt']

rawDescription: BeautifulSoup to find text within <img alt tag


code:
a = my_class()
print a.var
a.printout()
a.var = 'apple'
a.printout()

rawDescription: How to pass a class variable to a decorator inside class definition?

description: Pass a class variable to a decorator inside class definition


code: print df

rawDescription: Python pandas: How do I drop specific levels in a hierarchical index if any column values are NaN?


code:
import string

def foo(input_string, num):
    return input_string.translate(None, string.letters)[:num]

print foo('test120202test34234e23424', 6)   # 120202
print foo('ex120202test34234e23424',   6)   # 120202

rawDescription: Python print first N integers from a string


code:
my_dict = DescDict()
my_dict["foo"] = (0.5, "A foo var")  # just use a tuple if you only have 2 vals
print my_dict["foo"] + 15            # prints 15.5
print my_dict.get_desc("foo")        # prints 'A foo var'

rawDescription: Returning default members when accessing to objects in python


code:
import random

def shuffle(ary):
    initial = ary[:]
    a=len(ary)
    b=a-1
    for d in range(b,0,-1):
      e=random.randint(0,d)
      if e == d:
            return shuffle(initial)
      ary[d],ary[e]=ary[e],ary[d]
    return ary

ary = [1,2,3,4,5,6]
print shuffle(ary)

rawDescription: Instead of continue, rerun function

description: Instead of continue, rerun function


code:
a = ["paul Parthipan","paul","sdds","sdsdd"]
last_name = "Parthipan"
if any(last_name in ai for ai in a):
    print "matched"

rawDescription: how to find a particular string in an element of array in python

description: Find a particular string in an element of array in python


code:
for words in cleaned_example:
    if sentiment(words[0])[0] < sentiment(words[-1])[0]:
        print "Increasing"
    else:
        print "Decreasing"

rawDescription: How do I check if the values I am getting are increasing/decreasing?

description: Check if the values I am getting are increasing/decreasing


code:
for neighbor in root.iter('neighbor'):
  print neighbor.attrib

rawDescription: Python - What does my XML contain?

description: Python - What does my XML contain


code:
shops = [[0,1,1,1],[1,0,1,1],[1,1,0,1],[1,1,1,0]]
times = [0, 1, 1]

"""
Data structure
{
    shop: 'root',
    children: [
        {
            shop: 1,  # index of the shop
            children: [  # shops where you can go from here
                {
                    shop: 2,
                    children: [...]
                },
                ...
            ]
        },
        ...
    ]
}

"""

def get_shop(index):
    return shops[index]

def get_next_shop_indexes(shop, time_interval):
    next_shops = []
    for index, shop_time_interval in enumerate(shop):
        if shop_time_interval == time_interval:
            next_shops.append(index)
    return next_shops

def build_route_branch(branch, shop_index, time_intervals):
    shop = get_shop(shop_index)
    next_shop_indexes = get_next_shop_indexes(shop, time_intervals[0])
    for next_shop_index in next_shop_indexes:
        child_branch = {
            'shop': next_shop_index,
            'children': []
        }
        branch['children'].append(child_branch)
        if len(time_intervals) > 1:
            child_branch = build_route_branch(
                child_branch,
                next_shop_index,
                time_intervals[1:]
            )

tree = {
    'shop': 'root',
    'children': []
}
for index, shop in enumerate(shops):
    branch = build_route_branch(tree, index, times)

import pprint
pprint.pprint(tree)

print 'Drink beer :)'

rawDescription: Finding all combinations in a list with a constraint in python


code:
print 'Missing values =', ','.join([i for i in list1 if i not in set2])
print 'Missing values =', ','.join([i for i in list2 if i not in set1])

rawDescription: Missing and Additional values in 2 list

description: Missing and Additional values in 2 list


code:
for x in range(spalte+1):
    print x
    print spalte
    for i in range(spalte):
        print i
    print spalte-1

rawDescription: Loop gives other results

description: Loop gives other results