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

data = [
    ("Alice", [
        ("Keys", []),
        ("Purse", [
            ("Cellphone", [])
            ])
        ]),
    ("Bob", [
        ("Wallet", [
            ("Credit card", []),
            ("Money", [])
            ])
        ])
    ]

class Window(QWidget):

    def __init__(self):

        QWidget.__init__(self)

        self.treeView = QTreeView()
        self.treeView.setContextMenuPolicy(Qt.CustomContextMenu)
        self.treeView.customContextMenuRequested.connect(self.openMenu)

        self.model = QStandardItemModel()
        self.addItems(self.model, data)
        self.treeView.setModel(self.model)

        self.model.setHorizontalHeaderLabels([self.tr("Object")])

        layout = QVBoxLayout()
        layout.addWidget(self.treeView)
        self.setLayout(layout)

    def addItems(self, parent, elements):

        for text, children in elements:
            item = QStandardItem(text)
            parent.appendRow(item)
            if children:
                self.addItems(item, children)

    def openMenu(self, position):

        indexes = self.treeView.selectedIndexes()
        if len(indexes) > 0:

            level = 0
            index = indexes[0]
            while index.parent().isValid():
                index = index.parent()
                level += 1

        menu = QMenu()
        editMenu = None
        if level == 0:
            editMenu = QAction("Edit person", self)
            menu.addAction(editMenu)
        elif level == 1:
            editMenu = QAction("Edit object/container", self)
            menu.addAction(editMenu)
        elif level == 2:
            editMenu = QAction("Edit object", self)
            menu.addAction(editMenu)

        if editMenu:
            editMenu.triggered.connect(partial(self.editObjFunc, level))

        menu.exec_(self.treeView.viewport().mapToGlobal(position))

    def editObjFunc(self, level):
        print level

if __name__ == "__main__":

    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: How to send signal in context menu of QTreeWidget?

description: Send signal in context menu of QTreeWidget


code:
cstr = 'aabcdabcdabcdabcd'
dd = {}
for ii, ch in enumerate(cstr):
    # find all sequences of 3-6 characters long
    for jj in range(3,7):
        wrd = cstr[ii:ii+jj]
        if not len(wrd) == jj:
            break

        dd.setdefault(wrd, 0)
        dd[wrd] += 1

# find any "word" that occurs more than once
for k, v in dd.iteritems():
    if v > 2:
        print k, v

rawDescription: Find if groups of characters are repeated in a string in python


code:
import threading

def foo(number, name):
    print 'Hello from new thread'
    print 'Here are some arguments:', number, name

thread = threading.Thread(target=foo, args=(5,'bar'))
thread.start()

thread.join()

rawDescription: The Programming Theory Gods Strike: What is target = foo in Python 2.x?


code:
#!/usr/bin/env python

import requests
from json import loads

username = "liamgiannini"

r = requests.get('https://www.instagram.com/'+username)
html = r.text.encode("utf-8")
text = html[html.index("window._sharedData = ")+21:]
text = (text[:text.index("};</script>")]+"}").replace('\\"', "")
dictionary= loads(text)
data = dictionary["entry_data"]["ProfilePage"][0]["user"]

print "followers: "+str(data["followed_by"]["count"])

rawDescription: Extracting Text from Javascript using BeautifulSoup to obtain number of followers


code:
import urllib2
from BeautifulSoup import BeautifulSoup

url = "http://www.gsmarena.com/samsung-phones-f-9-0-p2.php"
text = urllib2.urlopen(url).read()
soup = BeautifulSoup(text)

data = soup.findAll('div',attrs={'class':'makers'})
for div in data:
    links = div.findAll('a')
    for a in links:
        print "http://www.gsmarena.com/" + a['href']

rawDescription: Python - Getting all links from a div having a class


code:
for model, category in self.current_session.query(Model, Category).join(Category).distinct():
    print model.category_id, category.name

rawDescription: how to use sqlalchemy for sql?

description: Use sqlalchemy for sql


code:
results = []

for number in aaa:
  if str(number)[0] == '4' and len(str(number)) == 4:
      results.append(number)

print results

rawDescription: Picking elements in a list in Python 2.7.6


code:
def capitalize_nested(x):
    newlist = []
    for item in x:
        newlist2 = []
        for word in item:
            newlist2.append(cap_first(word))
        newlist.append(newlist2)
    print newlist

rawDescription: Python capitalise first letter of words within nested lists


code:
g = gt.load_graph("flow-example.xml.gz") #producing example is in doc
cap = g.edge_properties["cap"]
src, tgt = g.vertex(0), g.vertex(1)
res = gt.boykov_kolmogorov_max_flow(g, src, tgt, cap)
res.a = cap.a - res.a  # the actual flow
max_flow = sum(res[e] for e in tgt.in_edges())
print max_flow
pos = g.vertex_properties["pos"]
gt.graph_draw(g, pos=pos, pin=True, penwidth=res, output="example-kolmogorov.png")

rawDescription: Fast max-flow min-cut library for Python


code:
class MyClass(object):
    def __init__(self, **kwargs): # variable named arguments
        for k, v in kwargs.items():
           setattr(self, k, v) # set the value of self.k to v, same as self.k = v

test = MyClass(param1="param1", param2="param2")
print test.param1 # "param1"

rawDescription: Self syntax in python

description: Self syntax in python


code:
def aceptar_piezas(self):
    num_piezas = self.entrypiezas.get()
    print num_piezas

    self.piezastext.grid_remove()
    self.entrypiezas.grid_remove()
    self.aceptarnumpiezas.grid_remove()
    # Create a list of tuples to hold the dynamically created Optionmenus
    # The first item in the tuple is the menu, the second is its variable
    self.optionmenus = list()
    n = 1
    while n <= int(num_piezas):
        self.textopieza = Label(self.frameOne, text = "Pieza", justify="left")
        self.textopieza.grid(row=n, column=0)

        # Variable for the Optionmenu
        var = StringVar()
        # The menu
        menu = OptionMenu(self.frameOne, var, "a","b","c")
        menu.grid(row=n, column=1)
        # Set the variable to "a" as default
        var.set("a")
        # Add the menu to the list of Optionmenus
        self.optionmenus.append((menu, var))

        n += 1
    def clicked():
        """This function was made just to demonstrate.  It is hooked up to the button"""
        for optionmenu in self.optionmenus:
            print optionmenu[1].get()
        print self.optionmenus
    # This button doesn't need to be in the while loop
    self.aceptarpiezas = Button(self.frameOne, text="Aceptar", command=clicked, width=8)
    self.aceptarpiezas.grid(row=int(num_piezas)+1, column=0)

rawDescription: Trying to put drop down list on a code using Tkinter


code:
from urlparse import urljoin

import requests
from bs4 import BeautifulSoup

base_url = 'http://www.chess.com/'
game_ids = []

next_page = 'http://www.chess.com/home/game_archive?sortby=&show=live&member=Hikaru'
while True:
    soup = BeautifulSoup(requests.get(next_page).content)

    # collect the game ids
    for link in soup.select('a[href^=/livechess/game?id=]'):
        gameid = link['href'].split("?id=")[1]
        game_ids.append(int(gameid))

    try:
        next_page = urljoin(base_url, soup.select('ul.pagination li.next-on a')[0].get('href'))
    except IndexError:
        break  # exiting the loop if "Next" link not found

print game_ids

rawDescription: BeautifulSoup looping through urls

description: BeautifulSoup looping through urls


code:
from multiprocessing import Process
import time
import threading

def f(name):
    time.sleep(100)
    print 'hello', name

def run_process_with_timeout(timeout, target, args):
    p = Process(target=target, args=args)
    p.start()
    time.sleep(timeout)
    p.terminate()

if __name__ == '__main__':
    t = threading.Thread(target=run_process_with_timeout, args=(5,f,('bob',)))
    t.start()
    print "This Needs to be Printed Immediately"

rawDescription: Terminate Python Process in a Limited Time


code:
import model

print model.Userdb.get_by_id(12)

rawDescription: How to call methods of Model Class in Interactive Console locally?

description: Call methods of Model Class in Interactive Console locally


code:
from urllib2 import urlopen
f = urlopen('http://localhost:8000')
for line in f:
    print line

rawDescription: Connect to python server using sockets in python 2.7


code:
@app.route("/", methods=("GET", "POST"))
def submit():
    form = MyForm(request.form, csrf_enabled=False)
    if form.validate_on_submit():
        print form.data

    return render_template("index.html", form=form)

rawDescription: Flask-WTF isn't processing my form response


code:
Str1 = '"HHHHLLLHHHHHLLLLL"'
if Str1.count("H") >= 8 : print "match"

rawDescription: How to search strings with certain number of occurence using Regular Expression?

description: Search strings with certain number of occurence using Regular Expression


code:
import argparse
import sys

class ExecuteShell(object):
    # This function demonstrates that you can put
    # methods in ExecuteShell(), if you need to,
    # without having them appear as command-line commands
    # simply by prepending an underscore.
    def _useful(self):
        """Useful method that ISNT a command."""
        return 3.14159

    def create(self, args):
        """create a file"""
        print 'xxxxxxxxxxx', args

    def list(self, args):
        """ccccccc"""
        print args

    def delete(self, args):
        """ddddddd"""
        print 'ddddddd'

class TestShell(object):

   def find_actions(self, subparsers, actions_module, args):
        for attr in (action for action in dir(actions_module) if not action.startswith('_')):
            callback = getattr(actions_module, attr)
            desc = callback.__doc__ or ''
            subparser = subparsers.add_parser(attr, description=desc, help=desc)

            # This add_argument describes the positional argument, like so:
            #   'files' -- the result of matching this argument will be
            #              stored in `options.files`
            #   metavar='FILE' -- The help messages will use the word "FILE"
            #                     when describing this argument
            #   nargs='+' -- `narg` describes how many arguments this should
            #                match. The value `+` means "all of them, but at
            #                least one."
            subparser.add_argument('files', metavar='FILE', nargs='+')

   def main(self, args):
        # setup parser
        parser = argparse.ArgumentParser()
        subparsers = parser.add_subparsers(dest='command')
        a = ExecuteShell()
        subcommand_parser = self.find_actions(subparsers, a, args)

        # Run parser
        args = parser.parse_args(args)

        # Run selected command
        # If we reach this statement, then:
        #    args.command is the command the user chose,
        #       for example, 'create' or 'list'
        #    args.files is the list of arguments that followed 'create' or 'list'
        #    a is an instance of ExecuteShell
        #    getattr(a, args.command) is the attribute or method of `a`
        #       the name in `args.command`, for example, a.create or a.list
        #    getattr(a, args.command)(args.files) invokes that method,
        #       passing in the list of user arguments
        #    So, this line in effect might call `a.create(['file1', 'file2'])`
        getattr(a, args.command)(args.files)

if __name__ == "__main__":

    a = TestShell()
    a.main(sys.argv[1:])

rawDescription: How to put 'args' into argparse.Argument in python

description: Put 'args' into argparse.Argument in python


code:
import datetime
import commands
import time
import sys

def main(argv):
  if len(argv) < 2:
    sys.stderr.write("Usage: %s <action>" % (argv[0],))
    return 1
  output = commands.getoutput("ps -e")
  while argv[1] in output:
    output = commands.getoutput("ps -e")
    print argv[1], " running", datetime.datetime.now()
    #it should be set depending upon the precision a user wants.
    time.sleep(5)
  sys.stderr.write("Process finished at %s\n" % datetime.datetime.now())

if __name__ == "__main__":
  sys.exit(main(sys.argv))

rawDescription: Note down time when a process stops

description: Note down time when a process stops


code:
import xlrd

book = xlrd.open_workbook("input.xls")
sheet = book.sheet_by_index(0)

print sheet.cell(0, 0)  # prints text:u'Andrea Bargnani'
print sheet.cell(0, 0).value  # prints Andrea Bargnani

rawDescription: Python 2.7 - xlrd - Matching A String To a Cell Value


code:
from lxml import parse
from lxml import etree
from io import StringIO

tree = etree.parse(StringIO("your file name"))
data_dict = dict()
for child in tree:
   # Element.tag return the PetOwnerTag. So u must go into, search the element by tag owner and get his value
   # data_dict[child.tag] = child
   owner = child.find("owner")
   if owner:
       data_dict[owner.text] = child

for owner in sorted(data_dict.iterkeys()):
    # here can u write your data to files
    print owner, etree.tostring (dict[owner])

rawDescription: Sorting XML according to certain tag

description: Sorting XML according to certain tag


code:
from mechanize import Browser

inp = raw_input("Enter Word: ")
Word = (inp)

SEARCH_PAGE = "http://dictionary.reference.com/"

browser = Browser()
browser.open( SEARCH_PAGE )

form = list(browser.forms())[0]                        #The first form
print form
names = map(lambda n: n.name, form.controls)
print names

browser.select_form( nr=0 )

browser[names[0]] = Word

txt = browser.submit().read()

#txt has the html from dictionary.reference.com

rawDescription: Input into site using Mechanize (Python)


code:
event = [0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1,
    1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1]
from itertools import izip_longest

def pair_iterator(event):
    event = [0] + event
    return enumerate(izip_longest(event, event[1:], fillvalue=0), -1)

def one_ranges(event):
    start = [i + 1 for i, pair in pair_iterator(event) if pair == (0, 1)]
    end = [i for i, pair in pair_iterator(event) if pair == (1, 0)]
    return zip(start, end)

print one_ranges(event)

rawDescription: getting the index of starting and ending 1 of a binary list having a sequence of 0s or 1s

description: Getting the index of starting and ending 1 of a binary list having a sequence of 0s or 1s


code:
from bs4 import BeautifulSoup

invalid = """<html>
<body>
</body>
</html>"""

valid = """<html>
<head>
</head>
<body>
</body>
</html>"""

def hashead(soup):
    if soup.head:
        print 'found head'
    else:
        print 'no head'

badsoup = BeautifulSoup(invalid, 'html.parser')
goodsoup = BeautifulSoup(valid, 'html.parser')

hashead(badsoup)
# >>> no head
hashead(goodsoup)
# >>> found head

rawDescription: How to check whether html has a head element with BeautifulSoup.

description: Check whether html has a head element with BeautifulSoup.


code:
import wx
from wx.lib import sized_controls

class MainFrame(sized_controls.SizedFrame):

    def __init__(self, *args, **kwargs):
        super(MainFrame, self).__init__(*args, **kwargs)
        self.SetTitle('MainFrame')
        pane = self.GetContentsPane()
        wx.Button(pane, label='No access until logged in')
        self.SetInitialSize((400, 400))

class LoginFrame(sized_controls.SizedDialog):

    def __init__(self, *args, **kwargs):
        super(LoginFrame, self).__init__(*args, **kwargs)
        self.parent = args[0]
        self.logged_in = False

        pane = self.GetContentsPane()

        pane_form = sized_controls.SizedPanel(pane)
        pane_form.SetSizerType('form')

        label = wx.StaticText(pane_form, label='User Name')
        label.SetSizerProps(halign='right', valign='center')

        self.user_name_ctrl = wx.TextCtrl(pane_form, size=((200, -1)))

        label = wx.StaticText(pane_form, label='Password')
        label.SetSizerProps(halign='right', valign='center')

        self.password_ctrl = wx.TextCtrl(
            pane_form, size=((200, -1)), style=wx.TE_PASSWORD)

        pane_btns = sized_controls.SizedPanel(pane)
        pane_btns.SetSizerType('horizontal')
        pane_btns.SetSizerProps(halign='right')

        login_btn = wx.Button(pane_btns, label='Login')
        login_btn.SetDefault()
        cancel_btn = wx.Button(pane_btns, label='Cancel')
        self.Fit()
        self.SetTitle('Login')
        self.CenterOnParent()
        self.parent.Disable()

        login_btn.Bind(wx.EVT_BUTTON, self.on_btn_login)
        cancel_btn.Bind(wx.EVT_BUTTON, self.on_btn_cancel)
        self.Bind(wx.EVT_CLOSE, self.on_close)

    def on_btn_login(self, event):
        user_name = self.user_name_ctrl.GetValue()
        password = self.password_ctrl.GetValue()
        print 'logged in as {} with password {}'.format(user_name, password)
        self.logged_in = True
        self.Close()

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

    def on_close(self, event):
        if not self.logged_in:
            self.parent.Close()
        self.parent.Enable()
        event.Skip()

if __name__ == '__main__':
    wxapp = wx.App(False)
    parent_frame = MainFrame(None)
    parent_frame.Show()
    login_frame = LoginFrame(parent_frame)
    login_frame.Show()
    wxapp.MainLoop()

rawDescription: Wxpython show dialog on main frame startup


code:
import win32com.client
objShell = win32com.client.Dispatch("WScript.Shell")
allUserDocs = objShell.SpecialFolders("AllUsersDesktop")
print allUserDocs

rawDescription: Find system folder locations in Python

description: Find system folder locations in Python


code:
with open("employees.yaml", 'r') as stream:
    out = yaml.load(stream)
    print out['Employees']['user']

rawDescription: Parse yaml into a list in python

description: Parse yaml into a list in python


code:
from Tkinter import *
import tkFileDialog
from PIL import ImageTk, Image

root = Tk()
#my_widget = Widget-name (its container window, ** its configuration options)
def callback():
    path = tkFileDialog.askopenfilename()
    print path

def create_widgets_in_first_frame():
    first_window_label1 = Label(first_frame, text="Analysis of Machine Learning Methods using Titanic Disaster Dataset",justify=CENTER,font=("Helvetica", 20,"bold")).place(x=200,y=20)

    first_window_label5 = Label(first_frame, text="Choose your Method:",justify=LEFT,font=("Helvetica", 15,"italic")).place(x=20,y=180)

    first_window_label2 = Label(first_frame, text="Upload your Titanic datasets .csv extension here:",justify=LEFT,font=("Helvetica", 15,"italic")).place(x=20,y=60)

    first_window_label3 = Label(first_frame, text="Training dataset ->",justify=LEFT,font=("Helvetica", 12)).place(x=50,y=100)
    training_data_path = StringVar()
    first_window_entry1 = Entry(first_frame, textvariable=training_data_path).place(x=350,y=100)
    first_window_button1 = Button(first_frame, text="Browse",command=lambda:training_data_path.set(tkFileDialog.askopenfilename())).place(x=550,y=100)

    first_window_label4 = Label(first_frame, text="Testing dataset ->",justify=LEFT,font=("Helvetica", 12)).place(x=50,y=140)
    testing_data_path = StringVar()
    first_window_entry2 = Entry(first_frame, textvariable=testing_data_path).place(x=350,y=140)
    first_window_button2 = Button(first_frame, text="Browse",command=lambda:testing_data_path.set(tkFileDialog.askopenfilename())).place(x=550,y=140)

    first_window_button3 = Button(first_frame, text="Decision Tree",font=("Helvetica", 15))
    first_window_button3.place(x=50,y=220)
    first_window_button3.bind('<Button-1>', call_second_frame_on_top)

    first_window_button4 = Button(first_frame, text="Random Forests",font=("Helvetica", 15))
    first_window_button4.place(x=350,y=220)
    first_window_button4.bind('<Button-1>', call_second_frame_on_top)

    first_window_button5 = Button(first_frame, text="Logistic Regression",font=("Helvetica", 15))
    first_window_button5.place(x=650,y=220)
    first_window_button5.bind('<Button-1>', call_second_frame_on_top)

    first_window_button6 = Button(first_frame, text="Analysis",font=("Helvetica", 15))
    first_window_button6.place(x=1000,y=220)
    first_window_button6.bind('<Button-1>', call_second_frame_on_top)

def create_widgets_in_second_frame():
    second_window_label6 = Label(root, text="Decision Trees",justify=CENTER,font=("Helvetica", 20,"bold")).place(x=200,y=20)
    print "graph is below"

def call_second_frame_on_top(event):
    first_frame.grid_forget()
    second_frame.grid(column=0, row=0, padx=20, pady=5)

window_width = 1300
window_heigth = 700

first_frame=Frame(root, width=window_width, height=window_heigth)
first_frame['borderwidth'] = 2
first_frame['relief'] = 'sunken'
first_frame.grid(column=0, row=0, padx=20, pady=5)

second_frame=Frame(root, width=window_width, height=window_heigth)
second_frame['borderwidth'] = 2
second_frame['relief'] = 'sunken'
second_frame.grid(column=0, row=0, padx=20, pady=5)

create_widgets_in_second_frame()
create_widgets_in_first_frame()

second_frame.grid_forget()

#root.minsize(width=1300, height=700)
#root.configure(background='lavender')
root.mainloop()

rawDescription: Unable to navigate to the next frame in the window using TKinter


code:
masterList = [[1, 123, 2], [22, 4567, 33], [0, 0, 0]]
print "\n".join("\t".join(["{0:04d}".format(num) for num in subList]) for subList in masterList)

rawDescription: Python pprint(): Can I format items in an array?


code:
import os
path = '/path/to/repo' # or use input from command line
savedPath = os.getcwd()

# do init stuff

os.chdir(path)

# do repo stuff
repo_path = '.'
repo_url = 'git@github.com:username/myfolder.git'
repo = Gittle(repo_path, origin_uri=repo_url)

print repo.modified_files

# finish repo stuff

os.chdir(savedPath)

# do other stuff

rawDescription: Gittle. How to get a true list of modified files?


code:
import collections

words = {'abandon':-2,'abandoned':-2,'abandons':-2,'abducted':-2,'abduction':-2,
'abductions':-2,'abhor': -3}
# throw away the values in the dictionary because they aren't being used
words = words.keys()

# this is a list [] not a dictionary ()
sentence = ['abandon', 'abandoned', 'abhorrent', 'hello', 'smart', 'hello',
    'die', 'happy', 'sad', 'up', 'down', 'happy', 'smart','cool',
    'clean', 'mean']

counts = collections.Counter([word for word in sentence if word not in words])

print counts
Counter({'hello': 2, 'smart': 2, 'happy': 2, 'down': 1, 'die': 1, 'up': 1,
'sad':1, 'abhorrent': 1, 'clean': 1, 'mean': 1, 'cool': 1})

rawDescription: Initialize dictionary, loop through list, add words and increment counter in dictionary


code:
br = mechanize.Browser()
resp = br.open('https://xxxxxxxxxxxxxxxxxxx')
br.select_form(nr=0)
br['username'] = username
br['password'] = password
response = br.submit()
time.sleep(1)
resp_second = br.open('https://secretwebpage')
print resp_second.read()

rawDescription: How to post data to a website, store cookies, then get another page

description: Post data to a website, store cookies, then get another page


code:
@route('/open/<item_id:int>/<url:path>')
def open(item_id , url):
    if request.query_string:
        url += '?' + request.query_string
    print url

rawDescription: path data type does't take the complete url with '?' in it

description: Path data type does't take the complete url with '?' in it


code:
def function1():
    var1 = raw_input("Please enter a number")
    var2 = raw_input("Please enter another number")
    return var1,var2

def function2():
    var1,var2 = function1()
    print var1,var2

while True:
    function2()

rawDescription: Returning variables and while True loop

description: Returning variables and while True loop


code:
import re

one_line = ''.join(menu).replace('\n', ' ')
print re.sub(', ([a-z]+:)', r'\n\1', one_line)[:-1]

rawDescription: combine text after : by python

description: Combine text after : by python


code:
from pylab import *

import time

ion()

tstart = time.time()               # for profiling
x = arange(0,2*pi,0.01)            # x-array
line, = plot(x,sin(x))

for i in arange(1,200):
    line.set_ydata(sin(x+i/10.0))  # update the data
    draw()                         # redraw the canvas

print 'FPS:' , 200/(time.time()-tstart)

rawDescription: Updating a plot in python in real time

description: Updating a plot in python in real time


code:
program_remaining = list()
for channel in channels:
    if current_time == start_time:
       print "the program has started"

    elif start_time != current_time < stop_time:
        print "program is half way"
        current_time = datetime.timedelta(hours = get_24_hours, minutes = get_24_minutes)
        end_program = datetime.timedelta(hours = int(program_hours), minutes = int(program_minutes))
        current_program = end_program - current_time
        test = int(current_program.seconds / 60)
    program_remaining.append(test)
    print "program_remaining"
    print program_remaining

rawDescription: create the list without reset the list

description: Create the list without reset the list


code:
m = [
    {'title': 'Song 1', 'artist': 'Artist 1',
        'Album': 'Album 1', 'Path': 'path 1'},
    {'title': 'Song 2', 'artist': 'Artist 1 Ft 2',
        'Album': 'Album 1', 'Path': 'path 2'},
    {'title': 'Song 3', 'artist': 'Artist 1 Ft 3',
        'Album': 'Album 1', 'Path': 'path 3'}
]

from collections import defaultdict

# Group all the artists, as per the Album name
d = defaultdict(list)
for item in m:
    d[item["Album"]].append(item["artist"])

# Gather paths corresponding to the Albums
p = {item["Album"]: item["Path"] for item in m}

# Recreate a list of all albums with artist names joined
result = []
for album in d:
    result.append({
        "Album" : album,
        "artist": "; ".join(d[album]),
        "Path"  : p[album]
    })

print result

rawDescription: Python: How to group dictionaries based on a key value pair


code:
import pygame
from pygame.locals import *
import math
import numpy

#----------------------------------------------------------------------
# functions
#----------------------------------------------------------------------

def SineWave(freq=1000, volume=16000, length=1):

    num_steps = length * SAMPLE_RATE
    s = []

    for n in range(num_steps):
        value = int(math.sin(n * freq * (6.28318/SAMPLE_RATE) * length) * volume)
        s.append( [value, value] )

    return numpy.array(s)

def SquareWave(freq=1000, volume=100000, length=1):

    num_steps = length * SAMPLE_RATE
    s = []

    length_of_plateau = SAMPLE_RATE / (2*freq)

    counter = 0
    state = 1

    for n in range(num_steps):

        value = state * volume
        s.append( [value, value] )

        counter += 1

        if counter == length_of_plateau:
            counter = 0
            state *= -1

    return numpy.array(s)

def MakeSound(arr):
    return pygame.sndarray.make_sound(arr)

def MakeSquareWave(freq=1000):
    return MakeSound(SquareWave(freq))

def MakeSineWave(freq=1000):
    return MakeSound(SineWave(freq))

#----------------------------------------------------------------------
# main program
#----------------------------------------------------------------------

pygame.init()

size = (1200, 720)
screen = pygame.display.set_mode(size, pygame.HWSURFACE | pygame.DOUBLEBUF)
pygame.display.set_caption('Nibbles!')

SAMPLE_RATE = 22050 ## This many array entries == 1 second of sound.

SINE_WAVE_TYPE = 'Sine'
SQUARE_WAVE_TYPE = 'Square'

sound_types = {SINE_WAVE_TYPE:SQUARE_WAVE_TYPE, SQUARE_WAVE_TYPE:SINE_WAVE_TYPE}

current_type = SINE_WAVE_TYPE

current_played = { 'z': None, 'c': None }

_running = True
while _running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            _running = False

        # some keys don't depend on `current_type`

        elif event.type == KEYDOWN:

            if event.key == K_ESCAPE:
                _running = False

            if event.key == K_RETURN:
                current_type = sound_types[current_type]  #Toggle
                print 'new type:', current_type

        # some keys depend on `current_type`

        if current_type == SINE_WAVE_TYPE:

            if event.type == KEYDOWN:

                #lower notes DOWN

                if event.key == K_z:
                    print current_type, 130.81
                    current_played['z'] = MakeSineWave(130.81)
                    current_played['z'].play()

                elif event.key == K_c:
                    print current_type, 180.81
                    current_played['c'] = MakeSineWave(180.81)
                    current_played['c'].play()

            elif event.type == KEYUP:

                #lower notes UP

                if event.key == K_z:
                    current_played['z'].fadeout(350)
                elif event.key == K_c:
                    current_played['c'].fadeout(350)

        elif current_type == SQUARE_WAVE_TYPE:

            if event.type == KEYDOWN:

                #lower notes DOWN

                if event.key == K_z:
                    print current_type, 80.81
                    current_played['z'] = MakeSineWave(80.81)
                    #current_played['z'] = MakeSquareWave(130.81)
                    current_played['z'].play()

                elif event.key == K_c:
                    print current_type, 180.81
                    current_played['c'] = MakeSineWave(180.81)
                    #current_played['c'] = MakeSquareWave(130.81)
                    current_played['c'].play()

            elif event.type == KEYUP:

                #lower notes UP

                if event.key == K_z:
                    current_played['z'].fadeout(350)
                elif event.key == K_c:
                    current_played['c'].fadeout(350)

pygame.quit()

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

rawDescription: Pygame audio code not working

description: Pygame audio code not working


code:
import web
import os
import urllib
import posixpath

urls = ("/.*", "hello")
app = web.application(urls, globals())

class hello:
    def GET(self):
        return 'Hello, world!'

class StaticMiddleware:
    """WSGI middleware for serving static files."""
    def __init__(self, app, prefix='/static/', root_path='/foo/bar/'):
        self.app = app
        self.prefix = prefix
        self.root_path = root_path

    def __call__(self, environ, start_response):
        path = environ.get('PATH_INFO', '')
        path = self.normpath(path)

        if path.startswith(self.prefix):
            environ["PATH_INFO"] = os.path.join(self.root_path, web.lstrips(path, self.prefix))
            return web.httpserver.StaticApp(environ, start_response)
        else:
            return self.app(environ, start_response)

    def normpath(self, path):
        path2 = posixpath.normpath(urllib.unquote(path))
        if path.endswith("/"):
            path2 += "/"
        return path2

if __name__ == "__main__":
    wsgifunc = app.wsgifunc()
    wsgifunc = StaticMiddleware(wsgifunc)
    wsgifunc = web.httpserver.LogMiddleware(wsgifunc)
    server = web.httpserver.WSGIServer(("0.0.0.0", 8080), wsgifunc)
    print "http://%s:%d/" % ("0.0.0.0", 8080)
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()

rawDescription: Changing the static directory path in webpy


code:
from UserDict import DictMixin

class SubDictView(DictMixin):

    def __init__(self, dct, keys):
        self._dct = dct
        self._keys = keys

    def __getitem__(self, key):
        if key not in self._keys:
            raise KeyError(key)
        return self._dct[key]

    def keys(self):
        return set(self._dct) & self._keys

    def __setitem__(self, key, val):
        raise RuntimeError('SubDictView is read-only')

    def __delitem__(self, key):
        raise RuntimeError('SubDictView is read-only')

d = {'a': 1, 'b': 2, 'c': 3}
dv = SubDictView(d, {'b', 'c'})
print dv
# {'c': 3, 'b': 2}
print 'a' in dv
# False
print dv['b']
# 2
print dv.get('a', 999)
# 999

rawDescription: Reusing dictionary without reconstruction


rawDescription: Vectorized operation on pandas dataframe


code:
def f(str):
    print str(123) # will raise an error, because 'str' is not callable (i.e. a function) anymore

f("some string here")

print str(123) # OK

rawDescription: Python built-in type as function parameter


code:
#!/usr/bin/env python
import subprocess

cmd = 'adb shell ls'
s = subprocess.check_output(cmd.split())
print s.split('\r\n')

rawDescription: Executing Android commands through Python and storing the result in a list


code:
s = 'string'
s2 = "'{0}'".format(s)
print s2

rawDescription: python Put Variable inside single quote

description: Python Put Variable inside single quote


code:
sequence = ['2', '4', '1', '2', '3', '4', '2', '4', '2', '4', '4']
key_list = ['2', '2', '4']

sub_lists = []
final_sub_lists = set()
len_key_list = len(key_list)

for index, value in enumerate(sequence):
    for sub_list in sub_lists:
        len_sub_list = len(sub_list)
        # Test if current value can continue the current sub list
        if len_sub_list < len_key_list and key_list[len_sub_list] == value:
            if len_sub_list == len_key_list - 1:
                # We have found a complete sub list
                final_sub_lists.add(tuple(sub_list + [index]))
            else:
                # We copy the current sub list to be sure not miss any sub lists
                # like for instance (6, 8, 9) and (6, 8, 10).
                sub_lists.insert(0, sub_list[:])
                sub_list.append(index)
    if key_list[0] == value:
        # Start a new sub list
        sub_lists.append([index])

print sorted(final_sub_lists)

rawDescription: Find specific sublists in a list

description: Find specific sublists in a list


code:
aword="iabcdefghijklm"
value=sum(map(ord,aword),(1-ord("a"))*len(aword))
print value==100, value

rawDescription: Changing a string into it's number value in python. [ord()]


code:
def backtracking(domains):
    if any(len(dom) == 0 for var, dom in domains.iteritems()):
        return None
    if all(len(dom) == 1 for var, dom in domains.iteritems()):
        return domains

    # minimum remaining values heuristic: process variables with few possible
    # values first (fail-first strategy)
    order = sorted(domains.iteritems(), key=lambda (var, dom): len(dom))
    for var, dom in order:
        if len(dom) == 1:
            continue

        for value in list(dom):
            doms = {v: d - {value} for v, d in domains.iteritems()
                                   if v != var}
            doms[var] = {value}

            solution = backtracking(doms)
            if solution is not None:
                return solution

print(backtracking({v: set(d) for v, d in options.iteritems()}))

rawDescription: Algorithm for resolving conflicts with overlapping choices


code:
import sys, signal, time

def handler(signum = None, frame = None):
    print 'Signal handler called with signal', signum
    time.sleep(1)  #here check if process is done
    print 'Wait done'
    sys.exit(0)

for sig in [signal.SIGTERM, signal.SIGINT, signal.SIGHUP, signal.SIGQUIT]:
    signal.signal(sig, handler)

while True:
    time.sleep(6)

rawDescription: How to properly handle and retain system shutdown (and SIGTERM) in order to finish its job in Python?

description: Properly handle and retain system shutdown (and SIGTERM) in order to finish its job in Python


code:
s = '2025'
for i in range(1, len(s)):
  print s[:i], s[i:]

rawDescription: In python how can I iterate through a string splitting it at different spots as I go?


code:
# subjects chooser

import Tkinter as tk

class SubjectsChooser(tk.Toplevel):

    def __init__(self, parent):
        tk.Toplevel.__init__(self, parent)
        self.parent = parent
        self.prompt = tk.Label(self.parent, text='Choose your school subjects',
                               border=1, relief='groove', padx=10, pady=10)
        self.prompt.pack(fill='both', padx=5, pady=5)

        self.top = tk.Frame(self.parent)

        # Using IntVar objects to save the state of the Checkbuttons
        # I will associate the property variable of each checkbutton
        # with the corrensponding IntVar object
        self.english_value = tk.IntVar(self.top)
        self.maths_value = tk.IntVar(self.top)
        self.sports_value = tk.IntVar(self.top)

        # I am saving the IntVar references in a list
        # in order to iterate through them easily,
        # when we need to check their values later!
        self.vars = [self.english_value, self.maths_value, self.sports_value]

        # Note I am associating the property 'variable' with self.english_value
        # which is a IntVar object
        # I am using this variables to check then the state of the checkbuttons
        # state: (checked=1, unchecked=0)
        self.english = tk.Checkbutton(self.top, text='English',
                                     variable=self.english_value)
        self.english.grid(row=0, column=0, sticky='nsw')
        self.maths = tk.Checkbutton(self.top, text='Maths',
                                   variable=self.maths_value)
        self.maths.grid(row=1, column=0, sticky='nsw')
        self.sports = tk.Checkbutton(self.top, text='Sports',
                                    variable=self.sports_value)
        self.sports.grid(row=2, column=0, sticky='nsw')
        self.top.pack(expand=1, fill='both')
        self.subjects = [self.english, self.maths, self.sports]

        self.bottom = tk.Frame(self.parent, border=1, relief='groove')
        # not I am associating self.choose as the command of self.ok
        self.ok = tk.Button(self.bottom, text='Confirm',
                           command=self.choose)
        self.ok.pack(side='right', padx=10, pady=5)
        self.bottom.pack(fill='both', padx=5, pady=5)

    def choose(self):
        # Needed to check how many checkbuttons are checked
        # Remember, the state of the check buttons is stored in
        # their corresponding IntVar variable
        # Actually, I could simply check the length of 'indices'.
        total_checked = 0
        indices = []  # will hold the indices of the checked subjects
        for index, intvar in enumerate(self.vars):
            if intvar.get() == 1:
                total_checked += 1
                indices.append(index)
        if total_checked <= 1:
            print 'You have to choose at least 2 subjects!'
        else:
            for i in indices:
                # using the method 'cget' to get the 'text' property
                # of the checked check buttons
                print 'You have choosen', self.subjects[i].cget('text')

if __name__ == '__main__': # in case this is launched as main app
    root = tk.Tk()
    schooser = SubjectsChooser(root)
    root.mainloop()

rawDescription: How can I get the value of a Label that is checked by a Checkbutton

description: Get the value of a Label that is checked by a Checkbutton


code:
import urllib2
import time

def testProxies(url, proxies):
    # prepare the request
    req = urllib2.Request(url)
    # run the request for each proxy
    results = ["Proxy           isGood Time"]
    for proxy in (proxies):
        # now set the proxy
        req.set_proxy(proxy, "http")
        # time it
        start = time.time()
        # try to open the URL
        try:
            urllib2.urlopen(req)
            # format the results for success
            results.append("%s  y      %.2f" % (proxy, time.time()-start))
        except urllib2.URLError:
            # format the results for failure
            results.append("%s  n      %.2f" % (proxy, time.time()-start))

    return results

testResults = testProxies("http://www.abc.com", ["200.43.54.112", "200.43.54.222",
                  "200.43.54.102", "200.43.54.111"])
for result in testResults:
    print result

rawDescription: How to validate a bunch of proxies against a URL?

description: Validate a bunch of proxies against a URL


rawDescription: Getting Coordinates from Given Lists

description: Getting Coordinates from Given Lists


code:
def other_function(self):
    print 'other'

def my_function(self):
    print 'one'
    QTimer.singleShot(1, self.other_function)
    print 'two'

rawDescription: PyQT equivalent of wx CallAfter?

description: PyQT equivalent of wx CallAfter


code:
import threading
some_lock = threading.Lock()

# use this code anywhere you need to acquire the lock and check for blocking
if not some_lock.acquire(False):
    print 'BLOCKING!'
    some_lock.acquire() # call again with blocking=True (which is the default)
else:
    print 'Acquired lock without blocking'
# lock has been acquired, make sure you release when done with critical section

rawDescription: determine when a thread is waiting for a lock to release

description: Determine when a thread is waiting for a lock to release


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(open("file.html",'r').read())
cols = [header.string for header in soup.find('thead').findAll('th')]
col_idx = cols.index('Username')
col_values = [td[col_idx].string for td in [tr.findAll('td') for tr in soup.find('tbody').findAll('tr')]]
print col_values

rawDescription: BeautifulSoup get all the values of a particular column


code:
from kivy.app import App

from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

class Fejkbiljett(App):

    def build(self):
        self.gen_btn = Button(text='Generera',
                         size_hint=(.90, .10),
                         pos=(5, 5),
                         font_size=21)
        self.gen_btn.bind(on_press=self.getMessageFejkbiljett)
        l = BoxLayout()
        l.add_widget(self.gen_btn)
        return l

    def getMessageFejkbiljett(self, *args):
        print "1. this is called on the method getMessageFejkbiljett of Fejkbiljett"
        st = StockholmTicket()
        st.getMessage(self)

class StockholmTicket():

    def getMessage(self, source):
        source.gen_btn.text = "the event was called"
        print "2. this is called on the method getMessage of StockholmTicket"

if __name__ == "__main__":
    Fejkbiljett().run()

rawDescription: Kivy: How to call something on button on_press


code:
namedict = dict((x['name'], y) for y in data for x in data[y]['localNodes'])
proddict = dict((z['name'], [y for y in z['consumesFrom'] if namedict[y] != x])
  for x in data for z in data[x]['localNodes'] if z['consumesFrom'] is not None)

print 'nA' in proddict['nC']

rawDescription: fastest way to search through this data object? (python)

description: Fastest way to search through this data object? (python)


code:
import cv
def main():
    import sys
    x = cv.Load(sys.argv[1])
    epsilon = float(sys.argv[2])
    y = cv.CloneImage(x)
    labels = range(x.height)
    tmp = cv.CreateImage((x.width, 1), x.depth, x.nChannels)
    for i in range(x.height):
        cv.SetImageROI(x, (0, i, x.width, 1))
        for j in range(i+1, x.height):
            cv.SetImageROI(y, (0, j, x.width, 1))
            cv.AbsDiff(x, y, tmp)
            dist, _, _, _ = cv.Avg(tmp)
            if dist < epsilon:
                for k, lbl in enumerate(labels):
                    if lbl == j:
                        labels[k] = i

    for i, lbl in enumerate(labels):
        print i, lbl

if __name__ == '__main__':
    main()

rawDescription: Single link clustering

description: Single link clustering


code:
def one_good_turn(n):
    return n + 1

def deserves_another(n):
    return one_good_turn(n) + 2

n = 1
print one_good_turn(n)
print deserves_another(n)

rawDescription: Functions calling functions in Python

description: Functions calling functions in Python


code:
def evaluate_result():
    print 'evaluate_result'
    return 1

class Foo:
    @staticmethod
    def compute_result():
        if not hasattr(Foo, '__compute_result'):
            Foo.__compute_result = evaluate_result()
        return Foo.__compute_result

Foo.compute_result()
Foo.compute_result()

rawDescription: Evaluate a function one time and store the result in python


code:
def encode_datetime(obj):
    """
    Extended encoder function that helps to serialize dates and images
    """
    if isinstance(obj, datetime.date):
        try:
            return obj.strftime('%Y-%m-%d')
        except ValueError, e:
            return ''

    if isinstance(obj, ImageFieldFile):
        try:
            return obj.path
        except ValueError, e:
            return ''

    raise TypeError(repr(obj) + " is not JSON serializable")

rawDescription: Serializing an ImageField in Django

description: Serializing an ImageField in Django


code:
#!/usr/bin/env python
from bs4 import BeautifulSoup
import bleach

def sanitizeHTML(value):
    soup = BeautifulSoup(bleach.clean(value,tags=VALID_TAGS,attributes=VALID_ATTRIBUTES),"html5lib")
    return soup.renderContents()

VALID_TAGS = ['img']
VALID_ATTRIBUTES = ['src']

string = '<img src="image.png"><input type=text>'
result = sanitizeHTML(string)

print result

rawDescription: Prevent certain HTML tags from rendering with Python


code:
#....
url2 = url + str(l)
print url2
#....

rawDescription: Unexpected python loop output

description: Unexpected python loop output


code:
data = [{"name": "John", "age": "20", "occupation": "Python pro"}, \
        {"name": "Jack", "age": "80", "occupation": "Olympic Athlete"}, \
        {"name": "John", "age": "20", "occupation": "Student"}]

new_data = []
names_ages = set([])
for d in data:
    name_age = (d["name"], d["age"])
    if name_age not in names_ages:
        new_data.append(d)
    names_ages.add(name_age)

print new_data
# [{'age': '20', 'name': 'John', 'occupation': 'Python pro'},
#  {'age': '80', 'name': 'Jack', 'occupation': 'Olympic Athlete'}]

rawDescription: List of dictionaries that should be filtered by certain values


code:
from PyZ3950 import zoom
conn = zoom.Connection ('z3950.iacentre.com', 210,user='gaurishankar')
conn.databaseName = 'itke'
conn.preferredRecordSyntax = 'USMARC'
query = zoom.Query ('CCL', 'mango')
res = conn.search (query)
for i in res:
    print i,i.data

rawDescription: How to connect to databse using z39.50

description: Connect to databse using z39.50


code:
def get_vlan_iface():
    while True:
        vlan = raw_input ("what VLAN ID do you want to add? "),
        iface = raw_input("what interface do you want to add the VLAN to? (e.g. eth10)")
        print "So we are adding VLAN %r to interface %r" % (vlan, interface)

        if raw_input("Are the details above correct? (Yes/No)>")[0].lower() == "y":
             return vlan,iface
        print "Please Fix Your Entries!"

vlan,iface = get_vlan_iface()

rawDescription: Python while loop back to specific point in code


code:
import Tkinter as tk

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        # Extract the friend lists from the keyword args
        friends1, friends2 = kwargs['friendlists']
        del kwargs['friendlists']

        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        # A generator that yields all pairs of people from the friends lists
        self.pairs = ((u, v) for u in friends1 for v in friends2)

        # A pair of labels to display the names
        self.friend1 = tk.StringVar()
        tk.Label(self, textvariable=self.friend1).grid(row=0, column=0)

        self.friend2 = tk.StringVar()
        tk.Label(self, textvariable=self.friend2).grid(row=0, column=1)

        # Set the first pair of names
        self.set_friends()

        cmd = lambda: self.test_friends(True)
        b = tk.Button(self, text="Friends!", width=25, command=cmd)
        b.grid(row=1, column=0)

        cmd = lambda: self.test_friends(False)
        b = tk.Button(self, text="Not friends.", width=25, command=cmd)
        b.grid(row=1, column=1)

    def set_friends(self):
        # Set the next pair of names
        f1, f2 = next(self.pairs)
        self.friend1.set(f1)
        self.friend2.set(f2)

    def test_friends(self, reply):
        f1, f2 =  self.friend1.get(), self.friend2.get()
        reply = (' not ', ' ')[reply]
        print '%s and %s are%sfriends' % (f1, f2, reply)
        try:
            self.set_friends()
        except StopIteration:
            # No more pairs
            print 'Finished!'
            self.parent.destroy()

def main():
    people_1 = [
        "John",
        "Tiffany",
        "Leo",
        "Tomas",
        #"Stacy",
        #"Robin",
        #"Carl",
    ]

    people_2 = [
        "George",
        "Jasmin",
        "Rosa",
        #"Connor",
        #"Valerie",
        #"James",
        #"Bob",
    ]

    root = tk.Tk()
    root.wm_title("Friend Info")
    app = MainApplication(root, friendlists=(people_1, people_2))
    app.pack()
    root.mainloop()

if __name__ == "__main__":
    main()

rawDescription: Tkinter loop function

description: Tkinter loop function


code:
print "foo\\nbar\\n\\tbaz"
print "foo\\nbar\\n\\tbaz".decode('string_escape')

rawDescription: Is there a Python module to parse line break notation in a raw string?


code:
some_name = 'wee'
setattr(my_entity, some_name, 'value')
print getattr(my_entity, some_name)
my_entity.put()

rawDescription: AppEngine: Can I write a Dynamic property (db.Expando) with a name chosen at runtime?


code:
import ssl
import requests
# this will disable the warnings from requests
requests.packages.urllib3.disable_warnings()
from pyVmomi import vim
from pyVim import connect
# this will only work if you have 2.7.9 or newer
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
context.verify_mode = ssl.CERT_NONE
service_instance = connect.SmartConnect(host="your host", user="your user", pwd="password", sslContext=context)
search_index = service_instance.content.searchIndex
root_folder = service_instance.content.rootFolder
# below is one of several ways to find a host.. this is one of the worst ways but it is quick for the purpose of this example
view_ref = service_instance.content.viewManager.CreateContainerView(container=root_folder,type=[vim.HostSystem], recursive=True)
host = view_ref.view[0]
print host.name
print host.summary.hardware.uuid
print host.summary.hardware.model
view_ref.Destroy

rawDescription: HostHardwareSummary in pyvomi

description: HostHardwareSummary in pyvomi


code:
#!/usr/bin/python
__author__ = 'efirvida'

from netaddr import iter_iprange
from scapy.all import IP, TCP, ICMP, sr1, sniff
import logging
logging.getLogger('scapy').setLevel(logging.ERROR)

def ip_range(star_ip, stop_ip):
    netaddr_ip_list = list(iter_iprange(star_ip, stop_ip))
    return [str(i) for i in netaddr_ip_list]

def online_ip(iplist, timeout):
    online_ips = []
    for ip in iplist:
        reply = sr1(IP(dst=ip)/ICMP(), timeout=timeout, verbose=False)
        if not (reply is None):
            online_ips.append(ip)

    return online_ips

if __name__ == '__main__':

    TIMEOUT = 0.5
    snf_pk = 30                                                 # Number of sniff package to get
    star_ip = '10.12.12.1'                                      #  start ip on the ip-range to scan
    stop_ip = '10.12.12.40'                                     #  last ip on the ip-range to scan
    ports = [21, 22, 80, 442, 443, 808, 1080, 3128, 8080]       # port list to scan on the active ips

    ip_list = online_ip(ip_range(star_ip, stop_ip), TIMEOUT)    # online ips on the ip range

    #check open ports on the online ips
    ip_ports = []
    for ip in ip_list:
        openports = []
        for port in ports:
            ans = sr1(IP(dst=ip)/TCP(dport=port, flags="S"), timeout=TIMEOUT, verbose=False)
            if not (type(ans) == type(None)):
                if ans[TCP].flags == 18:
                    openports.append(port)

        if openports:
            ip_ports.append({'ip':ip, 'ports': openports})
    #stop check open ports on the online ips

    #sniff active ports on each active ip
    for ip in ip_ports:
        for port in ip['ports']:
            print 'Sniffing in ' + ip['ip'] + ':' + str(port)
            snf = sniff(filter="tcp and port " + str(port) + " and host " + ip['ip'], count=snf_pk)
            snf.pdfdump('sniff_' + ip['ip'] + '_port_' + str(port) + '.pdf')

rawDescription: Python - Scapy - Sniffing local network

description: Python - Scapy - Sniffing local network


code:
import json
import urllib.request
response = urllib.request.urlopen('http://openexchangerates.org/api/currencies.json')
html = response.read().decode("utf-8")

my_dict = json.loads(html)
print my_dict

rawDescription: Fetch currencies from a website and return as a dictionary


code:
import xml.dom.minidom

content = """
<urlset xmlns="http://www.google.com/schemas/sitemap/0.90">
  <url>
    <loc>http://www.domain.com/</loc>
    <lastmod>2011-01-27T23:55:42+01:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>
  <url>
    <loc>http://www.domain.com/page1.html</loc>
    <lastmod>2011-01-26T17:24:27+01:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>
  <url>
    <loc>http://www.domain.com/page2.html</loc>
    <lastmod>2011-01-26T15:35:07+01:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
  </url>
</urlset>
"""

def get_first_node_val(obj, tag):
    return obj.getElementsByTagName(tag)[0].childNodes[0].nodeValue

xml = xml.dom.minidom.parseString(content)
urlset = xml.getElementsByTagName("urlset")[0]
urls = urlset.getElementsByTagName("url")

for url in urls:
    loc = get_first_node_val(url, "loc")
    lastmod = get_first_node_val(url, "lastmod")
    changefreq = get_first_node_val(url, "changefreq")
    priority = get_first_node_val(url, "priority")
    print "%s, %s, %s, %s" % (loc, lastmod, changefreq, priority)

rawDescription: Parsing XML to get a node's value

description: Parsing XML to get a node's value


code:
def configure():
  build()

def wrap(f):
  import new
  def build():
    print 'build'

  new.function(f.func_code, locals(), f.func_name, f.func_defaults, f.func_closure)()

wrap(configure)

rawDescription: Python closures and replacing surrounding scope


code:
if batch:
        key =""
        key = '({})'.format(','.join(elem for elem in batch[0]))
        print key
        value ='({})'.format(','.join("'"+str(eleme)+"'" for eleme in batch[0].values()))
        print value
        sqlWrite = []
        sqlWrite.append("INSERT IGNORE INTO %s " %writeTable)
        sqlWrite.append("".join(key))
        sqlWrite.append(" VALUES ")
        sqlWrite.append("".join(value))
        sql="".join(sqlWrite)
        print sql
        if batch:
            writeCur.executemany(sql, batch)
            cnx2.commit()

rawDescription: How to build dynamic sql query in python and use executemany() to insert?

description: Build dynamic sql query in python and use executemany() to insert


code:
import os

correct=0
incorrect=0
missed_questions=[]

def tryagain():
    while True:
       answer = input('Do you want to continue?:  Press Y for yes and N for no ')
       if answer.lower().startswith("y"):
          print()
       elif answer.lower().startswith("n"):
          exit()

def ask_question(question, correct_answer):
    os.system('cls')  # I'm not on Windows so this doesn't work for me
    print question
    print ''
    answer = int(input())
    if answer == correct_answer:
        print ''
        print ''
        global correct
        correct += 1
    else:
        global incorrect
        incorrect += 1
        global missed_questions
        missed_questions.append(question)

print('****** Welceome to the Online Maths Test ********')
print()
print()
print()
print()
print()
print()
print()
os.system("PAUSE") # I'm not on Windows so this doesn't work for me

## You could go further and put the data (all of the questions, correct answers, and
## a flag to indicate whether the user got it correct) into one array and loop
## through the array. In that same loop you can address how to make sure
## that the tryagain() works properly.
ask_question('Question 1: 123 - 39 = ? \n 1. 64 \n 2. 44 \n 3. 74 \n 4. 84', 4)
ask_question('Question 2: 123+39 = ? \n \n 1. 162 \n 2. 166 \n 3. 62 \n 4. 66', 1)
ask_question('Question 3: 123*9 = ? \n 1. 1007 \n 2. 1107 \n 3. 1106 \n 4. 1116', 2)
ask_question('Question 4: 135 / 15 = ? \n 1. 8 \n 2. 8.5 \n 3. 9 \n 4. 9.5', 3)
ask_question('Question 5: 12 * (12 / 2) = ? \n 1. 144 \n 2. 6 \n 3. 72 \n 4. 36', 3)
ask_question('Question 6: 130 / 2 + 8 = ? \n 1. 13 \n 2. 14 \n 3. 61 \n 4. 84', 4)
ask_question('Question 7: 10 + 12 + 13 * 6 / 2 = ? \n 1. 105 \n 2. 44 \n 3. 61 \n 4. 84', 3)
ask_question('Question 8: (10 + 12 + 13 * 6) / 2 = ? \n 1. 50 \n 2. 44 \n 3. 61 \n 4. 84', 1)
ask_question('Question 9: 8 (12 + 6 / 3 * 2) - 1 = ? \n 1. 127 \n 2. 109 \n 3. 95 \n 4. 135', 1)
ask_question('Question 10: 1 / 1 * 1 - 1 + 1 = ? \n 1. 1 \n 2. -1 \n 3. 0 \n 4. -2', 1)

print()
print()

os.system('cls')
print('Your total score is: ',correct,' / 10')
print('Your percentage is: ',correct*100/10,'%')
print()
print()

for q in missed_questions:
    print 'Missed question: ', q
    print ''

print()
print()
tryagain()

rawDescription: how to print incorrect questions?

description: Print incorrect questions


code:
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
import time

driver = webdriver.Firefox()
driver.get('http://www.kiva.org/lend/742129')

for _ in xrange(5):
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
    time.sleep(1)

more = WebDriverWait(driver, 10).until(lambda driver : driver.find_element_by_id('showMoreLenders'))
more.click()

time.sleep(2)

# get the lenders
for lender in driver.find_elements_by_xpath('//section[@id="theLenders"]//li//div[@class="name"]/a'):
    print lender.text

driver.close()

rawDescription: How to scrape some contents on a website which was hidden using JS in Python?

description: Scrape some contents on a website which was hidden using JS in Python


code:
from google.appengine.ext.blobstore import BlobInfo
qry = BlobInfo.all()
for f in qry:
    print f.filename

rawDescription: How to reading Blob on Google App Engine remotely?

description: Reading Blob on Google App Engine remotely


code:
#!/usr/bin/env python
import re
text = 'Proposal will boost bailout fund, inject cash into banks and cut Greek debt says reports.'
pattern = re.compile(r'boost bailout[\s\S]*?debt')
print re.findall(pattern, text)

rawDescription: Regex to extract paragraph

description: Regex to extract paragraph


code:
import Tkinter as tk
import time

class Example(tk.LabelFrame):
    def __init__(self, *args, **kwargs):
        tk.LabelFrame.__init__(self, *args, **kwargs)
        data = [
            # Nr. Name  Active
            [1,   "ST", True],
            [2,   "SO", False],
            [3,   "SX", True],
            ]

        self.grid_columnconfigure(1, weight=1)
        tk.Label(self, text="Nr.", anchor="w").grid(row=0, column=0, sticky="ew")
        tk.Label(self, text="Name", anchor="w").grid(row=0, column=1, sticky="ew")
        tk.Label(self, text="Active", anchor="w").grid(row=0, column=2, sticky="ew")
        tk.Label(self, text="Action", anchor="w").grid(row=0, column=3, sticky="ew")

        row = 1
        for (nr, name, active) in data:
            nr_label = tk.Label(self, text=str(nr), anchor="w")
            name_label = tk.Label(self, text=name, anchor="w")
            action_button = tk.Button(self, text="Delete", command=lambda nr=nr: self.delete(nr))
            active_cb = tk.Checkbutton(self, onvalue=True, offvalue=False)
            if active:
                active_cb.select()
            else:
                active_cb.deselect()

            nr_label.grid(row=row, column=0, sticky="ew")
            name_label.grid(row=row, column=1, sticky="ew")
            active_cb.grid(row=row, column=2, sticky="ew")
            action_button.grid(row=row, column=3, sticky="ew")

            row += 1

    def delete(self, nr):
        print "deleting...nr=", nr

if __name__ == "__main__":
    root = tk.Tk()
    Example(root, text="Hello").pack(side="top", fill="both", expand=True, padx=10, pady=10)
    root.mainloop()

rawDescription: Table of widgets in Python with Tkinter

description: Table of widgets in Python with Tkinter


code:
import subprocess

the_name = 'the_name'
myproc = subprocess.Popen(['echo %s | bash Hello.sh' % the_name], stdin = subprocess.PIPE, stdout = subprocess.PIPE, shell=True)
out, err = myproc.communicate()

print out

rawDescription: Enter shell script variable value non-interactively using python


code:
import argparse
import sys

class Scrabble:
    def __init__(self, tilesFile):
        with open(tilesFile, "r") as f:
            lines = [ line.strip().split(":") for line in f ]

        self.tiles = { k:int(v) for k,v in lines }

    def getWordValue(self, word):
        sum = 0
        for letter in word.upper():
            sum += self.tiles[letter]

        return sum

    def getBestWord(self):
        pass

def main(argv):
    s1 = Scrabble(argv[1])
    if len(argv) < 3:
        print 'no words given'
        sys.exit(1)

    # argv[2:] means the items in argv starting from the 3rd item.
    # the first item will be the name of the script you are running
    # the second item should be the tiles file.
    for word in argv[2:]:
        value = s1.getWordValue(word)
        print(value)

if __name__ == '__main__':
   main(argv)

rawDescription: Simple word scrabble code using python that takes command line parameters


code:
def n_factors(x, lower, upper):
    int_counter = 0 # integer counter
    div_count = 0 # divisor counter
    for i in range(lower, upper+1):
        for j in range(1, i + 1):
            if (i%j)==0:
                div_count += 1
        if div_count == x:
            print i
            int_counter += 1
        div_count = 0
    return int_counter

rawDescription: Determining the number of integers with a certain amount of factors between two numbers


code:
def populateMethod(self, method):
    print "method:", method

for method in ["one","two","three"]:
    button = Button(self.methodFrame, text=method,
        command=lambda m=method: self.populateMethod(m))
    button.pack({'fill': 'x', 'expand': 1, 'padx': 5, 'pady': 3})

rawDescription: Determine which Button was pressed in Tkinter?


code:
# context manager `with` takes care of file closing, error handling
with open(filename, 'r') as handle:
    for line in handle:
        if line.startswith('SequenceName_'):
             print line.split()
             # Write to file, etc.

rawDescription: Looping over lines with Python

description: Looping over lines with Python


code:
import mmap

print mmap.PAGESIZE

rawDescription: Finding SC_PAGE_SIZE using Python in Windows


code:
def splitlines (file) :
  fileNo=0001
  outFile=open("newdocs/%s.txt" % fileNo, 'a') ## open file to append
  reg = re.compile("Copyright ")
  for line in open(file, "r"):
    if reg.search("Copyright ", line): # if the line is equal to the regex
      outFile.close()  ##  close the file
      outFile=open("newdocs%s.txt" % fileNo, 'a') ## open file to append
      fileNo +=1  #and add one to the filename, starting to read lines in again

    outFile.write(line)          ## then append it to the open outFile

rawDescription: Slow python file I:O; Ruby runs better than this; Got the wrong language?


code:
def overlap(string1,string2):
    count = 0
    for i in range(min(len(string1), len(string2))):
        if string1[i] == string2[i]:
            count = count + 1
    return count

print overlap('summer','winter') #2
print overlap('abcb','dbeb') #2
print overlap('summer','sum') #3
print overlap('','winter') #0

rawDescription: Finding the number of matching letters in two different string at the same indices


code:
import json
import random

# use items to get a list
questions = json.load(open("questions.json")).items()
# ... that you can shuffle.
random.shuffle(questions)
# note, we used items() earlier, so we get a tuple.
# and we can ask all questions in random order.
for question, data in questions:
   answers = data['answers']
   correct_answer = data['correct_answer']
   print question
   for n, answer in enumerate(answers):
       print "%d) %s" % (n + 1, answer)
   resp = raw_input('answer: ')
   if resp == str(correct_answer):
       print "correct!"
   else:
       print "sorry, the correct answer was %s" % correct_answer

rawDescription: Continuous questions

description: Continuous questions


code:
period_val  = "1970"
family_val = "Smith"
environment = {'SDC_PERIOD': '{period}s'.format(period = period_val), 'FAMILY': '{legup_family}s'.format(legup_family = family_val)}
print environment

rawDescription: Doing a format string substitution within a dictionary


code:
class MyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.toolMenu = QtGui.QMenu(self.ui.toolButton)
        group = QtGui.QActionGroup(self.toolMenu)
        for i in range(3):
            action = self.toolMenu.addAction("Category %d" % i)
            action.setCheckable(True)
            action.setActionGroup(group)
            action.setData(i)
        self.ui.toolButton.setMenu(self.toolMenu)
        self.ui.toolButton.setPopupMode(QtGui.QToolButton.InstantPopup)
        group.triggered.connect(self.test)

    def test(self, act):
        print 'Action' , act.data().toInt()[0]

rawDescription: Capture actions from checkable combobox

description: Capture actions from checkable combobox


code:
import OpenSSL.crypto
from OpenSSL.crypto import load_certificate_request, FILETYPE_PEM

csr = '''-----BEGIN NEW CERTIFICATE REQUEST-----
MIIDPzCCAqgCAQAwZDELMAkGA1UEBhMCQ04xCzAJBgNVBAgTAmJqMQswCQYDVQQH
EwJiajERMA8GA1UEChMIbXhjei5uZXQxETAPBgNVBAsTCG14Y3oubmV0MRUwEwYD
VQQDEwx3d3cubXhjei5uZXQwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMQ7
an4v6pHRusBA0prMWXMWJCXY1AO1H0X8pvZj96T5GWg++JPCQE9guPgGwlD02U0B
NDoEABeD1fwyKZ+JV5UFiOeSjO5sWrzIupdMI7hf34UaPNxHo6r4bLYEykw/Rnmb
GKnNcD4QlPkypE+mLR4p0bnHZhe3lOlNtgd6NpXbAgMBAAGgggGZMBoGCisGAQQB
gjcNAgMxDBYKNS4yLjM3OTAuMjB7BgorBgEEAYI3AgEOMW0wazAOBgNVHQ8BAf8E
BAMCBPAwRAYJKoZIhvcNAQkPBDcwNTAOBggqhkiG9w0DAgICAIAwDgYIKoZIhvcN
AwQCAgCAMAcGBSsOAwIHMAoGCCqGSIb3DQMHMBMGA1UdJQQMMAoGCCsGAQUFBwMB
MIH9BgorBgEEAYI3DQICMYHuMIHrAgEBHloATQBpAGMAcgBvAHMAbwBmAHQAIABS
AFMAQQAgAFMAQwBoAGEAbgBuAGUAbAAgAEMAcgB5AHAAdABvAGcAcgBhAHAAaABp
AGMAIABQAHIAbwB2AGkAZABlAHIDgYkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAAAAAAADANBgkqhkiG9w0BAQUFAAOBgQBIKHVhHb9FZdVLV4VZ
9DK4aBSuYY//jlIpvsfMIdHXfAsuan7w7PH87asp1wdb6lD9snvLZix1UGK7VQg6
wUFYNlMqJh1m7ITVvzhjdnx7EzCKkBXSxEom4mwbvSNvzqOKAWsDE0gvHQ9aCSby
NFBQQMoW94LqrG/kuIQtjwVdZA==
-----END NEW CERTIFICATE REQUEST-----'''

req = load_certificate_request(FILETYPE_PEM, csr)
key = req.get_pubkey()
key_type = 'RSA' if key.type() == OpenSSL.crypto.TYPE_RSA else 'DSA'
subject = req.get_subject()
components = dict(subject.get_components())
print "Common name:", components['CN']
print "Organisation:", components['O']
print "Orgainistional unit", components['OU']
print "City/locality:", components['L']
print "State/province:", components['ST']
print "Country:", components['C']
print "Signature algorithm:", '?'
print "Key algorithm:", key_type
print "Key size:", key.bits()

rawDescription: How to decode CSR using pyOpenssl

description: Decode CSR using pyOpenssl


rawDescription: How to extract data from string using Python RegEx?

description: Extract data from string using Python RegEx


code:
x = re.findall(yo, line)
if x:
    count += 1 # multiple non-overlapping occurences on one line

print "what.txt had {0} lines that matched {1}".format(count, yo)

rawDescription: Counting the number of lines that special characters appear in a txt file from user input (Python 2.7)


code:
opener = urllib2.build_opener()
opener.addheaders = [('User-agent',
    ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) '
     'AppleWebKit/535.1 (KHTML, like Gecko) '
     'Chrome/13.0.782.13 Safari/535.1'))
]
response = opener.open('http://www.gocrimson.com/sports/mbkb/2011-12/roster')
print response.readlines() # divs are now a table

rawDescription: Programatically opening web page given unexpected results


code:
import Foundation
from AppKit import *
from PyObjCTools import AppHelper

class GetSongs(NSObject):
    def getMySongs_(self, song):
        song_details = {}
        ui = song.userInfo()
        for x in ui:
            song_details[x] = ui.objectForKey_(x)
        print song_details

nc = Foundation.NSDistributedNotificationCenter.defaultCenter()
GetSongs = GetSongs.new()
nc.addObserver_selector_name_object_(GetSongs, 'getMySongs:', 'com.apple.iTunes.playerInfo',None)

NSLog("Listening for new tunes....")
AppHelper.runConsoleEventLoop()

rawDescription: How do you listen to notifications from iTunes on a Mac (Using the NSDistributedNotificationCenter)

description: Listen to notifications from iTunes on a Mac (Using the NSDistributedNotificationCenter)


code:
s = 'Your ID number is: 41233'
print s.split(":")[1].strip()

rawDescription: Slicing a string in Python

description: Slicing a string in Python


code:
from time import sleep
from threading import Thread

informations = []

def funct_a (informations):
    while (1):
        sleep (0.5)
        print informations

def funct_b (informations):
    a = 0
    while (1):
        sleep (1)
        informations.append (a)
        a += 1

Thread (target = funct_a, args = (informations, )).start ()
Thread (target = funct_b, args = (informations, )).start ()

rawDescription: Two pygame windows running alongside each other


code:
import urllib, urllib2, sys, re
import cStringIO
import pycurl

def CaptureToken(cURL):
    buf = cStringIO.StringIO()
    c = pycurl.Curl()
    c.setopt(c.URL, cURL)
    c.setopt(c.WRITEFUNCTION, buf.write)
    c.setopt(c.CONNECTTIMEOUT, 30)
    c.setopt(c.TIMEOUT, 30)
    c.perform()
    html = buf.getvalue()
    buf.close()
    results = re.search(r'(type="hidden" name="([0-9a-f]{32})")', html).group(2)
    print results

CaptureToken('http://www.proregionisbono.org.pl/administrator/index.php')

rawDescription: regex capture html hidden input

description: Regex capture html hidden input


code:
def require_alive(func):
    def wrapper(self, *args, **kwargs):
        if not self.alive:
            raise Exception("Not alive")
        return func(self, *args, **kwargs)
    return wrapper
def require_hungry(func):
    def wrapper(self, *args, **kwargs):
        if not self.hungry:
            print "Not hungry..."
        else:
            return func(self, *args, **kwargs)
    return wrapper
class Pet(object):
    def __init__(self):
        self.alive = True
        self.hungry = True
    def die(self):
        self.alive = False
    @require_alive
    @require_hungry
    def eat(self):
        print "Eating..."
        self.hungry = False
    @require_alive
    def sleep(self):
        print "Sleeping..."
roofus = Pet()
roofus.eat()
roofus.eat()
roofus.sleep()
roofus.die()
roofus.eat()

rawDescription: if condition for multiple methods in a class

description: If condition for multiple methods in a class


code:
import wx

TRAY_TOOLTIP = 'System Tray Demo'
TRAY_ICON = 'icon.png'

def create_menu_item(menu, label, func):
    item = wx.MenuItem(menu, -1, label)
    menu.Bind(wx.EVT_MENU, func, id=item.GetId())
    menu.AppendItem(item)
    return item

class TaskBarIcon(wx.TaskBarIcon):
    def __init__(self):
        super(TaskBarIcon, self).__init__()
        self.set_icon(TRAY_ICON)
        self.Bind(wx.EVT_TASKBAR_LEFT_DOWN, self.on_left_down)

    def CreatePopupMenu(self):
        menu = wx.Menu()
        create_menu_item(menu, 'Say Hello', self.on_hello)
        menu.AppendSeparator()
        create_menu_item(menu, 'Exit', self.on_exit)
        return menu

    def set_icon(self, path):
        icon = wx.IconFromBitmap(wx.Bitmap(path))
        self.SetIcon(icon, TRAY_TOOLTIP)

    def on_left_down(self, event):
        print 'Tray icon was left-clicked.'

    def on_hello(self, event):
        print 'Hello, world!'

    def on_exit(self, event):
        wx.CallAfter(self.Destroy)

def main():
    app = wx.PySimpleApp()
    TaskBarIcon()
    app.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: Quick and easy: trayicon with python?

description: Quick and easy: trayicon with python


code:
import json
with open("file_2.json") as f2, open("file_1.json") as f1:
    json_pks     = json.loads(f2.read())
    json_updates = json.loads(f1.read())
    for pk in json_pks:
        x_value = json_updates[0].get(pk,'')
        y_value = json_updates[1].get(pk,'')

        if x_value and y_value:
            #db stuff
            print "update YOUR_TABLE set x=%r,y=%r where YOUR_PK=%s" % (x_value,y_value,pk)

rawDescription: Insert values from a json list of dicts containing the same keys for two different values in the list of dicts to a MYSQL database


code:
x = 0
for c in itertools.takewhile(lambda c: x < 10, itertools.count()):
    x = int(raw_input())
    print x, c

rawDescription: Pythonic enumeration of while loop

description: Pythonic enumeration of while loop


code:
def team(t):
    iterations = range(2, len(t)/2+1)

    totalscore = sum(t)
    halftotalscore = totalscore/2.0

    oldmoves = {}

    for p in t:
        people_left = t[:]
        people_left.remove(p)
        oldmoves[p] = people_left

    if iterations == []:
        solution = min(map(lambda i: (abs(float(i)-halftotalscore), i), oldmoves.keys()))
        return (solution[1], sum(oldmoves[solution[1]]), oldmoves[solution[1]])

    for n in iterations:
        newmoves = {}
        for total, roster in oldmoves.iteritems():
            for p in roster:
                people_left = roster[:]
                people_left.remove(p)
                newtotal = total+p
                if newtotal > halftotalscore: continue
                newmoves[newtotal] = people_left
        oldmoves = newmoves

    solution = min(map(lambda i: (abs(float(i)-halftotalscore), i), oldmoves.keys()))
    return (solution[1], sum(oldmoves[solution[1]]), oldmoves[solution[1]])

print team([90,200,100])
print team([2,3,10,5,8,9,7,3,5,2])
print team([1,1,1,1,1,1,1,1,1,9])
print team([87,100,28,67,68,41,67,1])
print team([1, 1, 50, 50, 50, 1000])

#output
#(200, 190, [90, 100])
#(27, 27, [3, 9, 7, 3, 5])
#(5, 13, [1, 1, 1, 1, 9])
#(229, 230, [28, 67, 68, 67])
#(150, 1002, [1, 1, 1000])

rawDescription: Algorithm to Divide a list of numbers into 2 equal sum lists


code:
#!c:/Python27/python.exe -u

import sys

print "Content-Type: text/plain;"
print "Content-Disposition: attachment; filename=TEST.txt"
print

filename = "C:\\TEST.TXT"
f = open(filename, 'rb')
while True:
    data = f.read(4096)
    sys.stdout.write(data)
    if not data:
        break

rawDescription: Transfer Text File in Web Server to Client


code:
date_string = "Mon Jun 24 01:30:08 EDT 2013"
fields = date_string.split()
print ' '.join(fields[1:5]) # Prints "June 24 01:30:08 EDT"

rawDescription: Using python to substitute awk for Linux commands


code:
from sqlalchemy import Column, Integer
from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta

class MyMeta(DeclarativeMeta):

    def __init__(klass, classname, bases, dict_):

        for k, v in dict_.items():

            if k.endswith('__column_dict'):

                for name, datatype, is_pk in v:

                    setattr(klass, name, Column(name, datatype, primary_key=is_pk))

        return DeclarativeMeta.__init__(klass, classname, bases, dict_)

Base = declarative_base(metaclass=MyMeta)

class Bob(Base):
    __tablename__ = 'bob'
    __column_dict = [('a', Integer, True), ('b', Integer, False)]

bob = Bob()
print bob.a
print bob.b

rawDescription: Dynamic Instance variables within Class Scope


code:
from scipy import stats
#Studnt, n=999, p<0.05, 2-tail
#equivalent to Excel TINV(0.05,999)
print stats.t.ppf(1-0.025, 999)

#Studnt, n=999, p<0.05%, Single tail
#equivalent to Excel TINV(2*0.05,999)
print stats.t.ppf(1-0.05, 999)

rawDescription: Python function to get the t-statistic

description: Python function to get the t-statistic


code:
kMaxLoad = 80
while True:
    x = [cpu.LoadPercentage for cpu in c.Win32_Processor()]
    if max(x) < kMaxLoad:
        break
print "okay, load is under %i" % kMaxLoad

rawDescription: python How to watch for Win32_Processor LoadPercentage change in wmi?

description: Python How to watch for Win32_Processor LoadPercentage change in wmi


code:
import itertools

class MyClass(object):
    @classmethod
    def fromdict(cls, d):
        allowed = ('key1', 'key2')
        df = {k : v for k, v in d.iteritems() if k in allowed}
        return cls(**df)

    def __init__(self, key1, key2):
        self.key1 = key1
        self.key2 = key2

dict = {'key1': 'value1', 'key2': 'value2', 'redundant_key': 'redundant_value'}

ob = MyClass.fromdict(dict)

print ob.key1
print ob.key2

rawDescription: Python creating class instance from dictionary


code:
from multiprocessing import Pool

def function(parm1, parm2, parm3):  # Function that is called during multiprocessing.
    print parm1, parm2, parm3
    print parm1 * parm2 * parm3
    return parm1 * parm2 * parm3

def store_info(a):  # The callback function.
    print a

if __name__ == "__main__":
    # Dictionary with dictionaries of parameters:
    my_dict = {"one":{"parm1":1, "parm2":2, "parm3":3}, "two":{"parm1":4, "parm2":5, "parm3":6}, "three":{"parm1":7, "parm2":8, "parm3":9}}

    p = Pool(4)  # Setting up the number of CPU's to use.

    for key, params_dict in my_dict.items():  # For loop used to separate keys from values.
        print params_dict
        p.apply_async(function, args=tuple(), kwds=params_dict, callback=store_info)

    p.close()
    p.join()

rawDescription: Passing python dictionary of parameters though multiprocessing


code:
# genPlayM21Score.py Generates and Plays 2 Music21 Scores "on the fly".
#
# see way below for source notes

from music21 import *

# we create the music21 Bottom Part, and do this explicitly, one object at a time.

n1 = note.Note('e4')
n1.duration.type = 'whole'
n2 = note.Note('d4')
n2.duration.type = 'whole'
m1 = stream.Measure()
m2 = stream.Measure()
m1.append(n1)
m2.append(n2)
partLower = stream.Part()
partLower.append(m1)
partLower.append(m2)

# For the music21 Upper Part, we automate the note creation procedure

data1 = [('g4', 'quarter'), ('a4', 'quarter'), ('b4', 'quarter'), ('c#5', 'quarter')]
data2 = [('d5', 'whole')]
data = [data1, data2]
partUpper = stream.Part()

def makeUpperPart(data):
    for mData in data:
        m = stream.Measure()
        for pitchName, durType in mData:
            n = note.Note(pitchName)
            n.duration.type = durType
            m.append(n)
        partUpper.append(m)
makeUpperPart(data)

# Now, we can add both Part objects into a music21 Score object.

sCadence = stream.Score()
sCadence.insert(0, partUpper)
sCadence.insert(0, partLower)

# Now, let's play the MIDI of the sCadence Score [from memory, ie no file  write necessary] using pygame

import cStringIO

# for music21 <= v.1.2:
if hasattr(sCadence, 'midiFile'):
   sCadence_mf = sCadence.midiFile
else: # for >= v.1.3:
   sCadence_mf = midi.translate.streamToMidiFile(sCadence)
sCadence_mStr = sCadence_mf.writestr()
sCadence_mStrFile = cStringIO.StringIO(sCadence_mStr)

import pygame

freq = 44100    # audio CD quality
bitsize = -16   # unsigned 16 bit
channels = 2    # 1 is mono, 2 is stereo
buffer = 1024    # number of samples
pygame.mixer.init(freq, bitsize, channels, buffer)

# optional volume 0 to 1.0
pygame.mixer.music.set_volume(0.8)

def play_music(music_file):
    """
    stream music with mixer.music module in blocking manner
    this will stream the sound from disk while playing
    """
    clock = pygame.time.Clock()
    try:
        pygame.mixer.music.load(music_file)
        print "Music file %s loaded!" % music_file
    except pygame.error:
        print "File %s not found! (%s)" % (music_file, pygame.get_error())
        return
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        # check if playback has finished
        clock.tick(30)

# play the midi file we just saved
play_music(sCadence_mStrFile)

#============================

# now let's make a new music21 Score by reversing the upperPart notes
data1.reverse()
data2 = [('d5', 'whole')]
data = [data1, data2]
partUpper = stream.Part()
makeUpperPart(data)
sCadence2 = stream.Score()
sCadence2.insert(0, partUpper)
sCadence2.insert(0, partLower)

# now let's play the new Score
sCadence2_mf = sCadence2.midiFile
sCadence2_mStr = sCadence2_mf.writestr()
sCadence2_mStrFile = cStringIO.StringIO(sCadence2_mStr)
play_music(sCadence2_mStrFile)

## SOURCE NOTES
## There are 3 sources for this mashup:

# 1. Source for the Music21 Score Creation http://web.mit.edu/music21/doc/html/quickStart.html#creating-notes-measures-parts-and-scores

# 2.  Source for the Music21 MidiFile Class Behaviour http://mit.edu/music21/doc/html/moduleMidiBase.html?highlight=midifile#music21.midi.base.MidiFile

# 3.  Source for the pygame player: http://www.daniweb.com/software-development/python/code/216979/embed-and-play-midi-music-in-your-code-python

rawDescription: How can I produce real-time audio output from music made with Music21?

description: Produce real-time audio output from music made with Music21


code:
## main.py ##

class MainWindow(QtGui.QMainWindow):

    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.resize(640,480)
        self.central = widget.Widget()
        self.setCentralWidget(self.central)

        self.toolbar = QtGui.QToolBar()
        self.toolbar.addAction("Reload Entire Widget", self._reloadWidget)
        self.addToolBar(QtCore.Qt.TopToolBarArea, self.toolbar)

    def _reloadWidget(self):
        print "Reloading", widget
        reload(widget)
        self.central.deleteLater()
        self.central = widget.Widget()
        self.setCentralWidget(self.central)

## widget.py ##

class Widget(QtGui.QWidget):

    def __init__(self, *args, **kwargs):
        super(Widget, self).__init__(*args, **kwargs)
        self.layout = QtGui.QVBoxLayout(self)
        self.button = QtGui.QPushButton("Click")
        self.layout.addWidget(self.button)

        self.button.clicked.connect(self.testMethod)

    def testMethod(self):
        print "testmethod(): FOO"

rawDescription: How to debug PyQt applications without relaunching?

description: Debug PyQt applications without relaunching


code:
import fcntl, time, os

f = open("testfile", "w+")
print "Locking..."
fcntl.flock(f.fileno(), fcntl.LOCK_EX)
print "locked"
fcntl.flock(f.fileno(), fcntl.LOCK_UN)

if os.fork() == 0:
    # We're in the child process, and we have an inherited copy of the fd.
    # Lock the file.
    print "Child process locking..."
    fcntl.flock(f.fileno(), fcntl.LOCK_EX)
    print "Child process locked..."
    time.sleep(1000)
else:
    # We're in the parent.  Give the child process a moment to lock the file.
    time.sleep(0.5)

    print "Parent process locking..."
    fcntl.flock(f.fileno(), fcntl.LOCK_EX)
    print "Parent process locked"
    time.sleep(1000)

rawDescription: Does python's fcntl.flock function provide thread level locking of file access?


code:
from scipy.optimize import curve_fit,fmin
import numpy
import pylab

# Create a gaussian function

def gaussian(x, a, b, c):
    val = a * numpy.exp(-(x - b)**2 / (2*c**2))
    return val

# Generate fake data.
zMinEntry = 80.0*1E-06
zMaxEntry = 180.0*1E-06
zStepEntry = 0.2*1E-06

x = numpy.arange(zMinEntry,
                 zMaxEntry,
                 zStepEntry,
                 dtype = numpy.float64)

n = len(x)

meanY = zMinEntry + (zMaxEntry - zMinEntry)/2
sigmaY = 10.0E-06

a = 1.0/(sigmaY*numpy.sqrt(2*numpy.pi))
y = gaussian(x, a, meanY, sigmaY) + a*0.1*numpy.random.normal(0, 1, size=len(x))

print a, meanY, sigmaY
# estimate starting values from the data
a = y.max()
b = x[numpy.argmax(a)]
c = b

# define a least squares function to optimize
def minfunc(params):
    return sum((y-gaussian(x,params[0],params[1],params[2]))**2)

# fit
popt = fmin(minfunc,[a,b,c])

# Print results
print("Scale =  %.3f" % (popt[0]))
print("Offset = %.3f" % (popt[1]))
print("Sigma =  %.3f" % (popt[2]))

pylab.plot(x, y, 'ro')
pylab.plot(x, gaussian(x, popt[0], popt[1], popt[2]),lw = 2)
pylab.xlim(x.min(),x.max())
pylab.grid(True)
pylab.show()

rawDescription: Python gaussian fit on simulated gaussian noisy data


code:
for pair in list:
    if pair[1] == stringdestination:
        print "target reached"

rawDescription: this simple function in python doesn't work properly

description: This simple function in python doesn't work properly


code: sorted(student_loan_portfolio.items(), key=lambda (k,v): v['rate'], reverse=True)

rawDescription: Iterate through dictionary with respect to nested dictionary


code:
import sys

def applejuice(q):
    func_name = sys._getframe().f_code.co_name
    print func_name

rawDescription: How to print the function name as a string in Python from inside that function

description: Print the function name as a string in Python from inside that function


code:
from github3 import GitHub
gh = GitHub()
releases = gh.repository("github", "git-lfs").iter_releases()
for release in releases:
  for asset in release.assets:
    print "Release %s: %s" % (release.name, asset.name)

rawDescription: Is it possible to access the 'Releases' Tag via PyGithub?


code:
List1 = []
for a in range(2):
    b = raw_input("cmd :")
    List1.append(b)
    a += 1
print List1

rawDescription: concatenate list by user input (string) and displaying the List

description: Concatenate list by user input (string) and displaying the List


rawDescription: Python precision when iterating through list?


code:
for line in lines:
    linedata = re.split(r'\t+', line)
    print ",".join(linedata)

rawDescription: python split string on whitespace

description: Python split string on whitespace


code:
import urllib2
from BeautifulSoup import BeautifulSoup

url = "http://www.samhsa.gov/data/NSDUH/2k10State/NSDUHsae2010/NSDUHsaeAppC2010.htm"
soup = BeautifulSoup(urllib2.urlopen(url).read())

for row in soup.findAll('table')[0].tbody.findAll('tr'):
    first_column = row.findAll('th')[0].contents
    third_column = row.findAll('td')[2].contents
    print first_column, third_column

rawDescription: Extracting selected columns from a table using BeautifulSoup


code:
from datetime import datetime,timedelta

def is_older_than_a_day(test_time):
    one_day_ago = datetime.now() - timedelta(days=1)

    if test_time > one_day_ago:
        print "The test time is less than one day old!"
    else:
        print "The test time is older than one day."

rawDescription: Comparing date and time in python

description: Comparing date and time in python


code:
import itertools as it

list1=['12aa','2a','c2']
list2=['2ac','c2a','1ac']

# First- Finding combinations of each two item from list1.
first = list(it.combinations(list1, 2))

# Second- Finding combinations of each two item from list2.
second = list(it.combinations(list2, 2))

# Third- Finding combinations of each two items from list1 and list2
third = list(it.product(list1, list2))

# Fourth- Calculating each combinations total length
for combination in first: # first, second, third
    print combination, len(''.join(combination))

rawDescription: Finding length of items from a list

description: Finding length of items from a list


code:
from PyQt4 import QtCore
import time
import sys

# Subclassing QThread
# http://qt-project.org/doc/latest/qthread.html
class AThread(QtCore.QThread):

    def run(self):
        count = 0
        while count < 5:
            time.sleep(1)
            print "Increasing"
            count += 1

# Subclassing QObject and using moveToThread
# http://blog.qt.digia.com/blog/2007/07/05/qthreads-no-longer-abstract
class SomeObject(QtCore.QObject):

    finished = QtCore.pyqtSignal()

    def longRunning(self):
        count = 0
        while count < 5:
            time.sleep(1)
            print "Increasing"
            count += 1
        self.finished.emit()

# Using a QRunnable
# http://qt-project.org/doc/latest/qthreadpool.html
# Note that a QRunnable isn't a subclass of QObject and therefore does
# not provide signals and slots.
class Runnable(QtCore.QRunnable):

    def run(self):
        count = 0
        app = QtCore.QCoreApplication.instance()
        while count < 5:
            print "Increasing"
            time.sleep(1)
            count += 1
        app.quit()

def usingQThread():
    app = QtCore.QCoreApplication([])
    thread = AThread()
    thread.finished.connect(app.exit)
    thread.start()
    sys.exit(app.exec_())

def usingMoveToThread():
    app = QtCore.QCoreApplication([])
    objThread = QtCore.QThread()
    obj = SomeObject()
    obj.moveToThread(objThread)
    obj.finished.connect(objThread.quit)
    objThread.started.connect(obj.longRunning)
    objThread.finished.connect(app.exit)
    objThread.start()
    sys.exit(app.exec_())

def usingQRunnable():
    app = QtCore.QCoreApplication([])
    runnable = Runnable()
    QtCore.QThreadPool.globalInstance().start(runnable)
    sys.exit(app.exec_())

if __name__ == "__main__":
    usingQThread()
    #usingMoveToThread()
    #usingQRunnable()

rawDescription: Background thread with QThread in PyQt

description: Background thread with QThread in PyQt


code:
from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)              # start 4 worker processes
    inputs = range(10)
    result = pool.map(f, inputs)
    print result

rawDescription: Naive and easiest way to decompose independent loop into parallel threads/processes


code:
import itertools
main = [
{'country': u'CYPRUS', 'naziv': 'AKEL', 'FCI': 2},
{'country': u'CYPRUS', 'naziv': 'DIKO', 'FCI': 4},
]
second = [
{'likes': '8625.00', 'talks': '1215.00', 'naziv': 'AKEL'},
{'likes': '2746.00', 'talks': 0, 'naziv': 'DIKO'},
]

lst = sorted(itertools.chain(main,second), key=lambda x:x['naziv'])
list_c = []
for k,v in itertools.groupby(lst, key=lambda x:x['naziv']):
    d = {}
    for dct in v:
        d.update(dct)
    list_c.append(d)
print list_c

rawDescription: Python update dictionary based on key value pair


code:
class Division(object):
    def __init__(self,dept, fullTime, partTime):
        self.fullTime = fullTime
        self.partTime = partTime
        self.dept=dept
    def getList(self):
      return "The {0} department has {1} full-time and {2} part-time instructors.".format(self.dept, self.fullTime, self.partTime)

class Department(Division):
    pass
myDept = Department("CIS",12,37)
print myDept.getList()

rawDescription: Python Classes and Inheritance

description: Python Classes and Inheritance


code:
import os

file1 = open("out1.txt", "r")
file2 = open("out2.txt", "w")

i = 0
for file in os.listdir('.'):
    if file.endswith('.ac3'):
        print file
        newname = str(i) + '.ac3'
        os.rename(file, newname)
        file2.write(file1.readline().rstrip() + ' ' + newname + '\n')
        i += 1

rawDescription: Batch renaming files

description: Batch renaming files


code:
def pid_is_alive(pid):
    try:
        os.kill(pid, 0)
        os.waitpid(pid, os.WNOHANG)
        os.kill(pid, 0)
    except OSError:
        return False
    return True

def test():
    X = 1000 * 1000
    Y = 5000
    pid = os.fork()
    if pid == 0:
        thread1 =  MyCustomThread() #Sleeps for 30 seconds and ends.
        thread1.start()
        print "Started 1!"
        timeout = X # say, 1000ms
        while timeout > 0:
            if not thread1.is_alive(): return "custom thread finished before the deadline!"
            timeout -= 1
            sleep(0.001)
        if thread1.is_alive():
            return "custom thread didn't finish before the deadline!"
            thread1.stop()
        exit()

    else:
        timeout2 = Y # say, 500ms
        while timeout2 > 0:
            if not pid_is_alive(pid): return "child PID finished!"
            timeout2 -= 1
            sleep(0.001)
        if pid_is_alive(pid):
            print "child PID didn't finish yet!"
            exit()
print test()
print "all done!"

rawDescription: Wait at most N seconds for a fork'd child PID to finish


code:
import datetime
import re

# Note the \\x to escape \x
foo = "aaa\bbb\ccc\ddd **16 April**\\xyz"
bar = "aaa\bbb\ccc\ddd\**eee** **1 December**\\xyz"

# Could do \d+ and \w+ aswell, it doesn't seem to matter too much in this situation
pattern = '\*\*(\d{1,2} \w{4,9})\*\*'

# "16 April" etc
foo_format = re.search(pattern, foo).group(1)
bar_format = re.search(pattern, bar).group(1)

year = str(datetime.datetime.now().year)

# Datetime object
foo_date = datetime.datetime.strptime(year + " " + foo_format, "%Y %d %B")
bar_date = datetime.datetime.strptime(year + " " + bar_format, "%Y %d %B")

print foo_date.strftime("%Y-%m-%d")
print bar_date.strftime("%Y-%m-%d")

rawDescription: Search text in string python

description: Search text in string python


code:
for i in range(0,len(list1),2):
    name = list1[i]
    tag = list1[i+1]
    print '<tag name="%s">%s</tag>' % (name, tag)

rawDescription: Python for loop access two elements at a time


code:
from openpyxl import Workbook, load_workbook

wb = Workbook()
ws = wb.create_sheet()
ws.title = 'Pi'
ws.cell('F5').value = 3.14156265
wb.save(filename=r'C:\book2.xls')

# Re-opening the file:
wb_re_read = load_workbook(filename=r'C:\book2.xls')
sheet = wb_re_read.get_sheet_by_name('Pi')
print sheet.cell('F5').value

rawDescription: How to append to an existing excel sheet with XLWT in Python

description: Append to an existing excel sheet with XLWT in Python


code:
import os
import subprocess

if __name__ == '__main__':
    package_name = 'package'
    short_package_name = 'package-1.0.6'

    print "Changing to SOURCES"
    os.chdir('SOURCES')

    tar_file = '.'.join([short_package_name, 'tar', 'gz'])
    print "Untarring ", tar_file
    p = subprocess.Popen(['tar', 'xzfv', tar_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, errors = p.communicate()

    print "Changing to ", short_package_name
    os.chdir(short_package_name)

    print "Setting up source distribution"
    p = subprocess.Popen(['python', 'setup.py', 'install'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, errors = p.communicate()

rawDescription: How to create a setup.py that consumes a tar file

description: Create a setup.py that consumes a tar file


code:
from urllib2 import urlopen
from bs4 import BeautifulSoup
import requests
import sys

URL= 'http://coe2.annauniv.edu/result/index.php'
soup = BeautifulSoup(urlopen(URL))
#print soup.prettify()

for hit in soup.findAll(attrs={'class' : 's2'}):
    print hit.contents[0].strip()

RegisterNumber = raw_input("Enter the registration number: ")
DateofBirth = raw_input("Enter the date of birth [DD-MM-YYYY]: ")
login_input = raw_input("Enter the what is()? ")

def main():
    # Start a session so we can have persistant cookies

    # Session() >> http://docs.python-requests.org/en/latest/api/#request-sessions
    session = requests.Session()

    # This is the form data that the page sends when logging in

    # You are wrongly using string values instead of the intended variables here that is RegisterNumber and not 'RegisterNumber'
    login_data = {
    'register_no': RegisterNumber,
    'dob': DateofBirth,
    'security_code_student': login_input,
    'gos': 'Login',
    }
    print login_data

    # Authenticate
    r = session.post(URL, data = login_data)
    # Try accessing a page that requires you to be logged in
    r = session.get('http://coe2.annauniv.edu/result/students_corner.php')
    print r

if __name__ == '__main__':
    main()

rawDescription: Login to a website using python

description: Login to a website using python


code:
from bs4 import BeautifulSoup as bs
from urllib2 import urlopen
r = urlopen('http://i.cantonfair.org.cn/en/expexhibitorlist.aspx?categoryno=410').read()
soup = bs(r, "lxml")
lis = soup.find_all("li")
hrefs = [c.a['href'] for c in lis]
print hrefs

rawDescription: How to get a tag which is present in div tag in python?

description: Get a tag which is present in div tag in python


code:
import flickrapi
api_key = 'API KEY YYYYYYYYYY' # you will need a key
api_password = 'your secret'
flickrClient = flickrapi.FlickrAPI(api_key, api_password)
# now you could use the methods on this client
# flickrClient.methodname(param)
favourites = flickrClient.favorites_getPublicList(user_id='userid')
# Get the title of the photos
for photo in favourites.photos[0].photo:
    print photo['title']

rawDescription: Using Python to read images from a www.flickr.com account


code:
import imaplib
import email
import time

GREETINGS = "Merry Christmas"

while True:
    # Connect
    imapClient = imaplib.IMAP4_SSL("imap.gmail.com")
    # Login
    imapClient.login(USERNAME, PASSWORD)
    # Choose folder inbox
    imapClient.select("INBOX")

    # Fetch unseen messages
    x, message_ids = imapClient.search(None, "UNSEEN")
    for msg_id in message_ids[0].split():
        # Download the message
        _, data = imapClient.fetch(msg_id, "(RFC822)")
        # Parse data using email module
        msg = email.message_from_string(data[0][1])

        if msg["subject"] == GREETINGS:
            # do something...
            print "Working"
        else:
            print "Not working"
        # do something else...

    # Log out
    imapClient.close()
    imapClient.logout()

    time.sleep(2)

rawDescription: Feedparser to Parse Specific Text in Entries


code:
import fileinput
for line in fileinput.input("C:\\Users\\Administrator\\Desktop\\new.txt",inplace=True):
    print "something", #print("something", end ="") for python 3

rawDescription: Insert a line into the middle of a text file in Python


code:
grapheme = grapheme.decode(sys.stdin.encoding)
if grapheme in orth:
    print u'success, your grapheme was: ' + grapheme
    return True

rawDescription: python2.7 utf-8 input through command line in Windows7

description: Python2.7 utf-8 input through command line in Windows7


rawDescription: Python: Read in escaped Unicode characters and turn them into readable text


code:
def index(request):
   a_list = [1,2,3,4]
   print a_list
   return render(request, 'index.html', {'list':a_list})

rawDescription: How do I print a list from views.py to the console?

description: Print a list from views.py to the console