code:
import re

parser1 = re.compile("[0-9]\\*?$")
parser3 = re.compile("\\([0-9]\\*[0-9]\\)$")
parser4 = re.compile("(\\([0-9]\\*[0-9]\\)|[0-9])\\*(\\([0-9]\\*[0-9]\\)|[0-9])$")

def validity(s):
    valid = False

    # Condition 1 and 2
    if parser1.match(s):
        return True
    # Condition 3
    if parser3.match(s):
        return True
    # Condition 4
    if parser4.match(s):
        return True

    return False

print validity('1') # Condition 1
print validity('9') # Condition 1
print validity('10') # Doesn't satisfy any of the conditions
print validity('1*') # Condition 2
print validity('4*') # Condition 2
print validity('9*') # Condition 2
print validity('10*') # Doesn't satisfy any of the conditions
print validity('(3*4)') # Condition 3
print validity('(3*9)') # Condition 3
print validity('(4*9)') # Condition 3
print validity('(10*9)') # Doesn't satisfy any of the conditions
print validity('(3*2)*(3*1)') # Condition 4
print validity('(3*2)*8') # Condition 4
print validity('(3*2)*z') # Doesn't satisfy any of the conditions

rawDescription: Validity of a string based on some conditions


code:
def hello():
   print "hello"
hello()
for x in range(10):
    if x % 2:
        print "%s is odd" % (x,)
    else:
        print "%s is even" % (x,)

rawDescription: How do I create a line-break in Terminal?

description: Create a line-break in Terminal


code:
class ConfigFile (dict):
    """
    Configuration file data
    """

    def __init__ (self, filename):
        """
        Parses config file.
        """

        from pyparsing import Suppress, Word, alphas, alphanums, nums, \
            delimitedList, restOfLine, printables, ZeroOrMore, Group, \
            Combine

        equal = Suppress ("=")
        lbrack = Suppress ("[")
        rbrack = Suppress ("]")
        delim = Suppress ("'")

        string = Word (printables, excludeChars = "'")
        identifier = Word (alphas, alphanums + '_')

        integer = Word (nums).setParseAction (lambda t: int (t[0]))
        real = Combine( Word(nums) + '.' + Word(nums) ).setParseAction (lambda t: float(t[0]))
        value = real | integer

        var_kwd = Suppress ("var")
        load_kwd = Suppress ("load")
        list_kwd = Suppress ("list")

        var_stm = Group (var_kwd + identifier + equal + value +
                         restOfLine.suppress ()).setParseAction (
                             lambda tok: tok[0].insert(len(tok[0]), 0))

        load_stm = Group (load_kwd + delim + string + delim +
                          restOfLine.suppress ()).setParseAction (
                              lambda tok: tok[0].insert(len(tok[0]), 1))

        list_stm = Group (list_kwd + identifier + equal + lbrack +
                          Group ( delimitedList (value, ",") ) +
                          rbrack + restOfLine.suppress ()).setParseAction (
                              lambda tok: tok[0].insert(len(tok[0]), 2))

        cnf_file = ZeroOrMore (var_stm | load_stm | list_stm)

        lines = cnf_file.parseFile (filename)
        self._lines = []
        for line in lines:
            self._lines.append ((line[-1], line[0]))
            if line[-1] != 1: dict.__setitem__(self, line[0], line[1])
        self.__initialized = True
        # after initialisation, setting attributes is the same as setting an item

    def __getattr__ (self, key):
        try:
            return dict.__getitem__ (self, key)
        except KeyError:
            return None

    def __setattr__ (self, key, value):
        """Maps attributes to values. Only if we are initialised"""

        # this test allows attributes to be set in the __init__ method
        if not self.__dict__.has_key ('_ConfigFile__initialized'):
            return dict.__setattr__(self, key, value)

        # any normal attributes are handled normally
        elif self.__dict__.has_key (key):
            dict.__setattr__(self, key, value)

        # takes care of including new 'load' statements
        elif key == 'load':
            if not isinstance (value, str):
                raise ValueError, "Invalid data type"
            self._lines.append ((1, value))

        # this is called when setting new attributes after __init__
        else:
            if not isinstance (value, int) and \
                not isinstance (value, float) and \
                not isinstance (value, list):
                raise ValueError, "Invalid data type"

            if dict.has_key (self, key):
                if type(dict.__getitem__(self, key)) != type (value):
                    raise ValueError, "Cannot modify data type."
            elif not isinstance (value, list): self._lines.append ((0, key))
            else: self._lines.append ((2, key))
            dict.__setitem__(self, key, value)

    def Write (self, filename):
        """
        Write config file.
        """
        fid = open (filename, 'w')
        for d in self._lines:
            if d[0] == 0: fid.write ("var %s = %s\n" % (d[1], str(dict.__getitem__(self, d[1]))))
            elif d[0] == 1: fid.write ("file '%s'\n" % (d[1]))
            else: fid.write ("list %s = %s\n" % (d[1], str(dict.__getitem__(self, d[1]))))

if __name__ == "__main__":

    input="""var foo = 5
load 'filename.txt'
var bar = 6
list baz = [1, 2, 3, 4]"""

    file ("test.txt", 'w').write (input)
    config = ConfigFile ("test.txt")
    # Modify existent items
    config.foo = config.foo * 2
    # Add new items
    config.foo2 = [4,5,6,7]
    config.foo3 = 12.3456
    config.load = 'filenameX.txt'
    config.load = 'filenameXX.txt'
    config.Write ("test_new.txt")

rawDescription: What is the pythonic way to implement a parse tree for custom format?


code: print soup.find('name').string

rawDescription: How to access a tag called "name" in BeautifulSoup

description: Access a tag called "name" in BeautifulSoup


code:
lines = [x for x in reader]
for line in lines[::-1]:
    print line

{' cars': ' chrysler', ' vegetables': ' corn', 'fruit': 'grape'}
{' cars': ' chevy', ' vegetables': ' celery', 'fruit': 'apple'}
{' cars': ' ford', ' vegetables': ' carrot', 'fruit': 'orange'}

rawDescription: Python csv.DictReader - how to reverse output?


code:
from itertools import combinations
from scipy.stats import ttest_ind
for list1, list2 in combinations(data.keys(), 2):
    t, p = ttest_ind(data[list1], data[list2])
    print list1, list2, p

rawDescription: How to calculate p-value for two lists of floats?

description: Calculate p-value for two lists of floats


code:
def find_matches():
    """
        Some consideration of the HTML header, body, etc. while computing duplicates.
    """

    from urllib2 import urlopen
    import hashlib
    from BeautifulSoup import BeautifulSoup
    import pprint

    urls = [ 'http://www.google.com', 'http://www.google.com/search'] # assuming all distinct urls

    def txt_md5(txt):
        return hashlib.md5(txt).hexdigest()

    MAX_FILE_SIZE = 1024*1024*1024
    d = {}
    url_contents = {}
    matches = []
    for url in urls:
        try:
            c = urlopen(url)
            url_contents[url] = []
            r = c.read(MAX_FILE_SIZE)
            soup = BeautifulSoup(r)
            header = soup.find('head').text
            body = soup.find('body').text
            # More fine-grained content options
            # like h1, h2, p, etc., can be included.
            # Common CSS tags like page, content, etc.
            # can also be included.
            for h in [header, body]:
                print h
                md5 = txt_md5(h)
                url_contents[url].append((md5, h))
                if md5 in d:
                    url2 = d[md5]
                    matches.append((md5, url, url2))
                else:
                    d[md5] = []
                d[md5].append(url)
        except Exception as e:
            print "Exception", e
    print '---------------'
    #pprint.pprint(url_contents)
    print matches

if __name__ == '__main__':
    find_matches()

rawDescription: The best way to check duplicated url in Python?

description: Check duplicated url in Python


code:
from pyparsing import Word,nums,alphas,countedArray

test = "key 02 01 30 03 40 20 10"

integer = Word(nums)

# each string is a countedArray of integers, and the data is a counted array
# of those, so...
lineExpr = Word(alphas)("keyword") + countedArray(countedArray(integer))("data")

# parse the test string, showing the keyworod, and list of lists for the data
print lineExpr.parseString(test).asList()

rawDescription: pyparsing: Nested countedArray?

description: Pyparsing: Nested countedArray


code:
from nltk.corpus import treebank
from nltk import ConditionalFreqDist as cfd
from itertools import chain

treebank_tagged_sents = list(chain(*[[tree.pos() for tree in treebank.parsed_sents(pf)] for pf in treebank.fileids()]))

total_len = len(treebank_tagged_sents)
train_len = int(90 * total_len /100)

train_set = treebank_tagged_sents[:train_len]
print len(train_set)
train_treebank_tagged_words = cfd(chain(*train_set))

test_set = treebank_tagged_sents[train_len:]
print len(test_set)
test_treebank_tagged_words = cfd(chain(*test_set))

rawDescription: Create Dictionary from Penn Treebank Corpus sample from NLTK?


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup(cont)
for a in soup.select('a'):  # Or soup.find_all('a') if you prefer
    if a.get('id') is not None:
        print a.get('id')

rawDescription: Capturing ids by xpath in python from url source


code:
import wx
import  wx.lib.newevent

class LblRadBox(wx.Panel):
    """
    Simple example of a composite widget
    Add methods as required to improve functionality...
    """
    def __init__(self, parent, stLbl="", rbLbl="", choices=[]):
        wx.Panel.__init__(self, parent)
        self.stLbl = wx.StaticText(self, label=stLbl)
        self.rbox = wx.RadioBox(self, label=rbLbl, choices=choices)

        sizer =  wx.BoxSizer()
        sizer.Add(self.stLbl)
        sizer.Add(self.rbox)
        self.SetSizerAndFit(sizer)

    def SetSTLabel(self, lbl):
        self.stLbl.SetLabel(lbl)

    def GetLabel(self):
        return self.rbox.GetLabel()

    def GetSelection(self, lbl):
        return self.rbox.GetSelection()

class GUI(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(700, 400))

        panelControl = wx.Panel(self, 1, style=wx.MAXIMIZE)
        sizerControl = wx.GridBagSizer(hgap=4,vgap = 4)

        lblTitle = wx.StaticText(panelControl, label="Pick Scores")
        self.btnRoll = wx.Button(panelControl, label="Roll!")

        sizerControl.Add(lblTitle, pos=(0,0),
                         flag=wx.ALIGN_CENTER|wx.TOP|wx.LEFT|wx.BOTTOM, border=5)
        sizerControl.Add(self.btnRoll, pos=(0,1),
                         span=(1,5), flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=5)

        rboxPick = ["Default", "Strength", "Dexterity", "Constitution",
                    "Intelligence", "Wisdom", "Charisma"
                    ]
        labels = ["One", "Two", "Three", "Four"]

        #Create, layout and bind the RadioBoxes
        for row, label in enumerate(labels):
            rbox = LblRadBox(panelControl, rbLbl="Roll %s"%(label), choices=rboxPick)
            #if u want to be able to access the rboxes outside of onRadioBox()
            #then add references of them to a dictionary like in method 1..

            sizerControl.Add(rbox, pos=(row+1, 1), span=(1,5),
                             flag=wx.EXPAND|wx.LEFT|wx.RIGHT,border=2)

        panelControl.Bind(wx.EVT_RADIOBOX, self.onRadioBox)

        sizerMain = wx.BoxSizer()
        sizerMain.Add(sizerControl)
        panelControl.SetSizerAndFit(sizerMain)

    def onRadioBox(self, evt):
        """Event handler for RadioBox.."""
        rbox = evt.GetEventObject()#Get a reference to the RadioBox
        rboxLbl = rbox.GetLabel()   #We can identify the RadioBox with its label
        selection = rbox.GetSelection()

        print rboxLbl
        print selection

        if rboxLbl == "Roll One":
            #do something
            pass
        elif rboxLbl == "Roll Two":
             #do something else
            pass

if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = GUI(None, -1, "")
    frame.Show(1)
    app.MainLoop()

rawDescription: wxpython - Creating Unique GUI Elements With a Loop

description: Wxpython - Creating Unique GUI Elements With a Loop


code:
def gold_room():
    print "This room is full of gold.  How much do you take?"
    while True:
        nxt = raw_input("> ")
        try:
            nxt = int(nxt)
            break
        except ValueError:
            print("Man,you need to learn how to print a number!")
            continue
    if nxt < 50:
        print("Nice, you're not greedy, you win!")
        return
    dead("You greedy b!*!*!*d!")

rawDescription: About if x is int

description: About if x is int


code:
for header in soup.select('tr td a h6'):
    name = header.get_text(strip=True)
    practice = header.parent.find_next_sibling(text=True).strip()
    address = header.find_parent('td').find_next_sibling('td').get_text(' ', strip=True)
    print name, practice, address

rawDescription: beautifulsoup selecting certain values only

description: Beautifulsoup selecting certain values only


code:
results = []
puller = pull_tuples(results); puller.next()
with open('vehicles.xml') as f:
    parse(f, LazySax(puller))
for result in results:
    print result

rawDescription: Python RE: how can I neglect empty space between tags?


rawDescription: How do I parse a CSV list enclosed in brackets in Python?

description: Parse a CSV list enclosed in brackets in Python


rawDescription: String reversal in Python

description: String reversal in Python


code:
import sys

for line in sys.stdin:
    # do something...
    print line,

rawDescription: Python: Read huge number of lines from stdin


code: print ''.join(map(lambda c:'\\x%02x'%c, map(ord, a)))

rawDescription: Python - string of binary escape sequences as literal


code:
import Tkinter as tk
import ttk

global parameter1
global parameter2
global list1
global list2

class SuppressableStingVar(tk.StringVar):
    def __init__(self, *args, **kargs):
        tk.StringVar.__init__(self, *args, **kargs)
        self.silenced = False
    def trace(self, mode, callback):
        conditional_callback = lambda *args, **kargs: callback(*args, **kargs) if not self.silenced else None
        tk.StringVar.trace(self, mode, conditional_callback)
    def set(self, value, suppress_callback = False):
        if suppress_callback:
            self.silenced = True
        tk.StringVar.set(self, value)
        self.silenced = False

list1 = ["apple","bananna","orange"]
list2 = ["moe","larry","curly"]

def parameter1_changed(arg1,arg2,arg3):
  print "Selection for List 1 changed"
  print "arg1=%s  arg2=%s  arg3=%s"%(arg1,arg2,arg3)
  parameter2.set(list2[1], True)

def parameter2_changed(arg1,arg2,arg3):
  print "Selection for List 2 changed"
  print "arg1=%s  arg2=%s  arg3=%s"%(arg1,arg2,arg3)

root = tk.Tk()

parameter1 = tk.StringVar()
parameter1.set(list1[0])

parameter2=SuppressableStingVar()
parameter2.set(list2[0])

tk.Label(root,text="List #1").grid(row=0,column=0,sticky=tk.E)
ttk.Combobox(root,values=list1,textvariable=parameter1,state='readonly').grid(row=0,column=1,sticky=tk.W)
tk.Label(root,text="List #2").grid(row=1,column=0,sticky=tk.E)
ttk.Combobox(root,values=list2,textvariable=parameter2,state='readonly').grid(row=1,column=1,sticky=tk.W)

parameter1.trace("w",parameter1_changed)
parameter2.trace("w",parameter2_changed)

root.mainloop()

rawDescription: Python / Tkinter Is there a way to distinguish a programmatic change to a combo box from a user initiated change?


code:
import random

def misspeller(word):
    characters = 'qwertyuioplkjhgfdsazxcvbnm,. '
    rand_word_position = random.randint(-1,len(word))
    rand_characters_position = random.randint(0,len(characters)-1)

    if rand_word_position == -1:
        misspelled_word = characters[rand_characters_position] + word
    elif rand_word_position == len(word):
        misspelled_word = word + characters[rand_characters_position]
    else:
        misspelled_word = list(word)
        misspelled_word[rand_word_position] = characters[rand_characters_position]
        misspelled_word = ''.join(misspelled_word)
    return misspelled_word

s = 'Hello how are you today, [name]?'
misspelled_s = ''
misspelled_list = []
for item in s.split(' '):
    if '[name]' in item:
        misspelled_list.append(item)
    else:
        misspelled_list.append(misspeller(item))
misspelled_s = ' '.join(misspelled_list)
print misspelled_s

rawDescription: Place random character in string if not a certain word


code: print soup.find('td', {'class': 'size-price'}).span.text

rawDescription: Using REGEX to match elements between lines in Python


code:
metadata_fields = ['Creator', 'CreationDate', 'Producer', 'ModDate']
with open('path_to_your_file.pdf') as my_pdf:
  meta_values = [line.rstrip('\n') for line in my_pdf.readlines()
             for item in metadata_fields if item in line]
  print meta_values

rawDescription: Without using any additional libraries, how would someone approach the challenge of reading the metadata of .pdf files in Python?


code:
g = lambda *arg: sum(arg)
print g(4, 5, 6)

rawDescription: Python lambda parameters

description: Python lambda parameters


code:
#!/bin/sh

exec 'python' '/usr/share/progname/main.py' "$@"

rawDescription: Generally speaking, how are (Python) projects structured?


code:
a='\tabc'
print a
str.strip(a)

rawDescription: How do I count the words in a string using only loops and string.strip()?

description: Count the words in a string using only loops and string.strip()


code: print '%.20f' % p

rawDescription: Curious Python behaviour when approaching x.0


code:
sequence = [1, 45, 65, 7]
for i, val in enumerate(sequence):
    print i, val

rawDescription: Is there a way to access an iteration-counter in Python's for loop?


code:
import collections
import sqlite3

class SqliteDict(collections.MutableMapping):
  @classmethod
  def create(cls, path, columns):
    conn = sqlite3.connect(path)
    conn.execute('DROP TABLE IF EXISTS SqliteDict')
    conn.execute('CREATE TABLE SqliteDict ({0})'.format(','.join(columns.split())))
    conn.commit()
    return cls(conn)

  @classmethod
  def open(cls, path):
    conn = sqlite3.connect(path)
    return cls(conn)

  def __init__(self, conn):
    # looks like for sime weird reason you want str, not unicode, when feasible, so...:
    conn.text_factory = sqlite3.OptimizedUnicode
    c = conn.cursor()
    c.execute('SELECT * FROM SqliteDict LIMIT 0')
    self.cols = [x[0] for x in c.description]
    self.conn = conn
    # start with a keyname (==column name) of `ID`
    self.set_key('ID')

  def set_key(self, key):
    self.i = self.cols.index(key)
    self.kn = key

  def __len__(self):
    c = self.conn.cursor()
    c.execute('SELECT COUNT(*) FROM SqliteDict')
    return c.fetchone()[0]

  def __iter__(self):
    c = self.conn.cursor()
    c.execute('SELECT * FROM SqliteDict')
    while True:
      result = c.fetchone()
      if result is None: break
      k = result.pop(self.i)
      return k, result

  def __getitem__(self, k):
    c = self.conn.cursor()
    # print 'doing:', 'SELECT * FROM SqliteDict WHERE {0}=?'.format(self.kn)
    # print ' with:', repr(k)
    c.execute('SELECT * FROM SqliteDict WHERE {0}=?'.format(self.kn), (k,))
    result = [list(r) for r in c.fetchall()]
    # print ' resu:', repr(result)
    for r in result: del r[self.i]
    return result

  def __contains__(self, k):
    c = self.conn.cursor()
    c.execute('SELECT * FROM SqliteDict WHERE {0}=?'.format(self.kn), (k,))
    return c.fetchone() is not None

  def __delitem__(self, k):
    c = self.conn.cursor()
    c.execute('DELETE FROM SqliteDict WHERE {0}=?'.format(self.kn), (k,))
    self.conn.commit()

  def __setitem__(self, k, v):
    r = list(v)
    r.insert(self.i, k)
    if len(r) != len(self.cols):
      raise ValueError, 'len({0}) is {1}, must be {2} instead'.format(r, len(r), len(self.cols))
    c = self.conn.cursor()
    # print 'doing:', 'REPLACE INTO SqliteDict VALUES({0})'.format(','.join(['?']*len(r)))
    # print ' with:', r
    c.execute('REPLACE INTO SqliteDict VALUES({0})'.format(','.join(['?']*len(r))), r)
    self.conn.commit()

  def close(self):
    self.conn.close()

def main():
  d = SqliteDict.create('student_table', 'ID NAME BIRTH AGE SEX')
  d['1'] = ["Joe", "01011980", "30", "M"]
  d['2'] = ["Rose", "12111986", "24", "F"]
  print len(d), 'items in table created.'
  print d['2']
  print d['1']
  d.close()

  d = SqliteDict.open('student_table')
  d.set_key('NAME')
  print len(d), 'items in table opened.'
  print d['Joe']

if __name__ == '__main__':
  main()

rawDescription: How can I design a dict like sqlite class in python which can using different field as "key"?

description: Design a dict like sqlite class in python which can using different field as "key"


code:
import cmd
import sys

class MyCmd(cmd.Cmd):
    def do_hello(self, line):
        print "hello"
    def do_exit(self, line):
        return True

if __name__ == '__main__':
    my_cmd = MyCmd()

    if len(sys.argv) > 1:
        my_cmd.onecmd(' '.join(sys.argv[1:]))
    else:
        my_cmd.cmdloop()

rawDescription: Unification of python command line interpreter and command-subcommand command line interfaces


code:
Example
class Base(object):
    def gen(self, data):
        for i in data:
            yield i

class Something(Base):
    def gen(self, data):
        data += "world"
        for i in super(Something, self).gen(data):
            yield i

s = Something()
for i in s.gen("hello"):
    print i

rawDescription: super call to DjangoSpider's parse method not working

description: Super call to DjangoSpider's parse method not working


code:
print "<form method=\"post\">"

for s in ListStr:
    print "<input type=hidden name=\"state_carry\" value=\"" + s + "\"><br />"

print "<input type=\"submit\" value=\"Submit\" />"
print "</form>"

rawDescription: Python Pass List into Form and Retrieve as List


code:
for rowdict in myReader:
  print ['%s:%s' % (f, rowdict[f]) for f in myReader.fieldnames]

rawDescription: Is it possible to keep the column order using the Python csv DictReader


code:
from struct import unpack
b = "\x00\x00\x00\x05\x00\x00\x00\x2a"

class Point(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(*unpack('!ii', b))
print p.x
print p.y

rawDescription: Python buffer decode

description: Python buffer decode


code:
from nltk.collocations import BigramCollocationFinder, BigramAssocMeasures, TrigramCollocationFinder, TrigramAssocMeasures
from nltk.corpus import genesis

# Initialize an association measure for bigrams.
bigram_measures = BigramAssocMeasures()
trigram_measures = TrigramAssocMeasures()

# Puts the corpus into a BigramCollocationFinder class.
# Now you can search for bigrams in the corpus
finder2 = BigramCollocationFinder.from_words(genesis.words('english-web.txt'))
finder3 = TrigramCollocationFinder.from_words(genesis.words('english-web.txt'))

blacklist = ["olive leaf plucked", "during mating searson"]
finder3.apply_ngram_filter(lambda w1, w2, w3: " ".join([w1,w2,w3]) in blacklist)

print finder3.nbest(trigram_measures.pmi, 10)

rawDescription: finder.apply_ngram_filter in nltk.collocations to classify some ngrams

description: Finder.apply_ngram_filter in nltk.collocations to classify some ngrams


code:
milestones = [15, 30, 45, 60, 75, 90, 100]
for i in range(N):
    #do work here
    percentage_complete = (100.0 * (i+1) / N)
    while len(milestones) > 0 and percentage_complete >= milestones[0]:
        print "{}% complete".format(milestones[0])
        #remove that milestone from the list
        milestones = milestones[1:]

rawDescription: Track and display percentage of code already executed


code:
im = Image.open('blob.png')
print find_centroid(im, 1)
print find_centroid(im, 20)
#output:
(432, 191)
(430, 190)

rawDescription: Finding a specific index in a binary image in linear time?


code:
from collections import OrderedDict
def EntryToFieldMatch(Entry, Fields):
    valid = []
    # create orderedDict from the words in Fields
    # dict lookups are 0(1)
    st = OrderedDict.fromkeys(Fields)
    # iterate over Entry
    for word in Entry:
        # split the words once on whitespace
        spl = word.split(None, 1)
        # if the first word/word appears in our dict keys
        if spl[0] in st:
            # add to valid list
            valid.append(word)
            # remove the key
            del st[spl[0]]
    print valid
    print "-"*50
    # only invalid words will be left
    print st.keys()

rawDescription: How to compare 2 list where string matches element in alternate list

description: Compare 2 list where string matches element in alternate list


code:
for codon in mutated_codon:
    print codon_lookup.get(codon, '*')

rawDescription: How can I do the following comparison without having to write 20 if-statements or making 20 lists/dictionaries?

description: Do the following comparison without having to write 20 if-statements or making 20 lists/dictionaries


rawDescription: Printing dictionary with lists into file


code:
from collections import OrderedDict
league={'PEDD United': {'id': 37828, 'rank': 12, 'totalpts': 307},'Fc Mbonabushia': {'id': 205633, 'rank': 6, 'totalpts': 356},'FC Slurp': {'id': 933573, 'rank': 11, 'totalpts': 312},'KFC_Overijse': {'id': 38861, 'rank': 5, 'totalpts': 362},'Fc Paris': {'id': 1538051, 'rank': 2, 'totalpts': 396}}
league = OrderedDict(sorted(league.items(), key= lambda x: x[1]['totalpts'], reverse=True))
print league

rawDescription: Sort dict in jinja2 loop

description: Sort dict in jinja2 loop


code:
import pprint
z = {'data':{'id':1,'title':'home','address':{'street':'some road','city':'anycity','postal':'somepostal'}}}

print '<pre>', pprint.pformat(z), '</pre>'

rawDescription: python: serialize a dictionary into a simple html output

description: Python: serialize a dictionary into a simple html output


code:
import pickle
from getpass import getpass

username = raw_input('What would you like your username to be?  ')
username2 = raw_input('Please enter the same username again: ')
while username != username2:
    print 'The usernames do not match.'
    username = raw_input('What would you like your username to be?  ')
    username2 = raw_input('Please enter the same username again: ')
pword = getpass("What would you like your password to be?  ")
pword2 = getpass("Please reenter the password: ")
while pword != pword2:
    print 'The passwords do not match'
    pword = getpass('What would you like your password to be?  ')
    pword2 = getpass('Please reenter the password: ')
money_left = 0
logininfo = [username, pword, money_left]
pickle.dump(logininfo, open( "%s.p" %username, "wb"))
print 'Your username is %s, and your password is %s. You have $%d ingame money.' % (username, pword, money_left)

rawDescription: How do I create an account to store information?

description: Create an account to store information


code:
def show(text):
    print text

responce = {
    'knight': lambda:show('Neee!'),
    'bunny': lambda:show('Rawwww!'),
    'pesant': lambda:show('Witch!'),
    'dingo': lambda:show('Bad, wicked, naughty Zoot!'),
}

rawDescription: Long elif chains vs dictionary with exec()


code:
vars = {'search': 'replace',
 'foo':    'bar'}
mystring = "Foo bar %foo% % search %."
for k, v in vars.items():
    mystring = mystring.replace('%%%s%%' % k, v)

print mystring

rawDescription: Regex to replace %variables%

description: Regex to replace %variables%


rawDescription: Capturing regular expression in Python

description: Capturing regular expression in Python


code:
pts = Profile_Tag.objects.all()
for pt in pts:
    print pt.profile_id

rawDescription: Django - Access ForeignKey value without hitting database


code:
words = '''Some sentence that is spliced...
and has a continuation.
this cannot be confused by U.S.A.
In that
last sentence...
an abbreviation ended the sentence!'''.split()

def format_sentence(words):
    output = []

    for word in words:
        if word.endswith('...') or not word.endswith('.'):
            output.append(word)
            output.append(' ')
        elif word.endswith('.'):
            output.append(word)
            output.append('\n')
        else:
            raise ValueError('Unexpected result from word: %r' % word)

    return ''.join(output)

print format_sentence(words)

rawDescription: How can I merge together sentence objects?

description: Merge together sentence objects


code:
class A:
  var = "1,2,3"

class B:
  var = A.var + ",4,5"

print A.var
print B.var

rawDescription: "Appending" instead of overriding superclass instance variables


code:
for k, layersListDict[k] in itertools.chain((first,),
                                             (k for k in layerListDict
                                               if k != first)):
    print k, v

rawDescription: How to Re-arrange items in a Python Dictionary during For Loop?


code:
elt2color = dict([('A', 'red'), ('B', 'red'), ('C', 'blue'),
                  ('D', 'blue'), ('E', 'green'), ('F', 'green'),
                  ('G', 'green'), ('H', 'yellow'), ('I', 'white'),
                  ('J', 'white'), ('K', 'black')])
for c in combs(elt2color):
    for element in c:
        print("%s-%s" % (element, elements[element]))
    print "\n"

rawDescription: Efficient combinations of N colored elements with restriction in the number of colors


code:
from itertools import combinations
for item in combinations("ABCD", 3):
    print item

rawDescription: What is the best way to write a multiple nested for loops in Python


code:
from mako.template import Template
print Template("${isinstance(a, int)}").render(a=1)
print Template("${isinstance(a, list)}").render(a=[1,2,3,4])

rawDescription: How to check instanceof in mako template?

description: Check instanceof in mako template


code:
from time import sleep
import sys

def print_slowly(text):
    for c in text:
        print c,
        sys.stdout.flush()
        sleep(0.5)

print_slowly('LOA')

rawDescription: Python: Print to one line with time delay between prints


code:
try:
    validictory.validate({'field1':"abcd",'field2':123.7},schema)
except validictory.FieldValidationError as e:
    print "field which failed validation:",e.fieldname

rawDescription: Python Validictory- Field Validation

description: Python Validictory- Field Validation


code:
class SettingsForm(forms.ModelForm):

    class Meta:
        model = SettingProxy
        exclude = ('domain',)

    def save(self, domain, *args, **kwargs):
        print self.cleaned_data
        commit = kwargs.get('commit', True)
        kwargs['commit'] = False
        setting = super(SettingsForm, self).save(*args, **kwargs)
        setting.domain = domain
        if commit:
            setting.save()
        return setting

rawDescription: Returning a custom model instance from a manager


code:
import timeit
import operator

class foo(object):
    def __init__(self):
        self.a = 1
        self.b = 2
        self.c = 3

def abc(f):
    return [getattr(f,x) for x in ('a','b','c')]

abc2 = operator.attrgetter('a','b','c')

f = foo()
print abc(f)
print abc2(f)

print timeit.timeit('abc(f)','from __main__ import abc,f')
print timeit.timeit('abc2(f)','from __main__ import abc2,f')

rawDescription: Using a variable as part of a variable name


code:
import csv
from cStringIO import StringIO
items = [{'name': 'foo', 'total_price' : 15, 'price': [4, 2, 4, 5]}, {'name': 'bar', 'total_price' : 10, 'price': [5, 2, 3]}]
f = StringIO()
csv_writer = csv.writer(f)
for item in items:
    csv_writer.writerow([item['name'], item['total_price']])
    csv_writer.writerows(['', p] for p in item['price'])

print f.getvalue()

rawDescription: how to format csv with some sub items

description: Format csv with some sub items


code:
for x in range(0, 3000000):
    open(str(x), 'a').close()

print not os.listdir('.')

rawDescription: How to test for an empty directory, no matter what its size, in Python?

description: Test for an empty directory, no matter what its size, in Python


code:
for a,b in cursor:
    print a,b

rawDescription: Why do values from SQLite 3 appear with a "u" prefix? How to hide the prefix


code:
import os
def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
    return total_size

print get_size()

rawDescription: Calculating a directory size using Python?


code:
import random
print random.randint(1,10)

rawDescription: Python Random number generator and currency system for text-based RPG


code: print '{0:06d}'.format(1)

rawDescription: How to add enough zeros before a number in order to have six digits for this number using Python?

description: Add enough zeros before a number in order to have six digits for this number using Python


code: print my_LINEARSVC_cross.values.sum() - my_LINEARSVC_cross.values.trace()

rawDescription: Addition of values in a 10x10 python pandas dataframe excluding the diagonal


code:
def get_input(prompt_text, valid_options):
    x = raw_input(prompt_text)
    while x not in valid_options:
        print x, "is not a valid value. Expected are :", valid_options
    return x

rawDescription: Python guesses my number (reverse number guess) UnboundLocalError


code:
import csv

file1reader = csv.reader(open("file1.csv"), delimiter=",")
file2reader = csv.reader(open("file2.csv"), delimiter=",")

header1 = file1reader.next() #header
header2 = file2reader.next() #header

for Code, DTime in file1reader:
    for id_, D, Sym, DateTime, Bid, Ask in file2reader:
        if DateTime.startswith(DTime): # found it
            print DateTime, Bid, Ask   # output data
            break                      # break and continue where we left next time

rawDescription: loop through rows of one csv file to find corresponding data in another

description: Loop through rows of one csv file to find corresponding data in another


code:
a1=[]
a2=[]
a1.append("abcdef")
x="abc"
y = "abcdef"
new = ""
for letter in y:
    if letter not in x:
        new = new + letter

a2.append(new)

print a1, a2

rawDescription: Appending unique part of string to list

description: Appending unique part of string to list


code:
from pyparsing import (nestedExpr, Literal, Word, alphanums,
    quotedString, replaceWith, nums, removeQuotes)

NIL = Literal("NIL").setParseAction(replaceWith(None))
integer = Word(nums).setParseAction(lambda t:int(t[0]))
quotedString.setParseAction(removeQuotes)
content = (NIL | integer | Word(alphanums))

print nestedExpr(content=content, ignoreExpr=quotedString).parseString(text)

rawDescription: parsing parenthesized list in python's imaplib

description: Parsing parenthesized list in python's imaplib


code:
l = []
def append_dict(d):
    if d.get("key1") == "value1":
        l.append(d)
        return

    for k,v in d.items():
        if isinstance(v, dict):
            append_dict(v)

append_dict(d)
print l

rawDescription: Check existence of a key recursively and append to array of dict


code:
A = [np.arange(i) for i in range(3, 6)]
A
for B in A: print B.mean()

rawDescription: Mean of object variables in a python array


code:
from itertools import product

for combo in product((None, True, False), repeat=3):
    arguments = {k: v for k, v in zip('abc', combo) if v is not None}
    print arguments

rawDescription: Find all possible combinations of arguments in Python


code:
import numpy as np
x = np.arange(9).reshape(3,3)
y = np.matrix(x)

a = y**3
b = np.linalg.matrix_power(x, 3)

print a
print b
assert np.all(a==b)

rawDescription: How to raise a numpy array to a power? (corresponding to repeated matrix multiplications, not elementwise)

description: Raise a numpy array to a power? (corresponding to repeated matrix multiplications, not elementwise)


code:
from itertools import groupby
from operator import itemgetter
mytuple = [('Andrew','10','20'),('Jim',"20",'12'),("Sarah","30",'43'),("Jim","23",'15'),("Andrew","54",'56')]
mytuple = sorted(mytuple)
FULL_HTML = []
for name, rows in groupby(mytuple, itemgetter(0)):
     table = []
     for name, value1, value2 in rows:
        table.append(
            "
{}	{}	{}
".format(
                name, value1, value2))
     table = "
\n{}\n
".format('\n'.join(table))
     FULL_HTML.append(table)

FULL_HTML = "\n{}\n".format('\n'.join(FULL_HTML))
print FULL_HTML

rawDescription: Generating HTML Tables from Tuple Python


code:
my_item.comms.append("super")
print "All Comments: ", my_item.comms

rawDescription: Sqlalchemy relationship to built-in type


code:
from lxml import html

HTML = """ TEXT HERE 1..............
 TEXT HERE 2..............
TEXT HERE 3..............
 TEXT HERE 4..............
 TEXT HERE 5..............
TEXT HERE 6..............
 TEXT HERE 7..............
 TEXT HERE 8..............
TEXT HERE 9..............

TEXT LINE 10.............

TEXT LINE 11.............

TEXT LINE 12.............

TEXT LINE 13.............
"""

tree = html.fromstring(HTML)
text_lines = tree.xpath('//span[contains(@id, "ctl00_ContentPlaceHolder1_CaseDetailParties1_gvParties_ctl02_gvAttyInfo_ctl")]')

results = dict()

for i, text_line in enumerate(text_lines):
    span_id = text_line.xpath('.//@id')[0]
    span_text = [x.strip() for x in text_line.xpath('.//text()')]
    results[i] = dict(id=span_id, texts=span_text)

print results

rawDescription: lxml xpath - Get all text within span tags

description: Lxml xpath - Get all text within span tags


code:
#!/usr/bin/env python

numbers = [i for i in xrange(6)]

print "The numbers: "

for num in numbers:
    print num

rawDescription: Using For Loop In stead of While loop in Python


code:
from Queue import Queue, Empty

button_pressed = Queue()

@post('/button')
def action():
    button_pressed.put(1)  # can be any value really
    redirect("/button")

def method():
    while True:
        try:
            button_pressed.get_nowait()
        except Empty:
            # NOTE: if you don't do anything here, this thread
            # will consume a single CPU core
            pass
        else:
            print "push recieved"

rawDescription: threading a bottle app

description: Threading a bottle app


code:
def send_mail(self, message, title):
    print "Sending mail..........."
    import smtplib
    from email.MIMEMultipart import MIMEMultipart
    from email.MIMEText import MIMEText
    gmailUser = 'mail_you_send_from@gmail.com'
    gmailPassword = 'password'
    recipient = 'mail_to_send_to'

    msg = MIMEMultipart()
    msg['From'] = gmailUser
    msg['To'] = recipient
    msg['Subject'] = title
    msg.attach(MIMEText(message))

    mailServer = smtplib.SMTP('smtp.gmail.com', 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmailUser, gmailPassword)
    mailServer.sendmail(gmailUser, recipient, msg.as_string())
    mailServer.close()
    print "Mail sent"

rawDescription: Sending e-mail after scrape in scrapy

description: Sending e-mail after scrape in scrapy


code:
class Manager(Observer):

    def __init__(self, ):
        self._subjects = []
        self._observers = []

    def monitorSubject(self, subject):
        self._subjects.append( weakref.ref(subject) )

        # observe the subject for deletion to
        # trigger list maintenance on "deleted"
        subject.registerObserver(self)

    def monitorObserver(self, observer):
        self._observers.append( weakref.ref(observer) )

    def deleted(self, subject):
        ''' a subject was deleted, remove it from the list.
        deleting() is called first, and the observers delete themselves.
        deleted() is called next, and is a hook for the manager to
        cleanup any dead subjects and observers '''

        # calling a weakref returns the original object, and `None` when the
        # reference is dead
        def isNotDead(r):
            return not r()==None

        # remove any dead subjects
        print 'Removing dead subjects...'
        self._subjects = filter(isNotDead, self._subjects)

        # remove any dead observers
        print 'Removing dead observers...'
        self._observers = filter(isNotDead, self._observers, )

    def __str__(self,):
        return "[Manager] Subjects:{0}, Observers:{1}".format(
            ','.join([str(r()) for r in self._subjects]),
            ','.join([str(r()) for r in self._observers])
        )

rawDescription: Using the observer pattern to delete an Observer when a Subject has been "deleted" in Python


code:
import time

class PLCApplication(object):
    def generate_data(self):
        a = 0
        countup = True
        while a >= 0:
            time.sleep(0.5)
            if countup:  # no need to do test if it equals True
                a += 2
            else:
                a -= 2
            if a < 0:
                countup = True
                a += 2
            if a == 12:
                countup = False
                a -= 2
            yield a

def do_stuff(b):
    print b

if __name__ == '__main__':
    plc = PLCApplication()
    for t in plc.generate_data():
        do_stuff(t)

rawDescription: one function generating numbers for another

description: One function generating numbers for another


code:
# z.py
def foo():
    print "Yessir!"

rawDescription: How can I replace a module without importing it?

description: Replace a module without importing it


code: print prog_rownum('file.csv', 'U16')

rawDescription: Function returns no value

description: Function returns no value


code:
scriptone_test = None
def test():
    print "Hello World"
    scriptone_test()

rawDescription: Running function from script it was imported by


code:
import argparse

class DictAction(argparse.Action):
    def __init__(self, *args, **kwargs):
        super(DictAction, self).__init__(*args, **kwargs)
        self.nargs = '*'

    def __call__(self, parser, namespace, values, option_string=None):
        # The default value is often set to `None` rather than an empty list.
        current_arg_vals = getattr(namespace, self.dest, []) or []
        setattr(namespace, self.dest, current_arg_vals)
        arg_vals = getattr(namespace, self.dest)
        arg_vals.append(dict(v.split(':') for v in values))

parser = argparse.ArgumentParser()
parser.add_argument('--group', action=DictAction)

print parser.parse_args()

rawDescription: grouping an unknown number of arguments with argparse

description: Grouping an unknown number of arguments with argparse


code:
from toolz.itertoolz import sliding_window
for line, prevline in sliding_wind(2, sys.stdin):
    if line.startswith('---(more') or prevline.startswith('---(more'):
        continue
    print line

rawDescription: What's an elegant way for one loop iteration to affect another?


code: print validateSchema(schema, tokens)

rawDescription: Programming contest like input validator


code:
#!/usr/bin/env python
from glob import glob
from hachoir_metadata import extractMetadata
from hachoir_parser import createParser

entries = [(path, extractMetadata(createParser(path)).get('duration'))
           for path in glob(u"*.wav")]
print "Min: path(%s), duration(%s)" % min(entries, key=lambda (_,d): d)
print "Max: path(%s), duration(%s)" % max(entries, key=lambda (_,d): d)
print "Total: duration(%s seconds)" % sum(d.total_seconds() for _, d in entries)

rawDescription: Get min, max, and total length of wav files


code: print top[0][0].text

rawDescription: Python elementree having hard time extracting data


code:
with open("file.txt", "r") as f:
    searchlines = f.readlines()
for i, line in enumerate(searchlines):
    if "searchphrase" in line:
        for l in searchlines[i:i+3]: print l,
        print

rawDescription: Search a text file and print related lines in Python?


code:
## JSON version
import json
# you could use pickle instead,
# just replace json.dumps/json.loads with pickle/unpickle

import redis

# set up the redis client
r = redis.StrictRedis(host = '', port = 6379, db = 0)

# sample parent dicts
parent0 = {'child0': {0:'a', 1:'b', 2:'c',}, 'child1':{5:'e', 6:'f', 7:'g'}}
parent1 = {'child0': {0:'h', 1:'i', 2:'j',}, 'child1':{5:'k', 6:'l', 7:'m'}}

# save the parents as hashfields, with the children as serialized strings
# bear in mind that JSON will convert the int keys to strings in the dumps() process
r.hmset('parent0', {key: json.dumps(parent0[key]) for key in parent0})
r.hmset('parent1', {key: json.dumps(parent0[key]) for key in parent1})

# Get a child dict from a parent
# say child1 of parent0
childstring = r.hget('parent0', 'child1')
childdict = json.loads(childstring)
# this could have been done in a single line...

# if you want to convert the keys back to ints:
for key in childdict.keys():
    childdict[int(key)] = childdict[key]
    del childdict[key]

print childdict

rawDescription: Data model and datastore technology for fast multidimensional data lookup


code:
def a():
    print "we want to exit here!"
    return

rawDescription: How can I stop a .py script that is triggered by some parent .py script without kiiling parent .py?

description: Stop a .py script that is triggered by some parent .py script without kiiling parent .py


code:
with open("hello.txt") as f:
    for line in f:
        print line,

rawDescription: Check if many URLs exists from a txt file (Python)


code:
import numpy as np

seqs = ["ACGTCCA","CGGATTG"]

CHARS = 'ACGT'
CHARS_COUNT = len(CHARS)

maxlen = max(map(len, seqs))
res = np.zeros((len(seqs), CHARS_COUNT * maxlen), dtype=np.uint8)

for si, seq in enumerate(seqs):
    seqlen = len(seq)
    arr = np.chararray((seqlen,), buffer=seq)
    for ii, char in enumerate(CHARS):
        res[si][ii*seqlen:(ii+1)*seqlen][arr == char] = 1

print res

rawDescription: How to generate one hot encoding for DNA sequences?

description: Generate one hot encoding for DNA sequences


code:
print matchPat("abcde", "abcd")
#False
print matchPat("a", "")
#False
print matchPat("", "a")
#True
print matchPat("", "")
#True
print matchPat("abc", "abc")
#True
print matchPat("ab*cd", "abacacd")
#False
print matchPat("ab*cd", "abaascd")
#True
print matchPat ('a*t*r', 'anteater')
#True
print matchPat ('a*t*r', 'albatross')
#True
print matchPat ('a*t*r', 'artist')
#False

rawDescription: Search for a pattern in a string in python


code:
cur = con.cursor()
cur.execut('''\
    select something from table1  -- 1st select
    union
    select something_else from table2  -- 2nd select
''')

for row in cur:
    print row

rawDescription: How print two different select results

description: How print two different select results


rawDescription: Slicing a matrix with Python

description: Slicing a matrix with Python


code:
import subprocess
import select
import multiprocessing
import time

def log_file_reader(filename, counter):
    f = subprocess.Popen(['tail', '-F',filename], stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    p = select.poll()
    p.register(f.stdout)
    while True:
        if p.poll(1):
            line = f.stdout.readline().strip()
            if line:
                '''appends 1 to counter if line is valid'''
                counter.append(1)

def main():
    m = multiprocessing.Manager()
    counter = m.list()  # initializes a counter in type list
    # starts up a process keep tailing file
    reader_process = multiprocessing.Process(target=log_file_reader, args=("/home/haifzhan/logfile.log", counter))
    reader_process.start()

    # main thread check the counter every 5 seconds
    while True:
        time.sleep(5)
        print "periodically check---counter:{0},id:{1}".format(len(counter), id(counter))

if __name__ == "__main__":
    # everything starts here
    main()

rawDescription: Why are changes to a list made in a sub-process not showing up in the parent process?


code:
from toolz.curried import pipe, filter, map
pipe(
    product(titles, repeat=2),
    # No reason to check duplicates
    filter(lambda (x, y): x > y),
    map(lambda (x, y): (x, y, fuzz.ratio(x, y))))

rawDescription: Organization of fuzzy matches

description: Organization of fuzzy matches


code:
import sys
import time

if sys.platform == "win32":
    # On Windows, the best timer is time.clock()
    default_timer = time.clock
else:
    # On most other platforms the best timer is time.time()
    default_timer = time.time

t0 = default_timer()
output = func()
t1 = default_timer()
print output, t1 - t0

rawDescription: Python timeit and program output

description: Python timeit and program output


code:
import re
line = "family: blah"
m = re.search("family: (.*)", line)
if m != None:
  print m.group(1)

rawDescription: trouble with regular expressions

description: Trouble with regular expressions


code:
x = np.zeros( (106, 106, 3) )
result = x[:, :, 0]
print result.shape

rawDescription: Numpy remove a dimension from np array

description: Numpy remove a dimension from np array


code: print textwrap.fill(splitme, width=10, subsequent_indent=' ' * 4)

rawDescription: Break up long line of text into lines of fixed width in Python 2.7


code:
twovowels=re.compile(r".*[aeiou].*[aeiou].*", re.I)
nonword=re.compile(r"\W+", re.U)
file = open("filename")
for line in file:
    for word in nonword.split(line):
        if twovowels.match(word): print word
file.close()

rawDescription: How to find the occurrences of any word with more than two vowels in a file using regex?

description: Find the occurrences of any word with more than two vowels in a file using regex


code: print "Everything is ok for now"

rawDescription: is it possible to use import after sys.exit(1)?

description: Is it possible to use import after sys.exit(1)


code:
import numbers
import sys
A = ["LA", 10, 3, 4]
print sorted(A, key=lambda n: n if isinstance(n, numbers.Number) else sys.float_info.max, reverse=True)

rawDescription: Sorting numbers in a list - Python

description: Sorting numbers in a list - Python


code:
from itertools import permutations
def combs(phrase):
    sp=phrase.split()
    com1=[map(lambda x:' '.join(x),li) for li in [permutations(sp,j) for j in range(1,len(sp)+1)]]
    for i,k in enumerate(sp):
          if not k.endswith('s'):
             sp[i]=k+'s'
    com2=[map(lambda x:' '.join(x),li) for li in [permutations(sp,j) for j in range(1,len(sp)+1)]]
    return com1+com2

print {j for i in combs('Car sales') for j in i}
set(['Car', 'sales', 'sales Cars', 'Car sales', 'Cars sales', 'sales Car', 'Cars'])

rawDescription: Searching for Phrase Keywords in MySQL

description: Searching for Phrase Keywords in MySQL


code:
ports = [[22,23],[22],[22,23,80],[23,80]]
table = port_table(ports)
for port, count in sorted(table.items()):
    if count > 1:
        print port, '->', count

rawDescription: Counting unique intersecting sets from a list


code:
import collections
import numbers
def pformat(thing, formatfunc):
    if isinstance(thing, dict):
        return type(thing)((key, pformat(value)) for key, value in thing.iteritems())
    if isinstance(thing, collections.Container):
        return type(thing)(pformat(value) for value in thing)
    if isinstance(thing, numbers.Number):
        return formatfunc(thing)
    return thing

def formatfloat(thing):
    return "%.3g" % float(thing)

x={'a':[1.05600000001,2.34581736481,[8.1111111112,9.999990111111]],
'b':[3.05600000001,4.34581736481,[5.1111111112,6.999990111111]]}

print pformat(x, formatfloat)

rawDescription: Rounding decimals in nested data structures in Python


code:
# INSTALL:
#   sudo apt-get install python-scapy
# RUN:
#   sudo /usr/bin/python ./pping.py

import sys, Queue, threading
from scapy import all as S

IFACE_LIST = 'wlan0','lo'

# pylint:disable=E1101
def run_ping(iface, out_q):
    host = '8.8.8.8'
    pkt = S.Ether()/S.IP(dst=host, ttl=(1,3))/S.ICMP()
    ans,_unans = S.srp(pkt, iface=iface, timeout=2)
    out_q.put( (iface,ans) )

result_q = Queue.Queue()
for iface in IFACE_LIST:
    threading.Thread(
        target=run_ping, args=(iface, result_q)
    ).start()

for t in threading.enumerate():
    if t != threading.current_thread():
        t.join()

print 'result:', dict( [
    result_q.get()
    for _ in range(result_q.qsize())
    ] )

rawDescription: How to create a script to capture packets using scapy and netinfo?

description: Create a script to capture packets using scapy and netinfo


code:
string_list = string.split(' ')
for word in wordList:
    if word in string_list:
        print word

rawDescription: How do I check a string for certain words without getting matches for parts of the words in the string in Python?

description: Check a string for certain words without getting matches for parts of the words in the string in Python


code:
import operator

class Range(object):

    def __init__(self, value, lowerbound, upperbound):
        self._lowerbound = lowerbound
        self._upperbound = upperbound
        self.value = value

    def __repr__(self):
        return "<Range: %s>" % (self.value)

    def _from_value(self, val):
        val = max(min(val, self._upperbound), self._lowerbound)
        # NOTE: it's nice to use type(self) instead of writing the class
        # name explicitly; it then continues to work if you change the
        # class name, or use a subclass
        return type(self)(val, rng._lowerbound, rng._upperbound)

    def _make_binary_method(fn):
        # this is NOT a method, just a helper function that is used
        # while the class body is being evaluated
        def bin_op(self, other):
            return self._from_value(fn(self.value, other))
        return bin_op

    __mul__ = _make_binary_method(operator.mul)
    __div__ = _make_binary_method(operator.truediv)
    __truediv__ = __div__
    __add__ = _make_binary_method(operator.add)
    __sub__ = _make_binary_method(operator.sub)

rng = Range(7, 0, 10)
print rng + 5
print rng * 50
print rng - 10
print rng / 100

rawDescription: Decorating arithmetic operators | should I be using a metaclass?


code:
i = 1
try:
    print stories[i]['title']
except IndexError:
    print "Story does not exist at index %d" % i

rawDescription: Python json get specific story and image


code:
def get_code(tree, feature_names):
        left      = tree.tree_.children_left
        right     = tree.tree_.children_right
        threshold = tree.tree_.threshold
        features  = [feature_names[i] for i in tree.tree_.feature]
        value = tree.tree_.value

        def recurse(left, right, threshold, features, node):
                if (threshold[node] != -2):
                        print "if ( " + features[node] + " <= " + str(threshold[node]) + " ) {"
                        if left[node] != -1:
                                recurse (left, right, threshold, features,left[node])
                        print "} else {"
                        if right[node] != -1:
                                recurse (left, right, threshold, features,right[node])
                        print "}"
                else:
                        print "return " + str(value[node])

        recurse(left, right, threshold, features, 0)

rawDescription: how to extract the decision rules from scikit-learn decision-tree?

description: Extract the decision rules from scikit-learn decision-tree


code:
import numpy as np
a = np.arange(12).reshape((4,3))
print a

n = np.array([[1.1,2.2,3.3]])
print n

print a/n

rawDescription: Divide each row by a vector element with floating value precision


code:
cache = {}
def how_many_used(n):
    if n in cache:
        return cache[n]
    result = 0
    if int(n) >= 10:
        if n[0] == '1':
            result += int(n[1:]) + 1
        result += how_many_used(str(int(n[1:])))
        result += how_many_used(str(int(str(int(n[0])-1) + "9"*(len(n) - 1))))
    else:
        result += 1 if n >= '1' else 0
    if n.endswith("9" * (len(n)-0)) or n.endswith("0" * (len(n)-1)):
        cache[n] = result
    return result

def how_many_have(i, stickers):
    return int(i) * stickers

def end_state(i, stickers):
    if i == '':
        return 0
    return how_many_have(i, stickers) - how_many_used(i)

cache2 = {}
def lowest_state(i, stickers):
    if stickers <= 0:
        return end_state(i, stickers)
    if i in ('', '0'):
        return 0
    if (i, stickers) in cache2:
        return cache2[(i, stickers)]

    lowest_candidats = []

    tail9 = '9' * (len(i)-1)
    if i[0] == '1':
        tail = str(int('0'+i[1:]))
        lowest_candidats.append(end_state(str(10**(len(i) - 1)), stickers))
        lowest_candidats.append(lowest_state(tail, stickers - 1) + end_state(str(10**(len(i) - 1)), stickers))
    else:
        tail = str(int(i[0])-1) + tail9
        series = end_state(tail9, stickers)
        if series < 0:
             lowest_candidats.append(lowest_state(str(int('0'+i[1:])), stickers) + end_state(i[0] + '0'*(len(i)-1), stickers))
        lowest_candidats.append(lowest_state(tail, stickers))
    result =  min(lowest_candidats)
    cache2[(i, stickers)] = result
    return result

def solve(stickers):
    i=1
    while lowest_state(str(i), stickers) >= 0:
        i *= 2

    top = i
    bottom = 0
    center = 0

    while top - bottom > 1:
        center = (top + bottom) / 2
        if lowest_state(str(center), stickers) >= 0:
            bottom = center
        else:
            top = center

    if lowest_state(str(top), stickers) >= 0:
        return top
    else:
        return bottom

import sys
sys.setrecursionlimit(sys.getrecursionlimit() * 10)

for i in xrange(10):
    print "%d: %d" % (i, solve(i))

rawDescription: Puzzle that defies the brute force approach?


code:
import re
from itertools import islice
groups = (4, 2, 2, 3, 3, 1)
def FormatPID(in_pid):
    pid_format = re.compile('\d{4}-\d{2}-\d{2}-\d{3}-\d{3}-\d{1}')
    in_pid = in_pid.zfill(15)
    if not pid_format.match(in_pid):
        it = iter(in_pid)
        return '-'.join(''.join(islice(it, i)) for i in groups)
    return in_pid

print FormatPID('1005191000060')
print FormatPID('001005191000060')
print FormatPID('0010-05-19-100-006-0')

rawDescription: Python how to force one string to match format of another


code:
#! /usr/bin/env python

import sys

def main():
    count = 1
    while True:
        line = sys.stdin.readline()
        if line == '':
            break   #EOF encountered

        print "%3d: [%s]" % (count, line[:-1])
        count += 1

if __name__ == '__main__':
    main()

rawDescription: Reading from stdin in Python 2.7.6. Sys.stdout.flush() and python -u doesn't work


code: print glob.glob.__doc__

rawDescription: List *.xyz files from a directory

description: List *.xyz files from a directory


code:
# this would print the object's __repr__
print "%r" % c

# this would print the object's __str__
print "%s" % c

rawDescription: Is there a python module that provides deeper analysis of a data structure than pprint?


code:
import json
from bs4 import BeautifulSoup

import requests

URL = 'http://www.ise.com/MarketDataService.asmx/ISE_Get_IntraDay_Summary'
response = requests.post(URL, headers={'Content-Type': 'application/json; charset=utf-8'})
data = json.loads(response.content)

soup = BeautifulSoup(data['d'])
for row in soup('tr'):
    print " | ".join(cell.text for cell in row('td'))

rawDescription: Scraping a website that uses AJAX Post to populate the data


code:
from ctypes import CDLL, POINTER, c_int, byref

dll = CDLL('test.so')

data1 = POINTER(c_int)()
data2 = POINTER(c_int)()
size = c_int()

dll.test(byref(size), byref(data1), byref(data2))

for i in range(size.value):
    print i, data1[i], data2[i]

rawDescription: Return malloc'ed array from C to Python using ctypes


code:
from lxml import etree
tree = etree.HTML('''

Title

Lorem Ipsum

                  ''')

imgs = tree.xpath('.//img')

for img in imgs:
    print 'OLD_SOURCE', img.get('src')
    img.set('src', '/media/new/python.jpg')

print etree.tostring(tree)

rawDescription: python regular expression find and replace html tag with specific attribute value

description: Python regular expression find and replace html tag with specific attribute value


code:
class B(object):

    def foo(self, aFunction, args):
        self.aThing = A("foo")
        aFunction(self.aThing, args)

    def bar(self) :
        self.foo(A.func, ["some", "stuff"])

class A(object):

    def __init__(self, name):
        self.name = name

    def func(self, args) :
        print "func called on", self.name, args

x = B()
x.bar()

rawDescription: Python, call passed function on object

description: Python, call passed function on object


code:
class Person(object):
    def __init__(self, name):
        self.name = name

def test(a):
    b = Person('b')
    print "{a.name} joins {b.name}".format(**locals())

test(Person('a'))

rawDescription: Passing current context to str.format?

description: Passing current context to str.format


code: print ''.join(word_list)

rawDescription: How can I print Chinese characters in the console?

description: Print Chinese characters in the console


code:
def groupLinesByMatch(filename,regex):
    import re
    from collections import defaultdict

    regex = re.compile(regex)
    result = defaultdict(list)

    for line in open(filename).readlines():
        matches = regex.match(line)
        if matches:
            result[matches.group(1)].append( line )

    return result.values()

for lines in groupLinesByMatch(filename, regex):
    for line in lines:
        print line,
    print

rawDescription: Search and return lines in a file with matching keyword in python


code:
import theano
import theano.tensor as T

max_time, num_batches, num_labels = 3, 4, 6
max_seq_len = 5

probs_ = np.arange(max_time * num_batches * num_labels).reshape(
    max_time, num_batches, num_labels)

targets_ = np.arange(num_batches * max_seq_len).reshape(max_seq_len,
    num_batches) % (num_batches - 1)  # mix stuff up

probs, targets = map(theano.shared, (probs_, targets_))

print probs_
print targets_

probs_y = probs[:, T.arange(targets.shape[1])[:, np.newaxis], targets.T]

print probs_y.eval()

rawDescription: Theano advanced indexing for tensor, shared index


code:
print [key
          for key, value in people.items()
          if value == criteria]

rawDescription: How do I iterate over a dictionary and return the key in Python?

description: Iterate over a dictionary and return the key in Python


code:
def get_payload(ldict):
    return {k:v for k,v in ldict.iteritems() if k != 'self' and v is not None}

class fred(object):
    some_class_var = 17
    def method(self, a, b=2):
        payload = get_payload(locals())
        print payload

rawDescription: Pythonic way of getting method arguments into a dict


code:
def used_by(tree, id, all_lnks=None):
    if all_lnks is None:
        all_lnks = set()
    lnks = tree.get(id)
    if not lnks:
        return all_lnks
    all_lnks.update(lnks)
    for lnk in lnks:
        all_lnks = used_by(tree, lnk, all_lnks)
    return all_lnks

for id in tree.keys():
    print id, 'is used by', list(used_by(tree, id))

rawDescription: How to reverse tree-like linkages in a set?

description: Reverse tree-like linkages in a set


code:
import re
regex_strings = ['test1','test2','test3']
regex = re.compile("(" + "|".join(regex_strings) + ")")
strgs = ['This is a test1','This is a test2','This is a test1','This is a test1','This is a test3']
result = []
for strg in strgs:
    temp = regex.search(strg)
    if temp:
        result.append(temp.group())
print result

rawDescription: Python regex list using list

description: Python regex list using list


rawDescription: Binning values into groups with a minimum size using pandas


code:
import inspect

chi_squared_template = """
def chi_squared(%(params)s):
    return (((f(data_x, %(params)s) - data_y) / errors) ** 2).sum()
"""

def make_chi_squared(f, data_x, data_y, errors):
    params = ", ".join(inspect.getargspec(f).args[1:])
    exec chi_squared_template % {"params": params}
    return chi_squared

rawDescription: How to define a chi2 value function for arbitrary function?

description: Define a chi2 value function for arbitrary function


code:
import pandas as pd

cats = pd.Categorical((1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L), (1L, 2L))
cats.categories = ('AAAA', 'BBBB')
data = pd.DataFrame({'rno': np.arange(1,9), 'channel': cats})
#   channel  rno
# 0    AAAA    1
# 1    BBBB    2
# 2    AAAA    3
# 3    AAAA    4
# 4    BBBB    5
# 5    BBBB    6
# 6    BBBB    7
# 7    AAAA    8

data10 = pd.get_dummies(data['channel']).astype(bool)

rawDescription: How to create lists from data frames in python

description: Create lists from data frames in python


rawDescription: Fastest way to count number of occurrences in a Python list


code:
x = ['x','y', '{a', 'b}', 'c']
print reassemble(x)

rawDescription: Functional programming in Python: returning none instead of correct value


code:
import re

text = '123.com 456.edu 999.com'

a = r'\d+\.(com|edu)'    # A capturing group.
b = r'\d+\.(?:com|edu)'  # A non-capturing group.

print re.findall(a, text)  # Only the captures: ['com', 'edu', 'com']
print re.findall(b, text)  # The full matches: ['123.com', '456.edu', '999.com']

rawDescription: EMAIL id matcher-python regular expression cant figure out


code:
from socket import *
s = socket()
s.connect(('example.com', 80))
s.send('GET / HTTP/1.1\r\n\r\n')
print s.recv(8192)

rawDescription: How to perform HTTP GET operation in Python?

description: Perform HTTP GET operation in Python


code:
dct = {'slab1': {'name':'myn1', 'age':20}, 'slab2':{'name':'myn2','age':200}}
lst = {'/store/dir1/dir_slab1/tindy', '/store/dir2/dirslab2_fine/tunka','/store/dir1/dirslab3/lunku'}
for item in lst:
   for pattern in dct:
      if pattern in item:
          print "%s, %s" % (item, dct[pattern]["age"])

rawDescription: match/search dict keys in elements of a list

description: Match/search dict keys in elements of a list


code:
class C(object):
    pass

vars(C)
type(C)
def get_me_a_c_class():
    return C

my_class = get_me_a_c_class()
my_instance = my_class()
type(my_instance)
type(get_me_a_c_class)
vars(get_me_a_c_class)
get_me_a_c_class.random_attribute = 5
print "Did I just put an attribute to a FUNCTION??: %s" % get_me_a_c_class.random_attribute

rawDescription: Duck-typable classes, ABC, iheritance, __new__


code:
import clang.cindex

s = '''
int fac(int n) {
    return (n>1) ? n*fac(n-1) : 1;
}
'''

idx = clang.cindex.Index.create()
tu = idx.parse('tmp.cpp', args=['-std=c++11'],
                unsaved_files=[('tmp.cpp', s)],  options=0)
for t in tu.get_tokens(extent=tu.cursor.extent):
    print t.kind

rawDescription: Using libclang to parse in C++ in Python


code:
playlist_feed = api.GetYouTubePlaylistFeed('http://gdata.youtube.com/feeds/api/playlists/E6DE6EC9A373AF57')
first_video = playlist_feed.entry[0]
entry_uri = [l.href for l in first_video.link if l.rel == 'related'][0]
video_entry = api.GetYouTubeVideoEntry(entry_uri)
print video_entry.GetSwfUrl()

rawDescription: is there a way to get the YouTubeVideoEntry from a YouTubePlayListVideoEntry in the python gdata youtube client?

description: Is there a way to get the YouTubeVideoEntry from a YouTubePlayListVideoEntry in the python gdata youtube client


code:
from pyspark.streaming import *
ssc = StreamingContext(sc, 30)
dataRdd = [sc.parallelize(d, 1) for d in [[1,2,3],[4,5],[6,7,8,9,9]]]
qs = ssc.queueStream(dataRdd)

def list_median((med,mylist),newval):
    mylist = [newval] if not mylist else mylist.append(newval)
    mylist = sorted(mylist)
    return (mylist[int(len(mylist)/2)], mylist)

medians = qs.reduce(list_median).map(lambda (med,list): med)
def printRec(rdd):
    import sys
    rdd.foreach(lambda rec: sys.stderr.write(repr(rec)))

medians.foreachRDD(printRec)
ssc.start(); ssc.awaitTermination()

rawDescription: Finding median in Spark Streaming

description: Finding median in Spark Streaming


code:
import Tkinter as tk

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

single = False

def test(event, extra=None):
    global single

    #print 'event-num:', event.num
    #print 'extra:', extra

    if extra == 1:
        single = True
        master.after(200, single_click)
    elif extra == 101:
        single = False
        click('double click')

def single_click():
    global single

    if single:
        single = False
        click('single click')

def click(msg):
    print 'It was', msg

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

master = tk.Tk()

b1 = tk.Button(master, text="QUIT", command=master.destroy, width=20, heigh=5)
b1.pack()

b2 = tk.Label(master, text="OK", width=20, heigh=5)
b2.pack()

b2.bind('<Double-Button-1>', lambda event:test(event,101))
b2.bind('<Button-1>', lambda event:test(event,1))

master.mainloop()

rawDescription: How would one bind two different button click events to the same label, namely "<Button-1>" and "<Double-Button1>" to same label?


code:
import types
class Test(object):
    @staticmethod
    def foo():
        print 'foo'

    def bar(self):
        print 'bar'

rawDescription: getattr on class objects

description: Getattr on class objects


code:
p = soup.find("meta", attrs={"itemprop": "price"})
print p['content']

rawDescription: How can I use beautiful soup to get the current price of a stock on Google Finance?

description: Use beautiful soup to get the current price of a stock on Google Finance


code:
def foo():
    return giveupthefunc()

zed = lambda: giveupthefunc()

bar, foo = foo, None

print bar()
print zed()

rawDescription: Python code to get current function into a variable?


code:
funcs = []
for i in range(3):
    a = i
    func = lambda x, a=a: a
    funcs.append(func)
print [func(0) for func in funcs]

rawDescription: functions depending on iterables

description: Functions depending on iterables


code: print foo

rawDescription: Python: How to make a cross-module variable?


code:
mylines = [
    "line1.split at the dot",
    "line2:split at the colon",
    "line3:a colon preceded. by a dot",
    "line4-neither a colon nor a dot"
]

for line in mylines:
    print split_log_line(line)

rawDescription: Split by the delimiter that comes first, Python


code:
def factorize(n):
    factors = []

    p = 2
    while True:
        while(n % p == 0 and n > 0): #while we can divide by smaller number, do so
            factors.append(p)
            n = n / p
        p += 1  #p is not necessary prime, but n%p == 0 only for prime numbers
        if p > n / p:
            break
    if n > 1:
        factors.append(n)
    return factors

print factorize(32*9*11*13*13)

rawDescription: Prime Factor Implementation

description: Prime Factor Implementation


rawDescription: Apply non-linear regression for multi dimension data samples in Python


code:
import ctypes
print ctypes.c_int(0xA867DF55 ^ 0).value

rawDescription: Replicating Javascript bitwise operation in Python


code: print MyModel.objects.extra(select={'cnt': 'SELECT COUNT (*) FROM myapp_mymodel B WHERE B.text LIKE "%%" || myapp_mymodel.text || "%%"'}, where=['cnt = 1']).query

rawDescription: How to compare field values across instances in a Django queryset?

description: Compare field values across instances in a Django queryset


code:
@synchronized
def foo(*args):
  print 'Only one thread can enter this function at a time'

rawDescription: Thead-safe object and dict types in python


code:
#!/usr/bin/env python

import random
import time

def test1():
    print "for loop with no multiproc: "
    m = 10000000
    t = time.time()
    for i in range(m):
        pick = random.choice(['on', 'off', 'both'])
    print time.time()-t

def test2():
    print "map with no multiproc: "
    m = 10000000
    t = time.time()
    map(lambda x: random.choice(['on', 'off', 'both']), range(m))
    print time.time()-t

def rdc(x):
    return random.choice(['on', 'off', 'both'])

def test3():
    from multiprocessing import Pool

    pool = Pool(processes=4)
    m = 10000000

    print "map with multiproc: "
    t = time.time()

    r = pool.map(rdc, range(m))
    print time.time()-t

if __name__ == "__main__":
    test1()
    test2()
    test3()

rawDescription: Speed-up a single task using multi-processing or threading


code:
import lxml.html as lh
from lxml import etree

elem_tree = lh.parse("Q12.html")
input_string = ["SFO to JFK on May 2, 2015", "Traveler name is John Doe"]

for i in input_string:
    xpath = "//*[contains(normalize-space(.), '{0}') and not(.//*[contains(normalize-space(.), '{0}')])]/*"
    node = elem_tree.xpath(xpath.format(i))[0]

    print '{0} -> {1}'.format(i, elem_tree.getpath(node))

    #Output:
    #SFO to JFK on May 2, 2015 -> /html/body/p[2]/b[1]
    #Traveler name is John Doe -> /html/body/div/h3

rawDescription: Get xpath for nodes that form a string in HTML document


code:
a=['comp','graphics','card','part']
with open('hello.txt', 'r') as f:
    for line in f:     # now the file is only done once...
        for key in a:  # ... and the key loop is done multiple times
            if key in line:
                print line, key

rawDescription: python parse prints only first line from list

description: Python parse prints only first line from list


code:
# function which returns highest mark given the name
high_mark = lambda name:max(s[name])
for i in sorted(s.keys(),key=high_mark,reverse=True):
    print i,high_mark(i)

rawDescription: Select and sort integers/strings from a text file in Python


code: print mydict['my_item']

rawDescription: Python: how to turn string into a list?

description: Python: how to turn string into a list


code:
tuples = [['Hussain', '1', '0', '0', '3'], ['Bon', '2', '1', '2', '3'], ['Alice', '1', '5', '2', '3'], ['Josh', '3', '1', '7', '10'], ['Jack', '2', '0', '8', '9'], ['Zyra', '3', '5', '1', '6']]

class_to_sort = 1

# reduce to classes that are requested by user
tuples = filter(lambda tuple: int(tuple[1]) == class_to_sort, tuples)

# sort the tuples
tuples = sorted(tuples, key=lambda tuple: tuple[0])

# throw out second column and converts strings to integers
tuples = [[tuple[0]] + map(int, tuple[2:]) for tuple in tuples]

# throw out all integers that aren't the maximum per tuple
tuples = [[tuple[0]] + [max(tuple[1:])] for tuple in tuples]

print tuples

rawDescription: Split many lists into 2 sections which contain strings and numbers


code:
import urllib2,sys
from BeautifulSoup import BeautifulSoup

address = 'http://www.presidency.ucsb.edu/ws/index.php?pid=29644&st=&st1=#axzz1fD98kGZW'
soup = BeautifulSoup(urllib2.urlopen(address).read())
span = soup.find("span", {"class":"displaytext"})
paras = [x for x in span.findAllNext("p")]

start = span.string
middle = "\n\n".join(["".join(x.findAll(text=True)) for x in paras[:-1]])
last = paras[-1].contents[0]
print "%s\n\n%s\n\n%s" % (start, middle, last)

rawDescription: Scraping with BeautifulSoup and multiple paragraphs


code:
from bs4 import BeautifulSoup
input_document = '''\

      About Us

      Help & Support

      Law & Information

'''
soup = BeautifulSoup(input_document)
for li in soup.find_all('li'):
    li.decompose()

print soup

rawDescription: How to remove content of <li>tags from HTML

description: Remove content of <li>tags from HTML


code:
import wx

x = dir(wx)
for y in x:
    if y.startswith('ID_'):
        print y

rawDescription: Special IDs in Python , want to create a Help section in Menu


code:
frob = (lambda f: lambda x: f(f,x))(lambda f, x: x if str(x) == str(x)[::-1] else f(f, x + int(str(x)[::-1])))
print frob(29)

rawDescription: Generating list until certain condition is met using a single line


code:
original = "/users/experiment_in14"
output2 = subprocess.check_output(['find', original, '-empty'])
print output2

rawDescription: replace path in subprocess.check_output()

description: Replace path in subprocess.check_output()


code:
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np

adjacency_matrix = np.array([[0,1,0,1], [1,0,1,0], [0,1,0,1], [1,0,1,0]])
print adjacency_matrix

rawDescription: How to find the number of edges bewteen any two nodes using networkx?

description: Find the number of edges bewteen any two nodes using networkx


code: print repr(raw_input('?'))  # You'll get 'f', not 'f\n'

rawDescription: Difference between python script output and python console output


code:
import itertools

files = ['a.dat', 'b.dat', 'c.dat']
handles = [open(file, 'r') for file in files]

for a, b, c in itertools.izip_longest(*handles, fillvalue=''):
    print a
    print b
    print c

rawDescription: Iterate over multiple generators (file handles)


rawDescription: Get text separated by tags / BS4

description: Get text separated by tags / BS4


code: result = [map(itemgetter(1), g) for k, g in groupby(enumerate(cycles), lambda (i,x):i-x)]

rawDescription: Adding data to an array instead of print?


code:
n = -4
for bit in reversed([ (n>>shift)&1 for shift in range(32) ]):
   print bit,

rawDescription: count the the number of 1s in its binary representation -- shift right don't work?

description: Count the the number of 1s in its binary representation -- shift right don't work


code:
s=u'M\xfcrk'
print s        # Formatted for output display
print repr(s)  # Formatted to view type and content
s              # It is what you get by default at interactive prompt

rawDescription: what makes a python webscrape output unicode?

description: What makes a python webscrape output unicode


code:
from itertools import groupby
import numpy as np

array_list = []

with open('data.txt') as f_data:
    for k, g in groupby(f_data, lambda x: x.startswith('#')):
        if not k:
            array_list.append(np.array([[float(x) for x in d.split()] for d in g if len(d.strip())]))

for entry in array_list:
    print entry
    print

rawDescription: Read txt data separated by empty lines as several numpy arrays


rawDescription: Tokenising integers in a string

description: Tokenising integers in a string


rawDescription: columnize with ljust in python

description: Columnize with ljust in python


code:
import re

s = "foo[bar]baz"
m = re.search("[\[\]]", s)
print m.group(0)
# => '['

t = "foo-bar]baz"
n = re.search("[\[\]]", t)
print n.group(0)
# => ']'

rawDescription: Search for brackets in a case insensitive using regular expressions


code: print data['8.12.']

rawDescription: Extracting data from a text file

description: Extracting data from a text file


code:
def some_method_wrapper(parent):

    def some_method():
        #access any parent attribute
        #by using the parent positional argument passed to the function
        print parent.desired_attribute
        return 'blabla'

    setattr(parent, 'new_attr', some_method)

rawDescription: How to get parent attributes from a child method attribute in Python?

description: Get parent attributes from a child method attribute in Python


code:
from foo import bar

print bar

rawDescription: Little confused with import python

description: Little confused with import python


code:
text = "devkit (c) 2012, ARM-3.4. aLL DATA conf"
pattern = re.compile(r'/\*(?:[^/]|(?<!\*)/)*?' + re.escape(text) + r'(?:[^/]|/(?!\*))*?\*/')
pattern.sub("", string)
print pattern.sub("", input)

rawDescription: How to do a non-greedy match

description: Do a non-greedy match


code:
import json
import urllib2
import csv

def api_iterate(myfile):
    url = "https://api-v3.mojepanstwo.pl/dane/krs_osoby"
    csv_myfile = csv.writer(myfile)
    cols = ['id', 'url']
    csv_myfile.writerow(cols)       # Write a header

    while True:
        print url
        json_page = urllib2.urlopen(url)
        data = json.load(json_page)
        json_page.close()

        for data_object in data['Dataobject']:
            csv_myfile.writerow([data_object[col] for col in cols])

        try:
            url = data['Links']['next']     # Get the next url
        except KeyError as e:
            break

with open(r'e:\python temp\output.csv', 'wb') as myfile:
    api_iterate(myfile)

rawDescription: Read data from api and populate .csv bug


code:
#!/usr/bin/env python
import os
import re
import sys

def fgrep(words, filenames, encoding='utf-8', case_insensitive=False):
    findwords = re.compile("|".join(r"\b%s\b" % re.escape(w) for w in words),
                           flags=re.I if case_insensitive else 0).findall
    for name in filenames:
        with open(name, 'rb') as file:
             text = file.read().decode(encoding)
             found_words = set(findwords(text))
             yield name, found_words

def main():
    words = [w.decode(sys.stdin.encoding) for w in sys.argv[1].split(",")]
    filenames = sys.argv[2:] # the rest is filenames
    for filename, found_words in fgrep(words, filenames):
        print "%s: %s" % (os.path.basename(filename), ",".join(found_words))

main()

rawDescription: Search for words (exact matches) in multiple texts using Python


code:
class Vector(object):
    def __init__(self, vec):
        self.data = vec[:]
    def __iter__(self):
        for i in self.data:
            yield i

x = Vector([1,2,3])
x
for i in x:
    print i

rawDescription: How to use an object with 'for-in' in python?

description: Use an object with 'for-in' in python


code:
class Thing:
    def __init__(self):
        self.value = None

bar = Thing()
bar.value = False

def someFunction(incoming_variable):
    incoming_variable.value = True

someFunction(bar)

print bar.value

rawDescription: Change a variable from a function

description: Change a variable from a function


code:
price = soup.find(text=lambda x: x.startswith(title)).strip().split()[0]
print float(price)

rawDescription: how to obtain class contents in html using beautifulsoup?

description: Obtain class contents in html using beautifulsoup


code:
ss = 'one [two [three] ] end of line'
print re.sub(r'\[.+?\]\s?','',ss)

rawDescription: Using regex to replace object within brackets in a text file


code:
inputqueue=multiprocessing.Queue()
resultqueue=multiprocessing.Queue()
idqueue=multiprocessing.Queue()

def Function(data):
    print data #or what you want

for data in datas:
       inputqueue.put(data)
for i in xrange(nbprocess):
      processThread(i, inputqueue,idqueue,Function,resultqueue).start()

rawDescription: python multiprocessing - pool allocation

description: Python multiprocessing - pool allocation


code:
from script import airportCode
print airportCode

rawDescription: How to import or include data structures (e.g. a dict) into a Python file from a separate file

description: Import or include data structures (e.g. a dict) into a Python file from a separate file


code:
class Example:
    @staticmethod
    def print_stuff(*args):
        # No more self...
        print 'My *args* is {}'.format(args)

Example().print_stuff(1, 2, 3)
# My *args* is (1, 2, 3)

rawDescription: Function inside of Object generating different print output than stand-alone function in Python 3.5


code:
with open("commonwords.tsv") as f:
    line = f.read().replace("\t", "\n")
    for ind, word in enumerate(line.split(), 1):
        print "{0} {1}".format(ind, word)

rawDescription: split file with python into new lines with counter

description: Split file with python into new lines with counter


code:
from __future__ import division
import random

pi = random._pi
error = 0.1
inCircle, Total = 0,0
while (error >= 0.0001):
    print '%g ...'%error
    while True:
        x,y = random.random(), random.random()
        if (0.5-x)**2+(0.5-y)**2 <= 0.25: inCircle += 1
        Total += 1
        estimate = 4*inCircle/Total
        if abs(estimate/pi-1) <= error:
            print '{est.} %g vs. {pi} %g after %d trials, {err} %g\n'%( \
                   estimate,pi,Total,error)
            break
    error *= 0.1

rawDescription: Simulating Pi using Monte Carlo

description: Simulating Pi using Monte Carlo


code:
import pandas as pd
import csv

df = pd.read_csv('data.csv', warn_bad_lines=True, error_bad_lines=False)

#compare length of rows by recommended value:
RECOMMENDED = 3

with open('data.csv') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    for row in reader:
        if (len(row) != RECOMMENDED):
            print ("Length of row is: %r" % len(row) )
            print row

#compare length of rows by length of columns in df
lencols = len(df.columns)
print lencols

with open('data.csv') as csv_file:
    reader = csv.reader(csv_file, delimiter=',')
    for row in reader:
        if (len(row) != lencols):
            print ("Length of row is: %r" % len(row) )
            print row

rawDescription: Pandas Bad Lines Warning Capture

description: Pandas Bad Lines Warning Capture


code:
for name in ['A', 'B', 'C']:
    class_ = type(name, (object, ), {})
    globals()[name] = class_

print A, B, C

rawDescription: Populating values in module namespace

description: Populating values in module namespace


code:
def number_to_name(number):
# fill in your code below

# convert number to a name using if/elif/else
# don't forget to return the result!
    if number == 0:
        return 'rock'
    elif number == 1:
        return 'Spock'
    elif number == 2:
        return 'paper'
    elif number == 3:
        return 'lizard'
    elif number == 4:
        return 'scissors'

def name_to_number(name):
# fill in your code below

# convert name to number using if/elif/else
# don't forget to return the result!
    if name == 'rock':
        return 0
    elif name == 'Spock':
        return 1
    elif name == 'paper':
        return 2
    elif name == 'lizard':
        return 3
    elif name == 'scissors':
        return 4

def rpsls(name):
# fill in your code below

# convert name to player_number using name_to_number
    player_number = name_to_number(name)
# compute random guess for comp_number using random.randrange()
    comp_number = random.randrange(5)
# compute difference of player_number and comp_number modulo five
    difference = (player_number - comp_number) % 5
# use if/elif/else to determine winner
    if difference in [1, 2]:
        winmsg = "Player wins!"
    elif difference == 0:
        winmsg = "Player and computer tie!"
    else:
        winmsg = "Computer wins!"
# convert comp_number to name using number_to_name
    comp_name = number_to_name(comp_number)
# print results
    print " "
    print "Player chooses " + str(name)
    print "Computer chooses " + str(comp_name)
    print winmsg

rawDescription: Why this code gives me error?

description: Why this code gives me error


code:
strs = "a b c d ef gh i"
strs.split()
print str.split.__doc__

rawDescription: convert first column of data from text file into a list in python

description: Convert first column of data from text file into a list in python


rawDescription: Creating a Python dictionary

description: Creating a Python dictionary


code: print ['{0:.2f}'.format(float(15)/x*100) for x in range(15,21)]

rawDescription: Python multiply range

description: Python multiply range


code:
name = raw_input("What is your name?\n> ")
print "Hello {}!".format(name)

rawDescription: More elegant way to produce a space python


code:
for item in position_start:
    print item

rawDescription: how to print the list of strings from the arrays

description: Print the list of strings from the arrays


code:
import sys # Used to add the BeautifulSoup folder the import path
import urllib2 # Used to read the html document

if __name__ == "__main__":
    ### Import Beautiful Soup
    ### Here, I have the BeautifulSoup folder in the level of this Python script
    ### So I need to tell Python where to look.
    sys.path.append("./BeautifulSoup")
    from BeautifulSoup import BeautifulSoup

    ### Create opener with Google-friendly user agent
    opener = urllib2.build_opener()
    opener.addheaders = [('User-agent', 'Mozilla/5.0')]

    ### Open page & generate soup
    ### the "start" variable will be used to iterate through 10 pages.
    for start in range(0,10):
        url = "http://www.google.com/search?q=site:stackoverflow.com&start=" + str(start*10)
        page = opener.open(url)
        soup = BeautifulSoup(page)

        ### Parse and find
        ### Looks like google contains URLs in <cite> tags.
        ### So for each cite tag on each page (10), print its contents (url)
        for cite in soup.findAll('cite'):
            print cite.text

rawDescription: Extract Google Search Results

description: Extract Google Search Results


code:
def run(self):
        while True:
            customer=Customer()
            self.mutex.acquire()

            if self.queue.full():
                print "Queue is full : Cant Enter Critical Section"
                # NOTE 1: you have to release mutex here: self.mutex.release()
            elif not self.queue.full():
                # NOTE 2: other threads can enter after releasing the lock
                print self.mutex.release()

                self.mutex.acquire()
                #Critical Section
                self.queue.put(customer)
                print "Customer %d Enters the Queue with %d service " %(
                    customer.id,customer.serviceTime
                )
                self.mutex.release()

rawDescription: Lock variable in python in a loop

description: Lock variable in python in a loop


code: print "{0} experience, {1} with {2}".format(*mytuple)

rawDescription: Printing formatted tuple values

description: Printing formatted tuple values


code:
# plugin1.py

# Register this plugin
import master
master.register()

# Respond to request from master
def shout():
   print "Hello from", __name__

rawDescription: How can I call a function from inside an imported module, aka design issue

description: Call a function from inside an imported module, aka design issue


code:
list_of_lists = [a, b]
print sorted(set(elem for l in list_of_lists for elem in l))

rawDescription: Given a bunch of ranges of numbers, get all the numbers within those ranges?


code:
from pandas import DataFrame

# A sparse matrix in dictionary form (can be a SQLite database). Tuples contains doc_id        and term_id.
doc_term_dict={('d1','t1'):12, ('d2','t3'):10, ('d3','t2'):5}

#extract all unique documents and terms ids and intialize a empty dataframe.
rows = set([d for (d,t) in doc_term_dict.keys()])
cols = set([t for (d,t) in doc_term_dict.keys()])
df = DataFrame(index = rows, columns = cols )
df = df.fillna(0)

#assign all nonzero values in dataframe
for key, value in doc_term_dict.items():
    df[key[1]][key[0]] = value

print df

rawDescription: Generating a dense matrix from a sparse matrix in numpy python


code:
import array
from ctypes import *

def get_file_info(filename, info):
    """
    Extract information from a file.
    """
    # Get size needed for buffer (0 if no info)
    size = windll.version.GetFileVersionInfoSizeA(filename, None)
    # If no info in file -> empty string
    if not size:
        return ''
    # Create buffer
    res = create_string_buffer(size)
    # Load file informations into buffer res
    windll.version.GetFileVersionInfoA(filename, None, size, res)
    r = c_uint()
    l = c_uint()
    # Look for codepages
    windll.version.VerQueryValueA(res, '\\VarFileInfo\\Translation',
                                  byref(r), byref(l))
    # If no codepage -> empty string
    if not l.value:
        return ''
    # Take the first codepage (what else ?)
    codepages = array.array('H', string_at(r.value, l.value))
    codepage = tuple(codepages[:2].tolist())
    # Extract information
    windll.version.VerQueryValueA(res, ('\\StringFileInfo\\%04x%04x\\'
+ info) % codepage, byref(r), byref(l))
    return string_at(r.value, l.value)

print get_file_info(r'C:\WINDOWS\system32\calc.exe', 'FileVersion')

rawDescription: Finding the version of an application from Python?


code:
import sys
print sys.builtin_module_names

rawDescription: where does the random.random.__doc__ doc string live?

description: Where does the random.random.__doc__ doc string live


code:
class UltimateBase(object):
    def dispatch(self, *args, **kwargs):
        print 'base dispatch'

class FooMixin(object):
    def dispatch(self, *args, **kwargs):
        print 'perform check A'
        return super(FooMixin, self).dispatch(*args, **kwargs)

class BarMixin(object):
    def dispatch(self, *args, **kwargs):
        print 'perform check B'
        return super(BarMixin, self).dispatch(*args, **kwargs)

class FooBar(FooMixin, BarMixin, UltimateBase):
    pass

FooBar().dispatch()

rawDescription: How does the order of mixins affect the derived class?


code:
class MyClass(object):
    def __init__(self):
        super(MyClass, self).__init__()
        self.__my_attr = 'My_Value'

    @property
    def my_attr(self):
        return self.__my_attr

    def doSomething(self):
        localVariable = self.__my_attr
        print localVariable

rawDescription: Python Classes Best Practices

description: Python Classes Best Practices


code:
class ThreadSafeList(list):
    def __init__(self, *args):
        super(ThreadSafeList, self).__init__(*args)
        self.lock = threading.Lock()
    def __setitem__(self, idx, value):
        with self.lock:
            print 'list acquired'
            super(ThreadSafeList, self)[idx] = value
            print 'list released'

rawDescription: Threading lock in python not working as desired


code:
import pandas
# create three rows of [0, 1, 2]
df = pandas.DataFrame([range(3), range(3), range(3)])
print df
my_columns = ["a", "b", "c"]
df.columns = my_columns
print df

rawDescription: Assigning column names from a list to a table


code:
def main():
  print 'Hello, world.'

if __name__ == '__main__':
  main()

rawDescription: Import Python Functions from Auto-Running Script


code:
#!/usr/bin/python

import time
import subprocess
import sys
import msvcrt

alarm1 = int(raw_input("How many seconds (alarm1)? "))

while (1):
    time.sleep(alarm1)
    print "Alarm1"
    sys.stdout.flush()

    # Try to flush the buffer
    while msvcrt.kbhit():
        msvcrt.getch()

    print "Continue (Y/N)?[Y]"
    doit = msvcrt.getch()
    print "Input",doit
    if doit == 'N' or doit=='n':
        print "Exiting....."
        break

rawDescription: How to flush the input stream in python?

description: Flush the input stream in python


code:
a = np.asarray([[1, 2, 3], [3, 4, 5]])

mask = np.zeros(a.shape,dtype=np.bool)

mask[:,1] = a[:,1] > 3

print mask

rawDescription: Filtering on one dimension retaining shape of array


code:
with A() as myobj:
    print 'inside with block'
    myobj.do_something()

rawDescription: python : tracking change in class to save it at the end

description: Python : tracking change in class to save it at the end


code:
try:
    response = tn.read_until(">", timeout=120) #or whatever timeout you choose.
except EOFError as e:
    print "Connection closed: %s" % e
if ">" in response:
   action1
else:
   action2

rawDescription: Python Telnetlib read_until '#' or '>', mutiple string determination?


code:
fname = raw_input("Enter file name: ")

with open(fname, 'rb') as fn:

    count = 0
    lst = []
    for line in fn:
        if line.startswith('From:'):
            print line.split()[1]
            count += 1

print "There were", count, "lines in the file with From as the first word"

rawDescription: List is printing index value twice

description: List is printing index value twice


code:
f = open("3HDL.pdb", "r")

for line in f:
  if line.startswith("REMARK 800"):
    if line.startswith("SITE_IDENTIFIER:", 11):
      site_id = line[28:].rstrip()
    elif line.startswith("EVIDENCE_CODE:", 11):
      evidence_code = line[26:].rstrip()
    elif line.startswith("SITE_DESCRIPTION:", 11):
      site_descrip = line[29:].rstrip()
      print site_id, evidence_code, site_descrip

f.close()

rawDescription: How to collect and gather words from multiple lines in a input text (PDB file) using Python?

description: Collect and gather words from multiple lines in a input text (PDB file) using Python


rawDescription: Python (2.7) dictionary Jinja confusion

description: Python (2.7) dictionary Jinja confusion


code:
import requests
p = requests.models.PreparedRequest()

data={'key1': 'value', 'key2': str(10)}
p.prepare_url(url='http://somehost.com/somecontroller/action', params=data)

print p.url

rawDescription: Python call URL with key=value pairs

description: Python call URL with key=value pairs


code:
def get_values_json( js, res ):
    if type(js) == list:
        for e in js:
            get_values_json(e, res)
    elif type(js) == dict:
        for k,v in js.iteritems():
            if type(v) ==  dict or type(v) == list:
                get_values_json(v, res)
            else:
                if k == 'lat' or k == 'lon':
                    res[k].append(v)

res = {'lat':[], 'lon':[]}
get_values_json(js, res)
print res

rawDescription: Write a loop that parses json dictionaries using python


code:
def file_split(file_name, delimiter, n=1):
    with open(file_name) as fh:
        for line in fh:
            line = line.rstrip()    # use .rstrip("\n") to only strip newlines
            if line == delimiter:
                n -= 1
                if n <= 0:
                    return
            print line

file_split('data.txt', '//', 3)

rawDescription: Python - Splitting a large string by number of delimiter occurrences


code:
d = {'foo': 'bar',
     'baz': {'fie': 'foo', 'zip': 'zap'},
     'bam': {'fie': 'foo', 'zip': {'zap': 'zup', 'mep': 'mop'}},
    }
print flattendict(d)

rawDescription: Transforming deeply nested dictionary to 1D dictionary with Python


code:
import hashlib
import bencode
data = ['only', 'lists', [1,2,3],
'dictionaries', {'a':0,'b':1}, 'numbers', 47, 'strings']
data_md5 = hashlib.md5(bencode.bencode(data)).hexdigest()
print data_md5

rawDescription: Computing an md5 hash of a data structure


code:
from pythonFunction import function
print function() # no need for pythonFunction.

rawDescription: how to call a function from another file?

description: Call a function from another file


code:
#!/usr/bin/python2.7
import argparse as ap
import sys

print 'sys.stdin.encoding is ', sys.stdin.encoding
print 'sys.getfilesystemencoding() is', sys.getfilesystemencoding()

def encoded(s):
    print 'encoded', repr(s)
    return s

def decoded_filesystemencoding(s):
    try:
        s = s.decode(sys.getfilesystemencoding())
    except UnicodeDecodeError:
        s = 'failed!'
    return s

def decoded_stdinputencoding(s):
    try:
        s = s.decode(sys.stdin.encoding)
    except UnicodeDecodeError:
        s = 'failed!'
    return s

parser = ap.ArgumentParser()
parser.add_argument('first', type=encoded)
parser.add_argument('second', type=decoded_filesystemencoding)
parser.add_argument('third', type=decoded_stdinputencoding)
args = parser.parse_args()

print repr(args)

rawDescription: Best way to decode command line inputs to Unicode Python 2.7 scripts

description: Decode command line inputs to Unicode Python 2.7 scripts