code:
"""declarative

Revision ID: 169ad57156f0
Revises: 29b4c2bfce6d
Create Date: 2014-06-25 09:00:06.784170
"""

revision = '169ad57156f0'
down_revision = '29b4c2bfce6d'

from alembic import op
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship

Session = sessionmaker()
Base = declarative_base()

class Foo(Base):
    __tablename__ = 'foo'

    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String, nullable=False, unique=True)

class Bar(Base):
    __tablename__ = 'bar'

    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String, nullable=False, unique=True)
    foos = relationship(Foo, lambda: foo_bar, backref='bars')

foo_bar = sa.Table(
    'foo_bar', Base.metadata,
    sa.Column('foo_id', sa.Integer, sa.ForeignKey('foo.id'), primary_key=True),
    sa.Column('bar_id', sa.Integer, sa.ForeignKey('bar.id'), primary_key=True)
)

def upgrade():
    bind = op.get_bind()

    Base.metadata.create_all(bind=bind)

    session = Session(bind=bind)
    session._model_changes = False  # if you are using Flask-SQLAlchemy, this works around a bug

    f1 = Foo(name='f1')
    f2 = Foo(name='f2')
    b1 = Bar(name='b1')
    b2 = Bar(name='b2')

    f1.bars = [b1, b2]
    b2.foos.append(f2)

    session.add_all([f1, f2, b1, b2])
    session.commit()

def downgrade():
    bind = op.get_bind()

    # in this case all we need to do is drop the tables
    # Base.metadata.drop_all(bind=bind)

    # but we could also delete data
    session = Session(bind=bind)
    session._model_changes = False  # if you are using Flask-SQLAlchemy, this works around a bug

    b1 = session.query(Bar).filter_by(name='b1').one()

    session.delete(b1)
    session.commit()

rawDescription: alembic create_table using declarative_base derived objects

description: Alembic create_table using declarative_base derived objects


code:
import boto.s3
conn = boto.s3.connect_to_region('us-east-1')
bucket = conn.get_bucket('mybucket')
keys = list(bucket.list(prefix='folder1/folder2/'))
keys.sort(key=lambda k: k.last_modified)

rawDescription: process the files in S3 based on their timestamp using python and boto

description: Process the files in S3 based on their timestamp using python and boto


code:
import numpy as np
from astropy import wcs

#create data
ra = np.random.uniform(130., 135., 1000)
dec = np.random.uniform(-55., -57., 1000)

#create wcs object
w = wcs.WCS(naxis=2)
# set coordinate and projection types for each axis
w.wcs.ctype = ["RA---ARC", "DEC--ARC"]

#do the projection
pixel_coords = w.wcs_world2pix(ra, dec, 1)

rawDescription: Perform coordinates projection with astropy


code:
import pandas as p
import csv
csv_list=['interview1.csv', 'interview2.csv', ...]
for itw in csv_list:
    df = p.read_csv(itw)
    df.to_csv('out.csv', mode='a')

rawDescription: Reading multiple csv files and writing it to another csv file


rawDescription: Pandas replace nan with mean value for a given grouping


code:
import numpy as np

def conv(x):
    return x.replace(',', '.')

data = np.genfromtxt((conv(x) for x in open("test.txt")), delimiter=';')

rawDescription: numpy genfromtxt converters unknown number of columns

description: Numpy genfromtxt converters unknown number of columns


code:
header = {
    'Content-Type': 'application/json',
    'Authorization': 'OAUTH2 access_token=%s' % (authToken)
}

rawDescription: What is the best way to store a string variable as a string value in a dictionary?


code:
import SimpleCV as scv
cam = scv.Camera()
del cam

rawDescription: How to stop SimpleCV camera stream?

description: Stop SimpleCV camera stream


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(3,3,sharex='col', sharey='row')

counter = 0
for j in range(9):
    if j in [0,3,6]:
        axes.flat[j].set_ylabel('Row '+str(counter), rotation=0, size='large',labelpad=40)
        axes.flat[j].set_title('plot '+str(j))
        counter = counter + 1
    if j in [0,1,2]:
        axes.flat[j].set_title('Column '+str(j)+'\n\nplot '+str(j))
    else:
        axes.flat[j].set_title('plot '+str(j))

plt.show()

rawDescription: Multiple titles (suptitle) with subplots


code:
following = UserFollows.objects.filter(user__id = user.id).select_related('user')
users_ids = [follow.user.id for follow in following]
posts = UserPost.objects.filter(user__id__in=users_ids)

rawDescription: Combining querysets obtained from a loop


code:
@ndb.transactional
def method1(self, entity_key_urlsafe):
  data1 = ndb.Key(urlsafe = entity_key_urlsafe).get()
  data1.property1 = "1"
  data1.put()

rawDescription: Is it possible to modify only one property of a ndb datastore entity?


code:
grouped = event_frame.groupby('user')  # This should work.
#     I cannot believe that it didn't work for you! I won't buy it till you show us proof!
for name, group in grouped:
    group.set_index('eventtime')  # This will make it easier to work with time series.
    #     I am changing index here because different users may have similar or
    #     overlapping times, and it is a pain in the neck to resolve indexing conflicts.
    login_ind = group[group['eventname'] == 'login'].index
    error_ind = group[group['eventname'] == 'error'].index
    update_ind = group[group['eventname'] == 'update_order'].index

    # Here you can compare the lists login_ind, error_ind and update_ind however you wish.
    #     Note that the list can even have a length of 0.
    # User name is stored in the variable name. So you can get it from there.

rawDescription: Query Pandas DataFrame distinctly with multiple conditions by unique row values


code:
class Node:
    def __init__(self, newvalue):
        self.left = None
        self.right = None
        self.newvalue = newvalue

class Tree:
    def __init__(self):
        self.root = None

    def put(self, newvalue):
        self.root = puter(self.root, newvalue)

    def write(self):
        writer(self.root)
        print("\n")

def writer(root):
    if root != None:
        writer(root.left)
        print(root.newvalue)
        writer(root.right)

def puter(root, newvalue):
    if root == None:
        root = Node(newvalue)
    else:
        if newvalue < root:
            if root.left != None:
                puter(root.left, newvalue)
            else:
                root.left=Node(newvalue)
        else:
            if root.right !=None:
                puter(root.right, newvalue)
            else:
                root.right = Node(newvalue)
    return root

tree = Tree()
tree.put("bird")
tree.put("snake")
tree.put("lion")
tree.put("elephant")
tree.put("snail")
tree.write()

rawDescription: Python - Binary tree - unable to print the tree


code:
ipdb = IPDB()
ipdb_netns = IPDB(nl=NetNS('vnsp0'))

program_command = ['ssh','bananapi@192.168.1.12']
#create vlan
link_iface = ipdb.interfaces['eth0']
with ipdb.create(kind="vlan", ifname='Lan1', link=link_iface, vlan_id=10).commit() as i:
    i.add_ip('192.168.1.11', 24)
    i.mtu = 1400
    i.up()
#add namespace
with ipdb.interfaces.Lan1 as lan:
    lan.net_ns_fd = 'vnsp0'
with ipdb_netns.interfaces.Lan1 as lan:
    lan.add_ip('192.168.1.11/24')
    lan.up()
#execute program
nsp = NSPopen('vnsp0', program_command, stdout=PIPE)
print("output: " + str(nsp.communicate()))
nsp.wait()
nsp.release()

rawDescription: Create and add a vlan to a network-namespace via python


code:
from itertools import izip_longest

for row1, row2 in izip_longest(first, second, fillvalue=[]):
    writer.writerow([int(a == b) for a, b in izip_longest(row1, row2)])

rawDescription: Python: CSV Parsing and Matching

description: Python: CSV Parsing and Matching


code:
# import json module for parsing
import json

# define a list of keywords
keywords = ('tax', 'policy', 'regulation', 'spending', 'budget', 'central bank')

with open('test.json') as json_file:

    # read json file line by line
    for line in json_file.readlines():

        # create python dict from json object
        json_dict = json.loads(line)

        # check if "body" (lowercased) contains any of the keywords
        if any(keyword in json_dict["body"].lower() for keyword in keywords):
            print(json_dict["date"])

rawDescription: Reading JSON file in Python and detecting specific keywords in field


code:
def sum(*args):
    result = 0
    for a in args:
        result += a
    return result

sum(1,2)
sum(9,5,7,8)
sum(1.7,2.3,8.9,3.4)

rawDescription: Name this python/ruby language construct (using array values to satisfy function parameters)


rawDescription: What is the best way to store integers mapped to strings so that the keys can be ranges in python?


rawDescription: Python removing every nth element in array


rawDescription: How can i change the values in dictionary of lists in python

description: Change the values in dictionary of lists in python


code:
import numpy as np

from cubature import cubature

x = np.linspace(-1, 1, 10)
y = np.linspace(-1, 1, 10)
X,Y = np.meshgrid(x, y)

z = np.linspace(1, 10, 100)

def func(z):
   return (X.ravel() - z) / ((X.ravel() - z)**2. + Y.ravel()**2)

res = cubature(1, func, np.array([1.]), np.array([10.]))[0].reshape(X.shape)

rawDescription: Python/Scipy - Integrate with Quad Along Axis


code:
includingtotals = pd.concat([formatted,pd.DataFrame(formatted.sum(axis=1),columns=['Total'])],axis=1)
sorted = includingtotals.sort_index(by=['Total'], ascending=[False])
sorted.to_csv('byqualityissue.csv', header=True)

rawDescription: Appending a Column with sum of rows and sorting in python


code:
import numpy as np

#Number of samples
K = 3

#Array
a =[[6, 5, 4], [3, 2, 1], [1, 2, 3], [4, 5, 6], [7, 8, 1], [5, 2, 6]]
N = len(a)

#Get an array on size of a, shuffle and take first K to use
#permutation used as suggested by @EelcoHoogendoorn
indices = np.random.permutation(N)

#Take the first k samples
samples = indices[:K]
b = [a[i] for i in samples]

#Print
print('a = ', a)
print('b = ', b)

rawDescription: How to extract n 1-D tensors from a given 2-D tensor?

description: Extract n 1-D tensors from a given 2-D tensor


code:
import urllib

args = {"key": "xxxx", "secret": "yyyy"}
url = "http://127.0.0.1:5000/data?{}".format(urllib.urlencode(args))

rawDescription: use a variable in python as string query to pass parameter in url

description: Use a variable in python as string query to pass parameter in url


code:
from selenium import webdriver
from time import sleep

driver = webdriver.Firefox()
driver.get('http://david.abcc.ncifcrf.gov/summary.jsp')
sleep(0.1)
query = """Apba3
Apoa1bp
Dexi
Dhps
Dnpep
Eral1
Gcsh
Git1
Grtp1
Guk1
Ifrd2
Lsm3
Map2k1ip1
Med31
Mettl11a
Mrpl2
mrpl24
Mrpl30
Mrpl46
Ndufaf3
Nr1h2
Obfc2b
Parp3
Pigt
Pop5
Ppt2
Ptpmt1
RGD1304567
RGD1306215
RGD1309708
Rras"""
listBox = driver.find_element_by_id("LISTBox")
listBox.send_keys(query)

IDT = driver.find_element_by_id("IDT")
IDT.send_keys("O")

radioCheck = driver.find_element_by_name("rbUploadType")
radioCheck.click()

submitButton = driver.find_element_by_name("B52")

submitButton.click()
sleep(0.1)
alert = driver.switch_to_alert()
alert.accept()
sleep(0.1)
html = driver.page_source

rawDescription: page returned by python post different from that by browser

description: Page returned by python post different from that by browser


code:
import time

def wait_until(somepredicate, timeout, period=0.25, *args, **kwargs):
  mustend = time.time() + timeout
  while time.time() < mustend:
    if somepredicate(*args, **kwargs): return True
    time.sleep(period)
  return False

rawDescription: Is there an easy way in Python to wait until certain condition is true?


code:
from re import sub
from decimal import Decimal

money = '$6,150,593.22'
value = Decimal(sub(r'[^\d.]', '', money))

rawDescription: How do I convert a currency string to a floating point number in Python?

description: Convert a currency string to a floating point number in Python


code:
renderer_dict = {} # dictionary of values to pass to the renderer
new_comment = render('new_comment.pt', renderer_dict, request)

rawDescription: How can I let users create html files on the file system from a template?

description: Let users create html files on the file system from a template


code:
def test_post(self):
    response = self.c.post('/url/', {'name' : 'postname', 'content' : 'abc'})
    # assume the above call has created an Post and a Category objects. Let's check them out.
    category = Category.objects.get(name='category')
    post = Post.objects.get(name='postname')
    self.assertEqual(post.content, 'abc')
    self.assertEqual(post.category, category)

rawDescription: Django tests Get created object against client.post()


code:
import tempfile
tf = tempfile.NamedTemporaryFile()
tf.name  # retrieve the name of the temp file just created

rawDescription: How to use Python's tempfile.NamedTemporaryFile()?

description: Use Python's tempfile.NamedTemporaryFile()


code:
import re
re.split(r'<(br\/|strong)>wwww', mystr)[::2]

rawDescription: Python: split on two different expressions?


rawDescription: How to detect if the values in array are in a certain range and return a binary array in Python?

description: Detect if the values in array are in a certain range and return a binary array in Python


code:
ww = Worker.objects.filter(eid__day__year=year,eid__day__month=month
                       ).values('name','job_title').annotate(
                           whours=Sum('hours'),
                           wcount=Count('name'),
                           recent=Max('eid__day'),).order_by(
                           '-wcount','-recent','hours','name')

rawDescription: Django Annotate Not Grouping Unless I Add Values()


code:
def run(statement, filename=None, sort=-1):
    """Run statement under profiler optionally saving results in filename

    This function takes a single argument that can be passed to the
    "exec" statement, and an optional file name.  In all cases this
    routine attempts to "exec" its first argument and gather profiling
    statistics from the execution. If no file name is present, then this
    function automatically prints a simple profiling report, sorted by the
    standard name string (file/line/function-name) that is presented in
    each line.
    """
    prof = Profile()
    result = None
    try:
        try:
            prof = prof.run(statement)
        except SystemExit:
            pass
    finally:
        if filename is not None:
            prof.dump_stats(filename)
        else:
            result = prof.print_stats(sort)
    return result

rawDescription: cProfile - keep data in Python object/defer write to disk

description: CProfile - keep data in Python object/defer write to disk


code:
text = """
{{ name = name
    prodcuer =producer
    writer = writer
    language = {{english}}
    country = USA
}}
Here is text I Need This paragraph.;
"""
import re
exp = "\{\{.+\}\}"
re.sub(exp, "", text, flags=re.S | re.I).strip()

rawDescription: rearding regex (python)

description: Rearding regex (python)


code:
from pylab import *

ycoords = [ncount(vector[i:i+n-1]) for i in xrange(length-n+1)]
xcoords = range(length-n+1)

plot(xcoords,ycoords)

show()

rawDescription: Plot random walk in python

description: Plot random walk in python


code:
pd.Index(the_indices_we_want)
df.ix[pd.Index(the_indices_we_want)]
df.ix[[tuple(x) for x in the_indices_we_want.values]]

rawDescription: How to get away with a multidimensional index in pandas

description: Get away with a multidimensional index in pandas


code:
class Blar1(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, unique = True, blank = False, null = False, verbose_name= "Name")

    class Meta:
        default_permissions = ()

rawDescription: Remove (or hide) default Permissions from Django


code: url_request = "https://maps.googleapis.com/maps/api/distancematrix/json?origins={0}&destinations={1}&mode={2}&language=en-EN&key={3}".format(orig_coord, dest_coord, mode, API_KEY)

rawDescription: The Google Distance Matrix API GPS coordinate search


rawDescription: Finding the first row in a colomn where a criteria is met (value is higher than x) in Python


code:
from sqlalchemy import or_, and_

company_filters = ["Filter1", "Filter2"]  # as many as you like

clauses = [(Exception.company == c) for c in company_filters]
q = session.query(Exception)
q = q.filter(and_(*clauses))  # or `or_(*clauses)`

rawDescription: Querying in SQL Alchemy Using Conjuctions


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from numpy.random import randn

from mpl_toolkits.axes_grid1.axes_divider import HBoxDivider
import mpl_toolkits.axes_grid1.axes_size as Size

def make_heights_equal(fig, rect, ax1, ax2, ax3, pad):
    # pad in inches

    h1, v1 = Size.AxesX(ax1), Size.AxesY(ax1)
    h2, v2 = Size.AxesX(ax2, 0.1), Size.AxesY(ax2)
    h3, v3 = Size.AxesX(ax3), Size.AxesY(ax3)

    pad_v = Size.Scaled(1)
    pad_h = Size.Fixed(pad)

    my_divider = HBoxDivider(fig, rect,
                             horizontal=[h1, pad_h, h2, pad_h, h3],
                             vertical=[v1, pad_v, v2, pad_v, v3])

    ax1.set_axes_locator(my_divider.new_locator(0))
    ax2.set_axes_locator(my_divider.new_locator(2))
    ax3.set_axes_locator(my_divider.new_locator(4))

# Make plot with vertical (default) colorbar
fig = plt.figure()
img_ax = fig.add_subplot(131)
bar_ax = fig.add_subplot(132)
ann_ax = fig.add_subplot(133)

data = np.clip(randn(250, 250), -1, 1)

im = img_ax.imshow(data, interpolation='nearest', cmap=cm.coolwarm)

# Add colorbar, make sure to specify tick locations to match desired ticklabels
cbar = fig.colorbar(im, cax=bar_ax, ticks=[-1, 0, 1])
cbar.ax.set_yticklabels(['< -1', '0', '> 1'])# vertically oriented colorbar

ann_ax.axis('off')

ann_ax.annotate("Hello, I'm an annotation", (0.5, 0.5),
                 xycoords="axes fraction", va="center", ha="center",
                 bbox=dict(boxstyle="round, pad=1", fc="w"))

make_heights_equal(fig, 111, img_ax, bar_ax, ann_ax, 0.2)

plt.savefig("try.png")

rawDescription: Adding an annotation box to a matplotlib contour/heat map plot


code: comment = next(user.get_comments(limit = 1))

rawDescription: How to return raw comment data in PRAW instead of memory address (Python 3.5)?

description: Return raw comment data in PRAW instead of memory address (Python 3.5)


code:
import tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        b = tk.Button(self, text="Done!", command=self.upload_cor)
        b.pack()
        table = tk.Frame(self)
        table.pack(side="top", fill="both", expand=True)

        data = (
            (45417, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
            (45418, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
            (45419, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
            (45420, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
            (45421, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
            (45422, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
            (45423, "rodringof", "CSP L2 Review", 0.000394, "2014-12-19 10:08:12", "2014-12-19 10:08:12"),
        )

        self.widgets = {}
        row = 0
        for rowid, reviewer, task, num_seconds, start_time, end_time in (data):
            row += 1
            self.widgets[rowid] = {
                "rowid": tk.Label(table, text=rowid),
                "reviewer": tk.Label(table, text=reviewer),
                "task": tk.Label(table, text=task),
                "num_seconds_correction": tk.Entry(table),
                "num_seconds": tk.Label(table, text=num_seconds),
                "start_time": tk.Label(table, text=start_time),
                "end_time": tk.Label(table, text=start_time)
            }

            self.widgets[rowid]["rowid"].grid(row=row, column=0, sticky="nsew")
            self.widgets[rowid]["reviewer"].grid(row=row, column=1, sticky="nsew")
            self.widgets[rowid]["task"].grid(row=row, column=2, sticky="nsew")
            self.widgets[rowid]["num_seconds_correction"].grid(row=row, column=3, sticky="nsew")
            self.widgets[rowid]["num_seconds"].grid(row=row, column=4, sticky="nsew")
            self.widgets[rowid]["start_time"].grid(row=row, column=5, sticky="nsew")
            self.widgets[rowid]["end_time"].grid(row=row, column=6, sticky="nsew")

        table.grid_columnconfigure(1, weight=1)
        table.grid_columnconfigure(2, weight=1)
        # invisible row after last row gets all extra space
        table.grid_rowconfigure(row+1, weight=1)

    def upload_cor(self):
        for rowid in sorted(self.widgets.keys()):
            entry_widget = self.widgets[rowid]["num_seconds_correction"]
            new_value = entry_widget.get()
            print("%s: %s" % (rowid, new_value))

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: SQL Query results in tkinter

description: SQL Query results in tkinter


code:
import numpy as np

a = np.ones(10000000, dtype=np.int64) * 500

mask = np.random.randint(0, 2, a.size)
b = np.ma.masked_array(a, mask=mask)

b[np.invert(b.mask)] = 1000
print(np.average(b), np.mean(b), np.ma.average(b), np.ma.mean(b))

rawDescription: Numpy average from a large masked array

description: Numpy average from a large masked array


code:
ax.plot_trisurf(xs, ys, zs, triangles=triangles,
                color=(0,0,0,0), edgecolor='Gray')

rawDescription: Matplotlib triangles (plot_trisurf) color and grid


code:
for file in glob.glob(path+"\\*.lst"):
    # If file is readable
    if os.access(file, os.R_OK):
        # Find lines inside files
        lines = [line.rstrip("\n") for line in codecs.open(file,"r","utf-8")]
        # For each line, do something
        for line in lines:
            base = os.path.basename(file)[:-4]
            sentence = re.sub("<sentence>|</sentence>","",line)

            df = df.append([dict(filename=base, sentence=sentence)])

rawDescription: Append data from file to dataframe with Python (pandas)


code:
print ("Getting MediaInfo...")
mediainfo_command = ["mediainfo", input_file_full]
mediainfo = subprocess.check_output(mediainfo_command)

rawDescription: How do I suppress the output in subprocess.call, but save the output?

description: Suppress the output in subprocess.call, but save the output


code: column.Properties["Expression"] = "If([some_column] = 1, 'YES', 'NO')"

rawDescription: How can I create a Calculated Column in Spotfire with IronPython script (preferably using External Name)?

description: Create a Calculated Column in Spotfire with IronPython script (preferably using External Name)


code:
class Test(models.Model):
    title = models.CharField('title', max_length=200)
    blah = models.CharField('blah', max_length=200)

    def save(self, force_insert=False, force_update=False):
        if not self.blah:
            self.blah = 'hello'
        super(Test, self).save(force_insert, force_update)

rawDescription: post_save in django to update instance immediately

description: Post_save in django to update instance immediately


code:
class Article(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    reviewer_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    author = db.relationship(User, foreign_keys=author_id, backref='written')
    reviewer = db.relationship(User, foreign_keys=reviewer_id, backref='reviewed')

rawDescription: How do I directly reference a table column in a database relationship?

description: Directly reference a table column in a database relationship


code:
import multiprocessing
import Tkinter as tk
import cv2

e = multiprocessing.Event()
p = None

# -------begin capturing and saving video
def startrecording(e):
    cap = cv2.VideoCapture(0)
    fourcc = cv2.cv.CV_FOURCC(*'XVID')
    out = cv2.VideoWriter('output.avi',fourcc,  20.0, (640,480))

    while(cap.isOpened()):
        if e.is_set():
            cap.release()
            out.release()
            cv2.destroyAllWindows()
            e.clear()
        ret, frame = cap.read()
        if ret==True:
            out.write(frame)
        else:
            break

def start_recording_proc():
    global p
    p = multiprocessing.Process(target=startrecording, args=(e,))
    p.start()

# -------end video capture and stop tk
def stoprecording():
    e.set()
    p.join()

    root.quit()
    root.destroy()

if __name__ == "__main__":
    # -------configure window
    root = tk.Tk()
    root.geometry("%dx%d+0+0" % (100, 100))
    startbutton=tk.Button(root,width=10,height=1,text='START',command=start_recording_proc)
    stopbutton=tk.Button(root,width=10,height=1,text='STOP', command=stoprecording)
    startbutton.pack()
    stopbutton.pack()

    # -------begin
    root.mainloop()

rawDescription: Record OpenCV video during Tkinter mainloop


code:
objs = [
    Message(
        recipient_number=e.mobile,
        content=batch.content,
        sender=e.contact_owner,
        billee=batch.user,
        sender_name=batch.sender_name
    )
    for e in q
]
msg = Message.objects.bulk_create(objs)

rawDescription: Django bulk_create function example

description: Django bulk_create function example


code:
import os
readEnd, writeEnd = os.pipe()
readFile = os.fdopen(readEnd)
firstLine = readFile.readline()

rawDescription: Python readline from pipe on Linux

description: Python readline from pipe on Linux


rawDescription: What is the Python equivalent of map in Ruby and Javascript?


code: n = [i if i.startswith('h') else 'http' + i for i in n]

rawDescription: Adding a string in front of a string for each item in a list in python


code: h = d.hour + d.minute / 60. + d.second / 3600.

rawDescription: How can I get hours from a Python datetime?

description: Get hours from a Python datetime


code:
import datetime
x=datetime.datetime(1865, 7, 2, 9, 30, 21)
x.isoformat()

rawDescription: Is there any way to use a strftime-like function for dates before 1900 in Python?


code:
from numpy import *
from pylab import *

Z = z.reshape(nx,ny) # makes a (Zy,Zx) matrix out of z
T = Z.T              # transposes the matrix (Zx,Zy)

imshow(T, aspect='auto', origin='lower', extent = ( x.min(), x.max(), y.min(), y.max()))
show()

rawDescription: What is the python analogy to splot pm3d map in gnuplot?


code:
@api.multi
@api.depends('field_x')
def _compute_field_to_compute(self):
    # prefetch
    data = {d['id']: d['field_to_compute']
            for d in self.read(['field_to_compute'])}
    for record in self:
        if record.field_x == '123456':
            record.field_to_compute = '654321'
        else:
            record.field_to_compute = data.get(record.id, 'default')

rawDescription: Odoo : Computed fields, don't update in some case?


code:
photo = tkinter.PhotoImage(file = './Images/img1.gif')
root.geometry("450x450")
root.update()
img = canvas.create_image(225,225, image=photo)
root.after(20000, lambda: canvas.delete(img)) # 20,000 milli seconds = 20 seconds
root.mainloop()

rawDescription: trying to achieve an automatic open -> close in tkinter

description: Trying to achieve an automatic open -> close in tkinter


code:
def remove_element(value,array):
    shift = 0
    for index in xrange(len(array)):
        try:
            array[index] = array[index + shift]
            while array[index] == value:
                shift += 1
                array[index] = array[index + shift]
        except IndexError:
            array[index] = None

rawDescription: Remove values from an array in-place without using extra memory


code:
from collections import deque
items = deque([1,2,3])
items.pop()
items.extend()
items.append()

rawDescription: Python list append and extend - slow speed


code:
dis.dis(compile("if not True: pass", "None", "exec",))
dis.dis(compile("if True: pass", "None", "exec",))

rawDescription: Python performance of conditional evaluation


rawDescription: Plotting a differentiated graph from nested lists in Python


code:
start = 33
end = 127
for v in range(start, end):
    if (start - v) % 10 == 0: # check if (start - v) is a multiple of 10
        print("")
    print(chr(v), end=' ')

rawDescription: ASCII character table Python 3

description: ASCII character table Python 3


code:
from kivy.cache import Cache
Cache.remove('kv.image')
Cache.remove('kv.texture')
# then change the source of the image

rawDescription: Kivy refresh image

description: Kivy refresh image


code:
import numpy as np

def common_rows(A, B):
    items = set(tuple(row) for row in B)
    return np.array([row for row in A if tuple(row[:3]) in items])

n = 10000
A = np.random.rand(n, 5)
B = np.random.rand(n, 3)

# Make some common rows
B[123,:] = A[5775,:3]
B[1443,:] = A[85,:3]

print("-- Expected:")
print(B[123])
print(B[1443])
print("-- Got:")
print(common_rows(A, B))

rawDescription: Array comparison of different length arrays in numpy


code:
def make_fibonacci(n):
    fib = []
    a, b = 0, 1
    for i in range(n):
        a, b = b, a+b
        fib.append(a)
    return tuple(fib)

make_fibonacci(10)

rawDescription: Fibonacci Sequence in tuple Python

description: Fibonacci Sequence in tuple Python


code:
from xlsxwriter.workbook import Workbook

workbook = Workbook('file.xlsx', {'constant_memory': True})
worksheet = workbook.add_worksheet()
...

rawDescription: Set cell format and style using Optimized Writer in openpyxl


rawDescription: Formatting Numbers Inside of a String

description: Formatting Numbers Inside of a String


rawDescription: Merge multiple 2d lists considering axis in order


code:
import subprocess
sslstrip = subprocess.Popen(["sslstrip", "-l", "1000", "-w", "cap.txt"], stdout=subprocess.PIPE)

# Run your script
# ...

# At the end terminate the process (in your KeyboardInterrput)
sslstrip.terminate()

rawDescription: python run 2 processes

description: Python run 2 processes


code:
from django.db import models

class _Contact(object):
    pass

class Company(models.Model):
    name = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)

    @property
    def employees(self):
        return self.employee_set.prefetch_related('phones').order_by('-created_at')

class Phone(models.Model):
    number = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)

class Employee(models.Model):
    name = models.CharField(max_length=255)
    street = models.CharField(max_length=255)
    phones = models.ManyToManyField('Phone', through='EmployeePhone', blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    company = models.ForeignKey(Company)

    @property
    def contact(self):
        _contact = _Contact()
        _contact.street = self.street
        _contact.phones = self.phones.order_by('-employeephone__created_at')

        return _contact

class EmployeePhone(models.Model):
    employee = models.ForeignKey(Employee)
    phone = models.ForeignKey(Phone)
    created_at = models.DateTimeField(auto_now_add=True)

rawDescription: django: need to design models/forms for a 'multiple level nested' structures

description: Django: need to design models/forms for a 'multiple level nested' structures


code:
# adding a pie chart to the drawing
self._add(self,Pie(),name='pie',validate=None,desc=None)

rawDescription: How to combine two charts into the single PDF using ReportLab?

description: Combine two charts into the single PDF using ReportLab


code:
def arrays_with_differences(arr, x):
    if x > len(arr):
        return []

    if len(arr) == 0:
        return [[]]

    smallColl1 = arrays_with_differences(arr[:len(arr)-1], x)
    smallColl2 = arrays_with_differences(arr[:len(arr)-1], x-1)

    last = arr[len(arr)-1]
    altLast1 = (last + 1) % 3
    altLast2 = (last + 2) % 3

    result = [smallArr + [last] for smallArr in smallColl1]
    result.extend([smallArr + [altLast1] for smallArr in smallColl2])
    result.extend([smallArr + [altLast2] for smallArr in smallColl2])
    return result

result = arrays_with_differences([1,0,1,0,1,1,1,1,1,1,1,1,1], 4)
print(len(result))

rawDescription: Filtering out conditioned arrays from a matrix


code:
import cv2

image = cv2.imread('example.jpg')
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv_image)
s.fill(255)
v.fill(255)
hsv_image = cv2.merge([h, s, v])

out = cv2.cvtColor(hsv_image, cv2.COLOR_HSV2BGR)

cv2.imshow('example', out)
cv2.waitKey()

rawDescription: Merge HSV channels under OpenCV 3 in Python


code:
from Tkinter import *

root = Tk()
root.minsize(width=200, height=200)
root.maxsize(width=650, height=500)
root.mainloop()

rawDescription: How do I set min and max resize sizes for my main window?

description: Set min and max resize sizes for my main window


code: udskrift.write((" %.5E , %.5E\n" % (entry[2], entry[3])).replace('E+', 'E'))

rawDescription: python with scientific notation EXY

description: Python with scientific notation EXY


code:
import numpy as np
import scipy.stats as st

my_data = np.random.randn(1000)

wald_params = st.wald.fit(my_data)
invgauss_params = st.invgauss.fit(my_data, f0=1)

rawDescription: wald distribution and inverse gaussian distribution in scipy.stats

description: Wald distribution and inverse gaussian distribution in scipy.stats


code:
import numpy
a = numpy.array([[0.0,1.630000e+01,1.990000e+01,1.840000e+01],
                 [1.0,1.630000e+01,1.990000e+01,1.840000e+01],
                 [2.0,1.630000e+01,1.990000e+01,1.840000e+01]])
fmt = ",".join(["%s"] + ["%10.6e"] * (a.shape[1]-1))

# numpy.savetxt, at least as of numpy 1.6.2, writes bytes
# to file, which doesn't work with a file open in text mode.  To
# work around this deficiency, open the file in binary mode, and
# write out the header as bytes.
with open('final.csv', 'wb') as f:
  f.write(b'SP,1,2,3\n')
  #f.write(bytes("SP,"+lists+"\n","UTF-8"))
  #Used this line for a variable list of numbers
  numpy.savetxt(f, a, fmt=fmt, delimiter=",")

rawDescription: Adding Header to Numpy array

description: Adding Header to Numpy array


rawDescription: Find two of the same character in a string with regular expressions


code:
mocked_object.assert_has_calls([
   call('mock', 'foobar', mock.ANY, 10)
])

rawDescription: How to check for mock calls with wildcards?

description: Check for mock calls with wildcards


code: s = p.stderr.readline()

rawDescription: ssh hangs when command invoked directly, but exits cleanly when run interactive

description: Ssh hangs when command invoked directly, but exits cleanly when run interactive


code:
try:
    del sys.modules['mycolours']
except KeyError:
    pass

rawDescription: Mock, import, and coverage

description: Mock, import, and coverage


code:
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-u", "--user", dest="user",
                  help="Database username")
parser.add_option("-p", "--password", dest="password",
                  help="Database password")
parser.add_option("-D", "--database", dest="database", default="myDatabase",
                  help="Database name")
parser.add_option("-e", "--engine", dest="engine", default="mysql",
                  help="Database engine")
parser.add_option("-H", "--host", dest="host", default="localhost",
                  help="Database host")

(options, args) = parser.parse_args()

def opt_hash(name):
    global options
    return getattr(options, name)

options.__getitem__ = opt_hash

metadata.bind = '%(engine)s://%(user)s:%(password)s@%(host)s/%(database)s' % options

rawDescription: Using multiple databases with Elixir

description: Using multiple databases with Elixir


code:
low, high = df.B.quantile([0.25,0.75])
df.query('{low}<B<{high}'.format(low=low,high=high))

rawDescription: How to filter rows that fall within 1st and 3rd quartile of a particular column in pandas dataframe?

description: Filter rows that fall within 1st and 3rd quartile of a particular column in pandas dataframe


code:
import pygame
from bluetooth import discover_devices

def main():
    pygame.mixer.pre_init(44100, 16, 2, 4096)
    pygame.init()
    _display = pygame.display.set_mode((500, 400))
    sound = pygame.mixer.Sound('sleep.wav')

    is_home = False
    print('Press Esc to end....')
    while True:
        print('Performing Enquire')

        for event in pygame.event.get():
            if event.type == pygame.KEYUP and event.key == pygame.K_ESCAPE:
                break

        nearby_devices = discover_devices(lookup_names=True)
        print('found {0} devices'.format(len(nearby_devices)))
        if nearby_devices:
            for address, name in nearby_devices:
                print(' {0} - {1}'.format(address, name))
                if name == 'Joelk':
                    is_home = True
                    break
            else:
                is_home = False

            if is_home:
                if sound.get_num_channels() > 0:
                    print('Playing')
                else:
                    sound.play()
            else:
                sound.stop()
                print('Not Playing')

if __name__ == '__main__':
    main()

rawDescription: How to play a sound when my bluetooth device is detected

description: Play a sound when my bluetooth device is detected


code:
from twisted.web import server, resource
from twisted.internet import reactor, endpoints
from twisted.internet.task import LoopingCall
from twisted.web.wsgi import WSGIResource

lc = LoopingCall(server_controller)
# run server_controller once a second
lc.start(1.0)
# serve a WSGI application
resource = WSGIResource(reactor, reactor.getThreadPool(), application)
site = server.Site(resource)
reactor.listenTCP(8080, site)
# enter into the even loop
reactor.run()

rawDescription: Python WSGI server + controller in a single event loop


code:
for i in range(len(t)):
    row = [[ e.a, e.b, e.c, ...] + [e.z[0], e.z[1], e.z[2], ...] for e in t[i]]
    t.writerow(row)

rawDescription: Write an array of differing lengths to a csv in python


code:
def myOpen(name, mode='r', buffer=None):
    if buffer:
        open_file = open(name, mode, buffer)
    else:
        open_file = open(name, mode)

rawDescription: python, default parameters/arguments for builtin open?

description: Python, default parameters/arguments for builtin open


code:
filename_queue = tf.FIFOQueue(100, tf.string)
enqueue_placeholder = tf.placeholder(dtype=tf.string)
enqueue_op = filename_queue.enqueue(enqueue_placeholder)

config = tf.ConfigProto()
config.operation_timeout_in_ms=2000  # for debugging queue hangs
sess = tf.InteractiveSession(config=config)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)

sess.run([enqueue_op], feed_dict={enqueue_placeholder:"/temp/dir1/0"})
sess.run([enqueue_op], feed_dict={enqueue_placeholder:"/temp/dir1/1"})

# do stats for /temp/dir1

sess.run([enqueue_op], feed_dict={enqueue_placeholder:"/temp/dir2/0"})
sess.run([enqueue_op], feed_dict={enqueue_placeholder:"/temp/dir2/1"})

# do stats for /temp/dir2

coord.request_stop()
coord.join(threads)

rawDescription: Tensorflow: Batching input queues then changing the queue source


code: im = image.convert("RGB").resize((600, 950), Image.ANTIALIAS)

rawDescription: View tif file using PIL, poor quality when resized


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

import math
import urllib2
import StringIO
from PIL import Image

def deg2num(lat_deg, lon_deg, zoom):
  lat_rad = math.radians(lat_deg)
  n = 2.0 ** zoom
  xtile = int((lon_deg + 180.0) / 360.0 * n)
  ytile = int((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n)
  return (xtile, ytile)

def num2deg(xtile, ytile, zoom):
  n = 2.0 ** zoom
  lon_deg = xtile / n * 360.0 - 180.0
  lat_rad = math.atan(math.sinh(math.pi * (1 - 2 * ytile / n)))
  lat_deg = math.degrees(lat_rad)
  return (lat_deg, lon_deg)

def getImageCluster(lat_deg, lon_deg, delta_lat,  delta_long, zoom):
    smurl = r"http://a.tile.openstreetmap.org/{0}/{1}/{2}.png"
    xmin, ymax =deg2num(lat_deg, lon_deg, zoom)
    xmax, ymin =deg2num(lat_deg + delta_lat, lon_deg + delta_long, zoom)

    Cluster = Image.new('RGB',((xmax-xmin+1)*256-1,(ymax-ymin+1)*256-1) )
    for xtile in range(xmin, xmax+1):
        for ytile in range(ymin,  ymax+1):
            try:
                imgurl=smurl.format(zoom, xtile, ytile)
                print("Opening: " + imgurl)
                imgstr = urllib2.urlopen(imgurl).read()
                tile = Image.open(StringIO.StringIO(imgstr))
                Cluster.paste(tile, box=((xtile-xmin)*256 ,  (ytile-ymin)*255))
            except:
                print("Couldn't download image")
                tile = None

    return Cluster

if __name__ == '__main__':

    a = getImageCluster(38.5, -77.04, 0.02,  0.05, 13)
    fig = plt.figure()
    fig.patch.set_facecolor('white')
    plt.imshow(np.asarray(a))
    plt.show()

rawDescription: Easy OpenStreetMap tile displaying for Python


rawDescription: How to pass output buffer to shared object

description: Pass output buffer to shared object


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

x = np.arange(0,10,0.1)

# The lines to plot
y1 = 4 - 2*x
y2 = 3 - 0.5*x
y3 = 1 -x

# The upper edge of polygon (min of lines y1 & y2)
y4 = np.minimum(y1, y2)

# Set y-limit, making neg y-values not show in plot
plt.ylim(0, 5)

# Plotting of lines
plt.plot(x, y1,
         x, y2,
         x, y3)

# Filling between line y3 and line y4
plt.fill_between(x, y3, y4, color='grey', alpha='0.5')
plt.show()

rawDescription: Matplotlib fill beetwen multiple lines

description: Matplotlib fill beetwen multiple lines


code: log.debug('formatted message: %s', interpolated_value)

rawDescription: Switching off debug prints

description: Switching off debug prints


code:
from tkinter import *

def converter():
    # Create functions for conversion
    def cel_fahr():
        res = int(entry.get()) * 9/5 +32
        print (res)
    def fahr_cel():
        res = (int(entry.get()) - 32) * 5/9
        print (res)

    def convert():
        if selected.get() == 'Celsius to Fahrenheit':
            cel_fahr()
        else:
            fahr_cel()

    #Options list for the dropdown
    list_opt = ['Celsius to Fahrenheit', 'Fahrenheit to Celsius']
    # Create the main window
    root = Tk()
    # Rename the title of the window
    root.title("Temperature Converter")
    # Set the size of the window
    root.geometry("250x250")
    # Set resizable FALSE
    root.resizable(0,0)
    # Create a variable for the default dropdown option
    selected = StringVar(root)
    # Set the default drop down option
    selected.set('Celsius to Fahrenheit')
    # Create the dropdown menu
    dropdown = OptionMenu(root, selected, 'Celsius to Fahrenheit', 'Fahrenheit to Celsius')
    # Place the dropdown menu
    dropdown.place(x=45, y=10)

    # Create an entry
    entry = Entry(root)
    entry.place (x=47, y=60)

    #Create a button
    button = Button(root, text='Convert', command=convert)
    button.place(x=85,y=90)

    root.mainloop()

converter()

rawDescription: [Python]Updating the GUI depending on the dropdown menu option


code: b = [range(x) for x in a]

rawDescription: List of lists based on numbers in another list


code:
r1 = re.compile("foo[bar]baz", re.DEBUG)
r2 = re.compile("""foo   # foo!
                   [bar] # b or a or r!
                   baz   # baz!""", re.VERBOSE|re.DEBUG)

rawDescription: Checking if two Python regex patterns are equivalent


rawDescription: Python unittest report passed test

description: Python unittest report passed test


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

xs = np.arange(8)
series1 = np.array([1, 3, 3, None, None, 5, 8, 9]).astype(np.double)
s1mask = np.isfinite(series1)
series2 = np.array([2, None, 5, None, 4, None, 3, 2]).astype(np.double)
s2mask = np.isfinite(series2)

plt.plot(xs[s1mask], series1[s1mask], linestyle='-', marker='o')
plt.plot(xs[s2mask], series2[s2mask], linestyle='-', marker='o')

plt.show()

rawDescription: matplotlib: drawing lines between points ignoring missing data

description: Matplotlib: drawing lines between points ignoring missing data


code: sum(Dictionary[c] for c in 'apple')

rawDescription: How to get the sum of output set of values in python?

description: Get the sum of output set of values in python


rawDescription: How to use CSS with Django forms?

description: Use CSS with Django forms


code: price = line[-3:]

rawDescription: attempting to add cost from the end of a line but only getting a blank space

description: Attempting to add cost from the end of a line but only getting a blank space


code:
import json
import urllib
url = 'http://python-data.dr-chuck.net/comments_204529.json'
uh = urllib.urlopen(url)
result = json.load(uh)
[comment["count"] for comment in result["comments"]]

rawDescription: How to extract numbers from JSON API

description: Extract numbers from JSON API


code:
classname = ""
classpick = input("Enter class name (\"A,B,C\") ")
while classname == "":
    try:
        if classpick.upper() == "A":
            classname = "classA.txt"
        elif classpick.upper() == "B":
            classname = "classB.txt"
        elif classpick.upper() == "C":
            classname = "classC.txt"
        elif classpick.upper() not in ["A","B","C"]:
            raise ValueError
    except ValueError:
        print("Invalid value. Please enter a letter A,B or C.")
        classpick = input("Enter class name (\"A,B,C\") ")

rawDescription: Why does my python loop continually hit my exception clause?


code:
from django.contrib import admin
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm, UserChangeForm

class MyUserCreationForm(UserCreationForm):
    username = forms.RegexField(
        label='Username',
        max_length=30,
        regex=r'^[\w-]+$',
        help_text = 'Required. 30 characters or fewer. Alphanumeric characters only (letters, digits, hyphens and underscores).',
        error_message = 'This value must contain only letters, numbers, hyphens and underscores.')

class MyUserChangeForm(UserChangeForm):
    username = forms.RegexField(
        label='Username',
        max_length=30,
        regex=r'^[\w-]+$',
        help_text = 'Required. 30 characters or fewer. Alphanumeric characters only (letters, digits, hyphens and underscores).',
        error_message = 'This value must contain only letters, numbers, hyphens and underscores.')

class MyUserAdmin(UserAdmin):
    form = MyUserChangeForm
    add_form = MyUserCreationForm

admin.site.unregister(User)
admin.site.register(User, MyUserAdmin)

rawDescription: Allowing the " - " character in usernames in the Django Admin interface


code:
def getRedisLock(name, max_time, r):
    lock = r.setnx(name, int(time.mktime(time.gmtime())))
    if not lock:
        lock_time = int(r.get(name))
        #if the lock expired (assume some client failed)
        if lock_time + max_time < int(time.mktime(time.gmtime())):
            old_time = int(r.getset(name, int(time.mktime(time.gmtime()))))
            if old_time == lock_time:
                lock = True
    #If you still have no lock, do something special here, if you want
    if not lock:
        pass
    return lock

def releaseRedisLock(self, name):
    r = self.r
    return r.delete(name)

rawDescription: Performing a global lock in a Python web application?


code:
import pkg_resources
my_data = pkg_resources.resource_string(__name__, "foo.dat")

rawDescription: Python equivalent to Java's Class.getResource


code:
import csv
from collections import defaultdict

mydict = defaultdict(list)  # <---

with open ('food.csv', 'r') as csvfile:
    fileDialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    dictReader = csv.DictReader(csvfile, dialect=fileDialect)
    for row in dictReader:
        mycategory= row.pop("Category")
        mydict[mycategory].append(row)  # Will put a list for not-existing key

mydict = dict(mydict)  # Convert back to a normal dictionary (optional)

rawDescription: Create a list of dictionaries in a dictionary from csv in Python


code:
s = "This_is_some_sentence_ID"
splited = s.rsplit('_', 1)
print(splited)

rawDescription: How to split sentence by separator to two parts only

description: Split sentence by separator to two parts only


code:
import random

words = []
translations = []

def add_words():
    # input word pairs until the user inputs "exit"
    print('\nInput word and translation pairs. Type "exit" to finish.')
    done = False
    while not done:
        word = raw_input("Add a word to your wordlist: ")
        # only input translation, if the word wasn't exit
        if word != "exit":
            translation = raw_input("Add the translation to this word: ")
        if word != "exit" and translation != "exit":
            # append in pairs only
            words.append(word)
            translations.append(translation)
        else:
            done = True

def exercise():
    # excercising until the user inputs "exit"
    print("\nExcercising starts. ")
    done = False
    while not done:
        # get a random index in the words
        index = random.randrange(0, len(words))
        # get the word and translation for the index
        word = words[index]
        translation = translations[index]
        # ask the user
        answer = raw_input('Enter the translation for "%s": ' % word)
        if answer == "exit":
            done = True
            print("\nGoodbye!")
        elif answer == translation:
            print("Correct!")
        else:
            print("Wrong!")

add_words()
exercise()

rawDescription: Making a 'quiz-construction' with arrays


code:
keyphraseList = (
     "some text",
     "some more text",
     "even more text I'm looking for")

...
for row in reader:
   for phrase in keyphraseList:
       if phrase in row[x]:
           total = total + 1
           writer.writerow(row)
           break

rawDescription: Is there a better way to read an element from a file in Python?


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.scatter(1, 2, c='blue', marker='x')
ax.scatter(2, 3, c='red', marker='o')
ax.legend(('1', '2'), loc=2, scatterpoints=1)
plt.show()

rawDescription: Setting numpoints in matplotlib legend does not work


code:
with open('FileA.txt', 'r') as a, open('FileB.txt', 'r') as b, open('output.txt', 'w') as o:
    chra, chrb = a.read().splitlines(), b.read().splitlines()
    to_remove = set(chra).intersection(set(chrb))
    for c in chra + chrb:
        if c not in to_remove:
            o.write(c + '\n')

rawDescription: How to filter out the coordinate information according to a text file provided using Python?

description: Filter out the coordinate information according to a text file provided using Python


code:
dct = {key:row['c'] for i, row in df[['b', 'c']].iterrows() for key in row['b']}
df['a'].map(dct).fillna(0)

rawDescription: pandas: check membership in array of lists, avoid looping through columns

description: Pandas: check membership in array of lists, avoid looping through columns


code:
from pandas import DataFrame
df = DataFrame(resoverall.fetchall())
df.columns = resoverall.keys()

rawDescription: How to convert SQL Query result to PANDAS Data Structure?

description: Convert SQL Query result to PANDAS Data Structure


code:
head=None
prev=None
for i in range(len):
    node=Node(number%10)
    if not head:
        head=node
    else:
        prev.next=node
    prev=node
    number=number/10
return head

rawDescription: Reversing a linked list in python

description: Reversing a linked list in python


code:
writer = pd.ExcelWriter('test.xlsx')
df = DataFrame(C,ind)    # C is the matrix and ind is the list of corresponding indices
df.to_excel(writer, startcol = 0, startrow = 5)

worksheet = writer.sheets['Sheet1']
worksheet.write_string(0, 0, 'Your text here')

writer.save()

rawDescription: Write dataframe to excel with a title

description: Write dataframe to excel with a title


code:
people = []
for _ in range(20):
    people.append(person_Birth())

rawDescription: Python: Creating an unique variable to store information


rawDescription: python importing module, find out what is exactly wrong

description: Python importing module, find out what is exactly wrong


code:
sum_nums = 0
for val in args:
    sum_nums += val

rawDescription: Using "*" inside python

description: Using "*" inside python


rawDescription: Get frame object that function was defined in


code: is_enabled = True if (cfg and cfg.get('enabled')) else False

rawDescription: Get True or False from dict and key's existence


code:
retVal_mapping = [
   ('mString1', 1),
   ('mString2', 2),
   ('mString3', 2),
   ('mString4', 2),
   ('', 0) # default as "'' in anyString" is always true.
]

for s, retVal in retVal_mapping:
    if s in mStrVar:
        break

# retVal now contains the right value

rawDescription: if elif with strings

description: If elif with strings


code:
# cell 1
from bokeh.plotting import figure, show, output_notebook, output_file, reset_output
p = figure(width=300, height=300)
p.line(range(5), range(5))
output_notebook()
show(p)

# cell 2
reset_output()
output_file('foo.html')
show(p)

# cell 3
reset_output()
output_notebook()
show(p)

rawDescription: Can one switch between output_notebook and output_file within an IPython notebook session with Bokeh?


code:
import pandas as pd
import numpy as np

# some sample data
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)).cumsum()

#plot the time series
ts.plot(style='k--')

# calculate a 60 day rolling mean and plot
pd.rolling_mean(ts, 60).plot(style='k')

# add the 20 day rolling variance:
pd.rolling_std(ts, 20).plot(style='b')

rawDescription: How can I simply calculate the rolling/moving variance of a timeseries in python?

description: Simply calculate the rolling/moving variance of a timeseries in python


code:
while True:
    x = random.randrange(0,xsize)
    y = random.randrange(0,ysize)

    for i in range(0,len(word)):
        if grid[y + direction[1]*i][x + direction[0]*i] not in ['.',word[i]]:
            break
    else:
        break
for i in range(0,len(word)):
    grid[y + direction[1]*i][x + direction[0]*i] = word[i]

rawDescription: -Python- WordSearch: Placing words to handle overlap properly


code:
import sys

from PyQt5.QtWidgets import *
import win32api
import win32con
import win32gui
import win32ts

WM_WTSSESSION_CHANGE = 0x2B1
WTS_SESSION_LOCK = 0x7
WTS_SESSION_UNLOCK = 0x8

# http://wiki.wxpython.org/HookingTheWndProc
# http://wiki.wxpython.org/HookingTheWndProc?action=AttachFile&do=view&target=WndProcHookMixin.py
# http://wiki.wxpython.org/HookingTheWndProc?action=AttachFile&do=view&target=WndProcHookMixinCtypes.py
class WndProcHookMixin:
    def __init__(self):
        self.msgDict = {}

    def hookWndProc(self):
        self.oldWndProc = win32gui.SetWindowLong(self.winId(), win32con.GWL_WNDPROC, self.localWndProc)

    def unhookWndProc(self):
        win32api.SetWindowLong(self.winId(), win32con.GWL_WNDPROC, self.oldWndProc)

    def addMsgHandler(self, messageNumber, handler):
        self.msgDict[messageNumber] = handler

    def localWndProc(self, hWnd, msg, wParam, lParam):
        if msg in self.msgDict:
            if self.msgDict[msg](wParam, lParam) == False:
                return

        if msg == win32con.WM_DESTROY:
            self.unhookWndProc()

        return win32gui.CallWindowProc(self.oldWndProc, hWnd, msg, wParam, lParam)

class Window(QWidget, WndProcHookMixin):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.show()
        win32ts.WTSRegisterSessionNotification(self.winId(), win32ts.NOTIFY_FOR_ALL_SESSIONS)
        self.addMsgHandler(WM_WTSSESSION_CHANGE, self.on_session)
        self.hookWndProc()

    def on_session(self, wParam, lParam):
        event, session_id = wParam, lParam
        if event == WTS_SESSION_LOCK:
            print("Locked")
        if event == WTS_SESSION_UNLOCK:
            print("Unlocked")

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win = Window()
    sys.exit(app.exec_())

rawDescription: Detect if Windows workstation is locked in PyQt5 application


code:
from lxml import etree
doc = etree.HTML("""

AC/DC
Live
4.0	CD

""")
doc.xpath('//td[@class="or_q_artist"]/a/text()|//td[@class="or_q_album"]/a/text()')

rawDescription: Reading web pages with Python

description: Reading web pages with Python


code:
rows, cols = np.where(t == 'bar')
t[rows]

rawDescription: Numpy where() on a 2D matrix

description: Numpy where() on a 2D matrix


code:
from functools import wraps

class Aclass(object):
    def __init__(self, value):
        self._value = value

    def complex(self, a, b):
        return a + b + self._value

def repartial(func, *parameters, **kparms):
    @wraps(func)
    def wrapped(self, *args, **kw):
        kw.update(kparms)
        return func(self, *(args + parameters), **kw)
    return wrapped

class Atype(type):
    def __new__(cls, name, bases, attrs):
        return super(Atype, cls).__new__(cls, name, (Aclass, ) + bases, attrs)

    def __init__(cls, name, bases, attrs):
        setattr(cls, 'simple', repartial(cls.complex, b=1))

class B(metaclass=Atype):
    pass

b = B(10)

print(b.complex(1, 2))
print(b.simple(1))

rawDescription: Create instance method in metaclass using partial in Python 3


code:
from collections import defaultdict

mylist = [('birthday', 1), ('ramen', 2), ('cake', 1), ('ramen', 1), ('cake', 2), ('ramen', 1)]

d = defaultdict(int)

for k,v in mylist:
    d[k] += v

print(d)
# defaultdict(<type 'int'>, {'cake': 3, 'birthday': 1, 'ramen': 4})

rawDescription: Accumulate values of duplicate items within a list


code:
r.table('backups').filter(
  (r.row['verified'] == True) & r.row['id'].match("^aad")
).run(conn)

rawDescription: Multiple filters with a lambda in RethinkDB


code:
i = "text"
field_new = '"\\"'+str(i)+'\\""'
field_new
field_new == r'"\"text\""'

rawDescription: String with Backslash and Quotes in Python is problems galore


code:
options = {
   'margin-bottom': '0.75in',
   'footer-right': '[page]'
   }
pdfkit.from_string('Hello World', 'out.pdf', options=options)

rawDescription: page number in pdf converted from html - pdfkit, python/django

description: Page number in pdf converted from html - pdfkit, python/django


code:
import calendar, datetime, time
def convert_enddate_to_seconds(ts):
  """Takes ISO 8601 format(string) and converts into epoch time."""
  dt = datetime.datetime.strptime(ts[:-7],'%Y-%m-%dT%H:%M:%S.%f')-\
      datetime.timedelta(hours=int(ts[-5:-3]),
      minutes=int(ts[-2:]))*int(ts[-6:-5]+'1')
  seconds = calendar.timegm(dt.timetuple()) + dt.microsecond/1000000.0
  return seconds

import iso8601
ts = '2012-09-30T15:31:50.262-08:00'
iso8601.parse(ts)
convert_enddate_to_seconds(ts)

rawDescription: convert ISO8601 format to seconds in python without using any external library

description: Convert ISO8601 format to seconds in python without using any external library


code:
# A test case
list1 = [0, 1, 2, 3, 4, 5, 6]
list2 = ['c', 'e', 'a']
indices = [2, 4, 0]

# Use conditional expressions
new_list = [list2[indices.index(idx)] if idx in indices else v for idx, v in enumerate(list1)] # idx2 = indices.index(idx), for list2

print(new_list)
# Output
['a', 1, 'c', 3, 'e', 5, 6]

rawDescription: Python one liner to substitute a list indices


code:
# suppose your have a Queue my_queue
aux_stack = Stack()
while not my_queue.isEmpty():
    aux_stack.push(my_queue.dequeue())

while not aux_stack.isEmpty():
    my_queue.enqueue(aux_stack.pop())

rawDescription: How would I reverse the contents of any given queue in python?


code:
from itertools import chain
l = chain.from_iterable(zip(*l))
list(l)

rawDescription: Iterating over a 2 dimensional python list


code:
from twisted.web.resource import Resource
from twisted.web.template import flatten
from twisted.web.server import NOT_DONE_YET

class ElementResource(Resource):
    def __init__(self, element):
        Resource.__init__(self)
        self.element = element
    def render_GET(self, request):
        d = flatten(request, self.element, request.write)
        def done(ignored):
            request.finish()
            return ignored
        d.addBoth(done)
        return NOT_DONE_YET

rawDescription: twisted.web.resource.Resource with twisted.web.template.Element example

description: Twisted.web.resource.Resource with twisted.web.template.Element example


code:
class Team(Base):

    __tablename__ = "teams"

    id = Column(Integer, primary_key=True)
    name = Column(String)
    espn_team_id = Column(Integer, unique=True, nullable=False)

    h_games = relationship(
                  "Game",
                  primaryjoin="Game.h_espn_id==Team.espn_team_id",
                  order_by="Game.date")
    a_games = relationship(
                  "Game",
                  primaryjoin="Game.a_espn_id==Team.espn_team_id",
                  order_by="Game.date")

    @hybrid_property
    def games(self):
        return self.h_games+self.a_games

    def __init__(self, name):
        self.name = name
        self.espn_team_id = espn_team_id
        self.h_games = h_games
        self.a_games = a_games
        self.games = games

rawDescription: SQLAlchemy Using relationship()

description: SQLAlchemy Using relationship()


code:
df_1 = df[['Date_x', 'Value_x']].rename(columns={'Date_x': 'Date', 'Value_x': 'Value'})
df_2 = df[['Date_y', 'Value_y']].rename(columns={'Date_y': 'Date', 'Value_y': 'Value'})

df = pd.concat([df1, df2]).sort_index()

rawDescription: Rearrange dataframe using python

description: Rearrange dataframe using python


code:
import CGIHTTPServer
import random
import sys
import cgi

class MyRequestHandler(CGIHTTPServer.CGIHTTPRequestHandler):
    global super_important_list
    super_important_list = range(10)
    random.shuffle(super_important_list)

    def do_POST(s):
        """Respond to a POST request."""
        form = cgi.FieldStorage(fp=s.rfile,headers=s.headers,environ={'REQUEST_METHOD':'POST','CONTENT_TYPE':s.headers['Content-Type'],})
        s.wfile.write("<title>Title goes here.</title>")
        s.wfile.write("
This is a test.
")
        s.wfile.write("
You accessed path: %s
" % s.path)
        s.wfile.write("
Also, super_important_list is:
")
        s.wfile.write(str(super_important_list))
        s.wfile.write("
Furthermore, you POSTed the following info: ")
        for item in form.keys():
            s.wfile.write("
Item: " + item)
            s.wfile.write("
Value: " + form[item].value)
        s.wfile.write("")

if __name__ == '__main__':
    server_address = ('', 8000)
    httpd = CGIHTTPServer.BaseHTTPServer.HTTPServer(server_address, MyRequestHandler)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        sys.exit()

rawDescription: Global variable in Python server

description: Global variable in Python server


code:
class Base_Metaclass(type):
    def __new__(meta, classname, bases, class_dict):
        new_type = type.__new__(meta, classname, bases, class_dict)
        if not (new_type.NOMINATOR % new_type.DENOMINATOR) == 0:
            raise Exception("Invalid subclass created - validation failed")
        return new_type

# have Base and all its descendants be enforced:
class Base(object):
    __metaclass__ = Base_Metaclass
    # I must pass the validation myself, no None's anymore...
    NOMINATOR = 1
    DENOMINATOR = 1

rawDescription: Automatic class decoration (or validation) upon derivation


code: query = 'SELECT * FROM table1 WHERE id = COALESCE(%s,id)'

rawDescription: Return all values when a condition value is NULL


rawDescription: How do I replace floats with rationals in a sympy expression?

description: Replace floats with rationals in a sympy expression


code:
sock.send(packed_data)

sock.settimeout(3)

try:
    received=sock.recv(61)
except socket.timeout:
    ...

rawDescription: Python & Time functions

description: Python & Time functions


code:
import os
os.environ['MY_ENV_VARIABLE'] = 'value'
# e.g. os.environ['MPLCONFIGDIR'] = '/path/to/config/dir'

rawDescription: Where and how do I set an environmental variable using mod-wsgi and django?


code:
import subprocess
last_line = subprocess.check_output(["tail", "-1", "DataLogging.csv"])
# to get the values (parsing via the csv module seems excessive for one line)
temp_hum = [float(x) for x in last_line.split()[2:]]

rawDescription: Get Values from last Row of .csv File

description: Get Values from last Row of .csv File


code: pages = [(wx.Panel(parent = self.parent, id = wx.ID_ANY), name.capitalize()) for name in self.package.vars["tabs"]]

rawDescription: wxPython Toolbook/Toolbar, blank space between toolbar and frame

description: WxPython Toolbook/Toolbar, blank space between toolbar and frame


code:
import pygtk
pygtk.require('2.0')
import gtk
import subprocess
import signal

class Teacher:

    def __init__(self):
        self.proc = None  # Initialize the handle to our subprocess
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_size_request(400, 200)
        window.set_title("Music Teacher")
        window.connect("delete_event",
                   lambda w,e: gtk.main_quit())

        table = gtk.Table(4, 4, True)
        window.add(table)

        play = gtk.Button("Play")
        play.connect("clicked", self.clicked_play)
        play.show()

        stop = gtk.Button("Stop")
        stop.connect("clicked", self.clicked_stop)
        stop.show()

        table.attach(play, 0, 1, 0, 1)
        table.attach(stop, 0, 1, 1, 2)

        window.show_all()

    def clicked_play(self, widget):
        self.proc = subprocess.Popen(["timidity", "~/somefile.mid"])

    def clicked_stop(self, widget=None):
        if self.proc:
            self.proc.terminate()
            self.proc.wait()

    def handle_sigterm(self, *args):
        self.clicked_stop()
        sys.exit()

    def main(self):
        signal.signal(signal.SIGTERM, self.handle_sigterm)
        try:
            gtk.main()
        except KeyboardInterrupt:
            self.clicked_stop()
            raise
        return 0

Teacher().main()

rawDescription: Stopping a process pygtk

description: Stopping a process pygtk


rawDescription: How to replace a character if there are characters either side of it?

description: Replace a character if there are characters either side of it


code:
def merge(Lsort, Rsort):
    sort = []

    i = 0
    j = 0
    while (len(Lsort) > i) & (len(Rsort) > j):
        if Lsort[i] < Rsort[j]:
            sort.append(Lsort[i])
            i += 1
        else:
            sort.append(Rsort[j])
            j += 1

    if len(Lsort) > 0:
        sort += Lsort[i:]

    if len(Rsort) > 0:
        sort += Rsort[j:]

    return sort

rawDescription: MergeSort recursive implentation

description: MergeSort recursive implentation


rawDescription: Print Pandas dataframe with index

description: Print Pandas dataframe with index


code:
def __eq__(self, other):
    if not isinstance(other, __class__):
        return NotImplemented
    return vars(self) == vars(other)

def __ne__(self, other):
    if not isinstance(other, __class__):
        return NotImplemented
    return not self.__eq__(other)

rawDescription: Out of Curiosity: Why is python3 not using __dict__ compare as the default equality implementation?


code: [(g[0], len(list(g[1]))) for g in itertools.groupby(['a', 'a', 'b', 'b', 'b'])]

rawDescription: How to get unique values with respective occurance count from a list in Python?

description: Get unique values with respective occurance count from a list in Python


code:
r.table("posts").get(1).update({
    views: r.row["views"].add(1)
})

rawDescription: RethinkDB - Integer Increment in Document (Python)


code:
ext = Extension(
      'milk.unsupervised._som',
      sources = ['milk/unsupervised/_som.cpp'],
      extra_compile_args=['-fopenmp'],
      extra_link_args=['-lgomp'])

...
setup(..., ext_modules = [ext])

rawDescription: Python and OpenMP C Extensions

description: Python and OpenMP C Extensions


code:
for i in tree.get_children():
    tree.delete(i)

rawDescription: How to clear an entire Treeview with Tkinter

description: Clear an entire Treeview with Tkinter


code:
from itertools import zip_longest
list(zip_longest(*a))

rawDescription: Python - Transpose List of Lists of various lengths - 3.3 easiest method


code:
import numpy as np

helper = np.vectorize(lambda x: x.total_seconds())
dt_sec = helper(dt)

rawDescription: elegant way of convert a numpy array containing datetime.timedelta into seconds in python 2.7

description: Elegant way of convert a numpy array containing datetime.timedelta into seconds in python 2.7


rawDescription: Python, Regular Expression help. Insert with re


code:
def populate_object_properties(values_as_strings,
                               object_to_populate,
                               properties_to_populate):
    model_properties = object_to_populate.properties()
    for k in properties_to_populate:
        value = values_as_strings.get(k)
        model_property = model_properties.get(k)
        if value:
            if isinstance(model_property, StringProperty):
                setattr(object_to_populate, k, str(value))
            elif isinstance(model_property, IntegerProperty):
                setattr(object_to_populate, k, int(value))
        else:
            setattr(object_to_populate, k, None)

rawDescription: Find the type of an attribute in a class


code:
codon_nodes = dict()

for i in codon_dict:
    codon_nodes[i] = gdb.create(({"aminoacid_name":i,"comprised_of":codon_dict[i]}))[0]

rel = gdb.create((codon_nodes['A'], 'is similar', codon_nodes['V']))

rawDescription: Create relationships after creating the nodes in py2neo


code:
class FSImagesStoreChangeableDirectory(FSImagesStore):

    def persist_image(self, key, image, buf, info,append_path):

        absolute_path = self._get_filesystem_path(append_path+'/'+key)
        self._mkdir(os.path.dirname(absolute_path), info)
        image.save(absolute_path)

class ProjectPipeline(ImagesPipeline):

    def __init__(self):
        super(ImagesPipeline, self).__init__()
        store_uri = settings.IMAGES_STORE
        if not store_uri:
            raise NotConfigured
        self.store = FSImagesStoreChangeableDirectory(store_uri)

rawDescription: Scrapy image download how to use custom filename


code:
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd

# dataframe with dates
dates = pd.DataFrame()
dates['2016'] = pd.date_range(start='2016', periods=4, freq='60Min')
dates['2017'] = pd.date_range(start='2017', periods=4, freq='60Min')
dates['2018'] = pd.date_range(start='2018', periods=4, freq='60Min')
dates.reset_index()
dates = dates.unstack()

# multi-indexed dataframe
df = pd.DataFrame(np.random.randn(36, 3))
df['concept'] = np.repeat(np.repeat(['A', 'B', 'C'], 3), 4)
df['datetime'] = pd.concat([dates, dates, dates], ignore_index=True)
df.set_index(['concept', 'datetime'], inplace=True)
df.sort_index(inplace=True)
df.columns = ['V1', 'V2', 'V3']
df.info()

# demonstrate how to customize the display different elements:
boxprops = dict(linestyle='-', linewidth=4, color='k')
medianprops = dict(linestyle='-', linewidth=4, color='k')

bp = df.boxplot(column=['V1'],
                by=df.index.get_level_values('datetime').year,
                showfliers=False, showmeans=True,
                boxprops=boxprops, medianprops=medianprops,
                return_type='dict')

# boxplot style adjustments
[[item.set_linewidth(4) for item in bp[key]['boxes']] for key in bp.keys()]
[[item.set_linewidth(4) for item in bp[key]['fliers']] for key in bp.keys()]
[[item.set_linewidth(4) for item in bp[key]['medians']] for key in bp.keys()]
[[item.set_linewidth(4) for item in bp[key]['means']] for key in bp.keys()]
[[item.set_linewidth(4) for item in bp[key]['whiskers']] for key in bp.keys()]
[[item.set_linewidth(4) for item in bp[key]['caps']] for key in bp.keys()]

[[item.set_color('g') for item in bp[key]['boxes']] for key in bp.keys()]
# seems to have no effect
[[item.set_color('b') for item in bp[key]['fliers']] for key in bp.keys()]
[[item.set_color('m') for item in bp[key]['medians']] for key in bp.keys()]
[[item.set_markerfacecolor('k') for item in bp[key]['means']] for key in bp.keys()]
[[item.set_color('c') for item in bp[key]['whiskers']] for key in bp.keys()]
[[item.set_color('y') for item in bp[key]['caps']] for key in bp.keys()]

# get rid of "boxplot grouped by" title
plt.suptitle("")

# label adjustment
p = plt.gca()
p.set_xlabel("")
p.set_title("Some plot", fontsize=30)
p.tick_params(axis='y', labelsize=30)
p.tick_params(axis='x', labelsize=30)

rawDescription: Pandas boxplot: set color and properties for box, median, mean


code:
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: Python: split list into chunks of defined size and fill up rest


code:
from win32api import GenerateConsoleCtrlEvent
GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0)

rawDescription: Send SIGINT in Windows using Python

description: Send SIGINT in Windows using Python


code:
import ast

for item in ["[u'cheese']", "[u'grapes', u'oranges']", "[u'apple']"]:
    for food in ast.literal_eval(item):
        print(food)

rawDescription: Parsing a variable that may be multiple items


code:
import time
def time_chunk( some_source, period=10 ):
    start= time.time()
    buffer= []
    for line in some_source:
        buffer.append( line )
        if time.time() - start >= period:
            start= time.time()
            yield buffer
            buffer= []
    yield buffer

for chunk in time_chunk( sys.stdin ):
    print( stats( chunk ) )

rawDescription: Loop line by line and wall clock time with a Python Filter


code:
from lxml import etree

with open("whatever.xml") as fp:
    tree = etree.parse(fp)
    i = 0
    for node in tree.xpath('//section'):
        output_filename = "output-%d.xml" % (i,)
        with open(output_filename,"w") as fp:
            fp.write(etree.tostring(node))
        i += 1

rawDescription: lxml: How to make new Element tree from given element in a tree

description: Lxml: How to make new Element tree from given element in a tree


code:
import csv
cursor = connection.cursor() # assuming you know how to connect to your oracle db
cursor.execute('select * from table_you_want_to_turn_to_csv')
with open('output_file.csv', 'wb') as fout:
    writer = csv.writer(fout)
    writer.writerow([ i[0] for i in cursor.description ]) # heading row
    writer.writerows(cursor.fetchall())

rawDescription: How to export a table to csv or excel format

description: Export a table to csv or excel format


code:
def send_document(file_path, access_token=access_token):
    """Uploads document to EchoSign and returns its ID

    :param access_token: EchoSign Access Token
    :param file_path: Absolute or relative path to File
    :return string: Document ID

    """
    headers = {
        'Access-Token': access_token,
    }
    data = {
        'Mime-Type': 'application/pdf',
        'File-Name': 'abc.pdf'
    }
    url = api_url + '/transientDocuments'
    files = {'File': open(file_path, 'rb')}
    return requests.post(url, headers=headers, data=data,
                         files=files).json().get('transientDocumentId')

rawDescription: python-requests and EchoSign

description: Python-requests and EchoSign


code:
@mod.route('/')
@mod.route('/<path>')
def home(*args, **kwargs):
    return render_template('index.html')

rawDescription: is this approach to Flask routing reasonable?

description: Is this approach to Flask routing reasonable


code:
def question_two():
    answer_two = raw_input("What's your mother's name?").lower()
    question_3()

rawDescription: How to make python accept random input

description: Make python accept random input


code:
with open('htmlfile.html','r') as file:
  rows = []
  for line in file:
    start = max(line.find('FORWARD'),line.find('REVERSE'))
    rows.append(line[start:].replace('<','').replace('>','').replace('/','').replace('td',' ').replace('tr',' ').strip().split('  '))
print(rows)

rawDescription: Import rows of a table from html file as a list in python


code:
import Tkinter as tk
import time

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.button = tk.Button(self, text="Press me!")
        self.text = tk.Text(self, width=40, height=6)
        self.vsb = tk.Scrollbar(self, command=self.text.yview)
        self.text.configure(yscrollcommand=self.vsb.set)

        self.button.pack(side="top")
        self.vsb.pack(side="right", fill="y")
        self.text.pack(side="bottom", fill="x")

        self.button.bind("<ButtonPress>", self.on_press)
        self.button.bind("<ButtonRelease>", self.on_release)

    def on_press(self, event):
        self.log("button was pressed")

    def on_release(self, event):
        self.log("button was released")

    def log(self, message):
        now = time.strftime("%I:%M:%S", time.localtime())
        self.text.insert("end", now + " " + message.strip() + "\n")
        self.text.see("end")

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

rawDescription: How can I identify when a Button is released in Tkinter?

description: Identify when a Button is released in Tkinter


code:
# Variables I'm assuming exist:
# `title`, `year`, `month`, `day`, `someOtherDay`, `titles`, `someOtherTitle`

myDict = {}
for title in titles: #Renamed `x` to `titles` for clarity.
    # Make sure myDict has the necessary keys.
    if not myDict[year]:
        myDict[year] = {}
    if not myDict[year][month]:
        myDict[year][month] = {}

    # Set the day to be a list with a single `title` (and possibly two).
    myDict[year][month][day] = [title]
    if day==someOtherDay:
        myDict[year][month][day].append(someotherTitle)

    # And FINALLY dump the result to a string.
    data = json.dumps(myDict)

rawDescription: Insert JSON in Array Python

description: Insert JSON in Array Python


code:
import matplotlib.pyplot as plot

x = range(1, 7)
y = (0, 300, 300, 290, 320, 315)
plot.bar(x, y, width=0.7, align="center")

ind = range(2, 7)    # the x locations for the groups
plot.xticks(ind, x)

plot.axhline(305, linewidth=3, color='r')

plot.show()

rawDescription: Manipulating x axis tick labels in matplotlib


code:
def main():

    # Patch the imp standard library module to fix an incompatibility between
    # py2app and gevent.httplib while running a py2app build on Mac OS-X.
    # This patch must be executed before applying gevent's monkey patching.
    if getattr(sys, 'frozen', None) == 'macosx_app':

        import imp, httplib

        original_load_module = imp.load_module
        original_find_module = imp.find_module

        def custom_load_module(name, file, pathname, description):
            if name == '__httplib__':
                return httplib
            return original_load_module(name, file, pathname, description)

        def custom_find_module(name, path=None):
            if name == 'httplib':
                return (None, None, None)
            return original_find_module(name, path)

        imp.load_module = custom_load_module
        imp.find_module = custom_find_module

        # Verify that the patch is working properly (you can remove these lines safely)
        __httplib__ = imp.load_module('__httplib__', *imp.find_module('httplib'))
        assert __httplib__ is httplib

        # Your application here

if __name__ == '__main__':
    main()

rawDescription: py2app'ed application runs properly in alias mode but not when bundled

description: Py2app'ed application runs properly in alias mode but not when bundled


code:
from matplotlib.ticker import FormatStrFormatter

df['YYYYMM'] = df['YYYYMM'].astype(str).str[:-2].astype(int)
t = df.pivot_table(df, index=['YYYYMM'], columns=['Group'], aggfunc=np.sum).loc[:, 'Count']

fig, axes = plt.subplots(1, 1)
margin = 0.5
t.plot(ax=axes, xticks=t.index.tolist(), xlim=(t.index.min()-margin, t.index.max()+margin), ylim=(t.min().min()-margin, t.max().max()+margin))
axes.xaxis.set_major_formatter(FormatStrFormatter('%.0f'))
plt.show()

rawDescription: Matplotlib Line Graph Shift X-Axis Values and Tick Labels


code:
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button

class mamdouh(App):

    def build(self):
        lbl = Label(text='paul')
        btn = Button(text='mamdouh')
        btn.bind(on_press=lambda b: app.stop())

        lbl.add_widget(btn)

        return lbl

if __name__ == '__main__':

    app = mamdouh()
    app.run()

rawDescription: python: kivy app not closing

description: Python: kivy app not closing


rawDescription: Inverse of a matrix 3x3 using symbols

description: Inverse of a matrix 3x3 using symbols


code:
def has_twin(ax):
    for other_ax in ax.figure.axes:
        if other_ax is ax:
            continue
        if other_ax.bbox.bounds == ax.bbox.bounds:
            return True
    return False

# Usage:

fig, ax = plt.subplots()
print(has_twin(ax))  # False

ax2 = ax.twinx()
print(has_twin(ax))  # True

rawDescription: How to detect if a twin axis has been generated for a matplotlib axis

description: Detect if a twin axis has been generated for a matplotlib axis


code:
import facebook
import hashlib
import hmac

def genAppSecretProof(app_secret, access_token):
    h = hmac.new (
        app_secret.encode('utf-8'),
        msg=access_token.encode('utf-8'),
        digestmod=hashlib.sha256
    )
    return h.hexdigest()

app_secret = "xxxxxxxxx"
access_token = "xxxxxxxxx"
api = facebook.GraphAPI(access_token)
msg = "Hello, world!"
postargs = {"appsecret_proof": genAppSecretProof(app_secret, access_token)}
status = api.put_wall_post(msg, postargs)

rawDescription: facebook graph api calls with appsecret_proof in python

description: Facebook graph api calls with appsecret_proof in python


code:
def _get_memcache_timeout(self, timeout):
    """
    Memcached deals with long (> 30 days) timeouts in a special
    way. Call this function to obtain a safe value for your timeout.
    """
    timeout = timeout or self.default_timeout
    if timeout > 2592000: # 60*60*24*30, 30 days
        # See http://code.google.com/p/memcached/wiki/FAQ
        # "You can set expire times up to 30 days in the future. After that
        # memcached interprets it as a date, and will expire the item after
        # said date. This is a simple (but obscure) mechanic."
        #
        # This means that we have to switch to absolute timestamps.
        timeout += int(time.time())
    return timeout

rawDescription: In Django/python, how do I set the memcache to infinite time?


code: os.system("python executer.pyc")

rawDescription: Issues with repeatedly executing .pyc script


code:
def _check(self, file):
    if self._rolled: return
    max_size = self._max_size
    if max_size and file.tell() > max_size:
        self.rollover()

rawDescription: SpooledTemporaryFile: units of maximum (in-memory) size?


code:
s = "AbcD"
s.lower()

rawDescription: Using Python's re to swap case

description: Using Python's re to swap case


code:
SomeModel.objects.all().datetimes('date_field', 'year')
[d.year for d in SomeModel.objects.all().datetimes('date_field', 'year')]

rawDescription: pulling all unique years from datetime fields from a django model

description: Pulling all unique years from datetime fields from a django model


code: ' '.join(text).replace(" ' ", "'")

rawDescription: join word + apostrophe + s to maintain possessive form of word

description: Join word + apostrophe + s to maintain possessive form of word


code: result = max( the_list, key=lambda item:item['likes']['count'] )

rawDescription: How to iterate through a list of dictionaries & pick one highest value

description: Iterate through a list of dictionaries & pick one highest value


code:
def dimensionalizeValue(nonDimValue, dimensions):
    return nonDimValue * dimensions

def nonDimensionalizeValue(dimValue):
    dimensions = dimValue / dimValue.value
    return dimValue / dimensions

def nonDimensionalizeFunction(function):
    def wrapper(*nonDimArgs):
        # Figure out the correct dimensions.
        dimensions = None
        # Transform/dimensionalize the arguments.
        dimArgs = [dimensionalizeValue(arg, dimensions) for arg in nonDimArgs]
        # Get output using dimensionalized arguments.
        dimVal = function(*dimArgs)
        # Non-dimensionalize the output.
        nonDimVal = nonDimensionalizeValue(dimVal)
        return nonDimVal
    return wrapper

rawDescription: Python -- nondimensionalize

description: Python -- nondimensionalize


rawDescription: Python-peewee get last saved row

description: Python-peewee get last saved row


rawDescription: Array modified via two others in python

description: Array modified via two others in python


code:
for list in dict['data']['user']['playlist']:
    db.execute("INSERT INTO json_col (title, album, artist, info) VALUES (%s, %s, %s, %s)" %
        (list[0], list[1], list[2], list[3]))
db.commit()

rawDescription: Auto-update MYSQL table with JSON using python


code:
import csv
from datetime import datetime
from cstringio import StringIO
from flask import Flask, stream_with_context
from werkzeug.datastructures import Headers
from werkzeug.wrappers import Response

app = Flask(__name__)

# example data, this could come from wherever you are storing logs
log = [
    ('login', datetime(2015, 1, 10, 5, 30)),
    ('deposit', datetime(2015, 1, 10, 5, 35)),
    ('order', datetime(2015, 1, 10, 5, 50)),
    ('withdraw', datetime(2015, 1, 10, 6, 10)),
    ('logout', datetime(2015, 1, 10, 6, 15))
]

@app.route('/')
def download_log():
    def generate():
        data = StringIO()
        w = csv.writer(data)

        # write header
        w.writerow(('action', 'timestamp'))
        yield data.getvalue()
        data.seek(0)
        data.truncate(0)

        # write each log item
        for item in log:
            w.writerow((
                item[0],
                item[1].isoformat()  # format datetime as string
            ))
            yield data.getvalue()
            data.seek(0)
            data.truncate(0)

    # add a filename
    headers = Headers()
    headers.set('Content-Disposition', 'attachment', filename='log.csv')

    # stream the response as the data is generated
    return Response(
        stream_with_context(generate()),
        mimetype='text/csv', headers=headers
    )

app.run()

rawDescription: Create and download a csv file

description: Create and download a csv file


rawDescription: Matplotlib histogram2d normalize not equal 1


code:
import logging
import sys

root = logging.getLogger()
root.setLevel(logging.DEBUG)

ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)

rawDescription: Making Python loggers output all messages to stdout in addition to log


rawDescription: Elegant mechanism to determine smallest magnitude number but preserve sign in Python


code:
with open('txt', 'r') as f:
    myList = [ line for line in f if blablablabla ]

rawDescription: Is .append() time-consuming?

description: Is .append() time-consuming


code:
def download(self, reply):
    self.request = reply.request()
    self.request.setUrl(reply.url())
    self.reply = self.manager.get(self.request)

def finished(self):
    path = os.path.expanduser(
        os.path.join('~',
                     unicode(self.reply.url().path()).split('/')[-1]))
    if self.reply.hasRawHeader('Content-Disposition'):
        cnt_dis = self.reply.rawHeader('Content-Disposition').data()
        if cnt_dis.startswith('attachment'):
            path = cnt_dis.split('=')[1]

    destination = QtGui.QFileDialog.getSaveFileName(self, "Save", path)
    if destination:
        f = open(destination[0], 'wb')
        f.write(self.reply.readAll())
        f.flush()
        f.close()

rawDescription: PySide QWebView and downloading unsupported content


code:
my_list = [1, 'the name of the set', [[1, 'data1', 'data2'],[2,'data3','data4']]]
my_list == json.loads(json.dumps(my_list))

rawDescription: User-readable file format for python list of lists


code: (input_img == 255).all(axis=2)

rawDescription: Using opencv / Numpy to find white pixels in a color image using python


code:
img = np.array([7765869, 16777215], dtype=np.uint32)
img.view(np.uint8)
img.view(np.uint8).reshape(img.shape+(4,))[..., :3]

rawDescription: Convert array of single integer pixels to RGB triplets in Python


code:
# using a set makes the later `x in keep` test faster
keep = set(['peach', 'plum', 'apple', 'kiwi', 'grape'])

list2= ['peach,0,1,1,0,1,0,1', 'carrot,1,0,1,1,0,1,1',
        'lime,0,1,1,0,1,1,0', 'apple,0,1,1,0,1,1,1']

# x.split(',',1)[0] = the part before the first `,`
new = [x for x in list2 if x.split(',',1)[0] in keep]

rawDescription: find items in list1 that are also in list2 and delete items not in list1

description: Find items in list1 that are also in list2 and delete items not in list1


code:
model = QStandardItemModel(0,1)
self.treeMedia.setModel(model)
#codus is the id of the user albums and photos' owner
for rowalb in self.SELECT_TREE_ALBUM(codus):
#we create the album item
    nodeItem = QStandardItem(str(rowalb[1]).decode('utf-8'))
    for rowph in self.SELECT_TREE_PHOTO(int(rowalb[0])):
        #after that we create photos into an album
        childItem = QStandardItem(str(rowph[0]))
        childItem.setEditable(False)
        nodeItem.insertRows(0, [childItem])
    nodeItem.setEditable(False)
    model.appendRow(nodeItem)
#the name of the column
model.setHorizontalHeaderLabels(['Data'])

rawDescription: How can I create a QTreeView like a folders and files view from database?

description: Create a QTreeView like a folders and files view from database


code:
from collections import OrderedDict
items = [1, 2, 3, 'a', 2, 4, 'a']
OrderedDict.fromkeys(items).keys()

rawDescription: Python unique list using set

description: Python unique list using set


code:
get_picks = PickViewset.as_view({
    'get': 'update_picks',
    'post': 'update_picks',
})

rawDescription: Using a single URL for GET and POST with Django REST Framework list_route


code:
folder_name_to_create = 'whatever'

if os.path.exists(folder_name_to_create):
    folder_name_to_create += '_1'

rawDescription: Python: How to find duplicate folder names and rename them?


code:
def recursivemethod(obj_to_act_on, persistent_obj=None):

    if persistent_obj == None:
        persistent_obj = set()

    # Act on your object

    return recursivemethod(newobj, persistent_obj)

rawDescription: Persistent objects in recursive python functions


rawDescription: datetime to Unix timestamp with millisecond precision

description: Datetime to Unix timestamp with millisecond precision


code:
from twill.commands import go, showforms, formclear, fv, submit

go('http://issola.caltech.edu/~t/qwsgi/qwsgi-demo.cgi/')
go('./widgets')
showforms()

formclear('1')
fv("1", "name", "test")
fv("1", "password", "testpass")
fv("1", "confirm", "yes")
showforms()

submit('0')

rawDescription: Automatically pressing a "submit" button using python


code:
iter = 0
for line in file:
  itermatch = re.search('Iteration \d+',line)
  if itermatch:
    iter = itermatch.group()
  else:
    scorematch = re.search(': [0-9.]+',line)
    if scorematch:
      dict[iter]= scorematch.group()

rawDescription: find certain words in file python

description: Find certain words in file python


code: [i for i, v in enumerate(L) if v[0] == 53]

rawDescription: How to search a list of tuples in Python

description: Search a list of tuples in Python


code:
import wx

class example(wx.Frame):
    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id,' Title', size = (205,330))
        panel = wx.Panel(self, wx.ID_ANY)
        self.textctrl = wx.TextCtrl(panel, -1,(""), pos=(10, 10),size=(170, 60))
        self.button=wx.Button(panel,label="1",pos=(100,210),size=(30,30))
        self.Bind(wx.EVT_BUTTON, self.OnButton, self.button)
    def OnButton (self,evt):
        label = evt.GetEventObject().GetLabel()
        #self.textctrl.SetValue(label)
        self.textctrl.AppendText(label)

if __name__=='__main__':
    app=wx.PySimpleApp()
    frame=example(parent=None,id=-1)
    frame.Show()
    app.MainLoop()

rawDescription: wxpython, How to display buttons label into textctrl area

description: Wxpython, How to display buttons label into textctrl area


rawDescription: How to identify the tenths part of a float in Python?

description: Identify the tenths part of a float in Python


code:
cbeds = {}
for i in range(5):
    key = 'cz' + str(i + 1)
    cbeds[key] = coolingbed(i + 1)

rawDescription: Python3: auto-generation of variable names for object children


code: sorted(a, key=lambda tup: (-tup[1],tup[0],tup[2]))

rawDescription: Sorting and ordering Vectors lists in python


code: from itertools import groupby

rawDescription: How to count sequences of repeated numbers in Python sequences?

description: Count sequences of repeated numbers in Python sequences


code:
import hashlib
from django.core.exceptions import ValidationError
from django.core.files import File
from django.db import models

class Image(models.Model):
    name = models.CharField(max_length = 255)
    caption = models.CharField(max_length = 255)
    image = models.ImageField(upload_to='uploads/',blank=True,null=True)
    original_filename = models.CharField(
        unique=False,
        null=False,
        blank=False,
        editable=False,
        max_length=256)
    sha1 = models.CharField(
        unique=True,
        null=False,
        blank=False,
        editable=False,
        max_length=40)
    rent_property = models.ForeignKey(RentProperty, related_name='Images')
    is_main_image = models.BooleanField(default=False)

    def clean(self):
        """
        Overriding clean to do the following:
            - Save  original file name, since it may already exist on our side.
            - Save SHA-1 hash and check for duplicate files.
        """

        self.original_filename = self.image.name.split('/')[-1]
        # get the hash
        file_hash = hashlib.sha1(self.image.read())
        self.sha1 = file_hash.hexdigest()

        # Check if this file has already been uploaded,
        # if so delete the temp file and raise ValidationError
        duplicate_hashes = Image.objects.all().exclude(
                id=self.id).values_list('sha1', flat=True)
        if self.sha1 in duplicate_hashes:
            if hasattr(self.image.file, 'temporary_file_path'):
                temp_file_path = self.image.file.temporary_file_path()
                os.unlink(temp_file_path)

            raise ValidationError(
                "This image already exists."
            )

rawDescription: using PATCH with a Django image field and s3

description: Using PATCH with a Django image field and s3


code:
import struct
with open("filename.txt", "r") as f:
    for line in f:
        (coop_id, lat, lon, elev, state, name, c1, c2, c3, utc_offset
         ) = struct.unpack("6sx8sx9sx6sx2sx30sx6sx6sx6sx2s", line.strip())
        (lat, lon, elev) = map(float, (lat, lon, elev))
        utc_offset = int(utc_offset)

rawDescription: Python Read Formatted String

description: Python Read Formatted String


rawDescription: SQLAlchemy (ORM, declarative): How to build query from key/values in a dict?


code:
exceptions = set("belize cambodge mexique mozambique zaire zimbabwe".split())
vowels = set('aeiou')
plurals = set("etats-unis pays-bas".split())

word, sentinel = "", "quit"
while word != sentinel:
  word = input("Enter the name of a country: ")
  if word == sentinel:
    continue
  male = word in exceptions or word[-1].lower() not in vowels
  plurality = word in plurals
  apo = word[0].lower() in vowels

  if apo:
    print("l'%s" %word)
  elif plurality:
    print("les", word)
  else:
    print("le" if male else "la", word)

rawDescription: Multiple if statements under one code, with multiple conditons


code:
def f(x):
    if (x<10):
        return f(x+1)
return x

rawDescription: exiting a Python function call

description: Exiting a Python function call


code:
if dlg.ShowModal() == wx.ID_YES:
    self.urlFld.SetValue("")
    for line in self.myList:
        conn = httplib.HTTPConnection("myproxy.com", 8080)
        conn.request("HEAD", line)
        r1 = conn.getresponse()

rawDescription: wxpython httplib with proxy shows 400 bad request

description: Wxpython httplib with proxy shows 400 bad request


code:
class DateAdd(Func):
    """
    Custom Func expression to add date and int fields as day addition
    Usage: SubscriptionProduct.objects.annotate(end_date=DateAdd('start_date','duration')).filter(end_date__gt=datetime.now)
    """
    arg_joiner = " + CAST("
    template = "%(expressions)s || ' days' as INTERVAL)"
    output_field = DateTimeField()

rawDescription: Using dateadd in django filter

description: Using dateadd in django filter


code:
mydict = {'nom':'singe', 'poids':70, 'taille':1.75}
myvar = input()
print(mydict[myvar])

rawDescription: translating user input in python

description: Translating user input in python


code:
import smtplib
from email.mime.text import MIMEText
s = smtplib.SMTP()
s.connect('localhost') # connect to the SMTP server
doc = "
Test title
"
while True:
    msg = MIMEText( doc, _subtype='html', _charset='utf-8' )
    s.sendmail('xx@xx.com', ['vholla@xx.com'], msg.as_string())
s.quit()

rawDescription: How to sendmail in Python using Mimemultipart

description: Sendmail in Python using Mimemultipart


code:
import requests
from bs4 import BeautifulSoup

serien = ['izombie', 'grandfathered', 'new-girl']
serien_links = []

# Gets chapter links
def episode_links(index_url):
    r = requests.get(index_url)
    soup = BeautifulSoup(r.content, 'lxml')
    links = soup.find_all('a')
    url_list = []
    for url in links:
        url_list.append((url.get('href')))
    return url_list

urls_unfiltered = episode_links('http://watchseriesus.tv/last-350-posts/')
with open('link.txt', 'a+') as f:
    cont = f.read().splitlines()
    for serie in serien:
        for x in urls_unfiltered:
            # check whether link is already in file. If not write link to file
            if (serie in x) and (x not in cont):
                f.write('{}\n'.format(x))

rawDescription: Reading and appending files context manager: Doesn't seem to read, only writes