code:
try:
    # Python 3.3+
    from unittest.mock import patch
except ImportError:
    # External dependency
    from mock import patch

def test():
    module_obj = {'name': Object, 'another_name': AnotherObject}

    with patch('importlib.import_module', module_obj.get):
        assert initialize('name') is module_obj['name']

rawDescription: Adding module to python at runtime

description: Adding module to python at runtime


code:
sex = ['Male', 'Female']
age = range(100)
df.columns = pd.MultiIndex.from_product([sex, age], names=['Sex', 'Age'])

rawDescription: Make multiindex columns in a pandas dataframe


code:
from django.core.files.storage import default_storage
import os

# Get the path to the barcodes folder in the media folder
# check if the folder exists and create it if not

folderPath = default_storage.path('barcodes')
if not default_storage.exists('barcodes'):
    os.mkdir(folderPath)

rawDescription: Save Image generated with Reportlab in my MEDIA folder (in Amazon S3)


code:
import sys
from PyQt4 import QtGui, QtCore

class ENUM_STATUS:
    CHECKED     = QtCore.QString('checked')
    NOT_CHECKED = QtCore.QString('not_checked')

class QCustomDelegate (QtGui.QItemDelegate):
    def paint (self, painterQPainter, optionQStyleOptionViewItem, indexQModelIndex):
        column = indexQModelIndex.column()
        if column == 1:
            textQString = indexQModelIndex.model().data(indexQModelIndex, QtCore.Qt.EditRole).toString()
            if   textQString == ENUM_STATUS.CHECKED:
                currentQColor = QtCore.Qt.darkGreen
            elif textQString == ENUM_STATUS.NOT_CHECKED:
                currentQColor = QtCore.Qt.darkRed
            else:
                currentQColor = QtCore.Qt.darkGray
            painterQPainter.setPen(currentQColor)
            painterQPainter.drawText(optionQStyleOptionViewItem.rect, QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter, textQString)
        else:
            QtGui.QItemDelegate.paint(self, painterQPainter, optionQStyleOptionViewItem, indexQModelIndex)

class QCustomTableWidget (QtGui.QTableWidget):
    def __init__ (self, parent = None):
        super(QCustomTableWidget, self).__init__(parent)

        ### <! This is initiate your QTableWidget or QTableView, Your code >! ###
        listsHorizontalHeaderItem = ['Name', 'Status']
        self.setColumnCount(len(listsHorizontalHeaderItem))
        for index in range(self.columnCount()):
            self.setHorizontalHeaderItem(index, QtGui.QTableWidgetItem(listsHorizontalHeaderItem[index]))
        listsData = [
            ['Mr. A', ENUM_STATUS.CHECKED],
            ['Mr. B', ENUM_STATUS.NOT_CHECKED],
            ['Mr. C', ENUM_STATUS.NOT_CHECKED],
            ['Mr. D', ENUM_STATUS.CHECKED],
            ['Mr. E', ENUM_STATUS.CHECKED]]
        self.setRowCount(len(listsData))
        for row in range(len(listsData)):
            for column in range(len(listsData[row])):
                self.setItem(row, column, QtGui.QTableWidgetItem(listsData[row][column]))
        ### <! End initiate >! ###

        # After initiated, Your have to setup delegate to your QTableWidget or QTableView, Add line
        self.myQCustomDelegate = QCustomDelegate()
        self.setItemDelegate(self.myQCustomDelegate)

if __name__ == '__main__':
    myQApplication = QtGui.QApplication(sys.argv)
    myQCustomTableWidget = QCustomTableWidget()
    myQCustomTableWidget.show()
    sys.exit(myQApplication.exec_())

rawDescription: Change color for a selected string in qtable in Pyqt


code:
class Foo:
    @classmethod
    def bar(cls):
        pass
    @staticmethod
    def baz():
        pass
import timeit
min(timeit.repeat('Foo.bar()', 'from __main__ import Foo', repeat=5, number=100000))
min(timeit.repeat('Foo.baz()', 'from __main__ import Foo', repeat=5, number=100000))
min(timeit.repeat('f.bar()', 'from __main__ import Foo; f = Foo()', repeat=5, number=100000))
min(timeit.repeat('f.baz()', 'from __main__ import Foo; f = Foo()', repeat=5, number=100000))

rawDescription: Speed Static Methods vs Class Method

description: Speed Static Methods vs Class Method


code:
#! /usr/bin/env python3

# The following is a database of problems, keywords, and solutions.
PROBLEMS = (('My phone does not turn on.',
             {'power', 'turn', 'on', 'off'},
             ('Smack it with a hammer.',
              'Wrap your phone in duck tape.',
              'Throw it into the ocean.')),
            ('My phone is freezing.',
             {'freeze', 'freezing'},
             ('Dowse it in a petroleum-based product.',
              'Light a match or find a suitable flame source.',
              'Barbecue your phone until it is well done.')),
            ('The screen is cracked.',
             {'cracked', 'crack', 'broke', 'broken', 'screen'},
             ('Find some super glue.',
              'Spread the super glue over the screen of the phone.',
              'Either sit on the phone or place a 100 pounds over it.')),
            ('I dropped my phone in water.',
             {'water', 'drop', 'dropped'},
             ('Blow dry your phone with air below zero degrees Celsius.',
              'Bake it in your oven at three hundred degrees Celsius.',
              'Leave your phone on your roof for one week.')))

# These are possible answers accepted for yes/no style questions.
POSITIVE = tuple(map(str.casefold, ('yes', 'true', '1')))
NEGATIVE = tuple(map(str.casefold, ('no', 'false', '0')))

def main():
    """Find out what problem is being experienced and provide a solution."""
    description = input('Please describe the problem with your phone: ')
    words = {''.join(filter(str.isalpha, word))
             for word in description.lower().split()}
    for problem, keywords, steps in PROBLEMS:
        if words & keywords:
            print('This may be what you are experiencing:')
            print(problem)
            if get_response('Does this match your problem? '):
                print('Please follow these steps to fix your phone:')
                for number, step in enumerate(steps, 1):
                    print('{}. {}'.format(number, step))
                print('After this, your phone should work.')
                print('If it does not, please take it to a professional.')
                break
    else:
        print('Sorry, but I cannot help you.')

def get_response(query):
    """Ask the user yes/no style questions and return the results."""
    while True:
        answer = input(query).casefold()
        if answer:
            if any(option.startswith(answer) for option in POSITIVE):
                return True
            if any(option.startswith(answer) for option in NEGATIVE):
                return False
        print('Please provide a positive or negative answer.')

if __name__ == '__main__':
    main()

rawDescription: How do i split the solutions for my code?

description: Split the solutions for my code


code:
class Singleton(type):
    """Metaclass which implements the singleton pattern"""

    _instances = {}

    def __call__(self, *args, **kwargs):
        if self not in self._instances:
            self._instances[self] = super(Singleton, self).__call__(*args, **kwargs)
        return self._instances[self]

    def __copy__(cls, instance):
        return instance

rawDescription: Singleton object and the copy module in Python


code:
btn = wx.Button(win, label="click me")
btn.Bind(wx.EVT_BUTTON, on_click)

rawDescription: What's the use of widget id on wxpython?

description: What's the use of widget id on wxpython


code:
class Foo(object):
    pass

eval("Foo")

rawDescription: Convert string to Python class object?

description: Convert string to Python class object


code:
# -*- coding: utf-8 -*-
import wxversion
wxversion.ensureMinimal('2.8')
import wx
import numpy as np
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.figure import Figure

class FigureCanvas(FigureCanvasWxAgg):
    def __init__(self,parent,id,figure,**kwargs):
        FigureCanvasWxAgg.__init__(self,parent=parent, id=id, figure=figure,**kwargs)
        self.figure = figure
        self.axes = self.figure.get_axes()[0] # Get axes
        self.connect() # Connect event

    def connect(self):
        """Connect pick event"""
        self.MOVE_LINE_EVT = self.mpl_connect("pick_event", self.on_pick)

    def on_pick(self,event):
        self._selected_line = event.artist # Get selected line
        # Get initial x,y data
        self._p0 = (event.mouseevent.xdata, event.mouseevent.ydata)
        self._xdata0 = self._selected_line.get_xdata()
        self._ydata0 = self._selected_line.get_ydata()
        # Connect events for motion and release.
        self._on_motion = self.mpl_connect("motion_notify_event", self.on_motion)
        self._on_release = self.mpl_connect("button_release_event", self.on_release)

    def on_motion(self,event):
        cx = event.xdata # Current xdata
        cy = event.ydata # Current ydata
        deltax = cx - self._p0[0]
        deltay = cy - self._p0[1]
        self._selected_line.set_xdata(self._xdata0 + deltax)
        self._selected_line.set_ydata(self._ydata0 + deltay)
        self.draw()

    def on_release(self,event):
        """On release, disconnect motion and release"""
        self.mpl_disconnect(self._on_motion)
        self.mpl_disconnect(self._on_release)
        self.axes.relim()
        self.axes.autoscale_view(True,True,True)
        self.draw()

class Frame(wx.Frame):
    def __init__(self,parent,title):
        wx.Frame.__init__(self,parent,title=title,size=(800,600))
        self.initCtrls()
        self.plotting()
        self.Centre(True)
        self.Show()

    def initCtrls(self):
        self.mainsizer = wx.GridSizer(rows=2, cols=2, hgap=2, vgap=2)
        # 1
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self, wx.ID_ANY, self.figure)

        # 2
        self.figure2 = Figure()
        self.axes2 = self.figure2.add_subplot(111)
        self.canvas2 = FigureCanvas(self, wx.ID_ANY, self.figure2)

        self.figure3 = Figure()
        self.axes3 = self.figure3.add_subplot(111)
        self.canvas3 = FigureCanvas(self, wx.ID_ANY, self.figure3)

        self.figure4 = Figure()
        self.axes4 = self.figure4.add_subplot(111)
        self.canvas4 = FigureCanvas(self, wx.ID_ANY, self.figure4)

        self.mainsizer.Add(self.canvas, 1, wx.EXPAND)
        self.mainsizer.Add(self.canvas2, 1, wx.EXPAND)
        self.mainsizer.Add(self.canvas3, 1, wx.EXPAND)
        self.mainsizer.Add(self.canvas4, 1, wx.EXPAND)
        self.SetSizer(self.mainsizer)

    def plotting(self):
        # Set picker property -> true
        self.axes2.plot(np.arange(1,11),10*np.random.rand(10),color='b',
                       marker='o', picker=True)
        self.axes3.plot(np.arange(1,11),10*np.random.rand(10),color='r',
                       marker='o', picker=True)
        self.canvas.draw()

if __name__=='__main__':
    app = wx.App()
    frame = Frame(None, "Matplotlib Demo")
    frame.Show()
    app.MainLoop()

rawDescription: Draggable Matplotlib Subplot using wxPython


code: file = client.files().list(q="title='YOUR TITLE'").execute()

rawDescription: get a google document by its title?

description: Get a google document by its title


code:
def changeColor(self, model):
    model.setData(model.index(1, 5), 1)
    model.setData(model.index(2, 5), 2)
    model.emit(QtCore.SIGNAL('dataChanged(QModelIndex,QModelIndex)'), model.index(1, 5), model.index(2, 5))

rawDescription: Change row color of a QTableView with QStandardItemModel


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

N = 1000
mean = [1,1]
cov = [[0.3, 0.2],[0.2, 0.2]]
data = np.random.multivariate_normal(mean, cov, N)
L = linalg.cholesky(cov)
# print(L.shape)
# (2, 2)
uncorrelated = np.random.standard_normal((2,N))
data2 = np.dot(L,uncorrelated) + np.array(mean).reshape(2,1)
# print(data2.shape)
# (2, 1000)
plt.scatter(data2[0,:], data2[1,:], c='green')
plt.scatter(data[:,0], data[:,1], c='yellow')
plt.show()

rawDescription: Generate a data set consisting of N=100 2-dimensional samples


code:
def getAllNestedElementInformation(element):
    infoDict = collections.defaultdict(dict)
    infoDict[element] = {'tagName':element.tag}
    infoDict[element].update(getItems(element))
    if element.text != None:
        if element.text.strip() != '':
            infoDict[element].update({'content':element.text})

    for nestedElement in element:
        infoDict[element]['nestedElement'] = getAllNestedElementInformation(nestedElement)

    return infoDict

rawDescription: Using recursion to put a nested structure into a dictionary without losing the structure


code:
def prepend_urls(self):
        return [
            url(
                r"^(?P<resource_name>%s)/(?P<my_id>\d+)/$"
                % self._meta.resource_name, self.wrap_view('dispatch_detail'),
                name="api_dispatch_detail_id"),
            url(
                r"^(?P<resource_name>%s)/(?P<name>[\w\d_.-]+)/$"
                % self._meta.resource_name, self.wrap_view('dispatch_detail'),
                name="api_dispatch_detail_name"),
        ]

rawDescription: Django-tastypie multiple urls in prepend_urls


code:
import requests
from flask import Flask
app = Flask(__name__)

@app.route('/some-url')
def get_data():
    return requests.get('http://example.com').content

rawDescription: How can I send a GET request from my flask app to another site?

description: Send a GET request from my flask app to another site


code:
z = 300
mylist = []

while(z > 1):
    z = z - 1
    x,y = divmod(600851475143, z)
    if y==0:
        mylist.append(x)

print(mylist)

rawDescription: How to tell if item in list contains certain characters

description: Tell if item in list contains certain characters


code:
class Converter:

    def __init__(self, fl, ln, vrbl):
        self.file = fl
        self.line = ln
        self.variable = vrbl

    def to_int(self):
        file = open(self.file, "r")
        for i in range(self.line):
            whatToConvert = file.readline()
        file.close
        return int(whatToConvert)

    def to_str(self):
        file = open(self.file, "r")
        for i in range(self.line):
            whatToConvert = file.readline()
        file.close
        return str(whatToConvert)

    def to_float(self):
        file = open(self.file, "r")
        for i in range(self.line):
            whatToConvert = file.readline()
        file.close
        return float(whatToConvert)

#Instantiation
foo = Converter('\a\path','an int?','')

#This is how you call the class methods.
foo.to_int()
foo.to_str()
foo.to_float()

rawDescription: How do I make a variable in a module on a global namespace?

description: Make a variable in a module on a global namespace


code:
self.composerMap = QgsComposerMap(self.composition, 5,2,408,286)
self.composition.addComposerMap(self.composerMap)
self.composition.moveItemToBottom(self.composerMap)
self.composition.moveSelectedItemsToBottom()

rawDescription: How to send a Composer item to bottom in QGIS?

description: Send a Composer item to bottom in QGIS


code:
class FILE_HEAD(ctypes.Structure):
    _pack_ = 1
    _fields_ = [
        ("name", ctypes.c_char * 4),                    # 4 bytes
        ("size", ctypes.c_int),                         # 4 bytes
        ("Cal_l", ctypes.c_double),                     # 8 bytes
        ("Cal_r", ctypes.c_double),                     # 8 bytes
        ("Speed_ChL", ctypes.c_byte),                   # 1 byte
        ("Speed_Pulses_ChL", ctypes.c_int),             # 4 bytes
        ("Speed_factor_ChL", ctypes.c_double),          # 8 bytes
        ("Quantity_ChL", ctypes.c_char * 3),            # 3 bytes
        ("Description_ChL", ctypes.c_char * 32),        # 32 bytes
        ("Unit_ChL", ctypes.c_char * 8),                # 8 bytes
        ("Speed_ChR", ctypes.c_byte),                   # 1 byte
        ("Speed_Pulses_ChR", ctypes.c_int),             # 4 bytes
        ("Speed_factor_ChR", ctypes.c_double),          # 8 bytes
        ("Quantity_ChR", ctypes.c_char * 3),            # 3 bytes
        ("Description_ChR", ctypes.c_char * 32),        # 32 bytes
        ("Unit_ChR", ctypes.c_char * 8)                 # 8 bytes
    ]                                                   # = 136 bytes

rawDescription: python ctypes structure wrong byte size

description: Python ctypes structure wrong byte size


code:
# graph input file
def graph(request):
    fig = Figure()
    ax = fig.add_subplot(111)
    data_df = pd.read_csv("C:/Users/vut46744/Desktop/graphite_project/sampleCSV.csv")
    data_df = pd.DataFrame(data_df)
    data_df.plot(ax=ax)
    canvas = FigureCanvas(fig)
    response = HttpResponse( content_type = 'image/png')
    canvas.print_png(response)
    return response

rawDescription: Create a graph from a CSV file and render to browser with Django and the Pandas Python library


code:
def func():
    pass

func.a = 19

func.__dict__
vars(func)
vars(func) is func.__dict__

rawDescription: python's function-attributes: getting a list/dict of all assigned attributes

description: Python's function-attributes: getting a list/dict of all assigned attributes


code:
import numpy as np
from decimal import Decimal
x = np.arange(Decimal(30), Decimal(90))
y = np.exp(x ** 2)
y[-1]

rawDescription: RuntimeWarning: overflow encountered in np.exp(x**2)


rawDescription: Formatting List Output

description: Formatting List Output


code:
try:
    retcode = subprocess.call(args)
except KeyboardInterrupt:
    pass # ignore CTRL-C

rawDescription: Keyboard interrupts and os.system vs subprocess.call


rawDescription: How to get a SObject instance from SearchKey?

description: Get a SObject instance from SearchKey


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
from matplotlib.collections import PatchCollection

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

myAngles=[0, -45, -90]
myColors=[30, 40, 50]
myPatches=[]

for color, angle in zip (myColors,myAngles):
    #r2 = patches.Rectangle((0,0), 20, 40, color=color,  alpha=0.50)
    r2 = patches.Rectangle((0,0), 20, 40)
    t2 = mpl.transforms.Affine2D().rotate_deg(angle) #+ ax.transData
    r2.set_transform(t2)
    #ax.add_patch(r2)
    myPatches.append(r2)

    plt.xlim(-20, 60)
    plt.ylim(-20, 60)

    plt.grid(True)

collection = PatchCollection(myPatches, cmap=mpl.cm.jet, alpha=0.5)
collection.set_array(np.array(myColors))
ax.add_collection(collection)

fig.savefig('withoutTransData.png')
plt.show()

rawDescription: Rotating a patch and applying colors

description: Rotating a patch and applying colors


code:
TIME_RANGE = datetime.timedelta(days=7)
now = datetime.datetime.now()

KarmaAction.objects.filter(created_at__gte=now - TIME_RANGE) \
                   .filter(user=recepient_user) \
                   .values('sender') \
                   .annotate(total_sent=Sum('karma')) \
                   .order_by('total_sent')

rawDescription: How do I get a list of senders with the corresponding sum of the karma they sent using Django?

description: Get a list of senders with the corresponding sum of the karma they sent using Django


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

import random, collections

# pseudo-randomly select element from table
# ensuring minimum distance before the same
# element is selected again

def choice_gen(choices, min_dist):
    last_choices = collections.deque()
    choices = set(choices)
    while 1:
        c = random.choice(list(choices))
        choices.remove(c)
        last_choices.append(c)
        if len(last_choices) == min_dist:
            choices.add(last_choices.popleft())
        yield c

rawDescription: Ensuring minimum distance between choices


code:
for host in nm.all_hosts():
    print(host)
    print(nm[host].get('osclass', 'unknown'))
    # {'vendor': 'Linux', 'accuracy': '100', 'type': 'general purpose',
    #  'osfamily': 'Linux', 'osgen': '3.X'}

rawDescription: Python3.4.3 Nmap : Host discovery with Operating System detection


code:
conn = pymysql.connect(host=myHost, port=myPort, user=myUser, passwd=myPassword, database=myDatabase, charset="utf8")
cur = conn.cursor()

theDateTime = re.sub( r' ', '-', str(datetime.now()))
theDateTime = theDateTime[0:10] + " " + theDateTime[11:19]

productName = 'abc'
myMaxPrice = 100.0

try:
    # The below query to the remote database returned tuples like (b'1', b'2015-01-02 23:11:19', b'25.00') for MySQL DB tableA columns: ID, date_changed, price
    query = "SELECT IFNULL(ID,''), IFNULL(date_changed,''), IFNULL(price, '') FROM tableA WHERE product = '" + productName + "';"
    cur.execute(query)
    for r in cur.fetchall():
        # Given the returned result tuple r[] from the remote DB included byte literals instead of strings, I had to encode the '' strings in the condition below to make them byte literals
        # However, I did not have to encode floats like mMaxyPrice and float(r[2]) as they were not a string; float calculations were working fine, even though the returned float values were also byte literals within the tuple
        if not r[1] and float(r[2]) >= myMaxPrice:
            #Had to encode and then decode r[0] below due to the ID column value r[0] coming back from the remote DB query / fetchall() as a byte literal with a "b" prefix
            query = "UPDATE tableA SET date_changed = '" + theDateTime + "', price = " + str(myMaxPrice) + " WHERE ID = " + r[0].decode(encoding='utf-8') + ";"
            cur.execute(query)
            conn.commit()
except pymysql.Error as e:
    try:
        print("\nMySQL Error {0}: {1}\n".format(e.args[0], e.args[1]))
    except IndexError:
        print("\nMySQL Index Error: {0}\n".format(str(e)))
    print("\nThere was a problem reading info from the remote database!!!\n")

rawDescription: pymysql connection select query and fetchall return tuple that has byte literals like b'25.00' rather than strings like '25.00'

description: Pymysql connection select query and fetchall return tuple that has byte literals like b'25.00' rather than strings like '25.00'


code:
import tkinter as tk
from tkinter import ttk

root = tk.Tk()
style = ttk.Style()
style.theme_create( "MyStyle", parent="alt", settings={
        "TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0] } },
        "TNotebook.Tab": {"configure": {"padding": [100, 100] },}})

style.theme_use("MyStyle")

a_notebook = ttk.Notebook(root, width=200, height=200)
a_tab = ttk.Frame(a_notebook)
a_notebook.add(a_tab, text = 'This is the first tab')
another_tab = ttk.Frame(a_notebook)
a_notebook.add(another_tab, text = 'This is another tab')
a_notebook.pack(expand=True, fill=tk.BOTH)

tk.Button(root, text='Some Text!').pack(fill=tk.X)

root.mainloop()

rawDescription: Changing the tab sizes of a Notebook widget in Python 3


code:
import seaborn as sns
import numpy as np

x = 0.3 + 0.3 * np.random.randn(10000)
y = 0.1 - 0.2 * x + 0.1 * np.random.randn(10000)
mask = (y > 0) & (x > 0)
x, y = x[mask], y[mask]

g = sns.jointplot(x, y, kind="hex", color="#5d5d60",
                  joint_kws={'gridsize':40, 'bins':'log'})
sns.regplot(x, y, ax=g.ax_joint, scatter=False)

rawDescription: How to plot regression line on hexbins with Seaborn?

description: Plot regression line on hexbins with Seaborn


rawDescription: How to add values based on the output of xrange()?

description: Add values based on the output of xrange()


code:
def fit_together(row1, row2):
    return row1[1] == row2[0] # or something like that

# to test all combinations:
for row1 in list1:
    for row2 in list2:
        if fit_together(row1, row2):
            do_sth()

# to test all rows with the same indices in their respective lists:
for row1, row2 in zip(list1, list2):
   if fit_together(row1, row2):
       do_sth()

rawDescription: Compare Values in Many Lists and Return Entire List If Specific Values Are Equal


code: any(customEquals(item, li) for li in myList)

rawDescription: How do I specify custom comparator for the "in" keyword in Python?

description: Specify custom comparator for the "in" keyword in Python


rawDescription: Python Regex: extract "a" from "01a"

description: Python Regex: extract "a" from "01a"


code:
import fdb
import io

con = fdb.connect(dsn='localhost:testdatabase', user='sysdba', password='masterkey')

cur = con.cursor()
statement = "insert into blob_test2 (text_blob) values (?)"
cur.execute(statement, ("test blob as string",))
cur.execute(statement, (io.StringIO("test blob as StringIO"),))
streamwrites = io.StringIO()
streamwrites.write("streamed write1,")
streamwrites.write("streamed write2,")
streamwrites.seek(0)
cur.execute(statement, (streamwrites,))

con.commit()

con.close()

rawDescription: Add list of values to a blob field in firebird using Python


code:
from models import Name
from datetime import datetime

# create a new model
name = Name(city='New York', state='NY')
# fields can also be set this way
name.zipcode = '10027'
# save the model to the database
name.save()
# find a model by zipcode
name = Name.objects.filter(zipcode='10027')
# modify it
name.curr_time = datetime.now()
# save it
name.save()

rawDescription: Django model with crud operations

description: Django model with crud operations


code:
from PyQt4 import QtCore, QtGui
import time

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_multippp(object):
    def setupUi(self, multippp):
        multippp.setObjectName(_fromUtf8("multippp"))
        multippp.resize(371, 43)
        self.verticalLayout = QtGui.QVBoxLayout(multippp)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.label = QtGui.QLabel(multippp)
        self.label.setObjectName(_fromUtf8("label"))
        self.verticalLayout.addWidget(self.label)
        self.verticalLayout_2 = QtGui.QVBoxLayout()
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.verticalLayout.addLayout(self.verticalLayout_2)

        self.retranslateUi(multippp)
        QtCore.QMetaObject.connectSlotsByName(multippp)

    def retranslateUi(self, multippp):
        multippp.setWindowTitle(QtGui.QApplication.translate("multippp", "Multiple PPP Accounts", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("multippp", "More than one PPP account found, please select one:", None, QtGui.QApplication.UnicodeUTF8))

import sys
app = QtGui.QApplication(sys.argv)
multippp = QtGui.QDialog()
ui = Ui_multippp()
ui.setupUi(multippp)
multippp.show()
# UI is visible and interactive at this point
# But after the next command, the UI will freeze for 5 seconds while the interpreter loop is 'busy' waiting for the command to return
time.sleep(5)

rawDescription: Why is my PyQt UI not frozen while I don't have a loop running?


code:
new_dict = {
    'tf' : original_dict.get('temp_f', None),
    'rh' : original_dict.get('relative_humidity', None),
     # And so on...
}

rawDescription: Insert Variable Dictionary Values to db

description: Insert Variable Dictionary Values to db


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

mod1 = np.array([ 468, 28000, 800000000 ])
mod2 = np.array([ 162, 2000, 228000000 ])

proc = mod2.astype(float) / mod1.astype(float)

for ii, bar in enumerate(proc):
    plt.bar(ii, bar)
    plt.text(ii + 0.4, bar + 0.01, "%.2f" % bar, ha='center', va='bottom')
plt.ylim(0, 1.0)
plt.show()

rawDescription: Bar chart to compare data of various fields


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

fig, ax = plt.subplots()
sin_l, = ax.plot(np.sin(0))
cos_l, = ax.plot(np.cos(0))
ax.set_ylim(-1, 1)
ax.set_xlim(0, 5)
dx = 0.1

def update(i):
    # i is a counter for each frame.
    # We'll increment x by dx each frame.
    x = np.arange(0, i) * dx
    sin_l.set_data(x, np.sin(x))
    cos_l.set_data(x, np.cos(x))
    return sin_l, cos_l

ani = animation.FuncAnimation(fig, update, frames=51, interval=50)
plt.show()

rawDescription: Matplotlib pyplot in real time

description: Matplotlib pyplot in real time


code: file.write('set address {}{} {}\n'.format(a, a+1, cleaned_ip_list[i]))

rawDescription: How do I concat strings and variables in a file?

description: Concat strings and variables in a file


code:
def on_mouseDrag( self, event ):
    do_stuff()

    if event.MiddleIsDown():
        do_other_stuff()

rawDescription: How can I handle a mouseMiddleDrag event in PythonCard?

description: Handle a mouseMiddleDrag event in PythonCard


code:
from django.db import models

class CommonInfo(models.Model):
    # ...
    class Meta:
        abstract = True
        ordering = ['name']

class Student(CommonInfo):
    # ...
    class Meta(CommonInfo.Meta):
        db_table = 'student_info'

rawDescription: Python super on Meta Class from another class


rawDescription: Python 2.7: making a dictionary object from a specially-formatted list object


code:
jobs = df.groupby('Job')['Salary'].mean()
jobs = jobs.to_frame().reset_index()
jobs.columns = ['Unique_Job', 'Avg_Salary']

rawDescription: Pandas dataframe groupby with aggregation


code:
self.defaultstyle = wx.richtext.RichTextAttr()
self.GetStyle(self.GetInsertionPoint(), self.defaultstyle)
self.defaultsize = self.defaultstyle.GetFont().GetPointSize()

rawDescription: Getting a RichTextCtrl's default font size in wxPython


code:
import requests
from bs4 import BeautifulSoup
from collections import OrderedDict

soup = BeautifulSoup(html, 'html.parser')
tables = soup.find_all('table')
rows = tables[1].find_all('tr')
t_data = OrderedDict((row.th.text, row.td.text) for row in rows if row.td)

rawDescription: OrderedDict comprehension?

description: OrderedDict comprehension


code:
app.config['SERVER_NAME'] = 'mydomain.com'
app.url_map.default_subdomain = "app"
app.register_blueprint(account, url_prefix='/account')
app.register_blueprint(users, url_prefix='/users')
app.register_blueprint(boxes, url_prefix='/boxes')
app.register_blueprint(api_1_0, subdomain='api')

rawDescription: How to setup different subdomains in Flask (using blueprints)?

description: Setup different subdomains in Flask (using blueprints)


code:
import sqlite3

def copy_database(source_connection, dest_dbname=':memory:'):
    '''Return a connection to a new copy of an existing database.
       Raises an sqlite3.OperationalError if the destination already exists.
    '''
    script = ''.join(source_connection.iterdump())
    dest_conn = sqlite3.connect(dest_dbname)
    dest_conn.executescript(script)
    return dest_conn

if __name__ == '__main__':
    from contextlib import closing

    with closing(sqlite3.connect('pepsearch.db')) as disk_db:
        mem_db = copy_database(disk_db)

    mem_db.execute('DELETE FROM documents WHERE uri="pep-3154"')
    mem_db.commit()

    copy_database(mem_db, 'changed.db').close()

rawDescription: Moving back and forth between an on-disk database and a fast in-memory database?


code:
def sortOD(od):
    res = OrderedDict()
    for k, v in sorted(od.items()):
        if isinstance(v, dict):
            res[k] = sortOD(v)
        else:
            res[k] = v
    return res

rawDescription: Sorting a nested OrderedDict by key, recursively


code:
def on_ok(event):
    if self.window.focus_get() == text:
        print('the text widget has focus')
    else:
        print('some other widget has focus')

rawDescription: tkinter: bind Return key to the OK button -- but not to the Text widget

description: Tkinter: bind Return key to the OK button -- but not to the Text widget


code:
from itertools import combinations

my_list = [1, 2, 3, 4]
list(combinations(my_list, 3))

# [(1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

rawDescription: How i do permutations of a list without shuffle?


code:
import ftplib

ftp = ftplib.FTP("ladsweb.nascom.nasa.gov")
ftp.login()

a = 'allData/5/MOD11A1/2002/001/MOD11A1.A2002001.h00v08.005.2007079015634.hdf'
fhandle = open('ftp-test', 'wb')
ftp.retrbinary('RETR ' + a, fhandle.write)
fhandle.close()

rawDescription: How to download FTP file using its full FTP path?

description: Download FTP file using its full FTP path


code:
p = subprocess.Popen(fullPath, shell=True, stdin=subprocess.PIPE)
stdO, stdE = p.communicate("foo\n")

rawDescription: running executable from python with keyboard input

description: Running executable from python with keyboard input


code:
import requests
from bs4 import BeautifulSoup

html = requests.get('http://www.atlasdermatologico.com.br/listar.asp?acao=indice').text
soup = BeautifulSoup(html, 'html5lib')

for a in soup.find_all('a'):
    href = a.get('href')

    if '\\' in repr(href):
        print(repr(href))

rawDescription: Parsing uncommon symbol using BeautifulSoup


code:
with open('myfile.txt', 'r') as f:
    for place in range(0, int(2e6), 50000):
        f.seek(place)
        content = f.read(50000)
        if content:
            with open('myfile{}.txt'.format(place), 'w') as o:
                o.write(content)
        else:
            break

rawDescription: how to split up a large text file (one long string) into 50kb text files

description: Split up a large text file (one long string) into 50kb text files


code:
def stub1(elem):
    #do something for match of type '-1'
    return
def stub2(elem):
    #do something for match of type 'SD4'
    return
def stub3(elem):
    #do something for match of type 'OPEN15'
    return

sg = [500782, u'BMOU9015488', u'SD4', u'CLOSED', -1, '', '', -1]
sg = map(unicode, sg)
patterns = {u"-1":stub1, u"SD4": stub2, u"OPEN15": stub3} # add more if you want

for elem in sg:
    for k, stub in patterns.iteritems():
        if k in elem:
            stub(elem)
            break

rawDescription: Format a python list and search for patterns


code:
maximums = {}
for key, val in A:
    if maximums.get(key, float('-inf')) < val:
        maximums[key] = val

B = [[key, val] for key, val in maximums.items()]

rawDescription: How to group and sort list of lost in python?

description: Group and sort list of lost in python


code:
class Master(object):
    def __new__(klass, *args, **kwargs):
        self = object.__new__(klass)
        self.attribute1 = ...
        self.attribute2 = ...
        return self

rawDescription: Python: Pitfalls of creating a super object


code:
class ParentForm(Form):
    name = StringField()

class ChildFormAge(ParentForm):
    age = IntegerField()

class ChildFormSalary(ParentForm):
    salary = FloatField()

rawDescription: How to remove certain fields in a WTForms child class?

description: Remove certain fields in a WTForms child class


code:
from Tkinter import *
from ttk import *

rawDescription: Ttk on python 2.7

description: Ttk on python 2.7


code:
search_criteria = 'DATE' #Ascending, most recent email last
search_criteria = 'REVERSE DATE' #Descending, most recent email first

search_criteria = '[REVERSE] sort-key' #format for sorting

rawDescription: Getting n most recent emails using IMAP and Python


code:
class Bar(Foo):
    adict = dict(Foo.adict)
    adict.update({'b': 2})

rawDescription: Python update inherited class level dictionary


code: var[i]['text'] = var[i]['text'].replace('\n', '')

rawDescription: Python String strip for new lines on a twitter feed


code:
class Entry(models.Model):
   id = models.AutoField(verbose_name="custom name")
   # and other fields...

rawDescription: Django: Overriding verbose_name for AutoField without dropping the model


code:
class MyDrag(QtGui.QDrag):
    dragStarted = QtCore.pyqtSignal()

    def __init__(self, dragSource):
        super(MyDrag, self).__init__(dragSource)

    def start(self):
        self.dragStarted.emit()

        super(MyDrag, self).start()

rawDescription: Drag.start in pyqt

description: Drag.start in pyqt


code:
import pygraphviz as pgv
from PIL import Image

d={'1': {'2': None}, '2': {'1': None, '3': None}, '3': {'2': None}}
A=pgv.AGraph(d)
A.node_attr['style']='filled'
n = A.get_node('1')
n.attr['fillcolor']="#CCCCFF"
n.attr['label'] = 'MY LOVELY LABEL'
A.layout() # default to neato
A.layout(prog='dot') # use dot
A.draw('file.png')
img = Image.open('file.png')
img.show()

rawDescription: Setting colour of nodes in pyGraphViz

description: Setting colour of nodes in pyGraphViz


code:
ts
DataFrame(np.diag(ts), columns=ts.index, index=ts.index)

rawDescription: Pandas Series - > Dataframe. Create columns from rows and fill nonmatching with zeros


code: re.split("[^-\w]+", "fat-free milk")

rawDescription: How do I split words in Python while keeping in consideration words with hyphens?

description: Split words in Python while keeping in consideration words with hyphens


code:
L2 = []
a = 0
for i in range(0, len(L), 2):
  a += 1
  L2.append(a)
  a += L[i+1] - L[i]
  L2.append(a)

print(L2)

rawDescription: Python - List manipulation (hidden intervals within)


code:
#!/usr/bin/env python
import sys
from datetime import datetime

known_systems = {'MIDRANGE_PROD', 'MIDRANGE_TEST'}

try:
    date_string, system_string = sys.argv[1:]
except ValueError:
    sys.exit('Usage: queue_cleaner <date> <system>')

if system_string not in known_systems:
   sys.exit('wrong system, expected: %s, got: %r' % (
       ' or '.join(known_systems), system_string))

try:
    input_date = datetime.strptime(date_string, '%Y%m%d').date()
except ValueError:
    sys.exit('expected date in YYYYMMDD format, got: %r' % date_string)

rawDescription: time.strptime() python3 best way to use it?

description: Time.strptime() python3 best way to use it


code:
for root, dirs, files in os.walk(indexpath):
    for name in files:
        foto_exist_check = Foto.select(Foto.fid).where(Foto.file_fullpath == os.path.abspath(os.path.join(root, name)))
        if foto_exist_check.count() == 0:
            foto = Foto(
                file_name=name,
                file_path=os.path.join(root, name),
                file_fullpath=os.path.abspath(os.path.join(root, name)),
                date_changed=datetime.datetime.strptime(time.ctime(os.path.getmtime(join(root, name))),"%a %b %d %H:%M:%S %Y"),
                size=getsize(join(root, name)),
                file_extension=os.path.splitext(name)[1],
                file_type=magic.from_file(join(root, name)),
                file_mime=magic.from_file(join(root, name), mime=True)
            )
            foto.save()
        else:
            foto = Foto(
                fid = foto_exist_check.get().fid,
                file_name=name,
                file_path=os.path.join(root, name),
                file_fullpath=os.path.abspath(os.path.join(root, name)),
                date_changed=datetime.datetime.strptime(time.ctime(os.path.getmtime(join(root, name))),"%a %b %d %H:%M:%S %Y"),
                size=getsize(join(root, name)),
                file_extension=os.path.splitext(name)[1],
                file_type=magic.from_file(join(root, name)),
                file_mime=magic.from_file(join(root, name), mime=True)
            )
            foto.save()

rawDescription: Python with peewee to MySQL, save / update doubles existing rows


code:
class Test:
    def test(self, p, d = None):
        if d is None:
            d = {}
        d.update(p)
        return d

rawDescription: Does dict.update affect a function's argspec?


code:
import tempfile
import os

tmp_file_name = request.FILES['my_file_field'].name
tmp_file_dir = tempfile.gettempdir()  # usually /tmp on Unix
tmp_file_path = os.path.join(tmp_file_dir, tmp_file_name)

mime = magic.Magic(mime=True)
file_mime_type = mime.from_file(tmp_file_path)

# then check mime and raise ValidationError if required

rawDescription: How does one use magic to verify file type in a Django form clean method?

description: Use magic to verify file type in a Django form clean method


code:
wait=True
while wait:
   url=urllib.urlopen('http://'+username+':'+password+'@localhost/httpAuth/action.html?add2Queue='+btid+'&system.name=<btid>&system.value=<'+btid+'>&system.name=<buildNumber>&system.value=<'+buildNumber+'>')
   if url.getcode()!=404:
     wait=False
   else:
     time.sleep(60)

rawDescription: Python question regarding a server listener


code:
e2s
test
e2s.merge(test)
test.merge(e2s)

rawDescription: merging in pandas vs merging in R

description: Merging in pandas vs merging in R


code:
while True:
    while queue:
        queue.pop()()

rawDescription: Event loop implementation for Python 3?

description: Event loop implementation for Python 3


code:
from tkinter import *

root = Tk()

f1=Frame(root)
img_list = []                  #<-- store references to images
for img,rlf in [ ('woman',RAISED),('mensetmanus',SOLID),
    ('terminal',SUNKEN), ('escherknot',FLAT),
    ('calculator',GROOVE),('letters',RIDGE)]:
        filename = img + ".gif"
        img1 = PhotoImage(file= filename)
        img_list.append(img1) #<-- store references to images
        Label(f1, image = img1, relief=rlf).pack(side=LEFT,
            padx=5)
f1.pack()

root.mainloop()

rawDescription: tkinter: why images are not dysplayed correctly

description: Tkinter: why images are not dysplayed correctly


code:
def create_list(self, object_list, bundle):
    """
    Unimplemented, as Tastypie never creates entire new lists, but
    present for consistency & possible extension.
    """

rawDescription: What does create_list refer to in Tastypie's custom authorisation?


code:
s = '/opt/ad/bin$ ./ptzflip\r\nValue = 1800\r\nMin = 0\r\nMax = 3600\r\nStep = 1\r\n'
d = {}
for pair in [val.split('=') for val in s.split('\r\n')[1:-1]]:
    d[pair[0]] = int(pair[1])

rawDescription: Extracting Values from a String

description: Extracting Values from a String


code:
from distutils.core import setup
import py2exe
setup(
    options={
       "py2exe" : {"includes" : ["sip",]}
    },
    data_files = [
      ('imageformats', [
        r'C:\programs\Python271\Lib\site-packages\PyQt4\plugins\imageformats\qico4.dll'
        ])],
    console=[{
       "script" : "manage.py"
    }]
)

rawDescription: py2exe and disappeared icon

description: Py2exe and disappeared icon


code:
chars = set("abc")
chars.issubset("bracket")
chars.issubset("fish")
chars.issubset("bad")

rawDescription: matching all characters in any order in regex

description: Matching all characters in any order in regex


rawDescription: Select Children of an Object With ForeignKey in Django?


code: df.ix[(df.condition==0) & (df.rank>1), 'rank'] = 1

rawDescription: Faster way to assign new values in pandas dataframe


code:
import json

a = {'foo': 'bar', 'baz': 42, 'biz': True}

# Save
with open('test.txt', 'w') as outf:
    json.dump(a, outf)

# Read
with open('test.txt', 'r') as inf:
    b = json.load(inf)

rawDescription: Convert String to Dictionary variable with right types


code:
def letter(word_list):
    words = []
    for word in word_list:
        if len(word)==4:
            words.append(word)
    return words

rawDescription: returning the word if it is of certain length in python

description: Returning the word if it is of certain length in python


code:
while questionNo == 10 and score >= 0:
    if schClass == '1':
     inFile = open("scores1.txt", 'a')
     inFile.write("\n" + name + " : " + str(score))
     inFile.close()
     score = -1
    elif schClass == '2':
     inFile = open("scores2.txt", 'a')
     inFile.write("\n" + name + " : " + str(score))
     inFile.close()
     score = -1
    elif schClass == '3':
     inFile = open("scores3.txt", 'a')
     inFile.write("\n" + name + " : " + str(score))
     inFile.close()
     score = -1

rawDescription: Trying to store answers in a text file

description: Trying to store answers in a text file


code:
widgets = {
            'content': forms.Textarea(),
            'post': forms.HiddenInput(),
        }

rawDescription: How can I get initial data in CreateView, Django

description: Get initial data in CreateView, Django


rawDescription: Multiple colors in Python

description: Multiple colors in Python


code:
import Tkinter as tk

root = tk.Tk()
root.geometry('200x200+200+200')

tk.Label(root, text='Label', bg='green').pack(expand=1, fill=tk.Y)
tk.Label(root, text='Label2', bg='red').pack(fill=tk.BOTH)

root.mainloop()

rawDescription: Difference between "fill" and "expand" options for tkinter pack method


code:
# Code that creates folder, statusCode, statusMessage, groupId
response = render_to_response('create.xml', {'statusCode': statusCode,
                                                   'statusMessage': statusMessage,
                                                   'groupId': groupId,
                                                   }, mimetype = 'text/xml')
# Some other code, maybe an import pdb; pdb.set_trace()
# So that you can inspect the response inside of a python shell.
return response

rawDescription: build an API service in Django

description: Build an API service in Django


code:
import wx

def createBoxes():
    outVSizer = wx.BoxSizer(wx.VERTICAL)
    outHSizer = wx.BoxSizer(wx.HORIZONTAL)
    outVSizer.AddStretchSpacer(1)
    outHSizer.AddStretchSpacer(1)
    sizer = wx.FlexGridSizer(rows=3, cols=3, vgap=55, hgap=20)

    box = {}
    boxSizer = {}
    #text = wx.StaticText(panel, wx.ID_ANY, "This is a test")
    for i in range(6):
        box[i] = wx.StaticBox(panel, wx.ID_ANY, "testBox", size=(0,100))
        text = wx.StaticText(panel, wx.ID_ANY, "This is a test")
        boxSizer[i] = wx.StaticBoxSizer(box[i], wx.VERTICAL)
        boxSizer[i].Add(text, proportion = 1, flag=wx.ALIGN_CENTER)
        sizer.Add(boxSizer[i], flag=wx.EXPAND)
    sizer.AddGrowableCol(0,1)
    sizer.AddGrowableCol(1,1)
    sizer.AddGrowableCol(2,1)

    outHSizer.Add(sizer, flag=wx.EXPAND, proportion=15)
    outHSizer.AddStretchSpacer(1)
    outVSizer.Add(outHSizer, flag=wx.EXPAND, proportion=15)
    panel.SetSizer(outVSizer)

app = wx.App()
frame = wx.Frame(None, size=(500,500))
panel = wx.Panel(frame)
createBoxes()
frame.Show()
app.MainLoop()

rawDescription: wxPython — StaticBox Sizer resizing Static Boxes

description: WxPython — StaticBox Sizer resizing Static Boxes


rawDescription: Making sublist indices refer to the original list


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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

sp = ax.scatter(data[:,0],data[:,1],data[:,2], s=20, c=data[:,3])
plt.colorbar(sp)

rawDescription: Plotting 4d-data

description: Plotting 4d-data


code:
def windows():
    while True:
        print('\n---Maintenence Window Config---\n')
        mwdate = input('Enter the date for the maintenance window (3 letters, Mon, Tue, Wed, etc.) : ')
        if len(mwdate) > 3 or len(mwdate) < 3:
            print('Error, date must be 3 characters in length.')
            continue

        mwstart = input('Enter the time in 24h format for the beginning of the maintenance window (e.x. 04:00): ')
        mwend = input('Enter the ending time of the maintenance window in 24h format (e.x. 04:30): ')
        if int((mwstart and mwend).replace(':','')) < 1000 and (mwstart and mwend).startswith('0'):
            mwindow = mwdate.capitalize()+mwstart+'-'+mwdate.capitalize()+mwend
            return mwindow

        print('Error, be sure you prefix your window times with a 0 if they are earlier than 10:00.')

rawDescription: Python function returning 'None' on consecutive runs


code:
count = 0
for match in all_files('*.html', '.'):       # all_files returns all html files in current directory
    with open(match) as thefile:
        content = thefile.read()                 # read entire file into memory
        replacedText = content.replace(oldtext, newtext)
    if replacedText!=content:
        with open(match, 'w') as thefile:
            count += 1
            thefile.write(replacedText)
print (count)        # print the number of files that we modified

rawDescription: Python string replace in a file without touching the file if no substitution was made


code:
from tkinter import *

root = Tk()
text = Text(root)
text.insert(INSERT, "Some example text.\n Some second line of example text")

def onclick(event):
    #print(event)
    event.widget.mark_set(INSERT, '1.0')

text.bind('<ButtonRelease-1>', onclick)
#text.bind('<Button-1>', onclick)

text.pack()

root.mainloop()

rawDescription: Unable to move text 'insert' index with mark_set widget function (Python & Tkinter)


code:
import random
functions = [functionA, functionB]
for _ in range(100):
    function = random.choice(functions)
    function()

rawDescription: How to Run a Random Function in Python 2

description: Run a Random Function in Python 2


code:
# memorize position of fixed elements
fixed = [(pos, item) for (pos,item) in enumerate(items) if item.freeze]
# shuffle list
random.shuffle(items)
# swap fixed elements back to their original position
for pos, item in fixed:
    index = items.index(item)
    items[pos], items[index] = items[index], items[pos]

rawDescription: Python: shuffling list, but keeping some elements frozen


rawDescription: Using Regular Expressions to Import a Large Amount of Data


code: filteredDf.loc[:,"ABCD"] = np.minimum(filteredDf.loc[:,"ABCD"], 2.0)

rawDescription: Finding minima and replacing values in pandas Dataframe


code:
def __init__(self, *args, **kwargs):
    super(MyModelAdminForm, self).__init__(*args, **kwargs)
    self.fields['value'].value = self.instance.get_reverted_value()

rawDescription: Modify variable just in the Django admin but not in database


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

def update_line(num, data, line, img):
    line.set_data(data[...,:num])
    if num == 24:
        img.set_visible(True)
    return line, img

fig1 = plt.figure()

data = np.random.rand(2, 25)
ax1=plt.subplot(211)
l, = plt.plot([], [], 'rx')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
ax2=plt.subplot(212)
nhist, xedges, yedges = np.histogram2d(data[0,:], data[1,:])
img = plt.imshow(nhist, aspect='auto', origin='lower')
img.set_visible(False)
line_ani = animation.FuncAnimation(fig1, update_line, 25,
                                   fargs=(data, l, img),
                                   interval=50, blit=True)
line_ani.repeat = False
plt.show()

rawDescription: Matplotlib - 2 Figures in Subplot - 1 is Animation


rawDescription: How to sort numpy arrays in arrays?

description: Sort numpy arrays in arrays


code:
class Root(object):
    @cherrypy.expose
    def index(self, foo=None):
        if not foo:
            jsondict = [('foo', '1'), ('foo', '2')]
            p = urllib.urlencode(jsondict)
            #url = urllib.urlopen("http://localhost:8080?%s" % params)
            #urlVar = 1
            #urlVar2 = 2
            #requests.get("localhost:8080/?", params =p)

            raise cherrypy.HTTPRedirect("/index?" + p)

        return foo

rawDescription: I add the query string on Url but the Url not exchange


code:
import dis
dis.dis(compile("[x for x in xrange(1000000)]", '<stdin>', 'exec'))

rawDescription: Python list() vs list comprehension building speed


code:
import urllib2
import xml.etree.cElementTree as ET
from datetime import date

from bs4 import SoupStrainer, BeautifulSoup
import nltk
from dateutil.rrule import rrule, DAILY
from nltk.corpus import stopwords

def main_parser():
    a = b = date(2014, 3, 27)
    articles = ET.Element("articles")
    for dt in rrule(DAILY, dtstart=a, until=b):
        url = "http://www.reuters.com/resources/archive/us/" + dt.strftime("%Y") + dt.strftime("%m") + dt.strftime(
            "%d") + ".html"

        links = SoupStrainer("div", "headlineMed")
        soup = BeautifulSoup(urllib2.urlopen(url), "lxml", parse_only=links)

        article_date = ET.SubElement(articles, "article_date")
        article_date.text = str(dt)
        for link in soup.find_all('a'):
            if not 'video' in link['href']:
                try:
                    article_time = ET.SubElement(article_date, "article_time")
                    article_time.text = str(link.text[-11:])

                    article_header = ET.SubElement(article_time, "article_name")
                    article_header.text = str(link.text)

                    article_link = ET.SubElement(article_time, "article_link")
                    article_link.text = str(link['href']).encode('utf-8')

                    try:
                        article_text = ET.SubElement(article_time, "article_text")
                        article_text.text = str(remove_stop_words(extract_article(link['href']))).encode('ascii', 'ignore')
                    except Exception:
                        pass
                except Exception:
                    pass

    tree = ET.ElementTree(articles)
    tree.write("~/Documents/test.xml", "utf-8")

def extract_article(url):
    paragraphs = SoupStrainer('p')
    soup = BeautifulSoup(urllib2.urlopen(url), "lxml", parse_only=paragraphs)
    return soup.text

def remove_stop_words(text):
    text = nltk.word_tokenize(text)
    filtered_words = [w for w in text if not w in stopwords.words('english')]
    return ' '.join(filtered_words)

rawDescription: Slow html parser. How to increase the speed?


code:
import numpy as np
myshape = (10,5,22,4,2)
myarray = np.zeros(myshape)

rawDescription: Python - Create multidimensional array like in R


code:
# rootpath.py
rootpath = "../../../"

# in your scripts
from rootpath import rootpath
datapath = os.path.join(rootpath, "src/resources/datafile1.txt")

rawDescription: Accessing resource files in Python unit tests & main code


code:
size = len("".join(lines).split()) # size of list
[(next(data), next(data)) for i in range(size / 2)]

rawDescription: Python 2.7: Determining the length when using next with a python Iterator


code:
reload(sys.modules['module_name'])
from module_name import one_function

rawDescription: Reload a module after change

description: Reload a module after change


code:
class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):

        self.readSettings()
        self.setWindowTitle('Simple')

        self.show()

    def readSettings(self):
        settings = QtCore.QSettings("AyaanTech", "SoftwareTest")
        self.setGeometry(settings.value("geometry", QtCore.QRect(300, 300, 250, 150)).toRect());

    def writeSettings(self):
        settings = QtCore.QSettings("AyaanTech", "SoftwareTest")
        settings.setValue("geometry", self.geometry());

    def closeEvent(self, event):
        quit_msg = "Do you want to save position and size?"
        reply = QtGui.QMessageBox.question(self, 'Message',
                     quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No, QtGui.QMessageBox.Cancel)

        if reply == QtGui.QMessageBox.Yes:
            self.writeSettings()
            event.accept()
        elif reply == QtGui.QMessageBox.No:
            event.accept()
        else:
            event.ignore()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: Save the selections made in the qcombobox in pyqt


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

img = cv2.imread('messi4.jpg')
b,g,r = cv2.split(img)
img2 = cv2.merge([r,g,b])
plt.subplot(121);plt.imshow(img) # expects distorted color
plt.subplot(122);plt.imshow(img2) # expect true color
plt.show()

cv2.imshow('bgr image',img) # expects true color
cv2.imshow('rgb image',img2) # expects distorted color
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: Extracting a region from an image using slicing in Python, OpenCV


code:
mydict = {'a': {'name': 'Marco', 'gender': 'm', 'age': 38, 'info': 'teacher musician'},
          'b': {'name': 'Daniela', 'gender': 'f', 'age': 28, 'info': 'student music'},
          'c': {'name': 'Maria', 'gender': 'f', 'age': 25, 'info': 'doctor dance whatever'}}

new_dict = {k:v for k,v in mydict.iteritems() if v['age'] < 30 and 'music' in v['info'].split()}
# {'b': {'info': 'student music', 'gender': 'f', 'age': 28, 'name': 'Daniela'}}

rawDescription: How to select a sub-dictionary given a condition

description: Select a sub-dictionary given a condition


code:
import matplotlib as mpl

#To make sure we have always the same matplotlib settings
#(the ones in comments are the ipython notebook settings)

mpl.rcParams['figure.figsize']=(8.0,6.0)    #(6.0,4.0)
mpl.rcParams['font.size']=12                #10
mpl.rcParams['savefig.dpi']=100             #72
mpl.rcParams['figure.subplot.bottom']=.1    #.125

rawDescription: Why is matplotlib plot produced from ipython notebook slightly different from terminal version?


code:
existing = set(x[0] for x in setup)
for expected in ('iapsetting', 'mmssetting', 'iap-mms'):
    if expected not in existing:
        setup.append((expected, 0))

rawDescription: Python insert missing elements in array

description: Python insert missing elements in array


code:
with open("C:/users/EuanRitchie/unempgdp.csv") as f:
    header = f.readline() #reads the first line
    for line in f:
        # Process the rest of the lines here
        ...

rawDescription: Append number to a list but skipping the first line: code not working


code:
import signal
os.kill(process.pid, signal.SIGKILL)

rawDescription: Killing process on Ubuntu with os.system() issue


code:
def hasSubstring(s, l):
    length = 0
    for c in str:
        if c in s:
            length += 1
        else:
            length = 0
        if length > l:
            return True
    return False

rawDescription: Python detect if string contains specific length substring of chars from specific set


code: pilImg = pilImg.convert("RGB")   # or "RGBA" to keep transparency

rawDescription: coloring a jpg image using PIL

description: Coloring a jpg image using PIL


code:
new_list = []
while condition:
    new_list.append(f(x))

rawDescription: Python: Add item to list until a condition is true


code:
def create_profile(sender, instance, created, **kwargs):
    profile = None
    if created:
        profile, created = Profile.objects.get_or_create(user=instance)

post_save.connect(create_profile, sender=User)

rawDescription: Django: create_new_user_and_profile

description: Django: create_new_user_and_profile


code:
volumes = list()
for index in range(0, 50):
    r = z[np.logical_and(zcosmo>index * 0.01, zcosmo<index * 0.01 + 0.01)] / 2
    h = x[np.logical_and(zcosmo>index * 0.01, zcosmo<index * 0.01 + 0.01)]

    volumes.append(math.pi*(r**2)*(h))

rawDescription: Slicing and finding the volume

description: Slicing and finding the volume


rawDescription: Python Pandas: Boolean indexing on multiple columns


code:
pipeline = [
    {'$match': {'date1': {'$exists': True}, 'date2': {'$exists': True}}},
    {'$redact': {'$cond': [{'$lt': ['$date1', '$date2']}, '$$KEEP', '$$PRUNE']}}
]
collection.aggregate(pipeline)

rawDescription: How to retrieve all documents where two fields' value are equals with pymongo?

description: Retrieve all documents where two fields' value are equals with pymongo


code:
from collections import OrderedDict
from itertools import chain

l = [{"items":["apple", "banana"]}, {"items":["banana", "strawberry"]}, {"items":["blueberry", "kiwi", "apple"]}]
OrderedDict.fromkeys(chain.from_iterable(d['items'] for d in l)).keys() # ['apple', 'banana', 'strawberry', 'blueberry', 'kiwi']

rawDescription: Python list comprehension: adding unique elements into list?


rawDescription: python check for duplicates by reversing strings

description: Python check for duplicates by reversing strings


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

x = np.array([1,2,3])
y = np.array([[2,2.2,3],[1,5,1]])

fig, ax = plt.subplots()
lines = ax.plot(x,y.T[:,:])
ax.legend(lines, [str(uuid.uuid4())[:6] for j in range(len(lines))])

plt.show()

rawDescription: add legend to numpy array in matplot lib

description: Add legend to numpy array in matplot lib


rawDescription: How do you create an incremental ID in a Python Class

description: Create an incremental ID in a Python Class


code:
unknown = list("46X90157")
unknown = ''.join(unknown)
for i in range(10):
    print([int(i) for i in unknown.replace("X", str(i))])

rawDescription: How to insert integers into a list without indexing using python?

description: Insert integers into a list without indexing using python


code: help(enumerate)

rawDescription: How to see function signature in Python?

description: See function signature in Python


code:
from django.db.models import Sum, F
qs = Leg.objects.filter(timetrial__leg__order__lte=F('order'))
qs = qs.annotate(duration_prefix_sum=Sum('timetrial__leg__duration'))

rawDescription: Django: Annotate model with a prefix sum


code:
import numpy
probs = numpy.array([proba[0] for proba in self.classifier.predict_proba(x_test)])
list_values = probs/maximum

rawDescription: Fastest way to scale a list of floats

description: Fastest way to scale a list of floats


code:
import functools
from flask import Flask, request, jsonify

app = Flask(__name__)

def accept(func_or_mimetype=None):
    """Decorator which allows to use multiple MIME type handlers for a single
    endpoint.
    """

    # Default MIME type.
    mimetype = 'text/html'

    class Accept(object):
        def __init__(self, func):
            self.default_mimetype = mimetype
            self.accept_handlers = {mimetype: func}
            functools.update_wrapper(self, func)

        def __call__(self, *args, **kwargs):
            default = self.default_mimetype
            mimetypes = request.accept_mimetypes
            best = mimetypes.best_match(self.accept_handlers.keys(), default)
            # In case of Accept: */*, choose default handler.
            if best != default and mimetypes[best] == mimetypes[default]:
                best = default
            return self.accept_handlers[best](*args, **kwargs)

        def accept(self, mimetype):
            """Register a MIME type handler."""

            def decorator(func):
                self.accept_handlers[mimetype] = func
                return func
            return decorator

    # If decorator is called without argument list, return Accept instance.
    if callable(func_or_mimetype):
        return Accept(func_or_mimetype)

    # Otherwise set new MIME type (if provided) and let Accept act as a
    # decorator.
    if func_or_mimetype is not None:
        mimetype = func_or_mimetype
    return Accept

@app.route('/')
@accept     # Or: @accept('text/html')
def index():
    return 'foobar'

@index.accept('application/json')
def index_json():
    return jsonify(foobar=True)

@index.accept('text/plain')
def index_text():
    return 'foobar\n', 200, {'Content-Type': 'text/plain'}

rawDescription: Route requests based on the Accept header in Flask


code:
import glob
files = glob.glob('C:\\python34\\*.txt')

rawDescription: Python: Need to add chosen filenames into an array


code:
from views.celerytasks.mytask1 import my_mega_task_number_one
my_mega_task_number_one.delay()

rawDescription: How to run periodic celery task manually from terminal in pyramid?

description: Run periodic celery task manually from terminal in pyramid


code:
import collections
files_by_str = collections.defaultdict(list)

thestrings = []
with open('Strings.txt') as f:
  for line in f:
    text = line.split('=', 1)[1]
    text = text.strip().replace('"', '')
    thestrings.append(text)

import os

for root, dirs, files in os.walk('/top/dir/of/interest'):
  for name in files:
    path = os.path.join(root, name)
    with open(path) as f:
      data = f.read()
      for text in thestrings:
        if text in data:
          files_by_str[text].append(path)
          break

rawDescription: Python Script to find instances of a set of strings in a set of files


rawDescription: How to remove thousands separator dot from the formatted numbers

description: Remove thousands separator dot from the formatted numbers


code:
db = DAL('sqlite://storage.db')
db = DAL('mysql://username:password@localhost/test')
db = DAL('gae')

rawDescription: Using web.py on Appengine

description: Using web.py on Appengine


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

x = np.arange(0, 5, 0.1);
y = np.sin(x)

fig, ax = plt.subplots()

ann = ax.annotate("Here's a note", xy=(2, 0.5), bbox=dict(facecolor='yellow'))
ann.draggable()

ax.plot(x, y)
plt.show()

rawDescription: "Sticky notes" in matplotlib

description: "Sticky notes" in matplotlib


code: r = re.sub(r"= '.*?';", '', text.rstrip('\r\n'), flags=re.DOTALL)

rawDescription: how to replace string between 2 chars with newline in python

description: Replace string between 2 chars with newline in python


code:
import pandas as pd
import os

source_directory = r'H:\folder'

master_list = []

for file in os.listdir(source_directory):
    if file.endswith(".xlsx") or file.endswith(".xls") or file.endswith(".xlsm") or file.endswith(".xlsb"):
        dataframe = pd.read_excel(source_directory + '\\' + file)
        master_list.append(dataframe)

masterDF = pd.concat(master_list, ignore_index=True)
print(masterDF)

rawDescription: Using python to run command on a specific extension file from a folder and moves it to another folder after it's done


code:
inventory = {'gold' : 500, 'pouch' : ['flint', 'twine', 'gemstone']}
inventory['gold'] += 50
inventory

rawDescription: Is it possible to add on to a value (int) already defined in a key for a dictionary?


code:
import pandas as pd
from pymongo import MongoClient

def _connect_mongo(host, port, username, password, db):
    """ A util for making a connection to mongo """

    if username and password:
        mongo_uri = 'mongodb://%s:%s@%s:%s/%s' % (username, password, host, port, db)
        conn = MongoClient(mongo_uri)
    else:
        conn = MongoClient(host, port)

    return conn[db]

def read_mongo(db, collection, query={}, host='localhost', port=27017, username=None, password=None, no_id=True):
    """ Read from Mongo and Store into DataFrame """

    # Connect to MongoDB
    db = _connect_mongo(host=host, port=port, username=username, password=password, db=db)

    # Make a query to the specific DB and Collection
    cursor = db[collection].find(query)

    # Expand the cursor and construct the DataFrame
    df =  pd.DataFrame(list(cursor))

    # Delete the _id
    if no_id:
        del df['_id']

    return df

rawDescription: How to import data from mongodb to pandas?

description: Import data from mongodb to pandas


code:
my_list = [['A B C','D E F'],['1 2 3 ', '4 5 6 ']]
map(lambda x:x.split(), map(" ".join, my_list))

rawDescription: a function that chages the structure of a python list

description: A function that chages the structure of a python list


code:
#!/usr/bin/env python
import sys
from contextlib import closing as C

import pycurl

class Writer:
   def __init__(self, file):
       self.file = file

   def write(self, data):
       sys.stderr.write(data)
       self.file.write(data)

   def close(self):
       self.file.close()

url = 'http://stackoverflow.com/questions/8909710/'
with C(pycurl.Curl()) as c, C(Writer(open('output','wb'))) as w:
    c.setopt(c.URL, url)
    c.setopt(c.WRITEFUNCTION, w.write)
    c.setopt(c.FOLLOWLOCATION, True)
    c.perform()
    print >>sys.stderr, c.getinfo(c.HTTP_CODE), c.getinfo(c.EFFECTIVE_URL)

rawDescription: How do you read individual cUrl chunks?

description: Read individual cUrl chunks


code: return [f for f in file_list if os.path.isfile(SC_JSON_DIR + f + ".json")]

rawDescription: How to rewrite this using list comprehension

description: Rewrite this using list comprehension


code:
from scipy.signal import convolve2d

def spill2(arr, nval=0, m=1):
    return convolve2d(arr, np.ones((2*m+1, 2*m+1)), mode='same')

np.allclose(spill(t), spill2(t))
# True

rawDescription: Expanding "pixels" on matplotlib + numpy array


rawDescription: Return instance of One to One Field

description: Return instance of One to One Field


code:
import asyncio
import unittest
from unittest.mock import Mock

class ImGoingToBeMocked:
    @asyncio.coroutine
    def yeah_im_not_going_to_run(self):
        yield from asyncio.sleep(1)
        return "sup"

class ImBeingTested:
    def __init__(self, hidude):
        self.hidude = hidude

    @asyncio.coroutine
    def i_call_other_coroutines(self):
        return (yield from self.hidude.yeah_im_not_going_to_run())

class TestImBeingTested(unittest.TestCase):

    def test_i_call_other_coroutines(self):
        mocked = Mock(ImGoingToBeMocked)
        ibt = ImBeingTested(mocked)

        @asyncio.coroutine
        def mock_coro():
            return "sup"
        mocked.yeah_im_not_going_to_run = mock_coro

        ret = asyncio.get_event_loop().run_until_complete(
            ibt.i_call_other_coroutines())
        self.assertEqual("sup", ret)

if __name__ == '__main__':
    unittest.main()

rawDescription: How to mock asyncio coroutines?

description: Mock asyncio coroutines


code:
import tkinter as tk

root = tk.Tk()
root.title("Radio Button Example")
button = tk.Radiobutton(root)  # Make a radio button
button.pack()  # Pack it to the screen
button.select()  #This is the bit that makes it checked
root.mainloop()

rawDescription: Radio buttons in python 3 and tkinter

description: Radio buttons in python 3 and tkinter


rawDescription: Find the closest fraction to a decimal with a specific denominator using Python's fractions module


code:
class MyGroup(models.Model):
    name = models.CharField(max_length=100)

class Membership(models.Model):
    group = models.ForeignKey(MyGroup)
    member = models.ForeignKey(User)

    invited_by = models.ForeignKey(User, related_name='invited_set')

rawDescription: Django many-to-many relations, and through


code: rooms = dict(('room_%d' % x, Room(x)) for x in range(1, 6))

rawDescription: Create variable names on demand

description: Create variable names on demand


code:
import json
d = {'this': 'This word', 'that': 'That other word', 'other': 'foo'}
json.dumps(d)
json.dumps(d, sort_keys=True)

rawDescription: Python + JSON serialization for MD5 hash - how can I guarantee that two equivalent objects will serialize to exactly the same string?


rawDescription: Accessing a dictionary member within the same dictionary


code:
import numpy as np
xs = np.linspace(-3, 5, 800)
ys = np.linspace(-3, 5, 800)
f_vals = np.random.normal(size=(xs.size, ys.size))
np.savez('the_file.npz', xs=xs, ys=ys, f=f_vals)

rawDescription: Storing and reading large data files efficiently


code: sorted_dict.keyOrder = [key[1] for key in sorted((v['priority'],k) for k,v in sorted_dict.items())]

rawDescription: pythonic way to sort a SortedDict

description: Pythonic way to sort a SortedDict


code:
si = StringIO.StringIO()
cw = csv.writer(si)
cw.writerows(csvList)
output = make_response(si.getvalue())
output.headers["Content-Disposition"] = "attachment; filename=export.csv"
output.headers["Content-type"] = "text/csv"
return output

rawDescription: Writing a CSV from Flask framework

description: Writing a CSV from Flask framework


code:
from slice_setup import SLICE_SETUP
import Tkinter as tk
import threading
import Queue

class GuiPart:
    def __init__(self, master, queue):
        self.queue = queue
        self.master = master
        self.master.geometry("300x100+400+250")
        self.master.title("RSAM BCT")
        tk.Label(master, text="REDCOM SLICE", fg="red").pack()
        tk.Label(master, text="BCT - Basic Configuration Test", fg= "red").pack()
        tk.Label(master, text="Please wait...", fg= "black").pack()
        tk.Label(master, text="Estimated time: 3 min 6 sec", fg= "black").pack()

    def processIncoming(self):
        while self.queue.qsize():
            try:
                text = self.queue.get(0)
                Complete(self.master, text)
            except Queue.Empty:
                pass

class ThreadedClient:
    def __init__(self, master):
        self.master = master
        self.queue = Queue.Queue()
        self.gui = GuiPart(master, self.queue)
        self.running = True
        self.thread = threading.Thread(target=self.workerThread1)
        self.thread.start()
        self.periodicCall()

    def periodicCall(self):
        self.gui.processIncoming()
        if not self.running:
            return
        self.master.after(100, self.periodicCall)

    def workerThread1(self):
        obj_rcs = SLICE_SETUP()
        obj_rcs.SLICE()
        self.queue.put("Configuration Complete!")
        self.running = False

class Complete(tk.Toplevel):
    def __init__(self, master=None, completetext=""):
        tk.Toplevel.__init__(self, master)
        self.geometry("400x300+400+250")
        self.title("RSAM BCT")
        tk.Label(self, text="REDCOME SLICE", fg="red").pack()
        tk.Label(self, text="BCT - Basic Configuration Test", fg="red").pack()
        tk.Label(self, text=completetext, fg="dark green").pack()
        tk.Label(self, text="Trunk 1: Port 1: Phone 1: 760-450-4500", fg="black").pack()
        tk.Label(self, text="Trunk 1: Port 2: Phone 2: 760-450-4501", fg="black").pack()
        tk.Button(self, text="    Exit    ", command=self.destroy).pack()

if __name__ == "__main__":
    root = Tkinter.Tk()
    client = ThreadedClient(root)
    root.mainloop()

rawDescription: Tkinter threading

description: Tkinter threading


rawDescription: Efficient Django Query

description: Efficient Django Query


code:
import sys
import os
import zipfile

source_dir = "C:\\myDir\\yourDir"
zip = zipfile.ZipFile("C:\\myDir\\yourDirZip.zip","w",allowZip64=True)

for root, dirs, files in os.walk(source_dir):
    for f in files:
        zip.write(os.path.join(root,f), arcname=f)

zip.close()

rawDescription: ZipFile bad directory structure

description: ZipFile bad directory structure


code:
df2 = churn_df.groupby(['states', 'CATEGORY'])    ['states'].count().unstack('CATEGORY').fillna(0)
df2[['good','bad']].plot(kind='bar', stacked=True, width=1)

rawDescription: Unable to find a way to plot the data in matplotlib


code:
from south.db import db
from south.v2 import SchemaMigration

class Migration(SchemaMigration):
    def forwards(self, orm):
        db.execute('alter table appname_modelname charset=utf8')
        db.execute('alter table appname_modelname alter column fieldname charset=utf8')
        # et cetera for any other char or text columns

    def backwards(self, orm):
        db.execute('alter table appname_modelname charset=latin1')
        db.execute('alter table appname_modelname alter column fieldname charset=latin1')
        # et cetera for any other char or text columns

    complete_apps = ['appname']

rawDescription: Changing the encoding of a table with django+south migrations


rawDescription: OpenCv version 3 some python bindings missing?


code:
driver.get(url)
driver.switch_to.frame(driver.find_element_by_xpath("//iframe"))
content = driver.page_source

rawDescription: Web Scraping : Getting HTML source generated from JSP using Python


code:
import numpy as np

np.sort(a, axis=None).reshape(a.shape)

rawDescription: Sorting matrix without flattening, numpy


code:
def __getitem__(self, x):
    if isinstance(x, slice):
        start = x.start
        stop = x.stop
        step = x.step
        # Do whatever you want to do to define your return
    ...

rawDescription: Data structure for custom indexing

description: Data structure for custom indexing


rawDescription: Making columns and ordering consistent in a Pandas DataFrame


code:
if not value_if_allowed:
    return True

rawDescription: Python, TK Entry field validation

description: Python, TK Entry field validation


code:
import matplotlib.pyplot as plt

plt.plot([0.1,0.5], [0.1,0.5], color='g', label='data1')
plt.plot([], [], color='b', label='data2')
plt.plot([0.2,0.6], [0.1,0.5], color='b', label='data3')
plt.legend(loc=0)

rawDescription: Legend in python without labels

description: Legend in python without labels


code: data = [d.Id for d in MyDate().query.all()]

rawDescription: Convert LINQ to List<T> to Python 2.7

description: Convert LINQ to List<T> to Python 2.7


code:
x = input("Enter x:")
y = input("Enter y:")
xv = input("Enter xv:")
yv = input("Enter yv:")
s = input("Enter s:")

DrawGraph(x, y, xv, yv, s)

rawDescription: How to use a function with an input?

description: Use a function with an input


code:
def add(self, second_number):
    difference = self.substract()
    return difference + second_number

rawDescription: Call a method from a class on something created by a different method in the same class?


code:
#!/usr/bin/env python
import urllib
import json
import codecs

search = urllib.urlopen("http://search.twitter.com/search.json?q="+"android&rpp=100")

with codecs.open('/tmp/fap.txt', 'a+', 'utf8') as f:
    dict = json.loads(search.read())
    for result in dict["results"]:
        f.write('# %s\n' % result["text"])

rawDescription: Python output from twitter search api to txt


code: test[numpy.logical_or.reduce([test[:,1] == x for x in wanted])]

rawDescription: Selecting rows from a NumPy ndarray

description: Selecting rows from a NumPy ndarray


rawDescription: How to minimize opened application with subprocess.call()

description: Minimize opened application with subprocess.call()


code: open('foo.txt', 'w').write(repr(foo))

rawDescription: how to explore a very big variable in python?

description: Explore a very big variable in python


code:
def max_ill(self):
    # Helper function to create the needed values. Not to be used directly
    maxval = max(self.illarr)
    maxpts = [idx for idx,val in enumerate(self.illarr) if val==maxval]
    maxpts = [ self.roomgrid.ptsdict[pt].ptid for pt in maxpts ]
    # Save the calculated values as attributes
    self._max_ill_data = maxval
    self._max_ill_points = maxpts

@property
def max_ill_data(self):
    try:
        # Get the saved value (raises an AttributeError when not existing)
        return self._max_ill_data
    except AttributeError:
        # We found None, so call the method that creates these and return it afterwards
        self.max_ill()
        return self._max_ill_data

@property
def max_ill_points(self):
    try:
        return self._max_ill_points
    except AttributeError:
        self.max_ill()
        return self._max_ill_points

rawDescription: What is the most efficient way to return multiple values from a class method in Python?


code:
from collections import defaultdict

outdict = defaultdict(list)
def getkeybyvalue(dictionary, value):
    return [i for i,j in dictionary.items() if value in j]

dict_from_file = """foo\tfoobar, bar, foo foo\tFoo bar language, computing\nprog\t python, java, c, c++\t computing\nedibles\tcereal, milk, whatever\tfood"""

columns = [line.strip().split('\t') for line in dict_from_file.split('\n')]
for c1, c2, c3 in columns:
    for c3_item in c3.split(','):
        outdict[c3_item.strip(', ')] += [c1] + [c.strip(' ,') for c in c2.split(',')]

for k in outdict:
    print(k, outdict[k])

print(getkeybyvalue(outdict, 'foo foo'))

rawDescription: Reversing key-values for dictionary read from textfile - python


code:
s = 'Promo 77'
"".join(i for i in s if i.isdigit())

rawDescription: Replace everything but digits

description: Replace everything but digits


code:
import crypt
def hashPassword(salt, password, rounds=5000):
    return crypt.crypt(password, '$6$rounds={:d}${}$'.format(rounds, salt))

rawDescription: PHP SHA-512 to Python+C SHA-512

description: PHP SHA-512 to Python+C SHA-512


code:
for index in range(n):
    for i,j in enumerate(range(index,n)):
        'do something'

rawDescription: How do I use 2 variables in a Python for loop in the recommended Pythonic way?

description: Use 2 variables in a Python for loop in the recommended Pythonic way


code:
from flask import Flask
import unittest

app = Flask(__name__)
app.debug = True

@app.route('/<int:thing>')
def num(thing):
    return 'INT'

@app.route('/<thing>')
def string(thing):
    return 'STR'

class TestDispatch(unittest.TestCase):

    def setUp(self):
        self.client = app.test_client()

    def test_int(self):
        resp = self.client.get('/10')
        self.assertEqual("INT", resp.data)

    def test_str(self):
        resp = self.client.get('/hello')
        self.assertEqual("STR", resp.data)

if __name__ == '__main__':
    unittest.main()

rawDescription: Flask equivalent of Sinatra's "passing"

description: Flask equivalent of Sinatra's "passing"


code: Graph.Read_Ncol(netFile, names=True, weights="if_present", directed=True)

rawDescription: python-igraph number of vertices

description: Python-igraph number of vertices


code:
#!/usr/bin/env python

import pyglet

window = pyglet.window.Window()
fps_display = pyglet.clock.ClockDisplay()
label = pyglet.text.Label('Hello World!',font_name='Arial',font_size=36, x=0, y=0)

@window.event
def on_mouse_motion(x, y, dx, dy):
    window.clear()
    label.x = x
    label.y = y

fps_display = pyglet.clock.ClockDisplay()

@window.event
def on_draw():
    fps_display.draw()
    label.draw()

pyglet.app.run()

rawDescription: How to use on_mouse_motion to move around a lable via pyglet?

description: Use on_mouse_motion to move around a lable via pyglet


rawDescription: Python reorder a sorted list so the highest value is in the middle


code:
import wx, wx.lib.customtreectrl, wx.gizmos
try:
    import treemixin
except ImportError:
    from wx.lib.mixins import treemixin

overview = treemixin.__doc__

class TreeModel(object):
    ''' TreeModel holds the domain objects that are shown in the different
    tree controls. Each domain object is simply a two-tuple consisting of
    a label and a list of child tuples, i.e. (label, [list of child tuples]).
    '''
    def __init__(self, *args, **kwargs):
        self.items = []
        self.itemCounter = 0
        super(TreeModel, self).__init__(*args, **kwargs)

    def GetItem(self, indices):
        text, children = 'Hidden root', self.items
        for index in indices:
            text, children = children[index]
        return text, children

    def GetText(self, indices):
        return self.GetItem(indices)[0]

    def GetChildren(self, indices):
        return self.GetItem(indices)[1]

    def GetChildrenCount(self, indices):
        return len(self.GetChildren(indices))

    def SetChildrenCount(self, indices, count):
        children = self.GetChildren(indices)
        while len(children) > count:
            children.pop()
        while len(children) < count:
            children.append(('item %d'%self.itemCounter, []))
            self.itemCounter += 1

    def MoveItem(self, itemToMoveIndex, newParentIndex):
        itemToMove = self.GetItem(itemToMoveIndex)
        newParentChildren = self.GetChildren(newParentIndex)
        newParentChildren.append(itemToMove)
        oldParentChildren = self.GetChildren(itemToMoveIndex[:-1])
        oldParentChildren.remove(itemToMove)

class DemoTreeMixin(treemixin.VirtualTree, treemixin.DragAndDrop,
                    treemixin.ExpansionState):
    def __init__(self, *args, **kwargs):
        self.model = kwargs.pop('treemodel')
#         self.log = kwargs.pop('log')
        super(DemoTreeMixin, self).__init__(*args, **kwargs)
        self.CreateImageList()

    def CreateImageList(self):
        size = (16, 16)
        self.imageList = wx.ImageList(*size)
        for art in wx.ART_FOLDER, wx.ART_FILE_OPEN, wx.ART_NORMAL_FILE:
            self.imageList.Add(wx.ArtProvider.GetBitmap(art, wx.ART_OTHER,
                                                        size))
        self.AssignImageList(self.imageList)

    def OnGetItemText(self, indices):
        return self.model.GetText(indices)

    def OnGetChildrenCount(self, indices):
        return self.model.GetChildrenCount(indices)

    def OnGetItemFont(self, indices):
        # Show how to change the item font. Here we use a small font for
        # items that have children and the default font otherwise.
        if self.model.GetChildrenCount(indices) > 0:
            return wx.SMALL_FONT
        else:
            return super(DemoTreeMixin, self).OnGetItemFont(indices)

    def OnGetItemTextColour(self, indices):
        # Show how to change the item text colour. In this case second level
        # items are coloured red and third level items are blue. All other
        # items have the default text colour.
        if len(indices) % 2 == 0:
            return wx.RED
        elif len(indices) % 3 == 0:
            return wx.BLUE
        else:
            return super(DemoTreeMixin, self).OnGetItemTextColour(indices)

    def OnGetItemBackgroundColour(self, indices):
        # Show how to change the item background colour. In this case the
        # background colour of each third item is green.
        if indices[-1] == 2:
            return wx.GREEN
        else:
            return super(DemoTreeMixin,
                         self).OnGetItemBackgroundColour(indices)

    def OnGetItemImage(self, indices, which):
        # Return the right icon depending on whether the item has children.
        if which in [wx.TreeItemIcon_Normal, wx.TreeItemIcon_Selected]:
            if self.model.GetChildrenCount(indices):
                return 0
            else:
                return 2
        else:
            return 1

    def OnDrop(self, dropTarget, dragItem):
        dropIndex = self.GetIndexOfItem(dropTarget)
        dropText = self.model.GetText(dropIndex)
        dragIndex = self.GetIndexOfItem(dragItem)
        dragText = self.model.GetText(dragIndex)

        self.model.MoveItem(dragIndex, dropIndex)
        self.GetParent().RefreshItems()

class VirtualTreeCtrl(DemoTreeMixin, wx.TreeCtrl):
    pass

class VirtualTreeListCtrl(DemoTreeMixin, wx.gizmos.TreeListCtrl):
    def __init__(self, *args, **kwargs):
        kwargs['style'] = wx.TR_DEFAULT_STYLE | wx.TR_FULL_ROW_HIGHLIGHT
        super(VirtualTreeListCtrl, self).__init__(*args, **kwargs)
        self.AddColumn('Column 0')
        self.AddColumn('Column 1')
        for art in wx.ART_TIP, wx.ART_WARNING:
            self.imageList.Add(wx.ArtProvider.GetBitmap(art, wx.ART_OTHER,
                                                        (16, 16)))

    def OnGetItemText(self, indices, column=0):
        # Return a different label depending on column.
        return '%s, column %d'%\
            (super(VirtualTreeListCtrl, self).OnGetItemText(indices), column)

    def OnGetItemImage(self, indices, which, column=0):
        # Also change the image of the other columns when the item has
        # children.
        if column == 0:
            return super(VirtualTreeListCtrl, self).OnGetItemImage(indices,
                                                                   which)
        elif self.OnGetChildrenCount(indices):
            return 4
        else:
            return 3

class VirtualCustomTreeCtrl(DemoTreeMixin,
                            wx.lib.customtreectrl.CustomTreeCtrl):
    def __init__(self, *args, **kwargs):
        self.checked = {}
        kwargs['style'] = wx.TR_HIDE_ROOT | \
            wx.TR_HAS_BUTTONS | wx.TR_FULL_ROW_HIGHLIGHT
        super(VirtualCustomTreeCtrl, self).__init__(*args, **kwargs)
        self.Bind(wx.lib.customtreectrl.EVT_TREE_ITEM_CHECKED,
                  self.OnItemChecked)

    def OnGetItemType(self, indices):
        if len(indices) == 1:
            return 1
        elif len(indices) == 2:
            return 2
        else:
            return 0

    def OnGetItemChecked(self, indices):
        return self.checked.get(indices, False)

    def OnItemChecked(self, event):
        item = event.GetItem()
        itemIndex = self.GetIndexOfItem(item)
        if self.GetItemType(item) == 2:
            # It's a radio item; reset other items on the same level
            for nr in range(self.GetChildrenCount(self.GetItemParent(item))):
                self.checked[itemIndex[:-1]+(nr,)] = False
        self.checked[itemIndex] = True

class TreeNotebook(wx.Notebook):
    def __init__(self, *args, **kwargs):
        treemodel = kwargs.pop('treemodel')
        super(TreeNotebook, self).__init__(*args, **kwargs)
        self.trees = []
        for class_, title in [(VirtualTreeCtrl, 'TreeCtrl'),
                              (VirtualTreeListCtrl, 'TreeListCtrl'),
                              (VirtualCustomTreeCtrl, 'CustomTreeCtrl')]:
            tree = class_(self, treemodel=treemodel)
            self.trees.append(tree)
            self.AddPage(tree, title)
        self.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED, self.OnPageChanged)

    def OnPageChanged(self, event):
        oldTree = self.GetPage(event.OldSelection)
        newTree = self.GetPage(event.Selection)
        newTree.RefreshItems()
        newTree.SetExpansionState(oldTree.GetExpansionState())
        event.Skip()

    def GetIndicesOfSelectedItems(self):
        tree = self.trees[self.GetSelection()]
        if tree.GetSelections():
            return [tree.GetIndexOfItem(item) for item in tree.GetSelections()]
        else:
            return [()]

    def RefreshItems(self):
        tree = self.trees[self.GetSelection()]
        tree.RefreshItems()
        tree.UnselectAll()

class TestPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.treemodel = TreeModel()
        self.CreateControls()
        self.LayoutControls()

    def CreateControls(self):
        self.notebook = TreeNotebook(self, treemodel=self.treemodel)
        self.label = wx.StaticText(self, label='Number of children: ')
        self.childrenCountCtrl = wx.SpinCtrl(self, value='0', max=10000)
        self.button = wx.Button(self, label='Update children')
        self.button.Bind(wx.EVT_BUTTON, self.OnEnter)

    def LayoutControls(self):
        hSizer = wx.BoxSizer(wx.HORIZONTAL)
        options = dict(flag=wx.ALIGN_CENTER_VERTICAL|wx.ALL, border=2)
        hSizer.Add(self.label, **options)
        hSizer.Add(self.childrenCountCtrl, 2, **options)
        hSizer.Add(self.button, **options)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.notebook, 1, wx.EXPAND)
        sizer.Add(hSizer, 0, wx.EXPAND)
        self.SetSizer(sizer)

    def OnEnter(self, event):
        indicesList = self.notebook.GetIndicesOfSelectedItems()
        newChildrenCount = self.childrenCountCtrl.GetValue()
        for indices in indicesList:
            text = self.treemodel.GetText(indices)
            oldChildrenCount = self.treemodel.GetChildrenCount(indices)
#             self.log.write('%s %s now has %d children (was %d)'%(text, indices,
#                 newChildrenCount, oldChildrenCount))
            self.treemodel.SetChildrenCount(indices, newChildrenCount)
        self.notebook.RefreshItems()

class MainFrame(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        """"""
        wx.Frame.__init__(self, None, title="Test")
        panel = TestPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MainFrame()
    frame.Show()
    app.MainLoop()

rawDescription: WxPython demo code- passing a logger object


rawDescription: Format() in Python Regex

description: Format() in Python Regex


code:
def multiply(a,b):
    r"""
    returns a \times b
    """
    return a*b

rawDescription: How to enable math in sphinx?

description: Enable math in sphinx


code:
from collections import abc
isinstance(set(), abc.Iterable)
isinstance((), abc.Iterable)
isinstance([], abc.Iterable)
isinstance('', abc.Iterable)
isinstance({}, abc.Iterable)
isinstance(0, abc.Iterable)

rawDescription: Common baseclass for iterables?

description: Common baseclass for iterables


code:
import os
import sys
os.path.dirname(sys.executable)

rawDescription: How can I know python's path under windows?

description: Know python's path under windows


code: numpy.apply_along_axis(sum, 1, X)

rawDescription: Vectorize over the rows of an array

description: Vectorize over the rows of an array


code:
lst = [3, 3, 4]
import itertools
set(itertools.permutations(lst))

rawDescription: Python get all combinations of numbers

description: Python get all combinations of numbers


code:
ts = calendar.timegm(datetime(2010, 7, 1, tzinfo=pytz.utc).timetuple())
datetime.fromtimestamp(ts, tz=pytz.utc)

rawDescription: Converting python datetime to timestamp and back in UTC still uses local timezone


code:
s = 'ifmmp'
new_s = ''
for c in s:
    n = ord(c)
    n = n - 1
    if n < ord('a'):
        # 'a' -> 'z'
        n = ord('z')
    new_s += chr(n)
# print('new_s = %r' % new_s)  -> new_s = 'hello'

rawDescription: Looping for every character in a string in Python decoder ring


code:
class Board:

    def __init__(self, square1=' ', square2=' ', square3=' ', square4=' ', square5=' ', square6=' ', square7=' ', square8=' ', square9=' '):
        self.square1 = square1
        self.square2 = square2
        self.square3 = square3
        self.square4 = square4
        self.square5 = square5
        self.square6 = square6
        self.square7 = square7
        self.square8 = square8
        self.square9 = square9

    def grid(self):
        message = '\nSQUARES ARE 0-8, TOP LEFT TO BOTTOM RIGHT, TRAVEL HORIZONTALLY\n   |   |   \n ' + self.square1+' | '+self.square2+' | '+self.square3+'  \n___|___|___\n   |   |   \n '+self.square4+' | '+self.square5 + ' | ' + self.square6+'  \n___|___|___\n   |   |   \n ' + self.square7 + ' | ' + self.square8+' | ' + self.square9+'  \n   |   |   '
        print(message)

game=Board()

print(game.grid)

while True:
    entry = raw_input('Please enter a number\n')
    if entry == '0':
        game.square1='X'

    elif entry == '1':
        game.square2='X'

    elif entry == '2':
        game.square3='X'

    elif entry == '3':
        game.square4='X'

    elif entry == '4':
        game.square5='X'

    elif entry == '5':
        game.square6='X'

    elif entry == '6':
        game.square7='X'

    elif entry == '7':
        game.square8='X'

    elif entry == '8':
        game.square9='X'

    print(game.grid())

rawDescription: OOP Python Tic Tac Toe update class for board


code:
class BaseModel(models.Model):
    """
    Base model which all other models can inherit from.
    """
    id = fields.CustomUUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)

    class Meta:
        # Abstract models are not created in the DB
        abstract = True

class MyModel(BaseModel):
    my_field = models.CharField(max_length=50)

    def save(self, *args, **kwargs):
        if self.created:
            # Do stuff
            pass
        super(MyModel, self).save(*args, **kwargs)

rawDescription: How to tell if a model instance is new or not when using UUIDField as a Primary Key

description: Tell if a model instance is new or not when using UUIDField as a Primary Key


code:
df = pd.DataFrame(np.random.randint(1,5, size=(3,3)))
df
map_array = {1:'one', 2:'two', 4:'four'}
df.replace(map_array)
df.replace(map_array, inplace=True)
df

rawDescription: Is there a way to do this Series.map in place?


code:
import sys
from PySide import QtGui

class Widget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

        self.view = QtGui.QGraphicsView()
        self.scene = QtGui.QGraphicsScene()
        self.scene.setSceneRect(0,0,100,100)
        self.view.setScene(self.scene)

        self.button = QtGui.QPushButton('Move path')
        self.button.clicked.connect(self.movePath)

        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.view)
        layout.addWidget(self.button)

        self.setLayout(layout)

        self.createPath()

    def createPath(self):
        path = QtGui.QPainterPath()

        path.moveTo(25, 25)
        path.lineTo(25, 75)
        path.lineTo(75, 75)
        path.lineTo(75, 25)
        path.lineTo(25, 25)

        self.pathItem = self.scene.addPath(path)

    def movePath(self):
        # get the path
        path = self.pathItem.path()

        # change some elements
        # element 0: moveTo(25, 25)
        # element 1: lineTo(25, 75)
        # element 2: lineTo(75, 75)
        # ...
        path.setElementPositionAt(2, 90, 85)
        path.setElementPositionAt(3, 90, 15)

        # set the new path
        self.pathItem.setPath(path)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Widget()
    main.show()

    sys.exit(app.exec_())

rawDescription: QPainterPath - moving/deleting Elements

description: QPainterPath - moving/deleting Elements


code:
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
import matplotlib.figure as mfig
import PyQt4.QtGui as gui, PyQt4.QtCore as core
import collections
import time
import random

#import serial
#ser = serial.Serial('/dev/tty.usbmodem1411', 9600)
#def get_line():
#    return ser.readline()

def get_line():
    x = time.time()%10000
    y = random.random() * 5
    return "%d %.3f\n" % (x,y)

refreshMillis = 300
N = 10
xs = collections.deque(maxlen=N)
ys = collections.deque(maxlen=N)

app = gui.QApplication([])

fig = mfig.Figure()
canvas = FigureCanvasQTAgg(fig)

ax = fig.add_subplot(111)
ax.set_ylim([0,5])
line2D, = ax.plot(xs,ys)
canvas.show()

def process_line():
    line = get_line()
    data = map(float,line.split(' '))
    xs.append(data[0])
    ys.append(data[1])
    line2D.set_data(xs,ys)
    xmin, xmax = min(xs),max(xs)
    if xmin == xmax:
        ax.set_xlim([xmin,xmin+1])
    else:
        ax.set_xlim([xmin,xmax])
    canvas.draw()

timer = core.QTimer()
timer.timeout.connect(process_line)
timer.start(refreshMillis)

app.exec_()

#ser.flush()
#ser.close()

rawDescription: Using Pyserial to plot time against voltage from an Arduino Serial Port


code:
from collections import deque
d = deque(maxlen=3)
d.append('g') # new keystroke
d.append('o') # new keystroke
d.append('d') # new keystroke
d
''.join(d) == 'god'  # check if we already in the god mode
d.append('x') # new keystroke
d
''.join(d) == 'god' # check if we already in the god mode

rawDescription: How to know when a certain sequence of chars is typed?

description: Know when a certain sequence of chars is typed


code:
class TeamModelAdmin(admin.ModelAdmin):
    def get_queryset(request):
         return Team.objects.filter(...)

rawDescription: Django - Restricting User Access to the Admin Site


code:
class PatchedImageView(pg.ImageView):
    def timeLineChanged(self):
        (ind, time) = self.timeIndex(self.timeLine)
        self.sigTimeChanged.emit(ind, time)
        if self.ignoreTimeLine:
            return
        self.play(0)
        if ind != self.currentIndex:
            self.currentIndex = ind
            self.updateImage()

rawDescription: Pyqtgraph's ImageView does not emit "time changed" signal


code: filter(bool, map(str.strip, s.replace('+--', '|').split('Parse:')[1].split('|')))

rawDescription: Extracting String within strings using Regex Python


code:
import gtk

w = gtk.Window()
w.connect('destroy', lambda x: gtk.main_quit())
f = gtk.Frame()
b = gtk.HBox()
f.add(b)
w.add(f)
w.show_all()

gtk.main()

rawDescription: Create a border abound a HBox/Any Widget