code:
from Tkinter import *

root=Tk()
root.geometry("540x250+400+250")
root.title('Converter')
root.resizable(0, 0)

frame = Frame(root)
frame.grid(row=0, column=0, sticky='NSEW')

frame.grid_columnconfigure(0,minsize=180 )
frame.grid_columnconfigure(1, weight=100,minsize=150)
frame.grid_columnconfigure(2, weight=100,minsize=150)
frame.grid_columnconfigure(3, weight=100,minsize=150)

variable = StringVar(root)
variable.set("   Select A Measurement   ") # default value

variable2 = StringVar(root)
variable2.set("Select A Second Measurement") # default value

l=Label(frame,text='To')
l.grid(row=1, column=1, sticky='NW',)

w = OptionMenu(frame, variable, "CM", "MM", "M", "Inches")
w.grid(row=1, column=0, sticky='NE')

w2 = OptionMenu(frame, variable2, "Inches", "MM", "M", "CM")
w2.grid(row=1, column=2, sticky='NW')

#spacers
w = Label(frame,text='  ')
w.grid(row=3, column=1, sticky='NW')

#spacers
w = Label(frame,text='  ')
w.grid(row=2, column=1, sticky='NW')

b = Button(frame, text="  Convert  ",font=(None,15))
b.grid(row=4, column=1, sticky='NW')

mainloop()

rawDescription: How To Keep The Widget's Centered In Tkinter?


code:
thread = Thread()
thread.finished.connect(gui.do_update_thingy)

rawDescription: keep alive thread in PyQt4

description: Keep alive thread in PyQt4


code:
from itertools import imap

def generate_playlist(pairs):
  '''
  @param pairs: list of pairs, first element is a file name, second - repetition amount
  @return: generator for playlist items
  '''
  max_show_times = max(imap(second, pairs))
  for i in xrange(max_show_times):
    for file_path, repetition_count in pairs:
      if i % (max_show_times / repetition_count) == 0:
           yield file_path

def second(col):
  if col and len(col) > 1:
    return col[1]

playlist = generate_playlist(file_to_count_pairs)
playlist = imap(get_file_name_without_ext, playlist)

rawDescription: Make playlist in python for Ads player

description: Make playlist in python for Ads player


code:
import os
os.system("cd mydir;cat * > merged.txt")

rawDescription: Unix cat function (cat * > merged.txt) in Python?


code:
def function(self):
    a = 'player'+str(self)
    getattr(database,a).update(data=0)

rawDescription: Python: Trying to access different dictionaries in an imported file, based on variable given


rawDescription: How to modify this string in Python

description: Modify this string in Python


code:
import ctypes
import sys
ctypes.pythonapi._PyDict_NewPresized.restype = ctypes.py_object
d = ctypes.pythonapi._PyDict_NewPresized(100)
sys.getsizeof(d)
sys.getsizeof({})
len(d)

rawDescription: Can a callout to C presize a Python dict's capacity?


code:
start_urls = ['mywebsite/?page=1']

def parse(self, response):
    sel = Selector(response)
    DateDifference= sel.xpath('xpath for date difference').extract()[0]

    i = response.meta['index'] if 'index' in response.meta else 1

    if DateDifference.days < 8:
        yield Request(Link, meta={'date': Date}, callback = self.crawl)
        i += 1
        yield Request('mywebsite/?page='+str(i), meta={'index':i}, callback=self.parse)

rawDescription: scrapy scrap on all pages that have this syntax

description: Scrapy scrap on all pages that have this syntax


code:
from sklearn.svm import SVC
from sklearn.grid_search import GridSearchCV
from sklearn import datasets
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

digits = datasets.load_digits()
X = digits.data
y = digits.target

clf_ = SVC(kernel='rbf')
Cs = [1, 10, 100, 1000]
Gammas = [1e-3, 1e-4]
clf = GridSearchCV(clf_,
            dict(C=Cs,
                 gamma=Gammas),
                 cv=2,
                 pre_dispatch='1*n_jobs',
                 n_jobs=1)

clf.fit(X, y)

scores = [x[1] for x in clf.grid_scores_]
scores = np.array(scores).reshape(len(Cs), len(Gammas))

for ind, i in enumerate(Cs):
    plt.plot(Gammas, scores[ind], label='C: ' + str(i))
plt.legend()
plt.xlabel('Gamma')
plt.ylabel('Mean score')
plt.show()

rawDescription: How to graph grid scores from GridSearchCV?

description: Graph grid scores from GridSearchCV


code:
from scrapy.http import Request
from scrapy import log
import os.path

class IgnoreVisitedItems(object):
    def __init__(self):
        # Load the URLs that have already been crawled
        self._cu_file = open("crawled_urls.txt", "a+")
        self._crawled_urls = set([line.strip() for line in self._cu_file.readlines()])

    def process_spider_output(self, response, result, spider):
        ret = []
        for x in result:
            # Find the URL in the result or response
            url = None
            if isinstance(x, Request):
                url = x.url
            else:
                url = response.request.url

            # Check if the URL has been crawled, and add
            # it to the list of crawled URLs.
            if url in self._crawled_urls:
                log.msg("Ignoring already visited: %s" % url,
                        level=log.INFO, spider=spider)
            else:
                log.msg("Adding %s to list of visited urls" % url,
                        level=log.INFO, spider=spider)
                self._cu_file.write(url + '\n')
                self._crawled_urls.add(url)
                ret.append(x)
        return ret

rawDescription: Spider middleware in Portia not called

description: Spider middleware in Portia not called


code:
def init_and_return(**init_dict):

    # this could be extended to allow for more than one k-v argument
    if len(init_dict) != 1:
        raise ValueError('Exactly one "name=type" pair should be supplied')

    _name, _type = init_dict.items()[0]
    def outer(function):

        @wraps(function)
        def inner(*args, **kwargs):

            # instantiate a new container
            _value = _type()

            # used to roll-back the original global variable
            _backup, _check = None, False

            # store original global variable (if it exists)
            if _name in function.func_globals:
                _backup = function.func_globals[_name]
                _check = True

            # add container to global scope
            function.func_globals[_name] = _value

            function(*args, **kwargs)

            # roll-back if it existed beforehand, delete otherwise
            if _check:
                function.func_globals[_name] = _backup
            else:
                del function.func_globals[_name]

            return _value
        return inner
    return outer

rawDescription: Pythonic way to create closures

description: Pythonic way to create closures


code:
from lxml import etree

doc = etree.parse("original.xml")
etree.ElementTree(doc.getroot()).write("out.xml",
                                       encoding="UTF-8",
                                       xml_declaration=True)

rawDescription: how to use etree.write() to output a xml file that doesn't have default ns?

description: Use etree.write() to output a xml file that doesn't have default ns


code:
from win32com.shell import shell, shellcon

desktop = shell.SHGetDesktopFolder()
for pidl in desktop:
    if desktop.GetDisplayNameOf(pidl, shellcon.SHGDN_NORMAL) == "Computer":
        break
folder = desktop.BindToObject(pidl, None, shell.IID_IShellFolder)
for pidl in folder:
     if folder.GetDisplayNameOf(pidl, shellcon.SHGDN_NORMAL) == "My iPhone":
         break
folder = folder.BindToObject(pidl, None, shell.IID_IShellFolder)
for pidl in folder:
    if folder.GetDisplayNameOf(pidl, shellcon.SHGDN_NORMAL) == "Internal Storage":
        break
# And so on...

rawDescription: How can I iterate across the photos on my connected iPhone from Windows 7 in Python?

description: Iterate across the photos on my connected iPhone from Windows 7 in Python


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

    def __add__(self, other):
        if not isinstance(other, Value):
            raise TypeError
        return Value(self.x + other.x)

    def __mul__(self, other):
        if not isinstance(other, Value):
            raise TypeError
        return Value(self.x * other.x)

assert (Value(2) + Value(3)).x == 5
assert (Value(2) * Value(3)).x == 6

rawDescription: How to modify arithmetic operators (+,-,x)

description: Modify arithmetic operators (+,-,x)


rawDescription: Pandas: Get out values from a list in a DataFrame


code:
import numpy as np
K=np.random.normal(size=(2,2))
eigenvalues, eigenvectors = np.linalg.eig(K)
eigenvectors
eigenvectors.shape

rawDescription: Python eigenvectors

description: Python eigenvectors


code: assertEqual([test.value for test in test_instance_objects], [1, 2, 3, 4, 5])

rawDescription: Python assertEquals generator

description: Python assertEquals generator


code:
import os

def executable_filter(filter_info, data):
    path = filter_info[0]
#   Note that this only checks if the current effective user may execute the file.  If you need to know if owner/group/other can execute it, you'll probably want something from the os.stat module.
    return os.access(path, os.X_OK)

filter_file.add_custom((gtk.FILE_FILTER_FILENAME, None, None, None), executable_filter, None)

rawDescription: Add filter on executable files in filechooser dialog using pygtk when OS is Ubuntu


code:
import os
from subprocess import Popen

devnull = open(os.devnull, 'wb') # use this in python < 3.3
# python >= 3.3 has subprocess.DEVNULL
Popen(['nohup', 'script.sh'], stdout=devnull, stderr=devnull)

rawDescription: how to spawn new independent process in python

description: Spawn new independent process in python


rawDescription: How to use trailing rows on a column for calculations on that same column | Pandas Python

description: Use trailing rows on a column for calculations on that same column | Pandas Python


code:
def sendkafka(messages):
    kafka = KafkaClient("localhost:9092")
    producer = SimpleProducer(kafka)
    for message in messages:
        yield producer.send_messages('topic', message)

sentRDD = messageRDD.mapPartitions(sendkafka)

rawDescription: Sending Large CSV to Kafka using python Spark


code:
a = [2,3,4]
function(1, *a) # equal to function(1,2,3,4)
b = {'x':42, 'y':None}
function(1, **b) # equal to function(1, x=42, y=None)

rawDescription: Passing a string as a keyed argument to a function


code:
from django.db.models import Avg

p = Property.objects.get(...)
stars_average = p.rating_set.aggregate(Avg('stars')).values()[0]

rawDescription: get average from set of objects in django

description: Get average from set of objects in django


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

fig = plt.figure()
ax = fig.gca(projection='3d')
matrix = np.array([[0, 1, 2, 3, 4], [.5, 1.5, 2.5, 3.5, 4.5], [1, 2, 3, 4, 5]])
z, x = matrix.shape
Z = np.arange(0, z, 1)
X = np.arange(0, x, 1)
Z, X = np.meshgrid(Z, X)
Y = matrix[Z, X]
ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
        linewidth=0, antialiased=False, cmap = cm.coolwarm)

plt.show()

rawDescription: Surface plot in python

description: Surface plot in python


code: [S+str(i) for i in range(1,11) for S in "ABCD"]

rawDescription: Using a Python list comprehension a bit like a zip


code:
from __future__ import unicode_literals
from xml.etree import cElementTree as etree

tree = etree.parse('sync_list.xml')
synced = tree.find('synced')
for filename in ["file\u00b9", "file2", "file3"]:
    sfile = etree.SubElement(synced, "sfile", name="Filename")
    sfile.text = filename

tree.write('sync_list_appended.xml', encoding='utf-8', xml_declaration=True)

rawDescription: Append filename in Elementtree

description: Append filename in Elementtree


code:
import ctypes

def int32_to_uint32(i):
    return ctypes.c_uint32(i).value

rawDescription: How to convert signed 32-bit int to unsigned 32-bit int in python?

description: Convert signed 32-bit int to unsigned 32-bit int in python


code:
file.info("/etc")
##      size isdir mode               mtime               ctime
## /etc 3638  TRUE  755 2015-07-22 10:51:58 2015-07-22 10:51:58
##                    atime uid gid uname grname
## /etc 2015-08-01 08:11:43   0   0  root  wheel

file.info("/etc/hosts")
##              size isdir mode               mtime               ctime
## /etc/hosts 787448 FALSE  644 2015-07-19 17:34:59 2015-07-19 17:34:59
##                          atime uid gid uname grname
## /etc/hosts 2015-08-06 12:30:26   0   0  root  wheel

file_test("-f", "/etc/hosts") # is a file and not a dir
## [1] TRUE

file_test("-d", "/etc") # is a dir
## [1] TRUE

dir.exists("/etc") # R 3.2.0+
## [1] TRUE

file.exists("/etc/hosts")
## [1] TRUE

Sys.readlink("/etc") # will return something if it's a symbolic link
## [1] "private/etc"

Sys.readlink("/tmp")
## [1] "private/tmp"

Sys.readlink("/bin") # or "" if not
## [1] ""

rawDescription: How to check if an argument is a file or a directory in R?

description: Check if an argument is a file or a directory in R


rawDescription: Dynamically join of dictionary

description: Dynamically join of dictionary


code:
import java
sdf = java.text.SimpleDateFormat

fmt_in = sdf('d MMM yyyy HH:mm:ss Z')
fmt_out = sdf('MM/dd/yyyy HH:mm:ssaa')

fmt_out.format(fmt_in.parse(time_str))

rawDescription: jython date conversion

description: Jython date conversion


code:
class MobileAppAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(MobileAppAdmin, self).get_form(request, obj, **kwargs)
        if request.method == 'GET':
            if obj:
                form.base_fields['images'].queryset = Image.objects.filter(pk__in=obj.images.all())
            else:
                form.base_fields['images'].queryset = Image.objects.filter(pk=0)
        return form

rawDescription: Select a valid choice. XYZ is not one of the available choices


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

def get_text_positions(text, x_data, y_data, txt_width, txt_height):
    a = zip(y_data, x_data)
    text_positions = list(y_data)
    for index, (y, x) in enumerate(a):
        local_text_positions = [i for i in a if i[0] > (y - txt_height)
                            and (abs(i[1] - x) < txt_width * 2) and i != (y,x)]
        if local_text_positions:
            sorted_ltp = sorted(local_text_positions)
            if abs(sorted_ltp[0][0] - y) < txt_height: #True == collision
                differ = np.diff(sorted_ltp, axis=0)
                a[index] = (sorted_ltp[-1][0] + txt_height, a[index][1])
                text_positions[index] = sorted_ltp[-1][0] + txt_height*1.01
                for k, (j, m) in enumerate(differ):
                    #j is the vertical distance between words
                    if j > txt_height * 2: #if True then room to fit a word in
                        a[index] = (sorted_ltp[k][0] + txt_height, a[index][2])
                        text_positions[index] = sorted_ltp[k][0] + txt_height
                        break
    return text_positions

def text_plotter(text, x_data, y_data, text_positions, txt_width,txt_height):
    for z,x,y,t in zip(text, x_data, y_data, text_positions):
        plt.annotate(str(z), xy=(x-txt_width/2, t), size=12)
        if y != t:
            plt.arrow(x, t,0,y-t, color='red',alpha=0.3, width=txt_width*0.1,
                head_width=txt_width, head_length=txt_height*0.5,
                zorder=0,length_includes_head=True)

# start new plot
plt.clf()
plt.xlabel("Proportional Euclidean Distance")
plt.ylabel("Percentage Timewindows Attended")
plt.title("Test plot")

together = [(0, 1.0, 0.4), (25, 1.0127692669427917, 0.41), (50, 1.016404709797609, 0.41), (75, 1.1043426359673716, 0.42), (100, 1.1610446924342996, 0.44), (125, 1.1685687930691457, 0.43), (150, 1.3486407784550272, 0.45), (250, 1.4013999168008104, 0.45)]
together.sort()

text = [x for (x,y,z) in together]
eucs = [y for (x,y,z) in together]
covers = [z for (x,y,z) in together]

p1 = plt.plot(eucs,covers,color="black", alpha=0.5)

txt_height = 0.0037*(plt.ylim()[1] - plt.ylim()[0])
txt_width = 0.018*(plt.xlim()[1] - plt.xlim()[0])

text_positions = get_text_positions(text, eucs, covers, txt_width, txt_height)

text_plotter(text, eucs, covers, text_positions, txt_width, txt_height)

plt.savefig("test.png")
plt.show()

rawDescription: Matplotlib overlapping annotations / text


code:
    # Algorithm notes: For any real number x, define a *best upper
    # approximation* to x to be a rational number p/q such that:
    #
    #   (1) p/q >= x, and
    #   (2) if p/q > r/s >= x then s > q, for any rational r/s.
    #
    # Define *best lower approximation* similarly.  Then it can be
    # proved that a rational number is a best upper or lower
    # approximation to x if, and only if, it is a convergent or
    # semiconvergent of the (unique shortest) continued fraction
    # associated to x.
    #
    # To find a best rational approximation with denominator <= M,
    # we find the best upper and lower approximations with
    # denominator <= M and take whichever of these is closer to x.
    # In the event of a tie, the bound with smaller denominator is
    # chosen.  If both denominators are equal (which can happen
    # only when max_denominator == 1 and self is midway between
    # two integers) the lower bound---i.e., the floor of self, is
    # taken.

rawDescription: How is python's fractions.limit_denominator implemented?


code:
def allUnique(x):
    return len(x) == len(set(x))

rawDescription: Determining whether a list consist of unique elements


rawDescription: Python Selenium Webdriver - Locating Set of Elements Within Table


code: sorted(glob.glob('*.dat'), key=lambda x: int(x.split('.')[0][4:]))

rawDescription: Sort list of filenames by number

description: Sort list of filenames by number


rawDescription: How do I evaluate string lists in Python

description: Evaluate string lists in Python


code:
import msvcrt

def flush_input():
  while msvcrt.kbhit():
    msvcrt.getch()

rawDescription: Avoiding raw_input to take keys pressed while in a loop for windows


code:
import fileinput

import code
console = code.InteractiveConsole(locals())

import re
r = re.compile(r'([ ]{4}|\t)(.*)')

code = ''

for line in fileinput.input():
    match = r.match(line)
    if match:
        console.push(match.group(2))

rawDescription: Literate Python

description: Literate Python


code:
#!/usr/local/cpython-3.4/bin/python

'''Compute average of numbers in tests.txt'''

# pylint: disable=superfluous-parens
# superfluous-parens: Parentheses are good for clarity and portability

from __future__ import with_statement

def main():
    '''Main function'''
    numbers = []
    with open('tests.txt', 'r') as file_:
        for line in file_:
            fields = line.split()
            print(line.rstrip('\n'))
            subnumbers = (float(field) for field in fields)
            numbers.extend(subnumbers)
    print('The average is %s' % avg(numbers))

def avg(numbers):
    '''Compute average'''
    average = (sum(numbers)/len(numbers))
    return average

main()

rawDescription: Reading a txt file and finding the average of the numbers in python


code: datetime.datetime(year, 1, 1) + datetime.timedelta(days - 1)

rawDescription: Python Question: Year and Day of Year to date?


rawDescription: Python Repotrlab vertical bar chart spacing inconsistency


code:
import argparse

parser = argparse.ArgumentParser(description='My app description')
parser.add_argument('-i', '--input', help='Path to input file')
parser.add_argument('-o', '--output', help='Path to output file')
args = parser.parse_args()

f = open(args.input,"r")

rawDescription: How to call external input and output file names to run Python Programs at Linux Command Prompt

description: Call external input and output file names to run Python Programs at Linux Command Prompt


code:
everything.sort(key=lambda x: (
    '/'.join(x['path'].split('/')[:-1]),
    x['type'],
    ''.join(x['path'].split('/')[-1:]),
  )
)

rawDescription: python list of dictionaries sort multiple keys

description: Python list of dictionaries sort multiple keys


code:
from datetime import datetime, timedelta

def findAll(fromDate, toDate):
    fromDate = datetime.strptime(fromDate, '%Y-%m-%d')
    toDate = datetime.strptime(toDate, '%Y-%m-%d') + timedelta(days=1)
    return session.query(SomeType).filter(
        SomeType.date >= fromDate,
        SomeType.date < toDate).all()

rawDescription: How to compare dates in sqlalchemy?

description: Compare dates in sqlalchemy


code:
import pygame, os.path
from pygame.locals import *

class TranslucentSprite(pygame.sprite.Sprite):
  def __init__(self):
    pygame.sprite.Sprite.__init__(self, TranslucentSprite.container)
    self.image = pygame.image.load(os.path.join('data', 'image.bmp'))
    self.image = self.image.convert()
    self.image.set_colorkey(-1, RLEACCEL)
    self.rect = self.image.get_rect()
    self.rect.center = (320,240)

def main():
  pygame.init()
  screen = pygame.display.set_mode((640,480))
  background = pygame.Surface(screen.get_size())
  background = background.convert()
  background.fill((250,250,250))
  clock = pygame.time.Clock()
  transgroups = pygame.sprite.Group()
  TranslucentSprite.container = transgroups

  """Here's the Translucency Code"""
  transsurface = pygame.display.set_mode(screen.get_size())
  transsurface = transsurface.convert(screen)
  transsurface.fill((255,0,255))
  transsurface.set_colorkey((255,0,255))
  transsurface.set_alpha(50)

  TranslucentSprite()
  while 1:
    clock.tick(60)
    for event in pygame.event.get():
      if event.type == QUIT:
        return
      elif event.type == KEYDOWN and event.key == K_ESCAPE:
        return
    transgroups.draw(transsurface)
    screen.blit(background,(0,0))
    screen.blit(transsurface,(0,0))
    pygame.display.flip()

if __name__ == '__main__' : main()

rawDescription: How to make translucent sprites in pygame

description: Make translucent sprites in pygame


code: os.system("screencapture screen.png")

rawDescription: Take screenshot in Python on Mac OS X

description: Take screenshot in Python on Mac OS X


code:
from collections import defaultdict

out = defaultdict(lambda: 1)

for key, val in my_list:
    out[key] *= val
dotproduct = sum(out.values())

rawDescription: List of numeric pairs - need strategy to multiply and sum products


code:
import ctypes

lib = ctypes.cdll.LoadLibrary(None)
prctl = lib.prctl
prctl.restype = ctypes.c_int
prctl.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_ulong,
                  ctypes.c_ulong, ctypes.c_ulong]

def set_proctitle(new_title):
    result = prctl(15, new_title, 0, 0, 0)
    if result != 0:
        raise OSError("prctl result: %d" % result)

rawDescription: Change process name while executing a python script


code:
from numpy import cov
cov([1, 2, 3], [2, 12, 14])

rawDescription: Calculating Covariance Matrix of Two Distributions In Python


code:
def nextId_page1(self):
    if radio_button.isChecked():
        return self.currentId()+1

    return self.currentId()+2

rawDescription: PyQt: Get the id of a specific QWizard page


code:
from zipfile import ZipFile
import os

zip_file = r"c:\folder\myzip.zip"
target_folder = r"C:\Users\Fred\Desktop"

with ZipFile(zip_file, 'r') as my_zip:
    mp3_files = [name for name in my_zip.namelist() if os.path.splitext(name)[1].lower() == '.mp3']
    my_zip.extractall(target_folder, mp3_files)

rawDescription: How to extract only mp3 files from a ZIP archive

description: Extract only mp3 files from a ZIP archive


code:
# get difference in x- and y- direction
sec_grad_x = np.diff(storm,n=1,axis=0)
sec_grad_y = np.diff(storm,n=1,axis=1)

cp = []
# starts from 1 because diff function gives a forward difference
for i in range(1,n-1):
    for j in range(1,n-1):
        # check when the difference changes its sign
        if ((sec_grad_x[i-1,j]<0) != (sec_grad_x[i-1+1,j]<0)) and \
           ((sec_grad_y[i,j-1]<0) != (sec_grad_y[i,j-1+1]<0)):
            cp.append([i,j,  storm[i,j]])

cp = np.array(cp)

rawDescription: How can I find the critical points of a 2D array in python?

description: Find the critical points of a 2D array in python


code:
import sys
import os

old_sys_path = list(sys.path)

virtualenv_path = "/path/to/venv"
activate_this_path = os.path.join(virtualenv_path, "bin", "activate_this.py")

execfile(activate_this_path, dict(__file__=activate_this_path))

# get my module here

# restore sys.path
sys.path = old_sys_path

rawDescription: How to find a module in a virtualenv without activating said virtualenv?

description: Find a module in a virtualenv without activating said virtualenv


code:
data = "Product Version: 0.0.1 | Launch Switch: hello | Product Version: 2.3.4 | Launch Switch: world"
re.findall("Product Version: ([0-9.]+).*?Launch Switch: (\w+)", data)

rawDescription: Can I use multiple search criteria in one python regex query to return a tuple?

description: Use multiple search criteria in one python regex query to return a tuple


code:
t = SortedSet([(1, 3), (2, 4), (-2, 9)], updator = OverlappingIntervalsUpdator)
print(t.overlap_point(-5))
print(t.overlap_point(5))
print(t.overlap_point(3.5))
print(t.overlap((-10, 10)))

rawDescription: Optimized approach to finding which pairs of numbers another number falls between?


code:
with open("StaffData.txt", "wt") as file:
    for contacts in staffList :
       file.write("\n".join(str(contacts).split(' - ')) + "\n")

rawDescription: Python 3.3 Writing A String From A List To A txt File


code:
import ftplib
ftp = ftplib.FTP('ftp.some.site', user = 'username', passwd = 'password_for_username')

for key in key_filings:
    for filing in key_filings[key]:
        remote_directory = '/foo/bar/' + key + '/' + filing['key_number']
        ftp.cwd(remote_directory)
        text_file = filing['txt']
        save_text_ref = open(save_dir + text_file, 'w')
        ftp.retrlines('RETR '+ text_file, lambda s, w = save_text_ref.write: w(s+'\n'))
        save_text_ref.close()
        hdr_file = filing['hdr']
        save_hdr_ref = open(save_dir +hdr_file,'w')
        ftp.retrlines('RETR ' + hdr_file, lambda s, w = save_hdr_ref.write: w(s+'\n'))
        save_hdr_ref.close()

rawDescription: How to correctly download files using ftplib so line breaks are added for windows

description: Correctly download files using ftplib so line breaks are added for windows


code:
def clean_are_you_cool(self):
    if self.cleaned_data.get('are_you_cool', None) == 'Yes':
        if self.cleaned_data.get('how_cool', None) is not None:
           #  Actions for cool user.
           pass
    #  Or if user not cool.

rawDescription: Django Form Wizard with Conditional Questions


code: values[1] = values[:]

rawDescription: infinite assignment in python list?

description: Infinite assignment in python list


code:
# root.update()  # not required
root.deiconify()

rawDescription: How to show a window that was hidden using "withdraw" method?

description: Show a window that was hidden using "withdraw" method


code: challenge = re.search(r"challenge *: *'(\S+)'", x).group(1)

rawDescription: How do I extract a long string of text from some JavaScript on a web page using BeautifulSoup?

description: Extract a long string of text from some JavaScript on a web page using BeautifulSoup


code:
import numpy as np
import matplotlib.pylab as pl

x = np.arange(100)
y = np.random.randint(1270000-10, 1270000+10, x.size)

pl.figure()
pl.subplot(121)
pl.plot(x,y)
pl.ylim(y.min()-1, y.max()+1)

pl.subplot(122)
pl.plot(x,y)
pl.ylim(y.min()-1, y.max()+1)
ax=pl.gca()
ax.get_yaxis().get_major_formatter().set_useOffset(False)

rawDescription: How matplotlib show obvious changes?

description: How matplotlib show obvious changes


code:
class App(Frame):
    def __init__(self, master):
        self.matrix = Grid(self, 10, 10)
        self.label = Label(self, text="Hello")
        self.matrix.grid(row=0, column=0, sticky="nsew")

        self.label.grid(row=0, column=1, sticky="nsew")
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

rawDescription: Label and buttons overlapping when using different classes, tkinter


code:
def update(cursor, columns, values):
    for value in values:
        sql = "UPDATE myTable SET {} WHERE ssn = ?".format(
            ", ".join(map("{} = ?".format, columns)))
        print(sql)
        cursor.execute(sql, values)

columns = ['Name', 'Age']
values  = [['Jon', 12, '545-45-7987'], ['Sam', 13, '454-78-4545']]
cursor = conn.cursor()
update(cursor, columns, values)

rawDescription: Updating multiple SQLite rows given columns and data


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

np.random.seed(0)
n = 2000
x = np.random.standard_normal(n)
y = 2.0 + 3.0 * x + 4.0 * np.random.standard_normal(n)

cmap = colors.ListedColormap(['white', 'yellow', 'orange'])
hb = plt.hexbin(x,y, bins='log', cmap=cmap, gridsize=20, edgecolor='gray')
plt.axis([-2, 2, -12, 12])
plt.title("sunflower plot")

counts = hb.get_array()
coords = hb.get_offsets()

for i, count in enumerate(counts):
    x, y = coords[i,:]
    count = int(10**count)
    if count>3 and count<=12:
        n = count // 1
        if n>1:
            plt.plot([x], [y], 'k.')
            plt.plot([x], [y], marker=(n, 2), color='k', markersize=18)
    if count>12:
        n = count // 5
        if n>1:
            plt.plot([x], [y], 'k.')
            plt.plot([x], [y], marker=(n, 2), color='k', markersize=18)

plt.show()

rawDescription: sunflower scatter plot using matplotlib

description: Sunflower scatter plot using matplotlib


code:
import xlrd

wb = xlrd.open_workbook(path)
sheet = wb.sheet_by_index(index)

column_list = range(0, sheet.ncols)

val_name = [sheet.cell_value(rowx=0, colx=i) for i in column_list]
channel = val_name.pop(0)
condition = val_name.pop(0)

print(channel, condition, "Value *", "Status")
lines = []
for r in range(1, sheet.nrows):
    row = [sheet.cell_value(rowx=r, colx=i) for i in column_list]
    channel = row[0]
    condition = row[1]
    values = row[2:]

    lines = zip( [channel]*len(values),
                 [condition]*len(values),
                 val_name,
                 values)
    for l in lines:
        print(l)

rawDescription: Excel (CSV) - transform header data to rows mapping with repeating rows


code:
import random, string
import wx

from wx.lib.pubsub import Publisher

class Frame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, size=(300, 300))
        self.CreateStatusBar(style=0)
        self.notebook = wx.Notebook(self)
        btn = wx.Button(self, label="add page")
        btn.Bind(wx.EVT_BUTTON, lambda evt: self.create_page(random.choice(string.letters)))

        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(btn, 0)
        box.Add(self.notebook, 1, wx.EXPAND)
        self.SetSizer(box)

        Publisher().subscribe(self.change_statusbar, 'change_statusbar')
        self.create_page("1")
        self.create_page("2")
        self.Layout()

    def create_page(self, text):
        self.notebook.AddPage(Page(self.notebook, text), text)

    def change_statusbar(self, msg):
        self.SetStatusText(msg.data)

class Page(wx.Panel):
    def __init__(self, parent, text):
        wx.Panel.__init__(self, parent)
        Publisher().sendMessage(('change_statusbar'), text)

app = wx.App(redirect=False)
top = Frame()
top.Show()
app.MainLoop()

rawDescription: wxPython: How to reference the frame's status bar from individual notebook panels?

description: WxPython: How to reference the frame's status bar from individual notebook panels


code:
from StringIO import StringIO
import csv

import web

urls = (
  '/retrieve',   'Retrieve',
)

app = web.application(urls, globals())
conn = mdb.connect(user='root', passwd='redhat', db='Merion_dev', host='localhost')

class Retrieve:

    def POST(self):
        cursor = conn.cursor()
        query = "SELECT * FROM adm_facility LIMIT 0,10 "
        cursor.execute(query)
        result = cursor.fetchall()
        csv_file = StringIO()
        csv_writer = csv.writer(csv_file)
        csv_writer.writerow(['Facility_id', 'Name', 'Account Number', 'Street'])
        for i in result :
            csv_writer.writerow([i[0],i[2],i[3],i[4]])
        web.header('Content-Type','text/csv')
        web.header('Content-disposition', 'attachment; filename=yourfilename.csv')
        return csv_file.getvalue()

if __name__ == "__main__":
    web.internalerror = web.debugerror
    app.run()

rawDescription: How to downlaod a csv file after writing data to it using python

description: Downlaod a csv file after writing data to it using python


code:
from itertools import groupby
s = 'aaabbccccabbb'
[''.join(y) for _,y in groupby(s)]

rawDescription: Split string into strings of repeating elements


code:
class MyObject(object):

    def __init__(self):
        self.output = []   # empty list

    def bold(self, userinput):
        self.output.append("<B>" + userinput + "</B>")

    def save(self, filename):
        with open(filename, "w") as outfile:
            # write items separated by line breaks
            outfile.write("\n".join(self.output))

rawDescription: Member Variables in Python?

description: Member Variables in Python


code:
from flask import current_app, abort

def check_inserted(documents):
    # get ID for current user
    user_id = current_app.auth.get_request_auth_value()
    # find tests for the current user
    collection = current_app.data.driver.db['tests']
    tests = collection.find({'user_id': user_id})

    if tests.count() > 0:
        abort(409, 'Test already present for this account. Only one allowed.')

rawDescription: Python eve - User-Restricted Resource Access feature with item's ID_FIELD as AUTH_FIELD


code:
subArray = []
newRow = []
for row in data:
    for i in xrange(0,len(row)):
        if (i % 3 == 0):
            continue
        newRow.append(row[i])
    subArray.append(newRow)
    newRow = []

rawDescription: Python creating a smaller sub-array from a larger 2D NumPy array?


code:
@freezegun.freeze_time('2015-9-21')
def test():
    assert ModelClass.create(...) == ModelClass(...)

rawDescription: How to mock _auto_now?

description: Mock _auto_now


code:
subject = "Some subject "+str(abc)
content = "Some content"
ml = subprocess.Popen('echo "{content}" | mutt -a "file_to_attach.log" -s "{subject}" -- myemailid@somedomain.in'.format(content=content, subject=subject), shell=True)
ml.communicate()

rawDescription: string variable values not showing in subprocess.Popen in python

description: String variable values not showing in subprocess.Popen in python


code:
from BeautifulSoup import BeautifulSoup

with open('Path/to/file', 'r') as content_file:
    content = content_file.read()

soup = BeautifulSoup(content)
[div.extract() for div in soup.findAll('div')]

with open('Path/to/file.modified', 'w') as output_file:
    output_file.write(str(soup))

rawDescription: Removing all div tags from HTML string

description: Removing all div tags from HTML string


code:
def foo():
    x = []
    def bar():
        y = input()
        x.append(y)
        return x
    return bar

b = foo()

# usage
In [8]: b()
aaa
Out[8]: ['aaa']

In [9]: b()
bbb
Out[9]: ['aaa', 'bbb']

In [10]: b()
ccc
Out[10]: ['aaa', 'bbb', 'ccc']

rawDescription: Python-Updating an Array Permanently After Calling it in a Function


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import from_levels_and_colors

nvals = np.random.randint(2, 20)
data = np.random.randint(0, nvals, (10, 10))

colors = np.random.random((nvals, 3))
# Make the colors pastels...
colors = colors / 2.5 + 0.55

levels = np.arange(nvals + 1) - 0.5
cmap, norm = from_levels_and_colors(levels, colors)

fig, ax = plt.subplots()
im = ax.imshow(data, interpolation='nearest', cmap=cmap, norm=norm)
fig.colorbar(im, ticks=np.arange(nvals))
plt.show()

rawDescription: How to define a colormap that only has one color

description: Define a colormap that only has one color


code:
class AutoJSONEncoder(JSONEncoder):
    def default(self, obj):
        try:
            return obj._json()
        except AttributeError:
            return JSONEncoder.default(self, obj)

rawDescription: Method to serialize custom object to JSON in Python


code: int_ts = int((datetime.datetime.strptime(extracted_ts, "%Y%m%d-%H%M") - datetime.datetime(1970,1,1)).total_seconds()) * 1000

rawDescription: Timestamp value behind by 4 hours

description: Timestamp value behind by 4 hours


rawDescription: How can I find all points of a given triangle for a refined triangulation in matplotlib?

description: Find all points of a given triangle for a refined triangulation in matplotlib


code:
dd = dd.str.split("::").str[0]

dd.apply(lambda x: sum(map(int, x.split(','))))

rawDescription: Pandas parse integers separated by commas and colons in a series


code:
import math

def binomial_cooefficient(n: int, k: int) -> int:
    n_fac = math.factorial(n)
    k_fac = math.factorial(k)
    n_minus_k_fac = math.factorial(n - k)
    return n_fac/(k_fac*n_minus_k_fac)

rawDescription: Get a number of possible combinations Python


code:
def count(s):
    if not s:
        return (0, 0)
    else:
        next_count = count(s[1:])
        return ((s[0] == 'h') + next_count[0],
                (s[0] == 'e') + next_count[1])

count("hello how are you here") # => (3, 4)

rawDescription: Count 2 (or more) characters recursively in string; return in (x,y) format in Python


code:
import pickle
class Foo(object): pass

a = Foo()
with open('data.pickle','wb') as f:
    pickle.dump(a,f)

rawDescription: Is there a way to view cPickle or Pickle file contents without loading Python in Windows?


code:
test_options = (random_aoi, random_read_mode)

def random_test(test_options, control_obj):
    ran_test_opt = choice(test_options)
    ran_test_opt(control_obj) # call the randomly selected function

rawDescription: Randomly select functions

description: Randomly select functions


code:
if request.method == 'POST' and request.is_ajax():
        if request.user.is_authenticated(): # note the ()
            result = True

rawDescription: how to determine the status of the user?

description: Determine the status of the user


rawDescription: Python regex with unicode characters bug?


code: df['num_choices'] = np.array([len(row) for row in df.options])

rawDescription: Using NumPy Vectorization to Create Column Containing Length of Another Column


code:
import xlwt

def output(filename, sheet, list1, list2, x, y, z):
    book = xlwt.Workbook()
    sh = book.add_sheet(sheet)

    variables = [x, y, z]
    x_desc = 'Display'
    y_desc = 'Dominance'
    z_desc = 'Test'
    desc = [x_desc, y_desc, z_desc]

    col1_name = 'Stimulus Time'
    col2_name = 'Reaction Time'

    #You may need to group the variables together
    #for n, (v_desc, v) in enumerate(zip(desc, variables)):
    for n, v_desc, v in enumerate(zip(desc, variables)):
        sh.write(n, 0, v_desc)
        sh.write(n, 1, v)

    n+=1

    sh.write(n, 0, col1_name)
    sh.write(n, 1, col2_name)

    for m, e1 in enumerate(list1, n+1):
        sh.write(m, 0, e1)

    for m, e2 in enumerate(list2, n+1):
        sh.write(m, 1, e2)

    book.save(filename)

rawDescription: Python - Write to Excel Spreadsheet

description: Python - Write to Excel Spreadsheet


code:
arr = np.arange(9).reshape(3,3)
arr
arr.sum(axis=1)
dict(enumerate(arr.sum(axis=1)))

rawDescription: Creating dictionary from numpy array

description: Creating dictionary from numpy array


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

import re
RE_TXT = re.compile(r'\|\s*X:(\S+)\s*\|\s*N\D*(\d+):\s*(.*)$')
txt = '|              |   | X:720                      | N°227: Done'
rx = RE_TXT.search(txt)
if rx:
    print(rx.group(1))
    print(rx.group(2))
    print(rx.group(3))

print('-' * 20)

# other way without regex, but with more complicated logic:
arr = [s.strip() for s in txt.split('|')]
if arr[3].startswith('X:'):
    print(arr[3].split(':')[1])
    N, state = arr[4].split(':')
    N = N[3:]
    state = state.strip()
    print(N)
    print(state)

rawDescription: Regex to find out fields which are having non ascii character in python


code:
...
ax2 = ax1.twiny()
a,b = 0,25000
ax1.set_ylim(a,b)
ax2.set_ylim(a,b)

rawDescription: two y axis with same scale

description: Two y axis with same scale


code:
def refresh():
    line = get_next_line()
    line = line.split('|')
    B_loc = line[0].split(':')[1].split(',')
    ...

    # call this function again in 20ms
    root.after(20, refresh)

rawDescription: Python Tkinter coords function not moving canvas objects inside loop


code:
import sys
sys.path.append("../a")
import main, second

rawDescription: importing from subdirectories in Python

description: Importing from subdirectories in Python


code:
import time
time.ctime(time.time())
time.strptime(time.ctime(time.time()))
time.strptime(time.asctime())

rawDescription: what is the inverse of time.asctime in Python

description: What is the inverse of time.asctime in Python


code:
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))

rawDescription: How to tell which Python env is faster

description: Tell which Python env is faster


code:
import sys
import wx
import wx.lib.mixins.listctrl  as  listmix

import win32api
import win32gui
import win32con
import win32gui_struct
import commctrl
import ctypes
from ctypes.wintypes import BOOL, HWND, RECT, UINT, DWORD, HDC, DWORD, LPARAM, COLORREF

LVM_FIRST = 0x1000
LVM_GETSUBITEMRECT=(LVM_FIRST + 56)
LVIR_BOUNDS             =0
LVIR_ICON               =1
LVIR_LABEL              =2
LVIR_SELECTBOUNDS       =3
DEFAULT_GUI_FONT    =17

#LPNMHDR
class NMHDR(ctypes.Structure):
    pass
INT = ctypes.c_int
NMHDR._fields_ = [('hwndFrom', HWND), ('idFrom', UINT), ('code', INT)]
LPNMHDR = ctypes.POINTER(NMHDR)

#LPNMCUSTOMDRAW
class NMCUSTOMDRAW(ctypes.Structure):
    pass
NMCUSTOMDRAW._fields_ = [('hdr', NMHDR), ('dwDrawStage', DWORD), ('hdc', ctypes.c_int),
                         ('rc', RECT), ('dwItemSpec', DWORD), ('uItemState', UINT),
                         ('lItemlParam', LPARAM)]
LPNMCUSTOMDRAW = ctypes.POINTER(NMCUSTOMDRAW)

#LPNMLVCUSTOMDRAW
class NMLVCUSTOMDRAW(ctypes.Structure):
    pass
NMLVCUSTOMDRAW._fields_ = [('nmcd', NMCUSTOMDRAW),
                           ('clrText', COLORREF),
                           ('clrTextBk', COLORREF),
                           ('iSubItem', ctypes.c_int),
                           ('dwItemType', DWORD),
                           ('clrFace', COLORREF),
                           ('iIconEffect', ctypes.c_int),
                           ('iIconPhase', ctypes.c_int),
                           ('iPartId', ctypes.c_int),
                           ('iStateId', ctypes.c_int),
                           ('rcText', RECT),
                           ('uAlign', UINT)
                           ]
LPNMLVCUSTOMDRAW = ctypes.POINTER(NMLVCUSTOMDRAW)

musicdata = {
1 : ("Bad English", "The Price Of Love", "Rock"),
2 : ("DNA featuring Suzanne Vega", "Tom's Diner", "Rock"),
3 : ("George Michael", "Praying For Time", "Rock"),
4 : ("Gloria Estefan", "Here We Are", "Rock"),
5 : ("Linda Ronstadt", "Don't Know Much", "Rock"),
6 : ("Michael Bolton", "How Am I Supposed To Live Without You", "Blues"),
7 : ("Paul Young", "Oh Girl", "Rock"),
8 : ("Paula Abdul", "Opposites Attract", "Rock"),
9 : ("Richard Marx", "Should've Known Better", "Rock"),
10 : ("Bobby Brown", "My Prerogative", "RnB"),
}

class MyListCtrl(wx.ListCtrl, listmix.ListCtrlAutoWidthMixin):
    def __init__(self, parent, ID, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0):
        wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
        listmix.ListCtrlAutoWidthMixin.__init__(self)

    def ShouldCustomDraw(self, row):
        if self.IsSelected(row):
            listitem = self.GetItem(row, 2)
            genre = listitem.GetText()

            return genre != "Rock"

    def CustomDraw(self, lpcd):
        if lpcd.contents.nmcd.dwDrawStage == commctrl.CDDS_PREPAINT:
            return (True, commctrl.CDRF_NOTIFYITEMDRAW)

        if lpcd.contents.nmcd.dwDrawStage == commctrl.CDDS_ITEMPREPAINT:
            if self.ShouldCustomDraw(lpcd.contents.nmcd.dwItemSpec):
                #do custom drawing for non Rock selected rows
                #paint the selection background
                color = win32api.RGB(255, 127, 0) #orange
                brush = win32gui.CreateSolidBrush(color)
                r = lpcd.contents.nmcd.rc
                win32gui.FillRect(int(lpcd.contents.nmcd.hdc),  (r.left+4, r.top, r.right, r.bottom), brush)
                win32gui.DeleteObject(brush)
                return (True, commctrl.CDRF_NOTIFYSUBITEMDRAW)

        if lpcd.contents.nmcd.dwDrawStage == commctrl.CDDS_ITEMPREPAINT|commctrl.CDDS_SUBITEM:
            row = lpcd.contents.nmcd.dwItemSpec
            col = lpcd.contents.iSubItem
            item = self.GetItem(row, col)
            text = item.GetText()
            #paint the text
            rc = RECT()
            rc.top = col
            if col > 0:
                rc.left = LVIR_BOUNDS
            else:
                rc.left = LVIR_LABEL
            success = win32api.SendMessage(self.Handle, LVM_GETSUBITEMRECT, row, ctypes.addressof(rc))
            if col > 0:
                rc.left += 5
            else:
                rc.left += 2
            rc.top += 2

            if success:
                oldColor = win32gui.SetTextColor(lpcd.contents.nmcd.hdc, win32gui.GetSysColor(win32con.COLOR_HIGHLIGHTTEXT))
                win32gui.DrawText(lpcd.contents.nmcd.hdc, text, len(text), (rc.left, rc.top, rc.right, rc.bottom), win32con.DT_LEFT|win32con.DT_VCENTER)
                win32gui.SetTextColor(lpcd.contents.nmcd.hdc, oldColor)

            return (True, commctrl.CDRF_SKIPDEFAULT)

        # don't need custom drawing
        return (True, commctrl.CDRF_DODEFAULT)

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)
        self._sizer = wx.BoxSizer(wx.VERTICAL)
        tID = wx.NewId()
        self._ctl = MyListCtrl(self, tID,
                                 style=wx.LC_REPORT
                                 #| wx.BORDER_SUNKEN
                                 | wx.BORDER_NONE
                                 | wx.LC_EDIT_LABELS
                                 | wx.LC_SORT_ASCENDING
                                 #| wx.LC_NO_HEADER
                                 #| wx.LC_VRULES
                                 #| wx.LC_HRULES
                                 #| wx.LC_SINGLE_SEL
                                 )
        self._sizer.Add(self._ctl, 1, wx.EXPAND, 3)
        self.PopulateList()

        self.oldWndProc = win32gui.SetWindowLong(self.GetHandle(), win32con.GWL_WNDPROC, self.MyWndProc)

    def MyWndProc(self, hWnd, msg, wParam, lParam):

        if msg == win32con.WM_NOTIFY:
            hwndFrom, idFrom, code = win32gui_struct.UnpackWMNOTIFY(lParam)
            if code == commctrl.NM_CUSTOMDRAW and hwndFrom == self._ctl.Handle:
                lpcd = ctypes.cast(lParam, LPNMLVCUSTOMDRAW)
                retProc, retCode = self._ctl.CustomDraw(lpcd)

                if retProc:
                    return retCode

        # Restore the old WndProc.  Notice the use of wxin32api
        # instead of win32gui here.  This is to avoid an error due to
        # not passing a callable object.
        if msg == win32con.WM_DESTROY:
            win32api.SetWindowLong(self.GetHandle(),
                              win32con.GWL_WNDPROC,
                              self.oldWndProc)

        # Pass all messages (in this case, yours may be different) on
        # to the original WndProc
        return win32gui.CallWindowProc(self.oldWndProc,
                                  hWnd, msg, wParam, lParam)

    def PopulateList(self):
        self._ctl.InsertColumn(0, "Artist")
        self._ctl.InsertColumn(1, "Title")
        self._ctl.InsertColumn(2, "Genre")

        items = musicdata.items()

        for key, data in items:
            index = self._ctl.InsertStringItem(sys.maxint, data[0])
            self._ctl.SetStringItem(index, 1, data[1])
            self._ctl.SetStringItem(index, 2, data[2])
            self._ctl.SetItemData(index, key)

        self._ctl.SetColumnWidth(0, wx.LIST_AUTOSIZE)
        self._ctl.SetColumnWidth(1, wx.LIST_AUTOSIZE)
        self._ctl.SetColumnWidth(2, 100)

        self.currentItem = 0

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'wxListCtrl StackOverflow')
        frame.Show()
        self.SetTopWindow(frame)
        return 1

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

rawDescription: wxPython wxListCtrl selected row color

description: WxPython wxListCtrl selected row color


code:
import md5

contest = "some data"
m = md5.new(contents)
m.digest()

rawDescription: Content-Seen check in Python

description: Content-Seen check in Python


code:
path = r'c:\xxx\abc\xyz\fileName.jpg'
import os
os.path.dirname(path)
os.path.basename(os.path.dirname(path))

rawDescription: How do I get a file's parent directory?

description: Get a file's parent directory


code:
from mapreduce import control

mapreduce_id = control.start_map(
    "My Mapper",
    "main.my_mapper",
    "mapreduce.input_readers.DatastoreInputReader",
    {"entity_kind": "models.MyEntity"},
    shard_count=10)

rawDescription: How to start mapreduce job from cron on GAE Python

description: Start mapreduce job from cron on GAE Python


code:
import urllib
import urllib2
import cookielib

login = 'user@host.com'
password = 'secret'

cookiejar = cookielib.CookieJar()
urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))

# adjust this to match the form's field names
values = {'username': login, 'password': password}
data = urllib.urlencode(values)
request = urllib2.Request('http://target.of.POST-method', data)
url = urlOpener.open(request)
# from now on, we're authenticated and we can access the rest of the site
url = urlOpener.open('http://rest.of.user.area')

rawDescription: Link Checker (Spider Crawler)

description: Link Checker (Spider Crawler)


code:
import urllib
import urllib2
import simplejson

url = 'http://en.wikipedia.org/w/api.php'
values = {'action' : 'query',
          'prop' : 'revisions',
          'titles' : 'Jennifer_Aniston',
          'rvprop' : 'content',
          'format' : 'json'}

data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
json = response.read()

rawDescription: Query Wikipedia data page

description: Query Wikipedia data page


code:
def proxy_url(url):
        return "http://localhost:8050/render.html?url=%s&timeout=15&wait=1" % url

def process_links(self,links):
        for link in links:
            link.url = proxy_url(link.url)
        return links

rawDescription: How to integrate javascript rendering module to scrapy?

description: Integrate javascript rendering module to scrapy


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

with open('thisone.txt') as file:
    array2d = [[int(digit) for digit in line.split()] for line in file]

with plt.style.context('fivethirtyeight'):
    for row in array2d:
        plt.plot(xrange(len(row)), row)

plt.show()

rawDescription: How do I plot a 2D array graph in Python using matplotlib

description: Plot a 2D array graph in Python using matplotlib


code:
PyLibMCTagsCache = type("PyLibMCTagsCache",
                        (BaseTagsMemcachedCache,),
                        vars(PyLibMCCache))

rawDescription: Is it possible in Python to create a class which duplicates the functionality of some class, but changes it's base class?


code:
from guardian.mixins import PermissionRequiredMixin
from guardian.utils import get_anonymous_user

class PermissionRequiredMixinWithAnonymous(PermissionRequiredMixin):
    def check_permissions(self, request):
        forbidden = super(PermissionRequiredMixinWithAnonymous, self).check_permissions(request)
        if forbidden:
            perms = self.get_required_permissions(request)
            anon = get_anonymous_user()
            obj = self.get_permission_object()
            has_permissions = all(anon.has_perm(perm, obj) for perm in perms)
            if has_permissions:
                forbidden = None
        return forbidden

rawDescription: Django guardian: How to give all users the permissions of the anonymous user


code:
import select

def client():
    sockets, _, _ = select.select([h, y], [], [])
    # If h or y has data, select exits and returns these sockets

    for sock in sockets:
        try:
            data = sock.recv(1024)
            if data == '':
                # sock was disconnected handle that
                continue

            # Process data here
        except Exception:
            continue

rawDescription: Check if there is a message received or skip it (python 3.4)


code:
def f(x=list):
    if isinstance(x, type): x = x()
    print(id(x))

rawDescription: Default parameter value for objects

description: Default parameter value for objects


code:
import csv

c1 = []
c2 = []
c3 = []
with open('Half-life.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        c1.append(row[0])
        c2.append(row[1])
        c3.append(row[2])

rawDescription: Python - splitting data as columns in csv file


code:
# At the beginning of the notebook
import logging
logger = logging.getLogger()
assert len(logger.handlers) == 1
handler = logger.handlers[0]
handler.setLevel(logging.INFO)

rawDescription: Change level logged to IPython/Jupyter notebook


code: dir(x)

rawDescription: Python get arguments for partial functions


code:
import itertools

def intermix(*containers):
    mix = []
    for c in sorted(containers, key=lambda c: len(c)):
        if len(c) >= len(mix):
            bigger, smaller = c, mix
        else:
            bigger, smaller = mix, c
        ratio, remainder = divmod(len(bigger), len(smaller) + 1)
        chunk_sizes = (ratio + (1 if i < remainder else 0) for i in range(len(smaller) + 1))
        chunk_offsets = itertools.accumulate(chunk_sizes)
        off_start = 0
        new_mix = []
        for i, off in enumerate(chunk_offsets):
            new_mix.extend(bigger[off_start:off])
            if i == len(smaller):
                break
            new_mix.append(smaller[i])
            off_start = off
        mix = new_mix
    return mix

rawDescription: Evenly intermix two lists of elements (load balance)


code:
import subprocess
process = subprocess.Popen(['python', 'your_script_name.py'])
process.wait() # If you want to stop caller until callee terminates

rawDescription: Scipy in Abaqus

description: Scipy in Abaqus


code:
li = [0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 3, 4, 4, 4]

from collections import Counter

result = []
last = 0

for k,v in sorted(Counter(li).items()):
    result.append(list(range(last, last + v)))
    last += v

rawDescription: Making a list of indexes into a list of lists


code:
xyloop2 = np.empty((ndata, kdata, 3, 3))

for i in xrange(ndata):
    xyloop2[i] = np.sum(x[i,:,:,:,None] * y[i,:,None,:,:], axis=-2)

rawDescription: Python Big Data Matrix manipulation

description: Python Big Data Matrix manipulation


code:
def inplace_unique_latest(L, key=None):
  if key is None:
    def key(x):
      return x
  seen = set()
  n = iter(xrange(len(L) - 1, -2, -1))
  for x in xrange(len(L) - 1, -1, -1):
    item = L[x]
    k = key(item)
    if k not in seen:
      seen.add(k)
      L[next(n)] = item
  L[:next(n) + 1] = []

rawDescription: Most efficient way to remove duplicates from Python list while preserving order and removing the oldest element


code:
def create_action(*args, **kwargs):
    action = Action(*args, **kwargs)

rawDescription: What's a more pythonic way to write this function declaration


code:
N1=4
list1 = []
list1 = [5]*5
list2 = [list1[:]]*N1
list3=[]
list3.append(list2)
list3
N2 = 2
list1 = [2]*5
list2 = [list1[:]]*N2
list3.append(list2)
list3

rawDescription: Python append arrays of different dimensions


code:
import pandas as pd
import numpy as np
# from pattern.db import date
import matplotlib.pyplot as plt

l = [dict(date=pd.to_datetime('2015-01-02'), one=0.1, two=0.2)]
l.append(dict(date=pd.to_datetime('2014-01-01'), one=0.2, two=0.5))
l.append(dict(date=pd.to_datetime('2014-02-01'), one=0.5, two=0.6))
l.append(dict(date=pd.to_datetime('2014-03-01'), one=0.1, two=0.7))

d1 = pd.DataFrame(l)
for i in range(100):
    d1['s%i'%i] = np.random.uniform(0,.5,4)
for i in range(10):
    d1['s%i'%i] = np.random.uniform(0,.7,4)

d2 = d1.set_index('date')

plt.style.use("ggplot")

fig = plt.figure(figsize=(10,6))

for i in d1.columns:
    if i=='date':
        continue
    if d1[i].max() >= 0.6:
        plt.plot(d1.index, d1[i], lw=2, label="monthly average " + i)
        plt.hold(True)
    else:
        plt.plot(d1.index, d1[i], lw=2, alpha=0.7, linewidth=0.3)
        plt.hold(True)

plt.ylim(0,1)
plt.legend(prop={'size':10})
plt.title("Occurence of various words in Naoki's blog")
plt.xlabel("Post publication date")
plt.ylabel("Term Frequency")
plt.show()

rawDescription: term frequency over time: how to plot +200 graphs in one plot with Python/pandas/matplotlib?

description: Term frequency over time: how to plot +200 graphs in one plot with Python/pandas/matplotlib


code: sorted(a) == sorted(b)

rawDescription: How can I compare two lists in python, and return that the second need to have the same values regardless of order?

description: Compare two lists in python, and return that the second need to have the same values regardless of order


code:
@app.after_request
def add_ua_compat(response):
    response.headers['X-UA-Compatible'] = 'IE=Edge'
    return response

rawDescription: How to apply decorator to every Flask view

description: Apply decorator to every Flask view


code:
from google.appengine.api import oauth

user = oauth.get_current_user()

rawDescription: How to use Google Users API with Google App Engine and Android

description: Use Google Users API with Google App Engine and Android


code:
from IPython.display import display
from ipywidgets import widgets
button1 = widgets.Button(description = 'Button1')
button2 = widgets.Button(description = 'Button2')
display(widgets.HBox((button1, button2)))

rawDescription: How to align widget buttons in IPython notebook

description: Align widget buttons in IPython notebook


code:
import numpy as np
import matplotlib.pyplot as plt
# create some data
data = np.random.rand(6,10)
fig, ax = plt.subplots(3,2)
ax = ax.reshape(6)
for ind, d in enumerate(data):
  ax[ind].hist(d)
fig.tight_layout()
plt.show()

rawDescription: Placing Multiple Histograms in Figure with PyLab


code:
from PyQt4 import QtCore, QtGui

import sys

app = QtGui.QApplication(sys.argv)

def filterUpdate():
    print('!')

filter = QtGui.QInputDialog()
filter.setInputMode (filter.TextInput)
filter.setOption(filter.NoButtons, True)
filter.setLabelText("Filter")
filter.textValueChanged.connect(filterUpdate)

filter.show()

sys.exit(app.exec_())

rawDescription: PyQt4 connect to signal "textValueChanged()"


code:
def find_any(what, where):
    for that in what:
       if that in where:
           return True
    return False

file = ['Tool','Cool','Pool']
word = 'Cool'
guesses = ['T','P']
for i in range(len(file)):
    if len(file[i]) == len(word) and find_any(guesses, file[i]):
        continue # This will skip to the next file
    # Do things with file[i] here

rawDescription: How to change iterations in a for loop?

description: Change iterations in a for loop


code:
def findSimilar(imagesdata):
    limg = imagesdata.pop()
    global img1  # making img1 accessible to getssim, a bad idea!
    img1 = limg[0][1]
    p = multiprocessing.Pool(maxtasksperchild=2)
    imagesdata = p.map(getssim, imagesdata)
    p.close()
    p.join()
    imagesdata.sort(key=operator.itemgetter(1))
    return limg[0][0]  #return name of image

rawDescription: Correcting use of pool on python iterable


code: db(db.auth_user.id == auth.user_id).update(score=float(balance) - float(cost))

rawDescription: Updating web2py auth_user custom fields programmatically


type: array

rawDescription: JSONSchema Resource that hints at its schema


code:
import os
with open('infile.txt') as f_in, open('outfile.txt', 'w') as f_out:
  f_out.write(f_in.read().replace('ROW_DEL ', os.linesep))

rawDescription: read a very big single line txt file and split it

description: Read a very big single line txt file and split it


code:
test_list_2 = [[1,2,3,4,5,6], 0, [7,8,9,10], [11,12,13,14]]
def lift_int(v):
    if not isinstance(v, list):
        return [v]
    else:
        return v

test_list_2 = [item for sublist in test_list_2 for item in lift_int(sublist)]
test_list_2

rawDescription: List of lists and integers into list

description: List of lists and integers into list


code:
import sys
from os.path import expanduser, join

pyw_executable = join(sys.prefix, "pythonw.exe")
shortcut_filename = "L-System Toolsss.lnk"
working_dir = expanduser(join('~','lsf_files'))
script_path = join(sys.prefix, "Scripts", "tklsystem-script.py")

if sys.argv[1] == '-install':
    # Log output to a file (for test)
    f = open(r"C:\test.txt",'w')
    print('Creating Shortcut', file=f)

    # Get paths to the desktop and start menu
    desktop_path = get_special_folder_path("CSIDL_COMMON_DESKTOPDIRECTORY")
    startmenu_path = get_special_folder_path("CSIDL_COMMON_STARTMENU")

    # Create shortcuts.
    for path in [desktop_path, startmenu_path]:
        create_shortcut(pyw_executable,
                    "A program to work with L-System Equations",
                    join(path, shortcut_filename),
                    script_path,
                    working_dir)

rawDescription: How to create a shortcut in startmenu using setuptools windows installer

description: Create a shortcut in startmenu using setuptools windows installer


code:
# copied from
# http://matplotlib.sourceforge.net/mpl_examples/mplot3d/wire3d_demo.py

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)

plt.show()

rawDescription: Waterfall plot python?

description: Waterfall plot python


code:
[(a, b, c)
 for c in range(1, 11)
 for a in range(1, c + 1)
 for b in range(1, a + 1)
 if a**2 + b**2 == c**2 and a + b + c == 24]

rawDescription: What is the list comprehension for right triangles in python à la Haskell?


code:
orderedList = sorted(bucketList, key=lambda k: k.last_modified)
keysYouWant = orderedList[0:100]

rawDescription: s3- boto- list files within a bucket by upload time

description: S3- boto- list files within a bucket by upload time


code:
def __repr__(self):
   return '%s %s'%(self.amount,self.currency)

rawDescription: Persistent objects and __repr__

description: Persistent objects and __repr__


code:
garbled = "IXXX aXXmX aXXXnXoXXXXXtXhXeXXXXrX sXXXXeXcXXXrXeXt mXXeXsXXXsXaXXXXXXgXeX!XX"
m = ''.join(filter(lambda x: x != 'X', garbled))
m
type(m)

rawDescription: python3 filter object with lambda fuctoin

description: Python3 filter object with lambda fuctoin


code:
def parse(self, response):
       hxs = HtmlXPathSelector(response)
       urls = hxs.select('//a[contains(@href, "content")]/@href').extract()  ## only grab url with content in url name
       for i in urls:
           yield Request(urlparse.urljoin(response.url, i[1:]),callback=self.parse_url)

def parse_url(self, response):
   hxs = HtmlXPathSelector(response)
   item = ZipgrabberItem()
   item['zip'] = hxs.select("//div[contains(@class,'odd')]/text()").extract() ## this bitch grabs it
   return item

rawDescription: Can scrapy yield both request and items?

description: Can scrapy yield both request and items


code:
usernames = ["Billy", "Bob", "Apple"]
if "Billy" in usernames:
    usernames.remove("Billy")
# usernames = ["Bob", "Apple"]

rawDescription: Remove a Python array element by name

description: Remove a Python array element by name


code: self.canvas.coords(tagOrID, x0, y0, x1, y1)

rawDescription: Stretch Tkinter Rectangle

description: Stretch Tkinter Rectangle


code: l = list(set(i.lower() for i in l))

rawDescription: How to remove case insensitive redundancies in Python lists?

description: Remove case insensitive redundancies in Python lists


code: result=[ x for y in (a for a in (funct() for funct in functs) if a) for x in y]

rawDescription: How to merge multiple returned lists into one

description: Merge multiple returned lists into one


code:
def DFS(gr, s):
    path = []
    DFS2(gr, s, path)
    return path

rawDescription: Writing a better recursive depth-first search in python


code:
for k, v in dicts1.iteritems():
    try:
        dicts2[k] =  type(v)(dicts2[k])
    except (TypeError, ValueError) as e:
        pass # types not compatible
    except KeyError as e:
        pass # No matching key in dict

rawDescription: Dynamic type casting in python

description: Dynamic type casting in python


code:
import pkg_resources
data = pkg_resources.resource_string(__name__, "mtr.txt")

rawDescription: Open a file relative to python module path


code:
def human_key(key):
    parts = re.split('(\d*\.\d+|\d+)', key.lower())
    return tuple((e.swapcase() if i % 2 == 0 else float(e)) for i, e in enumerate(parts))

if (ordered in ["unregistered_business_unit", "unregistered_operational_unit", "unregistered_date"]):
    a_list = list(a_list)
    for a in a_list:
        a_history = list(a.history.all().order_by('-logged_at'))
        if (len(a_history) > 0):
            a.last_a_history = a_history[0]
        else:
            a.last_a_history = None
    if (ordered == "unregistered_business_unit"):
        a_list.sort(key=lambda a: (a.last_a_history.business_unit.description.lower() if ((a.last_a_history) and (a.last_a_history.business_unit)) else None, a.last_a_history.business_unit.identifier if ((a.last_a_history) and (a.last_a_history.business_unit)) else None, human_key(a.last_a_history.operational_unit.identifier) if ((a.last_a_history) and (a.last_a_history.operational_unit)) else None, a.mac_address), reverse=reverse_flag)
    elif (ordered == "unregistered_operational_unit"):
        a_list.sort(key=lambda a: (human_key(a.last_a_history.operational_unit.identifier) if ((a.last_a_history) and (a.last_a_history.operational_unit)) else None, a.last_a_history.business_unit.description.lower() if ((a.last_a_history) and (a.last_a_history.business_unit)) else None, a.last_a_history.business_unit.identifier if ((a.last_a_history) and (a.last_a_history.business_unit)) else None, a.mac_address), reverse=reverse_flag)
    elif (ordered == "unregistered_date"):
        a_list.sort(key=lambda a: (a.last_a_history.logged_at if (a.last_a_history) else pytz.utc.localize(datetime(MINYEAR, 1, 1)), a.mac_address), reverse=reverse_flag)

rawDescription: How to order a reverse foreign key in Django?

description: Order a reverse foreign key in Django


code:
import random
[random.random() for _ in range(0, 10)]

rawDescription: how to create a range of random decimal numbers between 0 and 1

description: Create a range of random decimal numbers between 0 and 1


code:
parser.add_argument('--argument', '-a', help='''
    this is my
    long help text
    ''')

rawDescription: Wrap long python strings correctly for optparse


code:
from django.conf import settings
...
def myView(request):
    login_url = "%s?next=%s" % (settings.LOGIN_URL, request.path)
    logout_then_login(request, login_url=login_url)

rawDescription: Django logout_then_login with next param


code:
def parse_info(self, response):
    # items = []
    for tr in range(1, 5):
        xpath = "/html/body/table/tbody/tr[%s]/td[1]/text()" % tr
        td1 = Selector(response=response).xpath(xpath).extract()
        item = MyItem()
        item['col1'] = td1
        # items.append(item)
        yield item
    # return items

    # If there is a next page, extract href, build request
    # and send it to server
    next_page = response.xpath('//a[contains(text(), "Next")]/@href')
    if next_page:
        next_page_href = next_page.extract()[0]
        next_page_url = response.urljoin(next_page_href)
        request = scrapy.Request(next_page_url, callback=self.parse_info)
        yield request

rawDescription: Scrapy recursive website crawl after login


code: np.bincount(a, weights=b)

rawDescription: Sum values according to an index array

description: Sum values according to an index array


code: norm = sum(e**2 for e in y)**0.5

rawDescription: How to avoid a seemingly unavoidable divide by zero

description: Avoid a seemingly unavoidable divide by zero


code:
for i in range(1024): # some sensible upper limit, beyond which the input is suspicious
    myid= params.getfirst("myfield%d" % i)
    if not myid: break
        # do stuff with myid

rawDescription: python basic while loop

description: Python basic while loop


code:
def start_requests(self):
    return [Request(url, meta={'domain': domain}, callback=self.parse_item) for url, domain in zip(self.start_urls, self.start_domains)]

rawDescription: Crawl multiple domains with Scrapy without criss-cross


code:
running = True
while running: # This would start the event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT: # This would be a quit event.
            running = False # So the user can close the program
    screen.fill(0,0,0) # This fills the screen with black colour.
    pygame.display.flip() # This "flips" the display so that it shows something
pygame.quit()

rawDescription: pygame.display.set_mode Window opens but freeze python 3.5 mac osx 10.11.1

description: Pygame.display.set_mode Window opens but freeze python 3.5 mac osx 10.11.1


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('Test', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        print ('Hello World')

if __name__ == '__main__':

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

rawDescription: How to implement a simple button in PyQt

description: Implement a simple button in PyQt


rawDescription: Resetting a number in a number count (Python)


code:
from win32com.client.gencache import EnsureDispatch
from win32com.client import constants

outlook = EnsureDispatch("Outlook.Application")
newMail = outlook.CreateItem(constants.olMailItem)
newMail.Subject = "This is subject"

samplegrp1 = newMail.Recipients.Add("samplegrp1")
samplegrp2 = newMail.Recipients.Add("samplegrp2")
samplegrp1.Type = constants.olCC
samplegrp3.Type = constants.olCC
newMail.Recipients.ResolveAll()

rawDescription: Sending Outlook mail to multiple distribution lists in Python


code:
example = [[1, 2], [1, 5], [1, 8], [2, 1], [2, 9], [2,5]]
n = 5
[first for first, second in example if second == n]

rawDescription: finding a list in a list of list based on one element

description: Finding a list in a list of list based on one element


code:
from datetime import timedelta
from django.db.models import Sum
from django.utils import timezone

MyModel.objects.filter(
    pub_date__gte=timezone.now() - timedelta(days=7)
).aggregate(sum_hours=Sum('hours'))

rawDescription: Aggregate a field based on time interval


code:
import glob
contentlist = glob.glob(test[0])

rawDescription: os.listdir using input from array

description: Os.listdir using input from array


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

matplotlib.rcParams['font.family'] = 'ubuntu'
labels = ['Foo', 'Bar', 'Really long label']
values = [5, 3, 4]

ind = np.array(range(3))
fig, ax = plt.subplots()
ax.barh(ind, values, 0.5, align='center')
ax.set_yticks(range(3))
ax.set_yticklabels(labels)
fig.tight_layout()

txt = ax.yaxis.get_ticklabels()[-1]
txt.set_fontstretch('condensed')
txt.set_fontsize(5)  # I also change the font size

plt.draw()

rawDescription: Change axis label font for one value only


code:
from contextlib import closing
import requests
with closing(requests.get('http://httpbin.org/get', stream=True)) as r:
    while r.iter_content:
        # Do something with the stream..
        pass

rawDescription: how to receive streaming data using flask in python program

description: Receive streaming data using flask in python program


code:
a.set_zorder(1)
y.set_zorder(0)

rawDescription: Set top level axis for navigation toolbar and pick events


code:
value = my_list[0]
if isinstance(value, list):
    value = value[0]

# use the value

rawDescription: Reading first non-list value from the arbitrary nested list


code:
s = "dates like March 4 1998, but they are all missing commas"
regex = re.compile("""
(January|February|March|April|June|July|August|September|October|
 November|December)[ ]([0-9]{1,2})[ ]([0-9]{4})""", re.X)
regex.sub(r"\1 \2, \3", s)

rawDescription: How to add back commas into string python regex?

description: Add back commas into string python regex


code:
import pandas as pd
source = pd.DataFrame({'A': ['foo', 'bar'], 'B': [1, 2], 'C': [(1,2), (3,4)]})
source
source._get_numeric_data()

rawDescription: Drop non-numeric columns from a pandas DataFrame


code:
from dateutil import parser
s = "2014-04-23 13:06:32 America/New_York"
run_time_info = parser.parse(s, fuzzy=True)
run_time_info

rawDescription: python minidom firstChild.data ignore part of string (date + time + timezone) drop timezone

description: Python minidom firstChild.data ignore part of string (date + time + timezone) drop timezone


code: x = np.meshgrid(*y)

rawDescription: numpy - meshgrid for multiple dimensions

description: Numpy - meshgrid for multiple dimensions


code:
f = open(workbook.name, "w")
f.write(soup.prettify())
f.close()

rawDescription: write xml with beautiful soup

description: Write xml with beautiful soup


code:
import os
root_path = './work/animals/'
folders = ['cat','dog','horse','mouse','lion','cheetah','rat','baboon','donkey','snake','giraffe']
subfolders = ['male', 'female', 'uncategorized']
for folder in folders:
    os.mkdir(os.path.join(root_path,folder))
    for subfolder in subfolders :
        os.mkdir(os.path.join(root_path,folder,subfolder))

rawDescription: Creating similar multiple sub-folders in multiple different folders using python


code:
seen    = set()
results = []

for user in ladder:
    acc  = user['account']
    name = acc['name']
    if name not in seen:
        seen.add(name)
        twitch_name = acc['twitch']['name'] if "twitch" in acc else ''
        challenges  = acc['challenges']['total']
        results.append("%s,%s,%d" % (name, twitch_name, challenges))

with codecs.open('test.csv','w', encoding="UTF-8") as out:
    out.write("\n".join(results))

rawDescription: Is there a way to do it faster?

description: Is there a way to do it faster


code:
def ngram(text,grams):
    model=[]
    count=0
    for token in text[:len(x)-grams+1]:
       model.append(text[count:count+grams])
       count=count+1
    return model

rawDescription: Implementing ngrams in Python

description: Implementing ngrams in Python


code:
import cv2

def segmentize (image_path, segment_width=200, segment_height=50):
    # Croping Formula ==> y:h, x:w
    idx, x_axis, x_width,  = 1, 0, segment_width
    y_axis, y_height = 0, segment_height
    img = cv2.imread(image_path)
    height, width, dept = img.shape
    while y_axis <= height:
        while x_axis <= width:
            crop = img[y_axis:y_height, x_axis:x_width]
            x_axis=x_width
            x_width+=segment_width
            cropped_image_path = "crop/crop%d.png" % idx
            cv2.imwrite(cropped_image_path, crop)
            idx+=1
        y_axis += segment_height
        y_height += segment_height
        x_axis, x_width = 0, segment_width

rawDescription: Segmenting Image In Fixed Blocks

description: Segmenting Image In Fixed Blocks


code:
import curses

screen = curses.initscr()
curses.cbreak()
screen.keypad(1)

key = ''

while key != ord('q'):  # press <Q> to exit the program
    key = screen.getch()  # get the key
    screen.addch(0, 0, key)  # display it on the screen
    screen.refresh()

    # the same, but for <Up> and <Down> keys:
    if key == curses.KEY_UP:
        screen.addstr(0, 0, "Up")
    elif key == curses.KEY_DOWN:
        screen.addstr(0, 0, "Down")

curses.endwin()

rawDescription: Binding key presses

description: Binding key presses


code:
...
html = urlopen(t)
bsObj = BeautifulSoup(html)
nameList = bsObj.findAll("span",{"class":"titletext"})

for name in nameList:
    print(name.get_text(), name.parent.get('href'))  # <----

rawDescription: I want do some wescraping of googlenews using BeautifullSoup library in python


code:
df = pd.read_csv("sillytup.csv", converters={"colA": ast.literal_eval})
df
df.colA.iloc[0]
type(df.colA.iloc[0])

rawDescription: Reading back tuples from a csv file with pandas


code:
import os

if os.name == 'nt':
    import ctypes
    from ctypes import windll, wintypes
    from uuid import UUID

    # ctypes GUID copied from MSDN sample code
    class GUID(ctypes.Structure):
        _fields_ = [
            ("Data1", wintypes.DWORD),
            ("Data2", wintypes.WORD),
            ("Data3", wintypes.WORD),
            ("Data4", wintypes.BYTE * 8)
        ]

        def __init__(self, uuidstr):
            uuid = UUID(uuidstr)
            ctypes.Structure.__init__(self)
            self.Data1, self.Data2, self.Data3, \
                self.Data4[0], self.Data4[1], rest = uuid.fields
            for i in range(2, 8):
                self.Data4[i] = rest>>(8-i-1)*8 & 0xff

    SHGetKnownFolderPath = windll.shell32.SHGetKnownFolderPath
    SHGetKnownFolderPath.argtypes = [
        ctypes.POINTER(GUID), wintypes.DWORD,
        wintypes.HANDLE, ctypes.POINTER(ctypes.c_wchar_p)
    ]

    def _get_known_folder_path(uuidstr):
        pathptr = ctypes.c_wchar_p()
        guid = GUID(uuidstr)
        if SHGetKnownFolderPath(ctypes.byref(guid), 0, 0, ctypes.byref(pathptr)):
            raise ctypes.WinError()
        return pathptr.value

    FOLDERID_Download = '{374DE290-123F-4565-9164-39C4925E467B}'

    def get_download_folder():
        return _get_known_folder_path(FOLDERID_Download)
else:
    def get_download_folder():
        home = os.path.expanduser("~")
        return os.path.join(home, "Downloads")

rawDescription: python - Finding the user's "Downloads" folder

description: Python - Finding the user's "Downloads" folder


code:
from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF
drawing = svg2rlg("file.svg")
renderPDF.drawToFile(drawing, "file.pdf")

rawDescription: Generating PDFs from SVG input

description: Generating PDFs from SVG input


code:
class learningObject(models.Model):
    ...
    def __unicode__(self):
        return "whatever you want to name it"

rawDescription: Using another name for the class object in the django interface


rawDescription: Are tuples more efficient than lists in Python?


code:
myString = "fullName( name = 'Joe', family = 'Brand' )"
result = eval(myString)

rawDescription: Use a string to call function in Python

description: Use a string to call function in Python


code:
import re
dict = {}
dict[re.compile('actionname (\d+) (\d+)')] = method
dict[re.compile('differentaction (\w+) (\w+)')] = appropriate_method

def execute_method_for(str):
    #Match each regex on the string
    matches = (
        (regex.match(str), f) for regex, f in dict.iteritems()
    )

    #Filter out empty matches, and extract groups
    matches = (
        (match.groups(), f) for match, f in matches if match is not None
    )

    #Apply all the functions
    for args, f in matches:
        f(*args)

rawDescription: Regular expression dictionary in python

description: Regular expression dictionary in python


code:
from django.db.models import DateTimeField, F, Case, When
notes.annotate(newest_in_vault=Case(When(notereposter__isnull=False,
        then=F("notereposter__date_added")), default=F("date_created"),
        output_field=DateTimeField()))
# Sort it now
notes = notes.order_by("-newest_in_vault")

rawDescription: Django: Ordering by the datetime of many to many model and the datetime of model itself


code:
dictionary = {'foo': 3, u'bar': [6.7]}
str = repr(dictionary)
str
exec("adict = " + str)
adict

rawDescription: Generating py objects via python

description: Generating py objects via python


code:
ax = plt.gca()

# Make axes occupy whole canvas
ax.set_position([0,0,1,1])

# Same scale on x- and y-axes, change x- and y-limits to keep
# axes ratio and position
# 'equal' gives same scaling on x- and y-axes
# 'datalim' changes the xlim and ylim to fit the axes inside its boundary
ax.set_aspect('equal', 'datalim')

ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
[spine.set_visible(False) for spine in ax.spines.values()]

rawDescription: Cut the border of the axes

description: Cut the border of the axes


code:
from scapy.layers.inet import IP
from scapy.layers.inet import ICMP
from scapy.layers.inet import TCP
target = "10.9.8.7"
ttl = 64
id = 32711
sport = 2927
dport = 80
pak = IP(dst=target, src = "100.99.98.97", ttl=ttl, flags="DF", id=id, len=1200, chksum = 0)/TCP(flags="S", sport=sport, dport=int(dport), options=[('Timestamp',(0,0))], chksum = 0)
del pak[IP].chksum
del pak[TCP].chksum
pak.show2()

rawDescription: How to calculate a packet checksum without sending it?

description: Calculate a packet checksum without sending it


code:
import threading
import time
def func():
    global l
    i = 0
    while i < 15:
            l.append(i)
            i += 1
            time.sleep(1)
def foo(t):
    t.start()
    i = 20
    while i > 0:
            print(l)
            i -= 1
            time.sleep(0.5)
l = []
t = threading.Thread(target=func)
foo(t)

rawDescription: share a global variable in multi threading doesn't work in python

description: Share a global variable in multi threading doesn't work in python


code:
from django.core.files import File

# assuming your updated model looks like:
# class Photo(models.Model):
#     filename = models.CharField(max_length=240)
#     image = models.ImageField(max_length=240)

photos = Photo.objects.all()
for p in photos:
    f = open(p.filename)
    myimage = File(f)
    p.image.save(image_name, myimage) # name, content

rawDescription: CharField filenames into ImageFields in Django


code:
from collections import defaultdict
from functools import partial

results = defaultdict(partial(defaultdict, int))
for main, month, tot in list_data:
    results[main][month] += tot
    results[main]["total"] += tot
    results[u"grandtotal"][month] += tot
result_output = dict((k, dict(v)) for k, v in results.items())

rawDescription: Sum of values in a dict

description: Sum of values in a dict


code:
md = markdown.Markdown(safe_mode="escape", output_format='html4')
h2t = html2text.HTML2Text()

rawDescription: When used with uwsgi, redis APPENDs value instead of SETing it


code:
x = "a & 日本語:  enči hallöle".decode("utf-8")
x.replace("&", "&").encode("latin-1", "xmlcharrefreplace")

rawDescription: Convert a unicode object to a latin string with entities


rawDescription: Simultaneous matrix transpose for large array of matrices


code:
import numpy as np
import numpy.random
import matplotlib.pyplot as plt
p = plt.figure()
plt.style.use('ggplot')

np.random.seed(0)
x = np.random.rand(50)
y = np.random.rand(50)

heatmap, xedges, yedges = np.histogram2d(x, y, bins=4)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

plt.imshow(heatmap, extent=extent)
plt.show(p)

rawDescription: Matplotlib heatmap rotates image automatically


code:
 # what each person pays, catch errors
def payments(bill,ppl):
    try:
        return round((bill/ppl),2)
    except:
        print ('Invalid Calculation, try again')

#function to calculate tip, catch any errors dealing with percentages
def tip(bill,ppl,perc):
    try:
        return round(((bill * (perc/100))/ppl),2)
    except:
        print ('Please retry calculation with valid tip percentage')

'''
    function of body that will
    ask each question and will catch errors(if any),
    and continue to loop until valid entry is given
'''

def main():
    print ("How much is the bill?")
    while True:
        try:
            total_bill = float(input('>> $'))
            break
        except:
            print("")
            print("Must be a number value")
            print("")
    print("")

    print ("How many people?")
    while True:
        try:
            num_ppl = int(input('>>'))
            break
        except:
            print("")
            print("Must be a number value")
            print("")
        print("")

    print ("Tip Percentage?")
    while True:
        try:
            perc = int(input('>> %'))
            break
        except:
            print("")
            print("Must be a number value")
            print("")

    print ("")
    print ("Calculating Payment...")

        # Create variables to calculate total pay
    bill_payment = payments(total_bill,num_ppl)
    tip_payment = tip(total_bill,perc,num_ppl)
    total_payment = float(bill_payment)+float(tip_payment)

        #print each variable out with totals for each variable
    print ('Each Person pays $%s for the bill' % \
          str(bill_payment))
    print ('Each Person pays $%s for the tip' % \
          str(tip_payment))
    print ('Which means each person will pay a total of $%s' % \
          str(total_payment))

if __name__ == '__main__':
    main()

rawDescription: Python Calculator encountering infinite loops


code: [lambda: random.normalvariate(3.0, 2.0), lambda: random.normalvariate(1.0, 4.0)]

rawDescription: How to pass a random function as an argument?

description: Pass a random function as an argument


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

fig = plt.figure()
ax = fig.add_subplot(111)
x = y = np.arange(0, 1, 0.1)
plt.plot(x, y, label='my function')
plt.title('title')
ax.set_xlabel('xAxis')
ax.set_ylabel('yAxis')

#print fig.get_size_inches()
fig.set_size_inches(8, 6, forward=True)
fig.tight_layout()
plt.savefig('exact_size_test.png', dpi=100)

rawDescription: How do I get an image w/ the exact size in pixels, when using bbox_inches='tight' in matplotlib?

description: Get an image w/ the exact size in pixels, when using bbox_inches='tight' in matplotlib


code:
class BookForm(ModelForm):

    class Meta:
        model = Book
        fields = ('name', 'description')
        # NOTE: you can also use excludes, but many consider it a bad practice

rawDescription: How to save a field after commit=False with model Form in Django?

description: Save a field after commit=False with model Form in Django


code:
buf = cast(p, POINTER(c_char * n))[0]

# 2.6+
buf = (c_char * n).from_address(p)

rawDescription: c_void_p arguments in callbacks using ctypes in Python

description: C_void_p arguments in callbacks using ctypes in Python


code:
from multiprocessing import Pool

def connectAndCollect(server):
    c = Connection(server)
    return c.MyData.MyCollection.find_one()

pool = Pool(processes=10)
res = pool.map(connectAndCollect,servers)
map(lambda x: all_data.append(x),res)
pool.close()

rawDescription: How can I thread my remote MongoDB calls?

description: Thread my remote MongoDB calls


code:
import ctypes as c

class Point(c.Structure):
    _fields_ = [
        ('x',c.c_double),
        ('y',c.c_double),
        ('z',c.c_double)
        ]

def points_factory(num_points):
    class Points(c.Structure):
        _fields_ = [
            ('num_points', c.c_uint32),
            ('points', Point*num_points)
            ]
    return Points

#and when you need it in the code:
Points = points_factory(5)

rawDescription: ctypes variable length structures

description: Ctypes variable length structures


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

# Data similar to yours
green = np.array([2.5, 1, 0.9, 0.7, 0.4])
red = green
blue = np.array([3.8, 2, 1.8, 1.5, 0.6])
x = np.arange(2, 7)

# Plot bars where the left edge will be at each x-value
fig, ax = plt.subplots()

ax.bar(x, green, width=1, color='green')
ax.bar(x, red, width=1, bottom=green, color='red')
ax.bar(x, blue, width=1, bottom=green+red, color='blue')

ax.set(xlim=[0.5, 7.5])
plt.show()

description: Matplotlib.figure.add_subplot.vlines orientation


code:
if number == 1 or powerup == True:
        print(powerup)
        powerup = True
        print(powerup)

rawDescription: Python, boolean resets itsself

description: Python, boolean resets itsself


code:
def bilinear_interpolate(im, x, y):
    x = np.asarray(x)
    y = np.asarray(y)

    x0 = np.floor(x).astype(int)
    x1 = x0 + 1
    y0 = np.floor(y).astype(int)
    y1 = y0 + 1

    x0 = np.clip(x0, 0, im.shape[1]-1);
    x1 = np.clip(x1, 0, im.shape[1]-1);
    y0 = np.clip(y0, 0, im.shape[0]-1);
    y1 = np.clip(y1, 0, im.shape[0]-1);

    Ia = im[ y0, x0 ]
    Ib = im[ y1, x0 ]
    Ic = im[ y0, x1 ]
    Id = im[ y1, x1 ]

    wa = (x1-x) * (y1-y)
    wb = (x1-x) * (y-y0)
    wc = (x-x0) * (y1-y)
    wd = (x-x0) * (y-y0)

    return wa*Ia + wb*Ib + wc*Ic + wd*Id

rawDescription: Simple, efficient bilinear interpolation of images in numpy and python


code:
firstList = [1,2,3]
secondList=[]

counter = len(firstList)-1

while counter >= 0:
    secondList.append(firstList[counter])
    counter -= 1

rawDescription: How do I reverse a list using while loop?

description: Reverse a list using while loop


code:
import scipy.io
import numpy as np

def save_array(arr, arrname, fname):
    """
    Save an array to a .mat file
    Inputs:
      arr: ndarray to save
      arrname: name to save the array as (string)
      fname: .mat filename (string)
    """
    out_dict={arrname: arr}
    scipy.io.savemat(fname,out_dict)

save_array(np.array([1,2,3]), 'arr', 'test.mat')

rawDescription: How can my argument be used to create a matlab file?


code:
#!/usr/bin/env python
# coding: utf8
from __future__ import absolute_import, division, print_function
import os
from SimpleXMLRPCServer import list_public_methods, SimpleXMLRPCServer

class Filesystem(object):

    def __init__(self, base_directory):
        self.current_directory = self.base_directory = os.path.normpath(
            os.path.abspath(base_directory)
        )

    def _listMethods(self):
        return list_public_methods(self)

    def _get_directory(self, dirname):
        if os.path.isabs(dirname):
            drive, _ = os.path.splitdrive(dirname)
            if drive:
                raise ValueError('trying to change drive')
            dirname = dirname.lstrip(os.sep + (os.altsep or ''))
            self.current_directory = self.base_directory

        result = os.path.normpath(
            os.path.abspath(os.path.join(self.current_directory, dirname))
        )
        print(result, self.base_directory)
        if not result.startswith(self.base_directory):
            raise ValueError('trying to go higher than base directory')
        return result

    def list_dir(self, dirname):
        return os.listdir(self._get_directory(dirname))

    def change_dir(self, dirname):
        self.current_directory = self._get_directory(dirname)
        return True

def main():
    server = SimpleXMLRPCServer(('localhost', 8000))
    server.register_introspection_functions()
    server.register_instance(Filesystem(u'.'))
    server.serve_forever()

if __name__ == '__main__':
    main()

rawDescription: How can SimpleXMLRPCServer registered function access the server itself and use some local scope?


code: listctrl.myID = 5

rawDescription: wxPython -- differentiating between two identical widgets

description: WxPython -- differentiating between two identical widgets


code:
import os
import django

script_path = os.path.dirname(__file__)
os.environ['DJANGO_SETTINGS_MODULE']='myapp.settings'
django.setup()

rawDescription: How to use a model from a Django project in another Python script

description: Use a model from a Django project in another Python script


code:
import socket
def guard(*args, **kwargs):
    raise Exception("I told you not to use the Internet!")
socket.socket = guard

rawDescription: Python: block network connections for testing purposes?


code:
from celery.result import AsyncResult

@task
def verify_task(task_id):
    result = AsyncResult(task_id)
    if result.ready():
         do_something_with(result.get())
    else:
        verify_task.retry(countdown=1)

rawDescription: A finite celery beat task

description: A finite celery beat task


code: int1, int2 = tuple

rawDescription: How do I get integers from a tuple in Python?

description: Get integers from a tuple in Python


code:
def GET(self):
    request = web.input( path=None )
    getPath = request.path
    if os.path.exists( getPath ):
        getFile = file( getPath, 'rb' )
        web.header('Content-type','application/octet-stream')
        web.header('Content-transfer-encoding','base64')
        return base64.standard_b64encode( getFile.read( ) )
    else:
        raise web.notfound( )

rawDescription: Access files from web.py urls

description: Access files from web.py urls


code:
#In which we make contourplots with just one colorbar

import matplotlib.pyplot as plt
import numpy as np

plt.figure(1)
plt.clf()
plt.contourf(np.random.random((10,10)))
plt.colorbar()
for k in xrange(10):
    plt.contourf(np.random.random((10,10)))
plt.show()

rawDescription: Duplicated colorbars when creating an animation


code: unicodeCheckBox = QCheckBox( u'A \u2295 B' )

rawDescription: How to include special math symbols in QCheckBox text string?

description: Include special math symbols in QCheckBox text string


code:
from functools import wraps
def user_permission():
    @wraps(f)
    def decorated(self, *args, **kwargs):
        if self.myname == 'My Name':
            return f(self, *args, **kwargs)
        else:
            return "Not Permitted"
    return decorated

rawDescription: Pass parameters to a decorator for a class method is to be decorated


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--action', choices=['upload', 'dump'], default='dump')
parser.add_argument('--dump-format')
args = parser.parse_args()
if args.action != 'dump' and args.dump_format:
    parser.error('--dump-format can only be set when --action=dump.')

rawDescription: Conditional command line arguments in Python using argparse


code:
df.resample('15min', how='sum', label='right')
df.resample('15min', how='sum', label='right',base=7)
df.resample('15min', how='sum', label='left',base=7)
df.resample('15min', how='sum', label='right',loffset='7T')
df.resample('15min', how='sum', label='left',loffset='7T')

rawDescription: need pandas DataFrame.resample() to honor sub-period series start datetime

description: Need pandas DataFrame.resample() to honor sub-period series start datetime


code:
from wtforms.fields.html5 import TelField

phonenumber = TelField()

rawDescription: How do I use the "tel" or "number" input types in WTForms?

description: Use the "tel" or "number" input types in WTForms


code:
import daemon
import time

def write_time_to_file():
    with open("file.txt", "a") as f:
        hora = time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
        f.write(hora+"\n")

with daemon.DaemonContext():
    while(True):
        write_time_to_file()
        time.sleep(2)

rawDescription: Daemon in background in python

description: Daemon in background in python


code:
from pdb import set_trace
driver = webdriver.Firefox()
driver.get("google.com")
set_trace()
driver.find_element_by_xpath("//input[@id='gbqfq']").send_keys("cats" + Keys.RETURN)

rawDescription: Python with selenium: rerun on pre-existing browser


code:
#Initialize test list with 2 numpy float64 values
test = [numpy.float64(456),numpy.float64(456)]
#Attempting to insert a list containing only numpy data types will error
ws.Range(ws.Cells(1,1),ws.Cells(1,2)).value = test
#Changing one of the values to any other standard python data type will allow the list to be inserted
test[1] = 'test'
ws.Range(ws.Cells(1,1),ws.Cells(1,2)).value = test
test.append(numpy.int64(456))
ws.Range(ws.Cells(1,1),ws.Cells(1,3)).value = test
""" Conclusion: A list can be inserted only if all of the numpy data types are the same and there is a built-in data type in the list as well """
test[2] = numpy.float64(test[2])
ws.Range(ws.Cells(1,1),ws.Cells(1,3)).value = test

rawDescription: win32com MemoryError attempting to insert data into excel

description: Win32com MemoryError attempting to insert data into excel


code:
# define some constants
PI = 3.1415927
ANSWER = 42
UNLUCKY = 13

# put them into __main__ module (your interactive session)
if __name__ != "__main__":
    import sys as _sys
    _sys.modules["__main__"].__dict__.update(
        dict((k, v) for (k, v) in globals().iteritems() if not k.startswith("_")))

rawDescription: Python module variables into current workspace


code: pysqlite ; python_version < '3'

rawDescription: How can I specify a requirement only for Python 2 (ie not Python 3) in requirements.txt?

description: Specify a requirement only for Python 2 (ie not Python 3) in requirements.txt


code:
def createWidgets(self):
    ...
    self.buttons = {}
    for floor in floors:
        ...
        self.buttons[floor] = tk.Button(...)
    ...
def pressed(self, index):
    ...
    self.buttons[index].configure(bg="red")

rawDescription: Tkinter with Python 3.3 : Change colour of button on click


code: maxent_tagger = ClassifierBasedPosTagger(train=train_sents, classifier_builder=lambda train_feats: MaxentClassifier.train(train_feats, algorithm='megam', max_iter=10, min_lldelta=0.1))

rawDescription: Trying to use MEGAM as an NLTK ClassifierBasedPOSTagger?


code:
TARGET_DIR = '/home/me/projects/data/'
n = sum(1 for f in os.listdir(TARGET_DIR) if os.path.isfile(os.path.join(TARGET_DIR, f)))
new_name = "{}Trial_{}.xls".format(TARGET_DIR,n+1)

rawDescription: Python automated file names

description: Python automated file names


code:
...
if (event.type==pygame.KEYDOWN):
    if (event.unicode==pygame.K_COLON): #to match a colon
        pass
    elif (event.unicode== (pygame.K_Z | pygame.KMOD_SHIFT)): #to explicitly match a capital Z instead of just a z
       pass
...

rawDescription: What is a good way to get keyboard Input in Python/Pygame?


code:
import sys
import subprocess

logfile = open('logfile', 'w')
proc=subprocess.Popen(['cat', 'file'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in proc.stdout:
    sys.stdout.write(line)
    logfile.write(line)
proc.wait()

rawDescription: Python Popen: Write to stdout AND log file simultaneously