code:
variables = []

with open('filename.txt') as input:
    colour = mass = ''
    for line in input:
        fields = line.split()
        if len(fields)>6:
            value = fields[6]
            if 'The colour' in line:
                colour = value
            elif 'The mass' in line:
                mass = value
        elif line.startswith('Object'):
            variables.append((colour, mass))
            colour = mass = '' # may not be needed.
del(variables[0])

rawDescription: Python text file searching for values and compiling results found


code:
from itertools import *
from operator import mul
d = {2:2,5:1} # result of pf(20)
l = list(chain(*([k] * v for k, v in d.iteritems())))
l
factors = set(chain(*(permutations(l, i) for i in range(1,len(l)+1))))
set(reduce(mul, fs, 1) for fs in factors)

rawDescription: pythonic way of getting the list of divisors given prime factorization

description: Pythonic way of getting the list of divisors given prime factorization


code:
if PY_MAJOR_VERSION >= 3:
    from pickle import dumps as PyPickle_dumps
    from pickle import loads as PyPickle_loads
    from pickle import DEFAULT_PROTOCOL as PyPickle_PROTOCOL
else:
    try:
        from cPickle import dumps as PyPickle_dumps
        from cPickle import loads as PyPickle_loads
        from cPickle import HIGHEST_PROTOCOL as PyPickle_PROTOCOL
    except ImportError:
        from pickle  import dumps as PyPickle_dumps
        from pickle  import loads as PyPickle_loads
        from pickle  import HIGHEST_PROTOCOL as PyPickle_PROTOCOL

rawDescription: Does mpi4py use Python Pickle

description: Does mpi4py use Python Pickle


code:
from xml.etree.ElementTree import ElementTree
tree = ElementTree()
tree.parse("index.xhtml")

rawDescription: generate xml with sax2 in python

description: Generate xml with sax2 in python


code:
def poisson_probability(actual, mean):
    # naive:   math.exp(-mean) * mean**actual / factorial(actual)

    # iterative, to keep the components from getting too large or small:
    p = math.exp(-mean)
    for i in xrange(actual):
        p *= mean
        p /= i+1
    return p

rawDescription: Calculate poisson probability percentage


rawDescription: Sort three dimensional numpy array with two axes sorting constraints


code: subprocess.call(['/usr/local/bin/growlnotify', '-n',  'emesene', '-a', 'emesene', '-t', title, '-m', text])

rawDescription: Using Python subprocess rather than os.system


code:
@classmethod
def from_user(cls, user):
    return cls.objects.get(username=user.username)

rawDescription: Can an object method return an instance of the object?


code: number &= ~0xf

rawDescription: How To Mask Out Lower 'x' Bits of Python Integer Of Unknown Size


code:
mainList = [['foo', 'bar', 'baz'], ['spam', 'ham', 'eggs'], ['idle', 'cleese', 'jones']]
sliced = mainList[:2]
sliced
sliced[0][1] = 'parrot'
mainList

rawDescription: How can I get a range of rows in a python list without creating a new list object?

description: Get a range of rows in a python list without creating a new list object


rawDescription: PIL/Pillow convert Image to list and back again


code:
import re
s = '6M1I69M1D34M'
matches = re.findall(r'(\d+)([A-Z]{1})', s)
import pprint
pprint.pprint([{'type':m[1], 'length':int(m[0])} for m in matches])

rawDescription: Elegant parsing of text-based key-value list


code:
import os, win32com.client

def runScreensaver():
    strComputer = "."
    objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
    objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
    colItems = objSWbemServices.ExecQuery("Select * from Win32_Desktop")
    for objItem in colItems:
        if objItem.ScreenSaverExecutable:
            os.system(objItem.ScreenSaverExecutable + " /start")
            break

rawDescription: Control Screen with Python

description: Control Screen with Python


code:
wide_list = [[1,['a','b','c']],[2,['d','e']],[3, ['f']]]
long_list = [[k, v] for k, sublist in wide_list for v in sublist]
long_list

rawDescription: reshape an irregular list in python

description: Reshape an irregular list in python


code:
for line in fileinput.input(self.view.file_name(), inplace=1):
  sys.stdout.write(self.makeReplacements(line))

rawDescription: Search and replace in current file with Sublime Text plugin


code:
from sqlalchemy import case

@func.expression
def func(cls):
    return case(
        [
            (cls.some_column == True, cls.true_column * cls.amount),
        ],
        else_=cls.false_column * cls.amount
    )

rawDescription: if statement in a hybrid_property expression

description: If statement in a hybrid_property expression


code:
fig = plt.figure(figsize(15,8))
ax = fig.gca(projection='3d')

x = FilteredDF['Wavelength']
z = FilteredDF['DNI']
y = FilteredDF['TESTNUM']

ax.scatter(x, y, z, c=plt.cm.jet(z/max(z)))

ax.set_xlabel('Wavelength')
ax.set_ylabel('Test Number')
ax.set_zlabel('Intensity')

plt.show()

rawDescription: Python - color a 3d line plot

description: Python - color a 3d line plot


code:
def magicmethod(clazz, method):
    if method not in clazz.__dict__:  # Not defined in clazz : inherited
        return 'inherited'
    elif hasattr(super(clazz), method):  # Present in parent : overloaded
        return 'overloaded'
    else:  # Not present in parent : newly defined
        return 'newly defined'

rawDescription: Is there a way to identify an inherited method in Python?


code:
import sys
from PyQt4 import QtCore, QtGui
Qt = QtCore.Qt

class PandasModel(QtCore.QAbstractTableModel):
    def __init__(self, data, parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self._data = data

    def rowCount(self, parent=None):
        return len(self._data.values)

    def columnCount(self, parent=None):
        return self._data.columns.size

    def data(self, index, role=Qt.DisplayRole):
        if index.isValid():
            if role == Qt.DisplayRole:
                return QtCore.QVariant(str(
                    self._data.values[index.row()][index.column()]))
        return QtCore.QVariant()

if __name__ == '__main__':
    application = QtGui.QApplication(sys.argv)
    view = QtGui.QTableView()
    model = PandasModel(your_pandas_data)
    view.setModel(model)

    view.show()
    sys.exit(application.exec_())

rawDescription: Fastest way to populate QTableView from Pandas data frame


rawDescription: Python: Replace a number in array with a string


code:
def handle_events (self):
    """
    If you override this method in a subclass of the Screen
    class, you can specify how to handle different kinds of
    events.  However you must handle the quit condition!
    """
    events = pygame.event.get ()
    for event in events:
        if event.type == QUIT:
            self.quit ()
        elif event.type == KEYDOWN:
            self.keypress (event.key)
        elif event.type == MOUSEBUTTONUP:
            self.mouse_up (event.pos, event.button-1)
        elif event.type == MOUSEBUTTONDOWN:
            self.mouse_down (event.pos, event.button-1)

def quit (self):
    """
    Calling this method will stop the main loop from running and
    make the graphics window disappear.
    """

    self._exit = 1

def mainloop (self, fps = 50):
    """
    Run the pygame main loop. This will animate the objects on the
    screen and call their tick methods every tick.

    fps -- target frame rate
    """

    self._exit = 0

    while not self._exit:
        self._wait_frame (fps)

        for object in self._objects:
            if not object._static:
                object._erase ()
                object._dirty = 1

        # Take a copy of the _objects list as it may get changed in place.
        for object in self._objects [:]:
            if object._tickable: object._tick ()

        self.tick ()

        if Screen.got_statics:
            for object in self._objects:
                if not object._static:
                    for o in object.overlapping_objects ():
                        if o._static and not o._dirty:
                            o._erase ()
                            o._dirty = 1

        for object in self._objects:
            if object._dirty:
                object._draw ()
                object._dirty = 0

        self._update_display()

        self.handle_events()

    # Throw away any pending events.
    pygame.event.get()

rawDescription: pygame freezes when I try to exit it after running it from IDLE!

description: Pygame freezes when I try to exit it after running it from IDLE!


rawDescription: ListField without duplicates in Python mongoengine


code: result_file = open('result1.json', 'a')

rawDescription: Saving tweets in a file, but they are overwritten by Python


code:
import csv

datafile1 = csv.reader(open('datafile1.csv','rb'), delimiter=",", quotechar='|')
datafile2 = csv.reader(open('datafile2.csv','rb'), delimiter=",", quotechar='|')

class data(object):

    def __init__(self,data_file):

        self.date, self.data1, self.data2, self.data3 = [], [], [], []

        for row in data_file:
            self.date.append(row[0])
            self.data1.append(row[1])
            self.data2.append(row[2])
            self.data3.append(row[3])

data1 = data(datafile1)
data2 = data(datafile2)

rawDescription: How do I change this code into oop format so I can re-use code

description: Change this code into oop format so I can re-use code


code:
import json

user_dict = {'some user': 'some password'}

with open('my_database.json', 'w') as db:
    json.dump(user_dict, db)

# Now the data can be can easily loaded
user_data = json.load(open('my_database.json'))

# This will get you the dictionary back.

rawDescription: How do I take a text file and turn it into a dictionary in python

description: Take a text file and turn it into a dictionary in python


rawDescription: Preserving the dimensions of a slice from a Numpy 3d array


code:
xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
xl.Visible = True
xl.RegisterXLL('C:/path/addin.xll')
wb = xl.Workbooks.Open('Test.xlsx')

rawDescription: Load Excel add-in using win32com from Python


code:
from matplotlib.colors import LinearSegmentedColormap
data = np.array([[1, 0, 0, 1],
                 [0, 0, 1, 1],
                 [0, 0, 0, 1]])
colorInformation = np.array([[0.1, 0.12, 0.02, 0.01],
                             [0.12, 0.15, 0.18, 0.2],
                             [0.3, 0.34, 0.41, 0.32]])
alpha_up=abs(((data*2-1)*colorInformation).max())
alpha_low=abs(((data*2-1)*colorInformation).min())
mid=alpha_low/(alpha_up+alpha_low)
cdict1 = {'red':   ((0.0, 1.0, 1.0),
                   (mid, 1.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'green': ((0.0, 0.0, 0.0),
                   (1.0, 0.0, 0.0)),

         'blue':  ((0.0, 0.0, 0.0),
                   (mid, 0.0, 1.0),
                   (1.0, 1.0, 1.0)),

         'alpha':  ((0.0, alpha_low, alpha_low),
                   (mid, 0.0, 0.0),
                   (1.0, alpha_up, alpha_up))
        }
red_blue = LinearSegmentedColormap('red_blue', cdict1)
fig, ax = plt.subplots()
heatmap = ax.pcolormesh((data*2-1)*colorInformation, cmap=red_blue)

rawDescription: Matplotlib pcolormesh, separate datacolor and color brightness information


code:
make_pipeline(
    make_union(
        make_pipeline(FeatureSelector(some_columns), CountVectorizer()),
        make_pipeline(FeatureSelector(other_columns), CountVectorizer())),
    SGDClassifier())

rawDescription: scikit-learn pipeline

description: Scikit-learn pipeline


code:
my_file = open(filename, "r")
lines_of_file = my_file.readlines()
lines_of_file.insert(-1, "This line is added one before the last line")
my_file.writelines(lines_of_file)

rawDescription: How to update/modify a XML file in python?

description: Update/modify a XML file in python


code:
import os
from .implementation import some_other_api_call

_module_path = os.path.dirname(os.path.abspath(__file__))
_template = open(os.path.join(_module_path, 'templates/foo_template.txt')).read()

VERSION = '1.0.0'

def make_bar(baz, ham, spam):
    return _template.format(baz, ham, spam)

__all__ = ['some_other_api_call', 'make_bar']

rawDescription: Should I define __all__ even if I prefix hidden functions and variables with underscores in modules?


code:
import SocketServer
from SocketServer import BaseRequestHandler
import threading

class HTTPSERVER(BaseRequestHandler):

    def handle(self):
        rec = self.request.recv(1024)
        if rec:
           self.request.send('Got something!')

launchme = SocketServer.TCPServer(('', 82),HTTPSERVER)
launchme2 = SocketServer.TCPServer(('', 81),HTTPSERVER)
launchme3 = SocketServer.TCPServer(('', 80),HTTPSERVER)
t1 = threading.Thread(target=launchme.serve_forever)
t2 = threading.Thread(target=launchme2.serve_forever)
t3 = threading.Thread(target=launchme3.serve_forever)
for t in t1, t2, t3: t.start()
for t in t1, t2, t3: t.join()

rawDescription: SocketServer bind multiple server

description: SocketServer bind multiple server


code: date_list = [my_dt_ob.year, my_dt_ob.month, my_dt_ob.day, my_dt_ob.hour, my_dt_ob.minute, my_dt_ob.second]

rawDescription: how to convert a python datetime.datetime into a list

description: Convert a python datetime.datetime into a list


code:
import re
input_dirs = """dir/file  10
dir/dir2/file2  20
dir/dir2/file3  10
dir/file  10
dir3/file4  10
dir3/file5  10
dir/dir2/dir4/file2 10"""

def create_file_tree(input_string):
    dir_dict = {}
    for file_path in input_string.split('\n'):
        path_list = re.sub('/',' ',file_path).split()
        path_list[-1] = int(path_list[-1])
        path_dict = dir_dict
        final_item = ""
        for item in path_list[:-1]:
            parent_dict = path_dict
            last_item = item
            path_dict = path_dict.setdefault(item,{})
        parent_dict[last_item] = path_list[-1]
    return dir_dict

def pretty_file_tree(file_tree):
    def traverse(sub_dict,indent=0, total=0):
        string_out = ""
        indent += 1
        for key in sorted(sub_dict.keys()):
            if type(sub_dict[key]) == dict:
                sub_total = traverse(sub_dict[key],indent,0)
                total += sub_total[0]
                string_out += '  '*indent + key + ' ' + '**' + str(sub_total[0]) + '**' + '\n' + sub_total[1]
            else:
                string_out += '  '*indent + key  + '\n'
                total += sub_dict[key]

        return total, string_out

    output_string = traverse(file_tree)
    print(output_string[1])

pretty_file_tree(create_file_tree(input_dirs))

rawDescription: Working with nested dictionaries and formatting for display


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('navigate to url')

select_elem = driver.find_element_by_id('TargetRadius')
select_elem.click()
options = select_elem.find_elements_by_tag_name('option')
options[len(options)-1].click()

rawDescription: How can I select the last drop-down option in selenium with python?

description: Select the last drop-down option in selenium with python


code:
import psycopg2

for k in psycopg2.extensions.string_types.keys():
    del psycopg2.extensions.string_types[k]

cnn = psycopg2.connect('')
cur = cnn.cursor()
cur.execute("select 1::int, now()::timestamp, 'hello'::text")
cur.fetchone()
('1', '2011-12-19 16:50:11.396855', 'hello')

rawDescription: psycopg2 - how to always cast non-string value to string

description: Psycopg2 - how to always cast non-string value to string


code: dataRaw = pd.read_csv(name,sep=";|,")

rawDescription: Load .csv with unknown delimiter into Pandas DataFrame


code:
img_aspect_ratio =  float(pixmap.size().width()) / pixmap.size().height()
width = img_view.size().width()
img_view.setFixedHeight( width / img_aspect_ratio )
img_view.fitInView(img_scene.sceneRect(), QtCore.Qt.KeepAspectRatio)

rawDescription: PyQt4: Graphics View and Pixmap Size

description: PyQt4: Graphics View and Pixmap Size


code:
from collections import defaultdict
import json

def show_api(self):
    api_dict = defaultdict(dict)

    for route in self.bottle.routes:
        api_dict[route.rule]['url'] = 'http://myhost:port{}'.format(route.rule)
        api_dict[route.rule]['method'] = route.method

        # additional config params
        for key in route.config:
            api_dict[route.rule][key] = route.config[key]

    return json.dumps(api_dict)

rawDescription: Is there a way to automatically generate REST API JSON description from Bottle routes


code:
import threading, time
from msvcrt import getch

key = "lol"

def thread1():
    global key
    lock = threading.Lock()
    while True:
        with lock:
            key = getch()

threading.Thread(target = thread1).start()

while True:
    time.sleep(1)
    print(key)

rawDescription: How to use threads to get input from keyboard in python 3?

description: Use threads to get input from keyboard in python 3


code:
import matplotlib.pyplot as plt
import itertools

fig=plt.figure()
ax=fig.add_subplot(111)
all_data = [[1,10],[2,10],[3,10],[4,10],[5,10],[3,1],[3,2],[3,3],[3,4],[3,5]]
plt.plot(
    *zip(*itertools.chain.from_iterable(itertools.combinations(all_data, 2))),
    color = 'brown', marker = 'o')

plt.show()

rawDescription: How do you create line segments between two points?

description: Create line segments between two points


code:
writeto=['insert path to save to here']
save(writeto)
first_Pypath=['insert path of python script here']
py_call=horzcat('python ',first_Pypath);
system(py_call);

rawDescription: Alternate between Executing a MATLAB file and a Python script


code: qs_new = model_obj.objects.filter(...)

rawDescription: Multiple fields in the where clause of a QuerySet?


rawDescription: Python sorting dictionaries: Key [Ascending] and then Value [Descending]


code:
import fnmatch
import os
import shutil

rootPath = '/Volumes/VoigtKampff/Temp/TEST/'
destDir = '/Volumes/VoigtKampff/Temp/TEST2/'

matches = []

for root, dirnames, filenames in os.walk(rootPath):
    for filename in fnmatch.filter(filenames, '*.mp4'):
        matches.append(os.path.join(root, filename))
        print(os.path.join(root, filename))
        targetDir = os.path.join(destDir, root[len(rootPath):])
        if not os.path.exists(targetDir):
            os.makedirs(targetDir)
        shutil.move(os.path.join(root, filename), os.path.join(targetDir, filename))

rawDescription: recursive find files with python

description: Recursive find files with python


code: sorted(obj, key=lambda x: (x.name[0], int(x.name[1:])))

rawDescription: Sort list of objects by attribute alphanumerically


code:
from django.db.models import Q

query = Q()
for entry in a:
    query = query | Q(my_field__contains=entry)

queryset = MyModel.objects.filter(query)

rawDescription: django "__contains" and "__in" as a single query

description: Django "__contains" and "__in" as a single query


code:
from collections import Counter
cnt = Counter()
for key, values in t.items():
    for item in values:
        cnt[item] += 1

print([comp for comp in cnt if cnt[comp] > 1])

rawDescription: Multidicts and Sets

description: Multidicts and Sets


code:
class C(B):
    def preprocess(self, x):
        return x + x

rawDescription: Python: how to resolve this class inheritance


code:
import glob
from zipfile import ZipFile, ZIP_DEFLATED

files = glob.glob('mprm*') #find your stuff
z = ZipFile('mprm.zip', mode='w', compression=ZIP_DEFLATED) #change if needed
for f in files:
    z.write(f, f)
print ('done')

rawDescription: Zip only files starting with mprm* into mprm.zip in python


code: count = sum(isinstance(x, MyClass) for x in myList)

rawDescription: Count class instances in a Python list

description: Count class instances in a Python list


code:
class Team(models.Model):
    name = models.CharField(max_length=100)
    # other attributes that do not change over time

class Player(models.Model):
    name = models.CharField(max_length=100)
    team = models.ForeignKey(Team)
    # other attributes that do not change over time

class Match(models.Model):
    venue = models.CharField(max_length=100)
    date = models.DateField()
    # other non-redundant attributes

class PlayerMatch(models.Model):
    player = models.ForeignKey(Player)
    match = models.ForeignKey(Match)

    points = models.IntegerField()
    assists = models.IntegerField()
    rebounds = models.IntegerField()

rawDescription: How should I design my django models for team, player and match objects?


code:
import numpy
import matplotlib.pyplot as plt

x = numpy.random.rand(10)
x = numpy.random.rand(10)

plt.plot(x, y, 'o')

plt.grid(True, color='w', linestyle='-', linewidth=2)
plt.gca().patch.set_facecolor('0.8')

plt.show()

rawDescription: How can I fill a matplotlib grid?

description: Fill a matplotlib grid


code:
# An iterable with alll items in the MultiDict:
# [('check', 'a'), ('check', 'b'), ('name', 'Bob')]
self.request.POST.items()

rawDescription: How to request all the information from the HTML form in Google App Engine?

description: Request all the information from the HTML form in Google App Engine


code:
from datetime import datetime
import time
s = "16/08/2013 09:51:43"
d = datetime.strptime(s, "%d/%m/%Y %H:%M:%S")
time.mktime(d.timetuple())

rawDescription: Convert datetime format into seconds

description: Convert datetime format into seconds


code:
import pyqtgraph as pg
plt = pg.plot()
wave = plt.plot([1,2,3], [1,2,1])
wave.mapToDevice(pg.Point(3, 1))

rawDescription: How to get the pixel coordinates of a plot line in pyqtgraph

description: Get the pixel coordinates of a plot line in pyqtgraph


code: FinalList = [elem.strip() for elem in set(XYList) if elem and "." not in elem and "ae" not in elem]

rawDescription: Remove special characters from indvisual python list


code:
import sys, os
if os.isatty(sys.stdin.fileno()):
    # Debug mode.
    pass
else:
    # Cron mode.
    pass

rawDescription: Detect if python script is run from console or by crontab


rawDescription: how to link multiple xml files in python using DOM?

description: Link multiple xml files in python using DOM


code:
# Define list of numbers
lettersNumbersList = [["a", 0.2], ["b", 1], ["a", 0.2], ["a", 1]]

# Here is the dictionary you will populate.
numberOccurences = {}

# This function is used to increment the numbers depending on if they are less
# than or greater than one.
def incrementNumber(letter, number):

    countingArray = numberOccurences[letter]

    if number < 1:
        countingArray[0] = countingArray[0] + 1
    elif number >= 1:
        countingArray[1] = countingArray[1] + 1

    return(countingArray)

# Loops through all of the list, gets the number and letter from it. If the letter
# is already in the dictionary then increments the counters. Otherwise starts
# both from zero.
for item in lettersNumbersList:

    letter = item[0]
    number = item[1]

    if letter in numberOccurences:
        numberOccurences[letter] = incrementNumber(letter, number)

    else:
        numberOccurences[letter] = [0, 0]
        numberOccurences[letter] = incrementNumber(letter, number)

print(numberOccurences)

rawDescription: Modify existing value in dictionary (or defaultdictionary) by incrementing that value


code:
x = ['*a', 'b', 'c', '*d', 'e', '*f', '*g']
partials = []
for element in x:
    if element.startswith('*'):
        partials.append([])
    partials[-1].append(element)
concat = map("".join, partials)

rawDescription: Operate on a list in a pythonic way when output depends on other elements


rawDescription: Is it possible to unclutter a graph that uses seconds on x-axis in matplotlib


code:
from collections import namedtuple
center = namedtuple('center', ['x', 'y'], verbose=True)
center = center(x=3,y=4)
t_shape = T_Shape(center)

rawDescription: How to pass implicit parameters

description: Pass implicit parameters


rawDescription: Simple problem with dicT in Python

description: Simple problem with dicT in Python


code:
def remaining(ls, y, z):
    diff = y.difference(z)
    return filter(lambda i: i[0] in diff, ls)

rawDescription: More efficient way to remove items from large data sets


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

import numpy as np
import pylab
import matplotlib.cm as cm
import Image

f = pylab.figure()
for n, fname in enumerate(('1.png', '2.png')):
    image=Image.open(fname).convert("L")
    arr=np.asarray(image)
    f.add_subplot(2, 1, n)  # this line outputs images on top of each other
    # f.add_subplot(1, 2, n)  # this line outputs images side-by-side
    pylab.imshow(arr,cmap=cm.Greys_r)
pylab.title('Double image')
pylab.show()

rawDescription: display two png images simultaneously using pylab

description: Display two png images simultaneously using pylab


rawDescription: Django - order existing search results according to user choices


code:
box1=df.boxplot('data1',by='group',return_type='dict',patch_artist=False)
[x.set(color='g',linewidth=2) for x in box1['data1']['boxes']]
[x.set(facecolor='r') for x in box1['data1']['boxes']]

rawDescription: Colors in python bar plot when using df.barplot


code:
while True:
    userinput=input('Pick first player randomly? (yes/no) ').strip().lower()
    if userinput in ('no', 'yes'):
        handle_user_input(userinput)
        break

rawDescription: my idea - is this proper coding?

description: My idea - is this proper coding


rawDescription: Hex to Base64 convertion

description: Hex to Base64 convertion


code:
#models.py
class Contact(models.Model):
    #other fields
    contact_types = models.ManyToMany(ContactType)

class ContactType(models.Model):
    title = models.CharField(max_length=20, unique=true)

#forms.py
class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact

    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        self.fields['contact_types'].widget = forms.CheckboxSelectMultiple()

rawDescription: Add foreign key children to model form in Django


code: ["%.8f" % (x) for x in rates]

rawDescription: Problems with decimals and scientific notation in Python 2.6.6


code:
rand = random.randint(6, len(split_name) - 1)
search_name = name[rand:] + '*'
rqst = requests.get(name_srch % (key, search_name))

rawDescription: Does python have a better way to split a string than converting to a list?


code:
import string
text = "Free Quote!\n \n Protecting your family is the best investment you\'ll eve=\nr \n"
''.join([x for x in text if x in string.ascii_letters + '\'- '])

rawDescription: How to get only words from the string using python

description: Get only words from the string using python


rawDescription: User location information mapping with lastfm music track history in python


code:
class TransactionSerializer(serializers.ModelSerializer):
    changes = TransactionStatusSerializer(many=True, read_only=True, source='transactionstatus_set')

    class Meta:
        model = Transaction
        depth = 1
        fields = ('id', 'changes')

rawDescription: How to rename ForeignKey set field in Django Rest Framework

description: Rename ForeignKey set field in Django Rest Framework


code:
def proxy_alive(proxy):
    test = _get_data('http://m.naukri.com', proxy=proxy, silent=True)
    if test is not None:
        insert_in_alives(proxy)

rawDescription: access the length of list from inside a method

description: Access the length of list from inside a method


rawDescription: python - split array of objects

description: Python - split array of objects


code: [p for p in itertools.product(*x)]

rawDescription: Python: Choose One Item from Every List but Make Every Possible Combination


code:
import sys
from cx_Freeze import setup, Executable

base = None
if (sys.platform == "win32"):
    base = "Win32GUI"    # Tells the build script to hide the console.

# <The rest of your build script goes here.>

rawDescription: Hide console window with Tkinter and cx_Freeze


code: numpy.savetxt('test.txt', test, fmt=['%d', '%d', '%d', '%f'])

rawDescription: Numpy.savetxt() function

description: Numpy.savetxt() function


code:
with open('text.txt') as f:
    for line in f:
        coords = line.split()[1:5]  # Use slicing to get the 2nd through 5th elements

rawDescription: Divide a string in python using specific substring


code: webapp2.Route(r'/products', handler='handlers.ProductsHandler', name='products-list', schemes=['https'])

rawDescription: How to make all the Handlers(pages) on a google app engine website https

description: Make all the Handlers(pages) on a google app engine website https


code:
def __init__(self, *args, **kwargs):
    super(FilterForm, self).__init__(*args, **kwargs)
    choices = Stuff.objects.all().values_list("y", "y").distinct()
    self.fields['y'].choices = tuple([(u'', empty_label)] + list(choices))

rawDescription: Django adding an empty label to Choice Field using a ValueListQuery Set for distinct values


code: word_count = sum(len(line.split()) for line in file)

rawDescription: Python Nested Loop Comprehension

description: Python Nested Loop Comprehension


code:
# indices 0 - 3 are for horizontal, 4 - 7 are for vertical
dij = [(0, 1), (1, 0), (0, -1), (-1, 0),
       (1, 1), (1, -1), (-1, 1), (-1, -1)]

def getSurroundingTiles(self, tile, horizontal = True, vertical = True):
    index = list(self.getTiles()).index(tile)
    maxtile = self.sqrtnum - 1 # Offset for 0 indexing

    i = int(math.floor(index / self.sqrtnum))
    j = int(index % self.sqrtnum)

    surroundingTiles = []

    startat = 0 if horizontal else 4
    stopat = 8 if vertical else 4

    for di, dj in dij[startat:stopat]:
        if 0 <= i + di <= maxtile and 0 <= j + dj <= maxtile:
            surroundingTiles.append(self[i + di][j + dj])

    return surroundingTiles

rawDescription: Can you pretty this up?

description: Pretty this up


code: re.findall(needle, haystack)

rawDescription: Get second occurrence of match from pythons positive lookbehind assertion


code:
class YourSystemModel(QtGui.QFileSystemModel):

    def columnCount(self, parent = QtCore.QModelIndex()):
        return super(YourSystemModel, self).columnCount()+1

    def data(self, index, role):
        if index.column() == self.columnCount() - 1:
            if role == QtCore.Qt.DisplayRole:
                return QtCore.QString("YourText")
            if role == QtCore.Qt.TextAlignmentRole:
                return QtCore.Qt.AlignHCenter

        return super(YourSystemModel, self).data(index, role)

rawDescription: pyqt: Adding a custom column to QFileSystemModel

description: Pyqt: Adding a custom column to QFileSystemModel


code:
for x in doc.xpath("//p/text()|//sup"):
    try:
        print(to_sup(x.text))
    except AttributeError:
        print(x)

rawDescription: Extract text with lxml.html

description: Extract text with lxml.html


code:
full_query = None
for query in query_terms:
    q = Q(name__icontains=query) | Q(building__name__icontains=query)
    if full_query is None:
        full_query = q
    else:
        full_query = full_query & q

rawDescription: Concatenate filters in django query

description: Concatenate filters in django query


code:
class scraper0Spider(scrapy.Spider):
    name = "scraper0"
    allowed_domains = ["localhost"]
    start_urls = [
       "http://localhost/"
    ]

    def start_requests(self):
         for i in xrange(1, 1084):
            yield scrapy.Request("http://localhost/article%s.html" % i, self.parse, meta={"index": i})

    def parse(self, response):
        with open("article%s.json" % response.meta["index"], 'w') as f:
            json.dump(fullstring, f)

rawDescription: Iterative scraping

description: Iterative scraping


code:
def keyErrorOnRed(colour):
    def decorate(f):
        def wrapped(*args, **kwargs):
            if colour == "red":
                raise KeyError("Better dead than red")
            return f(*args, **kwargs)
        return wrapped
    return decorate

class Bar(object):
    @keyErrorOnRed("black")  #keyErrorOnRed("black")(Bar.__init__)(self, a, b)
    def __init__(self, a, b):
        self.vars = a, b

rawDescription: Inheriting decorating functions in Python?


code:
from __future__ import print_function
import select
import socket
import sys
import time
from random import randint

def serve():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    port = randint(10000, 50000)
    with open('.test_port', 'w') as f:
        f.write('{}'.format(port))
    sock.bind(('127.0.0.1', port))
    sock.listen(1)

    not_finished = True
    while not_finished:
        try:
            print('*'*40)
            print('Waiting for connection...')
            conn, addr = sock.accept()
            print('Waiting forever for data')
            select.select([conn], [], [])

            data = conn.recv(2048)
            print('got some data, so now I can go to work!')

            print('-'*40)
            print('Doing some work, doo da doo...')
            print('Counting to 20!')
            for x in range(20):
                print(x, end='\r')
                time.sleep(0.5)
            print('** Done with work! **')
            print('-'*40)

            conn.close()
        except KeyboardInterrupt:
            print('^C caught, quitting!')
            not_finished = False

def call():
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print('Connecting')
    with open('.test_port') as f:
        port = int(f.read())
    sock.connect(('127.0.0.1', port))
    sock.sendall(b'This is a message')
    sock.close()
    print('Done')

if __name__ == '__main__':
    if 'serve' in sys.argv:
        serve()
    elif 'call' in sys.argv:
        call()

rawDescription: Pause thread and wake it up from another script


code: device.startActivity( "", "android.settings.APPLICATION_DETAILS_SETTINGS", "<package name>" );

rawDescription: how to Launch android application through munkeyrunner by pythonscript


code:
class A(object):
   a = 'a'

a = A()
a.a
a.__dict__
a.b = 'b'
a.__dict__
import inspect
inspect.getmembers(a)
list(a.__dict__.iteritems())

rawDescription: In which "real-use" cases item.__dict__.iteritems() is used?


code:
def byRank():
    searchValue = input("Student to be found: ")
    try:
        index = s.index(searchValue)
    except ValueError:
        print("Name is not in the array.")
    else:
        print("Name", searchValue, "was found at index", index)

rawDescription: Python module cancelation

description: Python module cancelation


code:
recs = {
  'SELL':        1,
  'UNDERWEIGHT': 2,
  'HOLD':        3,
  'OVERWEIGHT':  4,
  'BUY':         5,
}

# this will fail correctly with a KeyError for non-expected states.
recommendation = recs[avg_recommendation]

rawDescription: python: how to convert if statements to enum or make it pythonic

description: Python: how to convert if statements to enum or make it pythonic


code:
def interpolate_data_frame(df, column, max_delta_x=None):
    if max_delta_x is None:
        df[column] = df[column].interpolate(method='values')
        return df

    df['previous_x'] = (df['B'] / df['B'] * df.index).fillna(method='ffill')
    df['next_x'] = (df['B'] / df['B'] * df.index).fillna(method='bfill')
    df['delta_x'] = df['next_x'] - df['previous_x']
    df['valid'] = (df['delta_x'] < max_delta_x).map(lambda x: 1 if x else np.nan)
    df[column] = df[column].interpolate(method='values') * df['valid']
    del(df['previous_x'])
    del(df['next_x'])
    del(df['delta_x'])
    del(df['valid'])
    return df

rawDescription: how do I specify a "maximum delta x" to pandas interpolation methods?

description: Specify a "maximum delta x" to pandas interpolation methods


code:
class LabAdmin(ModelAdmin):
    # form = LabForm

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "professor":
            kwargs["queryset"] = Author.objects.order_by("name")
        return super(MyModelAdmin, self).formfield_for_foreignkey(
            db_field, request, **kwargs
            )

rawDescription: Little green "+" button no longer displayed in the Django admin


code:
df
df.pivot_table(index=["Block", "Con"], columns=["Name", "Replicate"], values="Mean")

rawDescription: iterate through rows on condition pandas python

description: Iterate through rows on condition pandas python


code:
import itertools

def recombinate(families):
    "families is the list of 8 elements, each one with 12 individuals"
    for fi, fj in itertools.combinations(families, 2):
        for pair in itertools.product(fi, fj):
            yield pair

rawDescription: How to make all combinations of the elements in an array?

description: Make all combinations of the elements in an array


code:
import cherrypy

class Root(object):
    @cherrypy.expose
    def index(self):
        return "Hello World!"

cherrypy.config.update({'server.socket_port': 8090,
                        'engine.autoreload_on': False,
                        'log.access_file': './access.log',
                        'log.error_file': './error.log'})
cherrypy.quickstart(Root())

rawDescription: Correct way of implementing Cherrypy's autoreload module


code:
def add_timestamp_context(request):
    return {'current_time': datetime.datetime.now()}

rawDescription: Loading timestamp upon page load and comparing it to timestamp upon form submit


code:
th1 = threading.Thread(target=runServer)
th2 = threading.Thread(target=getInfo)

rawDescription: Multi threading in python : issue with parallel processing


code:
# The demonstration of improved face based data structure

from numpy import array

triangles = array([[ 5,  7, 10],
                  [ 7,  5,  6],
                  [ 4,  0,  3],
                  [ 0,  4,  6],
                  [ 4,  7,  6],
                  [ 4,  9, 10],
                  [ 7,  4, 10],
                  [ 0,  2,  1],
                  [ 2,  0,  6],
                  [ 2,  5,  1],
                  [ 5,  2,  6],
                  [ 8,  4,  3],
                  [ 4, 11,  9],
                  [ 8, 11,  4],
                  [ 9, 11,  3],
                  [11,  8,  3]], dtype=int)

points = array([[ 0.95448092,  0.45655774],
                [ 0.86370317,  0.02141752],
                [ 0.53821089,  0.16915935],
                [ 0.97218064,  0.72769053],
                [ 0.55030382,  0.70878147],
                [ 0.34692982,  0.08765148],
                [ 0.46289581,  0.29827649],
                [ 0.21159925,  0.39472549],
                [ 0.61679844,  0.79488884],
                [ 0.4272861 ,  0.93375762],
                [ 0.12451604,  0.54267654],
                [ 0.45974728,  0.91139648]])

import pylab as plt

fig = plt.figure()
pylab.triplot(points[:,0],points[:,1],triangles)

for i,tri in enumerate(triangles):
    v1,v2,v3 = points[tri]
    vavg = (v1 + v2 + v3)/3
    plt.text(vavg[0],vavg[1],i)

#plt.show()

## constructing improved face based data structure

def edge_search(v1,v2,skip):
    """
    Which triangle has edge with verticies i and j and aren't triangle <skip>?
    """
    neigh = -1
    for i,tri in enumerate(triangles):
        if (v1 in tri) and (v2 in tri):
            if i is skip:
                continue
            else:
                neigh = i
                break

    return(neigh)

def triangle_search(i):
    """
    For given vertex with index i return any triangle from neigberhood
    """
    for i,tri in enumerate(triangles):
        if i in tri:
            return(i)

neighberhood = []
for i,tri in enumerate(triangles):

    v1, v2, v3 = tri

    t3 = edge_search(v1,v2,i)
    t1 = edge_search(v2,v3,i)
    t2 = edge_search(v3,v1,i)

    neighberhood.append([t1,t2,t3])

neighberhood = array(neighberhood,dtype=int)

faces = []
for vi,_ in enumerate(points):
    faces.append(triangle_search(vi))

## Now walking over first ring can be implemented
def triangle_ring(vertex):

    tri_start = faces[vertex]
    tri = tri_start

    ## with asumption that vertex is not on the boundary
    for i in range(10):

        yield tri

        boolindx = triangles[tri]==vertex

        # permutating to next and previous vertex
        w = boolindx[[0,1,2]]
        cw = boolindx[[2,0,1]]
        ccw = boolindx[[1,2,0]]

        ct = neighberhood[tri][cw][0]

        if ct==tri_start:
            break
        else:
            tri=ct

for i in triangle_ring(6):
    print(i)

## Using it for drawing lines on plot

vertex = 6
ring_points = []

for i in triangle_ring(vertex):
    vi = triangles[i]
    cw = (vi==vertex)[[2,0,1]]
    print("v={}".format(vi[cw][0]))
    ring_points.append(vi[cw][0])

data = array([points[i] for i in ring_points])
plt.plot(data[:,0],data[:,1],"ro")
#plt.savefig("topology.png")
plt.show()

input("Press Enter to continue...")
plt.close("all")

rawDescription: Triangular mesh queries in Python

description: Triangular mesh queries in Python


code:
import numpy as np
import scipy as sci
from scipy.signal import blackman
from scipy.signal import hanning

a = np.array([1,2,3,4,5,6,7,8])

b = np.empty([2, int(len(a)/2)], dtype=complex)
b[0,:] = a[0:int(len(a)/2)]
b[1,:] = a[(int(len(a)/2)-1):-1]

res = np.empty([2, int(len(a)/2)], dtype=complex)

# create blackman window
w = blackman(int(len(a)/2))
# you could also use a hanning window:
# w = hanning(int(len(a)/2))

for i in range(2):
    res[i,:] = sci.fftpack.fft(b[i,:] * w)

rawDescription: Calculate FFT with windowing displacement and bandpass


code:
import requests
import json

send_url = 'http://freegeoip.net/json'
r = requests.get(send_url)
j = json.loads(r.text)
lat = j['latitude']
lon = j['longitude']

rawDescription: Get your location through python

description: Get your location through python


code:
def myglob(pattern, directory=u'.'):
    pattern = unicodedata.normalize('NFC', pattern)
    results = []
    enc = sys.getfilesystemencoding()
    for name in os.listdir(directory):
        if isinstance(name, bytes):
            try:
                name = name.decode(enc)
            except UnicodeDecodeError:
                # Filenames that are not proper unicode won't match any pattern
                continue
        if fnmatch.filter([unicodedata.normalize('NFC', name)], pattern):
            results.append(name)
    return results

rawDescription: Filesystem independent way of using glob.glob and regular expressions with unicode filenames in Python


code:
thedata = '''
Questa mattina
mi son svegliato
o bella ciao, bella ciao,
bella ciao, ciao, ciao
questa mattina
mi son svegliato
ho trovato l'invasor!
'''.splitlines(True)

class Push(protocol.Protocol):
    """This is just about the simplest possible protocol"""
    def connectionMade(self):
        for line in thedata:
          if not line or line.isspace():
            continue
          self.transport.write(line)
          time.sleep(1.0)
        self.transport.loseConnection()

rawDescription: Twisted: tcp server with push producer example?


code:
import numpy as np
from scipy.interpolate import Rbf
from matplotlib import pyplot as plt

def f(x, y):
    return np.sin(x) + np.cos(2 * y)

# 1D arrays of points
x = np.random.rand(100) * 2 * np.pi
y = np.random.rand(100) * 2 * np.pi
z = f(x, y)

# initialize radial basis function
rb = Rbf(x, y, z)

# interpolate onto a 100x100 regular grid
X, Y = np.mgrid[:2*np.pi:100j, :2*np.pi:100j]
Z = rb(X.ravel(), Y.ravel()).reshape(X.shape)

# plotting
fig, ax = plt.subplots(1, 1)
ax.set_aspect('equal')
ax.hold(True)
m = ax.contourf(X, Y, Z, 20, cmap=plt.cm.Greens)
ax.scatter(x, y, c=z, s=60, cmap=m.cmap, vmin=m.vmin, vmax=m.vmax)
cb = fig.colorbar(m)
cb.set_label('$f(x, y)$', fontsize='xx-large')
ax.set_xlabel('$x$', fontsize='xx-large')
ax.set_ylabel('$y$', fontsize='xx-large')
ax.margins(0.05)
fig.tight_layout()
plt.show()

rawDescription: Plot contours of a given set of points

description: Plot contours of a given set of points


code:
def fb_credits_callback(request):
    # parse with your parse function
    # handle request
    return HttpResponse(json.dumps(data))

rawDescription: Django Callback on Facebook Credits

description: Django Callback on Facebook Credits


code:
while count < num:
    context = ssl._create_unverified_context()
    htm = urllib.request.urlopen(url, context=context).read()

    soup = BeautifulSoup(htm)
    url = soup.find_all('a')[position].get('href')

    count += 1

rawDescription: Use BeautifulSoup to loop through and retrieve specific URLs


code:
def fn(n):
    max_palindrome = 1
    for x in range(n,1,-1):
        if x * n <= max_palindrome: # nothing bigger possible for remaining x
            break
        for y in range(n,x-1,-1):
            if x * y <= max_palindrome: #nothing bigger possible for current x
                break
            if is_palindrome(x*y):
                max_palindrome = x*y
    return max_palindrome

rawDescription: Generalized project euler #4

description: Generalized project euler #4


code:
from PyQt5 import QtCore, QtWidgets

class ComboBox(QtWidgets.QComboBox):
    popupAboutToBeShown = QtCore.pyqtSignal()

    def showPopup(self):
        self.popupAboutToBeShown.emit()
        super(ComboBox, self).showPopup()

class Window(QtWidgets.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.combo = ComboBox(self)
        self.combo.popupAboutToBeShown.connect(self.populateConbo)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.combo)

    def populateConbo(self):
        if not self.combo.count():
            self.combo.addItems('One Two Three Four'.split())

if __name__ == '__main__':

    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: QComboBox click event

description: QComboBox click event


code:
missing = []
if not user.phone:
    missing.append(REQUEST_PHONE)
if not user.address:
    missing.append(REQUEST_ADDRESS)

return missing or [REQUEST_NONE]

rawDescription: Cleaner way to represent Rules (if-else) in Python


rawDescription: Format a float in Python with a maximum number of decimal places and without extra zero padding


code:
class Room:
    def __init__(self, text, other_rooms=None):
        self.text = text
        self.other_rooms = other_rooms

    def set_other_rooms(self, other_rooms):
        self.other_rooms = other_rooms

rooms = [Room("You are in a small bedroom! There is a door to the north."),
         Room("You are now in a bigger bedroom! There is a door to the East!"),
         Room("You are now in the North hall! There is a Door to the South!"),
         Room("You are now in the South hall! There is a door to the East!"),
         Room("You are now in the dining room. You smell something past the North door!"),]

rooms[0].set_other_rooms( { "north":rooms[1],
                            "south":None,
                            "east":None,
                            "west":None } )

rooms[1].set_other_rooms( { "north":None,
                            "south":None,
                            "east":rooms[2],
                            "west":None } )

rooms[2].set_other_rooms( { "north":None,
                            "south":rooms[3],
                            "east":None,
                            "west":None } )

rooms[3].set_other_rooms( { "north":None,
                            "south":None,
                            "east":rooms[4],
                            "west":None } )

rooms[4].set_other_rooms( { "north":rooms[5],
                            "south":None,
                            "east":None,
                            "west":None } )

current_room = None
done = False

while not done:
    print(current_room.text)
    user_c = input("What direction do you want to go?").lower()
    if user_c == "exit":
        done = True
    elif current_room.other_rooms[ user_c ]:
        current_room = current_room.other_rooms[ user_c ]
    else:
        print("You can't go that way.")

rawDescription: While Loop for Adventure Game IN Python

description: While Loop for Adventure Game IN Python


code:
class Province(models.Model):
    numberPlate = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=20)
    content = models.TextField()
    office = models.ManyToManyField(Office)
    def __unicode__(self):
        return self.name

rawDescription: django one to many issue at the admin panel

description: Django one to many issue at the admin panel


code:
def gallery_folder(instance, filename):
    return '/'.join(['img/gallery', instance.gallery_id, filename])

class Image(models.Model):
    ...
    file = models.ImageField(upload_to=gallery_folder)

rawDescription: Django - Get Object with ForeignKey

description: Django - Get Object with ForeignKey


code:
def my_function():
    return "test"

output = my_function()
if output:
    print(output)

rawDescription: Passing function's output to variable in "if" statement


code:
import os

def is_valid_key(key):
  """Valid key should include an ID and current application ID.
  """
  if key.app() == os.getenv('APPLICATION_ID') and key.id():
    return True
  return False

rawDescription: Check if a key is a valid key for the current app id


code:
hours = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve"]

hour = int(input("Please enter the hour: "))

print(hours[hour-1]  + " O'clock")
# Subtract one from hour because arrays start at index 0 but hours starts at "one"

rawDescription: Getting a user input digit and converting it to a word?


code:
class Employee(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    employee_name = db.Column(db.String(120))
    parent = db.Column(db.Integer, db.ForeignKey('employee.id'), index=True)
    # implements nested intervals with fractions
    created = db.Column(db.DateTime, index=True)
    left_num = db.Column(db.Integer, nullable=False)
    left_den = db.Column(db.Integer, nullable=False)
    right_num = db.Column(db.Integer, nullable=False)
    right_den = db.Column(db.Integer, nullable=False)
    level = db.Column(db.Integer, nullable=False)

    def __init__(self, employee_name, parent):
        self.created = datetime.datetime.now()
        self.employee_name = employee_name
        self.parent = parent

        # handle case of first addition
        if not parent:
            self.level = 1
            left_node_num = 0
            left_node_den = 1
            right_node_num = 1
            right_node_den = 1
        else:
            parent_employee = Employee.query.get(self.parent)
            # if the parent exists, set level to 1 more
            self.level = parent_employee.level + 1
            # find the most recent sibling
            most_recent_sibling = Employee.query\
                .filter_by(parent=self.parent)\
                .order_by(Employee.id.desc())\
                .first()
            if not most_recent_sibling:
                # if no sibling, use parent boundaries
                left_node_num = parent_employee.left_num
                left_node_den = parent_employee.left_den
            else:
                left_node_num = most_recent_sibling.right_num
                left_node_den = most_recent_sibling.right_den
            right_node_num = parent_employee.right_num
            right_node_den = parent_employee.right_den
        left_boundary = fractions.Fraction(numerator=left_node_num + right_node_num,
                                           denominator=left_node_den + right_node_den)
        right_boundary = fractions.Fraction(numerator=left_boundary.numerator + right_node_num,
                                            denominator=left_boundary.denominator + right_node_den)
        self.left_num = left_boundary.numerator
        self.left_den = left_boundary.denominator
        self.right_num = right_boundary.numerator
        self.right_den = right_boundary.denominator

rawDescription: Performing tasks before insert, remove, etc. in flask-sqlalchemy


code:
class CasesFactory(factory.Factory):
    FACTORY_FOR = models.Case

    number = factory.Sequence(lambda n: '1021-{0}'.format(n))
    create_date = datetime.datetime.now()

rawDescription: Why is factory_boy superior to using the ORM directly in tests?


code:
import pygame
import base64
import xml.etree.ElementTree as ET
pygame.init()
dirt_image = pygame.image.load('dirt.gif')
dirt_xy = dirt_image.get_size()

# incantation starts here
# The result of tostring is a bytestring with basically binary data.
dirt_bytes = pygame.image.tostring(dirt_image, 'RGBX', False)
# b64 encode so that we have all printable characters in the string.
# Otherwise elementtree doesn't want to accept the content.
# The result is another byte string but with printable characters.
dirt_bytes_in_64 = base64.b64encode(dirt_bytes)
# in Python 3, ElementTree complains about bytestrings so we further encode
# it into utf-8. In Python 2, this is not necessary.
dirt_bytes_in_64_in_utf8 = dirt_bytes_in_64.decode('utf-8')

# ElementTree create, save, restore
root = ET.Element("root")
dirt = ET.SubElement(root, 'dirt')
dirt.set('bytes64utf8', dirt_bytes_in_64_in_utf8)
tree = ET.ElementTree(root)
tree.write('images.xml')
tree_restored = ET.parse('images.xml')
dirt_bytes_in_64_in_utf8_restored = tree_restored.find('dirt').get('bytes64utf8')

# Convert from utf-8 back to base64 bytestring.
dirt_bytes_in_64_restored = dirt_bytes_in_64_in_utf8_restored.encode('utf-8')
# Convert from base64 bytestring into the original binary bytestring
dirt_bytes_restored = base64.b64decode(dirt_bytes_in_64_restored)

# Shazam. (for me at least)
restored_image = pygame.image.fromstring(dirt_bytes_restored, dirt_xy, 'RGBX')
display_surf = pygame.display.set_mode((500, 500))
display_surf.blit(dirt_image, (0, 0))
display_surf.blit(restored_image, (32, 32))
pygame.display.flip()

rawDescription: How to store and read a byte string (PyGame image) with XML? I get ValueError or TypeError (cannot serialize).

description: Store and read a byte string (PyGame image) with XML? I get ValueError or TypeError (cannot serialize).


code:
i = bisect_right(times, time)
# times[j] <= time for j<i
# times[j] > time for j>=i
if times[i-1] == time:
      # exact match
      value = values[i-1]
else:
      # interpolate
      value = (values[i-1]+values[i])/2

rawDescription: Python library for dealing with time associated data?


code:
import tkinter as tk
from tkinter import ttk

class App():

    def __init__(self):
        self.root = tk.Tk()

        ttk.Label(self.root, text = 'label text', justify = 'center').grid(row=0, column=0)
        self.string = [tk.StringVar()]
        self.string[0].set('entry text')
        ttk.Entry(self.root, textvariable = self.string[0]).grid(row=0, column=1)
        self.mainButton = ttk.Button(self.root, text = 'BUTTON', command=self.callback)
        self.mainButton.grid(row = 1, columnspan = 2)

        self.root.mainloop()

    def callback(self):
        self.mainButton.grid_forget()
        self.string.append(tk.StringVar())
        l = len(self.string)
        self.string[l-1].set('entry text')
        ttk.Label(self.root, text = 'label text', justify = 'center').grid(row=l-1, column=0)
        ttk.Entry(self.root, textvariable = self.string[l-1]).grid(row=l-1, column=1)
        self.mainButton.grid(row = l, columnspan = 2)

App()

rawDescription: Change tkinter widget position

description: Change tkinter widget position


code:
#!/usr/bin/env python

from pyvirtualdisplay import Display
from selenium import webdriver

display = Display(visible=0, size=(800, 600))
display.start()

browser = webdriver.Firefox()
browser.get('http://www.google.com')
browser.save_screenshot('screenie.png')
browser.quit()

display.stop()

rawDescription: Python Webkit making web-site screenshots using virtual framebuffer


code:
med = df.groupby('A')['B'].transform('median')
df['B'].fillna(med)

rawDescription: Python-pandas Replace NA with the median or mean of a group in dataframe


code:
import matplotlib.pyplot as plt

fig1 = plt.figure()
ax1 = fig1.add_subplot(111)

fig2 = plt.figure()
ax2 = fig2.add_subplot(111)

for i in range(5):

    ax1.plot(xs_a[i], ys_a[i], label='line' + str(i))
    ax2.plot(xs_b[i], ys_b[i], label='line' + str(i))

plt.setp( ax1.xaxis.get_majorticklabels(), rotation=90)
plt.setp( ax2.xaxis.get_majorticklabels(), rotation=90)

fig1.savefig(fname_1)
fig2.savefig(fname_2)

rawDescription: How to define several figure-objects in matplotlib?

description: Define several figure-objects in matplotlib


code:
from django.db.models.query import CollectedObjects
u = User.objects.get(id=1)

instances_to_be_deleted = CollectedObjects()
u._collect_sub_objects(instances_to_be_deleted)

for k in instances_to_be_deleted.ordered_keys():
    inst_dict = instances_to_be_deleted.data[k]
    for i in inst_dict.values():
        i.sender = None  # You will need a more generic way for this
        i.save()

u.delete()

rawDescription: Nullable ForeignKeys and deleting a referenced model instance


code:
with open('in.txt', 'r') as infile:
    data=infile.read()
with open('out.txt', 'w') as outfile:
    outfile.write(data.replace("\n", "").replace("},", "},\n"))

rawDescription: Make a file more readable

description: Make a file more readable


code: LANGUAGE_CODE = 'fr'

rawDescription: changing installed package default language/locale

description: Changing installed package default language/locale


code: my_object.my_method(1, 2, 3, "string")

rawDescription: Getting variable name in Python?

description: Getting variable name in Python


code:
thread = threading.Thread(target=MonitorProcess)
thread.daemon = True
thread.start()

rawDescription: Python Spawn a Thread with Threading and kill when main finishes


code:
(
    one,
    two,
    three,
    four
) = range(4)

rawDescription: Clean python return assignment

description: Clean python return assignment


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup("""
Experience
Summary""")
newtg = soup.new_tag('br')
soup.insert(0, newtg)
soup

rawDescription: Add line break to HTML after text addition


code:
local_dict = locals()
for index in xrange(1, 7):
    local_dict['customscript%d' % index] = entry = Entry(rootfr)
    entry.insert(0, s1)
    entry.grid(column = 3, row = index)

rawDescription: Wanted to optimize creating Entries using Tkinter


code:
def callback(*args):
    name = var.get()
    print ('%s' % name)
    users.remove(name)
    print (users)
    menu = option['menu']
    menu.delete(menu.index(name))

rawDescription: Getting a dropdown menu to update based on a variable


code:
url = urlparse.urlparse(response.url)
domain = url.netloc        # 'www.google.com'
domain = domain.split(".") # ['www', 'google', 'com']
info = None
for i in range(len(domain)):
    subdomain = ".".join(domain[i:]) # 'www.google.com', 'google.com', 'com'
    try:
        info = domain_info[subdomain]
        break
    except KeyError:
        pass

rawDescription: Partial matches in a dictionary

description: Partial matches in a dictionary


rawDescription: how to plot a line in python with an interval at each data point

description: Plot a line in python with an interval at each data point


code:
import os
import glob
for hgx in glob.glob("*_bac.hgx"):
  os.remove(hgx)

rawDescription: Deleting certain files using python

description: Deleting certain files using python


code:
import threading

def script1():
    import script1
def script2():
    import script2

t1 = threading.Thread(target=script1)
t2 = threading.Thread(target=script2)
t1.start()
t2.start()
t1.join()
t2.join()

rawDescription: Python application multi-threading for dev environment only


code: return  num + math.copysign(1, num)

rawDescription: Incrementing a number based on its sign

description: Incrementing a number based on its sign


code:
def make_class(class_docstring):
    class X:
        __doc__ = class_docstring
    return X
x = make_class('test doc')
x
xx = x()
xx.__doc__

rawDescription: Setting a dynamic type's docstring in Python 3


code:
from django import test
from django.core.urlresolvers import reverse
from page.urls import urlpatterns

class PageTest(test.TestCase):

   def test_responses(self):
       for url in urlpatterns:
           response = self.client.get(reverse(url.name))
           self.assertEqual(response.status_code, 200)

rawDescription: Django - testing pages for 500 status

description: Django - testing pages for 500 status


rawDescription: Splitting strings in a series when a number is encountered in python


code:
def sumColumn(m, column):
    total = 0
    for row in range(len(m)):
        total += m[row][column]
    return total

column = 1
print("Sum of the elements in column", column, "is", sumColumn(matrix, column))

rawDescription: sum matrix columns in python

description: Sum matrix columns in python


rawDescription: Python how to delete empty row from list of dictionaries in a for loop?


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

import turtle
truck = turtle.Turtle()
truck.fd(50)

truck.color("blue", "red")
truck.begin_fill ()
truck.circle(50)
truck.fd(50)
truck.end_fill()

truck.color("blue", "green")
truck.begin_fill ()
for i in range(2):
    truck.right(90)
    truck.fd (100)
truck.right(90)
truck.fd(100)
truck.end_fill ()

turtle.done()

rawDescription: How to fill with multiple color in Python using turtle module?

description: Fill with multiple color in Python using turtle module


code:
filename = "test.html"
f = file(filename)
attachment = MIMEText(f.read(),'html')
msg.attach(attachment)

rawDescription: Send pandas dataframe data as html e-mail


code:
import sys
sys.exit("Error message")

rawDescription: Programatically stop execution of python script?


code:
User.objects.all().exclude(id=settings.ANONYMOUS_USER_ID) \
                  .exclude(is_superuser=True)

rawDescription: Excluding the two types of users in django


rawDescription: Reading malformed 'csv' file with pandas


code:
from random import randint
factors = {"factor 1" : "10 minutes",
"factor 2" : "2 minutes",
"factor 3" : "8 minutes",
"factor 4" : "20 minutes",
"factor 5" : "7 minutes"
}

wantedTime = 19;
String_1={}
String_2={}
total = 0
for k in list(factors.keys())[randint(0, 1000)%len(factors)-1]:
    v = factors[k]
    time = int(v.split(" ")[0])
    if total+time <= wantedTime:
        total +=time
        String_1[k]=v
    else:
        String_2[k]=v

rawDescription: diving a string depending on a variable

description: Diving a string depending on a variable


code:
d = OrderedDict([('a', 1), ('c', 3), ('b', 2)])
d
d2 = OrderedDict([('__C__', v) if k == 'c' else (k, v) for k, v in d.items()])
d2

rawDescription: change key in OrderedDict without loosing order

description: Change key in OrderedDict without loosing order


code:
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")]
print([s.strip('8') for s in lst]) # remove the 8 from the string borders
print([s.replace('8', '') for s in lst]) # remove all the 8s

rawDescription: Removing character in list of strings

description: Removing character in list of strings


code:
num = '12345'
let = 'abcde'

keys = [n+l for n,l in zip(num, let)]

rawDescription: How can I turn 2 strings into a key?

description: Turn 2 strings into a key


code:
while myprocess.poll() is None:
    print("Still working...")
    # sleep a while

rawDescription: Using subprocess wait() and poll()

description: Using subprocess wait() and poll()


code:
import wx
import cgi

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self,None)
        lb = wx.SimpleHtmlListBox(self)
        lb.Append( cgi.escape("foo <&> bar") )
        lb.Append("Line 1
 Line 2")

app = wx.PySimpleApp()
frame = MyFrame().Show()
app.MainLoop()

rawDescription: wxpython listbox newline in msw

description: Wxpython listbox newline in msw


code:
import json

response = get_response()
json_response = json.loads(response.content)
json_response['status']

rawDescription: Read data from HttpResponse using python script


code:
def calculateDistance(i1, i2):
    return numpy.sum((i1-i2)**2)

rawDescription: Optimize performance for calculation of euclidean distance between two images


code:
source_path = 'source_path.txt'

f = open(source_path)
lines = f.readlines()
f.close()

temp = ''
for line in lines:
    words = line.split(' ')
    if words[0].isupper():
        temp += words[0] + '\n' + ' '.join(words[1:])
    else:
        temp += line

f = open(source_path, 'w')
f.write(temp)
f.close()

rawDescription: Python: Add a new line after the first word in a sentence if the first word is all caps


code:
data
from struct import unpack, calcsize
scount, slength = unpack("!IH", data[:6])
assert scount == 1
symbol, error_code = unpack("!%dsb" % slength, data[6:6+slength+1])
assert error_code == 0
symbol
bar_count = unpack("!I", data[6+slength+1:6+slength+1+4])
bar_count
bar_format = "!5fQ"
from collections import namedtuple
Bar = namedtuple("Bar", "Close High Low Open Volume Timestamp")
b = Bar(*unpack(bar_format, data[6+slength+1+4:6+slength+1+4+calcsize(bar_format)]))
b
import time
time.ctime(b.Timestamp//1000)
int(b.Volume*100 + 0.5)

rawDescription: Python binary data reading

description: Python binary data reading


code:
class Company(db.Model):
    name = db.StringProperty()
    category = db.StringListProperty() #to allow multiple categories

#Creating a company
company = Company()
company.name = "XYZ Car Rental Corporation"
company.category = ["NEW YORK","CAR RENTAL", "CORPORATION"] #City and Company Category. I would make them all uppercase to prevent case-sensitive/typo issues.
company.put()

#querying
query = Company.all()
query.filter('category',"NEW YORK")
results = query.fetch(10)  #this returns Company entities with "NEW YORK" in their category list

#You can also do multiple categories (AND)
query = Company.all()
query.filter('category',"NEW YORK")
query.filter('category',"CORPORATION")
results = query.fetch(10)  #this returns Company entities with "NEW YORK" and "CORPORATION" in their category list

rawDescription: Differing ways of inputting categories into Google App Engine


code:
def doStuff(bar):
    thing = str(bar)
    return thing

doStuff('foo')

rawDescription: python pass request args to function

description: Python pass request args to function


code:
import pandas as pd
import numpy as np
import seaborn

df = pd.DataFrame(np.random.randn(1000, 4), columns=list("ABCD"))
df["Y"] = np.random.randint(0, 4, 1000)
df2 = pd.melt(df, id_vars="Y")
df2.sort_values(["Y", "variable"], inplace=True)
seaborn.boxplot(x="Y", y="value", hue="variable", data=df2)

rawDescription: Pandas Dataframe Boxplot: Group by one column (without subplots)


rawDescription: A pythonic way to sum the values of a dict with a specified key list?


rawDescription: Adding hatches to imshow - Matplotlib

description: Adding hatches to imshow - Matplotlib


code:
wave_file = wave.open('mono.wav', 'r')
data_size = wave_file.getnframes()
sample_rate = wave_file.getframerate()

while True:

    waveData = wave_file.readframes(10000)
    signal = np.fromstring(waveData , 'Int16')
    Time=np.linspace(0, len(signal), num=len(signal))

    plt.figure()
    fig = plt.figure(figsize=(xinch,yinch) , frameon=False)
    #fig = plt.figure(frameon=False)
    ax = fig.add_axes([0, 0, 1, 1])
    #ax.axis('off')

    plt.axis('off')
    line = plt.plot(Time,signal , 'w')
    plt.setp(line, linewidth=10)

    plt.savefig('signal' + str(x) + '.png')
    plt.close

    x+= 1
    if  wave_file.tell() == data_size:
            break

rawDescription: Plot a Wave files Audio Visually In Python


code:
import io
import os
import zipfile

print("Note: All theme files need to be inside of the 'theme_files' folder.")
themeName = input("\nTheme name: ")
themeAuthor = input("\nTheme author: ")
themeDescription = input("\nTheme description: ")
themeContact = input("\nAuthor contact: ")
otherInfo = input("\nAdd custom information? y/n: ")
if otherInfo == "y":
    os.system("cls" if os.name == "nt" else "clear")
    print("\nEnter extra theme package information below.\n--------------------\n")
    themeInfo = input()

pakName = themeName.replace(" ", "_").lower()

pakInf = io.StringIO()
pakInf.write("Theme name: "+ themeName +"\n"+"Theme author: "+ themeAuthor +"\n"+"Theme description: "+ themeDescription +"\n"+"Author contact: "+ themeContact)
if otherInfo == "y":
    pakInf.write("\n"+ themeInfo)

themePak = zipfile.ZipFile(pakName +".tpk", "w")
themePak.writestr("package.inf", pakInf.getvalue())
for dirname, subdirs, files in os.walk("theme_files"):
    themePak.write(dirname)
    for filename in files:
        themePak.write(os.path.join(dirname, filename))

themePak.close()

rawDescription: Write text file into a zip without temp files


code:
import struct
# ...your code for deflating and processing data here...

result_size = len(result)
# `@` means use native size, `I` means unsigned int, `s` means char[].
# the encoding for `bytes()` should be changed to whatever you need
to_send = struct.pack("@I{0}s".format(result_size), result_size, bytes(result, "utf-8"))

rawDescription: Use variable value as bytes array in Python


code: y1[range(y1.shape[0]), index] = 1

rawDescription: Python indirect indexing

description: Python indirect indexing


code:
# program.py file

def foo():
    """ analogous to a main().  do something here """
    pass

# ... fill in rest of function def's here ...

# here is where the code execution and control flow will
# actually originate for your code, when program.py is
# invoked as a program.  a very common Pythonism...
if __name__ == '__main__':
    foo()

rawDescription: Python Profiling in Eclipse

description: Python Profiling in Eclipse


code:
from mercurial import ui, hg
repo = hg.repository(ui.ui(), '/some/path/to/repo')
changesets = repo.revs("date('>1999-01-01') and date('<2000-12-31')")

rawDescription: How to test the date of a changeset in Mercurial API

description: Test the date of a changeset in Mercurial API


code:
a = [7, 5, 5, 4]
list(itertools.combinations(enumerate(a), 2))
b = list((i,j) for ((i,_),(j,_)) in itertools.combinations(enumerate(a), 2))
b

rawDescription: Python itertools.combinations: how to obtain the indices of the combined numbers


code:
list_of_keys = ["address_1", "address_2", ...]

if any(k in result for k in list_of_keys):
    ...

rawDescription: Check if one or more items of a list are in a dictionary in Python


code:
def find_domains(txt):

    # Regex out domains
    lines = txt.split('\n')
    domains = []
    unwanted_extensions = ('.exe', '.net', '.csv') # tuple containing unwanted extensions, add more if you want.

    for line in lines:
        line  = line.rstrip()
        results = re.findall('([\w\-\.]+(?:\.|\[\.\])+[a-z]{2,6})', line)
        for item in results:
            # check if item is not in domains already and if item doesn't end with any of the unwanted extensions.
            if item not in domains and not item.endswith(unwanted_extensions):
                domains.append(item)

rawDescription: How can I remove elements from a list only knowing part of the string?

description: Remove elements from a list only knowing part of the string


code:
def index_of_list_element_duplicates(x):
    seen = set()
    for index, element in enumerate(x):
        if isinstance(element, list):
            element = tuple(element)
        if element not in seen:
            seen.add(element)
        else:
            yield index

b = [[1, 1], [2, 2], [3, 'd'], [3, 'd'], [4, 4], [3, 'd'], 4, 4]
list(index_of_list_element_duplicates(b))

rawDescription: How should one get the indices of list duplicate elements where the elements are lists?


code:
path = '/path/to/database/file.db'
conn = sqlite3.connect(path)

rawDescription: Python Sqlite3 Get Sqlite Connection path


code:
import itertools
def paste(outfile, separator="\t", *infiles):
    for line in itertools.izip_longest(*infiles, fillvalue=""):
        outfile.write(separator.join(column.rstrip("\n") for column in line)+"\n")
if __name__=="__main__":
    import sys
    paste(sys.stdout, "\t", *map(open,sys.argv[1:]))

rawDescription: Text file generator using Python

description: Text file generator using Python


code:
import this
print(this.s)

rawDescription: What was the file that has rot13 coding in Python and what was the name?


code:
if normalize:
    a = (a - mean(a)) / (std(a) * len(a))
    v = (v - mean(v)) /  std(v)

rawDescription: Why NUMPY correlate and corrcoef return different values and how to "normalize" a correlate in "full" mode?


code:
fmt=raw_input("what is the form? >>>")
nargs=fmt.count('{') #Very simple counting to figure out how many parameters to ask about
args=[]
for i in xrange(nargs):
    args.append(raw_input("What is the value for parameter {0} >>>".format(i)))

fmt.format(*args)
          #^ unpacking operator (sometimes called star operator or splat operator)

rawDescription: Formatting using a variable number of .format( ) arguments in Python


rawDescription: Python regex - match everything not in mustache brackets


code:
from mutagen.easyid3 import EasyID3
filePath = "8049.mp3"
try:
   meta = EasyID3(filePath)
except mutagen.id3.ID3NoHeaderError:
   meta = mutagen.File(filePath, easy=True)
   meta.add_tags()
meta
type(meta)
meta['title'] = "This is a title"
meta['artist'] = "Artist Name"
meta['genre'] = "Space Funk"
meta.save()
changed = EasyID3("8049.mp3")
changed

rawDescription: Python - Add ID3 tags to mp3 file that has NO tags


code:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,10,100)
y = x**2
plt.plot(x,y)
ax = plt.gca()
minor_ticks = np.arange(0,100,5)
ax.set_yticks(minor_ticks, minor=True)
ax.yaxis.grid(which='minor')
plt.show()

rawDescription: Manipulate number of squares in a grid matplotlib


code:
def _compare_dict(self, d1, d2):
    """
    Compares two dictionaries of floating point numbers
    for equality.
    """
    if len(d1) != len(d2): # comparing `.keys()` is futile and slow
        return False
    try:
        return all(abs(d1[k] - d2[k]) < sys.float_info.epsilon for k in d1)
    except KeyError:
        return False

rawDescription: Python dictionary ordering with equal keys


rawDescription: Trim / strip zeros of a numpy array

description: Trim / strip zeros of a numpy array


rawDescription: Connecting a slot to a button in QDialogButtonBox


rawDescription: Plot graph in Pandas or Matplotlib

description: Plot graph in Pandas or Matplotlib


code:
from Tkinter import *
import tkMessageBox

class MainWindow(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("input")
        self.master.minsize(250, 150)
        self.grid(sticky=E+W+N+S)

        self.res=StringVar()
        self.res.set("---")

        top=self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)

        for i in range(4):self.rowconfigure(i, weight=1)
        self.columnconfigure(1, weight=1)

        self.label0 = Label(self, text="value 1   ")
        self.label0.grid(row=0, column=0, padx=2)

        self.entry0 = Entry(self)
        self.entry0.grid(row=0, column=1, pady=2, padx=2, sticky=E+W+N+S)

        self.label1 = Label(self, text="value 2   ")
        self.label1.grid(row=1, column=0, padx=2)

        self.entry1 = Entry(self)
        self.entry1.grid(row=1, column=1, pady=2, padx=2, sticky=E+W+N+S)

        self.button1 = Button(self, text="Save", command=self.save)
        self.button1.grid(row=2, column=0, columnspan=2, pady=2, padx=2, sticky=E+W+N+S)

        self.result = Label(self, textvariable=self.res)
        self.result.grid(row=3, column=0, columnspan=2, pady=2, padx=2, sticky=E+W+N+S)

    def save(self):
            v1 = self.entry0.get()
            if not v1:
                tkMessageBox.showwarning(title="Warning message box", message="The Value 1 is empty")
            else:
                try:
                    v1 = float(v1)
                except:
                    tkMessageBox.showwarning(title="Warning message box", message="The value 1 is not a numeric value")

            v2 = self.entry1.get()
            if not v2:
                tkMessageBox.showwarning(title="Warning message box", message="The Value 2 is empty")
            else:
                try:
                    v2 = float(v2)
                    if v2 >= 80:
                        if tkMessageBox.askyesno(title="Value 2",message="The value 2 is %s. Are you sure?" % v2) == 1:
                            v2 = v2
                    else:
                        pass
                except:
                    tkMessageBox.showwarning(title="Warning message box", message="The value 2 is not a numeric value")
            self.res.set(str(v1 * v2))

if __name__=="__main__":
    d=MainWindow()
    d.mainloop()

rawDescription: While-loop in Tkinter in Python to insert data


code:
import re
example = '<a href="somelink here something">'
regex_pattern=re.compile('href=\"(.*?)\"')
regex_pattern.search(example)
regex_pattern.search(example).group(1)

rawDescription: Extract portions of text if Regex in Python


code:
import numpy as np
arr = np.array([1,2,3])
arr.dtype.byteorder

rawDescription: Determine the endianness of a numpy array


code:
from multiprocessing import Pool

p = Pool()

def do_inner(outer, limit):
    for inner in xrange(outer, limit):
        sim(outer, inner, ...)

def foo():
    p.map(do_inner, xrange(limit))

foo()

rawDescription: Run a python program on multiple cores

description: Run a python program on multiple cores


code: [x for b in a for x in b]

rawDescription: Double Iteration in List Comprehension

description: Double Iteration in List Comprehension


code:
import datetime as DT

def getmonth(day, week, year):
    for month in range(1, 13):
        try:
            date = DT.datetime(year, month, day)
        except ValueError:
            continue
        iso_year, iso_weeknum, iso_weekday = date.isocalendar()
        if iso_weeknum == week:
            return date.month

print(getmonth(28, 52, 2014))
# 12

print(getmonth(13, 42, 2014))
# 10

print(getmonth(6, 2, 2015))
# 1

rawDescription: Get month by week, day and year

description: Get month by week, day and year


code:
class BTNode:
    '''Node in binary tree'''

    def __init__(self, value, left=None, right=None):
        '''
        Create new BTNode with value and possible children left and right
        '''
        self.value, self.left, self.right = value, left, right

    def count_nodes(self):
        '''
        Return a tuple containing the number of interior nodes and the number of
        leaves in the tree rooted at n, or (0,0) if n is None.
        '''
        if self.left is None and self.right is None:
            # leaf
            return (0, 1)
        else:
            # internal node
            left_nodes,  left_leaves  = (0, 0) if self.left  is None else self.left.count_nodes()
            right_nodes, right_leaves = (0, 0) if self.right is None else self.right.count_nodes()
            return (left_nodes + 1 + right_nodes, left_leaves + right_leaves)


code:
[loggers]
keys=root, gunicorn.error, gunicorn.access
...
[logger_gunicorn.access]
level=(DEBUG|INFO|ERROR)
handlers=console
propagate=0
qualname=gunicorn.access

rawDescription: JSON formatted logging with Flask and gunicorn


code: assert is_equal(result, union(copy.deepcopy(GRADUATES), copy.deepcopy(MANAGERS)))

rawDescription: Ordering of py.test functions results in failure


code:
import gc
class SelfReference(object):
    def __init__(self):
        self.x = self
    def __del__(self):
        pass

s = SelfReference()
s.x is s   # the instance references itself
del s      # deleting the only reference should clear it from memory
gc.collect()
gc.garbage # yet that instance is *still here*

rawDescription: what does 'self.variable = self' means in python

description: What does 'self.variable = self' means in python


code: x = [[] for _ in range(4)]

rawDescription: python empty list trick

description: Python empty list trick


code:
with open('sample.txt', 'r') as fin:
    lines = fin.readlines()

    with open('sample_output.txt', 'w') as fout:
        index = 1
        for line in lines:
            if line[0] == 'o':
                line = '*' + str(index) + line[1:]
                index += 1
            fout.write(line.rstrip() + '\n')

rawDescription: string formatting and concatenation

description: String formatting and concatenation


code:
for object in list_of_objects:
    object.method()

rawDescription: A more pythonic way to map an object's method to a list of objects


code:
import csv

with open('file.csv', 'r') as f:
    reader = csv.reader(f)

    dummy = []
    temperature = []
    color = ''
    count = 0

    for row in reader:
        try:
            if row[0] == 'temperature':
                temperature = map(int, row[1:])
            elif row[0] == 'color':
                color = row[1]
            elif row[0] == 'count':
                count = int(row[1])
            else:
                dummy.append(row)

        # for robustness, let's catch the case where a row
        # may be malformed or does not contain more than 1 column
        except IndexError:
            dummy.append(row)

rawDescription: How to automatically parse csv in python 2.7 into int, string and list objects and their values

description: Automatically parse csv in python 2.7 into int, string and list objects and their values


code:
def subsetsum(array,num):

    if num == 0 or num < 1:
        return None
    elif len(array) == 0:
        return None
    else:
        if array[0] == num:
            return [array[0]]
        else:
            with_v = subsetsum(array[1:],(num - array[0]))
            if with_v:
                return [array[0]] + with_v
            else:
                return subsetsum(array[1:],num)

rawDescription: Python Subset Sum

description: Python Subset Sum


code:
def parse_args(self, args=None, values=None):
    """
    parse_args(args : [string] = sys.argv[1:],
               values : Values = None)
    -> (values : Values, args : [string])

    Parse the command-line options found in 'args' (default:
    sys.argv[1:]).  Any errors result in a call to 'error()', which
    by default prints the usage message to stderr and calls
    sys.exit() with an error message.  On success returns a pair
    (values, args) where 'values' is an Values instance (with all
    your option values) and 'args' is the list of arguments left
    over after parsing options.
    """
    rargs = self._get_args(args)
    if values is None:
        values = self.get_default_values()

rawDescription: Triggering callback on default value in optparse


code:
class X(object): pass
class Y(object): pass

def create_other_y():
    class Y(X): pass
    global Y2
    Y2 = Y

create_other_y()

(Y, Y2)                      # => (__main__.Y, __main__.Y)
(Y.__bases__, Y2.__bases__)  # => ((object,), (__main__.X,))

rawDescription: Two classes with the name in the same module with different bases?


code:
import pandas as pd
df = pd.DataFrame({'foo': [1, 2, 3], 'bar': [1.0, 2.0, 3.0], 'baz': ['qux', 'quux', 'quuux']})
df.dtypes

rawDescription: datatype in python (looking for something similar to str in R)

description: Datatype in python (looking for something similar to str in R)


code:
l = ["Blah blah, blah               bao     123456     ",
     "hello, hello, hello           miao    299292929  "]
for item in l:
    re.split('\s{2,}', item.strip())

rawDescription: Parse a text file with columns aligned with white spaces


code:
import turtle
import math

def triangleBuild(width,height):
    l = ( height**2 + (width/2.0)**2)**0.5
    alfa = math.atan2(height, width/2.0) # To compute alfa
    alfa = math.degrees(alfa)
    alfa = 180.0 - alfa
    turtle.forward(width)
    turtle.left(alfa)
    turtle.forward(l)
    turtle.left(2*(180-alfa))
    turtle.forward(l)

turtle.penup()
turtle.goto(10,20)
turtle.pendown()

width = 200
height = 100
triangleBuild(width,height)

rawDescription: I need to create a triangle with parameters but its not working correctly


code:
# create a wave with 1Mhz and 0.5Mhz frequencies
dt = 40e-9
t = np.arange(0, 1000e-6, dt)
fscale = t/max(t)
y = np.cos(2 * pi * 1e6 * t*fscale) + (np.cos(2 * pi * 2e6 *t*fscale) * np.cos(2 * pi * 2e6 * t*fscale))
y *= np.hanning(len(y))
yy = np.concatenate((y, ([0] * 10 * len(y))))

# FFT of this
Fs = 1 / dt  # sampling rate, Fs = 500MHz = 1/2ns
n = len(yy)  # length of the signal
k = np.arange(n)
T = n / Fs
frq = k / T  # two sides frequency range
frq = frq[range(n / 2)]  # one side frequency range
Y = fft(yy) / n  # fft computing and normalization
Y = Y[range(n / 2)] / max(Y[range(n / 2)])

# plotting the data
subplot(3, 1, 1)
plot(t * 1e3, y, 'r')
xlabel('Time (micro seconds)')
ylabel('Amplitude')
grid()

# plotting the spectrum
subplot(3, 1, 2)
plot(frq[0:600], abs(Y[0:600]), 'k')
xlabel('Freq (Hz)')
ylabel('|Y(freq)|')
grid()

# plotting the specgram
subplot(3, 1, 3)
Pxx, freqs, bins, im = specgram(y, NFFT=512, Fs=Fs, noverlap=10)
show()

rawDescription: How do I generate a spectrogram of a 1D signal in python?

description: Generate a spectrogram of a 1D signal in python


code:
import wx

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

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "List Control Tutorial")

        # Add a panel so it looks the correct on all platforms
        panel = wx.Panel(self, wx.ID_ANY)
        self.index = 0

        self.list_ctrl = wx.ListCtrl(panel, size=(-1,100),
                                     style=wx.LC_REPORT
                                     |wx.BORDER_SUNKEN
                                     )
        self.list_ctrl.InsertColumn(0, '', width=50)
        self.list_ctrl.InsertColumn(1, 'Browser', width=200)

        # add some browsers
        self.list_ctrl.InsertStringItem(0, "foo")
        self.list_ctrl.SetStringItem(0, 1, "Google Chrome")
        self.list_ctrl.InsertStringItem(1, "bar")
        self.list_ctrl.SetStringItem(1, 1, "Mozilla Firefox")

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.list_ctrl, 0, wx.ALL|wx.EXPAND, 5)
        panel.SetSizer(sizer)

#----------------------------------------------------------------------
# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

rawDescription: wxPython - Set Items in ListCtrl and Get Selected Item

description: WxPython - Set Items in ListCtrl and Get Selected Item


code:
import types

obj.f = types.MethodType(f, obj)
obj.f()

rawDescription: How do you bind methods to objects in python during runtime?

description: Bind methods to objects in python during runtime


code:
# sns.lmplot('x1', 'y1', df1, fit_reg=True, ci = None)
# sns.lmplot('x2', 'y2', df2, fit_reg=True, ci = None)
df = pd.concat([df1.rename(columns={'x1':'x','y1':'y'})
                .join(pd.Series(['df1']*len(df1), name='df')),
                df2.rename(columns={'x2':'x','y2':'y'})
                .join(pd.Series(['df2']*len(df2), name='df'))],
               ignore_index=True)

pal = dict(df1="red", df2="blue")
g = sns.FacetGrid(df, hue='df', palette=pal, size=5);
g.map(plt.scatter, "x", "y", s=50, alpha=.7, linewidth=.5, edgecolor="white")
g.map(sns.regplot, "x", "y", ci=None, robust=1)
g.add_legend();

rawDescription: plotting multiple linear regressions on the same seaborn plot

description: Plotting multiple linear regressions on the same seaborn plot


code:
def reverse_insort(a, x, lo=0, hi=None):
    """Insert item x in list a, and keep it reverse-sorted assuming a
    is reverse-sorted.

    If x is already in a, insert it to the right of the rightmost x.

    Optional args lo (default 0) and hi (default len(a)) bound the
    slice of a to be searched.
    """
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi)//2
        if x > a[mid]: hi = mid
        else: lo = mid+1
    a.insert(lo, x)

rawDescription: python bisect, it is possible to work with descending sorted lists?

description: Python bisect, it is possible to work with descending sorted lists


code: response = api.request('statuses/show/:%d' % TWEET_ID)

rawDescription: geduldig Twitter API Cannot figure how to use statuses/show/:id

description: Geduldig Twitter API Cannot figure how to use statuses/show/:id


code:
class Info(db.Model):
    link = db.SelfReferenceProperty()
    val_1 = db.IntegerProperty()
    val_2 = db.IntegerProperty()
    ancestors = db.ListProperty(db.Key) #list of ancestor links

def updateLinked(cid):
    c = Info.get_by_id(int(cid))
    result = Info.all().filter('ancestors = ', c.key())
    for item in result:
        item.val_1 = c.val_1 + item.val_2
        item.put()

rawDescription: Trouble with GAE/Python Recursive link checking and entry update


code:
def search(db, col, search_text):
    if(not search_text ):
        return "";
    else:
        search_text = str(search_text)
    query = col.find({})
    results = []
    for result in query:
        if(str(result.values()).find(search_text)>=0):
            results.append(result)

rawDescription: Regex in Pymongo

description: Regex in Pymongo


code:
import shutil
shutil.copyfile('c:\\test_file.txt', 'c:\\test_file1.txt')

rawDescription: Copying File On Python 3

description: Copying File On Python 3


code:
def split_list(l):
    def sub(index, l, odd, even):
        try:
            if index % 2 == 0:
                even.append(l[index])
            else:
                odd.append(l[index])
        except IndexError: # we've reached the end of the list
            return odd, even
        return sub(index+1, l, odd, even) # recursive call by advancing the index
    return sub(0, l, [], []) # initial call to function

rawDescription: Recursively split a list into two parts

description: Recursively split a list into two parts


code:
# view example on python.org site (logging for multiple modules)
logging.config.fileConfig('logging.conf')

rawDescription: extending python logging module

description: Extending python logging module


rawDescription: Pandas Python - Save dataframe without time part of date


code:
import argparse
parser = argparse.ArgumentParser(
        description='My description')
parser.add_argument("-r", "--remote", action='store_true', help="help message")
parser.print_help()
opts = parser.parse_args([])
opts.remote
opts = parser.parse_args(['-r'])
opts.remote

rawDescription: python's argument parser printing the argument name in upper case

description: Python's argument parser printing the argument name in upper case


code:
df = DataFrame(np.arange(9).reshape(-1,1),columns=['value'],index=pd.MultiIndex.from_product([[1,2,3],['a','b','c']],names=['one','two']))
df
df.index.lexsort_depth
df.sortlevel(level=1)
df.sortlevel(level=1).index.lexsort_depth
df = DataFrame(np.arange(9).reshape(-1,1),columns=['value'],index=pd.MultiIndex.from_product([[1,2,3],['a','b','c']],names=['one','two']))
df
df.index.lexsort_depth
df.sortlevel(level=1)
df.sortlevel(level=1).index.lexsort_depth

rawDescription: key error and MultiIndex lexsort depth

description: Key error and MultiIndex lexsort depth


code:
df[c] = (df[c].str.lower()
              .str.decode('utf-8')
              .map(lambda x: unicodedata.normalize('NFKD', x))
              .str.encode('ascii', 'ignore'))

rawDescription: how do I apply normalize function to pandas string series?

description: Apply normalize function to pandas string series


code:
class Subscribe(models.Model):
    email = models.CharField(max_length=200)
    auth_code = models.CharField(max_length=200)
    auth_status = models.CharField(max_length=40)
    sub_datetime = models.DateTimeField()

    class Meta:
        index_together = [
            ["email", "auth_code"],
        ]

    def __unicode__(self):
        return "email=[%s], auth_status=[%s], sub_datetime=[%s]." % self.email, self.auth_status, self.sub_datetime

rawDescription: How to create index for model in Django?

description: Create index for model in Django


code:
class Foo(object):
    def __init__(self, val):
        self.val = val
    def __add__(self, other):
        return self.val + other.val
    def __radd__(self, other):
        return other + self.val

A = Foo(1)
B = Foo(2)
L = [A,B]
print(A+B)
# 3

print(sum(L))
# 3

rawDescription: __add__ all elements of a list

description: __add__ all elements of a list


code:
for i in range(0, n):
    triangle = triangle + str(i%8)
    print(triangle)

rawDescription: Create a simple number pattern in python?


code:
df['maxval'] = df.groupby(by=['idn']).transform('max')
df

rawDescription: Merging a pandas groupby result back into DataFrame


code:
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer

df = pd.read_csv('example.csv', header=None, sep=',',
                 names=['tweets', 'class'])   # columns names if no header
vect = TfidfVectorizer()
X = vect.fit_transform(df['tweets'])
y = df['class']

rawDescription: Load classified data from CSV to Scikit-Learn for machine learning


code:
def gen():
    while True:
        yield 1

sum(gen())

rawDescription: "Functions that consume an entire iterable won't terminate"?


rawDescription: activation values for all nodes in a PyBrain network

description: Activation values for all nodes in a PyBrain network


code:
from flask import Flask, make_response, request

app = Flask(__name__)

def transform(text_file_contents):
    return text_file_contents.replace("=", ",")

@app.route('/')
def form():
    return """

Transform a file demo

                <form action="/transform" method="post" enctype="multipart/form-data">
                    <input type="file" name="data_file" />
                    <input type="submit" />
                </form>

    """

@app.route('/transform', methods=["POST"])
def transform_view():
    file = request.files['data_file']
    if not file:
        return "No file"

    file_contents = file.stream.read().decode("utf-8")

    result = transform(file_contents)

    response = make_response(result)
    response.headers["Content-Disposition"] = "attachment; filename=result.csv"
    return response

rawDescription: Uploading and Downloading Files with Flask


code:
from urlparse import urljoin
urljoin('http://mysite.com/foo/bar/x.html', '../../images/img.png')

rawDescription: Reconstructing absolute urls from relative urls on a page


code: indexedDataFrame.loc[['user1'], 'TS']

rawDescription: Counting the number of results for a pandas.loc search


rawDescription: how to consult the base class of a class

description: Consult the base class of a class


code:
def paint_canvas():
    winname="Paint :: Press ESC to exit; Double Click to TAG"
    cv2.namedWindow(winname)
    cv2.setMouseCallback(winname,draw_text)
    while(1):
        cv2.imshow(winname,img)
        if cv2.waitKey(20) & 0xFF ==27:
            break
    cv2.destroyAllWindows()

rawDescription: OpenCV Python Mouse Event Unresponsive

description: OpenCV Python Mouse Event Unresponsive


code:
df['date2'] = df.groupby('symbol').apply(lambda x: x['date'].shift(-1))
df

rawDescription: Problems with Replace - pandas dataframe


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

fig = plt.figure()
ax1 = fig.add_subplot(111)
t = np.arange(0.01, 10.0, 0.01)
s1 = np.exp(t)
ax1.plot(t, s1, 'b-')
ax1.set_xlabel('time (s)')
# Make the y-axis label and tick labels match the line color.
ax1.set_ylabel('exp', color='b')
for tl in ax1.get_yticklabels():
    tl.set_color('b')

ax2 = ax1.twinx()
s2 = np.sin(2*np.pi*t)
ax2.plot(t, s2, 'r.')
ax2.set_ylabel('sin', color='r')
for tl in ax2.get_yticklabels():
    tl.set_color('r')
plt.show()

rawDescription: How to display yaxis on both side using matplotlib 0.99?

description: Display yaxis on both side using matplotlib 0.99


code:
""" Basic todo list using webpy 0.3 """
import web
import model

### Url mappings

urls = (
    '/', 'Index',
    '/login', 'Login',
    '/logout', 'Logout',
    '/del/(\d+)', 'Delete',
)

web.config.debug = False
render = web.template.render('templates', base='base')
app = web.application(urls, locals())
session = web.session.Session(app, web.session.DiskStore('sessions'))

allowed = (
    ('user','pass'),
)

class Login:

    login_form = web.form.Form( web.form.Textbox('username', web.form.notnull),
        web.form.Password('password', web.form.notnull),
        web.form.Button('Login'),
        )

    def GET(self):
        f = self.login_form()
        return render.login(f)

    def POST(self):
        if not self.login_form.validates():
            return render.login(self.login_form)

        username = self.login_form['username'].value
        password = self.login_form['password'].value
        if (username,password) in allowed:
            session.logged_in = True
            raise web.seeother('/')

        return render.login(self.login_form)

class Logout:
    def GET(self):
        session.logged_in = False
        raise web.seeother('/')

class Index:

    form = web.form.Form(
        web.form.Textbox('title', web.form.notnull,
            description="I need to:"),
        web.form.Button('Add todo'),
    )

    def GET(self):
        if session.get('logged_in', False):
            """ Show page """
            todos = model.get_todos()
            form = self.form()
            return render.index(todos, form)
        else:
            raise web.seeother('/login')

    def POST(self):
        """ Add new entry """
        form = self.form()
        if not form.validates():
            todos = model.get_todos()
            return render.index(todos, form)
        model.new_todo(form.d.title)
        raise web.seeother('/')

class Delete:

    def POST(self, id):
        """ Delete based on ID """
        id = int(id)
        model.del_todo(id)
        raise web.seeother('/')

app = web.application(urls, globals())

if web.config.get('_session') is None:
    session = web.session.Session(app, web.session.DiskStore('sessions'), {'count': 0})
    web.config._session = session
else:
    session = web.config._session

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

rawDescription: Web.py todo list with login

description: Web.py todo list with login


code: fp.write('\n'.join('%s %s' % x for x in mylist))

rawDescription: Python: Write a list of tuples to a file


code:
import datetime

#
# This creates new instace of `datetime.datetime` from a string according to
# the pattern given as the second argument.
#
start = datetime.datetime.strptime(s_date, '%Y%m%d')
end = datetime.datetime.strptime(e_date, '%Y%m%d')

# And now the query you want. Mind that you cannot use 'and' keyword
# inside .filter() function. Fortunately .filter() automatically ANDs
# all criteria you provide.
Activity.objects.filter(timestamp__gte=start, timestamp__lte=end)

rawDescription: querying for timestamp field in django

description: Querying for timestamp field in django


code:
textfile.write("""
def a_procedure():
    window = Tk()
""")

rawDescription: Write python procedure to write python procedure