code:
def find_renderer(fig):

    if hasattr(fig.canvas, "get_renderer"):
        #Some backends, such as TkAgg, have the get_renderer method, which
        #makes this easy.
        renderer = fig.canvas.get_renderer()
    else:
        #Other backends do not have the get_renderer method, so we have a work
        #around to find the renderer.  Print the figure to a temporary file
        #object, and then grab the renderer that was used.
        #(I stole this trick from the matplotlib backend_bases.py
        #print_figure() method.)
        import io
        fig.canvas.print_pdf(io.BytesIO())
        renderer = fig._cachedRenderer
    return(renderer)

rawDescription: matplotlib: get text bounding box, independent of backend

description: Matplotlib: get text bounding box, independent of backend


code: total = sum(v.amount for ob in self.oblist for v in ob.anotherob)

rawDescription: python one-liner

description: Python one-liner


code:
def funa():
    a=10
    b=20
    funb(a,b)

def funb(a,b):
    c=a+b
    print(c)

rawDescription: Python : child function unable to access parent function data


code:
from sqlalchemy.util import KeyedTuple
res = KeyedTuple(a + b, a.keys() + b.keys())

rawDescription: How do you join two KeyedTuple objects in sqlalchemy?

description: Join two KeyedTuple objects in sqlalchemy


code:
line1, = ax.plot([], [],'-k',label='black')
line2, = ax.plot([], [],'-r',label='red')
ax.legend()
for i in range(0, SIZE):
  A.append(R1 * i * np.sin(i))
  B.append(R2 * i * np.cos(i))
  line1.set_ydata(A)
  line1.set_xdata(range(len(A)))
  line2.set_ydata(B)
  line2.set_xdata(range(len(B)))
  ax.relim()
  ax.autoscale_view()
  plt.draw()

rawDescription: Python Matplotlib: Dynamically update plot - array length not known a priori


code:
with open(source) as fin, open(destination, 'w') as fout:
   reader = csv.reader(fin, delimiter=delim)
   writer = csv.writer(fout, delimiter=delim)
   for line in reader:
      line[0] = 42   # manipulate existing the column
      line.append('new column')  # Add a new column
      writer.writerow(line)

rawDescription: Write column on csv

description: Write column on csv


code:
l = [['John', '1', '2', '3'], ['Doe', '1', '2', '3']]
[[sublist[0]] + sorted(sublist[1:], key=int, reverse=True) for sublist in l]

rawDescription: Sorting list with strings & ints in numerical order


rawDescription: how to plot using a file with 2 columns of values in python

description: Plot using a file with 2 columns of values in python


code:
import spynner
b = spynner.Browser()
b.show()
b.load('http://vk.com')
b.wk_fill('input[name=email]', 'my@mail.ru')
b.wk_fill('input[name=pass]', 'my_secret_password')
b.click("#quick_login_button")
b.browse() # this way we see wha's going on

rawDescription: spynner how i can click login button?

description: Spynner how i can click login button


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

idx = pd.date_range('2011-05-01', '2011-07-01')
s = pd.Series(np.random.randn(len(idx)), index=idx)

fig, ax = plt.subplots()
ax.plot_date(idx.to_pydatetime(), s, 'v-')
ax.xaxis.set_minor_locator(dates.WeekdayLocator(byweekday=(1),
                                                interval=1))
ax.xaxis.set_minor_formatter(dates.DateFormatter('%d\n%a'))
ax.xaxis.grid(True, which="minor")
ax.yaxis.grid()
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_major_formatter(dates.DateFormatter('\n\n\n%b\n%Y'))
plt.tight_layout()
plt.show()

rawDescription: Pandas timeseries plot setting x-axis major and minor ticks and labels


code:
from Tkinter import *

def super_function():
    fen1.quit

fen1 = Tk()
entr = []
for i in xrange(10):
    entr.append(Entry(fen1))
    entr[i].grid(row=i)
# Use grid instead of pack here
Button(fen1,text='store everything in a list',command=super_function).grid()
fen1.mainloop()

rawDescription: Python/Tkinter Button and Entry on the same window


code:
import os
import sys
from contextlib import contextmanager

@contextmanager
def stdout_redirected(to=os.devnull):
    '''
    import os

    with stdout_redirected(to=filename):
        print("from Python")
        os.system("echo non-Python applications are also supported")
    '''
    fd = sys.stdout.fileno()

    ##### assert that Python and C stdio write using the same file descriptor
    ####assert libc.fileno(ctypes.c_void_p.in_dll(libc, "stdout")) == fd == 1

    def _redirect_stdout(to):
        sys.stdout.close() # + implicit flush()
        os.dup2(to.fileno(), fd) # fd writes to 'to' file
        sys.stdout = os.fdopen(fd, 'w') # Python writes to fd

    with os.fdopen(os.dup(fd), 'w') as old_stdout:
        with open(to, 'w') as file:
            _redirect_stdout(to=file)
        try:
            yield # allow code to be run with the redirected stdout
        finally:
            _redirect_stdout(to=old_stdout) # restore stdout.
                                            # buffering and flags such as
                                            # CLOEXEC may be different

rawDescription: How do I prevent a C shared library to print on stdout in python?

description: Prevent a C shared library to print on stdout in python


code:
def isPalindrome():
    string1 = input('Enter a string: ')
    string2 = string[::-1]
    if string1 == string2:
        return 'It is a palindrome'
    return 'It is not a palindrome'

isPalindrome()

rawDescription: Improving Python Palindrome code

description: Improving Python Palindrome code


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup("""
zdfsfsf
adfadfadf
adfadfasdfadfad  adfadf adf
Mill Valley, CA 94941
122-2323-24124
Email: adfadfadf
sfsfsfsf

""")
print(soup.get_text())

rawDescription: How to return just the text from a HTML snippet?

description: Return just the text from a HTML snippet


code:
pers = np.arange(1,101,1)

# Make each of the last 41 elements 5x more likely
prob = [1.0]*(len(pers)-41) + [5.0]*41

# Normalising to 1.0
prob /= np.sum(prob)

number = np.random.choice(pers, 1, p=prob)

rawDescription: Create random numbers with left skewed probability distribution


code:
import socket
import urllib2

# timeout in seconds
timeout = 10
socket.setdefaulttimeout(timeout)

# this call to urllib2.urlopen now uses the default timeout
# we have set in the socket module
req = urllib2.Request('http://www.voidspace.org.uk')
response = urllib2.urlopen(req)

rawDescription: Python send cmd on socket

description: Python send cmd on socket


code:
filename = raw_input()
datafile=open(filename, 'r')
data = datafile.read()
datafile.close() # Don't forget to close the file!
counts = {} # make sure counts is an empty dictionary
data = data.lower() # convert data to lowercase
for k in range(97, 123):  # letters a to z are ASCII codes 97 to 122
    character = chr(k) # get the ASCII character from the number
    counts[character] = data.count(character)

rawDescription: Python regular expressions and CMD

description: Python regular expressions and CMD


code:
l = [1,2,3,4]
[it for it in l for _ in range(2)]

rawDescription: Smallest way to expand a list by n

description: Smallest way to expand a list by n


code:
@property
def x(self):
    return self.datum[0]

@x.setter
def x(self, value):
    self.datum[0] = value

@property
def y(self):
    return self.datum[1]

@y.setter
def y(self, value):
    self.datum[1] = value

rawDescription: Assign attributes when another is changed


code:
elements.append(Flowable1)
elements.append(Flowable2)

c = Canvas(path)
f = Frame(fx, fy,fw,fh,showBoundary=0)

# compute the available height for the spacer
sheight = f._aH - (Flowable1.wrap(f._aW,f._aH)[1] + Flowable2.wrap(f._aW,f._aH)[1])

# create spacer
s = Spacer(width=0, height=sheight)

# insert the spacer between the two flowables
elements.insert(1,s)

# create a frame from the list of elements
f.addFromList(elements,c)

c.save()

rawDescription: Dynamic Spacer in ReportLab

description: Dynamic Spacer in ReportLab


code:
class PostList(generics.ListAPIView):
    ...
    def get_queryset(self):
        Post.objects.all().extra(select={
        'current_user_replies_count': 'SELECT COUNT(*) FROM <reply table> WHERE' +
        'post_id=posts_post.id AND owner_id = %s'
                                  },select_params=(request.user.id,))

rawDescription: Add a boolean field if a row exists in another table?


code:
class User(object):

    @classmethod
    def get_by_username(cls, dbsession, username):
        return dbsession.query(cls).filter(cls.username==username).one()

rawDescription: Is there something equivalent to django's managers in SQLAlchemy?


code:
d = self.monster_deaths.pop(...)
print("{}! The {} {} {}".format(self.monster.battlecry(),
                                self.monster.color,
                                type(self.monster).name,
                                d))

rawDescription: PEP8 formatting: long line with indentation and nested brackets


code:
from visual import sphere,color

count = 3
R=0.3

for x in range(-count,count+1):
    for y in range(-count,count+1):
        for z in range(-count,count+1):
            if ((x+y+z+3*count)%2) == 0:
                sphere(pos=[x,y,z],radius=R,color=color.green)
            else:
                sphere(pos=[x,y,z],radius=R,color=color.yellow)

rawDescription: Drawing cubic lattice in Python

description: Drawing cubic lattice in Python


code:
import os
f = open(os.path.join(os.path.dirname(__file__), "filename.txt"))

rawDescription: read files from directory that has running script rather than calling directory location from where the script was called, python

description: Read files from directory that has running script rather than calling directory location from where the script was called, python


code:
tup = [lst[x+1] for x in range(0, len(lst), 2)]
names = [lst[x] for x in range(0, len(lst), 2)]
b = []
[b.append(x) for x in tup if x not in b]
b
list(set(names))

rawDescription: How to separate strings and tuples from list?

description: Separate strings and tuples from list


code:
def infiniteSecret(secret):
    num = 0
    while true:
        yield secret[num % len(secret)]
        num += 1
#one direction
key_saved_in_database = map(lambda a, b: a ^ b, zip(infiniteSecret(secret), key))

#other direction
key = map(lambda a, b: a ^ b, zip(infiniteSecret(secret), key_saved_in_database))

rawDescription: Storing an api_key, api_pass

description: Storing an api_key, api_pass


code:
class PersonListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ('foo', 'bar',)

    def to_representation(self, instance):
        data = super(PersonListSerializer, self).to_representation(instance)
        data.update(...)
        return data

rawDescription: Can to_representation() in Django Rest Framework access the normal fields


rawDescription: python combining two lists of tuples into one big list of tuples?

description: Python combining two lists of tuples into one big list of tuples


rawDescription: Implementing ceil function without using if-else


code:
import numpy as np

def fitfunc(p, x):
    a = np.zeros(7)
    a[1:7] = p[:6]
    a[0] = 1 - a[1:4].sum()
    return a[0] + a[1]*exp(-x/a[4]) + a[2]*exp(-x/a[5]) + a[3]*exp(-x/a[6])

def errfunc(p, x, y1, y2):
    return np.concatenate((
        fitfunc(p[:6], x) - y1,
        fitfunc(p[6:12], x) - y2
    ))

rawDescription: Python: least square fit with side conditions on fit-parameters


code: {{ my_string_with_n|linebreaksbr }}

rawDescription: Django / Python make newline with '\n'

description: Django / Python make newline with '\n'


code:
lista=['LA.BF.2.1']
listb=['LA.BF.2.1','LA.BF64.1.2.1','LA.BF64.1.1']
any([ i in listb for i in lista])

rawDescription: Match logic between two lists

description: Match logic between two lists


code:
import Queue

def bfs(graph, start, end):
    q = Queue.Queue()
    path = [start]
    q.put(path)
    visited = set([start])

    while not q.empty():
        path = q.get()
        last_node = path[-1]
        if last_node == end:
            return path
        for node in graph[last_node]:
            if node not in visited:
                visited.add(node)
                q.put(path + [node])

rawDescription: Python Breadth First Search optimisation


code:
def get_hour(in_array):
    return int(in_array[1][11:13])

for x in npdata:
    hourlist[get_hour(x)].append(x)

rawDescription: Binning NumPy array by hour within a datetime field


code:
import re
s = "Can you help me!"
re.sub(r'[-\w]+', lambda w:w.group()[::-1], s)

rawDescription: String reverse in Python

description: String reverse in Python


code:
dict_a = {"A": 3.0, "C": 4.0, "B": 6.0}
dict_b = {"A": 3.0, "C": 5.0, "D": 1.0}
from collections import Counter
a = Counter(dict_a)
a.subtract(dict_b)
a

rawDescription: Subtracting elements from dictionaries

description: Subtracting elements from dictionaries


code:
import pandas
indexcols = ['ID', 'Boolean']

data = pandas.read_sql_query(engine, querytext)
full_index = pandas.MultiIndex.from_product(
    [data['ID'].unique(), [0, 1]],
    names=indexcols
)

data = (
    data.set_index(indexcols)
        .reindex(full_index)
        .fillna(0)
        .reset_index()
)

rawDescription: Fill in missing boolean rows in Pandas

description: Fill in missing boolean rows in Pandas


code:
my_args = sys.argv
# do something to my_args
# ...
parser.parse_args(my_args)

rawDescription: How to pass list to argparse.ArgumentParser?

description: Pass list to argparse.ArgumentParser


code: {{ mytemplatevar|timesince }}

rawDescription: Is there a Django template filter that turns a datetime into "5 hours ago" or "12 days ago"?


code:
value = float('1.72e-05')
string_value = "%f" % value

rawDescription: Python - unable to convert 1.72e-05 to a float value


code:
df = df.set_index('Count_Product')

ax = df['Count_Transaction'].plot(kind='bar', figsize=(5,5), color='blue')
ax.set_ylabel("Count_Transaction")
ax.set_xlabel("Count_Product")
patches, labels = ax.get_legend_handles_labels()
ax.legend(patches, labels, loc='best')

rawDescription: Python Pandas: Bar plot X axis issue

description: Python Pandas: Bar plot X axis issue


code: from PIL import Image, ImageDraw, ImageChops

rawDescription: Import Image works on GAE but not in dev_appserver.py


rawDescription: In Zope/ZODB, how to delete objects from a BTreeFolder2


rawDescription: String to datetime django

description: String to datetime django


code:
try:
    import zumba
except ImportError:
    import pip
    pip.main(['install', '--user', 'zumba'])
    import zumba

rawDescription: How to install a missing python package from inside the script that needs it?

description: Install a missing python package from inside the script that needs it


code:
sample = df['C'].values
a = df['A'].values
b = df['B'].values
population = np.concatenate((a,b), axis=0)

def mean_diff(s, p):
    m = np.mean(s)
    len_ = len(s)
    result = np.mean([m > np.mean(npr.choice(p, len_, True))
                            for _ in range(10000)])
    return result

mean_diff(sample, population)

rawDescription: Comparing sample mean vs random assortments in Python


code:
logger = logging.getLogger("mylog")
formatter = logging.Formatter('%(asctime)s | %(name)s |  %(levelname)s: %(message)s')
logger.setLevel(logging.DEBUG)

stream_handler = logging.StreamHandler()
stream_handler.setLevel(logging.INFO)
stream_handler.setFormatter(formatter)

logFilePath = "my.log"
file_handler = logging.handlers.TimedRotatingFileHandler(filename = logFilePath, when = 'midnight', backupCount = 30)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.DEBUG)

logger.addHandler(file_handler)
logger.addHandler(stream_handler)

logger.info("Started");
try:
    x = 14
    y = 0
    z = x / y
except Exception as ex:
    logger.error("Operation failed.")
    logger.debug("Encountered {0} when trying to perform calculation.".format(ex))

logger.info("Ended");

rawDescription: How to set different levels for different python log handlers

description: Set different levels for different python log handlers


rawDescription: Binary conversion and XOR in python

description: Binary conversion and XOR in python


rawDescription: test a boolean expression in a Python string

description: Test a boolean expression in a Python string


code:
subprocess.Popen(['convert', '1.png', '(', '+clone', '-background', 'black', '-shadow', '110x1+9+9',
                  ')', '+swap', '-background', 'none', '-layers', 'merge', '+repage', '2.png'],
                 otherargments=values, etc=etc)

rawDescription: sending a complex shell command to python subprocess

description: Sending a complex shell command to python subprocess


rawDescription: loop on a dictionary (previous values) python

description: Loop on a dictionary (previous values) python


code:
# Dictionary stored in d
from operator import itemgetter
# Iterate over the elements of the dictionary; below, by
# calling items(), k gets the key value of an entry and
# v gets the value of that entry
for k,v in d.items():
    if v and isinstance(v[0], list):
        v.sort(key=itemgetter(2)) # Start with 0, so third element is 2

rawDescription: Sorting dictionary list-values based on time


code:
import pygame
pygame.init()

screen = pygame.display.set_mode((600,200))

#--------------------------------------
# circles positions and transparency (x,y, alpha)

circles = []

for x in range(100):
    circles.append( [100+x*3, 200, x*2] )

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

white = True # background color

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

running = True

while running:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.KEYDOWN:

            if event.key == pygame.K_ESCAPE:
                running = False

            elif event.key == pygame.K_SPACE:
                white = not white

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

    if white:
        screen.fill((255,255,255))
    else:
        screen.fill((0,0,0))

    #--------------------------------------
    # first

    circle_img = pygame.Surface((20,20))
    pygame.draw.circle(circle_img, (255,0,0), (10,10), 10)
    circle_img.set_colorkey(0)

    for x in circles:

        circle_img.set_alpha(x[2])

        screen.blit(circle_img, (x[0],40))

    #--------------------------------------
    # second

    circle_img = pygame.Surface((20,20))

    for x in circles:

        pygame.draw.circle(circle_img, (255,255-x[2],255-x[2]), (10,10), 10)
        circle_img.set_colorkey(0)

        screen.blit(circle_img, (x[0],90))

    #--------------------------------------
    # last

    circle_img = pygame.Surface((20,20))

    for x in circles:

        pygame.draw.circle(circle_img, (255,255-x[2],255-x[2]), (10,10), 10)
        circle_img.set_colorkey(0)
        circle_img.set_alpha(x[2])

        screen.blit(circle_img, (x[0],140))

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

    pygame.display.flip()

pygame.quit()

rawDescription: Adding gradient to moving objects in pygame


rawDescription: Element-wise matrix multiplication in NumPy


code:
s = 'Abcd Efgh Axyx'
if s.endswith('Axyx'):
    s = s[:-len('Axyx')]

rawDescription: Strange Python strip() behavior

description: Strange Python strip() behavior


code:
import base64, urllib

decoded = base64.b64decode(urllib.urlopen("http://git.io/vYT4p").read())
with open('/tmp/31558315.png', 'w') as handle:
    handle.write(decoded)

rawDescription: How to save image using Python

description: Save image using Python


code:
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec

fig=plt.figure(figsize=(16,12))

gs = GridSpec(3,3)

# Top row
ax1=fig.add_subplot(gs[0,0])
ax2=fig.add_subplot(gs[0,1],sharey=ax1)
ax3=fig.add_subplot(gs[0,2],sharey=ax1)

# Middle row
ax4=fig.add_subplot(gs[1,0:2],sharey=ax1)

# Bottom row
ax5=fig.add_subplot(gs[2,0],sharey=ax1)
ax6=fig.add_subplot(gs[2,1],sharey=ax1)
ax7=fig.add_subplot(gs[2,2],sharey=ax1)

ax1.set_ylim(-15,10)

plt.show()

rawDescription: Python, Matplotlib custom axes share Y axis


code:
def run_server(dom):
        _run_on_start("%s" % dom)
        app.run(debug=True, use_reloader=False)

if __name__ == '__main__':
    if len(sys.argv) < 2:
        raise Exception("Must provide domain for application execution.")
    else:
        DOM = sys.argv[1]
        run_server(DOM)

rawDescription: What's the right approach for calling functions after a flask app is run?


code:
import networkx as nx
G = nx.Graph()
G.add_edge(1,2,l=['a','b','c'])
H = nx.Graph(G) # shallow copy
H[1][2]['l']
H[1][2]['l'].append('d')
H[1][2]['l']
G[1][2]['l']

rawDescription: Networkx copy clarification

description: Networkx copy clarification


code:
import  ast
ast.literal_eval("1")
ast.literal_eval("0")
ast.literal_eval("True")
ast.literal_eval("False")
ast.literal_eval("'foobar'")
ast.literal_eval("1.2")
ast.literal_eval("1.2e3")
ast.literal_eval("1,2")
ast.literal_eval("[1,2]")
ast.literal_eval("[1,2,(1,2)]")
ast.literal_eval("1f")

rawDescription: How can I evaluate a string into an object in Python?

description: Evaluate a string into an object in Python


code:
from tornado import web, gen
import tornado, time

class CoroutineFactorialHandler(web.RequestHandler):
    def factorial(self, limit=1):
        count = 1
        fact = 1
        while count <= limit:
            yield fact
            count = count + 1
            fact = fact * count

    def loop(self):
        try:
            self.fact = self.generator.next()
            tornado.ioloop.IOLoop.instance().add_callback(self.loop)
        except StopIteration:
            self.write("took : %f sec" %(time.time() - self.t))
            self.write("\n")
            self.write("f(%d) = %d" % (self.n, self.fact))
            self.finish()

    @web.asynchronous
    def get(self, n, *args, **kwargs):
        self.n = int(n)
        self.generator = self.factorial(self.n)
        self.t = time.time()
        self.set_header("Content-Type", "text/plain")
        tornado.ioloop.IOLoop.instance().add_callback(self.loop)

application = tornado.web.Application([
    (r"^/coroutine/factorial/(?P<n>\d+)", CoroutineFactorialHandler),
    #http://localhost:8888/coroutine/factorial/<int:n>
])

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

rawDescription: why my coroutine blocks whole tornado instance?

description: Why my coroutine blocks whole tornado instance


rawDescription: Add a text after pattern in python

description: Add a text after pattern in python


code: data = [d for d in data if d['id'] not in remove_ids]

rawDescription: Remove items from list of dicts with a matching attribute


rawDescription: Implementing 2D Laplacian in Cython for periodic boundary counditions


code: templates_path = ["templates"]

rawDescription: Customizing Sphinx to avoid generating search box


code:
regex = re.compile("Who created (.*?)\?", re.I)
regex.search("Who created Lord of the Rings?").groups()[0]

rawDescription: Using regular expression to catch phrases in Python


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

mu, sigma=100, 15
N=4
x=mu + sigma*np.random.randn(N)
plt.bar(range(N), x,  align='center')
labels=[
    'hello world 12345',
    'another long one',
    'what happened to pithy',
    'yada yada',
    ]
labels=[textwrap.fill(text,15) for text in labels]

plt.xticks(range(N), labels)
plt.show()

rawDescription: Python/Matplotlib - x tick label formatted into multiple columns?


code:
df
col_list = [3, 5]
df = df[col_list]
df

rawDescription: Deleting all columns except a few python-pandas


code:
def __getattr__(self, attr):
    return getattr(self.collection, attr)

rawDescription: How to pass instance method calls on to instance property?

description: Pass instance method calls on to instance property


code:
class BinaryTree:
    def __init__(self,rootObj, leftnode=None, rightnode=None):
        self.key = rootObj
        self.leftChild = leftnode
        self.rightChild = rightnode

    def insertLeft(self,newNode):
        #if self.leftChild == None: pass leftnode=None to constructor.
        # which is the same as passing leftnode=self.leftChild
        self.leftChild = BinaryTree(newNode, leftnode = self.leftChild)

rawDescription: Swapping variables in a class without using a temporary variable


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

def update_line(num, data, line):
    line.set_data(data[...,:num])
    return line,

fig1 = plt.figure()

data = np.random.rand(2, 25)
l, = plt.plot([], [], 'r-')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, 25, fargs=(data, l),
    interval=50, blit=True)

plt.show()

rawDescription: How to show the changes of multiple images in one figure?

description: Show the changes of multiple images in one figure


code:
inputfile = "tutorial.txt"
outputfile = "fixed_tutorial.txt"

def remove_strings():
    delete_list = ["end"]
    filein = open(inputfile)
    fileout = open(outputfile, "w+")
    for line in filein:
        for word in delete_list:
            line = line.replace(word, "")
        fileout.write(line)
    filein.close()
    fileout.close()

if __name__ == '__main__':
    remove_strings()

rawDescription: Removing a specific word from a file [Python 2.7.10] file 'object' has no attribute remove


code:
import io
with io.BytesIO(b"foo") as f: f.read()

rawDescription: Python's StringIO doesn't do well with `with` statements


code:
q = Queue()
q.put(1)
q.queue

rawDescription: See Queue items in Pydev debug

description: See Queue items in Pydev debug


code:
with open(filename, "wb") as f:
    f.seek(999999)
    f.write("\0")

rawDescription: How do I efficiently fill a file with null data from python?

description: Efficiently fill a file with null data from python


code:
def replaceWithContents(element):
    ix= element.parent.contents.index(element)
    for child in reversed(element.contents):
        element.parent.insert(ix, child)
    element.extract()

doc= BeautifulSoup(html) # maybe fromEncoding= 'utf-8'
for link in doc.findAll('a'):
    replaceWithContents(link)
str(doc)

rawDescription: strip only html anchor tags

description: Strip only html anchor tags


code:
import numpy
import numpy.random
x = numpy.random.rand(100, 3, 4)
mask = numpy.random.rand(*x.shape)
result = numpy.where(mask < 0.5, 0, x)

rawDescription: Chained list comprehension in python

description: Chained list comprehension in python


code:
from azure import *
from azure.storage import TableService

table_service = TableService(account_name='xxx', account_key='yyy')
i=0
next_pk = None
next_rk = None
while True:
    entities=table_service.query_entities('Address',"PartitionKey eq 'Address'", next_partition_key = next_pk, next_row_key = next_rk, top=1000)
    i+=1
    for entity in entities:
        print(entity.AddressLine1)
    if hasattr(entities, 'x_ms_continuation'):
        x_ms_continuation = getattr(entities, 'x_ms_continuation')
        next_pk = x_ms_continuation['nextpartitionkey']
        next_rk = x_ms_continuation['nextrowkey']
    else:
        break;

rawDescription: python querying all rows of azure table

description: Python querying all rows of azure table


rawDescription: How do I run a scipt from within Python on windows/dos?

description: Run a scipt from within Python on windows/dos


code:
seen_attributes = set()

# code here adding nodes

node = node_to_add
attribute = attribute_of_node

if attribute not in seen_attributes:
    G.add_node(node, coord=attribute)
    seen.add(attribute)

rawDescription: Add node to network x only if a node with same attribute doesn`t exist


code:
import signal
TIMEOUT = 20 * 60 # secs to wait for interaction

def interrupted(signum, frame):
    "called when read times out"
    print('Exiting')

signal.signal(signal.SIGALRM, interrupted)

def i_input():
    try:
            print('You have 20 minutes to interact or this script will cease to execute')
            foo = input()
            return foo
    except:
            # timeout
            return

# set alarm
signal.alarm(TIMEOUT)

inp = i_input()

# disable the alarm if not wanted any longer
# signal.alarm(0)

rawDescription: How can a "dead man's switch" be written in Python, something that monitors for an interaction in a specified time?


code:
inp = open(input,'r')
sliced_file = islice(inp,None)
for ind in listOfInd:
    print('ind ' + ind)
    for line_number, line in enumerate(sliced_file,start=1):
        print(line_number)
        number, rest = line.split('\t',1)
    inp.seek(0)

rawDescription: Looping through a text file using islice


rawDescription: Set the index of a dataframe as the columns and vice versa


code:
from os.path import basename
...
zip.write(first_path, basename(first_path))
zip.write(second_path, basename(second_path))
zip.close()

rawDescription: python/zip: How to eliminate absolute path in zip archive if absolute paths for files are provided?

description: Python/zip: How to eliminate absolute path in zip archive if absolute paths for files are provided


code:
with open(file, 'rb') as myfile:
    strings = myfile.readlines()

# do your stuff to strings
filestring = ''.join(strings)

rawDescription: python join "large" file

description: Python join "large" file


code: [x for x in values if x % 2 == 1] + [x for x in values if x % 2 == 0] == values

rawDescription: Pythonic method of determining if a list's contents change from odd to even values


code:
d1 = datetime.datetime.now() + datetime.timedelta(minutes=15)
d2 = datetime.datetime.now() + datetime.timedelta(hours=1)

rawDescription: In Python, how do I make a datetime that is 15 minutes from now? 1 hour from now?


code:
from collections import Counter

d = {1:'Bob',2:'Joe',3:'Bob', 4:'Bill', 5:'Bill'}

c = Counter()
new_d = {}

for k in sorted(d.keys()):
    name = d[k]
    c[name] += 1;
    new_d[k] = [name, c[name]]

print(new_d)
# {1: ['Bob', 1], 2: ['Joe', 1], 3: ['Bob', 2], 4: ['Bill', 1], 5: ['Bill', 2]}

rawDescription: python running count of values in dict

description: Python running count of values in dict


code:
import requests
from bs4 import BeautifulSoup

url = 'https://www.airbnb.com/rooms/5711344'
html = requests.get(url)
soup = BeautifulSoup(html.text, 'html.parser')
divs = soup.find_all('div', attrs={'class': 'col-md-3 text-muted'})
for div in divs:
    space = div.find('span').text.strip()
    if space == "The Space":
        print(space)

rawDescription: Scraping airbnb with python lxml

description: Scraping airbnb with python lxml


code: company_3 = [o.title() for o in company_2]

rawDescription: How can I iterate this code without using such a complicated for loop?

description: Iterate this code without using such a complicated for loop


code:
import csv
with open("C:/path/a.csv","rU") as f,open("C:/path/des.csv","wb") as w:
    not_ok_name= ["John Doe" , "Jim Foe"]
    reader = csv.reader(f)
    for row in f:
        name,other = row.split(",")
        if name not in not_ok_name:
            w.write(row)

rawDescription: Remove specific rows from csv file if matching the elements of a list - python / windows


code:
import matplotlib.pyplot as plt

data = [[0, 0.25], [0.5, 0.75]]

fig, ax = plt.subplots()
im = ax.imshow(data, cmap=plt.get_cmap('hot'), interpolation='nearest',
               vmin=0, vmax=1)
fig.colorbar(im)
plt.show()

rawDescription: matplotlib imshow - default colour normalisation

description: Matplotlib imshow - default colour normalisation


code:
script, input_file = argv
#...
current_file = open(input_file)
#...
#here, the body of current_file is executed,
#with f replaced by the value of current_file
print_all(current_file)

rawDescription: Learn Python the Hard Way, exercise 20, confused about functions


code:
if PwrPri in PhyPwrDict:
    print(PhyPwrDict[PwrPri])
else:
    print(Dismiss2)
    sys.exit(0)

rawDescription: python 3.4 - input, match key, print value

description: Python 3.4 - input, match key, print value


code:
import numpy as np
o = ['x','y','z','a','b']
a = np.zeros((len(o),len(o)),dtype=object)
s  =[('x',{'y':'1,3','z':'2'}), ('y',{'a':'4'}), ('z',{'b':'2,3'})]
for vi in s:
    i = o.index(vi[0])
    for vj in vi[1].items():
        j = o.index(vj[0])
        a[i,j] = vj[1]
        a[j,i] = a[i,j]

# building the structured array
b = np.zeros((len(o),), dtype=[(i,object) for i in o])
for i,vi in enumerate(o):
    b[vi] = a[i,:]

# building a dictionary to access the values
d = dict(( (vi, dict(( (vj, a[i,j]) for j,vj in enumerate(o) ))) for i,vi in enumerate(o) ))

rawDescription: constructing numpy array from list

description: Constructing numpy array from list


code:
from datetime import datetime
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as dt

df = pd.read_csv('data.csv')
df.amin = pd.to_datetime(df.amin).astype(datetime)
df.amax = pd.to_datetime(df.amax).astype(datetime)

fig = plt.figure()
ax = fig.add_subplot(111)
ax = ax.xaxis_date()
ax = plt.hlines(df.index, dt.date2num(df.amin), dt.date2num(df.amax))

rawDescription: How to plot stacked event duration (Gantt Charts) using Python Pandas?

description: Plot stacked event duration (Gantt Charts) using Python Pandas


code:
import PIL.Image
import PIL.ImageEnhance

# images
base_path = 'base.jpg'
watermark_path = 'watermark.png'
base = PIL.Image.open(base_path)
watermark = PIL.Image.open(watermark_path)

# optional lightness of watermark from 0.0 to 1.0
brightness = 0.5
watermark = PIL.ImageEnhance.Brightness(watermark).enhance(brightness)

# apply the watermark
some_xy_offset = (10, 20)
# the mask uses the transparency of the watermark (if it exists)
base.paste(watermark, some_xy_offset, mask=watermark)
base.save('final.png')
base.show()

rawDescription: Adding one image to another with PIL on Raspberry Pi


code:
import asyncio

def create_sub_task():
    sub_task = asyncio.ensure_future(sub())
    outer_task = asyncio.Task.current_task()

    multi_fut = asyncio.gather(sub_task, outer_task)
    for cb in outer_task._callbacks:
        multi_fut.add_done_callback(cb)
        outer_task.remove_done_callback(cb)

async def sub():
    await asyncio.sleep(2)
    print('sub done')

async def main():  # main is outer task for sub_task
    create_sub_task()
    await asyncio.sleep(1)
    print('outer done')

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

rawDescription: Await sub task finished on outer task finished event (async version of add_done_callback)


code:
x = ['a', 'b', 'c', 'd']
t = []
lenList = len(x)
for l in range(0, lenList):
    t.extend([x[l]] * (lenList - l))

t

rawDescription: Clone elements of a list

description: Clone elements of a list


code:
from urlparse import urljoin
from bs4 import BeautifulSoup
import requests

BASE_URL = "http://genius.com"
artist_url = "http://genius.com/artists/Andre-3000/"

response = requests.get(artist_url, headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36'})

soup = BeautifulSoup(response.text, "lxml")
for song_link in soup.select('ul.song_list > li > a'):
    link = urljoin(BASE_URL, song_link['href'])
    response = requests.get(link)
    soup = BeautifulSoup(response.text)
    lyrics = soup.find('div', class_='lyrics').text.strip()

    # tokenize `lyrics` with nltk

rawDescription: Web Scraping Rap lyrics on Rap Genius w/ Python


code:
import multiprocessing
pool = multiprocessing.Pool()
pool.map(function_x, list_of_files)

rawDescription: Python: Parallel processing of N files in list


rawDescription: What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?


code:
a = [0] * 1024
b = np.array(a)
getsizeof(a)
b.nbytes

rawDescription: Python memory usage of numpy arrays

description: Python memory usage of numpy arrays


code:
import Tkinter as tk

class App():
    def __init__(self):
        self.root = tk.Tk()
        self.root.attributes('-fullscreen', True)
        self.main_frame = tk.Frame(self.root)
        self.main_frame.config(background='red', cursor='none')
        self.main_frame.pack(fill=tk.BOTH, expand=tk.TRUE)
        self.root.bind('<F1>', self.opennote)
        self.root.bind('<F2>', self.closenote)
        self.root.bind('<F3>', self.quit)
        l = tk.Label(self.main_frame, text="some text here")
        l.pack()
        self.root.mainloop()

    def opennote(self, event):
        self.n = tk.Text(self.main_frame, background='blue')
        self.n.pack()

    def closenote(self, event):
        self.n.destroy()

    def quit(self, event):
        self.root.destroy()

App()

rawDescription: How to hide or disable the mouse pointer in Tkinter?

description: Hide or disable the mouse pointer in Tkinter


code:
def sampleVisibleLayer (self, V):
    reshaped = V.dimshuffle(0, 1, 3, 2).reshape((V.shape[0]*V.shape[3], V.shape[2]))
    S_reshaped = self.theano_rng.multinomial(n=1,pvals=reshaped)
    S = S_reshaped.reshape((V.shape[0], 1, V.shape[3], V.shape[2])).dimshuffle(0, 1, 3, 2)

rawDescription: Drawing samples from multinomial using Theano


code:
x = y = np.linspace(-1, 1, 21)
z = np.array([i*i+j*j for j in y for i in x])
Z = z.reshape(21, 21)
plt.imshow(Z, interpolation='bilinear')
plt.show()

rawDescription: How to plot a smooth 2D color plot for z = f(x, y)

description: Plot a smooth 2D color plot for z = f(x, y)


code:
df.groupby(['Country','Date']).agg(lambda x: x[x>0].mean())
df.ix[3, 'Hours'] = -1
df.groupby(['Country','Date']).agg(lambda x: x[x>0].mean())

rawDescription: pandas dataframe groupby: sum/count of only positive numbers

description: Pandas dataframe groupby: sum/count of only positive numbers


rawDescription: Multiple Tuple to Two-Pair Tuple in Python?


rawDescription: I want to extract a string from a string, whose values will change


code: tr[position() > 2 and position() < last()]

rawDescription: how to get tr between two positions

description: Get tr between two positions


code:
from mercurial import commands, extensions, cmdutil, util

cfe = cmdutil.commitforceeditor

def commitforceeditor(repo, ctx, subs):
    text = cfe(repo, ctx, subs)

    # Do not commit unless the commit message differs from
    # the one you specified on the command line
    if ctx.description() == text.strip():
        raise util.Abort("empty commit message")
    else:
        return text

def commit(originalcommit, ui, repo, *pats, **opts):
    if not opts["message"]:
        return originalcommit(ui, repo, *pats, **opts)
    else:
        opts["force_editor"] = True
        opts["message"] += " APPENDED"

        # monkey-patch
        cmdutil.commitforceeditor = commitforceeditor

        return originalcommit(ui, repo, *pats, **opts)

def uisetup(ui):
    extensions.wrapcommand(commands.table, 'commit', commit)

rawDescription: How can I write a basic mercurial extension?

description: Write a basic mercurial extension


code:
def Draw(self) :
    mdc = self.MemoryDC
    dc_width, dc_height = mdc.GetSizeTuple()
    text_width, text_height, descent, externalLeading = mdc.GetFullTextExtent(self.TextString)
    x = (dc_width  - text_width)  / 2
    y = (dc_height - text_height) / 2
    mdc.SetTextForeground('Blue')
    mdc.DrawText(self.TextString, x, y)

rawDescription: Need help working with self.MemoryDC in wxPython


code:
import matplotlib.pyplot as plt
ax = plt.subplot(111)
plt.imshow(...)
ax.yaxis.set_tick_params(labelright=True, labelleft=False)

rawDescription: yticklabels on the opposite axis

description: Yticklabels on the opposite axis


code:
rdata = rdata.reshape(-1, 2)
mask = (rdata != -1).all(1)

# remove every x, y pair that is after a pair with a -1.
mask[1:][mask[:-1] == False] = False
# remove first x, y pair
mask[0] = False

rdata = rdata[mask]

# Now need to use bincount, [::-1], since you use data[y,x]:
flat_rdata = np.ravel_multi_index(tuple(rdata.T)[::-1], (data_height, data_width))

res = np.bincount(flat_rdata, minlength=data_height * data_width)
res = res.reshape(data_height, data_width)

rawDescription: Speed up while loop matching pattern in array


code:
with open('file.txt') as f:
    for line in f:
        print(line.split(',', 1)[0])

rawDescription: Possible to Parse this semi-structured text file using BeautifulSoup or regex in Python


code:
from lxml import html
import requests
import re as regular_expression
import json

page = requests.get("http://www.disastercenter.com/crime/uscrime.htm")
tree = html.fromstring(page.text)

tables = [tree.xpath('//table/tbody/tr[2]/td/center/center/font/table/tbody'),
          tree.xpath('//table/tbody/tr[5]/td/center/center/font/table/tbody')]

tabs = []

for table in tables:
    tab = []
    for row in table:
        for col in row:
            var = col.text_content()
            var = var.strip().replace(" ", "")
            var = var.split('\n')
            if regular_expression.match('^\d{4}$', var[0].strip()):
                tab_row = {}
                tab_row["Year"] = var[0].strip()
                tab_row["Population"] = var[1].strip()
                tab_row["Total"] = var[2].strip()
                tab_row["Violent"] = var[3].strip()
                tab_row["Property"] = var[4].strip()
                tab_row["Murder"] = var[5].strip()
                tab_row["Forcible_Rape"] = var[6].strip()
                tab_row["Robbery"] = var[7].strip()
                tab_row["Aggravated_Assault"] = var[8].strip()
                tab_row["Burglary"] = var[9].strip()
                tab_row["Larceny_Theft"] = var[10].strip()
                tab_row["Vehicle_Theft"] = var[11].strip()
                tab.append(tab_row)
    tabs.append(tab)

json_data = json.dumps(tabs)

output = open("output.txt", "w")
output.write(json_data)
output.close()

rawDescription: Parse HTML table data to JSON and save to text file in Python 2.7


code:
ONE_WAY = True

if ONE_WAY:
    driver.find_element_by_id('oneway-flight-selector').click()
else:
    driver.find_element_by_id('return-flight-selector').click()

rawDescription: How to decide which radio button to click

description: Decide which radio button to click


code:
from flask import send_file

app = Flask(__name__)

@app.route('/get_image')
def get_image():
    return send_file(filename, mimetype='image/gif')

app.run()

rawDescription: flask dummy web app example

description: Flask dummy web app example


code:
class MyTest(unittest.TestCase):
    def setUpClass(cls): ...
    setUpClass = classmethod(setUpClass)

rawDescription: How to write a unittest with setUpClass & tearDownClass in Python 2.3

description: Write a unittest with setUpClass & tearDownClass in Python 2.3


code: foo[var]()

rawDescription: How can I call a class method in the same way a UI event handler does?

description: Call a class method in the same way a UI event handler does


code:
i = 1
fout = open("output0.txt","wb")
for line in fileinput.FileInput(filename):
  fout.write(line)
  i+=1
  if i%40000 == 0:
    fout.close()
    fout = open("output%d.txt"%(i/40000),"wb")

fout.close()

rawDescription: Split large files using python

description: Split large files using python


code:
key = random.choice([key for key, subtree in tree.thedict.items()
                         if subtree.parent and not subtree.isRoot])

rawDescription: Python: what's the pythonic way to perform this loop?


code:
l = [list(range(i, i+4)) for i in range(10,1,-1)]
l
sorted(l, key=sum)

rawDescription: Sort list of list with custom compare function in Python


code:
def parse(self, response):
    title_links  = response.xpath("//td[@class='nblu tabcontent']")
    descriptions = response.xpath("//td[contains(@class,'framed')]")
    for tl,d in zip(title_links, descriptions):
        item = DmozItem()
        item['title']       = tl.xpath("a/big/text()").extract()
        item['link']        = tl.xpath("a/@href").extract()
        item['description'] = d.xpath("b/text()").extract()
        yield item

rawDescription: What would be the correct way to to this to counter multiple xpath selectors?


rawDescription: Using numpy.where() to return the indexes of a full array where the tested condition is on a sliced one


code:
import requests
url = 'http://www.analysis.im/uploads/seminar/pdf-sample.pdf'
requests.get(url)
requests.get(url, headers={'User-Agent': 'firefox'})

rawDescription: Python request returns 404 while curl returns the pdf stream


code:
item = ListCtrl_name.GetItem(instance_location_dictionary [item_name])
ListCtrl_name.Select(item.GetId())

rawDescription: wxPython: ListCtrl finding the item with given string

description: WxPython: ListCtrl finding the item with given string


code:
import os
a = "C:\folder1\folder2\picture.jpg"
b = os.path.basename(a)

rawDescription: How can I get file's name from variable with its full path in python?

description: Get file's name from variable with its full path in python


code: os.system('shutdown -h now')

rawDescription: using result of a python script to invoke shutdown in terminal(ubuntu)

description: Using result of a python script to invoke shutdown in terminal(ubuntu)


code:
def center(win):
    win.update()
    w_req, h_req = win.winfo_width(), win.winfo_height()
    w_form = win.winfo_rootx() - win.winfo_x()
    w = w_req + w_form*2
    h = h_req + (win.winfo_rooty() - win.winfo_y()) + w_form
    x = (win.winfo_screenwidth() // 2) - (w // 2)
    y = (win.winfo_screenheight() // 2) - (h // 2)
    win.geometry('{0}x{1}+{2}+{3}'.format(w_req, h_req, x, y))

rawDescription: Get a Tkinter Toplevel's Size

description: Get a Tkinter Toplevel's Size


code:
class Position(object):
    def __init__(self, lat, lng):
        self.lat = lat
        self.lng = lng

    def __iter__(self):
        yield self.lat
        yield self.lng

pos = Position(30, 50)
print(pos.lat)
# 30
print(pos.lng)
# 50
for coord in pos:
    print(coord)
# 30
# 50
print(list(pos))
# [30, 50]

rawDescription: Python - Implement iteration over certain class attributes on given order


code:
import subprocess
import os
with open(os.devnull, 'w') as fp:
    cmd = subprocess.Popen(("[command]",), stdout=fp)

rawDescription: Suppress output from subprocess.Popen

description: Suppress output from subprocess.Popen


code:
def func(primes):
    for a in range(3, 500, 2):
        for b in range(2, int(a ** 0.5 + 0.5)):
            if a % b != 0:
                primes.append(a)
            if a % b == 0:
                [x for x in primes if x != a]
                return

primes = [2]
func(primes)

rawDescription: Double Break out of Nested Loops

description: Double Break out of Nested Loops


code:
import urllib2

proxy_handler = urllib2.ProxyHandler({})
opener = urllib2.build_opener(proxy_handler)
page = opener.open('http://www.google.com')

rawDescription: Python: Disable http_proxy in urllib2

description: Python: Disable http_proxy in urllib2


code:
scene = GameLogic.getCurrentScene();
pingMeter = scene.objects['Ping Meter'];
red = mathutils.Vector((1.0, 0.0, 0.0, 1.0));
pingMeter.color = red;

rawDescription: Getting an instance of KX_PolygonMaterial in Blender


code:
re.findall("(.+?)\1+", "FFFFFFF")
re.findall(r"(.+?)\1+", "FFFFFFF")

rawDescription: Python is not interpreting regex correctly


code:
# Deal with confusion between ElementTree module and class name
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import ElementTree, Element, SubElement, QName, tostring
from io import BytesIO

# Factored into a constant
GOOG = 'http://base.google.com/ns/1.0'
ET.register_namespace('g', GOOG)

# Make some elements
top = Element('top')
foo = SubElement(top, QName(GOOG, 'foo'))

# This is an alternate, seemingly inferior approach
# Documented here: http://effbot.org/zone/element-qnames.htm
# But not in the Python.org API docs as far as I can tell
bar = SubElement(top, '{http://base.google.com/ns/1.0}bar')

# Now it should output the namespace
print(tostring(top))

# But ElementTree.write() is the one that adds the xml declaration also
output = BytesIO()
ElementTree(top).write(output, xml_declaration=True)
print(output.getvalue())

rawDescription: xml.etree.ElementTree - Trouble setting xmlns = '...'

description: Xml.etree.ElementTree - Trouble setting xmlns = '...'


rawDescription: How can I do this in SQLAlchemy?

description: Do this in SQLAlchemy


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

plt.axis([0,50,60,80])
for i in np.arange(1,5):
    z = 68 + 4 * np.random.randn(50)
    zm = np.cumsum(z) / range(1,len(z)+1)
    plt.plot(zm)

n = np.arange(1,51)
su = 68 + 4 / np.sqrt(n)
sl = 68 - 4 / np.sqrt(n)

plt.plot(n,su,n,sl)

plt.show()

rawDescription: Python equivalent to 'hold on' in Matlab


code:
import os

for dirpath, dnames, fnames in os.walk("./"):
    for f in fnames:
        if f.endswith(".x"):
            x(os.path.join(dirpath, f))
        elif f.endswith(".xc"):
            xc(os.path.join(dirpath,f))

rawDescription: file walking in python

description: File walking in python


rawDescription: plotting list, clearing, then plotting a different list on same window with python

description: Plotting list, clearing, then plotting a different list on same window with python


code:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')

ax.update({'xlabel':'x', 'ylabel':'y', 'zlabel':'z'})

rawDescription: Setting all matplotlib axis labels at once


code:
df['NewVar'] = (df.TrialDur + 0.001).cumsum()
df.loc[df.index[-1]+1, 'NewVar'] = 0
df['NewVar'] = df.NewVar.shift(1)
df.loc[0, 'NewVar'] = 0

rawDescription: python pandas- adding values of a column above the row you're on

description: Python pandas- adding values of a column above the row you're on


code:
import random
random.sample(glob.glob('*.jpg'), number_of_images_to_choose)

rawDescription: Choose a non-repeating random element from a list using Python


code:
from skimage import io, color, measure, draw, img_as_bool
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt

image = img_as_bool(color.rgb2gray(io.imread('bubble.jpg')))
regions = measure.regionprops(image)
bubble = regions[0]

y0, x0 = bubble.centroid
r = bubble.major_axis_length / 2.

def cost(params):
    x0, y0, r = params
    coords = draw.circle(y0, x0, r, shape=image.shape)
    template = np.zeros_like(image)
    template[coords] = 1
    return -np.sum(template == image)

x0, y0, r = optimize.fmin(cost, (x0, y0, r))

import matplotlib.pyplot as plt

f, ax = plt.subplots()
circle = plt.Circle((x0, y0), r)
ax.imshow(image, cmap='gray', interpolation='nearest')
ax.add_artist(circle)
plt.show()

rawDescription: fitting a circle to a binary image

description: Fitting a circle to a binary image


rawDescription: NLTK: Converting from tree values to Lambda function notation


code:
user_key = ndb.Key(User, 'some_username')
a = Achievement(parent=user_key, achievement_name='some_name')

rawDescription: Using Ancestors vs. StructuredProperty for relationships between entities


code:
# open inputfile/read/auto-close
with open('inputfile.txt') as f:
    lines = f.readlines() # with block auto closes file after block is executed

output = []

for line in lines:
    if len(line) > 110:
        while True: # until break
            output.append(line[:107] + '...')
            if len(line[107:]) < 111: # if remainder of line is under 110 chars
                output.append('...' + line[107:])
                break
            line = line[107:] # otherwise loop continues with new line definition
    else:
        output.append(line)

# open outputfile/write/auto-closed
with open('outputfile.txt', 'w') as f:
    for line in output:
        f.write(line)

rawDescription: Python splitting text into blocks of x characters


code:
def tranf(obj):
    date_ret = obj.index.get_level_values('DATE RET')
    return (date_ret - date_ret[0]).days

df['DURATION'] = np.zeros(len(df), dtype='int64')
df['DURATION'] = df.groupby(level='OPR')['DURATION'].transform(tranf)
df

rawDescription: Pandas: Difference with first element of the group


author_username: BP

author_name: ABP

subject: Storage App

author_username: wigv

author_name: wigsv

subject: configuration - RPC-2.1

rawDescription: Custom Json String Format - Could this be written better/improved?


code:
import numpy
from matplotlib import pyplot as plt

X = numpy.array([[6, 32.1, 0, 12],
    [1.112, 6.12, 1, 9],
    [4, 2, 0, 6],
    [2, 3.2, 0, 11]])

Y = numpy.array([0, 1, 1, 2])

# map numbers to rgb colors
Y_color = numpy.zeros(shape=(Y.size, 3))
Y_color[Y == 0] = (1,0,0)
Y_color[Y == 1] = (0,1,0)
Y_color[Y == 2] = (0,0,1)

# use scatter instead of plot
plt.scatter(X[:,0], X[:,1], c=Y_color)
plt.show()

rawDescription: Plotting points based on what value they end up being in matplotlib and numpy


code:
X[condition & (distance_X < distance_Y)] = ...
Y[condition & (distance_Y < distance_X)] = ...

rawDescription: Conditional numpy array modification by the indices


code:
"""Provides a client to interact with Google Data API servers.

This module is used for version 2 of the Google Data APIs. The primary class
in this module is GDClient.

  GDClient: handles auth and CRUD operations when communicating with servers.
  GDataClient: deprecated client for version one services. Will be removed.
"""

rawDescription: What is the different between gdata.client and gdata.service inside gdata-python-client?


code: reward = int(self.rewards.get(next.tipo, next.tipo))

rawDescription: How to manipulate dict properly?

description: Manipulate dict properly


code:
param = '"The.New.York.Times"'
cur.execute("SELECT * FROM predb WHERE Match(name) AGAINST (%s IN BOOLEAN MODE)", (param, ))

rawDescription: Python and Mysql quotes and variables

description: Python and Mysql quotes and variables


code:
with pm.Model() as model:
    alpha = pm.Gamma('alpha', alpha=1, beta=1)
    scale = pm.Gamma('scale', alpha=1, beta=1)

    a = pm.Gamma('a', alpha=alpha, beta=1.0/scale, shape=n_test_participants)

    #mu = T.exp(a[test_participants_idx])
    mu = a[test_participants_idx]

    y = test_df['time_delay'].values
    y_est = pm.Poisson('y_est', mu=mu, observed=y)

    start = pm.find_MAP(fmin=scipy.optimize.fmin_powell)
    step = pm.Metropolis(start=start)
    trace = pm.sample(20000, step, start=start, progressbar=True)

rawDescription: Why does this hierarchical Poisson model not match true params from generated data?


rawDescription: String to int with help of for-loop

description: String to int with help of for-loop


code:
import tkinter as tk

def new_frequency_1000times(k=0):

    if k < 1000:
        freq_out.configure(text=str(k))
        #1000 ms = 1 seconds, adjust to taste.
        root.after(10, lambda: new_frequency_1000times(k+1))

root=tk.Tk()
freq_out = tk.Label(root)
freq_out.grid(row=0, column=1)
button_freq=tk.Button(root, command=new_frequency_1000times, text="Get new f")
button_freq.grid(row=0, column=0)
root.mainloop()

rawDescription: Tkinter's widget.configure inside a while loop


code:
import matplotlib.pyplot as plt

segments = {1: [(0, 500),
                (915, 1000)],
            2: [(0, 250),
                (500, 1000)]}

colors = {1: 'b', 2: 'r'}

for y in segments:
    col = colors.get(y, 'k')
    for seg in segments[y]:
        plt.plot(seg, [y, y], color=col)

rawDescription: How to plot interrupted horizontal lines (segments) in matplotlib in a "cheap way" without using NaNs?

description: Plot interrupted horizontal lines (segments) in matplotlib in a "cheap way" without using NaNs


code:
def find_filename(substring):
    import os
    import re
    files = os.listdir(os.getcwd())
    for file in files:
        search = re.search(substring, file)
        if search:
            filename = file
            break
    return filename

file = find_filename('stringyouwant')
WindowExists(file)

rawDescription: How to use win32gui FindWindow with Wildcard

description: Use win32gui FindWindow with Wildcard


code:
from datetime import time

x = excel_time # a float
x = int(x * 24 * 3600) # convert to number of seconds
my_time = time(x//3600, (x%3600)//60, x%60) # hours, minutes, seconds

rawDescription: Read time from excel sheet using xlrd, in time format and not in float


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

(n, m) = (250, 250)

# Meshing a unit sphere according to n, m
theta = np.linspace(0, 2 * np.pi, num=n, endpoint=False)
phi = np.linspace(np.pi * (-0.5 + 1./(m+1)), np.pi*0.5, num=m, endpoint=False)
theta, phi = np.meshgrid(theta, phi)
theta, phi = theta.ravel(), phi.ravel()
theta = np.append(theta, [0.]) # Adding the north pole...
phi = np.append(phi, [np.pi*0.5])
mesh_x, mesh_y = ((np.pi*0.5 - phi)*np.cos(theta), (np.pi*0.5 - phi)*np.sin(theta))
triangles = mtri.Triangulation(mesh_x, mesh_y).triangles
x, y, z = np.cos(phi)*np.cos(theta), np.cos(phi)*np.sin(theta), np.sin(phi)

# Defining a custom color scalar field
vals = np.sin(6*phi) * np.sin(3*theta)
colors = np.mean(vals[triangles], axis=1)

# Plotting
fig = plt.figure()
ax = fig.gca(projection='3d')
cmap = plt.get_cmap('Blues')
triang = mtri.Triangulation(x, y, triangles)
collec = ax.plot_trisurf(triang, z, cmap=cmap, shade=False, linewidth=0.)
collec.set_array(colors)
collec.autoscale()
plt.show()

rawDescription: Colouring the surface of a sphere with a set of scalar values in matplotlib


rawDescription: Using a database in a Django view

description: Using a database in a Django view


code:
def combinations(S,K):
    return S**K;

rawDescription: How to count the number of possible combinations to fill an arrray of K boxes and S symbols

description: Count the number of possible combinations to fill an arrray of K boxes and S symbols


code:
import string
import itertools

chars = string.digits + string.letters
MAX_CHARS = 4
for nletters in range(MAX_CHARS):
    for word in itertools.product(chars, repeat=nletters + 1):
        print (''.join(word))

rawDescription: Replace Nested For Loops... or not

description: Replace Nested For Loops... or not


code:
from gi.repository import Gtk
mymodel = Gtk.ListStore()
Gtk.TreeModelSort(model=mymodel)

rawDescription: A sorted and filtered treemodel in Python Gtk+3..?


rawDescription: replace value in an numpy ndarrary

description: Replace value in an numpy ndarrary


code:
# memways(n, k, coins) = number of ways of making
# change of n with less or equal k coins
calculated = {}
def memways(n, k, coins):
    if n<0:
        return 0
    if (n, k) in calculated:
        return calculated[n,k]
    if k == 0:
        v = 1
    else:
        v = memways(n-coins[k], k, coins) + memways(n, k-1, coins)
    calculated[n,k] = v
    return v

rawDescription: Complexity of this algorithm in big O notation?


code:
import logging
import pygtk
import gtk

class MyHandler(logging.Handler):
    def __init__(self, label):
        logging.Handler.__init__(self)
        self.label = label

    def handle(self, rec):
        original = self.label.get_text()
        self.label.set_text(rec.msg + "\n" + original)

class MyLogger():
    def __init__(self, label):
        self.logger = logging.getLogger("Example")
        self.handler = MyHandler(label)
        #self.handler.setLevel(logging.INFO)
        self.logger.addHandler(self.handler)

    def warning(self, msg):
        self.logger.warning(msg)

class MainWindow(gtk.Window):
    def __init__(self):
        gtk.Window.__init__(self)
        self.set_size_request(200, 100)
        self.connect("delete-event", self.on_delete_event)

        self.loglabel = gtk.Label()
        self.add(self.loglabel)

        self.show_all()

    def run(self):
        gtk.mainloop()

    def on_delete_event(self, w, d):
        gtk.main_quit()

def main():
    mw = MainWindow()

    logger = MyLogger(mw.loglabel)
    logger.warning("This is a test message")
    logger.warning("This is another message")

    mw.run()
    return 0

if __name__ == '__main__':
    main()

rawDescription: Logging messages to pygtk.entry

description: Logging messages to pygtk.entry


code:
def addodds2(x,y):
    total=0
    if y<len(x):    #you don't need a while there
        a=x[y]      #you have to do this operation if y<len(x), otherwise you would get the index error you are getting
        if a%2!=0:
            total+=a
        return total+addodds2(x,y+1)    #you have to sum the current total to the result returned by the addodds2() function (otherwise you would got 0 as the final result)
    return total

print(addodds2([3,2,4,7,2,4,1,3,2],0))

rawDescription: Recursive Function in Python adding Odd Values in List


code:
import re
newstring = re.sub(r'\(name:\s*([^)]+)\)',
                   r'\1',
                   old_string)

rawDescription: Python Regex - search and replace matches


code:
@gen.coroutine
def broadcast_message(self, message):
    count = 0
    for client in self.clients:
        client.write_message(message)
        count += 1
        if count % 100 == 0:
            yield gen.moment

rawDescription: Broadcasting a message using Tornado

description: Broadcasting a message using Tornado


code: "".join((char if char.isalpha() else " ") for char in test).split()

rawDescription: Dividing a string at various punctuation marks using split()


code:
import re
pattern = re.compile('|'.join(['ASSESSMENTS','KILOBYTE','INTERNATIONAL']))
isMatch = (pattern.search(thing_name) != None)

rawDescription: Searching string for different substrings


code:
import Tkinter as tk
#or from Tkinter import Canvas, Label, Tk

L1 = [0, 0, 0, 1]
L2 = [1, 0, 1, 2]
L3 = [2, 0, 2, 3]
L4 = [3, 0, 3, 4]
L5 = [4, 0, 4, 5]

top = tk.Tk()
canvas = tk.Canvas(top, width=500, height=500)

offset = 1
scale = 50
count = 1

for L in [L1, L2, L3, L4, L5]:
    canvas.create_line(*[scale*(i + offset) for i in L])
    #create label and place it above line
    lbl = tk.Label(top, text = "%sx"%(count))
    lbl.place(x=scale * count, y=20)
    #add to count manually
    count += 1

canvas.pack()
top.mainloop()

rawDescription: Labeling lines (Tkinter)

description: Labeling lines (Tkinter)


code: [eval(i, {"__builtins__":None}) for i in ['6.2', '"Hello, world!"', '7']]

rawDescription: Interpreting Strings as Other Data Types in Python


code:
d = {'1111758': ('TTAGAGTTTGATCCTGGCTCAGAACGAACGCTGGCGGCAGGCCTAA\n', ''),
'1111762': ('AGAGTTTGATCCTGGCTCAGATTGA\n', ''),
'1111763': ('AGAGTTTGATCCTGGCCTT\n', '') }
lis = []
for tup in d.values():
    lis.append(tup[0].rstrip('\n'))
''.join(lis)

rawDescription: concatenate the values of dictionary into single string or sequence

description: Concatenate the values of dictionary into single string or sequence


code:
import datetime

time_str = datetime.datetime.now().strftime("%Y%m%dT%H%M%S")
file_name_format = '/home/user/Desktop/DVH/dvh-%s_%s.txt'
file_name = file_name_format%(name.replace("/","-"), time_str)
np.savetxt(file_name, dvh1, delimiter=',')

rawDescription: Get time stamp on a automatic saved text file


rawDescription: Fetching only required string from the list


code:
import os
import parser
import unittest

class TestParser(unittest.TestCase):

    def setUp(self):
        self.raw_dir = "raw"

    def get_path(self, filename):
        path = os.path.join(self.raw_dir, filename)
        return path

    def file_parse(self, filename):
        # every method of this class being supposed to call
        # the parser, it makes sense to isolate these calls
        # into a specific method to avoid repetition
        # - won't be the same is the class is more general-purpose
        path = self.get_path(filename)
        actual = parser.parse(path)
        return actual

    def test_case_1(self):
        actual = self.file_parse(filename='case_1.csv')
        # assert actual == expected

    def test_case_2(self):
        actual = self.file_parse(filename='case_2.csv')
        # assert actual == expected

rawDescription: Python Unittesting: Design directory structure for mock input?


code:
from collections import OrderedDict
s = "mathematics"
alpha = "abcdefghiklmnopqrstuvwxyz"
d = OrderedDict.fromkeys(s+alpha)
d
''.join(d)

rawDescription: How to get ordered set?

description: Get ordered set


code:
cursor.execute('SELECT ...')
columns = []
for column in cursor.description:
    columns.append(column[0].lower())
failed_sites = {}
for row in cursor:
    for i in range(len(row)):
        failed_sites[columns[i]] = row[i]
        if isinstance(row[i], basestring):
             failed_sites[columns[i]] = row[i].strip()

rawDescription: Obtaining data from PostgreSQL as Dictionary


code:
@app.route('/my_endpoint', methods=['POST'])
def my_endpoint_handler():
    #do tracking in sub-thread so we don't hold up the page
    def handle_sub_view(req):
        with app.test_request_context():
            from flask import request
            request = req
            # Do Expensive work
    thread.start_new_thread(handle_sub_view, (request))
    return "Thanks"

rawDescription: Flask throwing 'working outside of request context' when starting sub thread


code:
class CsrfExtension(jinja2.ext.Extension):
    r""" Adds a {% csrf %} tag to Jinja. """

    tags = set(['csrf', 'csrf_token'])
    template = u'<input type="hidden" name="csrfmiddlewaretoken" value="%s">'

    def parse(self, parser):
        lineno = next(parser.stream).lineno
        ctx_ref = jinja2.nodes.ContextReference()
        node = self.call_method('_render_csrf', [ctx_ref], lineno=lineno)
        return jinja2.nodes.CallBlock(node, [], [], [], lineno=lineno)

    def _render_csrf(self, context, caller):
        csrf_token = context['csrf_token']
        return jinja2.Markup(self.template % unicode(csrf_token))

csrf = CsrfExtension

rawDescription: Jinja Extension that has access to Context


code:
x = [1,2,3,4,5]
y = [4,1,7,8,1]
xy = zip(x, y)
xy
import scipy.spatial.distance as ssd
ssd.cdist(xy, xy)

rawDescription: algorithms to calculate difference of any pair of 2 elements for a vector

description: Algorithms to calculate difference of any pair of 2 elements for a vector


code:
import re
desc = 'FBgn0207418 type=gene; loc=scaffold_12875:complement(14361770..14363857); ...'
fields = dict(re.findall(r'(\w+)=(.*?);', desc))
fields['type']
fields['length']

rawDescription: Fasta file description parsing using biopython


code:
import json

# writing
with open("Recipe.txt","w") as recipefile:
    json.dump({
        'name': name, 'numing': numing, 'orignumpep': orignumpep,
        'ingredient': ingredient, 'quantity': quantity, 'units': units},
        recipefile, sort_keys=True, indent=4, separators=(',', ': '))

# reading
with open("Recipe.txt") as recipefile:
    recipedata = json.load(recipefile)

# optional, but your code requires it right now
name = recipedata['name']
numing = recipedata['numing']
orignumpep = recipedata['orignumpep']
ingredient = recipedata['ingredient']
quantity = recipedata['quantity']
units = recipedata['units']

rawDescription: Writing and reading lists to text files in Python: Is there a more efficient way?


code:
from urllib2 import urlopen
from bs4 import BeautifulSoup

URL = "url here"

soup = BeautifulSoup(urlopen(URL))
links = soup.select('.topline > a')
for a in links:
    link = link.get('href')
    if link:
        # follow link
        link_soup = BeautifulSoup(urlopen(link))
        title = link_soup.find('title')
        # check title

rawDescription: Parse multiple URLs and extract data

description: Parse multiple URLs and extract data


code:
from retrying import retry
from selenium import webdriver
from timeoutcontext import timeout, TimeoutException

def retry_if_timeoutexception(exception):
    return isinstance(exception, TimeoutException)

@retry(retry_on_exception=retry_if_timeoutexception, stop_max_attempt_number=3)
@timeout(30)  # Allow the function 30 seconds to create and return the object
def get_browser():
    return webdriver.Chrome()

rawDescription: Python Selenium Failing When Some Threads Create Webdriver


code:
def division_factory(quotient):
    def divide(divisor):
        return divmod(quotient, divisor)
    return divide

divide_81_by = division_factory(81)
divide_81_by(3) # (27, 0)

rawDescription: Generating Functions with Functions

description: Generating Functions with Functions


code:
with open(bom_filename, 'r') as my_file:
    file_array = [word.strip() for word in my_file if word.startswith("/")]

rawDescription: Python: Stripping elements of a string array based on first character of each element


rawDescription: Python using 'OR with Regex

description: Python using 'OR with Regex


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

# data to plot
data1  = np.array((50, 35, 30, 33, 60))
data2 = np.array((25, 32, 34, 20, 5))

# find the size of the grey bar to be plotted at the top
ymax = 100
s = np.shape(data1)
n = s[0]
top = ymax*np.ones((n,)) - data1 - data2

ind = np.arange(n) # the x locations for the groups
width = 0.35 # the width of the bars

p1 = plt.bar(ind, data1, width, color='g')
p2 = plt.bar(ind, data2, width, color='y', bottom=data1)
p3 = plt.bar(ind, top, width, color ='grey', bottom=data2 + data1)

plt.show()

rawDescription: Matplotlib Set Default Bar for Comparison


code:
#!/usr/bin/python

import time
import sys

i = 0
hello = "hello world, goodbye universe "

while 1:
    print("\r"),

    cur = hello[i:] + hello[0:i]
    print("%s" % cur),
    sys.stdout.flush()

    i += 1
    if (i >= len(hello)):
        i = 0

    time.sleep(0.3)

rawDescription: Print with no new line python

description: Print with no new line python


rawDescription: Get a list of filtered values for a single field from a Django model


code: vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);

rawDescription: python string formatting in javascript

description: Python string formatting in javascript


code:
def get_rand_edges(g, n):
    visited = set()
    results = []
    edges = random.sample(g.edges(), n)
    for edge in edges:
        if edge[0] in visited or edge[1] in visited:
            continue
        results.append(edge)
        if len(results) == n:
            break
        visited.update(edge)
    return results

rawDescription: How to choose edges randomly in my graph?

description: Choose edges randomly in my graph


code:
cursor = db.events.aggregate([
{
    '$group':
    {
        '_id': '$anonymousId',
        'date': { '$first': '$timestamp' },
        'page': { '$push': '$context.page.path' }
    }
},
{
    '$unwind': '$page'
}
])

rawDescription: MongoDB return fields after group aggregation


code:
common = word_counts.most_common(num)[0]
for i in range(3):
    print("WORD: %s \nOCCURENCE: %d \n" % (common[i][0], common[i][1]))

rawDescription: Only print specific amount of Counter items, with decent formatting


code:
def handleItemClicked(self, account):
    try:
        accountsSelected = set()

        for account in range(self.mainAccountTable.rowCount()):
            if self.mainAccountTable.cellWidget(account, 0).findChild(type(QCheckBox())).isChecked():
                accountsSelected.add(self.mainAccountTable.item(account, 1).text())
                print ("selected:",accountsSelected)
        for account in range(self.mainAccountTable.rowCount()):
            if not self.mainAccountTable.cellWidget(account, 0).findChild(type(QCheckBox())).isChecked():
                accountsSelected.remove(self.mainAccountTable.item(account, 1).text())
                print ("not selected:",accountsSelected)

        print ("main:", accountsSelected)
        return accountsSelected
    except Exception as e:
        print ("error:",e)

rawDescription: PyQt strange behavior on clicked items

description: PyQt strange behavior on clicked items


code:
with open('input.txt') as ifp:
    with open('output.txt', 'w') as ofp:
        tec_seen = False
        empty_line = False
        for line in ifp:
            start_word = line.split(':', 1)[0]
            if start_word in ('Add', 'Name'):
                continue
            if start_word == 'Time':
                tec_seen = False
            if line.lstrip().startswith('k io res tec e'):
                tec_seen = True
                ofp.write(line)
                continue
            if tec_seen and line.strip():
                vals = line.split()
                res = int(vals[2])
                tec = int(vals[3])
                if not 1 <= res <= 3:
                    continue
                if not 4 <= tec <= 7:
                    continue
            else:
                if not line.strip():
                    if empty_line:
                        continue
                    empty_line = True
                else:
                    empty_line = False
            ofp.write(line)

rawDescription: Reading Formatted files in python

description: Reading Formatted files in python


code: blended = ImageChops.darker(image1, image2)

rawDescription: OR operation of two two black and white images using PIL/Pillow


rawDescription: Python: write numpy array contents to file


code:
leg = plot.legend('test') # this is where you create the legend
leg.draggable(True)  # this allows you to move the legend by dragging

rawDescription: are there tools on linux similar to matlab .fig files and it is possible to modify the pic mannually?

description: Are there tools on linux similar to matlab .fig files and it is possible to modify the pic mannually


code: ctypes.c_char_p( liba.say_hi() )

rawDescription: retrieve a `char *` returned from C function exported from .so in Python

description: Retrieve a `char *` returned from C function exported from .so in Python


code:
from django.db.models import Value
from django.db.models.functions import Coalesce

companies = Company.objects.values('name', 'id', 'logo_image').annotate(
    recommendations_score=Coalesce(Avg('companyinternshipreview__recommendation'), Value(0.0))
).annotate(
    apply_skills_score=Coalesce(Avg('companyinternshipreview__apply_skills'), Value(0.0))
).annotate(
    learn_new_score=Coalesce(Avg('companyinternshipreview__learn_new'), Value(0.0))
).order_by('-recommendations_score', '-apply_skills_score', '-learn_new_score')

rawDescription: Pass additional statement to Django model query


code:
#!/usr/bin/env python

import pyfits, os, re, glob, sys
from scipy.optimize import leastsq
from numpy import *
from pylab import *
from scipy import *
rc('font',**{'family':'serif','serif':['Helvetica']})
rc('ps',usedistiller='xpdf')
rc('text', usetex=True)
#------------------------------------------------------

tmin = 56200
tmax = 56249
pi = 3.14
data=pyfits.open('http://heasarc.gsfc.nasa.gov/docs/swift/results/transients/weak/GX304-1.orbit.lc.fits')

time  = data[1].data.field(0)/86400. + data[1].header['MJDREFF'] + data[1].header['MJDREFI']
rate  = data[1].data.field(1)
error = data[1].data.field(2)
data.close()

cond = ((time > tmin-5) & (time < tmax))
time=time[cond]
rate=rate[cond]
error=error[cond]

gauss_fit = lambda p, x: p[0]*(1/(2*pi*(p[2]**2))**(1/2))*exp(-(x-p[1])**2/(2*p[2]**2))+p[3]*(1/sqrt(2*pi*(p[5]**2)))*exp(-(x-p[4])**2/(2*p[5]**2)) #1d Gaussian func
e_gauss_fit = lambda p, x, y: (gauss_fit(p, x) -y) #1d Gaussian fit
v0= [0.20, 56210.0, 1, 0.40, 56234.0, 1] #inital guesses for Gaussian Fit, just do it around the peaks
out = leastsq(e_gauss_fit, v0[:], args=(time, rate), maxfev=100000, full_output=1) #Gauss Fit
v = out[0] #fit parameters out
xxx = arange(min(time), max(time), time[1] - time[0])
ccc = gauss_fit(v, xxx) # this will only work if the units are pixel and not wavelength
fig = figure(figsize=(9, 9)) #make a plot
ax1 = fig.add_subplot(111)
ax1.plot(time, rate, 'g.') #spectrum
ax1.plot(xxx, ccc, 'b-') #fitted spectrum
savefig("plotfitting.png")

axis([tmin-10,tmax,-0.00,0.45])

rawDescription: Python: How to fit curves

description: Python: How to fit curves


code:
for x in xrange(W):
	for y in xrange(H):
		p = img_src.getpixel(x, y)
		img_dest.setpixel(H-y-1, W-x-1)

rawDescription: Python image mirroring

description: Python image mirroring


code:
def r2(v):
    return Decimal(v).quantize(Decimal('0.00'))

rawDescription: Python (django) how to deal with money calculations accurately


code:
from robot.libraries.BuiltIn import BuiltIn
results_path = BuiltIn().get_variable_value("${RESULTS_PATH}")

rawDescription: Robot Framework: access robot's global variables from python library code?


code:
import unittest

class MyLiveServerTest(unittest.TestCase):
    def setUp(self):
        self.server = MyServer()
        self.server.start()

    def test_client(self):
        client = MyClient('localhost', self.server.port)
        assert client.get_colour() == "blue"

    def tearDown(self):
        self.server.stop()

rawDescription: Sharing objects between setup and teardown functions in nose


code:
@register.inclusion_tag('admin/submit_line.html', takes_context=True)
def submit_line_row(context):
    context = context or {}
    ctx= admin_modify.submit_row(context)
    if "show_save_as_draft" in context.keys():
        ctx["show_save_as_draft"] = context["show_save_as_draft"]
    return  ctx

rawDescription: how to send extra_context to submit_line.html in django?

description: Send extra_context to submit_line.html in django


code:
import serial
s = serial.Serial("/dev/ttyAMA0")
s.write(open("target.txt","rb").read())

rawDescription: Send file over serial port from Python

description: Send file over serial port from Python


code:
try:
    foo, bar = line.split('-', 1)
except ValueError:
    # not enough values
    foo, bar = line, None

rawDescription: How to handle missing data in split?

description: Handle missing data in split


code:
import pandas as pd
df = pd.DataFrame(graph).T  # transpose to look just like the sheet above
df.to_csv('file.csv')
df.to_excel('file.xls')

rawDescription: How to write a Dictionary to Excel in Python

description: Write a Dictionary to Excel in Python


rawDescription: Is there a way to add a number to the first part of a tuple in a list?


code:
from Tkinter import *
from random import random

root = Tk()
frame = Frame(root, height=200, width=200)

for i in range(10):
    Button(frame, text=str(i)).place(x=random() * 150, y=random() * 180)

frame.pack()
root.mainloop()

rawDescription: Randomly add buttons to Tkinter GUI?

description: Randomly add buttons to Tkinter GUI


rawDescription: Counting consecutive positive value in Python array


code:
g = Github(token)
user = g.get_user()
repo = user.create_repo(full_name)

rawDescription: How to create a new repository with PyGithub

description: Create a new repository with PyGithub


code:
cc
ccd = sparse.spdiags(1./cc.sum(1).T, 0, *cc.shape)
ccn = ccd * cc
np.round(ccn.todense(), 2)
ccn

rawDescription: Efficiently Row Standardize a Matrix

description: Efficiently Row Standardize a Matrix


code:
import sys

def fn(frame, msg, arg):
    if msg != 'call': return
    # Filter as appropriate
    if frame.f_code.co_filename.startswith("/usr"): return
    print("Called", frame.f_code.co_name)
    for i in range(frame.f_code.co_argcount):
        name = frame.f_code.co_varnames[i]
        print("    Argument", name, "is", frame.f_locals[name])

sys.settrace(fn)

def hai(a, b, c):
    print(a, b, c)

hai("Hallo", "Welt", "!")

rawDescription: Print function arguments in sys.settrace in python


code:
a = input("Letter: ")
b = input("Input: ")
words = b.split()
for word in words:
    if a in word:
        print(word)

rawDescription: Printing out a word if it has a specific letter in it?


code:
import nose

argv = sys.argv[:]
argv.insert(1, "--with-doctest")

nose.main(argv=argv)

rawDescription: Run doctest plugin with nose.main

description: Run doctest plugin with nose.main


code:
import os
import collections
import random
import shutil

def get_identifier(path):
    with open(path) as fd:
        return fd.readline().strip()       #assuming you don't want the \n in the identifier

paths = ['/home/file1', '/home/file2', '/home/file3']
destination_dir = '/tmp'
identifiers = collections.defaultdict(list)
for path in paths:
    identifier = get_identifier(path)
    identifiers[identifier].append(path)

for identifier, paths in identifiers.items():
    sample = random.sample(paths, 500)
    for path in sample:
        file_name = os.path.basename(path)
        destination = os.path.join(destination_dir, file_name)
        shutil.copy(path, destination)

rawDescription: Random sample of files based on condition in file


code:
class Main(object):
    def do_stuff(self):
        ...
    def save_work(self):
        ...
    def __init__(self):
        try:
            self.do_stuff()
        except KeyboardInterrupt:
            pass # Or print helpful info
        self.save_work()

rawDescription: Saving work after a SIGINT

description: Saving work after a SIGINT


code:
import os
from tempfile import SpooledTemporaryFile
from flask import Flask
from paramiko import SSHClient

app = Flask(__name__)

@app.route('/remote_download/<path:path>')
def remote_download(path):
    client = SSHClient()
    client.connect('host')
    transfer = client.open_sftp()

    with SpooledTemporaryFile(1024000) as f:  # example max size before moving to file = 1MB
        transfer.getfo(path, f)
        f.seek(0)
        r = app.response_class(f.read(), mimetype='application/octet-stream')

    r.headers.set('Content-Disposition', 'attachment', filename=os.path.basename(path))
    return r

app.run()

rawDescription: Serve file downloaded with Paramiko SFTP in Flask


code: listofwords[randomval], removed_word = substitute_word, listofwords[randomval]

rawDescription: Python: Is there an easier way to remove and replace an item in a list?


code:
file = open("save_file.txt")

for each_line in file:
    s = {}
    (s['name'], s['race'], s['class'], s['FOR'], s['INT'], s['DES']) = each_line.split(";")
    print(s['name'])
    print(s['race'])
    print(s['class'])
    print(s['FOR'])
    print(s['INT'])
    print(s['DES'])
    print(s['name'])
file.close()

rawDescription: How to print more lines?

description: Print more lines


code:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', port))

rawDescription: nc from host -> VM works (port 9050), but VM (running server written in Python) resets connection [TCP RST] from host -> VM on same port (9050)

description: Nc from host -> VM works (port 9050), but VM (running server written in Python) resets connection [TCP RST] from host -> VM on same port (9050)


code:
class rowarray():
    def __init__(self, arr):
        self.rows = []
        for row in arr:
            nonzeros = np.nonzero(row)[0]
            nzvalues = { i: row[i] for i in nonzeros }
            self.rows.append((set(nonzeros), nzvalues))

    def __getitem__(self, key):
        return self.rows[key]

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

class colarray(rowarray):
    def __init__(self, arr):
        rowarray.__init__(self, arr.T)

def maybe_less_naive(A, B, rows, cols):
    N = len(rows)
    vals = []
    for n in xrange(N):
        nz1,v1 = A[rows[n]]
        nz2,v2 = B[cols[n]]
        # list of common non-zeros
        nz = nz1.intersection(nz2)
        # sum of non-zeros
        vals.append(sum([ v1[i]*v2[i] for i in nz]))

    R = sps.coo_matrix((np.array(vals), (np.array(rows), np.array(cols))), shape=(len(A), len(B)), dtype=np.float64)
    return R

D = 1000

Ap = np.random.randn(D, D)
Ap[np.abs(Ap) > 0.1] = 0
A = rowarray(Ap)
Bp = np.random.randn(D, D)
Bp[np.abs(Bp) > 0.1] = 0
B = colarray(Bp)

X = np.random.randn(D, D)
X[np.abs(X) > 0.1] = 0
X[X != 0] = 1
X = sps.csr_matrix(X)
rows, cols = X.nonzero()
maybe_less_naive(A, B, rows, cols)

rawDescription: Sparse matrix multiplication when results' sparsity is known (in python|scipy|cython)


code:
shared_private_key = "ABCDEF"

def create_signature(data):
    return hashlib.sha1(repr(data) + "," + shared_private_key).hexdigest()

def verify_signature(data, signature):
    return signature == create_signature(data)

rawDescription: basics of python encryption w/ hashlib sha1

description: Basics of python encryption w/ hashlib sha1


code:
Code
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
from scipy.optimize import brentq
from sklearn.neighbors.kde import KernelDensity

# Generate normal functions
x_axis = np.linspace(-3, 3, 100)
gaussianA = norm.pdf(x_axis, 2, 0.5)  # mean, sigma
gaussianB = norm.pdf(x_axis, 0.1, 1.5)

# Random-sampling from functions
a_samples = norm.rvs(2, 0.5, size=100)
b_samples = norm.rvs(0.1, 1.5, size=100)

# Fit KDE
def kde_sklearn(x, x_grid, bandwidth=0.2, **kwargs):
    """Kernel Density Estimation with Scikit-learn"""
    kde_skl = KernelDensity(bandwidth=bandwidth, **kwargs)
    kde_skl.fit(x[:, np.newaxis])
    # score_samples() returns the log-likelihood of the samples
    log_pdf = kde_skl.score_samples(x_grid[:, np.newaxis])
    return kde_skl, np.exp(log_pdf)

kdeA, pdfA = kde_sklearn(a_samples, x_axis, bandwidth=0.25)
kdeB, pdfB = kde_sklearn(b_samples, x_axis, bandwidth=0.25)

# Find intersection
def findIntersection(fun1, fun2, lower, upper):
    return brentq(lambda x : fun1(x) - fun2(x), lower, upper)

funcA = lambda x: np.exp(kdeA.score_samples([[x]][0]))
funcB = lambda x: np.exp(kdeB.score_samples([[x]][0]))

result = findIntersection(funcA, funcB, -3, 3)

# Plot
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x_axis, gaussianA, color='green')
ax1.plot(x_axis, gaussianB, color='blue')
ax1.set_title('Original Gaussians')
ax2.plot(x_axis, pdfA, color='green')
ax2.plot(x_axis, pdfB, color='blue')
ax2.set_title('KDEs of subsampled Gaussians')
ax2.axvline(result, color='red')
plt.show()

rawDescription: python: finding the intersection of two gaussian_kde functions (objects)

description: Python: finding the intersection of two gaussian_kde functions (objects)


code:
from Tkinter import * # tkinter in Python 3

root = Tk()
root.withdraw()

top = Toplevel(root)
top.protocol("WM_DELETE_WINDOW", root.destroy)

but = Button(top, text='deiconify')
but['command'] = root.deiconify
but.pack()

root.mainloop()

rawDescription: Toplevel in Tkinter: Prevent Two Windows from Opening


code:
x = b"\xaa\xbb\xcc\xdd"

import struct

struct.unpack('I',x)
Out[3]: (3721182122,)

y = struct.unpack('I',x)

y[0]
Out[5]: 3721182122

hex(y[0])
Out[6]: '0xddccbbaa'

rawDescription: How to simply have python print "\xaa\xbb\xcc\xdd" as 0xddccbbaa?

description: Simply have python print "\xaa\xbb\xcc\xdd" as 0xddccbbaa


code: dfjoin = dfjoin[dfjoin['col4_x'] != dfjoin['col4_y']]

rawDescription: where condition with inner join in pandas

description: Where condition with inner join in pandas


code:
def __radd__(self,other):
    return self.offset + other

rawDescription: Allow a custom python class to add in both directions


code:
html = urllib.urlopen('http://www.nytimes.com/2009/12/21/us/21storm.html').read()
soup = BeautifulSoup(html, 'html.parser')
texts = soup.findAll(text=True)

def visible(element):
    if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
        return False
    elif re.match('<!--.*-->', str(element)):
        return False
    return True

visible_texts = filter(visible, texts)

rawDescription: BeautifulSoup Grab Visible Webpage Text

description: BeautifulSoup Grab Visible Webpage Text


code:
a = "['item 1', 'item 2', 'item 3']"
eval(a)
eval(a)[2]

rawDescription: Python: String to list (without split)

description: Python: String to list (without split)


code:
from gi.repository import Gtk, Gdk
import string

class Window(Gtk.Window):
    def __init__(self):
        super().__init__()
        self.connect('delete-event', Gtk.main_quit)
        self.set_size_request(200, 150)
        flowbox = Gtk.FlowBox()
        self.add(flowbox)

        for x in string.ascii_lowercase:
            eventbox = Gtk.EventBox()
            eventbox.add(Gtk.Label(label=x))
            flowbox.add(eventbox)
            eventbox.connect('button-press-event', self.on_button_press)

    def on_button_press(self, widget, event):
        if event.button == 3:
            print('Right click on: ' + widget.get_child().get_text())

win = Window()
win.show_all()
Gtk.main()

rawDescription: Gtk+ 3 make GtkTreeView render columns horizontally


code:
import os
os.environ['NAME'] = 'VALUE'

rawDescription: IPython env magic on Windows 7

description: IPython env magic on Windows 7


code:
def launch(exp):
    # check if exe or py
    if (exp.endswith(".exe")):                  # So it's an exe.
        a=subprocess.Popen(exp)
        a1=os.system(exp)
    else:                                       # Otherwise is a .py
       # Launch a compiled PsychoPy experiment (.py) via subprocess.
        command = [sys.executable, '-u', exp] # spaces in file names are ok
        proc = subprocess.Popen(command)
        proc.communicate()
        del proc

# And just put your exe filename between the two py files.
expts = ['myPythonFile1.py', r'myEXEfile.exe', 'myPythonFile2.py']
for exp in expts:
    launch(exp)

rawDescription: how to run both a .py and a .exe file from the same python script

description: Run both a .py and a .exe file from the same python script


code:
trees = {}
min_idx = (1, N)
min_length = N
first_index = -1
for i in range(N):
    trees[alley[i]] = i
    if len(trees) == K:
        if first_index == -1 or alley[first_index] == alley[i]:
            first_index = min(trees.values())
        idx = (first_index+1, i+1)
        length = idx[1] - idx[0] + 1
        if length < min_length:
            min_idx = idx
            min_length = length
            if min_length == K:
                break

rawDescription: find minimum-length subarray that has all numbers

description: Find minimum-length subarray that has all numbers


rawDescription: Confusion in working of Decimal and Round function


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

x, y = np.arange(0,101,1) ,300 - 0.1*np.arange(0,101,1)
mask = (x >= 50) & (x <= 100)

fig, ax = plt.subplots()
ax.scatter(x[mask], y[mask])

plt.show()

rawDescription: Matplotlib - fixing x axis scale and autoscale y axis


code: sorted(my_list, key=lambda item: (item.split()[:-1], 'Back' in item))

rawDescription: Python custom sort by multiple factors

description: Python custom sort by multiple factors


code:
def writecode (q, a, b, c):
    results = []
    while b < q:
        b = b + 1
        results.append("v%d_%d_%d = pairwise (caps[%d],sals[%d],poss[%d],poss[%d],poss[%d],pos_range)" % (a,b,c,a,a,a,b,c))
        results.append("votes%d_%d.append(v%d_%d_%d)" % (b,c,a,b,c,))
        results.append("v%d_%d_%d = pairwise (caps[%d],sals[%d],poss[%d],poss[%d],poss[%d],pos_range)" % (a,c,b,a,a,a,c,b))
        results.append("votes%d_%d.append(v%d_%d_%d)" % (c,b,a,c,b))
        results.append("")
    return "\n".join(results)

x = writecode (5,1,0,4)

out_file = open("code.txt", "a")
out_file.write(x)
out_file.close()

rawDescription: Function iterates with print but not with return


code:
element = root.xpath("path/to/element")
element[0].tail = None
string = tostring(element[0])

rawDescription: Python lxml etree remove tail from element


code: pd.read_fwf("296.dat", skiprows=[1])

rawDescription: Not able to retrieve data in a particular columns with Python


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

fig, axes = plt.subplots(nrows=4, ncols=4, sharex=True, sharey=True)

# "axes" is a 2D array of axes objects.  You can index it as axes[i,j]
# or iterate over all items with axes.flat

# Plot on all axes
for ax in axes.flat:
    x, y = 10 * np.random.random((2, 20))
    colors = np.random.random((20, 3))
    ax.scatter(x, y, s=80, facecolors=colors, edgecolors='')
    ax.set(xticks=np.linspace(0, 10, 6), yticks=np.linspace(0, 10, 6))

# Operate on just the top row of axes:
for ax, label in zip(axes[0, :], ['A', 'B', 'C', 'D']):
    ax.set_title(label, size=20)

# Operate on just the first column of axes:
for ax, label in zip(axes[:, 0], ['E', 'F', 'G', 'H']):
    ax.set_ylabel(label, size=20)

plt.show()

rawDescription: Automate the Populating of Subplots

description: Automate the Populating of Subplots


rawDescription: Print multidimensional list in python3

description: Print multidimensional list in python3


code:
def coordinates():
    userx = int(input("Please enter a number for coordinate x"))
    usery = int(input("coordinate y"))

    accepted = False
    if userx in range(0, 600):
        print("invalid x coordinate")
    else:
        accepted = True
        print("ok")

    accepted2 = False
    if usery in range(0, 400):
        print("invalid y coordinate")
    else:
        accepted2 = True
        print("ok")

    if accepted and accepted2:
        print("coordinates are ok")
    else:
        print("coordinates are not ok")

coordinates()

rawDescription: Comparing IF statements to a final script with outcome


code:
path_definition = {
       '00:00:00:00:00:01':'00:00:00:00:00:04',
       '00:00:00:00:00:02':'00:00:00:00:00:05',
       '00:00:00:00:00:03':'00:00:00:00:00:06' #comma not required
} #Semicolon not required

for key in path_definition.keys(): #semicolon missing
      print('value {}'.format(path_definition[key])) #extra parentheses missing

rawDescription: Getting value using key in dictionary in python not working


rawDescription: Accessing models by variable model name in django


code:
from multiprocessing import Pool

def get_user(users):
    return [u for u in users if 'N' in u]

def main(users):
    vusers = []
    results = []

    N = 2
    chunk = 200

    pool = Pool(N)
    for i in range(0, len(users), chunk):
        r = pool.apply_async(get_user, args=(users[i:i + chunk],))
        results.append(r)

    pool.close()
    pool.join()

    for r in results:
        vusers.extend(r.get())

    return vusers

if __name__ == '__main__':
    import random
    import string
    users = [random.sample(string.ascii_uppercase, 5) for i in range(10000)]
    vusers = main(users)

rawDescription: multithread in Python (is my code correct)

description: Multithread in Python (is my code correct)


code:
class PageDetailView(DetailView):
    ...

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(PageDetailView, self).get_context_data(**kwargs)
        # Add extra context from another model
        context['other_model'] = OtherModel.objects.get(...)
        return context

rawDescription: Django - Get data from another model in Detailview


code: plt.scatter([x], [y], color='g') # Replace x and y to the coordinate you want

rawDescription: How do I change the color of a scatterpoint in the legend?

description: Change the color of a scatterpoint in the legend


code:
def vprod(x):
    y = np.atleast_2d(x)
    return np.dot(y.T, y)

rawDescription: Transpose of a vector using numpy

description: Transpose of a vector using numpy


code: os.system("taskkill /pid " +str(pid)+ " /t")

rawDescription: Closing a program using python?

description: Closing a program using python


code:
from sqlalchemy.engine.url import URL

myDB = URL(drivername='mysql', host='localhost',
    database='my_database_name',
    query={ 'read_default_file' : '/path/to/.my.cnf' }
)
engine = create_engine(name_or_url=myDB)
# use the engine as usual, no password needed in your code file :)

rawDescription: how to use mysql defaults file (my.cnf) with sqlalchemy?

description: Use mysql defaults file (my.cnf) with sqlalchemy


code:
from Tkinter import Text
help(Text.keys)
Text().keys()

rawDescription: How to call method keys in Python 3

description: Call method keys in Python 3


code:
from modulefinder import ModuleFinder

finder = ModuleFinder()
finder.run_script('my_script.py')

for name, mod in finder.modules.iteritems():
    print(name)

rawDescription: How to list imports within a Python module?

description: List imports within a Python module


code:
df = pd.DataFrame(np.random.randn(10, 2), columns=['A', 'B'])
df
df.sort(columns='A', inplace=True)
df['A'].plot(use_index=False)

rawDescription: Is this a python pandas DataFrame post sort plot bug?


code:
valid_ratings = ratings.astype(bool)
user_matrix = valid_ratings.multiply(ratings[user_id])

rawDescription: Repeat a csr_matrix row over axis 0 to create a matrix


code:
result = [[my_function(x, y)
           for x in arange(0.3, 10.7, 2.2)]
          for y in arange(-3.2, 5.4, 0.7)]

rawDescription: python array indexing when using for arange loops

description: Python array indexing when using for arange loops


code:
import __future__
eval(compile('1/3', '<string>', 'eval', __future__.division.compiler_flag))

rawDescription: Python: eval() that coerces values to floating point?


code:
from math import factorial
def ErlangB (E, m):
    InvB = 1.0
    for j in range(1, m+1):
        InvB = 1.0 + InvB * (j/E)
    return (1.0 / InvB)

def ErlangC(A, N):
    L = (A**N/factorial(N)) * ( N/(N-A) )
    sum_ = 0
    for i in range(N-1):
        sum_ += (A**i)/factorial(i)
    return ( L / (sum_ + L) )

rawDescription: How to wtite Erlang B and Erlang C formulas in Python

description: Wtite Erlang B and Erlang C formulas in Python


rawDescription: What are the default URLs for Django's User Authentication system?


code:
from itertools import groupby
result = [max(group) for r, group in groupby(your_list, lambda x: x == 1) if not r]

rawDescription: Give me highest element

description: Give me highest element


code:
colors = {'A': 'b','B': 'purple', 'C': 'r','D' : 'grey','E' : 'green', 'F' : 'magenta'}
size= 1000

fig1, ax1 = plt.subplots(figsize=(10,8))

for t in ('A','B','C'):
    ax1.scatter(ds[ds['Label']==t]['factor2'], ds[ds['Label']==t]['factor1'],
                color=colors[t],
                label=t,
                s=size,
                alpha=0.7)

for label, x, y in zip(ds['Year'], ds['factor2'], ds['factor1']):
    ax1.annotate(label, xy = (x + 0.008, y - 0.003),fontsize = 15)
ax1.legend(markerscale=0.2)

rawDescription: Pandas/Matplotlib annotate on one column and label on another


code:
class SuperModel(type):
    def __new__(cls, name, base, attrs):
        if 'collection' not in attrs:
            attrs['collection'] = name.lower()

    return super().__new__(cls, name, base, attrs)

rawDescription: Python class specific global attributes

description: Python class specific global attributes