code:
cs=np.zeros(len(amp-1))

print "Using an initial guess of 1450 m/s"
cs[1] = (rho[i-1]*1450*(-1-amp[i]))/(rho[i]*(1-amp[i]))

for i in range(2,len(amp-1)):
  if twtt[i] == 0:
    print "Reached new cmp #: ",cmp_no[i],"as twwt has re-started at ",twtt[i]
    cs[i] = 1450
  else:
    print i
    cs[i] = (rho[i-1]*cs[i-1]*(-1-amp[i]))/(rho[i]*(1-amp[i]))

rawDescription: Python: Speeding up a slow for-loop calculation (np.append)


code:
import sys

y = int(sys.argv[1])
print y

rawDescription: Ssh variable found in one python script to another python script and then execute the second script


code:
import win32file
type=GetBinaryType("myfile.exe")
if type==win32file.SCS_32BIT_BINARY:
    print "32 bit"
# And so on

rawDescription: Determine if an executable (or library) is 32 -or 64-bits (on Windows)


code:
print get_level(('CS1010S', 'A+')) # 1
print get_level(('SSA1207', 'B+')) # 1

rawDescription: A functon that finds the numeric letter from the input


code:
def main():
    testdata = {
        "president": "FDR",
        "alive": False,
        "terms": 4,
        "firstelected": 1933,
    }
    apresident = President(**testdata)
    anotherpresident = President(president="BHO", terms=2, firstelected=2008)
    print apresident
    print apresident.alive
    print anotherpresident
    print anotherpresident.alive

class President:
    id_iter = itertools.count(1)
    #def __init__(self, president, alive, terms, firstelected):
    def __init__(self, **kwargs):
        self.id = self.id_iter.next()
        self.president = kwargs.get("president", None)
        self.alive = kwargs.get("alive", True)
        self.terms = kwargs.get("president", 1)
        self.firstelected = kwargs.get("president", None)

rawDescription: argument unpacking and assignment to class variables

description: Argument unpacking and assignment to class variables


code:
def foo(x):
  return x*x

class Bar(object):
  def zap(self, x):
    return foo(x) * self.x
  x = 3

print dill.source.importable(Bar.zap, source=True)

rawDescription: Pickle python class instance plus definition


code:
class Node():
    def __init__(self):
        pass

    def register(self, f, num, done):
        print f(num, done)

rawDescription: How to override a function call in Python?

description: Override a function call in Python


code:
common = set(x[0])
for l in x[1:]:
    common &= set(l)
print list(common)

rawDescription: Find (and keep) duplicates of sublist in python


code:
def XinY_Stack(x, y):
    stack = [(x, 0, [0]*y)]
    while stack:
        x, index, slots = stack.pop()
        if (y - index) == 1:
            slots[index] = x
            print slots
            slots[index] = 0
        else:
            for i in range(x + 1):
                slots[index] = x-i
                stack.append((i, index + 1, slots[:]))

rawDescription: Is it possible to remove recursion from this function?


code:
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket Created"
port = 21
host = "ftp.rediris.es"
ip = socket.gethostbyname(host)

print ip
print "ip of " +host+ " is " +ip

s.connect ((ip, port))
print "Socket Connected to "+host+" on ip "+ ip

reply = ''
while True:
    message = "HELP\r\n"
    reply += s.recv(1024)
    if not reply:
        break
    if '220 Only anonymous FTP is allowed here' in reply:
        s.sendall(message)
        break
reply += s.recv(65535)
print reply

rawDescription: Python Sockets connect to FTP don't receive what I expect


code:
import csv
import matplotlib.pyplot as plt

path = []

with open('paths_finished.tsv','r') as tsv:
    paths = [line.strip().split('\n') for line in tsv]
    newPath = paths[16:]
    counter = 0

items = []
for k in range(0,len(newPath)):
    path = newPath[counter][0].count(';')
    counter +=1
    items.append(path)
    print path

print items

path2 = list(set(items)) ## gets the unique values in the list

histo = []

for i in path2:
    histo.append(items.count(i)) ## add the number of occurances to the histo list

plt.bar(path2, histo)
plt.suptitle('Title', fontsize=14)
plt.xlabel('Number', fontsize=12)
plt.ylabel('Freq', fontsize=12)
plt.show()

rawDescription: Make histogram in python with list

description: Make histogram in python with list


rawDescription: How can I rewite this Python code using iteration?

description: Rewite this Python code using iteration


code:
l.sort(key=lambda x: _human_key(x.name))
print [o.name for o in l]
['a', 'AA', 'AB']

rawDescription: How to sort alphanumeric list of Django model objects

description: Sort alphanumeric list of Django model objects


code:
from unidecode import unidecode
print unidecode(u'stra\xdfe')

rawDescription: Python locale-aware string comparison

description: Python locale-aware string comparison


code:
#!/bin/python
import Queue
import threading
import time

def basic_worker(queue, thread_name):
    print "Starting %s" % (threading.currentThread().getName()) + "\n"
    while True:
       item = queue.get()
       ##do_work on item which might take 10-15 minutes to complete
       time.sleep(5) # to simulate work
       queue.task_done()

def basic(queue):
# http://docs.python.org/library/queue.html

    for i in range(10):
       print 'enqueuing', i
       t = threading.Thread(target=basic_worker, args=(queue, i))
       t.daemon = True
       t.start()
    queue.join()       # block until all tasks are done
    print 'got here' + '\n'

queue = Queue.Queue()

for item in range(4):
     queue.put(item)

basic(queue)

print "End of program"

rawDescription: Understanding Python Queues and Setting threads to run as a Daemon thread


code:
for code in codes:
    print lang[code]

rawDescription: python list items & convert language codes to names

description: Python list items & convert language codes to names


code: print r'baz "\"'

rawDescription: Python - Backslash Quoting in String Literals


rawDescription: Efficiently evaluate polynomial of 80 variables with 80,000 terms


code:
class Wand(object):
    def __init__(self, wandtype, length):
        self.length = length
        self.wandtype = wandtype
        self.spells = {} # Our container for spells.
        # You can add directly too: my_wand.spells['accio'] = Spell("aguamenti", "fire")

    def fulldesc(self):
        print "This is a %s wand and it is a %s long" % (self.wandtype, self.length)

    def addspell(self, spell):
        self.spells[spell.name] = spell

    def cast(self, spellname):
        """Check if requested spell exists, then call its "cast" method if it does."""
        if spellname in self.spells: # Check existence by name
            spell = self.spells[spellname] # Retrieve spell that was added before, name it "spell"
            spell.cast(self.wandtype) # Call that spell's cast method, passing wandtype as argument
        else:
            print "This wand doesn't have the %s spell." % spellname
            print "Available spells:"
            print "\n".join(sorted(self.spells.keys()))

class Spell(object):
    def __init__(self, name, target):
        self.name = name
        self.target = target

    def cast(self, wandtype=""):
        print "You cast the spell %s with your %s wand at %s." % (
               self.name, wandtype, self.target)
        if self.name == "lumus":
            print "The room lights up."
        elif self.name == "wingardium leviosa":
            print "You cast the levitation spell.",
            print "The %s starts to float!" % self.target

    def __repr__(self):
        return self.name

my_wand = Wand('Phoenix-feather', '12 inches')
lumus = Spell('lumus', 'door')
wingardium = Spell("wingardium leviosa", "enemy")

my_wand.fulldesc()
lumus.cast() # Not from a Wand! I.e., we're calling Spell.cast directly
print "\n\n"

my_wand.addspell(lumus) # Same as my_wand.spells["lumus"] = lumus
my_wand.addspell(wingardium)
print "\n\n"

my_wand.cast("lumus") # Same as my_wand.spells["lumus"].cast(my_wand.wandtype)
print "\n\n"
my_wand.cast("wingardium leviosa")
print "\n\n"
my_wand.cast("avada kadavra") # The check in Wand.cast fails, print spell list instead
print "\n\n"

rawDescription: Python Class Inheritance AttributeError - why? how to fix?


code:
import subprocess

process = subprocess.Popen(['df -h | awk \'{print $(NF-1),$NF}\''], stdout=subprocess.PIPE, shell=True)
out, err = process.communicate()
out = out.splitlines()[1:] # grab all the lines except the header line
results = {}
for i in out:
    tmp = i.split(' ')
    results[tmp[1]] = tmp[0]

for key, value in results.items():
    print key + " is " + str(value) +" full"

rawDescription: In Python, how do I get a list of all partitions in Mac OS X?


code:
import addressbook_pb2 as addressbook

person = addressbook.Person(id=1234, name="John Doe", email="foo@example.com")
person.phone.add(number="1234567890")

def dump_object(obj):
    for descriptor in obj.DESCRIPTOR.fields:
        value = getattr(obj, descriptor.name)
        if descriptor.type == descriptor.TYPE_MESSAGE:
            if descriptor.label == descriptor.LABEL_REPEATED:
                map(dump_object, value)
            else:
                dump_object(value)
        elif descriptor.type == descriptor.TYPE_ENUM:
            enum_name = descriptor.enum_type.values[value].name
            print "%s: %s" % (descriptor.full_name, enum_name)
        else:
            print "%s: %s" % (descriptor.full_name, value)

dump_object(person)

rawDescription: Looping over Protocol Buffers attributes in python


code:
from collections import defaultdict

def find_family(names):
    d = defaultdict(list)
    for fn, ln in names:
        d[ln].append(fn)
    return dict((k,v) for (k,v) in d.items() if len(v)>1)

names = set([('John', 'Lee'), ('Mary', 'Miller'), ('Paul', 'Ryan'),
             ('Bob', 'Ryan'), ('Tina', 'Lee'), ('Bob', 'Smith')])
print find_family(names)

rawDescription: Finding tuples with a common element

description: Finding tuples with a common element


code:
class Person(Base):
    __tablename__ = 'people'

    type_ = Column(types.String)

    __mapper_args__ = {
        'polymorphic_identity': None,
        'polymorphic_on': type_
    }

class Parent(Person):

    __mapper_args__ = {
        'polymorphic_identity': "parent",
        'polymorphic_on': type_
    }

    def work(self):
        print 'I am a parent'

class Child(Person):
    __mapper_args__ = {
        'polymorphic_identity': "child",
        'polymorphic_on': type_
    }

    def work(self):
        print 'I am a child'

rawDescription: method override fails when retrieving by base class

description: Method override fails when retrieving by base class


code:
import argparse

p = argparse.ArgumentParser()

p.add_argument('--foo')
p.add_argument('--bar')
p.add_argument('remaining', nargs=argparse.REMAINDER)

print p.parse_args()

rawDescription: Python argparse treat arguments in different ways


code:
from ij import IJ

imp = IJ.getImage()
result = imp.getProcessor().getPixel(0, 123)
print result

rawDescription: How to output the intensity of every point using imageJ?

description: Output the intensity of every point using imageJ


code:
import struct
length, command, eggs, spam = struct.unpack('!BBi4s',data)
#...whatever your fields really are
print "len: %i\ncmd: %i\negg qty: %i\nspam flavor: '%s'" % (
    length, command, eggs, spam)

rawDescription: Non-binary(hex) characters in string received over TCP with Python


code:
import re
from collections import Counter

# Patterns to save in the end, [name, attr, values]
patterns = [r"^([0-9a-z_-]{4,}$)", r"^([a-z_,\s]*$)", r"([0-9:,\s-]{4,})$"]

# Get file content, remove any trailing empty line.
with open('/path/to/my/file') as f:
    content = f.read().split('\n')
    if not content[-1]:
        content = content[:-1]

# 1) Find all single character columns in content with only whitespaces.
no_lines = len(content)
whitespaces = [i for l in content for i, char in enumerate(l) if char == ' ']
whi_columns = [k for k, v in Counter(whitespaces).iteritems() if v == no_lines]
#                                                .items() in python3
# 2) Get all real columns that are between whitespace columns.
columns_defs = []
for i, whi_col in enumerate(whi_columns + [len(content[0])]):
    if whi_col and not i: #special first column
        columns_defs.append(slice(whi_col))
    if whi_col > whi_columns[i - 1] + 1:
        columns_defs.append(slice(whi_columns[i - 1] + 1, whi_col))

# 3) Extract columns from file content.
data_columns = [[line[col].strip() for line in content] for col in columns_defs]

# 4) Save columns fitting patterns.
for data_col in data_columns:
    data = ''.join(data_col)
    if re.match(r'|'.join(patterns), data):
        print data

rawDescription: How to write regular expressions to match white space delimited multi-line column data

description: Write regular expressions to match white space delimited multi-line column data


code: print [{k + ' ' * positions[k] : v + ' ' * positions[k] for k,v in d.items()} for d in my_list]

rawDescription: How to append space at the end of Key and Values in the list of dictionary in python

description: Append space at the end of Key and Values in the list of dictionary in python


code:
import theano.pp #pp is for pretty print
x = T.dmatrix('x') #naming your variables is a good idea, and important i think
lr = LogisticRegression(x,n_in = 28*28, n_out= 10)
print pp(lr.p_y_given_x)

rawDescription: What is the prupose/meaning of passing "input" to a function in Theano?


code:
def linematcher(haystack, needles, lineNumbers):
    f = open(needles)
    needles = [line.strip() for n, line in enumerate(f, 1) if n in lineNumbers]
    f.close()

    hsubs = set(hash(s) for s in needles)
    for n, lineWithNewline in enumerate(open(haystack), 1):
        line = lineWithNewline.strip()
        hs = hash(line)
        if hs in hsubs and line in needles:
            print "{0} ===> {1}".format(lineNumbers[needles.index(line)], n)

rawDescription: Mapping line numbers across two diff files using emacs/python/winmerge


code:
with open('StoryTime.txt', 'rt') as story_file:
    index = make_index(story_file)

longest_word = max((len(word) for word in index))
for word, line_nums in sorted(index.iteritems()):
    print '{:<{}} {}'.format(word, longest_word, line_nums)

rawDescription: Check Values of A Dictionary for Repeating Numbers


code:
import socket

mysocket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
mysocket.settimeout(0.5)
dest = ('127.0.0.01', 88)

user_input = raw_input()

while user_input:
    mysocket.sendto(user_input, dest)
    acknowledged = False
    # spam dest until they acknowledge me (sounds like my kids)
    while not acknowledged:
        try:
            ACK, address = mysocket.recvfrom(1024)
            acknowledged = True
        except socket.timeout:
            mysocket.sendto(user_input, dest)
    print ACK
    user_input = raw_input()

mysocket.close()

rawDescription: Python implementation for Stop and Wait Algorithm


code:
import numpy as np
from scipy import integrate

# Define function and interval
a = 0.0
b = np.pi/2
f = lambda x: np.cos(x)

# Gauss-Legendre (default interval is [-1, 1])
deg = 6
x, w = np.polynomial.legendre.leggauss(deg)
# Translate x values from the interval [-1, 1] to [a, b]
t = 0.5*(x + 1)*(b - a) + a
gauss = sum(w * f(t)) * 0.5*(b - a)

# For comparison
quad, quad_err = integrate.quad(f, a, b)

print 'The QUADPACK solution: {0:.12} with error: {1:.12}'.format(quad, quad_err)
print 'Gauss-Legendre solution: {0:.12}'.format(gauss)
print 'Difference between QUADPACK and Gauss-Legendre: ', abs(gauss - quad)

rawDescription: Different intervals for Gauss-Legendre quadrature in numpy


code:
import serial
ser = serial.Serial('/dev/tty.usbserial', 9600)
while True:
    print ser.readline()

rawDescription: How can I interface python with the serial output from an Arduino Uno on a Mac?

description: Interface python with the serial output from an Arduino Uno on a Mac


code:
import multiprocessing
import time

def f(ns, ls, di):
    ns.x += 1
    ns.y[0] += 1
    ns_z = ns.z
    ns_z[0] += 1
    ns.z = ns_z

    ls[0] += 1
    ls[1][0] += 1
    ls_2 = ls[2]
    ls_2[0] += 1
    ls[2] = ls_2

    di[0] += 1
    di[1][0] += 1
    di_2 = di[2]
    di_2[0] += 1
    di[2] = di_2

if __name__ == '__main__':
    manager = multiprocessing.Manager()
    ns = manager.Namespace()
    ns.x = 1
    ns.y = [1]
    ns.z = [1]
    ls = manager.list([1, [1], [1]])
    di = manager.dict({0: 1, 1: [1], 2:[1]})

    print 'before', ns, ls, di
    p = multiprocessing.Process(target=f, args=(ns, ls, di))
    p.start()
    p.join()
    print 'after', ns, ls, di

rawDescription: How does multiprocessing.Manager() work in python?


code:
color_list = ["000050", "005000", "500000"]  # GBR
color_list.sort(key=get_hsv)
print color_list

rawDescription: Sort (hex) colors to match rainbow

description: Sort (hex) colors to match rainbow


code:
def foo(value): print value

@property_functions(f_1='property_1', f_2='property_2')
class MyClass(object):
    property_1 = 'foo'
    property_2 = 'bar'

mc = MyClass()
mc.f_1()
mc.f_2()

rawDescription: How to define similar class-functions related to different class-properties inside __init__

description: Define similar class-functions related to different class-properties inside __init__


code: print 'You said', name

rawDescription: How can the user communicate with my python script using the shell?


code:
import re

def callback(match):
    return match.group(0).replace('17', '19')

s = "[ 17 plane_17 \ 23 25 17 99 150 248 \ noname ]"

s = re.compile(r'\\.+?\\').sub(callback, s)

print s

rawDescription: regex/python to find and replace specific number within string

description: Regex/python to find and replace specific number within string


code:
import sys
import pygame
import knightmove
import os

pygame.init()

square_list = []
line_list = []
i = 0
j = 1

def make_gif():
    os.system("convert   -delay 40   -loop 0   Screenshots/screenshot*.png   knights_tour.gif")

def get_moves(start_move):
    return knightmove.knights_tour(start_move, 8)

def scratch(move):
    move_x, move_y = move
    x = int(move_x) * 50
    y = int(move_y) * 50
    line_list.append([x+25, y+25])
    square_list.append([x, y])
    for index in range(len(square_list)):
        screen.blit(square, square_list[index])

def draw_line():
    for index in range(len(line_list)-1):
        pygame.draw.line(screen, black, (line_list[index]), (line_list[index+1]), 2)

def draw_dot():
    return pygame.draw.circle(screen, red, (line_list[i]), 3, 0)

def screenshot():
    if j <= 9:
        c = "0"+str(j)
    else:
        c = j
    pygame.image.save(screen, "/home/renko/PycharmProjects/pygame_tut1/Screenshots/screenshot"+str(c)+".png")

size = width, height = 400, 400
white = 255, 255, 255
black = 0, 0, 0, 0
red = 255, 0, 0

screen = pygame.display.set_mode(size)
square = pygame.image.load("Untitled.png")

start = raw_input("Enter the start position:")
moves = get_moves(start)

while 1:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    screen.fill(white)
    pygame.draw.line(screen, black, (0, 50), (400, 50), 3)
    pygame.draw.line(screen, black, (0, 100), (400, 100), 3)
    pygame.draw.line(screen, black, (0, 150), (400, 150), 3)
    pygame.draw.line(screen, black, (0, 200), (400, 200), 3)
    pygame.draw.line(screen, black, (0, 250), (400, 250), 3)
    pygame.draw.line(screen, black, (0, 300), (400, 300), 3)
    pygame.draw.line(screen, black, (0, 350), (400, 350), 3)

    pygame.draw.line(screen, black, (50, 0), (50, 400), 3)
    pygame.draw.line(screen, black, (100, 0), (100, 400), 3)
    pygame.draw.line(screen, black, (150, 0), (150, 400), 3)
    pygame.draw.line(screen, black, (200, 0), (200, 400), 3)
    pygame.draw.line(screen, black, (250, 0), (250, 400), 3)
    pygame.draw.line(screen, black, (300, 0), (300, 400), 3)
    pygame.draw.line(screen, black, (350, 0), (350, 400), 3)

    scratch(moves[i])
    draw_line()
    draw_dot()
    screenshot()
    i += 1
    j += 1
    pygame.display.flip()
    if i == 64:
        make_gif()
        print "GIF was created"
        break

rawDescription: Simulating the Knight Sequence Tour

description: Simulating the Knight Sequence Tour


code:
from decimal import *

getcontext().prec = 5

def GetNodeRanks(a):        # graph, names, size
    # opt: pass in directly a[0], you do not use the rest
    numIterations = 10
    adjacencyMatrix = copy.deepcopy(a[0])
    #opt: why copy.deepcopy? You do not modify adjacencyMatric
    b = [Decimal(1)]*len(adjacencyMatrix)
    # opt: You often call Decimal(1) and Decimal(0), it takes some time
    # do it only once like
    # dec_zero = Decimal(0)
    # dec_one = Decimal(1)
    # prepare also other, repeatedly used data structures
    # len_adjacencyMatrix = len(adjacencyMatrix)
    # adjacencyMatrix_range = range(len_ajdacencyMatrix)
    # Replace code with pre-calculated variables yourself

    tmp = [Decimal(0)]*len(adjacencyMatrix)
    for i in range(numIterations):
        for j in range(len(adjacencyMatrix)):
            tmp[j] = Decimal(0)
            for k in range(len(adjacencyMatrix)):
                tmp[j] = Decimal(tmp[j] + adjacencyMatrix[j][k] * b[k])
        norm_sq = Decimal(0)
        for j in range(len(adjacencyMatrix)):
            norm_sq = Decimal(norm_sq + tmp[j]*tmp[j])
        norm = Decimal(norm_sq).sqrt #is this correct? I woudl expect .sqrt()
        for j in range(len(b)):
            b[j] = Decimal(tmp[j] / norm)
    print b
    return b

rawDescription: Speeding up arithmetic with Python Decimal library


code:
from Crypto.Hash import MD5
from Crypto.Cipher import DES

_password = 'q1w2e3r4t5y6'
_salt = '\x80\x40\xe0\x10\xf8\x04\xfe\x01'
_iterations = 50
plaintext_to_encrypt = 'MyP455w0rd'

# Pad plaintext per RFC 2898 Section 6.1
padding = 8 - len(plaintext_to_encrypt) % 8
plaintext_to_encrypt += chr(padding) * padding

if "__main__" == __name__:

    """Mimic Java's PBEWithMD5AndDES algorithm to produce a DES key"""
    hasher = MD5.new()
    hasher.update(_password)
    hasher.update(_salt)
    result = hasher.digest()

    for i in range(1, _iterations):
        hasher = MD5.new()
        hasher.update(result)
        result = hasher.digest()

    encoder = DES.new(result[:8], DES.MODE_CBC, result[8:16])
    encrypted = encoder.encrypt(plaintext_to_encrypt)

    print encrypted.encode('base64')

rawDescription: Replicate Java's PBEWithMD5AndDES in Python 2.7


code:
from itertools import combinations

def check(lst):
        for i in range(len(lst)):
            try:
                    if lst[i+1]-lst[i] != 1:
                            return False
            except IndexError:
                    pass
        return True

cards = ["3D", "4D", "5D", "6D"]
comb = []
for j in combinations(cards, 3):
    comb.append(list(j))
for j in combinations(cards, 4):
    comb.append(list(j))

subs = []
for i in comb:
        subs.append([int(item[0]) for item in i])

subs = [item for item in subs if check(item) == True]

comb = []

for i in subs:
        comb.append([str(item)+'D' for item in i])

print comb

rawDescription: Itertools, combinations

description: Itertools, combinations


code:
import urllib2
f = urllib2.urlopen('http://www.python.org/')
print f.read(100)

rawDescription: How do I get data from stdin using os.system()

description: Get data from stdin using os.system()


code:
import sys
import csv

def SJtag(file,len_tag):
    reader = csv.reader(open(file), dialect='excel-tab' )
    for row in reader:
        qstarts = row[1].split(",")[1:-1]
        n = len_tag/2
        for i in qstarts:
            name = row[0]

            start = int(i)-n
            if start<0:
                start = 0

            end = int(i)+n
            if end>len(row[2]):
                end=len(row[2])

            tag = row[2][start:end]
            print name, i, tag, len(tag)

if __name__ == '__main__':
    SJtag(sys.argv[1], int(sys.argv[2]))

rawDescription: How can I give parameters to a function of a python script through the command-line?

description: Give parameters to a function of a python script through the command-line


code:
from itertools import groupby
import win32com.client as win32

# All the same as yours
word = win32.Dispatch("Word.Application")
word.Visible = 0
word.Documents.Open("testdoc.doc")
doc = word.ActiveDocument

# Here we use itertools.groupby (without sorting anything) to
# find groups of words that share the same heading (note it picks
# up newlines). The tricky/confusing thing here is that you can't
# just group on the Style itself - you have to group on the str().
# There was some other interesting behavior, but I have zero
# experience with COMObjects so I'll leave it there :)
# All of these comments for two lines of code :)
for heading, grp_wrds in groupby(doc.Words, key=lambda x: str(x.Style)):
  print heading, ''.join(str(word) for word in grp_wrds)

rawDescription: Extract headings from a MS Word document in Python


code: print soupHandler.findAll('div', id=lambda x: x and x.startswith('post-'))

rawDescription: Matching id's in BeautifulSoup

description: Matching id's in BeautifulSoup


code:
from imdb import IMDb
ia = IMDb()
dp = ia.get_movie('1431045')
print dp.keys()
print dp.get('production companies')

rawDescription: get the company info for a movie from IMDB using IMDBPY

description: Get the company info for a movie from IMDB using IMDBPY


code:
matrix = [[-5, -6, 2], [7, 2, 1], [8, -4, 9]]

# column is positive until proven negativity.
results = [True, True, True]

# We loop over the rows...
for row in matrix:

    # And we loop over all the items in the row...
    for index,item in enumerate(row):

        # If the element is negative, item > 0 will be False, and this way results[index] will be set as False and will be True no more.
        results[index] = results[index] and (item > 0)

for index2,result in enumerate(results):
    if result:
        print "The {0} column is positive".format(index2)

        # Calculate the previous columns
        previous = index2 - 1

        # We invert the sign of the position 'previous' of every row.
        for row in matrix:
            row[previous] = - row[previous]

        break

rawDescription: Find the first column in the matrix, in which all elements are positive.


code:
def printy(P):
    for i in range(len(P[0])):
        print '---',
    print

    for i in range(len(P)):
        for j in range(len(P[0])):
            print P[i][j], '|',
        print
        for i in range(len(P[0])):
            print '---',
        print

rawDescription: How to change values in nested list python

description: Change values in nested list python


code: print re.findall(r"protocol': (.*?),", strevent)

rawDescription: Python regex findall unexpected output

description: Python regex findall unexpected output


code:
from collections import defaultdict

d = defaultdict(list)

with open("romEdges.txt") as fin:
    for line in fin:
        k, v = line.strip().split()
        d[k].append(v)
print d

rawDescription: Converting text file to dictionary in python


code:
import json
import pandas as pd

db = json.loads(open('pruItems.json', 'r').read())
pieces = []
for d in db:
    if d['data']:
        df = pd.DataFrame(d['data'])
        df.columns = ['date', 'bid', 'ask']
        df = df.set_index('date')
        pieces.append(df)

df = pd.concat(pieces, axis=1, keys=[d['fund'] for d in db])

print df

rawDescription: How to import Dictionary into DataFrame?

description: Import Dictionary into DataFrame


code:
s1='monkey Feb 20, 2015 loves 2014 bananas'
s2='monkey Feb 20, 2015 loves bananas'
s3='monkey 2/20/2015 loves bananas'
s4='monkey 20 Feb 2015 loves 2014 bananas'
print word_find(s1)
print word_find(s2)
print word_find(s3)
print word_find(s4)

rawDescription: Separating a date from a string in Python


code:
wanted = {'a.txt', 'b.txt'}  # use a set, it's faster for testing membership
import zipfile
with zipfile.ZipFile('foobar.zip','r') as inzipfile:
    for infile in (name for name in inzipfile.namelist() if name[-1] != '/'):
        if os.path.split(infile)[1] in wanted:
          print inzipfile.open(infile,'r').read()

rawDescription: Selective extracting and opening for zipfile in python


code:
class Base(object):
    @classmethod
    def acquire(cls, param):
        if cls is Base:
            raise Exception("Must be called via subclass :(")
        return "this is the result of `acquire`ing a %r with %r" % (cls, param)

class Something(Base):
    pass

class AnotherThing(Base):
    pass

print Something.acquire("example")
print AnotherThing.acquire("another example")
print Base.acquire("this will crash")

rawDescription: What does cls() function do inside a class method?


code:
items = {'banana': {'price': 4,   'stock': 6 },
         'apple':  {'price': 2,   'stock': 0 },
         'orange': {'price': 1.5, 'stock': 32},
         'pear':   {'price': 3,   'stock': 15},
        }

for key in items:
    print key
    print "price: %s" % items[key]['price']
    print "stock: %s" % items[key]['stock']

rawDescription: how to print keys and values of a dictionary in python

description: Print keys and values of a dictionary in python


code:
import sys
import re

def DentArthurDent(fp, dents = 0, nextline = None):
    '''Read from FP until EOF or an exdent
       Return dict and next line'''

    tree = []
    while True:
        line, nextline = nextline or fp.readline(), None
        if not line:
            return tree, ''
        parts = re.match(r'(^ *)(.*)', line).group(1,2)
        dent = len(parts[0])
        if dent == dents:
            tree.append(parts[1])
        elif dent > dents:
            child_tree, nextline = DentArthurDent(fp, dent, line)
            tree.append(child_tree)
        else:
            return tree,line

import json
tree, _ = DentArthurDent(sys.stdin)
print json.dumps(tree, indent=4)

rawDescription: Indentation based syntax -> AST

description: Indentation based syntax -> AST


rawDescription: Python nongreedy second match

description: Python nongreedy second match


code:
import itertools

data_set = [101,102,105,106,108,111]
data_times = [1,2,5,6,8,11]

new_time_set = range(data_times[0], data_times[-1]+1)
new_data_set = []

last_time = data_times[0]

for data, time in itertools.izip(data_set, data_times):
    new_data_set.extend([0] * (time-last_time-1) + [data])
    last_time = time

print "Data:", new_data_set
print "Times:", new_time_set

rawDescription: Python : list index out of range error for filling in data set


code: print df['item_list'].apply(lambda x: pd.Series(list(set(x)))).stack().drop_duplicates().tolist()

rawDescription: Python Pandas dataframe: Collect values of a column


code:
from itertools import product
voc=['A', 'B', 'C', 'D', '*']
for pro in product(voc,repeat=5):
   print ''.join(pro)

rawDescription: Generate random element from list with no more than one repetition of one element


code:
import numpy as np

mystr = "100110"
print np.array(list(mystr))
# ['1' '0' '0' '1' '1' '0']

rawDescription: Convert string to numpy array

description: Convert string to numpy array


code:
input= """0;0;0
0;0;1
0;1;2
0;1;2
1;2;0
2;3;4
0;0;0
0;1;2
0;1;2
0;1;2
1;2;3
2;3;4"""
lines = input.split('\n')

def count_cycles(lines, n):
    cycles = 0
    inside = False
    for line in lines:
        print line
        numbers = map(int, line.split(';'))
        if inside:
           if not n in numbers:
                # end of cycle
                cycles += 1
                inside = False
        else:
            print 'not inside'
            if n in numbers:
                # new cycle
                inside = True
    return cycles

print count_cycles(1)

rawDescription: identify an event and recurrance of number

description: Identify an event and recurrance of number


code:
import re
p = re.compile(ur'^ABC\S+\s+(\S+)(?=.*\sactive\b)', re.MULTILINE)

re.findall(p, input)

rawDescription: Regex positive look behind and look ahead


code:
from threading import Thread
import time

class myThreadClass(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.myVariable = 0

        print ('Value of myVariable is: %d')%self.myVariable#Initial value
        self.daemon = False
        print 'Starting Child thread.\n'
        self.start()
    def run(self):
        k = 1
        for i in range(0,5):
            self.myVariable = self.myVariable+k #Increment the value and assign
            print ('Value of self.myVariable now is: %d')%self.myVariable#Print current value
            k += 1

        print 'The final value of self.myVariable is: %d'%self.myVariable
        print 'Child thread finished its job'

if __name__ == "__main__":
    obj = myThreadClass()
    time.sleep(2)
    print 'This is the main thread. The value of self.myVariable is: %d'%obj.myVariable

rawDescription: Python: Modifying external variables from within a thread


code:
import time

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Chrome()

browser.get("https://medium.com/top-100/december-2013")
time.sleep(1)

elem = browser.find_element_by_tag_name("body")

no_of_pagedowns = 20

while no_of_pagedowns:
    elem.send_keys(Keys.PAGE_DOWN)
    time.sleep(0.2)
    no_of_pagedowns-=1

post_elems = browser.find_elements_by_class_name("post-item-title")

for post in post_elems:
    print post.text

rawDescription: How to load all entries in an infinite scroll at once to parse the HTML in python

description: Load all entries in an infinite scroll at once to parse the HTML in python


code:
import django.utils.termcolors as termcolors
red_hello = termcolors.colorize("Hello", fg='red') # '\x1b[31mHello\x1b[0m'
print red_hello

rawDescription: ANSI graphic codes and Python

description: ANSI graphic codes and Python


code:
def pow2(n):
    print 2**n
    if n<=0:
        return 1
    else:
        return 2**n + pow2(n-1)

rawDescription: I need to write a recursive function that prints 2**n as well as 2**(n-1) and 2**(n-2) etc. until 2**0. Outputs as one single sum currently


code:
def test_string_distance():
    test_data = [
        # a         b          index_b   expected
        ("ABC",    "ABCDEF",   0,        0),
        ("ABX",    "ABCDEF",   0,        1),
        ("XYZ",    "ABCDEF",   0,        3),
        ("XBC",    "ABCDEF",   0,        1),
        ("CEE",    "ABCDEF",   2,        1),
        ("DEF",    "ABCDEF",   3,        0),
        ("AAAAA",  "BBBBBBBB", 3,        5),
        ("BAAAA",  "BBBBBBBB", 3,        4),
        ("ABAAB",  "BBBBBBBB", 3,        3),
    ]
    for a, b, index_b, expected in test_data:
        result = string_distance(a, b, index_b)
        if result != expected:
            print "string_distance({}, {}, {}) was {} but should be {}".format(
                    a, b, index_b, result, expected)

def test_subsequence():
    test_data = [
        # A         B               n   expected
        ("AXY",    "AYAXXXAAYYAX",  3,  (2,1)),
        ("AXY",    "AYAXXXAAYYAX",  2,  (2,1)),
        ("AXY",    "AYAXXXAAYYAX",  1,  (2,1)),
        ("AXY",    "AYAXXXAAYYAX",  0,  (-1,-1)),
        ("XAAY",   "AYAXXXAAYYAX",  2,  (5,0)),
        ("XAAY",   "XXAXAAXAAY",    2,  (6,0)),
        ("ABCDEF", "ZZAABAXCDEEEF", 3,  (5,2)),
        ("ABCDEF", "ZZAABAXCDEEEF", 2,  (5,2)),
        ("ABCDEF", "ZZAABAXCDEEEF", 1,  (-1,-1)),
        ("ABCDEF", "ZZAABXBCDEEEF", 3,  (5,2)),
    ]
    for a, b, n, expected in test_data:
        result = subsequence(a, b, n)
        if result != expected:
            print "test_subsequence({}, {}, {}) was {} but should be {}".format(
                    a, b, n, result, expected)

if __name__ == '__main__':
    test_string_distance()
    test_subsequence()

rawDescription: Find Substring of A in B with n mistakes


code: print re.findall(re.findall('[\w#@]+', s), your_tweet)

rawDescription: How to format tweets using python through twitter api?

description: Format tweets using python through twitter api


code:
from __future__ import division
from pylab import *

dx, dy = 0.01, 0.01
D = 0.01
dx2, dy2 = dx**2 ,dy**2
dt = (dx2*dy2)/(2*D*(dx2+dy2))
endt = 0.1
Nt = int (endt/dt)
endX,endY = 1,1
nx, ny = int(endX/dx), int(endY/dy)
T = zeros([nx,ny])
Tcopy = zeros([nx,ny])
"""initial conditions"""

for i in range(nx):
 for j in range(ny):
  if( ((i*dx - 0.5)**2 +(j*dy - 0.5)**2 < 0.1) and ((i*dx - 0.5)**2 +(j*dy - 0.5)**2 >0.05) ):
   T[i][j] = 10

def integrate(T,Tcopy):

 T[1:-1, 1:-1] = Tcopy[1:-1, 1:-1] + D*dt*( (Tcopy[2:, 1:-1] - 2*Tcopy[1:-1, 1:-1] + T[:-2, 1:-1])/dx2 + (Tcopy[1:-1, 2:] - 2*Tcopy[1:-1, 1:-1] + T[1:-1, :-2])/dy2  )
 Tcopy = copy(T)
 return Tcopy,T

x = arange(0, endX, dx)
y = arange(0, endY, dy)
X,Y = meshgrid(x, y)

"""creating the plot"""

fig, ax_lst = plt.subplots(1, 2)
ax_lst[0].imshow(T, interpolation='nearest',
                            origin='bottom',
                            aspect='auto',
                            vmin=np.min(T),
                            vmax=np.max(T),
                            cmap='hot',extent=[0,1,0,1])
im = ax_lst[1].imshow(T, interpolation='nearest',
                            origin='bottom',
                            aspect='auto',
                            vmin=np.min(T),
                            vmax=np.max(T),
                            cmap='hot',extent=[0,1,0,1])
fig.colorbar(im)

"""main loop"""

for t in range(Nt):
 im.set_data(T)
 plt.draw()
 plt.pause(0.1)
 Tcopy,T = integrate(T,Tcopy)
 print np.mean(T), np.max(T), np.min(T)

rawDescription: matplotlib imshow is not updated

description: Matplotlib imshow is not updated


code:
import csv
from itertools import izip
with open('file_.csv','rb') as f :
    csvreader=csv.reader(f,delimiter=' ')
    print list(izip(*csvreader))

rawDescription: how to split .csv data in python?

description: Split .csv data in python


code:
def _loadComplete(self):
    page = self.page()
    doc = page.currentFrame().documentElement()
    link = doc.findFirst('#link-signup')
    if link and not link.isNull():
        pos = link.geometry().center()
        self._doMouseClick(page, pos)
    else:
        print "Link not found"

@staticmethod
def _doMouseClick(obj, pos):
    # mouse down
    evt = QMouseEvent(QEvent.MouseButtonPress, pos,
                            Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
    QApplication.sendEvent(obj, evt)
    # mouse up
    evt = QMouseEvent(QEvent.MouseButtonRelease, pos,
                            Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
    QApplication.sendEvent(obj, evt)

rawDescription: PyQt4 does not redirect me to the next page


code:
with open("input.txt") as f:
    a1 = [x.strip() for x in f]
with open("input1.txt") as f:
    a2 = [x.strip() for x in f]
set(a1) | set(a2)
[(x, a1.count(x), a2.count(x)) for x in set(a1) | set(a2)]
print "\n".join(",".join([x, str([a1.count(x), a2.count(x)])]) for x in set(a1) | set(a2))

rawDescription: store value into namedtuple in python

description: Store value into namedtuple in python


code:
import feedparser
import requests
from bs4 import BeautifulSoup

FEED_URL = 'http://serienjunkies.org/xml/feeds/episoden.xml'

def is_interesting_entry(entry, title_prefix, series_names):
    return (
        entry.title.startswith(title_prefix)
        and any(name in entry.title for name in series_names)
    )

def process_entry(entry, title_prefix):
    if not entry.title.startswith(title_prefix):
        raise ValueError(
            'expected prefix {0!r} not found in {1!r}'.format(
                title_prefix, entry.title
            )
        )
    return (entry.title[len(title_prefix):], entry.link)

def process_feed(feed_url, title_prefix, series_names):
    return (
        process_entry(entry, title_prefix)
        for entry in feedparser.parse(feed_url).entries
        if is_interesting_entry(entry, title_prefix, series_names)
    )

def get_series_soup(url, cache=dict()):
    if url in cache:
        return cache[url]
    else:
        result = BeautifulSoup(requests.get(url).text)
        cache[url] = result
        return result

def get_download_urls(soup, title):
    title_text = soup.find(text=title)
    if not title_text:
        return dict()
    else:
        return dict(
            (a_tag.next_sibling.strip('| '), a_tag['href'])
            for a_tag in title_text.parent.parent('a')
        )

def main():
    series_names = ['Game.of.Thrones', 'Arrow']
    for title, url in process_feed(FEED_URL, '[DEUTSCH] ', series_names):
        print
        print title
        hoster2url = get_download_urls(get_series_soup(url), title)
        if hoster2url:
            for hoster, download_url in sorted(hoster2url.iteritems()):
                print '{0:>20s}: {1}'.format(hoster, download_url)
        else:
            print '  --- No downloads ---'

if __name__ == '__main__':
    main()

rawDescription: Extracting links and title from several pages


code:
with open(sys.argv[1], 'rU') as infile, open('test2.csv', 'wr') as outfile:
    csv_file = csv.DictReader(infile ,delimiter = ',')
    for line in csv_file:
        print line['Name'] + ',' + line['DOB']
    fieldnames = ['Name','DOB']
    csvwriter = csv.DictWriter(outfile, delimiter=',', fieldnames=fieldnames)
    infile.seek(0)
    for row in csv_file:
        csvwriter.writerow(row)

rawDescription: Python: Reading in .csv data as dictionary and printing out data as dictionary to .csv file?


code:
row = FetchOneAssoc(cur)
print row['field3']

rawDescription: Pulling entry from MySQLdb in Python

description: Pulling entry from MySQLdb in Python


code:
f = "test.png"
METADATA = {"version":"1.0", "OP":"ihuston"}

# Create a sample image
import pylab as plt
import numpy as np
X = np.random.random((50,50))
plt.imshow(X)
plt.savefig(f)

# Use PIL to save some image metadata
from PIL import Image
from PIL import PngImagePlugin

im = Image.open(f)
meta = PngImagePlugin.PngInfo()

for x in METADATA:
    meta.add_text(x, METADATA[x])
im.save(f, "png", pnginfo=meta)

im2 = Image.open(f)
print im2.info

rawDescription: Can matplotlib add metadata to saved figures?


code:
def to_num(a):
    return map(str, a)

print to_num([1, 2, 3, 4])

rawDescription: Python integers to strings

description: Python integers to strings


code:
import Tkinter
import time

start = None
stop = None

key_watcher = Tkinter.Tk()

word_entry_label = Tkinter.Label(key_watcher, text="Type the required word")
word_entry_label.pack(side=Tkinter.LEFT)

word_entry_box = Tkinter.Entry(key_watcher)
word_entry_box.pack(side=Tkinter.LEFT)

word_repeat_label = Tkinter.Label(key_watcher,
                           text="Type the same to calculate the time")

word_repeat_label.pack(side=Tkinter.LEFT)

word_repeat_box = Tkinter.Entry(key_watcher)
word_repeat_box.pack(side=Tkinter.RIGHT)

word_entry_box.focus()

def pressed(keyevent):
  # print keyevent  #Left this in for debugging, you can see the key press.
  # start = time.time()  #start time will be reset every time this is called.
  first_word = word_entry_box.get()
  first_word_size = len(first_word)
  first_letter_list = tuple(first_word)
  first_word_first_letter = str(first_letter_list[0])
  first_word_last_letter = str(first_letter_list[-1])

  repeat_word = word_repeat_box.get()
  repeat_word_size = len(repeat_word)

  if repeat_word_size > 0:
      repeat_letter_list = tuple(repeat_word)
      repeat_word_first_letter = str(repeat_letter_list[0])
      repeat_word_last_letter = str(repeat_letter_list[-1])

  # Lets see whats happening on each press:
  print "Pressed:", keyevent.char
  print "First word:", first_word, "size", first_word_size
  print "repeat word:", repeat_word, "size", repeat_word_size

  # now that all the things we want to look at are defined, lets logic:

  if repeat_word_size == 1:
      global start
      start = time.time()
      print "time started!", start

  if first_word_size == repeat_word_size:
      print "words are same size"

      if first_word_last_letter == repeat_word_last_letter:
          global end
          stop = time.time()
          totaltime = stop - start
          print "Total time taken", totaltime

word_repeat_box.bind("<KeyRelease>", pressed)
key_watcher.mainloop()  # mainloop() should be called last, it starts your loop

rawDescription: Calculate the time between a range of key events in Python


code:
from datetime import datetime
print datetime.now().time().strftime('%H:%M')

rawDescription: Datetime in Python, just printing out the time and formatting


code:
list = [
    ['11', ' 0', " 'MMB'", " '2 MB INTERNATIONAL'", ' NULL', ' NULL', ' 0'],
    ['12', ' 0', " '3D STRUCTURES'", " '3D STRUCTURES'", ' NULL', ' NULL', ' 0'],
    ['13', ' 0', " '2 STRUCTURES'", " '2D STRUCTURES'", ' NULL', ' NULL', ' 0']]

for elem in list:
    print 'INSERT INTO \'Tbl_ABS\' VALUES (%s, %s, %s, %s, %s, %s, %s)' % tuple(elem)

rawDescription: Format Python List to SQL script?

description: Format Python List to SQL script


code:
#! /usr/bin/env python
import cgi, cgitb
cgitb.enable()

print "Content-Type: text/html\n"
i = cgi.FieldStorage()
if i.has_key("s"):
    if i["s"].value=="bow": print "Yeeeeey!!!! I got 'bow'!!!
"
    else: print "Woops! I got", i["s"].value, "instead of 'bow'
"
else: print "Argument 's' not present!
"
print "All received arguments:"
for x in i.keys(): print x, "
"

rawDescription: how to call python command from html page?

description: Call python command from html page


code:
import xml.etree.ElementTree as ET

xmlfile = ET.parse('file.xml')
a = xmlfile.getroot()

f = ET.Element('f')
g = ET.SubElement(f,'g')

f.tail = "\n    "
f.text = "\n        "
g.tail = "\n    "

a.insert(1, f)

print ET.tostring(a)

rawDescription: Formatting inserted elements using python xml.etree module, to include new lines


code:
import urllib2
f = urllib2.urlopen('http://facebook.com/')
print f.read()

rawDescription: Accessing Facebook from Python

description: Accessing Facebook from Python


code: print [x[0] != x[1] for x in zip(*d['Drd2'])]

rawDescription: How do Python's any and all functions work?


code:
s= 'Hello, World!'
codeList = list()
for c in s:
    codeList.append(ord(c))

print codeList

if len(codeList)%2 > 0:
    codeList.append(0)

finalList = list()
for d in range(0,len(codeList)-1, 2):
    finalList.append(codeList[d]*256+codeList[d+1])

print finalList

rawDescription: ascii string to sequence of 16-bit values

description: Ascii string to sequence of 16-bit values


code:
my_list = sorted(my_list)
print [a for a,b in zip(my_list[::2],my_list[1::2]) if a == b]

rawDescription: How to get all seperate all equal pairs from a list in python

description: Get all seperate all equal pairs from a list in python


code:
i = 1
def y(i=i): print i

i = 2
y()

rawDescription: How to get a closure to refer to the value that a variable had at the time of its definition

description: Get a closure to refer to the value that a variable had at the time of its definition


code:
def most_common(L):
  groups = itertools.groupby(sorted(L))
  def _auxfun((item, iterable)):
    return len(list(iterable)), -L.index(item)
  return max(groups, key=_auxfun)[0]

rawDescription: Python most common element in a list

description: Python most common element in a list


code:
def __enter__(self):
    print 'Enter the function'
    return self

rawDescription: Proxy pattern in Python

description: Proxy pattern in Python


rawDescription: Python regular expression issues

description: Python regular expression issues


code:
import re

numeric_tail = re.compile('_C\d*$')

for item in mylist:
    if not numeric_tail.search(item):
        print item

rawDescription: print item if it does not ends with a given pattern python

description: Print item if it does not ends with a given pattern python


code:
columns = header[1:]
print columns
['Age' 'Income' 'Deductions' 'Hours' 'Adjustment' 'Adjusted'
 'Employment_Consultant' 'Employment_PSFederal' 'Employment_PSLocal'
 'Employment_PSState' 'Employment_Private' 'Employment_SelfEmp'
 'Employment_Unemployed' 'Employment_Volunteer' 'Education_Associate'
 'Education_Bachelor' 'Education_College' 'Education_Doctorate'
 'Education_HSgrad' 'Education_Master' 'Education_Preschool'
 'Education_Professional' 'Education_Vocational' 'Education_Yr10'
 'Education_Yr11' 'Education_Yr12' 'Education_Yr5t6' 'Education_Yr7t8'
 'Education_Yr9' 'Marital_Absent' 'Marital_Divorced' 'Marital_Married'
 'Marital_Married-spouse-absent' 'Marital_Unmarried' 'Marital_Widowed'
 'Occupation_Cleaner' 'Occupation_Clerical' 'Occupation_Executive'
 'Occupation_Farming' 'Occupation_Machinist' 'Occupation_Professional'
 'Occupation_Repair' 'Occupation_Sales' 'Occupation_Service'
 'Occupation_Support' 'Occupation_Transport' 'Sex_Female' 'Sex_Male'
 'Accounts_Cuba' 'Accounts_England' 'Accounts_Germany' 'Accounts_India'
 'Accounts_Indonesia' 'Accounts_Iran' 'Accounts_Ireland' 'Accounts_Jamaica'
 'Accounts_Malaysia' 'Accounts_Mexico' 'Accounts_Philippines'
 'Accounts_Portugal' 'Accounts_UnitedStates' 'Accounts_Vietnam']

#if you need filter df by columns
df = df[columns]

rawDescription: Python pandas dataframe- remove columns from header


code:
import json
import re

class MySet:
    def __init__(self, *args):
        self._set = set(*args)

    def __contains__(self, x):
        return x in self._set

    def __repr__(self):
        return str(self)

    def __str__(self):
        return '{' + ', '.join((str(x) for x in self._set)) + '}'

dictat = {}
dicvalue = {}

def parse_declaration(valinfo):
    tree = valinfo['declared-variable']
    re.match ("x", valinfo['declared-variable'])
    value = parse_rvalue(valinfo['value'])
    if valinfo['declared-variable'] not in dictat.keys():
        dictat.update({valinfo['declared-variable']:(value)})
    dicvalue.update({tree: (value)})
    return ('let ',tree ,value)

def _rv_parse_apply_function(valinfo):
    assert valinfo['operator'] == 'apply-function'
    args = [parse_rvalue(a) for a in valinfo['arguments']]
    return "apply_function(" + ', '.join((str(a) for a in args)) + ")"

def _rv_parse_equal(valinfo):
    assert valinfo['operator']=='equal'
    args = [parse_rvalue(a) for a in valinfo['arguments']]
    return int(args[0] == args[1])

def _rv_parse_is_function(valinfo):
    assert valinfo['operator'] == 'is-function'
    args = [parse_rvalue(a) for a in valinfo['arguments']]
    return "is_function(" + ', '.join((str(a) for a in args)) + ")"

def _rv_parse_set(valinfo):
    assert valinfo['operator'] == 'set'
    args = [parse_rvalue(a) for a in valinfo['arguments']]
    try:
        #return set(args)
        return MySet(args)
    except:
        return args

def _rv_parse_tuple(valinfo):
    assert valinfo['operator']== 'tuple'
    args = [parse_rvalue(b) for b in valinfo['arguments']]
    return (tuple(x for x in args))

def _rv_parse_member(valinfo):
    assert valinfo['operator']=='member'
    args = [parse_rvalue(a) for a in valinfo['arguments']]
    return int(args[0] in args[1])

_rv_parser = {
    "apply-function": _rv_parse_apply_function,
    "equal":          _rv_parse_equal,
    "is-function":    _rv_parse_is_function,
    "set":            _rv_parse_set,
    "tuple":          _rv_parse_tuple,
    "member":         _rv_parse_member,
}

def parse_rvalue(valinfo):
#    try:
        if type(valinfo) is int:
            return valinfo
        elif type(valinfo) is set:
            return valinfo
        elif 'operator' in valinfo:
            opfunc = _rv_parser[valinfo['operator']]
            return opfunc(valinfo)
        elif 'variable' in valinfo:
            if valinfo['variable'] not in dictat.keys():
                return 'undefined'
            if valinfo['variable'] in dictat.keys():
                return dictat[valinfo['variable']]
#    except TypeError:
#        return ('be ', valinfo)

def parse_json(data):
    declaration_list = data['declaration-list']
    for i in declaration_list:
        parse_declaration(i)

    for i in sorted(dicvalue, key=lambda s: int(s[1:])):
        if i is not None:
            temp = str(dicvalue[i])
            print "let", i, "be", temp

if __name__ == "__main__":
    jsoninput = open("input.json").read()
    data = json.loads(jsoninput)
    parse_json(data)

rawDescription: Refactoring Python

description: Refactoring Python


code: print repr([s]).decode('string-escape')

rawDescription: Different encodings used in in "print s" vs "print [s]"?


code:
import nltk
from nltk.collocations import *
from nltk.tokenize import word_tokenize

text = "this is a foo bar bar black sheep  foo bar bar black sheep foo bar bar black sheep shep bar bar black sentence"

trigram_measures = nltk.collocations.TrigramAssocMeasures()
finder = TrigramCollocationFinder.from_words(word_tokenize(text))

for i in finder.score_ngrams(trigram_measures.pmi):
    print i

rawDescription: How to get PMI scores for trigrams with NLTK Collocations? python

description: Get PMI scores for trigrams with NLTK Collocations? python


code:
import pandas as pd

# some sample data...
rows = [('XD59876','KEN','height','5.9'),
        ('XD59876','KEN','weight','0.09'),
        ('XD59876','KEN','o2_sat','2'),
        ('FC00187 ','ROW','height','5.11')]
df = pd.DataFrame(rows, columns=['Key','Facility','Measurement','Value'])

# move everything but Value to the index
df.set_index(['Key', 'Facility', 'Measurement'], inplace=True)
# convert the Measurement index to column labels
df = df.unstack('Measurement')
# get rid of 'Measurement' label in the columns index
df.columns = df.columns.droplevel()
# get rid of Value label
df.columns.name = ''
# make Key and Facility regular columns again
df.reset_index(inplace=True)

print df

rawDescription: Split Data From One Column Into Separate Columns Based On Value


code:
for h2 in soup.find_all('h2'):
    n = h2.next_element
    if n.name == 'a':  print n

rawDescription: strip away html tags from extracted links

description: Strip away html tags from extracted links


code:
from ast import literal_eval
result = []
for item in data:
    temp = ""
    try:
        temp = literal_eval(item)
    except (SyntaxError, ValueError):
        pass
    if isinstance(temp, float):
        result.append(item)
print result
# ['31.8000']

rawDescription: How to know index of a decimal value in a python list

description: Know index of a decimal value in a python list


code:
if isIdentifierPresent == False:
    print "\nNOTICE: IDENTIFIERS OBJECT \""+identifier+"\" NOT LISTED IN TABLE"
    raise noIdentifier("<Optional message>")

rawDescription: Exit a Python Program (From a Function) with a Successful Run Result


code: print ', '.join(sorted(availletters))

rawDescription: letter/word guessing game in python

description: Letter/word guessing game in python


code:
for strong_tag in soup.find_all('strong'):
    print strong_tag.text, strong_tag.next_sibling

rawDescription: Using BeautifulSoup Extract Text without Tags


code:
def foo():
    foo.counter += 1
    print "Counter is %d" % foo.counter
foo.counter = 0

rawDescription: What is the Python equivalent of static variables inside a function?


code:
import csv
import re

tgt=['FirstResidue', 'SecondResidue', 'ThirdResidue']

with open(file) as f:
    reader=csv.reader(f)
    header=next(reader)
    for row in reader:
        di={k:v for k, v in zip(header, row)}
        if any(re.search(r'[A-Za-z]$', s) for s in [di[x] for x in tgt]):
            continue
        print row

rawDescription: Remove rows from a csv file where some column matches a specific regex


code:
from multiprocessing import Process, Queue
class Processor(Process):

    def __init__(self, queue, idx):
        super(Processor, self).__init__()
        self.queue = queue
        self.idx = idx

    def return_name(self):
        ## NOTE: self.name is an attribute of multiprocessing.Process
        return "Process idx=%s is called '%s'" % (self.idx, self.name)

    def run(self):
        self.queue.put(self.return_name())

## Create a list to hold running Processor objects
processes = list()

if __name__ == "__main__":

    q = Queue()
    for i in range(0,5):
        p=Processor(queue=q, idx=i)
        processes.append(p)
        p.start()
    for proc in processes:
        proc.join()
        ## NOTE: You cannot depend on the results to queue / dequeue in the
        ## same order
        print "RESULT: %s" % q.get()

description: Python subclassing multiprocessing.Process


code:
print "hello world" + str(i)
sys.stdout.flush()

rawDescription: Python: subprocess32 process.stdout.readline() waiting time


code:
from collections import defaultdict

mydict = defaultdict(list)
list_of_names = ['aaron', 'boo', 'charlie']
for name in list_of_names:
    if  'a' in name:
        mydict['has_a'].append(name)
print mydict['has_a']

rawDescription: How do I create a list as a dictionary entry for a specific key in Python?

description: Create a list as a dictionary entry for a specific key in Python


code:
N = 4

# enumerate all derangements for testing
import itertools
counter = {}
for p in itertools.permutations(range(N)):
    if all(p[i] != i for i in p):
        counter[p] = 0

# make M probes for each derangement
M = 5000
for _ in range(M*len(counter)):
    # generate a random derangement
    p = random_derangement(N)
    # is it really?
    assert p in counter
    # ok, record it
    counter[p] += 1

# the distribution looks uniform
for p, c in sorted(counter.items()):
    print p, c

rawDescription: Generate a random derangement of a list

description: Generate a random derangement of a list


code:
class foo(object):
    allowedattrs = ['eric', 'john', 'michael']

    def __init__(self):
        self.eric = 0
        self.john = 0
        self.michael = 0
        self.switchdict = {'Eric':self.eric, 'John':self.john, 'Michael':self.michael}

    def update(self, whattoupdate, value):
        key = whattoupdate.lower()
        if key not in self.allowedattrs:
            raise AttributeError(whattoupdate)
        setattr(self, key, getattr(self, key) + value)

f = foo()
f.update('john', 5)
f.update('john', 4)
print f.john

rawDescription: Use a dict as a switch to update class attributes - how to insert them as references?


code:
import time

from nltk.corpus import brown
from nltk import sent_tokenize, word_tokenize, pos_tag
from nltk import pos_tag_sents

# Load brown corpus
start = time.time()
brown_corpus = brown.raw()
loading_time = time.time() - start
print "Loading brown corpus took",  loading_time

# Sentence tokenizing corpus
start = time.time()
brown_sents = sent_tokenize(brown_corpus)
sent_time = time.time() - start
print "Sentence tokenizing corpus took", sent_time

# Word tokenizing corpus
start = time.time()
brown_words = [word_tokenize(i) for i in brown_sents]
word_time = time.time() - start
print "Word tokenizing corpus took", word_time

# Loading, sent_tokenize, word_tokenize all together.
start = time.time()
brown_words = [word_tokenize(s) for s in sent_tokenize(brown.raw())]
tokenize_time = time.time() - start
print "Loading and tokenizing corpus took", tokenize_time

# POS tagging one sentence at a time took.
start = time.time()
brown_tagged = [pos_tag(word_tokenize(s)) for s in sent_tokenize(brown.raw())]
tagging_time = time.time() - start
print "Tagging sentence by sentence took", tagging_time

# Using batch_pos_tag.
start = time.time()
brown_tagged = pos_tag_sents([word_tokenize(s) for s in sent_tokenize(brown.raw())])
tagging_time = time.time() - start
print "Tagging sentences by batch took", tagging_time

rawDescription: How to make POS n-grams more effective?

description: Make POS n-grams more effective


code:
from xml.etree import ElementTree as ET
from xml.dom import minidom

# Assume that we have an existing XML document with one "data" child
doc = ET.parse("file_notes.xml")
root = doc.getroot()

# Create 2 new "data" elements
data1 = ET.Element("data", {"a_version": "something_v001.0002.ma",
                            "b_user": "You",
                            "c_comment": "minor save"})
data2 = ET.Element("data", {"a_version": "something_v001.0003.ma",
                            "b_user": "Them",
                            "c_comment": "major save"})

# Append the new "data" elements to the root element of the XML document
root.append(data1)
root.append(data2)

# Now we have a new well-formed XML document. It is not very nicely formatted...
out = ET.tostring(root)

# ...so we'll use minidom to make the output a little prettier
dom = minidom.parseString(out)
print dom.toprettyxml()

rawDescription: Python: Appending children to an already created XML file's root using XML DOM


code:
size = int(input("size? "))
i = int(input("i? "))
j = int(input("j? "))

for i_ in range(size):
    row = []
    for j_ in range(size):
        if i_ >= i and j_ >= j:
            row.append("2")
        elif i_ < i:
            row.append("1")
        else:
            row.append("3")

    print " ".join(row)
    if i_ >= i:
        j += 1

rawDescription: How to assign values for i, j in a certain range within a matrix?

description: Assign values for i, j in a certain range within a matrix


code:
import clr
from System import Environment
print Environment.CurrentDirectory

rawDescription: C#, IronPython - import(?) from a non-static class


code:
#!/usr/bin/env python

import multiprocessing
import scipy
import scipy.misc
import scipy.ndimage

class Processor:
    def __init__(self,threshold):
        self._threshold=threshold

    def __call__(self,filename):
        im = scipy.misc.imread(filename)
        label,n = scipy.ndimage.label(im > self._threshold)
        return n

def main():
    scipy.misc.imsave("lena.png", scipy.misc.lena())
    files = ['lena.png'] * 100

    proc=Processor(128)
    pool=multiprocessing.Pool()
    results=pool.map(proc,files)

    print results

if __name__ == "__main__":
    main()

rawDescription: Asynchronously read and process an image in python


code:
from StringIO import StringIO

RAW_RESPONSE = """\
Port    Name               Status       Vlan       Duplex Speed Type
Fa0                        connected    1          a-full   a-100 10/100BaseTX
Fa1                        notconnect   1            auto    auto 10/100BaseTX
Fa2                        connected    1          a-full   a-100 10/100BaseTX
Fa3                        notconnect   313          auto    auto 10/100BaseTX
Fa4                        notconnect   1            auto    auto 10/100BaseTX
Fa5                        notconnect   1            auto    auto 10/100BaseTX
Fa6                        connected    1          a-full   a-100 10/100BaseTX
Fa7                        connected    1          a-full   a-100 10/100BaseTX
"""

def count_notconnected(response):
    counter = 0
    for line in response:
        if 'notconnect' in line:
            counter += 1
    return counter

response = StringIO(RAW_RESPONSE)
print count_notconnected(response)

rawDescription: Python - Trying to count instances of a string in SSH std.out


code:
def dump(obj, level=0):
   for attr in dir(obj):
      val = getattr(obj, a)
      if isinstance(val, (int, float, str, unicode, list, dict, set)):
           print level*' ', val
      else:
           dump(val, level=level+1)

rawDescription: Recursively dump an object

description: Recursively dump an object


code:
from pyparsing import oneOf, lineno

sample = """
<<Lot of stuff>>
Example2
<<More stuff>>
Example1
<<Stuff>>"""

expr = oneOf("Example1 Example2")

for toks, start, end in expr.scanString(sample):
    print toks
    print "starts at line", lineno(start, sample)
    print "ends at line", lineno(end, sample)
    print

rawDescription: Skip to first possibility in text with pyparsing


code:
from threading import Thread
from socket import SHUT_RDWR

def client(sock):
    while True:
        data = sock.recv(2048)
        if not data:
            break
        print data
    try:
        sock.shutdown(SHUT_RDWR)
        sock.close()
    except:
        pass

def server():
    while True:
        c, addr = s.accept()
        print 'Got connection from', addr
        c.send('Hi blork...')
        t = Thread(target=client, args=(c,))
        t.start()

t = Thread(target=server)
t.start()

rawDescription: Socket Programming with python

description: Socket Programming with python


code:
x = 1;
class Point:
    global x
    x = 2
print x # will print 2

rawDescription: Resetting variables

description: Resetting variables


code:
from Tkinter import *

root = Tk()

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

def callback(event):
    frame.focus_set()
    print "clicked at", event.x, event.y

frame = Frame(root, width=100, height=100)
frame.bind("<Key>", key)
frame.bind("<Button-1>", callback)
frame.pack()

root.mainloop()

rawDescription: Keyboard shortcuts with tkinter in Python 3


code:
import lxml.etree as ET
createCase=root.find('.//cre:createCase',namespaces=root.nsmap)
print ET.tostring(createCase, pretty_print=True)

rawDescription: Print Soap Body data using lxml

description: Print Soap Body data using lxml


code:
import sys
txt = open('1.txt','r')
a = []
for eachLine in txt:
    a.append(eachLine)
import re
pattern = re.compile('\d{2}:\d{2}:\d{2}')
for i in xrange(len(a)):
    match = pattern.search(a[i])
    print match.group()
#print a

rawDescription: Regular expression syntax in python

description: Regular expression syntax in python


code:
from lxml import html
from urlparse import urlparse
doc = html.fromstring(html_data)
links = doc.cssselect("a[href]")
domains = set([])
for link in links:
    href=link.attrib['href']
    parsed=urlparse(href)
    domains.add(parsed.netloc)
print domains

rawDescription: Extract domain from body of email

description: Extract domain from body of email


code:
def phonemes(word, explain=False):
    # rule engines should always be able to explain their results ;-)
    if explain:
        print "word  :", word

    result = " %s " % word.upper()  # add space around word to give the rules containing spaces something to work with
    step = 0

    # iterate over all the interesting tuples
    for rule, phoneme, ruletxt in rules:
        # for each rule, tmp is the string where all matches for `rule` have been replaced by `phoneme`
        tmp = match_and_replace(result, rule, phoneme)
        if explain and tmp != result:
            step += 1
            print 'step %d: %r ---> %r  [rule: %r (%r)]' % (
                step, result, tmp, ruletxt, rule
            )
        result = tmp

    # remove artifacts
    res, _count = re.subn(r'-+', '-', result.replace(' ', '').strip('-'))
    if explain:
        print "result:", res
        print
    return res

rawDescription: Python pattern matching of rules to parse text to phonemes


code:
class M3(M1, M2):
    def __new__(meta, name, bases, atts):
        print "M3 called for " + name
        return super(M3, meta).__new__(meta, name, bases, atts)
class C3(C1, C2):
    __metaclass__ = M3
type(C3)

rawDescription: Customary To Inherit Metaclasses From type?


code:
class B(object):
    def rename(self, name):
        self.name = name

class A(object):
    def say(self):
        print 'Hello', self.name

a, b = A(), B()
a.__dict__ = b.__dict__
b.rename('john')
a.say()
a.rename('mary')
b.say()

rawDescription: Universally create Derived class from Base in python


code:
import re

# Goal:  '717 N 2ND ST, MANKATO, MN 56001',
# Goal:  '717 N 2ND ST, MANKATO, MN, 56001',
# Goal:  '717 N 2ND ST NE, MANKATO, MN, 56001',
# Goal:  '717 N 2ND, MANKATO, MN, 56001',
regex = r'''
    (?x)            # verbose regular expression
    (?i)            # ignore case
    (?P<HouseNumber>\d+)\s+         # Matches '717 '
    (?P<Direction>[news])\s+        # Matches 'N '
    (?P<StreetName>\w+)\s*          # Matches '2ND ', with optional trailing space
    (?P<StreetDesignator>\w*)\s*    # Optionally Matches 'ST '
    (?P<StreetDirection>[news]*)\s* # Optionally Matches 'NE'
    ,\s+                            # Force a comma after the street
    (?P<TownName>.*),\s+            # Matches 'MANKATO, '
    (?P<State>[A-Z]{2}),?\s+        # Matches 'MN ' and 'MN, '
    (?P<ZIP>\d{5})                  # Matches '56001'
'''

regex = re.compile(regex)

for item in (
    '717 N 2ND ST, MANKATO, MN 56001',
    '717 N 2ND ST, MANKATO, MN, 56001',
    '717 N 2ND, Makata, 56001',   # Should reject this one
    '1234 N D AVE, East Boston, MA, 02134',
    '717 N 2ND ST NE, MANKATO, MN, 56001',
    '717 N 2ND, MANKATO, MN, 56001',
    ):
    match = regex.match(item)
    print item
    if match:
        print "    House is on {Direction} side of {TownName}".format(**match.groupdict())
    else:
        print "    invalid entry"

rawDescription: Python make sure address matches specific format


code:
class TextToNumbers():
    def __init__(self, number):
        self.text = str(number)
        self.chunks = TextToNumbers.parse_text_to_chunks(self.text)
        print self.chunks

    @classmethod
    def parse_text_to_chunks(cls, text_to_parse):
    # 1st parameter passed is the current CLASS on which this method is called
        cls.var1 = text_to_parse[1:]
        return cls.var1

TextToNumbers(123)

rawDescription: Python: How to define a variable in an __init__ function with a class method?


code:
from lxml import etree

# Create a root element with 3 children
root = etree.Element( "root" )
root.append( etree.Element( "child1" ) )
child2 = etree.SubElement( root, "child2" )
child2.text = 'CHILD2'
child3 = etree.SubElement( root, "child3" )
child3.text = 'CHILD3'

# Print the "ugly" XML (no whitespace)
print "\n--- UGLY ---"
print etree.tostring(root)

# Print the "pretty" XML
print "\n--- PRETTY ---"
pp = etree.tostring(root, pretty_print=True)
print pp

# Parse the pretty XML
tree = etree.fromstring(pp)

# remove last child
tree.remove(tree[2])

print "--- WITHOUT LAST CHILD PART 1 ---"
print etree.tostring(tree, pretty_print=True)

# Parse the pretty XML once again with parser option 'remove_blank_text=True'
tree = etree.fromstring(pp, etree.XMLParser(remove_blank_text=True))

# remove last child
tree.remove(tree[2])

print "--- WITHOUT LAST CHILD PART 2 ---"
print etree.tostring(tree, pretty_print=True)

rawDescription: Unwanted whitespace left after having removed element from pretty-printed XML


code:
audio = audioread.audio_open('/path/to/mp3')
print f.channels, f.samplerate, f.duration

rawDescription: python ringtone maker : how to split files

description: Python ringtone maker : how to split files


code:
for line in fileobj:
    print line

rawDescription: What is the difference between the buffering argument to open() and the hardcoded readahead buffer size used when iterating through a file?


code:
li1=[{'shape': 'square', 'color': 'red', 'priority': 2},
{'shape': 'circle', 'color': 'blue', 'priority': 2},
{'shape': 'triangle', 'color': 'green', 'priority': 2}]

li2=[{'shape': 'square', 'color': 'green', 'priority': 3},
{'shape': 'circle', 'color': 'red', 'priority': 1}]

res={}
for di in sorted(li1+li2, key=lambda d: d['priority']):
    res[di['shape']]=di

print res.values()

rawDescription: Merging a list of dictionaries in python based on one key/value pair?


code:
import re
prix=sheet.cell(r,3).value
prix = str(prix)
prix = re.sub('[^0-9.]+', '', prix )
print float(prix)

rawDescription: Import Data from Excel to Mysql Python

description: Import Data from Excel to Mysql Python


code:
from operator import itemgetter

data = """
General Motors,Chevrolet,K1500 TAHOE 4WD,18,2900,Standard SUV 4WD
General Motors,Chevrolet,TRAVERSE AWD,19,2750,Standard SUV 4WD
Chrysler Group LLC,Dodge,Durango AWD,19,2750,Standard SUV 4WD
Chrysler Group LLC,Dodge,Durango AWD,16,3400,Standard SUV 4WD
Ford Motor Company,Ford,Expedition 4WD,17,3100,Standard SUV 4WD
Ford Motor Company,Ford,EXPLORER AWD,19,2750,Standard SUV 4WD
"""

data_lines = [x.split(",") for x in data.splitlines()[1:]]

print sorted(data_lines, key=itemgetter(3))

# Optionally join back to strings:
map(",".join, sorted(data_lines, key=itemgetter(3)))

rawDescription: Sort nested list for element in nested list?


code:
def output_memory():
    d = defaultdict(int)
    for o in gc.get_objects():
        name = type(o).__name__
        d[name] += 1

    items = d.items()
    items.sort(key=lambda x:x[1])
    for key, value in items:
        print key, value

rawDescription: Dramatic memory leak in wxpython application


code:
import numpy

def F(x, a, b):
    return numpy.power(x, a+1.0) - b

N = 1000000

a = numpy.random.rand(N)
b = numpy.random.rand(N)

x0 = numpy.zeros(N)
x1 = numpy.ones(N) * 1000.0

max_step = 100
for step in range(max_step):
    x_mid = (x0 + x1)/2.0
    F0 = F(x0, a, b)
    F1 = F(x1, a, b)
    F_mid = F(x_mid, a, b)
    x0 = numpy.where( numpy.sign(F_mid) == numpy.sign(F0), x_mid, x0 )
    x1 = numpy.where( numpy.sign(F_mid) == numpy.sign(F1), x_mid, x1 )
    error_max = numpy.amax(numpy.abs(x1 - x0))
    print "step=%d error max=%f" % (step, error_max)
    if error_max < 1e-6: break

rawDescription: Finding the roots of a large number of functions with one variable


code:
def get_unique_scene_names (*nodeTypes):
    if not nodeTypes:
        nodeTypes = ('transform',)
    results = {}
    for longname in cmds.ls(type = nodeTypes, l=True):
        shortname = longname.rpartition("|")[-1]
        if not shortname in results:
            results[shortname] = set()
        results[shortname].add(longname)
    return results

def add_unique_name(item, node_dict):
    shortname = item.rpartition("|")[-1]
    if shortname in node_dict:
        node_dict[shortname].add(item)
    else:
        node_dict[shortname] = set([item])

def remove_unique_name(item, node_dict):
    shortname = item.rpartition("|")[-1]
    existing  = node_dict.get(shortname, [])
    if item in existing:
        existing.remove(item)

def apply_convention(node, new_name, node_dict):
    if not new_name in node_dict:
        renamed_item = cmds.ls(cmds.rename(node, new_name), l=True)[0]
        remove_unique_name(node, node_dict)
        add_unique_name ( renamed_item, node_dict)
        return renamed_item
    else:
        for n in range(99999):
            possible_name = new_name + str(n + 1)
            if not possible_name in node_dict:
                renamed_item =  cmds.ls(cmds.rename(node, possible_name), l=True)[0]
                add_unique_name(renamed_item, node_dict)
                return renamed_item
        raise RuntimeError, "Too many duplicate names"

rawDescription: Iterating over a large unicode list taking a long time?


code:
item = {}
item['foo'] = ["blah"]
garble = ["blah2"]
item['foo'] += garble
print item

rawDescription: Python add to a list that is a value of a key


code:
class Foo(object):
    def __init__(self, other=None):
        # make a circular reference
        self.link = other
        if other is not None:
            other.link = self

    def __del__(self):
        print "deling", self

if __name__ == '__main__':
    import gc
    gc.disable()
    f = Foo(Foo())
    print "before"
    del f # nothing gets deleted here
    print "after"
    gc.collect()
    print gc.garbage # The GC knows the two Foos are garbage, but won't delete
                     # them because they have a __del__ method
    print "after gc"
    # break up the cycle and delete the reference from gc.garbage
    del gc.garbage[0].link, gc.garbage[:]
    print "done"

rawDescription: How to force deletion of a python object?

description: Force deletion of a python object


code:
from re import sub

html = '
I
\

 have a question
\

\

The
\

answer is
\

not there
\

\

Please
\

Help
'

print [sub("\s+", " ", x).strip() for x in sub("<.*?>", " ", html).split(" ")]

rawDescription: how to extract all the data between

description: Extract all the data between


code:
a = range(10)
# Pick every other element in a starting from a[1]
b = a[1::2]
print b
[1, 3, 5, 7, 9]

rawDescription: good practice for string.partition in python

description: Good practice for string.partition in python


code:
print '''
dog
cat
'''.strip()

rawDescription: Python here document without newlines at top and bottom


code:
corr = 205
score = 100 * (corr / 225)
print score

rawDescription: python simple percentage calculation returning 0

description: Python simple percentage calculation returning 0


code:
def addplayers(alist):
    players = []
    for item in alist:
        # NOTE reuse the name item is not a good idea here. You can use player instead.
        item = Player("%s" % item)
        players.append(item)
        print "%s has %s HP of life and feels pretty much alive" %  (item.name, item.hitpoints, )
    return players

rawDescription: Function adding objects to a class through a list - calling objects


code:
# make some random points and weights
def setup(k=2, m=100, n=300):
    return np.random.randn(k,m), np.random.randn(k,n),np.random.randn(k,m)

a, b, w = setup()
d0 = slow_wdist(a, b, w)
d1 = fast_wdist(a, b, w)

print np.allclose(d0, d1)
# True

rawDescription: Fast weighted euclidean distance between points in arrays


code:
for friend in friends:
  print "%s - %s" % (friend["message"], friend["phone"])

rawDescription: Named dictionary in python

description: Named dictionary in python


code:
import re

data='''\
81728..81500    Gene 22
81500..81856    Gene 17
complement(82256..84292)    Gene 75
812..815    Gene 3 num
complement(822..842)    Gene compliment 3 num75
811..815    Gene 3 num
'''

def alpha_num_sort(li):
    def convert(s):
        return int(s) if s.isdigit() else s

    def key_func(key):
        return tuple(convert(c) for c in re.split('([0-9]+)', key))

    return sorted(li, key = key_func)

print '\n'.join(alpha_num_sort(data.splitlines()))

rawDescription: order all row according to contents of a row

description: Order all row according to contents of a row


code:
import re
with open('data.txt') as inf:
    salary = 0
    for line in inf:
        line = line.split('=')
        line[0] = line[0].strip()
        if line[0] == 'employee':
            employee = re.sub(r'[]\[\' ]','', line[1].strip()).split(',')
        elif line[0] == 'salary':
            salary = float(line[1])
        elif line[0] == 'managers':
            managers = re.sub(r'[]\[\' ]','', line[1].strip()).split(',')

print employee
print salary
print managers

rawDescription: Search for a variable in a file and get its value with python


code:
class MyClass:
    def __init__(self, value):
        self.value = value
    def __repr__(self):
        return 'MyClass({0.value})'.format(self)
    def delta(self, other):
        return abs(self.value - other.value)

def foo(a_list, key):
    return [key(a, b) for a, b in zip(a_list, a_list[1:])]

my_list = [MyClass(1), MyClass(10), MyClass(100)]
print foo(my_list, key=lambda x, y: abs(x.value - y.value)) # Using lambda
print foo(my_list, key=MyClass.delta) # Using unbound method

rawDescription: is there a way to give class method as a key parameter (sort/min/..) in python?

description: Is there a way to give class method as a key parameter (sort/min/..) in python


code:
for key in my_cool_dict:
    print '{0} = {1}'.format(key, my_cool_dict[key])

rawDescription: Create tuples in Python from an XML String/File


code:
# This is the function you want.

def roundPartial (value, resolution):
    return round (value / resolution) * resolution

# All these are just test cases, the first two being your own test data.

print "Rounding to fiftieths"
print roundPartial (0.405, 0.02)
print roundPartial (0.412, 0.02)

print "Rounding to quarters"
print roundPartial (1.38, 0.25)
print roundPartial (1.12, 0.25)
print roundPartial (9.24, 0.25)
print roundPartial (7.76, 0.25)

print "Rounding to hundreds"
print roundPartial (987654321, 100)

rawDescription: Round float to the nearest 2/100

description: Round float to the nearest 2/100


code:
nonalphas = ((n, i) for i, n in enumerate(shoestring) if not n.isalpha())
print '\n'.join('{} {}'.format(n, i) for n, i in nonalphas)

rawDescription: Python - Why is this function not returning the index for white space?


code:
def mapfunction((i, el)):
    return i * el

map(mapfunction, enumerate(a))

rawDescription: Can I use index information inside the map function?

description: Use index information inside the map function


code:
try:
  h = int(h)
except ValueError:
  print 'the input couldnt be converted into an integer'

rawDescription: Just an input in Python

description: Just an input in Python


code:
x = 8
y = x
x = 4
print y     # Still 8

x = "foo"
y = x
x = "bar"
print y     # Still 'foo'

x = [1,2,3]
y = x
x = [4,5,6]
print y     # Still [1,2,3]

rawDescription: Data-Binding in Python?

description: Data-Binding in Python


code:
links = [{"source":0, "target":1},
         {"source":0, "target":2},
         {"source":0, "target":3},
         {"source":1, "target":0}]

links = filter(
    lambda link: {"source":link["target"], "target":link["source"]} in links,
    links)

print links

rawDescription: does the for each loop in python based index?

description: Does the for each loop in python based index


code:
print get_section_text('Adresa:')
print get_section_text('Telefón:')
print get_section_text('Fax:')

rawDescription: Get text separated by tags / BS4

description: Get text separated by tags / BS4


code:
class Person(object):
    def __init__(self, **kw):
        self.__dict__ = kw
person = Person(name='Joe')
print person.name

rawDescription: Create Python class where the attributes is defined dynamically


code:
for tr in soup.find_all("tr"):
    print '>>>> NEW row <<<<'
    print '|'.join([x.getText() for x in tr.find_all('td')])

rawDescription: Python Data Scrapper

description: Python Data Scrapper


code:
try:
    main()
except SystemExit, err:
    if err.code == 0:
        set_success()
    raise

rawDescription: How can I register a function to be called only on *successful* exit of my Python program?

description: Register a function to be called only on *successful* exit of my Python program


code:
src='''\
int main( void )
   {
      return 0;
   }
'''

import re

for key, span in ((m.group(1), m.span(1)) for m in re.finditer(r'\b(int|main|void|return)\b', src)):
    print key, span

rawDescription: Find C Keywords inside a String with Python and Regex


code:
l = ['This', 'is', 'a', 'list']
print [x.capitalize() for x in l]
['This', 'Is', 'A', 'List']

rawDescription: Capitalize the first letter in each string in a list


code:
for k, v in [(k, v) for k, v in fnames.items() if not test_list(v)]:
    for fn in v:
        print fn  # could be os.remove(fn)

rawDescription: Python: Compare Filenames in Folder

description: Python: Compare Filenames in Folder


code:
from itertools import izip_longest
import csv

with open('test') as f:
    reader = csv.reader(f, delimiter=' ', skipinitialspace=True)
    cols = map(set, izip_longest(*reader))

print set.intersection(*cols)

rawDescription: common between all csv columns

description: Common between all csv columns


code:
from itertools import dropwhile
list1 = ['Mary','had','a','little','lamb','which','was','very','naughty']

list2 = list(dropwhile(lambda x: x!="little", list1))
list3 = list(dropwhile(lambda x: x!="very", reversed(list2)))
print list(reversed(list3))

rawDescription: Creating a smaller list from an existing list


code:
import os
import subprocess

if __name__ == "__main__":

    outfilename = "output.dat"
    os.mkfifo(outfilename,0777)

    i = []
    x = []
    xsquared = []

    writer = subprocess.Popen( "./writer" )

    with open(outfilename,'r') as fortranoutput:
        for line in fortranoutput:
            items=line.split()
            i.append(int(items[0]))
            x.append(float(items[1]))
            xsquared.append(float(items[2]))

    print "Got: i  = ", i
    print "     x  = ", x
    print "     x^2= ", xsquared

rawDescription: Call a program from Python that writes to a file - Can I avoid the IO?


code:
class Jungle6():
    def __call__(self):
        print "\nYou are east of the jungle."
        print "You can see a cave with a locked door.\n"

rawDescription: How do I make an engine to change the current area of a game in Python?

description: Make an engine to change the current area of a game in Python


code:
a = 'foo'
b = a
print b is a  #True -- They *are the same object*

rawDescription: Python: copy of a variable

description: Python: copy of a variable


code:
print "hello world"
a = 1

rawDescription: Import a python module without .py extension,


code:
from BeautifulSoup import BeautifulSoup
import re

day ='Mon'
codePat = re.compile(r'COMP\d+')

with open('timetable.txt', 'rt') as input_file:
  html = input_file.read()
  soup = BeautifulSoup(html)
  #finds correct day tag
  starttag = soup.find(text=day).parent.parent
#  print starttag
  nexttag = starttag
  row=[]
  x = 0
  #puts all td tags for that day in a list
  while x < 18:
    nexttag = nexttag.nextSibling.nextSibling
    found = codePat.search(repr(nexttag))
    if found:
      row.append(found.group(0))
    x += 1
print row

rawDescription: parsing an html table with BeautifulSoup

description: Parsing an html table with BeautifulSoup


code: print re.split("[\s,]+", data)

rawDescription: Python regex splitting on multiple whitespaces


code:
print uescapes.sub(uescape_decode, txt)
print uescapes.sub(uescape_decode, u'\\u003c? abc ?\\u003eDas Modell des Adaptiven Zyklus wurde aus vergleichenden Untersuchungen zur Dynamik von \xd6kosystemen abgeleitet.\\u003c? /abc ?\\u003e')

rawDescription: python mixed single and double unicode escape sequences

description: Python mixed single and double unicode escape sequences


code:
class Obj:
    def __init__(self, value):
        self.value = value

x = Obj(5)
y = copy.deepcopy(x)

print 'x:', x.value
print 'y:', y.value

x.value = 3

print 'x:', x.value
print 'y:', y.value

rawDescription: Python stack containing objects changing automatically


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

spf = wave.open('wavfile.wav','r')

#Extract Raw Audio from Wav File
signal = spf.readframes(-1)
signal = np.fromstring(signal, 'Int16')

#If Stereo
if spf.getnchannels() == 2:
    print 'Just mono files'
    sys.exit(0)

plt.figure(1)
plt.title('Signal Wave...')
plt.plot(signal)

rawDescription: How to plot a wav file

description: Plot a wav file


code:
records = self.browse(cr, uid, ids)
for rec in records:
     print rec.total
     print rec.otherfield

rawDescription: How can I loop and access values of fields in OpenERP?

description: Loop and access values of fields in OpenERP


code:
# add some new passes!
new_pass('Messi', 'Xavi')
new_pass('Xavi', 'Iniesta')
new_pass('Iniesta', 'Messi')
new_pass('Messi', 'Iniesta')
new_pass('Iniesta', 'Messi')

# let's see where we currently stand
print total_passes('Messi')
print total_passes('Iniesta')
print total_passes_from_p1_to_p2('Messi', 'Xavi')

rawDescription: Python Data Structure Selection

description: Python Data Structure Selection


code:
# itr is short for "iterable" and can be any sequence, iterator, or generator

def notlast(itr):
    itr = iter(itr)  # ensure we have an iterator
    prev = itr.next()
    for item in itr:
        yield prev
        prev = item

# lst is short for "list" and does not shadow the built-in list()
# 'L' is also commonly used for a random list name
lst = range(4)
for x in notlast(lst):
    print "Not last: ", x
print "Last: ", lst[-1]

rawDescription: How to treat the last element in list differently in Python?

description: Treat the last element in list differently in Python


code:
def divider(lst,n):
    lst = [float(x) for x in reversed(lst)]
    yield lst
    for i in range(2,n+1):
        lst = [x/i for x in lst]
        yield lst

for lst in divider([40, 60, 100, 240],3):
    print lst

rawDescription: loop through a list and use previous elements

description: Loop through a list and use previous elements


code:
import weakref

class Ghost(object):
    def __init__(self):
        #pass
        self.switch = {'eat':self.eat, 'sleep':self.sleep}

    def eat(self):
        pass

    def sleep(self):
        pass

ghost = Ghost()

def callback(o):
    print 'callback', o

wref = weakref.ref(ghost, callback)
print 'del ghost'
del ghost
print 'after del ghost'

rawDescription: internal reference prevents garbage collection

description: Internal reference prevents garbage collection


code:
NameRecord = collections.namedtuple("NameRecord", "id name age score1 score2 score3")

# generator from using yield
def lines_from_file(filename):
    with open(filename) as f:
        for line in f:
            yield line

# generator from generator expression
def name_records_from_lines(lines):
    return (NameRecord(*line.split()) for line in lines)

def name_records_matching_id(records, id):
    for record in records:
        if record.id == id:
            yield record

# identical to the method above for learning purposes
def name_records_matching_id_2(records, id):
    return (record for record in records if record.id == id)

id = raw_input("Your ID")
lines = lines_from_file('file.txt')
records = name_records_from_lines(lines)
matching_records = name_records_matching_id(records, id)
# Note: if your code is simple enough, you don't need to define a method:
# matching_records = (record for record in records if record.id == id)
for record in matching_records:
    print record.name, record.age, record.score1, record.score2, record.score3

rawDescription: How can i get a specific value from a key that has multiple values in it?

description: Get a specific value from a key that has multiple values in it


code:
v, _, _ = platform.mac_ver()
v = float('.'.join(v.split('.')[:2]))
print v

rawDescription: How to detect Mac OS version using Python?

description: Detect Mac OS version using Python


code:
print "hey...",
time.sleep(0.5)

rawDescription: Printing at timed intervals

description: Printing at timed intervals


code: print url

rawDescription: Sending a URL in a GET request to a Python server on Google App Engine


code:
import argparse
def quit():
    import sys
    sys.exit(1)

def perform_stuff(*args):
    print 'stuff', args

def retrive(*args):
    print 'retrieve', args

if __name__ == '__main__':
    p = argparse.ArgumentParser()
    # single letter `-d` string; use default None
    p.add_argument('-d', '--input_data')
    p.add_argument('-t', '--targets')
    p.add_argument('-i', '--input')
    p.add_argument('-o', '--output')
    opts = p.parse_args()
    print 'opts', opts

    if not any([opts.input, opts.output, opts.targets, opts.input_data]):
        p.print_usage()
        print 'press -h to see the help'
        quit()

    elif any([opts.targets,opts.input_data]):
        perform_stuff(opts.input_data, opts.targets)
        quit()

    elif any([opts.input, opts.output]):
        retrive(opts.input, opts.output)
    else:
        print 'else'

rawDescription: How to solve this argparse freeze issue?

description: Solve this argparse freeze issue


code:
from pyparsing import *

data = '(gimme [some {nested, nested [lists]}])'

opening = oneOf("( { [")
nonBracePrintables = ''.join(c for c in printables if c not in '(){}[]')
closingFor = dict(zip("({[",")}]"))
closing = Forward()
# initialize closing with an expression
closing << NoMatch()
closingStack = []
def pushClosing(t):
    closingStack.append(closing.expr)
    closing << Literal( closingFor[t[0]] )
def popClosing():
    closing << closingStack.pop()
opening.setParseAction(pushClosing)
closing.setParseAction(popClosing)

matchedNesting = nestedExpr( opening, closing, Word(alphas) | Word(nonBracePrintables) )

print matchedNesting.parseString(data).asList()

rawDescription: How can I use pyparsing to parse nested expressions that have mutiple opener/closer types?

description: Use pyparsing to parse nested expressions that have mutiple opener/closer types


code:
import regex
text = u"<Üäik>"
print regex.sub('[\p{P}\p{Sm}]+', '', text)
import string
print text.translate(dict.fromkeys(ord(c) for c in string.punctuation))

rawDescription: Strip special characters and punctuation from a unicode string


code:
number = Wrapper(Simple)

print "\nCalling wrapped 'one':"
number.one()

print "\nCalling wrapped 'two':"
number.two("2")

rawDescription: Create a wrapper class to call a pre and post function around existing functions?


code:
from collections import defaultdict
def filestat(file):
  try:
      stat = os.stat(file)
      user = pwd.getpwuid(stat[4])[0]
      group = grp.getgrgid(stat[5])[0]
      return user, file
  except OSError, e:
      print e
      return None
try:
    cores = (multiprocessing.cpu_count()*2)
except:
    cores = 8
print "Starting parallel execution with ", cores, "concurrency"
pool_get_attributes = multiprocessing.Pool(cores)
result_map = pool_get_attributes.map(filestat, files)
result = defaultdict(list)
for user,file in (r for r in result_map if r is not None):
    result[user].append(file)
pool_get_attributes.close()
pool_get_attributes.join()

rawDescription: Python Multiprocessing DictProxy append to dict of list not working


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

class simulation_tk(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()
        self.grid()

    def initialize(self):
        self.c2_low =Tkinter.StringVar()
        self.entry = Tkinter.Entry(self, textvariable = self.c2_low).grid(column=0,row=1,sticky='EW')
        self.resizable(False,False)

        button = Tkinter.Button(self,text=u"simulate",command=self.simulation)
        button.grid(column=3,row=9)

    def simulation(self):
        print self.c2_low.get()
        #code for this not included but uses all 16 entries/variable

if __name__ == "__main__":
    app = simulation_tk(None)
    app.title('Simulation')
    app.mainloop()

rawDescription: Using tkinter Entries for variables in external functions


code:
from cluster import *

data = [10.01,5.001,4.89,5.1,9.9,10.1,5.05,4.99]
cl = HierarchicalClustering(data, lambda x,y: abs(x-y))
print [mean(cluster) for cluster in cl.getlevel(1.0)]

rawDescription: sort list of floating-point numbers in groups

description: Sort list of floating-point numbers in groups


code:
from datetime import date, timedelta
days=30
d = date.today() - timedelta(days=days)
print d

rawDescription: Get Date in a particular format in python


code:
import numpy as np
if np.all(x>0 for x in np.array([-10,1,2])):
    print np.sum(x>0 for x in np.array([-10,1,2]))

rawDescription: All command in Python

description: All command in Python


code:
class Settings(dict):
    """Singleton settings class"""

    settings = {
                   'SectionA': {'a': 1, 'b': 2, 'c': 3},
                   'SectionB': {'d': 4, 'e': 5, 'f': 6}
               }

    def __getitem__(self, key): return self.settings[key]
    def __setitem__(self, key, item): self.settings[key] = item
    def __iter__(self): return iter(self.settings.keys())
    def keys(self): return self.settings.keys()

s = Settings()

for key in s:
    print key
    print s[key]

rawDescription: Python dictionary class, 'KeyError'

description: Python dictionary class, 'KeyError'


code:
import csv

from itertools import izip_longest

with open(fn1) as f1, open(fn2) as f2:
    r1=csv.reader(f1)
    r2=csv.reader(f2)
    for v1, v2 in izip_longest(r1, r2):
        print v1, v2

rawDescription: Processing two CSV files in parallel

description: Processing two CSV files in parallel


code:
import json

def parse_object(o):
    for key in o:
        if o[key] is None:
            o[key] = 'Cat'
    return o

decoder = json.JSONDecoder(object_hook=parse_object)

print decoder.decode('{"field1":null, "field2": "data!"}')
# that will print: {u'field2': u'data!', u'field1': u'Cat'}

rawDescription: Python JSONDecoder custom translation of null type


code:
from bs4 import BeautifulSoup

data = """

    H.S. AHMED ALLY

      Address : 217/7,Saleh Market,Adamjee Road,Saddar

      City : Rawalpindi

      Phone # : (92 51) 5511748, 5125396

      Fax : (92 51) 5511749

      E-mail : hsaforce@cyber.net.pk
Web :
      www.hsahmedally.com

"""

def get_field_value(soup, field):
    return soup.find('strong', text=lambda x: x.startswith(field)).next_sibling

soup = BeautifulSoup(data)
print get_field_value(soup, 'Address')
print get_field_value(soup, 'City')

rawDescription: Parsing HTML table with beautifulsoup

description: Parsing HTML table with beautifulsoup


code:
print "start command"
p = subprocess.Popen("adb pull ...",stdout = subprocess.PIPE,stderr=subprocess.PIPE)
stdout,stderr = p.communicate() # you could do p.wait() if you dont care about output
print "Command Finished!"
print stdout
print stderr

rawDescription: ADB pull completion

description: ADB pull completion


code:
import pathos
print pathos.multiprocessing.freeze_support.__doc__

rawDescription: Pathos multiprocessing can't call any package and function in the class


code:
title = "Friedrich_N\u00FCrnberg"
character = title.decode("unicode-escape")
character
print character

rawDescription: Unicode and subprocess.Popen

description: Unicode and subprocess.Popen


code:
import re
lst = ['"Some-text" {12345-ab123-cd456}', '"Some-Another-text2" {54321-ab123-cd456}]']

regexp = re.compile(r'"\s*.+-(\S+)\s*"\s+{\s*(\S+)\s*}')
for i in lst:
    line = re.match(regexp, i)
    if line:
        print line.group(1) + ", " + line.group(2)

rawDescription: How to get rightmost characters plus text between double quotes using regular expressions in Python

description: Get rightmost characters plus text between double quotes using regular expressions in Python


code:
def borda_sort(lists):
    scores = {}
    for l in lists:
        for idx, elem in enumerate(reversed(l)):
            if not elem in scores:
                scores[elem] = 0
            scores[elem] += idx
    return sorted(scores.keys(), key=lambda elem: scores[elem], reverse=True)

lists = [ ['a', 'c'], ['b', 'd', 'a'], ['b', 'a', 'c', 'd'] ]
print borda_sort(lists)
# ['b', 'a', 'c', 'd']

rawDescription: Borda’s positional ranking

description: Borda’s positional ranking


rawDescription: splitting a string into different columns in python

description: Splitting a string into different columns in python


code:
for result in perdelta(datetime.now(),
        datetime.now().replace(hour=19) + timedelta(days=1),
        timedelta(hours=8)):
    print result

rawDescription: Generate a list of datetimes between an interval


code:
import urllib
import re

url = ('http://www.epicurious.com/articlesguides/bestof/'
       'toprecipes/bestchickenrecipes/recipes/food/views/'
       'My-Favorite-Simple-Roast-Chicken-231348')

sock = urllib.urlopen(url)
ch = sock.read()
sock.close()

x = ch.find('ul class="ingredientsList">')

patingr = re.compile('
(.+?)
\n')

print patingr.findall(ch,x)

rawDescription: Python HTML parsing specific information within tags


code:
if np.count_nonzero(scores < 0):
    print 'average negative score: ', np.mean(scores[scores < 0])

rawDescription: Finding average of variable in objects python