code:
msg = ['Check-in  Mr. Benny Jones  Room  403 at 2014-11-02 05 20 (recorded)',
   'Check-out Mr. Ken Beis  Room  302 at 2014-11-03 05 20 (recorded)']
for each_guest in msg:
      m = re.match("([-_a-zA-Z]+)\s+(.*?)\s+Room\s+(\d+)\s+at\s+(\d+-\d+-\d+)\s+(\d+)\s+(\d+)\s+\(recorded\)", each_guest)
      action, name, number, date, time0, time1 = (m.group(i) for i in range(1, 7))
      print(action, name, number, date, time0, time1)

rawDescription: Restructuring a string

description: Restructuring a string


code:
class MountainLionNotification(Foundation.NSObject, Notification):

    def notify(self, title, subtitle, text, url):
        NSUserNotification = objc.lookUpClass('NSUserNotification')
        NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
        notification = NSUserNotification.alloc().init()
        notification.setTitle_(str(title))
        notification.setSubtitle_(str(subtitle))
        notification.setInformativeText_(str(text))
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
        notification.setHasActionButton_(True)
        notification.setOtherButtonTitle_("View")
        notification.setUserInfo_({"action":"open_url", "value":url})
        NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self)
        NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)

    def userNotificationCenter_didActivateNotification_(self, center, notification):
        userInfo = notification.userInfo()
        if userInfo["action"] == "open_url":
            import subprocess
            subprocess.Popen(['open', userInfo["value"]])

rawDescription: Working with Mountain Lion's Notification Center using PyObjC


code:
x = ["Albert Einstein", "test 1 s 2", "Einstein Albert", "foo bar baz", "baz foo bar"]
list(set(' '.join(sorted(s.split())) for s in x))

rawDescription: Absolute String matching in python

description: Absolute String matching in python


code:
def associated_with(func, seq):
    for item in seq:
        yield item, (other for other in seq if func(item, other))

rawDescription: does python have a partition_by function?

description: Does python have a partition_by function


code:
CONFIG = {
    # Default mode is WSGI
    'working_dir': '/path/to/my/django/project/',
    'python': '/path/to/virtualenv/bin/python',
    'user': 'user',
    'group': 'group',
    'args': (
        '--bind=127.0.0.1:8090',
        '--workers=3',
        # '--worker-class=egg:gunicorn#sync',
        #'--timeout=30',
        #'--preload',
        'myproject.wsgi'
    ),
}

rawDescription: Debian 7 + django + gunicorn + virtualenv : site-packages egg-link not in pythonpath


code:
lists=[[3,2,1,4],["three","two","one","four"],["tres","dos","uno","cuatro"]]
[[x for i, x in sorted(zip(lists[0], sublist))] for sublist in lists]

rawDescription: Python sort lists with lists inside

description: Python sort lists with lists inside


code:
from flask import Flask, request
app = Flask(__name__)

@app.route("/script_name")
def script_name():
    #Taking the arguments.
    arg1 = device_id = ast.literal_eval(request.data)['arg1']
    #Complete the logic here.

if __name__ == "__main__":
    app.run()

rawDescription: Best way to create simple web server for python files

description: Create simple web server for python files


code:
import re

text = "This is my post with #hashtags #sport #music"
hashtags = re.findall('#[\w]*', text)

if hashtags:
    a_href = '{}'
    for tag in hashtags:
        text = text.replace(tag, a_href.format(tag[1:], tag))

rawDescription: Add tag<a> to message from textarea in python flask


code:
name_key_dict = dict()
for i in range(ncols):
    name_key_dict[colnames[i]] = i # Assuming that names is the ordered list of columns
# I would add a check here that you have the required columns

param_col_list = [ # This constructs a list of parameters vs column numbers
    ('BU', name_key_dict.get('Bu_Col')),
    ('City_Param', name_key_dict.get('City')),
    ('CountryID_Param', name_key_dict.get('Country Code')),
]
for row in job_rowset: # Assuming job_rowset is an iterable with a member of getValue
    for (param, col) in param_col_list:
        diagram.setParameterValue(param, row.getValue(col))

rawDescription: Get value at column using SPSS Python Script


code:
from PyQt4 import QtGui, QtCore
import sys, random

def clear(listwidget):
    for i in range(listwidget.count()):
        item = listwidget.item(i)
        listwidget.setItemSelected(item, False)

app = QtGui.QApplication([])
top = QtGui.QWidget()

# list widget
myListWidget = QtGui.QListWidget(top)
myListWidget.setSelectionMode(2)
myListWidget.resize(200,300)
for i in range(10):
    item = QtGui.QListWidgetItem("item %i" % i, myListWidget)
    myListWidget.addItem(item)
    if random.random() > 0.5:
        # randomly select half of the items in the list
        item.setSelected(True)

# clear button
myButton = QtGui.QPushButton("Clear", top)
myButton.resize(60,30)
myButton.move(70,300)
myButton.clicked.connect(lambda: clear(myListWidget))
top.show()

sys.exit(app.exec_())

rawDescription: Clearing selection in QListWidget

description: Clearing selection in QListWidget


code:
import wx
from wx.lib import sized_controls

class MultiMessageFrame(sized_controls.SizedFrame):

    def __init__(self, *args, **kwargs):
        super(MultiMessageFrame, self).__init__(*args, **kwargs)
        pane = self.GetContentsPane()
        text_ctrl = wx.TextCtrl(
            pane, style=wx.TE_READONLY | wx.TE_CENTRE | wx.TE_MULTILINE)
        text_ctrl.SetSizerProps(proportion=1, expand=True)
        text_ctrl.SetBackgroundColour('White')
        self.text_ctrl = text_ctrl

        pane_btns = sized_controls.SizedPanel(pane)
        pane_btns.SetSizerType('horizontal')
        pane_btns.SetSizerProps(align='center')

        button_ok = wx.Button(pane_btns, wx.ID_OK)
        button_ok.Bind(wx.EVT_BUTTON, self.on_button_ok)

    def append_msg(self, title_text, msg_text):
        self.SetTitle(title_text)
        self.text_ctrl.AppendText(msg_text)

    def on_button_ok(self, event):
        self.Close()

class MainFrame(sized_controls.SizedFrame):

    def __init__(self, *args, **kwargs):
        super(MainFrame, self).__init__(*args, **kwargs)
        self.SetInitialSize((800, 600))
        self.CreateStatusBar()
        menubar = wx.MenuBar()
        self.SetMenuBar(menubar)
        menu_file = wx.Menu()
        menu_file.Append(
            wx.ID_NEW, 'Show msg', 'Add a new message to message frame')
        menubar.Append(menu_file, '&File')
        self.Bind(wx.EVT_MENU, self.on_new, id=wx.ID_NEW)

        self.count = 1
        self.multi_message_frame = None

    def on_new(self, event):
        title_text = 'MultiMessageFrame already exists'

        if not self.multi_message_frame:
            title_text = 'Newly created MultiMessageFrame'
            self.multi_message_frame = MultiMessageFrame(
                self, style=wx.DEFAULT_FRAME_STYLE | wx.FRAME_FLOAT_ON_PARENT)
            self.multi_message_frame.Bind(
                wx.EVT_CLOSE, self.on_multi_message_frame_close)
            self.multi_message_frame.Center()
            self.multi_message_frame.Show()

        self.multi_message_frame.append_msg(
            title_text, 'message no.{}\n'.format(self.count))
        self.count += 1

    def on_multi_message_frame_close(self, event):
        self.multi_message_frame = None
        event.Skip()

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

rawDescription: prevent the sub windows to open multiple times

description: Prevent the sub windows to open multiple times


code:
import os

def get_next_filename(output_dir):
    '''Gets the next numeric filename in a sequence.

    All files in the output directory must have the same name format,
    e.g. "txt1.txt".
    '''

    n = 0
    for f in os.listdir(output_dir):
        n = max(n, int(get_num_part(os.path.splitext(f)[0])))
    return 'txt%s.txt' % (n + 1)

def get_num_part(s):
    '''Get the numeric part of a string of the form "abc123".

    Quick and dirty implementation without using regex.'''

    for i in xrange(len(s)):
        if s[i:].isdigit():
            return s[i:]
    return ''

rawDescription: Save variable value in python

description: Save variable value in python


code:
class Test(object):
    def calculate_attr(self, attr):
        return something

    def __getattr__(self, name):
        return self.calculate_attr(name)

rawDescription: Should I use a metaclass, class decorator, or override the __new__ method?


code:
n_data = (data - data.mean(axis=0)) / data.std(axis=0)
evals, evecs = np.linalg.eig(np.cov(n_data.T))
evecs = evecs[:, np.argsort(evals)[::-1]].T
mlab.PCA(data).Wt
evecs

rawDescription: Python: Why are eigenvectors not the same as first PCA weights?


code:
si = sunburnt.SolrInterface("url","schema.xml")
query = si.query(arg1).facet(arg2)

if sort_flag:
  query = query.sort(arg3)
if exclude_flag:
  query = query.exclude(arg4)

response = query.execute()

rawDescription: Alternative way to use getattr in python?


code:
def f(a: str) -> Optional[str]:
    ...

rawDescription: Option type annotation/hinting for Python


code:
for word in search_terms:
   content = content.replace(word, '<strong>'+word+'</strong>')

rawDescription: style matching words in paragraphs python

description: Style matching words in paragraphs python


code:
"hello %(name)s , how are you %(name)s, welcome %(name)s" % {"name": "john"}
'hello john, how are you john, welcome john'

rawDescription: What is the most pythonic way to avoid specifying the same value in a string


code:
from gi.repository import Gtk

class window:
    def __init__(self):
        win = Gtk.Window()
        win.connect("delete_event", Gtk.main_quit)
        win.set_default_size(300,100)
        scroll = Gtk.ScrolledWindow(None, None)
        view = Gtk.Viewport(None, None)
        label = Gtk.Label('a\n\n\n\n\nb\n\n\n\n\n\n\n\nc')
        view.add(label)
        scroll.add(view)
        win.add(scroll)
        win.show_all()
        position = scroll.get_vadjustment()
        position.set_value(50)
        scroll.set_vadjustment(position)

if __name__ == '__main__':
    win = window()
    Gtk.main()

rawDescription: How to set Gtk.ScrolledWindow adjustment

description: Set Gtk.ScrolledWindow adjustment


code:
from itertools import permutations
def test_add_dependency(self):
    """Tasks can be added with dependencies"""
    for p in permutations("AB"):
        self.done = []
        def test(id):
            self.done.append("Test " + id)
        s = Schedule(threads=1)
        tasks = {id: Task("Test " + id, partial(test, id)) for id in "AB"}
        s.add_task(tasks['A'])
        s.add_task(tasks['B'])
        s.add_dependency(tasks[p[0]], tasks[p[1]])
        s.run()
        self.assertEqual(self.done, ["Test " + p[1], "Test " + p[0]])

rawDescription: Testing a function that can return non-deterministic results using Python unittest


code: sorted_list = sorted(lista, key=lambda f: os.stat(f).st_mtime)

rawDescription: How to sort by mtime a given list of files in Python3?

description: Sort by mtime a given list of files in Python3


code:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "web.settings")

rawDescription: Cannot import Django modules in IPython Notebook


code:
import os
rootDir = "myfolder"
fileSet = set()

for dir_, _, files in os.walk(rootDir):
    for fileName in files:
        relDir = os.path.relpath(dir_, rootDir)
        relFile = os.path.join(relDir, fileName)
        fileSet.add(relFile)

rawDescription: Python - Get relative path of all files and subfolders in a directory


code:
for i in range(0,13):
    v = np.ndarray(shape=(130,1),dtype=float)
    for j in range(0,130):
        v[j] = float(f[k])
        k += 1
    List.append(v)

rawDescription: Issues with printing in python a list of arrays


code:
import platform
import socket
import os
platform.node()
socket.gethostname()
os.environ['COMPUTERNAME']

rawDescription: Getting name of windows computer running python script?


code:
def __len__(self):
    return len(self.mylist)

def __iter__(self):
    for i in self.mylist:
        yield i

rawDescription: How to achieve the functionality of UserDict.DictMixin in Python 3?

description: Achieve the functionality of UserDict.DictMixin in Python 3


code:
import sys
import multiprocessing

global_var = [1, 2, 3]

def no_effect1():
    print(global_var[0] + global_var[1])
    print("No Effect Count: {}".format(sys.getrefcount(global_var)))
    return

def no_effect2():
    new_list = [i for i in global_var]
    print("New List Count: {}".format(sys.getrefcount(global_var)))

def change1():
    local_handle = global_var
    print("Local Handle Count: {}".format(sys.getrefcount(global_var)))

def change2():
    new_dict = {'item':global_var}
    print("Contained Count: {}".format(sys.getrefcount(global_var)))

p_list = [multiprocessing.Process(target=no_effect1),
          multiprocessing.Process(target=no_effect2),
          multiprocessing.Process(target=change1),
          multiprocessing.Process(target=change2)]

for p in p_list:
    p.start()

for p in p_list:
    p.join()

    p.join()

rawDescription: Python map function, threads, big structures


code: return HTMLString(u' '.join([subfield() for subfield in field]))

rawDescription: Validating many fields as they were one?

description: Validating many fields as they were one


rawDescription: groupby returns multilevel dataframe when used in a column with text

description: Groupby returns multilevel dataframe when used in a column with text


code:
pad = ['qz', 'abc', 'def', 'ghi', 'jkl', 'mno', 'prs', 'tuv', 'wxy']
letter_to_numbers = {
    ord(ch): ord(str(i))
    for i, chs in enumerate(pad, 1)
    for ch in chs
} # Map ord('f') to ord('3'), ...
"1-800-Flowers".lower().translate(letter_to_numbers)

rawDescription: Python Convert Letters Numbers

description: Python Convert Letters Numbers


code:
from string import Formatter
[x[1] for x in Formatter().parse(formatted_string) if x[1] is not None]

rawDescription: Getting named parameters from Python string


code:
print("Hello and welcome to the BMI calculator!!")
count = 0;
user = input("Would you like to go again, Y/N: ")
while user == "y":
     count += 1 #Increase count by one
     height = int(input("Please put in your height in Meters: "))
     weight = int(input("Please put in your weight in Kilogram: "))
     BMI = weight/ (height*height)
     if BMI < 18:
        print("Your BMI is:", BMI, "Eat some more Big Macs, you are             too skinny!")
     elif BMI > 25:
        print("Your BMI is:", BMI, "Stop eating all those Big Macs, you are far too fat!")
     elif BMI >18 < 25:
        print("Your BMI is:", BMI, "You are a normal and healthy weight, congratulations!!!")
     user = input("Would you like to go again, Y/N: ")

print("You checked your BMI", count, "times.")
input("\nPress the enter key to exit")

rawDescription: How to add a counter function?

description: Add a counter function


rawDescription: how to set unequal x axis intervals in Matplotlib

description: Set unequal x axis intervals in Matplotlib


code:
f1=open('first.txt','r')
f2=open('second.txt', 'r')
new_file=open("new_text.txt", 'w')
for line in f1:
    new_line=line +"...." + f2.readline()
    new_file.write(new_line,"\n")

rawDescription: Merging stock symbols with their EPS rating


code:
# code not tested, YMMV, etc.

from urlparse import urlparse

from django.core import urlresolvers

HOME = 'http://my.site.com/'

def generate_back_url(url, default_url=HOME):
    parsed = urlparse(url)
    if parsed.netloc == 'my.site.com':
        try:
            urlresolvers.resolve(parsed.path)
        except urlresolvers.Resolver404:
            back_url = default_url
        else:
            back_url = url
    else:
        back_url = default_url
    return back_url

# ...

def my_view(request):
    # ...
    # truth be told I'm not sure whether the .get() is necessary, sorry.
    back_url = generate_back_url(request.META.get('REFERER', HOME))
    # ...

rawDescription: How can I make a URL link in django that will go to the referring view?

description: Make a URL link in django that will go to the referring view


code:
from subprocess import Popen, PIPE

control_f4_sequence = '''keydown Control_L
key F4
keyup Control_L
'''

shift_a_sequence = '''keydown Shift_L
key A
keyup Shift_L
'''

def keypress(sequence):
    p = Popen(['xte'], stdin=PIPE)
    p.communicate(input=sequence)

keypress(shift_a_sequence)
keypress(control_f4_sequence)

rawDescription: How to run shortkeys using Python?

description: Run shortkeys using Python


code:
import wx
from wx.lib.scrolledpanel import ScrolledPanel

app = wx.PySimpleApp()
frame = wx.Frame(None, id=wx.ID_ANY, name="Just one child", size=(100,100))
scrollablePanel = ScrolledPanel(parent=frame, id=wx.ID_ANY, name="scrolledPanel", style=wx.ALWAYS_SHOW_SB)
scrollablePanel.SetupScrolling()
scrollablePanel.SetBackgroundColour(wx.Colour(128,128,128))
innerPanel = wx.Panel(parent=scrollablePanel, id=wx.ID_ANY, name="innerPanel", size=(250,100), style=wx.SIMPLE_BORDER)
innerPanel.SetBackgroundColour(wx.Colour(255,255,255))
vSizer = wx.BoxSizer(wx.VERTICAL)
vSizer.Add(innerPanel, proportion=0, flag=wx.ALL|wx.ALIGN_CENTER_HORIZONTAL, border=8)
hSizer = wx.BoxSizer(wx.HORIZONTAL)
hSizer.Add(vSizer, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL)
scrollablePanel.SetSizer(hSizer)
frame.Show()
app.MainLoop()

rawDescription: wxPython - implementing a scrollable view on a page similar to Visio or MS Word's print layout view

description: WxPython - implementing a scrollable view on a page similar to Visio or MS Word's print layout view


code:
# sample sub-query for testing
_another_query = session.query(Evaluation.module).filter(Evaluation.module > 3)

# define aliases
E1 = aliased(Evaluation, name="e1")
E2 = aliased(Evaluation, name="e2")

# inner query
sq = (
    session
    # .query(E1)
    # select columns explicitely to control labels
    .query(E1.user.label("user"), E1.points.label("points"))
    .outerjoin(E2, and_(
        E1.user == E2.user,
        E1.module == E2.module,
        E1.time < E2.time,
    ))
    .filter(E2.user == None)
    .filter(E1.module.in_(_another_query))
)
sq = sq.subquery(name="sq")

# now lets group by
q = (
    session
    .query(sq.c.user, func.sum(sq.c.points))
    .group_by(sq.c.user)
    .order_by(func.sum(sq.c.points))
    .limit(5)
)

rawDescription: Sqlalchemy: How to perform outer join with itself?


rawDescription: How to set a cookie in a django test case?

description: Set a cookie in a django test case


code:
import re

def unescape(text):
    return re.sub(r'\\x([0-9a-fA-F]{2})', lambda g: chr(int(g.group(1),16)), text)

rawDescription: Python hex string read in from file no longer interpreted as hex


code:
# set width of column 0 to 3, column 1 to 10
self.testTable.width(0,3,1,10)

rawDescription: How do I set different column widths for each column in a table using Python TkTable?

description: Set different column widths for each column in a table using Python TkTable


code:
files_to_do = [...] #put paths in here
for f in files_to_do:
    lines = [line for line in open(f,'r').readlines() if not line.startswith("#")]
    sorted_lines = sorted(lines, key=lambda line: int(line.split()[1]))
    #party

rawDescription: python read 2 files, ignore header (# beginning line), and sort data

description: Python read 2 files, ignore header (# beginning line), and sort data


code: ax.plot3D(x, y, z, 'k.', alpha=.8)

rawDescription: matplotlib 3D scatter plot colors of dots very light

description: Matplotlib 3D scatter plot colors of dots very light


code:
from functools import partial
for index in indexes:
    variable = partial(data.variable, index=index)
    variable(name="el_1_pt", value=event.el_pt[0])
    variable(name="el_1_eta", value=event.el_eta[0])
    variable(name="el_1_phi", value=event.el_phi[0])
    variable(name="jet_1_pt", value=event.jet_pt[0])
    variable(name="jet_1_eta", value=event.jet_eta[0])
    variable(name="jet_1_phi", value=event.jet_phi[0])
    variable(name="jet_1_e", value=event.jet_e[0])
    variable(name="jet_2_pt", value=event.jet_pt[1])
    variable(name="jet_2_eta", value=event.jet_phi[1])
    variable(name="jet_2_phi", value=event.jet_eta[1])
    variable(name="jet_2_e", value=event.jet_e[1])
    variable(name="met", value=event.met_met)
    variable(name="met_phi", value=event.met_phi)

rawDescription: How should one argument of a Python function that doesn't change be set?


code:
w = Canvas(outer)
w.setAttribute(QtCore.Qt.WA_StyledBackground)
w.setStyleSheet("background-color: black")

rawDescription: Stylesheet for nested custom widget not applied (PyQt4)


code:
newTE = TE(name, team, rushingYards, rushingTouchdowns, rushingFumbles, receptionYards,
           receptionTouchdowns, position="TE", gamesSuspended=SUSPENSIONS[name])

rawDescription: Basic Python Dictionary of String Keys and Int Values


code:
import numpy
from mpl_toolkits.mplot3d import proj3d
def orthogonal_proj(zfront, zback):
    a = (zfront+zback)/(zfront-zback)
    b = -2*(zfront*zback)/(zfront-zback)
    return numpy.array([[1,0,0,0],
                        [0,1,0,0],
                        [0,0,a,b],
                        [0,0,0,zback]])
proj3d.persp_transformation = orthogonal_proj

rawDescription: How to disable perspective in mplot3d?

description: Disable perspective in mplot3d


code:
import wx

class MyFrame(wx.Frame):

    def __init__(self, *args, **kw):
        super(MyFrame, self).__init__(*args, **kw)
        self.Init()

    def Init(self):

        panel = wx.Panel(self)
        button = wx.Button(panel, label='Button', pos=(30, 25))
        button.Bind(wx.EVT_ENTER_WINDOW, self.OnMouseEnter)
        button.Bind(wx.EVT_LEAVE_WINDOW, self.OnMouseLeave)
        self.StatusBar = self.CreateStatusBar()
        self.SetSize((200, 170))
        self.SetTitle('Statusbar...')
        self.Centre()
        self.Show(True)

    def OnMouseEnter(self, e):
        self.StatusBar.SetStatusText("Mouse Enter Event...")
        e.Skip()

    def OnMouseLeave(self, e):
        self.StatusBar.SetStatusText("Mouse Leave Event...")
        e.Skip()

def Main():

    app = wx.App()
    MyFrame(None)
    app.MainLoop()

if __name__ == '__main__':
    Main()

rawDescription: Use StatusBar for Mouse Hover on Button

description: Use StatusBar for Mouse Hover on Button


code:
#imports elided

class IFoo(Interface):
    bar = schema.Object(schema=Interface)

class IBar(Interface):
    foo = schema.Object(schema=IFoo)

IFoo['bar'].schema = IBar

rawDescription: Defining circular references using zope.schema


code:
import sys, tarfile

def get_members(tar, prefix):
    if not prefix.endswith('/'):
        prefix += '/'
    offset = len(prefix)
    for tarinfo in tar.getmembers():
        if tarinfo.name.startswith(prefix):
            tarinfo.name = tarinfo.name[offset:]
            yield tarinfo

args = sys.argv[1:]

if len(args) > 1:
    tar = tarfile.open(args[0])
    path = args[2] if len(args) > 2 else '.'
    tar.extractall(path, get_members(tar, args[1]))

rawDescription: Extract all files with directory path in given directory


code:
def merge(merged, a, b):

    if a and b:
        return merge(merged + [min(a[0], b[0])],
                     a[1:] if min(a[0], b[0]) == a[0] else a,
                     b[1:] if min(a[0], b[0]) == b[0] and not a[0] == b[0] else b
                     )

    elif a and not b and len(a) > 1:
        return merged + merge([], a[:len(a)/2], a[len(a)/2:])
    elif a and not b:
        return merged + a
    elif b and not a  and len(b) > 1:
        return merged + merge([], b[:len(b)/2], b[len(b)/2:])
    elif b and not a:
        return merged + b
    else:
        return merged

def mergesort(lst):

    if not lst:
        return []
    elif len(lst) == 2:
        return [min(lst), max(lst)]
    elif len(lst) == 1:
        return lst
    else:
        return merge([], mergesort(lst[:len(lst)/2]), mergesort(lst[len(lst)/2:]))

rawDescription: Bottom Up MergeSort using Python

description: Bottom Up MergeSort using Python


code:
import pygame

#from pygame.locals import *

#--------------------------------------------------------------------
# class for single sprite
#--------------------------------------------------------------------

class MySprite():

    def __init__(self, image, x, y):

        self.image = pygame.image.load(image)
        image_rect = self.image.get_rect()

        # Rect class to use "Sprite collision detect" - in the future
        # In rect you have sprite position and size
        # You can use self.rect.x, self.rect.y, self.rect.width, self.rect.height
        # and self.rect.center, self.rect.centerx, self.rect.top, self.rect.bottomright etc.

        self.rect = pygame.rect.Rect(x, y, image_rect.width, image_rect.height)

    def draw(self, screen):
        screen.blit(self.image, self.rect)

#--------------------------------------------------------------------
# class for player
#--------------------------------------------------------------------

class MyPlayer(MySprite):

    def __init__(self, image, x, y):
        # parent constructor always as a first in __init__
        MySprite.__init__(self, image, x, y)

        self.speed_x = self.speed_y = 0

    #-----------------------------

    def set_speed(self, x, y):
        self.speed_x = x
        self.speed_y = y

    #-----------------------------

    def update(self):
        self.rect.x += self.speed_x
        self.rect.y += self.speed_y

        if self.rect.centerx < 0 :
            self.rect.centerx = 800
        elif self.rect.centerx > 800 :
            self.rect.centerx = 0

        if self.rect.centery < 0 :
            self.rect.centery = 600
        elif self.rect.centery > 600 :
            self.rect.centery = 0

#--------------------------------------------------------------------

class Window():

    def __init__(self, width, height):

        #--------------------
        self.rect = pygame.Rect(0, 0, width, height)
        # or
        self.width, self.height = width, height
        #--------------------

        pygame.init()

        # most users and tutorials call it "screen"
        self.screen = pygame.display.set_mode(self.rect.size)

        #############################################################

        self.foreground = None
        self.background = None

        self.set_background("background.jpg")
        self.set_foreground("ball3.png")

        #################################################

        self.player = MyPlayer("ball1.png", 100, 200)

        self.sprites_list = []

        self.add_sprite(MySprite("ball2.png", 100, 400))
        self.add_sprite(MySprite("ball2.png", 300, 500))
        self.add_sprite(MySprite("ball2.png", 300, 200))

        self.remove_last_sprite()

        #-----------------------------

        # red text "PAUSE"
        font = pygame.font.SysFont("", 72)
        self.text_pause = font.render("PAUSE", True, (255, 0, 0))

        # center text on screen
        screen_center = self.screen.get_rect().center
        self.text_pause_rect = self.text_pause.get_rect(center=screen_center)

    #--------------------------

    def add_sprite(self, sprite):
        self.sprites_list.append(sprite)

    #--------------------------

    def remove_last_sprite(self):
        if self.sprites_list:
            del self.sprites_list[-1]

    #--------------------------

    def draw_sprites(self, screen):
        for sprite in self.sprites_list:
            sprite.draw(screen)

    #--------------------------

    def draw_background(self, screen):
        screen.fill((0,64,0)) # clear screen to green
        if self.background:
            screen.blit(self.background, (0,0))

    #--------------------------

    def draw_foreground(self, screen):
        if self.foreground:
            screen.blit(self.foreground, (0,0))

    #--------------------------

    def draw_world(self, image):
        temp = pygame.Surface(self.rect.size, pygame.SRCALPHA, 32).convert_alpha()
        image_rect = image.get_rect()

        for x in range(0, self.rect.width, 60):
            for y in range(0,self.rect.width, 60):
                temp.blit(image,(x,y))

        return temp

    #--------------------------

    def set_foreground(self, image=None):
        if image:
            img = pygame.image.load(image)
            self.foreground = self.draw_world(img)

    #--------------------------

    def set_background(self, image=None):
        if image:
            self.background = pygame.image.load(image)

    #--------------------------

    def run(self):

        clock = pygame.time.Clock()

        RUNNING = True
        PAUSED = False

        while RUNNING:

            #--- events ---

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    RUNNING = False

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        RUNNING = False
                    elif event.key == pygame.K_SPACE:
                        PAUSED = not PAUSED

                    if event.key == pygame.K_UP:
                        self.player.set_speed(0,-10)
                    elif event.key == pygame.K_DOWN:
                        self.player.set_speed(0,10)
                    elif event.key == pygame.K_LEFT:
                        self.player.set_speed(-10,0)
                    elif event.key == pygame.K_RIGHT:
                        self.player.set_speed(10,0)

                if event.type == pygame.KEYUP:
                    if event.key in (pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT):
                        self.player.set_speed(0,0)

            #--- changes ----

            if not PAUSED:
                # change elements position
                self.player.update()

            #--- draws ---

            self.draw_background(self.screen)
            self.draw_foreground(self.screen)
            self.draw_sprites(self.screen)
            self.player.draw(self.screen)

            if PAUSED:
                # draw pause string
                self.screen.blit(self.text_pause, self.text_pause_rect.topleft)

            pygame.display.update()

            #--- FPS ---

            clock.tick(25) # 25 Frames Per Seconds

        #--- finish ---

        pygame.quit()

#----------------------------------------------------------------------

Window(800,600).run()

rawDescription: Pygame- window and sprite class - python


code:
def handle_uploaded_file(f):
    with open('imgepath', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

rawDescription: how save image to disk

description: How save image to disk


code:
list1 = [["Ryan","10"],["James","40"],["John","30"],["Jake","15"],["Adam","20"]]
list2 = [["Ryan","Canada"],["John","United States"],["Jake","Spain"]]
list1_dict = dict(list1)
output = [item + [list1_dict[item[0]]] for item in list2]

rawDescription: Matching and Appending

description: Matching and Appending


code:
import urllib.request
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = urllib.request.HTTPBasicAuthHandler()
auth_handler.add_password(realm='PDQ Application',
                          uri='https://mahler:8092/site-updates.py',
                          user='klem',
                          passwd='kadidd!ehopper')
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
urllib.request.urlopen('http://www.example.com/login.html')

rawDescription: How to download a file over http with authorization in python 3.0, working around bugs?

description: Download a file over http with authorization in python 3.0, working around bugs


code:
import wx

class MyApp(wx.App):

  def OnInit(self):
    frame = InsertFrame(parent=None, id=-1)
    frame.Show()
    return True

class InsertFrame(wx.Frame):

  def __init__(self, parent, id):
    wx.Frame.__init__(self, parent, id, 'Test Frame', size = (300,100))
    panel = wx.Panel(self)
    pos_y = 0
    for i in range(50):
      pos_y += 20
      cb = wx.CheckBox(panel, label="sample checkbox", pos=(20, pos_y))

if __name__ == "__main__":
  app = MyApp()
  app.MainLoop()

rawDescription: How to dynamically create check boxes or buttons in Wxpython?

description: Dynamically create check boxes or buttons in Wxpython


code:
def recursive_iterate(iterable):
    iterated_object=[]
    for elem in iterable:
        if hasattr(elem,"__iter__"):
            iterated_object.append(recursive_iterate(elem))
        else:
            iterated_object.append(elem)
    return iterated_object

recursive_iterate([1,2,3,[4,5,6]])
recursive_iterate([1,2,3,xrange(10)])
recursive_iterate([1,2,3,[4,5,6,[xrange(10)]]])

rawDescription: Iterate a list with unknown sublist inside in Python?


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

import wx, os

script = "/path/to/script"

class myFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, 'wxButton')
        self.button = wx.Button(self, id=-1, label='Click Me!')
        self.button.Bind(wx.EVT_BUTTON, self.on_button_click)

        self.Show(True)

    def on_button_click(self, event):
        os.system(script)

app  = wx.PySimpleApp()
main = myFrame()
app.MainLoop()

rawDescription: interfacing wxpython and bash script

description: Interfacing wxpython and bash script


code:
C = numpy.ascontiguousarray([5,6,7],"uint16")  # make an array
C
rawPointer = C.ctypes.data
pC = ctypes.cast( rawPointer, ctypes.POINTER( ctypes.c_uint16 ))
pC[0:3]
pC[1]=100
pC[0:3]
C

rawDescription: In Python, how to access a uint16[3] array wrapped by SWIG (i.e. unwrap a PySwigObject)?


code:
import math

R = 6378.1 #Radius of the Earth
brng = 1.57 #Bearing is 90 degrees converted to radians.
d = 15 #Distance in km

#lat2  52.20444 - the lat result I'm hoping for
#lon2  0.36056 - the long result I'm hoping for.

lat1 = math.radians(52.20472) #Current lat point converted to radians
lon1 = math.radians(0.14056) #Current long point converted to radians

lat2 = math.asin( math.sin(lat1)*math.cos(d/R) +
     math.cos(lat1)*math.sin(d/R)*math.cos(brng))

lon2 = lon1 + math.atan2(math.sin(brng)*math.sin(d/R)*math.cos(lat1),
             math.cos(d/R)-math.sin(lat1)*math.sin(lat2))

lat2 = math.degrees(lat2)
lon2 = math.degrees(lon2)

print(lat2)
print(lon2)

rawDescription: Get lat/long given current point, distance and bearing


code:
class BufferedFile(object):
    ''' A buffered file that preserves the beginning of a stream up to buffer_size
    '''
    def __init__(self, fp, buffer_size=1024):
        self.data = cStringIO.StringIO()
        self.fp = fp
        self.offset = 0
        self.len = 0
        self.fp_offset = 0
        self.buffer_size = buffer_size

    @property
    def _buffer_full(self):
        return self.len >= self.buffer_size

    def readline(self):
        if self.len < self.offset < self.fp_offset:
            raise BufferError('Line is not available anymore')
        if self.offset >= self.len:
            line = self.fp.readline()
            self.fp_offset += len(line)

            self.offset += len(line)

            if not self._buffer_full:
                self.data.write(line)
                self.len += len(line)
        else:
            line = self.data.readline()
            self.offset += len(line)
        return line

    def seek(self, offset):
        if self.len < offset < self.fp_offset:
            raise BufferError('Cannot seek because data is not buffered here')
        self.offset = offset
        if offset < self.len:
            self.data.seek(offset)

rawDescription: Non blocking stream that supports seek from http response in Python


code:
import itertools

def reset_storage(self, path):
    total = 3715948544 * 2
    block_size = 4096  # Tune this if needed, just make sure it's a factor of the total
    fill = b'\xFF' * block_size

    with open(path, 'wb') as f:
        f.writelines(itertools.repeat(fill, total // block_size))
        # If you want to handle initialization of arbitrary totals without
        # needing to be careful that block_size evenly divides total, add
        # a single:
        # f.write(fill[:total % block_size])
        # here to write out the incomplete block.

rawDescription: How to efficiently allocate a file of predefined size and fill it with a non-zero value using Python?

description: Efficiently allocate a file of predefined size and fill it with a non-zero value using Python


code:
class OnlyOnce(object):
    def __init__(self, data):
        self.data = data
        self.printed = False

    def __str__(self):
        if self.printed is False:
            self.printed = True
            return self.data
        return ''

rawDescription: How to make sure a Jinja custom tag only outputs once?

description: Make sure a Jinja custom tag only outputs once


code:
import amqpstorm

class RabbitConnection(object):
    def __init__(self):
        self.connection = amqpstorm.Connection('localhost', 'guest', 'guest')
        self.channel = self.connection.channel()
        self.channel.queue.declare(queue=RABBITMQ_OUT_NAME, durable=True)
        self.channel.confirm_deliveries()

    def add_alert(self, new_alert):
        message = new_alert.to_json()
        delivered = self.channel.basic.publish(exchange='',
                                               routing_key=RABBITMQ_OUT_NAME,
                                               body=message,
                                               properties={
                                                   'delivery_mode': 2,
                                                   'content_type': 'application/json',
                                                })

rawDescription: pika with celery, connection closed

description: Pika with celery, connection closed


code: t = Text(self.lowerframe, width=5, height=1, background='#336699', font=('', 12))

rawDescription: align text in text widget vertically

description: Align text in text widget vertically


code: self.fields['myfield'].choices = [('%s' % d.id, '%s' % d.name) for d in MyModel.objects.filter(owners = user)]

rawDescription: User in Form-Class

description: User in Form-Class


code:
parts = (1, 'a', 'b', 2, 'c', 'd', None, 'f')
# parts = (self.house, self.suf, self.unit,
#           self.stex, self.stdir, self.stname,
#           self.stdes, self.stdessuf)
' '.join(str(part) for part in parts if part is not None)
# '1 a b 2 c d e f'

rawDescription: Python/Django Concatenate a string depending on whether that string exists


code:
file = 'c:\\file.txt'

k = []
p = []
rho = []
t = []
r = []

with open(file) as f:
    lines = f.read().splitlines()

i = 999
for line in lines:
    line = line.strip()
    if line.startswith(str(i)):
        lineSplitted = line.split('  ')
        k.append(lineSplitted[0])
        p.append(lineSplitted[1])
        rho.append(lineSplitted[2])
        t.append(lineSplitted[3])
        r.append(lineSplitted[4])
        i-=1

rawDescription: Selective loading of data from text file into arrays


rawDescription: Using numpy functions when dtype is object


code:
ans = np.logical_and(
    np.logical_and(array1 != 0, array2 != 0),
    array1 == array2 )

rawDescription: Comparing two numpy arrays to each other


code:
perforceBrowserWnd = None

def perforceBrowser2():
    global perforceBrowserWnd
    if perforceBrowserWnd is None:
        perforceBrowserWnd = PerforceWindow()
    perforceBrowserWnd.show()

rawDescription: Maya + PyQt dialog. How to run a single copy of Qt window?


code:
def match_strings(lastname, listofnames):
    firstCaseMatched = [name for name in listofnames if lastname[0] == name[0]]
    if len(firstCaseMatched):
        matchedidx = [index for index, ame in enumerate(firstCaseMatched) if Levenshtein.distance(lastname, name) < 2]
        match = len(matchedidx)
    else:
        match = 0
    if match == 1:
        newnamelist = [i for j, i in enumerate(listofnames) if j not in matchedidx]
        return 1, newnamelist
    return 0, listofnames

rawDescription: Python, nested loops, matching and performance


code:
class ChipCar(object):
    def __repr__(self):
        return '{}() object, id => 0x{:x}'.format(type(self).__name__, id(self))

ChipCar()

rawDescription: Confirming class instantiation with return value in function


code: [ax.text(p[0], p[1]+50, p[1], color='g') for p in zip(ax.get_xticks(), num_records_yob)]

rawDescription: How to get data labels on a Seaborn pointplot?

description: Get data labels on a Seaborn pointplot


code:
def str(obj):
    try:
        return obj.__str__()
    except ...:
        ...

rawDescription: Why str can't get a second parameter,when __str__ can?


rawDescription: Regex to retrieve the last few characters of a string


code:
def initUI(self):
    ...
    self.btn = QtGui.QPushButton('Play', self)
    self.btn.move(20, 50)
    self.btn.clicked.connect(self.play)

    self.btn = QtGui.QPushButton('Stop', self)
    self.btn.move(120, 50)
    self.btn.clicked.connect(self.stop)
    ...

def play(self):
    cb = QtGui.QApplication.clipboard()
    text = cb.text()
    self.words = text.split(' ')
    self.current_word = 0

    words_per_minute = 200

    # setInterval apparently takes msecs
    sleeptime = 60000.0 / words_per_minute

    self.timer = QtCore.QTimer(self)
    self.timer.setInterval(sleeptime)
    self.timer.timeout.connect(self.printword)
    self.timer.start()

def stop(self):
    self.timer.stop()

def printword(self):
    word = self.words[self.current_word]
    self.le.setText(word)

    self.current_word += 1
    if self.current_word == len(self.words):
        self.timer.stop()

rawDescription: Easiest way to interrupt pyqt4?

description: Easiest way to interrupt pyqt4


code: items[0] in items[1:]

rawDescription: I am trying to create a program that takes a list of numbers from the user and checks whether or not the first number given in repeated in the list


rawDescription: Getting one Field prior to an atomic update in MongoEngine


code:
from Bio import Entrez
Entrez.email = "your@mail.com" #put real mail

handle = Entrez.efetch(db="nuccore", id=['556503834'],
                   rettype="gbwithparts", retmode="txt")
print(handle.read())

rawDescription: biopython's efetch only returns the first features from any database

description: Biopython's efetch only returns the first features from any database


code:
def remove_accents(input_str):
    nkfd_form = unicodedata.normalize('NFKD', input_str)
    only_ascii = nkfd_form.encode('ASCII', 'ignore')
    return only_ascii

def normalize(text):
  text = re.sub(r'\s+', '', str(BeautifulSoup(text)), flags = re.MULTILINE)
  return str(remove_accents(text))

def compare_text(s1, s2):
  s1 = normalize(s1.lower())
  s2 = normalize(s2.lower())
  l1 = len(s1)
  l2 = len(s2)
  if l1 == l2:
    return  s1 == s2
  return False

t1="""

Bonjour à tous,

Je souhaite récolter des informations sur les actions menées en faveur des Seniors au sein du Groupe.

Si vous menez ou avez mené des actions en faveur des seniors et de leur insertion, pourriez-vous m’en faire part. Si je peux avoir des retours d’ici demain matin, ce serait super ! Merci d’avance de vos retours.

"""
t2="""

Bonjour à tous,

Je souhaite récolter des informations sur les actions menées en faveur des Seniors au sein du Groupe.

Si vous menez ou avez mené des actions en faveur des seniors et de leur insertion, pourriez-vous m’en faire part. Si je peux avoir des retours d’ici demain matin, ce serait super ! Merci d’avance de vos retours.

"""

print(compare_text(t1, t2))
True

rawDescription: Compare two texts

description: Compare two texts


code:
def figlegend(handles, labels, loc, **kwargs):
    ...
    l = gcf().legend(handles, labels, loc, **kwargs)
    draw_if_interactive()
    return l

rawDescription: Matplotlib Figure() (Case Sensitive) Does not have attribute figlegend


code: '7' in line and len(line) > 1

rawDescription: elegant python pattern search without if-else statement

description: Elegant python pattern search without if-else statement


code:
path = 'ngs.pradhi.com:/upload'
path.split(':')[0]

rawDescription: How to extract hostname from the given URL in Python?

description: Extract hostname from the given URL in Python


code:
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=username, password=password, port=port, timeout=30)  # setting up ssh connection
ssh.exec_command('<Execute Your Remote Script here>')
ssh.close()

rawDescription: How do I connect to Python program from another Python program on another computer?

description: Connect to Python program from another Python program on another computer


code:
a = "column_number"
b = "_url1"
x = 1234
globals()[a + b] = x
column_number_url1

rawDescription: Create variable name from two string in python


code:
module_name = 'a.foo'
module = __import__(module_name, globals(), locals(), ['*'])

rawDescription: django - import different module when variable change

description: Django - import different module when variable change


code: [int(item) for item in string.split(",")]

rawDescription: List importation from .txt

description: List importation from .txt


code:
def returnLambda(i):
    return lambda x: np.percentile(x,i)

for i in xrange(0,101,10):
    d[str(i)+'_perc'] = returnLambda(i)
    print(i)

rawDescription: strange overwriting occurring when using lamda functions as dict values

description: Strange overwriting occurring when using lamda functions as dict values


code:
first = {"phone": {"home": "(234) 442-4424"},"address":"xyz"}
second = {"phone": {"home": "(234) 442-5555","home1": "(234) 442-4424"},"address":{}}

# recursive deep update you can find here: http://stackoverflow.com/a/3233356/956660
import collections

def update(d, u):
    for k, v in u.iteritems():
        if isinstance(v, collections.Mapping):
            r = update(d.get(k, {}), v)
            d[k] = r
        else:
            d[k] = u[k]
    return d

third = second.copy()
update(third, first)

print(third)

rawDescription: Merge two dictionaries and persist the values of first dictionaries


code:
query = Game.objects.all().query
query.group_by = ['date']
results = QuerySet(query=query, model=Game)

rawDescription: django, group model by days

description: Django, group model by days


code: tree.SetItemImage(node, -1)

rawDescription: Remove image from treectrl items

description: Remove image from treectrl items


code:
import random

list = [1, 2, 3, 4]

random_elements = [random.choice(list) for n in range(5)]

rawDescription: How do I pick x random elements from a list, for x > len(list)?

description: Pick x random elements from a list, for x > len(list)


rawDescription: Python dateutil.parser.parse parses month first, not day


code:
# ... pygame and app initialization

# get screen size
info = pygame.display.Info()
sw = info.current_w
sh = info.current_h

# initial position
x = y = 0
# initial direction
dx = 5
dy = 2

while True:

    # update position with direction
    x += dx
    y += dy

    # check bounds
    if x - dx < 0 or x + dx > sw:
        dx = -dx
    if y - dy < 0 or y + dy > sh:
        dy = -dy

    # then draw and use x/y in your drawing instructions!
    # ... pygame events ...

rawDescription: Pygame moving an object

description: Pygame moving an object


code:
class Foo(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def do_this(self):
        pass

    def do_that(self):
        pass

    def __call__(self):
        self.do_this()
        self.do_that()

foo = Foo(x, y)
foo()
foo.do_this()

rawDescription: Call Nested Function in Python

description: Call Nested Function in Python


code:
taskqueue.add(url='/path/to/my/worker/', params={'key': key},
              target='1.backend1')

rawDescription: Can dynamic backends be started dynamically in Google App Engine?


code:
from __future__ import print_function

import itertools

reservoir = {
    ('a', 'b'): 2,
    ('a', 'c'): 3,
    ('b', 'a'): 1,
    ('b', 'c'): 3,
    ('c', 'a'): 1,
    ('c', 'b'): 2,
    ('c', 'd'): 5
}

fields = sorted(list(set(itertools.chain.from_iterable(reservoir))))

print(' ', *fields)

for row in fields:
    print(row, end=' ')

    for column in fields:
        print(reservoir.get((row, column), 0), end=' ')

    print()

rawDescription: Adjacency Matrix of Non-numeric tuples

description: Adjacency Matrix of Non-numeric tuples


code:
my_list = [y for y in my_list
             if not any(meets_requirement(x,y) for x in my_list)]

rawDescription: Alternative to Double Iteration

description: Alternative to Double Iteration


code:
import subprocess
proc = subprocess.Popen('shell command', stdin=subprocess.PIPE)
proc.stdin.write("my data")

rawDescription: python subprocess pipes stdin without using files

description: Python subprocess pipes stdin without using files


code:
"abc hi ho".count("hi")
"ABChi hi".count("hi")

rawDescription: Return a number of times of a specific string in python


code:
import csv

data = {
        9: [[0, 0, 'ABC'], [1, 2, 'DE"F'], [3, 4, 'GHI']],
        11: [[9, 30, 'LEOPAR"D'], [17, 28, 'DOG'], [19, 43, 'APP"LE']]
       }

fieldnames = ['Field{}'.format(i) for i in range(1,5)]

with open( 'outfile', 'w' ) as f:
    writer = csv.writer(f, delimiter='\t', quoting=csv.QUOTE_NONE, escapechar='\\', quotechar="")
    writer.writerow(fieldnames)
    for k, vv in data.items():
        for v in vv:
            writer.writerow([k] + v)

rawDescription: How to export a dictionary of lists to csv with no headers in python?

description: Export a dictionary of lists to csv with no headers in python


code:
keywords = ("banana", "apple", "orange", ...)
before = 50
after = 100
TEXT = "a big text string,  i.e., a page of a book"

for k in keywords:
    for match in re.finditer(k, TEXT):
        position = match.start()
        cut = TEXT[max(position - before, 0):position + after] # max is needed because that index must not be negative
        trimmed_match = re.match("\w*?\W+(.*)\W+\w*", cut, re.MULTILINE)
        finalcut = trimmed_match.group(1)

rawDescription: Python: Grab text before and after a keyword


code:
styleN = styles["Normal"]
data = []
table_row = ['ID', 'Some Information']
data.append(table_row)
table_row = []
table_row.append(Paragraph(object.ID, styleN))
paragraphs = []
info1 = Paragraph(object.some_information1, styleN)
info2 = Paragraph(object.some_information2, styleN)
paragraphs.append(info1)
paragraphs.append(info2)
table_row.append(paragraphs)
data.append(table_row)
t = Table(data, (6*cm,6*cm,2*cm,2*cm,2*cm), None, style=ts)

rawDescription: Reportlab - Add two Paragraphs into one table cell


rawDescription: Python join all combinations of elements within each list


code:
from __future__ import print_function
print = lambda x: sys.stdout.write("%s\n" % x)

rawDescription: Python 2.7: Print thread safe

description: Python 2.7: Print thread safe


code:
a = sniff(...)
for packet in a:
    if HTTPResponse in packet:
        packet.show()

rawDescription: Scapy not showing HTTP responses

description: Scapy not showing HTTP responses


code:
from rpy2.robjects.lib import ggplot2
class ScaleShapeDiscrete(ggplot2.Scale):
    _constructor = ggplot2.ggplot2_env['scale_shape_discrete']
scale_shape_discrete = ScaleShapeDiscrete.new

rawDescription: Changing legends in ggplot2 with rpy2

description: Changing legends in ggplot2 with rpy2


code:
cj = cookielib.LWPCookieJar()
cj.save('cookies.txt', ignore_discard=False, ignore_expires=False)
...
cj.load('cookies.txt', ignore_discard=False, ignore_expires=False)

rawDescription: Can't automate login using python mechanize (must "activate" specific browser)


code:
def in_dictionary(word):
  for line in open('words', 'r').readlines():
    if word == line.strip():
      return True

  return False

rawDescription: Need to match whole word completely from long set with no partials in Python


code:
import transaction
from zope.app.component.hooks import setSite
from Testing.makerequest import makerequest
from AccessControl.SecurityManagement import newSecurityManager

plone_site_id = 'Plone' # Adjust as needed.

app = makerequest(app)
site = app[plone_site_id]
setSite(site)
user = app.acl_users.getUser('admin').__of__(site.acl_users)
newSecurityManager(None, user)

rawDescription: Creating Content with createContentInContainer


code:
from collections import Counter

c = Counter(tuple(l) for l in big_list)
new_list = []
for l in big_list:
    t = tuple(l)
    if c[t] > 1:
        new_list.append(l)
        c[t] = 0

rawDescription: comparing a list of lists with itself

description: Comparing a list of lists with itself


code:
@register.filter
def isotime(datestring):
    datestring = str(datestring)
    return datestring.replace("T"," ")

rawDescription: How to remove T from time format %Y-%m-%dT%H:%M:%S?

description: Remove T from time format %Y-%m-%dT%H:%M:%S


rawDescription: Python Four Digits Counter

description: Python Four Digits Counter


code:
import urllib2
from BeautifulSoup import BeautifulSoup
page = BeautifulSoup(urllib2.urlopen("http://www.url.com"))
page.findAll('img')

rawDescription: Python - Getting all images from an html file


code:
from tornado.ioloop import IOLoop
from datetime import timedelta

class WebSocketHandler(tornado.websocket.WebSocketHandler):

    def open(self):
        print('connected')
        self.daemon = Daemon()
        self.write_message(self.daemon.get_status())
        self.schedule_update()

    def schedule_update(self):
        self.timeout = IOLoop.instance().add_timeout(timedelta(seconds=5),
                                                     self.update_client)
    def update_client(self):
        try:
            self.write_message(self.daemon.get_status())
        finally:
            self.schedule_update()

    def on_close(self):
        IOLoop.instance().remove_timeout(self.timeout)
        print('disconnected')

rawDescription: Using Tornado To Send Intermittent Updates to Client


rawDescription: python datetime question

description: Python datetime question


code: request.session['viewed_post_%s' % post.id] = True

rawDescription: Django : How to count number of people viewed


code: call(["xdotool", "mousemove", str(x), str(y)])

rawDescription: In Python how to use variables in call function?


code:
#!/usr/bin/env python

from random import normalvariate

# Build the network
from pybrain.tools.shortcuts import buildNetwork
net = buildNetwork(2, 1, 1, bias=True)

# Add samples
from pybrain.datasets import SupervisedDataSet
ds = SupervisedDataSet(2, 1)
for i in range(100):
    x = normalvariate(3, 0.6)
    y = normalvariate(2, 1)
    ds.addSample((x, y), (0,))
for i in range(100):
    x = normalvariate(7, 0.5)
    y = normalvariate(1, 0.1)
    ds.addSample((x, y), (1,))

# Train with samples
from pybrain.supervised.trainers import BackpropTrainer
trainer = BackpropTrainer(net, ds, learningrate=0.1, momentum=0.99)

print("Start training")
print(trainer.train())
a = trainer.trainUntilConvergence(dataset=ds,
                                  maxEpochs=1000,
                                  verbose=True,
                                  continueEpochs=10,
                                  validationProportion=0.1,
                                  outlayer=softmax)

print("Finished training")
print(trainer.train())

# See if it remembers
print("Test function f(x)=4x+1")
for x in range(-10,10):
    for y in range(-10,10):
        print("f(%i, %i) = %i" % (x, y, net.activate((x, y))))
print("f(%i, %i) = %i" % (3, 2, net.activate((3, 2))))
print("f(%i, %i) = %i" % (7, 1, net.activate((7, 1))))

rawDescription: How can I use PyBrain to train a simple linear function?

description: Use PyBrain to train a simple linear function


code:
parser = argparse.ArgumentParser()
# Add arguments...
usage = parser.format_usage()
parser.usage = usage.rstrip() + ' ...\n'

rawDescription: Python argparse: Display parse_known_args mode in usage string


code:
class car(object):
    db_read = False
    def read_spec_and_populate_db():
        if not car.db_read:
            spec = read_from_file(spec.yaml)
            populate_db(spec)
            car.db_read = True

rawDescription: How to restrict base class method to be run only once

description: Restrict base class method to be run only once


code:
import datetime
import wmi

wmiob = wmi.WMI()
sdata = wmiob.Win32_PerfFormattedData_PerfOS_System()
uptime = sdata[-1].SystemUpTime
tnow = datetime.datetime.now()
utime = datetime.timedelta(seconds=int(uptime))
boot = tnow-utime
bootime = "Boot time was around {}:{}:{}".format(boot.hour, boot.minute, boot.second)
print(bootime)

rawDescription: Getting startup time in Windows 10 doesn't give always the same time


code:
result = doc.xpath('//li[position() <= 2]')
# [<Element li at 0x7f7728684530>, <Element li at 0x7f7728684590>]

rawDescription: how to get a few items from the set?

description: Get a few items from the set


code:
plt.figure(figsize = (8,6), dpi = 72)
plt.xlabel('RF Region')
plt.ylabel('Frequency [%]')
plt.title('Distribution of Rating Results')
ylim(0,50)
ax = plt.gca()
colors= ['r', 'b']
df.plot(kind='bar',color=colors, alpha=0.75, ax=ax)
ax.yaxis.set_major_locator(MultipleLocator(10))
ax.yaxis.set_minor_locator(MultipleLocator(5))
plt.grid(b=True, which='major', linewidth=1.0)
plt.grid(b=True, which='minor')

rawDescription: Pandas Bar Chart Issue

description: Pandas Bar Chart Issue


code:
from django.core.urlresolvers import reverse

class ModelBAdmin(admin.ModelAdmin):
    list_display = ('id', 'a_link', )
    list_display_links = None
    ordering = ('-id', )

    def a_link(obj):
        return format_html('{}', reverse(
            'admin:myapp_a_change', args=[obj.a.id]), obj.a.name)
    a_link.short_description = "Model A Details"

admin.site.register(ModelB, ModelBAdmin)

rawDescription: Link ForeignKey record to its detail view in Django Admin?


code:
from xlsxwriter.workbook import Workbook

workbook = Workbook('tab_colors.xlsx')

# Set up some worksheets.
worksheet1 = workbook.add_worksheet()
worksheet2 = workbook.add_worksheet()
worksheet3 = workbook.add_worksheet()
worksheet4 = workbook.add_worksheet()

# Set tab colours
worksheet1.set_tab_color('red')
worksheet2.set_tab_color('green')
worksheet3.set_tab_color('#FF9900')  # Orange

# worksheet4 will have the default colour.
workbook.close()

rawDescription: Coloring a tab in openpyxl

description: Coloring a tab in openpyxl


code:
import csv
with open('test.csv', 'w', newline='') as fp:
    a = csv.writer(fp, delimiter=',')
    data = [['Me', 'You'],
            ['293', '219'],
            ['54', '13']]
    a.writerows(data)

rawDescription: Writing to CSV with Python adds blank lines


code:
def OnPress(self, sender):
    self.panel.remove(self.curPage)
    self.panel.add(self.spinner, DockPanel.CENTER)
    self.curPage=self.spinner
    Timer(5000, self.OnTimer)
    return CalculatePercentage()

def OnTimer(self, target):
    self.panel.remove(self.curPage)
    self.panel.add(self.recommendation, DockPanel.CENTER)
    self.curPage=self.recommendation

rawDescription: Timer not being called by button press in pyjs


code:
# your values go here, where lat_values[24] = -67, etc.
time_values = np.array(['2015-01-01', '2015-01-02', ...])
lat_values = np.array([...])
lon_values = np.array([...])

# read the coded coords
_, time, lat, lon = np.loadtxt('coords', dtype=int).T

# decode
time = time_values[time]
lat = lat_values[lat]
lon = lon_values[lon]

rawDescription: Python: Replacing every number in an array with a different number


code:
#for the whole widget
self.setStyleSheet("QLabel {font: 30pt Comic Sans MS}")
#Just for this label
label.setStyleSheet("font: 30pt Comic Sans MS")

rawDescription: Modify the size and the type of the font


code: 'hello world'[::-1]

rawDescription: Reverse a string in Python

description: Reverse a string in Python


code:
import xlwt

style = xlwt.XFStyle()
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = xlwt.Style.colour_map['dark_purple']
style.pattern = pattern

rawDescription: python xlwt set custom background colour of a cell

description: Python xlwt set custom background colour of a cell


code:
soup = BeautifulSoup(htmlstring)
soup.findAll('div', style="width=300px;")

rawDescription: Find a specific tag with BeautifulSoup

description: Find a specific tag with BeautifulSoup


code:
def my_coroutine():
    yield (yield (yield 1))
from cotoolz import comap
cm = comap(lambda a: a + 1, my_coroutine())
next(cm)
cm.send(2)
cm.send(3)
cm.send(4)

rawDescription: Modifying yield from's return value

description: Modifying yield from's return value


code:
from StringIO import StringIO
import Image

file = StringIO()
image = Image.new("RGBA", size=(50,50), color=(256,0,0))
image.save(file, 'png')
file.name = 'test.png'
file.seek(0)

rawDescription: Generate in-memory image for Django testing


code:
def fib():
    a, b = 0,1 #initially a=0 and b=1
    while True: #infinite loop term.
        yield b #generate b and use it again.
        a,b = b, a + b #a and b are now own their new values.

for i in fib(): #generate i using fib() function. i equals to b also thanks to yield term.
    print(i) #i think you known this
    if i>100:
        break #we have to stop loop because of yield.

rawDescription: What does "for i in generator():" do?

description: What does "for i in generator():" do


code:
import numpy as np
import theano
from theano import tensor as te

a = te.fscalar("a")
b = te.fscalar("b")
M = te.stacklists([[a, b], [b, a]])

f = theano.function([a, b], M)

print(f(1.0, 2.0))
# [[ 1.  2.]
#  [ 2.  1.]]

rawDescription: Theano matrix composed of theano scalars


rawDescription: Store old password hashes in Django, so Users can't reuse the same password


code: subprocess.Popen([PATH_TO_G++ + "/g++", "file.cpp", "-o", "file.exe"])

rawDescription: How to launch a program with many arguments in Python/Linux

description: Launch a program with many arguments in Python/Linux


code:
# Code that modifies the current `session`; we must be in a test context already.
headers = {}
with self.client.session_transaction():
    # Get the cookie that is sent to the browser to establish a connection
    # via a fake request.
    response = make_response()
    self.app.session_interface.save_session(self.app, session, response)
    headers['Cookie'] = response.headers.get('Set-Cookie', '')
self.client.post(..., headers=headers)  # also works for .get, .put, etc.

rawDescription: Unit test a Flask session - cannot reproduce failure with session_transaction


code:
def parsePcap():
  IPList = []
  count=0
  for pkt in pkts:
        #print pkt.summary()
        if pkt.haslayer(IP):
                proto = pkt.getlayer(IP).proto
                x = pkt.getlayer(IP).src
                y = pkt.getlayer(IP).dst
                IPList[count].append((proto,x,y))
                count+=1
  return IPList[count]

rawDescription: create list of protocols and src,dst IP in scapy using python

description: Create list of protocols and src,dst IP in scapy using python


code:
from multiprocessing import Pool, Value, RawArray, RLock
from time import sleep

class Latch:

    '''A countdown latch that lets us wait for a job of "n" parts'''

    def __init__(self, n):
        self.__counter = Value('i', n)
        self.__lock = RLock()

    def decrement(self):
        with self.__lock:
            self.__counter.value -= 1
            print('dec', self.read())
        return self.read() == 0

    def read(self):
        with self.__lock:
            return self.__counter.value

    def join(self):
        while self.read():
            sleep(1)

def list_of_values(x):
    '''An expensive function'''
    print(x, ': thinking...')
    sleep(1)
    print(x, ': thought')
    return list(range(x))

pool = Pool()

def async_f(x, on_complete=None):
    '''Return the sum of the values in the expensive list'''
    if x == 0:
        on_complete(0) # no list, return 0
    else:
        n = x # need to know size of result beforehand
        latch = Latch(n) # wait for n entires to be calculated
        result = RawArray('i', n+1) # where we will assemble the map
        def delayed_map(values):
            '''This is the callback for the pool async process - it runs
               in a separate thread within this process once the
               expensive list has been calculated and orchestrates the
               mapping of f over the result.'''
            result[0] = x # first value in list is x
            for (v, i) in enumerate(values):
                def callback(fx, i=i):
                    '''This is the callback passed to f() and is called when
                       the function completes.  If it is the last of all the
                       calls in the map then it calls on_complete() (ie another
                       instance of this function) for the calling f().'''
                    result[i+1] = fx
                    if latch.decrement(): # have completed list
                        # at this point result contains [x]+map(f, ...)
                        on_complete(sum(result)) # so return sum
                async_f(v, callback)
        # Ask worker to generate list then call delayed_map
        pool.apply_async(list_of_values, [x], callback=delayed_map)

def run():
    '''Tie into the same mechanism as above, for the final value.'''
    result = Value('i')
    latch = Latch(1)
    def final_callback(value):
        result.value = value
        latch.decrement()
    async_f(6, final_callback)
    latch.join() # wait for everything to complete
    return result.value

print(run())

rawDescription: parallel recursive function in python?

description: Parallel recursive function in python


code:
for i in range(len(states_list)):
     if i > 0:
         if states_list[i][0] != states_list[i-1][0]:
             print('\n')
     print(states_list[i])

rawDescription: How do I print a blank line whenever the first letter of the state differs from the previous state's first letter

description: Print a blank line whenever the first letter of the state differs from the previous state's first letter


code:
converter = Converter(encoded_file_path)
converter.change_to_temp_dir = Mock()
converter.do_stuff = Mock()
converter.change_to_original_dir = Mock()

m = Mock()
m.configure_mock(first=converter.change_to_temp_dir,
                 second=converter.do_stuff,
                 third=converter.change_to_original_dir)

converter.run()
m.assert_has_calls([call.first(), call.second(), call.third()])

rawDescription: Asserting execution order in python unittest


code:
def lerp(a, b, coord):
    if isinstance(a, tuple):
        return tuple([lerp(c, d, coord) for c,d in zip(a,b)])
    ratio = coord - math.floor(coord)
    return int(round(a * (1.0-ratio) + b * ratio))

def bilinear(im, x, y):
    x1, y1 = int(floor(x)), int(floor(y))
    x2, y2 = x1+1, y1+1
    left = lerp(im.getpixel((x1, y1)), im.getpixel((x1, y2)), y)
    right = lerp(im.getpixel((x2, y1)), im.getpixel((x2, y2)), y)
    return lerp(left, right, x)

rawDescription: How to do bilinear interpolation for PIL Image in python?

description: Do bilinear interpolation for PIL Image in python


code:
failname = input("Insert the fail name: ")
fail = open(failname, encoding = "UTF-8")

for line in fail:
    for char in line:
        if char.lower() == "õ":
            print("oe".upper(), end = "")
        elif char.lower() == "ö":
            print("oe".upper(), end = "")
        elif char.lower() == "ä":
            print("ae".upper(), end = "")
        elif char.lower() == "ü":
            print("ue".upper(), end = "")
        else:
            print(char.upper(), end = "")
    print("\n")

rawDescription: For loop won't give to right answer

description: For loop won't give to right answer


code:
def part_of_day_statistics(x):
    if x.hour >= 6 and x.hour < 12:
        return 'Morning'
    if x.hour >= 12 and x.hour < 18:
        return 'Afternoon'

rawDescription: How to check against a time value?

description: Check against a time value


code: pwd = getpass.getpass('password:')

rawDescription: Passing a password to KLOG from within a script, using `subprocess.POPEN`


code:
class MyHandler(tornado.web.RequestHandler):

    @asynchronous
    @gen.engine
    def get(self):
        response = yield gen.Task(self.dosomething, 'argument')
        self.write(response)
        self.finish()

    def dosomething(self, myargument, callback):
        return callback(myargument)

rawDescription: using gen.task with Tornado for a simple function

description: Using gen.task with Tornado for a simple function


code:
class MyListField(ListField):
    def __init__(self, max_length=None,  **kwargs):
        self.max_length = max_length
        super(MyListField, self).__init__(**kwargs)

    def validate(self, value):
        super(MyListField, self).validate(value)

        if self.max_length is not None and len(value) > self.max_length:
            self.error('Too many items in the list')

rawDescription: Limit length of ListField in mongoengine


code:
while True:
    input_string = input("Enter a string")
    if len(set(input_string)) == len(input_string):
        break
    print("Please avoid repeating any characters")

rawDescription: How to check if every character of the string is different?

description: Check if every character of the string is different


code:
import re
def getNthStartingPosOfPattern(pattern, text, n):
    for i,x in enumerate(re.finditer(pattern, text)):
        if i == n-1:
            return x.start()

text = "09834 82 Monkey-wtf 2323, 8371853 Monkey-wtf 244, 39082348 Monkey-ftw 827,2  Monkey-lbj 2,24857 Monkey-kkk,oo293 Monkey-iij 55, 273 Monkey-eif 7,22288888 Monkey-abc"
pattern = r'Monkey-[a-z]{3}'
print(getNthStartingPosOfPattern(pattern, text, 5))

rawDescription: How to Find The Starting Position of the Nth Match of A Regular Expression in Python?


code: [s.strip() for s in input_line[1:-1].split(',')]

rawDescription: python convert str to list

description: Python convert str to list


code:
from django import forms

from . import models

class DriftwoodForm(forms.ModelForm):
    class Meta:
        model = models.Driftwood
        fields = ('user', 'title', 'description', 'image')

    image = forms.ImageField()

rawDescription: Django - ModelForm: Add a field not belonging to the model


code:
class BlogPostAdmin(model_admin):

    def save_model(self, request, instance, form, change):
        user = request.user
        instance = form.save(commit=False)
        if not change or not instance.author:
            instance.author = user
        instance.save()
        form.save_m2m()
        return instance

rawDescription: Getting current logged_in user in Django


code:
with open(filename) as f:
    for num, line in enumerate(f, 1):
        if 'that/' in line:
            myString = line
            where_is_that = myString.find('that/')
            mySub = myString[where_is_that:myString.find(' ', where_is_that)]
            print(mySub, str(num))
            formattedLines.append(mySub + ' ' + str(num) + '\n')

rawDescription: Finding string in text file, and then printing several characters beyond that in Python


code:
import json

posts = (Post.objects.filter(owner=authenticated_user)
                     .values('id', 'title', 'summary'))
json_posts = json.dumps(list(posts))

rawDescription: Django Serialize Queryset to JSON to construct RESTful response with only field information and id


code:
import fileinput

for line in fileinput.input():
    process(line)

rawDescription: Treat multiple text files as one big file


code:
#! /usr/bin/env python3

"""Cell Phone Self-Diagnoses Program

The following program is designed to help users to fix problems that they may
encounter while trying to use their cells phones. It asks questions and tries
to narrow down what the possible cause of the problem might be. After finding
the cause of the problem, a recommended action is provided as an attempt that
could possibly fix the user's device."""

# This is a database of questions used to diagnose cell phones.
ROOT = 0
DATABASE = {
            # The format of the database may take either of two forms:
            # LABEL: (QUESTION, GOTO IF YES, GOTO IF NO)
            # LABEL: ANSWER
            ROOT: ('Does your phone turn on? ', 1, 2),
            1: ('Does it freeze? ', 11, 12),
            2: ('Have you plugged in a charger? ', 21, 22),
            11: ('Did you drop your device in water? ', 111, 112),
            111: 'Do not charge it and take it to the nearest specialist.',
            112: 'Try a hard reset when the battery has charge.',
            12: 'I cannot help you with your phone.',
            21: 'Charge it with a different charger in a different phone '
                'socket.',
            22: ('Plug it in and leave it for 20 minutes. Has it come on? ',
                 221, 222),
            221: ('Are there any more problems? ', 222, 2212),
            222: ('Is the screen cracked? ', 2221, 2222),
            2212: 'Thank you for using my troubleshooting program!',
            2221: 'Replace in a shop.',
            2222: 'Take it to a specialist.'
            }

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

def main():
    """Help diagnose the problems with the user's cell phone."""
    verify(DATABASE, ROOT)
    welcome()
    ask_questions(DATABASE, ROOT)

def verify(database, root):
    """Check that the database has been formatted correctly."""
    db, nodes, visited = database.copy(), [root], set()
    while nodes:
        key = nodes.pop()
        if key in db:
            node = db.pop(key)
            visited.add(key)
            if isinstance(node, tuple):
                if len(node) != 3:
                    raise ValueError('tuple nodes must have three values')
                query, positive, negative = node
                if not isinstance(query, str):
                    raise TypeError('queries must be of type str')
                if len(query) < 3:
                    raise ValueError('queries must have 3 or more characters')
                if not query[0].isupper():
                    raise ValueError('queries must start with capital letters')
                if query[-2:] != '? ':
                    raise ValueError('queries must end with the "? " suffix')
                if not isinstance(positive, int):
                    raise TypeError('positive node names must be of type int')
                if not isinstance(negative, int):
                    raise TypeError('negative node names must be of type int')
                nodes.extend((positive, negative))
            elif isinstance(node, str):
                if len(node) < 2:
                    raise ValueError('string nodes must have 2 or more values')
                if not node[0].isupper():
                    raise ValueError('string nodes must begin with capital')
                if node[-1] not in {'.', '!'}:
                    raise ValueError('string nodes must end with "." or "!"')
            else:
                raise TypeError('nodes must either be of type tuple or str')
        elif key not in visited:
            raise ValueError('node {!r} does not exist'.format(key))
    if db:
        raise ValueError('the following nodes are not reachable: ' +
                         ', '.join(map(repr, db)))

def welcome():
    """Greet the user of the application using the provided name."""
    print("Welcome to Sam's Phone Troubleshooting program!")
    name = input('What is your name? ')
    print('Thank you for using this program, {!s}.'.format(name))

def ask_questions(database, node):
    """Work through the database by asking questions and processing answers."""
    while True:
        item = database[node]
        if isinstance(item, str):
            print(item)
            break
        else:
            query, positive, negative = item
            node = positive if get_response(query) else negative

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

if __name__ == '__main__':
    main()

rawDescription: How do you add a list to jump to a line on my code?

description: Add a list to jump to a line on my code


code:
import wx
class MyForm(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Toggle")
        panel = wx.Panel(self, wx.ID_ANY)
        self.button = wx.ToggleButton(panel, label="Press Me")
        self.button.Bind(wx.EVT_TOGGLEBUTTON, self.onToggle)
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.button, 0, wx.ALL, 5)
        panel.SetSizer(sizer)

    def onToggle(self, event):
        if self.button.GetValue() == True:
            self.button.SetLabel("On")
        else:
            self.button.SetLabel("Off")

if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

rawDescription: How do I change the style of a toggle button in wxPython?

description: Change the style of a toggle button in wxPython


code: [tuple(x.split(',')) for x in a]

rawDescription: Assigning comma separated strings to an array of tuples - python, numpy


code: etree.tostring(root, method="html")

rawDescription: Override lxml behavior to write a closing and opening element for Null tags


code:
def collatz(n):

    templist = [n]
    while (n > 1):
        if n % 2 == 0:
            n=int(n**0.5)
        else:
            n=int(n**1.5)
        if n == 1:
            templist.append(1)
        else:
            templist.append(n)
    print(templist)

rawDescription: How can I print my outcome as a list?

description: Print my outcome as a list


code:
import sys
from PyQt4 import QtCore, QtGui

class Tree(QtGui.QTreeWidget):
    ENUM_COMBOBOX = 1
    ENUM_LINEEDIT = 2
    def __init__(self, *args, **kwargs):
        super(Tree, self).__init__()
        for each in ['Item_1','Item_2','Item_3','Item_4','Item_5']:
            item=QtGui.QTreeWidgetItem([each])
            self.addTopLevelItem(item)
            self.setItemWidget(item, self.ENUM_COMBOBOX, QtGui.QComboBox())
            self.setItemWidget(item, self.ENUM_LINEEDIT, QtGui.QLineEdit())
        self.setColumnCount(5)
        self.resize(360,240)
        self.show()
        self.connect(self, QtCore.SIGNAL('itemClicked (QTreeWidgetItem *, int)'), self.itemClickedEvent)

    def itemClickedEvent (self, currentQTreeWidgetItem, column):
        currentQWidget = self.itemWidget(currentQTreeWidgetItem, self.ENUM_LINEEDIT)
        currentQWidget.setFocus()

app = QtGui.QApplication([])
tree=Tree()
sys.exit(app.exec_())

rawDescription: How to select all QTreeWidgetItem widgets automatically

description: Select all QTreeWidgetItem widgets automatically


code:
import Tkinter as tk

class Application(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.text = tk.Text(self, wrap="word", height=20)
        self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview)
        self.text.configure(yscrollcommand=self.vsb.set)
        self.vsb.pack(side="right", fill="y")
        self.text.pack(side="left", fill="both", expand=True)

        self.text.bind("<Return>", self.process_input)
        self.prompt = ">>> "

        self.insert_prompt()

    def insert_prompt(self):
        # make sure the last line ends with a newline; remember that
        # tkinter guarantees a trailing newline, so we get the
        # character before this trailing newline ('end-1c' gets the
        # trailing newline, 'end-2c' gets the char before that)
        c = self.text.get("end-2c")
        if c != "\n":
            self.text.insert("end", "\n")
        self.text.insert("end", self.prompt, ("prompt",))

        # this mark lets us find the end of the prompt, and thus
        # the beggining of the user input
        self.text.mark_set("end-of-prompt", "end-1c")
        self.text.mark_gravity("end-of-prompt", "left")

    def process_input(self, event=None):
        # if there is an event, it happened before the class binding,
        # thus before the newline actually got inserted; we'll
        # do that here, then skip the class binding.
        self.text.insert("end", "\n")
        command = self.text.get("end-of-prompt", "end-1c")
        self.text.insert("end", "output of the command '%s'...!" % command)
        self.text.see("end")
        self.insert_prompt()

        # this prevents the class binding from firing, since we
        # inserted the newline in this method
        return "break"

root = tk.Tk()
root.wm_geometry("400x100")
app = Application(root).pack(side="top", fill="both", expand=True)

root.mainloop()

rawDescription: Tkinter Input and Output in One Widget

description: Tkinter Input and Output in One Widget


code:
from zope.publisher.browser import BrowserView
from zope.component import getMultiAdapter

class DispatchingView(BrowserView):
    def __call__(self):
        if somecondition:
            newviewname = 'foo'
        else:
            newviewname = 'bar'

        return getMultiAdapter((self.context, self.request), name=newviewname)()

rawDescription: Custom views for ATDocuments created through GenericSetup


code:
import itertools

def my_long_operation():
    return itertools.chain(do_something(), do_something_else())

rawDescription: Long polling in Django

description: Long polling in Django


code:
from string import digits, punctuation

def create_dictionary():

    words = set()

    bad_char = digits + punctuation + '...' # may need more characters
    replace = ' ' * len(bad_char)
    table = str.maketrans(bad_char, replace)

    with open('frankenstein.txt') as infile:
        for line in infile:
            line = line.strip().translate(table)
            for word in line.split():
                if len(word) > 2:
                    words.add(word)

    with open('dictionary.txt', 'w') as outfile:
        outfile.writelines(sorted(words)) # note 'lines'

rawDescription: How can I simplify and format this function?

description: Simplify and format this function


code:
class user(db.Model):
    ...
    def put(self, *args, **kw):
        if self.isFromUK:
            if not self.fromCountry:
                raise ValueError("Need fromCountry if isFromUK..")
        super(user, self).put(*args, **kwargs)

rawDescription: GAE require model property iff another has a certain value?


code:
a = {'test': 1, 'key': 1, 'other': 2}
b = [k for k, it in itertools.groupby(sorted(a.values()))]
print(b)

rawDescription: Python 34: Is there something simple like a set for un-hashable objects


code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    customSignal = QtCore.pyqtSignal()

    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.edit = QtGui.QLineEdit(self)
        self.edit.textChanged.connect(self.handleTextChanged)
        self.button = QtGui.QPushButton(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.edit)
        layout.addWidget(self.button)
        self.machine = QtCore.QStateMachine()
        self.off = QtCore.QState()
        self.off.assignProperty(self.button, 'text', 'Off')
        self.on = QtCore.QState()
        self.on.assignProperty(self.button, 'text', 'On')
        self.foo = QtCore.QState()
        self.foo.assignProperty(self.button, 'text', 'Foo')
        self.off.addTransition(self.button.clicked, self.on)
        self.on.addTransition(self.button.clicked, self.foo)
        self.foo.addTransition(self.customSignal, self.off)
        self.machine.addState(self.off)
        self.machine.addState(self.on)
        self.machine.addState(self.foo)
        self.machine.setInitialState(self.off)
        self.machine.start()

    def handleTextChanged(self, text):
        if text == 'foo':
            self.edit.clear()
            self.customSignal.emit()

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    window.setGeometry(500, 300, 100, 100)
    sys.exit(app.exec_())

rawDescription: how to use a custom signal with QStateMachine addtransition

description: Use a custom signal with QStateMachine addtransition


code:
def drawArrow(A, B):
    plt.arrow(A[0], A[1], B[0] - A[0], B[1] - A[1],
              head_width=3, length_includes_head=True)

rawDescription: matplotlib arrows between 3 points

description: Matplotlib arrows between 3 points


code:
import sys # you don't need StringIO if you're reading the data from a file
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO
import pandas as pd

dfstr = StringIO(""" | Model  | Company  | Url  | Criteria              |    Rating
1| Mode11 | Company1 | Url1 |[Criteria1, Criteria2] | [Rating1 , Rating2]
2| Mode12 | Company2 | Url2 |[Criteria4, Criteria5] | [Rating4, Rating5]""")
df = pd.DataFrame.from_csv(dfstr, sep='|')
df.columns = ['Model','Company','Url','Criteria','Rating'] # no whitespace

def slist(listish): # list-without-quotes is kind of a pain
    return listish.strip(' []').split(', ')

def row2df(oldrow): # make a little sub-DataFrame for each row
    tmp = pd.DataFrame(zip(slist(row[1].Criteria),slist(row[1].Rating)))
    for val in ['Model','Company','Url']:
        tmp[val] = row[1][val]
    return tmp

outdf = pd.concat([row2df(row) for row in df.iterrows()]) # and stick them together
outdf.index = outdf[0] # index on the Criteria
outdf.drop(0, axis=1,inplace=True)
outdf.columns = ['Rating','Model','Company','Url'] # tidy up the names
print(outdf)

rawDescription: How to split a pandas dataframe that contains lists as fields into a multi-indexed dataframe?

description: Split a pandas dataframe that contains lists as fields into a multi-indexed dataframe


code:
from Tkinter import *
from tkFileDialog import *

class trip_calculator:

    def gui(self):

        returned_values = {}

        def open_file_dialog():
            returned_values['filename'] = askopenfilename()

        root = Tk()
        Button(root, text='Browse', command= open_file_dialog).pack()

        root.mainloop()

        filepath = returned_values.get('filename')
        return filepath

        root.quit()

print(trip_calculator().gui())

rawDescription: Python TkInter Button Command Return

description: Python TkInter Button Command Return


code:
from django.forms import inlineformset_factory

MembershipFormSet = inlineformset_factory(Group, Membership, fields=(
    'person', 'date_joined', 'invite_reason'))
group = Group.objects.get(pk=group_id)
formset = MembershipFormSet(instance=group)

rawDescription: Django M2MFields 'through' widgets

description: Django M2MFields 'through' widgets


code:
import IPython.nbformat.current as nbf
nb = nbf.read(open('test.py', 'r'), 'py')
nbf.write(nb, open('test.ipynb', 'w'), 'ipynb')

rawDescription: Is there a way to create a .ipynb from a .py file command line?


code: output = StringIO.StringIO(r.content)

rawDescription: Python str to file type

description: Python str to file type


rawDescription: Name of variable in python and program efficiency


rawDescription: Return index of every non-zero element in array


code:
def makeLimitedInt(minimum, maximum, default):
    class LimitedInt(int):
        def __new__(cls, x= default, *args, **kwargs):
            instance= int.__new__(cls, x, *args, **kwargs)
            if not minimum<=instance<=maximum:
                raise ValueError('Value outside LimitedInt range')
            return instance
    return LimitedInt

rawDescription: Extending Python’s int type to accept only values within a given range


code:
import hashlib
actually_random = hashlib.sha1(uuid).digest()

rawDescription: Can I make uuid's more random?

description: Make uuid's more random


rawDescription: Switching to ipython for python3?

description: Switching to ipython for python3


code:
from datetime import datetime, timedelta
import time

# Get today's datetime
dtnow = datetime.now()

# Create datetime variable for 6 AM
dt6 = None

# If today's hour is < 6 AM
if dtnow.hour < 6:

    # Create date object for today's year, month, day at 6 AM
    dt6 = datetime(dtnow.year, dtnow.month, dtnow.day, 6, 0, 0, 0)

# If today is past 6 AM, increment date by 1 day
else:

    # Get 1 day duration to add
    day = timedelta(days=1)

    # Generate tomorrow's datetime
    tomorrow = dtnow + day

    # Create new datetime object using tomorrow's year, month, day at 6 AM
    dt6 = datetime(tomorrow.year, tomorrow.month, tomorrow.day, 6, 0, 0, 0)

# Create timestamp from datetime object
timestamp = time.mktime(dt6.timetuple())

print(timestamp)

rawDescription: How to convert tomorrows (at specific time) date to a timestamp

description: Convert tomorrows (at specific time) date to a timestamp


code:
import numpy as np, copy
import matplotlib.pyplot as plt, matplotlib.lines as ml

fig=plt.figure(1)
data=np.arange(0,10,0.01)
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
ax4=fig.add_subplot(2,2,4)

#create the lines
line1=ml.Line2D(data,data)
line2=ml.Line2D(data,data**2/10,ls='--',color='green')
line3=ml.Line2D(data,np.sin(data),color='red')
#add the copies of the lines to the first 3 panels
ax1.add_line(copy.copy(line1))
ax2.add_line(copy.copy(line2))
ax3.add_line(copy.copy(line3))

[ax4.add_line(_l) for _l in [line1,line2,line3]] # add 3 lines to the 4th panel

[_a.autoscale() for _a in [ax1,ax2,ax3,ax4]] # autoscale if needed
plt.draw()

rawDescription: How do I reuse plots in matplotlib?

description: Reuse plots in matplotlib


code:
import multiprocessing

manager = multiprocessing.Manager()
a_shared_big_dictionary = manager.dict(a_big_dictionary)

po = multiprocessing.Pool()
for elements in a_list:
    results.append(po.apply_async(my_module.my_function, (some_arguments, elements, a_shared_big_dictionary)))
po.close()
po.join()
for r in results:
    a_new_list.add(r.get())

rawDescription: Giving a large dictionary to a async function is making the code very slow


code:
import sqlite3

conn = sqlite3.connect('boo2.db')
c = conn.cursor()

x=c.execute("SELECT * FROM sqlite_master where type='table'")

for y in x.fetchall():
    print(y)

rawDescription: How to display all the tables created in sqlite database on python3

description: Display all the tables created in sqlite database on python3


code: T.switch(T.eq(self.squared_euclidean_distances, 0), 0, c / self.squared_euclidean_distances)

rawDescription: How to prevent division by zero or replace infinite values in Theano?

description: Prevent division by zero or replace infinite values in Theano


code:
class IMAP4_SSL_CA_CHECKER(IMAP4_SSL):
    def open(self, host = '', port = IMAP4_SSL_PORT, ca_certs = None):
        self.host = host
        self.port = port
        self.sock = socket.create_connection((host, port))
        self.sslobj = ssl.wrap_socket(self.sock, self.keyfile,
                          self.certificate, ca_certs=ca_certs)
        self.file = self.sslobj.makefile('rb')

rawDescription: Certificate Authority for imaplib and poplib python


rawDescription: How to do & operation on binary no.(0b1100) and bin(4)?

description: Do & operation on binary no.(0b1100) and bin(4)


code:
#!/usr/python
import cgi
print('Content-Type: text/html; charset=utf-8\n')
form = cgi.FieldStorage()

if 'name' in form:
    with open('/var/www/cgi-bin/temp.txt','w') as file:
        file.write(form['name'])

rawDescription: how read data in python script called from javascript post

description: How read data in python script called from javascript post


code: cursor.execute("INSERT INTO registrants VALUES( " + "'" + first_name.strip() + "'" + ", " + "'" + last_name.strip() + "'" + ");")

rawDescription: How to trim white space in MySQLdb using python

description: Trim white space in MySQLdb using python


code:
import re
name = 'XYZ'
value = '5'
content = 'XYZ.Value = 5'
print(re.sub(r'(%s\.Value\s*=\s*)([^;]+)' %name, r'\g<1>' + value, content))
# => XYZ.Value = 5

rawDescription: re.sub group value

description: Re.sub group value


code:
import wx

db = [
          {"id": 1, "name_link": "Video 1", "link": "C:\\first_video.mp4"},
          {"id": 2, "name_link": "Video 2", "link": "C:\\second_video.mp4"},
          {"id": 3, "name_link": "Video 3", "link": "C:\\third_video.mp4"},
      ]

class MyFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, parent=None, title="List of Videos")

        self.opt = wx.ListBox(self)
        self.fillOpt()

        self.opt.Bind(wx.EVT_LISTBOX_DCLICK, self.startVideo)
        self.Show()

    def fillOpt(self):
        for row in db:
            self.opt.Append(row['name_link'], row['link']) # Label, ClientData

    def startVideo(self, event):
        wx.MessageBox(parent=self, message=event.GetClientData(), caption="Video")

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

rawDescription: WX.EVT_LISTBOX_DCLICK click for different video


code:
import numpy as NP
import numpy.linalg as LA

# generate some data
fnx = lambda : NP.random.randint(0, 10, 10)
s1, s2 = fnx(), fnx()

# a function to calculate cosine similarity
cx = lambda a, b : round(NP.inner(a, b)/(LA.norm(a)*LA.norm(b)), 2)

cx(s1, s2)
# returns 0.85

rawDescription: Difference between data sets

description: Difference between data sets


code:
from flask import Flask, request
import librunner
app = Flask(__name__)
current_run = None

@app.route('/run', methods=['POST'])
def run():
    data = request.get_data()
    global current_run
    current_run = librunner.Run(data)
    output = current_run.get_output()
    # do something with output...
    current_run.run()
    return "Success!", 200, {'Content-Type': 'text/plain'}

@app.route('/running')
def running():
    result = False
    global current_run
    if current_run != None:
        result = current_run.is_running()
    return str(result), 200, {'Content-Type': 'text/plain'}

rawDescription: Flask, boost::python and threads

description: Flask, boost::python and threads


code:
dict(
    ('{t}.{c}'.format(t=h.table_name, c=h.column_name), h.position)
    for h in self.heading_set.all()
    )

rawDescription: Make map() return a dictionary

description: Make map() return a dictionary


code:
res1 = [[i for i in j if i] for j in res]
dictt = {}
[[dictt.__setitem__(i, dictt.setdefault(i, 0) + 1) for i in j] for j in res1]

rawDescription: deleting empty values from list inside list

description: Deleting empty values from list inside list


code:
from math import ceil

def week_of_month(dt):

    first_day = dt.replace(day=1)

    dom = dt.day
    adjusted_dom = dom + first_day.weekday()

    return int(ceil(adjusted_dom/7.0))

rawDescription: How to find out week no of the month in python?

description: Find out week no of the month in python


code:
from sympy import *
from sympy.abc import x, y, b
eq1 = Eq(x - 1/y - b, 0)
eq2 = Eq(2*x - y, 0)
solve([eq1, eq2], b)

rawDescription: How to define and solve mutually referencing expressions in SymPy

description: Define and solve mutually referencing expressions in SymPy


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

winterAzi = datafomPySolarAzi
winterAlt = datafromPySolarAlt

# create instance of basemap, note we want a south polar projection to 90 = E
myMap = Basemap(projection='spstere',boundinglat=0,lon_0=180,resolution='l',round=True,suppress_ticks=True)
# set the grid up
gridX,gridY = 10.0,15.0
parallelGrid = np.arange(-90.0,90.0,gridX)
meridianGrid = np.arange(-180.0,180.0,gridY)

# draw parallel and meridian grid, not labels are off. We have to manually create these.
myMap.drawparallels(parallelGrid,labels=[False,False,False,False])
myMap.drawmeridians(meridianGrid,labels=[False,False,False,False],labelstyle='+/-',fmt='%i')

# we have to send our values through basemap to convert coordinates, note -winterAlt
winterX,winterY = myMap(winterAzi,-winterAlt)

# plot azimuth labels, with a North label.
ax = plt.gca()
ax.text(0.5,1.025,'N',transform=ax.transAxes,horizontalalignment='center',verticalalignment='bottom',size=25)
for para in np.arange(gridY,360,gridY):
    x= (1.1*0.5*np.sin(np.deg2rad(para)))+0.5
    y= (1.1*0.5*np.cos(np.deg2rad(para)))+0.5
    ax.text(x,y,u'%i\N{DEGREE SIGN}'%para,transform=ax.transAxes,horizontalalignment='center',verticalalignment='center')

# plot the winter values
myMap.plot(winterX,winterY ,'bo')

rawDescription: Stereographic Sun Diagram matplotlib polar plot python


code:
import wx

class myframe(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, title='Test', size=(200,200))
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.SetDoubleBuffered(True)
        self.Show()

    def OnPaint(self, event):

        dc = wx.BufferedPaintDC(self)
        dc.Clear()

        dc.BeginDrawing()

        dc.SetBrush(wx.Brush(wx.RED, wx.SOLID))
        # dc.SetBrush(wx.Brush(wx.RED, wx.TRANSPARENT)) # when you dont want to fill

        dc.SetPen(wx.Pen(wx.NamedColour('cyan'), 1))

        #dc.DrawLines([(100,100), (120,100), (120,120), (100,120)]) # without fill, open end
        dc.DrawPolygon([(100,100), (120,100), (120,120), (100,120)])  # closed, filled

        dc.EndDrawing()

if __name__ == '__main__':

    app = wx.PySimpleApp(0)
    frame = myframe()
    app.MainLoop()

rawDescription: how can i fill Shape consist of lines and filled (wxpython)

description: Fill Shape consist of lines and filled (wxpython)