code:
for i in range(len(a)):
    for j in range(i + 1, len(a)):
        # compare the elements here
        print(a[i], a[j])

rawDescription: Pair every elements on a list

description: Pair every elements on a list


code:
#!/usr/bin/python
import urllib2

class HttpFile(object):
    def __init__(self, url):
        self.url = url
        self.offset = 0
        self._size = -1

    def size(self):
        if self._size < 0:
            f = urllib2.urlopen(self.url)
            self._size = int(f.headers["Content-length"])
        return self._size

    def read(self, count=-1):
        req = urllib2.Request(self.url)
        if count < 0:
            end = self.size() - 1
        else:
            end = self.offset + count - 1
        req.headers['Range'] = "bytes=%s-%s" % (self.offset, end)
        f = urllib2.urlopen(req)
        data = f.read()
        # FIXME: should check that we got the range expected, etc.
        chunk = len(data)
        if count >= 0:
            assert chunk == count
        self.offset += chunk
        return data

    def seek(self, offset, whence=0):
        if whence == 0:
            self.offset = offset
        elif whence == 1:
            self.offset += offset
        elif whence == 2:
            self.offset = self.size() + offset
        else:
            raise Exception("Invalid whence")

    def tell(self):
        return self.offset

rawDescription: Is there a library for retrieving a file from a remote zip?


code:
response.delete_cookie('cookie_name', domain="cookie_domain")
return response

rawDescription: How to delete a Cookie in Python

description: Delete a Cookie in Python


code:
urlfixed = "http://www.fatm.com.es/Datos_Equipo.asp?"
cod = ["01GR0001","01GR0004","03GR0006","02GR0003","01GR0030","01GR0018","04GR0007","03GR0032","01AL0001","02AL0003"]
for i in cod:
    sock = urllib.urlopen(urlfixed + "Cod=" + i)
    htmlSource = sock.read()
    sock.close()
    soup = BeautifulSoup(htmlSource)
    form = soup.find("form", {'id': "FORM1"})

    valores = [item.get('value') for item in form.find_all('input')]
    valores.remove('Imprimir')
    valores.remove('Cerrar')
    values = valores

    out = open('tomate.csv', 'ab')
    w = csv.writer(out)
    w.writerow([s.encode("utf-8") for s in values])
    out.close()
#the loop ends here

rawDescription: How to iterate over URLs for writing CSV

description: Iterate over URLs for writing CSV


rawDescription: Convert list of dictionaries to Dataframe


code:
with open(filname) as f:
   for line in f:
      if "search_term" in line:
           break

rawDescription: How to load a big text file efficiently in python

description: Load a big text file efficiently in python


rawDescription: Calculations using list values

description: Calculations using list values


code:
class DequeHandler(jsonpickle.handlers.BaseHandler):
    def flatten(self, obj, data):
        return list(obj),obj.maxlen
    def restore(self,obj):
        return deque(obj[0], maxlen=obj[1])
jsonpickle.handlers.register(deque, DequeHandler)

rawDescription: jsonpickle ignores maxlen of collection deque

description: Jsonpickle ignores maxlen of collection deque


code:
# PostgreSQL
from sqlalchemy.sql import extract
session.query(MyTable).filter(extract('dow', MyTable.my_date) == 1)

# MySQL
from sqlalchemy import func
session.query(MyTable).filter(func.dayofweek(MyTable.my_date) == 2)

rawDescription: SQLAlchemy Filter based on a function of an a field of a table


code:
gi = pygeoip.GeoIP('GeoIPCity.dat')
gi.record_by_addr('64.233.161.99')
gi.time_zone_by_addr('64.233.161.99')

rawDescription: How to get latitude, longtitude from country, region code using pygeoip

description: Get latitude, longtitude from country, region code using pygeoip


code:
from tkinter import *
import time

def updateDisplay(myString):
    displayVar.set(myString + ' --- ' + time.ctime())

root = Tk()

displayVar = StringVar()

displayLab = Label(root, textvariable=displayVar)

displayLab.pack()

rawDescription: Tkinter Dynamically updating text field with incoming messages


code:
import json
import requests

# protected
_accessCode = "someaccesscode"
_accessStr = "?access_token=" + _accessCode
_myID = "someidnumber"

r = requests.get("https://graph.facebook.com/"
    + _myID + "/friends/" + _accessStr)
raw = json.loads(r.text)

terminate = len(raw["data"])

a = list()
for k in range(0, terminate - 1):
    friendID = raw["data"][k]["id"]
    friendName = raw["data"][k]["name"]
    url = ("https://graph.facebook.com/me/mutualfriends/"
        + friendID + _accessStr)
    req = requests.get(url)
    temp = json.loads(req.text)
    print("Processing: " + str(k + 1) + " of " + str(terminate))
    for j in range(0, len(temp["data"])):
        a.append(friendID + "," + temp["data"][j]["id"] + ","
            + friendName + "," + temp["data"][j]["name"])

# dump contents to file:
outputFile = "C:/Users/franklin/Documents/gen/friendsRaw.csv"
output = open(outputFile, "w")
print("Dumping to file...")
# write all me/friend relationships to file
for k in range(0, terminate):
    output.write(_myID + "," + raw["data"][k]["id"]
        + ",me," + str(raw["data"][k]["name"].encode("utf-8", "ignore")) + "\n")

# write all friend/friend relationships to file
for i in range(0, len(a)):
    output.write(str(a[i].encode("utf-8", "ignore")) + "\n")

output.close()

rawDescription: optimize python processing json retrieved from the fb-graph-api

description: Optimize python processing json retrieved from the fb-graph-api


code:
zoomin = lambda x: None if len(np.setdiff1d(['judge', 'lawyer'], x['job type'])) else 'lawyer_judge'
df.groupby('person').apply(zoomin)

rawDescription: Pandas: complex aggregation issue

description: Pandas: complex aggregation issue


rawDescription: percentage of column pandas

description: Percentage of column pandas


code:
l = ["My", "turtle", "is", "old"]
l.sort(key=len, reverse=True)
# -> ['turtle', 'old', 'My', 'is']

rawDescription: outputting a list in order of shortest word to longest word (python)

description: Outputting a list in order of shortest word to longest word (python)


code:
import a
import b

rawDescription: What are efficient practices for importing python modules?


rawDescription: Get unicode string out of binary data in python


code:
rbounds = bounds.readlines()
lines_with_data = rbounds[9:12]    # gives lines 9-11, given first line is 0th
for l in lines_with_data:
    pass  # parse_line here

rawDescription: Read specific line from text file and assign to variable using Python 2.7


code:
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
import csv

mark_font=3
lats=lons=population=[]
filename = 'D:/22_sept_14/mvsf.csv'
with open(filename) as f:
    reader = csv.reader(f)
    for row in reader:
        lats.append(float(row[0]))
        lons.append(float(row[1]))
        population.append(float(row[2]))

m = Basemap(projection='robin', resolution = 'l', area_thresh = 10000.0,
              lat_0=0, lon_0=0)
m.drawcoastlines()
m.drawcountries()
m.fillcontinents(color = 'gray')
m.drawmapboundary(fill_color='aqua')
m.drawmeridians(np.arange(0, 360, 30))
m.drawparallels(np.arange(-90, 90, 30))
# fill continents, set lake color same as ocean color.
# draw parallels and meridians.
# label parallels on right and top
# meridians on bottom and left
parallels = np.arange(0.,81,10.)
# labels = [left,right,top,bottom]
m.drawparallels(parallels,labels=[False,True,True,False])
meridians = np.arange(10.,351.,20.)
m.drawmeridians(meridians,labels=[True,False,False,True])
# plot blue dot on Boulder, colorado and label it as such.
lon, lat = -100.237, 49.125 # Location of Boulder
# convert to map projection coords.
# Note that lon,lat can be scalars, lists or numpy arrays.
xpt,ypt = m(lon,lat)
# convert back to lat/lon
lonpt, latpt = m(xpt,ypt,inverse=True)
m.plot(xpt,ypt,'go',markersize=17*mark_font,alpha=.8)  # plot a blue dot there
# put some text next to the dot, offset a little bit
# (the offset is in map projection coordinates)
plt.text(xpt,ypt,'17%' , fontsize=17,color='w')

lon, lat = -104.237, 40.125 # Location of Boulder
# convert to map projection coords.
# Note that lon,lat can be scalars, lists or numpy arrays.
xpt,ypt = m(lon,lat)
# convert back to lat/lon
lonpt, latpt = m(xpt,ypt,inverse=True)
m.plot(xpt,ypt,'ro',markersize=16*mark_font,alpha=.8)  # plot a blue dot there
# put some text next to the dot, offset a little bit
# (the offset is in map projection coordinates)
plt.text(xpt,ypt,'16%' , fontsize=16,color='w')

plt.show()

rawDescription: plotting categorical data on world map

description: Plotting categorical data on world map


code:
#! /usr/bin/env python3
from collections import deque
from operator import eq

def main():
    """Show how to search for similar neighbors in a 2D array structure."""
    some_array = ((0, 1, 1, 0),
                  (0, 1, 0, 1),
                  (0, 1, 0, 1),
                  (0, 1, 1, 0))
    neighbors = (-1, 0), (0, +1), (+1, 0), (0, -1)
    start = 0, 0
    similar = eq
    print(list(find_similar(some_array, neighbors, start, similar, 'BFS')))

def find_similar(array, neighbors, start, similar, mode):
    """Run either a BFS or DFS algorithm based on criteria from arguments."""
    match = get_item(array, start)
    block = {start}
    visit = deque(block)
    child = dict(BFS=deque.popleft, DFS=deque.pop)[mode]
    while visit:
        node = child(visit)
        for offset in neighbors:
            index = get_next(node, offset)
            if index not in block:
                block.add(index)
                if is_valid(array, index):
                    value = get_item(array, index)
                    if similar(value, match):
                        visit.append(index)
        yield node

def get_item(array, index):
    """Access the data structure based on the given position information."""
    row, column = index
    return array[row][column]

def get_next(node, offset):
    """Find the next location based on an offset from the current location."""
    row, column = node
    row_offset, column_offset = offset
    return row + row_offset, column + column_offset

def is_valid(array, index):
    """Verify that the index is in range of the data structure's contents."""
    row, column = index
    return 0 <= row < len(array) and 0 <= column < len(array[row])

if __name__ == '__main__':
    main()

rawDescription: Locate all similar "touching" elements in a 2D Array (Python)


code:
bulk = Users._get_collection().initialize_ordered_bulk_op()

for user in users:  # where users is a list of dicts containing data to work on
    bulk.find({ "matchField": user['matchField'] }).upsert().replace_one(user)

bulk.execute()

rawDescription: mongoengine bulk upsert a batch of record?

description: Mongoengine bulk upsert a batch of record


code: word_count = Counter(words)

rawDescription: Python: Add occurrences of a list element and its total count to another list, avoid adding duplicates


code:
import re

my_re = re.compile(";".join(r"(\d+)" for i in range(6)))

return re.sub(
  my_re,
  lambda match: ";".join(str(int(match.group(i)) / 2) for i in range(1, 7)),
  editor.getText())

rawDescription: python finding text and after that text multiple numbers

description: Python finding text and after that text multiple numbers


code:
if __name__ == '__main__':

   root = Tkinter.Tk()
   root.minsize(width=250, height=50)

   Title = Label(self, text='Questionnaire', bg='firebrick', fg='white', width=50, font=('MS', 24, 'bold'))
   Title.grid(row=0,column=0, columnspan=4, rowspan=1)

rawDescription: How to keep a label widget (Page title) in Tkinter at the top of a frame

description: Keep a label widget (Page title) in Tkinter at the top of a frame


code:
alpha=[('A',1,1,2),('B',2,2,2),('C',3,1,2)]
total = float(sum(reduce(mul,a[1:]) for a in alpha))
total
[(a[0], "%.2f" % (reduce(mul,a[1:])/total)) for a in alpha]

rawDescription: nested operators

description: Nested operators


code:
sobel_x = tf.constant([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], tf.float32)
sobel_x_filter = tf.reshape(sobel_x, [3, 3, 1, 1])
sobel_y_filter = tf.transpose(soble_x_filter, [1, 0, 2, 3])

# Shape = height x width.
image = tf.placeholder(tf.float32, shape=[None, None])

# Shape = 1 x height x width x 1.
image_resized = tf.expand_dims(tf.expand_dims(image, 0), 3)

filtered_x = tf.nn.conv2d(image_resized, sobel_x_filter,
                          strides=[1, 1, 1, 1], padding='SAME')
filtered_y = tf.nn.conv2d(image_resized, sobel_y_filter,
                          strides=[1, 1, 1, 1], padding='SAME')

rawDescription: Is there a convolution function in Tensorflow to apply a Sobel filter?


code:
for namespace in each(db.GqlQuery("SELECT * FROM __namespace__")):
    # set the namespace
    namespace_manager.set_namespace( namespace.namespace_name )
    # get all the kinds used in this namespace
    for kind in each(db.GqlQuery("SELECT * FROM __kind__")):
        # get entity 'keys only'
        for key in each(db.GqlQuery("SELECT __key__ FROM %s" % kind.kind_name)):
            db.delete(key)

rawDescription: How do I delete all Entities in all namespaces in GAE?

description: Delete all Entities in all namespaces in GAE


rawDescription: Transforming Pandas dataframe

description: Transforming Pandas dataframe


code:
from struct import unpack

inputFile = open("test.txt", "r")
byteString = inputFile.read(4)

# Unpack the first 4 bytes as a little ended unsigned integer
result = unpack("<I", byteString)[0]

# Do some bit arithmetic
tmp = result & 0xff

# Show variable values
print("%08x %08x" % (result, tmp))

rawDescription: How to read binary data and display as a little endian hexstring in Python?

description: Read binary data and display as a little endian hexstring in Python


code:
import string
s = '\xffDSI....'
cleaned = ''.join(c for c in s if c in string.printable)

rawDescription: remove hex value from string

description: Remove hex value from string


code:
def create(mime_type='application/octet-stream',
           _blobinfo_uploaded_filename=None):
  """Create a writable blobstore file.

  Args:
    mime_type: Resulting blob content MIME type as string.
    _blobinfo_uploaded_filename: Resulting blob's BlobInfo file name as string.

  Returns:
    A file name for blobstore file. This file can be opened for write
    by File API open function. To read the file or obtain its blob key, finalize
    it and call get_blob_key function.
  """

rawDescription: storing MIME type with blobstore

description: Storing MIME type with blobstore


code:
for item in itertools.chain(list, [singleobj]):
    ...

rawDescription: python for loop list plus one item

description: Python for loop list plus one item


code:
data = {"outfit":{"shirt":"red","pants":{"jeans":"blue","trousers":"khaki"}}}
import json
from collections import OrderedDict

def node(name, children):
    n = OrderedDict()
    n['id'] = 'node' + name.capitalize()
    n['name'] = name
    n['data'] = {}
    n['children'] = children
    return n

def convert(d):
    if type(d) == dict:
        return [node(k, convert(v)) for k, v in d.items()]
    else:
        return [node(d, [])]

print(json.dumps(convert(data), indent=True))

rawDescription: Manipulating data structures in Python

description: Manipulating data structures in Python


rawDescription: Matplotlib x-labels for logarithmic graph


code:
import os
import tempfile
from contextlib import contextmanager

@contextmanager
def tempinput(data):
    temp = tempfile.NamedTemporaryFile(delete=False)
    temp.write(data)
    temp.close()
    yield temp.name
    os.unlink(temp.name)

with tempinput('Some data.\nSome more data.') as tempfilename:
    processFile(tempfilename)

rawDescription: Python StringIO and compatibility with `with' statement (context manager)


rawDescription: How can I write data from a dictionary to a CSV file in Python

description: Write data from a dictionary to a CSV file in Python


code:
from tkinter import *
root = Tk()

root.iconbitmap(r'C:\Program Files\Factorio\bin\x64\Factorio.exe')
root.mainloop()

rawDescription: tkinter - changing the title bar icon

description: Tkinter - changing the title bar icon


code: xl.DisplayAlerts = False

rawDescription: Handle Excel Message Box from Within Python using Win32com


code:
valid = set()
for string in substrings:
  for line in dictionary_words:
      if string in line:
          valid.add(string)
          break
f.writelines(sorted(valid))

rawDescription: Python string compare issue

description: Python string compare issue


code:
# This dict associates the old values to the values to which they should be changed
replacing_dict = {'WaveDir': Dir, 'WaveHs': Hs, 'WaveTp': Tp}

new_lines = []
with open(file_platform) as f_input:
    for line in f_input:
        first_non_space = line.strip().split(' ')[0]
        if first_non_space in replacing_dict:
            line.replace(first_non_space, replacing_dict[first_non_space])

        new_lines.append(line)

# Write new_lines into a file and, optionally, replace this new file for the old file

rawDescription: replace an array of values in a file with new values

description: Replace an array of values in a file with new values


rawDescription: Slice a binary number into groups of five digits


code:
import datetime

def minimalist_xldate_as_datetime(xldate, datemode):
    # datemode: 0 for 1900-based, 1 for 1904-based
    return (
        datetime.datetime(1899, 12, 30)
        + datetime.timedelta(days=xldate + 1462 * datemode)
    )

rawDescription: Converting date/time in Pandas

description: Converting date/time in Pandas


code: output = csv.DictWriter(open('file3.csv','w'), delimiter=',', lineterminator='\n', fieldnames=headers)

rawDescription: Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python


code:
def get_fun(fn):
    return '.'.join([fn.__module__, fn.__name__])

rawDescription: How to get the name of a function (plus its module) in Python?

description: Get the name of a function (plus its module) in Python


code:
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.image as img
import matplotlib.cm as cm

fig = plt.figure(figsize=(16, 8))

# here I am drawing a greyscale image
image = img.imread(filename)
ax1=fig.add_subplot(1, 2, 1, aspect='equal')
ax1.imshow(image, cmap=cm.Greys_r)
fig.tight_layout()
plt.axis('off')

# and here I am drawing a scatterplot based on this image.
X, Y = image.shape
x, y = np.nonzero(image)
ax2=fig.add_subplot(1, 2, 2, aspect='equal')
ax2.scatter(y - Y, -x, s=1, linewidths=0)
ax2.set_xlim(-Y, 0)
ax2.set_ylim(-X, 0)
fig.tight_layout()

plt.show()

rawDescription: How can I make image and scatterplot the same height?

description: Make image and scatterplot the same height


code:
while True:
    poz=input("Give the position:")
    try:
        val=int(poz)
        if val>=0:
            break
        else:
            print ("The position has to be bigger then 0")
    except ValueError:
        print ("invalid number")

rawDescription: Checking a value in python

description: Checking a value in python


code:
from PIL import ImageFont, Image, ImageDraw
import textwrap

# Source text, and wrap it.
userinput = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet scelerisque nulla. Pellentesque mollis tellus ut arcu malesuada auctor. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut tristique purus non ultricies vulputate"
text = textwrap.fill(userinput, 50)

# Font size, color and type.
fontcolor = (255, 255, 255)
fontsize = 40
font = ImageFont.truetype("/System/Library/Fonts/AppleGothic.ttf", fontsize)

# Determine text size using a scratch image.
img = Image.new("RGBA", (1,1))
draw = ImageDraw.Draw(img)
textsize = draw.textsize(text, font)

# Now that we know how big it should be, create
# the final image and put the text on it.
background = (200, 255, 0)
img = Image.new("RGBA", textsize, background)
draw = ImageDraw.Draw(img)
draw.text((0, 0), text, fontcolor, font)

img.show()
img.save("seesharp.png")

rawDescription: Determining pixel height of a string with newlines in Pillow


code:
import pandas as pd
import glob

globbed_files = glob.glob("*.csv") #creates a list of all csv files

data = [] # pd.concat takes a list of dataframes as an agrument
for csv in globbed_files:
    frame = pd.read_csv(csv)
    data.append(frame)

bigframe = pd.concat(data, ignore_index=True) #dont want pandas to try an align row indexes
bigframe.to_csv("output.csv")

rawDescription: Stack columns from multiple CSV's into a master file


code:
import time, urllib2

HTML = '<img class="right" src="{}" width="32" height="32">'

def internet_on():

    try:
        urllib2.urlopen('http://64.233.160.94',timeout=1)
        status_image = 'networkon.png'
    except urllib2.URLError as err:
        status_image = 'networkoff.png'

    with open('/var/www/html/viv/wifiout.html', 'w') as f:
        f.write(HTML.format(status_image))

while True:
    internet_on()
    time.sleep(1)

rawDescription: Run Python Script every X seconds

description: Run Python Script every X seconds


code:
from ast import literal_eval

# use generator
# instead of allocating
# 400 000 lists at a time
your_lists = (literal_eval(s) for s in open('filename.txt'))

rawDescription: Python and read text file that contains lists with strings and numbers


code:
numrows = len(input)    # 3 rows in your example
numcols = len(input[0]) # 2 columns in your example

rawDescription: Find length of 2D array Python

description: Find length of 2D array Python


code:
src = {
    'corp': 'http://www.youtube.com/embed/0lrqEGlu0Fo',
    'uk': 'http://www.youtube.com/embed/30MfCTLhdZ4',
}

followers = {
    'corp': 'uk',
    'uk': 'corp',
}

return {
    'opener': {'lookup': 'opener', 'src': src[opener]},
    'follower': {'lookup': 'follower', 'src': src[followers[opener]]},
}

rawDescription: How to provide a set of values in an either-or situation?

description: Provide a set of values in an either-or situation


code: [i for i in l if 'Delta' in i]

rawDescription: Python // Remove String // Array

description: Python // Remove String // Array


code:
import numpy as np
import theano.tensor as T
from lasagne import layers
from lasagne.updates import nesterov_momentum
from nolearn.lasagne import NeuralNet
from nolearn.lasagne import BatchIterator
from lasagne import nonlinearities

# custom loss: multi label cross entropy
def multilabel_objective(predictions, targets):
    epsilon = np.float32(1.0e-6)
    one = np.float32(1.0)
    pred = T.clip(predictions, epsilon, one - epsilon)
    return -T.sum(targets * T.log(pred) + (one - targets) * T.log(one - pred), axis=1)

net = NeuralNet(
    # customize "layers" to represent the architecture you want
    # here I took a dummy architecture
    layers=[(layers.InputLayer, {"name": 'input', 'shape': (None, 1, 229, 1)}),

            (layers.DenseLayer, {"name": 'hidden1', 'num_units': 20}),
            (layers.DenseLayer, {"name": 'output', 'nonlinearity': nonlinearities.sigmoid, 'num_units': 13})], #because you have 13 outputs

    # optimization method:
    update=nesterov_momentum,
    update_learning_rate=5*10**(-3),
    update_momentum=0.9,

    max_epochs=500,  # we want to train this many epochs
    verbose=1,

    #Here are the important parameters for multi labels
    regression=True,

    objective_loss_function=multilabel_objective,
    custom_score=("validation score", lambda x, y: np.mean(np.abs(x - y)))

    )

net.fit(X_train, labels_train)

rawDescription: nolearn for multi-label classification

description: Nolearn for multi-label classification


code:
def insertdata(db,tuplelist):
    i = db.insert()
    i.execute([dict(user=elem[0], password=elem[1]) for elem in tuplelist])
#-----main-------
tuplelist = readfile("C:/py/tst.txt")  #parse file is really fast
mydb = initdatabase()
insertdata(mydb,tuplelist)

rawDescription: SQLAlchemy insert millions data inefficiently


code:
release = ''
latex_elements = { 'releasename': '' }

rawDescription: How do I get rid of the "Release 1" in the Page Header of the Sphinx Latex Output?

description: Get rid of the "Release 1" in the Page Header of the Sphinx Latex Output


code:
import paramiko
paramiko.util.log_to_file('/tmp/paramiko.log')

# Open a transport

host = "example.com"
port = 22
transport = paramiko.Transport((host, port))

# Auth

password = "foo"
username = "bar"
transport.connect(username = username, password = password)

# Go!

sftp = paramiko.SFTPClient.from_transport(transport)

# Download

filepath = '/etc/passwd'
localpath = '/home/remotepasswd'
sftp.get(filepath, localpath)

# Upload

filepath = '/home/foo.jpg'
localpath = '/home/pony.jpg'
sftp.put(localpath, filepath)

# Close

sftp.close()
transport.close()

rawDescription: paramiko's sshclient with sftp

description: Paramiko's sshclient with sftp


code:
people = [("John","Smith"), ("Jane","Doe"), ("Jane","Smith")]
table_data = []
for i, person in enumerate(people):
    # Add a row to the table
    table_data.append([person[0], person[1]])
# Create the table
issue_table = Table(table_data, colWidths=[doc.width/3.0]*3)

Story.append(issue_table)

rawDescription: How can I create a table with reportlab using objects in an existing list

description: Create a table with reportlab using objects in an existing list


code:
for i in itertools.product(string.ascii_letters + string.digits, repeat=8):
     print(''.join(i))

rawDescription: Write to a file to bypass memory cap when generating a big variable. Python 3.3


code:
import sys
outfile = open( r'/Users/x/Desktop/myDoc.txt', 'w' )
i = 0
lis = []
n = int(raw_input("How many interviews are there? "))
table = "

\
    Start	\
    End	\
    People	\
    Interview Type

 \
    %s
"

while n:
   i += 1
   istart = raw_input("Interview Start Time: ")
   iend= raw_input("Interview End Time: ")
   ipeople= raw_input("What are the interviewer names: ")
   itype= raw_input("What is the interview type: ")
   lis.append("
%s	%s	%s	%s
" % (istart, iend, ipeople, itype))
   n-=1

outfile.write(table % ''.join(lis))
outfile.close()

rawDescription: Loop within a print statement

description: Loop within a print statement


code:
def f1(line):
 a,b,c = line.split()

def f2(line):
 (a,b,c) = line.split()

def f3(line):
 [a,b,c] = line.split()

import dis
dis.dis(f1)
dis.dis(f2)
dis.dis(f3)

rawDescription: Python assignment destructuring

description: Python assignment destructuring


code: cv2.drawContours(img, contours, -1, (0,255,0), 3)

rawDescription: Draw Contours in opencv around recognized polygon


rawDescription: Rotation matrix to quaternion equivalence


code:
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
import numpy as np

maxnum = 13
numfilled = 40
x = np.random.randint(0, maxnum, size=numfilled)
y = np.random.randint(0, maxnum, size=numfilled)
z = x * y

fig, ax = plt.subplots()

for X,Y,Z in zip(x,y,z):
    ax.text(X+0.5,Y+0.5,str(Z), ha='center', va='center')

ax.axis([0, maxnum, 0, maxnum])

for axis in [ax.xaxis, ax.yaxis]:
    axis.set_minor_locator(MultipleLocator(1))
    axis.set_ticks(np.arange(maxnum) + 0.5)
    axis.set_ticklabels(range(maxnum))

ax.grid(which='minor')
ax.xaxis.set_ticks_position('top')

plt.show()

rawDescription: Using Matplotlib to create a partial multiplication table checkerboard?


code:
mapper(Address, addresses_table,
            exclude_properties=['street', 'city', 'state', 'zip'])

rawDescription: Constant property/column value for objects in SQLAlchemy


code:
class foo(Structure):
    _fields_=[("i",c_int),
              ("b1",POINTER(c_int)),
              ("w1",POINTER(c_float))]

rawDescription: How to declare a C struct with a pointer to array in ctypes?

description: Declare a C struct with a pointer to array in ctypes


code:
s = "2 dogs. 4 cats. horses. 7 goats"
import re
re.findall(r'\d+\s(\w+)', s)

rawDescription: Lookbehind in python

description: Lookbehind in python


code:
def walk_to_value(d, l):
    for e in l:
        d = d[e]
    return d

rawDescription: An elegant way of walking a multidimensional dict with a list of keys?


code:
import pylab as plt

fig, ax = plt.subplots()
ax.plot([1,2,3],[4,5,6])

labels = [item.get_text() for item in ax.get_xticklabels()]

empty_string_labels = ['']*len(labels)
ax.set_xticklabels(empty_string_labels)

plt.show()

rawDescription: How to hide ticks label in python but keep the ticks in place?

description: Hide ticks label in python but keep the ticks in place


code:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

U = np.random.rand(10, 10, 10) - 0.5
V = np.random.rand(10, 10, 10) - 0.5
cmap = plt.cm.jet
time_samples = U.shape[-1]
for t in xrange(time_samples):
    plt.quiver(U[..., t], V[..., t], color=cmap(j/time_samples))
plt.show()

rawDescription: Matplotlib: Superimpose multiple 2d quiver plots over time


rawDescription: Different operation per each row on multiple columns in python Pandas


code:
def func(stdscr):
    if curses.can_change_color():
        # init_color(n, r, g, b)
        # n=0 is background
        curses.init_color(0, 0, 0, 0)
    c = stdscr.getkey()

rawDescription: Python: curses and the default black color


code:
df.index = pd.DatetimeIndex(df.index)
df.index

rawDescription: Pandas time series index from list of dictionaries


code:
groups = []
for k,g in itertools.groupby(input_list, lambda x: x is not None):
    if k:
        groups.append(list(g))

rawDescription: Is there a str.split equivalent for lists in Python?


code: snr = scipy.stats.signaltonoise(img, axis=None)

rawDescription: How to get the Signal-to-Noise-Ratio from an image in Python?

description: Get the Signal-to-Noise-Ratio from an image in Python


code:
from operator import attrgetter
a.sort(key=attrgetter('LName'))   #sorts in-place
print(a) #list should be sorted here.

rawDescription: Sorting a list of classes alphabetically based on variable in class python 2.7


code:
for mailpart in mailitem.walk():
    if mailpart.get_content_maintype() == 'multipart':
        continue
    message = str(mailpart.get_payload(decode=True))

rawDescription: Python Mail Converts Random Characters to '='


code:
funtpl = """
def __TheFunction__(self):
    %s

"""

def create_custom_method(print_end):
    # this would be better done by a template engine I think
    source = ['print self.text']
    if print_end:
        source.append('print "end"')

    source = funtpl % "\n    ".join(source)
    bytecode = compile(source, "<string>", "exec", )
    locals = {}
    eval(bytecode, globals(), locals)
    return locals["__TheFunction__"]

class Faa(object):
    def __init__(self, print_end):
        self.text='faa'
        fun = create_custom_method(print_end)
        self.custom_method = fun.__get__(self, type(self))

f = Faa(True)
f.custom_method()

rawDescription: Dynamically generate method after executing __init__


code:
import sys
import pycuda.autoinit
import pycuda.driver as cuda
import numpy as np

listToProcess = []
for i in range(0, 10):
    listToProcess.append(i)

l2p = np.array(listToProcess, dtype=np.int32)
listToProcess_gpu = cuda.mem_alloc(l2p.nbytes)
cuda.memcpy_htod(listToProcess_gpu, l2p)

rawDescription: How to handle a python list with PyCUDA?

description: Handle a python list with PyCUDA


code:
def __setitem__(self, k, v):
    if hasattr(k, 'lower'):
        k = k.lower()
    return super(MyDict, self).__setitem__(k, v)

rawDescription: Is there a better way to create a class which is a subclass of `dict` but case-insensitive?


code:
points = [(0,0),(0,1),(1,1,),(1,0)]

for point in points:
    plt.plot(point[0], point[1], 'o')

automin, automax = plt.xlim()
plt.xlim(automin-0.5, automax+0.5)
automin, automax = plt.ylim()
plt.ylim(automin-0.5, automax+0.5)

plt.show()

rawDescription: Python & Matplot: how to set auto-offset?


rawDescription: gradient function of fmin_cg in scipy

description: Gradient function of fmin_cg in scipy


code:
loop = True
status = True
exit = set(["exit","leave"])
while loop:
    while status:
        print ("Any of these commands will quit the program", exit)
        num = input("Pick a number: ")
        if 1 == 2:
            print ("What the hell, how does 1 = 2?")
        elif num in exit:
            loop = False
            status = False
        else:
            continue

rawDescription: Trying to exit using a set in python. What am i doing wrong?


code:
def list(request):
    lang = request.LANGUAGE_CODE
    entry = Entry.objects.get(pk=1)
    description = getattr(entry, 'description_%s' % lang)
    return render(request, 'name.html', {'description': description})

rawDescription: Django Translations - how to do it efficiently?


code:
config["the-list"].append("newstring")
with file('config.yml', 'w') as f:
    yaml.dump(config, f)

rawDescription: PyYAML add string to list

description: PyYAML add string to list


code: levelsList = [list(x) for x in level]

rawDescription: Replacing string with tuple in list of tuples


code:
import collections
import json
d = collections.OrderedDict()
d['foo'] = 'bar'
d['baz'] = 'quux'
json.dumps(d)
d['wat'] = 'waaaaat'
json.dumps(d)
d['baz'] = 'qux'
json.dumps(d)
d[123] = 456
json.dumps(d)

rawDescription: JSON Ordered Set

description: JSON Ordered Set


code:
entries =[]
for i in range(5):
    entries.append(Entry(self, ...))

rawDescription: How to create multiple entry widgets at once?

description: Create multiple entry widgets at once


rawDescription: Do all chars of a string belong to a set?


code:
import itertools

def genThueMorse():
    for n in itertools.count():
        yield (1 if bin(n).count('1')%2 else 0)

rawDescription: Is this an efficient way to generate the Thue-Morse sequence in Python?


code:
lst = ['abcd1234','abcdabcd1234','gqweri7890','poiupoiupoiupoiu7890']
d = {} # to keep the longest items for digits.
for item in lst:
    key = item[-4:] # last 4 characters
    d[key] = max(d.get(key, ''), item, key=len)
d.values() # list(d.values()) in Python 3.x

rawDescription: Filter List by Longest Element Containing a String


code:
import pip

def install(package):
    pip.main(['install', package])

# Example
if __name__ == '__main__':
    install('argh')

rawDescription: Installing python module within code

description: Installing python module within code


rawDescription: Is there a function to return all single letter colors in Matplotlib?


code:
from functools import partial

if (condition):
    RV = partial(np.random.normal, loc=avg, scale=stdev)
else:
    RV = partial(np.random.exponential, scale=scale)

rawDescription: Python code for polymorphism with random number generator


code: ind = [uberdata.index(i) for i in order]

rawDescription: Can someone explain implicit "for loops" to me?


code:
foo = []
found = False
for i, tag in enumerate(content):
    if content[i].text == 'Example':
        found = True
        foo.append('Example')
        break
    else:
        continue
if not found:
    foo.append('Not Example')

rawDescription: Python beautiful soup select text

description: Python beautiful soup select text


code:
size = 0
for line in f1:
  if str(line) == '</Service>\n':
    break
  else:
    f2.write(line)
    size += len(line)
    print('size = ' + str(size))

rawDescription: After writing to a file, why does os.path.getsize still return the previous size?


code:
sel = Selector(response)

item['Heading'] = sel.xpath('//*[@id="main1"]/div[1]/div[1]/div/div[2]/div[2]/div/div[1]/h2/span/text()').extract()
item['Content'] = sel.xpath('//*[@id="main1"]/div[1]/div[1]/div/div[2]/div[2]/div/p/text()').extract()

rawDescription: Python Crawler is unable to scrape the required element


code:
def getFitsWithTag(tagID, ownerID=None, where=None, eager=None):
    # ...
    fits = (saveddata_session.query(Fit)
            .join(fit_tags).filter(fit_tags.c.tagID == tagID) # @note: add me
            .options(*eager).filter(filter)
            ).all()
    # ...
    return fits

rawDescription: Querying many-to-many in SQL Alchemy

description: Querying many-to-many in SQL Alchemy


code:
#! /usr/bin/python

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "my@email.com"
you = "your@email.com"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\

Hi!

       How are you?

       Here is the link you wanted.

"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()

rawDescription: Sending HTML email using Python

description: Sending HTML email using Python


code:
from traits.api import HasStrictTraits, Int, String
from traitsui.api import Item
from traitsui.qt4.extra.qt_view import QtView

class MinimalWorkingExample(HasStrictTraits):
    name = String
    age = Int

    def traits_view(self):
        style_sheet_name = '''
            QLineEdit { background: yellow }
            '''
        style_sheet_age = '''
            QLineEdit { background: green }
            '''

        return QtView(
            Item('object.name', style_sheet=style_sheet_name),
            Item('object.age', style_sheet=style_sheet_age),
        )

if __name__ == '__main__':
    mwe = MinimalWorkingExample(name='Steven', age=32)
    mwe.configure_traits()

rawDescription: How can I use a Qt4 id or class selector in the style sheet with TraitsUI?

description: Use a Qt4 id or class selector in the style sheet with TraitsUI


code:
import numpy as np

@np.vectorize
def colorUp(x):
    return 'b' if x <=5.0 else 'r'

# Each scatterplot requires two arrays. You are only passing one;
# I am assuming that this would be the second array passed into
# each '.scatter' call
second_array = np.arange(df.shape[0])

fig, ax = plt.subplots(4, 5)
for i, column in enumerate(selection):
    if column in df.columns:
        ax[i % 4, i / 4].scatter(df[column], second_array, c = colorUp(df[column]))
plt.show()

rawDescription: How to make 18 separate scatterplots for 18 different columns from the same pandas Dataframe?

description: Make 18 separate scatterplots for 18 different columns from the same pandas Dataframe


code:
from pytun import TunTapDevice, IFF_TUN, IFF_NO_PI
tun = TunTapDevice(name="vpn",flags=(IFF_TUN | IFF_NO_PI))

rawDescription: Packets larger than MTU arriving on TUN interface


code:
from itertools import chain
foo = [0]
for i in (1, 2):
        bar = (range(a, a+i) for a in foo)
        foo = chain.from_iterable(bar)

i = 10
list(foo)

rawDescription: Python: Weird behavior of itertools.chain.from_iterable


code:
import Tkinter as tk
import re

class CustomText(tk.Text):
    '''A text widget with a new method, HighlightPattern

    example:

    text = CustomText()
    text.tag_configure("red",foreground="#ff0000")
    text.HighlightPattern("this should be red", "red")

    The HighlightPattern method is a simplified python
    version of the tcl code at http://wiki.tcl.tk/3246
    '''
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

    def HighlightPattern(self, pattern, tag, start="1.0", end="end", regexp=True):
        '''Apply the given tag to all text that matches the given pattern'''

        start = self.index(start)
        end = self.index(end)
        self.mark_set("matchStart",start)
        self.mark_set("matchEnd",end)
        self.mark_set("searchLimit", end)

        count = tk.IntVar()
        while True:
            index = self.search(pattern, "matchEnd","searchLimit",count=count, regexp=regexp)
            if index == "": break
            self.mark_set("matchStart", index)
            self.mark_set("matchEnd", "%s+%sc" % (index,count.get()))
            self.tag_add(tag, "matchStart","matchEnd")

def aboutF():
     win = tk.Toplevel()
     win.title("About")
     about = '''Top/bottom 3 - Reports only the top/bottom 3 rows for a param you will later specify.
        Set noise threshold - Filters results with deltas below the specified noise threshold in ps.
        Sort output - Sorts by test,pre,post,unit,delta,abs(delta).
        Top 2 IDD2P/IDD6 registers - Reports only the top 2 IDD2P/IDD6 registers.
        Only critical registers - Reports only critical registers.
        Use tilda output format - Converts the output file from csv to tilda.
        Use html output format - Converts the output file from csv to html.'''
     about = re.sub("\n\s*", "\n", about) # remove leading whitespace from each line
     t=CustomText(win, wrap="word", width=100, height=10, borderwidth=0)
     t.tag_configure("blue", foreground="blue")
     t.pack(sid="top",fill="both",expand=True)
     t.insert("1.0", about)
     t.HighlightPattern("^.*? - ", "blue")
     tk.Button(win, text='OK', command=win.destroy).pack()

root=tk.Tk()
aboutF()
root.mainloop()

rawDescription: Python Tkinter Help Menu

description: Python Tkinter Help Menu


code:
class Event(models.Model):
    ...
    vehicles = models.ManyToManyField(Vehicle, through='EventVehicle')

class EventVehicle(models.Model):
    event = models.ForeignKey(Event)
    vehicle = models.ForeignKey(Vehicle)
    loaded = models.IntegerField(default=2)

rawDescription: Many to many relationship with Django, Python


code:
class Link:
    empty = ()

    def __init__(self, first, rest=empty):
        assert rest is Link.empty or isinstance(rest, Link)
        self.first = first
        self.rest = rest

def print_link(link):
    """Print elements of a linked list link.
    """
    print('<' + helper(link).rstrip() +'>')

def list_to_link(lst):
    """Takes a Python list and returns a Link with the same elements.
    """
    if len(lst) == 1:
        return Link(lst[0])
    return Link(lst[0], list_to_link(lst[1:]))  # <<<< RECURSIVE

def helper(link):
    if isinstance(link.first, Link):
        first = '<' + helper(link.first).rstrip() + '>'  # <<<< RECURSIVE
    else:
        first = str(link.first)

    if link.rest != Link.empty:
        return first + ' ' + helper(link.rest)  # <<<< RECURSIVE
    else:
        return first + ' '

def main():
    """ Below are taken from sample in function prototype comments
    """
    link = list_to_link([1, 2, 3])
    print_link(link)

    link = Link(1, Link(2, Link(3)))
    print_link(link)
    link1 = Link(1, Link(Link(2), Link(3)))
    print_link(link1)
    link1 = Link(3, Link(Link(4), Link(5, Link(6))))
    print_link(link1)

if __name__ == '__main__':
    main()

rawDescription: Converting a list to a linked list

description: Converting a list to a linked list


code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtGui, QtCore

class MyWindow(QtGui.QTabWidget):
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.setStyleSheet("""
            QTabBar::tab {
                color: #FF0000;
            }
        """)

        for tabNumber in range(3):
            widget = QtGui.QLabel(self)
            widget.setText("This is widget #{0}".format(tabNumber))

            self.addTab(widget, "Tab {0}".format(tabNumber))

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())

rawDescription: Is there a way, in PySide to style the tab buttons on a QtabWidget?


code:
import sys
import os
import os.path
import re
import itertools

#generator function to merge sound and word files
def takeuntil(iterable, stop):
    for x in iterable:
        yield x
        if x[1] == stop:
            break

def process_words_and_sounds(word_file, sound_file):
    #open word and sound files
    total_words = 0
    with open(word_file) as unsplit_words, open(sound_file) as unsplit_sounds:
        sounds = (line.split() for line in unsplit_sounds)
        words = (line.split() for line in unsplit_words)
        output = [
            (word, " ".join(sound for _, _, sound in
                            takeuntil(sounds, stop)))
            for start, stop, word in words
            ]
        for x in output:
            total_words += 1
    return total_words, output

for root, dir, files in os.walk(sys.argv[1]):
    words = [ os.path.join( root, f ) for f in files if f.endswith('.WRD')]
    phones = [ os.path.join( root, f ) for f in files if f.endswith('.PHN')]
    phones.sort()
    words.sort()
    files = zip(words, phones)
    # print files

output = []
total_words = 0
for word_sounds in files:
    word_file, sound_file = word_sounds
    word_count, output_subset = process_words_and_sounds(word_file, sound_file)
    total_words += word_count
    output.extend( output_subset )

#open a dictionary file and create subset of words
class_defintion = re.compile('([1-2] [lnr] t en|[1-2] t en)')
with open('TIMITDIC.TXT') as w_list:
    entries = (line.split(' ', 1) for line in w_list)
    comp_set = [ x[0] for x in entries if class_defintion.search(x[1]) ]

#extract words from above into list of words in dictionary set
glottal_environments = [ x for x in output if x[0] in comp_set ]

rawDescription: Python: Compare files with similar names (recursively)


rawDescription: Why I cannot import a library that is in my pip list?


rawDescription: How to plot image data versus time with matplotlib

description: Plot image data versus time with matplotlib


code:
def index():
    if request.vars.random:
        request.vars.itemId = generate_random_id()
    form = FORM(DIV(INPUT(_name='itemId', _type='text',
        _value=request.vars.itemId if request.vars else '',
        requires=[IS_NOT_EMPTY(), IS_LENGTH(maxsize=12)]),
        INPUT(_type='submit', _value='search', _name='search'),
        INPUT(_type='submit', _value="random_search", _name='random')))
    return dict(message=form.process())

rawDescription: How to set a form's input text to a specific value in web2py when the form is submitted?

description: Set a form's input text to a specific value in web2py when the form is submitted


code:
from tkinter import *
from tkinter import ttk

def write_text():
    text = edit.get('1.0', END)
    with open("DATA/Test.txt", "w") as f:
        f.write(text)

root = Tk()
root.title("This May Help")
root.geometry("600x600")

edit = Text(root, width=80, height=25, wrap=NONE)
edit.insert('1.0', '[enter text]')
edit.grid(column=0, row=0, sticky=(N,W,E,S))

yscroll = ttk.Scrollbar(root, orient=VERTICAL, command=edit.yview)
yscroll.grid(column=1, row=0, sticky=(N,S))
edit['yscrollcommand'] = yscroll.set

xscroll = ttk.Scrollbar(root, orient=HORIZONTAL, command=edit.xview)
xscroll.grid(column=0, row=1, sticky=(W,E))
edit['xscrollcommand'] = xscroll.set

write_button = Button(text="Write", command=write_text)
write_button.grid(column=0, row=2)

rawDescription: What is a way to convert text to a string in Python 3.3.0


code:
from collections import namedtuple
Info = namedtuple('Info', ['name', 'location', 'region', 'idcode'])
information =[
    ['BlueLake1','MO','North','98812'],
    ['BlueLake2','TX','West','65343'],
    ['BlueLake3','NY','sales','87645'],
    ['RedLake1','NY','sales','58923'],
    ['RedLake2','NY','sales','12644'],
    ['RedLake3','KY','sales','32642']
]
[Info(*x) for x in information]

rawDescription: How Turning List into Class Object for Flask Templating


code:
xlmodule = book.VBProject.VBComponents.Add(1) # http://support.microsoft.com/kb/282830 if this line throws an error
xlmodule.CodeModule.AddFromString('Public Sub AnotherCalculateFull() \n\
                                               Application.CalculateFull \n\
                                               End Sub')

rawDescription: How to F9 Excel book using Python?

description: F9 Excel book using Python


code:
import os
os.getcwd()
os.chdir(r'/home/username/Downloads')
os.getcwd()

rawDescription: How do i change the location directory of python open document?

description: Change the location directory of python open document


code:
def main():
    intro()
    choice = question()
    processing(choice)

def intro():

    print("program to draw a national flag.")
    print()

def processing(choice):

    for f in choice:
        if choice == "1":
            unitedStates()

        elif choice == "2":
            italy()

        elif choice == "3":
            germany()

def question():

    while True:

        choice = ()
        print("Please choose a flag:")
        print("     1, for United States;")
        print("     2, for Italy;")
        print("     3, for Germany;")

        choice = input("-->", )

        if choice[0] >= "1" and choice[0] <= "5" and len(choice) == 1:
            break
        print("Choice must be, between 1-5, not ", choice + ".")
        print("Try again.")
        print()

    print()
    return choice

#========================================================
#      Flag functions added by Michael
#========================================================

def unitedStates():

    for i in range(1,5):
        print((" * * *" * 2), ("X" * 34))
        print("* * * " * 2)

    print(" * * *" * 2, "X" * 34)

    for i in range(4):
        print()
        print("X" * 47)
    print()

def italy():

    green(14, "G")
    white(14, "W")
    red(14, "R")
    for i in range(15):

        print(green(15, "G") + white(15, ".") + red(15, "R"))
    print()

def green(gn, gch):

    pg = gn * gch

    return pg

def white(wn, wch):

    pw = wn * wch

    return pw

def red(rn, rch):

    pr = rn * rch
    return pr

def germany():

    black(47, "G")
    red(47, "W")
    yellow(47, "R")
    for cBlack in range(5):
        print(black(47, "B"))
    for cRed in range(5):
        print(red(47, "`"))
    for cYellow in range(5):
        print(yellow(47, "Y"))

def black(gn, gch):

    pg = gn * gch

    return pg

def red(wn, wch):

    pw = wn * wch

    return pw

def yellow(rn, rch):

    pr = rn * rch
    return pr

main() #call main here

rawDescription: Python user selected function

description: Python user selected function


code:
import itertools as it
import re

three_pat=re.compile(r'\w{3}')
text = "Hello world. It is a nice day today. Don't you think so?"
for key,group in it.groupby(text.split(),lambda x: bool(three_pat.match(x))):
    if key:
        group=list(group)
        for i in range(0,len(group)-1):
            print(' '.join(group[i:i+2]))

# Hello world.
# nice day
# day today.
# today. Don't
# Don't you
# you think

rawDescription: python regex finding all groups of words

description: Python regex finding all groups of words


code:
S = itertools.product('AaBb', repeat=n)
SS = itertools.imap(lambda x: ''.join(x), S)
SSS = itertools.ifilter(inv, SS)

rawDescription: Finitely generated words

description: Finitely generated words


code: c = [l for l in a if [] not in l]

rawDescription: Removing list having empty list

description: Removing list having empty list


code:
rng = pd.date_range('12/1/2012', periods=4, freq='D')
s = pd.Series(pd.np.random.randn(len(rng)), index=rng)
s
dict(zip(s.index.format(), s))

rawDescription: How to convert Pandas time series into a dict with string key

description: Convert Pandas time series into a dict with string key


rawDescription: Printing a python dict without the unicode


code:
f = open(r"temp.txt")
[[c for c in line] for line in f]

rawDescription: nesting python list comprehensions to construct a list of lists

description: Nesting python list comprehensions to construct a list of lists


code:
import logging
from cherrypy import _cplogging
from logging import handlers
import cherrypy

class HelloWorld:
    @cherrypy.expose
    def index(self):
        return "Hello world!"

    @cherrypy.expose
    def link(self):
        #print HelloWorld.c

        #print self.j
        return "link"

    @cherrypy.expose
    def link2(self):
        return "link2"

if name == 'main' :
    applicationLogFileHandler = handlers.TimedRotatingFileHandler('rot_access_file', "midnight", 1)
    applicationLogFileHandler.setLevel(logging.DEBUG)
    applicationLogFileHandler.setFormatter(_cplogging.logfmt)
    cherrypy.log.access_log.addHandler(applicationLogFileHandler)

    applicationLogFileHandler = handlers.TimedRotatingFileHandler('rot_error_file', "midnight", 1)
    applicationLogFileHandler.setLevel(logging.DEBUG)
    applicationLogFileHandler.setFormatter(_cplogging.logfmt)
    cherrypy.log.error_log.addHandler(applicationLogFileHandler)

    cherrypy.quickstart(HelloWorld())

rawDescription: cherrypy: python how to create separate request log files for everyday with the help of log rotator

description: Cherrypy: python how to create separate request log files for everyday with the help of log rotator


code:
np.all(np.diff(x) > 0)
np.all(np.diff(y) > 0)

rawDescription: numpy's interp function - how to find a value of x for a given value of y?

description: Numpy's interp function - how to find a value of x for a given value of y


code:
import cherrypy

class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

cherrypy.quickstart(HelloWorld())

rawDescription: Python handing of Web Forms

description: Python handing of Web Forms


code:
d = defaultdict(int)
d['a'] += 1
d
d.default_factory = None
d['b'] += 2

rawDescription: Exposing `defaultdict` as a regular `dict`


code: d = dict(zip(list1, list2))

rawDescription: Python dictionary with list elements as keys and the elements of another list as the values?


code: sorted_qs = sorted(chain(fqs, sqs), key=lambda obj: obj.added)

rawDescription: sort two joined querysets - django

description: Sort two joined querysets - django


code:
for item in a:
    bitem = ''
    for chr in item:
        if chr != i:
            bitem += '-'
        else:
            bitem += chr
    b.append(bitem)

rawDescription: List Iteration and editing list's items, Please improve my code


code:
import StringIO
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

plt.plot([1,2,3,4])
imgdata = StringIO.StringIO()
plt.savefig(imgdata, format='png')
imgdata.seek(0)
mpimg.imread(imgdata)

rawDescription: Pylab - use plot() result as image directly


code:
def executeCommandWithOtherUser(command):
  p = pexpect.spawn('su', ['otherUser'])
  p.expect('Password:')
  p.sendline('1234')
  prompt = r'\$'
  p.expect(prompt)
  p.sendline(command)
  p.expect(prompt)
  p.close()
  return

rawDescription: How to make pexpect commands execute without interact() in my program

description: Make pexpect commands execute without interact() in my program


code:
import numpy as np

a = np.fromfile('A.csv', dtype=np.int)
b = np.fromfile('B.csv', dtype=np.int)
c = np.fromfile('C.csv', dtype=np.int)

d = (a + b + c) / 3.0

d.tofile('D.csv')

rawDescription: Computing averages of records from multiple files with python


code:
import pylab as pl

data = pl.loadtxt("myfile.txt")

pl.figure(figsize=(14,6))
pl.plot(data[:,1], data[:,0], "b")
pl.plot(data[:,2], data[:,0], "r")
pl.plot(data[:,3], data[:,0], "r")

pl.show()

rawDescription: Plotting three data sets on a single plot using matplotlib


code:
[pytest]
DJANGO_SETTINGS_MODULE = test_settings

rawDescription: Using different database with pytest

description: Using different database with pytest


code:
df = pandas.read_table('gradStat_mmn.tdf')
df.ix[0:10]
df['mean'].dtype
df['mean'][0]

rawDescription: How do I convert a column from a pandas DataFrame from str (scientific notation) to numpy.float64?

description: Convert a column from a pandas DataFrame from str (scientific notation) to numpy.float64


code:
import re
input = "
This is a sample text. sydney.edu.au/ somthing else text.
"
regex = "((?:https?://)?(?:www\.)?[a-zA-Z]+\.[a-z]+[^ ]*)"
re.sub(regex, '\\1', input)

rawDescription: To check if it is URL in text and if yes then edit it with href tag Using Python


code:
import numpy as np
import datetime as dt
import pylab as plt
import matplotlib.dates as dates

t0 = dt.date.today()
t1 = t0+dt.timedelta(days=10)

times = np.linspace(dates.date2num(t0), dates.date2num(t1), 10)
dt = times[-1]-times[0]
price =  100 - (times-times.mean())**2
dp = price.max() - price.min()
volume = np.linspace(1, 100, 10)

tgrid = np.linspace(times.min(), times.max(), 100)
pgrid = np.linspace(70, 110, 100)
tgrid, pgrid = np.meshgrid(tgrid, pgrid)
heat = np.zeros_like(tgrid)

for t,p,v in zip(times, price, volume):
    delt = (t-tgrid)**2
    delp = (p-pgrid)**2
    heat += v/( delt + delp*1.e-2 + 5.e-1 )**2

fig = plt.figure()
ax = fig.add_subplot(111)
ax.pcolormesh(tgrid, pgrid, heat, cmap='gist_heat_r')

plt.scatter(times, price, volume, marker='x')

locator = dates.DayLocator()
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(dates.AutoDateFormatter(locator))
fig.autofmt_xdate()

plt.show()

rawDescription: Generate a heatmap in MatPlotLib using a scatter data set


code:
base_url = "http://example.com/something/?page=%d"
results_per_page = 60

div = page.xpath("//div[contains(@class, 'b-tabs-utility')]")[0].text
last_pg = int(div.split()[-2]) / results_per_page
for i in xrange(last_pg):
    r = requests.get(base_url % i)

rawDescription: Handling pagination in lxml

description: Handling pagination in lxml


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

fig = plt.figure()
ax = fig.add_subplot(111)
ax.quiver((0,0), (0,0), (1,0), (1,3), units = 'xy', scale = 1)
plt.axis('equal')
plt.xticks(range(-5,6))
plt.yticks(range(-5,6))
plt.grid()
plt.show()

rawDescription: Understanding Matplotlib's quiver plotting


code:
from matplotlib import pyplot as plt

f = plt.figure()
ax = f.gca()
f.show()

for i in range(10):
    ax.plot(i, i, 'ko')
    f.canvas.draw()
    raw_input('pause : press any key ...')
f.close()

rawDescription: how do I redraw an image using python's matplotlib?

description: Redraw an image using python's matplotlib


code:
def iter_column_row():
    for i in range(self.getColumnCount()):
        for j in range(self.getRowCount()):
            yield self.env[j][i]

rawDescription: Python __iter__ and next() functions

description: Python __iter__ and next() functions


code:
# Answer to question 1 - just use the built-in functionality of lists.
#
# There is no need to use variables when lists let you do so much more
#   in a quick and organised fashion.
lines = []
for line in open_file:
   lines.append(line)

rawDescription: Python - assign lists within nest to variable


rawDescription: Make a 2D out of 1D numpy array

description: Make a 2D out of 1D numpy array


code:
def get_lock(name):
    fd = open('/tmp/' + name, 'w')

    try:
        flock(fd, LOCK_EX | LOCK_NB)  # open for exclusive locking
        return fd
    except IOError as e:
        logger.warn('Could not get the lock for ' + str(name))
        fd.close()
        return None

def release_lock(fd):
    sleep(2)  # extend the time a bit longer in the hopes that it blocks the other proc
    flock(fd, LOCK_UN)
    fd.close()

rawDescription: Single apscheduler instance in Flask application


code:
dat = Table(dat, masked=True)  # Convert to a masked table
for col in dat.columns.values():
    col.mask = np.isnan(col) | (col == 0.0)

rawDescription: implementing masking in python Astropy tables

description: Implementing masking in python Astropy tables


code:
from django.core import serializers

def get_product(request, pk):
    return HttpResponse(serializers.serialize("xml", Product.objects.filter(pk=pk)))

rawDescription: Prepopulate tabularinline with value from related lookup in manytomany field


code:
styles = (easyxf(), easyxf('pattern: pattern solid, fore_color gray25'))

for rx, record in enumerate(records, start=1):
    style = styles[rx % 2]  # Do your own conditional style selection here
    for cx, value in enumerate(record):
        ws.write(rx, cx, value, style)

rawDescription: set_style in Python xlwt library does not work for cells containing text

description: Set_style in Python xlwt library does not work for cells containing text


code:
import sys
import fileinput
import os
import os.path
import re

# Descriptions: iterates over files in source directory, removes whitespace characters and saves to destination directory.

print ('Source Directory:', str(sys.argv[1]))
print ('Destination Directory:', str(sys.argv[2]))

for i in os.listdir(sys.argv[1]):
    fullSource = (os.path.join(sys.argv[1], i))
    fullDestination = (os.path.join(sys.argv[2], i))
    newfile = open(fullDestination, "x")
    for line in fileinput.input(fullSource, mode='rb'):  # explicite binary mode
        line = line.decode('latin1')   # convert to string in Python3
        matchObj = re.search('(?<!\r)\n', line)
        if matchObj:
            newfile.write(line.rstrip('\r\n'))
        else:
            newfile.write(line)
    newfile.close
    print ("created " + fullDestination)

rawDescription: Detecting Line feeds with Python

description: Detecting Line feeds with Python


code:
class CustomConceptQuerySetTest(TestCase):
    @classmethod
    def setUpClass(cls):
        ...

rawDescription: Retaining items created during setup of a python test


code:
#imports left out, code not tested - just to point you in the right direction
class MyDocTestRunner(DocTestRunner):
    def run(self, test, compileflags=None, out=None, clear_globs=True):
        if out is None:
            handler = None
        else:
            handler = StreamHandler(out)
        logger = logging.getLogger() # root logger (say)
        if handler:
            logger.addHandler(handler)
        try:
            DocTestRunner.run(self, test, compileflags, out, clear_globs)
        finally:
            if handler:
                logger.removeHandler(handler)
                handler.close()

rawDescription: use doctest and logging in python program

description: Use doctest and logging in python program


code:
#!/bin/python
import tornado.web
import tornado.http
import tornado.escape
import functools
import logging
import urllib

import Author

def upgrade_lp_login_cookie(method):
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        if not self.current_user and self.get_cookie('lp_login'):
            self.upgrade_lp_login(self.async_callback(method, self, *args, **kwargs))
        else:
            return method(self, *args, **kwargs)
    return wrapper

class BaseHandler(tornado.web.RequestHandler):
    def get_current_user(self):
        user_id = self.get_secure_cookie("user")
        if user_id:
            return Author.objects.get(id=int(user_id))

    def upgrade_lp_login(self, callback):
        lp_login = self.get_cookie("lp_login")
        try:
            username, hashed_password = urllib.unquote(lp_login).rsplit(',',1)
        except ValueError:
            # check against malicious clients
            logging.info('invalid lp_login cookie %s' % lp_login)
            return callback()

        url = "http://%(host)s/api/user/username/%s/%s" % (self.request.host,
                                                        urllib.quote(username),
                                                        urllib.quote(hashed_password))
        http = tornado.httpclient.AsyncHTTPClient()
        http.fetch(url, self.async_callback(self.finish_upgrade_lp_login, callback))

    def finish_upgrade_lp_login(self, callback, response):
        answer = tornado.escape.json_decode(response.body)
        # username = answer['username']
        if answer['has_valid_credentials']:
            # set for self.current_user, overriding previous output of self.get_current_user()
            self._current_user = Author.objects.get(email=answer["email"])
            # set the cookie for next request
            self.set_secure_cookie("user", str(self.current_user.id))

        # now chain to the real get/post method
        callback()

    @upgrade_lp_login_cookie
    def get(self):
        self.render('template.tmpl')

rawDescription: Authentication using cookie key with asynchronous callback


code:
while time.time() < start + secs and Current_State is not True:
    Current_State = GPIO.input(GPIO_PIR)
    if Current_State==1:
        takePics(3)

rawDescription: while conditions not meeting in python

description: While conditions not meeting in python


code:
import ast
s = '''(0, 0), (0, 2), ...'''
result = ast.literal_eval('({0})'.format(s))

rawDescription: Reading comma separated tuples from a file in python


code:
strings = []
strings.append('string')
strings.append('other_string')
...
','.join(strings)

rawDescription: What is the fastest performance tuple for large data sets in python?


code:
new = []
a
for i in a:
    for j in i:
        new.append(j)

new
#If you want result back in tuple

tuple(new)

rawDescription: How to remove formatting in python

description: Remove formatting in python


code:
q = '''SELECT * FROM MY_TABLE WHERE FIELD LIKE ?'''
some_query_value = '%test%'
cursor.execute(q, [some_query_value])

rawDescription: Python SQLite how do you do partial searches using '?' placeholders?


code: ('key1', 'val1') in d.viewitems()

rawDescription: conditionals with dicts Python

description: Conditionals with dicts Python


rawDescription: Unexpected eigenvectors in numPy

description: Unexpected eigenvectors in numPy


code:
import itertools
T=[[1, 2, 3], [4, 5], [6]]
result = list(itertools.product(*T)) # result contains your desired list

rawDescription: how to access elements in lists of list in out wise in python

description: Access elements in lists of list in out wise in python


code:
with open('filename', 'rb') as infile:
    with open('filename.out', 'wb') as outfile:
        for j, line in enumerate(infile):
            if j == 0: #skip first line
                continue
            listLine = line.split(' ')
            listLine.insert(3, thingToInsert) #elements 4-6 are now elements 5-7
            listLine = (el for i, el in enumerate(listLine) if i>4 and i<=7)
            outfile.write(' '.join(listLine))

rawDescription: Add element to line

description: Add element to line


code:
r'''(?:        # Non-capturing group
      "[^"]*"  # A quote, followed by not-quotes, followed by a quote
      |        # or
      [^"#]    # not a quote or a hash
    )          # end group
    *          # Match quoted strings and not-quote-not-hash characters until...
    (#)        # the comment begins!
'''

rawDescription: Removing hash comments that are not inside quotes


code:
gold = 0

def display():
    calculate()
    calculate()

def calculate():
    global gold
    gold += 10
    gold = gold + 10
    print(gold)

display()

rawDescription: Why doesn't this function update the variable properly?


code:
import operator
inverted = dict((v,k) for k,v in sorted(d.iteritems(), key=operator.itemgetter(1)))

rawDescription: Inverting Dictionaries in Python

description: Inverting Dictionaries in Python


code:
import re
s = 'This is A test of a TREE, HOUSE'
re.findall(r'\b[A-Z0-9]{1,4}\b', s)

rawDescription: Create a python regular expression for finding 1 to 4 chars uppercase


code:
import re

s1 = '#define VKU_BS_MAJOR_VERSION_S "2"'
s2 = '#define VKU_BS_MINOR_VERSION_S "55"'
s3 = '#define VKU_BS_B123UILD_N456UMBE789R_S "10"'

re.findall("\d+", s1)
#['2']

re.findall("\d+", s2)
#['55']

r.findall("\d+", s3)
#['123', '456', '789', '10']

rawDescription: Python regular expressions - get numbers


code:
def start():
     print("Hello world!")
     name=input("Please enter your name: ")
     print("Hi {0}".format(name))
     run=input("type | True | to run the program: ").capitalize()
     if run== "True":
         main() #the user typed true, so lets jump to your main function
     else:
         print("You need to enter | True | to run the program")

def main():
    print("1 = Add")
    print("2 = Subtract")
    print("3 = Times")
    print("4 = Divide")
    print("5 = Quit program")
    calc=int(input("enter number of choise: "))

start() #the program never runs your start function without this line

rawDescription: I am trying to set a value to 'true' so i can start a program


code:
#general format
from your.package.name import some_delete_function

@route(r"/api/v2/tokens/([^/]+)")
class TokenV2HandlerGet(APIBaseHandler):
    def delete(self, token):
        """Delete a token
        """
        some_delete_function(arg1,arg2,etc)

#assuming all of this is in the same parent dir
from pushservices import apns as some_delete_function

rawDescription: Python: calling function inside a class inside a route from another file


code:
from pandas.io.excel import read_excel
import pandas as pd
import numpy as np

url = 'http://www.bankofengland.co.uk/statistics/Documents/yieldcurve/uknom05_mdaily.xls'

# check the sheet number, spot: 9/9, short end 7/9
spot_curve = read_excel(url, sheetname=8)
short_end_spot_curve = read_excel('uknom05_mdaily.xls', sheetname=6)

# preprocessing spot_curve
# ==============================================
# do a few inspection on the table
spot_curve.shape
spot_curve.iloc[:, 0]
spot_curve.iloc[:, -1]
spot_curve.iloc[0, :]
spot_curve.iloc[-1, :]
# do some cleaning, keep NaN for now, as forward fill NaN is not recommended for yield curve
spot_curve.columns = spot_curve.loc['years:']
spot_curve.columns.name = 'years'
valid_index = spot_curve.index[4:]
spot_curve = spot_curve.loc[valid_index]
# remove all maturities within 5 years as those are duplicated in short-end file
col_mask = spot_curve.columns.values > 5
spot_curve = spot_curve.iloc[:, col_mask]

# now spot_curve is ready, check it
spot_curve.head()
spot_curve.tail()
spot_curve.shape

spot_curve.shape
Out[184]: (2715, 40)

# preprocessing short end spot_curve
# ==============================================
short_end_spot_curve.columns = short_end_spot_curve.loc['years:']
short_end_spot_curve.columns.name = 'years'
valid_index = short_end_spot_curve.index[4:]
short_end_spot_curve = short_end_spot_curve.loc[valid_index]
short_end_spot_curve.head()
short_end_spot_curve.tail()
short_end_spot_curve.shape

short_end_spot_curve.shape
Out[185]: (2715, 60)

# merge these two, time index are identical
# ==============================================
combined_data = pd.concat([short_end_spot_curve, spot_curve], axis=1, join='outer')
# sort the maturity from short end to long end
combined_data.sort_index(axis=1, inplace=True)

combined_data.head()
combined_data.tail()
combined_data.shape

# deal with NaN: the most sound approach is fit the non-arbitrage NSS curve
# however, this is not currently supported in python.
# do a cubic spline instead
# ==============================================

# if more than half of the maturity points are NaN, then interpolation is likely to be unstable, so I'll remove all rows with NaNs count greater than  50
def filter_func(group):
    return group.isnull().sum(axis=1) <= 50

combined_data = combined_data.groupby(level=0).filter(filter_func)
# no. of rows down from 2715 to 2628
combined_data.shape

combined_data.shape
Out[186]: (2628, 100)

from scipy.interpolate import interp1d

# mapping points, monthly frequency, 1 mon to 25 years
maturity = pd.Series((np.arange(12 * 25) + 1) / 12)
# do the interpolation day by day
key = lambda x: x.date
by_day = combined_data.groupby(level=0)

# write out apply function
def interpolate_maturities(group):
    # transpose row vector to column vector and drops all nans
    a = group.T.dropna().reset_index()
    f = interp1d(a.iloc[:, 0], a.iloc[:, 1], kind='cubic', bounds_error=False, assume_sorted=True)
    return pd.Series(maturity.apply(f).values, index=maturity.values)

# this may take a while .... apply provides flexibility but spead is not good
cleaned_spot_curve = by_day.apply(interpolate_maturities)

# a quick look on the data
cleaned_spot_curve.iloc[[1,1000, 2000], :].T.plot(title='Cross-Maturity Yield Curve')
cleaned_spot_curve.iloc[:, [23, 59, 119]].plot(title='Time-Series')

rawDescription: Restructuring Dataframe in Python

description: Restructuring Dataframe in Python


code:
def create_data_structure(iterable):
    data = {}
    for (index,item) in enumerate(iterable):
        if item not in data:
            data[item] = linked_list(index) # Index is first node
        else:
            data[item].append(index) # Index is last node
    return data

data = create_data_structure(my_list)
for i,item in enumerate(mylist):
    process(item, mylist[data[item][i].next()])

rawDescription: Sequential search takes o(n^2) time. Want it to be either O(1) or O(log n)


code:
def set_extra_headers(self, path):
    self.set_header("Cache-control", "no-cache")

rawDescription: Disable static file caching in Tornado

description: Disable static file caching in Tornado


code:
import jinja2
env = jinja2.Environment()
env.globals.update(zip=zip)
# use env to load template(s)

rawDescription: zip(list1, list2) in Jinja2?

description: Zip(list1, list2) in Jinja2


code: y = lambda symbol: 'X' if symbol==True else 'O' if symbol==False else ' '

rawDescription: Multiple if statements in a lambda function


rawDescription: How to parse somewhat wrong JSON with Python?

description: Parse somewhat wrong JSON with Python


code:
LL = ["this","is","a","sample","list"]
dict(enumerate(LL))

rawDescription: python: dictionary comprehension with list index

description: Python: dictionary comprehension with list index


code:
def main():

    print("Last, \tFirst")
    print

    name_list = get_names()
    print_list(name_list)
    new_file(name_list)
    search_list(name_list)

def get_names():
    # open the data file
    infile = open('names.txt', 'r')

    # read all the lines from the file
    name_list = infile.read().split('\n')

    #close the input file
    infile.close()

    #print data read into memory
    print(name_list)

    return(name_list)

#def print list
def print_list(name_list):
    #print the data
    for name in name_list:
        print (name)
    return(name)

#def new_file
def new_file(name_list):
    outfile = open('sorted_names.txt' ,'w')
    for item in name_list:
        outfile.write(item + '\n')

    outfile.close()

#def search_list
def search_list(name_list):
    again = 'Y'
    while again.upper()== 'Y':
        name = raw_input("What name would you like to look for? :")
        try:
            name_index = name_list.index(name)
            print (name), (" was found in the list at index point: "), name_index

        except ValueError as err:
            print (name), (" was not found in the list.")

            print ("Would you like to search for another name?")
            again = raw_input("Would you like to run the program again? [y/n]") == 'y'

# execute the main function
main()

rawDescription: importing a file, printing data, searching then printing again - PYTHON

description: Importing a file, printing data, searching then printing again - PYTHON


code:
# Get parent of parent
import os, sys
pp = os.path.realpath(__file__)
for _ in range(3): pp = os.path.dirname(pp)
# Add np to path
sys.path.append(os.path.join(pp, 'util', 'src'))

# Import file
import Util1

# Call function
Util1.foo()

rawDescription: Python 3.4 importing a util class from another directory


code:
import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np

cdict = {
  'red'  :  ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
  'green':  ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
  'blue' :  ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}

cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)

data = 2*( np.sin(X) + np.sin(3*Y) )

def do_plot(n, f, title):
    #plt.clf()
    plt.subplot(1, 3, n)
    plt.pcolor(X, Y, f(data), cmap=cm, vmin=-4, vmax=4)
    plt.title(title)
    plt.colorbar()

plt.figure()
do_plot(1, lambda x:x, "all")
do_plot(2, lambda x:np.clip(x, -4, 0), "<0")
do_plot(3, lambda x:np.clip(x, 0, 4), ">0")
plt.show()

rawDescription: Set Colorbar Range in matplotlib

description: Set Colorbar Range in matplotlib


code:
for path in glob.glob(pattern):
    if os.path.ismount(path):
        print(path)  # Or do whatever else you want to do with the mounts.

rawDescription: Can i use a wildcard in os.path.ismount() in python

description: Use a wildcard in os.path.ismount() in python


code:
import scipy
import pylab
import scipy.cluster.hierarchy as sch

# Generate features and distance matrix.
x = scipy.rand(40)
D = scipy.zeros([40,40])
for i in range(40):
    for j in range(40):
        D[i,j] = abs(x[i] - x[j])

# Compute and plot dendrogram.
fig = pylab.figure()
axdendro = fig.add_axes([0.09,0.1,0.2,0.8])
Y = sch.linkage(D, method='centroid')
Z = sch.dendrogram(Y, orientation='right')
axdendro.set_xticks([])
axdendro.set_yticks([])

# Plot distance matrix.
axmatrix = fig.add_axes([0.3,0.1,0.6,0.8])
index = Z['leaves']
D = D[index,:]
D = D[:,index]
im = axmatrix.matshow(D, aspect='auto', origin='lower')
axmatrix.set_xticks([])
axmatrix.set_yticks([])

# Plot colorbar.
axcolor = fig.add_axes([0.91,0.1,0.02,0.8])
pylab.colorbar(im, cax=axcolor)

# Display and save figure.
fig.show()
fig.savefig('dendrogram.png')

rawDescription: Reordering matrix elements to reflect column and row clustering in naiive python


code:
s = "238 NEO Sports"
s.split(" ", 1)

rawDescription: Split a string only by first space in python


code:
from abc import ABCMeta, abstractproperty, abstractmethod

class MyInterface(object):
    __metaclass__ = ABCMeta

    @abstractmethod
    def required_method(self):
        pass

    @abstractproperty
    def required_property(self):
        pass

rawDescription: Is it a good idea to define properties in Python interfaces?


code:
with open('input') as f:
    sorted_file = sorted(f)

#save to a file
with open('output') as f:
    f.writelines(sorted_file)

#write to stdout
import sys
sys.stdout.writelines(sorted_file)

rawDescription: Sorting contents of a file

description: Sorting contents of a file


code:
# -*- coding: utf-8 -*-
import scrapy
from scrapy import Item, Field

class GagItem(Item):
    entry_id = Field()
    url = Field()
    votes = Field()
    comments = Field()
    title = Field()
    img_url = Field()

class FirstSpider(scrapy.Spider):

    name = "first"
    allowed_domains = ["9gag.com"]
    start_urls = ('http://www.9gag.com/', )

    last_gag_id = None
    COUNT_MAX = 30
    count = 0

    def parse(self, response):

        for article in response.xpath('//article'):
            gag_id = article.xpath('@data-entry-id').extract()
            ninegag_item = GagItem()
            ninegag_item['entry_id'] = gag_id[0]
            ninegag_item['url'] = article.xpath('@data-entry-url').extract()[0]
            ninegag_item['votes'] = article.xpath('@data-entry-votes').extract()[0]
            ninegag_item['comments'] = article.xpath('@data-entry-comments').extract()[0]
            ninegag_item['title'] = article.xpath('.//h2/a/text()').extract()[0].strip()
            ninegag_item['img_url'] = article.xpath('.//div[1]/a/img/@src').extract()
            self.last_gag_id = gag_id[0]
            self.count = self.count + 1
            yield ninegag_item

        if (self.count < self.COUNT_MAX):
            next_url = 'http://9gag.com/?id=%s&c=10' % self.last_gag_id
            yield scrapy.Request(url=next_url, callback=self.parse)

rawDescription: How to stop scrapy spider after certain number of requests?

description: Stop scrapy spider after certain number of requests


code:
SOME_KEY = ''
ANOTHER_KEY = ''

rawDescription: How can I 'filter' the content of a file on the filesystem?


code:
import pickle

d = {'key1':'value1'}
dd = {frozenset(d.items()):'my_value'}

# Save to dumpfile
pickle.dump(dd, open('dumpfile', 'wb'))

# Load again from dumpfile
dd = pickle.load(open('dumpfile', 'rb'))

rawDescription: How do I convert a string back to frozenset?

description: Convert a string back to frozenset


code:
from collections import defaultdict

nesteddict = defaultdict(dict)

nesteddict['abc']['spam'] = 'ham'

rawDescription: Python 2 Dimension Array (Matrix) with string indices


code:
i = df.groupby('City')['Nu'].transform('idxmax').values
df['H2'] = df['H'] / df.loc[i, 'H'].values
df

rawDescription: pandas find max value in groupby and apply function

description: Pandas find max value in groupby and apply function


code:
from __future__ import division
import Tkinter

ORIGINAL_WIDTH  = 32
ORIGINAL_HEIGHT = 32
WINDOW_WIDTH  = 512
WINDOW_HEIGHT = 512
WIDTH_RATIO  = WINDOW_WIDTH/ORIGINAL_WIDTH
HEIGHT_RATIO = WINDOW_HEIGHT/ORIGINAL_HEIGHT

class App(Tkinter.Tk):

    def __init__(self, *args, **kwargs):
        Tkinter.Tk.__init__(self, *args, **kwargs)
        self.canvas = canvas = Tkinter.Canvas( self,
                                               highlightthickness = 0,
                                               width  = WINDOW_WIDTH,
                                               height = WINDOW_HEIGHT )
        self.canvas.pack()
        # Create a list for holding canvas objects
        self.scene = []
        # Draw objects and scale them
        self.draw()
        self.zoom()

    def draw(self):
        canvas = self.canvas

        # Draw rectangles within the range of 0..32 x 0..32
        rect1 = canvas.create_rectangle(  2,  0, 30,  2, fill='black' )
        rect2 = canvas.create_rectangle(  0,  2,  2, 30, fill='black' )
        rect3 = canvas.create_rectangle( 30,  2, 32, 30, fill='black' )
        rect4 = canvas.create_rectangle(  2, 30, 30, 32, fill='black' )
        rect5 = canvas.create_rectangle( 10, 10, 22, 22, fill='black' )

        self.scene.extend( (rect1, rect2, rect3, rect4, rect5) )

    def zoom(self):
        canvas = self.canvas
        # Scale all objects on scene
        for item in self.scene:
            canvas.scale( item, 0, 0, WIDTH_RATIO, HEIGHT_RATIO )

App().mainloop()

rawDescription: Logically zooming in/out in canvas

description: Logically zooming in/out in canvas


code:
n = len(name)  # it might be wise to store this

if n <= 4:     # as you have already
    ...
elif n <= 7:   # you already know n > 4 here; no need to test for that
    ...
else:          # you already know n > 7 here; this should be else
    ...

rawDescription: Looking for a way to fix my program with if and elif statements


rawDescription: How to modify N columns of numpy array at the same time?

description: Modify N columns of numpy array at the same time


code:
from multiprocessing import Pool

if __name__ == "__main__":
   pool = Pool() # use all available CPUs
   for result in pool.imap_unordered(delayed(testtm), powerset(all_turns),
                                     chunksize=1000):
       print(result)

rawDescription: parallel for loop python

description: Parallel for loop python


code:
time.strftime("%H:%M:%S", time.strptime("0100", "%H%M"))
time.strftime("%H:%M:%S", time.strptime("0130", "%H%M"))
time.strftime("%H:%M:%S", time.strptime("2130", "%H%M"))

rawDescription: Python Numeric String to time conversion


rawDescription: 1 1 1 [ 0.] 84.714 : Why are the brackets getting printed?


code:
from collections import Counter

[...]

seen = Counter()

# extract different keywords from Deny lines
for lines in match :

    [...]

    summarized = prot + ip_src + ip_dst + ip_dport

    # NOTE: summarized must be a string or tuple.
    seen.update([summarized])

rawDescription: If not exist, append. If exist, increment count


code:
placeholder = "__placeholder___"
base = reverse("foo_details",
               kwargs={"ver": foo.version,
                       "locale": foo.locale,
                       "name": placeholder})
# ...
url = base.replace(placeholder, foo.name)

rawDescription: Partial reverse url lookup in django

description: Partial reverse url lookup in django


code:
my_dict = {
  "airport": {
     "London": "Heathrow",
     "Tokyo": "Narita",
  },
  "hipsters": {
     "London": "Soho"
  }
}

rawDescription: Python `dict` indexed by tuple: Getting a slice of the pie


code:
names = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l']
df = pd.read_csv(StringIO(data), header=None, names=names)
mask = df.applymap(lambda x: x in ['X', 'XX', None, np.nan])
df[-mask.any(axis=1)]

rawDescription: removing particular rows from DataFrame in python pandas

description: Removing particular rows from DataFrame in python pandas


code:
try:
    import Tkinter as tk     ## Python 2.x
except ImportError:
    import tkinter as tk     ## Python 3.x

from functools import partial

class OpenToplevels():
    """ open and close additional Toplevels with a button
    """
    def __init__(self):
        self.root = tk.Tk()
        self.button_ctr=0
        but=tk.Button(self.root, text="Open a Toplevel",
                     command=self.open_another)
        but.grid(row=0, column=0)
        tk.Button(self.root, text="Exit Tkinter", bg="red",
                 command=self.root.quit).grid(row=1, column=0, sticky="we")
        self.root.mainloop()

    def close_it(self, id):
        id.destroy()

    def open_another(self):
        self.button_ctr += 1
        id = tk.Toplevel(self.root)
        id.title("Toplevel #%d" % (self.button_ctr))
        tk.Button(id, text="Close Toplevel #%d" % (self.button_ctr),
                 command=partial(self.close_it, id),
                 bg="orange").grid(row=1, column=0)

Ot=OpenToplevels()

rawDescription: How to change __init__ to Tk() windows?

description: Change __init__ to Tk() windows


code:
from random import choice
from collections import Counter

diceNo = int(raw_input('How many dice do you need? '))
diceValues = ['skull', 'skull', 'skull', 'symbol', 'shield', 'shield']

counter = Counter()
counter.update(choice(diceValues) for _ in range(diceNo))

print("Rolls:")
for value, count in counter.items():
    print("{}: {}".format(value, count))

print ('YOUR DICE ROLLS HAVE COMPLETED')
raw_input("PRESS ANY KEY TO CONTINUE.")

rawDescription: Printing a randomly chosen variable in Python


code:
df = df.sort(["ID", "Date"])
df
df["everagain"] = df["ID"] == df["ID"].shift(-1)
df

rawDescription: Pandas Dataframe, Apply Function, Return Index


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import PathPatch

x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2*np.pi*x)
y2 = 1.2*np.sin(4*np.pi*x)

fig, ax = plt.subplots()
pc = ax.fill_betweenx(x, 0, y1, color='blue')

# Now we'll add the hatches...
for path in pc.get_paths():
    patch = PathPatch(path, hatch='/', facecolor='none')
    ax.add_patch(patch)

plt.show()

rawDescription: How to hatch PolyCollection instance?

description: Hatch PolyCollection instance


code:
def chatReturn(self, evt):
    self.chat.config(state = NORMAL)
    self.chat.insert(END, self.msg.get(1.0, END))
    self.chat.config(state = DISABLED)
    self.msg.delete(1.0, END)
    return 'break' # <---------

rawDescription: Tkinter text widget : pressing <Return> key goes to line


code:
import asyncio

async def request_handler(reader, writer):
    await asyncio.sleep(2)
    data = await reader.read(100)
    message = data.decode()
    addr = writer.get_extra_info('peername')
    print("Received %r from %r" % (message, addr))

    body = "Hello <br/>\n"
    response = 'HTTP/1.1 {status}\r\n'.format(status="200")
    response += 'Content-Length: {size}\r\n'.format(size=len(body))
    response += 'Content-Type: text/html; charset=utf-8\r\n'.format(size=len(body))
    response += 'Connection: close\r\n'.format(size=len(body))
    response += '\r\n'
    response += body

    writer.write(response.encode('utf-8'))
    await writer.drain()
    writer.close()

loop = asyncio.get_event_loop()
coro = asyncio.start_server(request_handler, '127.0.0.1', 8080, loop=loop)
server = loop.run_until_complete(coro)

print('Start server on {}'.format(server.sockets[0].getsockname()))
try:
    loop.run_forever()
except KeyboardInterrupt:
    pass

# Close the server
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()

rawDescription: How to correct asyncio yield from in data_received

description: Correct asyncio yield from in data_received


code:
def create_ref(obj, hashfn='sha256'):
    """
    Returns a tuple of hexdigest and the method used to generate
    the digest.

    >>> create_ref({}, 'sha1')
    ('bf21a9e8fbc5a3846fb05b4fa0859e0917b2202f', 'sha1')
    >>> create_ref({}, 'md5')
    ('99914b932bd37a50b983c5e7c90ae93b', 'md5')
    """
    allowed = hashlib.algorithms
    if hashfn in allowed:
        return (getattr(hashlib,hashfn)(unicode(obj)).hexdigest(), hashfn)
    else:
        raise NameError('Not a valid algorithm')

rawDescription: Safely evaluate string in Python to call hashlib


rawDescription: List of Dictionary Manipulation in python - TypeError: unhashable type: 'dict'


code:
my_list = [1, 2, 3, 1, 2, 1, 2, 3]
brks = [i for i in range(1,len(my_list)) if my_list[i] < my_list[i-1]]
[my_list[x:y] for x,y in zip([0]+brks,brks+[None])]

rawDescription: Python: Split list in subsets if the current element is minor than previous element


code:
import datetime

repeat = True
datestr = raw_input('Enter a date in the format MM/DD/YYYY')

while repeat:
    try:
        # Parse to datetime, then convert to date since that's all you use
        date = datetime.datetime.strptime(datestr, '%m/%d/%Y').date()
    except ValueError:
        pass  # Handle bad dates in common code
    else:
        if 0000 < date.year < 2017:
            datestr = raw_input('The date you entered is valid, enter another date in the format MM/DD/YYYY')
            continue  # Bypass invalid date input common code

    # Both exception and invalid years will fall through to this common code
    datestr = raw_input('invalid date found! Please enter another date in the format MM/DD/YYYY')

rawDescription: i need help adding the leap year functionality into my python program

description: I need help adding the leap year functionality into my python program


code:
class TestForm(Form):
    Attr_field = SelectField("Attr ", choices=[("ALL", "label")], default="ALL")

rawDescription: Can a WTForms BooleanField have a custom value?


code:
data = {'distance{}'.format(i+1): d for i, d in enumerate(mList)}
print(data['distance1'])

rawDescription: How to assign items in nested lists a variable automatically in Python 2.7?

description: Assign items in nested lists a variable automatically in Python 2.7


code:
try:
    import win32api
except ImportError:
    pass

rawDescription: How to avoid importing module dependencies when importing module?

description: Avoid importing module dependencies when importing module


code:
from reportlab.lib.styles import ParagraphStyle
from reportlab.pdfbase.pdfmetrics import registerFont
from reportlab.platypus import Paragraph, PageBreak, SimpleDocTemplate, Spacer

registerFont(TTFont('Calibri', 'Calibri.ttf')) # Just some font imports
registerFont(TTFont('Calibri-Bold', 'calibrib.ttf'))

pH = ParagraphStyle(name = 'Header', fontName = 'Calibri-Bold', fontSize = 13, leftIndent = 20, firstLineIndent = -20, spaceBefore = 10, leading = 16)
sH = ParagraphStyle(name = 'SubHeader', fontName = 'Calibri', fontSize = 12, leftIndent = 40, firstLineIndent = -20, spaceBefore = 5, leading = 16)

doc = SimpleDocTemplate('Reports\\PDFname.pdf')
story = [Spacer(1, 2 * inch)]

story.append(Paragraph('1. First Title', pH)) # Linking the anchor to reference 0
story.append(Paragraph('1.1. First Subtitle', sH)) # Linking the anchor to reference 1
story.append(PageBreak())

story.append(Paragraph(' 1. First Title', pH)) # Creating anchor with reference 0
story.append(Paragraph('
 1.1. First Subtitle', style)) # Creating anchor with reference 1

doc.build(story)

rawDescription: Generating a PDF Index with ReportLab

description: Generating a PDF Index with ReportLab


code:
import os
os.urandom(10)
type(os.urandom(10))
map(ord, os.urandom(10))

rawDescription: How can I create a random number that is cryptographically secure in python?

description: Create a random number that is cryptographically secure in python


code:
import tkinter as tk

class Scale2d(object):
    def __init__(self, root):
        self.root = root
        self.canvas = tk.Canvas(root, height=500, width=500)
        self.canvas.pack()
        self.canvas.bind('<1>', self.movement) # the magic
        self.canvas.bind('<B1-Motion>', self.movement) # similar magic
        self.canvas.bind('<ButtonRelease-1>', self.report) # result of magic
        self.indicator = self.canvas.create_rectangle(245,245,255,255, fill='black') # dot

    def movement(self, event): # move the dot
        self.canvas.coords(self.indicator, event.x-5, event.y-5, event.x+5, event.y+5)

    def report(self, event): # report the dot
        print(event.x, 500-event.y) # 500-event.y to invert y axis
        self.canvas.coords(self.indicator, 245, 245, 255, 255) # snap back

root = tk.Tk()
scale2d = Scale2d(root)
root.mainloop()

rawDescription: How to make a Python 2 axis slider

description: Make a Python 2 axis slider


code:
import os
import h5py
import numpy as np
path = '/tmp/out.h5'
os.remove(path)
with h5py.File(path, "a") as f:
    dset = f.create_dataset('voltage284', (10**5,), maxshape=(None,),
                            dtype='i8', chunks=(10**4,))
    dset[:] = np.random.random(dset.shape)
    print(dset.shape)
    # (100000,)

    for i in range(3):
        dset.resize(dset.shape[0]+10**4, axis=0)
        dset[-10**4:] = np.random.random(10**4)
        print(dset.shape)
        # (110000,)
        # (120000,)
        # (130000,)

rawDescription: incremental writes to hdf5 with h5py

description: Incremental writes to hdf5 with h5py


code: dict([(t.__name__, t) for t in fun_list])

rawDescription: How can I get the name of an object in Python?

description: Get the name of an object in Python


code:
from psychopy import visual, core, event #import some libraries from PsychoPy
import random

#create a window
mywin = visual.Window([800,600],monitor="testMonitor", units="deg")

#stimuli
lineo = visual.Line(mywin, start=(-5, -1), end=(-5, 1))
fixation = visual.GratingStim(mywin, size=0.2, pos=[0,0], color = 'black')

orientationlist = [20,30,40,50,60] # CHANGED. No need to redefine on every iteration of the while-loop.
#draw the stimuli and update the window
n = 5 # trial number

for i in range(n):  # CHANGED. This is much neater in your case than a while loop. No need to "manually" increment i.
    #fixation
    fixation.draw()
    mywin.flip()
    event.waitKeys(1)  # CHANGED. No need to assign output to anything if it isn't used.
    # stimulus

    lineo.ori = random.choice(orientationlist)  # CHANGED. Alternative: lineo.setOri(random.choice(orientationlist)).
    lineo.draw()
    mywin.flip()
    event.waitKeys(2)

# At this point, all the stimuli have been shown. So no need to do an if-statement within the loop. The following code will run at the appropriate time
lineo.draw()
mywin.flip()
event.waitKeys(keyList=['escape'])  # CHANGED. Listen for escape, do not assign to variable
# CHANGED. No need to call core.quit() or myWin.close() here since python automatically cleans everything up on script end.

rawDescription: how to set the orientation of the stimulus for each trial in psychopy

description: Set the orientation of the stimulus for each trial in psychopy


code:
import os
os.system('Path to your .bat file')

rawDescription: How to run batch file using python script?

description: Run batch file using python script


code:
class ClassB():
    def __init__(self, a):
        self.a = a

    def method(self):
        return self.a

class ClassA:
    a = 'a'

    def class_b_factory(self):
        return ClassB(self)

instance = ClassA()
instance2 = instance.class_b_factory()
instance2.method()

rawDescription: Python Accessing to the parent class (Not inheritance)


rawDescription: Creating a VideoClip of only one frame and Finding the Frame rate of an existing Video


code:
#!/usr/bin/env python3
import re
import sys
from mmap import ACCESS_READ, mmap

def generate_tokens(filename, pattern):
    with open(filename) as f, mmap(f.fileno(), 0, access=ACCESS_READ) as mm:
         yield from re.finditer(pattern, mm)

# sum all integers in a file specified at the command-line
print(sum(int(m.group()) for m in generate_tokens(sys.argv[1], br'\d+')))

rawDescription: How to read tokens without reading whole line or file

description: Read tokens without reading whole line or file


rawDescription: Python, numpy; How to best deal with possible 0d arrays


code:
# I suppose you already have your session somehow...
# If you want to add it to the database
# Assuming you did not change the __init__ method
obj = Object(**data_dictionary_with_keys_matching_column_names)
session.add(obj)

# If you want to issue an update
# obj is already there somehow...
for k, v in data_dictionary_with_keys_matching_column_names.iterkeys():
    setattr(obj, k, v)

session.commit()

rawDescription: sending data in dictionary in database using python

description: Sending data in dictionary in database using python


code:
length = len(filelist)
for i in range(length):
   self.importFiles(filelist[i],timestamps[i])

rawDescription: How can I get the values from two list a time

description: Get the values from two list a time