code:
import sys
from PyQt4 import QtGui

class QCustomQWidget (QtGui.QWidget):
    def __init__ (self, parent = None):
        super(QCustomQWidget, self).__init__(parent)
        self.textQVBoxLayout = QtGui.QVBoxLayout()
        self.textUpQLabel    = QtGui.QLabel()
        self.textDownQLabel  = QtGui.QLabel()
        self.textQVBoxLayout.addWidget(self.textUpQLabel)
        self.textQVBoxLayout.addWidget(self.textDownQLabel)
        self.allQHBoxLayout  = QtGui.QHBoxLayout()
        self.iconQLabel      = QtGui.QLabel()
        self.allQHBoxLayout.addWidget(self.iconQLabel, 0)
        self.allQHBoxLayout.addLayout(self.textQVBoxLayout, 1)
        self.setLayout(self.allQHBoxLayout)
        # setStyleSheet
        self.textUpQLabel.setStyleSheet('''
            color: rgb(0, 0, 255);
        ''')
        self.textDownQLabel.setStyleSheet('''
            color: rgb(255, 0, 0);
        ''')

    def setTextUp (self, text):
        self.textUpQLabel.setText(text)

    def setTextDown (self, text):
        self.textDownQLabel.setText(text)

    def setIcon (self, imagePath):
        self.iconQLabel.setPixmap(QtGui.QPixmap(imagePath))

class exampleQMainWindow (QtGui.QMainWindow):
    def __init__ (self):
        super(exampleQMainWindow, self).__init__()
        # Create QListWidget
        self.myQListWidget = QtGui.QListWidget(self)
        for index, name, icon in [
            ('No.1', 'Meyoko',  'icon.png'),
            ('No.2', 'Nyaruko', 'icon.png'),
            ('No.3', 'Louise',  'icon.png')]:
            # Create QCustomQWidget
            myQCustomQWidget = QCustomQWidget()
            myQCustomQWidget.setTextUp(index)
            myQCustomQWidget.setTextDown(name)
            myQCustomQWidget.setIcon(icon)
            # Create QListWidgetItem
            myQListWidgetItem = QtGui.QListWidgetItem(self.myQListWidget)
            # Set size hint
            myQListWidgetItem.setSizeHint(myQCustomQWidget.sizeHint())
            # Add QListWidgetItem into QListWidget
            self.myQListWidget.addItem(myQListWidgetItem)
            self.myQListWidget.setItemWidget(myQListWidgetItem, myQCustomQWidget)
        self.setCentralWidget(self.myQListWidget)

app = QtGui.QApplication([])
window = exampleQMainWindow()
window.show()
sys.exit(app.exec_())

rawDescription: PyQt QListWidget custom items

description: PyQt QListWidget custom items


code:
import csv
result = []
listFromCSV = []
names = ['alex','sherlock']
csvFile = open('yourFile.csv')
reader = csv.DictReader(csvFile)
fieldnames = reader.fieldnames
for row in reader:
    listFromCSV.append(row)
csvFile.close()
for name in names:
    for row in listFromCSV:
        if name.strip() in row['surname']:
            result.append(row)

rawDescription: Find matching value in nested list from list


code:
class a(object):
    b = 'bbbb'
    def __init__(self):
        self.c = 'cccc'
a1=a()
a2=a()
a1.b
a2.b
a1.c='dddd'
a1.c
a2.c
a.b= 'common'
a1.b
a2.b

rawDescription: Any difference between 'b' and 'c'?

description: Any difference between 'b' and 'c'


code: commands[com](*args)

rawDescription: Pass elements of a list as arguments to a function in python


code:
from django.db.models.signals import pre_save
from django.dispatch import receiver
import reversion

@receiver(pre_save)
def _pre_save(sender, **kwargs):
    _i = kwargs.get('instance')
    _i_old = sender.objects.get(pk=_i.pk)
    _current, _past = set(_i.__dict__.keys()), set(_i_old.__dict__.keys())
    _intersection = _current.intersection(_past)
    _changed_keys = set(o for o in _intersection if _i.__dict__[o] != _i_old.__dict__[o])
    _comment = ['changed {} from {} to {}'.format(_, _i_old.__dict__[_], _i.__dict__[_]) for _ in _changed_keys]
    reversion.set_comment(', '.join(_comment))

rawDescription: split the revision.comment into field and value in Django-reversion

description: Split the revision.comment into field and value in Django-reversion


code:
import random
random.seed(1)
random.random()
random.random()
random.random()
random.seed(1)
random.random()
random.random()
random.random()

rawDescription: doctest for a function using a randomly generated variable

description: Doctest for a function using a randomly generated variable


code:
class inverted_index(dict):
    def __init__(self,collection_of_docs):
        self.collection_of_docs = collection_of_docs #to store those
        # ... rest of your code

    def get_with_surroundings(document_id, position_tuple):
        start, end = position_tuple
        return self.collection_of_docs[document_id].text[start-10:end+10]

rawDescription: Python - query for inverted index

description: Python - query for inverted index


code:
E = np.einsum('uk, vl, xk, yl, xy, kl->uvxy', Fu, Fv, Fx, Fy, P, B)
E1 = np.einsum('uvxy->uv', E)
E2 = np.einsum('uvxy->uv', np.square(E))

rawDescription: How to do a sum of sums of the square of sum of sums?

description: Do a sum of sums of the square of sum of sums


code:
import numpy as np
from scipy.spatial.distance import cdist, euclidean

def geometric_median(X, eps=1e-5):
    y = np.mean(X, 0)

    while True:
        D = cdist(X, [y])
        nonzeros = (D != 0)[:, 0]

        Dinv = 1 / D[nonzeros]
        Dinvs = np.sum(Dinv)
        W = Dinv / Dinvs
        T = np.sum(W * X[nonzeros], 0)

        num_zeros = len(X) - np.sum(nonzeros)
        if num_zeros == 0:
            y1 = T
        elif num_zeros == len(X):
            return y
        else:
            R = (T - y) * Dinvs
            r = np.linalg.norm(R)
            rinv = 0 if r == 0 else num_zeros/r
            y1 = max(0, 1-rinv)*T + min(1, rinv)*y

        if euclidean(y, y1) < eps:
            return y1

        y = y1

rawDescription: Geometric median of multidimensional points


rawDescription: How to make a Group by and order by max(...) in django

description: Make a Group by and order by max(...) in django


code:
from sqlalchemy.orm import reconstructor
class Cmd(Base):
    __tablename__ = "commands"
    dbid = Column(Integer, Sequence("commands_seq"), primary_key = True)
    cmd_id = Column(SmallInteger)
    instance_dbid =  Column(Integer, ForeignKey("instances.dbid"))
    type = Column(String(20))

    __mapper_args__ = {
    "polymorphic_on" : type,
    "polymorphic_identity" : "Cmd"
    }

    def __init__(self, cmd_id):
        self.cmd_id = cmd_id
        self.cmd_name = event_names[self.cmd_id]

    @reconstructor
    def init_db_load(self):
        self.cmd_name = event_names[self.cmd_id]

rawDescription: SQLAlchemy: Initializing attribute based on other attribute


code:
name_list = ["bob","jim","james","julie","june"]
number_list = ["1","2","3","4","5"]
name_and_number = dict(zip(name_list, number_list))

def namenumb(something):
    try:
        for key,value in name_and_number.items():
            if key == something:
                print("{0}'s number is {1}".format(
                                             something, name_and_number[something]))
            elif value == something:
                print("{0}'s name is {1}".format(
                                             something, key))
    except KeyError:
        print("That name doesn't exist"
            .format(namenumb))

while True:
    word = raw_input("> ")
    namenumb(word)

rawDescription: Python zip() function

description: Python zip() function


code:
class A:
    def meth_a(self): pass

    m = {1: meth_a}
    def foo(self, number):
        self.m[number](self)

a = A()
a.foo(1)

rawDescription: "Programmatically" add stuff to a class?

description: "Programmatically" add stuff to a class


code:
def calc_Factorial(my_list, n, x, e):

  if not my_list:
    my_list.append(n-(n-1))
    return calc_Factorial(my_list, n, x, e)
  else:
    if len(my_list) < n:
         my_list.append(my_list[e]*x)
         return calc_Factorial(my_list, n, x+1, e+1)

    if len(my_list) == n:
        return (my_list)

e = 0
x = 2
n = int(input("Enter number: "))
my_list = []
print (calc_Factorial(my_list, n, x, e))

rawDescription: Function is printing multiple times

description: Function is printing multiple times


code:
from ast import literal_eval
var = "(5, 'kghjsg'), (6, 'kghjsghk'), (7, 'jksgjsg'), (8, 'ksgshgk'), (9, 'hjsdhg')"
literal_eval(var)

rawDescription: splitting a string in python having multiple splitters

description: Splitting a string in python having multiple splitters


code:
import itertools

letters = [ chr(l) for l in range(ord('a'), ord('z')+1) ]

def combinations(skip_to=None):
    combinations = ( itertools.combinations_with_replacement(letters, k) for k in range(1, len(letters)+1) )
    flat = itertools.chain.from_iterable( combinations )
    return flat if skip_to is None else itertools.dropwhile( lambda x: x != skip_to, flat )

rawDescription: Starting value for Pythonic generator over possible letter combinations


code:
def __init__(self, parent, title, percent):

    super(Example, self).__init__(parent, title=title)
    screen_size_x, scree_size_y = wx.GetDisplaySize()
    size_x = round(screen_size_x*percent,0)
    size_y = round(screen_size_y*percent,0)
    self.SetSize((size_x, size_y))
    self.Show()

rawDescription: How to draw a layout size in terms of % in wxpython

description: Draw a layout size in terms of % in wxpython


code:
# After your "Define model parameters" block

def compute_and_plot(ax, alpha):
    #Calculate grid values
    V, W = np.meshgrid(v,w)
    Z = (V**(beta))*(W**(1-beta))
    X = x_bar + a + b*Z
    U = alpha*np.log(V) + (1-alpha)*np.log(X) - c*(W+V)

    CS = QuadContourSet(ax, V, W, U, 200)
    pyl.clabel(CS, inline=1, fontsize=10)

# Plot
fig = pyl.figure()
pyl.title('Simplest default with labels')
ax = fig.add_subplot(221)
compute_and_plot(ax, alpha)

#Define slider for alpha
axcolor = 'lightgoldenrodyellow'
alpha_axis  = pyl.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
alpha_slider = Slider(alpha_axis, 'Amp', 0, 1, valinit=.5)

def update(ax, val):
    alpha = alpha_slider.val
    ax.cla()
    compute_and_plot(ax, alpha)
    pyl.draw()

alpha_slider.on_changed(lambda val: update(ax, val))

pyl.show()

rawDescription: Matplotlib: contour plot with slider widget


code:
import subprocess
import os
import shutil
import re

# default values for command execution - to be configured at installation
defCommand = "test.bat"
defEnd = "Appuyez"
defSource = "."
defDest = ".."
# BEWARE : pattern is in regex format !
defPattern="x.*\.txt"

class Launcher(object):
    '''
Helper to launch a command, wait for a defined string from stderr or stdout
of the command, copy files from a source folder to a destination folder,
and write a newline to the stdin of the command.
Limits : use blocking IO without timeout'''
    def __init__(self, command=defCommand, end=defEnd, source=defSource,
                 dest=defDest, pattern = defPattern):
        self.command = command
        self.end = end
        self.source = source
        self.dest = dest
        self.pattern = pattern

    def start(self):
        'Actualy starts the command and copies the files'
        found = False
        pipes = os.pipe() # use explicit pipes to mix stdout and stderr
        rx = re.compile(self.pattern)
        cmd = subprocess.Popen(self.command, shell=True, stdin=subprocess.PIPE,
                               stdout=pipes[1], stderr=pipes[1])
        os.close(pipes[1])
        while True:
            txt = os.read(pipes[0], 1024)
            #print(txt) # for debug
            if str(txt).find(self.end) != -1:
                found = True
                break
        # only try to copy files if end string found
        if found:
            for file in os.listdir(self.source):
                if rx.match(file):
                    shutil.copy(os.path.join(self.source, file), self.dest)
                    print("Copied : %s" % (file,))
            # copy done : write the newline to command input
            cmd.stdin.write(b"\n")
        cmd.stdin.close()
        try:
            cmd.wait()
            print("Command terminated with %d status" % (cmd.returncode,))
        except:
            print("Calling terminate ...")
            cmd.terminate()
        os.close(pipes[0])

# allows to use the file either as an imported module or directly as a script
if __name__ == '__main__':
    # parse optional parameters
    import argparse

    parser = argparse.ArgumentParser(description='Launch a command and copy files')
    parser.add_argument('--command', '-c', nargs = 1, default = defCommand,
                        help="full text of the command to launch")
    parser.add_argument('--endString', '-e', nargs = 1, default = defEnd,
                        dest="end",
                        help="string that denotes that command has finished processing")
    parser.add_argument('--source', '-s', nargs = 1, default = defSource,
                        help="source folder")
    parser.add_argument('--dest', '-d', nargs = 1, default = defDest,
                        help = "destination folder")
    parser.add_argument('--pattern', '-p', nargs = 1, default = defPattern,
                        help = "pattern (regex format) for files to be copied")

    args = parser.parse_args()

    # create and start a Launcher ...
    launcher = Launcher(args.command, args.end, args.source, args.dest,
                        args.pattern)
    launcher.start()

rawDescription: running command before other finished in python

description: Running command before other finished in python


code:
from Tkinter import Tk

def check():
    root.after(50, check) # 50 stands for 50 ms.

root = Tk()
root.after(50, check)
root.mainloop()

rawDescription: KeyboardInterrupt taking a while

description: KeyboardInterrupt taking a while


code:
def UpdateQuery(data,where):
    if isinstance(data, dict) and where:
        vals = ','.join(["%s=?" %(k) for k,v in data.iteritems()])
        query = "update myTable set %s where id=?" % (vals)
        res = cr.execute(query,where)

rawDescription: Creating an SQL query from a dictionary

description: Creating an SQL query from a dictionary


code: some_large_container = None

rawDescription: Optimizing web-scraper python loop

description: Optimizing web-scraper python loop


code:
import xlwt
import os
import fnmatch

wbk = xlwt.Workbook()
sheet = wbk.add_sheet('data')
row = 0

# sheet.write(1, 1, "Hello")

for (dir, dirs, files) in os.walk('.'):
     # print dir
     for file in files:
         # print " ", file
         if fnmatch.fnmatch(file, '*.txt'):
             L = open(os.path.join(dir, file), "r").read()
             # print "  ", L.__repr__()
             a = sheet.write(row,5,L[:-1])
             # sheet.write(row, 4, "hello")
             # print "   ", a
             row += 1

wbk.save('read_all_txt_in_folders.xls')

rawDescription: How to read all text file contents in a folder and copy those contents as rows into one excel file

description: Read all text file contents in a folder and copy those contents as rows into one excel file


code:
@register.tag
def render_string(parser, token):
    bits = token.contents.split()
    if len(bits) != 2:
        raise TemplateSyntaxError("...")
    return RenderStringNode(bits[1])

class RenderStringNode(Node):
    def __init__(self, varname):
        self.varname = varname

    def render(self, context):
        var = context.get(self.varname, "")
        return Template(var).render(context)

rawDescription: How to display string which contains django template variables?

description: Display string which contains django template variables


code:
#!/usr/bin/env python
# coding: utf8

import socket

MAX_PACKET = 32768

def recv_all(sock):
    r'''Receive everything from `sock`, until timeout occurs, meaning sender
    is exhausted, return result as string.'''

    # dirty hack to simplify this stuff - you should really use zero timeout,
    # deal with async socket and implement finite automata to handle incoming data

    prev_timeout = sock.gettimeout()
    try:
        sock.settimeout(0.01)

        rdata = []
        while True:
            try:
                rdata.append(sock.recv(MAX_PACKET))
            except socket.timeout:
                return ''.join(rdata)

        # unreachable
    finally:
        sock.settimeout(prev_timeout)

def normalize_line_endings(s):
    r'''Convert string containing various line endings like \n, \r or \r\n,
    to uniform \n.'''

    return ''.join((line + '\n') for line in s.splitlines())

def run():
    r'''Main loop'''

    # Create TCP socket listening on 10000 port for all connections,
    # with connection queue of length 1
    server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, \
                                socket.IPPROTO_TCP)
    server_sock.bind(('0.0.0.0', 13000))
    server_sock.listen(1)

    while True:
        # accept connection
        client_sock, client_addr = server_sock.accept()

        # headers and body are divided with \n\n (or \r\n\r\n - that's why we
        # normalize endings). In real application usage, you should handle
        # all variations of line endings not to screw request body
        request = normalize_line_endings(recv_all(client_sock)) # hack again
        request_head, request_body = request.split('\n\n', 1)

        # first line is request headline, and others are headers
        request_head = request_head.splitlines()
        request_headline = request_head[0]
        # headers have their name up to first ': '. In real world uses, they
        # could duplicate, and dict drops duplicates by default, so
        # be aware of this.
        request_headers = dict(x.split(': ', 1) for x in request_head[1:])

        # headline has form of "POST /can/i/haz/requests HTTP/1.0"
        request_method, request_uri, request_proto = request_headline.split(' ', 3)

        response_body = [
            '
Hello, world!
',
            '
This page is in location %(request_uri)r, was requested ' % locals(),
            'using %(request_method)r, and with %(request_proto)r.
' % locals(),
            '
Request body is %(request_body)r
' % locals(),
            '
Actual set of headers received:
',
            '
',
        ]

        for request_header_name, request_header_value in request_headers.iteritems():
            response_body.append('
%r == %r
' % (request_header_name, \
                                                    request_header_value))

        response_body.append('
')

        response_body_raw = ''.join(response_body)

        # Clearly state that connection will be closed after this response,
        # and specify length of response body
        response_headers = {
            'Content-Type': 'text/html; encoding=utf8',
            'Content-Length': len(response_body_raw),
            'Connection': 'close',
        }

        response_headers_raw = ''.join('%s: %s\n' % (k, v) for k, v in \
                                                response_headers.iteritems())

        # Reply as HTTP/1.1 server, saying "HTTP OK" (code 200).
        response_proto = 'HTTP/1.1'
        response_status = '200'
        response_status_text = 'OK' # this can be random

        # sending all this stuff
        client_sock.send('%s %s %s' % (response_proto, response_status, \
                                                        response_status_text))
        client_sock.send(response_headers_raw)
        client_sock.send('\n') # to separate headers from body
        client_sock.send(response_body_raw)

        # and closing connection, as we stated before
        client_sock.close()

run()

rawDescription: How to properly send HTTP response with Python using socket library only?

description: Properly send HTTP response with Python using socket library only


code:
with open('pdftable.csv', 'wt') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    for i in sectionlist:
        writer.writerow([i]) # note the square brackets here

rawDescription: Entire string in For loop, not just character by character


code:
from Bio.Restriction.Restriction import RestrictionBatch

sequence=('ACGGCGAATTCTATCGATAACTG...')

# Read enzyme name from input.
enzyme_name = input("Enter enzyme name:\n") # E.g EcoRI
print (type(enzyme_name)) # <type 'str'>

# Get RestrictionType by name
batch = RestrictionBatch()
batch.add(enzyme_name)
enzyme = batch.get(enzyme_name)
print (type(enzyme)) # RestrictionType

print (enzyme.site in sequence) # True

rawDescription: User input to check a DNA sequence for restriction sites with BioPython


code:
def runCommandWhenInitialized():
    activeWindow = sublime.active_window()
    if activeWindow is not None:
        activeWindow.run_command("mkshelf")
    else:
        sublime.set_timeout(lambda: runCommandWhenInitialized(), 100)

sublime.set_timeout(lambda: runCommandWhenInitialized(), 100)

rawDescription: Safe way to initialize a Plugin that depends on Project settings


code: cLoss =  len(dist_) - sum(TLabels * scipy.ndimage.measurements.sum(TLabels,dist_,dist_) / len(dist_))

rawDescription: NumPy: How to avoid this loop?

description: NumPy: How to avoid this loop


code:
found = False
newlines = []

for line in f:
    if oldstring in line:
        found = True
        newlines.append(line.replace(oldstring, newstring))
    else:
        newlines.append(line)

rawDescription: In Python, how do I efficiently check if a string has been found in a file yet?


code:
if __name__ == "__main__":
    from traits.etsconfig.api import ETSConfig
    ETSConfig.toolkit = 'qt4'
    #
    import warnings
    warnings.filterwarnings(action = "ignore", category = FutureWarning, module="chaco")
    warnings.filterwarnings(action = "ignore", category = FutureWarning, module="traits")
#
from PySide import QtGui, QtCore
import numpy as np
from enable.api import Component, Container, Window
from chaco.api import *
import sys
#
class ChacoPlot(QtGui.QWidget):
    def __init__(self, parent=None):
        super(ChacoPlot, self).__init__(parent)
        #
        self.container = OverlayPlotContainer(padding=40)
        #
        self.enableWindow = Window(self, -1, component=self.container)
        windowLayout = QtGui.QVBoxLayout(self)
        windowLayout.addWidget(self.enableWindow.control)
        #
        self.xRange = DataRange1D()
        self.yRange = DataRange1D()
        #
        self.xMapper = LinearMapper(range=self.xRange)
        self.yMapper = LinearMapper(range=self.yRange)
        #
        self.plots = {}
        # keep a list of plots added to the container
    #
    def setMinimumSize(self, width, height):
        self.enableWindow.control.setMinimumSize(width, height)
    #
    def addLine(self, name, plotType):
        xSource = ArrayDataSource([0])
        ySource = ArrayDataSource([0])
        #
        self.xRange.add(xSource)
        self.yRange.add(ySource)
        #
        index_mapper = self.xMapper
        value_mapper = self.yMapper
        #
        # plotType is a class name
        plot = plotType(    index = xSource,
                            value = ySource,
                            index_mapper = index_mapper,
                            value_mapper = value_mapper,
                            visible = False
                       )
        #
        self.container.add(plot)
        #
        self.plots[name] = {'plot':plot, 'xSource':xSource, 'ySource':ySource}
    #
    def updateLine(self, name, xData, yData):
        plot = self.plots[name]
        #
        if np.array(xData).size != 0:
            plot['plot'].visible = True
        else:
            plot['plot'].visible = False
            xData = [0]
            yData = [0]
        #
        plot['xSource'].set_data(xData)
        plot['ySource'].set_data(yData)
    #
    def addAxis(self, plotName, orientation):
        plot = self.plots[plotName]['plot']
        #
        if orientation == 'top' or orientation == 'bottom':
            mapper = self.xMapper
        if orientation == 'left' or orientation == 'right':
            mapper = self.yMapper
        #
        axis = PlotAxis(plot, orientation=orientation, mapper=mapper)
        plot.overlays.append(axis)
        #
        return axis
    #
    def addMinorAxis(self, plotName, orientation):
        plot = self.plots[plotName]['plot']
        #
        if orientation == 'top' or orientation == 'bottom':
            mapper = self.xMapper
            range = self.xRange
        if orientation == 'left' or orientation == 'right':
            mapper = self.yMapper
            range = self.yRange
        #
        newAxis = PlotAxis(plot, orientation=orientation, mapper=mapper)
        plot.overlays.append(newAxis)
        #
        newAxis.tick_generator = MinorTickGenerator()
        #
        newAxis.tick_label_formatter  = lambda x: ''
        newAxis.tick_in  = 2
        newAxis.tick_out = 2
    #
#
class MinorTickGenerator(AbstractTickGenerator):
    def __init__(self):
        super(MinorTickGenerator, self).__init__()
    #
    def get_ticks(self, data_low, data_high, bounds_low, bounds_high, interval, use_endpoints=False, scale='linear'):
        interval = interval
        #
        if interval == 'auto':
            interval = auto_interval(data_low, data_high)/5.0
        #
        return auto_ticks(data_low, data_high, bounds_low, bounds_high, interval, use_endpoints)
    #
#
if __name__ == "__main__":
    appQT = QtGui.QApplication.instance()
    #
    x1 = np.arange(300)/18.0
    y1 = np.sin(x1)
    x2 = np.arange(300)/18.0
    y2 = 2.0*np.cos(x2)
    #
    plot = ChacoPlot()
    plot.setMinimumSize(400,300)
    #
    plot.addLine('line1', LinePlot)
    plot.addLine('line2', LinePlot)
    plot.updateLine('line1', x1, y1)
    plot.updateLine('line2', x2, y2)
    #
    plot.addAxis('line1', 'bottom')
    plot.addAxis('line1', 'left')
    plot.addMinorAxis('line1', 'bottom')
    plot.addMinorAxis('line1', 'left')
    #
    plot.show()
    appQT.exec_()

rawDescription: Minor ticks in Chaco plot?

description: Minor ticks in Chaco plot


code:
def login_view(request):
    if request.method == 'POST':
        user = authenticate(username=request.POST['username'],     password=request.POST['password'])

        if user is not None:

            if user.is_active:
                login(request, user)
                request.session['user'] = user
                userdetails = user.get_profile()
                timezone.activate(pytz.timezone(userdetails.timezone))
                request.session['django_timezone'] = pytz.timezone(userdetails.timezone)
                # Prioritize favorite company in index list of companies
                return companyHome(request, userdetails.get_favorite_company_id())

rawDescription: Django 1.5 - Python 2.7 - TIME_ZONE does not set correctly ( from custom user field ) upon login, until after first page reload


code:
import  wx

test_list_data = {
1 : ("New", "Explanation text new"),
2 : ("Open", "Explanation text open"),
3 : ("Copy", "Explanation text copy"),
4 : ("Paste", "Explanation text paste")}

class TestListCtrlPanel(wx.Panel):
    def __init__(self, *args, **kwds):
        wx.Panel.__init__(self, *args, **kwds)

        sizer = wx.BoxSizer(wx.VERTICAL)
        BMP_SIZE = 24
        tsize = (BMP_SIZE, BMP_SIZE)
        self.il = wx.ImageList(BMP_SIZE, BMP_SIZE)

        # bitmap generation, uses stock bitmaps included in wxPython
        new_bmp =  wx.ArtProvider.GetBitmap(wx.ART_NEW, wx.ART_TOOLBAR, tsize)
        open_bmp = wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_TOOLBAR, tsize)
        copy_bmp = wx.ArtProvider.GetBitmap(wx.ART_COPY, wx.ART_TOOLBAR, tsize)
        paste_bmp= wx.ArtProvider.GetBitmap(wx.ART_PASTE, wx.ART_TOOLBAR, tsize)

        self.bmpdict = {1: new_bmp, 2: open_bmp, 3: copy_bmp, 4: paste_bmp}

        # mapping wxImageList indices to keys in test_list_data
        self.imglistdict = {}

        for idx, bmp in self.bmpdict.iteritems():
            self.imglistdict[idx] = self.il.Add(bmp)

        self.listctl = wx.ListCtrl(self, -1,
                                 style=wx.LC_REPORT
                                 #| wx.BORDER_SUNKEN
                                 | wx.BORDER_NONE
                                 | wx.LC_EDIT_LABELS
                                 | wx.LC_SORT_ASCENDING
                                 #| wx.LC_NO_HEADER
                                 #| wx.LC_VRULES
                                 #| wx.LC_HRULES
                                 #| wx.LC_SINGLE_SEL
                                 )

        self.listctl.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
        sizer.Add(self.listctl, 1, wx.EXPAND)

        self.PopulateList()

        self.SetSizer(sizer)
        self.SetAutoLayout(True)

    def PopulateList(self):
        # header creation
        info = wx.ListItem()
        info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE | wx.LIST_MASK_FORMAT
        info.m_image = -1
        info.m_format = 0
        info.m_text = "Artist"
        self.listctl.InsertColumnInfo(0, info)

        info.m_text = "Title"
        self.listctl.InsertColumnInfo(1, info)

        # ListCtrl data generation
        items = test_list_data.items()
        for key, data in items:
            imglist_idx = self.imglistdict[key]
            index = self.listctl.InsertImageStringItem(key, data[0], imglist_idx)
            self.listctl.SetStringItem(index, 1, data[1])
            self.listctl.SetItemData(index, key)

class listctltest(wx.Frame):
    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)
        self.pnl = TestListCtrlPanel(self, -1)

if __name__ == '__main__':
    app = wx.App(redirect=False)
    frm = listctltest(None, -1, 'title')
    frm.Show()
    app.MainLoop()

rawDescription: wxPython List Ctrl: Add Column and Images

description: WxPython List Ctrl: Add Column and Images


code:
def prompt():
  global number
  number = raw_input("new 4 digit number: ")
  prompt()

rawDescription: Update a variable used in an infinite loop


code:
class UnInit(object):
    """
    No value yet given to this attribute
    """

class Coordinate(object):
    x = UnInit
    y = UnInit
    z = UnInit

rawDescription: A class whose attributes are all optional


rawDescription: Could I use array slicing instead of creating vectors?


rawDescription: Splitting each item in an array into a separate data frame column


code:
class SquaresTo:
    def __init__(self, n):
        self.n = n
    def __iter__(self):
        for i in range(self.n):
            yield i * i
s = SquaresTo(5)
tuple(s)
list(s)
sum(s)

rawDescription: How to convert an custom class object to a tuple in Python?

description: Convert an custom class object to a tuple in Python


rawDescription: Matplotlib: Plot movements in 3D

description: Matplotlib: Plot movements in 3D


code: returncode = subprocess.call(["python", absolute_path_to_manage_py, "migrate"])

rawDescription: External script and unapplied migrations


code:
import os, re
n = 1
for i in os.listdir('.'):
    os.rename(i, re.sub(r'\(\d{4}\)', '(2009) ({n})'.format(n=n), i))
    n += 1

rawDescription: Python - Rename files and give them sequential number


rawDescription: Project Euler no. 17 - Streamlining Python


code:
if __name__ == '__main__':
  currtag = currentTag()
  newtag = newTag()
  compareTag(currtag,newtag)

rawDescription: 2 responses from 2 functions into new function


code:
pid = subprocess.Popen(["vlc", "-vvv",
    "rtsp://%s" % target_nvc.ip_address + ":554/ch0_multicast_one",
    "--sout=#transcode{acodec=none}:duplicate{dst=rtp{sdp=rtsp://:5544/user_hash.sdp},dst=display}",
    ":no-sout-rtp-sap", ":no-sout-standard-sap",
    ":ttl=1", ":sout-keep" ], stdout=subprocess.PIPE,
    stderr=subprocess.PIPE, stdin=subprocess.PIPE)

rawDescription: executing a subprocess from python

description: Executing a subprocess from python


code:
import matplotlib.pyplot as plt
import seaborn as sns

gammas = sns.load_dataset("gammas")
sns.set(context="paper", palette="colorblind", style="ticks")
fig = plt.figure(figsize=(5,5))
ax1 = fig.add_subplot(111)
sns.tsplot(gammas[(gammas["ROI"] == "IPS")].reset_index(), time="timepoint", unit="subject", value="BOLD signal", ci=95, color="#4477AA", legend=False, ax=ax1)
ax1.set_xlabel("Timepoint")
ax1.set_ylabel("BOLD signal (1)")
ax1.spines["top"].set_visible(False)
ax1.tick_params(top='off')
ax2 = ax1.twinx()
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position("right")
sns.tsplot(gammas[(gammas["ROI"] == "AG")].reset_index(), time="timepoint", unit="subject", value="BOLD signal", ci=95, color="#CC6677", legend=False, ax=ax2)
ax2.set_ylabel("BOLD signal (2)")
ax2.spines["top"].set_visible(False)
ax2.tick_params(top='off')
# Set legend #
ax2.legend([ax1.get_lines()[0], ax2.get_lines()[0]], ["IPS", "AG"], loc='upper left')
# set the aspect ratio so that the scaling is the same on all the axes
ax1.set_aspect('equal')
ax2.set_aspect('equal')

rawDescription: How to make a squared plot when using 2 different y-axis in matplotlib?

description: Make a squared plot when using 2 different y-axis in matplotlib


code:
def _create_file(n, t):
    try:
        n = int(n)
    except:
        n = 1
    ...

@app.route('/create')
def create_file():
    n = request.args.get('n')
    t = request.args.get('t')
    return _create_file(n, t)

@app.route('/create', methods = ['POST'])
def create_file_form():
    n = request.form.get('n')
    t = request.form.get('t')
    return _create_file(n, t)

@app.route('/api/create', methods = ['POST'])
def create_file_json():
    if not request.json:
        abort(400); # bad request
    n = request.json.get('n')
    t = request.json.get('t')
    return _create_file(n, t)

rawDescription: A better way to accept multiple request types in a single view method?


rawDescription: execfile with argument in python shell

description: Execfile with argument in python shell


code:
import os, shutil

for i in files:
  os.mkdir(os.path.join(dir_name , i.split(".")[0]))
  shutil.copy(os.path.join(dir_name , i), os.path.join(dir_name , i.split(".")[0]))

rawDescription: How to create a folder for each item in a directory?

description: Create a folder for each item in a directory


code:
p = subprocess.Popen([sys.executable, '/path/to/script.py'],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.STDOUT)

rawDescription: How do I run another script in Python without waiting for it to finish?

description: Run another script in Python without waiting for it to finish


code:
try:
  nextmonthdate = x.replace(month=x.month+1)
except ValueError:
  if x.month == 12:
    nextmonthdate = x.replace(year=x.year+1, month=1)
  else:
    # next month is too short to have "same date"
    # pick your own heuristic, or re-raise the exception:
    raise

rawDescription: how to get the same day of next month of a given day in python using datetime

description: Get the same day of next month of a given day in python using datetime


code:
import tkinter as tk
import time
import sys

class Display(tk.Frame):
    def __init__(self):
       tk.Frame.__init__(self)
       self.doIt = tk.Button(self,text="Start", command=self.start, background = 'black', fg='white')
       self.doIt.pack()

       self.output = tk.Text(self, width=100, height=15, background = 'black', fg='white')
       self.output.pack(side=tk.LEFT)

       self.scrollbar = tk.Scrollbar(self, orient="vertical", command = self.output.yview)
       self.scrollbar.pack(side=tk.RIGHT, fill="y")

       self.output['yscrollcommand'] = self.scrollbar.set

       self.count = 1
       self.configure(background='black')
       self.pack()

    def start(self):
        if self.count < 1000:
            self.write(str(self.count) + '\n')
            print (self.count)
            self.count += 1
            self.after(2000, self.start)

    def write(self, txt):
        self.output.insert(tk.END,str(txt))
        self.update_idletasks()

if __name__ == '__main__':
    Display().mainloop()

rawDescription: Problems with outputing console to GUI in tkinter


code:
sentence = "The quick brown fox jumps the lazy dog"
words = sentence.split()
# this is a list comprension
# you can create a new list by applying functions to each element in the list.
word_lengths = [len(w) for w in words]
word_length_strings = [str(l).ljust(l) for l in word_lengths]
# now you have a list of strings that start with a number and are left padded
# with spaces to that number.
assert len(words[0]) == len(word_length_strings[0])
# and to join the words up in to one line
line = ' '.join(word_length_strings)
print(sentence)
print(line)

rawDescription: Mapping and looping in python

description: Mapping and looping in python


code:
import slumber
from requests.auth import AuthBase

class ParseAuth(AuthBase):
    def __init__(self, app_id, api_key):
        self.app_id = app_id
        self.api_key = api_key

    def __call__(self, r):
        r.headers['X-Parse-Application-Id'] = self.app_id
        r.headers['X-Parse-REST-API-Key'] = self.api_key
        return r

api = slumber.API("http://api.parse.com/1/", auth=ParseAuth("my_app_id", "my_api_key"))

rawDescription: How to add headers to slumber in python?

description: Add headers to slumber in python


rawDescription: Forming Django queryset for one-to-many relation


code:
import Tkinter as tk

class ScrollableFrame(tk.Frame):
    def __init__(self, master, **kwargs):
        tk.Frame.__init__(self, master, **kwargs)

        # create a canvas object and a vertical scrollbar for scrolling it
        self.vscrollbar = tk.Scrollbar(self, orient=tk.VERTICAL)
        self.vscrollbar.pack(side='right', fill="y",  expand="false")
        self.canvas = tk.Canvas(self,
                                bg='#444444', bd=0,
                                height=350,
                                highlightthickness=0,
                                yscrollcommand=self.vscrollbar.set)
        self.canvas.pack(side="left", fill="both", expand="true")
        self.vscrollbar.config(command=self.canvas.yview)

        # reset the view
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = tk.Frame(self.canvas, **kwargs)
        self.canvas.create_window(0, 0, window=self.interior, anchor="nw")

        self.bind('<Configure>', self.set_scrollregion)

    def set_scrollregion(self, event=None):
        """ Set the scroll region on the canvas"""
        self.canvas.configure(scrollregion=self.canvas.bbox('all'))

if __name__ == '__main__':
    root = tk.Tk()
    checkbox_pane = ScrollableFrame(root, bg='#444444')
    checkbox_pane.pack(expand="true", fill="both")

    def button_callback():
        for x in range(1,20):
            tk.Checkbutton(checkbox_pane.interior, text="hello world! %s" % x).grid(row=x, column=0)

    btn_checkbox = tk.Button(checkbox_pane.interior, text="Click Me!", command=button_callback)
    btn_checkbox.grid(row=0, column=0)
    root.mainloop()

rawDescription: Dynamically adding checkboxes into scrollable frame


code:
cr.save()    # push a new context onto the stack
cr.scale(0.5, 0.5)    # scale the context by (x, y)
cr.set_source_surface(imagesurface, margin, margin)
cr.paint()
cr.restore()    # pop the context

rawDescription: Create PDF with (resized) PNG images using Pycairo - rescaling Surface issue


code:
from math import atan2, degrees

def toast_xy_to_latlon(x, y, size, inside=False):
    """
    Given TOAST x,y coordinates into a size*size HTM
    return lat, lon
      where -90 <= lat <= 90  (degrees North)
      and     0 <= lon <= 360 (degrees East)
    """
    half = size / 2

    # Figure out which quadrant (x, y) is in;
    #   save longitude offset and cast to first quadrant
    #   in new pixel-centered (u, v) coordinate system
    #   where 0.5 <= u,v <= half - 0.5 and (0,0) is North
    if x < half:
        if y < half:
            # 6,7
            lon_offset = 270
            u,v = half - x - 0.5, half - y - 0.5
        else:
            # 0,1
            lon_offset = 0
            u,v = y + 0.5 - half, half - x - 0.5
    else:
        if y < half:
            # 4,5
            lon_offset = 180
            u,v = half - y - 0.5, x + 0.5 - half
        else:
            # 2,3
            lon_offset = 90
            u, v = x + 0.5 - half, y + 0.5 - half

    # Find latitude
    lat = 90 * (1 - (u + v) / half)

    # Find longitude
    if u + v <= half:
        # Northern hemisphere
        lon = degrees(atan2(u, v))
    else:
        # Southern hemisphere
        lon = degrees(atan2(half - v, half - u))

    # Correct longitude offset -
    #   outside projection longitudes are measured CCW from left,
    #   inside projections CCW from right (rotated 180 degrees)
    if inside:
        lon_offset = (lon_offset + 180) % 360

    return lat, lon + lon_offset

rawDescription: Converting a point on a TOAST map to the lat/lon on a sphere


code:
def printInfo(self, basicList):
    ratingList = self.calc(basicList)
    ...

rawDescription: Transferring list from one class method to another


rawDescription: get the flagged bit index in pure python

description: Get the flagged bit index in pure python


code:
from apiclient.http import BatchHttpRequest

def insert_event(request_id, response, exception):
  if exception is not None:
    # Do something with the exception
     pass
  else:
    # Do something with the response
    pass

service = build('calendar', 'v3')

batch = BatchHttpRequest(callback=insert_event)

batch.add(service.events().quickAdd(calendarId="you@domain.com",
  text="Lunch with Jim on Friday"))
batch.add(service.events().quickAdd(calendarId="you@domain.com",
  text="Dinner with Amy on Saturday"))
batch.add(service.events().quickAdd(calendarId="you@domain.com",
  text="Breakfast with John on Sunday"))
batch.execute(http=http)

rawDescription: Google Calendar API v3 batch update in python


code:
import distutils.command.build

class BuildCommandProxy(distutils.command.build.build):
    pass

rawDescription: How do I subclass the build command?

description: Subclass the build command


code:
d = {u'text': u'Foo'}
d.keys()
'text' in d
u'text' in d
d['text']
d[u'text']

rawDescription: Working with unicode keys in a python dictionary


code:
import StringIO

...

base64FileData = attachmentObj.data['data']
fileData = base64.urlsafe_b64decode(base64FileData.encode('UTF-8'))

memoryFile = StringIO.StringIO(fileData)

someFunctionThatOperatesOnFileObjects(memoryFile)

rawDescription: How to convert fileData from str to file type in Python?

description: Convert fileData from str to file type in Python


code: result = int(float(s) * 100)

rawDescription: Python regular expression: decimal part of float


code:
module_dir = os.path.dirname(__file__)
CFG = SafeConfigParser()
cfg_full_path = os.path.join(module_dir, ARGS['--cfg'])
if not CFG.read(cfg_full_path):
    ...

rawDescription: How can I load a configuration file based on the relative path from the script being executed?

description: Load a configuration file based on the relative path from the script being executed


code: {{ form.instance.guest_name }}

rawDescription: Django - Find out which model instance I'm editing in an inline formset


code:
for key in sorted(my_dict, key=operator.itemgetter(1,0)):
    print(my_dict[key])

rawDescription: Iterating through a specific key set in python


code:
import tkinter as tk

root = tk.Tk()
root.geometry("800x600")

height = 20

label_frame = tk.Frame(root,width=700,height=height,bg="white")
label_frame.pack_propagate(0) # Stops child widgets of label_frame from resizing it
tk.Label(label_frame,bg="white",fg="black",text="test",font=("Calibri",15)).pack()
label_frame.place(x=10,y=10)

root.mainloop()

rawDescription: tkinter - create label widget (containing text) with size defined by pixel dimensions

description: Tkinter - create label widget (containing text) with size defined by pixel dimensions


rawDescription: numpy - update values using slicing given an array value

description: Numpy - update values using slicing given an array value


code:
[('Button.button', {'children':
    [('Button.focus', {'children':
        [('Button.padding', {'children':
            [('Button.label', {'sticky': 'nswe'})],
        'sticky': 'nswe'})],
    'sticky': 'nswe'})],
'sticky': 'nswe'})]

rawDescription: Setting the relief of a button in ttk

description: Setting the relief of a button in ttk


code:
def Fin_adj(row, field):
    if field == 'Cr':
        if row[field] <= .7:
            return Range_eval(row[field],0.,.69,.0,.25)
        elif row[field] <= .9:
            return Range_eval(row[field],.7,.89,.25,.5)
        elif row[field] <= 1.1:
            return Range_eval(row[field],.9,1.10,.9,.95)
        elif row[field] <= 1.5:
            return Range_eval(row[field],1.1,1.49,.95,1)
        elif row[field] <= 3.:
            return 1
        else:
            return Range_eval(row[field],3.,df[field].max(),.95,1)

def Range_eval (val_in, Oldmin, Oldmax, Newmin, Newmax):
    return (((val_in - Oldmin) * (Newmax - Newmin)) / (Oldmax - Oldmin)) + Newmin

rawDescription: Data not passing back to Pandas from nested function


code: "{0}\"".format(str(round(x, 1) if x % 1 else int(x)))

rawDescription: Python string interpolation: only show necessary decimal places


code:
import ctypes

# get the module handle and create a ctypes library object
libHandle = ctypes.windll.kernel32.LoadLibraryA('mydll.dll')
lib = ctypes.WinDLL(None, handle=libHandle)

# do stuff with lib in the usual way
lib.Foo(42, 666)

# clean up by removing reference to the ctypes library object
del lib

# unload the DLL
ctypes.windll.kernel32.FreeLibrary(libHandle)

rawDescription: ctypes unload dll

description: Ctypes unload dll


code:
def search(table, scan_filter=None, range_key=None,
           attributes_to_get=None,
           limit=None):

    start_key = None

    while True:
        results = self.conn.layer1.scan(table_name=table,
                                  attributes_to_get=attributes_to_get,
                                  exclusive_start_key=start_key,
                                  limit=request_limit)
        # do stuff with your results

        start_key = results['LastEvaluatedKey']
        if start_key is None:
            break

rawDescription: Clarification questions about Boto Dynamo aws


code:
from tkinter import *

ui = Tk()

e1 = Entry(ui)
e1.insert(0, 'username')
e1.pack()

ui.mainloop()

rawDescription: How to add placeholder to an Entry in tkinter?

description: Add placeholder to an Entry in tkinter


code:
class RegisterView(generic.CreateView):
    model = User
    form_class = forms.RegisterForm
    template_name = 'register.html'
    success_url = reverse_lazy('platforms')

    def get(self, request, *args, **kwargs):
        if request.user is not None:
            return redirect('home')
        # register logic
        return render(request, 'register.html', data)

    def form_valid(self, form):
        response = super(RegisterView, self).form_valid(form)
        user = authenticate(username=form.instance.username, password=form.cleaned_data['password'])
        login(self.request, user)
        return response

rawDescription: How to add logic to classview

description: Add logic to classview


code:
with h5py.File(input,  "a") as f:
    f.__delitem__(datasetname)

rawDescription: Deleting hdf5 dataset using h5py

description: Deleting hdf5 dataset using h5py


code:
a = str(input("your str :"))
x=[]
for i in a:
   x.append(i)
x.reverse()
b = " ".join(x)
print(b)

rawDescription: transformation list to str and print it using join f(x)

description: Transformation list to str and print it using join f(x)


code: self.loop.create_server(lambda: Session(self), 'localhost', 1234)

rawDescription: Python Cyclic Dependency with Async I/O

description: Python Cyclic Dependency with Async I/O


code:
from queue import Empty
from ctypes import c_bool
import multiprocessing

class Worker(multiprocessing.Process):
    def __init__(self, queue):
        multiprocessing.Process.__init__(self) # , daemon=True)
        self.queue = queue
        self.close = multiprocessing.Value(c_bool, False)

    def stop(self):
        self.close.value = True
        print(self.close)

    def run(self):
        while (not self.close.value) or self.queue.qsize() > 0:
            print(self.close)
            print(self.queue.qsize())
            for item in range(0, self.queue.qsize()):
                try:
                    self.queue.get_nowait()
                except Empty:
                    continue

if __name__ == '__main__':
    queue = multiprocessing.Queue()
    dbq = Worker(queue)
    dbq.start()
    queue.put("d")
    dbq.stop()
    dbq.join()

rawDescription: Communicating with Process in Python 3.4 multiprocessing through function calling


rawDescription: Refreshing detached entity in sqlalchemy


code:
def unbiasedsleep(n):
  start = kernel32.QueryUnbiasedInterruptTime()
  target = start + n * 10 * 1000 * 1000
  while True:
    timeleft = target - kernel32.QueryUnbiasedInterruptTime()
    if timeleft > 0:
      time.sleep(timeleft / (10 * 1000 * 1000.0))

rawDescription: time.sleep and suspend (ie. standby and hibernate)

description: Time.sleep and suspend (ie. standby and hibernate)


code:
df = d.reset_index().groupby(['host','operation']).apply(calc_load).set_index('index')
df

rawDescription: Pandas apply to data frame groupby

description: Pandas apply to data frame groupby


code:
for date, mac, rssi in newData:
    requests.post("http://www.google-analytics.com/collect",
          data="v=1&tid=UA-22560594-2&cid={}&t=event&ec={}&ea={}".format(
              mac,
              date,
              rssi)
    )

rawDescription: Looping through a list of tuples to make a POST request with each tuple


code:
class App(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent

        # initialize the new_state
        self.new_state = 'normal'

        self.parent.bind('<Configure>', self._resize_handler)

    def _resize_handler(self, event):
        self.old_state = self.new_state # assign the old state value
        self.new_state = self.parent.state() # get the new state value

        if self.new_state == 'zoomed':
            print('maximize event')
        elif self.new_state == 'normal' and self.old_state == 'zoomed':
            print('restore event')
        else:
            print('dragged resize event')

root = Tk()
App(root).pack()
root.mainloop()

description: Tkinter maximize/restore/resize differentiation


code:
s = Sound()
s.read('sound.wav')
s.play()

rawDescription: Automatically play sound in IPython notebook


code:
lesser_length = min(len(A), len(B))
answer = lesser_length # If one of the lists is shorter and a sublist,
                       # this will be the answer, because the if condition
                       # will never be satisfied.
for i in xrange(lesser_length):
    if A[i] != B[i]:
        answer = i
        break

rawDescription: Index of first differing element without loop


code:
def get_values(request, value_a, value_b):
    person = MyModel.objects.get(field_a=value_a)
    domain = MyModel.objects.get(field_b=value_b)

rawDescription: Fetch values from database

description: Fetch values from database


code:
def retrieve_user(self, id=None, name=None, email=None):
    if id:
        return self.session.query(User).\
            filter(User.id == id).one()
    if name:
        return self.session.query(User).\
            filter(func.lower(User.username) == func.lower(name)).first()
etc

rawDescription: Cleaner, shorter code using conditionals (IF/ELIF/ELSE)


code:
from google.appengine.api import users

class Premium(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if not user:
      this.redirect(users.create_login_url(this.request.uri))
    # Your normal page code here

rawDescription: How to use Google Acounts API in App Engine?

description: Use Google Acounts API in App Engine


code:
for x in range(len(requests)):
    movement += abs(position - requests[x])
    position = requests[x]
    print("Servicing " + str(position))

rawDescription: why doest list[x] go to the next element in python every time?

description: Why doest list[x] go to the next element in python every time


code: [Ingredient(*ing) for ing in ings]

rawDescription: Populating a list with objects using list comprehension expression


code:
from tkinter import *
from tkinter import ttk

def send(view, entry):
    view.insert('1.0', entry.get() + "\n")

root = Tk()

msgview = Text(root, width=100, height=20)
msgview.grid(sticky=(N,E,S,W))

mymessage = StringVar(value="type here...")

msginput = Entry(root, textvariable=mymessage)
msginput.grid(sticky=(E,W))

sendbutton = ttk.Button(root, text="send",\
                        command=lambda: send(msgview, msginput))
sendbutton.grid()

root.mainloop()

rawDescription: Good-styled console input

description: Good-styled console input


code:
with open('example.txt') as f:
    result = {k:int(v) for k,v in re.findall('([^:\s]+):\s*(\d+)', f.read())}

result
'Grapes' in result
'Bananas' in result
result['Grapes']

rawDescription: python text file variable search

description: Python text file variable search


code:
source /opt/python/run/venv/bin/activate
source /opt/python/current/env

rawDescription: Elastic Beanstalk connect to RDS from shell SSH


rawDescription: Python: Checking whether a substring of one string is a substring of another string, conditional on the first substring being a particular length


code:
from django.db.models import Q

Post.objects.filter( \
    Q(userBy=some_user) | \
    Q(userBy__accept_user__user1=some_user) | \
    Q(userBy__request_user__user2=some_user)).distinct()

rawDescription: Complex query with Django (posts from all friends)


code:
line1 = file1.readline()
line2 = file2.readline()
while file1_not_at_end and file2_not_at_end:
    if line1 < line2:
        file3.write(line1)
        line1 = file1.readline()
    else:
        file3.write(line2)
        line2 = file2.readline()

 # merge file 1 into file 3
 # merge file 2 into file 3

rawDescription: Python - reading and deleting the top line of a file without loading it into memory


code:
from operator import itemgetter

def dfs(space, fragments, path=None, cost=0):
    if path == None:
        path = []
        path_end = space[0]
    else:
        path_end = path[-1][1]

    for i, fragment in enumerate(fragments):
        if fragment[0] > path_end: # this fragment would leave a gap (as
            break                  # will all the rest) so we can stop
        elif path_end < fragment[1]: # useless fragments are skipped
            new_path = path + [fragment]
            new_cost = cost + get_marginal_cost(fragment)
            if fragment[1] == space[1]:  # this fragment reaches the end,
                yield new_path, new_cost # so this is a base case
            else:     # recursive case
                for result in dfs(space, fragments[i+1:], # slice frag list
                                  new_path, new_cost):
                    yield result # in Python 3.3 and later, you can skip the
                                 # loop and just use "yield from dfs(...)"

def find_minimum_cost_path(space, fragments):
    fragments.sort(key=itemgetter(0)) # sort by start of the fragments
    path, cost = min(dfs(space, fragments), key=itemgetter(1))
    return path

rawDescription: Finding minimum by passing a variable to recursive function with yield


code:
writer = ExcelWriter('output.xlsx')
non_peatlands = df.loc['Non-Peatlands']
peat = df.loc['Peatlands']

peat.reset_index().to_excel(writer,'1',startrow=no_peatlands.shape[0])#not sure if you need to add +1 or -1 to start or not so header is overwritten play around with it
no_peatlands.reset_index().to_excel(writer,'1') #this comes second to overwrite the columns of peat frame
writer.save()

rawDescription: Stack/Unstack Multi-index pivot table in Python Pandas


code:
def after_return(self, status, retval, task_id, args, kwargs, einfo):
    #exit point for context managers
    self.taskLogger.__exit__(status, retval, task_id, args, kwargs, einfo)

rawDescription: Celery: access to time of last run of task?


code:
import smtplib
smtp_client = smtplib.SMTP('smtp.gmail.com', 587)
smtp_client.starttls()
smtp_client.login(username, password)

rawDescription: Automate SMTP Using Python

description: Automate SMTP Using Python


code:
def copyfileobj(src, dst, length=None):
    """Copy length bytes from fileobj src to fileobj dst.
       If length is None, copy the entire content.
    """
    if length == 0:
        return
    if length is None:
        shutil.copyfileobj(src, dst)
        return

    BUFSIZE = 16 * 1024
    blocks, remainder = divmod(length, BUFSIZE)
    for b in xrange(blocks):
        buf = src.read(BUFSIZE)
        if len(buf) < BUFSIZE:
            raise IOError("end of file reached")
        dst.write(buf)

    if remainder != 0:
        buf = src.read(remainder)
        if len(buf) < remainder:
            raise IOError("end of file reached")
        dst.write(buf)
    return

rawDescription: Does Python's `tarfile` module store the archives it's building in memory?


rawDescription: convert a string into an hexadecimal

description: Convert a string into an hexadecimal


code:
PermissionValidatorMap.objects.exclude(
    validator_set__in=ValidatorMetaData.objects.exclude(id__in=validator_list))

rawDescription: Unable to check if queryset is a subset

description: Unable to check if queryset is a subset


code:
import random
attempt = 1
closestmin = 0
closestmax = 100

print('Welcome to the game')
print('The game consists of guessing a secret integer, selected randomly in  the range of 1 to 100, in 10 or fewer attempts.')

x = random.randint(1, 100)

for guess in range(10):
    print("Attempt", attempt)
    n = int(input('Type your guess'))

    if n == x:
        attempt = str(attempt)
        print('Congratulations, you have guessed the number in' , attempt, 'attempts')
        break

    elif n < x:
        if n > closestmin:      #if guess is closer than previous closest lowest guess
            closestmin = n      #update closest lowest guess with new number
            print('x >', n)
        elif n < closestmin:
            print("We already know that x <", closestmin)

    elif n > x :
        if n < closestmax:      #if guess is closer than previous closest lowest guess
            closestmax = n      #update closest largest guess with new number
            print('x <', n)
        elif n > closestmax:
            print("We already know that x <", closestmax)

    attempt = attempt + 1
    if attempt > 10:
        print('Unfortunately you have not able to find out the number in 10 attempts. The number was' , x)
        break

rawDescription: How to keep accounts for the range of possible numbers on which it is reasonable to make an attempt to guess (Guessing The Number Game on Python)

description: Keep accounts for the range of possible numbers on which it is reasonable to make an attempt to guess (Guessing The Number Game on Python)


code: length = sum(len(s) for s in strings)

rawDescription: Python: Sum string lengths

description: Python: Sum string lengths


code:
filename = 'myimage.png'
imagea = (scipy.misc.imread(filename)).astype(float)

poissonNoise = numpy.random.poisson(50,imagea.shape).astype(float)

noisyImage = imagea + poissonNoise

rawDescription: Adding poisson noise to an image in Python


code:
'hello'[::] # here the value of stride is 1, means take a step of one between two indexes
'hello'[::2] #take a step of 2 so starting from h -->l --> o
'abcdef'[::-1] #negative step actually means 'abcdef'[-1:-len('abcdef')-1:-1]

rawDescription: Can someone explain what the third expression in python's indexing syntax represents?


code:
# Stuff

import subprocess

__version__ = '1.2.3'
__build__ = subprocess.check_output('git describe --tags --always HEAD'
                                    .split()).decode().strip()

with open('mypkg/_version.py', 'w') as f:
    f.write('''\
# I will destroy any changes you make to this file.
# Sincerely,
# setup.py ;)

__version__ = '{}'
__build__ = '{}'
'''.format(__version__, __build__))

# other stuff

settings.update(
    version=__version__,
# more stuff
)

rawDescription: How can I add a version/build information to my project and setup.py?

description: Add a version/build information to my project and setup.py


code:
setup(...,
      data_files=[('/sbin', ['rootfill']),
                  ('/etc/init.d', ['init-script'])]
     )

rawDescription: How to install scripts to sbin with python's distutils?

description: Install scripts to sbin with python's distutils


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
#  test_icon.py
#
#  Copyright 2015 John Coppens <john@jcoppens.com>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
#

import pygtk
import gtk

IMAGE_FILE = "/put/an/imagename here"

class MainWindow(gtk.Window):
    def __init__(self, debug = None):
        gtk.Window.__init__(self)
        self.connect("delete-event", self.on_delete_event)

        btn = gtk.Button()
        img = gtk.Image()
        img.set_from_file(IMAGE_FILE)
        btn.set_image(img)

        self.add(btn)
        self.show_all()

    def on_delete_event(self, win, data):
        gtk.main_quit()

    def run(self):
        gtk.mainloop()

def main():
    w = MainWindow()
    w.run()
    return 0

if __name__ == '__main__':
    main()

rawDescription: Clickable Icon in Python GTK

description: Clickable Icon in Python GTK


code:
import random

used_cards = set()

def choose_cards(n_cards):
    # No need to do 'global used_cards', used_cards is
    #    already global and can be modified inplace
    # Find the set difference between all the cards and
    #   those that have been used
    available = set(range(52)) - used_cards
    chosen = random.sample(available, n_cards)
    for card in chosen:
        used_cards.add(card)
    return chosen

for i in range(4):
    print(choose_cards(5))
    print(used_cards)

rawDescription: Make a list of random numbers in python without using numbers in another list


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
from matplotlib.cbook import get_sample_data

def main():
    x = np.linspace(0, 10, 20)
    y = np.cos(x)
    image_path = get_sample_data('ada.png')
    fig, ax = plt.subplots()
    imscatter(x, y, image_path, zoom=0.1, ax=ax)
    ax.plot(x, y)
    plt.show()

def imscatter(x, y, image, ax=None, zoom=1):
    if ax is None:
        ax = plt.gca()
    try:
        image = plt.imread(image)
    except TypeError:
        # Likely already an array...
        pass
    im = OffsetImage(image, zoom=zoom)
    x, y = np.atleast_1d(x, y)
    artists = []
    for x0, y0 in zip(x, y):
        ab = AnnotationBbox(im, (x0, y0), xycoords='data', frameon=False)
        artists.append(ax.add_artist(ab))
    ax.update_datalim(np.column_stack([x, y]))
    ax.autoscale()
    return artists

main()

rawDescription: Matplotlib: How to plot images instead of points?


code:
class UserChangeForm(forms.ModelForm):

    class Meta:
        fields = ('email', 'company_name', 'headquarters',
                           'first_name', 'last_name', )

    def __init__(self, *args, **kwargs):
        super(UserChangeForm, self).__init__(*args, **kwargs)
        if self.instance.is_company:
            fields_to_delete = ('first_name', 'last_name')
        else:
            fields_to_delete = ('company_name', 'headquarters')
        for field in fields_to_delete:
            del self.fields[field]

rawDescription: Conditional fields in a ModelForm.Meta

description: Conditional fields in a ModelForm.Meta


code:
import string
alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits + '+/'

rawDescription: Is there an easy way to represent the base64 alphabet in a Python list?


code:
import sys
print(sys.path[0])

rawDescription: How to know the path the script the python run?

description: Know the path the script the python run


rawDescription: Decoding an IEEE double precision float (8 byte)


code:
class OutputTestCase(unittest.TestCase):

    def get_output(self, input):
       ...  # You haven't mentioned how "input" is taken or how output is taken.

    def test_script(self):
       input = ...
       expected = ...

       output = self.get_output(input)
       self.assertEqual(output, expected)

rawDescription: python: testing the outputs ( ... not unit testing ?)

description: Python: testing the outputs ( ... not unit testing ?)


code:
for base in letters:
    dna += seqcom.get(base, 'x')

rawDescription: Replace individual character elements of string


code:
import time
time.time() * 1000

rawDescription: How can I create a Python timestamp with millisecond granularity?

description: Create a Python timestamp with millisecond granularity


code: a = [intern("foo".replace("o","1")) for a in range(0,1000000)]

rawDescription: How do I make Python make all identical strings use the same memory?

description: Make Python make all identical strings use the same memory


code:
from mock import patch

m = dict()

with patch.dict(m, {'categories': [1, 2, 3]}):
    print(m['categories'])

print(m)

rawDescription: Is it possible to use python mock for complex multidimensional dictionary input?


code:
class TestBase(unittest.TestCase):

    def check(self, input, expected_output):
        obj = self.class_under_test(input)
        actual_output = obj.get_result()
        self.assertEqual(actual_output, expected_output)

    def check_all(self):
        for value in self.values:
            self.check(value[0], value[1])

class TestMyClass1(TestBase):
    values = ((1, 2), (3, 4))
    class_under_test = MyClass1

    def test_it(self):
        self.check_all()

class TestMyClass2(TestBase):
    values = (('a', 'b'), ('d', 'e'))
    class_under_test = MyClass2

    def test_it(self):
        self.check_all()

rawDescription: Python unittest TestCase with inheritance


code:
for element in my_list:
    if element.aaa == 'query value':
        element.bbb = 'new value'
        break

rawDescription: Update an element in a list

description: Update an element in a list


code:
redirect_response = self.testapp.post(
    '/signup', params=post_params, status=302)
full_response = redirect_response.follow()

rawDescription: How to follow Pyramid redirect on tests?

description: Follow Pyramid redirect on tests


code:
with open('shafile.txt', 'r') as f:
    value = f.read().strip()

rawDescription: str argument only functioning when submitted via single quotes as opposed to assigned variable

description: Str argument only functioning when submitted via single quotes as opposed to assigned variable


rawDescription: Sort a list of lists containing integers


code:
def get_detail(self, slug):
    qr = v1_api.canonical_resource_for('question')
    try:
        question = qr.cached_obj_get(slug=slug)
    except Question.DoesNotExist:
        raise Http404

    bundle = qr.full_dehydrate(qr.build_bundle(obj=question))

    # create response
    desired_format = qr.determine_format(self.request)
    serialized = qr.serialize(self.request, bundle, desired_format)
    return serialized

rawDescription: Tastypie building data bundle from canonical_resource_for('object')


rawDescription: How to compare two time fields in python

description: Compare two time fields in python


code:
def partitionfunc(n,k,l=1):
    '''n is the integer to partition, k is the length of partitions, l is the min partition element size'''
    if k < 1:
        raise StopIteration
    if k == 1:
        if n >= l:
            yield (n,)
        raise StopIteration
    for i in range(l,n+1):
        for result in partitionfunc(n-i,k-1,i):
            yield (i,)+result

rawDescription: Python Integer Partitioning with given k partitions


rawDescription: Count Frequency of the nth item of each List within Larger List


rawDescription: Multiple substitutions of numbers in string using regex python


code:
import mock   # See http://www.voidspace.org.uk/python/mock/

MOCK_MODULES = ['module1', 'module2', ...]
for mod_name in MOCK_MODULES:
    sys.modules[mod_name] = mock.Mock()

rawDescription: How to make my package importable without initializing the GPU

description: Make my package importable without initializing the GPU


code:
from datetime import datetime,timedelta
current_date=datetime.now()
currQuarter = (current_date.month - 1) / 3 + 1
dtFirstDay = datetime(current_date.year, 3 * currQuarter - 2, 1)
dtLastDay = datetime(current_date.year, 3 * currQuarter + 1, 1) + timedelta(days=-1)

rawDescription: Get First Date and Last Date of Current Quarter in Python?


code:
pywinauto.controls.HwndWrapper.DragMouse(button='left', pressed='',
                                         press_coords=(0, 0),
                                         release_coords=(0, 0))

rawDescription: Problem with dragging mouse cursor with Python


code:
new_src = link.replace('foo', 'bar') # or element.get('src').replace('foo', 'bar')
element.set('src', new_src)

rawDescription: How to replace links using lxml and iterlinks

description: Replace links using lxml and iterlinks


code:
A = []
B = []
for item in L:
    if item['b'] == 0:
        target = A
    else:
        target = B
    target.append(item)

rawDescription: How to separate one list in two via list comprehension or otherwise

description: Separate one list in two via list comprehension or otherwise


code:
def test(axes):
    axes.bar(x,y)
    axes.set_xticks(x)
    axes.set_xticklabels([i+100 for i in x])

rawDescription: Why set_xticks doesn't set the lables of ticks?


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

import random

def slope(x, y):
    return (y[0] - y[1]) / (x[0] - x[1])

def get_color(condition):
    if condition < 0:
        if abs(condition) < 1:
            return 'red'
        else:
            return 'green'
    else:
        if abs(condition) < 1:
            return 'blue'
        else: return 'cyan'

XX = [(random.random(), random.random()) for _ in range(12)]
YY = [(random.random(), random.random()) for _ in range(12)]

plt.figure(1)
for x, y in zip(XX, YY):
    color = get_color(slope(x, y))

    plt.plot(x ,y, linewidth=3, color=color)
plt.show()

rawDescription: plot different lines in different colors based on a property they have

description: Plot different lines in different colors based on a property they have


code:
class Thing:
      def __getstate__(self):
            state = dict(self.__dict__)
            del state['cachedBar']
            return state

rawDescription: Can I mark variables as transient so they won't be pickled?

description: Mark variables as transient so they won't be pickled


code:
def shard_chooser(mapper, instance, clause=None):
    """return a shard key based on the instance being handled"""

def id_chooser(query, ident):
    """return a shard key based on primary key"""

def query_chooser(query):
    """return a shard key based on the query"""

create_session = sessionmaker(class_=ShardedSession)
create_session.configure(
    shards={
        # map keys to engines
    },
    shard_chooser=shard_chooser,
    id_chooser=id_chooser,
    query_chooser=query_chooser
)

rawDescription: SQLAlchemy transparent access to same table accross databases


code:
a = 'a b c zzz a yyy a 2 xxx 2 3 wwww a c'
re.sub(r'(?<=\b\w)\s+(?=\w\b)', '', a)

rawDescription: Collapse successive alphanumeric characters in a string


code:
cmds = {}
cmds['name1'] = func1

try:
     while True:
        str = self.dataQ.get_nowait()
        cmd_name, cmd_params = str.split(' ', 1)
        try:
            res = cmds[cmd_name](cmd_params)
        except:
            ## command not found
            pass
except queue.Empty:
    raise StopIteration

rawDescription: Parsing PySerial Data from queue and executing function on command match


code:
import pandas as pd
import seaborn as sns

df = pd.read_csv('LakeLevels.csv', delimiter=',', index_col='Year')
sns.heatmap(df)

rawDescription: Efficiently ploting a table in csv format using Python


code:
import numpy
from matplotlib import pyplot as plt

# graphic parameters
fig = plt.figure()
plt.ion()
plt.set_cmap('bwr')

# Some data
a = numpy.linspace(0, 1, 5)
b = numpy.linspace(0, 1, 5)
a_prime = numpy.linspace(0, 1, 6) #[0, .2, .4, .6, .8, 1]
b_prime = numpy.linspace(0, 1, 6)
A, B = numpy.meshgrid(a, b)

plt.pcolor(a_prime, b_prime, A-B, vmin=-1, vmax=1)
plt.colorbar(orientation='horizontal')

rawDescription: Plotting nxn Matrix visualized as (n-1)x(n-1) Matrix with pyplot.pcolor


code:
import threading
import time
import sys

mess = 'foo'

def other_stuff():
  while True:
    sys.stdout.write('mess == {}\n'.format(mess))
    time.sleep(1)

t = threading.Thread(target=other_stuff)
t.daemon=True
t.start()

while True:
  mess = raw_input('Type: ')

rawDescription: How to do other stuff while user deciding if write anything in raw_input?

description: Do other stuff while user deciding if write anything in raw_input


code:
if fileformat == 'raw':
    zip_file = open('C:\temp\core\files\CDX_COMPOSITES_20140626.zip', 'rb')
    response = HttpResponse(FileWrapper(zip_file), content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename="%s"' % 'CDX_COMPOSITES_20140626.zip'
    return response

rawDescription: django rest framework return file

description: Django rest framework return file


code:
def prepend_urls(self):
    return [

        url(r"^(?P<resource_name>%s)/(?P<pk>\w[\w/,-]*)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
    ]

rawDescription: deserialize a URl in Django-Tastypie

description: Deserialize a URl in Django-Tastypie


code:
pd.concat([df,
           df.groupby('Country', as_index=False).sum(),
           df.groupby('Group', as_index=False).sum()],
          ignore_index=True).sort(columns='Revenue',
                                  ascending=False).fillna('')

rawDescription: Rank all possible groupby combinations

description: Rank all possible groupby combinations


code:
@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()  # Auto-populates from request data.
    name = None
    age = None
    if form.validate_on_submit():
        name = form.name.data
        age  = form.age.data

        # Lets now create a form, but ignore the request data, so it's empty:
        form = NameForm(formdata=None)
    return render_template('index.html', form = form, name = name, age = age)

rawDescription: How to empty a numeric value from a form built with WTForm

description: Empty a numeric value from a form built with WTForm


code:
import cv2

def rotate(img1):  # rotate img1 and save it in img
    angle = 30  # rotated angle
    h, w, c = img1.shape

    m = cv2.getRotationMatrix2D((w/2, h/2), angle, 1)
    img2 = cv2.warpAffine(img1, m, (w, h))  # rotate the img1 to img2
    cv2.imwrite("rotate1.jpg", img2)  # save the rotated image within the function, successfully!
    return img2

img = cv2.imread("image.jpg")

img_out=rotate(img)

cv2.imwrite("rotate2.jpg", img_out)  # save the rotated image in the main function, failed!

print("Finished!")

rawDescription: Rotate the image via opencv in my defined function with Python


rawDescription: How do I format an MD5 hash with dashes between pairs of digits in python?

description: Format an MD5 hash with dashes between pairs of digits in python


code:
from gi.repository import Gtk

objectsList = Gtk.TreeStore(str, bool)

for i in range(2):
    parent = objectsList.append(None, ['Parent {}'.format(i), False])
    for j in range(2):
        objectsList.append(parent, ['Child {}'.format(j), True])

gcombo = Gtk.ComboBox.new_with_model(objectsList)
renderer_text = Gtk.CellRendererText()
gcombo.pack_start(renderer_text, True)
gcombo.add_attribute(renderer_text, "text", 0)
gcombo.add_attribute(renderer_text, 'sensitive', 1)
gcombo.show()

win = Gtk.Window()
win.add(gcombo)
win.show_all()
win.connect('destroy', Gtk.main_quit)

Gtk.main()

rawDescription: GTK3 ComboBox shows parent items from a TreeStore


code:
def isfloat(x):
    try:
        a = float(x)
    except ValueError:
        return False
    else:
        return True

def isint(x):
    try:
        a = float(x)
        b = int(a)
    except ValueError:
        return False
    else:
        return a == b

rawDescription: Python, Determine if a string should be converted into Int or Float


code:
class Book:
    def __init__(self):
        self.page_id = []
        self.page = []

    def __getitem__(self, ref):
        try:
            return self.page[ref]   # assume it's an int
        except TypeError:
            return self.page[self.page_id.index(ref)] # assume it's a string if not an int

rawDescription: overloading __getitem__ to support different access arguments

description: Overloading __getitem__ to support different access arguments


code:
import csv
import random

with open("random.csv",'a') as newFile:
    newWriter = csv.writer(newFile, dialect='excel')
    case_number = str(random.randint(0,1000000000))
    print("Your problem has been stored. We have allocated a case number which  will be sent off to a technician. Please take a note of your case number: ",  case_number)
    newWriter.writerow([case_number])
    newFile.close()

rawDescription: How to write new rows in a CSV using Python

description: Write new rows in a CSV using Python


rawDescription: How to modify pixel values in numpy array of HSV image data?

description: Modify pixel values in numpy array of HSV image data


code:
test3 = pd.concat([test1, test2], axis=1)
test3.columns = ['a','b']

rawDescription: pandas equivalent of R's cbind (concatenate/stack vectors vertically)

description: Pandas equivalent of R's cbind (concatenate/stack vectors vertically)


code:
class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

rawDescription: Automatic creation date for django model form objects?


rawDescription: selecting last of day in a pandas index

description: Selecting last of day in a pandas index


code:
fout=open("out.csv","a")
# first file:
for line in open("sh1.csv"):
    fout.write(line)
# now the rest:
for num in range(2,201):
    f = open("sh"+str(num)+".csv")
    f.next() # skip the header
    for line in f:
         fout.write(line)
    f.close() # not really needed
fout.close()

rawDescription: how to merge 200 csv files in Python

description: Merge 200 csv files in Python


code: df[df['tags'].map(lambda tags: 'Food' in tags)]

rawDescription: Filter pandas DataFrame by membership in set-of-tags


code:
point_data = mesh.mlab_source.dataset.point_data
point_data.scalars = t
point_data.scalars.name = 'Point data'
point_data.update()

mesh2 = mlab.pipeline.set_active_attribute(mesh,
        point_scalars='Point data')

rawDescription: Mayavi: interpolate face colors in triangular_mesh


code:
x = ()
not x
x = []
not x
x = ''
not x
x = 0
not x
x is None

rawDescription: Is there a difference between "if not x" and "if x is None"?


code:
from M2Crypto import RSA, X509
data = ssl_sock.getpeercert(1)
# load the certificate into M2Crypto to manipulate it
cert = X509.load_cert_string(data, X509.FORMAT_DER)
pub_key = cert.get_pubkey()
rsa_key = pub_key.get_rsa()
cipher = rsa_key.public_encrypt('plaintext', RSA.pkcs1_padding)

rawDescription: extracting public key from certificate and encrypting data

description: Extracting public key from certificate and encrypting data


code:
from flask.ext.testing import TestCase

class MyViewTestCase(TestCase):
    def create_app(self):
        # This method is required by flask.ext.testing.TestCase. It is called
        # before setUp().
        return create_app()

    def test_get_success(self):
        response = self.client.get('/pgt/myview')
        self.assertEqual(self.get_context_variable('var1'), 'value 1')

rawDescription: How to test template context variables with Flask

description: Test template context variables with Flask


code: myvar = mydict.get('m', 'Melon')

rawDescription: Shortest Way to Assign "A or B" to a Variable in Python?


code:
class SomewhatObjectifiedElement(etree.ElementBase):
    nsmap = {'ns': 'http://www.my.org/namespace'}

    def __getattr__(self, name):
        return self.find('ns:' + name, self.nsmap)

rawDescription: Is it possible to add arbitrary data to an ObjectifiedElement instance?


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

def func(xi, ti):
    res = np.cos(ti)*np.sin(xi)
    return res

timeSpacing = 20
timeStart = 0
timeEnd = 1
time = np.linspace(timeStart, timeEnd, timeSpacing)

widthSpacing = 50
widthStart = 0
widthEnd = 3
width = np.linspace(widthStart, widthEnd, widthSpacing)

X,T = np.meshgrid(width,time)
F = func(X,T)

DF = np.diff(np.diff(F,axis=0),axis=1)

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

ax.plot_wireframe(X[:-1,:-1],T[:-1,:-1],DF)

plt.show()

rawDescription: How to index List/ numpy array in order to plot the data with matplotlib

description: Index List/ numpy array in order to plot the data with matplotlib


code: my_data[my_data == 0.0] = numpy.nan

rawDescription: Setting points with no data to white with Matplotlib imshow


code:
import datetime
print (datetime.date.today() + datetime.timedelta(6*365/12)).isoformat()

rawDescription: How do I calculate the date six months from the current date using the datetime Python module?

description: Calculate the date six months from the current date using the datetime Python module


code:
import re
strs='clock[5,4,1,0]'
nums = re.findall("\d+",strs)        #find all the numbers in string
word = re.search("\w+",strs).group() #find the word in the string
[ "{0}[{1}]".format(word,x) for x in nums]

rawDescription: Convert one string to a list of strings based on certain numbers inside the string


code:
import re
text = "Oh, in that case. I'm sorry. I'm sure everyone's day will come, it's just a matter of time."
re.findall(r"(?i)(?:i'm|i am).*?[.?!]", text)

rawDescription: Locate and extract a piece of string that contains a keyword from text in python


code:
last_three = []
for j in range(1, its + 2):
    ...
    k2 = cost(candidate1, candidate2)
    if k2 in last_three:
        continue
    elif k2 < k1:
        ...
    last_three[(j%3)-1] = k2

rawDescription: How to create a list within a loop that only stores the previous n values of the loop

description: Create a list within a loop that only stores the previous n values of the loop


code: AI = {"Hello" : "Hi", "Goodbye" : "Bye"}

rawDescription: Access value from string in list in Python?


code:
for fieldname in allowed_fields:
    setattr(obj, fieldname, getattr(individual, fieldname))

rawDescription: djangoproject access fields of object dynamically

description: Djangoproject access fields of object dynamically


code:
def f(s):
    for x in range(len(s)):
        if s[x] == 'o':
            s = s[:x]+'e'+s[x+1:]
    return s

rawDescription: Python 3.4 help - using slicing to replace characters in a string


code:
import multiprocessing as mp

def foo(q):
    q.put('hello')

if __name__ == '__main__':
    mp.set_start_method('spawn')
    q = mp.Queue()
    p = mp.Process(target=foo, args=(q,))
    p.start()
    print(q.get())
    p.join()

rawDescription: Multiprocessing HTTP get requests in Python


code:
from django.contrib.admin.templatetags.log import *  # noqa

def __AdminLogNode_render(self, context):
    if self.user is None:
        entries = LogEntry.objects.all()
    else:
        user_id = self.user
        if not user_id.isdigit():
            user_id = context[self.user].pk
        entries = LogEntry.objects.filter(user__pk=user_id)
    entries = entries.exclude(content_type=4, action_flag=1)
    context[self.varname] = entries.select_related('content_type', 'user')[:int(self.limit)]
    return ''
__AdminLogNode_render.__name__ = 'render'

AdminLogNode.render = __AdminLogNode_render

rawDescription: Override django admin activity log

description: Override django admin activity log


code:
def annihilateUnicorns(*unicorns):
    for i in unicorns: # stored in a list
        i.splode()
    return "404 Unicorns not found. They sploded."

rawDescription: Python equivalent of ActionScript 3's restParam


code:
import re

set_number = re.compile(r'Data set number (\d+)'),
patterns = {
    'line_count': re.compile(r'Number of lines (\d+)'),
    'max_num': re.compile(r'Max number of column 3 is (\d+)'),
}

with open(filename, 'r') as infh:
    results = {}
    set_numbers = []

    for line in infh:
        if not line.startswith('#'):
            # skip lines without a comment
            continue

        set_match = set_number.match(line)
        if set_match:
            set_numbers.append(int(set_match.group(1)))
        else:
            for name, pattern in patterns.items():
                match = pattern.search(line)
                if match:
                    results[name] = int(match.group(1))

rawDescription: python csv module read data from header

description: Python csv module read data from header


rawDescription: GtkSourceView Scroll to Line with Gobject Introspection [python]


code:
from Tkinter import *
import sys,time

class App():
    def __init__(self, parent):
        parent.title("Title")
        parent.geometry("500x500")
        self.labels = []
        self.parent = parent
        x,y = 50,50
        for index in range(3):
            label = Label(parent, text='0')
            label.place(x = x, y = y)
            self.labels.append(label)
            y += 50
        self.parent.after(1000, self.Task)

    def Task(self):
        t = time.strftime("%H:%M:%S", time.localtime())
        print(t)
        index = 0
        for c in t.split(':'):
            b = format(int(c), '04b')
            self.labels[index].configure(text=b)
            index += 1
        self.parent.after(1000, self.Task)

def main():
    root = Tk()
    app = App(root)
    root.mainloop()

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

rawDescription: Tkinter gui stops processing (Binary clock)


code:
import base64
import hashlib

def lineToFingerprint(line):
    key = base64.b64decode(line.strip().split()[1].encode('ascii'))
    fp_plain = hashlib.md5(key).hexdigest()
    return ':'.join(a+b for a,b in zip(fp_plain[::2], fp_plain[1::2]))

rawDescription: Deriving an SSH Fingerprint from a Public Key in Python


code:
# This is a trivial modification of the example here:
# http://matplotlib.sourceforge.net/examples/pylab_examples/pie_demo.html

from pylab import *

data = {(87, 82, 44): 1, (255, 245, 241): 11, (24, 13, 9): 4}

colors = []
counts = []

for color, count in data.items():
    colors.append([float(x)/255 for x in color])
    counts.append(count)

figure(1, figsize=(6,6))

pie(counts, colors=colors, autopct='%1.1f%%', shadow=True)
title('Example Pie Chart', bbox={'facecolor':'0.8', 'pad':5})

show()

rawDescription: how to plot a pie of color list

description: Plot a pie of color list


rawDescription: Creating all lists of length "n" from a list of q elements


code:
import pathlib

pathlib.Path(absolute_path_string).as_uri()

rawDescription: Convert a filename to a file:// URL

description: Convert a filename to a file:// URL


code:
import pandas as pd
s = pd.Series([1, 2, 3, np.NaN, np.NaN, 5, 6])
s.isnull()
s[s.isnull()]
s.index[s.isnull()]

rawDescription: Missing value check in pandas series

description: Missing value check in pandas series


code:
import numpy, Image

for n in xrange(10):
    a = numpy.random.rand(30,30,3) * 255
    im_out = Image.fromarray(a.astype('uint8')).convert('RGBA')
    im_out.save('out%000d.jpg' % n)

rawDescription: Create set of random JPGs

description: Create set of random JPGs


code:
for _ in range(10000):
    theDeck = MakeDeck()
    playgame(theDeck)

rawDescription: How do I repeat a function but get it to return different values on each repetition? (Python)

description: Repeat a function but get it to return different values on each repetition? (Python)


code:
from IPython import start_ipython
start_ipython()

rawDescription: starting IPython using Python code

description: Starting IPython using Python code


code: Point = namedtuple('Point', "x y", verbose=True)

rawDescription: How named tuples are implemented internally in python?


code:
from multiprocessing import Pool

def do_experiment(exp):
    # run the experiment `exp`, will be called by `p.map`
    return result

p = Pool() # automatically scales to the number of CPUs available

results = p.map(do_experiment, experiment_collection)
p.close()
p.join()

rawDescription: Python Multiprocessing - 'Queue' object has no attribute 'task_done' / 'join'


code: re.sub(r'^\s+|\s+$', '', ' hello world ')

rawDescription: Remove String spaces with regular expression


code:
from tkinter import *

class zoomer(Tk):

    def __init__(self):
        x=100
        y=100
        Tk.__init__(self)
        self.border = 10
        self.size_x = x
        self.size_y = y

        #SIZE
        self.app_sizex = 200
        self.app_sizey = 200
        fontSize=int(x/20)

        self.title("Graphic")
        self.geometry(str(self.app_sizex+10) + "x" + str(self.app_sizey+40))

        #CANVAS + BORDER
        self.canvas = Canvas(self, width = self.app_sizex, height = self.app_sizey, scrollregion=(0,0,x,y))
        self.canvas.grid(row=0, column=0, sticky="nsew")
        self.canvas.create_line(self.border, self.border, self.border, y-self.border)
        self.canvas.create_line(x-self.border, self.border, x-self.border, y-self.border)
        self.canvas.create_line(self.border,   self.border, x-self.border, self.border)
        self.canvas.create_line(self.border, y-self.border, x-self.border, y-self.border)
        self.canvas.create_line(self.border,   self.border, x-self.border, y-self.border)
        text1=self.canvas.create_text(50, 50, fill="white",font=("Purisa", fontSize))
        self.canvas.itemconfig(text1, text="Graphic Text")

        #SCROLLING BARS
        self.vbar=Scrollbar(self,orient=VERTICAL)
        self.vbar.grid(row=0, column=1, sticky="ns")
        self.vbar.config(command=self.canvas.yview)
        self.hbar=Scrollbar(self,orient=HORIZONTAL)
        self.hbar.grid(row=2, column=0, sticky="ew")
        self.hbar.config(command=self.canvas.xview)
        self.canvas.config(xscrollcommand=self.hbar.set, yscrollcommand=self.vbar.set)

        #zoom button
        save_button = Button(self, text = "Zoom")
        save_button["command"] = lambda: self.zoom_in()
        save_button.grid(row=3, column = 0, pady = 5)

    def zoom_in(self):
        #Clean canvas
        self.canvas.delete("all")
        self.size_x = int(self.size_x * 1.1)
        self.size_y = int(self.size_y * 1.1)
        x=self.size_x
        y=self.size_y
        fontSize=int(x/20)
        self.canvas.create_line(self.border, self.border, self.border, y-self.border)
        self.canvas.create_line(x-self.border, self.border, x-self.border, y-self.border)
        self.canvas.create_line(self.border, self.border, x-self.border, self.border)
        self.canvas.create_line(self.border, y-self.border, x-self.border, y-self.border)
        self.canvas.create_line(self.border,   self.border, x-self.border, y-self.border)
        text1=self.canvas.create_text(self.size_x/2, self.size_y/2, fill="white",font=("Purisa", fontSize) )
        self.canvas.itemconfig(text1, text="Graphic Text")
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

        #SCROLLING BARS
        self.vbar.config(command=self.canvas.yview)
        self.hbar.config(command=self.canvas.xview)
        self.canvas.config(xscrollcommand=self.hbar.set, yscrollcommand=self.vbar.set)

if __name__ == '__main__':
    my_gui=zoomer()
    my_gui.mainloop()

rawDescription: Tkinter on canvas resize scroll bar does not adjust


code:
import os

def getfile_insensitive(path):
    directory, filename = os.path.split(path)
    directory, filename = (directory or '.'), filename.lower()
    for f in os.listdir(directory):
        newpath = os.path.join(directory, f)
        if os.path.isfile(newpath) and f.lower() == filename:
            return newpath

def isfile_insensitive(path):
    return getfile_insensitive(path) is not None

rawDescription: Can you force os.path.isfile() to use case insensitivity when checking a file on a case-sensitive file system?

description: Force os.path.isfile() to use case insensitivity when checking a file on a case-sensitive file system


code:
import json
json.loads('[{"foo": 42, "bar": "conversion"}]')
# [{u'bar': u'conversion', u'foo': 42}]

rawDescription: Converting a String to a List of Dictionaries


code:
import matplotlib.pyplot as plt
import numpy as np
f, axes = plt.subplots(1,2)  # 1 row containing 2 subplots.

# Plot random points on one subplots.
axes[0].scatter(np.random.randn(10), np.random.randn(10))

# Plot histogram on the other one.
axes[1].hist(np.random.randn(100))

# Adjust the size and layout through the Figure-object.
f.set_size_inches(10, 5)
f.tight_layout()

rawDescription: return values of subplot

description: Return values of subplot


code:
def num_of_times(n):
    if n > 0 and n <= 50:
        return 1
    elif n > 50:
        return 1+num_of_times(n - 50)
    else:
        return 0

rawDescription: Using recursion in Python

description: Using recursion in Python


code:
from pylab import *

x = linspace(0.1, 2*pi, 10)
markerline, stemlines, baseline = stem(x, cos(x), '-.', bottom=.5)
setp(markerline, 'markerfacecolor', 'b')
setp(baseline, 'color','r', 'linewidth', 2)

show()

rawDescription: matplotlib: stem plot with horizontal offset

description: Matplotlib: stem plot with horizontal offset


code:
p = figure(tools = "box_select, tap", width = 400, height = 400,
           x_range = (0,100), y_range = (0,100))

circles1 = p.circle(x1, y1, size=10, color="red", line_color=None)
circles1.selection_glyph    = Circle(fill_color="blue", line_color=None)
circles1.nonselection_glyph = Circle(fill_color="red",  line_color=None)

circles2 = p.circle(x2, y2, size=10, color="blue", line_color=None)
circles2.selection_glyph    = Circle(fill_color="blue", line_color=None)
circles2.nonselection_glyph = Circle(fill_color="red",  line_color=None)

rawDescription: Is there a way to have multiple colours for selection glyphs in Bokeh?


code:
from pprint import pprint # to pretty print the cursor result.
import pandas as pd
import pymongo
client = pymongo.MongoClient()
db = client.test
collection = db.collection
memberID = ['856589080', '906903383', '837210554', '935634391', '929185103']
dxCodes = [[4280, 4293, 4241, 4240, 4242, 4243], [7612], [4550, 4553, 1582],[78791, 28860, 1582, 496, 25000, 4019], [30500, 42731, 4280, 496, 59972, 4019, 3051]]
dxCount = [6, 1, 3, 6, 7]
score = [1.8, 2.6, 3.1, 1.1, 2.8]
df = pd.DataFrame({'memberID': memberID, 'dxCodes': dxCodes, 'score': score})
df
collection.insert_many(df.to_dict('records')) # you need to pass the 'records' as argument in order to get a list of dict.
pprint(list(collection.find()))

rawDescription: insert rows from Pandas dataframe into mongodb collection as individual documents using Python

description: Insert rows from Pandas dataframe into mongodb collection as individual documents using Python


code:
import fileinput

def process(line):
    return 'Replaced line with static text'

with fileinput.input(files=('task3.txt'), inplace=True) as f:
    for line in f:
        print(process(line))

rawDescription: replacing the values of a list in python

description: Replacing the values of a list in python


code:
import csv
candy_reader = csv.reader(open('candy.csv', 'rb'))

for row in candy_reader:
  if row[0] in candy_to_find:
    monday_total += row[1]
    # etc.

rawDescription: using an excel table format in python

description: Using an excel table format in python


code:
x = [1, 2, 3, 4, 5]
all(item >= 0 for item in x) or all(item < 0 for item in x)

rawDescription: Check if all numbers in a list are same sign in Python?


code:
import matplotlib.dates as mdates
month_day_fmt = mdates.DateFormatter('%b %d') # "Locale's abbreviated month name. + day of the month"
ax.xaxis.set_major_formatter(month_day_fmt)

rawDescription: Compare multiple year data on a single plot python


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

def doPlot():

    x = [ 1.83259571, 1.76278254, 1.38753676, 1.6406095, 1.34390352, 1.23045712, 1.85877565, 1.26536371, 0.97738438]

    y = [ 0.04363323, 0.05235988, 0.09599311, 0.10471976, 0.1134464, 0.13962634, 0.17453293, 0.20943951, 0.23561945]

    gridx = np.linspace(min(x),max(x),11)
    gridy = np.linspace(min(y),max(y),11)

    H, xedges, yedges = np.histogram2d(x, y, bins=[gridx, gridy])

    plt.figure()
    plt.plot(x, y, 'ro')
    plt.grid(True)

    #wrong origin convention for pcolormesh?
    #plt.figure()
    #plt.pcolormesh(gridx, gridy, H)
    #plt.plot(x, y, 'ro')
    #plt.colorbar()

    plt.figure()
    myextent  =[xedges[0],xedges[-1],yedges[0],yedges[-1]]
    plt.imshow(H.T,origin='low',extent=myextent,interpolation='nearest',aspect='auto')
    plt.plot(x,y,'ro')
    plt.colorbar()

    plt.show()

if __name__=="__main__":
    doPlot()

rawDescription: Having trouble plotting 2-D histogram with numpy.histogram2d and matplotlib


code:
result = set() # {} literal syntax works in 2.x
while len(result) < 1000:
  result.add(''.join(random.choice(chars) for i in range(length)))

rawDescription: generate unique passwords with python

description: Generate unique passwords with python


rawDescription: pandas: count things

description: Pandas: count things


code:
ids = b_associate.split(',')
for id in ids:
    b_obj = B.objects.get(id=id)
    A.b_associate.add(b_obj)

rawDescription: Associate model instance to ManyToManyField in Django


code:
from functools import wraps, WRAPPER_ASSIGNMENTS

def decorator2(fn):
    @wraps(fn, assigned=WRAPPER_ASSIGNMENTS + ('__dict__',), updated=())
    def fn_wrapper(*args, **kwargs):
        if my_condition(fn):
            fn(*args, **kwargs)
    return fn_wrapper

rawDescription: Wrapping a function hides its attributes?


code:
{'primary_key': 0,
 'nullable': False,
 'default': None,
 'autoincrement': False,
 'type': VARCHAR(),
 'name': u'third_column'}

rawDescription: How to override reflected column only if it exists using SQLAlchemy?

description: Override reflected column only if it exists using SQLAlchemy