code:
x = np.arange(0.5, 1.0, delta)
y = np.arange(0.5, 1.0, delta)

rawDescription: How to set as default matplotlib contour plot to always label contours

description: Set as default matplotlib contour plot to always label contours


code:
import sys
import time
from random import randrange

words = ''' this is a cool delay typing program,
right now it print string by string.

I need to know how to make it print a word by word.'''

for i in words.split():
    sys.stdout.write("{} ".format(i))
    sys.stdout.flush()

    seconds = ".8" + str(randrange(1,5,2))
    seconds = float(seconds)
    time.sleep(seconds)

rawDescription: Python 2.7 time delay word by word

description: Python 2.7 time delay word by word


code:
# define somewhere following:
import sys
import os
from contextlib import contextmanager

@contextmanager
def quiet():
    sys.stdout = sys.stderr = open(os.devnull, "w")
    try:
        yield
    finally:
        sys.stdout = sys.__stdout__
        sys.stderr = sys.__stderr__

# use it
with quiet():
    # all is quiet in this scope
    import this  # just for testing
    from rpy import *  # or whatever you want
# and this will print something
import something_that_prints

rawDescription: import rpy quietly

description: Import rpy quietly


code:
class Base:
    def __init__(self, something):
        pass

    def method_ab(self):
        pass

class A(Base):
    def __init__(self, something):
        super().__init__(something)
        self.a = X(something)

    def method_a(self):
        self.a.go()

    def method_ab(self):
        super().method_ab()
        self.a.go()

class B(Base):
    def __init__(self, something):
        super().__init__(something)
        self.b = X(something)

    def method_b(self):
        self.b.go()

    def method_ab(self):
        super().method_ab()
        self.b.go()

class C(A, B):
    pass

rawDescription: Elegant multiple inheritance in Python

description: Elegant multiple inheritance in Python


code: (value, ) = long().chained().expression().that().returns().tuple()

rawDescription: Readable convention for unpacking single value tuple


code:
[easy_install]
zip_ok = False

rawDescription: pip: Why sometimes installed as egg, sometimes installed as files

description: Pip: Why sometimes installed as egg, sometimes installed as files


code:
import urllib
f = urllib.urlopen('http://www.cnn.com')
page = f.read()
f.close()

rawDescription: with python's win32com and parsing html problem

description: With python's win32com and parsing html problem


code:
cost = opts["weightcost_pretrain"].dot(net["weights"][ix1][ix2])
weight = lrate * (CD / nCases - cost)
net["weights"][ix1][ix2] += weight

rawDescription: Readability of Scientific Python Code (Line Continuations, Variable Names, Imports)


code:
import time # import the time module
time.sleep(3) # sleep for 3 seconds

rawDescription: How to add a timer/ countdown before printing text

description: Add a timer/ countdown before printing text


code:
from collections import defaultdict

res = defaultdict(list)
for dic in data:
    for key, value in dic.items():
        old_value = res[key]
        if isinstance(value, list):
            old_value.extend(value)
        else:
            old_value.append(value)

        # alternatively:
        old_value += [value] if not isinstance(value, list) else value

rawDescription: Flattening list of dictionaries

description: Flattening list of dictionaries


code:
if int(mul)<0:
    negative.append((el,mul))
if int(mul)>0:
    positive.append((el,mul))

rawDescription: looking at a number in a tuple

description: Looking at a number in a tuple


code:
print("car, train, bus".split(','))
['car', ' train', ' bus']

rawDescription: Split a column of a csv file

description: Split a column of a csv file


code: dict3 = {k: [dict2[i] for i in v] for k, v in dict1.items()}

rawDescription: merge dictionaries in python with common key/value

description: Merge dictionaries in python with common key/value


rawDescription: Can a DataFrame be "reverse indexed"?

description: Can a DataFrame be "reverse indexed"


code:
## Using the Car constructor for validation

def __init__(self,color,manufacturer,price=1000):
    if color in manufacturer.allowed_colors:
        self.color = color
        self.manufacturer
    else:
        raise LookupError() # or something more relevant.
    self.price = price

## Or just a generic function that can be called:

def validate_car(color,manufacturer):
    if color in manufacturer.allowed_colors:
        return true
    return false

if validate_car(color,manufacturer):
    car = Car(color,manufacturer)
    session.add(car)

rawDescription: How to ensure that a attribute has a specific value?

description: Ensure that a attribute has a specific value


code:
#includes parentheses around the #QUESTION and the rest of the expression)
pattern = re.compile('(#QUESTION(?:(?:.|\s|$)[^#]+))')

rawDescription: How to keep track of and save pattern in regular expression?

description: Keep track of and save pattern in regular expression


code:
db = None
dbname = None
cursor = None

def connectdb(name = None):
    """
    Set up the global database connection and cursor, if it isn't already.

    Omit 'name' when the caller doesn't care what database is used,
    and is happy to accept whatever database is already connected or
    connect to a default database.

    Since there cannot be multiple global databases, an exception is thrown
    if 'name' is specified, the global connection already exists, and the
    names don't match.
    """
    global db, dbname, cursor
    if db is None:
        if name is None:
            name = 'MyDatabase'
        db = MySQLdb.connect(host='localhost', user='admin', password='admin', db=name)
        dbname = name
        cursor = db.cursor()
    elif name not in (None, dbname):
        raise Exception('cannot connect to the specified db: the global connection already exists and connects to a different db')

rawDescription: MySQLdb Python - test databases

description: MySQLdb Python - test databases


code:
s = "ATAGATATATGGCCCGGCCCATAGATATAT"

def fuzzy_compare(s1, s2):
    # sanity check
    if len(s1) != len(s2):
        return False

    diffs = 0
    for a, b in zip(s1, s2):
        if a != b:
            diffs += 1

        if diffs > 1:
            return False

    return True

slen = len(s) # 30
for l in range(6, 16):
  i = 0
  while (i + l * 2) <= slen:
    sub1 = s[i:i+l]
    for j in range(i+l, slen - l):
        sub2 = s[j:j+l]
        if fuzzy_compare(sub1, sub2):
            # checking if this could be partial
            partial = False
            if i + l < j and j + l < slen:
                extsub1 = s[i:i+l+1]
                extsub2 = s[j:j+l+1]
                # if it is partial, we'll get it later in the main loop
                if fuzzy_compare(extsub1, extsub2):
                   partial = True

            if not partial:
                print (i, i+l), (j, j+l)

    i += 1

rawDescription: Find repeats with certain length within a string using python


code:
from itertools import combinations
a = ['a', 'b', 'c']
map(list, combinations(a, len(a)-1))

rawDescription: Create new lists with del function

description: Create new lists with del function


rawDescription: Index numpy arrays columns by another numpy array


code:
#! /usr/bin/python2

import sys
from lxml import etree

result = etree.Element('root')
parser = etree.XMLParser(remove_blank_text=True)

# Add each file to the tree
for xmlfile in sys.argv[1:]:
  with open(xmlfile) as xmlfile:
    btree = etree.parse(xmlfile, parser)
  # Ensure that the resulting tree has the right root
  result.tag = btree.getroot().tag
  # Consider each 2nd-level item
  for bchild in btree.xpath("/*/*"):
    tags = result.xpath("./%s"%bchild.tag)
    if len(tags) == 0:
      # Add <dog-list>, for example
      #print "adding %s to %s"%(bchild.tag, result.tag)
      result.append(bchild)
    else:
      for bgrandchild in bchild:
        # add <dog>, for example
        #print "adding %s to %s"%(bgrandchild.tag, tags[0].tag)
        tags[0].append(bgrandchild)

with open("output.xml", "w") as output:
  output.write(etree.tostring(result, pretty_print = True))

rawDescription: Adding XML data from a XML file to an existing XML file


code:
years = range(min_time, max_time + 1, increment_time)

for year in years:
    print(year, end=" ") # prints a space after each value, rather than a newline
print() # add a newline at the end of the row

row_str = " ".join(str(year) for year in years) # join year strings with spaces
print(row_str) # prints whole row in one step, with a newline at the end

rawDescription: Printing x amount of times in Python

description: Printing x amount of times in Python


code:
# -*- coding: utf-8 -*-

from PySide import QtCore, QtGui, QtWebKit

class WebPage(QtWebKit.QWebPage):
    """
    QWebPage that prints Javascript errors.
    """

    def javaScriptConsoleMessage(self, message, lineNumber, sourceID):
        print('Javascript error at line number %d' % lineNumber)
        print('%s' % message)
        print('Source ID: %s' % sourceID)

class myWindow(QtWebKit.QWebView):
    def __init__(self, parent=None):
        super(myWindow, self).__init__(parent)
        self.loadFinished.connect(self.on_loadFinished)
        self.runloadfinished = True
        self.web_page = WebPage()
        self.setPage(self.web_page)
        self.load(QtCore.QUrl('http://stackoverflow.com/'))

    def on_loadFinished(self):
        if self.runloadfinished:
            self.sendkeys(QtCore.Qt.Key_Tab)
            self.sendstring("لا اله الا الله ")
            #self.sendstring("Hello World")
            self.sendkeys(QtCore.Qt.Key_Enter)
            self.sendkeys(QtCore.Qt.Key_Return)
            self.runloadfinished = False

    def sendkeys(self, char, modifier=QtCore.Qt.NoModifier, text=None):
        if not text:
            event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, char, modifier)
        else:
            event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, char, modifier, text)
        QtCore.QCoreApplication.postEvent(self, event)

    def sendstring(self, string):
        for chara in string:
            print(chara)

            # QtCore.QString() is missing when using PyQt4 for Python3
            # since str() is unicode by default on Python3
            # http://inputvalidation.blogspot.in/2010/10/python3-pyqt4-and-missing-qstring.html
            try:
                text = QtCore.QString(chara)
            except AttributeError:
                text = str(chara)

            self.sendkeys(char=QtGui.QKeySequence.fromString(str(chara))[0],
                          text=text)

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('myWindow')

    main = myWindow()
    main.show()

    sys.exit(app.exec_())

rawDescription: send keystrokes from unicode string pyqt pyside

description: Send keystrokes from unicode string pyqt pyside


code:
for i, word in enumerate(split):
    split[i] = word[0].upper() + word[1:]

result = ' '.join(split)

rawDescription: Capitalized Word Function

description: Capitalized Word Function


code: [s[:m.start()] for m in re.finditer(':|$', s)]

rawDescription: Iterating through prefixes with Python

description: Iterating through prefixes with Python


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

# Make dummy csv file for this example
from io import StringIO
result_csv = StringIO(u"""
xstuff, data1, data2, data3
0, 1, 2, 3
1, 1, 3, 4
2, 2, 1, 3
3, 1, 2, 5
""")

# Read in csv. Use names=True to also store column headers
per_data=np.genfromtxt(result_csv,delimiter=',',names=True)

# Loop over columns. Here I assume you have the x-data in the first column, so skip that one
for name in per_data.dtype.names[1:]:
    # Set the line's label to the column name
    plt.plot(per_data['xstuff'],per_data[name],label=name)

# Add a legend
plt.legend(loc=0)

plt.xlabel ('x stuff')
plt.ylabel ('y stuff')
plt.title('my test result')
plt.grid()
plt.show()

rawDescription: matplotlib add legend from csv title row to line graph

description: Matplotlib add legend from csv title row to line graph


code:
com = [["ls","/"],["wc"]]
p = None
for c in com:
    p = Popen(c, stdin=(p.stdout if p else None), stdout=PIPE, stderr=PIPE)

rawDescription: Create an empty Popen() object in Python?


code:
class Foo1:
    something = 0
    def __init__(self, n):
        self.something = n

Foo1.something
class Foo2:
    def __init__(self, n):
        self.something = n

Foo2.something

rawDescription: Class Attributes/Variables in Python

description: Class Attributes/Variables in Python


code:
import json
import urllib2

data = urllib2.urlopen('http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&q=jum&cp=3')

j = json.load(data)
k = [i for i, j, k in j[1]]
l = json.dumps(k)

rawDescription: Python: Convert JSON (returned by URL) into List


code:
import re
re.match(r'^org/?P<company_name>\w+/$', 'org/companyA')
re.match(r'^org/(?P<company_name>\w+)/?$', 'org/companyA')
re.match(r'^org/(?P<company_name>\w+)/?$', 'org/companyA').groupdict()

rawDescription: Using Python Regular Expression in Django


code:
def dispatch(self, request, *args, **kwargs):
    response = super(MySimpleView, self).dispatch(request, *args, **kwargs)

    data = {}
    data['out'] = response.data
    data['message'] = "My message"

    response.data = data

    return response

rawDescription: django-rest-framework customize serializer's output

description: Django-rest-framework customize serializer's output


code:
def kth_diag_indices(a, k):
    rows, cols = np.diag_indices_from(a)
    if k < 0:
        return rows[:k], cols[-k:]
    elif k > 0:
        return rows[k:], cols[:-k]
    else:
        return rows, cols

rawDescription: NumPy k-th diagonal indices

description: NumPy k-th diagonal indices


code:
from django.utils import simplejson

def my_ajax_view(request):
    if not request.is_ajax():
        raise Http404

    data_dict = getmydata() #lets supose is a dict
    return HttpResponse(simplejson.dumps(data_dict))

rawDescription: Passing JSON data to the front end using Django


code:
from itertools import combinations_with_replacement

n = 10
print([x for x in combinations_with_replacement(range(1,n), 2) if sum(x) == n])

[(1, 9), (2, 8), (3, 7), (4, 6), (5, 5)]

rawDescription: Find all possible combinations/partitions of 2 numbers for a given number


code:
import re

with open('input.txt') as source, open('output.txt', 'w') as target:

    newline = ''
    for line in source:
        match = re.search(r'Stuff', line)
        if match:
            target.write(newline + match.group())
            newline = '\n'

rawDescription: Don't write final new line character to a file


code:
the_list = ['albert', 'angela', 'leo', 'bridget']
[ word.upper().replace('A', 'a') for word in the_list]

rawDescription: Iterate python list and capitalize specific letters


code:
import csv
dict1 = {}

with open("test.csv", "rb") as infile:
    reader = csv.reader(infile)
    headers = next(reader)[1:]
    for row in reader:
        dict1[row[0]] = {key: int(value) for key, value in zip(headers, row[1:])}

rawDescription: python read csv file with row and column headers into dictionary with two keys

description: Python read csv file with row and column headers into dictionary with two keys


code:
def get_send_items(items, results):
    send_items = []
    results_dict = {i.path:i for i in results}
    for p, s, m in items:
        result = results_dict.get(p)
        if result is None:
            send_items.append((p, s, m, None))
        elif result.mtime != m:
            send_items.append((p, s, result.mtime, result.hash))
    return send_items

rawDescription: What is a better approach to filter these two lists into one?


code:
sentiment_words = {}  # this will be a dict of 3-member lists, with word as key

for word in words:
    if not word in sentiment_words:  # initialize the word if it's not present yet
        sentiment_words[word] = [0, 0, 0]
    if ispositive(word):  # increment the right sentiment item in the list
        sentiment_words[word][0] += 1
    elif isnegative(word):
        sentiment_words[word][1] += 1
    elif isneutral(word):
        sentiment_words[word][2] += 1

rawDescription: What data structure to use to store the sentiment count of corresponding word during sentiment analysis in python?


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

A = np.fromfile(filename, dtype='int16', sep="")
A = A.reshape([1024, 1024])
plt.imshow(A)

rawDescription: Read in Raw Binary Image in Python

description: Read in Raw Binary Image in Python


code:
# define aliases as we will need to join the table on itself
p1 = Photo
p2 = db.aliased(Photo, name='p2')

q = (
    p1.query
    # join *Photo* on itself and count the *rank* of current photo by counting the photos with date before it in the same year
    .join(p2, sa.and_(
        sa.func.extract("year", p1.date) == sa.func.extract("year", p2.date),
        p1.date >= p2.date,
    ))
    .group_by(p1.id)
    .having(sa.func.count() <= 5)
    .order_by(p1.date)  # This will automatically order by year and rank
)

rawDescription: SQLAlchemy: Query max amount per year

description: SQLAlchemy: Query max amount per year


code:
def clean_up_duplicates(dup_lookback):
    try:
        dup_start_str = dup_lookback.strftime('%Y-%m-%d %H:%M:%S')
    except AttributeError:
        dup_start = date.today() - timedelta(days=dup_lookback)
        dup_start_str = dup_start.strftime('%Y-%m-%d %H:%M:%S')

rawDescription: Is reuse of a function argument for multiple types in Python 3.4 pythonic, and how does it relate to duck typing? Should I split the function up?


code:
#!/usr/bin/env python3
import json

print(json.dumps(u'XüX → YœYö'))
# -> "X\u00fcX \u2192 Y\u0153Y\u00f6"

rawDescription: Python unicode-escape: use only \uNNNN codes, no \xNN


code:
example = u"Xerox ™ printer"
example
example.encode('ascii')
example.encode('ascii', errors='ignore')

rawDescription: python scrapy how to remove extra parsed character

description: Python scrapy how to remove extra parsed character


code:
import os
import glob
my_path = glob.glob('C:\\Windows\\Program Files\\MySWv1*\\bin')[0]
os.path.exists(my_path)

rawDescription: Interpret path with * in Windows with Python


code:
import urllib2
from bs4 import BeautifulSoup
response = urllib2.urlopen('http://www.directmirror.com/files/0GR7ZPCY')
html = response.read()
sp = BeautifulSoup(html)
ll = sp.find_all('a')
ll

rawDescription: cannot extract links with beautifulsoup4 on dirrectmirror web page

description: Cannot extract links with beautifulsoup4 on dirrectmirror web page


code:
ids = [i['id'] for i in json_array]
qs = model.objects.exclude(id__in=ids)

rawDescription: Django - Query models where id equals attribute on python list


code: print ('%10d %10s') % (value1, value2),

rawDescription: python 2.6 print with formatting (%): remove newline

description: Python 2.6 print with formatting (%): remove newline


rawDescription: How to remove standart menuitem from QTextEdit context menu

description: Remove standart menuitem from QTextEdit context menu


code:
pl.figure(0, figsize=(16,6))
gs = gridspec.GridSpec(1,1)
gs.update(left=0.05, right=0.45, bottom=0.15, top=0.95)
ax = pl.subplot(gs[0,0])  # save the axes to ax
pl.imshow(scores, interpolation='nearest', cmap=pl.cm.spectral)
pl.xlabel('gamma')
pl.ylabel('C')
pl.xticks(np.arange(len(gamma_range)), gamma_range, rotation=45)
pl.yticks(np.arange(len(C_range)), C_range)
gs = gridspec.GridSpec(3,3)
gs.update(left=0.5, right=0.95, bottom=0.05, top=0.95)
pl.subplot(gs[0,0])  # here's where the shift happens

pl.colorbar(ax=ax) # create colorbar for ax
pl.show()

rawDescription: Inadvertantly Shifting Plots in Matplotlib


code:
from random import*
a=randrange(1,51)
b = 0
guesses = 0 #Initialize a variable to store how many guesses the user has used
while b != a:
    b=int(input("Can you guess my number?: "))
    if a>b:
        b=int(input("Too low, try again: "))
    else:
        b=int(input("Too high, try again: "))
    guesses+=1

print("You got it! The number was", a)
print("You took {} guesses!".format(guesses))

rawDescription: how do I keep track of the number of inputs for a while loop in python?

description: Keep track of the number of inputs for a while loop in python


rawDescription: How to transfer a file between two FTP servers?

description: Transfer a file between two FTP servers


code:
from scipy.spatial.distance import cosine
from pandas import DataFrame

df = DataFrame({"col1": [158, 25, 180, 152, 96],
                "col2": [173, 191, 33, 165, 108]})

print(1 - cosine(df["col1"], df["col2"]))

rawDescription: Python pandas: Finding cosine similarity of two columns


code:
from matplotlib.pyplot import plot, show
plot([SSLPXPoint1, SSLPXPoint2], [SSLPYPoint1, SSLPYPoint2])
plot([SSLPXPoint3, SSLPXPoint2], [SSLPYPoint3, SSLPYPoint2])
plot([SSLPXPoint3, SSLPXPoint4], [SSLPYPoint3, SSLPYPoint4])
show()

rawDescription: Connecting lines between points plotted in Matplotlib


code:
returned = Person.objects.filter( carusage__end__isnull=True ).annotate(Max('carusage__start'))
not_returned = Person.objects.filter( carusage__end__isnull=False ).annotate(Max('carusage__end'))

rawDescription: Retrieving newest object for persons

description: Retrieving newest object for persons


code:
import sys
import re
import os

assert len(sys.argv) == 3, "Usage: %s LT-dir extract-dir"%sys.argv[0]
_, ltdir, exdir = sys.argv

def key(x):
    return [int(y) for y in re.findall('\d+', x)]
ltfiles = sorted(os.listdir(ltdir), key=key)
exfiles = sorted(os.listdir(exdir), key=key)

for exfile,ltfile in zip(exfiles, ltfiles):
    os.rename(os.path.join(exdir,exfile), os.path.join(exdir,ltfile))

rawDescription: Rename files in a folder based on names in a different folder


code:
env.Command('foo.out', 'foo.in',
            'dateVar=$$(date +%F-%k-%M); '
            'sed -i "s/\.txt/\.txt?v=$$dateVar/g" example.properties');

rawDescription: How to append timestamp to matching string using SCons' env.Command

description: Append timestamp to matching string using SCons' env.Command


rawDescription: Python: Is there a way to access variables from other functions without using 'global'?


code:
application = webapp.WSGIApplication([
    (r'/view/<database:[^/]*>/<table:[^/]*>', ViewTable),
], debug=True)

rawDescription: Nested routing in webapp2

description: Nested routing in webapp2


code:
condition = df.one >= df.two
df.loc[condition, 'three'] = df['four']
df.loc[condition, 'five'] = df['two'] / df['four']

rawDescription: in dataframe multicolumn elementwise operation (Pandas)

description: In dataframe multicolumn elementwise operation (Pandas)


code:
from mpl_toolkits.mplot3d import axes3d, art3d
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x, t = np.arange(0,10,0.1), np.arange(0,10,0.1)
X, T = np.meshgrid(x, t)  # generate two 100x100 arrays
Z = np.cos(2*np.pi*(X/3.0 - T/6.0))

wire = ax.plot_wireframe(X, T, Z, rstride=10, cstride=10)

# Retrive data from internal storage of plot_wireframe, then delete it
nx, ny, _  = np.shape(wire._segments3d)
wire_x = np.array(wire._segments3d)[:, :, 0].ravel()
wire_y = np.array(wire._segments3d)[:, :, 1].ravel()
wire_z = np.array(wire._segments3d)[:, :, 2].ravel()
wire.remove()

# create data for a LineCollection
wire_x1 = np.vstack([wire_x, np.roll(wire_x, 1)])
wire_y1 = np.vstack([wire_y, np.roll(wire_y, 1)])
wire_z1 = np.vstack([wire_z, np.roll(wire_z, 1)])
to_delete = np.arange(0, nx*ny, ny)
wire_x1 = np.delete(wire_x1, to_delete, axis=1)
wire_y1 = np.delete(wire_y1, to_delete, axis=1)
wire_z1 = np.delete(wire_z1, to_delete, axis=1)
scalars = np.delete(wire_z, to_delete)

segs = [list(zip(xl, yl, zl)) for xl, yl, zl in \
                 zip(wire_x1.T, wire_y1.T, wire_z1.T)]

# Plots the wireframe by a  a line3DCollection
my_wire = art3d.Line3DCollection(segs, cmap="hsv")
my_wire.set_array(scalars)
ax.add_collection(my_wire)

plt.colorbar(my_wire)

#cl1 = fig.colorbar(pl1)
#cl1.set_label("$z$-axis")
fig.suptitle(r'Travelling wave $z=f(x,t)=\cos(2\pi(x/3-t/6))$')
ax.set_xlabel(r'$x$', fontsize=16)
ax.set_ylabel(r'$t_0$', fontsize=16)
ax.set_zlabel(r'$z$', fontsize=16)

fig.canvas.draw()
plt.show()

rawDescription: Colored mesh plot of a function in Python


code:
filename = 'path/to/file{0:05}.ext'
n = 0
while os.path.exists(filename.format(n)):
    n += 1
print(filename.format(n))

rawDescription: CSV folder always get overwritten

description: CSV folder always get overwritten


code:
from tkinter import * #imports everything from the tkinter library

def confirm(event=None): #set event to None to take the key argument from .bind
    print('Function successfully called!') #this will output in the shell

master = Tk() #creates our window

option1 = Button(master, text = 'Press Return', command = confirm)
option1.pack() #the past 2 lines define our button and make it visible

master.bind('<Return>', confirm) #binds 'return' to the confirm function

rawDescription: How to call a function whenever a key is pressed in python

description: Call a function whenever a key is pressed in python


code:
#!<here goes user defined python directory absolute path>
# -*- coding: utf-8 -*-

import sys
from main_script import main

if __name__ == "__main__":
    sys.exit(main())

rawDescription: changing os.environ with global scope

description: Changing os.environ with global scope


code:
def application(env, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return [ env['SERVER_PORT'] ]

rawDescription: Apache running on which Port

description: Apache running on which Port


rawDescription: Tk basic label placement

description: Tk basic label placement


code:
from shapely.geometry import LineString
from shapely.ops import cascaded_union

lines = [
    LineString([(845, 555), (365, -5), (130, -650)]),
    LineString([(740, 605), (640, 60), (315, -375)]),
    LineString([(0, -500), (655, -150), (900, 300)]),
]

# Two example unions
unioned_lines = cascaded_union(lines)
unioned_buffered_poly = cascaded_union([l.buffer(50) for l in lines])

rawDescription: How to merge multiple buffer objects in Python?

description: Merge multiple buffer objects in Python


code:
txt = elementParent.get_text()
# for example

rawDescription: Is it possible to address a web element using its webdriver object ID (temporary name)?


code:
classes = ['class0', 'class1', 'class2']
values =[0,1,2]
output = {} #create a dictionary instance

for x, y in zip(classes, values):
    output[x] = np.where(data == y) #use the class name as the dictionary key

rawDescription: Pythonic way to simple array handling

description: Pythonic way to simple array handling


code:
def test(request):
    obj2 = Student.objects.get(name='john')
    classes_name = obj2._meta.get_field('classes').related_model.__name__
    return render(request, 'test/list.html',
                  {'obj2':obj2, 'classes_name': classes_name})

rawDescription: How can I properly use related_name in django models to get back the class name?

description: Properly use related_name in django models to get back the class name


code:
from flask import request
from flask.ext.restful import abort, Resource
from functools import wraps

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth:
            abort(401)
        user = User.objects(username=auth.username).first()
        auth_ok = False
        if user != None:
            auth_ok = verify_password(auth.password) == user.password
        if not auth_ok:
            return abort(401)
        return f(*args, **kwargs)
    return decorated

class UserAPI(Resource):
    @requires_auth
    def get(self):
        user = User.objects(username=request.authorization.username).\
            exclude('password').first()

        if user is not None:
            return user.to_json()
        else:
            abort(404, message='User not found: ' + username)

rawDescription: Flask RESTful API and authenticating for a specific user


code:
for i in range(len(versions)):
    for j in range(len(versions['v8'+str(i)])):
        try:
            if client['client_' + str(i+1)][j] < versions['v8' + str(i)][j]:
                print ("client_" + str(i+1), "Program_" + str(j+1), client["client_" + str(i+1)][j],"-->",versions["v8"+str(i)][j])
        except TypeError:
            print ("client_" + str(i+1), "Program_" + str(j+1), "Missing")
            continue

rawDescription: Compare integer values between two dictionaries in Python


code:
with open("hk_L1.ref") as f:
    data = numpy.array(f.read().split(), dtype=float).reshape(7000, 8)

rawDescription: Python: How to read a data file with uneven number of columns


code:
from itertools import compress, cycle
array = [1, 2, 3, 4, 5, 6, 7, 8]
list(compress(array, cycle([1,1,0,0])))

rawDescription: Python - Iterating through array in an unorthodox manner


code:
a, b, c = 10, 10, 1    #default values
mylist = [int(x) for x in input.split(',')]
a, b, c = mylist + [a, b, c][len(mylist):]

rawDescription: What's the best way to parse values from a variable length string?


code:
def f():
  pass
class A(object):
  pass
a = A()
a == f
setattr(A, '__eq__', lambda x,y: True)
a == f
setattr(f.__class__, '__eq__', lambda x,y: True)

rawDescription: Test equality of two functions in python


code: #!/usr/bin/python

rawDescription: Make Python script globally executable

description: Make Python script globally executable


code:
with app.test_client() as c:
    with c.session_transaction() as sess:
        sess['user_id'] = 'myuserid'
        sess['_fresh'] = True
    c.set_cookie('localhost', 'MYCOOKIE', 'cookie_value')
    resp = c.get('/someurl')

rawDescription: flask unit test: send cookies after modifying the session

description: Flask unit test: send cookies after modifying the session


rawDescription: Remove columns with values 0 or 999999

description: Remove columns with values 0 or 999999


code:
def proofOfConcept():
    def wrapper(func):

        class MethodDecoratorAdapter(object):
            def __init__(self, func):
                self.func = func
                self.is_method = False

            def __get__(self, instance, owner):
                if not self.is_method:
                    self.is_method = True
                self.instance = instance

                return self

            def __call__(self, *args, **kwargs):
                # Decorator real logic goes here
                if self.is_method:
                    return self.func(self.instance, *args, **kwargs)
                else:
                    return self.func(*args, **kwargs)

        return wraps(func)(MethodDecoratorAdapter(func))

    return wrapper

rawDescription: How to detect is decorator has been applied to method or function?

description: Detect is decorator has been applied to method or function


code:
import urllib2

url = "http://localhost:8888/"
data = '{"From": "sender@email.com", "To": "recipient@email.com", "Subject": "Postmark test", "HtmlBody": "Hello dear Postmark user."}'
headers = {
    "Content-Type": "application/json"
}
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()

rawDescription: How to POST a local file using urllib2 in Python?


code:
from datetime import datetime as DateTime
from itertools import imap, groupby
from operator import itemgetter

get_first = itemgetter(0)
get_second = itemgetter(1)

def process_line(line):
    timestamp_string, _, values = line.partition(',')
    timestamp = DateTime.strptime(timestamp_string, '%Y-%m-%d %H:%M:%S')
    return (
        timestamp.replace(minute=timestamp.minute // 15 * 15, second=0),
        values
    )

def main():
    with open('sample.txt', 'r') as lines:
        for date, group in groupby(imap(process_line, lines), get_first):
            with open('{0:%Y-%m-%d %H_%M}.csv'.format(date), 'w') as out_file:
                out_file.writelines(imap(get_second, group))

if __name__ == '__main__':
    main()

rawDescription: Generating multiple CSV files on hourly basis in Python


code:
for i in range(3):
    for j in range(4):
        img_tmp = img.crop((i*a, j*b, (i+1)*a, (j+1)*b))
        img_tmp.save("img_{}_{}.jpg".format(i, j))

rawDescription: Automate image cutting with python

description: Automate image cutting with python


code:
@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename) #Sanitised here
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))

rawDescription: How to sanitize user-provided paths in Python and Flask?

description: Sanitize user-provided paths in Python and Flask


code: bisect.insort(L, X)

rawDescription: Inserting and removing into/from sorted list in Python


code:
safe_md5 = hashlib.md5(salt + password)
crypto_hash = safe_md5.digest()
hash_correct = crypto_hash.encode('base64')

rawDescription: Correct way to put long function calls on multiple lines


code:
from PyQt4 import QtGui

app = QtGui.QApplication([])

menu = QtGui.QMenu()

sub_menu = QtGui.QMenu("Sub Menu")

for i in ["a", "b", "c"]: #or your dict
    sub_menu.addAction(i) #it is just a regular QMenu

menu.addMenu(sub_menu)

menu.show()

app.exec_()

rawDescription: dropdown menu with sub menu in pyqt4

description: Dropdown menu with sub menu in pyqt4


code:
sentences = [ "the quick brown fox jumps over the lazy dogs",
"Then a cop quizzed Mick Jagger's ex-wives briefly." ]
word2vec.Word2Vec([s.encode('utf-8').split() for s in sentences], size=100, window=5, min_count=5, workers=4)

rawDescription: How to load sentences into Python gensim?

description: Load sentences into Python gensim


code:
import sys
sys.setrecursionlimit(10000)

rawDescription: Two versions of my input function, recursion vs while-loop?


code:
import urllib2
import lxml.html as LH

url = 'http://www.mega.pk/laptop_products/13242/Apple-MacBook-Pro-with-Retina-Display-Z0RG0000V.html'
response = urllib2.urlopen(url)
html = response.read()
doc=LH.fromstring(html)
heading = doc.xpath('//*[@id="main1"]/div[1]/div[1]/div/div[2]/div[2]/div/div[1]/h2/span/text()')
content = doc.xpath('//*[@id="main1"]/div[1]/div[1]/div/div[2]/div[2]/div/p/text()')
price = doc.xpath('//*[@id="main1"]/div[1]/div[1]/div/div[2]/div[2]/div/div[2]/div[1]/div[2]/span/text()')
wifi_location = doc.xpath('//*[@id="laptop_detail"]//tr/td[contains(. ,"Wireless")]')[0]
wifi_status = wifi_location.getnext().find('span').text

rawDescription: Unable to fetch element using scrapy

description: Unable to fetch element using scrapy


code:
self.colorVar = StringVar()
btOrange = Radiocutton(..., variable=self.colorVar, value="Orange")
btPurple = Radiobutton(..., variable=self.colorVar, value="Purple")

rawDescription: Only allow one RadioButton selection in tkinter


code:
with open('log.txt','w') as log:
    for value in log_disk.values():
        log.write('{}\n'.format(value))

rawDescription: writing only dictionary values into a text file

description: Writing only dictionary values into a text file


code:
_all = list(set(A))+list(set(B))+list(set(C))
indexes = [[u.index(x) for x in u if (_all).count(x) > 1] for u in [A, B, C]]

rawDescription: get the index of the string elements which are common to more than one lists

description: Get the index of the string elements which are common to more than one lists


code:
def getBlocks(filepath):
    with open(filepath) as f:
        blocks = []
        go = False
        for line in f:
            if line.strip() == startDelimiter:
                block = ''
                go = True
            if go:
                block += line
            if line.strip() == endDelimiter:
                blocks.append(block)
                block = ''
                go = False
        if block:
            blocks.append(block)
    return blocks

rawDescription: Python read specific lines of text

description: Python read specific lines of text


code:
import io,re,unittest,os,json,sys
from subprocess import PIPE, STDOUT, Popen
sub = Popen(["/usr/bin/python3.4", "test2.py", "pipe"], stdin=PIPE, stdout=PIPE, stderr=sys.stderr, close_fds=True, shell=False)
(writer,reader) = (sub.stdin, sub.stdout)
writer.write("HELO\t1\n".encode("utf-8"))
writer.flush()
sub.poll()
line = reader.readline().decode("utf-8")
assert(re.match("^OK\t", line))
writer.write("Q\ttest.com\tIN\tSOA\t-1\t127.0.0.1\n".encode("utf-8"))
writer.flush() # <<< INSERTED FLUSH <<<
line = reader.readline().decode("utf-8")
assert(re.match("^DATA\ttest.com\tIN\tSOA\t300\t-1\tsns.dns.icann.org. noc.dns.icann.org. 2013073082 7200 3600 1209600 3600", line))
sub.stdout.close()
sub.stdin.close()
sub.kill()
sub.wait()
sub.wait()

rawDescription: Script incompatibility for Python 2.x and Python 3.x


code:
df = pd.DataFrame.from_dict(list_of_dictionaries)
df.groupby('item_id').sum()

rawDescription: How to increment Python Pandas DataFrame based on key/values from a dictionary

description: Increment Python Pandas DataFrame based on key/values from a dictionary


code:
import ast

with open("scores.txt") as inf:
    scores = [ast.literal_eval(line) for line in inf]

scores.sort(key = lambda x: -x[1])

rawDescription: how to read a list of tuples in Python

description: Read a list of tuples in Python


code: itemsKeyedById = dict((i["id"], i) for i in myList)

rawDescription: python dict comprehension working locally but not on server - version issue

description: Python dict comprehension working locally but not on server - version issue


code:
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('foo', dest='foo', nargs=1)
group.add_argument('read', dest='read', nargs=1)
args = parser.parse_args()
return args

rawDescription: How to require one command line action argument among several possible but exclusive?

description: Require one command line action argument among several possible but exclusive


code:
numInversions = 0
for i in range(16):
    for j in range(i):
        if state.index(START[j]) > state.index(START[i]):
            numInversions += 1

rawDescription: How exactly does this work sum()?

description: How exactly does this work sum()


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

def multicolored_lines():
    """
    http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
    http://matplotlib.org/examples/pylab_examples/multicolored_line.html
    """

    x = np.linspace(0, 4. * np.pi, 100)
    y = np.sin(x)
    fig, ax = plt.subplots()
    lc = colorline(x, y, cmap='hsv')
    plt.colorbar(lc)
    plt.xlim(x.min(), x.max())
    plt.ylim(-1.0, 1.0)
    plt.show()

def colorline(
        x, y, z=None, cmap='copper', norm=plt.Normalize(0.0, 1.0),
        linewidth=3, alpha=1.0):
    """
    http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
    http://matplotlib.org/examples/pylab_examples/multicolored_line.html
    Plot a colored line with coordinates x and y
    Optionally specify colors in the array z
    Optionally specify a colormap, a norm function and a line width
    """

    # Default colors equally spaced on [0,1]:
    if z is None:
        z = np.linspace(0.0, 1.0, len(x))

    # Special case if a single number:
    # to check for numerical input -- this is a hack
    if not hasattr(z, "__iter__"):
        z = np.array([z])

    z = np.asarray(z)

    segments = make_segments(x, y)
    lc = mcoll.LineCollection(segments, array=z, cmap=cmap, norm=norm,
                              linewidth=linewidth, alpha=alpha)

    ax = plt.gca()
    ax.add_collection(lc)

    return lc

def make_segments(x, y):
    """
    Create list of line segments from x and y coordinates, in the correct format
    for LineCollection: an array of the form numlines x (points per line) x 2 (x
    and y) array
    """

    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    return segments

multicolored_lines()

rawDescription: python matplotlib with a line color gradient and colorbar

description: Python matplotlib with a line color gradient and colorbar


code:
import random
import string
def passgen(n = 12):
    possible_lettters = string.ascii_letters + string.digits
    return ''.join(random.choice(possible_lettters ) \
                   for x in range(n))

In [92]: print(passgen(30))
cjBQgGJO5nlEyMlP2fdiZ6ra4IvDzF

rawDescription: Why does this script only print up to 32 characters?


code:
from collections import Counter

with open('ip.txt') as f:
    cnt = Counter(line.strip() for line in f)
    print('{:<20} {}'.format('IP Address', 'count(number of repeated)'))
    for ip, c in cnt.most_common():
        print('{:<20} {}'.format(ip, c))

rawDescription: Count number of repeated in the list

description: Count number of repeated in the list


rawDescription: Confusion with re.sub

description: Confusion with re.sub


code:
from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
    im=Image.open(filename)
    image_list.append(im)

rawDescription: Importing images from a directory (Python)


code:
with open('infile.txt', 'r') as f:
    lines = f.readlines()

with open('outfile.txt', 'w') as f:
    f.write('\\data\\\n')
    f.write('n-grams = {}\n'.format(len(lines)))
    f.write('\\1-grams:\n')
    for l in lines:
        f.write(l)

rawDescription: How to count number of lines and insert that value in the file

description: Count number of lines and insert that value in the file


code:
AUTHENTICATION_BACKENDS = (
    'django_auth_ldap.backend.LDAPBackend',
    'django.contrib.auth.backends.ModelBackend',
)

rawDescription: LDAP authentication with django REST

description: LDAP authentication with django REST


code: textwrap.fill(text, width)

rawDescription: Python - Insert newlines into text so text won't exceed max character width


code:
x
dict( i.split('=') for i in x )

rawDescription: Simple way to convert list to dict

description: Simple way to convert list to dict


rawDescription: How do I see "print"s from a python tkinter app converted to a .exe?

description: See "print"s from a python tkinter app converted to a .exe


code:
import operator

def operations(value, position, func):
    actions = {
        0: (operator.mul, 2),
        1: (operator.add, 2),
        2: (operator.mul, 3),
        3: (operator.add, 0),
    }

    for i, action in actions.items():
        if position == i:
            value = func(value)
        operation, val2 = action
        value = operation(value, val2)
    return value

rawDescription: Specify the postion to call a function in a series of steps


code:
def OnPaste(evt):
    pass #do something

pasteID = wx.NewId()
aTable = wx.AcceleratorTable([(wx.ACCEL_CTRL,  ord('V'), pasteID ),])
my_main_frame.SetAcceleratorTable(aTable)
my_main_frame.Bind(wx.EVT_MENU,OnPaste,pasteID )

rawDescription: Wxpython: How to bind keyboard events of windows os directly with Application


code:
f = open('df.info', 'w+')

df.info(buf=f)

f.close()

rawDescription: how to save output from dataframe info to file a excel or text file

description: Save output from dataframe info to file a excel or text file


code:
import collections
inverse = collections.defaultdict(list)
for key, val in d.items():
    inverse[val].append(key)

rawDescription: Using append method in a for loop

description: Using append method in a for loop


rawDescription: Selecting parent element when child has a specific value of attribute using elementree xpath in Python


code:
class MySerializer(Serializer):
    def format_datetime(self, data):
        return utc_to_est_human(data)

    def format_date(self, data):
        return data.strftime("%Y-%m-%d")

    def to_xml(self, data, options=None):
        """
        Given some Python data, produces XML output.
        """
        options = options or {}

        if lxml is None:
            raise ImproperlyConfigured("Usage of the XML aspects requires lxml and defusedxml.")

        etree = self.to_etree(data, options)

        for element in  etree.xpath('//media/object'):
            for child in element.getchildren():
                element.set(child.tag, child.text)
                element.remove(child)

        return tostring(etree, encoding='utf-8')

rawDescription: Custom output XML (with attributes) with TastyPie?


code:
def setup_logger(logger_name, log_filename):
    import logging
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.DEBUG)
    file_handler = logging.FileHandler(log_filename, 'w')
    formatter = logging.Formatter(_FORMAT)
    file_handler.setFormatter(formatter)

    # Replace the previous handlers with the new FileHandler
    for old_handler in logger.handlers:
        logger.removeHandler(old_handler)
    logger.addHandler(file_handler)

    return logger

rawDescription: Python: multiple loggers write logs into similar file


code:
for elem in soup.findAll(['script', 'style']):
    elem.extract()

rawDescription: Getting html stripped of script and style tags with BeautifulSoup?


rawDescription: producing an array with the same number in

description: Producing an array with the same number in


code:
(t - pd.Timestamp(0)).days
Out[12]: 16217

(d - datetime.datetime(1970, 1, 1)).days
Out[13]: 16217

rawDescription: Methods for reference date from pandas Timestamp object and datetime object?


code:
megroup = t1sub.add_mutually_exclusive_group()
megroup.add_argument('--in', action='store_true')
megroup.add_argument('--out', action='store_true')
parser.parse_args(['task1', '--in'])
t1sub.print_help()
parser.print_help()

rawDescription: Python: how to have mutually exclusive groups in subparser using argparse?


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

im = plt.imread('stinkbug.png')

# Create Figure and Axes objects
fig,ax = plt.subplots(1)

# display the image on the Axes
implot = ax.imshow(im)

# Some dummy data to use in pcolor
x = np.arange(im.shape[1])
y = np.arange(im.shape[0])
X,Y = np.meshgrid(x,y)
data = X+Y

# plot the pcolor on the Axes. Use alpha to set the transparency
p=ax.pcolor(X,Y,data,alpha=0.5,cmap='viridis')

# Note I changed your coordinates so the arrow would fit on this image
ax.annotate("",
        xy=(458, 150), xycoords='data',
        xytext=(452.8, 250), textcoords='data',
        arrowprops=dict(arrowstyle="<-",
                        connectionstyle="arc3"),
        )

# Add a colorbar for the pcolor field
fig.colorbar(p,ax=ax)

plt.savefig('foo.png')

rawDescription: How to plot pcolor over image matplotlib?

description: Plot pcolor over image matplotlib


rawDescription: Adding a row to a Pandas DataFrame that would duplicate index


code: d = datetime.utcfromtimestamp(3600 * ((input_epoch + 1800) // 3600))

rawDescription: python epoch to hour with rounding

description: Python epoch to hour with rounding


code:
class Picture(ndb.Model):
    cdate = ndb.DateTimeProperty(auto_now_add=True)
    filename = ndb.StringProperty(required=True)
    gs_key = ndb.StringProperty(required=True)
    _serving_url = ndb.StringProperty(indexed=False)

    @property
    def serving_url(self):
        if self.gs_key:
            if not self._serving_url:
                self._serving_url = images.get_serving_url(self.gs_key,48,True)
                self.put()
            return self._serving_url
        return ''

rawDescription: It is "safely persist" the url generated by the images.get_serving_url()


code:
self.main_widget = QtGui.QWidget(self)
self.plot_widget = QtGui.QWidget(self.main_widget)
self.plot_widget.setGeometry(250,180,500,600)
self.figure = plt.figure()
self.plotting = FigureCanvas(self.figure)
self.plot()
plot_box = QtGui.QVBoxLayout()
plot_box.addWidget(self.plotting)
self.plot_widget.setLayout(plot_box)

rawDescription: Python - PyQt Matplotlib plot positioning


code:
import keyword
keyword.kwlist

rawDescription: List of python keywords

description: List of python keywords


code:
import base64
from PIL import Image
from io import BytesIO

im = Image.open(BytesIO(base64.b64decode(data)))
output = BytesIO()
im.save(output, 'JPEG')
jpg_img = output.read()

rawDescription: Converting base64 images to base64 JPG

description: Converting base64 images to base64 JPG


code:
assert self.__observers[event] == []
observer_ref = self.__observers[event]
observer_ref.append(1)                    # this modifies self.__observers[event]
assert self.__observers[event] == [1]

rawDescription: Is it possible to take a reference to a dictionary item in Python?


code:
articles_per_author_per_year = Article.objects.all() \
    .values('year', 'authors_name').order_by('year')\
    .annotate(articles=models.Count('id'))

rawDescription: Annotate values and group by M2M field in Django


rawDescription: Difference between list slicing and direct assignment from list?


code: df[df.categories.map(lambda cats: 'Restaurants' in cats)]

rawDescription: Python pandas dataframe slicing, with if condition


code: r'''\copy (select sr, id, rc AS jql from sr UNION select 'quickfilter', "ID", "QUERY" from "AO_60DB71_QUICKFILTER") TO xxx.csv'''

rawDescription: How to easily work with python strings containing both single and double quotes?

description: Easily work with python strings containing both single and double quotes


code: list(product(*nested_list)) # without list() normally, of course

rawDescription: pass list of iterables to itertools function

description: Pass list of iterables to itertools function


code:
Solution
import pandas as pd

df.loc[pd.IndexSlice[:, 'bbb'], :]

rawDescription: Nested Pandas dataframe - How to select / group by data?


code:
# order='F' is important here so column-wise assignment can
# occur with a stride of 1.  Switching the order results
# in a significant performance hit.
coords = numpy.zeros([a.size,4],'d',order='F')

NI, NJ, NK = a.shape

# build columns for (i,j,k) tuples using repeat and tile
coords[:,0] = numpy.repeat(range(NI),NJ*NK)
coords[:,1] = numpy.tile(numpy.repeat(range(NJ),NK), NI)
coords[:,2] = numpy.tile(range(NK), NI*NJ)
coords[:,3] = a.flatten()

rawDescription: Efficiently Reshape 3D Numpy Array into 1D List Plus Coordinate Vector


code:
response = requests.get('https://github.com/')
len(response.content)

rawDescription: Size of raw response in bytes

description: Size of raw response in bytes


code:
for i in xrange(DB_MOD):
    db_dict = myapp.copy()
    db_dict['NAME'] = 'myapp_idmod_' % i
    DATABASES['myapp_idmod_%s' % i] = db_dict

rawDescription: django settings.py and multi-database help

description: Django settings.py and multi-database help


code:
import random
L1 = [['sub11'],['sub12'],['sub13']]
L2 = [['sub21'],['sub22'],['sub23']]
L3 = [['sub31'],['sub32'],['sub33']]
L4 = [['sub41'],['sub42'],['sub43']]
all_lists = [L1, L2, L3, L4]
random_lists = map(list, list(zip(*(random.sample(item, len(item)) for item in all_lists))))
for i in random_lists:
    print(i)

rawDescription: Randomly select subsets from lists of sublists


code:
from collections import Counter
import csv

with open("/Users/Adnan/Desktop/twitter_data.txt") as data, open("trending.txt") as out:
    wr = csv.writer(out)
    counts = Counter(part for tag in map(str.capitalize, data)
                     for part in data.split()
                         if "#" in part)
    wr.writerows(counts.most_common())

rawDescription: How to order by frequency from highest to lowest

description: Order by frequency from highest to lowest


code:
control_list = numpy.array([1, 0, 1, 1, 0])
data_list = numpy.array([5, 4, 5, 5, 4])
numpy.product(data_list[control_list==1])

rawDescription: conditional product in numpy

description: Conditional product in numpy


code:
doc = view.page().mainFrame().documentElement()
zoom_level = doc.evaluateJavaScript("PyMaps[0].gmap.getZoom();")

rawDescription: PyMaps: How to interact with javascript in python


rawDescription: Return groupby columns as new dataframe in Python Pandas


code:
import matplotlib.pyplot as plt

# column indices
HS, MATH, VERBAL, COLLEGE, COMPSCI = range(5)
# column labels
LABELS = ["High school GPA", "Math SAT", "Verbal SAT", "College GPA", "CompSci GPA"]
# column data types
DTYPES = [ float,             int,        int,          float,         float       ]

def read_columns(fname, encoding="utf-8", separator=",", dtypes=None):
    """
    Return columns of data from a file

    If dtypes is specified, convert each column to the given data type
    """
    # read rows from data file
    with open(fname, encoding=encoding) as inf:
        rows = [line.split(separator) for line in inf]
    # transpose to columns
    cols = zip(*rows)
    # apply data types
    if dtypes is not None:
        cols = [[dtype(cell) for cell in col] for dtype,col in zip(dtypes,cols)]
    return cols

def linear_regression(xs, ys):
    """
    Return the linear regression constants m,b
      in the least-squares best fit to y = m*x+b
    """
    # if you have SciPy you can use scipy.stats.linregress instead
    n = len(xs)
    xsum  = sum(xs)
    ysum  = sum(ys)
    xxsum = sum(x*x for x in xs)
    xysum = sum(x*y for x,y in zip(xs, ys))
    m = (n * xysum - xsum * ysum) / (n * xxsum - xsum * xsum)
    b = (ysum - m * xsum) / n
    return m, b

def r_squared(xs, ys):
    m, b = linear_regression(xs, ys)
    ysum, n = sum(ys), len(ys)
    ymean = ysum / n
    ssum = sum((y - (m * x + b))**2 for x,y in zip(xs, ys))
    tsum = sum((y - ymean)**2 for y in ys)
    return 1 - ssum / tsum

def plot_regression(xs, xlabel, ys, ylabel):
    m, b = linear_regression(xs, ys)
    min_, max_ = min(xs), max(xs)
    plt.scatter(xs, ys)
    plt.plot([min_, max_], [m * min_ + b, m * max_ + b], "r")
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.show()

def main():
    # read data
    scores = read_columns("satFINAL.txt", dtypes=DTYPES)
    # add composite math-and-verbal score
    MATH_VERBAL = 5
    LABELS.append("Math+Verbal SAT")
    DTYPES.append(int)
    scores.append([math+verbal for math,verbal in zip(scores[MATH], scores[VERBAL])])

    # do raw score plots
    plt.figure(1)
    num_figs = len(LABELS)
    # draw subplots
    for fig, column, nums in zip(range(num_figs), LABELS, scores):
        plt.subplot(num_figs, 1, fig+1)
        plt.plot(range(len(nums)), nums)
        plt.xlabel(LABELS[fig])
    # display results
    plt.show()

    # do regression plots
    regressions = [
        (HS,          COLLEGE),
        (MATH,        COLLEGE),
        (VERBAL,      COLLEGE),
        (MATH_VERBAL, COLLEGE),
        (MATH,        VERBAL),
        (MATH,        COMPSCI),
        (HS,          COMPSCI),
        (MATH_VERBAL, COMPSCI)
    ]
    for x,y in regressions:
        print("r**2 for {} and {}: {}".format(LABELS[x], LABELS[y], r_squared(scores[x], scores[y])))
        plot_regression(scores[x], LABELS[x], scores[y], LABELS[y])

if __name__=="__main__":
    main()

rawDescription: Keep getting this error, local variable not referenced before assignment (python)


code:
testdata1()
test_that_uses_testdata1()
testdata1_finalizer()
test_data2()
test_that_uses_testdata2()
test_something_else()
testdata2_finalizer()
testdata1()
test_something_else_that_uses_testdata1()
testdata1_finalizer()

rawDescription: Mutually exclusive fixtures?

description: Mutually exclusive fixtures


code: chart.set_x_axis({'num_font':  {'rotation': 45}})

rawDescription: Python XlsxWriter chart : x-axis value labels angle orientation


code:
def arbitrary_tensor(dtype, shape, name=None):
    # create the type.
    var_type = theano.tensor.TensorType(
        dtype=dtype,
        broadcastable=[False]*len(shape))

    # create the variable from the type.
    return var_type(name)

rawDescription: How do I create an arbitrary theano tensor given a dtype and a shape?

description: Create an arbitrary theano tensor given a dtype and a shape


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

rawDescription: How to speed up json decode and encode operations in Python?

description: Speed up json decode and encode operations in Python


code:
with open('filepath','r') as f:
    header = np.fromfile(f, dtype=np.int, count=number_of_integers)
    data = np.fromfile(f, dtype=np.float32)

rawDescription: Python: Reading Fortran Binary file using numpy or scipy


code:
import numpy as np
import matplotlib.pyplot as plt
from sqlalchemy import create_engine
import _mssql

fig = plt.figure()
ax = fig.add_subplot(111)

engine = create_engine('mssql+pymssql://**:****@127.0.0.1:1433/AffectV_Test')
connection = engine.connect()
result = connection.execute('SELECT Campaign_id, SUM(Count) AS Total_Count FROM Impressions GROUP BY Campaign_id')

## the data

data = []
xTickMarks = []

for row in result:
   data.append(int(row[1]))
   xTickMarks.append(str(row[0]))

connection.close()

## necessary variables
ind = np.arange(len(data))                # the x locations for the groups
width = 0.35                      # the width of the bars

## the bars
rects1 = ax.bar(ind, data, width,
                color='black',
                error_kw=dict(elinewidth=2,ecolor='red'))

# axes and labels
ax.set_xlim(-width,len(ind)+width)
ax.set_ylim(0,45)

ax.set_ylabel('Y LABEL')
ax.set_xlabel('X LABEL')
ax.set_title('TITLE_HERE')

ax.set_xticks(ind+width)
xtickNames = ax.set_xticklabels(xTickMarks)
plt.setp(xtickNames, rotation=45, fontsize=10)

plt.show()

rawDescription: Matplotlib: Plot the result of an SQL query


code:
"foo" in ("foo", "bar", "baz")
"foo" in ("bar", "baz")

rawDescription: What does "return a in b" mean?

description: What does "return a in b" mean


code:
import json
import urllib2

data = {
        'ids': [12, 3, 4, 5, 6]
}

req = urllib2.Request('http://example.com/api/posts/create')
req.add_header('Content-Type', 'application/json')

response = urllib2.urlopen(req, json.dumps(data))

rawDescription: How do I send a POST request as a JSON?

description: Send a POST request as a JSON


code:
IMAGE_MAX_SIZE = 800, 800
class Picture(models.Model):
    ...
    image = models.ImageField(upload_to='images/%Y/%m/%d/')

    # img is a InMemoryUploadedFile, received from a post upload
    def set_image(self, img):
        self.image = img
        self.__scale_image(self.image, IMAGE_MAX_SIZE)

    def __scale_image(self, image, size):
        image.file.seek(0) # just in case
        img = Image.open(StringIO(image.file.read()))
        img.thumbnail(size, Image.ANTIALIAS)
        imageString = StringIO()
        img.save(imageString, img.format)

        # for some reason content_type is e.g. 'images/jpeg' instead of 'image/jpeg'
        c_type = image.file.content_type.replace('images', 'image')
        imf = InMemoryUploadedFile(imageString, None, image.name, c_type, imageString.len, None)
        imf.seek(0)
        image.save(
                image.name,
                imf,
                save=False
            )

rawDescription: Scale Django ImageField before saving to disk


code:
x = [1, 2, 3, 4, 1]
y = [ i for i in xrange(len(x)) if x[i] == 1 ]
y
len(y)

rawDescription: Python: How to check the occurrences of a number in a list and the list positions it occurs in


rawDescription: django form + weird behavior with arrays

description: Django form + weird behavior with arrays


code:
from django.db.models import Count
Checkins.objects.filter(user=my_user).annotate(chkn_count=Count('location')).order_by('-chkn_count')

rawDescription: Django query foreign object that occurs more than once


code:
def get(self):
    #See if logged in
    self.Session = Session()
    if not 'userkey' in self.Session:
        doRender(
            self,
            'base/index.html',
            {'error' : 'Please login to vote'})
        return

    #Get current vote total
    key = self.request.get('url_id')
    vurl = models.URL.get_by_id(int(key))
    vurl.votes += 1 #pull current site vote total & add 1
    vurl.put();

    logging.info('Adding a vote')

    #Create a new Vote object
    newvote = models.Vote(user=self.Session['userkey'], url=vurl)
    newvote.put();

    self.redirect('/', { })

rawDescription: Transaction on GAE entity property

description: Transaction on GAE entity property


code:
def this(self, value):
    if value == "Other":
        self.otherEntry.config(state=NORMAL)
        self.otherEntry.delete(0, "end")
    ...

rawDescription: How to delete Entry text when disabling and re-enabling widget

description: Delete Entry text when disabling and re-enabling widget


rawDescription: Finding row in Numpy array maximizing some function


code:
import collections
MyModel.objects.extra(
    select=collections.SortedDict([(
        'types',
        'CASE WHEN type = %d THEN 0 ',
        'WHEN type = %d THEN 1',
        'WHEN type = %s THEN 2',
        'END' % (
            MyModel.TYPE_ANOTHER,
            MyModel.TYPE_SOMETHING,
            MyModel.TYPE_SOMETHING_ELSE
        ))
    ])
).order_by('types')

rawDescription: Order Django QuerySet in specific order based off model field


code:
"""
blinking LED
"""

import tkinter as tk
import threading
import time

led_switch=False

def start_stop():
    global led_switch
    led_switch=not led_switch
    if led_switch:
        t=threading.Thread(target=LED)
        t.start()

def LED():
    while led_switch:
        print('LED on')
        time.sleep(1)
        print('LED off')
        time.sleep(1)

root=tk.Tk()

button=tk.Button(root,command=lambda: start_stop(),text='start/stop')
button.pack()
tk.mainloop()

rawDescription: Python - How do I continuously repeat a sequence without a While loop and still be able to stop the sequence at any time


code:
t
d = dict(t)
[d.get(el, 0) for el in xrange(1, 12)]

rawDescription: Create a list out of a tuple of tuples

description: Create a list out of a tuple of tuples


rawDescription: How to combine two lists which removing duplicate from the second?

description: Combine two lists which removing duplicate from the second


code:
# Drop missing obs
x = df.aquatic[~ pd.isnull(df.aquatic)]

def get_quartile1(a):
    a = a.sort(inplace=False)
    pos1 = (len(a) + 1) / 4.0
    round_pos1 = int(np.floor((len(a) + 1) / 4.0))
    first_part = a.iloc[round_pos1 - 1]
    extra_prop = pos1 - round_pos1
    interp_part = extra_prop * (a.iloc[round_pos1] - first_part)
    return first_part + interp_part

get_quartile1(x)
Out[84]: 0.17499999999999999

def get_quartile3(a):
    a = a.sort(inplace=False)
    pos3 = (3 * len(a) + 3) / 4.0
    round_pos3 = round((3 * len(a) + 3) / 4)
    first_part = a.iloc[round_pos3 - 1]
    extra_prop = pos3 - round_pos3
    interp_part = extra_prop * (a.iloc[round_pos3] - first_part)
    return first_part + interp_part

get_quartile3(x)
Out[86]: 0.57250000000000001

rawDescription: How to compute Minitab-equivalent quartiles using NumPy

description: Compute Minitab-equivalent quartiles using NumPy


code:
tournaments = self.get_queryset()
for tournament in tournaments:
    tournament.reason_to_not_subscribe = tournament.why_subscription_impossible(self.request)

rawDescription: How to add some context to each entry of a django QuerySet

description: Add some context to each entry of a django QuerySet


code:
import time, threading
def generate_token(username, password):
      # do some stuff to get token
      self._token = "token value"
      threading.Timer(60, generate_token(username, password)).start()

rawDescription: Python, Function in Class that fires off every n seconds


code:
if hasattr(sys, 'frozen'): # this means we're installed using py2exe/pyinstaller
    INSTDIR = os.path.dirname(sys.executable)
else:
    ...

rawDescription: Python 3.0.1 Executable Creator

description: Python 3.0.1 Executable Creator


code:
class Conference(models.Model):
    conference_name = models.CharField(max_length=50)
    url = models.URLField()

    def __unicode__(self):
        return self.conference_name

    class Meta:
        ordering = ['conference_name']

rawDescription: Django admin page dropdowns

description: Django admin page dropdowns


code:
with open("Bus.csv", 'rb') as f_r, open("PJM_LMP.csv", "wb") as f_w:
    reader = csv.reader(f_r)
    writer = csv.writer(f_w)
    writer.writerows(r for r in reader if r[3] in {"PJM_H", "PJM_G"})

rawDescription: python writelines in one cell of csv

description: Python writelines in one cell of csv


code: import pygame

rawDescription: Making image move across screen in python


code:
import psutil, os
p = psutil.Process(os.getpid())
p.ionice(psutil.IOPRIO_CLASS_IDLE)

rawDescription: How to limit I/O consumption of Python processes (possibly using ionice)?

description: Limit I/O consumption of Python processes (possibly using ionice)


code:
#!/usr/bin/env python
import numpy as np
N = 4
a = np.random.random(20).reshape(4, 5)
print(a)

# Convert it into a 1D array
a_1d = a.flatten()

# Find the indices in the 1D array
idx_1d = a_1d.argsort()[-N:]

# convert the idx_1d back into indices arrays for each dimension
x_idx, y_idx = np.unravel_index(idx_1d, a.shape)

# Check that we got the largest values.
for x, y, in zip(x_idx, y_idx):
    print(a[x][y])

rawDescription: how to get the index of the largest n values in a multi-dimensional numpy array

description: Get the index of the largest n values in a multi-dimensional numpy array


code: res = User.query.filter(User.email.in_(('x1@dom1.com', 'x2@dom2.com')))

rawDescription: Flask-SQLAlchemy filters and operators

description: Flask-SQLAlchemy filters and operators


code:
class A():
    def __len__(self):
        return 100

a = A()
len(a)

rawDescription: python object to accept len function to run against it

description: Python object to accept len function to run against it


code:
from numpy import *
import matplotlib.pyplot as plt

fig = plt.figure()

ax = fig.add_subplot(111)
x=random.uniform(0,5,size=5)

#plot
ax.barh(arange(len(x)),x,1)

#set ticks
T=arange(len(x))+0.5
ax.set_yticks(T)

#set labels
labels=['a','b','c','d','e']
ax.set_yticklabels(labels)

plt.show()

rawDescription: yticklabels only at major ticks matplotlib

description: Yticklabels only at major ticks matplotlib


code:
from django.db.models import Count, Case, Sum, When, IntegerField
from django.db.models.expressions import DateTime

queryset = location.objects.annotate(
    datetimes=DateTime('votes__timestamp', 'hour', tz),
    positive_votes=Count(Case(
        When(votes__value__gt=0, then=1),
        default=None,
        output_field=IntegerField())),
    indifferent_votes=Count(Case(
        When(votes__value=0, then=1),
        default=None,
        output_field=IntegerField())),
    negative_votes=Count(Case(
        When(votes__value__lt=0, then=1),
        default=None,
        output_field=IntegerField())),
    score=Sum(Case(
        When(votes__value__lt=0, then=-4),
        When(votes__value=0, then=1),
        When(votes__value__gt=0, then=2),
        output_field=IntegerField())),
    ).values_list('datetimes', 'positive_votes', 'indifferent_votes', 'negative_votes', 'score').distinct().order_by('datetimes')

rawDescription: Django raw sql/postgres time zone confusion


code:
import pylab as py
from numpy.random import rand

x = rand(10)
y = rand(10)
p = py.gca()
p.plot(x,y, '.', label="x:y")

# other code, possibly a new cell in the notebook

a = rand(10)
b = rand(10)

p.plot(a,b, '--', label="a:b")

rawDescription: Add layers of data in matplotlib

description: Add layers of data in matplotlib


code:
class StudentResource(ModelResource):
    course = fields.ForeignKey('website.api.course.CourseResource', "course")

class CourseResource(ModelResource):
    student = fields.ForeignKey('website.api.student.StudentResource', "student")

rawDescription: How to deal with circular imports in tastypie

description: Deal with circular imports in tastypie


code:
data = [
    {
        "link": "https://f.com/1"
    },
    {
        "link": "https://f.com/2"
    },
    {
        "link": "https://f.com/3"
    }
]

print([x["link"] for x in data])

rawDescription: Get all values from a JSON object and store in a flat array with Python


code:
from pptx.dml.color import RGBColor

line = pic.line
line.color.rgb = RGBColor(0xFF, 0x00, 0x00)
line.width = Inches(0.1)

rawDescription: Adding a border to picture(plot) in a PPTX generated by python and matplotlib


code:
n2id = dict(zip(graph.vs["name"],[v.index for v in graph.vs]))
name = "J. Smith" # name of the vertices you are interested in
neighbors = graph.neighborhood(n2id[name], order=1)

rawDescription: Adding infos to edges/vertices by name

description: Adding infos to edges/vertices by name


rawDescription: How do I merge columns by two in a table in pandas?

description: Merge columns by two in a table in pandas


code:
from inspect import signature
def decorator(f):
    @functools.wraps(f)
    def wrapper(*args, **kwargs):
            return f(*args, **kwargs)

    wrapper.__signature__ = signature(f)

    return wrapper

rawDescription: How to avoid that decorators break inspection of parameters?

description: Avoid that decorators break inspection of parameters


rawDescription: JSON encoding from python objects?

description: JSON encoding from python objects


code:
i = variable
if i != 'literal':
    whatever

rawDescription: Is there any way of assigning vars inside an if condition in python


code:
import urllib

urllib.urlretrieve('http://example.com/file.ext', '/path/to/dir/filename.ext')

rawDescription: How to download to a specific directory with Python?

description: Download to a specific directory with Python


rawDescription: Splitting strings into lists and splitting again


code:
n = 10
x = np.arange(n)
a = np.random.rand(n)
b = np.random.rand(n)
c = np.random.rand(n)

fig, axs = plt.subplots(2,1,figsize=(10,8))

axs[0].bar(x, a, width=0.3, facecolor='b', edgecolor='b', linewidth=3, alpha=.5)
axs[0].bar(x+0.3, b, width=0.3, facecolor='r', edgecolor='r', linewidth=3, alpha=.5)
axs[0].bar(x+0.6, c, width=0.3, facecolor='g', edgecolor='g', linewidth=3, alpha=.5)

axs[1].bar(x, a, width=1/3, facecolor='b', alpha=.5, linewidth=0)
axs[1].bar(x+1/3, b, width=1/3, facecolor='r', alpha=.5, linewidth=0)
axs[1].bar(x+2/3, c, width=1/3, facecolor='g', alpha=.5, linewidth=0)

rawDescription: Matplotlib Bar Graph Overlapping of Bars


code: giant = max(nx.connected_component_subgraphs(G), key=len)

rawDescription: How do I get the giant component of a NetworkX graph?

description: Get the giant component of a NetworkX graph


code:
from Tkinter import *

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

class MainWindow():

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

    def __init__(self, main):

        # canvas for image
        self.canvas = Canvas(main, width=60, height=60)
        self.canvas.grid(row=0, column=0)

        # images
        self.my_images = []
        self.my_images.append(PhotoImage(file = "ball1.gif"))
        self.my_images.append(PhotoImage(file = "ball2.gif"))
        self.my_images.append(PhotoImage(file = "ball3.gif"))
        self.my_image_number = 0

        # set first image on canvas
        self.image_on_canvas = self.canvas.create_image(0, 0, anchor = NW, image = self.my_images[self.my_image_number])

        # button to change image
        self.button = Button(main, text="Change", command=self.onButton)
        self.button.grid(row=1, column=0)

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

    def onButton(self):

        # next image
        self.my_image_number += 1

        # return to first image
        if self.my_image_number == len(self.my_images):
            self.my_image_number = 0

        # change image
        self.canvas.itemconfig(self.image_on_canvas, image = self.my_images[self.my_image_number])

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

root = Tk()
MainWindow(root)
root.mainloop()

rawDescription: Python Tkinter: Update Image in Canvas

description: Python Tkinter: Update Image in Canvas


code:
import win32gui
import win32ui
hwnd = win32gui.FindWindow(None, windowname)
wDC = win32gui.GetWindowDC(hwnd)
dcObj=win32ui.CreateDCFromHandle(wDC)
cDC=dcObj.CreateCompatibleDC()
dataBitMap = win32ui.CreateBitmap()
dataBitMap.CreateCompatibleBitmap(dcObj, w, h)
cDC.SelectObject(dataBitMap)
cDC.BitBlt((0,0),(w, h) , dcObj, (0,0), win32con.SRCCOPY)
dataBitMap.SaveBitmapFile(cDC, bmpfilenamename)
# Free Resources
dcObj.DeleteDC()
cDC.DeleteDC()
win32gui.ReleaseDC(hwnd, wDC)
win32gui.DeleteObject(dataBitMap.GetHandle())

rawDescription: Fastest way to take a screenshot with python on windows


code:
class MyLog(models.Model):
    LOG_ACTIONS = (
        ('login', 'User logged in'),
        ('delete_object', 'User delete object'),
        ('create_object', 'User create object'),
        ('buy_object', 'User buy object'),
        #   ...     ...     ...
        # Whatever you need here
    )
    user = models.ForeignKey(User)
    action = models.CharField(max_length=20, default='login', choices=LOG_ACTIONS, verbose_name= 'action')
    date = models.DateTimeField(auto_now_add=True, verbose_name='date')

    class Meta:
        ordering = ['-dt']
        verbose_name = 'Action log'
        verbose_name_plural = 'Actions log'

rawDescription: Logging events in django application

description: Logging events in django application


rawDescription: Python Flask Intentional Empty Response

description: Python Flask Intentional Empty Response


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

small_data = np.random.random((2, 10))
large_data = np.random.random((2, 100))

fig, axes = plt.subplots(ncols=2, figsize=(10, 5), sharex=True, sharey=True)

# For consistency's sake, we'll set the bins to be identical
bins = np.linspace(0, 1, 10)

axes[0].hist2d(*small_data, bins=bins, vmin=0, vmax=5)
axes[1].hist2d(*large_data, bins=bins, vmin=0, vmax=5)

plt.show()

rawDescription: Altering height range of matplotlib histogram2d


code:
for element in node:
    if 'parent' in element:
        if 'children' not in node[element['parent']]:
            node[element['parent']]['children'] = []
        node[element['parent']]['children'].append(element)
        del element['parent']

test = node[0]

rawDescription: Python - how to convert parent child into a nested dictionary


code: cherrypy.config.update({ "environment": "embedded" })

rawDescription: Suppressing Cherrypy's output when running unit tests using Nose


code:
date_str = '2014-06-18 13:06:00.349565827'

# split off the seconds & microseconds
beginning, sec = date_str.rsplit(':', 1)

# Use string formatting to recreate a rounded timestamp
date = dateutil.parser.parse('{}:{:02.6f}'.format(beginning, float(sec)))

rawDescription: Getting Python to round Timestamp with NS versus Truncate


code:
red_fish = set(n for u,v,d in G.edges_iter(data=True)
               if d['color']=='red'
               for n in (u, v)
               if G.node[n]['label']=='fish')

print(red_fish)
# set([2])

rawDescription: Best practices for Querying graphs by edge and node attributes in NetworkX


code: wx.Frame.__init__(self, None, -1, 'CR Part 1', size=(800, 600))

rawDescription: How Do I Make a GUI Open with the Correct Size with wxPython?


rawDescription: Date as Type: type and determining time left


code: self.matplotlibwidget.axes.plot(x, y)

rawDescription: Drawing in a matplotlib widget in QtDesigner


code:
import pandas as pd
from collections import Counter

food_info = pd.read_excel("ABBREV.xlsx")
dfi_1 = food_info

to_be_found = ['BUTTER', 'CHEESE', 'MILK', 'OIL', 'CORN', 'SALT', 'INF', 'PEPPER', 'PASTA', 'GLUTEN-FREE']
found = []
dfi_6 =  dfi_1.Shrt_Desc.str.split(',')
for row in dfi_6.iteritems():
    for x in to_be_found:
        if x in row[1]:
            found.append(x)

print(found)
print(len(found))

c = Counter(found)
print(c)

rawDescription: Pandas: Search and return data frame that includes specific words in a column


code:
def test_chart_renders_from_url(self):
    url = 'http://localhost:8000/analyse/'
    self.browser.get(url)
    org = driver.find_element_by_id('org')
    # Find the value of org?
    val = org.get_attribute("attribute name")

rawDescription: How to get attribute of element from Selenium?

description: Get attribute of element from Selenium


code: map(lambda x: datetime.fromtimestamp(x).weekday(), timestamp)

rawDescription: making a calculation on a timestamp array

description: Making a calculation on a timestamp array


code:
from subprocess import Popen, PIPE, STDOUT

#do some stuff
data = do_some_computation_from_file

#prepare your executable using subprocess.Popen
exe = Popen(['your_executable'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)

#pass in the computed data to the executable and grap the result
result = exe.communicate(input=data)[0]

rawDescription: Python send data to an executable passed as parameter in terminal


rawDescription: How to sort by two different dataFrame columns?

description: Sort by two different dataFrame columns


code:
import win32com.client
from win32com.client import Dispatch

session = Dispatch('MAPI.session')
session.Logon ('Outlook') # this is profile name
inbox = session.Inbox
messages = session.Inbox.Messages
message = inbox.Messages.GetFirst()

if(message):
    attachments = message.Attachments
    for i in range(attachments.Count):
        attachment = attachments.Item(i + 1) # yep, indexes are 1 based

        filename = "c:\\tmpfile" + str(i)
        attachment.WriteToFile(FileName=filename)
session.Logoff()

rawDescription: Extracting Embedded Images From Outlook Email


code:
import numpy as np
import matplotlib.pyplot as plt
import scipy.special as sc

def bWave2(t, fc=10000, B=1.25):
    """ Useing only numpy """
    Vc, fm = 6, 3
    y = np.zeros(len(t))
    for n in range(-5,5):
        y += Vc*sc.jv(n,B)*np.cos(2*np.pi*(fc+n*fm)*t)
    return y

fg, ax = plt.subplots(1, 1)

fc=10000
for q in range(0, 5):
    k = 15001*(1+q)
    t = np.linspace(0-0.25*q, 0.5+0.25*q, k)
    y = bWave2(t, fc)

    Y = np.fft.rfft(y)/N # since y is real, rfft() instead of fft is used
    f = np.fft.rfftfreq(k, t[1] - t[0]) # frequencies for rfft()

    ax.plot(f, np.abs(Y), label=u"$\\tau=${}".format(t[-1]-t[0]), alpha=.5)
ax.set_xlim(fc-50, fc+50)
ax.grid(True)
ax.legend(loc="best")
fg.canvas.draw()

plt.show()

rawDescription: Improving FFT resolution - scaling Y axis


code:
with open(firstFile) as f1, open(secondFile) as f2,\
                                             open(writeTo, 'w') as text_file:
    for line1, line2 in zip(f1, f2):
         text_file.write(line1 + line2)

rawDescription: How to mix up lines from two text files?

description: Mix up lines from two text files


code:
class DataModel(QtCore.QAbstractItemModel):
    def __init__(self, settingsDirectory, parent = None):
        super(DataModel, self).__init__(parent)
        settingsDirectory.setNameFilters(["*.xml"])
        files = settingsDirectory.entryList()
        print(files)

        self.data = {}
        self.parsingLog = {}

        for i in range(len(files)):
            filePath = str(files[i])
            file = QtCore.QFile(settingsDirectory.absolutePath() + "/" + str(filePath))
            fileOpens = file.open(file.ReadOnly | file.Text)
            if fileOpens:
                parser = QtCore.QXmlStreamReader(file)

                currData = []
                haveStartToken = False

                print(self.tr("--------Beginning parsing--------"))
                print(self.tr("Reading file: "+str(filePath)))
                print(self.tr("---------------------------------"))

                while not parser.atEnd():
                    if not parser.hasError():
                        parser.readNext()
                        token = parser.tokenType()

                        print(self.tr("--------------------"))
                        print(self.tr("Token type: " + str(self.printTokenType(token))))

                        if token == parser.StartElement:
                            tokenName = parser.name()
                            attributes = parser.attributes()
                            parseAs = attributes.value("parseAs")

                            print(self.tr("Reading StartElement: " + str(tokenName)))
                            print(self.tr("parseAs: " + str(parseAs)))

                            if parseAs == "text":
                                textValue = self.parseText(parser.readElementText())
                                print(self.tr("Text Value: " + str(textValue)))

                                if len(currData) != 0:
                                    currData[len(currData)-1][1][tokenName] = textValue
                                else:
                                    print(self.tr("*******Terminating application*******"))
                                    print(self.tr("Reason: currData is empty"))
                                    print(self.tr("*******Terminating application*******"))
                                    sys.exit()
                            elif parseAs == "element":
                                currData.append((tokenName, {}))
                            else:
                                print(self.tr("******WARNING******"))
                                print(self.tr("parseAs attribute is not given correctly"))
                                print(self.tr("******WARNING******"))

                            print(self.tr("--------------------"))

                        elif token == parser.EndElement:
                            tokenName = parser.name()

                            print(self.tr("Reading EndElement: " + str(tokenName)))
                            print(self.tr("currData before: " + str(currData)))

                            if not haveStartToken:
                                startToken = currData[0][0]
                                haveStartToken = True

                            for i in currData:
                                if i[0] == tokenName:
                                    print(self.tr("Closing token: " + str(tokenName)))
                                    if i[0] != startToken:
                                        currData[len(currData)-2][1][tokenName] = currData[len(currData)-1][1]
                                        del currData[len(currData)-1]
                                        print(self.tr("currData after: " + str(currData)))
                                        print(self.tr("--------------------"))
                                    elif i[0] == startToken:
                                        print(self.tr("This is the final token, writing to self.data"), end = "")
                                        self.data[startToken] = currData[0][1]
                                        for i in range(5):
                                            time.sleep(0.25)
                                            print(self.tr("."), end = "")
                                        print(self.tr("done."))
                                        print(self.tr("--------------------"))

                        elif token == parser.Characters:
                            print(self.tr("Characters value: " + str(parser.text())))
                            print(self.tr("--------------------"))

                        elif token == parser.StartDocument:
                            self.parsingLog["File: "+str(filePath)] = {}
                            self.parsingLog["File: "+str(filePath)]["XML Version"] = str(parser.documentVersion())
                            self.parsingLog["File: "+str(filePath)]["XML Encoding"] = str(parser.documentEncoding())
                            print(self.tr("File Version: " + str(self.parsingLog["File: "+str(filePath)]["XML Version"])))
                            print(self.tr("File Encoding: " + str(self.parsingLog["File: "+str(filePath)]["XML Encoding"])))

                        elif token == parser.EndDocument:
                            print(self.tr("Cleaning up"), end = "")
                            for i in range(5):
                                time.sleep(0.25)
                                print(self.tr("."), end = "")
                            time.sleep(0.1)
                            print(self.tr("done."))
                            print(self.tr("self.data: " + str(self.data)))
                            print(self.tr("types of data: yesNo (should be str) - " +
                                          str(type(self.data["building"]["specialSlot"]["yesNo"])) +
                                          " - id - should be int - " + str(type(self.data["building"]["specialSlot"]["id"])) +
                                          " - isItFloat - should be float - " + str(type(self.data["building"]["specialSlot"]["isItFloat"]))))
                            print(self.tr("--------------------"))

                    else:
                        print(self.tr("XML file is not well-formatted"))

            else:
                print(self.tr("xml file did not open properly"))

    def parseText(self, text):
        if isinstance(text, str):
            if text == "":
                return str(text)
            for i in text:
                if i not in ("0123456789."):
                    return str(text)
            for j in text:
                if j not in ("0123456789"):
                    return float(text)
            return int(text)
        else:
            return ValueError

    def printTokenType(self, token):
        if token == QtCore.QXmlStreamReader.NoToken:
            return "NoToken"
        elif token == 1:
            return "Invalid"
        elif token == QtCore.QXmlStreamReader.StartDocument:
            return "StartDocument"
        elif token == QtCore.QXmlStreamReader.EndDocument:
            return "EndDocument"
        elif token == QtCore.QXmlStreamReader.StartElement:
            return "StartElement"
        elif token == QtCore.QXmlStreamReader.EndElement:
            return "EndElement"
        elif token == QtCore.QXmlStreamReader.Characters:
            return "Characters"
        elif token == QtCore.QXmlStreamReader.Comment:
            return "Comment"
        elif token == QtCore.QXmlStreamReader.DTD:
            return "DTD"
        elif token == QtCore.QXmlStreamReader.EntityReference:
            return "EntityReference"
        elif token == QtCore.QXmlStreamReader.ProcessingInstruction:
            return "ProcessingInstruction"

rawDescription: The reading loop of QXmlReader for PyQt5 does not return the expected data


code:
def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done

rawDescription: Sending messages between class threads Python


code:
class Blog(Base):

    comments = association_proxy('posts', 'comments')

rawDescription: SQL Alchemy: Relationship with grandson

description: SQL Alchemy: Relationship with grandson


code:
# the path of your files
path = 'C:\\Users\\Office\\Desktop\\TEST\\LOAD'
# the place you want to output your files
# set to input because i have no idea where you want them
dest_path = path
# the type of files you want to rename
ext = r'xls'

# file will contain the path of the file
for file in glob.glob('{path}\\*.{ext}'.format(path=path, ext=ext)):
    # the filename we are going to change (dont want the path at all)
    name = file.split('\\')[-1]

    # the new name of the file
    new_file = '{path}\\{name}.{ext}'.format(
        path=dest_path,
        name=name.split('.')[3],
        ext=ext
    )

    os.rename(file, new_file)

rawDescription: Python Rename Filename With Substring Best Practices


code:
from selenium import webdriver

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("prefs", {"profile.default_content_settings.cookies": 2})

driver = webdriver.Chrome(chrome_options=chrome_options)

rawDescription: Disabling Cookies in Webdriver for Chrome/Firefox


code: len(a) == len(b) and all(j > i for i, j in zip(a, b))

rawDescription: Python comparing two lists

description: Python comparing two lists


code:
import struct
struct.unpack('d', b'\xab>W[\xb1\xbf\xe0?')

rawDescription: Decoding Simulink's UDP Packets in Python


code:
x = np.random.randn(200, 10)
y = np.random.randn(1e5, 10)
scale = np.abs(np.random.randn(1, 10))
scale_sqrt = np.sqrt(scale)

dist_map = dist.cdist(x*scale_sqrt, y*scale_sqrt, 'sqeuclidean')

rawDescription: Efficient weighted vector distance calculation with numpy


code:
ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)

rawDescription: Perform commands over ssh with Python

description: Perform commands over ssh with Python


code:
import urllib
from urllib.request import urlopen

address = "http://www.hobo-web.co.uk/headers/"
webPage = urllib.request.urlopen(address)

print (webPage.read())

rawDescription: Extracting HTML information from a URL

description: Extracting HTML information from a URL


code:
d = {'name':{0:'tom',1:'dav'}, 'age':{0:22,1:23}}
values = zip(*[value.values() for value in d.values()])
l = [{'name': name, 'age': age} for name, age in values]
l

rawDescription: Convert nested dicts to list in python?

description: Convert nested dicts to list in python


code:
class Test:
    def __init__(self, i):
        self.i = i
    def __int__(self):
        return self.i * 2

t = Test(5)
print( int(t) )
# 10

rawDescription: Overload int() in Python

description: Overload int() in Python


code:
with open("ted.csv") as f1, open("ted2.csv") as f2, open('foo.csv', 'w') as out:
    f1.readline()
    f2.readline()
    r1, r2 = csv.reader(f1), csv.reader(f2)

rawDescription: python csv reader ignore blank row

description: Python csv reader ignore blank row


code:
import clr
clr.AddReference('System.Data')
from System.Data import SqlClient
from System.Data import *
from System.Data import DataTable

import clr
clr.AddReference('System')
from System import *
from System import Console
from System import Data

sqlConnectionString = "<sql-connection-string>"
sqlDbConnection = SqlClient.SqlConnection(sqlConnectionString)
sqlDbConnection.Open()

workTable = DataTable()
workTable.Columns.Add("Col1", Byte)
workTable.Columns.Add("Col2",Byte)
workTable.Columns.Add("Col3", Int32)
workTable.Columns.Add("Col4", Byte)
workTable.Columns.Add("Col5", Byte)
workTable.Columns.Add("Col6", Single)

sampleArray = [Byte(7), Byte(8), Int32(1), Byte(15), Byte(12), Single(0.34324)]
for i in range (0, 189000) :
  workTable.Rows.Add(Array[object](sampleArray))

cmd = SqlClient.SqlCommand("truncate table dbo.MyTable", sqlDbConnection);
def bulkLoadEsgData ():
    sbc = SqlClient.SqlBulkCopy(sqlConnectionString, SqlClient.SqlBulkCopyOptions.TableLock, BulkCopyTimeout=0, DestinationTableName="dbo.MyTable")
    sbc.WriteToServer(workTable)

# Start simulation
Console.WriteLine("Enter number of simulations (1 simulation = 189,000 data rows):"+"\n")
strN = Console.ReadLine()

n = int(strN)
cmd.ExecuteNonQuery()
for i in range (0, n):
    bulkLoadEsgData()

sqlDbConnection.Close()
Environment.Exit(1111)

rawDescription: Python and SQL Bulk Insert

description: Python and SQL Bulk Insert


code:
def getperm(index,generator):
    aux=0
    for j in generator:
        if aux == index:
            return j
        else:
            aux = aux +1

In:  getperm(15,permute(['A', 'B', 'C', 'D']))
Out: ['C', 'A', 'D', 'B']

rawDescription: Indexing a list of permutations in Python


code:
class GtkTextViewHandler(logging.Handler):
  def __init__(self, tv):
    logging.Handler.__init__(self)
    self.tv = tv
    self.tbf = tv.get_buffer()
    self.formatter = None

  def emit(self, record):
    try:
      msg = self.format(record)
      fs  = "%s\n"
      self.tbf.insert(self.tbf.get_end_iter(), fs % msg)
      self.tv.scroll_to_iter(self.tv.get_end_iter(), 0.0, False, 0, 0)
    except:
      self.handleError(record)

rawDescription: How do I inherit from logging.Handler to log to a GtkTextView?

description: Inherit from logging.Handler to log to a GtkTextView


code:
from fabric.api import *

credentials = load_credentials_from_your_db()
for (hostname, username, password) in credentials:
    host_string = username + '@' + hostname
    env.hosts.append(host_string)
    env.passwords[host_string] = password

rawDescription: Python Fabric + multiple host configuration in database


code:
class VerticalScrolledFrame(Frame):
    """A pure Tkinter vertically scrollable frame.

    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling
    """
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set, width=240)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior, anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)

        return

rawDescription: Scrollbar is visible and slidable, but does not function as a scrollbar


code:
#!/usr/bin/env python

import math
import tornado.httpserver
import tornado.escape
import tornado.ioloop
import tornado.web

class DistanceService(tornado.web.RequestHandler):
    def get(self):
        x1 = float(self.get_argument('x1'))
        y1 = float(self.get_argument('y1'))
        x2 = float(self.get_argument('x2'))
        y2 = float(self.get_argument('y2'))
        dx = x1 - x2
        dy = y1 - y2
        magnitude = math.sqrt(dx * dx + dy * dy)
        self.write("the distance between the points is %3.2f" % magnitude)

class WService(tornado.web.RequestHandler):
    def get(self):
        self.write("value of request.uri: %s" % self.request.uri)
        self.write("
")
        self.write("value of request.path: %s" % self.request.path)
        self.write("
")
        self.write("value of request.query: %s" % self.request.query)

application = tornado.web.Application([
    (r"/distance", DistanceService),
    (r"/", WService),
])

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(9000)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Tornado Not Interpreting URL

description: Tornado Not Interpreting URL


rawDescription: Calculate the size of a list

description: Calculate the size of a list


code: cv2.warpPerspective(src_img, H_from_src_to_dst, dst_size, dst_img)

rawDescription: interpolation of transformPerspective openCV

description: Interpolation of transformPerspective openCV


code:
class YourUploadHandler(webapp.RequestHandler):
    def post(self):
        your_binary_content = self.request.body

rawDescription: How to handle direct file upload with GAE/python?

description: Handle direct file upload with GAE/python


rawDescription: Index Slicing with Float64Index not working in pandas


code: pd.crosstab(df.index, df['Crime type'])

rawDescription: Group and count unique values in Python pandas dataframe


code:
my_list[7:10], my_list[2:4] = my_list[2:4], my_list[7:10]
my_list

rawDescription: Swapping two sublists in a list

description: Swapping two sublists in a list


code:
h5file_path="/absolute/path/to/file"

def readchunk(v):
    empty = h5.File(h5file_path)
    return empty['/mydata'][v,:]

foo = sc.parallelize(range(0,100)).map(lambda v: readchunk(v))
foo.count()

rawDescription: Loading bigger than memory hdf5 file in pyspark


code:
import mock
class Foo(object):
  bar = 1000000

with mock.patch.object(Foo, 'bar', 10):
  print(Foo.bar)

print(Foo.bar)

rawDescription: Nose - Is it possible to stub a class constant?


code:
from ghost import Ghost
ghost = Ghost()
page, resources = ghost.open('http://my.web.page')

rawDescription: How can I extract the list of urls obtained during a HTML page render in python?

description: Extract the list of urls obtained during a HTML page render in python


code:
result = es.get('/_search', data={
    "query": {
        "filtered": {
            "query" : { "match_all" : {}},
            "filter": {
                "range": {
                   "@timestamp": {
                      "from": datetime(2013, 3, 11, 8, 0, 30,   tzinfo=paristimezone),
                       "to": datetime(2013, 3, 12, 11, 0, 30, tzinfo=paristimezone)
                    }
                }
            }
        }
    },
   "facets" : {
       "error" : {
        "terms" : {
            "field" : "status_code"
        },
         "facet_filter" : {
            "term" : {"server" : "testserver01"}
           }
        }
    }
})

rawDescription: ElasticSearch requests range timestamp in python


code:
import math
import pylab

pylab.plot(range(11), range(11))

opt = {'head_width': 0.4, 'head_length': 0.4, 'width': 0.2,
        'length_includes_head': True}
for i in xrange(1, 360, 20):
    x = math.radians(i)*math.cos(math.radians(i))
    y = math.radians(i)*math.sin(math.radians(i))

    # Here is your method.
    arr = pylab.Arrow(4, 6, x, y, fc='r', alpha=0.3)
    pylab.gca().add_patch(arr)

    # Here is the proposed method.
    pylab.arrow(4, 6, x, y, alpha=0.8, **opt)

pylab.show()

rawDescription: Equal-sized arrowheads in matplotlib

description: Equal-sized arrowheads in matplotlib