code:
cars = Car.objects.all().prefetch_related('pictures')

@property
def default_picture(self):
    pics = self.pictures.all()
    return pics[0] if pics else None

rawDescription: Select related - one object from foreign key


code:
# admin.py
from django.contrib import admin
from django.db.models import Count
from app.models import Specialization

class SpecializationAdmin(admin.ModelAdmin):

    list_display = ['name', 'doctor_count_display']

    def get_queryset(self, request):
        qs = super(SpecializationAdmin, self).get_queryset(request)
        return qs.annotate(doctor_count=Count('doctor')).order_by('-doctor_count')

    def doctor_count_display(self, obj):
        return obj.doctor_count
    doctor_count_display.short_description = 'Number of doctors'
    doctor_count_display.admin_order_field = 'doctor_count'

admin.site.register(Specialization, SpecializationAdmin)

rawDescription: Get count for objects

description: Get count for objects


code:
import SimpleHTTPServer
import SocketServer

class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def handle_one_request(self):
        print(self.client_address[0])
        return SimpleHTTPServer.SimpleHTTPRequestHandler.handle_one_request(self)

print("Serving local directory")
httpd = SocketServer.TCPServer(("", 8080), MyHandler)

while True:
    httpd.handle_request()

rawDescription: How to get client IP from SimpleHTTPServer

description: Get client IP from SimpleHTTPServer


rawDescription: What's the most efficient way to select a non-rectangular ROI of an Image in OpenCV?


code:
df.groupby(["score", "type"]).sum()
df.groupby(["score", "type"], as_index=False).sum()

rawDescription: Sum up column values in Pandas DataFrame


code:
list1 = ['John', 'Don', 'Sam']
list2 = ['Melissa', 'Amber', 'Liz']
[' and '.join(i) for i in zip(list1, list2)]

rawDescription: How to perform list comprehension on the following two lists?

description: Perform list comprehension on the following two lists


code:
node_iterator = iter(inputNodes)
for hiddenNode, count in zip(hiddenNodes, partition):
    for _ in xrange(count):
        Edge(next(node_iterator), hiddenNode)

rawDescription: Splitting a list according to a partition of its length


code:
def OnSaveToFile(self, event):
    context = wx.ClientDC(self)
    memory = wx.MemoryDC()
    x, y = self.ClientSize
    bitmap = wx.EmptyBitmap(x, y, -1)
    memory.SelectObject(bitmap)
    memory.Blit(0, 0, x, y, context, 0, 0)
    memory.SelectObject(wx.NullBitmap)
    bitmap.SaveFile('test.bmp', wx.BITMAP_TYPE_BMP)

rawDescription: Creating a image of a panel

description: Creating a image of a panel


rawDescription: Interpolating periodic data in Python

description: Interpolating periodic data in Python


rawDescription: sub string python pandas

description: Sub string python pandas


code:
import struct
struct.unpack('<f', '\xc0\x05\xe5\x3f')

rawDescription: Reading a 32 bit floating point binary data file (little endian)


code:
b = bytearray(your_byte_data)
big_endian = (b[0] == 0x52)
offset = 768 + big_endian
current_orientation = b[offset]  # get current orientation
b[offset] = new_offset           # set it to something new
open('out_file', 'wb').write(b)

rawDescription: Decode image file to extract image header information and modify it (with python)


code:
from datetime import datetime

def str2datetime(s):
    parts = s.split('.')
    dt = datetime.strptime(parts[0], "%Y-%m-%d %H:%M:%S")
    return dt.replace(microsecond=int(parts[1]))

rawDescription: Parsing datetime strings with microseconds


code:
cut = N.in1d(my_array, sublist)
my_array = my_array[cut]

rawDescription: Numpy: efficient way of filtering a very large array with a list of values


code:
from matplotlib.pyplot import *
import numpy

spectrum =numpy.fft.fft(x1)
spectrum = abs(spectrum[:len(spectrum)/2]) # Just first half of the spectrum, as the second is the negative copy
figure()
plot(spectrum)
show()

rawDescription: Python - Plotting Fourier transform from text file


code:
l = [1,2,3,4,5]
n = 2
a = 0  # Number of items that meet the condition
for x in l:
    if x % 2 == 0:
        a += 1
        if a > n:
            break
a == n

rawDescription: Fastest way to check if exactly n items in a list match a condition in python


code:
def content_file_name(instance, filename):
    return "user_{id}/{folder}/{file}".format(id=instance, folder=instance.folder_name, file=filename)

class Audio(models.Model):
    audiofile = models.FileField(upload_to=content_file_name)
    folder_name = models.CharField(max_length=1000)

rawDescription: django save file into folder

description: Django save file into folder


rawDescription: Return a parent tag attribute from selected child


rawDescription: In python, how can I use regex to replace square bracket with parentheses


code:
def deco(cls):
    cls.initStuff()
    return cls
@deco
class Foo(object):
    x = 10

    @classmethod
    def initStuff(cls):
        cls.x = 88
Foo.x
Foo.x = 10
Foo.x
Foo.initStuff() # reinitialize
Foo.x

rawDescription: How can I access a classmethod from inside a class in Python

description: Access a classmethod from inside a class in Python


code:
if not isinstance(lst, (list, tuple)):
    lst = [lst]

rawDescription: Jinja2 join only for lists

description: Jinja2 join only for lists


code:
def get_dangerous_query():
    # do some database access
    # For a demo, just return what we know the table contains
    return "SELECT * FROM TABLE WHERE COL1 = '%s' and COL2 = '%s'"

qry = get_dangerous_query() % (var1, var2)

rawDescription: enforce triple quotes around strings in python

description: Enforce triple quotes around strings in python


code:
out = initial_input
for func in [function1, function2, function3, function4]:
    out = func(out)

rawDescription: Better way to call a chain of functions in python?


code: codes = ','.join(x.strip('[]\'"') for x in var)

rawDescription: Deal with special characters in regex

description: Deal with special characters in regex


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

#assign display window dimensions
winwidth = 400
winheight = 700

#number of rows, number of colums
numrows = 10
numcols = 10

#Keeping brick size proportionate to the window size
brickwidth = winwidth / numcols
brickheight = winheight / numcols

#initialize pygame
pygame.init()
#Set display window width, height
windowSurface = pygame.display.set_mode((winwidth, winheight), 0, 0)

#Colours
blue = [0, 0, 255]
green = [0, 255, 0]
yellow = [255, 255, 0]
red = [255, 0, 0]
white = [255, 255, 255]

colours = [white, white, red, red, green, green, yellow, yellow, blue, blue]

class Setup():
    def __init__(self):
        #Setup nest for loop to generate 2d array of blocks.
        for y in range(0, numrows):
            for x in range(0, numcols):
                #Using modulo to get the different colours for rows, we use y as the changing key
                col_index = y % len(colours)
                pygame.draw.rect(windowSurface, colours[col_index], (x*brickwidth, y*brickheight, brickwidth, brickheight))

class Main():
    Setup()
    pygame.display.update()

rawDescription: (Python) List traversal in a nested for-loop?


code:
import csv

student_name = input("Name: ")
score = input("Score: ")

with open("student_scores.csv", "r") as f:
    data = [item for item in csv.reader(f)]

for item in data:
    if item[0] == student_name :
        item.append(score)
        with open("student_scores.csv", 'w') as f:
            csv.writer(f).writerows(data)
        break
else:
    with open("student_scores.csv", 'a') as f:
        csv.writer(f).writerow([student_name, score])

rawDescription: create new column of values against an existing string in a csv file in python

description: Create new column of values against an existing string in a csv file in python


code:
import boto
c = boto.connect_ec2(ec2_key, ec2_secret)
image = c.get_image(ec2_ami)

reservation = image.run(key_name=ec2_keypair,
                        security_groups=ec2_secgroups,
                        instance_type=ec2_instancetype)

instance = reservation.instances[0]
c.create_tags([instance.id], {"Name": instance_name})

rawDescription: With boto, how can I name a newly spawned EC2 instance?


code:
tup = (url, first, middle, last, rank, words, city, school, year)
tup

rawDescription: How can I organize each scraped item into a csv row?

description: Organize each scraped item into a csv row


rawDescription: How to properly get a serializer instance in Django view?

description: Properly get a serializer instance in Django view


code:
import _csv
_csv

rawDescription: What is "_csv" in Python?

description: What is "_csv" in Python


code:
import matplotlib.pyplot as plt

left = 0.1
width = 0.8

ax1 = plt.axes([left, 0.5, width, 0.45])
ax2 = plt.axes([left, 0.3, width, 0.19])
ax3 = plt.axes([left, 0.2, width, 0.09], sharex=ax2)
ax4 = plt.axes([left, 0.1, width, 0.09], sharex=ax2)

# ticks at the top of the top plot
ax1.xaxis.tick_top()

# remove ticks for ax2 and ax3
ax2.xaxis.set_visible(False)
ax3.xaxis.set_visible(False)

# only put ticks on the bottom of ax4
ax4.xaxis.tick_bottom()

plt.show()

rawDescription: Creating subplots with differing shapes in matplotlib


code:
import sys

infile, outfile = sys.argv[1], sys.argv[2]

with open(infile) as inf, open(outfile,"w") as outf:
    line_words = (line.split(',') for line in inf)
    outf.writelines(words[1].strip() + '\n' for words in line_words if len(words)>1)

rawDescription: python parse file

description: Python parse file


code:
s = "First Middle Last"
s.split(" ")

rawDescription: Python: split a full name "First Last", "First Middle Last," etc ... into separate variables?


code:
s = 'insert 0 9'
li= s.split(' ')
var = li[0]
del li[0]

print(var)
insert

print(li)

['0', '9']

rawDescription: How to seperate numbers from strings?

description: Seperate numbers from strings


code:
def has_vowels(string):
  if not string:  # check for empty string
    return False  # empty strings never have vowels
  # TODO we have a non-empty string at this point and can use recursion

def is_valid_password(string):
  return len(string) > 0 and not has_vowels(string)

def request_password():
  while True:   # use an endless loop here, we don't won't to repeat
                # the "input" statement. We could also change this to
                # something like `for i in range(3)` to allow only a limited
                # number of tries.
    passwd = input('Please enter a password with no vowels in it: ')
    # TODO check if input is valid, if yes, return, if no, print an error

rawDescription: How can I tell the difference between a user-input blank string and one I created?

description: Tell the difference between a user-input blank string and one I created


code:
import matplotlib.pyplot as plt

subplotsize=[5.,5.]
figuresize=[10.,10.]

left = 0.5*(1.-subplotsize[0]/figuresize[0])
right = 1.-left
bottom = 0.5*(1.-subplotsize[1]/figuresize[1])
top = 1.-bottom
fig=plt.figure(figsize=(figuresize[0],figuresize[1]))
fig.subplots_adjust(left=left,right=right,bottom=bottom,top=top)
ax=fig.add_subplot(111)
plt.show()

rawDescription: Specify subplot size instead of figsize in matplotlib


code:
from xmpp import *
cl=Client('example.com')
cl.connect()
cl.auth('sender', 'sender_pass')
ibb = filetransfer.IBB()
ibb.PlugIn(cl)

f = open('/tmp/foo')
ibb.OpenStream('123', 'receiver@example.com/resource', f)

rawDescription: How can I send data using xmpppy?

description: Send data using xmpppy


code:
new_list = []
for innerDict in original_list:
    newDict = {}
    for key in innerDict:
        if key not in ['Data_Type', 'Column_Style', 'others']:
            newDict[key] = innerDict[key]
        elif key == 'Data_Type':
            if innerDict['Column_Style']:
                newDict['Data_Type'] = innerDict['Data_Type'] + '(' + innerDict['Column_Style'] + ')'
            else:
                newDict['Data_Type'] = innerDict['Data_Type']
    new_list.append(newDict)

rawDescription: list of dict from existing list of dict in python

description: List of dict from existing list of dict in python


code:
# Import guzzle theme https://github.com/guzzle/guzzle_sphinx_theme
# Not actually using the theme but intead using the
# sitemap functionality and overriding the theme/templates in source/
html_translator_class = 'guzzle_sphinx_theme.HTMLTranslator'
html_theme_path = guzzle_sphinx_theme.html_theme_path()
html_theme = 'guzzle_sphinx_theme'
extensions.append("guzzle_sphinx_theme")
html_theme_options = {
    "base_url": "YOURSITEURL"
}

rawDescription: How do I generate a sitemap.xml file with sphinx?

description: Generate a sitemap.xml file with sphinx


code:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
type(Point)

rawDescription: Why should I use CamelCase for namedtuple?


code:
import pygame
from pygame.locals import *

pygame.init()

def circle_drawing(surf):
    pass
    #your circle drawing function using passed in surface

DISPLAY = (1, 1)
DEPTH = 32
FLAGS = 0
screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH)
work_surface  = pygame.Surface((500,500))
count = 0
while True:
    ws = circle_drawing(work_surface.copy())
    pygame.image.save(ws, "circles_" + str(count)+".png")
    count +=1

rawDescription: Creating a window in pygame without displaying it


code:
import os
statinfo = os.stat('somefile.txt')
statinfo
statinfo.st_size

rawDescription: How to check file size in python?

description: Check file size in python


code:
import matplotlib.pyplot as plt
import pandas as pd
import itertools
#data
df = pd.DataFrame(
    {'id': [1, 2, 3, 3],
     'labels': ['HPRR1234', 'HPRR4321', 'HPRR2345', 'HPRR2345'],
     'g': ['KRAS', 'KRAS', 'ELK4', 'ELK4'],
     'r1': [15, 9, 15, 1],
     'r2': [14, 8, 7, 0],
     'r3': [14, 16, 9, 12]})
#extra setup
plt.rcParams['xtick.major.pad'] = 8
#plotting style(s)
marker = itertools.cycle((',', '+', '.', 'o', '*'))
color = itertools.cycle(('b', 'g', 'r', 'c', 'm', 'y', 'k'))
#plot
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(df['id'], df['r1'], ls='', ms=10, mew=2,
        marker=marker.next(), color=color.next())
ax.plot(df['id'], df['r2'], ls='', ms=10, mew=2,
        marker=marker.next(), color=color.next())
ax.plot(df['id'], df['r3'], ls='', ms=10, mew=2,
        marker=marker.next(), color=color.next())
# set the tick labels
ax.xaxis.set_ticks(df['id'])
ax.xaxis.set_ticklabels(df['labels'])
plt.setp(ax.get_xticklabels(), rotation='vertical', fontsize=12)
plt.tight_layout()
fig.savefig("example.pdf")

rawDescription: Pandas: plot multiple columns to same x value


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

import os
import shutil

import cherrypy

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8,
  }
}

class App:

  @cherrypy.expose
  def index(self):
    return '''<!DOCTYPE html>
      <html>
      <head>
        <title>CherryPy Async Upload</title>
      </head>
      <body>
        <form id='upload' action=''>
          <label for='fileselect'>Files to upload:</label>
          <input type='file' id='fileselect' multiple='multiple' />
        </form>
        <script type='text/javascript'>
          function upload(file)
          {
            var xhr = new XMLHttpRequest();

            xhr.upload.addEventListener('progress', function(event)
            {
              console.log('progess', file.name, event.loaded, event.total);
            });
            xhr.addEventListener('readystatechange', function(event)
            {
              console.log(
                'ready state',
                file.name,
                xhr.readyState,
                xhr.readyState == 4 && xhr.status
              );
            });

            xhr.open('POST', '/upload', true);
            xhr.setRequestHeader('X-Filename', file.name);

            console.log('sending', file.name, file);
            xhr.send(file);
          }

          var select = document.getElementById('fileselect');
          var form   = document.getElementById('upload')
          select.addEventListener('change', function(event)
          {
            for(var i = 0; i < event.target.files.length; i += 1)
            {
              upload(event.target.files[i]);
            }
            form.reset();
          });
        </script>
      </body>
      </html>
   '''

  @cherrypy.expose
  def upload(self):
    '''Handle non-multipart upload'''

    filename    = os.path.basename(cherrypy.request.headers['x-filename'])
    destination = os.path.join('/home/user', filename)
    with open(destination, 'wb') as f:
      shutil.copyfileobj(cherrypy.request.body, f)

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: Uploading a file in ajax to CherryPy

description: Uploading a file in ajax to CherryPy


code:
import sys
import unittest
try:
    import simplejson as json
except ImportError:
    import json

class TestSomething(unittest.TestCase):
    def test_json(self):
        if ('json' in sys.modules or 'simplejson' in sys.modules):
            self.assert_(True, "some kind of json loaded")
        else:
            self.fail()

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

rawDescription: Python unittest/test fixture testing if module is loaded


code:
def parseWikiTitles(x):
    counter = 1

    while '===' in x:
        if counter == 1:
            x = x.replace('===','',1)
            counter = 2

        else:
            x = x.replace('===',r'',1)
            counter = 1

    counter = 1

    while '==' in x:
        if counter == 1:
            x = x.replace('==','',1)
            counter = 2

        else:
            x = x.replace('==',r'',1)
            counter = 1

    x = x.replace(' ', '', 50)
    x = x.replace(r' ', r'', 50)
    x = x.replace(' ', '', 50)
    x = x.replace(r' ', r'', 50)

    return x

rawDescription: Making a (hopefully simple) wiki parser with python


code:
labels = dict(choices)
label = labels[some_int]

rawDescription: Efficiently search two-tuple

description: Efficiently search two-tuple


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

data = np.random.rand(2,2)
im3 = plt.imshow(data)

cb = plt.colorbar(im3)

cb.outline.set_visible(False)

# this worked on matplotlib 1.3.1
#cb.outline.set_linewidth(0.05)

cb.set_ticks([])

#Im saving as pdf
plt.savefig("thing.pdf",dpi=1000, bbox_inches='tight')

rawDescription: Remove colorbar's borders matplotlib

description: Remove colorbar's borders matplotlib


rawDescription: How do I clear screen in IronPython console?

description: Clear screen in IronPython console


rawDescription: How do I get the dimensions of the view (not obstructed by scrollbars) in a wx.ScrolledWindow?

description: Get the dimensions of the view (not obstructed by scrollbars) in a wx.ScrolledWindow


code:
route_kwargs_decoded = {}
for key, value in self.request.route_kwargs.iteritems():
    route_kwargs_decoded[key] = value.decode('utf-8')
self.request.route_kwargs = route_kwargs_decoded

rawDescription: How do I make handlers automatically .decode('utf-8') on all routed parameters?

description: Make handlers automatically .decode('utf-8') on all routed parameters


code:
import sys
if sys.version_info[0] == 2:
    import startup2
else:
    import startup3

rawDescription: $PYTHONSTARTUP with python 2.7 and python 3.2


code: import ipdb; ipdb.set_trace()

rawDescription: Python - equivalent of Matlab/Octave keyboard function?


code:
l = [[1,2,3],[4,5,6], [7], [8,9]]
[item for sublist in l for item in sublist]
5 in [item for sublist in l for item in sublist]

rawDescription: How can I deep search a Python list?

description: Deep search a Python list


code:
import os.path
pid = os.getpid() # Replace your PID here - writing to your own process is boring
with open(os.path.join('/proc', str(pid), 'fd', '1'), 'a') as stdin:
  stdin.write('Hello there\n')

rawDescription: How can I get a process's stdin by a process id?

description: Get a process's stdin by a process id


code:
class SerializeEmail(Email):

    def write_email(self,file_name):

        with open(file_name,"w") as f:
            json.dump(self,f,cls=SerializeEmailJSONEncoder,sort_keys=True,indent=4)

    @staticmethod
    def read_email(file_name):

        with open(file_name,"r") as f:
           return json.load(f,cls=SerializeEmailJSONDecoder)

# You can now create a new instance by simply doing the following:
new_email = SerializeEmail.read_email('my_email.txt')

rawDescription: Using Python "json" module to make a class serializable


code:
rows = list(myreader)
totalrows = len(rows)
for i, row in enumerate(rows):
    print("Row %d/%d" % (i+1, totalrows))

rawDescription: Number of lines in csv.DictReader

description: Number of lines in csv.DictReader


code:
import regex
m = regex.search(r'(?|a+(\sb)|b+(\sa))', 'b a')
m.group()
m.group(1)
m = regex.search(r'(?|a+(\sb)|b+(\sa))', 'a b')
m.group()
m.group(1)

rawDescription: Grouping and OR in regex

description: Grouping and OR in regex


code:
try:
    import BeautifulSoup # Standard
except ImportError:
    import MyBeautifulSoup as BeautifulSoup # internal distribution

rawDescription: Import a module in Python only if it doesn't already exist


code:
def trend(self):
    range_start = self.time_measured.minute - timedelta(minute=10)
    data = Data.objects.filter(time_measured__minute__gt=range_start)
return float(data_operation(data))

rawDescription: Time filtering in django model

description: Time filtering in django model


code: print('String' * 500)

rawDescription: Python - Print a string a certain number of times


code:
from itertools import islice

def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

rawDescription: Rolling or sliding window iterator in Python


rawDescription: Python : Correct way to strip <p> and </p> from string?


rawDescription: Transpose of matrix

description: Transpose of matrix


code:
timerThread = None

def timesUp():
    global timerThread
    print('Nice!')
    timerThread = Timer(10, timesUp)
    timerThread.start()

def main():
    global timerThread
    timerThread = Timer(10, timesUp)
    timerThread.start()
    while 1:
        input = str(sys.stdin.readline())
        if input == 'EXIT\n':
            timerThread.cancel()
            break;

rawDescription: python timer thread shutdown

description: Python timer thread shutdown


code:
lst = [np.zeros(7680) for x in range(800)]  #just a list of 800 ndarrays ...
arr = np.array(lst)   #make them into an array
arr.shape   #shape looks OK to me :-)

rawDescription: Array shape in python

description: Array shape in python


code:
A = [100,100,100,100]
Scale = 1

B= []
for idx, val in enumerate(A):
    B.append( (val*idx)/(len(A)-1) * Scale)

rawDescription: Points on line with Python

description: Points on line with Python


code:
import gc
class GCMiddleware(object):
    def process_response(self, request, response):
        gc.collect()
        return response

rawDescription: Django Python Garbage Collection woes

description: Django Python Garbage Collection woes


code:
def mergeAndCount(left, right):
    result = []
    count = 0
    i,j = 0,0

    while(i < len(left) and j < len(right)):
        if(left[i] > 2*right[j]):
            count += len(left)-i
            j += 1
        else:
            i += 1

    i,j = 0,0
    while(i < len(left) and j < len(right)):
        if(left[i] < right[j]):
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1

    while(left[i:] or right[j:]):
        if(left[i:]):
            result.append(left[i])
            i += 1
        if(right[j:]):
            result.append(right[j])
            j += 1
    return result, count

rawDescription: Significant Inversions in an array

description: Significant Inversions in an array


code:
class AdminHandler(tornado.web.RequestHandler):
  @tornado.gen.coroutine
  def get_users(self):
    cursor = self.mc.web_app.user.find()
    users = [user['email'] for user in (yield cursor.to_list(length=1000))]
    raise tornado.gen.Return(users)

  @tornado.gen.coroutine
  def get(self):
    self.xsrf_token
    users = yield self.get_users()
    self.render('main/index.html', users=users)

rawDescription: Querying for more than one document inside of view with Motor


code:
import os
import unittest2

import tornado.database

settings = dict(
    db_host="127.0.0.1:3306",
    db_name="testdb",
    db_user="testdb",
    db_password="secret",
    db_fixtures_file=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fixtures.sql'),
)

def load_fixtures():
    """Fixtures are stored in an SQL dump.
    """
    os.system("psql %s --user=%s --password=%s < %s" % (settings['db_name'],
        settings['db_user'], settings['db_password'], settings['db_fixtures_file']))

    return tornado.database.Connection(
        host=settings['db_host'], database=settings['db_name'],
        user=settings['db_user'], password=settings['db_password'])

rawDescription: Tornado. Django-like testrunner and test database


rawDescription: Python string function parameter replacing


rawDescription: how to extract a particular node in xml using xpath in python

description: Extract a particular node in xml using xpath in python


code:
my_dict_1 = {'foo':1}
my_dict_2 = {'foo':2}
my_dict_1,my_dict_2

rawDescription: Towards understanding dictionaries

description: Towards understanding dictionaries


code:
import pygame
import sys
import time

def rotate45(gameObject, rotations={}):
    r = rotations.get(gameObject,0) + 45
    rotations[gameObject] = r
    return pygame.transform.rotate(gameObject, r)

def main():
    pygame.init()
    screen = pygame.display.set_mode((800,600))
    Tardis = pygame.image.load("Tardis.bmp")
    Tardis.set_colorkey((255, 0, 0))

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
        screen.fill( (0,0,0) )
        rotatedTardis = rotate45(Tardis)
        screen.blit(rotatedTardis, (400,300))
        pygame.display.update()
        time.sleep(1)

main()

rawDescription: When I use pygame.transform.rotate(), it moves my image so that, if used in succession, it will go off screen. Why?


code:
t = Tkinter.Text(root)
while some_condition:
    s = p.readline()          # get subprocess output
    t.insert(END, s)

rawDescription: Widget to Display subprocess stdout?

description: Widget to Display subprocess stdout


code:
def delete(head, value):
    curr = head
    prev = curr.next
    while prev.next != head:
        prev = prev.next

    if curr.value == value:
        prev.next = curr.next

    curr = curr.next
    prev = prev.next
    while curr.value != value and curr != head:
        curr = curr.next
        prev = prev.next

    if curr.value == value:
        prev.next = curr.next

rawDescription: Alternate way to delete a node in circular linked in python


rawDescription: Sort a numpy matrix based on its diagonal


code:
n = 4
df = DataFrame(randn(n, 2), index=date_range('1/1/2001', periods=n, freq='30S'))
resampled = df.resample('S')
resampled.head()
interp = resampled.interpolate()
interp.head()
interp.tail()

rawDescription: Python Numpy or Pandas Linear Interpolation For Datetime related Values


rawDescription: Python: Sorting this list

description: Python: Sorting this list


code:
def create(self, validated_data):
    profiles_data = validated_data.pop('profiles')
    user = User.objects.create(**validated_data)
    for profile_data in profiles_data:
        profile = Profile.objects.create(user=user,**profile_data)
    return user

rawDescription: create multiple objects using writable nested serializers in django rest framework 3

description: Create multiple objects using writable nested serializers in django rest framework 3


code:
import pandas as pd
import random
import matplotlib.pyplot as plt
import seaborn as sns

#make a test dataframe
features = {}
for i in range(7):
    features['feature%s'%i] = [random.random() for j in range(10)]
f = pd.DataFrame(features)
labels = pd.DataFrame({'label':[random.random() for j in range(10)]})

#unstack it so feature labels are now in a single column
unstacked = pd.DataFrame(f.unstack()).reset_index()
unstacked.columns = ['feature', 'feature_index', 'feature_value']
#merge them together to get the label value for each feature value
plot_data = pd.merge(unstacked, labels, left_on = 'feature_index', right_index = True)
#wrap a seaborn facetgrid
kws = dict(s=50, linewidth=.5, edgecolor="w")
g = sns.FacetGrid(plot_data, col="feature")
g = (g.map(plt.scatter, "feature_value", "label", **kws))

rawDescription: How to plot a FacetGrid scatter plot with multiple data frames?

description: Plot a FacetGrid scatter plot with multiple data frames


code:
writenames = "test,QC,Plate,Sample".split(",") # example
reader = csv.reader(input_file_handle)
writer = csv.writer(output_file_handle)
# don't forget to open both files in binary mode (2.x)
# or with `newline=''` (3.x)
readnames = reader.next()
name2index = dict((name, index) for index, name in enumerate(readnames))
writeindices = [name2index[name] for name in writenames]
reorderfunc = operator.itemgetter(*writeindices)
writer.writerow(writenames)
for row in reader:
    writer.writerow(reorderfunc(row))

rawDescription: write CSV columns out in a different order in Python

description: Write CSV columns out in a different order in Python


code:
xdata = pylab.arange(1961, 2031, 1)
pylab.figure(num=None, figsize=(20.48, 10.24), dpi=100, facecolor='w', edgecolor='k')
pylab.plot(xdata, ydata, linewidth=3.0)
pylab.xlabel(xlabel)
pylab.ylabel(ylabel)
pylab.title(title)
pylab.grid(True)

ram = cStringIO.StringIO()
pylab.savefig(ram, format='png')

import Image
im = Image.open(ram.read())

rawDescription: Matplotlib how to draw on figure on PIL image


code:
import re
import csv

re_expression = '^(.*?) <- (.*?): \((.*?), (.*?)\) correlation \(R\)=(.*?) \((.*?) ms\)$'

with open('output.csv', 'w', newline='') as csvfile:
    outfile = csv.writer(csvfile)
    with open('input.txt') as f:
        while True:
            line = f.readline()
            if not line: break
            m = re.split(re_expression, line)
            outfile.writerow(m[1:-1])

rawDescription: Getting specific numbers from a text file containing a mix of alphanumeric characters in python


code:
from django.db import models
from django.contrib.auth.models import User

# Create your models here.

class LDAPUser(models.Model):
        user = models.OneToOneField(User, editable=False)
        username = models.CharField(max_length=32, unique=True)

        def save(self, *args, **kwargs):
                self.user, _ = User.objects.get_or_create(username=self.username)
                self.user.save()
                '''
                Do custom saving here:
                from django_auth_ldap.backend import LDAPBackend

                user = LDAPBackend().populate_user('alice')
                '''
                super(LDAPUser, self).save(*args, **kwargs)

        def __unicode__(self):
                return self.username

rawDescription: Using Django Admin Page to Add Users with other AUTHENTICATION_BACKEND


code:
import tkinter
import time

DEFAULT_FONT = ('Helvetica',30)
class LoL_JungleTimer():
    def __init__(self):
        self._root_window = tkinter.Tk()

        Dragon_button = tkinter.Button(master = self._root_window, text = 'Dragon', fg = 'purple', command = self._dragon_start)
        BlueBuff_button = tkinter.Button(master = self._root_window, text = 'Blue Buff', fg = 'blue', command = self._blue_buff_start)
        RedBuff_button = tkinter.Button(master = self._root_window, text = 'Red Buff', fg = 'red', command = self._red_buff_start)

        self._blue_buff_label = tkinter.Label(master = self._root_window, text = '5:00', fg = 'blue', font = DEFAULT_FONT)
        self._red_buff_label = tkinter.Label(master = self._root_window, text = '5:00', fg = 'red', font = DEFAULT_FONT)
        self._dragon_label = tkinter.Label(master = self._root_window, text = '6:00', fg = 'purple', font = DEFAULT_FONT)

        Dragon_button.grid(row = 0, column = 0, padx = 10, pady = 10)
        BlueBuff_button.grid(row = 1, column = 0, padx = 10, pady = 10)
        RedBuff_button.grid(row = 2, column = 0, padx = 10, pady = 10)

        self._blue_buff_label.grid(row = 1, column = 1, padx = 10, pady = 10)
        self._red_buff_label.grid(row = 2, column = 1, padx = 10, pady = 10)
        self._dragon_label.grid(row = 0, column = 1, padx = 10, pady = 10)

        self.drag_minute = 5
        self.drag_second = 59
        self.BB_minute = 4
        self.BB_second = 59
        self.RB_minute = 4
        self.RB_second = 59

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

    def _time_counter(self, minutes, seconds):
        if seconds < 60:
            seconds -= 1
        if seconds == 0:
            seconds = 59
            minutes -= 1
        return minutes, seconds

    def _blue_buff_start(self):
        self._blue_buff_label.configure(text = "{0}:{1:02d}".format(self.BB_minute,self.BB_second))
        self._root_window.update()
        self.BB_minute,self.BB_second = self._time_counter(self.BB_minute,self.BB_second)
        self._root_window.after(1000, func = self._blue_buff_start)

    def _dragon_start(self):
        self._dragon_label.configure(text = "{0}:{1:02d}".format(self.drag_minute,self.drag_second))
        self._root_window.update()
        self.drag_minute,self.drag_second = self._time_counter(self.drag_minute,self.drag_second)
        self._root_window.after(1000, func = self._dragon_start)

    def _red_buff_start(self):
        self._red_buff_label.configure(text = "{0}:{1:02d}".format(self.RB_minute,self.RB_second))
        self._root_window.update()
        self.RB_minute,self.RB_second = self._time_counter(self.RB_minute,self.RB_second)
        self._root_window.after(1000, func = self._red_buff_start)

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

rawDescription: Why do my event handlers for button clicks stop when a different button is clicked?


code:
for subset in combinations(ListOfName, 3):
    arg = ','.join(subset)
    occuring(arg)

rawDescription: After joining set items into a single string seperated by commas, how to assign that value to a string?


rawDescription: how to get the upper-left and bottom right coordinates of the box around a certain value in a matrix using python?

description: Get the upper-left and bottom right coordinates of the box around a certain value in a matrix using python


code:
class SomeModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(SomeModelForm, self).__init__(*args, **kwargs)
        self.fields['some_field'].widget = forms.CheckboxSelectMultiple()

rawDescription: Django ModelForm CheckBox Widget

description: Django ModelForm CheckBox Widget


code:
random.seed(1)
random.choice('abcdef')
random.choice('abcdef')
random.choice('abcdef')
random.seed(1)
random.choice('abcdef')
random.choice('abcdef')
random.choice('abcdef')

rawDescription: Is there a random seed for strings in Python


code:
import sys
import os
filename= sys.argv[1]
lines = [int(x) for x in sys.argv[2:]]

#open two files one for reading and one for writing

with open(filename) as f,open("newfile","w") as f2:

#use enumerate to get the line as well as line number, use enumerate(f,1) to start index from 1
    for i,line in enumerate(f):
        if i not in lines:     #`if i not in lines` is more clear than `if not i in line`
            f2.write(line)
os.rename("newfile",filename)  #rename the newfile to original one

rawDescription: python remove "many" lines from file

description: Python remove "many" lines from file


code:
from sklearn.feature_extraction import text

stop_words = text.ENGLISH_STOP_WORDS.union(my_additional_stop_words)

rawDescription: Adding words to scikit-learn's CountVectorizer's stop list


code:
class Search(object):
    def __init__(self):
        self.sorters = []
        self.filters = []

rawDescription: python objects, garbage collection

description: Python objects, garbage collection


code:
import re
# read the book into a variable 'text'
matches = re.findall(r'\w+ is for \w+ \w+ing his \w+', text)

rawDescription: It's probably simpler in awk, but how can I say this in Python?


code:
def __init__(self, *args, **kwargs):
    super(YourModel, self).__init__(*args, **kwargs)
    self.impact = self.user.get_profile().someIntField

rawDescription: Initialize django model capturing a derivative attribute from that moment


code:
def simple_clean(word):
    return word.lower().replace(" ","").replace("hotel","")

a = "Ramada Hotel & Suites Vilnius"
b = "Hotel Ramada Suites Vilnous"
a = simple_clean(a)
b = simple_clean(b)
a
b
import difflib
difflib.SequenceMatcher(None,a,b).ratio()

rawDescription: How can I match partial strings / is there a better way?

description: Match partial strings / is there a better way


code:
class FakePage(object):
    """
    Fake page used by Django paginator.
    Required for wrapping responses from Solr.
    """

    def __init__(self, object_list, number, total_count):
        """
        Create fake page instance.

        Args:
            object_list: list of objects, represented by a page
            number: 1-based page number
            total_count: total count of objects (in all pages)
        """
        self.object_list = object_list
        self.number = number
        # count of objects per page equals to length of list
        self.per_page = len(object_list)
        if self.per_page > 0:
            self.num_pages = total_count // self.per_page
        else:
            self.num_pages = 0
        self.total_count = total_count

    def __repr__(self):
        return '<Page %s of %s>' % (self.number, self.num_pages)

    def __len__(self):
        return len(self.object_list)

    def __getitem__(self, index):
        if not isinstance(index, (slice,) + six.integer_types):
            raise TypeError
        # The object_list is converted to a list so that if it was a QuerySet
        # it won't be a database hit per __getitem__.
        if not isinstance(self.object_list, list):
            self.object_list = list(self.object_list)
        return self.object_list[index]

    def total_count(self):
        return self.total_count

    def has_next(self):
        return self.number < self.num_pages

    def has_previous(self):
        return self.number > 1

    def has_other_pages(self):
        return self.has_previous() or self.has_next()

    def next_page_number(self):
        if self.has_next():
            return self.number + 1
        raise EmptyPage('Next page does not exist')

    def previous_page_number(self):
        if self.has_previous():
            return self.number - 1
        raise EmptyPage('Previous page does not exist')

    def start_index(self):
        """
        Returns the 1-based index of the first object on this page,
        relative to total objects in the paginator.
        """
        # Special case, return zero if no items.
        if self.total_count == 0:
            return 0
        return (self.per_page * (self.number - 1)) + 1

    def end_index(self):
        """
        Returns the 1-based index of the last object on this page,
        relative to total objects found (hits).
        """
        # Special case for the last page because there can be orphans.
        if self.number == self.num_pages:
            return self.total_count
        return self.number * self.per_page

class SearchListModelMixin(object):
    """
    List search results or a queryset.
    """
    # Set this attribute to make a custom URL paramter for the query.
    # EX: ../widgets?query=something
    query_param = 'query'

    # Set this attribute to define the type of search.
    # This determines the source of the query value.
    # For example, for regular text search,
    # the query comes from a URL param. However, for a related search,
    # the query is a unique identifier in the URL itself.
    search_type = SearchType.QUERY

    def search_list(self, request, *args, **kwargs):
        # Get the query from the URL parameters dictionary.
        query = self.request.GET.get(self.query_param, None)

        # If there is no query use default REST Framework behavior.
        if query is None and self.search_type == SearchType.QUERY:
            return self.list(request, *args, **kwargs)

        # Get the page of objects and the total count of the results.
        if hasattr(self, 'get_search_results'):
            self.object_list, total_count = self.get_search_results()
            if not isinstance(self.object_list, list) and not isinstance(total_count, int):
               raise ImproperlyConfigured("'%s.get_search_results()' must return (list, int)"
                                    % self.__class__.__name__)
        else:
            raise ImproperlyConfigured("'%s' must define 'get_search_results()'"
                                    % self.__class__.__name__)

        # Normally, we would be serializing a QuerySet,
        # which is lazily evaluated and has the entire result set.
        # Here, we just have a Python list containing only the elements for the
        # requested page. Thus, we must generate a fake page,
        # simulating a Django page in order to fully support pagination.
        # Otherwise, the `count` field would be equal to the page size.
        page = FakePage(self.object_list,
            int(self.request.GET.get(self.page_kwarg, 1)),
            total_count)

        # Prepare a SearchPaginationSerializer
        # with the object_serializer_class
        # set to the serializer_class of the APIView.
        serializer = self.get_search_pagination_serializer(page)

        return Response(serializer.data)

    def get_search_pagination_serializer(self, page):
        """
        Return a serializer instance to use with paginated search data.
        """
        class SerializerClass(SearchPaginationSerializer):
            class Meta:
                object_serializer_class = self.get_serializer_class()

        pagination_serializer_class = SerializerClass
        context = self.get_serializer_context()
        return pagination_serializer_class(instance=page, context=context)

    def get_solr_results(self, sort=None):
        """
        This method is optional. It encapsulates logic for a Solr request
        for a list of ids using pagination. Another method could be provided to
        do the search request.
        """
        queryset = super(self.__class__, self).get_queryset()

        conn = solr.Solr(settings.SOLR_URL)

        # Create a SearchHandler and get the query with respect to
        # the type of search.
        if self.search_type == SearchType.QUERY:
            query = self.request.GET.get(self.query_param, None)
            sh = solr.SearchHandler(conn, "/select")
        elif self.search_type == SearchType.RELATED:
            query  = str(self.kwargs[self.lookup_field])
            sh = solr.SearchHandler(conn, "/morelikethis")

        # Get the pagination information and populate kwargs.
        page_num = int(self.request.GET.get(self.page_kwarg, 1))
        per_page = self.get_paginate_by()
        offset = (page_num - 1) * per_page
        kwargs = {'rows': per_page, 'start': offset}
        if sort:
            kwargs['sort'] = sort

        # Perform the Solr request and build a list of results.
        # For now, this only gets the id field, but this could be
        # customized later.
        response = sh(query, 'id', **kwargs)
        results = [int(r['id']) for r in response.results]

        # Get a dictionary representing a page of objects.
        # The dict has pk keys and object values, sorted by id.
        object_dict = queryset.in_bulk(results)

        # Build the sorted list of objects.
        sorted_objects = []
        for pk in results:
            obj = object_dict.get(pk, None)
            if obj:
                sorted_objects.append(obj)
        return sorted_objects, response.numFound

class SearchType(object):
    """
    This enum-like class defines types of Solr searches
    that can be used in APIViews.
    """
    QUERY = 1
    RELATED = 2

class SearchPaginationSerializer(pagination.BasePaginationSerializer):
    count = serializers.Field(source='total_count')
    next = pagination.NextPageField(source='*')
    previous = pagination.PreviousPageField(source='*')

class SearchListCreateAPIView(SearchListModelMixin, generics.ListCreateAPIView):
    """
    Concrete view for listing search results, a queryset, or creating a model instance.
    """
    def get(self, request, *args, **kwargs):
        return self.search_list(request, *args, **kwargs)

class SearchListAPIView(SearchListModelMixin, generics.ListAPIView):
    """
    Concrete view for listing search results or a queryset.
    """
    def get(self, request, *args, **kwargs):
        return self.search_list(request, *args, **kwargs)

class WidgetList(SearchListCreateAPIView):
    """
    List all Widgets or create a new Widget.
    """
    model = Widget
    queryset = Widget.objects.all()
    serializer_class = WidgetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    search_type = SearchType.QUERY # this is default, but explicitly declared here

    def get_queryset(self):
        """
        The method implemented for database powered results.
        I'm simply illustrating the default behavior here.
        """
        queryset = super(WidgetList, self).get_queryset()
        return queryset

    def get_search_results(self):
        """
        The method implemented for search engine powered results.
        """
        return self.get_solr_results(solr_sort)

class RelatedList(SearchListAPIView):
    """
    List all related Widgets.
    """
    model = Widget
    queryset = Widget.objects.all()
    serializer_class = WdigetSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
    search_type = SearchType.RELATED

    def get_search_results(self):
        return self.get_solr_results()

rawDescription: Solr search results with Django REST Framework


code:
import csv

with open('data.csv') as input, open('out.csv','w') as output:
    reader = csv.reader(input)
    writer = csv.writer(output, delimiter=',', quoting=csv.QUOTE_ALL)
    for line in reader:
        writer.writerow(line)

rawDescription: Python Enclosing Words With Quotes In A String


code:
import audiolab, scipy
a, fs, enc = audiolab.wavread('file1.wav')
b, fs, enc = audiolab.wavread('file2.wav')
c = scipy.vstack((a,b))
audiolab.wavwrite(c, 'file3.wav', fs, enc)

rawDescription: How to join two wav files using python?

description: Join two wav files using python


code:
while True:
    while Function == "Home":
        # check for the QUIT event
        events = pygame.event.get()
        for event in events:
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEBUTTONUP:
                Function = "txtbox"
                break

        pygame.display.flip()

    while Function == "txtbox":

        events = pygame.event.get()
        # process other events
        for event in events:

              if event.type == pygame.MOUSEBUTTONUP:
                Function = "Home"
                break

        pygame.display.flip()

rawDescription: How to switch between multiple while statements in Python

description: Switch between multiple while statements in Python


code:
def item_completed(self, results, item, info):

    for result in [x for ok, x in results if ok]:
        path = result['path']
        slug = slugify(item['designer'])

        settings = get_project_settings()
        storage = settings.get('IMAGES_STORE')

        target_path = os.path.join(storage, slug, os.path.basename(path))
        path = os.path.join(storage, path)

        # If path doesn't exist, it will be created
        if not os.path.exists(os.path.join(storage, slug)):
            os.makedirs(os.path.join(storage, slug))

        if not os.rename(path, target_path):
            raise DropItem("Could not move image to target folder")

    if self.IMAGES_RESULT_FIELD in item.fields:
        item[self.IMAGES_RESULT_FIELD] = [x for ok, x in results if ok]
    return item

rawDescription: How to change the directory where images are saved, scrapy

description: Change the directory where images are saved, scrapy


code:
def ask_close ():
    self.CloseDialog.run ()
gobject.idle_add (ask_close)

rawDescription: Use Thread in Pygtk

description: Use Thread in Pygtk


code:
p.xaxis.axis_label = 'whatever'
p.xaxis.axis_label_text_font_size = "40pt"

rawDescription: adjusting x_axis_label or y_axis_label font/font size (Bokeh)

description: Adjusting x_axis_label or y_axis_label font/font size (Bokeh)


rawDescription: In Django ORM: Select record from each group with maximal value of a given attribute


code:
from twisted.internet.threads import deferToThread as __deferToThread
from twisted.internet import reactor

def mmprint(s):
    print(s)

class TwistedRAWInput(object):
    def start(self,callable,terminator):
        self.callable=callable
        self.terminator=terminator
        self.startReceiving()
    def startReceiving(self,s=''):
        if s!=self.terminator:
            self.callable(s)
            __deferToThread(raw_input,':').addCallback(self.startReceiving)

tri = TwistedRAWInput()
reactor.callWhenRunning(tri.start,mmprint,'q')
reactor.run()

rawDescription: Simple Twisted Echo Client

description: Simple Twisted Echo Client


code:
import csv

search_for = ['OneTouch AT','LinkRunner AT','AirCheck']

with open('in.csv') as inf, open('out.csv','w') as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf, delimiter='\t', quotechar='"', quoting=csv.QUOTE_MINIMAL)
    for row in reader:
        if row[0] in search_for:
            print('Found: {}'.format(row))
            writer.writerow(row)

rawDescription: Search for string in CSV Files using python and write the results


code:
from sqlalchemy import MetaData
meta = MetaData()

with contextlib.closing(engine.connect()) as con:
    trans = con.begin()
    for table in reversed(meta.sorted_tables):
        con.execute(table.delete())
    trans.commit()

rawDescription: SQLAlchemy, clear database content but don't drop the schema


code:
import re
target = 'ATGcccATGgggTAGgATGtttTGA'
results = re.findall(r'(ATG.*?(?:TAG|TGA|TGA))', target)
# ['ATGcccATGgggTAG', 'ATGtttTGA']

rawDescription: search for pattern in string

description: Search for pattern in string


code:
import glob
path = "/home/me/Documents/coverage/H*/*.txt"
for filename in glob.glob(path):
    fileStream = open(filename )

rawDescription: I want to use python to walk through directories to get to text files and processed them


code:
from importlib import import_module # Awesome line! :)

for i in range(1000):
    test_include = import_module("Test_include_%s" % i)
    model = test_include.aDefinedFunction

rawDescription: How can I dynamically import in Python?

description: Dynamically import in Python


code:
from collections import Counter
c = Counter(b)
ans = []
for x in a:
    ans += [x]*c.get(x,0)

rawDescription: Compare 2 lists and print the element of the 2nd list if it is present in first list, but not by using 2 for loops


code:
class a:
    def __init__(self,l=None):
        if l is None:
            self.l = []
        ...

rawDescription: Python initialising object in a loop

description: Python initialising object in a loop


code:
import time
while True:
    # sleep for the remaining seconds until the next hour
    time.sleep(3600-time.time()%3600)
    spk.speak('It is now <time>')

rawDescription: Running a line in 1 hour intervals in python


code:
#!/usr/bin/env python

import os
import sys
import time

_ = raw_input('Enter the the secret code: ')
if os.fork(): # returns 0 in the child, pid of the child in the parent
    sys.exit()

time.sleep(2)
print('All good things must come to an end')

rawDescription: Running a python script in background with raw_input command


code:
import glob
for filename in glob.glob(r"C:\script\test\*.dat"):
    with open(filename, 'rb') as inputfile:
        data = inputfile.read()
    with open(filename, 'wb') as outputfile:
        outputfile.write(data.replace("^", "|"))

rawDescription: Python in Windows

description: Python in Windows


code:
import numpy
import mayavi.mlab as mlab

# Create some random data
N = 20
x, y, z = numpy.mgrid[-5:5:20j, -5:5:20j, -5:5:20j]
val = numpy.random.random(z.shape)

# Plot and show in mayavi2
pts = mlab.points3d(x, y, z, val, scale_factor=.5,transparent=True)
mlab.show()

rawDescription: Plot a cube of 3D intensity data

description: Plot a cube of 3D intensity data


code: mylist = ['XXX' if v == 'abc' else v for v in mylist]

rawDescription: Replacing particular elements in a list

description: Replacing particular elements in a list


code:
import unittest
import helpspot

class TestHelpSpot(unittest.TestCase):
    "A few simple tests for HelpSpot"

    def __init__(self, testname, path, user, pword):
        super(TestHelpSpot, self).__init__(testname)
        self.hs = helpspot.HelpSpot(path, user, pword)

    def test_version(self):
        a = self.hs.version()
        b = self.hs.private_version()
        self.assertEqual(a, b)

    def test_get_with_param(self):
        a = self.hs.filter_get(xFilter=1)

    def test_unknown_method(self):
        self.assertRaises(helpspot.HelpSpotError, self.hs.private_wuggienorple)

if __name__ == '__main__':
    import sys
    user = sys.argv[1]
    pword = sys.argv[2]
    path = sys.argv[3]

    suite = unittest.TestSuite()
    suite.addTest(TestHelpSpot("test_version", path, user, pword))
    suite.addTest(TestHelpSpot("test_get_with_param", path, user, pword))
    suite.addTest(TestHelpSpot("test_unknown_method", path, user, pword))

    unittest.TextTestRunner().run(suite)

rawDescription: Python, unit test - Pass command line arguments to setUp of unittest.TestCase


code:
def __getattr__(self, name):
    try:
        return self.__dict[name]
    except KeyError:
        msg = "'{0}' object has no attribute '{1}'"
        raise AttributeError(msg.format(type(self).__name__, name))

rawDescription: How do I dynamically create properties in Python?

description: Dynamically create properties in Python


code:
import urllib2
import lxml.etree as etree
page = urllib2.urlopen(url)
parser = etree.HTMLParser()
tree = etree.parse(page,parser)

rawDescription: How to handle nested form tags with lxml

description: Handle nested form tags with lxml


code:
import requests
from bs4 import BeautifulSoup

def getArticle(url):
    url = 'http://www.bbc.com/news/business-34421804'
    result = requests.get(url)
    c = result.content
    soup = BeautifulSoup(c)

    article_text = ''
    article = soup.find("div", {"class":"story-body__inner"}).findAll('p')
    for element in article:
        article_text += '\n' + ''.join(element.findAll(text = True))
    return article_text

rawDescription: Getting the text from all p elements in a div with BeautifulSoup


code: y = [1 if z > 0 else 0 for z in x]

rawDescription: if and else for list comprehension

description: If and else for list comprehension


code:
#!/bin/sh
"exec" "python" "-B" "$0" "$@"

# The rest of the Python program follows below:

rawDescription: Stop Python from generating pyc files in shebang


code:
results = []
for i in range(50):
    # do things
    results.append(result)

rawDescription: Formatting a variable with another variable in Python


rawDescription: Django: How to declare a project wide template context processor?


code: d = defaultdict(lambda: defaultdict(int))

rawDescription: Multiple levels of 'collection.defaultdict' in Python


rawDescription: Get a list from a set in python

description: Get a list from a set in python


code:
output = subprocess.check_output(['abc.sh', user, password])
print(output)
running = 'not' not in output

rawDescription: Return a value from shell script when it is called from a python script


code:
for ticker in tickers:
   t = Thread(target = quotes, args = (ticker,) )

rawDescription: Python - iterate through list in threaded script


rawDescription: Pandas: Get top 10 values AFTER grouping


code:
import pylab, numpy
from StringIO import StringIO
from PIL import Image

# plot a histogram
pylab.hist(numpy.random.rand(100))

buf = StringIO()
pylab.savefig(buf, format='png')

buf.seek(0)
im = Image.open(buf)
im.show()

rawDescription: Save images as string? IS it possible

description: Save images as string? IS it possible


code:
word ='SAMPLE TEXT               :HELLO                '
k, v = map(str.strip, word.split(':'))
k
v

rawDescription: Is there an easy way to remove the white spaces in list items


code:
f = lambda x: x*x
f(5)
globals().update({'f': (lambda g: lambda x: g(x)+1)(f)})
f(5)
f, g = None, f
g(5)

rawDescription: Altering the definition of a function without an assignment


code:
def __number():
    # "Factura" object in format "n/year"
    latest_object = Factura.objects.filter(f_type__exact=False).latest('number')

    # Better name can be available if you explain why the first number is important and what it means
    # Do Factura objects not have a __repr__ or __str__ method that you must cast it?
    first_number = int(str(latest_object).split('/')[0])
    current_year = date.today().strftime('%y')
    # Use "is None" rather than "== None"
    if first_number is None:
        return '1/%d' % current_year
    # No else needed because of return above
    # Why do we add 1 to first number? Comments should explain _why_, not how
    return '%d/%d' % (first_number + 1, current_year)

rawDescription: Any way to improve this python function?

description: Any way to improve this python function


code:
def check(match):
    g = match.group(1) # group(1) or any group number you have
    if g == '50':
        return '
%s
' % g
    else:
        return '
%s
' % g

res = re.sub(pat, check, value)

rawDescription: Conditional Regex Substition in Python

description: Conditional Regex Substition in Python


code:
documents = {}
for i in range(1, 11):
    i = str(i)
    with open('doc' + i + '.txt') as f:  # This closes the files when done.
        documents['doc' + i] = f.read()

rawDescription: Opening multiple files and assign them to a dictionary


rawDescription: Regular Expression to remove \n outside of curly bracket


code:
def get_addresses(fname):
    addresses = {}
    with open(fname) as f:
        lines = [l.strip().lower() for l in f]

    for i, line in enumerate(lines):
        if line.startswith("ip address"):
            ip = line.split(": ")[1]
            address_type = lines[i-1]
            if address_type == "entry address(es):":
                addresses["entry"] = ip
            elif address_type == "management address(es):":
                addresses["management"] = ip
            # Add additional address type handling here

    return addresses

rawDescription: I want to match a newline character followed by a string using regular expression in python


code:
class Registration():
    'Class telling us what modules students are taking'
    def __init__(self):
        self.regdict = {}
    def add(self, name, module):
        self.regdict.setdefault(name, []).append(Modules(module))
    def modules(self, name):
        return self.regdict[name]

rawDescription: How do I create a class using inputs from previous classes?

description: Create a class using inputs from previous classes


code:
import wx

class MyForm(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial", size=(500,500))

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

        SAVE_FILE_ID = wx.NewId()
        self.Bind(wx.EVT_MENU, self.saveFile, id=SAVE_FILE_ID)

        LOAD_FILE_ID = wx.NewId()
        self.Bind(wx.EVT_MENU, self.loadFile, id=LOAD_FILE_ID)

        accel_tbl = wx.AcceleratorTable([(wx.ACCEL_CTRL,  ord('O'), LOAD_FILE_ID ),
                                         (wx.ACCEL_CTRL,  ord('S'), SAVE_FILE_ID )]
                                        )
        self.SetAcceleratorTable(accel_tbl)

    #----------------------------------------------------------------------
    def loadFile(self, event):
        openFileDialog = wx.FileDialog(self, "Open", "", "",
                                       "Python files (*.py)|*.py",
                                       wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
        openFileDialog.ShowModal()
        openFileDialog.GetPath()
        openFileDialog.Destroy()

    #----------------------------------------------------------------------
    def saveFile(self, event):
        saveFileDialog = wx.FileDialog(self, "Save As", "", "",
                                       "Python files (*.py)|*.py",
                                       wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
        saveFileDialog.ShowModal()
        saveFileDialog.GetPath()
        saveFileDialog.Destroy()

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

rawDescription: WxPython File Dialogs

description: WxPython File Dialogs


code:
for (n, v) in the_dict.items():
    exec('%s=%s' % (n, repr(v)))

rawDescription: Best way to retrieve variable values from a text file - Python - Json

description: Retrieve variable values from a text file - Python - Json


code:
# The data
x = np.linspace(0, 10, 1000)
y = np.sin(2 * np.pi * x)

# The colormap
cmap = cm.jet

# Create figure and axes
fig = plt.figure(1)
fig.clf()
ax = fig.add_subplot(1, 1, 1)

c = np.linspace(0, 10, 1000)
ax.scatter(x, y, c=c, cmap=cmap)

rawDescription: matplotlib - change marker color along plot line

description: Matplotlib - change marker color along plot line


rawDescription: Get href value in Splinter?

description: Get href value in Splinter


code:
with open('/var/log/dmesg') as logf:
    log = logf.read()
print(log)

rawDescription: how to copy os.system('cat /var/log/dmesg') to a variable

description: Copy os.system('cat /var/log/dmesg') to a variable


code:
def sbc(): #splits up dataframe by spotx account
    accounts = []
    frame = rlf()
    while True:
        acc = raw_input("Enter account abbreviations one at a time. Enter 'end' to load media lists.")
        if acc == 'end':
            break
        else:
            accounts.append(acc)
    for ac in accounts:
        frame = frame[frame['Campaign'].str.startswith(ac)]
        path = r'C:\\Users\\CP\\Documents\\Python_WL\\'+str(ac)+str(time.strftime("%d.%m.%Y"))+'.xls'
        if len(frame) > 50:
            frame.to_excel(path)

rawDescription: How do I get multiple inputs from UI?

description: Get multiple inputs from UI


code:
def writeConfig(**kwargs):
    template = """
    apiVersion: v1
    kind: pod
    metadata:
      name: {name}
    spec:
      replicas: {replicas}
      template:
        metadata:
          labels:
            run: {name}
        spec:
          containers:
          - name: {name}
            image: {image}
            ports:
            - containerPort: 80"""

    with open('somefile.yaml', 'w') as yfile:
        yfile.write(template.format(**kwargs))

# usage:
writeConfig(name="someName", image="myImg", replicas="many")

rawDescription: How can I create kubernetes yaml file using pure python

description: Create kubernetes yaml file using pure python


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

z = np.random.rand(10, 10) # generate random data
nx, ny = z.shape
indx, indy = np.arange(nx), np.arange(ny)
x, y = np.meshgrid(indx, indy)

fig, ax = plt.subplots()
ax.imshow(z.T, interpolation="nearest", cmap=cm.YlGn) # plot grid values

for xval, yval in zip(x.flatten(), y.flatten()):
    zval = z[xval, yval]
    t = "%.1f%%"%(zval * 100,) # format value with 1 decimal point
    c = 'w' if zval > 0.75 else 'k' # if dark-green, change text color to white
    ax.text(xval, yval, t, color=c, va='center', ha='center')

xlabels = 'abcdefghij'
ylabels = '0123456789'
ax.set_xticks(indx+0.5) # offset x/y ticks so gridlines run on border of boxes
ax.set_yticks(indy+0.5)
ax.grid(ls='-', lw=2)

# the tick labels, if you want them centered need to be adjusted in
# this special way.
for a, ind, labels in zip((ax.xaxis, ax.yaxis), (indx, indy),
                          (xlabels, ylabels)):
    a.set_major_formatter(ticker.NullFormatter())
    a.set_minor_locator(ticker.FixedLocator(ind))
    a.set_minor_formatter(ticker.FixedFormatter(labels))

ax.xaxis.tick_top()

plt.show()

rawDescription: Colorplot of 2D array with Text Labels

description: Colorplot of 2D array with Text Labels


code: {{ user.profile.foo }}

rawDescription: {{ user.get_profile.foo }} not working in Django


code:
from StringIO import StringIO
import sys
import re

from pip import parseopts
from pip.commands import commands

def list_outdated(pypi_server):
    args = ['list', '-o', '-f', pypi_server, '--no-index']
    cmd_name, options, args, parser = parseopts(args)
    command = commands['list'](parser)

    _stdout = sys.stdout
    output = StringIO()
    sys.stdout = output
    command.main(args, options)
    sys.stdout = _stdout

    return re.findall('(\w+)\s+\(Current:\s+(.*?) Latest:\s+(.*?)\)', output.read() * 2)

outdated = list_outdated('http://my_server:8080/packages/')

rawDescription: how to use pip module to list versions on a server?

description: Use pip module to list versions on a server


code:
from itertools import product
d = {'Color': ['Red', 'Yellow'], 'Size': ['Small', 'Medium', 'Large']}
[dict(zip(d, v)) for v in product(*d.values())]

rawDescription: Combine Python Dictionary Permutations into List of Dictionaries


rawDescription: Data manipulation via regex in python for removal/editing of certain data in parentheses.


code: df.xs(1, axis=1, level=0)

rawDescription: How to slice multindex columns in pandas DataFrames?

description: Slice multindex columns in pandas DataFrames


code:
def save(self, **kwargs):
    super(Publisher, self).save(**kwargs)

    for item in self.item_set.all():
        item.code = "%s - whatever" % item.code

rawDescription: Django foreign key access in save() function


code:
def OnBrowse (self, event = None):
        """ Going to browse for file... """
        current = self.GetValue()
        directory = os.path.split(current)
        if os.path.isdir( current):
            directory = current
            current = ''
        elif directory and os.path.isdir( directory[0] ):
            current = directory[1]
            directory = directory [0]
        else:
            directory = self.startDirectory
            current = ''
        dlg = wx.FileDialog(self, self.dialogTitle, directory, current,
                            self.fileMask, self.fileMode)

        if dlg.ShowModal() == wx.ID_OK:
            self.SetValue(dlg.GetPath())
        dlg.Destroy()

rawDescription: How to disable/remove the input box in wx.lib.filebrowsebutton.FileBrowseButton?

description: Disable/remove the input box in wx.lib.filebrowsebutton.FileBrowseButton


code:
for indexIncr, rowArea in enumerate(cursorArea):
    rowArea[0] = listAreas[indexIncr]
    cursorArea.updateRow(rowArea)

rawDescription: Update Rows in Database with items from list, Python


code:
POSITION_CHOICES = (
    HOME_MAIN, "HOME_MAIN",
    BUTTOM_MAIN, "BOTTOM_MAIN",
    TOP_MAIN, "TOP_MAIN"
)

class Article(models.Model):
    position = models.CharField(max_lenght=50, choices=POSITION_CHOICES)

rawDescription: Best way to make an article model on Django?

description: Make an article model on Django


code: strings = "foo bar apple".split()

rawDescription: Python: efficient syntax for creating a list composed of strings


rawDescription: \b Regex include period as word

description: \b Regex include period as word


code: df.sub(df.a, axis=0)

rawDescription: Column operations in Pandas

description: Column operations in Pandas


code:
y=None
x=5
while x != y:
    y=int(input('GUESS the number: '))
    if y==x:
        print('you win! ')
    elif y<x:
        print('x is higher than',y)
    elif y>x:
        print('x is lower than',y)

rawDescription: How to make an algorithm repeat itself in python

description: Make an algorithm repeat itself in python


code:
import datetime
import peewee as pw
import acme.core as acme

adapter = pw.MySQLDatabase(
    acme.get_config(path='database.db'),
    host=acme.get_config(path='database.host'),
    port=int(acme.get_config(path='database.port', default=3306)),
    user=acme.get_config(path='database.user'),
    passwd=acme.get_config(path='database.password'))

class Model(pw.Model):
    """
    The base model that will connect the database
    """
    id = pw.PrimaryKeyField()
    created_at = pw.DateTimeField()
    updated_at = pw.DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = adapter

class ServerModule(Model):
    enabled = pw.BooleanField()
    ipaddr = pw.IntegerField()
    port = pw.IntegerField()

    class Meta:
        db_table = 'module_server'

rawDescription: pee wee Meta subclass inheritance

description: Pee wee Meta subclass inheritance


code:
def sorted(iterable):
    templist = list(iterable)
    templist.sort()
    return templist

rawDescription: Python set sorted, Why so fast?

description: Python set sorted, Why so fast


code:
class TestFirefox:
    browser = '*firefox'

    def pytest_funcarg__selenium(self, request):
        sel = selenium('10.3.10.154', 5555, self.browser, 'http://10.3.10.180:8000')
        sel.start()
        return sel

class TestChrome(TestFirefox):
    browser = '*opera'

rawDescription: Testing multiple browsers with a single test definition in Selenium


code:
all_data = []

fhand = open('/tmp/data')

for line in fhand:
    data_parts = line.strip().split(',')
    # Convert the data to a tuple of country and the exchange rate as
    # a number (rather than a string).
    data_item = (data_parts[0], float(data_parts[2]))
    all_data.append(data_item)
fhand.close()

# Sort that data by the 2nd part of the tuple: the exchange rate
all_data.sort(key = lambda x: x[1])
# print out the sorted list but only print the first part: the country
for di in all_data:
    print(di[0])

rawDescription: Sorting a list of list/tuple by element at a certain index


code: m = re.match(r"(?:[^euioa]|[euioa](?![euioa]))*$", word)

rawDescription: Regex Adjacent Characters

description: Regex Adjacent Characters


code: url_for('add', variable=foo)

rawDescription: Create dynamic URLs in Flask with url_for()


code:
polys = []
for cont in contours1:
    approx_curve = cv2.approxPolyDP(cont, 3, False)
    polys.append(approx_curve)
cv2.drawContours(img, polys, -1, (0, 255, 0), thickness=1, lineType=8)
cv2.imshow("medicine polygons", img)
cv2.waitKey()

rawDescription: How to create vector polygon objects after watershed segmentation

description: Create vector polygon objects after watershed segmentation


code:
from ghost import Ghost
ghost = Ghost()
page, resources = ghost.open('http://stackoverflow.com/')
if page.http_status == 200:
    result, extra = ghost.evaluate('document.title;')
    print('The title is: {}'.format(result))

rawDescription: Get information from a Ghost.py file

description: Get information from a Ghost.py file


code:
import os
from setuptools import setup
from setuptools.command.install import install
import subprocess

def get_virtualenv_path():
    """Used to work out path to install compiled binaries to."""
    if hasattr(sys, 'real_prefix'):
        return sys.prefix

    if hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix:
        return sys.prefix

    if 'conda' in sys.prefix:
        return sys.prefix

    return None

def compile_and_install_software():
    """Used the subprocess module to compile/install the C software."""
    src_path = './some_c_package/'

    # compile the software
    cmd = "./configure CFLAGS='-03 -w -fPIC'"
    venv = get_virtualenv_path()
    if venv:
        cmd += ' --prefix=' + os.path.abspath(venv)
    subprocess.check_call(cmd, cwd=src_path, shell=True)

    # install the software (into the virtualenv bin dir if present)
    subprocess.check_call('make install', cwd=src_path, shell=True)

class CustomInstall(install):
    """Custom handler for the 'install' command."""
    def run(self):
        compile_and_install_software()
        super().run()

setup(name='foo',
      # ...other settings skipped...
      cmdclass={'install': CustomInstall})

rawDescription: Compiling & installing C executable using python's setuptools/setup.py?


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

# http://en.wikipedia.org/wiki/File:Bilininterp.png
xi = np.array([0.0, 1.0])
yi = np.array([0.0, 1.0])
zi = np.array([[0.0, 1.0], [1.0, 0.5]])

# Another example
xi = np.array([0.0, 0.25, 1.0])
yi = np.array([0.0, 0.75, 1.0])
zi = np.array([[0.0, 0.5, 1.0], [0.5, 0.7, 0.5], [1.0, 1.0, 1.0]])

# I want 20 "levels" to be shown
contour_breaks = 20
ticks = np.linspace(zi.min(), zi.max(), contour_breaks, endpoint=True)

# Attempt 4 (interp2d does to correct bilinear interpolation)
fig = plt.figure()
axes = fig.add_subplot(111, aspect='equal')
f = interp2d(xi, yi, zi, kind='linear')
xi2 = np.linspace(0., 1., 100)
yi2 = np.linspace(0., 1., 100)
zi2 = f(xi2, yi2)
axes.contour(xi2, yi2, zi2, ticks[1:-1], colors='k')
fill = axes.contourf(xi2, yi2, zi2, ticks, cmap=cm.jet)
fig.colorbar(fill, ticks=ticks)

# Show the plots
plt.show()

rawDescription: Python/Matplotlib - Contour Plot with Bilinear Interpolation


code:
import spidermonkey

def loadfile(fname):
    return open(fname).read()

rt = spidermonkey.Runtime()
cx = rt.new_context()
cx.add_global("loadfile", loadfile)
ret = cx.execute('var contents = loadfile("foo.js"); eval(contents);')

rawDescription: file I/O in Spidermonkey

description: File I/O in Spidermonkey


code:
for r in results:
    pie_chart.add(r[1], [{'value': r[0], 'label': r[1]}])

rawDescription: Using PyGal, how can I embed a label on the pie chart itself on hover?


code:
from tkinter import Tk, Scale

root = Tk()

w = Scale(root, from_=0, to=200)
w.pack()
w.set(100)  # Set the initial value to 100

root.mainloop()

rawDescription: How to make scale on Tkinter start in certain place?

description: Make scale on Tkinter start in certain place


code:
from rest_framework.pagination import BasePaginationSerializer, NextPageField
class MyPaginationSerializer(BasePaginationSerializer):

    next = NextPageField(source='*')

rawDescription: Change or Remove Default Return Values from PaginationSerializer


code: intermediate_list = (combinations(item,2) for item in windowed) # outer parentheses required

rawDescription: combining sliding window with pairs enumeration in Python

description: Combining sliding window with pairs enumeration in Python


code:
d = { "Report": 1,
      "Article": 2,
       "Book": 3 }
result = sorted(mylist, key=lambda x:d[x[0]])

rawDescription: Python: How to custom order a list?

description: Python: How to custom order a list


code:
flattened.composite(img,
                    PythonMagick.GravityType.CenterGravity,            # this
                    PythonMagick.CompositeOperator.SrcOverCompositeOp)

rawDescription: How to compose with center gravity in PythonMagick

description: Compose with center gravity in PythonMagick


code:
import datetime

d = datetime.date(2013,12,8)

last_day = datetime.date(d.year, (d.month+1)%12, 1) - datetime.timedelta(1,0,0)

rawDescription: How to get date range at now to end of the month?

description: Get date range at now to end of the month


code:
def turnMainImageOn1 (event):
    if event.widget != root:
        return
    #rest of function goes here

#...

def turnMainImageOff (event): #sets main image to off
    if event.widget != root:
        return
    #rest of function goes here

rawDescription: Python tkinter main window bind mouse over/leave triggering while still inside main window


code: login_password = forms.CharField(label=u'password', widget=forms.PasswordInput(render_value=False, attrs={'placeholder': 'password'}))

rawDescription: How to use more than one widget in a Django field?

description: Use more than one widget in a Django field


code:
data
data.set_index('Date').diff()

rawDescription: Calculating difference between two rows in Python / Pandas


code:
# import xml.etree.cElementTree as et
import lxml.etree as et
import sys

toc = [
  {'entryno': 1, 'level': 1, 'pageno': 17, 'title': 'title a'},
  {'entryno': 2, 'level': 2, 'pageno': 19, 'title': 'title b'},
  {'entryno': 3, 'level': 1, 'pageno': 25, 'title': 'Smith & Wesson'},
  {'entryno': 4, 'level': 2, 'pageno': 27, 'title': '<duct tape>'},
  {'entryno': 5, 'level': 2, 'pageno': 29, 'title': u'\u0404'},
  ]

root = et.Element("root")
tree = et.ElementTree(root)
parent = {0: root}
for entry in toc:
    level = entry['level']
    entryno = entry['entryno']
    # create the element and link it to its parent
    elem = et.SubElement(parent[level - 1], "entry", {'id': str(entryno)})
    # create children to hold the other data items
    for k, v in entry.iteritems():
        if k in ('entryno', 'level'): continue
        child = et.SubElement(elem, k)
        child.text = unicode(v)
    # record current element as a possible parent
    parent[level] = elem
# tree.write(sys.stdout)
tree.write(sys.stdout, pretty_print=True)

rawDescription: Python: How to create nested XML from a flat datastructure


code:
_id = 18865
T = aliased(ProductStock, name="T")
T1 = aliased(ProductStock, name="T1")
subquery = (
    session.query(func.max(T1.detected_date).label("detected_date"))
    .filter(T1.id == _id)
    # .filter(T1.id == T.id)  # @note: i prefer this one to the line above
    .as_scalar()
)
qry = (
    session.query(T)
    .filter(T.detected_date == subquery)
    .filter(T.id == _id)
)

rawDescription: Convert raw SQL to SQLAlchemy query

description: Convert raw SQL to SQLAlchemy query


code:
import matplotlib.pyplot as plt

linestyle = dict(color='red', marker='^', linestyle='--', linewidth=2)

fig, ax = plt.subplots()
line, = ax.plot(range(10))

plt.setp(ax, xlim=[-1, 12], ylim=[-5, 12], xlabel='X-axis')
plt.setp(line, **linestyle)

plt.show()

rawDescription: matplotlib assign multiple variables to axes instance with single command

description: Matplotlib assign multiple variables to axes instance with single command


code:
def calc_quotient(numerator, denominator):
    if denominator == 0:
        raise ValueError("denominator can't be zero!")

    sign = -1 if numerator * denominator < 0 else 1
    numerator = abs(numerator)
    denominator = abs(denominator)

    quotient = 0
    while numerator >= denominator:
        numerator -= denominator
        quotient += 1
    return sign * quotient

def get_num_of_inputs():
    return int(input("What is the number of inputs?: "))

def get_input():
    numerator = int(input("\nEnter the numerator: "))
    denominator = int(input("Enter the denominator (must not be zero): "))
    return numerator, denominator

def display_output(numerator, denominator, quotient):
    print("\nThe quotient of", numerator, "and", denominator, "is:", quotient)

def main():
    num_of_inputs = get_num_of_inputs()
    for i in range(num_of_inputs):
        numerator, denominator = get_input()
        quotient = calc_quotient(numerator, denominator)
        display_output(numerator, denominator, quotient)

if __name__ == '__main__':
    main()

rawDescription: Trouble with Iterations in Function

description: Trouble with Iterations in Function


code: f_words = [(word, freq) for (word, freq) in the_list if word.startswith('f')]

rawDescription: Dictionary manipulation in Python

description: Dictionary manipulation in Python


code: 'django.contrib.flatpages', # added for flatpages

rawDescription: Django Flatpages DB Tables Not Created

description: Django Flatpages DB Tables Not Created


code:
a = 1
isinstance(a, int)
s = "test"
isinstance(s, str)

rawDescription: How to know the type of a object in a simple way?

description: Know the type of a object in a simple way


code:
# spell out the args that were passed to the Matlab function
N=10
Fc=40
Fs=1600
# provide them to firwin
h=scipy.signal.firwin( numtaps=N, cutoff=40, nyq=Fs/2)

y=scipy.signal.lfilter( h, 1.0, x) # 'x' is the time-series data you are filtering

rawDescription: Lowpass Filter in python

description: Lowpass Filter in python


code: tags = {e.tag for e in doc.iter() if e.text}

rawDescription: Fastest way to get tags containing text

description: Fastest way to get tags containing text


code:
data = sc.parallelize(['abc123Key1asdas','abc123Key1asdas','abc123Key1asdas', 'abcw23Key2asdad', 'abcw23Key2asdad', 'abcasdKeynasdas', 'asfssdKeynasda', 'asdaasKeynsdfa'])
data.map(lambda line: (line[6:10],line)).groupByKey().mapValues(list).collect()

rawDescription: Apache Spark Python GroupByKey or reduceByKey or combineByKey


code:
class MyList(list):
    #your stuff here

    def __getslice__(self, i, j):
        return MyList(list.__getslice__(self, i, j))

rawDescription: Python Subclass Builtin List

description: Python Subclass Builtin List


code:
def getWord(string, word):
    index = 0
    data = []
    for i in string.split(' '):
        if i.lower() in word.lower():
            data.append(index)
        index += 1
    return data

rawDescription: How can I find and print the indexes of multiple elements in a list?

description: Find and print the indexes of multiple elements in a list


code:
#typecasting the JSON to string for json.loads to work
data = str(data)
#returning type dict from json
j_data = json.loads(data)
#typecasting the dict to string before writing to log
self.log(str(j_data))

rawDescription: Unable to convert returned JSON data into Dict in Scrapy


code:
nx,ny = smallerArray.shape
largeArray[0:nx,0:ny] = smallerArray[0:nx,0:ny]

rawDescription: Python - Copying into Numpy Array of set size


code:
srcpath = os.path.join(src, columns['label'])
dstpath = os.path.join(dst, columns['label'])
shutil.copyfile(srcpath, dstpath)

rawDescription: Copy certain files from one folder to another using python


code:
d = {}
d["newVar"] = 87
d["foo"] = "Hello world!"
print(d["foo"])

rawDescription: Strings to Variables containing Strings - Python


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

import cherrypy

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}

def isconnected():
  instance = cherrypy.serving.request.handler.callable.__self__
  if not instance.instanceAttr:
    raise cherrypy.HTTPError("403 Forbidden")

cherrypy.tools.isconnected = cherrypy.Tool('before_handler', isconnected)

class App:

  instanceAttr = None

  def __init__(self):
    self.instanceAttr = 123

  @cherrypy.tools.isconnected()
  @cherrypy.expose
  def index(self):
    return '''foo'''

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: How to write a one function tool that does a check on a class variable in cherrypy

description: Write a one function tool that does a check on a class variable in cherrypy


code:
import heapq
import random

SIZE = 10
with open('yourfile') as fin:
    sample = heapq.nlargest(SIZE, fin, key=lambda L: random.random())

rawDescription: Extracting a random line in a file without loading the file into RAM in python


code:
from scipy.integrate import odeint
from numpy import array,linspace,tile,empty_like
a = array([-2.0,-1.5,-1.,-0.5])
b = array([-.1,-.1,-.1,-.1])

yinit = tile(array([0.0005,0.2]),a.size)

def deriv(y,_):
    dy = empty_like(y)
    dy[0::2]=y[1::2]
    dy[1::2]=y[::2]*a+b*y[1::2]
    return dy
time = linspace(0.0,10.0,100)
y = odeint(deriv,yinit,time)

rawDescription: Using numpy arrays with scipy odeint

description: Using numpy arrays with scipy odeint


code: text = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Some help text'}))

rawDescription: How to add help_text to display as input value?

description: Add help_text to display as input value


code:
#update_data={"enable_vod_hd": "1", "enable_est_hd": "1"}
newfile.write((
    """<cleared_for_hd_vod>%(enable_est_hd)s</cleared_for_hd_vod>
       <cleared_for_hd_sale>%(enable_vod_hd)s</cleared_for_hd_sale>
    """ %
    ({
      'enable_est_hd': bool(update_data["enable_est_hd"]),
      'enable_vod_hd': bool(update_data["enable_vod_hd"])
    })
).lower())

rawDescription: Convert Mysql bool to python True/False

description: Convert Mysql bool to python True/False


code:
import csv

def open_writer(tag):
    handle_w = open('%s.csv' %(tag, ), 'wb')
    return handle_w, csv.writer(handle_w, delimiter=' ')

handle0 = open('ss.csv', 'r')
writers = map(open_writer, [tag.rstrip() for tag in handle0])

handle0.close()

with open('ss.csv') as handle2:
    for w, tag in zip(writers, handle2):
        w[1].writerow(["  ", "Waybill", "Contents", "  ", "Amount", "COD Amount", "Type", "  ", "Error"])
        with open('1.csv', 'rb') as csvfile:
            handle1 = csv.reader(csvfile, delimiter=' ')
            for row in handle1:
                if tag.rstrip() in row:
                    w[1].writerow(row)

map(lambda w: w[0].close(), writers)

rawDescription: How to make python read csv files and extract data and paste it another csv?

description: Make python read csv files and extract data and paste it another csv


code:
class Category(models.Model):
   name = models.CharField(max_length=30, unique=True)

   def __unicode__(self):
        return self.name

rawDescription: How can I change name of option in django select box

description: Change name of option in django select box


code:
def handleCollision(collidedLands, testRectangle):
    newRectangle = Rectangle(testRectangle.X + xVelocity, testRectangle.Y)
    return newRectangle

rawDescription: Java Pass By Reference Transcode To Python


code:
def remove_every_nth_word_from_file(filename, n):
    with open(filename) as f:
        words = f.read().split()
        del words[n - 1::n]
    return words

rawDescription: remove every nth word from file

description: Remove every nth word from file


code:
by_row = {1: [1, 2, 3, 4], 2: [1, 2, 3, 4]}
by_column = {n+1:[row[n] for row in by_row.values()] for n in range(len(by_row[1]))}
by_column

rawDescription: Keying by columns, not rows

description: Keying by columns, not rows


rawDescription: Why was the value of a global variable being altered when I didn't program it to (strange behavior)?


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

width=5
height=3
col_width=.075

data=numpy.array([[1, 2,5],[3,4,7],[7,9,5]])
headings=['long heading 1', 'long heading 2', 'longish 3']
fig=plt.figure(figsize=(width,height))
ax=fig.add_subplot(111, frameon=False, xticks=[], yticks=[])

the_table = plt.table(cellText=data, rowLabels=headings,
    colWidths=[col_width]*data.shape[1], loc='center') #remove colLabels
the_table.auto_set_font_size(False)
the_table.set_fontsize(10)
the_table.scale(1, 1.6)

#custom heading titles - new portion
hoffset=0.42 #find this number from trial and error
voffset=0.66 #find this number from trial and error
line_fac=0.98 #controls the length of the dividing line
count=0
for string in headings:
    ax.annotate('  '+string, xy=(hoffset+count*col_width,voffset),
        xycoords='axes fraction', ha='left', va='bottom',
        rotation=45, size=10)

    #add a dividing line
    ax.annotate('', xy=(hoffset+(count+0.5)*col_width,voffset),
        xytext=(hoffset+(count+0.5)*col_width+line_fac/width,voffset+line_fac/height),
        xycoords='axes fraction', arrowprops={'arrowstyle':'-'})

    count+=1

plt.show()

rawDescription: How can I rotate column titles in pyplot.table?

description: Rotate column titles in pyplot.table


code:
s = s.reorder_levels(['date', 'id'])
s = s.sortlevel(0)

results = []

for i in range(len(s.index.levels[0])-1):
    t = time.time()
    s0 = s.loc[s.index.levels[0][i]]
    s1 = s.loc[s.index.levels[0][i+1]]
    df = pd.concat((s0, s1), axis=1)

    # Note: this is slower than the line above
    # df = s.loc[s.index.levels[0][0:2], :].unstack(0)

    df = df.fillna('unknown')
    mi = pd.MultiIndex.from_arrays((df.iloc[:, 0], df.iloc[:, 1]))
    s2 = pd.Series(1, mi)
    res = s2.groupby(level=[0, 1]).apply(np.sum)
    results.append(res)
    print(time.time() - t)

results = pd.concat(results, axis=1)

rawDescription: Pandas optimizing an interpolation/counting algorithm


code:
@app.route('/poll', methods = ['GET', 'POST'])
def poll():
    form = PollForm()
    if form.validate_on_submit():
        # use request.form to update your database
        return redirect('/details')
    return render_template('poll.html', form=form)

@app.route('/details')
def details():
    # query the database to show the updated poll
    return render_template('details.html')

rawDescription: Flask request empty after redirect

description: Flask request empty after redirect


code:
import shelve
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
db = shelve.open('/path/to/my/database/file.db', writeback=True) # Notice the file must already exist
db['a'] = a[2:5]
db.close()
quit()
import shelve
db = shelve.open('/path/to/my/database/file.db', writeback=True)
db['a']

rawDescription: Is there anyway to select and save any part of array?


code:
from itertools import product
first_index=1
for i in product(*[range(i) for i in count]):
    for j in range(len(count)):
        print( '{0:3} , {1:3} , {2:1}'.format(first_index, table[i[j]][j], j+1))
    first_index += 1

rawDescription: python dynamically create loops

description: Python dynamically create loops


code:
def alter_list_data_to_serialize(self, request, data):
    #call external procedure here
    return data

rawDescription: customize tastypie patch_list

description: Customize tastypie patch_list


code:
@view_defaults(route_name='myservice')
class MyServiceView(object):

    def __init__(self, request):
        self.request = request

    @view_config(request_method='GET')
    def get(self):
        return Response(u'This is the GET view')

    @view_config(request_method='POST')
    def post(self):
        return Response(u'This is the POST view')

    @view_config(request_method='PUT')
    def put(self):
        return Response(u'This is the PUT view')

    @view_config(request_method='DELETE')
    def delete(self):
        return Response(u'This is the DELETE view')

rawDescription: Building a web service with Pyramid

description: Building a web service with Pyramid


code:
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

def exponential_fit(x, a, b, c):
    return a*np.exp(-b*x) + c

if __name__ == "__main__":
    x = np.array([0, 1, 2, 3, 4, 5])
    y = np.array([30, 50, 80, 160, 300, 580])
    fitting_parameters, covariance = curve_fit(exponential_fit, x, y)
    a, b, c = fitting_parameters

    next_x = 6
    next_y = exponential_fit(next_x, a, b, c)

    plt.plot(y)
    plt.plot(np.append(y, next_y), 'ro')
    plt.show()

rawDescription: extrapolating data with numpy/python

description: Extrapolating data with numpy/python


code:
import urllib2
import xmltodict

def homepage(request):
    file = urllib2.urlopen('https://www.goodreads.com/review/list/20990068.xml?key=nGvCqaQ6tn9w4HNpW8kquw&v=2&shelf=toread')
    data = file.read()
    file.close()

    data = xmltodict.parse(data)
    return render_to_response('my_template.html', {'data': data})

rawDescription: Parse XML from URL into python object

description: Parse XML from URL into python object


code:
if condition_one_true:
    sound_one = Sound('sound1.mp3')
    sound_one.play()

if condition_two_true:
    sound_two= Sound('sound2.mp3')
    sound_two.play()

rawDescription: Choosing which sound to play in Pygame

description: Choosing which sound to play in Pygame


code:
import struct
# read 2 bytes from hardware as a string
s = hardware.readbytes(2)
# h means signed short
# < means "little-endian, standard size (16 bit)"
# > means "big-endian, standard size (16 bit)"
value = struct.unpack("<h", s) # hardware returns little-endian
value = struct.unpack(">h", s) # hardware returns big-endian

rawDescription: Receiving 16-bit integers in Python

description: Receiving 16-bit integers in Python


code:
def fib():
    a, b = 0, 1
    while True:
        a, b = b, a + b
        yield a

rawDescription: Length of generator output

description: Length of generator output


code:
from flask import request, current_app

@app.before_request
def log_request():
    if current_app.config.get('LOG_REQUESTS'):
        current_app.logger.debug('whatever')
        # Or if you dont want to use a logger, implement
        # whatever system you prefer here
        # print request.headers
        # open(current_app.config['REQUEST_LOG_FILE'], 'w').write('...')

rawDescription: Dumping HTTP requests with Flask

description: Dumping HTTP requests with Flask


code: any(d['site'] == 'Superuser' for d in data)

rawDescription: What's the best way to search for a Python dictionary value in a list of dictionaries?


code:
from pyparsing import OneOrMore,QuotedString
bracketed = QuotedString('[',endQuoteChar=']')
OneOrMore(bracketed).parseString('[sldflsdjkf][asdf][sdf]').asList()

rawDescription: Wrap Words in Square Bracket Instead of sglQuotedString or dblQuotedString


rawDescription: How do I change the background color of a matplotlib inline plot in LightTable?

description: Change the background color of a matplotlib inline plot in LightTable


code:
class MyWidget(QWidget):

    def __init__(parent):

        self.treeWidget = ...

        # switch off "default" editing behaviour
        # as it does not allow to configure only an individual
        # column as editable
        self.treeWidget.setEditTriggers(self._treeWidget.NoEditTriggers)

        # to be able to decide on your own whether a particular item
        # can be edited, connect e.g. to itemDoubleClicked
        self.treeWidget.itemDoubleClicked.connect(self.checkEdit)

    # in your connected slot, you can implement any edit-or-not-logic
    # you want
    def checkEdit(self, item, column):
        # e.g. to allow editing only of column 1:
        if column == 1:
            self.treeWidget.editItem(item, column)

rawDescription: How to edit only one column of a QTreeWidgetItem

description: Edit only one column of a QTreeWidgetItem


code:
import sys
from PyQt4 import QtCore, QtGui

def F(n, m):
    return n + m

class MainWindow(QtGui.QWidget):
    # http://stackoverflow.com/a/11458784/190597 (reclosedev)
    def __init__(self, parent=None):
        self.rows = range(50)
        self.cols = range(100)
        super(MainWindow, self).__init__(parent)
        self.table_widget = QtGui.QTableWidget()
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.table_widget)
        self.setLayout(layout)
        self.populate()

    def populate(self):
        self.table_widget.setRowCount(len(self.rows))
        self.table_widget.setColumnCount(len(self.cols))
        self.table_widget.setHorizontalHeaderLabels(map(str, self.cols))
        for i, n in enumerate(self.rows):
            for j, m in enumerate(self.cols):
                value = QtGui.QTableWidgetItem(str(F(n, m)))
                self.table_widget.setItem(i, j, value)
        self.table_widget.item(5,2).setBackgroundColor(QtGui.QColor(0,255,255))
        self.table_widget.item(5,2).setTextColor(QtGui.QColor("red"))

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    wnd = MainWindow()
    wnd.resize(640, 480)
    wnd.show()
    sys.exit(app.exec_())

rawDescription: display the values of a function in bidimensional graphical table

description: Display the values of a function in bidimensional graphical table


code:
class Node(Base):

    __tablename__ = 'Node'
    ID = Column(Integer, primary_key=True)
    ParentID = Column(Integer, ForeignKey('Node.ID', ondelete='CASCADE'))
    type = Column(Text(50))

    Children = relationship(
                'Node',
                cascade="all",
                backref=backref("Parent", remote_side='Node.ID'),
            )

    __mapper_args__ = {
                'polymorphic_identity':'Node',
                'polymorphic_on':type
            }

rawDescription: Deleting from self-referential inherited objects does not cascade in SQLAlchemy-SQLite


code:
class MyOrderedDict(OrderedDict):
    def next_key(self, key):
            next = self._OrderedDict__map[key][1]
            if next is self._OrderedDict__root:
                    raise ValueError("{!r} is the last key".format(key))
            return next[2]
    def first_key(self):
            for key in self: return key
            raise ValueError("OrderedDict() is empty")

od = MyOrderedDict([('apple', 4), ('banana', 3), ('orange', 2), ('pear', 1)])
od.next_key("apple")
od.next_key("banana")
od.next_key("orange")
od.next_key("pear")
od.first_key()

rawDescription: How to get the "next" item in an OrderedDict?

description: Get the "next" item in an OrderedDict