code:
import numpy as np
from math import *

def multivariate_t_distribution(x,mu,Sigma,df,d):
    '''
    Multivariate t-student density:
    output:
        the density of the given element
    input:
        x = parameter (d dimensional numpy array or scalar)
        mu = mean (d dimensional numpy array or scalar)
        Sigma = scale matrix (dxd numpy array)
        df = degrees of freedom
        d: dimension
    '''
    Num = gamma(1. * (d+df)/2)
    Denom = ( gamma(1.*df/2) * pow(df*pi,1.*d/2) * pow(np.linalg.det(Sigma),1./2) * pow(1 + (1./df)*np.dot(np.dot((x - mu),np.linalg.inv(Sigma)), (x - mu)),1.* (d+df)/2))
    d = 1. * Num / Denom
    return d

rawDescription: multivariate student t-distribution with python

description: Multivariate student t-distribution with python


code:
dict0 = {'k0': 0, 'k1': 1, 'dict2':{'k3': 3, 'k4': 4},
         'dict3':{'k5': 5, 'dict4':{'k6': 6}}}

def keys(dic, klist=[]):
    subdics = []
    for key in sorted(dic):
        val = dic[key]
        if isinstance(val, dict):
            subdics.append(val)
        else:
            klist.append(key)
    for subdict in subdics:
        keys(subdict, klist)
    return klist

result = keys(dict0)
print(result, '\n', result == ['k0','k1','k3','k4','k5','k6'])

def keylines(dic, name='outer_dict', lines=[]):
    vals = []
    subdics = []
    for key in sorted(dic):
        val = dic[key]
        if isinstance(val, dict):
            subdics.append((key,val))
        else:
            vals.append(key)
    vals.extend(pair[0] for pair in subdics)
    lines.append('{}_keys = {}'.format(name, vals))
    for subdict in subdics:
        keylines(subdict[1], subdict[0], lines)
    return lines

result = keylines(dict0)
for line in result:
    print(line,)
print()
expect = [
        "outer_dict_keys = ['k0', 'k1', 'dict2', 'dict3']",
        "dict2_keys = ['k3', 'k4']",
        "dict3_keys = ['k5', 'dict4']",
        "dict4_keys = ['k6']"]
for actual, want in zip(result, expect):
    if actual != want:
        print(want)
        for i, (c1, c2) in enumerate(zip(actual, want)):
            if c1 != c2:
                print(i, c1, c2)

rawDescription: How to get keys from nested dictionary of arbitrary length in Python

description: Get keys from nested dictionary of arbitrary length in Python


code:
meta = soup.find_all("div", {"class": "content"})

wordage = [s.h1 for s in meta if s.h1 not in ([], None)]
link = [s.a['href'] for s in wordage]

rawDescription: Scraping all h1 tags contents with beautiful soup


code:
from subprocess import call

acrobat = "C:\Program Files\Adobe\Acrobat 7.0\Acrobat.exe" ## Acrobat reader would also work, apparently
file = "C:\path\to\my\file.pdf"
printer = "Printer Name Goes Here"

call([acrobat, "/T", file, printer])

rawDescription: Python's win32api only printing to default printer


rawDescription: Add 1 To Every Element in an ndarray if Not Zero


code:
x, y = np.indices(array.shape)
x = x.ravel(order='F')
y = y.ravel(order='F')
values = array.ravel(order='F')

rawDescription: Get x,y,value 1D arrays from 2D numpy array (linear indexing)


code:
inp = [("abc", 1, "def"), ("abc", 1, "ghi"), ("bc", 2, "a"), ("bc", 2, "b"), ("bc", 3, "a")]
res = []
[res.append(el) for el in inp if not [tmp for tmp in res if tmp[0] == el[0] and tmp[1] == el[1]]]

rawDescription: list comprehension with tuple comparision

description: List comprehension with tuple comparision


code:
looped = 0
numbergen = 0
max_num = None
while looped < 3: #how many times a number's supposed to be re-generated
    x = randint(1,1001)
    max_num = x if max_num is None else max(x, max_num)
    print(x)
    looped = looped + 1
print('max num: {0}'.format(max_num))

rawDescription: The highest set value of an integer that's constantly changing


code:
PAGE_URL = '{slug}'
PAGE_SAVE_AS = '{slug}'

rawDescription: Python Pelican order menu items

description: Python Pelican order menu items


code:
from PIL import Image
import StringIO
tempBuff = StringIO.StringIO()
tempBuff.write(curimg)
tempBuff.seek(0) #need to jump back to the beginning before handing it off to PIL
Image.open(tempBuff)

rawDescription: Converting jpeg string to PIL image object


code:
s1 = range(10)
s2 = range(5,20)
set(s1) & set(s2)  #set intersection returns the common keys

rawDescription: Efficient way to compare elements in 2 lists


code:
class MyUserAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        self.exclude = []
        if not request.user.is_superuser:
            self.exclude.append('Permissions') #here!
        return super(MyUserAdmin, self).get_form(request, obj, **kwargs)

rawDescription: Exclude fields in Django admin for users other than superuser


code:
z = [(i, x.index(item)) for i, x in enumerate(alist) if item in x][0]
alist[z[0]][z[1]] = blist[z[0]][z[1]]
alist

rawDescription: Replacing items in 1 list to items in another list in python


code:
from datetime import datetime, timedelta
serial_number = (datetime(2012, 1, 1, 9, 55, 56) + timedelta(223)).strftime('%d-%h-%y %H:%M:%S')

rawDescription: How can I convert data into "ddmmyyyy hh:mm:ss"?

description: Convert data into "ddmmyyyy hh:mm:ss"


code:
for x in range(len(vals)):
    curr=vals[x];
    for y in range(x+1,len(vals)):
        if(curr > vals[y]):
            temp = vals[y]
            vals[y] = curr
            vals[x] = temp
            curr = vals[x] # <--

rawDescription: What is wrong with this sorting code? Python


code:
url = 'http://upload.wikimedia.org/wikipedia/commons/thumb/4/43/Timba%2B1.jpg/220px-Timba%2B1.jpg'
user_agent = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.19 (KHTML, like Gecko) Ubuntu/12.04 Chromium/18.0.1025.168 Chrome/18.0.1025.168 Safari/535.19'
u = urllib.request.urlopen(urllib.request.Request(url, headers={'User-Agent': user_agent}))

rawDescription: Python3 urllib image retreval

description: Python3 urllib image retreval


code:
import pandas as pd

# define the file name and "sheet name"
fn = 'Book1.xlsx'
sn = 'Sheet1'

data = pd.read_csv(fn, sheetname=sn, index_col=0, skiprows=1, header=0, skip_footer=1)

rawDescription: Read a specific column of a certain cell range and store the values using Pandas


code:
import cProfile
import time
import pstats
import io

pr = cProfile.Profile(time.process_time)

pr.enable()

time.sleep(1)
for i in range(0, 1000):
    print("hello world")
time.sleep(1)
pr.disable()

s = io.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())

rawDescription: Is cProfile betraying me?

description: Is cProfile betraying me


code:
session = sqlalchemy.orm.Session.object_session(model)
session.is_modified(model)

rawDescription: Find out if a persistent sqlalchemy mapped object was modified


code:
class LocationDayAdmin(admin.ModelAdmin):
    list_display = ('id', 'show_variants' )

    def show_variants(self, obj):
        return "<a href='/admin/<package>/variants/attribute__id__exact=" + str(obj.id) + "'>show variants"

    show_variants.allow_tags = True

rawDescription: Django admin - filtered list view

description: Django admin - filtered list view


code: server = Popen("./app.py", stdout=PIPE, stderr=PIPE, shell=True)

rawDescription: Unable to kill Flask server launched by Popen on Ubuntu


code:
auth = tweepy.AppAuthHandler(token, secret)
api = tweepy.API(auth)

rawDescription: How to change authentication type on Twitter API

description: Change authentication type on Twitter API


code:
import csv

names = ['bar', 'foo', 'foobar']
data = []

# read data
with open('all.csv', 'r') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=',')
    for row in spamreader:
        if row[1] in names:
            data.append(row)

# maybe some more processing
# ...

# write back data that meets criteria
with open('bar.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    spamwriter.writerows(data)

rawDescription: How to save only lines containing a particular String (in a CSV file) as a separate CSV file?

description: Save only lines containing a particular String (in a CSV file) as a separate CSV file


code:
my_array = np.arange(20.)
my_array[4::5] = np.nan
my_array

rawDescription: Python: Replace every 5th value of numpy array


code:
import json
def remap_keys(mapping):
    return [{'key':k, 'value': v} for k, v in mapping.iteritems()]

json.dumps(remap_keys({(1, 2): 'foo'}))

rawDescription: json serialize a dictionary with tuples as key

description: Json serialize a dictionary with tuples as key


rawDescription: assign multiple instances of a class to variables

description: Assign multiple instances of a class to variables


rawDescription: Logging events in Python; How to log events inside classes?


code:
# Code above here is unchanged

gameExit = False

logo1 = pygame.image.load('logo.png')  # Don't load these in a loop!
logo2 = pygame.image.load('logo2.png') # Only need to load them once.

# Make sure you record start_time here! Because the timer actually
# started several seconds before the display is ready.

start_time = pygame.time.get_ticks() / 1000

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True

    time = pygame.time.get_ticks() / 1000
    elapsed = time - start_time

    gameDisplay.fill(black)

    if elapsed > 4:
        gameDisplay.fill(white)
        button(0, 0, 10, 10, 'exit')
        pygame.draw.rect(gameDisplay, red, (0, 0, 10, 10))
    elif elapsed > 2:
        gameDisplay.blit(logo2, (0, 0))
    elif elapsed > 0:
        gameDisplay.blit(logo1, (1, 1))

    pygame.display.update()
    clock.tick(15)

pygame.quit()
quit()

rawDescription: Pygame crashes every time i click in the window


code:
class OnlyOne:
    class __OnlyOne:
        def __init__(self, arg):
            self.val = arg
        def __str__(self):
            return repr(self) + self.val
    instance = None
    def __init__(self, arg):
        if not OnlyOne.instance:
            OnlyOne.instance = OnlyOne.__OnlyOne(arg)
        else:
            OnlyOne.instance.val = arg
    def __getattr__(self, name):
        return getattr(self.instance, name)

rawDescription: How make a singleton using Python?

description: How make a singleton using Python


rawDescription: pass stryng between two python scripts

description: Pass stryng between two python scripts


code:
class Bank(models.Model):

    ...

    def __unicode__(self):
        return unicode(self.name)

rawDescription: How to use ForeignKey field in Django Model

description: Use ForeignKey field in Django Model


rawDescription: Sort by a value in a many to one field with a django queryset?


code:
# spawn only if i am worker 1
if uwsgi.worker_id() == 1: spawn()

rawDescription: Only one instance of background task in uWSGI and gevent environment


code:
def ShowReportWidget(self):
    self.f = QtGui.QWidget()
    self.ReportWidget = ReportWidget(self)
    self.ReportWidget.setupUi(self.f)
    self.f.exec_()

class ReportWidget(QtGui.QWidget):
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self,parent)

    def setupUi(self,Widget):
        self.ui = rw.Ui_ReportWidget()
        self.ui.setupUi(Widget)

rawDescription: How to call a QWidget from another QWidget in PyQt

description: Call a QWidget from another QWidget in PyQt


rawDescription: control flow for loops that identify chapters in a book

description: Control flow for loops that identify chapters in a book


code:
sublist = [[a[0], a[1]] for a in list]
subarray = [a[2] for a in list]

rawDescription: How to divide a 2D list into one 2D list and one array (remove the last column)

description: Divide a 2D list into one 2D list and one array (remove the last column)


code:
import cv2
import numpy as np

im = cv2.imread('holes2.jpg')

gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
gray=cv2.threshold(gray,20,255,cv2.THRESH_BINARY)[1]
cv2.imshow('gray',gray)

contours,hierarchy = cv2.findContours(gray,cv2.RETR_LIST ,cv2.CHAIN_APPROX_SIMPLE   )

for cnt in contours:
    area = cv2.contourArea(cnt)
    if area<400:
        cv2.drawContours(im,[cnt],0,(255,0,0),2)

cv2.imshow('im',im)
cv2.waitKey()

rawDescription: Python opencv - Trouble detecting tiny "holes" (circles)


code:
cherrypy.tree.mount(...)
cherrypy.tree.mount(...)
cherrypy.tree.mount(...)
application = cherrypy.tree

rawDescription: cherrypy.tree.mount and mod_wsgi

description: Cherrypy.tree.mount and mod_wsgi


code:
for item in your_list[:n]:
    ...

rawDescription: How to iterate over the first n elements of a list?

description: Iterate over the first n elements of a list


code:
raw_matches = re.finditer('(([0-9a-f]{2}[:-]){5}[0-9a-f]{2})', line)
if raw_matches:
        matches = []
        for match in raw_matches:
                matches.append(match)

rawDescription: user = matches[1] object has no attribute '_getitem_' Python errorr

description: User = matches[1] object has no attribute '_getitem_' Python errorr


code:
# Get xy_cond equivalent after extending dimensions of basic_pts to a 2D array
# version by "pushing" separately col-0 and col-1 to axis=0 and creating a
# singleton dimension at axis=1.
# Compare these two extended versions with col-1 of new_pts.
xyc = (basic_pts[:,0,None] > new_pts[:,1]) & (basic_pts[:,1,None] > new_pts[:,1])

# Create mask equivalent and index into new_pts to get selective rows from it
mask = ~(xyc).any(0)
res_pts_out = new_pts[mask]

rawDescription: Compare numpy arrays of different sizes

description: Compare numpy arrays of different sizes


rawDescription: Mapping JSON Data to Python Keyword Arguments


code:
ping = os.stat('/bin/ping')
ping.st_mode & stat.S_ISUID
echo = os.stat('/bin/echo')
echo.st_mode & stat.S_ISUID

rawDescription: Check if a file is setuid root in Python


code: unicodedata.category(u'ą')[0] in 'LNPS'

rawDescription: python curses.ascii depending on locale?

description: Python curses.ascii depending on locale


cmd:
python
-u
main.py
--args1 --args2

rawDescription: SublimeText: Define a run configuration

description: SublimeText: Define a run configuration


code:
def factorial(x):
    n = 1   # this will store the factorial value
    while x > 0:
        n = n*x
        x -= 1
    return n

rawDescription: Calculating factorials with Python

description: Calculating factorials with Python


code:
from lxml import etree
class DTDResolver(etree.Resolver):
    def resolve(self, url, id, context):
        print("Resolving URL '%s'" % url)
        return self.resolve_string(
            '<!ENTITY myentity "[resolved text: %s]">' % url, context)

rawDescription: python lxml: import XSD from a buffer?

description: Python lxml: import XSD from a buffer


code:
url_list = ["cat", "dog", "mouse"]

for url in url_list:
    driver.get("https://www.google.com/webhp?hl=en#hl=en&q=" + url)
    # do stuff

rawDescription: Insert different variable (pulled from dictionary) into URL within a loop


code:
def process(infile, outfile, keywords):
    '''Search through inputfile whatever is between a pair startkeyword (excluded)
and endkeyword (included). Each chunk if copied to outfile and followed with
an empty line.
infile and outfile are strings representing file paths
keyword is an iterable containing pairs (startkeyword, endkeyword)

Raises an exception if  an endkeyword is not found before end of file

Returns a list of lists [ startkeyword, endkeyword, nb of occurences]'''
    keys = [ [k[0], k[1], 0] for k in keywords ]
    endk = None
    with open(infile, "r") as fdin:
        with open(outfile, "w") as fdout:
            for line in fdin:
                if endk is not None:
                    fdout.write(line)
                    if line.find(endk) >= 0:
                        fdout.write("\n")
                        endk = None
                else:
                    for k in keys:
                        index = line.find(k[0])
                        if index >= 0:
                            fdout.write(line[index + len(k[0]):].lstrip())
                            endk = k[1]
                            k[2] += 1
    if endk is not None:
        raise Exception(endk + " not found before end of file")
    return keys

rawDescription: Search text file for multiple strings and print out results to a new text file


code:
def process_packets():
    pkts = rdpcap(infile)
    cooked=[]
    timestamp = 1234567890.000000
    for p in pkts:
        p.time = timestamp
        timestamp += 0.000001
        pmod=p
        cooked.append(pmod)
    wrpcap("dump.pcap", cooked)

rawDescription: Increment PCAP timestamp values

description: Increment PCAP timestamp values


code:
logger = logging.getLogger()
handler = logging.handlers.RotatingFileHandler(logfile, maxBytes=2000000,
                                               backupCount=5)
formatter = logging.Formatter(fmt='%(asctime)s %(name)s %(levelname)s %(message)s',
                              datefmt='%y%m%d-%H:%M:%S')
handler.setFormatter(formatter)
handler.setLevel(logging.DEBUG)
logger.addHandler(handler)

rawDescription: Global Python Logger with file Rotator

description: Global Python Logger with file Rotator


code:
import base64
import lxml.etree
text = "<attack_headline><site_id>1</site_id><category>U1FMIEluamVjdGlvbg==</category><subcategory>Q2xhc3NpYyBTUUwgQ29tbWVudCAmcXVvdDstLSZxdW90Ow==</subcategory><client_ip>192.168.1.102</client_ip><date>1363807248</date><gmt_diff>0</gmt_diff><reference_id>E711-3EFB-5F43-5FAC</reference_id></attack_headline>"
xml = lxml.etree.fromstring(text)
for tag_with_base64 in ('category','subcategory'):
    node = xml.find(tag_with_base64)
    if node:
        node.text = base64.b64decode(node.text)
lxml.etree.tostring(xml)

rawDescription: Base64 decode a section of a string using re and base64 modules


rawDescription: Python httplib2 is not working for authenticated resource


code:
lst = [('first', 1), ('second', 2), ('third', 3)]
dict(lst)

rawDescription: Python Ordered Dictionary to regular Dictionary


code:
w, h = 300, 200
blockSize = 20
totalList = []

for xStart in xrange(0, w, blockSize):
    xEnd = min(xStart+blockSize, w)
    for yStart in range(0, h, blockSize):
        yEnd = min(yStart+blockSize, h)
        partCoords = [(x,y) for x in xrange(xStart, xEnd) for y in xrange(yStart, yEnd)]
        totalList.append(partCoords)

rawDescription: List of coordinate pairs from an array in 20 x 20 chunks


rawDescription: Is it possible to increment a slice of a list in Python?


code:
l = [np.arange(10).reshape((5,2)) for i in range(10)]
np.array(l).shape

rawDescription: Converting list of 2-D arrays into a 3-D array, adding elements along "fast" axes


code:
from sqlalchemy.orm import aliased

agent = aliased(User, name='agent')
manager = aliased(User, name='manager')
DBSession.query(
        agent.name, manager.name, MyStats.kpi_one, MyStats.kpi_two
    ).filter(
        agent.id == MyStats.agent,
        manager.id == MyStats.manager
    )

rawDescription: Querying the same table more than once in SQLAlchemy


code:
import Tkinter
import threading
import matplotlib.backends.backend_tkagg

root = Tkinter.Tk()

class Plotter():
    def __init__(self,fig):
        t = threading.Thread(target=self.PlottingThread,args=(fig,))
        t.start()

    def PlottingThread(self,fig):
        canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(fig, master=root)
        canvas.show()
        canvas.get_tk_widget().pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)

        toolbar = matplotlib.backends.backend_tkagg.NavigationToolbar2TkAgg(canvas, root)
        toolbar.update()
        canvas._tkcanvas.pack(side=Tkinter.TOP, fill=Tkinter.BOTH, expand=1)

        Tkinter.mainloop()

if __name__ == "__main__":
    import time

    fig1 = matplotlib.figure.Figure(figsize=(5,4), dpi=100)
    fig1.gca().plot([1,2,3])
    fig2 = matplotlib.figure.Figure(figsize=(5,4), dpi=100)
    fig2.gca().plot([3,2,1])

    #Shows fig1 and not fig2, just like it's supposed to
    Plotter(fig1)

    time.sleep(1)

    #I can still plot to fig1 from my main thread
    fig1.gca().clear()
    fig1.gca().plot([5,2,7])
    fig1.canvas.draw()

rawDescription: Creating a matplotlib interactive plotting window for an existing figure


code:
latin1 = "latin-1"
japanese = "Shift-JIS"

control_l = "\x0c"
control_j = "\n"

encodingMap = {
    control_l: latin1,
    control_j: japanese}

def funkyDecode(s, initialCodec=latin1):
    output = u""
    accum = ""
    currentCodec = initialCodec
    for ch in s:
        if ch in encodingMap:
            output += accum.decode(currentCodec)
            currentCodec = encodingMap[ch]
            accum = ""
        else:
            accum += ch
    output += accum.decode(currentCodec)
    return output

rawDescription: Dealing with a string containing multiple character encodings


code:
class Type(db.Model):
    id           = db.Column(db.Integer, primary_key=True)
    name         = db.Column(db.String(50), nullable=False, unique=True, index=True)
    area_id      = db.Column(db.Integer, db.ForeignKey("area.id", onupdate='CASCADE', ondelete='SET NULL'), index=True)
    description  = db.Column(db.Text)

class Area(db.Model):
    id           = db.Column(db.Integer, primary_key=True)
    name         = db.Column(db.String(50), nullable=False, unique=True, index=True)
    description  = db.Column(db.Text)
    types = db.relationship('Type', backref='Area', lazy='dynamic')

rawDescription: flask-admin imposes required attribute on relationship

description: Flask-admin imposes required attribute on relationship


code:
import re

# Build a dictionary of replacements:
with open('File 1') as f:
    repl = dict(line.split() for line in f)

# Read in the file and make the replacements:
with open('File 2') as f:
    data = f.read()
data = re.sub(r'(\d+):',lambda m: repl[m.group(1)]+':',data)

# Write it back out:
with open('File 2','w') as f:
    f.write(data)

rawDescription: I need to replace a string in one file using key value paris from another file


code:
with mock.patch.object(Parent, 'test_method') as mock_method:
    child = Child()
    mock_param = mock.Mock()
    child.test_method(mock_param)
    mock_method.assert_called_with(mock_param)

rawDescription: How to mock a base class's method when it was overridden?

description: Mock a base class's method when it was overridden


code:
file_content = set([line.rstrip() for line in file_handler])
only_in_platform = set(platform_specific_req).difference(file_content)

rawDescription: How do I start reading a file from the top in python?

description: Start reading a file from the top in python


code:
class Location(object):
    def __init__(self, lat, lng):
        self.coordinates = [lat, lng]

loc = Location(33.5206608, -86.80249)
latlong = [loc]

print(latlong[0].coordinates[0])

rawDescription: What is this terminology referring to: "latlong[0].coordinates[0]"? from Google Geocoder.geocode response


code:
def search_date(lines):
    lista = [line.decode('utf8').split(",", 1)[0] for line in lines]

rawDescription: Python/Django - Bytes back to string

description: Python/Django - Bytes back to string


code:
import csv

f = file("file.csv", 'a')
csv_writer = csv.writer(f)

my_record = ["This", "is", "a", "row", "of", "data"]

csv_writer.writerow(my_record)

rawDescription: Append new data to a .csv?

description: Append new data to a .csv


code:
DataFrame(np.random.randn(10,10)).to_hdf('test.h5','df',mode='w',format='table')
store = pd.HDFStore('test.h5')
store
store.get_storer('df').nrows

rawDescription: Peek the number of rows in an hdf5 file in pandas


code:
connection = sqllite3.connect('test.sqlite')
cursor = connection.execute('select * from abc')
names = list(map(lambda x: x[0], cursor.description))

rawDescription: Python Sqlite, not able to print first line


code:
bins = np.linspace(0, 1, 10)
v1 = cdf_a(bins)
v2 = cdf_b(bins)

rawDescription: Getting CDF of variable-sized numpy arrays in Python using same bins?


rawDescription: How do I update 0.0.0.0:5000 to show changes in app.py on foreman, ubuntu

description: Update 0.0.0.0:5000 to show changes in app.py on foreman, ubuntu


code:
from collections import Counter
Counter([d.rsplit('-',1)[0] for d in date_list])

rawDescription: Get count of string obj in list by substring


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

from os.path import join, isdir

Builder.load_string("""
<MyWidget>:
    FileChooserListView:
        filters: [root.is_dir]
""")

class MyWidget(BoxLayout):
    def is_dir(self, directory, filename):
        return isdir(join(directory, filename))

class MyApp(App):
    def build(self):
        return MyWidget()

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

rawDescription: Kivy FileChooser: List only directories

description: Kivy FileChooser: List only directories


code:
pylab.plot(xarr, yarr, label='data')
pylab.plot(xarr,func(xarr, *popt), label='curve_fit')
ap, bp, cp = 2.22726000005, 0.1073, 2.68937000008
pylab.plot(xarr,func(xarr, ap,bp,cp), label='supplied a,b,c')
pylab.legend()
pylab.show()

rawDescription: Scipy.optimize.curvefit log function

description: Scipy.optimize.curvefit log function


code:
prob2 = np.zeros((len(probabilities), 2))
prob2[:,0] = 1 - probabilities
prob2[:,1] = probabilities

rawDescription: sklearn decision_function with 2 or more classes

description: Sklearn decision_function with 2 or more classes


code:
from appscript import *
map(lambda x: x.title(), app('Google Chrome').windows[0].tabs())

rawDescription: List of open browser tabs programmatically


code:
import re
s = "These are the words in a sentence"
regex = re.compile('are|words')
[(m.start(0),m.group()) for m in re.finditer(regex,s)]

rawDescription: Determine which fragment of an OR regex matched with the string


code:
from __future__ import print_function
import csv

with open('test_list.txt', 'r') as f: # with statement ensures your file is closed
    primary_set = set(line.strip() for line in f)

with open('test.csv', 'rb') as f: #### see note below ###
    for row in csv.reader(f): # delimiter=',' is the default
        print(sum(i in primary_set for i in row)) # i in primary_set has int value 0 or 1

rawDescription: Reading csv file and compare objects to a list


code:
if self.steps.current == "form1":
    data = self.request.POST["form1-response"]
    user = CustomerModel.objects.get(id=self.request.user.id)
    user.response = data
    user.form_step = "form1"
    user.save()

rawDescription: Save form data on every step using Django FormWizard


code: [ item for item in lst if not any(char.isdigit() for char in item) ]

rawDescription: Python: remove item from list if item has a number


code:
import re

# a partial table of atomic weights, replace with something better!
weights = { "H" : 1,  "Na": 11, "Mg": 12, "C" : 12, "N" : 14,
            "O" : 16, "F" : 19, "Al": 27, "S" : 32, "Cl": 35,
      }

def molecularWeight(formula):
    matches = re.findall(r"([A-Z][a-z]?)([0-9]*)", formula)
    return sum(weights[symbol] * (int(count) if count else 1)
               for (symbol, count) in matches)

rawDescription: Using a list to divide and store a string to be used in a variable


code:
import urllib, urllib2

def steam_login(username,password):
    data = urllib.urlencode({
      'action': 'doLogin',
      'goto': '',
      'steamAccountName': username,
      'steamPassword': password,
    })
    request = urllib2.Request('https://steamcommunity.com/',data)
    cookie_handler = urllib2.HTTPCookieProcessor()
    opener = urllib2.build_opener(cookie_handler)
    response = opener.open(request)
    if not 200 <= response.code < 300:
        raise Exception("HTTP error: %d %s" % (response.code,response.msg))
    else:
        return cookie_handler.cookiejar

rawDescription: How to recreate this PHP code in Python?

description: Recreate this PHP code in Python


code:
import wx
import matplotlib
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.NewId(), "Main")
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)

        self.figure = Figure(figsize=(1,2))
        self.axe = self.figure.add_subplot(111)
        self.figurecanvas = FigureCanvas(self, -1, self.figure)
        self.valueCtrl = wx.TextCtrl(self, -1, "")
        self.buttonPlot = wx.Button(self, wx.NewId(), "Plot")

        self.sizer.Add(self.figurecanvas, proportion=1, border=5, flag=wx.ALL | wx.EXPAND)
        self.sizer.Add(self.buttonPlot, proportion=0, border=2, flag=wx.ALL)
        self.sizer.Add(self.valueCtrl, proportion=0, border=2, flag=wx.ALL)
        self.SetSizer(self.sizer)
        self.buttonPlot.Bind(wx.EVT_BUTTON, self.on_button_plot)

    def on_button_plot(self, evt):
        self.figure.set_canvas(self.figurecanvas)
        self.axe.clear()
        self.axe.plot(range(int(self.valueCtrl.GetValue())), color='green')
        self.figurecanvas.draw()

class MyApp(wx.App):
    def OnInit(self):
        frame = MainFrame()
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

app = MyApp(0)
app.MainLoop()

rawDescription: wxPython Refresh a plot with another graph by a button event

description: WxPython Refresh a plot with another graph by a button event


code:
from itertools import permutations

# number of lists may vary (>= length of lists)
list1 = ["l11", "l12", "l13"]
list2 = ["l21", "l22", "l23"]
list3 = ["l31", "l32", "l33"]
list4 = ["l41", "l42", "l43"]
lists = [list1, list2, list3, list4]

# lenths of lists must be the same and will be the size of outputs
size = len(lists[0])
for subset in permutations(lists, size):
    print([sublist[item_i] for item_i, sublist in enumerate(subset)])

rawDescription: All combinations of lists using unique indexes in Python


code:
import ctypes
drive_name = "PhysicalDrive1"
target = (ctypes.c_wchar * 32768)(); # Creates an instance of a character array
target_len = ctypes.windll.kernel32.QueryDosDeviceW(drive_name, target, len(target))
if not target_len:
     print("The device does not exist")
else:
     print("The device exists")

rawDescription: How to check if a Raw(unmounted) Windows Drive exists in Python

description: Check if a Raw(unmounted) Windows Drive exists in Python


code:
from time import time

def index():
    # THE REST OF YOUR CODE GOES HERE
    start = time.time()
    resp = template.render(message=message)
    end = time.time()
    processing_time = end - start
    # LOG PROCESSING TIME SOMEPLACE
    return resp

rawDescription: Flask + Jinja2: how to measure performances


code:
zones = DeliveryZones.objects.filter(zone='SOME_NAME', is_active=True)
restaurants = get_list_or_404(
    Restaurant, is_active=True,
    service_type='SOME_GIVEN_SERVICE_TYPE_NAME',
    delivery_zones__in=zones
)

rawDescription: Django 1.9 Find object in list that has attribute equal to some value


code:
#!/usr/bin/env python

import sys
import dbus
from PyQt4.QtGui import QApplication
from dbus.mainloop.qt import DBusQtMainLoop

class DBus_Answer():
    def __init__(self, text):
        self.answer = text
        bus_loop = DBusQtMainLoop(set_as_default=True)
        self.bus = dbus.SessionBus()
        self.bus.add_signal_receiver(self.my_func,
                                     dbus_interface="im.pidgin.purple.PurpleInterface",
                                     signal_name="ReceivedImMsg")

    def my_func(self, account, sender, message, conversation, flags):
        obj = self.bus.get_object("im.pidgin.purple.PurpleService", "/im/pidgin/purple/PurpleObject")
        purple = dbus.Interface(obj, "im.pidgin.purple.PurpleInterface")
        purple.PurpleConvImSend(purple.PurpleConvIm(conversation), self.answer)

app = QApplication(sys.argv)
run = DBus_Answer("Slam")
app.exec_()

rawDescription: Using DBus in python program

description: Using DBus in python program


code:
import urllib, urllib2
url = 'http://db.systemsbiology.net/gestalt/cgi-pub/Kaviar.pl'
form_data = {'chr':'chr1', 'pos':'46743'} # the form takes 2 parameters: 'chr', and 'pos'
                                          # the values given in the dict are
                                          # just examples.
# the next line POSTs the form to url, and reads the resulting response (HTML
# in this case) into the variable response
response = urllib2.urlopen(url,urllib.urlencode(form_data)).read()
# now you can happily parse response.

rawDescription: Best way to submit data to a form using Python?

description: Submit data to a form using Python


code:
import wx
import time
import serial
out = serial.Serial("COM5", 9600)

def arduino_on(event):
    byte = 102
    time.sleep(3)
    out.write(chr(byte))
    print("I received: ")
    print(chr(byte))
    print("LED should be on!\n")

def arduino_off(event):
    byte = 97
    time.sleep(3)
    out.write(chr(byte))
    print("I received: ")
    print(chr(byte))
    print("LED should be off!\n")

app = wx.PySimpleApp()

frame1 = wx.Frame(None, -1, size=(240, 100))
frame1.SetTitle("Arduino Communicator v. 0.1")
button1 = wx.Button(frame1, -1, "LED On")
button2 = wx.Button(frame1, -1, "LED off")
button1.Bind(wx.EVT_BUTTON, arduino_on)
button2.Bind(wx.EVT_BUTTON, arduino_off)
sizer1 = wx.GridBagSizer(vgap = 3, hgap = 3)
sizer1.Add(button1, (1,0), (1, 1), wx.ALIGN_CENTER)
sizer1.Add(button2, (1,1), (1, 1), wx.ALIGN_CENTER)
frame1.SetSizer(sizer1)
frame1.Show()
app.MainLoop()

rawDescription: GUI in Python doesn't work reliably with Arduino without time.sleep(3)


code:
class RackWidget(RelativeLayout):

    def __init__(self, game, **kwargs):
        super(RackWidget, self).__init__(**kwargs)
        print("TileRackWidget pos:", self.pos)

        x, y = 0, 0
        for symbol in game.symbols:
            tileWidget = TileWidget(symbol=symbol, pos= (x,y))
            self.add_widget(tileWidget)
            print("tileWidget pos:", tileWidget.pos)
            x+=50

rawDescription: Kivy layout positioning problems - not understanding/properly using __init__, kv, kv properties


code:
import subprocess
cmd = ["cacls",  "E:/" + list1[2], list1[3], "/p", str]

pro = subprocess.Popen(final, stdin=subprocess.PIPE)
pro.communicate("y\r\n")

rawDescription: Python code to send command through command line


code:
sql=('UPDATE results SET '
     + ', '.join(key+' = ?' for key in keys)
     + 'WHERE id = ?')
args = [results[key] for key in keys] + [id]
cur.execute(sql,args)

rawDescription: Sqlite db, multiple row updates: handling text and floats


code:
def model(t, params):

    y0, h, A1, x1, s1, A2, x2, s2, A3, x3, s3, A4, x4, s4 = [value for value in params]

    y = y0 + h * (
                  A1 * (0.5 + 0.5 * erf((t - x1) / (s1 * 2**0.5))) +
                  A2 * (0.5 + 0.5 * erf((t - x2) / (s2 * 2**0.5))) +
                  A3 * (0.5 + 0.5 * erf((t - x3) / (s3 * 2**0.5))) +
                  A4 * (0.5 + 0.5 * erf((t - x4) / (s4 * 2**0.5)))
                 )

    return y

def sum_residuals(params):  # the function we want to minimize

    y0, h, A1, x1, s1, A2, x2, s2, A3, x3, s3, A4, x4, s4 = [value for value in params]

    return sum((list_y - model(list_x, params))**2)

def constraints(params):

    y0, h, A1, x1, s1, A2, x2, s2, A3, x3, s3, A4, x4, s4 = [value for value in params]

    return 1 - (A1 + A2 + A3 + A4)

pfit = scimin.fmin_slsqp(sum_residuals,
                         p0,
                         f_eqcons=constraints,
                         bounds=bounds,
                         iprint=0,
                         iter=300
                        )

rawDescription: lmfit: maximum recursion depth exceeded

description: Lmfit: maximum recursion depth exceeded


code:
input_num = '781623954'
next_num = int(input_num) + 1
input_digits = set(input_num)
found = False
while not found:
    next_num += 1
    next_digits = set(str(next_num))
    found = len(next_digits) == 9 and input_digits == next_digits
    if next_num > 987654321:
        break

if found:
    print(next_num)
else:
    print("No number was found.")

rawDescription: Switch indexes, create the next highest number using the same exact 9 digits presented


code:
label = Gtk.Label()
label.set_use_markup(True)
label.set_markup("<big>This is bigger text</big>")

rawDescription: PyGTK object that displays text

description: PyGTK object that displays text


code:
b2 = {x for n,x in b}
c = {(n,x) for (n,x) in a if x not in b2}
c

rawDescription: Difference of two sets of tuples in Python


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

import wx

class Example(wx.Frame):

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

        self.InitUI()

    def InitUI(self):

        pnl = wx.Panel(self)
        pnl.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        pnl.SetFocus()

        self.SetSize((250, 180))
        self.SetTitle('Key event')
        self.Centre()
        self.Show(True)

    def OnKeyDown(self, e):

        key = e.GetKeyCode()

        if key == wx.WXK_ESCAPE:

            ret  = wx.MessageBox('Are you sure to quit?', 'Question',
                wx.YES_NO | wx.NO_DEFAULT, self)

            if ret == wx.YES:
                self.Close()

def main():

    ex = wx.App()
    Example(None)
    ex.MainLoop()

rawDescription: wx python windows can't hide my MenuBar

description: Wx python windows can't hide my MenuBar


code:
import csv

with open('name_of_file') as f:
    reader = csv.reader(f)
    next(reader) # skips the first line, the header
    for row in reader:
       print(row[0]) # The first column

rawDescription: removing entries in a column of data, python

description: Removing entries in a column of data, python


code:
from PySide import QtGui, QtCore
import sys

class MainWindow(QtGui.QWidget):

    def __init__(self):
        super().__init__()

        layout = QtGui.QHBoxLayout()
        self.setLayout(layout)

        label = QtGui.QLabel('5')
        label.setAutoFillBackground(True)
        p = label.palette()
        p.setColor(label.backgroundRole(), QtCore.Qt.red)
        label.setPalette(p)
        layout.addWidget(label)

        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: PySide QLabel doesn't fill the available height


code:
with open('file.txt','w') as file:
    for item in List:
        print>>file, item

rawDescription: I'm trying to export a Python list to a .txt file, but the text file ends up having too few lines


code:
from threading import Lock

class Counter(object):
    def __init__(self):
        self.value = 0
        self.lock = Lock()

    def incr(self, x):
        with self.lock:
            self.value += 1

rawDescription: Can I implement a counter for multiprocessing using pool callback?

description: Implement a counter for multiprocessing using pool callback


rawDescription: Copy out results after submitting web form using Selenium (Python)


code:
import re

count('aaacodebbb')
count('codexxcode')
count('cozexxcope')

rawDescription: Strategies for searching through strings in python?


code:
import matplotlib.pyplot as plt
from matplotlib.dates import date2num , DateFormatter
import datetime as dt

 # different times from the same timespan
TA = map(lambda x: date2num(dt.datetime(2015, 6, 15, 12, 1, x)),
         range(1, 20, 5))
TB = map(lambda x: date2num(dt.datetime(2015, 6, 15, 12, 1, x)),
         range(1, 20, 3))
A = [1.2, 1.1, 0.8, 0.66]
B = [1.3, 1.2, 0.7, 0.5, 0.45, 0.4, 0.3]

fig, ax = plt.subplots()
ax.plot_date(TA, A, 'b--')
ax.plot_date(TB, B, 'g:')
ax.xaxis.set_major_formatter(DateFormatter('%H:%M:%S'))
plt.show()

rawDescription: How can I plot two different spaced time series on one same plot in Python

description: Plot two different spaced time series on one same plot in Python


code:
q = Queue.Queue()
result = {}  # used to store the results
for fileName in fileNames:
  q.put(fileName)

def worker():
  while True:
    fileName = q.get()
    if fileName is None:  # EOF?
      return
    subprocess_stuff_using(fileName)
    wait_for_finishing_subprocess()
    checksum = collect_md5_result_for(fileName)
    result[fileName] = checksum  # store it

threads = [ threading.Thread(target=worker) for _i in range(20) ]
for thread in threads:
  thread.start()
  q.put(None)  # one EOF marker for each thread

rawDescription: Python: running subprocess in parallel

description: Python: running subprocess in parallel


code:
buffer = BytesIO()
imsave(buffer, rgb)
encoded_png = buffer.getbuffer()

#and then my class derived from BaseHTTPRequestHandler can transmit it as the response to a GET
self.send_response(200)
self.send_header("Content-Type", "image/png")
self.end_headers()

self.wfile.write(encoded_png)
return

rawDescription: Using python how do I convert an RGB array to an encoded image suitable for transmission via HTTP?


rawDescription: Query Python dictionary to get value from tuple


code:
keep_phrases = ["ACCESSION", "haplogroup", "locality"]
remove_phrases = ['codon', 'TAA']

stuff_to_write = []
with open('C:/a.txt') as f:
    for line in f.readlines():
        if any(phrase in line for phrase in keep_phrases):
            do_not_write = False
            if 'note' in line:
                if any(phrase in line.split('note')[1] for phrase in remove_phrases):
                    do_not_write = True
            if not do_not_write:
                stuff_to_write.append(line)

with open('C:/b.txt','w') as f:
    f.write('\r\n'.join(stuff_to_write))

rawDescription: Extracting lines from txt file with Python


code:
import zipfile

fh = open(targetzip, 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
    z.extract(name, extractto)
fh.close()

rawDescription: A simple Script to extracting a zip file


code:
def file_len(fname):
    with open(fname) as f:
        for line in f:
            if line.strip() == "{A   B}":
                break
        return sum(1 for line in f)

rawDescription: How to count number of lines after a certain line

description: Count number of lines after a certain line


code:
import Tkinter
import Image, ImageTk
root = Tkinter.Tk()
label = Tkinter.Label(root)
def change_image(image):
    photoimage = ImageTk.PhotoImage(image)
    label.config(image=photoimage)
root.mainloop()

rawDescription: Displaying a sequence of PIL images with Tkinter


code: lines = sys.stdin.readlines()

rawDescription: Why can't I do a loop in sys.stdin two times in a row ? (Python)


code:
def value_to_db_time(self, value):
    if value is None:
        return None

    # MySQL doesn't support tz-aware times
    if timezone.is_aware(value):
        raise ValueError("MySQL backend does not support timezone-aware times.")

    # MySQL doesn't support microseconds
    return six.text_type(value.replace(microsecond=0))

rawDescription: django drops milliseconds during saving in admin form

description: Django drops milliseconds during saving in admin form


code:
s = set(L1)
new_list = [a for a in L2 if any(b in s for b in a)]

rawDescription: python: Searching strings in one list in another list, then appending an entire list entry to a new list

description: Python: Searching strings in one list in another list, then appending an entire list entry to a new list


code:
def findNodes(nodes):
    def traverse(ns):
        if not ns:
            return ''

        ret = ['
']
        for child in ns:
            ret.extend(['
', traverse(child.Children), '
'])
        ret.append('
')
        return ''.join(ret)

    return traverse(nodes)

rawDescription: Python: traverse tree adding html list (ul)


code:
class Container(object):
    def __init__(self):
        self.thing = A()
    def change(self):
        self.thing = B()
    def hi(self):
        self.thing.hi()

test = Container()
test.hi() # prints A
test.change()
test.hi() # prints B

rawDescription: Python change object reference from object itself


code: ax.text(x, y, label, gid='foo')

rawDescription: python, matplotlib, svg and hyperlinks in text labels

description: Python, matplotlib, svg and hyperlinks in text labels


code:
customClassInst = self.parent()
while customClassInst is not None and type(customClassInst) != CustomClass:
    customClassInst = customClassInst.parent()

rawDescription: PySide get QObject's parent anywhere in its hierarchy


code:
for i in range(len(list_)):
    Foo(list_[:i] + list_[i+1:])

rawDescription: Can Python slicing be used to skip one specific element by index?


code:
pattern = '(David Maxwell|David|Maxwell).*(educated at|graduated from|attended|studied at|graduate of).*Eton College'
str = "David Maxwell was educated at Eton College, where he was a King's Scholar and Captain of Boats, and at Cambridge University where he rowed in the winning Cambridge boat in the 1971 and 1972 Boat Races."
re.search(pattern, str)

rawDescription: python reg-ex pattern not matching

description: Python reg-ex pattern not matching


code:
for t in threads:
    t.join()

rawDescription: How to block the main thread until all the other threads finish executing?

description: Block the main thread until all the other threads finish executing


rawDescription: Get only URL from string - Python

description: Get only URL from string - Python


code:
import numpy as np

def on_xlim_changed(ax):
    xlim = ax.get_xlim()
    for a in ax.figure.axes:
        # shortcuts: last avoids n**2 behavior when each axis fires event
        if a is ax or len(a.lines) == 0 or getattr(a, 'xlim', None) == xlim:
            continue

        ylim = np.inf, -np.inf
        for l in a.lines:
            x, y = l.get_data()
            # faster, but assumes that x is sorted
            start, stop = np.searchsorted(x, xlim)
            yc = y[max(start-1,0):(stop+1)]
            ylim = min(ylim[0], np.nanmin(yc)), max(ylim[1], np.nanmax(yc))

        # TODO: update limits from Patches, Texts, Collections, ...

        # x axis: emit=False avoids infinite loop
        a.set_xlim(xlim, emit=False)

        # y axis: set dataLim, make sure that autoscale in 'y' is on
        corners = (xlim[0], ylim[0]), (xlim[1], ylim[1])
        a.dataLim.update_from_data_xy(corners, ignore=True, updatex=False)
        a.autoscale(enable=True, axis='y')
        # cache xlim to mark 'a' as treated
        a.xlim = xlim

for ax in fig.axes:
    ax.callbacks.connect('xlim_changed', on_xlim_changed)

rawDescription: matplotlib linked x axes with autoscaled y axes on zoom

description: Matplotlib linked x axes with autoscaled y axes on zoom


code:
SPECIES = []
'''An automatically generated list of the available species types.'''

def _do_import():
    '''Automatically populates SPECIES with all the modules in this
    folder.

    :Note:
        Written as a function to prevent local variables from being
        imported.
    '''
    import os

    for _, _, files in os.walk(__path__[0]):
        for filename in (file for file in files if file[0] != '_' and file[-3:] == '.py'):
            modname = filename[:filename.find('.')]
            mod = __import__(modname, globals(), fromlist=[])
            for cls in (getattr(mod, s) for s in dir(mod)):
                if cls is not Species and type(cls) is type and issubclass(cls, Species):
                    if getattr(cls, '_include_automatically', True):
                        SPECIES.append(cls)
                        globals()[cls.__name__] = cls

_do_import()

rawDescription: How does one create an extension loader in Python?

description: Create an extension loader in Python


code:
s = pd.Series(range(10,20))
s
val_mask = s == 13
val_mask
s[val_mask]
s[val_mask].index

rawDescription: Finding index of a pandas DataFrame value


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

# datasets to treat
t1 = [2,6,7,8,10,13,14,16,17]
X1 = [10,10,10,20,20,20,30,30,30]

t2 = [3,4,5,6,8,10,11,14,15,16]
X2 = [95,100,100,105,158,150,142,196,200,204]

X1Series = pd.Series(X1, index = t1)
X2Series = pd.Series(X2, index = t2)

X1Values = X1Series.drop_duplicates().values #returns all occuring values of X1 without duplicates as array

# lists for results
XNew = []
YNew = []

#find for every occuring value X1 the mean value of X2 in the range of X1
for value in X1Values:
    indexpos = X1Series[X1Series == value].index.values
    max_t = indexpos[indexpos.argmax()] # get max and min index of the range of X1
    min_t =indexpos[indexpos.argmin()]
    print("X1 = "+str(value)+" occurs in range from "+str(min_t)+" to "+str(max_t))
    slicedX2 = X2Series[(X2Series.index >= min_t) & (X2Series.index <= max_t)] # select range of X2
    print("in this range there are following values of X2:")
    print(slicedX2)
    mean = slicedX2.mean() #calculate mean value of selection and append extracted values
    print("with the mean value of: " + str(mean))
    XNew.append(value)
    YNew.append(mean)

fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

ax1.plot(t1, X1,'ro-',label='X1(t)')
ax1.plot(t2, X2,'bo',label='X2(t)')
ax1.legend(loc=2)
ax1.set_xlabel('t')
ax1.set_ylabel('X1/X2')

ax2.plot(XNew,YNew,'ro-',label='YNew(XNew)')
ax2.legend(loc=2)
ax2.set_xlabel('XNew')
ax2.set_ylabel('YNew')
plt.show()

rawDescription: Python merge datasets X1(t), X2(t) -> X1(X2)


code:
f=open('test.txt','w')
f.write(10*'a')
f.tell()
f.write(100*'a')
f.tell()

rawDescription: How do I limit a file size when writing to files in python

description: Limit a file size when writing to files in python


code:
import tornado.options
tornado.options.parse_config_file("/etc/server.conf")
tornado.options.parse_command_line()

rawDescription: Tornado application layout. Options.

description: Tornado application layout. Options.


rawDescription: Collect results from parallel Celery task executions


rawDescription: Lossy compression for video files before being uploaded on server (Django web app)


code:
import pymel.core as pc
pc.namespace(set = ":")         # just in case if there is any preset namespace

for obj in pc.ls(rn=False):     # Referenced objects cannot be renamed
    if "hello:" in obj:
        pc.rename(obj, obj.replace(":", "_"))

rawDescription: Changing namespace separator from colon(:) to underscore (_) in Maya


code:
# monkeypatch.py
import other_module
from other_module import func as orig_func
def replacement():
    do_stuff()
    orig_func()
    do_stuff()
other_module.func = replacement

rawDescription: Does monkey patching in Python affect direct imports?


code:
def hello(request):
    return render(request, "hello.html", {"name": "mike"})

rawDescription: Django Variable Template Tags

description: Django Variable Template Tags


code:
from __future__ import division

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

fig = plt.figure(figsize=plt.figaspect(1))  # Square figure
ax = fig.add_subplot(111, projection='3d')

r=1;
u=np.linspace(-2,2,200);
v=np.linspace(0,2*np.pi,60);
[u,v]=np.meshgrid(u,v);

a = 1
b = 1
c = 1

x = a*np.cosh(u)*np.cos(v)
y = b*np.cosh(u)*np.sin(v)
z = c*np.sinh(u)

ax.plot_surface(x, y, z,  rstride=4, cstride=4, color='b')

plt.show()

rawDescription: Plotting A Hyperboloid

description: Plotting A Hyperboloid


code:
s = input("Enter your string: ")
lowers = []

for word in s.strip().split():
    if not word.islower():
        print(word)
    else:
        lowers.append(word)

print('\n'.join(lowers))

rawDescription: Creating 2 lists from user input in python 3


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

h = plt.figure()
plt.plot(range(1,11), range(1,11), gid='dummy')
my_legend = plt.legend(['a line'])
plt.title('myfigure')  # not sure if this is the same as set(h, 'name', 'myfigure')
my_axis = plt.gca()
my_axis.set_xlim(0,5)
for p in set(h.findobj(lambda x: x.get_gid()=='dummy')):
    p.set_ydata(np.ones(10)*10.0)
plt.show()

rawDescription: what is the corresponding matplotlib code of this matlab code

description: What is the corresponding matplotlib code of this matlab code


code:
def some_function():

    def some_other_function():
        # code that does stuff
        pass

    # code that does stuff
    pass

rawDescription: Can we use 'local' in python as we can use 'local' in scheme?


code:
import time
import turtle
a = turtle.Turtle ()
x = 0
y = 10
factor = 0.55
while True:
    a.forward (y)
    x = factor * (x + y)
    a.left(90)
    a.forward (x)
    y = factor * (x + y)
    a.left (90)
    time.sleep (0.02)

rawDescription: How see more of FIbbonaci spiral in python?


code:
ld = pd.DataFrame(labeldict).T
ld.columns = ['color', 'size']
ld.index.name = 'label'
df.merge(ld.reset_index(), on='label')

rawDescription: Pandas: Assigning multiple *new* columns simultaneously


code: from gi.repository import WebKit2

rawDescription: Is there a webkit2 module for python?

description: Is there a webkit2 module for python


code: doc = SimpleDocTemplate(output, pagesize=(502*inch, 502*inch) )

rawDescription: Generating a pdf of long tables with reportlab


code:
def filetype(astring):
    mode = 'r' # or 'w' etc.
    try:
        f = open(astring, mode)
    except IOError:
        raise argparse.ArgumentError('')
    return f

rawDescription: Open compressed file directly with argparse


code:
import numpy as np
a = np.random.random((11, 13))
b = np.random.random((11, 13))
c = np.random.random((11, 13))

d = np.dstack([a,b,c])

d.shape

a[1,5], b[1,5], c[1,5]
d[1,5]

rawDescription: Combining 3 arrays in one 3D array in numpy


code:
from bokeh.io import curdoc
from bokeh.plotting import figure
import pandas as pd

p  = figure()

f = open('lines.csv', 'r')
cv = pd.read_csv(f)
df = pd.DataFrame(cv)
f.close()

X = df.x
Y = df.y
r1 = p.line(x=X, y=Y, line_width=2)
ds = r1.data_source

def update():
  f = open('lines.csv', 'r')
  cv = pd.read_csv(f)
  df = pd.DataFrame(cv)

  ds.data['x'] = df.x
  ds.data['y'] = df.y
  f.close()

curdoc().add_periodic_callback(update, 50)

rawDescription: Bokeh, can't use callback with CSV files


code:
@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])
def download(filename):
    uploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])
    return send_from_directory(directory=uploads, filename=filename)

rawDescription: Flask Download a File

description: Flask Download a File


code:
Code
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sls
from scipy.linalg.blas import ddot
import timeit

## Define inner product.
def l2_inner_blas( f, g, dx ):
    return ddot( f, g )*dx / np.pi

def l2_inner( f, g, dx ):
    return np.inner( f, g )*dx / np.pi

def l2_inner_trapz( f, g, dx ):
    return np.trapz(f*g,dx=dx) / np.pi

sin1 = lambda x: np.sin( x )
sin2 = lambda x: np.sin( 2.0 * x)

## Timing setups.
setup1 = "import numpy as np; from __main__ import l2_inner,"
setup1 += "l2_inner_trapz, l2_inner_blas, sin1, sin2;"
setup1 += "n=%d; x=np.linspace(-np.pi,np.pi,n); dx=2.0*np.pi/(n-1);"
setup1 += "f=sin1(x); g=sin2(x);"

def time( n ):
    setupstr = setup1 % n
    time1 = timeit.timeit( 'l2_inner( f, g, dx)', setupstr, number=10 )
    time2 = timeit.timeit( 'l2_inner_blas( f, g, dx)', setupstr, number=10 )
    time3 = timeit.timeit( 'l2_inner_trapz( f, g, dx)', setupstr, number=10 )
    return (time1, time2, time3)

setup2 = "import numpy as np; x = np.linspace(-np.pi,np.pi,%d);"
def time_eval( n ):
    setupstr = setup2 % n
    time_sin = timeit.timeit( 'np.sin(x)', setupstr, number=10 )
    time_sqrt = timeit.timeit( 'np.sqrt(x)', setupstr, number=10 )
    time_exp = timeit.timeit( 'np.exp(x)', setupstr, number=10 )
    return (time_sin, time_sqrt, time_exp)

## Perform timing for vector product.
times = np.zeros( (7,3) )
for i in range(7):
    times[i,:] = time( 10**(i+1) )

x = 10**np.arange(1,8,1)
f, ax = plt.subplots()
ax.set( xscale='log', yscale='log', title='Inner vs. BLAS vs. trapz', \
        ylabel='time [s]', xlabel='n')
ax.plot( x, times[:,0], label='numpy.inner' )
ax.plot( x, times[:,1], label='scipy.linalg.blas.ddot')
ax.plot( x, times[:,2], label='numpy.trapz')
plt.legend()

## Perform timing for function evaluation.
times_eval = np.zeros( (7,3) )
for i in range(7):
    times_eval[i,:] = time_eval( 10**(i+1) )

x = 10**np.arange(1,8,1)
f, ax = plt.subplots()
ax.set( xscale='log', yscale='log', title='sin vs. sqrt vs. exp', \
        ylabel='time [s]', xlabel='n')
ax.plot( x, times_eval[:,0], label='numpy.sin' )
ax.plot( x, times_eval[:,1], label='numpy.sqrt')
ax.plot( x, times_eval[:,2], label='numpy.exp' )
plt.legend()

## Test convergence.
def error( n ):
    x = np.linspace( -np.pi, np.pi, n )
    dx = 2.0 * np.pi / (n-1)
    f = np.exp( x )
    l2 = 0.5/np.pi*(np.exp(2.0*np.pi) - np.exp(-2.0*np.pi))
    err1 = np.abs( (l2 - l2_inner( f, f, dx )) / l2)
    err2 = np.abs( (l2 - l2_inner_blas( f, f, dx )) / l2)
    err3 = np.abs( (l2 - l2_inner_trapz( f, f, dx )) / l2)
    return (err1, err2, err3)

acc = np.zeros( (7,3) )
for i in range(7):
    acc[i,:] = error( 10**(i+1) )

x = 10**np.arange(1,8,1)
f, ax = plt.subplots()
ax.plot( x, acc[:,0], label='numpy.inner' )
ax.plot( x, acc[:,1], label='scipy.linalg.blas.ddot')
ax.plot( x, acc[:,2], label='numpy.trapz')
ax.set( xscale='log', yscale='log', title=r'$\langle \exp(x), \exp(x) \rangle$', \
        ylabel='Relative Error', xlabel='n')
plt.legend()

rawDescription: Calculating the L2 inner product in numpy?


code:
# here app is a Flask current application object
from flask import Request as FlaskRequest
from werkzeug.routing import Rule as FlaskRule

class Request(FlaskRequest):
    def is_foo(self):
        return bool(self.url_rule._foo) if self.url_rule else False

    def get_bar(self):
        return getattr(self.url_rule, '_bar')

class Rule(FlaskRule):
    def __init__(self, *args, **kwargs):
        for param in ('_foo', '_bar'):
            setattr(self, param, kwargs.pop(param, None))
        super().__init__(*args, **kwargs)

# app initialization
app.request_class = Request
app.url_rule_class = Rule

# route example
@app.route('/path', _foo=True, _bar='baz')
def route():
    pass

rawDescription: Bind some arbitrary value to route in Flask


code:
huge_object = Huge_Class()
x = huge_object
del huge_object
gc.collect() # does not free memory for the huge object

rawDescription: Does gc.collect release memory for variables that I've deleted?


code: [np.mean(a[max(i-6, 0):i+1,:], axis=0) for i in xrange(len(a))]

rawDescription: Create new array for average of previous 7 slices of numpy array


code:
a = np.empty((5,), dtype=object)
a
a[0] = []
a
a[0].append(4)
a

rawDescription: Initializing 2D array to hold a list in each location


code:
with open("testfile.txt") as infile:
    with open("outfile.txt",'w') as outfile:
        titleset = set()

        for line in infile:
            title =  line.split('|')[0]
            if title not in titleset:
                titleset.add(title)
                outfile.write(line)

rawDescription: Removing Duplicate Lines by Title Only

description: Removing Duplicate Lines by Title Only


rawDescription: BeautifulSoup: passing a function for ever tag and parsing text


code:
def onchange_partner(self, cr, uid, ids, partner_id, context=None):
    res = {}
    if partner_id:
        obj = self.pool.get('res.partner').browse(cr, uid, partner_id)
        res['field1'] = obj.field1
        res['field2'] = obj.field2
        res['field3'] = 'Hello' # this field type must be char or if not then give
        #value accordingly, its just to prove you that values are filled on onchange.
    return {'value': res}

rawDescription: OpenERP - onchange method for fields in different page of view?


code:
import datetime
today = datetime.datetime.today()
today.weekday()

rawDescription: Seting up a cron job in google app engine


code:
import Tkinter as tk

class View(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.image = tk.PhotoImage(file="somefile.gif")
        b = tk.Button(self, text="Hello, world", image=self.image, compound="left")
        b.pack(side="top")

if __name__ == "__main__":
    root = tk.Tk()
    view = View(root)
    view.pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: How to have image + text in one button in Tkinter

description: Have image + text in one button in Tkinter


code:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1 as axes_grid1
np.random.seed(1)

data = np.random.randn(10, 10)

fig = plt.figure()
grid = axes_grid1.AxesGrid(
    fig, 111, nrows_ncols=(1, 2), axes_pad = 0.5, cbar_location = "right",
    cbar_mode="each", cbar_size="15%", cbar_pad="5%",)

im0 = grid[0].imshow(data, cmap='gray', interpolation='nearest')
grid.cbar_axes[0].colorbar(im0)

im1 = grid[1].imshow(data, cmap='jet', interpolation='nearest')
grid.cbar_axes[1].colorbar(im1)
plt.savefig('/tmp/test.png', bbox_inches='tight', pad_inches=0.0, dpi=200,)

rawDescription: Matplotlib : What is the function of cmap in imshow?


code:
@unittest.skip("showing class skipping")
class MySkippedTestCase(unittest.TestCase):
    def test_not_run(self):
        pass

rawDescription: Python: is there a better way to skip the test module?


code: my_list.sort(key=lambda x:(x[1], x[2]), reverse=True)

rawDescription: Python reordering the list of lists after sorting


code:
def save_image_to_model(instance, **kwargs):
   fieldname = kwargs.pop('fieldname')
   imgpath = kwargs.pop('imgpath')
   imagefile_name = urlparse(imgpath).path.split('/')[-1]
   data = urllib2.urlopen(imgpath).read()
   field = getattr(instance, fieldname)
   field.save(imagefile_name, ContentFile(data))
   instance.save()

rawDescription: django - save instance - attribute as a variable - not working

description: Django - save instance - attribute as a variable - not working


code:
import io
import sys
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
import scipy.interpolate as interpolate

content = '''0.025876 139 0
0.030881 140 0
0.030982 141 0
0.035602 142 0
0.035521 143 0
0.038479 144 0
0.040668 145 0
0.040121 146 0
0.037953 147 0
0.039027 148 0
0.038338 149 0
0.047557 139 1
0.045105 140 1
0.044943 141 1
0.042370 142 1
0.042025 143 1
0.038946 144 1
0.037953 145 1
0.033373 146 1
0.030070 147 1
0.029118 148 1
0.025552 149 1'''

data = np.genfromtxt(io.BytesIO(content), dtype=None, names='x, y, z')

# Or, to read from a file:
# data = np.genfromtxt(filename, dtype=None, names='x, y, z')

x, y, z = data['x'], data['y'], data['z']
N = 20
xi = np.linspace(x.min(), x.max(), N)
yi = np.linspace(y.min(), y.max(), N)

X, Y = np.meshgrid(xi, yi)
Z = interpolate.griddata((x, y), z, (X, Y), method='nearest')

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.scatter(data['x'], data['y'], data['z'])
ax.plot_wireframe(X, Y, Z, rstride=1, cstride=1)
# ax.plot_surface(X, Y, Z)
plt.show()

rawDescription: "Inputs x and y must be 1D or 2D" error in matplotlib


rawDescription: Recursively creating hardlinks using python


code:
from pyramid.events import NewRequest
from pyramid.events import subscriber

@subscriber(NewRequest)
def mysubscriber(event):
    event.request.environ['HTTP_HOST'] = 'example.com'

rawDescription: Pyramid: How to specify the base URL for the application


code: X[np.diag_indices_from(X)] /= c

rawDescription: Numpy modify ndarray diagonal

description: Numpy modify ndarray diagonal


code:
class foo(pygame.Surface):
    def __init__(self):
        pygame.Surface.__init__(self, (20, 20))
        more_data = "You should be able to extend this class freely"

rawDescription: Returning value when instance "called"

description: Returning value when instance "called"


code:
import wx, wx.grid

class GridData(wx.grid.PyGridTableBase):
    _cols = "This is a long column name,b,c".split(",")
    _data = [
        "1 2 3".split(),
        "4,5,And here is a long cell value".split(","),
        "7 8 9".split()
    ]

    def GetColLabelValue(self, col):
        return self._cols[col]

    def GetNumberRows(self):
        return len(self._data)

    def GetNumberCols(self):
        return len(self._cols)

    def GetValue(self, row, col):
        return self._data[row][col]

class Test(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None)
        grid = wx.grid.Grid(self)
        grid.SetTable(GridData())
        grid.EnableEditing(False)
        grid.SetSelectionMode(wx.grid.Grid.SelectRows)
        grid.SetRowLabelSize(0)
        grid.AutoSizeColumns()

app = wx.PySimpleApp()
app.TopWindow = Test()
app.TopWindow.Show()
app.MainLoop()

rawDescription: How can I get the width of a wx.ListCtrl and its column name?

description: Get the width of a wx.ListCtrl and its column name


code:
import mock

...

class UserAPITest(AsyncHTTPTestCase):
    def get_app(self):
        self.app = Application([('/', MainHandler)],
                    cookie_secret='asdfasdf')
        return self.app

    def test_user_profile_annoymous(self):
        with mock.patch.object(MainHandler, 'get_secure_cookie') as m:
            m.return_value = 'user_email'
            response = self.fetch('/', method='GET')
        self.assertEqual('sucess', to_unicode(response.body) )

rawDescription: How to use a test tornado server handler that authenticates a user via a secure cookie

description: Use a test tornado server handler that authenticates a user via a secure cookie


code:
env = jinja2.Environment(undefined=jinja2.DebugUndefined)
t = env.from_string("{{foo}}{{bar}}")
t.render(foo=123)  # will print u'123{{ bar }}'

rawDescription: Jinja leave template tags after render

description: Jinja leave template tags after render


code:
def lookup(index,KEYWORDS):
    kw = KEYWORDS.split()
    if len(kw) == 1:
        return [site[0] for site in index[kw[0]]]
    else:
        positions = {}
        result = []
        kw = KEYWORDS.split()
        for kword in kw:
            for site in index[kword]:
                positions[(kword,site[0])]=site[1]
        for i in range(0,len(kw)-1):
            cur_urls = [site[0] for site in index[kw[i]]]
            next_urls = [site[0] for site in index[kw[i+1]]]
            if i == 0:
                result = cur_urls
            for url in cur_urls:
                if url in next_urls:
                    if not (positions[kw[i+1],url]-positions[kw[i],url]) == 1:
                        result.remove(url)
                else:
                    if url in result:
                        result.remove(url)
        return result

rawDescription: Python Multiword Index

description: Python Multiword Index


code:
from django.test import RequestFactory
from myapp import save

self.factory = RequestFactory()
request = self.factory.get('/customer/details')
request = self.factory.post('/customers/',{"name":"alfred"})
save(request)

rawDescription: How to call a django view function from external python script

description: Call a django view function from external python script


code:
from Tkinter import *
from PIL import Image, ImageTk

root = Tk()
canvas = Canvas(root, width=500, height=500)
canvas.pack()

im = Image.open("image.png")
cropped = im.crop((0, 0, 200, 200))
tk_im = ImageTk.PhotoImage(cropped)
canvas.create_image(250, 250, image=tk_im)

root.mainloop()

rawDescription: How to put a cropped image on a Tkinter Canvas in Python

description: Put a cropped image on a Tkinter Canvas in Python


code:
class ApplicationRoot(object):

    def __getitem__(self, name):
        if name == "rest":
            return RestAPIRoot(parent=self, name=name)
        ...

rawDescription: Best way to make subapps with Traversal

description: Make subapps with Traversal


code:
src = mlab.pipeline.scalar_scatter(x,y,z,s)
iso=mlab.pipeline.iso_surface(gs)

rawDescription: Plotting isosurface with Mayavi of irregularly spaced data


code:
select_data = {"d": """strftime('%%m/%%d/%%Y', time_stamp)"""}

data = My_Model.objects.extra(select=select_data).values('d').annotate(Sum("numbers_data")).order_by()

rawDescription: Django GROUP BY strftime date format

description: Django GROUP BY strftime date format


code:
for matchDiv in soup.find_all("div", attrs={"class" : "contentCol"}):
    h3Url = matchDiv.find("a").get("href")

rawDescription: How to get link of <h3> in a Website with BeautfulSoup4

description: Get link of <h3> in a Website with BeautfulSoup4


code:
s = "the quick brown fox\x00jumped over the lazy\00programmer\00\00"
filter(None, s.split('\x00'))

rawDescription: How to split a multistring in python?

description: Split a multistring in python


code: User.phone_number << contacts

rawDescription: How to do an IN operator in peewee

description: Do an IN operator in peewee


code: def __repr__(self): return repr(self.__dict__) # the dictionary of attributes in __repr__

rawDescription: Listing instance attributes with __dict__


code: np.outer(a, b)

rawDescription: Multiply two arrays with different dimensions using numpy


rawDescription: Why can't I create a numpy array like this: array([1, 2], 3)


code:
def onColWidthChange(col, width):
    # Note that "width" is a GParamInt object, not an integer
    ...

col.connect("notify::width", onColWidthChange)

rawDescription: Detect when column in gtk.treeview is resized


code:
A=[w,y,x,z]
all(p == x for p in A)

rawDescription: Check if list contains only item x

description: Check if list contains only item x


code:
# Note that portions of MLSD data are case insensitive...
def parseinfo(info):
    for fact in info.split(';'):
        if not fact:
            continue
        name, value = fact.split('=', 1)
        yield name.lower(), value

ftp = ftplib.FTP(host, user, passwd)
dirinfo = {}
def callback(line):
    info, fname = line.split(' ', 1)
    dirinfo[fname] = dict(parseinfo(info))
ftp.retrlines('MLSD {}'.format(path), callback)
print(dirinfo)

rawDescription: Is there a rich ftp client library for Python?


code:
def find_using_like( some_partial_key, dictionary ):
    for  k in dictionary:
        if some_partial_key in key:
            return dictionary[k]

rawDescription: Python search: how to do it efficiently

description: Python search: how to do it efficiently


code:
with open('output.txt', 'w+') as ofp, open('input.txt', 'r') as ifp:
    for line in ifp:
        line = line.strip()
        if len(line) > 8:
            line = line[:8]
        elif len(line) <= 4:
            continue

        ofp.write(line + '\n')

rawDescription: python script for limit text file words

description: Python script for limit text file words


code:
items = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for item in items:
    if 5 <= item <= 10:
        print(item)

rawDescription: Search list for number in range

description: Search list for number in range


code:
def records(path):
    with open(path) as f:
        contents = f.read()
        return (record for record in contents.split('^^'))

csv.reader(records('input.csv'))

rawDescription: Reading a csv file in Python with different line terminator


code:
def find_popular_service():
    if (countS) > (countW):
        print ("The most used service to buy tickets was the school.")
    else:
        print ("The most used service to buy tickets was the website.")
    return

rawDescription: Comparing 2 string values, not working!?

description: Comparing 2 string values, not working!


code:
parser = argparse.ArgumentParser(description=TEST_DESCRIPTION,
                                 formatter_class=argparse.RawTextHelpFormatter)

rawDescription: Description parameter to argparse.ArgumentParser() function


code:
@fixture(params=[Param('hello'), Param('world')], ids=['hello', 'world'])
def data(request):
    return request.param

rawDescription: How to make pytest display a custom string representation for fixture parameters?

description: Make pytest display a custom string representation for fixture parameters


rawDescription: Disabling Mouse events - Pygame

description: Disabling Mouse events - Pygame


code:
# for the sake of performance, we turn the lookup list into a set
excludes = set(['R7', 'R5'])

ix = df.Codes.str.split(',').apply(lambda codes: not any(c in excludes for c in codes))
df[ix] # returns the filtered DataFrame

rawDescription: Pandas DataFrame list comparison for every row in a column


code:
def request_seen(self, request):
    fp = request_fingerprint(request)
    added = self.server.sadd(self.key, fp)
    return not added

rawDescription: What are the values stored in requests.seen file in Scrapy?


code:
class HDict(dict):
    def __hash__(self):
        return hash(frozenset(self.items()))

substs = HDict({'foo': 'bar', 'baz': 'quz'})
cache = {substs: True}

rawDescription: Using @functools.lru_cache with dictionary arguments


code:
with open('visit_summary.csv', 'r') as f1, open('clinics.csv', 'w') as f2:
    for line in f1:
        line = line.replace('Calendar: ', '')
        line = line.replace('Something else', '')
        f2.write(line)

rawDescription: Fixing a CSV using Python

description: Fixing a CSV using Python


code:
# untested
class file_iter():
    def __init__(self, file_name):
        self.file = open(file_name)
        self.counted_lines = 0
        self.exhausted = False
    def __iter__(self):
        return self
    def __next__(self):
        if self.exhausted:
            raise StopIteration
        try:
            next_line = self.file.readline()
            self.counted_lines += 1
            return next_line
        except EOFError:
            self.file.close()
            self.exhausted = True
            raise StopIteration

rawDescription: Inspecting and closing a python generator


code:
import os, shutil
folder = '/path/to/folder'
for the_file in os.listdir(folder):
    file_path = os.path.join(folder, the_file)
    try:
        if os.path.isfile(file_path):
            os.unlink(file_path)
        #elif os.path.isdir(file_path): shutil.rmtree(file_path)
    except Exception as e:
        print(e)

rawDescription: Delete Folder Contents in Python

description: Delete Folder Contents in Python


code:
y = np.matrix(x)
y.dtype
y**100
y = np.matrix(x, dtype=object)
y**100
y = np.matrix(x, dtype=float)
y**100

rawDescription: Matrix multiplication gives wrong result


code:
class Foo(object):
   def __init__(self):
      self._x = 0

   def _get_x(self):
      return self._x

   def _set_x(self, x):
      self._x = x

   def _del_x(self):
      del self._x

   x = property(_get_x, _set_x, _del_x, "the x property")

rawDescription: public string blaBla { get; set; } in python

description: Public string blaBla { get; set; } in python


code:
import random

print([random.randint(1,6) for _ in xrange(100)])

rawDescription: Python: how to simulate the roll of a dice 100 times


code:
si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESHOWWINDOW
si.wShowWindow = 3   # SW_MAXIMIZE

rawDescription: subprocess.Popen sets size and location of the external executed programme?

description: Subprocess.Popen sets size and location of the external executed programme


code:
import glob
import os
files = glob.glob("*.pdf")
files.sort()

for ifl, fl in enumerate(files[:-1]):
    if files[ifl+1].startswith(fl[:10]):    #Check if next file is same day
        os.unlink(fl)                       # It is - delete current file

rawDescription: Keep latest file and delete all other

description: Keep latest file and delete all other


code:
pattern3 = r'\n\n'
pattern3
re.findall(pattern3, text)

rawDescription: understanding raw string for regular expressions in python

description: Understanding raw string for regular expressions in python


code:
import fields

def metaclass__call__(cls, *args, **kw):
    instance = super(FieldModelMetaclass, cls).__call__(*args, **kw)
    # do something to the instance
    return instance

FieldModelMetaclass.__call__ = metaclass__call__

rawDescription: Is modifying a metaclass from an external module possible?


code:
"""An example of how to use models and views in PyQt4.
Model/view documentation can be found at
http://doc.qt.nokia.com/latest/model-view-programming.html.
"""
import sys

from PyQt4.QtGui import (QApplication, QColumnView, QFileSystemModel,
                         QSplitter, QTreeView)
from PyQt4.QtCore import QDir, Qt

if __name__ == '__main__':
    app = QApplication(sys.argv)
    # Splitter to show 2 views in same widget easily.
    splitter = QSplitter()
    # The model.
    model = QFileSystemModel()
    # You can setRootPath to any path.
    model.setRootPath(QDir.rootPath())
    # List of views.
    views = []
    for ViewType in (QColumnView, QTreeView):
        # Create the view in the splitter.
        view = ViewType(splitter)
        # Set the model of the view.
        view.setModel(model)
        # Set the root index of the view as the user's home directory.
        view.setRootIndex(model.index(QDir.homePath()))
    # Show the splitter.
    splitter.show()
    # Maximize the splitter.
    splitter.setWindowState(Qt.WindowMaximized)
    # Start the main loop.
    sys.exit(app.exec_())

rawDescription: how to create folder view in pyqt inside main window

description: Create folder view in pyqt inside main window


code:
i = 65
with open('outputfile.bin', 'wb') as f:
    f.write(bytes([i]))
    f.write('A'.encode('ascii'))
    f.write(bytes('A', encoding='ascii'))

rawDescription: Writing the letter A to a file in binary mode


code:
df = pd.concat((df1, df2))
print(df.drop_duplicates('id_col'))

rawDescription: Pandas merge tables: only distinct Ids from second table


rawDescription: How can I replace text inside the parentheses using re.sub()

description: Replace text inside the parentheses using re.sub()


code:
def is_prime(n):
    if n <= 3:
        if n <= 1:
            return False
        return True
    if not n%2 or not n%3:
        return False
    for i in range(5, int(n**0.5) + 1, 6):
        if not n%i or not n%(i + 2):
            return False
    return True

rawDescription: Function to check prime according to specfic instructions


code:
import socket

HOST = 'yourhost'    # The remote host
PORT = 101             # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
data = s.recv(1024)
s.close()
with open('yourfile','w') as f:
     f.write(data)

rawDescription: python socket - how to save stream to file

description: Python socket - how to save stream to file


code:
import sys
with open('file.txt') as f:
  for line in f:
    if '1947' in line: # or some complex regular expressions test
      sys.stdout.write(line)

rawDescription: Reading from a text file

description: Reading from a text file


code:
# Note: all keys and values in these structures are strings

# easiest, but immutable QueryDict
d = request.POST

# dict
d = dict(request.POST.items())

# array
a = list(request.POST.items())  # list of key-value tuples
a = request.POST.values()  # list of values only

rawDescription: Loop through form POST store data in python variable


code:
import xlsxwriter

workbook = xlsxwriter.Workbook('my_export.xlsx')
worksheet = workbook.add_worksheet(name='export_object1')

link_format = workbook.add_format({'color': 'blue',
                                   'underline': True,
                                   'text_wrap': True})

text_format = workbook.add_format({'text_wrap': True})

worksheet.write('A1', 'Its\na bum\nwrap',           text_format)
worksheet.write('B1', 'http://stackoverflow.com/',  link_format)

workbook.close()

rawDescription: python XlsxWriter text wrapping and links styling

description: Python XlsxWriter text wrapping and links styling


code: new_list = [x for x in old_list if x[1] not in to_be_removed]

rawDescription: iterate through second value of each nested list in python

description: Iterate through second value of each nested list in python


code:
animals=sc.parallelize([(1,"mouse"),(2,"elephant"),(3,"cat")])
fruits=sc.parallelize([(1,"apple"),(1,"orange"),(3,"banana")])
fruitAnimals=animals.join(fruits).values()
fruitAnimals.collect()
#[('mouse', 'apple'), ('mouse', 'orange'), ('cat', 'banana')]

rawDescription: Apache Spark convert from join result set (K, (V, W)) to (V,W) key value pair


code:
p = subprocess.Popen(args, stdout=subprocess.PIPE, \
                     stderr=subprocess.PIPE, \
                     universal_newlines=True)
for line in iter(p.stdout.readline, ""):
    sys.stdout.write('\r'+line[:-1])
    sys.stdout.flush()

rawDescription: Real time output of subprocess.popen() and not line by line


code:
import pylab as pl

pl.clf()
ax = pl.gca()
ax.set_xticks([1, 2, 3])
ax.set_xticks([1, 2, 3], minor=True)
ax.set_xticklabels(['one', 'two', 'three'], minor=True)
pl.setp(ax.xaxis.get_minorticklabels(), rotation=-45)

for t in ax.get_xticklabels(minor=True):
    t.set_y(-0.03)

rawDescription: Rotating part of xticks

description: Rotating part of xticks


code:
"""
Utilities for XML generation/parsing.
"""

from xml.sax.saxutils import XMLGenerator

class SimplerXMLGenerator(XMLGenerator):
    def addQuickElement(self, name, contents=None, attrs=None):
        "Convenience method for adding an element with no children"
        if attrs is None: attrs = {}
        self.startElement(name, attrs)
        if contents is not None:
            self.characters(contents)
        self.endElement(name)

rawDescription: How to generate empty closed element use XMLGenerator?

description: Generate empty closed element use XMLGenerator


code:
import matplotlib
import matplotlib.pyplot as plt

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
matplotlib.use('TkAgg')

from Tkinter import *
from ttk import *

def graph(text):
    tmptext = entry.get()
    tmptext = "$"+tmptext+"$"

    ax.clear()
    ax.text(0.2, 0.6, tmptext, fontsize = 50)
    canvas.draw()

root = Tk()

mainframe = Frame(root)
mainframe.pack()

text = StringVar()
entry = Entry(mainframe, width=70, textvariable=text)
entry.pack()

label = Label(mainframe)
label.pack()

fig = matplotlib.figure.Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(111)

canvas = FigureCanvasTkAgg(fig, master=label)
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)

root.bind('<Return>', graph)
root.mainloop()

rawDescription: Is it possible for Python to display LaTex in real time in a text box?


code:
def __init__(self, master, number_of_people, node_size):
    a = 350
    b = 140
    ellipsePoints = [(a * cos(theta), b * sin(theta))
                     for theta in (pi*2 * i/number_of_people for i in range(number_of_people))]
    DisplayFrame = Canvas(root, bg="white", width=725, height=320)
    DisplayFrame.grid(row=0, columnspan=7, column=0, sticky='W', padx=5, pady=5)
    for i in range(number_of_people):
            DisplayFrame.create_oval(ellipsePoints[i][0]+355, ellipsePoints[i][1]+155,
                                     ellipsePoints[i][0]+355+node_size, ellipsePoints[i][1]+155+node_size, fill="red")

rawDescription: How to place evenly spaced circles on an elliptical path?

description: Place evenly spaced circles on an elliptical path


rawDescription: Python numerical calculation concerns

description: Python numerical calculation concerns


code:
seq_length = tf.placeholder(tf.int32)
outputs, states = rnn.rnn(cell, inputs, initial_state=initial_state, sequence_length=seq_length)

sess = tf.Session()
feed = {
    seq_lenght: 20,
    #other feeds
}
sess.run(outputs, feed_dict=feed)

rawDescription: Tensorflow RNN with varying length sentences


code:
def __init__(self, city="Berlin"):
  self.city = city

rawDescription: Multiple constructors in python?

description: Multiple constructors in python


code:
nbrs_count = sum(np.roll(np.roll(mat1, i, 0), j, 1)
                 for i in (-1, 0, 1) for j in (-1, 0, 1)
                 if (i != 0 or j != 0))

rawDescription: More efficient way of suming over a matrix in numpy/regular python


code: myDict.pop(key, None)

rawDescription: Python del if in dictionary in one line

description: Python del if in dictionary in one line


code:
file = open("dizionario_della_vela.txt", "r")
data = file.read()
file.close()
data = data.split("\n") # getting every line as seperate list
myDict = {}
for line in data:
    line = line.split(":")
    key = line[0] # getting first element as key
    value = ":".join(line[1:]) # joins elements (starting with second) with
                               # ":". We need this because previous line
                               # was splitted by ":" to get your key. This
                               # is where "string" value is produced.
    myDict[key] = value

for key in myDict.keys():
    print(myDict[key])

rawDescription: Python splitting text returns a str and a list of str


code:
name = 'brian molko-olsdal stefan olsdal-molko'
name.title()

rawDescription: Split lastnames with python, keep the '-' sign in appropriate position


code:
parent = user.parent
user.parent = parent.parent
parent.parent = user

children = user.children

for child in children:
    child.parent = parent

user.children = parent.children

for child in user.children:
    if child is user:
        child = parent

    child.parent = user

parent.children = children

for child in user.parent.children:
    if child is parent:
        child = user

rawDescription: How to solve this complex recursive problem, pyramid point system

description: Solve this complex recursive problem, pyramid point system


code:
import multiprocessing
from your_database_layer import create_new_session, WhateverType

work = multiprocessing.JoinableQueue()

def writer(commit_every = 50):
    global work
    session = create_new_session()
    counter = 0

    while True:
        item = work.get()
        if item is None:
            break

        session.add(item)
        counter += 1
        if counter % commit_every == 0:
            session.commit()

        work.task_done()

    # Last DB writes
    session.commit()

    # Mark the final None in the queue as complete
    work.task_done()
    return

def very_expensive_object_creation(data):
    global work
    very_expensive_object = WhateverType(**data)
    # Perform lots of computation
    work.put(very_expensive_object)
    return

def main():
    writer_process = multiprocessing.Process(target=writer)
    writer_process.start()

    # Create your pool that will feed the queue here, i.e.
    workers = multiprocessing.Pool()
    # Dispatch lots of work to very_expensive_object_creation in parallel here
    workers.map(very_expensive_object_creation, some_iterable_source_here)
    # --or-- in whatever other way floats your boat, such as
    workers.apply_async(very_expensive_object_creation, args=(some_data_1,))
    workers.apply_async(very_expensive_object_creation, args=(some_data_2,))
    # etc.

    # Signal that we won't dispatch any more work
    workers.close()

    # Wait for the creation work to be done
    workers.join()

    # Trigger the exit condition for the writer
    work.put(None)

    # Wait for the queue to be emptied
    work.join()

    return

rawDescription: Python SQLAlchemy Update Postgres Record


code: data.plot.scatter(x=('x', 'mean'), y=('y', 'mean'))

rawDescription: pandas - a better way to plot binned x vs y

description: Pandas - a better way to plot binned x vs y


code:
# it's lazy object
rating = myinstance.rating.get_ratings()

# do additional query for db
if not rating.filter(user=user, ip_address=request.META['REMOTE_ADDR']).exists():
    ...

rawDescription: How to access cookie and IP fields in DjangoRatings?

description: Access cookie and IP fields in DjangoRatings


code:
import numpy as np
import pandas as pd

df = pd.DataFrame(np.arange(12).reshape(3,4), columns=list('ABCD'))
#    A  B   C   D
# 0  0  1   2   3
# 1  4  5   6   7
# 2  8  9  10  11

np.diff(df.values, axis=0)    # difference of the rows
# array([[4, 4, 4, 4],
#        [4, 4, 4, 4]])

np.diff(df.values, axis=1)    # difference of the columns
# array([[1, 1, 1],
#        [1, 1, 1],
#        [1, 1, 1]])

rawDescription: How to calculate differences across n columns in pandas rather than rows

description: Calculate differences across n columns in pandas rather than rows


rawDescription: pass variable from python to shell script

description: Pass variable from python to shell script


code:
# Connect to Xbee
self.ser = serial.Serial(port, baud, timeout=timeout)

# Send data (a string)
self.ser.write(packet)

# Read data
self.data += self.ser.read()

rawDescription: How can I send strings of data to an XBee with a python library?

description: Send strings of data to an XBee with a python library


code:
def gridsums(grid):
    previous_row_sums = [set() for _ in grid[0]]
    previous_row_sums[0].add(0) #seed
    for row in grid:
        left_sums = set()
        row_sums = []
        for value, above_sums in zip(row, previous_row_sums):
            old_sums = left_sums | above_sums
            sums = {value + old for old in old_sums}
            row_sums.append(sums)
            left_sums = sums
        previous_row_sums = row_sums
    return sums

rawDescription: Implement Dynamic Programming in this algorithm?


code:
a = Linter("ahahah")
a.write_file()
a = dict()
a["first"] = []
a["first"].append([1,2,3])
a["first"].append([4,5,6])
a["second"] = []
a["second"].append([7,8,9])
a

rawDescription: How do I append multiple lists to one key in a python dictionary?

description: Append multiple lists to one key in a python dictionary


code:
from datetime import datetime
dt = datetime.strptime(str_date, '%d/%m/%Y')

rawDescription: Does Django 1.7 has a automatic way to convert datetime fields from manual HTML form to model?


code:
fig, ax = plt.subplots()
line1, = ax.plot([1,2,3], label="Line 1", linestyle='--')
line2, = ax.plot([3,2,1], label="Line 2\nThis is a \nvery long\nlegend", linewidth=4)
line3, = ax.plot([2,2,2], label="Can this be left justified?")

# Create a legend for the first two lines.
# 'loc' sets anchor position of the legend frame relative to itself,
# bbox_to_anchor puts legend's anchor to (x, y) in axes coordinates.
first_legend = ax.legend(handles=[line1], loc='upper left', bbox_to_anchor=(0.65, 1))
second_legend = ax.legend(handles=[line2], loc='center left', bbox_to_anchor=(0.65, 0.5))

# Add the legends manually to the current Axes.
ax.add_artist(first_legend)
ax.add_artist(second_legend)

# Create another legend for the last line.
ax.legend(handles=[line3], loc='lower left', bbox_to_anchor=(0.65, 0))

plt.show()

rawDescription: Matplotlib: how to vertically align multiple legends


code:
from collections import defaultdict
from decimal import Decimal
qs = Price_Report.objects.values_list("created_at", "amount")
tmp = defaultdict(Decimal)
for date, amount in qs:
   tmp[date.year, date.month] += amount

rawDescription: Django ORM query for month and year

description: Django ORM query for month and year


code:
def has_default(self):
    """
    Returns a boolean of whether this field has a default value.
    """
    return self.default is not NOT_PROVIDED

def get_default(self):
    """
    Returns the default value for this field.
    """
    if self.has_default():
        if callable(self.default):
            return self.default()
        return force_text(self.default, strings_only=True)
    if (not self.empty_strings_allowed or (self.null and
               not connection.features.interprets_empty_strings_as_nulls)):
        return None
    return ""

rawDescription: What is the default values for Django fields?


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

xdata = np.array([-2,-1.64,-1.33,-0.7,0,0.45,1.2,1.64,2.32,2.9])
ydata = np.array([0.69,0.70,0.69,1.0,1.9,2.4,1.9,0.9,-0.7,-1.4])

def func(x, p1,p2):
  return p1*np.cos(p2*x) + p2*np.sin(p1*x)

# Here you give the initial parameters for p0 which Python then iterates over
# to find the best fit
popt, pcov = curve_fit(func,xdata,ydata,p0=(1.0,0.3))

print(popt) # This contains your two best fit parameters

# Performing sum of squares
p1 = popt[0]
p2 = popt[1]
residuals = ydata - func(xdata,p1,p2)
fres = sum(residuals**2)

print(fres)

xaxis = np.linspace(-2,3,100) # we can plot with xdata, but fit will not look good
curve_y = func(xaxis,p1,p2)
plt.plot(xdata,ydata,'*')
plt.plot(xaxis,curve_y,'-')
plt.show()

rawDescription: Non-linear fit in Python 3.3

description: Non-linear fit in Python 3.3


code:
def compact_zero_runs(iterable, max_zeros):
    zeros = 0
    for i in iterable:
        if i == 0:
            zeros += 1
            if zeros <= max_zeros:
                yield i
        else:
            zeros = 0
            yield i

rawDescription: How can I delete all zeros except for x of them in every run of consecutive zeros within a list?

description: Delete all zeros except for x of them in every run of consecutive zeros within a list


code:
from django.db.models.signals import post_save

@receiver(post_save, sender=Voucher)
def decrease_quota(sender, instance, created, *args, **kwargs):
    if created:
        instance.vc -= 1
        instance.save()

rawDescription: Django: Overriding the Save (Either Model or Admin Section)


code:
from xlsxwriter.workbook import Workbook

workbook = Workbook('test.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('A1', 49)
worksheet.write('A2', 51)

format1 = workbook.add_format({'bold': 1, 'italic': 1})
worksheet.conditional_format('A1:A2', {'type': 'cell',
                                       'criteria': '>=',
                                       'value': 50,
                                       'format': format1})
workbook.close()

rawDescription: Conditional Formatting xlwt

description: Conditional Formatting xlwt


code:
def orders(request):
    no = GetNewOrders()
    oiids_new = no.getOrderItemId()

    context_dict = {'oiids_new':oiids_new}
    return render(request, 'orders/orders.html', context_dict)

rawDescription: django data not changing dynamically

description: Django data not changing dynamically


code:
import struct

struct.pack('qii', # Format string  here.
            100, # Your 64-bit integer
            50, # Your first 32-bit integer
            25) # Your second 32-bit integer

# This will return the following:
'd\x00\x00\x00\x00\x00\x00\x002\x00\x00\x00\x19\x00\x00\x00'

rawDescription: How to determine whether the number is 32-bit or 64-bit integer in Python?

description: Determine whether the number is 32-bit or 64-bit integer in Python


code:
from PySide import QtGui

app = QtGui.QApplication([])
window = QtGui.QWidget()
window.setStyleSheet('QPushButton{margin-left:-1px;}') # remove this line if you want to have a tiny bit of spacing left

layout = QtGui.QHBoxLayout(window)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
layout.addWidget(QtGui.QPushButton('Button'))
layout.addWidget(QtGui.QPushButton('Button'))
layout.addWidget(QtGui.QPushButton('Button'))
layout.addWidget(QtGui.QPushButton('Button'))
layout.addWidget(QtGui.QPushButton('Button'))
layout.addWidget(QtGui.QPushButton('Button'))

window.show()

app.exec_()

rawDescription: How Not to space the widgets within QHBoxLayout


code:
def vif_ridge(corr_x, pen_factors, is_corr=True):
    """variance inflation factor for Ridge regression

    assumes penalization is on standardized variables
    data should not include a constant

    Parameters
    ----------
    corr_x : array_like
        correlation matrix if is_corr=True or original data if is_corr is False.
    pen_factors : iterable
        iterable of Ridge penalization factors
    is_corr : bool
        Boolean to indicate how corr_x is interpreted, see corr_x

    Returns
    -------
    vif : ndarray
        variance inflation factors for parameters in columns and ridge
        penalization factors in rows

    could be optimized for repeated calculations
    """
    corr_x = np.asarray(corr_x)
    if not is_corr:
        corr = np.corrcoef(corr_x, rowvar=0, bias=True)
    else:
        corr = corr_x

    eye = np.eye(corr.shape[1])
    res = []
    for k in pen_factors:
        minv = np.linalg.inv(corr + k * eye)
        vif = minv.dot(corr).dot(minv)
        res.append(np.diag(vif))
    return np.asarray(res)

rawDescription: Variance inflation factor in ridge regression in python


code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
from scrapy.item import Item, Field

class AppleItem(Item):
    reference_link = Field()
    rss_link = Field()

class AppleSpider(CrawlSpider):

    name = 'apple'
    allowed_domains = ['apple.com']
    start_urls = ['http://apple.com']
    rules = [Rule(SgmlLinkExtractor(allow=()), follow=True, callback='parse_item')]

    def parse_item(self, response):
        sel = HtmlXPathSelector(response)
        rsslinks = sel.select('/html/head/link[@type="application/rss+xml"]/@href').extract()
        #items = []
        item = AppleItem()
        item['reference_link'] = response.url
        item['rss_link'] = rsslinks
        #items.append(item)
        return item

rawDescription: Get RSS links given a domain

description: Get RSS links given a domain


code:
def getTotalDeflection(self, x):
    return sum(self.beamDeflection(loadval, x) for loadval in self.Loads)

rawDescription: Guidance needed with 'class' task (beginner)


rawDescription: Python invert every two elements of list


code:
from PIL import Image
from selenium import webdriver

def get_captcha(driver, element, path):
    # now that we have the preliminary stuff out of the way time to get that image :D
    location = element.location
    size = element.size
    # saves screenshot of entire page
    driver.save_screenshot(path)

    # uses PIL library to open image in memory
    image = Image.open(path)

    left = location['x']
    top = location['y'] + 140
    right = location['x'] + size['width']
    bottom = location['y'] + size['height'] + 140

    image = image.crop((left, top, right, bottom))  # defines crop points
    image.save(path, 'jpeg')  # saves new cropped image

driver = webdriver.Firefox()
driver.get("http://sistemas.cvm.gov.br/?fundosreg")

# change frame
driver.switch_to.frame("Main")

# download image/captcha
img = driver.find_element_by_xpath(".//*[@id='trRandom3']/td[2]/img")
get_captcha(driver, img, "captcha.jpeg")

driver = webdriver.Firefox()
driver.get("http://sistemas.cvm.gov.br/?fundosreg")

# change frame
driver.switch_to.frame("Main")

# download image/captcha
img = driver.find_element_by_xpath(".//*[@id='trRandom3']/td[2]/img")
get_captcha(driver, img, "captcha.jpeg")

rawDescription: Selenium downloading different captcha image than the one in browser


code:
def selection(a_list, first, last, k):
    assert (k - 1 >= first)
    assert (k - 1 <= last)
    intReturn = partition(a_list, first, last)

    if intReturn + 1 == k:
         return a_list[intReturn]

    if intReturn + 1 < k:
        return selection(a_list, intReturn + 1, last, k)

    if intReturn + 1 > k:
        return selection(a_list, first, intReturn - 1, k)

rawDescription: Finding the rank of an element using modified quicksort