code:
from Tkinter import Tk, W, E
from ttk import Label, Button, Frame, Entry, Style
import sys
import matplotlib.figure as mplfig
import matplotlib.backends.backend_tkagg as tkagg
import numpy as np

class program(Frame):

    def __init__(self, main):

        Frame.__init__(self, main)
        self.main = main
        self.initUI()

    def initUI(self):

        self.main.title('COSINUSEK')
        Style().configure('TFrame', background='black')
        Style().configure('TLabel', background='black', foreground='blue')
        Style().configure("TButton", background='red', foreground='blue')

        self.rowconfigure(0, pad=3)
        self.rowconfigure(1, pad=3)
        self.rowconfigure(2, pad=3)
        self.rowconfigure(3, pad=3)
        self.rowconfigure(4, pad=3)

        self.columnconfigure(0, pad=3)
        self.columnconfigure(1, pad=3)
        self.columnconfigure(2, pad=3)
        self.columnconfigure(3, pad=3)
        self.columnconfigure(4, pad=3)

        label = Label(self, text='Give me range in degrees ').grid(
            row=0, column=3)
        od = Label(self, text='             From').grid(row=1, column=0)
        do = Label(self, text='             To').grid(row=1, column=4)
        self.entry = Entry(self, justify='center')
        self.entry.grid(row=2, column=0, columnspan=2, sticky=E + W)
        self.entry1 = Entry(self, justify='center')
        self.entry1.grid(row=2, column=4, columnspan=2, sticky=E)
        button = Button(
            self, text='Ok', command=self.ok).grid(row=3, column=3)
        button1 = Button(
            self, text='Draw', command=self.dra).grid(row=4, column=3)

        self.fig = mplfig.Figure(figsize=(5, 4), dpi = 100)
        self.ax = self.fig.add_subplot(111)
        self.canvas = tkagg.FigureCanvasTkAgg(self.fig, self.main)
        self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1)
        self.line = None
        self.pack()

    def run(self):
        self.main.mainloop()

    def ok(self):
        z = int(self.entry.get())
        w = int(self.entry1.get())
        self.x = np.arange(z, w, 0.01)
        self.y = np.cos((self.x * np.pi) / 180)

    def dra(self):
        self.ok()
        if self.line is not None:
            self.line.set_xdata(self.x)
            self.line.set_ydata(self.y)
        else:
            self.line = self.ax.plot(self.x, self.y)[0]
        self.ax.set_xlim(self.x.min(), self.x.max())
        self.ax.relim()
        self.ax.autoscale_view(True, True, True)

        self.fig.canvas.draw()

program(Tk()).run()

rawDescription: Cosinus graph drawing

description: Cosinus graph drawing


code:
sourceFileContents_utf8 = open(sourceFileName, 'r+').read()
sourceFileContents_unicode = sourceFileContents_utf8.decode('utf8')
print(len(sourceFileContents_unicode))

i = 0
source_file_contents_length = len(sourceFileContents_unicode)
while i < source_file_contents_length:
    print('%s %s' % (str(i), sourceFileContents[i]))
    i += 1

rawDescription: File contents not as long as expected

description: File contents not as long as expected


code:
def compose(f, g):
    return lambda x: f(g(x))

square = lambda x:x*2
g = square
for i in xrange(4):
    g = compose(g, square)

rawDescription: function making

description: Function making


rawDescription: Numpy splitting multidimensional arrays

description: Numpy splitting multidimensional arrays


code:
for row, r in enumerate(matrix):
    for col, c in enumerate(r):
        r[col] = 1               # Note `col`, not `c`

rawDescription: Iterate Across Columns in a List of Lists in Python


code:
c = df.corr()['m'].abs()
so = c.sort_values(kind='quicksort')
print(so)

rawDescription: Pandas correlation table limited to m columns by n rows


code:
categories = unipart.categories.exclude(
                 categorieschild__unipart = unipart).distinct()

rawDescription: Simplest way of eliminating objects from queryset in Django


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

data = np.arange(25)
data.shape = (5,5)

plt.imshow(data, interpolation='none', extent=(-3, 27, 5, 31))
plt.show()

rawDescription: How can I rescale axis without scaling the image in an image plot with matplotlib?

description: Rescale axis without scaling the image in an image plot with matplotlib


code:
...
with open("test.gcode","r+") as s:
    with open("test_replaced.gcode","a") as replaced:
        ...
print ("Done! - " + str(a) + " number of operations done!")
print ("Loopcount: " + str(b))

rawDescription: Python, read and write file is cutting final output file to limited number of lines?


code:
import functools
import time
import threading
import logging

import tornado.web
import tornado.websocket
import tornado.locale
import tornado.ioloop

class Handler(tornado.web.RequestHandler):
    def perform(self, callback):
        #do something cuz hey, we're in a thread!
        time.sleep(5)
        output = 'foo'
        tornado.ioloop.IOLoop.instance().add_callback(functools.partial(callback, output))

    def initialize(self):
        self.thread = None

    @tornado.web.asynchronous
    def get(self):
        self.thread = threading.Thread(target=self.perform, args=(self.on_callback,))
        self.thread.start()

        self.write('In the request')
        self.flush()

    def on_callback(self, output):
        logging.info('In on_callback()')
        self.write("Thread output: %s" % output)
        self.finish()

application = tornado.web.Application([
    (r"/", Handler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Where to join threads created in an asynchronous tornado request handler?


code:
import numpy as np
from shapely.geometry import MultiLineString
from shapely.ops import polygonize

x = np.linspace(-5, -1, 8)
y = np.linspace(1, 5, 8)

hlines = [((x1, yi), (x2, yi)) for x1, x2 in zip(x[:-1], x[1:]) for yi in y]
vlines = [((xi, y1), (xi, y2)) for y1, y2 in zip(y[:-1], y[1:]) for xi in x]

grids = list(polygonize(MultiLineString(hlines + vlines)))

rawDescription: numpy meshgrid to Shapely polygons

description: Numpy meshgrid to Shapely polygons


code:
import numpy
a = numpy.array([1, 2, 'a'], dtype=object) # makes type of array what you need
numpy.equal(a, None)

rawDescription: numpy.equal with string values

description: Numpy.equal with string values


code:
@login_required(login_url='/')
def course(request):
    data = Students.objects.all()
    return render(request, 'login/course.html', {'data': data})

rawDescription: Only allowing authenticated users to access certain pages in django


code:
keys = [ x.key for x in objects ]
subset = [ x for x in myobj if x.key in keys ]

rawDescription: python get elements by checking keys in another list

description: Python get elements by checking keys in another list


code:
import arabic_reshaper
from bidi.algorithm import get_display

#...
reshaped_text = arabic_reshaper.reshape(u'اللغة العربية رائعة')
bidi_text = get_display(reshaped_text)
pass_arabic_text_to_render(bidi_text)
#...

rawDescription: pyfribidi for windows or any other bidi algorithm

description: Pyfribidi for windows or any other bidi algorithm


code: Truncator(value).words(length, html=True, truncate=' ...')

rawDescription: Shortening HTML content python / django

description: Shortening HTML content python / django


code:
import re
import fileinput
from glob import glob

dir_prefix = '.'
glob_pattern = '{}/periodic_table/*_lj_dat/lj_dat_sim.dat'.format(dir_prefix)
element_pattern = re.compile(r'.*periodic_table/(.+)_lj_dat/lj_dat_sim.dat')

with open('mergedlj.dat', 'w') as outfile:
    element = ''
    for line in fileinput.input(glob(glob_pattern)):
        if fileinput.isfirstline():
            # extract the element name from the file name
            element = element_pattern.match(fileinput.filename()).groups()[0]
        else:
            print(' '.join([element, line]), end='', file=outfile)

rawDescription: Execute multiple *.dat files from subdirectories (bash, python)


code:
from nltk.corpus import PlaintextCorpusReader
from nltk.text import Text

# For example, I create an example text file
text1 = '''
This is a story about a foo bar. Foo likes to go to the bar and his last name is also bar. At home, he kept a lot of gold chocolate bars.
'''
text2 = '''
One day, foo went to the bar in his neighborhood and was shot down by a sheep, a blah blah black sheep.
'''
texts = ['text1','text2']
corpusdir = './mycorpus' # the directory where you keep the corpus
for i, t in enumerate(texts):
    outfilename = 'text'+str(i)+'.txt'
    print>>open(corpusdir+outfilename,'w'), t

# Read the the example corpus into NLTK's corpus class.
mycorpus = PlaintextCorpusReader(corpusdir, '.*')

# Read the NLTK's corpus into NLTK's text class,
# where your book-like concoordance search is available
mytext = Text(mycorpus.words())

mytext.concoordance('foo')

rawDescription: How do I use the book functions (e.g. concoordance) in NLTK?

description: Use the book functions (e.g. concoordance) in NLTK


code:
import subprocess

sp = subprocess.Popen("PATH_TO_CHROME\chrome")
#If you want your process to wait for chrome to "complete"
ret_val = sp.wait()
#or
sp_out, sp_error = sp.communicate()

rawDescription: How to launch an external program in a python script

description: Launch an external program in a python script


code:
lowerNick = lower(player['nick'])
...
cursor.execute('SELECT yes FROM newstats WHERE nick = %s ORDER BY totalgames DESC LIMIT 1', [lowerNick] )
...
cursor.execute('UPDATE newstats SET totalgames = totalgames + 1, wins = wins + 1, medicgames = medicgames + 1, medicwins = medicwins +1 WHERE nick = %s', [lowerNick])
...
cursor.execute('UPDATE newstats SET totalgames = totalgames + 1, wins = wins + 1 WHERE nick = %s', [lowerNick])

rawDescription: Python threading with Postgres: things are not being updated properly


rawDescription: pylab scilimits not working

description: Pylab scilimits not working


rawDescription: Slicing a numpy array

description: Slicing a numpy array


code: os.system("7z x install.zip subfolder -y -r -oc:\\\"Program Files (x86)\\\"Calibre2")

rawDescription: Extracting only a specific subfolder 7zip


code:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)))

# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(im, cax=cax)

rawDescription: Set Matplotlib colorbar size to match graph


code:
import itertools
lst = range(1,5)
list(itertools.chain.from_iterable(itertools.repeat(x, 3) for x in lst))

Out[8]: [1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

rawDescription: Repeating elements of a list n times

description: Repeating elements of a list n times


rawDescription: Python, print delimited list

description: Python, print delimited list


code:
def dispatch(self, request, *args, **kwargs):
  url = request.REQUEST['url']
  host = urlparse.urlparse(url).netloc.lower().strip()

  domains = Domain.objects.filter(domain=host)
  if len(domains):
    return super(ProcessRequestView, self).dispatch(request, *args, **kwargs)
  else:
    newHost = '.%s' %host
    dotPosition = -1
    for i in range(newHost.count('.')):
      dotPosition = newHost.find('.', dotPosition + 1)
      domains = Domain.objects.filter(domain=newHost[dotPosition:])
      if len(domains):
        return super(ProcessRequestView, self).dispatch(request, *args, **kwargs)

    return HttpResponseForbidden()

rawDescription: A Djangoic method of checking if it is an allowed subdomain


code:
import os
# ...
os = "abc"
# ...
os.path # <-- error

rawDescription: os.path.basename(path) what does "AttributeError: 'unicode' object has no attribute 'path'" mean?

description: Os.path.basename(path) what does "AttributeError: 'unicode' object has no attribute 'path'" mean


code:
from django.db import IntegrityError

class MyTemporaryObject(models.Model):
    auto_pseudoid = models.CharField(max_length=16, blank=True, editable=False, unique=True)
    # add index=True if you plan to look objects up by it
    # blank=True is so you can validate objects before saving - the save method will ensure that it gets a value

    # other fields as desired

    def save(self, *args, **kwargs):
        if not self.auto_pseudoid:
            self.auto_pseudoid = generate_random_alphanumeric(16)
            # using your function as above or anything else
        success = False
        failures = 0
        while not success:
            try:
                super(MyTemporaryObject, self).save(*args, **kwargs)
            except IntegrityError:
                 failures += 1
                 if failures > 5: # or some other arbitrary cutoff point at which things are clearly wrong
                     raise
                 else:
                     # looks like a collision, try another random value
                     self.auto_pseudoid = generate_random_alphanumeric(16)
            else:
                 success = True

rawDescription: Generate a random alphanumeric string as a primary key for a model


code:
num = 10
top = np.argpartition(myBigArray, num, axis=1)[:, :num]
myBigArray[np.arange(myBigArray.shape[0])[:, None], top]

rawDescription: How to apply the output of numpy.argpartition for 2-D Arrays?

description: Apply the output of numpy.argpartition for 2-D Arrays


code:
from itertools import combinations
a=[comb for comb in combinations(range(1,27+1), 6) if sum(comb) == 27]
print(a+"\n")

rawDescription: Finding possible combinations of number with 6 dim


code:
class Test(cmd.Cmd):
    # ...
    def cmdloop(self):
        cmd.Cmd.cmdloop(self)
        return self.value

rawDescription: cmd.Cmd object doesn't return any value

description: Cmd.Cmd object doesn't return any value


rawDescription: Candlestick charts with two scales

description: Candlestick charts with two scales


code:
from itertools import izip

file1 = 'data_files/titles.csv'
file2 = 'import_this_file_into_wordpress.csv'
dest = 'combined.csv'

with open(file1) as f1, open(file2) as f2, open(dest, 'w') as dest:
    for [part1, part2] in izip(f1, f2):
        dest.write("%s,%s" % (part1.rstrip(), part2))

rawDescription: Python Append Data Line By Line To Second Column Of CSV File


code:
from distutils.core import setup
from pkgutil import walk_packages

import mypackage

def find_packages(path=__path__, prefix=""):
    yield prefix
    prefix = prefix + "."
    for _, name, ispkg in walk_packages(path, prefix):
        if ispkg:
            yield name

setup(
    # ... snip ...
    packages = list(find_packages(mypackage.__path__, mypackage.__name__)),
    # ... snip ...
)

rawDescription: make distutils in Python automatically find packages

description: Make distutils in Python automatically find packages


code:
def accumulate(xs, f):
    return reduce(lambda a, x: a + [f(a[-1], x)], xs[1:], [xs[0]])

description: Itertools.accumulate() versus functools.reduce()


code:
from tkinter import *
import threading, time

class Threader(threading.Thread):

    def __init__(self, *args, **kwargs):

        threading.Thread.__init__(self, *args, **kwargs)
        self.daemon = True
        self.start()

    def run(self):

         while True:
            print("Look a while true loop that doesn't block the GUI!")
            print("Current Thread: %s" % self.name)
            time.sleep(1)

if __name__ == '__main__':

    root = Tk()
    leftFrame = Frame(root)
    leftFrame.pack(side=LEFT)
    rightFrame = Frame(root)
    rightFrame.pack(side=RIGHT)
    playButton = Button(leftFrame, text="Play", fg="blue",
        command= lambda: Threader(name='Play-Thread'))
    stopButton = Button(rightFrame, text="Stop", fg="red",
        command= lambda: Threader(name='Stop-Thread'))
    playButton.pack(side=TOP)
    stopButton.pack(side=BOTTOM)
    root.mainloop()

rawDescription: Python, Tkinter: how can I prevent tkinter gui mainloop crash using threading


code:
mystring = "python"
list_output = ["on", "p", "h", "yt"]
sorted(list_output, key=mystring.index)

rawDescription: Sorting list to match its ordering to a string


code:
if __name__ == '__main__':
    dictionary = populateprimelist()
    print(dictionary)

rawDescription: Python function does not call in __init__


code:
class Foo(object):
    def __init__(self):
        self.someAttr = 10

rawDescription: How to find attributes of a python user-defined class?

description: Find attributes of a python user-defined class


code:
my_list = [['a', 'b', 1], ['a', 'c', 2], ['b', 'a', 3], ['b', 'c', 4]]
my_dict = {}
for item in my_list:
    try:
        my_dict[item[0]].update({item[1]: item[2]})
    except KeyError:
        my_dict[item[0]] = {item[1]: item[2]}

my_dict

rawDescription: How to convert list of list to dict of dict in Python

description: Convert list of list to dict of dict in Python


code:
class PersonModel(Base):
    ...
    job = relationship('JobModel', lazy='joined')

rawDescription: How to avoid two queries and replace with join?

description: Avoid two queries and replace with join


code:
import numpy
import matplotlib.pyplot as plt

good = np.array([0, 1, 28, 144, 0, 41, 23, 5, 7, 2, 3, 9, 48])
bad = np.array([0, 1, 28, 144, 0, 41, 23, 5, 7, 2, 3, 9, 48])
keys = np.array([u'gaming', u'recreation', u'business', u'computer_internet',
                 u'unknown', u'culture_politics', u'science_technology',
                 u'law_crime', u'sports', u'religion', u'weather',
                 u'health', u'arts_entertainment'])
ind = np.arange(1, len(keys) + 1)

order = np.argsort(good + bad)
good, bad, keys = good[order], bad[order], keys[order]

c2 = '#FF7777'
c1 = '#7777FF'
p1 = plt.barh(ind, good, color=c1, align="center", label="good")
p2 = plt.barh(ind, bad, color=c2, left=good, align="center", label="bad")

plt.xlabel('Number of URLs scanned')
plt.yticks(ind, keys)
plt.legend(loc="center right")
plt.tight_layout()

rawDescription: matplotlib.pyplot overlaying axis labels on bars

description: Matplotlib.pyplot overlaying axis labels on bars


code:
from math import ceil

batch_size = 1000

for start_at in range(int(ceil(total_rows / 1000 * 1.0))):
    sql = 'SELECT `id` from `RECORDS` ORDER BY `id` DESC LIMIT %i, %i'
    sql = sql % (start_at * batch_size, batch_size)
    # fetch rows

rawDescription: PyMySQL: Query with large number of rows failing


code:
@csrf_protect
def register(request, extra_context=None):
    if request.method == 'POST':

        user_form = AddUserForm(data=request.POST, files=request.FILES)
        user_profile_form = AddUserProfileForm(data=request.POST, files=request.FILES)

        if user_form.is_valid() and user_profile_form.is_valid():
            new_user = user_form.save(request.get_host())
            new_user_profile = user_profile_form.save(request.get_host(), new_user)
            return HttpResponseRedirect(reverse('registration_complete'))
    else:
        user_form = AddUserForm()
        user_profile_form = AddUserProfileForm()

    context = {}
    return render_to_response('registration_form.html',
                            {   'user_form': user_form,
                                'user_profile_form': user_profile_form },
                            context_instance=context)

rawDescription: How to combine 2 forms for use on the same page?

description: Combine 2 forms for use on the same page


code:
fp = open("data.txt", "r")
data = fp.read();

data = data.split(">");

i = 0;

while True:
    filename = data[i].split('" ')[1].split('"')[1]
    text = data[i+1].split('<')[0].strip()

    fp1 = open(filename + ".txt", "w")
    fp1.write(text)
    fp1.close()

    i += 2
    if i >= (len(data) - 1):
        break;

rawDescription: Python extract data from file and write to another


rawDescription: Pandas - Plotting series

description: Pandas - Plotting series


code:
def unencodeRLE(i):
    i = list(i) #Copies the list to a new list, so the original one is not changed.
    r = []

    while i:
        count = i.pop(0)
        n = i.pop(0)
        r+= [n for _ in xrange(count)]
    return r

rawDescription: Decompress an array in Python

description: Decompress an array in Python


code:
driver.execute_script("for(var i = 0; i < document.links.length; i++){document.links[i].onclick = function clicked(){var e = document.createElement('a'); e.setAttribute('id','myUniqueID'); e.setAttribute('value', this); document.getElementsByTagName('body')[0].appendChild(e);};}")

clicked = driver.find_element_by_id('myUniqueID').get_attribute('value')

rawDescription: Firefox + Selenium in python: How to interactively get an element html?


code:
# -*- coding: utf-8 -*-
from robot.libraries.BuiltIn import BuiltIn

class global_hooks(object):
    """
        Global scope library listener
        as global hook mechanism.
    """

    ROBOT_LISTENER_API_VERSION = 3
    ROBOT_LIBRARY_SCOPE = "GLOBAL"

    def __init__(self):
        self.ROBOT_LIBRARY_LISTENER = self

    def __log_variables(self):
        """
            Example private function.
        """
        if BuiltIn().get_variable_value(name='${SOME_VAR}', default=False):
            BuiltIn().run_keyword(name=self.log_test_variables.__name__)

    def end_test(self, data, result):
        """ The `end test` hook """

        self.__log_variables()

    def log_test_variables(self):
        """
            Keyword for showing up all variables in the test context.
        """

        BuiltIn().log_variables(level='INFO')

rawDescription: Global test hook or global test teardown for each test in robot framework


rawDescription: Do dictionaries in Python have a single repr value?


code:
Base = declarative_base()

class A(Base):
    __tablename__ = 'a'

    id = Column(Integer, primary_key=True)

class B(Base):
    __tablename__ = 'b'

    id = Column(Integer, primary_key=True)
    a_id = Column(Integer, ForeignKey('a.id'))

    foobar = relationship('A')

    def __init__(self):
        self.foobar = A()

rawDescription: Mapping a class that contains references to another class


code:
from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

rawDescription: How to perform OR condition in django queryset?

description: Perform OR condition in django queryset


code:
groups = df.groupby(['code','colour']).groups
groups['one','white']

rawDescription: Pandas groupby: storing only indexes

description: Pandas groupby: storing only indexes


code:
ToKeep = (ListA != np.array(None))
ListA = ListA[ToKeep]
ListB = ListA[ToKeep]

rawDescription: Remove NoneType from two lists

description: Remove NoneType from two lists


code:
def deleteGridWidget(self, index):
    item = self.sa_grid.itemAt(index)
    if item is not None:
        widget = item.widget()
        if widget is not None:
            self.sa_grid.removeWidget(widget)
            widget.deleteLater()

rawDescription: Updating dynamic QGridLayout - Python PyQt


code:
class A(object):
    def test(self):
        print("I am A")

class B(object):
    def test(self, a1, a2):
        a1.test()
        a2.test()

a1 = A()
a2 = A()
b = B()
b.test(a1, a2)

rawDescription: Two the same type arguments in one class method in Python


code:
import math

def square():
    print ('What would you like to square?')

    user_input = raw_input('> ')

    try:
        number = float(user_input)
    except ValueError:
        print('You did not input a number!')
    else:
        print(math.sqrt(number))

square()

rawDescription: Im trying to make a square root function in python


rawDescription: Python MatplotLib plot x-axis with first x-axis value labeled as 1 (instead of 0)


code:
import json
null_list = [None]*10
null_list
json.dumps(null_list)

rawDescription: How to write a JS null to file in Python instead of 'null' as a string

description: Write a JS null to file in Python instead of 'null' as a string


code:
from gi.repository import Gio

setting = Gio.Settings.new("org.gtk.Settings.FileChooser")
setting.set_boolean("sort-directories-first", True)

rawDescription: Programmatically change FileChooserDialog to list directories first with Python 3.4 and Gtk3?


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

import wxversion
wxversion.select('3.0-classic', True)

import wx
from wx.lib.mixins.inspection import InspectionMixin

import wx.lib.sized_controls as sc

print(wx.VERSION_STRING)

class MySplashScreen(wx.SplashScreen):
    def __init__(self):
        #bmp =  wx.Image(opj(os.path.abspath(os.path.join(os.path.split(__file__)[0],"bitmaps","splash.png")))).ConvertToBitmap()
        bmp = wx.ArtProvider.GetBitmap(wx.ART_QUESTION, wx.ART_OTHER, wx.Size(64, 64))
        wx.SplashScreen.__init__(self, bmp,
                                 wx.SPLASH_CENTER_ON_SCREEN | wx.SPLASH_TIMEOUT, #  | wx.STAY_ON_TOP,
                                 3000, None, -1)

        self.Bind(wx.EVT_CLOSE, self.OnClose)
        self.fc = wx.FutureCall(2000, self.ShowMain)

    def OnClose(self, evt):
        # Make sure the default handler runs too so this window gets
        # destroyed
        evt.Skip()
        self.Hide()

        # if the timer is still running then go ahead and show the
        # main frame now
        if self.fc.IsRunning():
            self.fc.Stop()
            self.ShowMain()

    def ShowMain(self):
        frame = MainFrame(None, title="A sample frame")
        frame.Show()
        if self.fc.IsRunning():
            self.Raise()

class MainFrame(sc.SizedFrame):
    def __init__(self, *args, **kwds):
        kwds["style"] = wx.DEFAULT_FRAME_STYLE|wx.FULL_REPAINT_ON_RESIZE|wx.TAB_TRAVERSAL

        super(MainFrame, self).__init__(*args, **kwds)

        self.SetTitle("A sample")
        self.Centre(wx.BOTH)

        paneContent = self.GetContentsPane()

        # lets add a few controls
        for x in range(5):
            wx.StaticText(paneContent, -1, 'some string %s' % x)

        paneBtn = sc.SizedPanel(paneContent)
        paneBtn.SetSizerType('horizontal')
        # and a few buttons
        for x in range(3):
            wx.Button(paneBtn, -1, 'a button %s' % x)

        self.Fit()

class BaseApp(wx.App, InspectionMixin):

    """The Application, using WIT to help debugging."""

    def OnInit(self):
        """
        Do application initialization work, e.g. define application globals.
        """
        self.Init()
        self._loginShown = False
        splash = MySplashScreen()

        return True

if __name__ == '__main__':
    app = BaseApp()
    app.MainLoop()

rawDescription: Close properly splash-screen

description: Close properly splash-screen


code:
from Tkinter import *
import Tkinter as tk
import pygame
from pygame.locals import *
import os

def set_screen():
    global screen

    pygame.init()
    pygame.display.init()
    screen = pygame.display.set_mode((600,600))
    screen_rect = screen.get_rect()
    pygame.draw.circle(screen, (255,0,0), screen_rect.center, 50 )
    pygame.display.flip()

def set_tk():
    global root
    global embed
    global tkwin
    root = tk.Tk()
    root.wm_title("OpenBox")
    embed = tk.Frame(root, width = 600, height = 600)
    embed.pack(side=LEFT)
    windowid = embed.winfo_id()
    tkwin = tk.Frame(root, width = 200, height = 600)
    tkwin.pack(side=RIGHT)
    os.environ['SDL_WINDOWID'] = str(windowid)
    #~ if sys.platform == "win32":
        #~ os.environ['SDL_VIDEODRIVER'] = 'windib'
    #~ if len(sys.argv) > 1:
        #~ if sys.argv[1] == "-f":
            #~ root.attributes("-fullscreen", True)
    root.after(100,set_screen)
    root.mainloop()

set_tk()

rawDescription: Virtualbox Ubuntu pygame.display.set_mode acts differently in interactive python than when interpreting file


code:
class AdminBlogEdit(MethodView):
    def __init__(self):
            self.blog_form = NewBlogEntryForm(csrf_enabled=False)

    def get(self,blog_key_id=None):
        if blog_key_id:
            self.blog_model = BlogEntryModel.get_by_id(blog_key_id)
            self.blog_form = NewBlogEntryForm(obj = self.blog_model)

        return render_template('admin/blog_edit.html', form=self.blog_form)

    def post(self,blog_key_id=None):
        if self.blog_form.validate():
            self.update_post(blog_key_id)
            self.blog_model.put()
            return redirect(url_for(".admin"))
        else:
            return render_template('admin/blog_edit.html', form=self.blog_form)
        return redirect(url_for(".admin"))

    def update_post(self,blog_key_id):
        if blog_key_id:
            self.blog_model = BlogEntryModel.get_by_id(blog_key_id)
            self.blog_form.populate_obj(self.blog_model)
        else:
            self.blog_model = BlogEntryModel(title  =   self.blog_form.title.data, date_created = self.blog_form.date_created.data,
                                                            entry = self.blog_form.entry.data)

rawDescription: How do I load an entity from the App Engine datastore into my WTForms model_form?

description: Load an entity from the App Engine datastore into my WTForms model_form


code:
def feed(self, line):
    self.buff.append(' ' * (self.indentation * 4) + line)

rawDescription: Django force makemigrations to use tabs instead of spaces


code:
#!/usr/bin/python
from subprocess import Popen, PIPE
import sys

data = Popen(["monitor-services"], stdout=PIPE).communicate()[0]

sys.exit("failure" in data)

rawDescription: monitor service for "failure"

description: Monitor service for "failure"


code:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_gtk import FigureCanvasGTK as FigureCanvas
import gtk
import numpy as np

class W(gtk.Window):

    def __init__(self):

        gtk.Window.__init__(self)

        img = np.random.uniform(0,1,(200,200))

        fig = plt.Figure()
        fig.gca().imshow(img)
        self.image_canvas = FigureCanvas(fig)
        self.image_canvas.connect('button_press_event', self.do_clip)

        self.add(self.image_canvas)
        self.show_all()

    def do_clip(self, widget=None, event=None):

        snap = self.image_canvas.get_snapshot()
        pixbuf = gtk.gdk.pixbuf_get_from_drawable(None, snap,
            snap.get_colormap(),0,0,0,0,
            snap.get_size()[0], snap.get_size()[1])
        clip = gtk.Clipboard()
        clip.set_image(pixbuf)

w=W()
gtk.main()

rawDescription: PyGTK: copy matplotlib figure to clipboard


code:
from selenium.webdriver.support.select import Select

option_value = "Malicious E-mail"

select_element = browser.find_element_by_xpath("//select[option[@value = '%s']]" % option_value)
select = Select(select_element)
select.select_by_value(option_value)

rawDescription: Selenium - Python - Select dropdown meun option - No ID or Name


code:
import  wx

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

class TestRadioBox(wx.Panel):
    def __init__(self, parent, log):
        self.log = log
        wx.Panel.__init__(self, parent, -1)
        #self.SetBackgroundColour(wx.BLUE)
    sampleList = ['zero', 'one', 'two', 'three', 'four', 'five',
                  'six', 'seven', 'eight']

    sizer = wx.BoxSizer(wx.VERTICAL)

    rb = wx.RadioBox(
            self, -1, "wx.RadioBox", wx.DefaultPosition, wx.DefaultSize,
            sampleList, 2, wx.RA_SPECIFY_COLS
            )

    self.Bind(wx.EVT_RADIOBOX, self.EvtRadioBox, rb)
    #rb.SetBackgroundColour(wx.BLUE)
    rb.SetToolTip(wx.ToolTip("This is a ToolTip!"))
    #rb.SetLabel("wx.RadioBox")

    sizer.Add(rb, 0, wx.ALL, 20)

    rb = wx.RadioBox(
            self, -1, "", wx.DefaultPosition, wx.DefaultSize,
            sampleList, 3, wx.RA_SPECIFY_COLS | wx.NO_BORDER
            )

    self.Bind(wx.EVT_RADIOBOX, self.EvtRadioBox, rb)
    rb.SetToolTip(wx.ToolTip("This box has no label"))

    sizer.Add(rb, 0, wx.LEFT|wx.RIGHT|wx.BOTTOM, 20)

    self.SetSizer(sizer)

def EvtRadioBox(self, event):
    self.log.WriteText('EvtRadioBox: %d\n' % event.GetInt())

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

def runTest(frame, nb, log):
    win = TestRadioBox(nb, log)
    return win

overview = """\
A RadioBox is used to select one of a number of mutually exclusive
choices.  It is displayed as a vertical column or horizontal row of
labelled buttons, surrounded by a box that can optionally have a
label.

"""

if __name__ == '__main__':
    import sys,os
    import run
    run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])

rawDescription: Assigning list of labels to radiobuttons using wxpython


code:
def filter(txt, oldfile, newfile):
    '''\
    Read a list of names from a file line by line into an output file.
    If a line begins with a particular name, insert a string of text
    after the name before appending the line to the output file.
    '''

    with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
        for line in infile:
            if line.startswith(txt):
                line = line[0:len(txt)] + ' - Truly a great person!\n'
            outfile.write(line)

# input the name you want to check against
text = input('Please enter the name of a great person: ')
letsgo = filter(text,'Spanish', 'Spanish2')

rawDescription: How to open a file using the open with statement

description: Open a file using the open with statement


code:
_application = django.core.handlers.wsgi.WSGIHandler()

def application(environ, start_response):
    os.environ['SCRIPT_NAME'] = '/myproj/'
    return _application(environ, start_response)

rawDescription: Webfaction apache + mod_wsgi + django configuration issue


code:
x = np.arange(0, 10)
y = np.exp(-x / 3.0)
f = interpolate.interp1d(x, y, "cubic")
i = np.arange(0.5, 9.5, 1)
f(i)

rawDescription: Python spline interpolation with two different dataset


code: foo = re.findall(r'The ([\w ]+) won (\d+) - (\d+) over the ([\w ]+)\.', mystring)

rawDescription: Matching two subsequent words with a regex?


code:
import re
text = "A tall-ish wall, with trim.I don't want to paint it;"
re.findall("[-'\w]+", text)

rawDescription: Specific Punctuation Stripping Python

description: Specific Punctuation Stripping Python


rawDescription: How to make a html link to open in new tab in Python

description: Make a html link to open in new tab in Python


code:
stdoutRegistry = set()

class A(object):
    def __init__(self):
        self.stdoutRegistry.add(self)

    def stdoutNotify(self):
        pass

original_stdoutWrite = sys.stdout.write
def stdoutWrite(*a, **kw):
    if a in stdoutRegistry:
        a.stdoutNotify()
    original_stdoutWrite(*a, **kw)
sys.stdout.write = stdoutWrite

rawDescription: Python - detect when my object is written to stdout?


code:
from flask import Response
@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    return Response(xml, mimetype='text/xml')

rawDescription: Python Flask, how to set content type

description: Python Flask, how to set content type


code:
# No need for select_related in this case
Event.objects.values('name', 'date', 'place__name', 'place__address')

[{
   "name": "event1",
   "date": "date1",
   "place__name": "place1",
   "place__address": "address1",
},{
   "name": "event2",
   "date": "date2",
   "place__name": "place2",
   "place__address": "address2",
}]

rawDescription: Django: convert QuerySet with related objects to JSON


rawDescription: How can I transform blocks into a blockdiagonal matrix (NumPy)

description: Transform blocks into a blockdiagonal matrix (NumPy)


code: ':'.join(s.encode('hex') for s in '00163e2fbab7'.decode('hex'))

rawDescription: How to convert a MAC number to MAC string?

description: Convert a MAC number to MAC string


code:
from ctypes import *
windll.user32.MessageBoxA(None, "Hello world", "ctypes", 0);

rawDescription: How can I call a DLL from a scripting language?

description: Call a DLL from a scripting language


code:
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n"
       % (fromaddr, ", ".join(toaddrs)))

rawDescription: Python: smtplib Adds Newline to Message

description: Python: smtplib Adds Newline to Message


code:
def do_HEAD(self):
    self.send_response(200)
def do_GET(self):
    """Respond to a GET request."""
    print('client', self.client_address)
    print('server', self.server)
    self.send_response(200)

rawDescription: Python http server storing received message


code:
class CustomCourseWidget(forms.Select):
    #http://djangosnippets.org/snippets/200/
    def render(self, name, value, attrs=None, choices=()):
        from django.utils.html import escape
        from django.utils.encoding import smart_unicode
        from django.forms.util import flatatt

        if value is None:
            value = ''
        final_attrs = self.build_attrs(attrs, name=name)
        output = [u'<select%s>' % flatatt(final_attrs)]
        output.append(u'<option value=""></option>') # Empty line for default text
        str_value = smart_unicode(value)
        optgroup_open = False
        for group in self.choices:
            option_value = smart_unicode(group[0])
            option_label = smart_unicode(group[1])
            if not ">" in option_label and optgroup_open == True:
                output.append(u'</optgroup>')
                optgroup_open = False
            if not ">" in option_label and optgroup_open == False:
                output.append(u'<optgroup label="%s">' % escape(option_label))
                optgroup_open = True
            if " > " in option_label:
                #optgroup_open = True
                selected_html = (option_value == str_value) and u' selected="selected"' or ''
                output.append(u'<option value="%s"%s>%s</option>' % (escape(option_value), selected_html, escape(option_label.split(" > ")[1])))

        output.append(u'</select>')
        return mark_safe(u'\n'.join(output))

rawDescription: Django Forms and ModelChoiceField: Add HTML optgroup element to specific objects in QuerySet?


code:
class C:
    x = 1

    @classmethod
    def m(cls):
        return cls.x

class D(C):
    x = 2

print(C.m()) # 1
print(D.m()) # 2

rawDescription: classmethod built-in function - Can't understand a statement from Documentation

description: Classmethod built-in function - Can't understand a statement from Documentation


code:
import json
json.dump([{'name': i['name'], 'number': i['number']} for i in var ], f)

rawDescription: Write JSON field with its key

description: Write JSON field with its key


rawDescription: python re.sub, only replace part of match

description: Python re.sub, only replace part of match


code:
def create_animal_eating(food):
    gen = (subclass for subclass in Animal.__subclasses__() if subclass.eats(food))
    subclass = next(gen, None)
    if subclass is None:
        raise ValueError("No animal eats " + repr(food))
    new_obj = subclass()

rawDescription: Python - Iterate through list of classes that extend class?


code:
import pygame
from pygame import gfxdraw

RED = pygame.Color("red")
WHITE = pygame.Color("white")

def draw_arc(surface, center, radius, start_angle, stop_angle, color):
    x,y = center
    start_angle = int(start_angle%360)
    stop_angle = int(stop_angle%360)
    if start_angle == stop_angle:
        gfxdraw.circle(surface, x, y, radius, color)
    else:
        gfxdraw.arc(surface, x, y, radius, start_angle, stop_angle, color)

pygame.init()
screen = pygame.display.set_mode([500,500])
screen_rect = screen.get_rect()
x,y = screen_rect.center
clock = pygame.time.Clock()
done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    screen.fill((0,0,0))
    #Arcs
    draw_arc(screen, screen_rect.center, 200, 45, 360, WHITE)
    draw_arc(screen, screen_rect.center, 220, 0, 360, WHITE)
    draw_arc(screen, screen_rect.center, 100, -90, -135, WHITE)
    draw_arc(screen, screen_rect.center, 120, -135, -90, WHITE)
    # Horizontal and vertical lines for comparison
    pygame.draw.line(screen, RED, screen_rect.center, screen_rect.midright)
    pygame.draw.line(screen, RED, screen_rect.center, screen_rect.midtop)
    pygame.draw.line(screen, RED, screen_rect.topleft, screen_rect.bottomright)
    pygame.display.flip()
    clock.tick(30)

pygame.quit()

rawDescription: Pygame.draw.arc() completion bug or just me?


code:
import time
def function_1():
    start_time = time.time()
    while True:
         # do long stuff
         running_time = time.time() -start_time
         if running_time > 2 * 60 * 60: # 2 hours
              yield #<partial results can be yield here, if you want>
              start_time = time.time()

runner = function_1()
while True:
    try:
        runner.next()
    except StopIteration:
        # function_1 had got to the end
        break
    # do other stuff

rawDescription: How to stop a function at a specific time and continue with next function in python?

description: Stop a function at a specific time and continue with next function in python


code:
x = 4
float(x)

rawDescription: Convert Number to Float in Python

description: Convert Number to Float in Python


code:
from lxml.html import fromstring
s="""Steffen Eddine (PhD) (SEED)

Petra Schmidt (PESC)

Peter Kumar (PEKU)

Raksha Khaldoun (RAKH)

Yash Chevalier (YACH)"""
st=fromstring(s)
[c.text for c in st.getchildren() if c.text]

rawDescription: Python picking texts from Html using Regular Expression


code:
from math import sin, cos, pi, radians, ceil
import itertools

try:
    rng = xrange    # Python 2.x
except NameError:
    rng = range     # Python 3.x

# for the following calculations,
# - all angles are in radians (unless otherwise specified)
# - latitude is in [-pi/2..pi/2]
# - longitude is in [-pi..pi)
MIN_LAT = -pi/2   # South Pole
MAX_LAT = pi/2    # North Pole
MIN_LON = -pi     # Far West
MAX_LON = pi      # Far East

def floatRange(start, end=None, step=1.0):
    "Floating-point range generator"
    start += 0.0    # cast to float
    if end is None:
        end = start
        start = 0.0
    steps = int(ceil((end-start)/step))
    return (start + k*step for k in rng(0, steps+1))

def patch2d(xmin, xmax, ymin, ymax, step=1.0):
    "2d rectangular grid generator"
    if xmin>xmax:
        xmin,xmax = xmax,xmin
    xrange = floatRange(xmin, xmax, step)

    if ymin>ymax:
        ymin,ymax = ymax,ymin
    yrange = floatRange(ymin, ymax, step)

    return itertools.product(xrange, yrange)

def patch2d_to_3d(xyIter, zFn):
    "Convert 2d field to 2.5d height-field"
    mapFn = lambda a: (a[0], a[1], zFn(a[0],a[1]))
    return itertools.imap(mapFn, xyIter)

#
# Representation conversion functions
#

def to_spherical(lon, lat, rad):
    "Map from spherical to spherical coordinates (identity function)"
    return lon, lat, rad

def to_cylindrical(lon, lat, rad):
    "Map from spherical to cylindrical coordinates"
    # angle, z, radius
    return lon, rad*sin(lat), rad*cos(lat)

def to_cartesian(lon, lat, rad):
    "Map from spherical to Cartesian coordinates"
    # x, y, z
    cos_lat = cos(lat)
    return rad*cos_lat*cos(lon), rad*cos_lat*sin(lon), rad*sin(lat)

def bumpySphere(gridSize, radiusFn, outConv):
    lonlat = patch2d(MIN_LON, MAX_LON, MIN_LAT, MAX_LAT, gridSize)
    return list(outConv(*lonlatrad) for lonlatrad in patch2d_to_3d(lonlat, radiusFn))

# make a plain sphere of radius 10
sphere = bumpySphere(radians(5.0), lambda x,y: 10.0, to_cartesian)

# spiky-star-function maker
def starFnMaker(xWidth, xOffset, yWidth, yOffset, minRad, maxRad):
    # make a spiky-star function:
    #   longitudinal and latitudinal triangular waveforms,
    #   joined as boolean intersection,
    #   resulting in a grid of positive square pyramids
    def starFn(x, y, xWidth=xWidth, xOffset=xOffset, yWidth=yWidth, yOffset=yOffset, minRad=minRad, maxRad=maxRad):
        xo = ((x-xOffset)/float(xWidth)) % 1.0   # xo in [0.0..1.0), progress across a single pattern-repetition
        xh = 2 * min(xo, 1.0-xo)                 # height at xo in [0.0..1.0]
        xHeight = minRad + xh*(maxRad-minRad)

        yo = ((y-yOffset)/float(yWidth)) % 1.0
        yh = 2 * min(yo, 1.0-yo)
        yHeight = minRad + yh*(maxRad-minRad)

        return min(xHeight, yHeight)
    return starFn

# parameters to spike-star-function maker
width = 2*pi
horDivs = 20    # number of waveforms longitudinally
horShift = 0.0  # longitudinal offset in [0.0..1.0) of a wave

height = pi
verDivs = 10
verShift = 0.5      # leave spikes at the poles

minRad = 10.0
maxRad = 15.0

deathstarFn = starFnMaker(width/horDivs, width*horShift/horDivs, height/verDivs, height*verShift/verDivs, minRad, maxRad)

deathstar = bumpySphere(radians(2.0), deathstarFn, to_cartesian)

rawDescription: creating deformations on a sphere surface (using python?)

description: Creating deformations on a sphere surface (using python?)


code:
for x in range(y):
    try:
        do_something()
    except SomeException:
        continue
    # The following line will not get executed for the current x value if a SomeException is raised
    do_another_thing()

for x in range(y):
    try:
        do_something()
    except SomeException:
        pass
    # The following line will get executed regardless of whether SomeException is thrown or not
    do_another_thing()

rawDescription: Is "continue" the Pythonic way to escape from a try catch block?


code:
import sys, os
from Tkinter import *
import pygst
pygst.require("0.10")
import gst

def start():
        player.set_property('video-sink', None)
        player.set_property("uri", "file:///" + sys.argv[1])
        player.set_state(gst.STATE_PLAYING)

def on_sync_message(bus, message):
        if message.structure is None:
                return
        message_name = message.structure.get_name()
        if message_name == "prepare-xwindow-id":
                imagesink = message.src
                imagesink.set_property("force-aspect-ratio", True)
                imagesink.set_xwindow_id(mwin_id)

window = Tk()
window.geometry("500x400")
movie_window = Frame(window,bg='#000000')
movie_window.pack(side=BOTTOM,anchor=S,expand=YES,fill=BOTH)

mwin_id = movie_window.winfo_id()

player = gst.element_factory_make("playbin2", "player")
fakesink = gst.element_factory_make('fakesink', 'novideo')
player.set_property('video-sink', fakesink)

bus = player.get_bus()
bus.add_signal_watch()
bus.enable_sync_message_emission()
bus.connect("sync-message::element", on_sync_message)

start()
window.mainloop()

rawDescription: Video Output In Tkinter From GStreamer?

description: Video Output In Tkinter From GStreamer


code:
import io

with io.open('all.txt', 'r', encoding='utf8') as f_in:
    with io.open('all.out', 'w', encoding='utf8') as f_out:
        for line in f_in:
            if u"<title>" in line:
                f_out.write(line)

rawDescription: How to use encoding utf-8.py instead of cp1252.py in Python

description: Use encoding utf-8.py instead of cp1252.py in Python


rawDescription: How to clear/reset all configured logging handlers in Python?

description: Clear/reset all configured logging handlers in Python


code: {x:'AZ' for x in range(1, 100)} # Use xrange in Python 2

rawDescription: Dictionary with Key Range Possible?

description: Dictionary with Key Range Possible


code:
a=[0,3,6]
b=[0,3,4]
c=[1, 7]

x = [0,1,3,4,6,7]

ya = []

val = 0
for i in x:
    if i in a:
        val += 1
        ya.append(val)
    else:
        ya.append(val)

ya

rawDescription: Cumulative plot for many variables in matplotlib?


rawDescription: Python code fragment - List

description: Python code fragment - List


code: testdf['avg_sales_per_sku'] = testdf.sales.sum() / testdf.skus.sum()

rawDescription: Better way to add constant column to pandas data frame


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup("""

           ....other things...

          ....other things...

""")
live_events = soup.find(id="live-events")
ids = [div["id"] for div in live_events.find_all("div")]
ids

rawDescription: Extract DIV ID names found in a specific containing DIV using Python


code:
from itertools import imap
''.join(imap(str, item))

rawDescription: Convert list item to string

description: Convert list item to string


code:
import json
myjson = json.dumps({
    "extract": extract
})

rawDescription: Building json strings in Python - issues with strings and unicode


code:
import csv
from operator import itemgetter

with open('studentScores.csv', 'r') as f:
    data = [line for line in csv.reader(f)]

newRecord = [Score, Name, Gender, FormGroup, Percentage]
data.append(newRecord)

data.sort(key=itemgetter(1))  # 1 being the column number

with open('studentScores.csv', 'w') as f:
    csv.writer(f).writerows(data)

rawDescription: How to sort a CSV file alphabetically?

description: Sort a CSV file alphabetically


code:
def Login():
    log = input ('\nLogin (Case sensitive): ')
    LoggedInStudent(log)

def LoggedInStudent(log):
    ...

rawDescription: A way to use a defined input in later defined scripts (python)?


rawDescription: Loss of quotes when encoding into ascii

description: Loss of quotes when encoding into ascii


code:
from google.appengine.api import runtime

runtime.memory_usage().current()

rawDescription: AppEngine (Python): can I know programmatically how much memory is used by the current instance?


code:
from django.forms.models import BaseInlineFormSet

class TeamPlayerFormset(BaseInlineFormSet):
    def clean(self):
        """Check that exactly 11 players are entered."""
        super(TeamPlayerFormset, self).clean()

        if any(self.errors):
            return

        count = 0
        for cleaned_data in self.cleaned_data:
            if cleaned_data and not cleaned_data.get('DELETE', False):
                count += 1
        if count != 11:
            raise forms.ValidationError('You must enter 11 team players.')

class TeamPlayerInline(admin.TabularInline):
    model = TeamPlayer
    max_num = 11
    extra = 11
    formset = TeamPlayerFormset

class TeamAdmin(admin.ModelAdmin):
    inlines = [TeamPlayerInline]

rawDescription: Validating number of ManyToManyField items (with intermediate model) in Django admin


code:
import wx
import wx.grid as gridlib

########################################################################
class MyForm(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, parent=None, title="A Simple Grid")
        panel = wx.Panel(self)

        myGrid = gridlib.Grid(panel)
        myGrid.CreateGrid(12, 8)

        # get the cell attribute for the top left row
        editor = myGrid.GetCellEditor(0,0)
        attr = gridlib.GridCellAttr()
        attr.SetReadOnly(True)
        myGrid.SetRowAttr(0, attr)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(myGrid, 1, wx.EXPAND)
        panel.SetSizer(sizer)

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

rawDescription: How to set an entire row/column as read only in wx.grid (wxpython)?

description: Set an entire row/column as read only in wx.grid (wxpython)


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

#Fake data
data = (np.random.random(50), np.random.random(50))
labels = ('random set 1', 'random set 2')

plt.boxplot(data)
plt.xticks(np.arange(len(labels))+1,labels)
plt.show()

rawDescription: Python multiple boxplots automatic label


code:
if not text.rstrip():
  log.warning("Empty param 'text': " + text)
  return None

rawDescription: How to check if a string is different string constant (such as '\n', '\t') with Python

description: Check if a string is different string constant (such as '\n', '\t') with Python


code:
ex = ['liberty of freedom', 'liberty', 'organizations of human rights', 'human rights']
file = " The american people enjoys a liberty of freedom and there are many international organizations of human rights."
reg = '|'.join(ex)
import re
re.sub('('+reg+')', r'[\1]', file)

rawDescription: Replace a string in a file

description: Replace a string in a file


code:
def fill_array(a, b, N, out=None):
    if out is None:
        out = np.zeros(N, N)
    out[0] = a
    out[-1] = b
    return out

rawDescription: Functions and numpy array preallocation

description: Functions and numpy array preallocation


code: print("%s" % x)

rawDescription: Closest approximation to Python 2 style printing in python 3


code:
def your_common_function(i, txt):
   # here you may decide what to do with arguments according to "i" value
   if i == 1:
      print(txt)
   else:
      print(txt+'s')

for i in range(1, 233):
    exec("def add%d(txt):\n\tyour_common_function(%d, txt)" % (i, i))

add1("hello world")  # prints "hello world"
add167("hello world")  # prints "hello worlds"

rawDescription: Is there a way to automate the defining of a function in python?


code: url = raw_input("Please enter a URL to crawl: ")

rawDescription: How can i put a value in HTML and execute a python code with that value as a variable

description: Put a value in HTML and execute a python code with that value as a variable


code:
url = "imageurl"
result = urlfetch.fetch(url)
if result.status_code == 200:
   prof.avatar = db.Blob(result.content)

rawDescription: How do I save web images to App Engine's blobstore?

description: Save web images to App Engine's blobstore


code:
from collections import deque

deque(map(somefunc, ((i,d) for i in range(10**3))), maxlen=0)

rawDescription: Force all iterations on an iterable

description: Force all iterations on an iterable


code:
import subprocess

commands = [ ["p1"], ["p2"] ]
programs = [ subprocess.Popen(c) for c in commands ]
while True:
    for i in range(len(programs)):
        if programs[i].returncode is None:
            continue # still running
        else:
            # restart this one
            programs[i]= subprocess.Popen(commands[i])
        time.sleep(1.0)

rawDescription: Multi-server monitor/auto restarter in python


code:
class xml_file_generation:
    def xml_parse_new(self):
        for event, elem in ET.iterparse('a.xml', events=events, tag="{abc.org}context"):
                print("In loop")
                print(ET.tostring(elem))
                print("%s" % (elem.tag))

test = xml_file_generation()
test.xml_parse_new()

rawDescription: lxml iterparse with file fails

description: Lxml iterparse with file fails


code:
backup = open(filename, 'rb')
while True:
    part_of_file = backup.read(60000000) # not exactly 60 MB....
    response = connection.put() # submit part_of_file here to amazon

rawDescription: S3 Backup Memory Usage in Python

description: S3 Backup Memory Usage in Python


code:
def nested_del(structure, del_spec):
    for item in del_spec[:-1]:  # Loop through all but the last element.
        structure = structure[item]  # Go further into the nested structure
    del structure[del_spec[-1]]  # Use the last element to delete the desired value

nested_del(a, b)
nested_del(a, c)

rawDescription: remove an arbitrary element from a nest of lists and dicts in python

description: Remove an arbitrary element from a nest of lists and dicts in python


code:
import operator
sorted_comments = sorted(this_users_comments, key=operator.attrgetter("date"))
# The comments will probably be sorted with earlier comments at the front of the list
# If you want ten most recent, also add the following line:
# sorted_comments.reverse()
ten_comments = sorted_comments[:10]

rawDescription: How do I order by date when using ReferenceProperty?

description: Order by date when using ReferenceProperty


code:
import datetime
import copy

def getDates(startdate, enddate):
    days  = (enddate + datetime.timedelta(days=1) - startdate).days
    dates = [ startdate + datetime.timedelta(days=x) for x in range(0, days) ]
    return dates

dates1 = getDates(datetime.datetime(2013, 1, 1), datetime.datetime(2013, 1, 31))
dates2 = getDates(datetime.datetime(2013, 3, 1), datetime.datetime(2013, 3, 31))
dates = dates1+dates2
data = np.arange(len(dates))

Locator = mpl.dates.DayLocator(interval=5)
Formatter = mpl.dates.DateFormatter('%d-%m-%y')

fig, (ax, ax2) = plt.subplots(1, 2, sharey=True, tight_layout=True)
fig.subplots_adjust(wspace=0.05)
fig.set_size_inches(10, 3, forward=True)

ax.plot(dates, data)
ax2.plot(dates, data)

ax.legend(loc=1)
ax.set_ylim(0, 61)
ax.set_xlim(datetime.datetime(2013, 1, 1), datetime.datetime(2013, 1, 31))
ax2.set_xlim(datetime.datetime(2013, 3, 1), datetime.datetime(2013, 3, 31))

labels = ax.get_xticklabels()
for label in labels:
    label.set_rotation(30)
labels = ax2.get_xticklabels()
for label in labels:
    label.set_rotation(30)

ax.spines['right'].set_visible(False)
ax2.spines['left'].set_visible(False)
ax.tick_params(right='off')
ax2.tick_params(left='off')
ax2.yaxis.tick_right()

# note the copy here
ax.xaxis.set_major_locator(copy.copy(Locator))
ax.xaxis.set_major_formatter(copy.copy(Formatter))
ax2.xaxis.set_major_locator(copy.copy(Locator))
ax2.xaxis.set_major_formatter(copy.copy(Formatter))

rawDescription: Discontinuous timeseries plot with dates on x-axis


code:
def getValue(line):
    '''Lookup value in pivot table "data" given the contents of the line passed in from df'''
    value = lambda line: '% Male Survived' if line.Sex == 'male' else '% Female Survived'
    result = data.ix[line.Embarked][value(line)].get(line.Pclass)
    return result

df['Chance of Survival'] = df.apply(getValue, axis=1)

rawDescription: Pandas: assigning values to a dataframe column based on pivot table values using an if statement


code:
fig = plt.figure()

ax1 = fig.add_subplot(1,2,1)
im = ax1.tricontourf(x_exp, y_exp, z_exp)
plt.colorbar(im, drawedges=True, orientation='vertical')
ax1.set_aspect('equal')
ax1.set_axis_off()
ax1.set_title('tricontour')

ax2 = fig.add_subplot(1,2,2)
im = ax2.tricontourf(x_exp, y_exp, z_exp2)
plt.colorbar(im, drawedges=True, orientation='vertical')
ax2.set_aspect('equal')
ax2.set_axis_off()
ax2.set_title('tricontour')

plt.show()

rawDescription: Subplot with equal aspect ratio

description: Subplot with equal aspect ratio


code:
class EditLinkMixin(object):
    def get_admin_link(self):
        return '/admin/%s/%s/%d/' % (self._meta.app_name, self.__class__.__name__, self.pk)

class MyModel(models.Model, EditLinkMixin):
    pass

rawDescription: How can I get the name of app inside a model?

description: Get the name of app inside a model


rawDescription: Pandas group by and sum two columns

description: Pandas group by and sum two columns


code: msg = data.split('X-OriginalArrivalTime', 1)[1].split('\n', 1)[1]

rawDescription: Python - search for string, copy until end of doc


code:
SEARCHED_LOCATION = db.GeoPt("48.8566667, 2.3509871") # Location of Paris.
DISTANCE = 50000 #Between 10000 and 150000.
MAX_RESULTS = 300

# Resolution '4' is about 150 kilometers i suppose it's a good compromise.
bbox = geocell.compute_box(geocell.compute(SEARCHED_LOCATION, resolution=4))
cell = geocell.best_bbox_search_cells(bbox, geomodel.default_cost_function)

query.filter('location_geocells IN', cell)

# Python filters
def _func(x):
  """Private method used to set the distance of the model to the searched location
  and return this distance.
  """
  x.dist = geomath.distance(SEARCHED_LOCATION, x.location)
  return x.dist

results = sorted(query.fetch(MAX_RESULTS), key=_func) # Order the result by distance
results = [x for x in results if x.dist <= DISTANCE]  # Filter the result

rawDescription: Python GeoModel alternative

description: Python GeoModel alternative


rawDescription: How do I use Python PIL to save an image to a particular directory?

description: Use Python PIL to save an image to a particular directory


rawDescription: How to aggregate multiple columns in pandas groupby

description: Aggregate multiple columns in pandas groupby


rawDescription: A Unicode string written in escaped ASCII


code:
for index, g in enumerate(games[0:4]):
    g.output(index)

rawDescription: How to output an index while iterating over an array in python

description: Output an index while iterating over an array in python


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

s = pd.Series(np.random.normal(0, 100, 10000))
p = s.plot(kind='hist', bins=50, color='orange')

bar_value_to_label = 100
min_distance = float("inf")  # initialize min_distance with infinity
index_of_bar_to_label = 0
for i, rectangle in enumerate(p.patches):  # iterate over every bar
    tmp = abs(  # tmp = distance from middle of the bar to bar_value_to_label
        (rectangle.get_x() +
            (rectangle.get_width() * (1 / 2))) - bar_value_to_label)
    if tmp < min_distance:  # we are searching for the bar with x cordinate
                            # closest to bar_value_to_label
        min_distance = tmp
        index_of_bar_to_label = i
p.patches[index_of_bar_to_label].set_color('b')

plt.show()

rawDescription: Change the colour of a matplotlib histogram bin bar given a value


code:
from pylab import *
from matplotlib.widgets import Slider
import numpy as np

hte = np.array([10, 11, 12, 13, 15, 20, 21, 22, 25, 30])
hre = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

k = 20 * hte
n4 = 10 * hre
t, w4 = 6, 25
x = arange(1, 100, 10)
d = log10(x) / 10

y = k + n4 * d + t + w4 + 8

ax = subplot(111)
subplots_adjust(left=0.15, bottom=0.25)
line, = plot(x, y, linewidth=2, color='r')

xlabel('X - Title')
ylabel('Y - title')
title('$Our Chart$')
grid(True)

axcolor = 'lightgoldenrodyellow'
axhte = axes([0.15, 0.1, 0.65, 0.03], axisbg=axcolor)
axhre = axes([0.15, 0.15, 0.65, 0.03], axisbg=axcolor)

shte = Slider(axhte, 'hte', 0.1, 30.0, valinit=1)
shre = Slider(axhre, 'hre', 0.1, 10.0, valinit=1)

def update(val):
    k = 20 * hte * shte.val
    n4 = 10 * hre * shre.val

    y= k + n4 * d + t + w4 + 8

    line.set_ydata(y)
    ax.set_ylim(y.min(), y.max())
    draw()

shte.on_changed(update)
shre.on_changed(update)

show()

rawDescription: Add slider to matplotlib chart

description: Add slider to matplotlib chart


code:
import pygame,math
from pygame.locals import *

pygame.init()
screen=pygame.display.set_mode((640,480))
run=True
themap=pygame.image.load('map1.png')
clock=pygame.time.Clock()

class AI(object):
    def __init__(self,x,y):
        self.x=x
        self.y=y
        self.path=[(144,114),(280,114),(280,300),(100,302)]
    def update(self):
        speed=2
        if self.x<(self.path[0])[0]:
            self.x+=speed
        if self.x>(self.path[0])[0]:
            self.x-=speed
        if self.y<(self.path[0])[1]:
            self.y+=speed
        if self.y>(self.path[0])[1]:
            self.y-=speed
        z=(self.x-(self.path[0])[0],self.y-(self.path[0])[1])
        if (z[0]/-speed,z[1]/-speed)==(0,0):
            self.path=self.path[1:]
        pygame.draw.circle(screen,((255,0,0)),(self.x,self.y),3,0)
enemies=[AI(-5,114)]
while run:
    screen.blit(themap,(0,0))
    for e in enemies:
        e.update()
    for e in pygame.event.get():
        if e.type==QUIT:
            run=False
    clock.tick(60)
    pygame.display.flip()

rawDescription: Pygame Move through a list of points?

description: Pygame Move through a list of points


code:
def find_loops(rna, min_pairs=3, min_loop=3):
    n = len(rna)
    result = []
    for loop_start in xrange(min_pairs, n - min_pairs - min_loop + 1):
        for loop_end in xrange(loop_start + min_loop, n - min_pairs):
            if (loop_end - loop_start < min_loop + 2 or
                    not base_pair(rna[loop_start], rna[loop_end - 1])):
                max_pairs = min(loop_start, n - loop_end)
                for k in xrange(max_pairs):
                    if not base_pair(rna[loop_start - k - 1], rna[loop_end + k]):
                        break
                else:
                    k = max_pairs
                if k >= min_pairs:
                    result.append((loop_start - k, k, loop_end - loop_start))
    return result

def base_pair(x, y):
    return (x == 'A' and y == 'U' or
            x == 'C' and y == 'G' or
            x == 'G' and y == 'C' or
            x == 'U' and y == 'A')

rawDescription: Nested loops to find all possible combinations in Python


rawDescription: group multi-index pandas dataframe

description: Group multi-index pandas dataframe


rawDescription: Copy a ndarray into another ndarray at a given position


code:
from google.appengine.api import mail

message = mail.EmailMessage(sender="Example.com Support <support@example.com>",
                            subject="Your account has been approved")

message.to = "Albert Johnson <Albert.Johnson@example.com>"

message.body = """
Dear Albert:

Your example.com account has been approved.  You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.

Please let us know if you have any questions.

The example.com Team
"""

message.html = """

Dear Albert:

Your example.com account has been approved.  You can now visit
http://www.example.com/ and sign in using your Google Account to
access new features.

Please let us know if you have any questions.

The example.com Team

"""

message.send()

rawDescription: Send HTML e-mail in App Engine / Python?

description: Send HTML e-mail in App Engine / Python


code:
pizza_form = PizzaFormSet(request.POST or None)

choices = [(t.pk, unicode(t)) for t in restaraunt.toppings.all().order_by('-id')]

for form in pizza_form:
    form.fields['toppings'].choices = choices

rawDescription: How to filter the queryset of a django modelformset manytomany memeber

description: Filter the queryset of a django modelformset manytomany memeber


code:
rows = table_service.query_entities( \
    tableName, \
    "((PartitionKey eq '6' and RowKey gt '1452702466022') and RowKey lt '1452702466422')")

rawDescription: Python - How to make range queries in Azure Table Storage


code:
import pandas as pd
csv_loc = 'C:/yourcsv.csv'
df = pd.read_csv(csv_loc, sep=',', header=0) #http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html
df['name'] # would select a column called name
# This would show observations which start with STARBUC
match = df['name'].str.contains('(^STARBUC)')
print(df['name'][match].value_counts())

rawDescription: How Can I Index a CSV File to Search Efficiently?

description: Index a CSV File to Search Efficiently


code:
from tkinter import *
from tkinter import messagebox
calculator = Tk()
calculator.title("Calcualtor")
calculator.geometry("317x145")

menubar = Menu(calculator)

class Calculator(Frame):
    def __init__(self):
        Frame.__init__(self)
        display = Frame(calculator, bd=0, width=1000, height=1000, relief=SUNKEN)
        buttons = Frame(calculator, bd=0, width=7, height=1, relief=GROOVE)
        display.grid(column=0, row=0, padx=0, pady=0)
        buttons.grid(column=0, row=1, padx=1)
        numbers = StringVar()
        self.results = Entry(display, textvariable=numbers, width=31, fg="DarkOrchid4", bg="lavender blush", font="Verdana")
        self.results.pack()
        self.results.grid(column=0, row=0)

        def showup(x):
            return lambda: self.results.insert(END, x)

        numbers=["7", "4", "1", "8", "5", "2", "9", "6", "3"]
        for i in range(9):
            n=numbers[i]
            Button(buttons, bg="snow", text=n, width=7, height=1, command=showup(n), relief=RAISED).grid(row=i%3, column=i//3)

        Clear = Button(buttons, bg="snow", text="C", width=7, height=1, command=self.clear, relief=RAISED)
        Clear.grid(padx=2, pady=2, column=3, row=0)
        All_clear = Button(buttons, bg="snow", text="AC", width=7, height=1, command=self.all_clear, relief=RAISED)
        All_clear.grid(padx=2, pady=2, column=4, row=0)
        Bracket_one = Button(buttons, bg="snow", text="(", width=7, height=1, command=self.bracket_one, relief=RAISED)
        Bracket_one.grid(padx=2, pady=2, column=2, row=3)
        Bracket_two = Button(buttons, bg="snow", text=")", width=7, height=1, command=self.bracket_two, relief=RAISED)
        Bracket_two.grid(padx=2, pady=2, column=3, row=3)
        Zero = Button(buttons, bg="snow", text="0", width=7, height=1, command=self.zero, relief=RAISED)
        Zero.grid(padx=2, pady=2, column=0, row=3)
        Decimal_point = Button(buttons, bg="snow", text=".", width=7, height=1, command=self.decimal_point, relief=RAISED)
        Decimal_point.grid(padx=2, pady=2, column=1, row=3)
        Multiplication = Button(buttons, bg="red", text="x", width=7, height=1, command=self.multiplication, relief=RAISED)
        Multiplication.grid(padx=2, pady=2, column=3, row=1)
        Division = Button(buttons, bg="powder blue", text="/", width=7, height=1, command=self.division, relief=RAISED)
        Division.grid(padx=2, pady=2, column=4, row=1)
        Addition = Button(buttons, bg="yellow", text="+", width=7, height=1, command=self.addition, relief=RAISED)
        Addition.grid(padx=2, pady=2, column=3, row=2)
        Subtraction = Button(buttons, bg="green", text="-", width=7, height=1, command=self.subtraction, relief=RAISED)
        Subtraction.grid(padx=2, pady=2, column=4, row=2)
        Equals = Button(buttons, bg="orange", text="=", width=7, height=1, command=self.equals, relief=RAISED)
        Equals.grid(padx=2, pady=2, column=4, row=3)

    def equals(self):
        try:
            result = eval(self.results.get())
        except:
            result = "Invalid input"
        self.all_clear()
        self.results.insert(0, result)
    def zero(self):
        self.results.insert(END, "0")
    def bracket_one(self):
        self.results.insert(END, "(")
    def bracket_two(self):
        self.results.insert(END, ")")
    def all_clear(self):
        self.results.delete(0, END)
    def clear(self):
        self.results.delete(-1)
    def multiplication(self):
        self.results.insert(END, "x")
    def division(self):
        self.results.insert(END, "/")
    def addition(self):
        self.results.insert(END, "+")
    def subtraction(self):
        self.results.insert(END, "-")
    def decimal_point(self):
        self.results.insert(END, ".")

if __name__ == '__main__':
    Calculator().mainloop()
    calculator.config(menu=menubar)
    calculator.mainloop()

rawDescription: Attribute error python tkinter

description: Attribute error python tkinter


code:
def constrain(val, min_val, max_val):
    return min(max_val, max(min_val, val))

rawDescription: a pythonic way to write a constrain() function

description: A pythonic way to write a constrain() function


code:
a = "A13:F20"
a = filter(lambda x: x.isalpha(), a)

rawDescription: python regular expression, pulling all letters out

description: Python regular expression, pulling all letters out


code:
String = "I saw a frog in my garden"
letter = 'g'
[w for w in String.split() if letter in w]

rawDescription: Search a word in a dictionary

description: Search a word in a dictionary


code:
import re

inputText = """The dodo was one of the sturdiest birds.
An educated termite may learn how to operate a phonograph,
but it's unlikely. I sense that an amalgam that includes
magma will enlighten Papa."""

regex = re.compile(r"((\w{2})\w*\2)")
answer = regex.findall(inputText)
print("answer = {}".format(answer))

rawDescription: Python matching word by using regex

description: Python matching word by using regex


code:
def both_decorators(func):
    return decorator1(decorator2(func))

rawDescription: Making a single decorator of out multiple


code:
def items(self):
    for i, obj in enumerate(Blog.objects.order_by('-pubDate')):
       obj.priority = i < 3 and 1 or 0.5
       yield obj

def priority(self, obj):
    return obj.priority

rawDescription: Priority issue in Sitemaps

description: Priority issue in Sitemaps


code:
import gzip

f_name = 'file.gz'

filtered = []
with gzip.open(f_name, 'r') as infile:
    for line in infile:
        for i in line.split(' '):
            if i.startswith('/bin/movie/tribune'):
                filtered.append(line)
                break # to avoid duplicates

rawDescription: Read Large Gzip Files in Python

description: Read Large Gzip Files in Python


code:
table = pd.pivot_table(df, values='C', index='A',columns='B', aggfunc=len)
df
table

rawDescription: Get value_counts based on multiple column in python


code:
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(x_data,y_data)
ax.set_xlim(xmin=0.0, xmax=1000)
plt.savefig(filename)

rawDescription: Why is set_xlim() not setting the x-limits in my figure?


code:
assert u'/wiki/Cookbook:Bulgarian_Meatball_Soup_(Supa_Topcheta)' == expected[0]
assert u"/wiki/Cookbook:Campfire_S'mores" == expected[1]
assert u'/wiki/Cookbook:Candied_Almonds_(Brända_mandlar)' == expected[2]
assert u'/wiki/Cookbook:Chicken_&_Pasta_Alfredo' == expected[3]
assert u'/wiki/Cookbook:Cozido_à_Portuguesa' == expected[4]

rawDescription: Decoding/Encoding Href Links

description: Decoding/Encoding Href Links


code:
world.browser.get(world.browser.current_url)

element = WebDriverWait(world.browser, 50).until(
    EC.presence_of_element_located((By.ID, "header"))
)

rawDescription: Python-Selenium won't wait for my website to refresh?


code:
def flags(self, index):
    if not index.isValid():
        return Qt.ItemIsEnabled

    if index.column() in self.booleanSet:
        return Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
    elif index.column() in self.readOnlySet:
        return Qt.ItemIsSelectable | Qt.ItemIsEnabled
    else:
        return QSortFilterProxyModel.flags(self, index)

def data(self, index, role):
    if not index.isValid():
        return QVariant()

    if index.column() in self.booleanSet and role in (Qt.CheckStateRole, Qt.DisplayRole):
        if role == Qt.CheckStateRole:
            value = QVariant(Qt.Checked) if index.data(Qt.EditRole).toBool() else QVariant(Qt.Unchecked)
            return value
        else: #if role == Qt.DisplayRole:
            return QVariant()
    else:
        return QSortFilterProxyModel.data(self, index, role)

def setData(self, index, data, role):
    if not index.isValid():
        return False

    if index.column() in self.booleanSet and role == Qt.CheckStateRole:
        value = QVariant(True) if data.toInt()[0] == Qt.Checked else QVariant(False)
        return QSortFilterProxyModel.setData(self, index, value, Qt.EditRole)
    else:
        return QSortFilterProxyModel.setData(self, index, data, role)

rawDescription: How do I create a tree view (with checkbox) inside a combo box - PyQt

description: Create a tree view (with checkbox) inside a combo box - PyQt


code:
from scipy.stats import rv_discrete
numbers = (1,2,3)
distribution = (1./6, 2./6, 3./6)
random_variable = rv_discrete(values=(numbers,distribution))
random_variable.rvs(size=10)

rawDescription: Random number with given PDF in Python

description: Random number with given PDF in Python


code:
with open(file,'r+') as f:
    text = f.read()
    f.seek(0)
    f.truncate()
    f.write(replace_pattern.sub('',text))

rawDescription: read and write the same text file

description: Read and write the same text file


code:
output = np.column_stack((arrA.flatten(),arrB.flatten(),arrC.flatten()))
np.savetxt('output.dat',output,delimiter=',')

rawDescription: Write multiple NumPy arrays into CSV file in separate columns?


code:
class TabBar(QTabBar):

   def tabSizeHint(self, index):
       width = QTabBar.tabSizeHint(self, index).width()
       return QSize(width, your_wanted_height)

rawDescription: PyQt4: Set size of the tab bar in QTabWidget


rawDescription: Getting newest S3 keys first

description: Getting newest S3 keys first


rawDescription: Parsing JIRA webhook comments

description: Parsing JIRA webhook comments


code:
def numToBinary(n):
    '''Returns the string with the binary representation of non-negative integer n.'''
    result = ''
    for x in range(8):
        r = n % 2
        n = n // 2
        result += str(r)

    result = result[::-1]
    return result

def NumToTc(n):
    '''Returns the string with the binary representation of non-negative integer n.'''
    binary = numToBinary(n)
    for digit in binary:
        if int(digit) < 0:
            binary = (1 << 8) + n
    return binary

rawDescription: Convert binary string into two's complement


code:
def index():
    form_component = LOAD('default', 'form.load', ajax=True)
    return dict(form_component=form_component)

def form():
    form = FORM(...).process()
    return dict(form=form)

rawDescription: How to allow multiple form submissions in web2py?

description: Allow multiple form submissions in web2py


code:
# Had to add an edge from 3 to 4 to your example edges
#   or there's no path from 1 to 5
edges = [(1, 2, 1), (2, 3, 2), (3, 4, 1), (4, 5, 2)]

G = networkx.Graph()

for start, end, length in edges:
    # You can attach any attributes you want when adding the edge
    G.add_edge(start, end, length=length)

networkx.shortest_path_length(G, 1, 5, weight='length')
Out[8]: 6

rawDescription: How to specify edge length in Networkx for calculating shortest distance?

description: Specify edge length in Networkx for calculating shortest distance


rawDescription: Performing arithmetic operation on string list


code:
def exp(x, n):
    if n < 0:
        return exp(1 / x, -n)
    elif n == 0:
        return 1
    elif n == 1:
        return x
    elif n % 2 == 0:
        return exp(x * x, n / 2)
    else:
        return x * exp(x * x, (n - 1) / 2)

rawDescription: Repetitive squaring (python)

description: Repetitive squaring (python)


code:
sentence = "The fat cat sat on the mat"
words = sentence.lower().split()
word_to_find = "the"
[pos for pos, word in enumerate(words, start=1) if word == word_to_find]

rawDescription: How to make a python program that lists the position/positions of a certain word in a sentence

description: Make a python program that lists the position/positions of a certain word in a sentence


rawDescription: Efficient way to check for a M2M intersection in Django?


code:
for index, value in enumerate(EPL_10, start=1):
    Label(root, text=str(index)).grid(row=index, column=0, sticky='W')
    Label(root, text=value).grid(row=index, column=1, sticky='W')

rawDescription: Output text as Label in GUI rather than printing Python 2


code: hist, bin_edges = apply_along_axis(lambda x: histogram(x, bins=bins), 0, B)

rawDescription: Numpy histogram on multi-dimensional array


code:
c = [el for el in a if (el-1) in b]
d = [el for el in b if (el+1) in a]

rawDescription: How do I reduce the contents of a list based on the values of the other list?

description: Reduce the contents of a list based on the values of the other list


code: [{"pk": 1, "model": "app_name.model", "fields": {"field1": "value1", "field2": "value2", }}, {"pk": 2, "model": "app_name.model", "fields": {"fiel1": "value2", "field2": "value2",  }}]

rawDescription: Will data be displayed after a new migration?


code:
class DailyStats(object):
    pass

row = ['10', '20', '30', '40', '50']

daily_stats = DailyStats()

items = {'Turnover':0,
         'Cars':1,
         'Cash':[2,3,4]}

for item, value in items.items():
    try:
        val = sum(int(row[val]) for val in value)
    except TypeError:
        val = int(row[value])
    setattr(daily_stats, item, val)

print(daily_stats.Turnover) # 10
print(daily_stats.Cars) # 20
print(daily_stats.Cash) # 120

rawDescription: Pythonic Variable Assignment

description: Pythonic Variable Assignment


code:
cl = ['a', 'b', 'c', 'd', 'e']
rangeiter = iter(xrange(0, len(cl)))
for x in rangeiter:
    print('{}-'.format(x)),
    for y in xrange(x, len(cl)):
        print('{}'.format(cl[y])),
        if y == 3:
            print
            break
    # fast forward parent range
    next(dropwhile(lambda v: v < y, rangeiter), None)

rawDescription: Fast Forward an xrange from Nested Loop Using Dropwhile?


code:
d = {}
for line in result:
    d[line[0], line[1]] = line[2:]

rawDescription: Find an item in a list of lists by multiple elements


code:
for row in reader:
    if headers:
        conn.execute('INSERT INTO COMPANY (Brand, Stock_Code, Description, Quantity, Price_Ex_VAT) VALUES (?,?,?,?,?);', (row[0],    row[1], row[2], row[3], row[4]))
        y = y + 1
        if x == 0:
            stdout.write("\rWorking \\")
            #print("Working.", end = "")
        elif x == 1:
            stdout.write("\rWorking |")
            #print("Working..", end="")
        elif x == 2:
            stdout.write("\rWorking /")
            #print("Working..", end="")
        else:
            stdout.write("\rWorking -")
            x = -1
            #print("Working", end = "")
        stdout.flush()
        x = x +1
    else:
        headers = True
        stdout.write("\n") # move the cursor to the next line
    stdout.write("Complete ")
    stdout.write(str(y))

rawDescription: Python Indentation (for loop)

description: Python Indentation (for loop)


code:
from urllib import urlopen

def get_context_data(self, **kwargs):
    context = super(IndexView, self).get_context_data(**kwargs)
    my_stock_url = 'http://mystockpage.org/stocks/'
    context['stocks'] = json.loads(urlopen(my_stock_url).read())
    context['last_stock'] = stocks[0]['target'].split()[2].strip(')')
    return context

rawDescription: Importing JSON data into Django View/Template


rawDescription: How to get largest value from the 2-d array in python

description: Get largest value from the 2-d array in python


code: result = [o for o in msg1 if o[3:] not in [field[3:] for field in msg2]]

rawDescription: How to compare lists in Python for partial matches?

description: Compare lists in Python for partial matches


rawDescription: MOD_WSGI : "SERVER_NAME"( of php) equivalency in Python or WSGI?


code:
def __init__ (self, id, description):
    self.content = 'item %s: %s...' % (str(id), description[:25])
    self.item = urwid.AttrWrap(
        urwid.Text('item %s: %s' % (id, description)), 'body', 'focus'
        )
    super(ItemWidget, self).__init__(self.item)

rawDescription: Urwid: how to select the whole row, not one column?


code:
from idlelib import PyShell,EditorWindow
import threading,sys
try:
    import tkinter as tk #python 3.X
except ImportError:
    import Tkinter as tk #python 2
    import tkMessageBox as messagebox
    tk.messagebox = messagebox

class ThreadShell(PyShell.PyShell):
    """mostly copied from idlelib.PyShell module but adapted to work with threads"""
    #__adapted_by__ = "Tadhg McDonald-Jensen"
    def __init__(self, tk_root,target=None):
        #not sure exactly what the FileList object is for but it is required by the shell
        flist = PyShell.PyShellFileList(tk_root)
        super(ThreadShell,self).__init__(flist)

        #internal event flag for input, allows thread waiting for input to wait until a tk event handles it
        self.__input_flag = threading.Event()
        #target is stored and called in .run_command() which also deals with finishing the shell
        self.target = target
        self.thread = threading.Thread(target=self.run_command)
        #tk_root.after makes the .start method call when the program starts (after 0 miliseconds)
        tk_root.after(0,self.start)

    def start(self):
        """starts executing the Thread"""
        super(ThreadShell,self).beginexecuting()
        try:
            self.thread.start()
        except RuntimeError:
            self.executing = 0
            self.canceled = 0
            #self.top.quit() #this causes double deletion warnings with better Implementation of mainloop

    beginexecuting = start

    def run_command(self):
        """calls target from constructor with self as argument then cleans up shell"""
        if self.target:
            self.target(self)
        self.prompt_exit()
        self.executing = 0
        self.canceled = 0
        try:
            self.text.after(1,self.close)
        except RuntimeError:
            pass #tkinter has issues with changing threads so often after closing one shell others will throw this error

    def printf(self,*stuff,**kw):
        """works just like python 3.x print function but writes to shell's .stdout file"""
        if self.executing:
##            if USING_OLD_METHOD:       #Pretty sure this would do exact same thing
##                kw.setdefault("file",self.stdout)
##                print(*stuff,**kw), self.resetoutput()
##                return
            sep = kw.get("sep"," ")
            end = kw.get("end","\n")
            text = sep.join(stuff) + end
            self.stdout.write(text)
            self.resetoutput()

    def input(self,prompt="",timeout=None):
        """python 2 equivelent to raw_input or py 3+ input
Prompts user for input and freezes thread until input is given
Will return "" if .executing is False or it timed out from optional timeout argument"""
        if self.executing or self.closing:
            if prompt:
                self.stdout.write(prompt)
            self.__in_buffer = ""
            self.__input_flag.clear()
            self.reading=True
            self.__input_flag.wait(timeout)
            #input is inserted into .__in_buffer by other events
            #then set __input_flag so that it can be delivered to thread
            self.reading = False
            return self.__in_buffer.strip("\n")
        else:
            raise RuntimeError("cannot take input after finished")

    def prompt_exit(self):
        """writes press enter to quit" to the console colour then waits for input"""
        self.executing = False
        self.closing = True
        self.console.write("\n press enter to quit")
        self.input()

    def join_thread(self,timeout=None):
        """sets .executing label to False then waits to join thead,
returns True if thread finished or False if timeout activated"""
        self.executing = False
        self.closing = True
        if self.thread:
            self.thread.join(timeout)
        return not self.thread.is_alive()

    def _close(self):
        "Extend EditorWindow._close(), joins thread to close it"

        # Restore std streams
        sys.stdout = self.save_stdout
        sys.stderr = self.save_stderr
        sys.stdin = self.save_stdin
        # Break cycles
        self.interp = None
        self.console = None
        self.flist.pyshell = None
        self.history = None
        EditorWindow.EditorWindow._close(self)
        self.join_thread()

    def stop_readline(self):
        self.__in_buffer = ""
        self.__input_flag.set()

    def update_in(self):
        """updates input from user, I think some of the labels are probably unnecessary but it is easier to leave it alone"""
        line = self.text.get("iomark", "end-1c")
        if len(line) == 0:  # may be EOF if we quit our mainloop with Ctrl-C
            line = "\n"
        self.resetoutput()
        if self.canceled:
            self.canceled = 0
        if self.endoffile:
            self.endoffile = 0
            line = ""
        self.__in_buffer = line
        self.__input_flag.set()

    def cancel_callback(self, event=None):
        try:
            if self.text.compare("sel.first", "!=", "sel.last"):
                return # Active selection -- always use default binding
        except:
            pass
        if not (self.executing or self.reading):
            return "break"
        self.endoffile = 0
        self.canceled = 1
        if self.reading:
            self.update_in()
        return "break"

    def eof_callback(self, event):
        if self.executing and not self.reading:
            return # Let the default binding (delete next char) take over
        if not (self.text.compare("iomark", "==", "insert") and
                self.text.compare("insert", "==", "end-1c")):
            return # Let the default binding (delete next char) take over
        if not self.executing:
            self.resetoutput()
            self.close()
        else:
            self.canceled = 0
            self.endoffile = 1
            self.update_in()
        return "break"

    def enter_callback(self, event):
        """called when the enter/return key is pressed,
only the recursive self.top.mainloop() / self.top.quit() had to be changed for support"""
        # it is very long to copy/paste for the one line change, so I override the method temporarily
        save = self.top.quit
        self.top.quit = self.update_in
        super(ThreadShell,self).enter_callback(event)
        self.top.quit = save

#stupid module depends on this being set from the main function, so it needs to be done manually
PyShell.use_subprocess = True

#this defines the root tkinter window and sets it up
root = tk.Tk()
EditorWindow.fixwordbreaks(root)
root.withdraw()
#I need this to work on my mac, not sure if there are other OS specific stuff that should be included
try:
    from idlelib import macosxSupport
    macosxSupport.setupApp(root, None)
except (ImportError,AttributeError):
    pass

##!!!!!!!!!!!!!!!!!!!! And This Is The Part You Need To Worry About !!!!!!!!!!!!!!!!!!!!##

switch = threading.Event()
switch.clear()

def foo(shell):
    global x
    x = shell.input("enter a message: ")
    switch.set()
    shell.printf("message sent")

def foo2(shell):
    shell.printf("waiting for message...")
    while shell.executing and not switch.is_set():
        switch.wait(2)   # by using shell.executing in the loop it will occasionally check
                         # if the program should quit because the window was closed
    if shell.executing:
        shell.printf("message recieved: ",x)

shell1 = ThreadShell(root,foo)
shell2 = ThreadShell(root,foo2)
first_time = True
while shell1.executing or shell2.executing or first_time:
    first_time = False
    root.mainloop()
root.destroy()

rawDescription: How to run a function/thread in a different terminal window in python?

description: Run a function/thread in a different terminal window in python


code:
url= "http://www.nsf.gov/awardsearch/showAward?AWD_ID=1227110&HistoricalAwards=false"
import requests

from bs4 import BeautifulSoup

r = requests.get(url)

tds = BeautifulSoup(r.content).find_all("td",{"class":"tabletext2"})

print([td.find_next("td").text.strip() for td in tds if td.text.startswith("Program Reference Code(s)")])

[u'131E, 113E, 8048, 7433']

rawDescription: Grabbing td element under web scrapping in Python


code:
payload = 'ZZZZZZZZZZZZZZZZZZZZZ'
pkt = Ether() / IP() / TCP() / payload

rawDescription: Specifying packet length with scapy

description: Specifying packet length with scapy


code: any(x.name == "t2" for x in l)

rawDescription: Check if List of Objects contain an object with a certain attribute value


code:
from math import radians, cos, sin, atan2, sqrt, pow, pi, log, floor, tan, atan, exp

class Coordinate(object):
    def __init__(self, lat, lng):
        """
        Represents a coordinate with decimal latitude and longitude in degrees
        :type lat: float
        :type lng: float
        """
        self.lat = lat
        self.lng = lng

    def in_rectangle(self, box):
        """
        :param box: Box
        :return: True or False
        """
        return (box.south_west.lat <= self.lat <= box.north_east.lat) and \
               (box.south_west.lng <= self.lng <= box.north_east.lng)

    def distance_to_coordinate(self, another_coordinate):
        # convert decimal degrees to radians
        """
        Calculates the distance between the coordinate and the supplied coordinate. Based on the Haversine formula.
        Returns the value in meters.
        :param another_coordinate: Coordinate
        :return: float
        """
        lon1, lat1, lon2, lat2 = map(radians, [self.lng, self.lat, another_coordinate.lng, another_coordinate.lat])
        # haversine formula
        delta_lon = lon2 - lon1
        delta_lat = lat2 - lat1
        a = sin(delta_lat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(delta_lon / 2) ** 2
        c = 2 * atan2(sqrt(a), sqrt(1-a))
        km = 6378100 * c
        return km

class Box(object):
    def __init__(self, south_west, north_east):
        """
        Represents a rectangle on the sphere with the south west and north east corners.
        :type north_east: Coordinate
        :type south_west: Coordinate
        """
        self.north_east = north_east
        self.south_west = south_west

    def center(self):
        """
        Calculates the center point of the box
        :rtype : Coordinate
        """
        lat_center = self.south_west.lat + (self.north_east.lat-self.south_west.lat)/2
        lng_center = self.south_west.lng + (self.north_east.lng-self.south_west.lng)/2
        return Coordinate(lat_center, lng_center)

def max_zoom_level_to_fit_box_in_element(box, element_width, element_height):
    """
    Calculates the maximum zoom level that would fit box in a map element with the specified width and height
    :type box: Box
    :type element_height: float
    :type element_width: float
    """
    WORLD_HEIGHT = 256
    WORLD_WIDTH = 256
    ZOOM_MAX = 21
    ne = box.north_east
    sw = box.south_west

    lat_fraction = (_lat_to_rad(ne.lat) - _lat_to_rad(sw.lat)) / pi
    lng_delta = ne.lng - sw.lng
    lng_fraction = ((lng_delta+360) if lng_delta < 0 else lng_delta)/360

    lat_zoom = _zoom(element_height, WORLD_HEIGHT, lat_fraction)
    lng_zoom = _zoom(element_width, WORLD_WIDTH, lng_fraction)

    return min(lat_zoom, lng_zoom, ZOOM_MAX)

def viewport_for_box_in_element(box, element_width, element_height, zoom):
    """
    Calculates the viewport, rectangle, which will fit box within it for a given map size and zoom level.
    The return value is a box, with coordinates on the sphere.
    :param box: Box
    :param element_width: float
    :param element_height: float
    :param zoom: float
    :return: Box
    """
    center_x, center_y = _lat_and_lng_to_x_and_y_for_zoom(box.center().lat, box.center().lng, zoom)

    viewport_sw_x, viewport_sw_y = center_x - element_width/2, center_y+element_height/2
    viewport_ne_x, viewport_ne_y = center_x + element_width/2, center_y-element_height/2

    viewport_sw = _x_and_y_to_lat_and_lng_for_zoom(viewport_sw_x, viewport_sw_y, zoom)
    viewport_ne = _x_and_y_to_lat_and_lng_for_zoom(viewport_ne_x, viewport_ne_y, zoom)

    return Box(viewport_sw, viewport_ne)

def _lat_and_lng_to_x_and_y_for_zoom(lat, lng, zoom):
    """
    Converts decimal degree coordinates on the sphere to x and y points on the flat Web Mercator projection, for a
    given zoom level.
    :param lat: float
    :param lng: float
    :param zoom: float
    :return: x,y: float
    """
    lat_rad = lat * (pi/180)
    lng_rad = lng * (pi/180)
    x = (128/pi)*pow(2, zoom)*(lng_rad + pi)
    y = (128/pi)*pow(2, zoom)*(pi-log(tan(pi/4+lat_rad/2)))
    return x, y

def _x_and_y_to_lat_and_lng_for_zoom(x, y, zoom):
    """
    Converts x and y points on the flat Web Mercator projection, for a given zoom level, to decimal degrees on the
    spehere.
    :param x: float
    :param y: float
    :param zoom: float
    :return: Coordinate
    """
    lng_rad = (x*pi)/(pow(2, zoom)*128)-pi
    lat_rad = 2*atan(exp(pi-((y*pi)/(pow(2, zoom)*128))))-pi/2
    return Coordinate(lat_rad*(180/pi), lng_rad*(180/pi))

def _lat_to_rad(lat):
    """
    Converts a decimal degree latitude to radians, given the fact how Web Mercator projection wraps on the latitude.
    :param lat: float
    :return: float
    """
    _sin = sin(lat * pi / 180)
    rad_x2 = log((1 + _sin) / (1 - _sin)) / 2
    return max(min(rad_x2, pi), -pi) / 2

def _zoom(map_px, world_px, fraction):
    """
    Calculates a zoom level
    :param map_px: float
    :param world_px: float
    :param fraction: float
    :return:
    """
    ln_2 = log(2)
    return floor(log(map_px / world_px / fraction) / ln_2)

rawDescription: Calculate viewport that fitBounds() return for given bounds and map size


code:
tags = db.session.query(
    db.coalesce(db.func.count(models.followers.c.follower_id), 0).label('total'),
    models.Tag.name,
    models.Tag.title
).outerjoin(models.followers).group_by(
    models.Tag.name,
    models.Tag.title
).order_by('total DESC')

rawDescription: SQLAlchemy count followers to a tag

description: SQLAlchemy count followers to a tag


code: root.grid_columnconfigure(0, weight=1)

rawDescription: Expand Text widget to fill the entire parent Frame in Tkinter


code:
def get_members(obj, typ, include_public=[], imported=False):
    items = []
    for name in dir(obj):
        try:
            obj_name = safe_getattr(obj, name)
            documenter = get_documenter(obj_name, obj)
        except AttributeError:
            continue
        if documenter.objtype == typ:
            try:
                cond = (
                    imported or
                    obj_name.__module__ == obj.__name__
                    )
            except AttributeError:
                cond = True
            if cond:
                items.append(name)
    public = [x for x in items
              if x in include_public or not x.startswith('_')]
    return public, items

rawDescription: sphinx autosummary with toctree also lists imported members

description: Sphinx autosummary with toctree also lists imported members


rawDescription: How to get an array with modulus from array with complex numbers?

description: Get an array with modulus from array with complex numbers


code:
def parse(self, response):
     return scrapy.Request(url,
                           meta={"number": number},
                           callback=self.parse_page)

def parse_page(self, response):
    print(response.meta["number"])

rawDescription: how to keep a reference for the requests in scrapy

description: Keep a reference for the requests in scrapy


code: citiesTruncated = {key.replace(" ", ""): value for key, value in cities.items()}

rawDescription: Way to combine substrings in dictionary keys


code:
U = np.zeros((N,N))
ind = 1
k = np.zeros(N)
k[:] = U[ind,:]

rawDescription: root mean square in numpy and complications of matrix and arrays of numpy

description: Root mean square in numpy and complications of matrix and arrays of numpy


code:
class Bicycle:

    def __init__(self):
        self.cadence = 0
        self.speed  = 0
        self.gear  =1

    def changeCadence(self, newValue):
        self.cadence = newValue

    def changeGear(self, newValue):
        self.gear = newValue

    # and same for other functions

if __name__ == "__main__":
    obj = Bicycle()
    obj.changeCadence()

rawDescription: Python equivalent from a very simple Java program example