code:
contacts = Contact.objects.all()
for contact in contacts:
    values = []
    for f in fields_foreign:
        value = getattr(contact, f[0])
        if f[1]: # Foreignkey, call str() on the model object
           value = str(value) # this calls __str__ in model
        values.append(value)
    print values

rawDescription: Model.objects.all() returns integers for ForeignKeys and choice fields - how to force it to return names instead?


code:
import itertools

with open("your_document") as f:
    lines = sorted(map(str.int, f.read().strip().split()))
    for x,y in itertools.groupby(lines):
        print x, list(y)

rawDescription: How do I count occurences of a unique label?

description: Count occurences of a unique label


code:
#set more as estimated number of columns
N = 30

df1 = pd.read_csv('test/file.txt', sep="\s+", names=range(N))

df1 = df1.dropna(axis=1, how='all')  #drop columns with all NaN

df1.columns = df1.loc[0].dropna()[:-1].append(pd.Series(range(1, len(df1.columns) - len(df1.loc[0].dropna()[:-1]) + 1 )))

#remove first line with uncomplete column names
df1 = df1.ix[1:]
print df1.head()

rawDescription: How to read unstructured csv in pandas

description: Read unstructured csv in pandas


rawDescription: Python regex for line of digits and optional dash+digits. Why not matching?


code:
def solve_equation(start, end, equation):
    for x in xrange(start, end):
        yield equation(x)

def my_equation(x):
    wt=647
    wp=119000
    e0=10983849
    e1 =e0-(wp**2/(w*2+wt))
    return e1

print solve_equation(0, 100, my_equation)
print solve_equation(500, 1000, my_equation)

rawDescription: how to variate a parameter in an equation python

description: Variate a parameter in an equation python


code:
#!/usr/bin/env python

import numpy
import numpy.random
import numpy.linalg
import sys
import time

def init(n):
    a = numpy.matrix(numpy.random.rand(n,n))
    b = numpy.random.rand(n,1)
    b = b.reshape((n,1))
    return a,b

def np_mult(a, b):
    c = numpy.multiply(a,b)
    return c

def manual_mult(a,b):
    c = numpy.matrix(numpy.zeros_like(a))
    for i in range(0,a.shape[0]):
        for j in range(0,a.shape[1]):
             c[i,j] = a[i,j] * b[i]
    return c

def main(argv=None):
    if argv is None:
        argv = sys.argv

    n = int(argv[1])
    niters = int(argv[2])
    a,b = init(n)

    start = time.time()
    for i in xrange(niters):
        cnp = np_mult(a,b)
    end = time.time()

    nptime = (end-start)/niters
    print 'Numpy: ', nptime

    start = time.time()
    for i in xrange(niters):
        cm = manual_mult(a,b)
    end = time.time()

    manualtime = (end-start)/niters
    print 'Manual: ', manualtime
    print 'Speed difference = ', manualtime/nptime
    print 'Diff = ', numpy.linalg.norm(cm - cnp)/numpy.linalg.norm(cnp)

    return 0

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

rawDescription: Python Parallel Matrix Vector Multiplication


code:
r = re.compile("[A-Z]{3}([a-z])[A-Z]{3}")
print r.match(gibberish).group(1)

rawDescription: Find a lowercase letter surronded by three uppercase letters


code:
idx = [1]
for i in idx:
    print dict_list[i]["Client"], dict_list[i]['Contact Name'], dict_list[i]['Email']

rawDescription: Python Dictionary inside a list (pulling individual values)


code:
def func():
    print 'hello'

def func():
    print 'hello'
    return None

rawDescription: Python: "return" in functions

description: Python: "return" in functions


code:
def get_count_for_rows(*rows):
    rows = sorted(rows)
    counts = []
    with open("so_cnt_file.txt") as infile:
        cur_row = 0
        for i in range(cur_row, 2):
             next(infile)
        while rows:
            inrow = rows.pop(0)
            for i in range(cur_row, inrow):
                next(infile)
            cnt = 0
            for line in infile:
                row, col = [int(val) for val in line.strip().split(" ") if val]
                if col == 0:
                    counts.append((inrow, cnt))
                    break
                cnt += 1
            cur_row = row
    return counts

print get_count_for_rows(1, 6)

rawDescription: Python counting lines in files using exact locations


code:
import urllib2
from bs4 import BeautifulSoup
url = "https://www.facebook.com/hellomeets/events"

html = urllib2.urlopen(url).read()
print html

rawDescription: Python wget saves a file. how to get data in variable


code:
#!/usr/bin/python

import operator

def step_range(start, end, step, step_func, compare_func):
    while compare_func(start, end):
        yield start
        start = step_func(start, step)

def main():
    print [x for x in step_range(1, 64, 2, operator.mul, operator.le)]
    print [x for x in step_range(64, 0, 2, operator.div, operator.gt)]
    print [x for x in step_range(0, 64, 8, operator.add, operator.le)]
    print [x for x in step_range(64, 0, 8, operator.sub, operator.ge)]

if __name__ == '__main__':
    main()

rawDescription: For loop with step

description: For loop with step


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

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

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

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

Time=np.linspace(0, len(signal)/fs, num=len(signal))

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

rawDescription: How to plot a wav file

description: Plot a wav file


code:
import shlex
print shlex.split(r'C:\\test.exe --help')
print shlex.split(r'"C:\\test.exe" --help')
print shlex.split(r'"C:\\Program Files\\test.exe" --help')

rawDescription: Python os.path.basename, strip parameters


code:
import operator
print("Calculator")

var1 = input("Give the first number: ")
var2 = input("Give the second number: ")

print("(1) +\n(2) -\n(3) *\n(4) /\n(5)Change numbers\n(6)Quit")
print("Current numbers: " + var1 + " " + var2)
operations={"1":operator.add,"2":operator.sub,"3":operator.mul,"4":operator.div}
while True:
    option = input("Please select something (1-6): ")
    print option
    if option in operations:
        var3=operations[option](int(var1),int(var2))
        print "value"+str( var3)
        continue
    if (option == "6"):
        print "quiting"
        break
    elif (option == "5"):
        var1 = input("Give the first number: ")
        var2 = input("Give the second number: ")
    else:
        print("Selection was not correct.")

print("Thank you!")

rawDescription: Python: I fell in an infinite loop

description: Python: I fell in an infinite loop


code:
import zipfile
from cStringIO import StringIO

s = StringIO()
temp_zip_file = zipfile.ZipFile(s, 'w')
# ...
temp_zip_file.close()

print s.getvalue()

rawDescription: Create temp zip file on Django and delete it after return


code:
def main():
    executor = concurrent.futures.ProcessPoolExecutor(10)
    futures = [executor.submit(enqueue_tasks, group) for group in grouper(key_list, 40)]
    concurrent.futures.wait(futures)
    print sum(len(future.result()) for future in futures)

rawDescription: My queue is empty after multiprocessing.Process instances finish


code:
import sys

print "No settings module specified."
sys.exit()

rawDescription: How can I detect when a Django server is started without a settings module?

description: Detect when a Django server is started without a settings module


rawDescription: Find next date by day of week

description: Find next date by day of week


code:
my_string = "deadbeef"
my_hex = my_string.decode('hex')  # python 2 only
print my_hex

rawDescription: Python: print a variable in hex

description: Python: print a variable in hex


code:
#!/usr/bin/python
import subprocess, os, select, time

path = "/usr/bin/python"
proc = subprocess.Popen([path, "foo.py"], shell=False,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
for i in xrange(0,5):
    time.sleep(1)
    inputready, outputready, exceptready = select.select(
        [proc.stdout, proc.stderr], [proc.stdin,],
        [proc.stdout, proc.stderr, proc.stdin], 0)
    if not inputready:
        print "No Data",
    print inputready, outputready, exceptready
    for s in inputready:
        print s.fileno(),s.readline()

proc.terminate()
print "After Terminating"

for i in xrange(0,5):
    inputready, outputready, exceptready = select.select(
        [proc.stdout, proc.stderr], [proc.stdin,],
        [proc.stdout, proc.stderr, proc.stdin], 0)
    if not inputready:
        print "No Data",
    print inputready, outputready, exceptready
    for s in inputready:
        print s.fileno(),s.readline()

rawDescription: Asyncronous Bidirectional IO Redirection for a child process


rawDescription: Converting list items to dictionary using lists items


code:
for i, j in enumerate(L):
    print L[i]
    temp = map(str, L[j:])
    while temp:
            print ' ', ','.join(temp)
            temp = temp[1:]

rawDescription: Scanning a list

description: Scanning a list


code:
title = win32gui.GetWindowText(win32gui.GetForegroundWindow())
if re.search(title, "python", re.IGNORECASE):
    print "Found it!"

rawDescription: Have to find if some window name has some string on it with python


code:
m = numpy.ones(1000, dtype=numpy.float64) / 1000
print repr(m.sum())

rawDescription: Python 32/64-bit machine float summing of transposed matrix not correct?


code:
res = {'value': []}
def revnest(inp, keys=[]):
    res2 = res['value']
    if type(inp) == list:
        inp = {i:j[i] for j in inp for i in j}
    for x in inp:
        if x == 'value':
            res2.append({inp[x]:{}})
            res2 = res2[-1][inp[x]]
            for y in keys[::-1]:
                res2[y] = {}
                res2 = res2[y]
        else:
            revnest(inp[x], keys+[x])

revnest(exampleset)
print res

rawDescription: Using recursion to reverse a dictionary around a value in python


code:
import csv

a = {}
with open('/Users/settingj/Desktop/NOxMultiplier.csv') as f:
    reader = csv.reader(f, delimiter='\t')
    for row in reader:
        a[row[0]] = row[1]
print a

rawDescription: Parsing with Python

description: Parsing with Python


code:
list_without_units = [1,2,3]
list_with_units = [str(value)+"kg" for value in list_without_units]

print list_with_units # ['1kg', '2kg', '3kg']

rawDescription: How to add units like kg or grams 'superficially ' in a list in python

description: Add units like kg or grams 'superficially ' in a list in python


code:
print data.loc[data['Gender']==1, 'Scores'].max()
8

rawDescription: how to use if statements to read from two columns in Python?

description: Use if statements to read from two columns in Python


code:
def determine_winner(results):
    print results
    for key in results:
        results[key].sort()          # sort all the results
        length = len(results[key])

    for l in range(length):          # examine the scores in order
        max_score = 0
        next_results = {}
        for key in results:          # compare each scorer
            score = results[key][l]
            if score < max_score:    # ignore this scorer
                continue
            if score == max_score:   # multiple high scores
                winner = 'Tied'
            else:                    # new high score
                winner = key
                max_score = score
            # prepare the results for the next round
            next_results[key] = results[key]
        results = next_results       # get ready for the next round
    print winner

determine_winner({'A':[1,1], 'B':[2,2], 'C':[1,1]})
determine_winner({'A':[1,2,3,4], 'B':[2,3,4,1], 'C':[1,3,4,5]})
determine_winner({'A':[1,2,3,4], 'B':[2,3,4,1], 'C':[1,4,1,5]})

rawDescription: Python Error with producing key of max of mins


code:
 #!/usr/bin/python
import sched, time
s = sched.scheduler(time.time, time.sleep)
def print_time():
    s.enter(5, 1, print_time, ())
    print "From print_time", time.time()

def print_some_times():
    print time.time()
    s.enter(5, 1, print_time, ())
    s.run()

print_some_times()

rawDescription: run python scheduler continuously

description: Run python scheduler continuously


code:
import re
p = re.compile(ur'\bMyHost="xxxx"\r?\n.*?MyIp=\s*\"([^"]*)', re.IGNORECASE)
test_str = u"blah blah blah MyHost=\"xxxx\"\nagain blah blah blah MyIp= \"x.x.x.x\""

re.findall(p, test_str)

rawDescription: Match a pattern only when previous pattern matches


code:
import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
    print "Invalid"
else:
    print "Valid"

rawDescription: How to check a string for a special character?

description: Check a string for a special character


code:
try:
    # try the thing you expect to work
    mp3 = open('Tracks/' + title + '.mp3', 'w')
except OSError, e:
    # exception is for the unlikely case
    os.makedirs('Tracks')
    mp3 = open('Tracks/' + title + '.mp3', 'w')

mp3.write(mp3File.content)
mp3.close()
print '%s has been created.' % fileName

rawDescription: Error Handling for When a Directory Doesn't Exist


code:
#!/usr/bin/env python

import pytz
import babel.dates
import re

country_timezones = {}
for (country, tzlist) in pytz.country_timezones.iteritems():
    country_name = pytz.country_names[country]
    cities = []
    for timezone in tzlist:
        # remove continent
        city = re.sub(r'^[^/]*/', r'', timezone)
        # Argentina has an extra "Argentina/" on my system (pytz 2010b)
        city = re.sub(country_name + '/', '', city)
        # Indiana and North Dakota have different rules by country
        # change Indiana/Location to Location, Indiana
        city = re.sub(r'^([^/]*)/(.*)', r'\2, \1', city)
        # change underscores to spaces
        city = re.sub(r'_', r' ', city)
        cities.append(city)
    country_timezones[country_name] = cities

for country in sorted(country_timezones):
    print country
    for city in sorted(country_timezones[country]):
        print "\t%s" % (city)

rawDescription: Better python datetime display?

description: Better python datetime display


code:
import itertools

list_input =     [["John","Matt","Steve"],["is"],["a"],["great","dedicated"],["engineer","student","athelete"]]
for element in itertools.product(*list_input):
    print element

rawDescription: Python module to generate all permutations of possible string replacements in a string?


code:
from socket import *

serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
print 'Server is now running...'
while 1:
    connectionSocket, addr = serverSocket.accept()
    connectionSocket.sendall("HTTP/1.0 200 OK\r\n"+
                             "Content-Type: text/html\r\n"+
                             "Connection: close\r\n"+
                             "\r\n"+
        """<!DOCTYPE html>
        <title>Lab sign-up - AntonX Server</title>

Lab Sign-up

        <form action=\"localhost:12000\" method=\"GET\">

Time	Name

1 PM	<input type=\"text\" name=\"time_1\">

2 PM	<input type=\"text\" name=\"time_2\">

3 PM	<input type=\"text\" name=\"time_3\">

4 PM	<input type=\"text\" name=\"time_4\">

5 PM	<input type=\"text\" name=\"time_5\">

<input type=\"submit\" name=\"submit\" value=\"Steal this spot!\">

        </form>

        \r\n
    """)
    connectionSocket.close()

rawDescription: Why is my Python sockets web-server code failing?


code:
def rounding_iterator(seq, stride):
    try:
        i = 0
        while True:
            yield seq[int(round(i*stride))]
            i += 1
    except IndexError:
        pass

pies = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print list(rounding_iterator(pies, 1))
print list(rounding_iterator(pies, 1.1))
print list(rounding_iterator(pies, .9))

rawDescription: Python Array Index - Every X elements?

description: Python Array Index - Every X elements


code:
import subprocess, shlex, re
strs =  subprocess.check_output(shlex.split('ip r l'))
match_string = r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
ip = re.search('src '+ match_string, strs).group(1)
gateway = re.search('default via ' + match_string, strs).group(1)
print gateway, ip
#10.64.64.64 106.205.92.100

rawDescription: Find IP and Gateway using Python Script

description: Find IP and Gateway using Python Script


rawDescription: Referencing range of IP addresses

description: Referencing range of IP addresses


code:
import re
def repl(matchobj):
    global counter
    replacementFor = {'{search-string1}': '{replace-string1}',
                      '{search-string2}': '{replace-string2}',
                      '{search-string3}': '{replace-string3}'}

    counter = counter+1
    if counter == 2:
        return replacementFor.get(matchobj.group(0), matchobj.group(0))
    else:
        return matchobj.group(0)

counter = 0
line = "$lang['MY_KEY'] = '{search-string} wird in Analyse {search-string1} bercksichtigt'";
print re.sub(r'{.*?}',repl,line)

counter = 0
line = "$lang['MY_KEY'] = '{search-string} wird in Analyse {search-string3} bercksichtigt'";
print re.sub(r'{.*?}',repl,line)

rawDescription: Search & replace a substring in python

description: Search & replace a substring in python


code:
class GUI(wx.Frame):

    def __init__(self, parent, id, title):
        screenSize = (400, 400)
        wx.Frame.__init__(self, None, id, title, size=screenSize)
        myFont = wx.Font(15, wx.MODERN, wx.NORMAL, wx.BOLD)
        panelsSizer = wx.BoxSizer(wx.VERTICAL)
        sizer1 = wx.BoxSizer(wx.VERTICAL)
        myPanel = wx.Panel(self, -1,style=wx.SIMPLE_BORDER)
        #Uncommenting the following line has no effect on scroll bar behavior!
        #myPanel.Bind(wx.EVT_SCROLLWIN, self.OnScroll)
        myPanel.SetScrollbar(wx.VERTICAL, 0, 0, 2, 0)
        panel1 = wx.lib.scrolledpanel.ScrolledPanel(myPanel, -1, style=wx.SIMPLE_BORDER)
        panel1.SetBackgroundColour('#FFFFFF')
        panel2 = wx.lib.scrolledpanel.ScrolledPanel(myPanel, -1, style=wx.SIMPLE_BORDER)
        panel2.SetBackgroundColour('#55F4FF')

        k = 0
        for i in range(1,10):
            sPanel ='Panel' +str(k)
            sPanel = wx.Panel(panel1)
            label = str(k)+'This is panel-1'
            text = wx.StaticText(sPanel, -1, label)
            text.SetForegroundColour('#0101DF')
            text.SetFont(myFont)
            sizer1.Add(sPanel, 0, wx.ALL, 5)
            sizer1.Add(wx.StaticLine(panel1), 0, wx.ALL|wx.EXPAND, 0)
            k += 1

        panel1.SetSizer(sizer1)
        panelsSizer.Add(panel1, 1, wx.EXPAND)
        panelsSizer.Add(panel2, 1, wx.EXPAND)
        myPanel.SetSizer(panelsSizer)

    def OnScroll(self, evt):
          print "Got it"
          pass

if __name__=='__main__':
   app = wx.App()
   frame = GUI(parent=None, id=-1, title="Test")
   frame.Show()
   app.MainLoop()

rawDescription: Disablling scrolling of a scroll bar while keeping it visible in wxPython


code:
child_methods = [] # a list of all the methods in `Child`

class Parent(object):
    def parent_method(self):
        print "parent_method() called"
        method = child_methods[0]
        method(self)

class Child(Parent):
    def child_method(self):
        print "child_method() called"

# add child_method to child_methods
child_methods.append(Child.child_method)

rawDescription: [Python]Calling method(self)

description: [Python]Calling method(self)


code:
def only_evens(lst):
    return [sublist for sublist in lst if all(item % 2 == 0 for item in sublist)]

print only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]])
# [[4, 0, 6], [2]]

rawDescription: Python - return the list of lists in lst that contain only integers?


code:
diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
             'ore\ntree\nemu\n'.splitlines(1))
diff = list(diff) # materialize the generated delta into a list
print ''.join(restore(diff, 1)),
print ''.join(restore(diff, 2)),

rawDescription: Python - Comparing two CSV documents from the same python script from an update to another one


code:
import re
from bs4 import BeautifulSoup

html = """

    TF4 - Oreos (0)
    Awesome Game Boy Facts (0)

"""
soup = BeautifulSoup(html)
links = soup.find_all('a', {'id': re.compile('^c\d+')})
for link in links:
    print link.text

rawDescription: Find specific link text with bs4

description: Find specific link text with bs4


code:
import sys

if not sys.stdin.isatty():
    stdin = sys.stdin.readlines()
    print stdin
    sys.stdin = open('/dev/tty')
else:
    print "No stdin"

test_raw = raw_input()
print test_raw

rawDescription: Argparse optional stdin argument

description: Argparse optional stdin argument


code:
import json

with open('source.txt', 'rb') as f:
    print json.load(f)

rawDescription: How do you read in a text (.txt) file as a .py file in Python 2.7?

description: Read in a text (.txt) file as a .py file in Python 2.7


code:
class Blah:
    ABC, DEF = range(2)

    def meth(self, arg=ABC):
        print arg

Blah().meth()
# it prints '0'

rawDescription: Using class attribute in method definition as argument?


code:
from bs4 import BeautifulSoup

data = """

First paragraph

Second paragraph

Third paragraph

"""

soup = BeautifulSoup(data, 'html.parser')
for index, p in enumerate(soup.find_all('p'), start=1):
    p['id'] = index

print soup

rawDescription: Python: How can I add a counter to the replacement argument of re.sub()


code:
def prid():
    id = idgen.next()
    print id
prid()
prid()
prid()
prid()

rawDescription: Spark: Using iterator lambda function in RDD map()


code:
if location not in colo:
   print 'Not a recognized location'

rawDescription: How to compare list with actual string in Python?

description: Compare list with actual string in Python


code:
import pylab
from matplotlib.widgets import Button

def draw_button1(event):
    fig = pylab.figure()
    a = pylab.axes([0.1, 0.1, 0.8, 0.8])
    b = Button(a, 'Button 1')

    def say_something(event):
        print "This works."

    b.on_clicked(say_something)
    fig._my_btn = b
    pylab.show()

def draw_button2():
    fig = pylab.figure()
    a = pylab.axes([0.1, 0.1, 0.1, 0.1])
    b = Button(a, 'Button 2')
    b.on_clicked(draw_button1)
    pylab.show()
    fig._my_btn = b

draw_button2()

rawDescription: Button does not work in second (nested) figure


code:
# add the properties
for p in ('edgar','allan','poe'):
    def f(self):
        print 'IN %s' % p
        return '[%s]' % p
    setattr(myClass, p, property(f))

rawDescription: Procedurally created decorator functions


code:
for tbl, values in My_Table.viewitems():
    values['Results'][:] = [x for x in values['Results'] if x[1] is not None]
    print values['Results']

rawDescription: Removing an list from a list of list

description: Removing an list from a list of list


code:
import pandas

cmf = pandas.read_csv('CMF.csv', names=['wavelength', 'x', 'y', 'z'])
d65 = pandas.read_csv('D65.csv', names=['wavelength', 'a', 'b'])
data = pandas.read_csv('data.csv', names=['serialNumber', 'wavelength', 'measurement', 'name'])

lookup = pandas.merge(cmf, d65, on='wavelength')
merged = pandas.merge(data, lookup, on='wavelength')

totals = ((lookup[['x', 'y', 'z']].T*lookup['a']).T).sum()
wps  = totals/totals['y']

print totals['y']
print "D65_CMF_2006_10_deg white point = "
print wps

rawDescription: Python: multiply csv data together with dict()


code:
def f(x, y):
    rand1 = random.randint(0, 10)
    rand2 = random.randint(0, 10)
    result = rand1*x + rand2*y
    print result
    return (result, rand1, rand2)

fxy, a, b = f(x, y)

rawDescription: Getting a particular value from a function


rawDescription: how can i convert a string like 123245wkjsvd :/' to list and sort?

description: Convert a string like 123245wkjsvd :/' to list and sort


code:
import time
import requests
import datetime
dict = {'u56pt7jQXxgmtGnX5MBgsnUz4kgqKS': 'User1', 'uoREW3cuvy3SbSnyc7Ra737nVbrBQh': 'user2'}
app = "app id"
for k in dict:
    user = k
    params = {
    'token': app,
    'user': user,
    'title': 'lala',
    'message': 'test',
    'retry': 300,
    'expire': 40,
    'priority': 2 ,
    'sound': 'siren',
    'ack': False
    }
    msg = requests.post('https://api.pushover.net/1/messages.json', data=params)
    print "POSTed message to " + dict[k]
    json_data = msg.json()
    print json_data['receipt']
    time.sleep(5)
    d = json_data['receipt']
    v = requests.get("https://api.pushover.net/1/receipts/"+ d + ".json?token=" + app)
    out = v.json()
while out['acknowledged'] is 0:
    print "not yet" #placed for debugging
    time.sleep(5)
    v = requests.get("https://api.pushover.net/1/receipts/"+ d + ".json?token=" + app)
    out = v.json() #update the out, so you can check again

def all_acknowledged(dict):
    for user in params:
        if not params['ack']:
            return False
    return True

# Line below is commented out because if we got this far we have at least one acknowledgement
# if out['acknowledged'] is 1:
while not all_acknowledged(dict): # custom function to check whether all users have made an acknowledgement
    ack = out['acknowledged_by']
    for k in dict:
        if ack in k:
            acked = dict[k]
            params['ack'] = True # We must update this when we come across an acknowledged user
            t = datetime.datetime.strftime(datetime.datetime.now(), '%H:%M')
            print (acked + " acknowledged at " + t)
    v = requests.get("https://api.pushover.net/1/receipts/"+ d + ".json?token=" + app)
    out = v.json() #update the out, so you can check again

rawDescription: python acknowlage in pushover using dict

description: Python acknowlage in pushover using dict


code:
class A(object) :
    def __init__(self) :
        d = {"arg1" : (1, "arg1_v"),
             "arg2" : (2, "arg2_v")}
        for key, value in d.items() :
            setattr(self, key, f(*value))

a = A()
print a.arg1
print a.arg2

rawDescription: Map return value of function calls to object attribute


code:
(invid, stock, published, price, invtype, title, author) = read_one_file()

print "Item ID:", invid

rawDescription: Passing variables in Python

description: Passing variables in Python


code:
import requests
from bs4 import BeautifulSoup

r = requests.get("<add your URL here>")
soup = BeautifulSoup(r.content)

for a_tag in soup.find_all('a', class_='listing-name', href=True):
    print 'href: ', a_tag['href']

rawDescription: Python and BeautifulSoup Opening pages

description: Python and BeautifulSoup Opening pages


code:
import os, sys
if len(sys.argv) == 2:
  os.system("sudo rtcwake -m off -s {}".format(sys.argv[1]))
else: print "usage: ..."

rawDescription: Defining the command line arguments of a linux command in python


code:
class MyApp(App):

    def build(self):
        main_widget = Builder.load_string(login_kv)

    def do_login(self, *args):
        print'jo'

rawDescription: Kivy run function from kv button

description: Kivy run function from kv button


code:
from flask import Flask
from flask.ext.restful import Api, Resource
from flask.ext.restful import reqparse

app = Flask(__name__)
api = Api(app)

class UserAPI(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('name', type = str, required = True, help = "No name provided", location = 'json')
        self.reqparse.add_argument('email', type = str, required = True, help = "No email provided", location = 'json')
        self.reqparse.add_argument('password', type = str, required = True, help = "No password provided", location = 'json')
        super(UserAPI, self).__init__()

    def get(self, id):
        if True: #Just checks to see if user with that id exists
            return {"message": "You have GET me"}
        abort(404)

    def put(self, id):
        if True:
            return {"message": "You have PUT me"}
        abort(404)

    def delete(self, id):
        deleteUser(id)
        return { 'result': True}

class UserListAPI(Resource):
    def __init__(self):
        self.reqparse = reqparse.RequestParser()
        self.reqparse.add_argument('name', type = str, required = True, help = "No name provided", location = 'json')
        self.reqparse.add_argument('email', type = str, required = True, help = "No email provided", location = 'json')
        self.reqparse.add_argument('password', type = str, required = True, help = "No password provided", location = 'json')
        self.reqparse.add_argument('role', type = bool, default = 0, location = 'json')
        super(UserListAPI, self).__init__()

    def get(self):
        return { 'users': map(lambda u: marshal(u, user_fields), getAllUsers()) }

    def post(self):
        print self.reqparse.parse_args()
        args = self.reqparse.parse_args()
        new_user = User(args['name'], args['email'], args['password'], args['role'])
        addUser(new_user)
        return {'user' : marshal(new_user, user_fields)}, 201

api.add_resource(UserAPI, '/api/user/<int:id>', endpoint = 'user')
api.add_resource(UserListAPI, '/api/users/', endpoint = 'users')

if __name__ == "__main__":

    app.run(debug=True)

rawDescription: PUT curl request returns bad URI (flask-RESTful)


code:
import types

class what:
    def __init__(self):
        def yolo(self):
            self.extra = "Hello"
            print self.extra

        self.yolo = types.MethodType(yolo, self)

what().yolo()

rawDescription: exec to add a function into a class

description: Exec to add a function into a class


code:
import csv
import operator

with open('input.txt', 'rb') as f_input:
    csv_input = csv.reader(f_input, delimiter='\t')
    headers = next(csv_input)
    row_number = 1

    for k, g in itertools.groupby(csv_input, key=operator.itemgetter(0)):
        row = []
        for entry in g:
            entry = [float(e) for e in entry]
            row.append([row_number] + entry)
            row_number += 1
        print row

rawDescription: Create a list of lists / matrices from a text file in Python 3.4


code:
from multiprocessing import Process, Queue, cpu_count
import random
import time

def serve(queue):
    works = ["task_1", "task_2"]
    while True:
        time.sleep(0.01)
        queue.put(random.choice(works))

def work(id, queue):
    while True:
        task = queue.get()
        if task is None:
            break
        time.sleep(0.05)
        print "%d task:" % id, task
    queue.put(None)

class Manager:
    def __init__(self):
        self.queue = Queue()
        self.NUMBER_OF_PROCESSES = cpu_count()

    def start(self):
        print "starting %d workers" % self.NUMBER_OF_PROCESSES
        self.workers = [Process(target=work, args=(i, self.queue,))
                        for i in xrange(self.NUMBER_OF_PROCESSES)]
        for w in self.workers:
            w.start()

        serve(self.queue)

    def stop(self):
        self.queue.put(None)
        for i in range(self.NUMBER_OF_PROCESS):
            self.workers[i].join()
        queue.close()

Manager().start()

rawDescription: producer/consumer problem with python multiprocessing

description: Producer/consumer problem with python multiprocessing


rawDescription: How can I efficiently process a numpy array in blocks similar to Matlab's blkproc (blockproc) function

description: Efficiently process a numpy array in blocks similar to Matlab's blkproc (blockproc) function


code:
import multiprocessing
import ctypes
import numpy as np

shared_array_base = multiprocessing.Array(ctypes.c_double, 10*10)
shared_array = np.ctypeslib.as_array(shared_array_base.get_obj())
shared_array = shared_array.reshape(10, 10)

#-- edited 2015-05-01: the assert check below checks the wrong thing
#   with recent versions of Numpy/multiprocessing. That no copy is made
#   is indicated by the fact that the program prints the output shown below.
## No copy was made
##assert shared_array.base.base is shared_array_base.get_obj()

# Parallel processing
def my_func(i, def_param=shared_array):
    shared_array[i,:] = i

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=4)
    pool.map(my_func, range(10))

    print shared_array

rawDescription: Is shared readonly data copied to different processes for Python multiprocessing?


code:
t_set = TimedSet()
t_set.add('a')
time.sleep(0.6)
print 'a' in t_set
time.sleep(0.6)
print 'a' in t_set

t_set.add('x', 0.3)
t_set.add('y', 0.4)
t_set.add('z', 0.5)
time.sleep(0.35)
for item in t_set:
    print item

rawDescription: Set class with timed auto remove of elements


code:
from xml.etree import ElementTree as ET

data = """<?xml version="1.0"?>
<config version="1.0" timestamp="xxxxxxxxxx">
    <a>
        <aa>
        ..
        </aa>
    </a>
    <b>
        <bb>
        ...
        </bb>
    </b>
    <c>
        <cc>
            <ccc>
                <cccc>
                    <test>value to find</test>
                </cccc>
            </ccc>
        </cc>
    </c>
</config>"""

tree = ET.fromstring(data)

parent = tree.find('.//cccc')
print next(iter(parent)).text

rawDescription: Find element in xml

description: Find element in xml


code:
import struct
int_no = struct.unpack('>H', v)[0]
print int_no

rawDescription: Python: get int value from a char string


code:
for i in map(int,raw_input().split()):
    ans = do_something(i)
print ans

rawDescription: Taking space separated input in loop with python


code:
import pandas as pd

data = [{"startDate": 123, "endDate": 456, "campaignName": 'abc',
         "campaignCfid": 789, "budgetImpressions": 10},
        {"startDate": 123, "endDate": 456, "campaignName": 'abc',
         "campaignCfid": 789, "budgetImpressions": 50},
        {"startDate": 456, "endDate": 789, "campaignName": 'def',
         "campaignCfid": 123, "budgetImpressions": 80}]

df = pd.DataFrame(data)

grouped = df.groupby(['startDate', 'endDate', 'campaignCfid',
                      'campaignName']).agg(sum)

print grouped.reset_index().to_dict('records')

rawDescription: Group By & Aggregate List of Dictionaries in Python


rawDescription: how to re-order bytes in a python hex string and convert to long

description: Re-order bytes in a python hex string and convert to long


code:
from itertools import islice
with open("datafile") as myfile:
    head = list(islice(myfile, N))
print head

rawDescription: Read first N lines of a file in python

description: Read first N lines of a file in python


code:
print s.split('Parameter(')[1].split(')')[0]
print t.split('Parameter(')[1].split(')')[0]

rawDescription: How to print string inside a parentheses in a line in Python?

description: Print string inside a parentheses in a line in Python


code:
import sys
from PyQt4 import QtGui, QtCore
import numpy as np
import pyqtgraph as pg

class sinus_wave(QtGui.QWidget):
    def __init__(self):
        super(sinus_wave, self).__init__()
        self.init_ui()
        self.qt_connections()
        self.plotcurve = pg.PlotCurveItem()
        self.plotwidget.addItem(self.plotcurve)
        self.amplitude = 10
        self.t = 0
        self.updateplot()

        self.timer = pg.QtCore.QTimer()
        self.timer.timeout.connect(self.moveplot)
        self.timer.start(500)

    def init_ui(self):
        self.setWindowTitle('Sinuswave')
        hbox = QtGui.QVBoxLayout()
        self.setLayout(hbox)

        self.plotwidget = pg.PlotWidget()
        hbox.addWidget(self.plotwidget)

        self.increasebutton = QtGui.QPushButton("Increase Amplitude")
        self.decreasebutton = QtGui.QPushButton("Decrease Amplitude")

        hbox.addWidget(self.increasebutton)
        hbox.addWidget(self.decreasebutton)

        self.setGeometry(10, 10, 1000, 600)
        self.show()

    def qt_connections(self):
        self.increasebutton.clicked.connect(self.on_increasebutton_clicked)
        self.decreasebutton.clicked.connect(self.on_decreasebutton_clicked)

    def moveplot(self):
        self.t+=1
        self.updateplot()

    def updateplot(self):
        print "Update"
        data1 = self.amplitude*np.sin(np.linspace(0,30,121)+self.t)
        self.plotcurve.setData(data1)

    def on_increasebutton_clicked(self):
        print ("Amplitude increased")
        self.amplitude += 1
        self.updateplot()

    def on_decreasebutton_clicked(self):
        print ("Amplitude decreased")
        self.amplitude -= 1
        self.updateplot()

def main():
    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('Sinuswave')
    ex = sinus_wave()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: How to update a realtime plot and use buttons to interact in pyqtgraph?

description: Update a realtime plot and use buttons to interact in pyqtgraph


code:
source
import os, requests
import threading
import urllib2
import time

URL = "http://www.nasa.gov/images/content/607800main_kepler1200_1600-1200.jpg"

def buildRange(value, numsplits):
    lst = []
    for i in range(numsplits):
        if i == 0:
            lst.append('%s-%s' % (i, int(round(1 + i * value/(numsplits*1.0) + value/(numsplits*1.0)-1, 0))))
        else:
            lst.append('%s-%s' % (int(round(1 + i * value/(numsplits*1.0),0)), int(round(1 + i * value/(numsplits*1.0) + value/(numsplits*1.0)-1, 0))))
    return lst

def main(url=None, splitBy=3):
    start_time = time.time()
    if not url:
        print "Please Enter some url to begin download."
        return

    fileName = url.split('/')[-1]
    sizeInBytes = requests.head(url, headers={'Accept-Encoding': 'identity'}).headers.get('content-length', None)
    print "%s bytes to download." % sizeInBytes
    if not sizeInBytes:
        print "Size cannot be determined."
        return

    dataDict = {}

    # split total num bytes into ranges
    ranges = buildRange(int(sizeInBytes), splitBy)

    def downloadChunk(idx, irange):
        req = urllib2.Request(url)
        req.headers['Range'] = 'bytes={}'.format(irange)
        dataDict[idx] = urllib2.urlopen(req).read()

    # create one downloading thread per chunk
    downloaders = [
        threading.Thread(
            target=downloadChunk,
            args=(idx, irange),
        )
        for idx,irange in enumerate(ranges)
        ]

    # start threads, let run in parallel, wait for all to finish
    for th in downloaders:
        th.start()
    for th in downloaders:
        th.join()

    print 'done: got {} chunks, total {} bytes'.format(
        len(dataDict), sum( (
            len(chunk) for chunk in dataDict.values()
        ) )
    )

    print "--- %s seconds ---" % str(time.time() - start_time)

    if os.path.exists(fileName):
        os.remove(fileName)
    # reassemble file in correct order
    with open(fileName, 'w') as fh:
        for _idx,chunk in sorted(dataDict.iteritems()):
            fh.write(chunk)

    print "Finished Writing file %s" % fileName
    print 'file size {} bytes'.format(os.path.getsize(fileName))

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

rawDescription: tryng to split the file download buffer to into separate threads

description: Tryng to split the file download buffer to into separate threads


code:
# This is the main code which will access the commands from commands.py
import commands

def userSelection():
    userSelection = raw_input('New \nSaved \nRemove \nAlerts')
    userSel = userSelection.lower()
    if userSel == 'new':
        commands.getDesc()
    elif userSel == 'saved':
        commands.savedBills()
    elif userSel == 'remove':
        commands.removeBills()
    elif userSel == 'alerts':
        commands.setAlerts()
    else:
        print 'Please enter a valid command'
        userSelection()

print 'Hello, Welcome to your friendly text-based bill reminder.'
print '\nI will be tracking all of your bills so you will never miss a payment again.'
print '\nLet\'s get started, please type on of the following commands.'
userSelection()

rawDescription: Having trouble importing functions in python from my directory


code:
from mpl_toolkits.mplot3d.axes3d import Axes3D
from mpl_toolkits.mplot3d import proj3d

import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt

#Make sure these are floating point values:
scale_x = 1.0
scale_y = 2.0
scale_z = 3.0

#Axes are scaled down to fit in scene
max_scale=max(scale_x, scale_y, scale_z)

scale_x=scale_x/max_scale
scale_y=scale_y/max_scale
scale_z=scale_z/max_scale

#Create scaling matrix
scale = np.array([[scale_x,0,0,0],
                  [0,scale_y,0,0],
                  [0,0,scale_z,0],
                  [0,0,0,1]])
print scale

def get_proj_scale(self):
    """
    Create the projection matrix from the current viewing position.

    elev stores the elevation angle in the z plane
    azim stores the azimuth angle in the x,y plane

    dist is the distance of the eye viewing point from the object
    point.

    """
    relev, razim = np.pi * self.elev/180, np.pi * self.azim/180

    xmin, xmax = self.get_xlim3d()
    ymin, ymax = self.get_ylim3d()
    zmin, zmax = self.get_zlim3d()

    # transform to uniform world coordinates 0-1.0,0-1.0,0-1.0
    worldM = proj3d.world_transformation(
        xmin, xmax,
        ymin, ymax,
        zmin, zmax)

    # look into the middle of the new coordinates
    R = np.array([0.5, 0.5, 0.5])

    xp = R[0] + np.cos(razim) * np.cos(relev) * self.dist
    yp = R[1] + np.sin(razim) * np.cos(relev) * self.dist
    zp = R[2] + np.sin(relev) * self.dist
    E = np.array((xp, yp, zp))

    self.eye = E
    self.vvec = R - E
    self.vvec = self.vvec / proj3d.mod(self.vvec)

    if abs(relev) > np.pi/2:
    # upside down
      V = np.array((0, 0, -1))
    else:
      V = np.array((0, 0, 1))
    zfront, zback = -self.dist, self.dist

    viewM = proj3d.view_transformation(E, R, V)
    perspM = proj3d.persp_transformation(zfront, zback)
    M0 = np.dot(viewM, worldM)
    M = np.dot(perspM, M0)

    return np.dot(M, scale);

Axes3D.get_proj=get_proj_scale

"""
You need to include all the code above.
From here on you should be able to plot as usual.
"""

mpl.rcParams['legend.fontsize'] = 10

fig = plt.figure(figsize=(5,5))
ax = fig.gca(projection='3d')
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()

plt.show()

rawDescription: matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3D Plot?

description: Matplotlib (mplot3d) - how to increase the size of an axis (stretch) in a 3D Plot


rawDescription: python -> combinations of numbers and letters

description: Python -> combinations of numbers and letters


code:
import threading
import time

class myThread (threading.Thread):

    def __init__(self, threadID):
        self.threadID = threadID
        self.count = 0
        threading.Thread.__init__(self)

    def run(self):
        for i in range(10):
            print "count is now: ", self.count, " for thread ", self.threadID, "\n"
            time.sleep(5)

def main():
    # spawn one or more threads
    thread1 = myThread(1)
    thread1.start()

    for i in range(20):
        time.sleep(2)
        thread1.count = thread1.count + 1

    # wait for thread1 to finish
    thread1.join()
    print thread1.count

main()

rawDescription: how to avoid global in python threads when sharing resources?

description: Avoid global in python threads when sharing resources


rawDescription: How to print formatted python output for javascript?

description: Print formatted python output for javascript


code:
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

driver = webdriver.Chrome()  # or webdriver.Firefox()
driver.get("https://www.fiverr.com/search/gigs?utf8=%E2%9C%93&search_in=everywhere&source=top-bar&query=explainer%20video&page=1&layout=lists&filter=new")

wait = WebDriverWait(driver, 10)
while True:
    try:
        load_more = wait.until(EC.visibility_of_element_located((By.LINK_TEXT, 'LOAD MORE')))
    except TimeoutException:
        break

    load_more.click()

for item in driver.find_elements_by_css_selector("div.gig-item h3 a.gig-link-main"):
    print item.text.strip()

rawDescription: Selenium can't seem to find and click a button on website? - Python


code:
import ctypes
import random
import time
import math

def move_mouse(pos):
    x_pos, y_pos = pos
    screen_size = ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1)
    x = 65536L * x_pos / screen_size[0] + 1
    y = 65536L * y_pos / screen_size[1] + 1
    return ctypes.windll.user32.mouse_event(32769, x, y, 0, 0)

def random_movement(top_left_corner, bottom_right_corner, min_speed=100, max_speed=200):
    '''speed is in pixels per second'''

    x_bound = top_left_corner[0], bottom_right_corner[0]
    y_bound = top_left_corner[1], bottom_right_corner[1]

    pos = (random.randrange(*x_bound),
                    random.randrange(*y_bound))

    speed = min_speed + random.random()*(max_speed-min_speed)
    direction = 2*math.pi*random.random()

    def get_new_val(min_val, max_val, val, delta=0.01):
        new_val = val + random.randrange(-1,2)*(max_val-min_val)*delta
        if new_val<min_val or new_val>max_val:
            return get_new_val(min_val, max_val, val, delta)
        return new_val

    steps_per_second = 35.0
    while True:
        move_mouse(pos)
        time.sleep(1.0/steps_per_second)

        speed = get_new_val(min_speed, max_speed, speed)
        direction+=random.randrange(-1,2)*math.pi/5.0*random.random()

        new_pos = (int(round(pos[0]+speed*math.cos(direction)/steps_per_second)),
               int(round(pos[1]+speed*math.sin(direction)/steps_per_second)))

        while new_pos[0] not in xrange(*x_bound) or new_pos[1] not in xrange(*y_bound):
            direction  = 2*math.pi*random.random()
            new_pos = (int(round(pos[0]+speed*math.cos(direction)/steps_per_second)),
               int(round(pos[1]+speed*math.sin(direction)/steps_per_second)))
        pos=new_pos

rawDescription: python random mouse movements

description: Python random mouse movements


code:
print hash(1)             # 1
print hash(20)            # 20
print hash(1000)          # 1000

rawDescription: Iterating over dictionary returns keys in sorted order


code: print [(each, i) for i, each in enumerate(calendar.month_name[1:],start = 1)]

rawDescription: list comprehension for multiple variables generate month name and number

description: List comprehension for multiple variables generate month name and number


code:
doc = 'a b c d e f'
words = doc.split(None)
max = 3

for index in xrange(len(words)):
    for n in xrange(max):
        if index + n < len(words):
            print ' '.join(words[index:index+n+1])

rawDescription: How do I generate multi-word terms recursively?

description: Generate multi-word terms recursively


code:
import time

def query_listing_info(hosts):
    for host in hosts:
        info = get_listing_info(host)
        if not info:
            print "Still looking"
        else:
            for listing_id, sub_total, fee_amount in parse_listing_info(info):
                total_price = sub_total + fee_amount
                print("listingId {listing_id} = [ {sub_total} + {fee_amount} = "
                      " {total_price} ]".format(**vars()))

hosts = ['x.x.x.x', 'y.y.y.y']
while 1:
    query_listing_info(hosts)
    time.sleep(25) # pause requests

rawDescription: python- How to properly send http GET requests to different Host-IPs but same host

description: Python- How to properly send http GET requests to different Host-IPs but same host


code:
markup = '''

        <title>Övriga fakta</title>
        <meta charset="latin-1" />

Öhman Företagsobligationsfond

Detta är en svensk sida.

'''

soup = BeautifulSoup(markup)
print soup.find('h1')

try:
    # Version 4
    soup = BeautifulSoup(markup, from_encoding='utf-8')
except TypeError:
    # Version 3
    soup = BeautifulSoup(markup, fromEncoding='utf-8')

print soup.find('h1')

rawDescription: Beautiful Soup, Python and the swedish characters ÅÄÖ


code:
used_iter = iter(range(5))
used_iter.next()
for i, val in annotate(used_iter):
    print i, val

rawDescription: Pythonic way of determining if the current element is the first or last element of a generator?


code:
import fileinput

def clause(line):
    return len(line) < 5

for line in fileinput.input('file.txt', inplace=1):
    if clause(line):
        print '+ ' + line[:-1]
fileinput.close()

rawDescription: Python Replace String in File in With clause


code:
for w in text.split():
    ti = w.split('/')
    tok =ti[0]
    tag =ti[1]
    dic[tok] = tag
print dic

rawDescription: Create a dictionary for the token, tags of a text


code:
if x == 0:
    print "X is 0\n"
elif x == 1:
    print "X is 1\n"
elif x == 2:
    print "X is 2r\n"
elif x == 3:
    print "X is 3\n"

rawDescription: How to use switch in Python?

description: Use switch in Python


code:
with open(file, "rb") as f:
    byte = f.read(20)

for i,b in enumerate(byte):
    print "%02d:  %02x"  % (i,b)

rawDescription: Extract first 20 bytes in a binary header


code:
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
zero25 = "0" * 25
for idx in range (len (alpha)):
    print "%s = (%s1%s)" % (alpha[idx], zero25[:idx], zero25[:25-idx])

rawDescription: Whats the easiest way to pad an alphabet index both sides with zeroes?


rawDescription: How to Enter an unknown number of variables into a function?


code:
info_dict = {}
info_dict["info"] = info
info_dict["list1"] = list1
# ... and do that with the rest of it.
while True:
    lastcommand = input("C-Gen@H//Vilius #OpDesc: ")
    try:
        print info_dict[lastcommand]
    except KeyError:
        print ("Error: incorrect command (" + lastcommand + ")")

rawDescription: Python looping [Module]

description: Python looping [Module]


code:
def fight_match():
    print "Okay you're in the ring, ready to go three rounds with this dude"
    print "He throws a left hook, which way will you dodge?"

    dodge = raw_input()
    fight1 = Sparring()

    while fight1.best != 2:
        if 'right' in dodge:
            print "Nice job, you knocked him out!"
            fight1.my_score()
        else:
            print 'Oh no he knocked you out'
            fight1.his_score()

rawDescription: Using a class to keep score in python

description: Using a class to keep score in python


code:
# Tested on Python 2.6.7, Ubuntu 14.04.4
import xml.etree.cElementTree as et
import sqlite3

# Tools to deal with namespaces
ixid_uri = 'http://www.website.com/ixid/xmlfile/v8'
def extract_local_tag(qname):
    return qname.split('}')[-1]

# A db connection to illustrate the example
conn = sqlite3.connect(":memory:")
c = conn.cursor()
c.execute("create table foo (joury_uid text, tag text, tpl text)")
conn.commit()

# The main part of the code: iterate over the XML,
# storing DB stuff at the end of every <Journey>
with open('i.xml') as xml_file:
    for event, elem in et.iterparse(xml_file):
        # Must compare tag to qualified name
        if elem.tag == et.QName(ixid_uri, 'Journey'):
            c.executemany('insert into foo values(?, ?, ?)',
                [
                    (elem.attrib['uid'],
                    extract_local_tag(child.tag),
                    child.attrib.get('tpl', None))
                    for child in elem
                ])
            conn.commit()
            # Note: only clears <Journey> elements and their children.
            # There is a memory leak of any elements not children of <Journey>
            elem.clear()
for row in c.execute('select * from foo'):
    print row

rawDescription: iterparse large XML using python

description: Iterparse large XML using python


code: print " ".join([ correct(words[i]) for i in range(len(words)) ])

rawDescription: Python Converting output into sentence

description: Python Converting output into sentence


code:
import re
print re.findall(r'<\s*textarea.*?>(.*?)<', s)

rawDescription: Get content of textarea

description: Get content of textarea


code:
for x in range(1,10):
    print '-> %d' % x

rawDescription: How can you use Python in Vim?

description: Use Python in Vim


rawDescription: How to Speed up with Bulk Insert to MS Server from Python with Pyodbc from CSV


rawDescription: List of 3x1 numpy arrays in Python

description: List of 3x1 numpy arrays in Python


code:
url = 'http://www.example.com/wps/portal/!ut/p/c1/lYuxDJBMjBCNQ!!/?CompanyName=A1&tabOrder=7&chart_type=chart_oneDay&announcmentNumber=&isAnnual=/'
url = url.replace('Name=A1', 'Name=')
compaines = ['a1','a2','a3']
for ele in compaines:
    start = url.find("CompanyName=") + 12
    newUrl1 = url[:start] + ele
    newUrl2 = newUrl1 + url[start:]
    print newUrl2

rawDescription: Parsing a url in Python

description: Parsing a url in Python


code:
user_to_count_map = {}
for username in list_of_usernames:
    x = user_to_count_map.setdefault(username, [0])
    x[0] += 1
for username, counter in sorted(user_to_count_map.items()):
    print username, counter[0]

rawDescription: Using setdefault, but not wanting to reassign back to map/dict


code:
import pandas as pd

s = pd.Series([1, 2, 3, 4], index=iter('ABCD'))

for ind, val in s.iteritems():
    print ind, val

rawDescription: Pandas Series - print columns and rows

description: Pandas Series - print columns and rows


code:
for result in response['result']:
    for attrname, value in result.items():
        if not value:  # empty list or None
            print attrname

rawDescription: Parsing a json (a response from freebase) in python


code: print ', '.join(words)

rawDescription: Removing Set Identifier when Printing sets in Python


code:
x = Int('x')
print "x types"
print is_int(x) # true, is of sort int
print is_int_value(x) # false, not a "value"

x_ = IntVal(7)
print "x_ types"
print is_int(x_) # true, is also of sort int
print is_int_value(x_) # true, is a value

rawDescription: how to check if a const in z3 is a variable or a value?

description: Check if a const in z3 is a variable or a value


code:
def func_with_three_params(a, b, c):
    print a, b, c

three_args = "1 2 3".split()
func_with_three_params(*three_args)

rawDescription: Create a sort of command line for a python server


code:
df = df.loc['WOC(kg/ha)', ['ATM', 'TOT']]
print df
#            ATM  TOT
#
#WOC(kg/ha)  382   55
#WOC(kg/ha)  382   53

rawDescription: Reading in repeated blocks of data using pandas and python


code: print item.rstrip() + str(i)

rawDescription: String concatenation acting crazy

description: String concatenation acting crazy


code:
class MyIter(object):
    def __init__(self, data):
        self.data = data
        self.idx = -1

    def __iter__(self):
        return self

    def next(self):
        if self.idx >= len(self.data) - 1:
            raise StopIteration

        self.idx += 1
        return {self.data[self.idx][0]: self.data[self.idx][1]}

mydata = zip(range(0,10), range(100,110))

for it in MyIter(mydata):
    print it

rawDescription: Iterator for custom 'dictionary with order' data structure


code:
import csv

search_text = raw_input('Enter search text:').strip()

file2 =  '/home/vivek/Desktop/stackoverflow/file3.txt'

with open(file2) as fp1:
    root = csv.reader(fp1)
    if search_text=="*":
        result =  list(root)
    else:
        result = [i for i in root  if search_text==i[0]]
        #result = []
        #for i in root:
        #   if search_text == i[0]:
        #       result.append(i)

print result

rawDescription: Python wild card match

description: Python wild card match


code:
c = Config(3)
print c.y

rawDescription: Python dynamic import and changing a variable


code:
def wrapper():
    class A(object):
        print 'hello'
        1+1
        pass

dis.dis(wrapper)
dis.dis(wrapper.__code__.co_consts[2])

rawDescription: Why does a class definition always produce the same bytecode?


code:
import pandas as pd
df = pd.DataFrame({'Product': ['AAA', 'ABB', 'ACC'],
                   'Score': ['1/4', '1/2', '1/1']})
s = df['Score'].str.split('/', expand=True).astype(int)
df['Score'] = s[0].div(s[1])
print df

rawDescription: Convert quotient to numerical value

description: Convert quotient to numerical value


code:
class Foo(object):
    __metaclass__ = ImmutableMeta
    _attributes_ = 'a b'

    def sayhi(self):
        print "Hello from {0}".format(type(self).__name__)

class Bar(Foo):
    _attributes_ = 'c'

    def saybye(self):
        print "Goodbye from {0}".format(type(self).__name__)

rawDescription: Immutable types allowing subclassing in Python


code:
import re

def f(s, pat):
    pat = r'(\w*%s\w*)' % pat       # Not thrilled about this line
    return re.findall(pat, s)

print f("This is just a simple text to test some basic things", "si")

rawDescription: Python regexes: return a list of words containing a given substring


code:
from itertools import imap
file2 = dict(imap(str.split, open("file2")))
with open("file1") as fin:
    for key, value in imap(str.split, fin):
        if value in file2:
            print key

rawDescription: Two lists, if a common match is found print another list element


code:
import tensorflow as tf
from game_env import game

experience = tf.RandomShuffleQueue(10000,
                                   1000, tf.float32,
                                   shapes=[32,32],
                                   name='experience_replay')

screen_placeholder = tf.placeholder(tf.float32, [32, 32])
# You can create a single enqueue op and dequeued tensor, and reuse these from
# multiple threads.
enqueue_op = experience.enqueue(screen_placeholder)
dequeued_t = experience.dequeue()
# ...

init_op = tf.initialize_all_variables()

game_obj = game()

sess = tf.Session()
coord = tf.train.Coordinator()

# Define a custom thread for running the enqueue op that grabs a new
# screen in a loop and feeds it to the placeholder.
def enqueue_thread():
    with coord.stop_on_exception():
        while not coord.should_stop():
            screen_val = game_obj.grab_screen()
            # Run the same op, but feed a different value for the screen.
            sess.run(enqueue_op, feed_dict={screen_placeholder: screen_val})

available_threads = 4
for _ in range(available_threads):
    threading.Thread(target=enqueue_thread).start()

while True:
    # N.B. It's more efficient to reuse the same dequeue op in a loop.
    print sess.run(dequeued_t)
    time.sleep(0.5)

rawDescription: How to add dynamically created input images to a RandomShuffleQueue using a QueueRunner in tensor flow

description: Add dynamically created input images to a RandomShuffleQueue using a QueueRunner in tensor flow


code: print [s for s in list if sub in s]

rawDescription: python: finding substring within a list

description: Python: finding substring within a list


code:
data['w:x:y:z'] = {'a':5, 'b':10}

for path, d in data.items():
    print '%s:%s' % (path, ':'.join("%s=%r" % pair for pair in d.items()))

rawDescription: How to os.walk deep defaultdict for values?

description: Os.walk deep defaultdict for values


code:
from os import chdir, name as osname
from os.path import dirname, abspath

def voom():
    if osname == 'posix':
        chdir(dirname(abspath(__file__)))
    return "Testing! This is your nine o'clock alarm call!"

if __name__ == '__main__':
    print voom()
    exit(0)

rawDescription: Execute a python separate application in a java application


code:
newdata = {}

for data in result['data']:
    try:
        newdata[data['project']].append({"description":data['description'],"start":data['start'],"time":data['dur']})
    except:
        newdata[data['project']] = []
        newdata[data['project']].append({"description":data['description'],"start":data['start'],"time":data['dur']})

print newdata

rawDescription: Add an item with common key to a dictionary in python


code:
import inspect

def methodsWithDecorator(cls, decoratorName):
    sourcelines = inspect.getsourcelines(cls)[0]
    for i,line in enumerate(sourcelines):
        line = line.strip()
        if line.split('(')[0].strip() == '@'+decoratorName: # leaving a bit out
            nextLine = sourcelines[i+1]
            name = nextLine.split('def')[1].split('(')[0].strip()
            yield(name)

class A(object):
    @property
    def name():
        return "Masnun"

print list(methodsWithDecorator(A, 'property'))

rawDescription: Lookup @property methods with inspect module


code:
import datetime
cursor = [{u'date': datetime.datetime(2014, 9, 2, 12, 27, 51, 184000),
           u'domains': [u'domain1', u'domain2']},
          {u'date': datetime.datetime(2014, 9, 3, 11, 23, 51, 184000),
           u'domains': [u'domain3', u'domain4', u'domain5']}]
for node in cursor:
    print node['date'].strftime("%d-%m-%Y")
    for domain in node['domains']:
        print domain
    print "total: {0} domains\n".format(len(node['domains']))

rawDescription: PyMongo: Print length and items of arrays inside MongoDB Documents


rawDescription: Concatenate Pandas columns under new multi-index level


code:
import re
import collections

def cleandup(fh):
    for line in fh:
        for word in re.findall('[a-z]+', line.lower()):
            yield word

with open ('DQ.txt') as doc:
    wordlist = collections.Counter(cleanedup(doc))
    print wordlist.most_commond(5)

rawDescription: Python program: foreign language word-frequency dictionary


code:
import datetime
import calendar

def main():
    year = datetime.date.today().year
    userin = int(raw_input("Enter a month as number: "))  # Python 3: `int(input(...))`
    print '{}, {}'.format(calendar.month_abbr[userin], calendar.monthrange(year, userin)[1])

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


code:
animals_questions = 'Animals Questions'
capitals_questions = 'Capitals Questions'
math_questions = 'Math Questions'

questions = [animals_questions, capitals_questions, math_questions]

quiz = {animals_questions: [("All lionesses in a pride", True),
                        ("Another animals question", False),
                        ("Last animals question", False)],

        capitals_questions: [("Cairo is the capital city of Egypt", True),
                         ("Another capitals question", True),
                         ("Last capitals question", False)],

        math_questions: [("20 is log 100 for base 1o", False),
                     ("Another math question", True),
                     ("Last math question", False)]
}

result = {"Correct": 0, "Incorrect": 0}

def get_quiz_choice():
    while True:
        try:
            quiz_number = int(raw_input(
                'Choose the quiz you like\n1 for {}\n2 for {}\n3 for {}\nYour choice:'.format(animals_questions,
                                                                                capitals_questions,
                                                                                math_questions)))
        except ValueError:
            print "Not a number, please try again\n"
        else:
            if 0 >= quiz_number or quiz_number > len(quiz):
                print "Invalid value, please try again\n"
            else:
                return quiz_number

def get_answer(question, correct_answer):
    while True:
        try:
            print "Q: {}".format(question)
            answer = int(raw_input("1 for True\n0 for False\nYour answer: "))
        except ValueError:
            print "Not a number, please try again\n"
        else:
            if answer is not 0 and answer is not 1:
                print "Invalid value, please try again\n"
            elif bool(answer) is correct_answer:
                result["Correct"] += 1
                return True
            else:
                result["Incorrect"] += 1
                return False

choice = get_quiz_choice()
quiz_name = questions[choice - 1]
print "\nYou chose the {}\n".format(quiz_name)
quiz_questions = quiz[quiz_name]
for q in (quiz_questions):
    print "Your answer is: {}\n".format(str(get_answer(q[0], q[1])))

rawDescription: How to create a simple quiz in python with multiple topics?

description: Create a simple quiz in python with multiple topics


code:
class UserRegistration(object):
    username_and_password = {}
    def __init__(self):
        self.username = ""
    def register_name(self):
        while True:
            self.username = raw_input("Choose Username> ")
            if self.username in self.username_and_password:
                print "Username taken, please try again"
                continue
            else:
                return self.register_pass()

    def register_pass(self):
        while True:
            password = getpass.getpass("Choose Password> ")
            confirm_password = getpass.getpass("Confirm Password> ")
            if password == confirm_password:
                self.username_and_password[self.username] = password
                return
            else:
                print "Passwords didn't match"
                continue

rawDescription: if True: update, if False: restart

description: If True: update, if False: restart


code:
while True:
   command=raw_input("j;/")
   command1="help"
   command2="jver"

   if command==command1:
      print "List of commands"
      print""
      print""
      print"help = shows all commands"
      print ""
      print "jver = Version of MS-Josh"
   elif command==command2:
        print "MS-Josh version 3.12."
        print ""
        print "memory used: 7,117 bytes"
        print "memory on computer: 1,434,078 bytes"
        print "memory free: 1,426,961"
   else:
      print "incorrect command"

rawDescription: How do I go back to a variable in python?

description: Go back to a variable in python


code:
from collections import Counter
import itertools
a= [[1,2,3],[4,2],[5,1,6]]

print Counter(itertools.chain(*a))

#output Counter({1: 2, 2: 2, 3: 1, 4: 1, 5: 1, 6: 1})

b=Counter(itertools.chain(*a))
for key,val in b.iteritems():
    print key,':',val

rawDescription: unique count in (list of smaller lists)

description: Unique count in (list of smaller lists)


code:
lis = ['Text', 'in', 'the', 'middle!', 'END']
width = 13
for s1 in lis:
    L = len(s1)                                    #length of line
    periods_rtside = (width - L)//2                #periods on the RHS
    periods_leftside = width - periods_rtside - L  #peroids on the LHS
    periods_rt_str = '.' * periods_rtside
    periods_left_str = '.' * periods_leftside
    line1 = periods_left_str + s1 + periods_rt_str
    print line1

rawDescription: Python Logic - Centering text using periods


code:
if args.toolname == 'counter':
    print 'Running counter'
else:
    print 'Running fasta2bed'

rawDescription: How to skip a positional argument in Python Argparse

description: Skip a positional argument in Python Argparse


code:
for path, dirs, files in os.walk(root_dir, topdown=False):
    if 'bin' in path:
        print path

rawDescription: Picking a particular directory path using os path in Python


code: print employee_dict[1]['name']

rawDescription: a loop to read lines that start with specific letters

description: A loop to read lines that start with specific letters


code:
noOfBits = 5
for n in range(2**noOfBits):
    binVal = bin(n)[2:].zfill(noOfBits)
    b = [ x for x in binVal]
    print b

rawDescription: List of combinations

description: List of combinations


code:
import re

for email in emails:
    print email
    lines = email.split('\n')
    name = re.search(r'name\s*', lines[0], re.I)
    price = re.search(r'off(er(ing)?)?\s*', lines[0], re.I)
    for line in lines[1:]:
        n = line[name.start():name.end()].strip()
        p = line[price.start():price.end()].strip()
        print (n, p)
    print

rawDescription: Python - Extracting text by Column Header from Given Row


code:
from scrapy.spider import Spider
from scrapy.selector import Selector
from scrapy.cmdline import execute

class MySpider(Spider):

    name = "goal"
    allowed_domains = ["whoscored.com"]
    start_urls = ["http://www.whoscored.com/Players/3859/Fixtures/Wayne-Rooney"]

    def parse(self, response):
        sel = Selector(response)

        #titles = sel.xpath("normalize-space(//title)")
        #print 'titles:', titles.extract()[0]
        print
        print 'titles:', "".join( sel.css("title::text").extract() ).strip()
        print

        #rows = sel.xpath('//table[@id="player-fixture"]//tbody//tr')
        rows = sel.css('table#player-fixture tbody tr')

        for row in rows:
            #print 'date:', row.xpath('.//td[@class="date"]/text()').extract()
            #print 'result:', row.xpath('.//td[@class="result"]/a/text()').extract()
            print 'date:', "".join( row.css('.date::text').extract() ).strip()
            print 'result:', "".join( row.css('.result a::text').extract() ).strip()
            print 'team_home:', "".join( row.css('.team.home a::text').extract() ).strip()
            print 'team_away:', "".join( row.css('.team.away a::text').extract() ).strip()
            print 'info:', "".join( row.css('.info::text').extract() ).strip(), "".join( row.css('.info::attr(title)').extract() ).strip()
            print 'rating:', "".join( row.css('.rating::text').extract() ).strip()
            print 'incidents:', ", ".join( row.css('.incidents-icon::attr(title)').extract() ).strip()
            print '-'*40

#execute(['scrapy','crawl','goal'])
execute(['scrapy','runspider','main.py'])

rawDescription: Xpath() method not returning results using Scrapy


code:
if len(sentences) == 1:
    print sentences[0] + 'STRING'
elif len(sentences) > 1:
    isentences = ('%s%s%d' % (s, 'STRING', i) for i, s in enumerate(sentences, 1))
    print ' '.join(isentences)

rawDescription: Basic numbering of sentence splits?

description: Basic numbering of sentence splits


code:
l=[0,0,0,0,0,0,0,0,0,0,0,0]
n = 11

for i in range (0,n):
        l[i] = 1

print l
carryidx = 0
for i in reversed(range(0,n - 1)):
        v = l[ n - 1] + l[i]
        if v > 9:
                while l[carryidx] > 9:
                        carryidx += 1
                l[carryidx] += 1
        else:
                l[n - 1] = v
        l[i] = l[i] - 1
        print l

rawDescription: All possible set of digits that sum==n in python list


code:
precedence_dict = {'A':0, 'a':1, 'G':2,'g':3}

for i in xrange(len(genetics)):
    genetics[i] = list(genetics[i])
    genetics[i].sort(key=lambda x: precedence_dict[x])
    genetics[i] = ''.join(genetics[i])
from sets import Set

genetics = list(Set(genetics))
genetics.sort()

print genetics

rawDescription: Rearrange strings in list alphabetically and by case


rawDescription: Walk through each column in a numpy matrix efficiently in Python


code:
from pyparsing import makeHTMLTags, oneOf, withAttribute, Word, nums, Group, htmlComment
import calendar

# have pyparsing define tag start/end expressions for the
# tags we want to look for inside the comments
span,spanEnd = makeHTMLTags("span")
i,iEnd = makeHTMLTags("i")

# only want spans with class=titlefont
span.addParseAction(withAttribute(**{'class':'titlefont'}))

# define what specifically we are looking for in this comment
weekdayname = oneOf(list(calendar.day_name))
integer = Word(nums)
dateExpr = Group(weekdayname("day") + integer("daynum"))
commentBody = '

don't want the next one, wrong span class

not even a span tag!

another matching comment, on a different day

"""

for comment in htmlComment.searchString(htmlsource):
    parsedDate = comment.date
    # date info can be accessed like elements in a list
    print parsedDate[0], parsedDate[1]
    # because we named the expressions within the dateExpr Group
    # we can also get at them by name (this is much more robust, and
    # easier to maintain/update later)
    print parsedDate.day
    print parsedDate.daynum
    print

rawDescription: How to find the comment tag <!--...--> with BeautifulSoup?

description: Find the comment tag <!--...--> with BeautifulSoup


code:
labels = ['id', 'Version', 'chip_name', 'xversion', 'device', 'opt_param',
    'place_effort']
values = [1, 1.0, u'virtex2', u'xilinx11.5', u'xc5vlx50', u'Speed', u'High']

paddedLabels = []
paddedValues = []
dividers = []
dblDividers = []

for label, value in zip(labels, values):
    value = str(value)
    columnWidth = max(len(label), len(value))
    paddedLabels.append(label.center(columnWidth))
    paddedValues.append(value.center(columnWidth))
    dividers.append('-' * columnWidth)
    dblDividers.append('=' * columnWidth)

print '+-' + '-+-'.join(dividers) + '-+'
print '| ' + ' | '.join(paddedLabels) + ' |'
print '+=' + '=+='.join(dblDividers) + '=+'
print '| ' + ' | '.join(paddedValues) + ' |'
print '+-' + '-+-'.join(dividers) + '-+'

rawDescription: pretty printer with Python?

description: Pretty printer with Python


code: print "{:3}".format(p),

rawDescription: How to print a list of integers in 10 columns?

description: Print a list of integers in 10 columns


code:
class A(Base):
    x = 2

a = A()
print a.get_x()

rawDescription: how does django set up object method before it was defined

description: How does django set up object method before it was defined


code:
unique_id = None

def foo(request):
    global unique_id
    unique_id = 10

def bar(request):
    print unique_id

rawDescription: How do I send a variable from one function to another function?

description: Send a variable from one function to another function


code:
# walk around a while
currentRoom = house  # or Room.lookup['house']
while 1:
    print "You are at the %s" % currentRoom.name
    print currentRoom.showExits()
    command = raw_input("which direction? ").lower()

    if command == 'q':
        break

    if command not in list("nsew"):
        print "that is not a valid direction"
        continue

    if command in currentRoom.exits:
        direction = command
        nextRoomName = currentRoom.exits[direction]
        nextRoom = Room.lookup[nextRoomName]

        # move by setting currentRoom to the nextRoom
        currentRoom = nextRoom

    else:
        print "you can't go that way"

rawDescription: Relationships between variables

description: Relationships between variables


code:
group_by_obj = df.groupby('A')
group_dict = group_by_obj.groups

print group_dict

rawDescription: Using print to access individual cells of pandas dataframe after groupby


code:
var = 10
somelist = []
var2 = 1

def show_var2():
    print var2

rawDescription: Global Variables between different modules


code:
for key in counts.keys():
    print key, counts.get(key)

rawDescription: Python :getting the count for the adjectives in a string


code:
allBlueCars = sum(1 for event in events if event.car.isBlue())
print "Number of blue cars: {}".format(allBlueCars)

maxCarLen = 4
for region in zip(range(maxCarLen ), range(1, maxCarLen +1)):
    minlen, maxlen = region
    print "Cars between {} and {} m that are blue:".format(minlen, maxlen)
    blueCarsInRegion = [str(event.car) for event in events if event.car.isBlue() and minlen <= event.car.length() < maxlen]
    if blueCarsInRegion:
        print '\n'.join(['\t{}'.format(car) for car in blueCarsInRegion])
    else:
        print 'no blue cars in this region'
    fraction = float(len(blueCarsInRegion)) / allBlueCars
    print "fraction of cars that are blue and between {} and {} m long: {}".format(minlen, maxlen, fraction)
    print

rawDescription: In Python, what would be a clear, efficient way to count things in regions?


code:
def all_numbers():
    return [(1,5), (2,6)]
lucky_number = 5
for i, x in enumerate(all_numbers()):
    print('{} {}'.format(i, x))
    if x == lucky_number:
        print 'Found it!'

rawDescription: find all ocurrences inside a list

description: Find all ocurrences inside a list


code:
import subprocess
import re
proc = subprocess.check_output("ipconfig" )
print "\n".join(re.findall(r"(?<=IPv4 Address. . . . . . . . . . . : )(\d+\.\d+\.\d+\.\d+)",proc))

rawDescription: How to list all the IP addresses defined on a Windows system with python?

description: List all the IP addresses defined on a Windows system with python


code:
import csv
import urllib2

downloaded_data  = urllib2.urlopen('http://...')
csv_data = csv.reader(downloaded_data)

for row in csv_data:
    print row

rawDescription: get csv data from a website

description: Get csv data from a website


code:
import itertools

for x, y, z in itertools.product(range(1,10), range(1,10), range(1,10)):
    product = x * y * z
    if product == 36:
        print "factors : {0},{1},{2}".format(x,y,z)

rawDescription: Simplify Python iterations

description: Simplify Python iterations


code:
from bs4 import BeautifulSoup

data = """

        123

               $1.23

        456

               $1.23

        789

               $1.23

"""

soup = BeautifulSoup(data)
for inventory in soup.select('div.inventory'):
    number = inventory.find('span', class_='item-number').text
    link = inventory.find('span', class_='cost').a.get('href')
    print number, link

rawDescription: How to print the text inside of a child tag and the href of a grandchild element with a single BeautifulSoup Object?

description: Print the text inside of a child tag and the href of a grandchild element with a single BeautifulSoup Object


code: lambda (_,v): [(x, y) for x in v for y in v if x < y]

rawDescription: python double list comprehension to scala equivalent

description: Python double list comprehension to scala equivalent


code:
with open('input') as f:
    words = f.read().upper().split()
symbols = [word for word in words if len(word) > 1 and word[0]=="$" and word[1:].isalpha()]
freqs = Counter(symbols)
freqs = {}
for sym in symbols:
    freqs[sym] = freqs.get(sym, 0) + 1
for key in sorted(freqs):
    print '%-8s : %3i' % (key, freqs[key])

rawDescription: Stock Symbol Frequency using Regex in Python


code:
from lxml import etree

xml_snippet = '''<topology>
 <switch id="10">
     <port no="1">h1</port>
     <port no="2">h2</port>
 </switch>

 <tunnel dpid="91">
 <port no="1">s1</port>
 <port no="8">s8</port>
 </tunnel>
 </topology>'''

root = etree.fromstring(xml_snippet)

for element in root.iter("*"):
  print element.tag, element.items()

rawDescription: How to parse an XML file using Python?

description: Parse an XML file using Python


code:
mystr = "Higher id: 38"
mynewstr = mystr.replace('38', '55')
print mynewstr

rawDescription: Replace string element with split method


code:
class Group:
    def __init__(self):
        self.members = []
        self.text = []

with open('text1.txt') as f:
    groups = collections.defaultdict(Group)
    group_pattern = re.compile(r'^(\S+)\((.*)\)$')
    current_group = None
    for line in f:
        line = line.strip()
        m = group_pattern.match(line)
        if m:    # this is a group definition line
            group_name, group_members = m.groups()
            groups[group_name].members += filter(lambda x: x not in groups[group_name].members , group_members.split(','))
            current_group = group_name
        else:
            if (current_group is not None) and (len(line) > 0):
                groups[current_group].text.append(line)

for group_name, group in groups.items():
    print "%s(%s)" % (group_name, ','.join(group.members))
    print '\n'.join(group.text)
    print

rawDescription: python preserving order in set after removing duplicate

description: Python preserving order in set after removing duplicate


code:
if 'b' in l1 and 'b' in l2: # Separated both statements to prevent ValueErrors
    if l1.index('b') == l2.index('b'):
        print 'b is in both lists and same position!'

rawDescription: How to compare if an item in a list has the same value AND position as an item in another list? Python 2.7

description: Compare if an item in a list has the same value AND position as an item in another list? Python 2.7


code:
def max_number(n):
    s = str(n)
    digits = sorted(s, reverse=n>0)
    return int(''.join(digits))

print max_number(231)
print max_number(-231)
print max_number(+231)

rawDescription: Find the biggest number formed by digits of input numer


code:
dat = np.array([[1,2,3], [4,5,nan], [nan,6,nan], [nan,nan,nan]])
mdat = np.ma.masked_array(dat,np.isnan(dat))
mm = np.mean(mdat,axis=1)
print mm.filled(np.nan) # the desired answer

rawDescription: NumPy: calculate averages with NaNs removed


code:
names = ['tom','mary','jessica','john']
fruits = ['oranges','apples','grapes','bananas']
hobbies = ['dancing','sitting','bicycling','watching tv']

for name in names:
    for fruit in fruits:
        for hobby in hobbies:
            print '%(name)s likes to eat %(fruit)s while %(hobby)s' % {'name':name, 'fruit':fruit, 'hobby':hobby}

rawDescription: Python string formating using values from multiple lists


code:
for line in docs:
    print pattern.findall(line)

rawDescription: Substring search for multiword strings - Python


code:
for i in []:
    print i
else:
    print "Nooooo"

rawDescription: Python - How to check if the text is in a file txt?


code:
data = '''* list item 1
* list item 2
** list item 3
** list item 4
*** list item 5
* list item 6'''.splitlines()

class Node(object):
  def __init__(self, payload):
    self.payload = payload
    self.children = []
  def show(self, indent):
    print ' '*indent, self.payload
    for c in self.children:
      c.show(indent+2)

def makenest(linelist):
  rootnode = Node(None)
  stack = [(rootnode, 0)]
  for line in linelist:
    for i, c in enumerate(line):
      if c != '*': break
    stars, payload = line[:i], line[i:].strip()
    curlev = len(stars)
    curnod = Node(payload)
    while True:
      parent, level = stack[-1]
      if curlev > level: break
      del stack[-1]
    # a child node of the current top-of-stack
    parent.children.append(curnod)
    stack.append((curnod, curlev))
  rootnode.show(0)

makenest(data)

rawDescription: How do I process a nested list?

description: Process a nested list


code:
import pandas as pd
import time
from datetime import datetime

def bulkcsv():
  inputfile = 'inp.csv'
  df = pd.read_csv(('csvfiles/' + inputfile), dtype=str, usecols=['IP Address'])
  #print df
  #for row in df:
  #print df['IP Address'].shape
  df['IP Address'].map(bulkfunc)

def bulkfunc(x):
  global f
  global ip
  ip = x
  f = open('results/%s' % ip + "_" + datetime.now().strftime("%Y-%m-%d@%H%M%S") + '.txt', 'a')
  print "Static Information: "
  f.write("Static Information: ")
  print "-" * 30
  f.write("-" * 30)
  parsenetworkcsv(ip)
  ping(ip)
  nmaprun(ip, "-sV")
  print "The output is complete."
  f.write("-" * 30)
  f.write("created by OP")
  f.close()
  time.sleep(1)

bulkcsv()

rawDescription: Pandas is looping twice when applying a function on a csv row python


code:
import re

lines='''\
Worker name is %s and id is %d
That is %i%%
%c
Decimal: %d  Justified: %.6d
%10c%5hc%5C%5lc
The temp is %.*f
%ss%lii
%*.*s | %.3d | %lC | %s%%%02d'''

cfmt='''\
(                                  # start of capture group 1
%                                  # literal "%"
(?:                                # first option
(?:[-+0 #]{0,5})                   # optional flags
(?:\d+|\*)?                        # width
(?:\.(?:\d+|\*))?                  # precision
(?:h|l|ll|w|I|I32|I64)?            # size
[cCdiouxXeEfgGaAnpsSZ]             # type
) |                                # OR
%%)                                # literal "%%"
'''

for line in lines.splitlines():
    print '"{}"\n\t{}\n'.format(line,
           tuple((m.start(1), m.group(1)) for m in re.finditer(cfmt, line, flags=re.X)))

rawDescription: How can I parse a C format string in Python?

description: Parse a C format string in Python


code:
import os
#hard code the path to the external file
external_file = 'names.txt'

#if file doesn' exists, create a new file
if not os.path.exists(external_file):
    #Ask the user's name
    name = raw_input("What's your name?")
    with open(external_file, "a") as f: #using "a" will append to the file
        f.write(name)# Write the name to names.txt
        f.write("\n")
        f.close()
else:
    #if file exists, use it to load name, else ask user
    with open(external_file, "r") as f:#r+ opens a file for reading & writing
        lines = f.read().split('\n') # split the names
        f.close()
        print "Hi {}".format(lines[0])
        response = raw_input("Is this your name?")
        if 'no' in response.lower():
            name = raw_input("What's your name?") # Asks for new name
            with open(external_file, "w") as f:
                f.write(name)# Write the name to names.txt
                f.write("\n")
                f.close()

rawDescription: Taking info from a File

description: Taking info from a File


code:
for i1 in cursor1.fetchall():
    print 'hello'
for i in cursor.fetchall():
    print 'hello'

if i in i1:
    print i
else:
    print i1

rawDescription: python retrieve all data from mysql table after if statement

description: Python retrieve all data from mysql table after if statement


code: if 'line': print 'true'

rawDescription: Using If-elif-else statements with Python


code:
from bs4 import BeautifulSoup

html = '''

some unnecessary text here

Here's the desired text!

'''

link = BeautifulSoup(html, 'html')
print link.find('div', class_="text").text.strip()

rawDescription: How to properly get an element with BeautifulSoup?

description: Properly get an element with BeautifulSoup


code:
import Tkinter
import os

class simpleapp_tk(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()
        self.Result =[]
        #self.minsize(8000,300)
        self.geometry("800x300")

    def initialize(self):
        self.grid()

        self.entryVariable = Tkinter.StringVar()
        self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
        self.entry.grid(column=0,row=0,sticky='EW')
        self.entry.bind("<Return>", self.OnPressEnter)
        self.entryVariable.set(u"")

        self.labelVars = []
        for j in range (1,30):
            labelVar = Tkinter.StringVar()
            labelVar.set('')
            self.labelVars.append(labelVar)
            label = Tkinter.Label(self,textvariable=labelVar,
                              anchor="w",fg="black",bg="white")

            label.bind("<1>", lambda event, text="some text": \
                          self.click_link(event, text))

            label.grid(column=0,row=j,columnspan=2,sticky='EW')

        self.grid_columnconfigure(0,weight=1)
        self.resizable(True,False)
        self.update()
        self.geometry(self.geometry())
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)

    def OnPressEnter(self,event):
        #Result is a list
        self.Result = self.entryVariable.get()
        self.Result = list(reversed(self.Result))
        for i in range (0,len( self.Result)):
            print "result",i,":", self.Result[i]
            self.labelVars[i].set(self.Result[i])
        self.entry.focus_set()
        self.entry.selection_range(0, Tkinter.END)

    def click_link(self, event, text):
        print "you clicked '%s'" % event.widget["text"]

if __name__ == "__main__":
     app = simpleapp_tk(None)
     app.title('my application')
     app.mainloop()

rawDescription: return label text when clicked

description: Return label text when clicked


code:
foo = 8
print foo - 7

rawDescription: Setting a lambda function as a property

description: Setting a lambda function as a property


code:
from bs4 import BeautifulSoup
from selenium import webdriver

driver = webdriver.PhantomJS()
driver.get('http://www.animenewsnetwork.com/encyclopedia/anime.php?id=160')
elem = driver.find_element_by_xpath("//*")
source_codeANN = elem.get_attribute("outerHTML")
soup2 = BeautifulSoup(source_codeANN, 'html.parser')
genre_div = soup2.find('div', id='infotype-30')
genres = [ a.text for a in genre_div.find_all('a') ]
print genres
# [u'adventure', u'comedy', u'science fiction']

rawDescription: How can I extract only certain text from similar elements using BeautifulSoup and Python

description: Extract only certain text from similar elements using BeautifulSoup and Python


code:
import re

line = '-------------------------------------------------------------\n'

ss = ('I gave two similar things to my two twin sons: '
      'two spankings, two nice BICYCLES of 300 dollars each, '
      'yes 600 dollars for two horridly nice BICYCLES, '
      'two times 300 dollars for two sons receiving two BICYCLES !, '
      'two dollars too, but never two dogs')
print ss,'\n\n'

print line + '1) Replacing the more at right before the first "BICYCLES":\n'
reg = re.compile('two(?=(?:.(?!two))*?BICYCLES)(.+)')
print reg.sub('@@@@\\1',ss)

print line + '2) Replacing the more at right before the last "BICYCLES":\n'
reg = re.compile('two(?=(?:.(?!two))*?BICYCLES(?!.*?BICYCLES))')
print reg.sub('@@@@',ss)

print line + '3) Replacing all before the first "BICYCLES":\n'
reg = re.compile('(two)|BICYCLES.+')
print reg.sub(lambda mat: '@@@@' if mat.group(1) else mat.group(),ss)

print line + '4) Replacing all before the last "BICYCLES":\n'
reg = re.compile('(two)|BICYCLES(?!.*?BICYCLES).+')
print reg.sub(lambda mat: '@@@@' if mat.group(1) else mat.group(),ss)

rawDescription: Python regular expressions - find a string in a file that occurs somewhere before another string?


rawDescription: assign values executed to array in python

description: Assign values executed to array in python


code:
import datetime
import dateutil.rrule as drrule
import dateutil.relativedelta as drel
import pprint

def dt2d(date):
    '''
    Convert a datetime.datetime to datetime.date object
    '''
    return datetime.date(date.year,date.month,date.day)

def enumerate_dates(start,end):
    days=map(dt2d,drrule.rrule(drrule.DAILY, dtstart=start, until=end))

    # Find the Monday on or before start
    start_week=start+drel.relativedelta(weekday=drel.MO(-1))
    end_week=end+drel.relativedelta(weekday=drel.MO(-1))
    weeks=map(dt2d,drrule.rrule(drrule.WEEKLY, dtstart=start_week, until=end_week))

    # Find the first day of the month
    start_month=start.replace(day=1)
    end_month=end.replace(day=1)
    months=map(dt2d,drrule.rrule(drrule.MONTHLY, dtstart=start_month, until=end_month))
    return days,weeks,months

if __name__=='__main__':
    days,weeks,months=enumerate_dates(datetime.date(2010,11,28),
                                      datetime.date(2010,12,01))
    print('''\
days: {d}
weeks: {w}
months: {m}'''.format(d=map(str,days),w=map(str,weeks),m=map(str,months)))

rawDescription: Is there a consistent way to enumerate days/weeks/months between two dates?


code:
def write_html_file(path, data, heads):
    html = []
    tab_attr = ' border="1" cellpadding="3" style="background-color:#FAFCFF; text-align:right"'
    head_attr = ' style="background-color:#C0CFE2"'

    # opening lines needed for html table
    try:
        html.append('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ')
        html.append('"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> ')
        html.append('')
        html.append('')
        html.append('
')
    except:
        print 'Error setting up html heading data'

    # html table headings (if required)
    if headings_on:
        try:
            html.append('
')
            for item in heads:
                html.append(' '*6+''+str(item)+'	')
            html.append('
')
        except:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
            print 'Error writing html table headings:'
            print ''.join('!! ' + line for line in lines)

    # html table content
    try:
        for row in data:
            html.append('
')
            for item in row:
                html.append(' '*6+''+str(item)+'	')
            html.append('
')
    except:
        print 'Error writing body of html data'

    # closing lines needed
    try:
        html.append('
')
        html.append('')
        html.append('')
    except:
        print 'Error closing html data'

    # write html data to file
    fileout = open(path, 'w')
    for line in html:
        fileout.write(line)

    print 'Data written to:', path, '\n'

    if sql_path:
        os.startfile(path)
    else:
        v_open = raw_input("Open file (Y/N):").upper()
        if v_open == 'Y':
            os.startfile(path)

rawDescription: Search through directories for specific Excel files and compare data from these files with inputvalues


code:
proc = subprocess.Popen("ping %s" % ip, shell=True,
                        stdout=subprocess.PIPE)
print
while True:
    line = proc.stdout.readline()
    wx.Yield()
    if line.strip() == "":
        pass
    else:
        print line.strip()
    if not line: break
proc.wait()

rawDescription: Read a command prompt output in a separate window in python


code:
import subprocess
print sum(int(subprocess.check_output(["/bin/sh", "-c", "n=`expr {} + 1` && echo $n".format(i)])) for i in range(10))

rawDescription: Is it possible to cross reference bash and python variables in python script


code:
from itertools import chain
import csv
import re

days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
days_rep = [[day.lower()[:l] for l in xrange(len(day), 0, -1)] for day in days]
days_rep = sorted(chain.from_iterable([(len(day), day, index) for day in days] for index, days in enumerate(days_rep)), reverse=True)
days_d = {day : ' {} '.format(days[value]) for length, day, value in days_rep}
re_days = re.compile(r'({})'.format('|'.join(day for length, day, value in days_rep)), flags=re.I)

def normalise(entry):
    to_days = re_days.sub(lambda x: days_d[x.group(1).lower()], entry)
    return to_days.replace('  ', ' ').replace(' - ', '-').strip()

with open('input.csv', 'rb') as f_input:
    for cols in csv.reader(f_input):
        print "{} {} {}".format(cols[0], normalise(cols[1]), cols[2])

rawDescription: Regex to pick days of the week from a string in Python


code:
class MyDecorator(object):
    def __init__(self, argument):
        self.arg = argument

    def __call__(self, fn):
        @functools.wraps(fn)
        def decorated(*args, **kwargs):
            print "In my decorator before call, with arg %s" % self.arg
            fn(*args, **kwargs)
            print "In my decorator after call, with arg %s" % self.arg
        return decorated

rawDescription: Python Class Based Decorator with parameters that can decorate a method or a function


code:
x = "abcdefghi"
x = list(x)
for i in range(len(x)):
    if i < 4:
        x[i] = x[i+2]
        print "".join(x)

rawDescription: python replace records in variable

description: Python replace records in variable


code: print "A" * 10

rawDescription: What is the easiest way to print 10 characters in Python?


code:
sort_of_dict = [('ALice', 1), ('in', 2), ('Wonderland', 3)]

for key, value in sort_of_dict:
  print key

rawDescription: Enumerate Keys in a dictionary?

description: Enumerate Keys in a dictionary


code:
#
#                               Preparations
#

nodes=[]
NUMNODES=3

#
#                                   Defining Node Class
#

class Node(object):

    def __init__(self,name=None):
        self.name=name
        self.activation_threshold=1.0
        self.net_input=0.0
        self.outgoing_connections=[]
        self.incoming_connections=[]
        self.connections=[]
        self.activation=None

    def __str__(self):
        return self.name

    def addconnection(self,sender,weight=1.0):
        self.connections.append(Connection(self,sender,weight))
        print "Node", str(self), "now contains", str(self.connections[-1])

    def update_input(self):
        self.net_input=0.0
        for conn in self.connections:
            self.net_input += conn.weight * conn.sender.activation
        print 'Updated Input for node', str(self), 'is', self.net_input

    def update_activation(self):
        self.activation = self.net_input - 0.5
        print 'Updated Activation for node', str(self), 'is', self.activation

#
#                                   Defining Connection Class
#

class Connection(object):
    def __init__(self, sender, reciever, weight):
        self.weight=weight
        self.sender=sender
        self.reciever=reciever
        sender.outgoing_connections.append(self)
        reciever.incoming_connections.append(self)
        print 'Created', str(self)

    def __str__(self):
        string = "Connection from " + str(self.sender) + " to " + str(self.reciever) + ", weight = " + str(self.weight)
        return string
#
#                                 Other Programs
#

def set_activations(act_vector):
    """Activation vector must be same length as nodes list"""
    for i in xrange(len(act_vector)):
        nodes[i].activation = act_vector[i]

for i in xrange(NUMNODES):
    nodes.append(Node(str(i)))
    print "Created node:", nodes[i]

for i in xrange(NUMNODES):#go thru all the nodes calling them i
    for j in xrange(NUMNODES):#go thru all the nodes calling them j
        if i!=j:#as long as i and j are not the same
            nodes[i].addconnection(nodes[j])#connects the nodes together
#
#                                         Setting Activations
#
set_activations([1.0,1.0,0.0])

#
#                                        Running 10 Iterations
#
for thing in nodes:
    thing.update_input() #initializing inputs

for i in xrange(10):
    for thing in nodes:
        thing.update_activation()
        thing.update_input()

rawDescription: Python Neural Networking: Run 10 iterations but I get the same output


code:
def _recurse_tree(parent, depth, source, tree=None):
    if tree is None:
        tree = {}

    last_line = source.readline().rstrip()
    while last_line:
        if last_line.startswith('-'):
            tabs = len( re.match(PATTERN, last_line).group() )
        else:
            tabs = 0
        if tabs < depth:
            break
        node = re.sub(PATTERN, '', last_line.strip())
        if tabs >= depth:
            if parent is not None:
                print "%s: %s" %(parent, node)
                if parent in tree:
                    tree[parent].append(node)
                else:
                    tree[parent] = [ node, ]
            last_line = _recurse_tree(node, tabs+1, source, tree)
    return last_line

rawDescription: Refactoring to eliminate global variable in recursive function


code:
import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(1, 9).reshape((2, 4)),
        columns=["a1", "b1", "a2", "b2"])

part1 = df.iloc[:,0:2]
part2 = df.iloc[:,2:4]

new_columns = ["c", "d"]
part1.columns = new_columns
part2.columns = new_columns

print pd.concat([part1, part2], ignore_index=True)

rawDescription: How do you stack two Pandas Dataframe columns on top of each other?

description: Stack two Pandas Dataframe columns on top of each other