code:
engine.execute(table_addresses.insert(), name='Joe', age=20)
engine.execute(table_contacts.insert(), email='joe@something.com', cellnumber='267534320')

rawDescription: Insert data into specific table (sqlalchemy)


code: await setattr(t, 'attrib', 3)

rawDescription: Asynchronous property setter

description: Asynchronous property setter


rawDescription: How to slice a list from an element n to the end in python?

description: Slice a list from an element n to the end in python


code:
import sys
from collections import namedtuple
import random

from PyQt4 import QtCore, QtGui

groupItem = namedtuple("groupItem",["name","children","index"])
rowItem = namedtuple("rowItem",["groupIndex","random"])

class GrouperProxyModel(QtGui.QAbstractProxyModel):
    def __init__(self, parent=None):
        super(GrouperProxyModel, self).__init__(parent)

        self._rootItem = QtCore.QModelIndex()
        self._groups = []       # list of groupItems
        self._groupMap = {}     # map of group names to group indexes
        self._groupIndexes = [] # list of groupIndexes for locating group row
        self._sourceRows = []   # map of source rows to group index
        self._groupColumn = 0   # grouping column.

    def setSourceModel(self, source, groupColumn=0):
        super(GrouperProxyModel, self).setSourceModel(source)

        # connect signals
        self.sourceModel().columnsAboutToBeInserted.connect(self.columnsAboutToBeInserted.emit)
        self.sourceModel().columnsInserted.connect(self.columnsInserted.emit)
        self.sourceModel().columnsAboutToBeRemoved.connect(self.columnsAboutToBeRemoved.emit)
        self.sourceModel().columnsRemoved.connect(self.columnsRemoved.emit)

        self.sourceModel().rowsInserted.connect(self._rowsInserted)
        self.sourceModel().rowsRemoved.connect(self._rowsRemoved)
        self.sourceModel().dataChanged.connect(self._dataChanged)

        # set grouping
        self.groupBy(groupColumn)

    def rowCount(self, parent):
        if parent == self._rootItem:
            # root level
            return len(self._groups)
        elif parent.internalPointer() == self._rootItem:
            # children level
            return len(self._groups[parent.row()].children)
        else:
            return 0

    def columnCount(self, parent):
        if self.sourceModel():
            return self.sourceModel().columnCount(QtCore.QModelIndex())
        else:
            return 0

    def index(self, row, column, parent):
        if parent == self._rootItem:
            # this is a group
            return self.createIndex(row,column,self._rootItem)
        elif parent.internalPointer() == self._rootItem:
            return self.createIndex(row,column,self._groups[parent.row()].index)
        else:
            return QtCore.QModelIndex()

    def parent(self, index):
        parent =  index.internalPointer()
        if parent == self._rootItem:
            return self._rootItem
        else:
            parentRow = self._getGroupRow(parent)
            return self.createIndex(parentRow,0,self._rootItem)

    def data(self, index, role):
        if role == QtCore.Qt.DisplayRole:
            parent = index.internalPointer()
            if parent == self._rootItem:
                return self._groups[index.row()].name
            else:
                parentRow = self._getGroupRow(parent)
                sourceRow = self._sourceRows.index(self._groups[parentRow].children[index.row()])
                sourceIndex = self.createIndex(sourceRow, index.column(), 0)
                return self.sourceModel().data(sourceIndex, role)
        return None

    def flags(self, index):
        return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable

    def headerData(self, section, orientation, role):
        return self.sourceModel().headerData(section, orientation, role)

    def mapToSource(self, index):
        if not index.isValid():
            return QtCore.QModelIndex()

        parent = index.internalPointer()
        if not parent.isValid():
            return QtCore.QModelIndex()
        elif parent == self._rootItem:
            return QtCore.QModelIndex()
        else:
            rowItem_ = self._groups[parent.row()].children[index.row()]
            sourceRow = self._sourceRows.index(rowItem_)
            return self.createIndex(sourceRow, index.column(), QtCore.QModelIndex())

    def mapFromSource(self, index):
        rowItem_ = self._sourceRows[index.row()]
        groupRow = self._getGroupRow(rowItem_.groupIndex)
        itemRow = self._groups[groupRow].children.index(rowItem_)
        return self.createIndex(itemRow,index.column(),self._groupIndexes[groupRow])

    def _clearGroups(self):
        self._groupMap = {}
        self._groups = []
        self._sourceRows = []

    def groupBy(self,column=0):
        self.beginResetModel()
        self._clearGroups()
        self._groupColumn = column
        sourceModel = self.sourceModel()
        for row in range(sourceModel.rowCount(QtCore.QModelIndex())):
            groupName = sourceModel.data(self.createIndex(row,column,0),
                                         QtCore.Qt.DisplayRole)

            groupIndex = self._getGroupIndex(groupName)
            rowItem_ = rowItem(groupIndex,random.random())
            self._groups[groupIndex.row()].children.append(rowItem_)
            self._sourceRows.append(rowItem_)

        self.endResetModel()

    def _getGroupIndex(self, groupName):
        """ return the index for a group denoted with name.
        if there is no group with given name, create and then return"""
        if groupName in self._groupMap:
            return self._groupMap[groupName]
        else:
            groupRow = len(self._groupMap)
            groupIndex = self.createIndex(groupRow,0,self._rootItem)
            self._groupMap[groupName] = groupIndex
            self._groups.append(groupItem(groupName,[],groupIndex))
            self._groupIndexes.append(groupIndex)
            self.layoutChanged.emit()
            return groupIndex

    def _getGroupRow(self, groupIndex):
        for i,x in enumerate(self._groupIndexes):
            if id(groupIndex)==id(x):
                return i
        return 0

    def _rowsInserted(self, parent, start, end):
        for row in range(start, end+1):
            groupName = self.sourceModel().data(self.createIndex(row,self._groupColumn,0),
                                                QtCore.Qt.DisplayRole)
            groupIndex = self._getGroupIndex(groupName)
            self._getGroupRow(groupIndex)
            groupItem_ = self._groups[self._getGroupRow(groupIndex)]
            rowItem_ = rowItem(groupIndex,random.random())
            groupItem_.children.append(rowItem_)
            self._sourceRows.insert(row, rowItem_)
        self.layoutChanged.emit()

    def _rowsRemoved(self, parent, start, end):
        for row in range(start, end+1):
            rowItem_ = self._sourceRows[start]
            groupIndex = rowItem_.groupIndex
            groupItem_ = self._groups[self._getGroupRow(groupIndex)]
            childrenRow = groupItem_.children.index(rowItem_)
            groupItem_.children.pop(childrenRow)
            self._sourceRows.pop(start)
            if not len(groupItem_.children):
                # remove the group
                groupRow = self._getGroupRow(groupIndex)
                groupName = self._groups[groupRow].name
                self._groups.pop(groupRow)
                self._groupIndexes.pop(groupRow)
                del self._groupMap[groupName]
        self.layoutChanged.emit()

    def _dataChanged(self, topLeft, bottomRight):
        topRow = topLeft.row()
        bottomRow = bottomRight.row()
        sourceModel = self.sourceModel()
        # loop through all the changed data
        for row in range(topRow,bottomRow+1):
            oldGroupIndex = self._sourceRows[row].groupIndex
            oldGroupItem = self._groups[self._getGroupRow(oldGroupIndex)]
            newGroupName = sourceModel.data(self.createIndex(row,self._groupColumn,0),QtCore.Qt.DisplayRole)
            if newGroupName != oldGroupItem.name:
                # move to new group...
                newGroupIndex = self._getGroupIndex(newGroupName)
                newGroupItem = self._groups[self._getGroupRow(newGroupIndex)]

                rowItem_ = self._sourceRows[row]
                newGroupItem.children.append(rowItem_)

                # delete from old group
                oldGroupItem.children.remove(rowItem_)
                if not len(oldGroupItem.children):
                    # remove the group
                    groupRow = self._getGroupRow(oldGroupItem.index)
                    groupName = oldGroupItem.name
                    self._groups.pop(groupRow)
                    self._groupIndexes.pop(groupRow)
                    del self._groupMap[groupName]

        self.layoutChanged.emit()

rawDescription: qt pyside - qsql*model, qabstractitemmodel and qtreeview interaction

description: Qt pyside - qsql*model, qabstractitemmodel and qtreeview interaction


code:
def urlretrieve(url, filename, cache, lock=threading.Lock()):
    'Read contents of an open url, use etags and decompress if needed'

    request = urllib2.Request(url)
    request.add_header('Accept-Encoding', 'gzip')
    with lock:
        if ('etag ' + url) in cache:
            request.add_header('If-None-Match', cache['etag ' + url])
        if ('date ' + url) in cache:
            request.add_header('If-Modified-Since', cache['date ' + url])

    try:
        u = urllib2.urlopen(request)
    except urllib2.HTTPError as e:
        return Response(e.code, e.msg, False, False)
    content = u.read()
    u.close()

    compressed = u.info().getheader('Content-Encoding') == 'gzip'
    if compressed:
        content = gzip.GzipFile(fileobj=StringIO.StringIO(content), mode='rb').read()

    written = writefile(filename, content)

    with lock:
        etag = u.info().getheader('Etag')
        if etag:
            cache['etag ' + url] = etag
        timestamp = u.info().getheader('Date')
        if timestamp:
            cache['date ' + url] = timestamp

    return Response(u.code, u.msg, compressed, written)

rawDescription: Best way to implement frequent calls to taxing Python scripts

description: Implement frequent calls to taxing Python scripts


code:
ships.update(
  {'_id': 1},
  {"$set": {'staff': staff}},
  false,true
)

rawDescription: pymongo: Add field containing a dict

description: Pymongo: Add field containing a dict


rawDescription: How to lookup element in AWS response with lxml (namespace issue?)

description: Lookup element in AWS response with lxml (namespace issue?)


code:
def main():
    print("This program tests the validity of a given date")

    date = (raw_input("Please enter a date (mm/dd/yyyy): "))
    month, day, year = date.split("/")
    month = int(month)
    day = int(day)
    year = int(year)
    Mylist31 = [1, 3, 5, 7, 8, 10, 12]
    Mylist30 = [4, 6, 9, 11]

    ##Calculates whether input year is a leap year or not
    if year >= 100 and year % 4 == 0 and year % 400 == 0:
        is_leap_year = True
    elif year >= 0 and year <100 and year % 4 == 0:
        is_leap_year = True
    else:
        is_leap_year = False

    if is_leap_year:
        if month in Mylist31 and day in range(1, 32):
            print("Valid date")
        elif month in Mylist30 and day in range(1,31):
            print("Valid date")
        elif month == 2 and day in range(1,30):
            print("Valid date")
        else:
            print("Not a Valid date")
    else:
        #TODO: validate non-leap-year date
        pass

main()

rawDescription: Trying to Figure out how to properly use a while loop in Python 3.3.0


code:
import numpy
import colorsys
import random
import os
from matplotlib.mlab import PCA as mlabPCA
from matplotlib import pyplot as plt

def get_colors(num_colors):
    """
    Function to generate a list of randomly generated colors
    The function first generates 256 different colors and then
    we randomly select the number of colors required from it
    num_colors        -> Number of colors to generate
    colors            -> Consists of 256 different colors
    random_colors     -> Randomly returns required(num_color) colors
    """
    colors = []
    random_colors = []
    # Generate 256 different colors and choose num_clors randomly
    for i in numpy.arange(0., 360., 360. / 256.):
        hue = i / 360.
        lightness = (50 + numpy.random.rand() * 10) / 100.
        saturation = (90 + numpy.random.rand() * 10) / 100.
        colors.append(colorsys.hls_to_rgb(hue, lightness, saturation))

    for i in range(0, num_colors):
        random_colors.append(colors[random.randint(0, len(colors) - 1)])
    return random_colors

def random_centroid_selector(total_clusters , clusters_plotted):
    """
    Function to generate a list of randomly selected
    centroids to plot on the output png
    total_clusters        -> Total number of clusters
    clusters_plotted      -> Number of clusters to plot
    random_list           -> Contains the index of clusters
                             to be plotted
    """
    random_list = []
    for i in range(0 , clusters_plotted):
        random_list.append(random.randint(0, total_clusters - 1))
    return random_list

def plot_cluster(kmeansdata, centroid_list, label_list , num_cluster):
    """
    Function to convert the n-dimensional cluster to
    2-dimensional cluster and plotting 50 random clusters
    file%d.png    -> file where the output is stored indexed
                     by first available file index
                     e.g. file1.png , file2.png ...
    """
    mlab_pca = mlabPCA(kmeansdata)
    cutoff = mlab_pca.fracs[1]
    users_2d = mlab_pca.project(kmeansdata, minfrac=cutoff)
    centroids_2d = mlab_pca.project(centroid_list, minfrac=cutoff)

    colors = get_colors(num_cluster)
    plt.figure()
    plt.xlim([users_2d[:, 0].min() - 3, users_2d[:, 0].max() + 3])
    plt.ylim([users_2d[:, 1].min() - 3, users_2d[:, 1].max() + 3])

    # Plotting 50 clusters only for now
    random_list = random_centroid_selector(num_cluster , 50)

    # Plotting only the centroids which were randomly_selected
    # Centroids are represented as a large 'o' marker
    for i, position in enumerate(centroids_2d):
        if i in random_list:
            plt.scatter(centroids_2d[i, 0], centroids_2d[i, 1], marker='o', c=colors[i], s=100)

    # Plotting only the points whose centers were plotted
    # Points are represented as a small '+' marker
    for i, position in enumerate(label_list):
        if position in random_list:
            plt.scatter(users_2d[i, 0], users_2d[i, 1] , marker='+' , c=colors[position])

    filename = "name"
    i = 0
    while True:
        if os.path.isfile(filename + str(i) + ".png") == False:
            #new index found write file and return
            plt.savefig(filename + str(i) + ".png")
            break
        else:
            #Changing index to next number
            i = i + 1
    return

rawDescription: Plot multi-dimension cluster to 2D plot python


code: re.match("^[a-zA-Z]+$", textToRestrict)

rawDescription: python: regex match string and only string

description: Python: regex match string and only string


code:
license_number = raw_input("please insert the vehicels license number: ")
car_type = raw_input("what car type? ")
# etc.

# validate inputs here.
# note that with python 2.x the variables will always be strings
# if using python 3.x, use input() instead of raw_input()

# put them into a query using string formatting
query = "INSERT INTO VEHICLE VALUES('%s','%s','%s','%s')" % (license_number, 'null', car_type, owner_name)

rawDescription: first time to build a simple app by python

description: First time to build a simple app by python


code:
class myView(TemplateView):

    @request_management
    def dispatch(self, request, *args, **kwargs):
        ...
        return super(myView, self).dispatch(request, *args, **kwargs)

    def request_management(method):
        @wraps(method)
        def decorator(self, request, *args, **kwargs):
            logger.debug("request = %s" % str(request))
            self.request = request

            return method(self, request, *args, **kwargs)

        return decorator

rawDescription: How to add/modify an attribute to a Django class based view from a Decorator?

description: Add/modify an attribute to a Django class based view from a Decorator


code:
import datetime
pub = lastItem.pub_date
end_date = datetime.datetime(pub.year, pub.month, pub.day)

rawDescription: django python date time set to midnight

description: Django python date time set to midnight


code:
from django.core.urlresolvers import set_script_prefix

set_script_prefix('/mysite')

rawDescription: Django reverse returns different values when called from WSGI or shell


code:
import requests
f = open('C:\\Users\\myname\\Desktop\\image.jpg', 'rb')
urls='http://localhost:8000/upper'
cookies = {'csrftoken': 'token'}
headers = {'X-CSRF-TOKEN': 'token'}
r=requests.post(urls, files={'uploads':f}, cookies=cookies, headers=headers)
print(r.status_code)

rawDescription: how can I provide csrf protection in case of using requests module to post data to a django view

description: Provide csrf protection in case of using requests module to post data to a django view


code:
directions = ["up", "down", "left", "right"]

start_dir = random.choice(directions)

if start_dir == "left" or start_dir == "right":
    checkXstate(x)
else:
    checkYstate(y)

rawDescription: start with a random function and then alternate (Python)

description: Start with a random function and then alternate (Python)


code:
import Tkinter

class Application(Tkinter.Frame):
   def __init__(self, master, width, height):
       Tkinter.Frame.__init__(self, master)
       self.master.minsize(width=width, height=height)
       self.master.config()
       self.pack()

       self.main_frame = Tkinter.Frame(self.master)

       self.button_scroll_bar = Tkinter.Scrollbar(
           self.main_frame,
           orient='vertical')

       self.button_canvas = Tkinter.Canvas(
           self.main_frame,
           yscrollcommand=self.button_scroll_bar.set,
           relief='flat',
           borderwidth=0)

       self.button_canvas.bind('<MouseWheel>', self._on_mousewheel)
       self.button_scroll_bar.config(command=self.button_canvas.yview)

       self.button_scroll_bar.pack(side='right', fill='y')
       self.button_canvas.pack(fill='both', expand=True)

       for i in range(0, 15):
           for j in range(0, 2):
               b = Tkinter.Button(
                   self.button_canvas,
                   text='Text')

               # note we are separating the buttons 80 units horizontally
               # and 30 units vertically...I just chose these numbers
               # since they looked reasonable.
               self.button_canvas.create_window(
                   (80 * j),
                   (30 * i),
                   anchor='nw',
                   window=b
               )
       # here we need to update the scrollregion, notice the same x, y numbers
       # multiplied times the number of buttons we placed in the canvas
       self.button_canvas.config(scrollregion=(0, 0, 80*2, 30*15))

       self.main_frame.pack(fill='both', expand=True)

   def _on_mousewheel(self, event):
       self.button_canvas.yview_scroll(-event.delta, "units")

root = Tkinter.Tk()
root.title('Title Here')

w = 512
h = 256

app = Application(root, width=w, height=h)
app.mainloop()

rawDescription: How to add a scroll bar to the following code? (with Tkinter for 2.7.5)

description: Add a scroll bar to the following code? (with Tkinter for 2.7.5)


code: [i[2] for i in conv]

rawDescription: How can I print one part of a Python substring?

description: Print one part of a Python substring


code:
class Convert(object):
    def __init__(self):
        self.A = packageA.get_the_entirety_of_A_expensively()
        self.B = getB() # or put get_B's code in here
    def AB(self, input):
        return self.A[self.B[input]]

converter = Convert()
converter.AB('blah')

rawDescription: How do I get around not using global variables and passing too many arguments?

description: Get around not using global variables and passing too many arguments


code:
import pandas as pd

frames = pd.DataFrame(columns=['TimeEET', 'TemperatureC', 'Dew PointC', 'Humidity','Sea Level PressurehPa',
       'VisibilityKm', 'Wind Direction', 'Wind SpeedKm/h','Gust SpeedKm/h','Precipitationmm',
       'Events','Conditions', 'WindDirDegrees', 'DateUTC<br />'])

# Iterate through year, month, and day
df_list = []
for y in range(2006, 2007):
    for m in range(1, 13):
       for d in range(1, 32):

# Check if leap year
        if y%400 == 0:
            leap = True
        elif y%100 == 0:
            leap = False
        elif y%4 == 0:
            leap = True
        else:
            leap = False

#Check if already gone through month
        if (m == 2 and leap and d > 29):
            continue
        elif (m == 2 and d > 28):
            continue
        elif (m in [4, 6, 9, 10] and d > 30):
            continue

 # Open wunderground.com url
        url = "http://www.wunderground.com/history/airport/EFHK/"+str(y)+ "/" + str(m) + "/" + str(d) + "/DailyHistory.html?req_city=Vantaa&req_state=&req_statename=Finlandia&reqdb.zip=00000&reqdb.magic=4&reqdb.wmo=02974&format=1"
        df=pd.read_csv(url, sep=',',skiprows=2)
        df_list.append(df)
frames=pd.concat(df_list, ignore_index=True)

rawDescription: Concating url pages as a single Data Frame


code:
from collections import Counter, defaultdict
l = ['a', 'b', 'c', 'a', 'b', 'b', 'c']

counts = Counter(l)
freqs = defaultdict(list)

for k,v in counts.items():
    freqs[v].append(k)

freqs

rawDescription: Most effective way to group element counter in Python


code:
import os, filecmp, shutil

def resolve_diffs(src, dst):
    for src_root, src_dirs, src_files in os.walk(src, topdown=True):
        dst_root = os.path.join(dst, os.path.relpath(src_root, src))
        dirs = filecmp.dircmp(src_root, dst_root)
        for item in dirs.right_only:
            print('Removing ' + item)
            dst_path = os.path.join(dst_root, item)
            if os.path.isdir(dst_path):
                shutil.rmtree(dst_path)
            else:
                os.remove(dst_path)
        for item in dirs.left_only:
            print('Adding ' + item)
            src_path = os.path.join(src_root, item)
            if os.path.isdir(src_path):
                shutil.copytree(src_path, os.path.join(dst_root, item))
            else:
                shutil.copy2(src_path, os.path.join(dst_root, item))

rawDescription: Compare directories, delete leftover files, copy new ones


code:
import os
import urllib
for url in urllist:
    filename = url.rstrip('/').rsplit('/', 1)[-1]
    path = os.path.join(os.path.join(os.path.sep, 'extrafanart'), filename)
    urllib.urlretrieve(url, path)

rawDescription: Python - download url and save with generic filename


code:
import re

lst = ['INQ/DATA', 'ENTRY', '1', 'MONETARY', '0', 'TRAN', 'GRID', '0', 'BCR', '0', 'ENVIRONMENT', 'TBL', '0', 'PRODUCT', 'FILE', '0', 'STOP/HOLD', '1', 'QUERY', '0', 'LOOKUP', 'FILE', '0', 'REPORT', 'FILE', '0']
s = " ".join(lst)

p = re.compile(r'(\d+)')
result = [i.strip() for i in p.split(s) if i != '']
# ['INQ/DATA ENTRY', '1', 'MONETARY', '0', 'TRAN GRID', '0', 'BCR', '0', 'ENVIRONMENT TBL', '0', 'PRODUCT FILE', '0', 'STOP/HOLD', '1', 'QUERY', '0', 'LOOKUP FILE', '0', 'REPORT FILE', '0']

rawDescription: combining specific values in python list

description: Combining specific values in python list


code:
key1, key2 = random.sample(list(d), 2)
d[key1], d[key2] = d[key2], d[key1]

rawDescription: Swap two random values in dictionary

description: Swap two random values in dictionary


code:
import re
import string

with open('dna.txt', 'rb') as f:
    data = f.read()

data = [x.split('\n', 1) for x in data.split('>')]
data = [(x[0], ''.join(x[1].split())) for x in data if len(x) == 2]

start, end = [re.compile(x) for x in 'ATG TAG|TGA|TAA'.split()]

revtrans = string.maketrans("ATGC","TACG")

def get_longest(starts, ends):
    ''' Simple brute-force for now.  Optimize later...
        Given a list of start locations and a list
        of end locations, return the longest valid
        string.  Returns tuple (length, start position)

        Assume starts and ends are sorted correctly
        from beginning to end of string.
    '''
    results = {}
    # Use smallest end that is bigger than each start
    ends.reverse()
    for start in starts:
        for end in ends:
            if end > start and (end - start) % 3 == 0:
                results[start] = end + 3
    results = [(end - start, start) for
               start, end in results.iteritems()]
    return max(results) if results else (0, 0)

def get_orfs(dna):
    ''' Returns length, header, forward/reverse indication,
        and longest match (corrected if reversed)
    '''
    header, seqf = dna
    seqr = seqf[::-1].translate(revtrans)
    def readgroup(seq, group):
        return list(x.start() for x in group.finditer(seq))
    f = get_longest(readgroup(seqf, start), readgroup(seqf, end))
    r = get_longest(readgroup(seqr, start), readgroup(seqr, end))
    (length, index), s, direction = max((f, seqf, 'forward'), (r, seqr, 'reverse'))
    return length, header, direction, s[index:index + length]

# Process entire file
all_orfs = [get_orfs(x) for x in data]

# Put in groups of 3
all_orfs = zip(all_orfs[::3], all_orfs[1::3], all_orfs[2::3])

# Process each group of 3
for x in all_orfs:
    x = max(x)   # Only pring longest in each group
    print(x)
    print('')

rawDescription: Python calculate ORFs from any arbitrary reading frame


code:
class item:
    def __init__(self,attr): self.attr = attr
    def __eq__(self,o): return isinstance(o, item) and self.attr.lower() == o.attr.lower()

lst = [item("a"), item("b")]
item("A") in lst
item("a") in lst
item("B") in lst
item("C") in lst
"A" in lst

rawDescription: python item equivalent to another in list

description: Python item equivalent to another in list


code: from Foundation import *

rawDescription: Using Voice instead of 'raw_input' in python for Mac OS X


code: self.Bind(wx.EVT_BUTTON, lambda evt, i: self.Rem(evt,i), btn4)

rawDescription: wxPython - button

description: WxPython - button


code:
import pymongo
import bson
import threading

connection = pymongo.MongoClient("localhost", 27017)
db = connection.test

def set_cache(db):
    cache_id = db.test_collection.save({'test': 'some string'})
    return cache_id

def get_cache(db, cache_id):
    entry = db.test_collection.find_one({'_id' : bson.objectid.ObjectId(cache_id)})
    if not entry:
        print('No entry for %s' % cache_id)

    return entry

i = 0
while 1:
    i += 1
    cache_id = set_cache(db)

    t = threading.Thread(target=get_cache, args=(db, cache_id))
    t.start()
    t.join()

    if i > 10000:
        break

rawDescription: Get no result for reading from thread in pymongo


code:
topics = sns.get_all_topics()
topic_list = topics['ListTopicsResponse']['ListTopicsResult']['Topics']
topic_names = [t['TopicArn'].split(':')[5] for t in topic_list]

if 'test' in topic_names:
   print(True)

rawDescription: Verify if a topic exists based on topic name


code:
from itertools import groupby
from operator import itemgetter

d = {}
with open("some_file_name", "r") as f:
    lines = (line.split(",") for line in f)
    for k, g in groupby(lines, key=itemgetter(0)):
        d[k] = [line[-1] for line in g]

rawDescription: Repeating code of for-loop for lines sharing same identifier value


code: bysign = [int(x >= 0) for x in somelist]

rawDescription: Apply Indicator Function to List

description: Apply Indicator Function to List


code:
import gzip
import cStringIO
from Crypto.Cipher import Blowfish

#gzip and encrypt
small_buffer = cStringIO.StringIO()
small_string = "test data"
with gzip.GzipFile(fileobj=small_buffer,compresslevel=6, mode='wb') as gzip_obj:
    gzip_obj.write(small_string)
compressed_str = small_buffer.getvalue()
blowfish = Blowfish.new('better than bad')
#remainder = '|'*(8 - (len(compressed_str) % 8))
pad_bytes = 8 - (len(compressed_str) % 8)
padding = chr(pad_bytes)*pad_bytes
compressed_str += padding
encrypted = blowfish.encrypt(compressed_str)
print("encrypted: {}".format(encrypted))

#decrypt and ungzip (pretending to be in a separate space here)
value = encrypted
blowfish = Blowfish.new('better than bad')
decrypted = blowfish.decrypt(value)
buff = cStringIO.StringIO(decrypted)
buff.seek(-1,2) #move to the last byte
pad_bytes = ord(buff.read(1)) #get the size of the padding from the last byte
buff.truncate(len(buff.getvalue()) - pad_bytes) #probably a better way to do this.
buff.seek(0)
with gzip.GzipFile(fileobj=buff) as gz:
    back_home = gz.read()
print("back home: {}".format(back_home))

rawDescription: Python IOError: Not a gzipped file (Gzip and Blowfish Encrypt/Compress)


rawDescription: how to make a range() only even numbers in python3.3?

description: Make a range() only even numbers in python3.3


code:
def get_queryset(self):
    qs = super(MyView, self).get_queryset()
    return qs.filter(person__user=self.request.user)

rawDescription: Django - Filtering in DetailView

description: Django - Filtering in DetailView


code:
#user configurable variables:
number_of_files = 4

#delete the following lines to use your own files.
f1 = open('1.csv','w')
f1.write('''"Street", "Number", "Occupants"
"Test Road", "7", "4"
"Test Street", "5", "1"
"Test Avenue", "2", "6"''')
f1.close()

f2 = open('2.csv','w')
f2.write('''"Street", "Number", "Occupants"
"Test Road", "12", "2"
"Test Street", "11", "3"
"Test Avenue", "9", "2"''')
f2.close()

f3 = open('3.csv','w')
f3.write('''"Street", "Number", "Occupants"
"Test Road", "34", "2"
"Test Street", "22", "3"
"Test Lane", "19", "2"''')
f3.close()

f4 = open('4.csv','w')
f4.write('''"Street", "Number", "Occupants"
"Test Road", "4", "7"
"Test Street", "1243", "6"
"Test Lane", "17", "1"''')
f4.close()
#stop deleteing

#the rest 'should' take care of itself.
file_set = []
for y in range(number_of_files):
    exec("f"+str(y+1)+" = [x.split(',') for x in open('"+str(y+1)+".csv','r').read().replace('\"','').replace(', ',',').split('\\n')]")
    exec("file_set.append(f"+str(y+1)+")")

num_files = len(file_set)

data_dict = {}

for file in file_set:
    block = file_set.index(file)

    for line in file:
        row = file.index(line)

        if line[0] not in data_dict:
            data_dict[line[0]] = num_files*[['N/A','N/A']]

        data_dict[line[0]][block] = line[1:]

print (data_dict)

f0 = open('output.csv','w')
f0.write(',Street')
for x in range(num_files):
    f0.write(','+str(x+1))
f0.write('\n')

temp = 0
for key in data_dict:
    if key != 'Street':
        if temp == 0:
            f0.write('Number,'+key)
            temp = 1
        else:
            f0.write(','+key)
        for x in range(num_files):
            f0.write(','+data_dict[key][x][0])
        f0.write('\n')

temp = 0
for key in data_dict:
    if key != 'Street':
        if temp == 0:
            f0.write('Occupants,'+key)
            temp = 1
        else:
            f0.write(','+key)
        for x in range(num_files):
            f0.write(','+data_dict[key][x][1])
        f0.write('\n')

f0.close()

rawDescription: CSV files and dictionary

description: CSV files and dictionary


code:
import enum

class Color(enum.IntEnum):
    green = 1
    blue = 2
    red = 3
    yellow = 4

color_code = 4
# cast to enum
color = Color(color_code)

# cast back to int
color_code = int(color)

rawDescription: Cast int to enum in Python for my program?


code:
import SoftLayer
from pprint import pprint as pp

client = SoftLayer.Client()
subjects = client['Ticket_Subject'].getAllObjects()
pp(subjects)

rawDescription: Softlayer API information needed on using SoftLayer_Ticket with subjectId


code:
def nmoment(x, counts, c, n):
    return np.sum((x-c)^n*counts) / np.sum(counts)

rawDescription: Calculate moments (mean, variance) of distribution in python


rawDescription: Pandas Panel Boolean Selection

description: Pandas Panel Boolean Selection


code:
def list_to_items(lst):
    return [(item.upper(), item.title(), '') for item in lst]

rawDescription: Convert a list into a sequence of string triples


code:
phonemes = {TH : [th], O : [o], OH : [oh, oo]}

for char in set(list1):
    if char not in d:
        d[char] = {char.lower() : {phone : list2.count(phone) for phone in phonemes[char]}}

rawDescription: Adding keys to defaultdict(dict)

description: Adding keys to defaultdict(dict)


code:
x = np.arange(12).reshape(4,3)
y = np.array([0,3,2])
x[y[None, :], np.arange(len(y))[None,:]][0]
x

rawDescription: Numpy: select value at a particular row for each column of a matrix


code:
def userInput():
    a= input("Please put in the weight of your package:")
    weight = None
    try:
        weight= float(a)
    except:
        userInput()
    return weight

def calculate(weight):
    if weight <= 2:
        print('Your rate is $1.10')
    elif weight > 2 and weight <= 6:
        print('Your rate is $2.20')
    elif weight > 6 and weight <= 10:
        print('Your rate is $3.70')
    else:
        print('Your rate is $3.80')

def main():
    weight = userInput()
    calculate(weight)

main()

rawDescription: Using user input date from one module in another


code:
from urlparse import parse_qs
parse_qs('blabla=hihi&hello=', keep_blank_values=True)

rawDescription: What is the standard for 'application/x-www-form-urlencoded' and an empty value?


code:
import struct
struct.pack("i",1024)
struct.pack("i",10240)
struct.pack("i",900000)

rawDescription: how to write integer number in particular no of bytes in python ( file writing)

description: Write integer number in particular no of bytes in python ( file writing)


code:
import unittest

from mock import patch, Mock

import code

class test(unittest.TestCase):
    def test_code_function(self):
        with patch('code.cExtensionClass') as m:
            m.return_value.cExtensionFunc = func = Mock()
            code.CodeClass.code_function()
            func.assert_called_with()

    #@patch('code.cExtensionClass')
    #def test_code_function(self, m):
    #    m.return_value.cExtensionFunc = func = Mock()
    #    code.CodeClass.code_function()
    #    func.assert_called_with()

rawDescription: In Python, how to mock a c extension class?


code:
def read_csv (filename):
    with open(filename) as incsv:
       reader = csv.DictReader(incsv, delimiter=';')
       for r in reader:
           yield r

columns = ['article_name', 'another_column', 'sku']

with open('newfile.csv', 'w+') as f:
    writer = csv.DictWriter(f, columns, delimiter=';')
    writer.writeheader()

    for row in read_csv('oldfile.csv'):
        # add a property
        row['another_column'] = 'foo'

        # write row (using the order specified in columns)
        writer.writerow(row)

rawDescription: change order of colums in csv (python)

description: Change order of colums in csv (python)


rawDescription: SQLAlchemy Regex with MySQL database using \b


code:
from ast import literal_eval
a = ['(100,9),(200,10)']
list(literal_eval(a[0]))

rawDescription: convert lists of string tuples to lists of tuples

description: Convert lists of string tuples to lists of tuples


code:
import re
sample = "[xy][abc]"
re.findall(r'\[([^]]*)\]',sample)

rawDescription: Python: How to get multiple elements inside square brackets


code:
if not atype_config.LocalityDisplay:
    self.cleaned_data.pop('address_locality', None)

rawDescription: django strip/remove/clear value

description: Django strip/remove/clear value


code: _, y = function()

rawDescription: Can a Python function return only the second of two values?


code:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
cipher_suite = Fernet(key)
cipher_text = cipher_suite.encrypt(b"A really secret message. Not for prying eyes.")
plain_text = cipher_suite.decrypt(cipher_text)

rawDescription: writing a variable to a text file and encrypting it?

description: Writing a variable to a text file and encrypting it


code:
from itertools import combinations, chain

unassigned_blocks = {
    ('a', 400),
    ('b', 200),
    ('c', 250),
    ('d',  50),
    # ...
}

sections_and_assigned_blocks = {
    ('1', 250): {},
    ('2', 650): {},
    # ...
}

for section in sorted(sections_and_assigned_blocks.keys()):
    best, best_length = {}, 0
    for combination in chain(*[combinations(unassigned_blocks, n)
                               for n in xrange(1, len(unassigned_blocks)+1)]):
        combination = set(combination)
        length = sum(block[1] for block in combination)
        if best_length < length <= section[1]:
            best, best_length = combination, length
    sections_and_assigned_blocks[section] = best
    unassigned_blocks -= best

from pprint import pprint
pprint(sections_and_assigned_blocks)
# {('1', 250): set([('c', 250)]),
#  ('2', 650): set([('a', 400), ('b', 200), ('d', 50)])}

rawDescription: Fill an area with best fitting "blocks"

description: Fill an area with best fitting "blocks"


code:
def my_preexec_fn():
    os.setuid(10033)
process = subprocess.Popen(cmdstr,stdout=subprocess.PIPE, stderr=subprocess.STDOUT, preexec_fn=my_preexec_fn)

rawDescription: execute 'ls' command as a different User within python script

description: Execute 'ls' command as a different User within python script


code:
for i in FOO.objects.map_reduce(map_f, reduce_f, {"merge":"COLLECTION_NAME"}):
    pass

rawDescription: MongoEngine map_reduce merge collections


rawDescription: python plot and powerlaw fit

description: Python plot and powerlaw fit


code:
@hybrid_property
def original_brand_id(self):
    return cast(func.regexp_replace(self.page_title, '.*::: ',''), Numeric)

rawDescription: SQLAlchemy: how to perform regexp_replace on column values


rawDescription: Get time object from milliseconds

description: Get time object from milliseconds


code:
import tkinter as tk
root = tk.Tk()
root.geometry('400x400')
canvas = tk.Canvas(root)
canvas.pack()

label = tk.Label(canvas, text='foo')
label.pack()

root.mainloop()

rawDescription: In tkinter, the canvas size settings seem to stop working when the canvas is used as a master for another widget. Is there a way to get around this?


code:
'\xe3\x81\x82'.decode('utf-8')    # three top-bit-set bytes, representing one character
u'\u3042'.encode('shift-jis')
unicode('\x82\xa0', 'shift-jis')  # alternative way of doing a decode

rawDescription: What is the proper way to use str.decode and unicode.encode?


code: classificationCode != 'b'

rawDescription: C++: Checking if user input is one of the characters A, W, or D


code:
from django.contrib.auth.decorators import login_required
from django.shortcuts import render

from your_app.models import ToDo

@login_required
def todos_for_user(request):
    todos = ToDo.objects.filter(user=request.user)
    return render(request, 'todos/index.html', {'todos' : todos})

rawDescription: django: keep each users data separate

description: Django: keep each users data separate


code: result = ["_".join((i, j)) for i, j in itertools.izip(la, itertools.cycle(lb))]

rawDescription: loop over 2 lists, repeating the shortest until end of longest

description: Loop over 2 lists, repeating the shortest until end of longest


code:
# Import what you need
import numpy as np
import pylab as plt

# Set the number of steps you're going to walk along
steps = 1000

# Set the random walk start coordinates
# for each of four random walks
n1=np.array([50,50],int)
n2=np.array([-50,50],int)
n3=np.array([-50,-50],int)
n4=np.array([50,-50],int)
na_list = [n1,n2,n3,n4]

# Set the colors of the four random walks
clr_list = ['g','c','m','y']

# Create one figure with one subplot
fig, ax=plt.subplots()
# Set the background color to black
ax.set_axis_bgcolor('black')

# Loop through the different random walks
for na, clr in zip(na_list, clr_list):

    # Create a list of coordinates
    # initiated by the start coordinates
    coar = np.ones([steps+1,2],int) * na

    # For each step figure out if you're
    # going to walk right, left, up or down
    for t in range(0,steps):

        # Set coar for the point after
        # this step (t+1) to be the point the
        # step starts at (t)
        coar[t+1] = coar[t]

        # Get a random number
        bin = np.random.randint(4)

        if(bin==0):
            # Step to the right (inc x by 1)
            coar[t+1][0] = coar[t,0] + 1
        elif(bin==1):
            # Step to the left (dec x by 1)
            coar[t+1][0] = coar[t,0] - 1
        elif(bin==2):
            # Step up (inc y by 1)
            coar[t+1][1] = coar[t,1] + 1
        elif(bin==3):
            # Step down (dec y by 1)
            coar[t+1][1] = coar[t,1] - 1

    # Plot these coordinates
    ax.plot(coar.T[0], coar.T[1], c=clr)

    # And show the starting point with a white triangle
    # just to make it clear where you started
    ax.scatter(coar[0,0], coar[0,1], marker='^', c='w', edgecolor='w', s=70, zorder=3)

# Autoscale the axis
ax.autoscale()
# And show the plot
plt.show()

rawDescription: Using SubPlots With LineCollection

description: Using SubPlots With LineCollection


code: image_set += pixel_adj[:,None,None,:]

rawDescription: NumPy Broadcast: Adding an ndarray across elements (a,b) in (M,A,B,N) shaped array


code:
from collections import Counter

def contains_anagram(s1, s2):
    return len(list((Counter(s1) & Counter(s2)).elements())) == len(s2)

rawDescription: Finding an anagram of one string in another


code:
target.write(line2+"\n")
target.write(line3)
target.close() #<------- You need to close the file when you're done writing.
#file read
txt = open(filename)

rawDescription: Python basics- why aren't the contents of my file printing?


rawDescription: Displaying ASCII-art in TKinter

description: Displaying ASCII-art in TKinter


code:
img.save("a.jpg","JPEG")

img2 = img.resize( (800, 800))
img2.save("b.jpg","JPEG")

rawDescription: Making an image bigger after creating it


code:
class Meta:
    unique_together = (('bar', 'name'),)

rawDescription: django unique relations not unique table

description: Django unique relations not unique table


code:
w = open('<filename>','w+b')
w.write(f.read())

rawDescription: http file upload to disk

description: Http file upload to disk


rawDescription: Getting the pattern back from a compiled re?


code:
s = (W != 0).multiply(sp.csr_matrix(v))
W + s

rawDescription: Add a dense vector to a sparse matrix in scipy (via broadcasting)


code:
from random import choice

get_signal_somehow = lambda: choice(["A", "B"])

def main():
    A = routine_a()
    B = routine_b()
    signal = get_signal_somehow()
    while True:
        if signal == 'A':
            signal = next(A)
        elif signal == 'B':
            signal = next(B)

def routine_a():
    #do stuff
    if get_signal_somehow() == 'B':
        yield 'B'
    else:
        yield 'A'

def routine_b():
    #do stuff
    if get_signal_somehow() == 'A':
        yield 'A'
    else:
        yield 'B'

rawDescription: Python switching between routines

description: Python switching between routines


code:
from datetime import datetime, timedelta

class DisplayServices(ListView):
    queryset = Service.objects.filter(pub_date__gte=datetime.now()-timedelta(days=60))

    ...

rawDescription: Expiration logic with DateTimeField in Django


code:
@pytest.fixture(scope='session')
def sessiondir(request):
    dir = py.path.local(tempfile.mkdtemp())
    request.addfinalizer(lambda: dir.remove(rec=1))
    # Any extra setup here
    return dir

@pytest.fixture
def dir(sessiondir, tmpdir):
    sessiondir.copy(tmpdir)
    return tmpdir

rawDescription: py.test: Temporary folder for the session scope

description: Py.test: Temporary folder for the session scope


code:
df = DataFrame({'A' : np.random.randn(10000)},index=pd.date_range('20130101',periods=10000,freq='s'))
store = pd.HDFStore('test.h5',mode='w')
store.append('df',df)
nrows = store.get_storer('df').nrows
nrows
store.select('df',start=nrows-1,stop=nrows)
df.iloc[[-1]]

rawDescription: Get last row in pandas HDF5 query

description: Get last row in pandas HDF5 query


code:
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import pyqtSignal
import os,sys

class Main(QtGui.QWidget):

    def __init__(self, parent=None):
        super(Main, self).__init__(parent)

        layout = QtGui.QVBoxLayout(self) # layout of main widget

        button =  HoverButton(self)
        button.setIconSize(QtCore.QSize(200,200))

        layout.addWidget(button) # set your button to the widgets layout
                                 # this will size the button nicely

class HoverButton(QtGui.QToolButton):

    def __init__(self, parent=None):
        super(HoverButton, self).__init__(parent)
        self.setMouseTracking(True)

    def enterEvent(self,event):
        print("Enter")
        self.setStyleSheet("background-color:#45b545;")

    def leaveEvent(self,event):
        self.setStyleSheet("background-color:yellow;")
        print("Leave")

app = QtGui.QApplication(sys.argv)
main = Main()
main.show()
sys.exit(app.exec_())

rawDescription: Hover issue in PyQt

description: Hover issue in PyQt


code: names = [person.GetName() for person in persons]

rawDescription: Converting a list of dict to a list of a specific value


code:
overlapped = plot(xdata[-2:-1],ydata[-2:-1],'-',lw=4.5)

for item in overlapped:
    item.set_solid_capstyle('butt')

rawDescription: Accurate line ends with matplotlib

description: Accurate line ends with matplotlib


code:
print (re.match(r"(?:aaa)(_bbb)", string1).group(0))
print (re.match(r"(?:aaa)(_bbb)", string1).group(1))
print (re.match(r"(?:aaa)(_bbb)", string1).group(2))

rawDescription: Why regular expression's "non-capturing" group is not working


code:
#!/usr/bin/python

import copy

class Test:
    def __init__(self):
        ...
        info = {'tBin'   : __tBin.copy(),
                'pBin'   : __pBin.copy(),
                'results': __results}
        ...
        self.__tests = {'test1' : copy.deepcopy(info),
                        'test2' : copy.deepcopy(info),
                        'test3' : copy.deepcopy(info)}

    def test(self):
        ...

...

rawDescription: Python Two Dictionaries within another Dictionary within another Dictionary


code:
class PredictionTransformer(sklearn.base.BaseEstimator, sklearn.base.TransformerMixin):
    def __init__(self, estimator):
        self.estimator = estimator

    def fit(self, X, y):
        self.estimator.fit(X, y)
        return self

    def transform(self, X):
        return self.estimator.predict_proba(X)

rawDescription: Can one train estimators in a scikit-learn pipeline simultaneously?


code:
if all(i % n == 0 for n in range(11, 101)):
    print(i)

rawDescription: Testing divisibility by multiple numbers


code:
from django.utils.html import urlize
from bs4 import BeautifulSoup

def html_urlize(self, text):
    soup = BeautifulSoup(text, "html.parser")

    print(soup)

    textNodes = soup.findAll(text=True)
    for textNode in textNodes:
        if textNode.parent and getattr(textNode.parent, 'name') == 'a':
            continue  # skip already formatted links
        urlizedText = urlize(textNode)
        textNode.replaceWith(BeautifulSoup(urlizedText, "html.parser"))

    print(soup)

    return str(soup)

rawDescription: BeautifulSoup replaceWith() method adding escaped html, want it unescaped


code:
def strip_http_headers(http_reply):
    p = http_reply.find('\r\n\r\n')
    if p >= 0:
        return http_reply[p+4:]
    return http_reply

rawDescription: How do I get the body of a http response from a string containing the entire response, in Python?

description: Get the body of a http response from a string containing the entire response, in Python


code:
labels = ['business', 'health']
cm = confusion_matrix(y_test, pred, labels)
print(cm)
fig = plt.figure()
ax = fig.add_subplot(111)
cax = ax.matshow(cm)
pl.title('Confusion matrix of the classifier')
fig.colorbar(cax)
ax.set_xticklabels([''] + labels)
ax.set_yticklabels([''] + labels)
pl.xlabel('Predicted')
pl.ylabel('True')
pl.show()

rawDescription: sklearn plot confusion matrix with labels

description: Sklearn plot confusion matrix with labels


code:
reader1, reader2 = itertools.tee(csv.reader(f, delimiter=d))
columns = len(next(reader1))
del reader1
for row in reader2:
    ...

rawDescription: Find number of columns in csv file

description: Find number of columns in csv file


code:
ax = DataFrame([1]).plot(kind='bar')
ax.lines[0].set_visible(False)
ax.set_ylim(-0.2, 1.2)

rawDescription: Strange dashed line in pandas bar plot

description: Strange dashed line in pandas bar plot


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

center = (4.3323, 2.3433)
angles = [60, 120, 240]
angles = [a/180.0*np.pi for a in angles]

# scale
l = 1

# the center point
x, y = center

# draw each line
for a in angles:
    dx = l * np.sin(a)
    dy = l * np.cos(a)
    plt.plot([x, x + dx], [y, y + dy], 'k-')

# draw the center circle
plt.plot(x, y, 'wo', ms=l*100)
plt.show()

rawDescription: Representing a Fan Shaped Image on a Map using Python


code:
import dns.resolver

my_resolver = dns.resolver.Resolver()

# 8.8.8.8 is Google's public DNS server
my_resolver.nameservers = ['8.8.8.8']

answer = my_resolver.query('google.com')

rawDescription: Set specific DNS server using dns.resolver (pythondns)


code:
from django.core.management import call_command
call_command('loaddata', 'data.json', stdout=out, verbosity=0)

rawDescription: Load fixture.json through python script

description: Load fixture.json through python script


code:
def test(actual, expected):
    """ Compare the actual to the expected value,
        and print a suitable message.
    """
    import sys
    linenum = sys._getframe(1).f_lineno   # get the caller's line number.
    if (expected == actual):
        msg = "Test on line {0} passed.".format(linenum)
    else:
        msg = ("Test on line {0} failed. Expected '{1}', but got '{2}'."
                                     . format(linenum, expected, actual))
    print(msg)

rawDescription: test()-function in python? Book "How to Think Like a Computer Scientist"

description: Test()-function in python? Book "How to Think Like a Computer Scientist"


code:
class A(object):
    def __init__(self):
        self.x = "whatever"
        self.y= "cumbersome"
        self.z = "idea"

    def method1(self):
        self.x = self.x.lower()

class B(A):
    def __init__(self):
         super(B, self).__init__()
         self.a = 87

    def method1(self):
         super(B, self).method1()
         self.y =self.y.upper()

rawDescription: Clean and DRY way to extend an Object in Python


rawDescription: Can i get all methods of a python object?

description: Get all methods of a python object


code:
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

FLOOR = -10
CEILING = 10

class AnimatedScatter(object):
    def __init__(self, numpoints=5):
        self.numpoints = numpoints
        self.stream = self.data_stream()
        self.angle = 0

        self.fig = plt.figure()
        self.fig.canvas.mpl_connect('draw_event',self.forceUpdate)
        self.ax = self.fig.add_subplot(111,projection = '3d')
        self.ani = animation.FuncAnimation(self.fig, self.update, interval=100,
                                       init_func=self.setup_plot, frames=20)

    def change_angle(self):
        self.angle = (self.angle + 1)%360

    def forceUpdate(self, event):
        self.scat.changed()

    def setup_plot(self):
        X = next(self.stream)
        c = ['b', 'r', 'g', 'y', 'm']
        self.scat = self.ax.scatter(X[:,0], X[:,1], X[:,2] , c=c, s=200)

        self.ax.set_xlim3d(FLOOR, CEILING)
        self.ax.set_ylim3d(FLOOR, CEILING)
        self.ax.set_zlim3d(FLOOR, CEILING)

        return self.scat,

    def data_stream(self):
        data = np.zeros(( self.numpoints , 3 ))
        xyz = data[:,:3]
        while True:
            xyz += 2 * (np.random.random(( self.numpoints,3)) - 0.5)
            yield data

    def update(self, i):
        data = next(self.stream)
        self.scat._offsets3d = ( np.ma.ravel(data[:,0]) , np.ma.ravel(data[:,1]) , np.ma.ravel(data[:,2]) )
        return self.scat,

    def show(self):
        plt.show()

if __name__ == '__main__':
    a = AnimatedScatter()
    a.ani.save("movie.avi", codec='avi')
    a.show()

rawDescription: Saving scatterplot animations with matplotlib


rawDescription: Append element to smallest list in dictionary of lists


code:
item_list = [('apple OR ora nge AND NOT pineapple'), ('(sugar and salt) or (pepper and vinegar)')]
[[x.strip() for x in re.split(r'(?i)(?:\b(?:AND|OR|NOT)\b|[]\[()])', x) if x.strip()] for x in item_list]

rawDescription: Split string based on certain words and remove certain special characters in Python


code:
from appscript import *
it = app('iTunes')   # the "application" object
it.player_state()    # access properties of the "application" object
it.player_position() #   (calling the property "( )" implies a "get" action)
it.player_position()
it.current_track.artist()

rawDescription: Using ScriptingBridge and Python, what properties can I get from the track currently playing?


code:
def is_finite(x):
    return not math.isnan(x) and not math.isinf(x)

def get_floats(source):
    for x in source.split():
        try:
            yield float(x)
        except ValueError:
            pass

def get_finite_floats(source):
    return (x for x in get_floats(source) if is_finite(x))

rawDescription: convert string to float without silent NaN/Inf conversion

description: Convert string to float without silent NaN/Inf conversion


code:
lst = [ ( 132, 'foobar' ), ( 58, 'other value' ) ]
lst.append( ( 70, 'some data value' ) )
lst
lst.sort( key=lambda x: x[0] )
lst
lst.sort( key=lambda x: x[1] )
lst

rawDescription: Python - Which data structure to use?

description: Python - Which data structure to use


code:
# Create an uninitialised array with 100 records
a = numpy.recarray(100,
                   formats=["f8", "f8", "i4"],
                   names=["latitude", "longitude", "date"])
# initialise to 0
a[:] = (0.0, 0.0, 0)
# assign a single record
a[0] = (-65.100234, -38.32432, 1309351408)
# access the date of the first record
a[0].date
# access the whole date column
a.date

rawDescription: Simple to implement struct for memory efficient list of tuples


code:
a=frange(0,1.0,0.01)
for z in itertools.product(a, repeat=n):
    calculate(*z)

rawDescription: Iteration over n values

description: Iteration over n values


code: enumerate(j for j in range(10) if (3 < j) and (j < 8))

rawDescription: Conditionally enumerating items in python


code:
search_phrase = "Escherichia coli[organism]) AND (complete genome[keyword])"
handle = Entrez.esearch(db="nuccore", term=search_phrase, retmax=100)
result = Entrez.read(handle)
handle.close()
fetch_handle = Entrez.efetch(db="nuccore", id=results["IdList"], rettype="acc", retmode="text")
acc_ids = [id.strip() for id in fetch_handle]
fetch_handle.close()
print(acc_ids)

rawDescription: Using search terms with Biopython to return accession numbers


code: df.to_csv(path, mode='a')

rawDescription: Concatenate rows of data to new dataframe in Pandas


code:
df1
df2
df3
df4

rawDescription: Transforming financial data from postgres to pandas dataframe for use with Zipline


code:
from docx import *
from docx.shared import Inches

def TestDocument(request):

    document = Document()
    docx_title="TEST_DOCUMENT.docx"
    # ---- Cover Letter ----
    document.add_picture((r'%s/static/images/my-header.png' % (settings.PROJECT_PATH)), width=Inches(4))
    document.add_paragraph()
    document.add_paragraph("%s" % date.today().strftime('%B %d, %Y'))

    document.add_paragraph('Dear Sir or Madam:')
    document.add_paragraph('We are pleased to help you with your widgets.')
    document.add_paragraph('Please feel free to contact me for any additional information.')
    document.add_paragraph('I look forward to assisting you in this project.')

    document.add_paragraph()
    document.add_paragraph('Best regards,')
    document.add_paragraph('Acme Specialist 1]')
    document.add_page_break()

    # Prepare document for download
    # -----------------------------
    f = StringIO()
    document.save(f)
    length = f.tell()
    f.seek(0)
    response = HttpResponse(
        f.getvalue(),
        content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    )
    response['Content-Disposition'] = 'attachment; filename=' + docx_title
    response['Content-Length'] = length
    return response

rawDescription: Generate the MS word document in django

description: Generate the MS word document in django


code:
q = session.query(Member).\
        join(Member.group).\
        join(Group.department).\
        filter(Department.name=='depart_name')

result = q.all()

rawDescription: SQLAlchemy Relationships between 3 tables


rawDescription: How to evaluate a non-variable node in computation graph of Tensorflow?

description: Evaluate a non-variable node in computation graph of Tensorflow


code:
import numpy as np
from numpy import exp,arange,log
from pylab import meshgrid,cm,imshow,contour,clabel,colorbar,axis,title,show,streamplot

# PSI = streamline
def f(x, y, U = 5, hv = 18.326581, cv = 37.0857):
    x2 = x ** 2
    y2plus = (y + hv) ** 2
    y2minus = (y - hv) ** 2
    PSI_1 = U * y
    PSI_2 =   0.5 * cv * log(x2 + y2minus)
    PSI_3 = - 0.5 * cv * log(x2 + y2plus)
    psi = PSI_1 + PSI_2 + PSI_3
    return psi

x = arange(-20.0,20.0,0.1)
y = arange(-20.0,20.0,0.1)
X,Y = meshgrid(x, y) # grid of point
#Z = z_func(X, Y) # evaluation of the function on the grid
Z= f(X, Y)

dx, dy = 1e-6, 1e-6
U = (f(X+dx, Y) - f(X, Y))/dx
V = (f(X, Y+dy) - f(X, Y))/dy
streamplot(X, Y, U, V, linewidth=1, color=(0, 0, 1, 0.3))

cset = contour(X, Y, Z,arange(-20,20,2.0),linewidths=2,cmap=cm.Set2)
clabel(cset,inline=True,fmt='%1.1f',fontsize=9)
colorbar(im) # adding the colobar on the right

# latex fashion title
title('$phi= 5.0 y + (1/2)* 37.0857 log(x^2 + (y - 18.326581)^2)-(1/2)* 37.085...$')

show()

rawDescription: Working code but getting a "confusing" plot with labels


code:
time = [0]
[time] = time
time

rawDescription: Python - List issues (multiple lists?)

description: Python - List issues (multiple lists?)


code:
#!/usr/bin/env python3

import matplotlib.pyplot as plt
from itertools import cycle

def main():

    colors = cycle(["aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "purple", "red", "silver", "teal", "yellow"])

    data = [
        [
            [1,   2, 3,   4, 5],
            [1, 1.5, 2, 2.5, 3]
        ],
        [
            [1, 2, 3, 4, 5, 6,  2],
            [1, 2, 3, 4, 6, 9, 10]
        ],
        [
            [1, 3, 5,  7],
            [1, 4, 9, 16]
        ]
    ]

    fig = plt.figure()
    ax = fig.add_subplot(111)

    for i, item in enumerate(data):
        ax.plot(item[0], item[1], label="Data " + str(i), color=next(colors))

    ax.set_xlabel("Number of Hellos", fontsize=15)
    ax.set_ylabel("Number of Worlds", fontsize=18)

    ax.legend(loc="best")

    ax.margins(0.1)
    fig.tight_layout()

    plt.savefig("mwe.png")

if __name__ == "__main__":
    main()

rawDescription: Matplotlib: (Automating) Plotting unknown number of data sources/line/plots on 1 subplot


code:
post_parameters = {
    'methods[]':'CF',
    'aasequence':'EEEEEEEEEEEEEEEEEEE'
}

rawDescription: Not getting the correct response In BeautifulSoup parsing


code:
import sys
from PyQt4 import QtGui, QtCore

class MainForm(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(MainForm, self).__init__(parent)

        # create button
        self.button = QtGui.QPushButton("test button", self)
        self.button.resize(100, 30)

        # set button context menu policy
        self.button.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        self.button.customContextMenuRequested.connect(self.on_context_menu)

        # create context menu
        self.popMenu = QtGui.QMenu(self)
        self.popMenu.addAction(QtGui.QAction('test0', self))
        self.popMenu.addAction(QtGui.QAction('test1', self))
        self.popMenu.addSeparator()
        self.popMenu.addAction(QtGui.QAction('test2', self))

    def on_context_menu(self, point):
        # show context menu
        self.popMenu.exec_(self.button.mapToGlobal(point))

def main():
    app = QtGui.QApplication(sys.argv)
    form = MainForm()
    form.show()
    app.exec_()

if __name__ == '__main__':
    main()

rawDescription: Right click contextMenu on QPushButton

description: Right click contextMenu on QPushButton


code:
settings.py
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES['default'] =  dj_database_url.config()

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']

# Static asset configuration
import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)

rawDescription: Is ALLOWED_HOSTS needed on Heroku?

description: Is ALLOWED_HOSTS needed on Heroku


code:
#!/usr/bin/env python
import re
import nltk  # $ pip install nltk

def paragraphs(file):
    """Yield blank-line separated paragraphs labeled with ##-numbers."""
    lines = []
    for line in file:
        if line.strip():
            lines.append(line)
        elif lines:  # blank line, the end of a non-empty paragraph
            paragraph = ''.join(lines)
            numbers = re.findall(r'##([0-9]+)', paragraph)  # only ASCII-digits
            assert len(numbers) == 1  # only one ##-number per paragraph
            yield int(numbers[0]), paragraph
            del lines[:]

def sentences(filenames):
    for filename in filenames:
        with open(filename) as file:
            for number, paragraph in paragraphs(file):
                for sentence in nltk.sent_tokenize(paragraph):
                    yield number, sentence

filenames = ('w_acad_%d.txt' % n for n in range(1990, 2013))
print(reservoir_sample(sentences(filenames), 2000))

rawDescription: Randomly Select Sentences from Text File, Find Coresponding ID Number


code:
argList = ["egg1", "egg2"]
egg2(*argList)

rawDescription: How to split list and pass them as separate parameter?

description: Split list and pass them as separate parameter


code:
xpath = "//table[2]/tr/td//text()[re:match(., '\\S')]"

filtered_html = tree.xpath(
    xpath,
    namespaces={"re": "http://exslt.org/regular-expressions"})

rawDescription: Timetable Web Scraping with multiple tables (Python)


code: data_df.plot(x='Compression Velocity', y='Compression Force', xticks=d['Compression Velocity'])

rawDescription: Set x-axis intervals(ticks) for graph of Pandas DataFrame


code:
def digit_to_char(digit):
    if digit < 10:
        return str(digit)
    return chr(ord('a') + digit - 10)

def str_base(number,base):
    if number < 0:
        return '-' + str_base(-number, base)
    (d, m) = divmod(number, base)
    if d > 0:
        return str_base(d, base) + digit_to_char(m)
    return digit_to_char(m)

rawDescription: Python elegant inverse function of int(string,base)


code:
if settings.DEBUG:
    import debug_toolbar
    urlpatterns += patterns(
        'django.views.static',
        (r'media/(?P<path>.*)',
        'serve',
        {'document_root': settings.MEDIA_ROOT}),
        url(r'^__debug__/', include(debug_toolbar.urls))
    )

rawDescription: (Django) How to apply css?

description: (Django) How to apply css


code:
def draw_ngon(Surface, color, n, radius, position):
    pi2 = 2 * 3.14

    for i in range(0, n):
        pygame.draw.line(Surface, color, position, (cos(i / n * pi2) * radius + position[0], sin(i / n * pi2) * radius + position[1]))

    return pygame.draw.lines(Surface,
          color,
          True,
          [(cos(i / n * pi2) * radius + position[0], sin(i / n * pi2) * radius + position[1]) for i in range(0, n)])

rawDescription: Drawing pentagon,hexagon in Pygame

description: Drawing pentagon,hexagon in Pygame


code:
if mydict["key"]:
    ...

rawDescription: The most Pythonic way of checking if a value in a dictionary is defined/has zero length


code:
def custom_sort(population):
    pop_dict = { ind.ID: ind for ind in population }

    start = []
    nones = []
    end = []
    for ind in population:
        if ind.mate is None:
            nones.append(ind)
        elif pop_dict[ind.mate] not in start:
            start.insert(0, ind)
            end.append(pop_dict[ind.mate])
    return start + nones + end

rawDescription: Python: Sort a list according to two attributes


code:
with open('def') as f1, open('abc') as f2, open('out.txt', 'w') as f3:
    in_atoms = False # state -> in_atoms (only 2 states)

    # read `def` file content into memory as set
    references = set(f1.read().split())

    # Removed a loop which iterate reference file.
    for line in f2:
        if line.startswith('Atoms'):
            in_atoms = True
        elif line.startswith('Velocities'):
            in_atoms = False
        elif in_atoms:
            values = line.split()
            # Check number match with one of the references.
            if values and values[0] in references:
                values[2] = '100'
                line = ' '.join(values) + '\n'
        f3.write(line)

rawDescription: Modifying data file with certain condition in row


code: new_class = type("new_class", cls_list, {})

rawDescription: How to Inherit a list of python class object into a class?


code: count=sum(i!=j for i,j in zip(list1,list2))

rawDescription: How to count the difference between two nested lists in Python?

description: Count the difference between two nested lists in Python


code:
import matplotlib as mpl
import matplotlib.pylab as plt
import numpy as np
np.random.seed(42)

# create some toy data
n, m = 2, 2
data = []
for i in range(n*m):
    data.append(np.random.rand(30))

# and do the plotting
with mpl.rc_context():
    mpl.rc("axes", color_cycle="red")
    fig, axes = plt.subplots(n, m, figsize=(8,8))
    for ax, d in zip(axes.flat, data):
        ax.hist(d)

rawDescription: how to change the colors of multiple subplots at once?

description: Change the colors of multiple subplots at once


code:
import glob
import os

names = ['Info_1_250.csv', 'Info_1_500.csv', 'Info_1_1000.csv']

path_name = '/Users/user/Desktop/test/'
third_level_path = os.path.join(path_name, '*', '*')
dirs = [d for d in glob.glob(third_level_path) if os.path.isdir(d)]

for d in dirs:
    for name in names:
        f = os.path.join(d, name)
        if not os.path.isfile(f):
            write_file(f)

rawDescription: Write file if file does not exist in a recursive way


code:
def __init__(self):
    ...
    QObject.connect(self.cbLayer, SIGNAL("currentIndexChanged(int)"), self.warn)

def warn(index):
    QMessageBox.warning(self, "items: ", do_stuff(cbLayer.itemData(index)) )

def do_stuff(self, item):
    QMessageBox.warning(self, str(item))

rawDescription: display a QMessageBox PyQT when a different combobox /list box item is selected

description: Display a QMessageBox PyQT when a different combobox /list box item is selected


code:
def delete(self, key):
    """ delete the node with the given key and return the
    root node of the tree """

    if self.key == key:
        # found the node we need to delete

        if self.right and self.left:

            # get the successor node and its parent
            [psucc, succ] = self.right._findMin(self)

            # splice out the successor
            # (we need the parent to do this)

            if psucc.left == succ:
                psucc.left = succ.right
            else:
                psucc.right = succ.right

            # reset the left and right children of the successor

            succ.left = self.left
            succ.right = self.right

            return succ

        else:
            # "easier" case
            if self.left:
                return self.left    # promote the left subtree
            else:
                return self.right   # promote the right subtree
    else:
        if self.key > key:          # key should be in the left subtree
            if self.left:
                self.left = self.left.delete(key)
            # else the key is not in the tree

        else:                       # key should be in the right subtree
            if self.right:
                self.right = self.right.delete(key)

    return self

def _findMin(self, parent):
    """ return the minimum node in the current tree and its parent """

    # we use an ugly trick: the parent node is passed in as an argument
    # so that eventually when the leftmost child is reached, the
    # call can return both the parent to the successor and the successor

    if self.left:
        return self.left._findMin(self)
    else:
        return [parent, self]

rawDescription: delete node in binary search tree python

description: Delete node in binary search tree python


code:
class DTestWrapper(BaseA if inLinux else unittest.TestCase):
    def setUpDTest(self):
        parent_method = 'setUpTestCase' if inLinux else 'setUp'
        getattr(super(DTestWrapper, self), parent_method)()

    def tearDownDTest(self):
        parent_method = 'tearDownTestCase' if inLinux else 'tearDown'
        getattr(super(DTestWrapper, self), parent_method)()

rawDescription: How to call functions from different base class

description: Call functions from different base class


code:
corpus = []
for i in range(len(data) -1):
    corpus.append(data[i]['body'] + data[i+1]['body'])
print(corpus)

rawDescription: Concatenating through a loop articles in Python


code:
import simplejson, urllib
orig_coord = orig_lat, orig_lng
dest_coord = dest_lat, dest_lng
url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins={0}&destinations={1}&mode=driving&language=en-EN&sensor=false".format(str(orig_coord),str(dest_coord))
result= simplejson.load(urllib.urlopen(url))
driving_time = result['rows'][0]['elements'][0]['duration']['value']

rawDescription: Python Google Maps Driving Time

description: Python Google Maps Driving Time


code:
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User

from userena.models import UserenaLanguageBaseProfile

import datetime

class Profile(UserenaLanguageBaseProfile):
    """ Default profile """
    GENDER_CHOICES = (
        (1, _('Male')),
        (2, _('Female')),)

    user = models.OneToOneField(User,
                                unique=True,
                                verbose_name=_('user'),
                                related_name='profile')

    gender = models.PositiveSmallIntegerField(_('gender'),
                                              choices=GENDER_CHOICES,
                                              blank=True,
                                              null=True)
    website = models.URLField(_('website'), blank=True, verify_exists=True)
    location =  models.CharField(_('location'), max_length=255, blank=True)
    birth_date = models.DateField(_('birth date'), blank=True, null=True)
    about_me = models.TextField(_('about me'), blank=True)

rawDescription: How to accomplish integration of django-userena and social auth

description: Accomplish integration of django-userena and social auth


code:
def main():
    # calculate something
    num1, num2 = randomNumbers()
    # calculate something else

def randomNumbers():
    # calculate something
    return num1, num2

rawDescription: Avoiding using globals in python

description: Avoiding using globals in python


rawDescription: How can I plot output from a function which returns multiple values in Python?

description: Plot output from a function which returns multiple values in Python


code:
def hist_norm_height(n,bins,const):
    ''' Function to normalise bin height by a constant.
        Needs n and bins from np.histogram or ax.hist.'''

    n = np.repeat(n,2)
    n = float32(n) / const
    new_bins = [bins[0]]
    new_bins.extend(np.repeat(bins[1:],2))
    return n,new_bins[:-1]

rawDescription: Dividing matplotlib histogram by maximum bin value


rawDescription: Numpy: Add Rows of Matrix over another Matrix of different dimension


code:
wrap('HA HA HA /services/nfs_qa/log.lol HO HO HO', '/services/nfs_qa/[^ ]*')
'HA HA HA Link to the file HO HO HO'

rawDescription: Regex to convert path to URL

description: Regex to convert path to URL


code:
for x in a[:]: # make a slice copy of the entire list
   if len(x) > 6: a.insert(0, x)
a

rawDescription: Is safe ( documented behaviour? ) to delete the domain of an iterator in execution


rawDescription: How do you remove the nth index of a nested list?

description: Remove the nth index of a nested list


code:
import json

f = open('/path/to/your/json', 'r')
persons = json.load(f)
years_months = {}
years_months_names = {}

for person in persons['persons']:
    year = person['dob'][-4:]
    month = person['dob'][3:5]
    month_year = month + ' ' + year
    name = person['name']

    if year not in years_months.keys():
        years_months[year] = { 'count': 1, 'months' : {} }
        if month not in years_months[year]['months'].keys():
            years_months[year]['months'][month] = 1
        else:
            years_months[year]['months'][month] += 1
    else:
        years_months[year]['count'] += 1
        if month not in years_months[year]['months'].keys():
            years_months[year]['months'][month] = 1
        else:
            years_months[year]['months'][month] += 1

    if month_year not in years_months_names.keys():
        years_months_names[month_year] = set([name])
    else:
        years_months_names[month_year].add(name)

for k, v in years_months.items():
    print(k + ': ' + str(v['count']))
    for month, count in v['months'].items():
        print("-- " + str(month) + ": " + str(count))
for k, v in years_months_names.items():
    print(k + ": " + str(len(v)))

rawDescription: Nested Counter for json data

description: Nested Counter for json data


code: type(l[0]) in [int, str] and all( type(e) == type(l[0]) for e in l)

rawDescription: the simple way to check if the elements of a list or set are single type?

description: The simple way to check if the elements of a list or set are single type


code:
capitals = {
    'Austria': 'Vienna',
    'Belgium': 'Brussels',
    'Denmark': 'Copenhagen',
    'France': 'Paris',
    'Germany': 'Berlin',
    'Netherlands': 'Amsterdam',
    'Norway': 'Oslo',
    'Sweden': 'Stockholm',
    'Switzerland': 'Bern',
    'United Kingdom': 'London'
}

while True:
    country = input("Enter a country: ")

    # abort the loop if the user didn’t enter anything
    if not country:
        break

    # check whether we know that country
    if country in capitals:
        capital = input("What is the capital of {}? ".format(country))

        if capital == capitals[country]:
            print('That was correct!')
        else:
            print('You made a mistake there.')

    else:
        print('I do not know that country, sorry.')

rawDescription: How to compare two objects in a dictionary

description: Compare two objects in a dictionary


code:
response = make_response(send_file(mp3_filepath))
response.headers['X-Something'] = 'header value goes here'
return response

rawDescription: How to send header in flask send_file?

description: Send header in flask send_file


code:
class AddressModelAdmin(admin.ModelAdmin):
    def get_readonly_fields(self, request, obj=None):
        if obj: # If object exists, means you're editing one.
            return self.readonly_fields + ('street1', 'street2')
        return self.readonly_fields

rawDescription: How can i have only a VIEW(readonly) function in django admin's page where there is a table named X and having some data in it?

description: Have only a VIEW(readonly) function in django admin's page where there is a table named X and having some data in it


code:
import boto3

sqs = boto3.resource('sqs')
emq = boto3.resource('sqs', endpoint_url="http://www.foo.com")

rawDescription: Set the endpoint for boto3 SQS

description: Set the endpoint for boto3 SQS


code:
def test():
    return (1, 2)

thing = test()
thing
type(thing)
type(thing).__name__

rawDescription: Force Python function to return type 'tuple'


code:
stdin_list = list(sys.stdin)
sys.stdin = open('/dev/tty')
for filepath in stdin_list:
    dir = os.path.basename(filepath)
    ...
    IPython.embed()

rawDescription: How do I debug a script that uses stdin with ipython?

description: Debug a script that uses stdin with ipython


code:
import os

env_name = 'g_folder'
assembly_name = 'genome_assembly_name'

g = os.getenv(env_name)
assembly = os.getenv(assembly_name)

file_name = os.path.join(g, assembly) + ".fa"

rawDescription: Passing environmental variables as parameters


code:
class MultiWrite(object):
    def __init__(self, *files):
        self.files = files
    def write(self, text):
        for file in self.files:
            file.write(text)
    def close(self):
        for file in self.files:
            file.close()

import sys

# no need to save stdout. There's already a copy in sys.__stdout__.
sys.stdout = MultiWrite(open('file-1', 'w'), open('file-2', 'w'))
print("Hello, World!")

sys.stdout.close()

sys.stdout = sys.__stdout__  #reassign old stdout.

rawDescription: How do I log the contents of print messages to two files with stdout

description: Log the contents of print messages to two files with stdout


code:
b, c = [], []
for i, j in map(lambda x: x.func1(), list1):
    b.append(i)
    c.append(j)

rawDescription: Return different variables from map()

description: Return different variables from map()


code:
tup_1 = 5, 'adasd', 'dadas'
tup_2 = 4, 'adasda', 'dadad'
tup_3 = 3, 'adasds', 'asdasda'
gap = -2
score = 2

print(max((tup_1[0] + score, tup_1),
          (tup_2[0] + gap, tup_2),
          (tup_3[0] + gap, tup_3))[1])

rawDescription: max() function, getting the max tuple

description: Max() function, getting the max tuple


code:
list = ['apples','grapes','bannas','peaches','pears','oranges','mangos']
a,b = random.sample(list, 2)
a
b

rawDescription: How to eliminate an item from a list after using random.choice()?

description: Eliminate an item from a list after using random.choice()


code:
def cartprod(x,y):
    nx = len(x)
    ny = len(y)
    for i in range(nx+ny):
        for j in range(max(0,i-ny+1), min(i+1,nx)):
            yield (x[j],y[i-j])

rawDescription: How to iterate the cartesian product so top items combine first?

description: Iterate the cartesian product so top items combine first


code:
from datetime import datetime as dt
dt.now()
# you can also use dt.max, dt.min, etc.

rawDescription: how to directly import now() from datetime.datetime submodule

description: Directly import now() from datetime.datetime submodule


code:
lstlen=len(sslist)
sslist = [sum(sslist[i:min(i+grouping,lstlen)]) for i in range(lstlen)]

rawDescription: Taking the sum of a sliding window of indices in python


code: min(max(x,lo),hi)

rawDescription: How would I write this program without using conditionals


code:
class WebsocketEchoHandler:
    @asyncio.coroutine
    def __call__(self, request):
        ws = web.WebSocketResponse()
        ws.start(request)

        connection = yield from asyncio_redis.Connection.create(host='127.0.0.1', port=6379)
        subscriber = yield from connection.start_subscribe()
        yield from subscriber.subscribe(['ch1', 'ch2'])

        print('Connection opened')
        try:
            # Kick off both coroutines in parallel, and then block
            # until both are completed.
            yield from asyncio.gather(self.handle_ws(ws), self.handle_redis(subscriber))
        except Exception as e:  # Don't do except: pass
            import traceback
            traceback.print_exc()
        finally:
            print('Connection closed')
        return ws

    @asyncio.coroutine
    def handle_ws(self, ws):
        while True:
            msg_ws = yield from ws.receive()
            if msg_ws:
                self.on_msg_from_ws(msg_ws)

    @asyncio.coroutine
    def handle_redis(self, subscriber):
        while True:
            msg_redis = yield from subscriber.next_published()
            if msg_redis:
                self.on_msg_from_redis(msg_redis)

rawDescription: Asyncio + aiohttp - redis Pub/Sub and websocket read/write in single handler


code:
from datetime import datetime, timedelta

one_day_interval_before = datetime.now() - timedelta(days=1)

rawDescription: How to calculate past 1 day interval from current time in sqlalchemy

description: Calculate past 1 day interval from current time in sqlalchemy


code:
def form_valid(self, request, *args, **kwargs):
    is_actually_valid = some_custom_logic()
    if not is_actually_valid:
        return self.form_invalid(request, *args, **kwargs)

rawDescription: How can redirect to form invalid from the form_valid function in django


code:
form_class = forms.models.modelform_factory(Einflussideen,
                 widgets={'einfluss': forms.RadioSelect(choices=EINFLUSS)})

rawDescription: Understanding UpdateView to change the Form and FormWidget


code:
if settings.DEBUG:
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    from django.conf.urls.static import static

    # this connects STATIC_URL to STATIC_ROOT
    urlpatterns += staticfiles_urlpatterns()

    # connect other paths to directories
    urlpatterns += static(settings.MEDIA_URL,
        document_root=settings.MEDIA_ROOT)
    urlpatterns += static('/app/',
        document_root=join(settings.BASE_DIR, '../ng_app/'))

rawDescription: What is the right way to setup urls.py for django-rest-framework + angular-route + static files?


code:
class ArticleManager(models.Manager):
    def get_queryset(self):
        return super(ArticleManager, self).get_queryset().filter(origin=None)

class Article(models.Model):
    objects = ArticleManager()
    origin = models.ForeignKey('self', null=True, related_name="%(app_label)s_%(class)s_revision")

rawDescription: Django recursive relationship: How to remove object from Manager object


code:
def process(request):
    if request.method == 'POST':
        data = request.POST
        spec_filter = {}
        for attribute in ['screenGroup', 'storage', 'mSystem']:
            if attribute in data and data[attribute]:
                spec_filter[attribute] = data[attribute]
        results = Specs.objects.filter(**spec_filter)
        context = {'results' : results}
        return render(request, 'process.html', context)

rawDescription: Filter only if the value is defined in Django


code:
functype = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, ctypes.c_int)
func = functype(raw_address)
func

rawDescription: Python ctype directly call a function with raw offset


code:
item_position = [i for i, x in enumerate(list2) if x[0] == (16,29,32,40) ]
print("item_position", item_position)

rawDescription: How do I find index of list in nested list in python

description: Find index of list in nested list in python


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

#Generate data
delta = 0.025

x = numpy.arange(-3.0, 3.0, delta)
y = numpy.arange(-2.0, 2.0, delta)

X, Y = numpy.meshgrid(x, y)

Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

#Plot
fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)

PC = ax1.pcolor(X, Y, Z)
CF = ax1.contour(X, Y, Z, 50, colors = "black")

cbar = plt.colorbar(PC)
cbar.add_lines(CF)

plt.show()

rawDescription: Matplotlib: contourlevels as lines in colorbar


code:
import datetime
mindate = datetime.date(datetime.MINYEAR, 1, 1)

def getaccountingdate(x):
  return x['accountingdate'] or mindate

results = sorted(results, key=getaccountingdate, reverse=True)

rawDescription: In python, sorting on date field, field may sometimes be null


code:
import numpy as np
X, Y = np.meshgrid(np.arange(0, 2, 0.1), np.arange(3, 5, 0.1))
def func(x) :
    return x[0]**2 + x[1]**2

Z = func([X,Y])

rawDescription: numpy iterate over two 2d arrays

description: Numpy iterate over two 2d arrays


code:
def perm_given_index(alist, apermindex):
    alist = alist[:]
    for i in range(len(alist)-1):
        apermindex, j = divmod(apermindex, len(alist)-i)
        alist[i], alist[i+j] = alist[i+j], alist[i]
    return alist

rawDescription: Random picks from permutation generator?

description: Random picks from permutation generator


code:
from datetime import  date

date1 = date(2005, 1, 1)
date2 = date(2008, 1, 1)

date1_ord = date1.toordinal()
date2_ord = date2.toordinal()
cnt = 0

for d_ord in range(date1_ord, date2_ord):
    d = date.fromordinal(d_ord)
    if (d.weekday() == 6) and (d.day == 1):
        cnt = cnt + 1

print("Number of Sunday 1'st days is {}".format(cnt))

rawDescription: Python - count the number of sundays on the first day of month between two dates


code:
from subprocess import call
call(["open", "hi.jpg"])

rawDescription: I want to get python to output a png file


code:
from functools import reduce
x = reduce(lambda x, y: (x,), range(10000))
x  # recursion limit hit in C code
import pprint
pprint.pprint(x)  # recursion limit hit in Python standard library code.

rawDescription: Is recursion worse than iteration?

description: Is recursion worse than iteration


code:
from winreg import*

a=OpenKey(HKEY_CURRENT_USER,"Software\\Microsoft\\Command Processor",0,KEY_WRITE)
SetValueEx(a,"Autorun",0,REG_SZ,"cd\\The path that I wantsss.")
CloseKey(a)

rawDescription: Python: Change Cmd Startup folder programmatically


code: bundle.data['stuff'] = [st.__dict__ for st in Stuff.objects.all()]

rawDescription: Serializing a queryset in dehydrate

description: Serializing a queryset in dehydrate


code:
if choice == FIND_LOWEST_NUMBER_CHOICE:
    print("The Lowest Number Is:",  min(numbers))
elif choice == FIND_HIGHEST_NUMBER_CHOICE:
    print("The Highest Number Is:", max(numbers))
elif choice == FIND_TOTAL_CHOICE:
    print("The Sum The Numbers Is:", sum(numbers))
elif choice == FIND_AVERAGE_CHOICE:
    print("The Average The Numbers Is:", sum(numbers)/len(numbers))
elif choice == QUIT_CHOICE:
    print("Exiting program....")
else:
    print('Error')

rawDescription: Python concept. Else statement printing when it shouldn't


code:
before_dec, after_dec = str(d).split('.')
float('.'.join((before_dec, after_dec[0:2])))

rawDescription: Truncate a decimal value in Python

description: Truncate a decimal value in Python


code:
s = "aabbccdd"
i = 2
print("-".join([s[j:j+i] for j in range(0,len(s),i)]))
aa-bb-cc-dd

rawDescription: how to insert characters in defined places in a python string?

description: Insert characters in defined places in a python string


rawDescription: Reshaping panel data to dataframe pandas


code:
def consecutive_length(S):
    if S == '':
        return 0
    if len(S) == 1:
        return 1
    if S[0] == S[1]:
        return 1 + consecutive_length(S[1:])
    return 1

def compress(S):
    if S == '':
        return []
    cons_length = consecutive_length(S)
    return [cons_length] + compress(S[cons_length:])

rawDescription: Print only one list in recursion

description: Print only one list in recursion


code:
for field in self.request.arguments():
  value = self.request.get(field)

rawDescription: In google app engine, how to iterate through form fields (python, wsgiref.handlers)


code: dict([(name, cls) for name, cls in mod.__dict__.items() if isinstance(cls, type)])

rawDescription: Iterate the classes defined in a module imported dynamically


code:
def update(self, instance, validated_data):
    # First, update the User
    user_data = validated_data.pop('user', None)
    for attr, value in user_data.items():
            setattr(instance.user, attr, value)
    # Then, update UserProfile
    for attr, value in validated_data.items():
        setattr(instance, attr, value)
    instance.save()
    return instance

rawDescription: Extend user model Django REST framework 3.x.x


code:
if login_successful:
    if not params_up_to_date(hashed_password):
        hashed_password = hash(entered_password)
        # update database record

rawDescription: Python - Proper way to store passwords with scrypt?


code:
B = {}
import os
import datetime
def modification_date_time(file_name):
    time = os.path.getmtime(file_name)
    return datetime.datetime.fromtimestamp(time)

for file in file_list:
    B[modification_date_time(file_name)] = file_name

rawDescription: find a file from a list with a particular modified date python

description: Find a file from a list with a particular modified date python


rawDescription: what does two sets of list brackets placed together mean in python?

description: What does two sets of list brackets placed together mean in python


code:
from openerp import api

date = fields.Date('Start Date')
product = fields.Char('Product')
namecompute = fields.Char('name',  compute='_get_name')

@api.depends('date', 'product')
def _get_name(self):
    for record in self:
        record.namecompute = record.date + record.product

rawDescription: Python ( OpenERP ) Compute Field1 and Field 2


code:
# from socket.h
# define SO_BINDTODEVICE 25

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, 25, 'eth0')

rawDescription: HTTP Requests using a range of IP address on python


code:
import ast,codegen

def find_by_line(root, line):
    found = None
    if hasattr(root, "lineno"):
        if root.lineno == line:
            return root
    if hasattr(root, "body"):
        for node in root.body:
            found = find_by_line(node, line)
            if found:
                break
    return found

def get_func_code(path, line):
    with open(path) as file:
        code_tree = ast.parse(file.read())
        unit = find_by_line(code_tree, line)
        return codegen.to_source(unit)

rawDescription: Get a function/class code from a file knowing the line and the column of it's definition


code:
from bs4 import BeautifulSoup

import requests

r = requests.get("http://www.mediafire.com/download/alv8dq6k35n4m2k/For+You.zip")

soup = BeautifulSoup(r.content)

link = soup.find("div",{"class":"download_link"})
import re

url = re.findall("http.*.zip?",link.text)[0]

rawDescription: BeautifulSoup url scrapping

description: BeautifulSoup url scrapping


code: setattr(widget, k, v)

rawDescription: How to create dynamic fields in Google App Engine expando class?

description: Create dynamic fields in Google App Engine expando class


code:
import tkinter as tk  # 3.x
root = tk.Tk()
strings = ['First', 'Second', 'Third', 'Last', 'Closing']
strit = iter(strings)
label = tk.Label(root, text=next(strit), width=(50), height=(25))
label.pack()

def refresh():
    try:
        label['text'] = next(strit)
        root.after(1000, refresh)
    except StopIteration:
        root.destroy()

root.after(1000, refresh)
root.mainloop()

rawDescription: How to refresh a Tk inter window with new data from a string

description: Refresh a Tk inter window with new data from a string


code:
palette = array( [ [0,0,0],                # black
                   [255,0,0],              # red
                   [0,255,0],              # green
                   [0,0,255],              # blue
                   [255,255,255] ] )       # white
image = array( [ [ 0, 1, 2, 0 ],           # each value corresponds to a color in the palette
                 [ 0, 3, 4, 0 ]  ] )
palette[image]                            # the (2,4,3) color image

rawDescription: Array Indexing in multi dimensional numpy array


code:
new_df = df >= threshold
new_df[df.isnull()] = np.NaN

rawDescription: Keeping NaNs with pandas dataframe inequalities


rawDescription: How can I speed up this IronPython code that generates a string of arbitrary size

description: Speed up this IronPython code that generates a string of arbitrary size


code:
import random
import sys
import matplotlib.pyplot as plt

CLOCKWISE = -1
COLLINEAR = 0
COUNTERCLOCKWISE = +1
eps = sys.float_info.epsilon

def orientation(a, b):
    x0, y0 = a
    x1, y1 = b
    cross = x0 * y1 - x1 * y0
    if cross > eps:
        return COUNTERCLOCKWISE
    elif cross < -eps:
        return CLOCKWISE
    else:
        return COLLINEAR

def same_halfplane(a, b):
    x0, y0 = a
    x1, y1 = b
    dot = x0 * x1 + y0 * y1
    if dot >= eps:
        return True
    elif dot < eps:
        return False

def jarvis(points):
    """
    http://cgi.di.uoa.gr/~compgeom/pycgalvisual/whypython.shtml
    Jarvis Convex Hull algorithm.
    """
    points = points[:]
    r0 = min(points)
    hull = [r0]
    r, u = r0, None
    remainingPoints = [x for x in points if x not in hull]
    while u != r0 and remainingPoints:
        u = random.choice(remainingPoints)
        for t in points:
            a = (u[0] - r[0], u[1] - r[1])
            b = (t[0] - u[0], t[1] - u[1])
            if (t != u and
                (orientation(a, b) == CLOCKWISE or
                 (orientation(a, b) == COLLINEAR and
                  same_halfplane(a, b)))):
                u = t
        r = u
        points.remove(r)
        hull.append(r)
        try:
            remainingPoints.remove(r)
        except ValueError:
            # ValueError: list.remove(x): x not in list
            pass
    return hull

if __name__ == '__main__':
    points = iter(random.uniform(0, 10) for _ in xrange(20))
    points = zip(points, points)
    hull = jarvis(points)
    px, py = zip(*points)
    hx, hy = zip(*hull)
    plt.plot(px, py, 'b.', markersize=10)
    plt.plot(hx, hy, 'g.-', markersize=10)
    plt.show()

rawDescription: Python - plot only the outermost points of a dataset


code:
def contents(self):
    return [action for action in dir(self) if all(
        not action in ['contents','start_response'],
        not action.startswith('_'),
        callable(action))]

rawDescription: in pylongs, is there a way to loop through all the controllers and actions?

description: In pylongs, is there a way to loop through all the controllers and actions


rawDescription: Python: convert unix time to durations

description: Python: convert unix time to durations


code:
fig = mlab.figure(figure='ICVM', bgcolor=(1,1,1), fgcolor=(0,0,0), size=(1024,786))
mlab.clf()

topo = mlab.surf(lat1d[::-1], lon1d, elev[::-1], colormap='gist_earth', warp_scale=-1e-4)

mlab.axes(xlabel='lat.', ylabel='lon.')
mlab.outline()

rawDescription: Mayavi showing wrong object extent

description: Mayavi showing wrong object extent


code:
import ctypes
MessageBox = ctypes.windll.user32.MessageBoxA
MessageBox(None, 'Hello', 'Window title', 0)

rawDescription: Python Message Box Without huge library dependancy


code:
import os
os.system("xterm -e 'bash -c \"fft -i 3 AddedK AddedK_ifft; exit -f exec bash\"' ")

rawDescription: Run $Path command in Terminal in a python script


code:
def foo(request):
   num = request.session.get('num')
   if not num:
      num = 1
   request.session['num'] = num
   return render(request,'foo.html')

def anotherfoo(request):
   num = request.session.get('num')
   # and so on, and so on

rawDescription: django global variable

description: Django global variable


code:
df = pandas.read_csv('foo1.csv', sep='[\s]{2,}')
df
df1 = df[['ItemId', 'ItemDescription']].drop_duplicates().set_index('ItemId')
df1
df2 = df[['ItemId', 'ClientId', 'PriceQuoted']]
df2

rawDescription: pandas: normalizing a DataFrame

description: Pandas: normalizing a DataFrame


code:
for i in range(10):
    print(i)
    input() # Loop continues after <Enter> is pressed

rawDescription: What is the simplest way to pause a loop by waiting for a user to press a key?


code:
# This is the mataclass-defined __init__
def auto_init(self, *args, **kwargs):
    for arg_val, arg_name in zip(args, self.init_args):
        setattr(self, arg_name, arg_val)

    # This would allow the user to explicitly specify field values with named arguments
    self.__dict__.update(kwargs)

class MetaBase(type):
    def __new__(cls, name, bases, attrs):
        attrs['__init__'] = auto_init
        return super(MetaBase, cls).__new__(cls, name, bases, attrs)

class Base(object):
    __metaclass__ = MetaBase

# No need to define __init__
class Foo(Base):
    init_args = ['first', 'last', 'email', 'mi']

description: Automatically-generated Python constructor


code: cur.execute("SELECT stock_groups.name FROM stock_groups_styles_map, stock_groups WHERE stock_groups_styles_map.style=%s", product_code)

rawDescription: Issue with inserting parameter values into MySQLdb.execute()


code:
from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

    def _get_full_name(self):
        return "%s %s" % (self.first_name, self.last_name)

    def _set_full_name(self, combined_name):
        self.first_name, self.last_name = combined_name.split(' ', 1)

    full_name = property(_get_full_name)

    full_name_2 = property(_get_full_name, _set_full_name)

rawDescription: How can I overload the assignment of a class member?

description: Overload the assignment of a class member


code:
def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i]>alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp

alist = raw_input('Enter the list to sort (seperated by spaces): ').rstrip()
alist = alist.split(' ')

bubbleSort(alist)
print(alist)

rawDescription: How to ask for an input and bubble sort that input?

description: Ask for an input and bubble sort that input


rawDescription: Sorting list of strings based on substring in each string


code:
def Username():
   Name = "Name: "
   Name += input("What's your Dicer's name?:\n")
   print(Name)

rawDescription: Python 3: How do I .join() input() With A String?


code:
import psutil
psutil.virtual_memory()
psutil.swap_memory()

rawDescription: How to get hardware information with Python

description: Get hardware information with Python


code:
def findpath(target, start=os.path.curdir):
    sdrive, start = os.path.splitdrive(start)
    tdrive, target = os.path.splitdrive(target)
    rdrive = tdrive or sdrive
    return os.path.normpath(os.path.join(rdrive, os.path.join(start, target)))

rawDescription: Find a path in Windows relative to another