code:
from collections import Counter
from sklearn.feature_extraction import DictVectorizer
vect = DictVectorizer()
samples = [":) :) :)", "I have to push the pram a lot"]
X = vect.fit_transform(Counter(s.split()) for s in samples)
X
vect.vocabulary_
vect.inverse_transform(X[0])  # just for inspection

rawDescription: Incorporating emoticons into a scikit model


code:
class dev_person(Model):
    _name = "dev.person"
    _description = "Person"
    _columns = {
        'name': fields.char('Person', size=128, required=True),
        'properties': fields.many2one('dev.property', 'property_id', select=True),
       }

    _sql_constraints = [
        (
            'dev_person_name_uniq',
            'unique(name)',
            "You can't have two people with the same name!",
        ),
    ]

rawDescription: odoo one2many acts like many2many

description: Odoo one2many acts like many2many


code:
import Tkinter as tk

root = tk.Tk()
root.geometry("500x500")
root.title("Drawing lines to a canvas")

cv = tk.Canvas(root,height="500",width="500",bg="white")
cv.pack()

def linemaker(screen_points):
    """ Function to take list of points and make them into lines
    """
    is_first = True
    # Set up some variables to hold x,y coods
    x0 = y0 = 0
    # Grab each pair of points from the input list
    for (x,y) in screen_points:
        # If its the first point in a set, set x0,y0 to the values
        if is_first:
            x0 = x
            y0 = y
            is_first = False
        else:
            # If its not the fist point yeild previous pair and current pair
            yield x0,y0,x,y
            # Set current x,y to start coords of next line
            x0,y0 = x,y

list_of_screen_coods = [(50,250),(150,100),(250,250),(350,100)]

for (x0,y0,x1,y1) in linemaker(list_of_screen_coods):
    cv.create_line(x0,y0,x1,y1, width=1,fill="red")

root.mainloop()

rawDescription: Create a line using a list of coordinates in python GUI


code:
master = Tk()

leftValue = IntVar()  # IntVars to hold
rightValue = IntVar() # values of scales

leftScale = Scale(master, from_=0, to=249, variable=leftValue, showvalue=0)
leftScale.set(152)

rightScale = Scale(master, from_=0, to=249, variable=rightValue, showvalue=0)
rightScale.set(152)

leftLabel = Label(master, textvariable=leftValue)   # labels that will update
rightLabel = Label(master, textvariable=rightValue) # with IntVars as slider moves

leftLabel.grid(row=0, column=0)
leftScale.grid(row=0, column=1)
rightLabel.grid(row=0, column=3)
rightScale.grid(row=0, column=2)

mainloop()

rawDescription: How to I set which side the numbers go on in a scale using tkinter on python?


code:
application = Applications.query.filter_by(brochureID=brochure.id)
entries = application.all()

rawDescription: SQLAlchemy get every row the matches query and loop through them


code: driver.execute_script("date1 = '13-11-2015T17:25'; date2 = '25-11-2015T11:01'; return window.PF.start_diff(date1, date2);")

rawDescription: Selenium Python execute script in the Firefox console


code:
year, month, day = cal.get_date()
return '{0:04d}-{1:02d}-{2:02d}'.format(year, month+1, day)

rawDescription: Python `YYYY-MM-DD`

description: Python `YYYY-MM-DD`


code:
import os, fcntl
fcntl.fcntl(thePipe, fcntl.F_SETFL, os.O_NONBLOCK)

rawDescription: How to read from an os.pipe() without getting blocked?

description: Read from an os.pipe() without getting blocked


rawDescription: Python: Change the time on xticks for Pandas Plot


code:
def random_char():
       return random.sample(b,26)
a = random_char() # now a list of separate elements
print(a)
['S', 'I', 'P', 'O', 'L', 'Y', 'J', 'T', 'C', 'F', 'Z', 'A', 'B', 'M', 'V', 'D', 'K', 'H', 'X', 'N', 'Q', 'U', 'G', 'W', 'E', 'R']

print(a[0])
S

rawDescription: Generate a list of characters

description: Generate a list of characters


code:
class MainApp:
    def __init__(self):
        self.UI = BaseApp(self)

rawDescription: Python - Access a function in a child class


code: plt.ylabel('Intensity $(10^{' + str(int(orderMagnitude)) + '})$')

rawDescription: matplotlib tex label adds/removes whitespace

description: Matplotlib tex label adds/removes whitespace


code:
pipe = {"$group": {"_id": {"a": "$a", "b": "$b", "c": "$c"}}}
A.objects.aggregate(pipeline=pipe)

rawDescription: Exclude documents from query with duplicate fields value


code:
import gtk, glib
import webkit
import threading
import time

# Use threads
gtk.gdk.threads_init()

class App(object):
    def __init__(self):
        window = gtk.Window()
        webView = webkit.WebView()
        window.add(webView)
        window.show_all()

        self.window = window
        self.webView = webView

    def run(self):
        gtk.main()

    def show_html(self):
        # Get your html string
        time.sleep(3)
        html_str = '
Hello Mars
'

        # Update widget in main thread
        glib.idle_add(self.webView.load_html_string,
                      html_str, 'file:///')

app = App()

thread = threading.Thread(target=app.show_html)
thread.start()

app.run()
gtk.main()

rawDescription: PyGTK, Threads and WebKit

description: PyGTK, Threads and WebKit


rawDescription: How can I quickly set a field of all instances of a Django model at once?

description: Quickly set a field of all instances of a Django model at once


code:
def cmp(a, b):
    return (a["qty"] / (a["cost"] * a["ppl"])) - (b["qty"] / (b["cost"] * b["ppl"]))

list = sorted(list, cmp)

rawDescription: Finding the best "deal" in a "group buy", given a table of values


code:
#!/usr/bin/env python
#@author: Prahlad Yeri
#@description: Small daemon to create a wifi hotspot on linux
#@license: MIT
import cli

#INSTALL IT
from distutils.core import setup
setup(name='hotspotd',
    version='0.1',
    description='Small daemon to create a wifi hotspot on linux',
    license='MIT',
    author='Prahlad Yeri',
    author_email='prahladyeri@yahoo.com',
    url='https://github.com/prahladyeri/hotspotd',
    package_dir={'hotspotd': ''},
    packages=['hotspotd'],
    data_files=[('config',['run.dat'])],
    scripts=["scriptname"], # Here the Magic Happens
    )

#CONFIGURE IT

rawDescription: setup.py - Symlink a module to /usr/bin after installation

description: Setup.py - Symlink a module to /usr/bin after installation


rawDescription: Anyone know where I can download a zipped Python distribution?


code:
import datetime

import tkinter

from tkinter import *

import matplotlib.finance as finance

root = Tk()

# create a StrringVar
ticker_entry_var = StringVar()

E1 = Entry(root, bd=8, textvariable=ticker_entry_var)

E1.pack(fill=Y)

root.mainloop()

startdate = datetime.date(2013,1,1)
today = enddate = datetime.date.today()

# get value from the entry box
ticker = ticker_entry_var.get()
print(ticker)

rawDescription: I am working with Tk inter and yahoo_finance


code:
class BaseAttrEnforcer(type):
    def __init__(cls, name, bases, d):
        if 'loglevel' not in d:
            raise ValueError("Class %s doesn't define loglevel attribute" % name)
        type.__init__(cls, name, bases, d)

class Base(object):
    __metaclass__ = BaseAttrEnforcer
    loglevel = None

class d1(Base):
    logfile = "d1.log"
    loglevel = "debug"

class d2(Base):
    logfile = "d2.log"
    loglevel = "info"

class d3(Base):
    logfile = "d3.log"
    # I should fail

rawDescription: different values for class variables in each subclass in python

description: Different values for class variables in each subclass in python


code:
with open(config_path, mode = 'r') as file_in:
    with open(config_path.replace('.txt', '.py'), mode = 'w') as file_out:
        for line in file_in:
            file_out.write(line)
return importlib.import_module(config_path.replace('.txt',''))

rawDescription: Configurations from file for python dictionaries and strings


rawDescription: how to split a string with a " " delimiter?

description: Split a string with a " " delimiter


code:
def coordinates1(d):
    return [tuple(map(float,coords.split(','))) for coords in d.split()[1:-1]]

rawDescription: Converting a string to a list of 2-tuples


code:
import time
import json
import urllib
import urllib.request

url = 'https://btc-e.com/api/3/ticker/btc_usd?ignore_invalid=1'

def main(btce_url = url):
    req = urllib.request.urlopen(btce_url)
    result = json.loads(req.readall().decode('utf-8'))
    print(result['btc_usd']['low']) # for example ..

if __name__ == "__main__":
    main()

rawDescription: JSON Httpresponse in python 3.4

description: JSON Httpresponse in python 3.4


code:
from maya.api.OpenMaya import MVector, MMatrix
import maya.cmds as cmds

normal_vector = MVector(*cmds.getAttr('pointOnCurveInfo1.result.normal')).normal()
tangent_vector = MVector(*cmds.getAttr('pointOnCurveInfo1.result.tangent')).normal()
cross_vector = normal_vector ^ tangent_vector
position = MVector(*cmds.getAttr('pointOnCurveInfo1.result.position'))
matrix = (
 tangent_vector[0], tangent_vector[1], tangent_vector[2], 0,
     normal_vector [0], normal_vector [1], normal_vector[2],  0,
     cross_vector[0],   cross_vector[1],   cross_vector[2],   0,
     position[0],       position[1],       position[2],       1
)

 # if you want it in api form so you can do multiplies, etc:
api_matrix = MMatrix(matrix)

api_matrix

rawDescription: Maya python get correct matrix decomposition from point on curve


code:
def is_square(x):
    s = int(sqrt(x) + 0.5)
    return s * s == x

rawDescription: How to check if number is integer number, with good precision?

description: Check if number is integer number, with good precision


code:
from urllib.parse import parse_qs, urlparse

strr = "https://stackexchange.com/oauth/login_success/#access_token=xxxxxx))&expires=86400"
o = parse_qs(urlparse(strr).fragment)
print(o['access_token'])

rawDescription: Python: regex to parse URL components

description: Python: regex to parse URL components


code:
import csv
import io

alist, blist = [], []

with open("ngrams.csv", "rb") as fileA:
    reader = csv.reader(fileA, delimiter=',')
    for row in reader:
        alist.append(row)
with open("ngramstest.csv", "rb") as fileB:
    reader = csv.reader(fileB, delimiter=',')
    for row in reader:
        blist.append(row)

f_dict = {e[0]:e[1:] for e in alist}
s_dict = {e[0]:e[1:] for e in blist}

res = {}
for k,v in f_dict.items():
    if k in s_dict:
        res[k] = float(v[1])/float(s_dict[k][1])

print(res)

rawDescription: Comparing the first columns in two csv files using python and printing matches


code:
def Help(string):
    if string == 'Manifest':
        return Manifest()
    elif string == 'Intent':
        return Intent()
    else:
        print('The options available are:\n%s\nType Q to Quit\n' % '\n'.join(andHelp))
        x = input('What option do you choose: ')
        print('\n')
        if x != 'Q':
            Help(x)

rawDescription: Loop keeps going after being carried out


code:
class MyDialog(gtk.Dialog, gtk.Buildable):
    __gtype_name__ = "MyDialog"

    def do_parser_finished(self, builder):
        self.treeview = builder.get_object("treeview1")
        # Do any other associated post-initialization

rawDescription: gtk.Builder, container subclass and binding child widgets

description: Gtk.Builder, container subclass and binding child widgets


code:
import numpy as np
x =  np.array([0, 1, 2, 3, 4, 5])

for i in range(1,len(x) + 1):
    print(x[1:i])

rawDescription: Numpy array manipulation

description: Numpy array manipulation


code:
file1 = open(sys.argv[1],"r")
file2 = open(sys.argv[2],"r")
file3 = open(sys.argv[3],"w")

for line1 in file1:
    if '@' in line1:  # line1.startswith('@') is probably better here
        a=line1.lstrip('@').rstrip('\n')
        b=file1.next().rstrip('\n')
        for line2 in file2:
            if '@' in line2:
                c=file2.next().rstrip('\n')
                break
        file3.write(">%s\n%s:%s\n"%(a,b,c))

file1.close()
file2.close()
file3.close()

rawDescription: Python MemoryError when storing saved lists


code:
from Tkinter import *

class Application(Frame):
    # ...

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

root = Tk()
app = Application(master=root)

rawDescription: Why use a default value of None for this class initialiser?


code:
struct.unpack_from('x', buf)
struct.unpack_from('I', buf)
struct.unpack_from('B', buf)
struct.unpack_from('H', buf)
struct.unpack_from('l', buf)

rawDescription: Porting java code to Python

description: Porting java code to Python


rawDescription: Specify port for url_for

description: Specify port for url_for


code:
def filter(self, *q_objs, **query):
    """An alias of :meth:`~mongoengine.queryset.QuerySet.__call__`
    """
    return self.__call__(*q_objs, **query)

rawDescription: What is the difference of objects and filter in mongoengine?


code:
import threading
t = threading.Thread(target = tornado.ioloop.IOLoop.instance().start)
t.start()

rawDescription: Giving my Python application a web interface to monitor it, using Tornado


code:
class MyNotebook(AuiNotebook):
  def __init__(self, parent, id, *args, **kwds): #@ReservedAssignment
    AuiNotebook.__init__(self, parent, id, *args,
      style = NO_BORDER | AUI_NB_CLOSE_ON_ALL_TABS | AUI_NB_TAB_SPLIT, **kwds)

    self._tabs = ['Jobs', 'Devices', 'Actions', 'Transforms']

    self.Bind(EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnPageClosed)

  def OnPageClosed(self, evt):
    page = self.GetPageText(evt.GetSelection())

rawDescription: wxpython get currently selected notebook tab label (not index)

description: Wxpython get currently selected notebook tab label (not index)


code:
import fnmatch
import os

path = os.path.expanduser('~/documents')
tree = ET.parse("sync_list.xml")
root = tree.getroot()
synced = [elt.text for elt in root.findall('synced/sfile')]
for filename in os.listdir(path):
    if fnmatch.fnmatch(filename, '*.blah') and filename not in synced:
        filename = os.path.join(path, filename)

rawDescription: Looping through a directory of files in Python


code:
import datetime
import time
dt = datetime.datetime.today().replace(hour=13, minute=0, second=0, microsecond=0)
print(dt)
time.mktime(dt.timetuple())

rawDescription: Write a python script to generate a timestamp ( unix epoch value) each day at a give time


code:
root = elem.getroot()
for child in root:
    if child.name != "prop":
        continue
    if True:# TODO: do your check here!
        root.remove(child)

rawDescription: Search and remove element with elementTree in Python


code:
set2 = set(list2)
not_matched = [a for a in list1 if not a.item1 in set2]

rawDescription: Python: most effective way of filtering a list


code:
def update_rank(rank, article):
      old = Article.object.get(rank=rank)
      old.rank = None
      old.save()
      article.rank = rank
      article.save()

rawDescription: How can I order elements in this case? - Django

description: Order elements in this case? - Django


code:
import pandas as pd
import numpy as np

def add_columns(x, *args):
    col_names = args[0]
    return pd.Series({i: x for i in col_names})

def add_range(x, *args):
    col_names = args[1]
    return pd.Series({k: v for k,v in zip(args[1],range(args[0]))})

df = pd.DataFrame(np.random.uniform(size=(10,2)),columns=["A","B"])

labels = ["L1","L2","L3"]

# This populates with values from "A" column
df.merge(df["A"].apply(add_columns, args=([labels])),left_index=True, right_index=True)

# This populates with values from range(number_passed) function
df.merge(df["A"].apply(add_range, args=([3,labels])),left_index=True, right_index=True)

rawDescription: How can I add a variable amount of columns in Pandas?

description: Add a variable amount of columns in Pandas


code:
class E(object):
   def __init__(self, obj):
        self.obj = obj
   def __eq__(self, other):
        return self.obj.value  == getattr(other, "obj", other).value

rawDescription: Python: how to make comparable hashable objects of the same type to be treated by set/dict as the single object?


code:
import email

filename = 'xxx.eml'

with open(filename, 'rb') as f:
    msg = email.message_from_file(f)

    # count number of attachments in an email
    #
    totalattachments = 0
    firsttextattachmentseen = False
    lastseenboundary = ''
    # .walk steps through all the parts of an email including boundaries and attachments
    alternativetextplainfound = False
    alternativetexthtmlfound = False
    for part in msg.walk():
        if part.is_multipart():
            # this is a boundary, so we record what the last seen boundary was and continue to next part
            lastseenboundary = part.get_content_type()
            continue
        if lastseenboundary == 'multipart/alternative':
            #for HTML emails, the multipart/alternative part contains the HTML and its alternative text representation
            #BUT it seems that plenty of messages add file attachments after the txt and html, so we'll have to account for that
            if part.get_content_type() == 'text/plain' and alternativetextplainfound == False:
                alternativetextplainfound = True
                continue
            if part.get_content_type() == 'text/html' and alternativetexthtmlfound == False:
                alternativetexthtmlfound = True
                continue
        if (part.get_content_type() == 'text/plain') and (lastseenboundary != 'multipart/alternative'):
            #if this is a plain text email, then the first txt attachment is the message body so we do not
            #count it as an attachment
            if firsttextattachmentseen == False:
                firsttextattachmentseen = True
                continue
            else:
                totalattachments += 1
                continue
        # any other part we encounter we shall assume is a user added attachment
        totalattachments += 1

    print(totalattachments, ': ', filename)

rawDescription: In Python, how can I count the number of files a sender has attached to an email?


code:
df = DataFrame(dict(A = Timestamp('20130101'), B = np.random.randn(5), C = np.nan))
df
df.dtypes
df['A'] = pd.to_datetime(df['A'])
df['C'] = pd.to_datetime(df['C'])
df
df.dtypes

rawDescription: Converting pandas columns to datetime64 including missing values


code:
df = df.sort_values(by='PublishDate').copy()
df = df.pivot_table(index = 'Date',columns = 'Stock',values = 'Value', aggfunc = 'last')

rawDescription: Pivoting tables with duplicated data in pandas


code:
matrices = []                       # Allocate an empty list
for filename in sys.argv[1:]:       # Skip argv[0], name of script
    mat = np.loadtxt(filename)      # Read a matrix
    matrices.append(mat)            # Append it to the list

rawDescription: How to allocate an unknown number of variables corresponding to input arguments

description: Allocate an unknown number of variables corresponding to input arguments


code:
def insert_advertisement(posts_list, advertisement, step):
    for i, post in enumerate(posts_list):
        if i > 0 and i % step == 0:
            yield advertisement
        yield post
list(insert_advertisement([1, 2, 3, 4, 5, 6, 7], 'ad', 3))

rawDescription: Intersperse list with a step

description: Intersperse list with a step


code: del ret["_%s__%s" % (MyClasss.__name__, "prv")]

rawDescription: python: reference "private" variables' names in an organized way

description: Python: reference "private" variables' names in an organized way


code:
url = urlparse.urlparse(address)
subdomain = url.hostname.split('.')[0]

rawDescription: Get subdomain from URL using Python

description: Get subdomain from URL using Python


code:
xmlstr = "<sec>header
para 0
 text
para 1
 footer</sec>"
element = etree.fromstring(xmlstr)
element.text + "".join(map (etree.tostring, element))

rawDescription: Equivalent of Beautiful Soup's renderContents() method in lxml?


code:
import Tkinter as tk

class App(object):
    def new_row(self):
        # Create widgets
        new_entry = tk.Entry(root, width=7)

        # Put widgets in grid
        self.num_rows += 1
        new_entry.grid(column=0, row=self.num_rows, sticky='WE')

    def __init__(self):
        self.num_rows = 1
        createRow_button = tk.Button(
            root, text='New Row', command=self.new_row)
        createRow_button.grid()

root = tk.Tk()
app = App()
root.mainloop()

rawDescription: In tkinter how do I generate a new row every time a button is pressed?


code:
import win32api, win32con, win32gui

class MyWindow:

    def __init__(self):
        win32gui.InitCommonControls()
        self.hinst = win32api.GetModuleHandle(None)
        className = 'MyWndClass'
        message_map = {
            win32con.WM_DESTROY: self.OnDestroy,
        }
        wc = win32gui.WNDCLASS()
        wc.style = win32con.CS_HREDRAW | win32con.CS_VREDRAW
        wc.lpfnWndProc = message_map
        wc.lpszClassName = className
        win32gui.RegisterClass(wc)
        style = win32con.WS_OVERLAPPEDWINDOW
        self.hwnd = win32gui.CreateWindow(
            className,
            'My win32api app',
            style,
            win32con.CW_USEDEFAULT,
            win32con.CW_USEDEFAULT,
            300,
            300,
            0,
            0,
            self.hinst,
            None
        )
        win32gui.UpdateWindow(self.hwnd)
        win32gui.ShowWindow(self.hwnd, win32con.SW_SHOW)

    def OnDestroy(self, hwnd, message, wparam, lparam):
        win32gui.PostQuitMessage(0)
        return True

w = MyWindow()
win32gui.PumpMessages()

rawDescription: python3 ctype CreateWindowEx simple example

description: Python3 ctype CreateWindowEx simple example


code:
from twisted.protocols.ftp import FTPFactory, FTPRealm
from twisted.cred.portal import Portal
from twisted.cred.checkers import AllowAnonymousAccess, FilePasswordDB
from twisted.internet import reactor

p = Portal(FTPRealm('./'),
           [AllowAnonymousAccess(), FilePasswordDB("pass.dat")])
f = FTPFactory(p)

reactor.listenTCP(21, f)
reactor.run()

rawDescription: Implementing FTP interface/protocol

description: Implementing FTP interface/protocol


code:
dct
np.hstack(dct[k] for k in sorted(dct))

rawDescription: Concetenating arrays in a dictionary

description: Concetenating arrays in a dictionary


code: dfb[['wgs_x', 'wgs_y']] = dfb.apply(lambda row:utm15_wgs84(row['COORDENADA_X'], row['COORDENADA_Y'], inverse=True), axis=1).apply(pd.Series)

rawDescription: Coordinates from UTM to Latitude and Longitude in pandas


code:
### Suggested one runs the above code first.
### Unknowns we are interested in

est_centroid_one = mc.Uniform("est_centroid_one", 5000, 5050 )
est_centroid_two = mc.Uniform("est_centroid_two", 5000, 5050 )

est_sigma_one = mc.Uniform( "est_sigma_one", 0, 5 )
est_sigma_two = mc.Uniform( "est_sigma_two", 0, 5 )

est_height_one = mc.Uniform( "est_height_one", 0, 5 )
est_height_two = mc.Uniform( "est_height_two", 0, 5 )

#std deviation of the noise, converted to precision by tau = 1/sigma**2
precision= 1./mc.Uniform("std", 0, 1)**2

#Set up the model's relationships.

@mc.deterministic( trace = False)
def est_profile_1(x = wavelength, centroid = est_centroid_one, sigma = est_sigma_one, height= est_height_one):
    return GaussFunc( x, height, centroid, sigma )

@mc.deterministic( trace = False)
def est_profile_2(x = wavelength, centroid = est_centroid_two, sigma = est_sigma_two, height= est_height_two):
    return GaussFunc( x, height, centroid, sigma )

@mc.deterministic( trace = False )
def mean( profile_1 = est_profile_1, profile_2 = est_profile_2 ):
    return profile_1 + profile_2

observations = mc.Normal("obs", mean, precision, value = combined, observed = True)

model = mc.Model([est_centroid_one,
              est_centroid_two,
                est_height_one,
                est_height_two,
                est_sigma_one,
                est_sigma_two,
                precision])

#always a good idea to MAP it prior to MCMC, so as to start with good initial values
map_ = mc.MAP( model )
map_.fit()

mcmc = mc.MCMC( model )
mcmc.sample( 50000,40000 ) #try running for longer if not happy with convergence.

rawDescription: Fit two normal distributions (histograms) with MCMC using pymc?


code:
from pymongo import MongoClient

client = MongoClient("mongodb://host1")
db = client.MYDB
collection = db.MYCOLLECTION
index = db.provisioning.index_information()

client2 = MongoClient("mongodb://host2")
db2 = client2.MYDB
collection2 = db2.MYCOLLECTION
for i in index.keys():
    name_index = index[i]['key'][0][0]
    order = index[i]['key'][0][1]
    collection2.create_index([(name_index, order)])

rawDescription: With PyMongo how do I import indexes using create_index() that were exported with index_information()?


code:
varname = 'spam'
value = 'eggs'
locals()
locals()[varname] = value
locals()
print(spam)

rawDescription: variable names based on a parsed string

description: Variable names based on a parsed string


code:
q1 = Employee.query()
q1
q2 = gql('SELECT * FROM Employee')
q2

rawDescription: ndb.gql vs ndb.query - Google App Engine

description: Ndb.gql vs ndb.query - Google App Engine


code:
import csv

cursor = arcpy.InsertCursor(pointFC)
with open('yourcsvfile.csv', 'rb') as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        point = arcpy.CreateObject("Point")
        point.X, point.Y = float(row[5]), float(row[27])  # take the 6th and 28th columns from the row
        cursor.insertRow(point)

rawDescription: Convert .CSV file to point feature class using python 2.7


code:
from operator import add

rdd = sc.parallelize([
   "Python", "python", "Haskell", "Clojure", "Scala", "scala"])
rdd.map(lambda word: (word.lower(), 1)).reduceByKey(add).collectAsMap()

## {'clojure': 1, 'haskell': 1, 'python': 2, 'scala': 2}

rawDescription: PySpark - how to merge key with case ignored


code:
item = QtGui.QTableWidgetItem()
# We set our icon and value
item.setIcon(icon)
item.setData(QtCore.Qt.EditRole, QtCore.QVariant(col))
# We set the size of our item. My icon is 80x32 pixels, but it was getting clipped off so I added 5 pixels of width
item.setData(QtCore.Qt.SizeHintRole, QtCore.QSize(85,32))
# We prevent the column from being resized. In my case it's the first column, so the index is 0
self.deckTable.horizontalHeader().setResizeMode(0, QtGui.QHeaderView.Fixed)

rawDescription: PyQt4: Sorting a QTableWidget by a column containing an icon


code:
import os
import struct

import pylzma

def sevenzip(infile, outfile):
    size = os.stat(infile).st_size
    with open(infile, "rb") as ip, open(outfile, "wb") as op:
        s = pylzma.compressfile(ip)
        op.write(s.read(5))
        op.write(struct.pack('<Q', size))
        while True:
            # Read 128K chunks.
            # Not sure if this has to be 1 instead to trigger streaming in pylzma...
            tmp = s.read(1<<17)
            if not tmp:
                break
            op.write(tmp)

if __name__ == "__main__":
    import sys
    try:
        _, infile, outfile = sys.argv
    except:
        infile, outfile = __file__, __file__ + u".7z"

    sevenzip(infile, outfile)
    print("compressed {} to {}".format(infile, outfile))

rawDescription: Using Pylzma with streaming and 7Zip compatibility


code:
name = 'Mr.Ed'
''.join(c.lower() if c.isupper() else c.upper() for c in name)

rawDescription: better way to invert case of string

description: Better way to invert case of string


code:
from django.core.files import File

user1=User(name='abc')
user1.pic.save('abc.png', File(open('/tmp/pic.png', 'r')))

rawDescription: Saving image/file through django shell

description: Saving image/file through django shell


code:
class ProfileInfoSerializer(serializers.ModelSerializer):
    avatar_url = serializers.SerializerMethodField()

    def get_avatar_url(obj, self):
        return obj.socialaccount_set.first().get_avatar_id()

    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name', 'avatar_url')

rawDescription: How to serialize the return value of a method in a model?

description: Serialize the return value of a method in a model


code:
def inventory_value(b: Book)->str:
    return (b.price * b.instock)

max(BSI, key=inventory_value)

rawDescription: Max value in a named tupple

description: Max value in a named tupple


code:
@event.listens_for(AuditColumns, "instrument_class", propagate=True)
def instrument_class(mapper, class_):
    if mapper.local_table is not None:
        trigger_for_table(mapper.local_table)

def trigger_for_table(table):
    trig_ddl = DDL("""
                CREATE TRIGGER tr_%s_audit_columns BEFORE INSERT OR UPDATE
                ON %s
                FOR EACH ROW EXECUTE PROCEDURE
                ss_test();
            """ % (table.name, table.name))

    event.listen(table, 'after_create', trig_ddl)

rawDescription: SQLAlchemy events after_create for all models


code: np.argmax(d==1, axis=1)

rawDescription: Is there a numpy.where() equivalent for row-wise operations?


code:
import tkinter as tk
import threading
import queue
import time

class GUI(object):
    """GUI Object"""
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("Window")

        self.status = tk.StringVar()
        self.status.set("plop")
        self.root.status_lbl = tk.Label(self.root, textvariable=self.status, width = 30)
        self.root.status_lbl.grid(row = 0, column = 0)

        self.root.start = tk.Button(self.root, text = "Start", width = 30, command = self.doing_things)
        self.root.start.grid(row = 1, column = 0)

        self.root.stop = tk.Button(self.root, text = "Stop", width = 30, command = None)
        self.root.stop.grid(row = 2, column = 0)

        self.root.mainloop()

    def doing_things(self):
        self.root.start.config(state = 'disabled')
        Other_thread = threading.Thread(None, Other, args=(self,))
        Other_thread.start()

class Other(object):
    """Something Else"""
    def __init__(self, gui):
        self.gui = gui
        self.msg2 = "Other Thread"

        self.doing_things()

    def doing_things(self):
        count = 0
        while 1 == 1:
            count += 1
            data = (self.msg2 + " " + str(count))
            print(data)
            self.gui.status.set(data)
            time.sleep(1)

GUI_thread = threading.Thread(None, GUI)

GUI_thread.start()

rawDescription: Python 3 threading and queueing

description: Python 3 threading and queueing


rawDescription: How to sort a list of dictionaries by length of dictionary

description: Sort a list of dictionaries by length of dictionary


rawDescription: How to encode a single string in python

description: Encode a single string in python


code:
re.search('(?<!/)foo', 'foo')
re.search('(?<!/)foo', '/foo')
re.search('(?<!/)foo', 'barfoo')

rawDescription: Python regular expression question - sub string but not prepended with


code:
def midpoint(s, e):
    '''Midpoint of start and end strings'''
    (sb, eb) = (int.from_bytes(bytes(x, 'utf-8'), byteorder='big') for x in (s, e))
    midpoint = int((eb - sb) / 2 + sb)

    midpoint_bytes = midpoint.to_bytes((midpoint.bit_length() // 8) + 1, byteorder='big')
    return midpoint_bytes.decode('utf-8')

rawDescription: Get the string that is the midpoint between two other strings


code: i = (lambda a: a.index(f(a)))([... for i in input])

rawDescription: Can one use list comprehension derivatives in its methods?


code:
import struct

data = [123,45,67,89]

# Show hex values of data.
print(list('%2x'%b for b in data))  # -> ['7b', '2d', '43', '59']

# Convert to 4 byte unsigned integer.
values = struct.unpack("I", bytearray(data))
print(hex(values[0]))  # -> 0x59432d7b

rawDescription: Convert 4 bytes to integer using struct in Python


code:
from sphinx.ext.autodoc import DataDocumenter, ModuleLevelDocumenter, SUPPRESS
from sphinx.util.inspect import safe_repr

def add_directive_header(self, sig):
    ModuleLevelDocumenter.add_directive_header(self, sig)
    if not self.options.annotation:
        try:
            objrepr = safe_repr(self.object)

            # PATCH: truncate the value if longer than 50 characters
            if len(objrepr) > 50:
                objrepr = objrepr[:50] + "..."

        except ValueError:
            pass
        else:
            self.add_line(u'   :annotation: = ' + objrepr, '<autodoc>')
    elif self.options.annotation is SUPPRESS:
        pass
    else:
        self.add_line(u'   :annotation: %s' % self.options.annotation,
                      '<autodoc>')

DataDocumenter.add_directive_header = add_directive_header

rawDescription: Ellipsis / truncation on module attribute value in Sphinx generated documentation


code:
class A:
    pass

class B:
    a = A()

A.b = B()

rawDescription: Python mutually dependent classes (circular dependencies)


code:
plt.hist([df1['text'],df2['printed']],
          bins=100, range=(1,100), stacked=True, color = ['r','g'])

rawDescription: creating stacked histogram with pandas dataframes data python

description: Creating stacked histogram with pandas dataframes data python


code:
hist = cv.CreateHist([255], cv.CV_HIST_ARRAY, [[0,255]], 1)
cv.CalcHist([im] , hist)
for h in range(255):
    zm = cv.QueryHistValue_1D(hist, h)
    objectArea.append([int(zm)])

rawDescription: Area of multiple blobs in a binary image python


rawDescription: apply to the entire dataframe a user-defined function involving another dataframe in pandas

description: Apply to the entire dataframe a user-defined function involving another dataframe in pandas


code:
def kaze_match(im1_path, im2_path):
    # load the image and convert it to grayscale
    im1 = cv2.imread(im1_path)
    im2 = cv2.imread(im2_path)
    gray1 = cv2.cvtColor(im1, cv2.COLOR_BGR2GRAY)
    gray2 = cv2.cvtColor(im2, cv2.COLOR_BGR2GRAY)

    # initialize the AKAZE descriptor, then detect keypoints and extract
    # local invariant descriptors from the image
    detector = cv2.AKAZE_create()
    (kps1, descs1) = detector.detectAndCompute(gray1, None)
    (kps2, descs2) = detector.detectAndCompute(gray2, None)

    print("keypoints: {}, descriptors: {}".format(len(kps1), descs1.shape))
    print("keypoints: {}, descriptors: {}".format(len(kps2), descs2.shape))

    # Match the features
    bf = cv2.BFMatcher(cv2.NORM_HAMMING)
    matches = bf.knnMatch(descs1,descs1, k=2)

    # Apply ratio test
    good = []
    for m,n in matches:
        if m.distance < 0.9*n.distance:
            good.append([m])

    # cv2.drawMatchesKnn expects list of lists as matches.
    im3 = cv2.drawMatchesKnn(im1, kps1, im2, kps2, good[1:20], None, flags=2)
    cv2.imshow("AKAZE matching", im3)
    cv2.waitKey(0)

rawDescription: How do you use Akaze in Open CV on python

description: Use Akaze in Open CV on python


code:
import subprocess
from time import strftime       # Load just the strftime Module from Time

f = open('check_'+strftime("%Y-%m-%d")+'.log', 'w')
for server in open('check.txt'):
    f.write(server.strip() + "\n")
    p = subprocess.Popen(['plink', server.strip(), 'df','-k'],stdout=f)
    p.wait()
    f.flush()

rawDescription: Format the output - python

description: Format the output - python


rawDescription: PyQt: Can I make a toolbar button with an icon and text?


code: filter(lambda x:x[0] is not None, instances)

rawDescription: get public ip of instances in AWS

description: Get public ip of instances in AWS


code: dic = {m : my_function(m) for m in my_list}

rawDescription: Joining dictionaries in a for loop

description: Joining dictionaries in a for loop


rawDescription: Getting the last half of string written on backwards


code:
PICKLE_FILENAME_INSTRUCTION_IDS = 'pickled_instruction_ids.txt'

def compare_instruction_id_list_with_baseline(baselineidspicklefile):
    baseline_ids = load_pickled_ids(baselineidspicklefile)
    current_main_url_content = get_page_content(main_url_test)
    root = lh.fromstring(current_main_url_content)
    current_ids = get_instruction_ids(root)
    diff = [id for id in current_ids if id not in baseline_ids]
    return locals()

rawDescription: Accessing all variables declared in a function without duplicating code


code:
import os, stat
info = os.stat(dirpath)
uid, gid = info[stat.ST_UID], info[stat.ST_GID]

rawDescription: Set files to ownership of current directory in Python


code: another_function( lambda x: 2*x )

rawDescription: Python: can function be defined inside of another function's argument list?


code:
for i in range(0,5):
    plt.subplot2grid((1,5),(0,i))
    ax=df.Survived[df.SibSp == i].value_counts().ix[[0,1]].plot(kind='bar')
    ax.set_xticklabels(['alive', 'dead'])
    title(str(i))

rawDescription: matplotlib changing barplot xtick labels and sorting the order of bars

description: Matplotlib changing barplot xtick labels and sorting the order of bars


code:
with open(r'C:\Users\MyUsername\Desktop\answer.txt', 'a') as fd:
    print(' '.join(final), file=fd, end='\n')

rawDescription: Python 3.3.0: How to output a variable onto a .txt file


code:
n = numpy.ones(100)
n[50] = 0
n.argmin()

rawDescription: Finding first 0 in first row of numpy array


code:
@pytest.fixture(
    scope='module', # so that it's reused in the module scope
    params=[100, 200]
)
def simulation(request):
    speed = request.param
    # create the simulation
    return df

class Test:

    def test1(self, simulation):
        ...

    def test2(self, simulation):
        ...

rawDescription: How to create a Test class with parameters?

description: Create a Test class with parameters


code:
def altElement(a):
    return a[::2]

rawDescription: Skipping every other element after the first


rawDescription: How to make slice modification in python 3 (or operator overloading missing)

description: Make slice modification in python 3 (or operator overloading missing)


code:
import os, sys
lib_path = os.path.abspath(os.path.join('..', '..', '..', 'lib'))
sys.path.append(lib_path)
import mymodule

rawDescription: Import module from specific folder

description: Import module from specific folder


code:
import dl
from module_ import *
dl.open(library, dl.RTLD_NOW, dl.RTLD_GLOBAL)

rawDescription: SWIG - running python code upon import

description: SWIG - running python code upon import


code:
import random
hello = ['hi', 'hello', 'yo', 'bonjour', 'hola', 'salaam']
random.choice(hello)

rawDescription: How to make python choose randomly between multiple strings?

description: Make python choose randomly between multiple strings


code:
def verify_fonts_are_installed_for_statements():
    import subprocess
    from os import path
    potential_locations = [
        '/usr/bin/fc-list',
        '/usr/sbin/fc-list',
        '/usr/local/sbin/fc-list',
        '/usr/local/bin/fc-list',
    ]
    valid_path = None
    for file_path in potential_locations:
        if path.exists(file_path):
            valid_path = file_path
            break
    if valid_path is None:
        raise IOError('could not find fc-list to verify fonts exist.')

    cmd = [valid_path]
    output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]

    if 'Helvetica Neue' not in output:
        raise FontNotInstalledException('Helvetica Neue')
    if 'Courier' not in output:
        raise FontNotInstalledException('Courier')

    log.debug('Courier and Helvetica Neue were found to be installed.')

rawDescription: check system if font exists python (OS agnostic)

description: Check system if font exists python (OS agnostic)


code:
import tkinter as tk
from tkinter import messagebox as box

#Does the actual saving
def save(oldfile):
    file_ = open(oldfile+".py", 'r')
    #[...]
    newfile.close()
    #do not destroy window here

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title('Save a file')

        frame3 = tk.Frame()
        frame3.pack(padx=5, pady=5)
        self.filename = tk.Entry(frame3)
        self.filename.pack(side=tk.LEFT)

        #click button
        save_btn2 = tk.Button(frame3, text='Save to Testicles.py', command=self.save_conf)
        save_btn2.pack(side=tk.RIGHT, padx=2)

    def save_conf(self):
        var = box.askokcancel('Save', 'Are you sure you want to save?')
        if var == 1:
            save(self.FileName.get())
            self.destroy()  #<-- here come the destroy

def launch_app():
    app = App()
    app.mainloop()

if __name__ == "__main__":
    launch_app()

rawDescription: Splitting a TKInter function

description: Splitting a TKInter function


code:
def rfftfreq(n, d=1.0):
    """
Return the Discrete Fourier Transform sample frequencies
(for usage with rfft, irfft).

The returned float array `f` contains the frequency bin centers in cycles
per unit of the sample spacing (with zero at the start). For instance, if
the sample spacing is in seconds, then the frequency unit is cycles/second.

Given a window length `n` and a sample spacing `d`::

f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is even
f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd

Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`)
the Nyquist frequency component is considered to be positive.

Parameters
----------
n : int
Window length.
d : scalar, optional
Sample spacing (inverse of the sampling rate). Defaults to 1.

Returns
-------
f : ndarray
Array of length ``n//2 + 1`` containing the sample frequencies.

Examples
--------
>>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float)
>>> fourier = np.fft.rfft(signal)
>>> n = signal.size
>>> sample_rate = 100
>>> freq = np.fft.fftfreq(n, d=1./sample_rate)
>>> freq
array([ 0., 10., 20., 30., 40., -50., -40., -30., -20., -10.])
>>> freq = np.fft.rfftfreq(n, d=1./sample_rate)
>>> freq
array([ 0., 10., 20., 30., 40., 50.])

"""
    if not (isinstance(n,int) or isinstance(n, integer)):
        raise ValueError("n should be an integer")
    val = 1.0/(n*d)
    N = n//2 + 1
    results = arange(0, N, dtype=int)
    return results * val

rawDescription: Python plot frequency of fft.rfft

description: Python plot frequency of fft.rfft


code:
import youtube_dl

class MyLogger(object):
    def debug(self, msg):
        pass

    def warning(self, msg):
        pass

    def error(self, msg):
        print(msg)

ydl_opts = {
    'logger': MyLogger(),
}

with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    info = ydl.extract_info('http://www.youtube.com/watch?v=BaW_jenozKc', download=True)
print('The duration is {0}'.format(info['duration']))

rawDescription: Issues with basic embedding of youtube_dl into a Python 3.4 script


code:
for cols in data.columns.tolist()[1:]:
    data = data.ix[data[cols] > 0]

rawDescription: Python Pandas: DataFrame filter negative values


code:
stacked_bar_data["total"] = stacked_bar_data.Series1 + stacked_bar_data.Series2 # Creates 'total column of two series you're interested in.

#Plot 1 - background - "total" (top) series
sns.barplot(x = stacked_bar_data.Group, y = stacked_bar_data.total, color = "blue")

#Plot 2 - overlay - "bottom" series
bottom_plot = sns.barplot(x = stacked_bar_data.Group, y = stacked_bar_data.Series1, color = "red")

topbar = plt.Rectangle((0,0),1,1,fc="red", edgecolor = 'none')
bottombar = plt.Rectangle((0,0),1,1,fc='#0000A3',  edgecolor = 'none')
l = plt.legend([bottombar, topbar], ['Bottom Bar', 'Top Bar'], loc=1, ncol = 2, prop={'size':16})
l.draw_frame(False)

rawDescription: How to plot binary colored histogram in Python?

description: Plot binary colored histogram in Python


code:
from pyspark.sql.functions import col, lag, unix_timestamp
from pyspark.sql.window import Window

rawDF = sc.parallelize([
    ("station1", "part1", "2015-01-03 00:11:02"),
    ("station2", "part2", "2015-02-00 10:20:10"),
    ("station3", "part3", "2015-03-02 00:30:00"),
    ("station1", "part1", "2015-05-00 01:07:00"),
    ("station1", "part1", "2015-01-13 05:16:10"),
    ("station1", "part1", "2015-11-20 10:22:40"),
    ("station3", "part3", "2015-09-04 03:15:22"),
    ("station1", "part1", "2015-03-05 00:41:33")
]).toDF(["station", "part", "event"])

eventDF = rawDF.withColumn("event", unix_timestamp(col("event")))

w = Window.partitionBy(col("station")).orderBy(col("event"))

(eventDF
  .withColumn("prev_event", lag(col("event")).over(w))
  .withColumn("cycle_time", col("event") - col("prev_event")))

rawDescription: Spark: Python Windowed Functions for Data Frames


code: raw_input("press enter")

rawDescription: how to pause a script of python

description: Pause a script of python


code:
from Tkinter import *
from tkMessageBox import *
root = Tk()
val = 0
val2 = 0

def op1():

    global e, l, root, val, e2, b, new
    try:
        val = int(e.get())
    except ValueError:
        showerror("Error", "Enter an int")
    else:
        new = Toplevel()
        e2 = Entry(new)
        e2.pack(side = LEFT)
        b2 = Button(new, text = "OK", command = op2)
        b2.pack(side = RIGHT)
        l2 = Label(new, text = "Enter new number to multiply %d by" %val)
        l2.pack()
        e2.focus_force()
        root.wait_window(new)
        for i in range(5):
            print (i + 1)

def op2():
    global val
    try:
        val2 = int(e2.get())
    except ValueError:
        showerror("Error", "Enter an int")
        e2.focus_force()
    else:
        val = val * val2
        l.config(text = "This is your total: %d Click OK to exit" %val)
        new.destroy()
        b.config(command = op3)
def op3():
    root.destroy()

e = Entry(root)
e.pack(side = LEFT)
b = Button(root, text = "OK", command = op1)
b.pack(side = RIGHT)
l = Label(root, text = "Enter a number")
l.pack()
root.mainloop()

rawDescription: Pause execution until user input received from tkinter window


code:
TIME_ZONE = 'America/Phoenix'
DATETIME_FORMAT = 'm-d-Y H:m:s T'
DATE_FORMAT = _('m-d-Y')
JS_DATE_FORMAT = _('mm-dd-yy')
PERC_DATE_FORMAT = _('%m-%d-%Y')

rawDescription: Django date filter: how come the format used is different from the one in datetime library?


code:
# Generate data like the question
observed_dates = pd.date_range("jan 2004", "april 2013", freq="M")
submissions = np.random.normal(5000, 100, len(observed_dates))
submissions += np.arange(len(observed_dates)) * 10
submissions[::12] += 800

# Plot the observed data
plt.plot(observed_dates, submissions, marker="o")

# Fit a model and predict future dates
predict_dates = pd.date_range("jan 2004", "jan 2020", freq="M")
model = np.polyfit(observed_dates.asi8, submissions, 1)
predicted = np.polyval(model, predict_dates.asi8)

# Plot the model
plt.plot(predict_dates, predicted, lw=3)

rawDescription: Extending regressions beyond data in Matplotlib


code:
resolvers = []

def sb_new_service(browser, interface, protocol, name, type, domain, flags ):
    sb_log.debug('new: {}'.format(name))
    if not (flags & Avahi.LookupResultFlags.GA_LOOKUP_RESULT_LOCAL):
        sb_log.debug('resolving: {}'.format(name))
        service_resolver = Avahi.ServiceResolver(
            interface=interface,
            protocol=protocol,
            name=name,
            type=type,
            domain=domain,
            aprotocol=Avahi.Protocol.GA_PROTOCOL_UNSPEC,
            flags=0,)
        service_resolver.connect('found', sr_found)
        service_resolver.connect('failure', sr_failure)
        service_resolver.attach(avahi_client)
        global resolvers
        resolvers.append(service_resolver)

rawDescription: Can't get Avahi.ServiceResolver to work

description: Can't get Avahi.ServiceResolver to work


rawDescription: iterator and type checking

description: Iterator and type checking


code:
import pandas as pd
df = pd.DataFrame({'a': [-3, -2, 4], 'b': [-2, 2, 5], 'c': [-1, 3, 7], 'd': [1, 4, 8]})
df.values
df.values.flatten()
sum(n < 0 for n in df.values.flatten())

rawDescription: Need count of negative values in a dataframe


code:
from bs4 import BeautifulSoup
import re
import urllib2,sys

url = "http://www.charityvillage.ca/cv/nonpr/nonpr1.html"
html = urllib2.urlopen(url).read()
soup = BeautifulSoup(html)

for item in soup.find_all(text=re.compile('\(.+: Ottawa', re.IGNORECASE)):
    link = item.find_previous_sibling(lambda tag: tag.has_key('href'))
    if link is None:
        continue
    print(u'{} [{}]: {}'.format(link.text,
                               item.strip(),
                               link['href']).encode('utf8'))

rawDescription: Using BeautifulSoup to extract an li element based on a string contained within


code: from yourscriptname import a

rawDescription: Run a Python script from Python prompt such that variables are loaded into the interactive environment


code:
class Dog(object):
    def make_sound(self):
        return "woof!"

class Cat(object):
    def make_sound(self):
        return "meow!"

class LolCat(object):
    def make_sound(self):
        return "i can has cheezburger?"

rawDescription: As a Java programmer learning Python, what should I look out for?


code:
#!/usr/bin/python
import zipfile, os

def zipdir(path, fname="test.zip"):
    zipf = zipfile.ZipFile(fname, 'w', zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(path):
        for file in files:
            zipf.write(os.path.join(root, file))
    zipf.close()

rawDescription: How to put files in a zip archive using Python zipfile

description: Put files in a zip archive using Python zipfile


code:
writer = open("filename.txt", 'w+')
# w+ is the flag for overwriting if the file already exists
# a+ is the flag for appending if it already exists

t = (val1, val2) #a tuple of values you want to save

for elem in t:
    writer.write(str(elem) + ', ')
writer.write('\n') #the write function doesn't automatically put a new line at the end

writer.close()

rawDescription: Writing user input to a text file in python


rawDescription: unpick a list of lists in Python

description: Unpick a list of lists in Python


rawDescription: Single string or list of strings in a method


code: module = __import__('module_name')

rawDescription: list of import statements in python

description: List of import statements in python


code:
local_path = os.path.abspath(os.path.basename(__file__))
raster_path = os.path.join(local_path, 'rasters')

rawDescription: How to make file paths configurable within an ArcGIS Python Add-In?

description: Make file paths configurable within an ArcGIS Python Add-In


code:
br.select_form(nr=0) # select the first form
br.submit()

rawDescription: Following the result of pressing a submit button in Python Mechanize


rawDescription: Change last octet of IP address

description: Change last octet of IP address


code:
if __name__ == "__main__":
    file_path = os.path.abspath(__file__)
    tests_path = os.path.join(os.path.abspath(os.path.dirname(file_path)), "tests")
    result = nose.run(argv=[os.path.abspath(__file__),
                            "--with-cov", "--verbosity=3", "--cover-package=phased", tests_path])

rawDescription: NoseTest: running with coverage from Python script


code:
if text in ( 'Text1', 'Text2', 'Text3', 'Text4' ):
    do_something()

rawDescription: Python multiple comparisons style?

description: Python multiple comparisons style


rawDescription: Map and work with (X, Y), (X,Z) and (Y,Z) pairs and associated X, Y or Z coordinates


code:
from bs4 import BeautifulSoup
from urllib.request import urlopen as uReq

url = 'http://afltables.com/afl/stats/games/2015/031420150402.html'
client = uReq(url)  # grabs the page
soup = BeautifulSoup(client.read(), 'html.parser')  # using the default html parser
tables = soup.find_all('table')  # gets all the tables
print(tables[7])  # scoring progression table, the 8th's table

rawDescription: BeautifulSoup not reading entire HTML obtained by requests


rawDescription: Python/Tkinter window events and properties


code: reload(socket)

rawDescription: Gevent monkey unpatch

description: Gevent monkey unpatch


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

# create an ellipse
el = matplotlib.patches.Ellipse((50,-23), 10, 13.7, 30, facecolor=(1,0,0,.2), edgecolor='none')

# calculate the x and y points possibly within the ellipse
y_int = np.arange(-30, -15)
x_int = np.arange(40, 60)

# create a list of possible coordinates
g = np.meshgrid(x_int, y_int)
coords = list(zip(*(c.flat for c in g)))

# create the list of valid coordinates (from untransformed)
ellipsepoints = np.vstack([p for p in coords if el.contains_point(p, radius=0)])

# just to see if this works
fig = plt.figure()
ax = fig.add_subplot(111)
ax.add_artist(el)
ep = np.array(ellipsepoints)
ax.plot(ellipsepoints[:,0], ellipsepoints[:,1], 'ko')

rawDescription: Extract coordinates enclosed by a matplotlib patch.


rawDescription: Python: only replace a string in specific location if the string appears several time in a line


code:
ipython = get_ipython()
from IPython.html import widgets

###del ipython._post_execute[make_svg]  ##add it if you rerun the cell.
r = 50
def make_svg():
    svg_code = """<svg width="300" height="200">
    <circle cx="50" cy="50" r="%d" stroke="black" stroke-width="3" fill="red" />
</svg>
""" % r
    _modal_body_label.value = "
%s
" % svg_code
ipython.register_post_execute(make_svg)

_modal_body_label = widgets.HTMLWidget(value = 'Not hooked')

_modal_body_label

rawDescription: Auto-update SVG representation of object in iPython notebook


code: uniq_animal_groups = set(map(tuple, animal_groups))

rawDescription: Get unique items from list of lists?

description: Get unique items from list of lists


code:
import numpy as np
import pylab as pl

def threshold_plot(x, y, th, fmt_lo, fmt_hi):
    idx = np.where(np.diff(y > th))[0]
    x_insert = x[idx] + (th - y[idx]) / (y[idx+1] - y[idx]) * (x[idx+1] - x[idx])
    y_insert = np.full_like(x_insert, th)

    xn, yn = np.insert(x, idx+1, x_insert), np.insert(y, idx+1, y_insert)

    mask = yn < th
    pl.plot(np.ma.masked_where(mask, xn), np.ma.masked_where(mask, yn), fmt_hi, lw=2)

    mask = yn > th
    pl.plot(np.ma.masked_where(mask, xn), np.ma.masked_where(mask, yn), fmt_lo)
    pl.axhline(th, color="black", linestyle="--")

x = np.linspace(0, 3 * np.pi, 50)
y = np.random.rand(len(x))
threshold_plot(x, y, 0.7, "b", "r")

rawDescription: Multiple colors in the one graph in Matplotlib


code:
with open(PATH, 'wb') as log_file:
    subprocess.check_call(cmd, stdout=log_file)

rawDescription: Using subprocess to log print statements of a command


code: import a.b

rawDescription: How can I find out what package that a python module belongs to?

description: Find out what package that a python module belongs to


code:
import sys,types,xml
xml.config = sys.modules['xml.config'] = types.ModuleType('xml.config')
import xml.config
from xml import config
from xml import config as x
x

rawDescription: Making a virtual package available via sys.modules


code: GLOBAL_1 = getattr(settings, 'GLOBAL_1', 'Def value for global 1')

rawDescription: Default configuration in python/django

description: Default configuration in python/django


code:
#arcpy.Extent(293490,5898230,316430,5930230)

#use 'CURRENT' if running from arcmap, when published use MXD on disk
mxd = arcpy.mapping.MapDocument("CURRENT")

df = arcpy.mapping.ListDataFrames(mxd)[0]
newExtent = df.extent
newExtent.XMin, newExtent.YMin = 293490,5898230
newExtent.XMax, newExtent.YMax = 316430,5930230
df.extent = newExtent

rawDescription: Output Extent (Environment Setting)

description: Output Extent (Environment Setting)


code:
def test(df):
    df.drop(pd.Int64Index([1]), inplace=True)

rawDescription: How can pandas drops some rows in a function?


code:
import re
exp = 'qty * price - discount + 100'
exp = re.sub('(qty|price|discount)','%(\\1)f', exp)%vars(obj)

rawDescription: python string conversion for eval

description: Python string conversion for eval


code:
from nose.tools import *
class Test_mysim():
    def setup(self):
        self.ans = calculate_it_once()

    def test_sync(self):
        ans=calculate_it_sync()
        assert_equal(ans,self.ans)

    def test_async(self):
        ans=calculate_it_async()
        assert_equal(ans,self.ans)

rawDescription: Python unit-testing with nose: Making sequential tests


code:
import pandas
pandas.read_fwf('f.out',
   colspecs=[x[:2] for x in keys.values()],
   dtype=[x[2] for x in keys.values()]
   )

rawDescription: Python IO: Reading a file using format specifier


rawDescription: How to revert a persistent Delegate ModelIndex back to "normal"

description: Revert a persistent Delegate ModelIndex back to "normal"


code:
name = 'Ryan'
days = 3
print(name, 'has been alive for', days, 'days.')
from __future__ import print_function
print(name, 'has been alive for', days, 'days.', sep=', ')

rawDescription: print() is showing quotation marks in results

description: Print() is showing quotation marks in results


code:
# __package__ is not guaranteed to be defined or could be set to None
# to represent that it's proper value is unknown
package = globals.get('__package__')
if package is None:
    package = globals['__name__']
    if '__path__' not in globals:
        package = package.rpartition('.')[0]
module = _gcd_import(name, package, level)

rawDescription: Distinguish modules from packages

description: Distinguish modules from packages


rawDescription: How to normalize '1:2:3' to '01:02:03' by using re module of Python?

description: Normalize '1:2:3' to '01:02:03' by using re module of Python


rawDescription: Add unit to python format function

description: Add unit to python format function


code:
import os, re

filenames = os.listdir('/path/to/your/files')
filenames.sort(key=lambda L: map(int, re.findall('\d+', L)))

rawDescription: Directory file listing sorted in output :(


rawDescription: Pandas DataFrame get substrings from column


code: A.objects.filter(b__c__in = c_subset)

rawDescription: How to query SELECT WHERE EXISTS... in django

description: Query SELECT WHERE EXISTS... in django


code:
class Test(object):
    def __init__(self, *args, **kwargs):
        print("in test init")
    def make(self):
        print("in test make")

cls_name = "Test"
method_name = "make"
callback = getattr(globals()[cls_name](), method_name)
callback()

rawDescription: How can use variable class name and function in Python


code:
import Tkinter as tk

class ExampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.label = tk.Label(self, text="", width=10)
        self.label.pack()
        self.remaining = 0
        self.countdown(10)

    def countdown(self, remaining = None):
        if remaining is not None:
            self.remaining = remaining

        if self.remaining <= 0:
            self.label.configure(text="time's up!")
        else:
            self.label.configure(text="%d" % self.remaining)
            self.remaining = self.remaining - 1
            self.after(1000, self.countdown)

if __name__ == "__main__":
    app = ExampleApp()
    app.mainloop()

rawDescription: Making a countdown timer with Python and Tkinter?


code:
term_width = 50
with contextlib.closing(fileinput.input(['my_file'], inplace=True)) as f:
    for line in f:
        if line.strip():
            sys.stdout.write('_____ {l}'.format(l=line))
        else:
            sys.stdout.write('\n'.rjust(term_width, '_'))

rawDescription: How to turn newlines in a file to lines extending to end of line?

description: Turn newlines in a file to lines extending to end of line


code:
import Defaults
Defaults.integral_method = somefunc

rawDescription: Set defaults at runtime

description: Set defaults at runtime


code:
cur.execute("""
    CREATE TABLE IF NOT EXISTS "{}"
    (fnr, kjonn, landbakgrunn, alder, arbkomm, naring)
    """.format(t))
cur.executemany("""
    INSERT OR IGNORE INTO "{}" (fnr, kjonn, landbakgrunn, alder, arbkomm, naring)
    VALUES (?,?,?,?,?,?)
    """.format(t), to_db)

rawDescription: How to use filenames from csv-files as table names in sqlite?

description: Use filenames from csv-files as table names in sqlite


code:
def question_by_date(request):
    year = request.GET.get('year', 2005)
    month = request.GET.get('month', 1)
    day = request.GET.get('day', 1)
    # use the parameters however you want afterwards

rawDescription: Django - regex optional function parameters in URL


code: messages = ([msg['created_at'], msg['txt'], msg['user']['id']] for msg in js['statuses'])

rawDescription: Python generator expression Twitter

description: Python generator expression Twitter


code:
ansdb = {}
for row in prsnobj.result:
    ansdb[int(row[0])] = int(row[1])

rawDescription: Dictionary output is not as expected in PYTHON


code:
file=open('corpus.txt','r')
data=file.readlines()
file.close()

diccionario = {}

for linea in data:
    linea.decode('latin_1').encode('UTF-8') # para los acentos
    palabra_tag = linea.split('\n')
    cadena = str(palabra_tag[0])
    if(diccionario.has_key(cadena)):
        aux = diccionario.get(cadena)
        aux += 1
        diccionario.update({cadena:aux})
    else:
        diccionario.update({cadena:1})

outfile = open('lexic.txt', 'w')
outfile.write('Palabra\tTag\tApariciones\n')

for key, value in diccionario.iteritems() :
    s = str(value)
    outfile.write(key +" "+s+'\n')
outfile.close()

rawDescription: Error generating a model reading corpus from a big .txt file


code:
import matplotlib.pyplot as plt

plt.subplot(1,2,1)
plt.plot(range(10), antialiased=False)
plt.title('Antialiasing Off')

plt.subplot(1,2,2)
plt.plot(range(10), antialiased=True)
plt.title('Antialiasing On')

plt.show()

rawDescription: What is antialiaseds in matplotlib.collections and how to set the parameter for it?


code:
click_element(get_element_by_xpath('your xpath'), wait=True)
click_link(get_element_by_xpath('your xpath'), wait=True)
click_button(get_element_by_xpath('your xpath'), wait=True)

rawDescription: Using SST framework, how do you click a link by css class or xpath?


code:
class A(object):
    pass

class B(object):
    def __init__(self, foo):
        self.foo = foo

someA = A() #creates an object of type A, with no custom variables or methods
someB = B('bar') #creates an object of type B, in which foo is set

rawDescription: About Classes and init method

description: About Classes and init method


code:
import itertools
from collections import Counter
first = ['a','b','c','d']
second = [['a','b','c','d'], ['a','b'], ['a','c','d'], ['a','b','d']]
uniques = []
c = Counter()
for let in second:
    letPermut = list(set(itertools.permutations(let, 2)))
    for i in first:
        for permut in letPermut:
            if permut[0] == i and not permut in uniques:
                c[i] += 1
                uniques.append(permut)
for item in c.items():
    print(item)

rawDescription: Counting number of permutations of each element


code:
class DesignerMainWindow(QtGui.QMainWindow, Ui_fiberModesMainWindow):
    def __init__(self, parent = None):
        super(DesignerMainWindow, self).__init__(parent)
        self.setupUi(self)
        self.pb_addRow_1.clicked.connect( self.addRow )

    def addRow( self ):
        rows = self.PropertyLayout.rowCount()
        columns = self.PropertyLayout.columnCount()
        for column in range(columns):
            layout = self.PropertyLayout.itemAtPosition(rows - 1, column)
            if layout is not None:
                widget = layout.widget()
                if isinstance(widget, QtGui.QPushButton):
                    widget.setText('Remove %d' % (rows - 1))
                    widget.clicked.disconnect(self.addRow)
                    widget.clicked.connect(self.removeRow)
                else:
                    widget.setEnabled(False)
        widget = QtGui.QLineEdit(self.centralwidget)
        self.PropertyLayout.addWidget(widget, rows, 1, 1, 1)
        widget = QtGui.QPushButton(self.centralwidget)
        widget.setText('Add Row')
        widget.clicked.connect(self.addRow)
        self.PropertyLayout.addWidget(widget, rows, columns - 1, 1, 1)

    def removeRow(self):
        index = self.PropertyLayout.indexOf(self.sender())
        row = self.PropertyLayout.getItemPosition(index)[0]
        for column in range(self.PropertyLayout.columnCount()):
            layout = self.PropertyLayout.itemAtPosition(row, column)
            if layout is not None:
                layout.widget().deleteLater()
                self.PropertyLayout.removeItem(layout)

rawDescription: pyside - how to delete widgets from gridLayout

description: Pyside - how to delete widgets from gridLayout


code:
class TestServer(SocketServer.TCPServer):
    allow_reuse_address = True

...
httpd = TestServer(("", PORT), handler)

rawDescription: Using SimpleHTTPServer for unit testing

description: Using SimpleHTTPServer for unit testing


code:
def reversed(self):
    """Creates a cursor for use in a query with a reversed sort order."""
    for pos in self.__compiled_cursor.position_list():
        if pos.has_start_key():
            raise datastore_errors.BadRequestError('Cursor cannot be reversed.')

    rev_pb = datastore_pb.CompiledCursor()
    rev_pb.CopyFrom(self.__compiled_cursor)
    for pos in rev_pb.position_list():
        pos.set_start_inclusive(not pos.start_inclusive())
    return Cursor(_cursor_pb=rev_pb)

rawDescription: Is it possible to tell whether an NDB cursor has been reversed?


code:
import re
re.sub(r'(.)\1+', r'\1\1', "haaaaapppppyyy")

rawDescription: Remove repeating characters from words

description: Remove repeating characters from words


code:
#!/usr/bin/env python
import asyncio
import aiohttp  # $ pip install aiohttp

async def fetch(session, key, item, base_url='http://example.com/posts/'):
    async with session.get(base_url + item) as response:
        return key, await response.json()

async def main():
    d = {'a': '1', 'b': '2', 'c': '3'}
    with aiohttp.ClientSession() as session:
        ####tasks = map(functools.partial(fetch, session), *zip(*d.items()))
        tasks = [fetch(session, *item) for item in d.items()]
        responses = await asyncio.gather(*tasks)
    print(dict(responses))

asyncio.get_event_loop().run_until_complete(main())

rawDescription: Associating aiohttp requests with their responses


code: and_((Matter.id == WorkItem.matter_id), (WorkItem.line_item_id == None))

rawDescription: How do I specify a relation in SQLAlchemy where one condition requires a column to be null?

description: Specify a relation in SQLAlchemy where one condition requires a column to be null


code:
x = [log(1),log(2),log(4),log(5),log(8)]
#Import y data from a file
free= curve_fit(func,np.array(x),np.array(y))[0][0]
yline = func(free, np.array(x))

rawDescription: Why is the returned array of a function is twice as large as the input list?


code:
from werkzeug.wrappers import BaseRequest, ETagRequestMixin

class Request(BaseRequest, ETagRequestMixin):
    pass

app = Flask(__name__)
app.request_class = Request

rawDescription: expand werkzeug useragent class

description: Expand werkzeug useragent class


code:
from tkinter import *
import time

def openNewWindow():
    firstWindow.destroy()

    secondWindow = Tk()
    secondWindow.title("Second Window")

    photoTwo = PhotoImage(file="freedom.gif")
    labelTwo = Label(secondWindow, image=photoTwo).pack()

    secondWindow.mainloop()

firstWindow = Tk()

firstWindow.title("First Window")

logo = PhotoImage(file="burger.gif")
w1 = Label(firstWindow, image=logo).pack()

closeBttn = Button(firstWindow, text="Close!", command=openNewWindow)
closeBttn.pack()

firstWindow.mainloop()

rawDescription: Multiple windows open at once in python

description: Multiple windows open at once in python


code:
from operator import itemgetter
L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]
sorted(L, key=itemgetter(2))

rawDescription: How to sort a list of lists by a specific index of the inner list?

description: Sort a list of lists by a specific index of the inner list


code:
variables = ["cellA", "cellB"]
expression = "cellA.isEqual(cellB)"
chunk = eval("(lambda " + ','.join(variables) + " : " + expression + ")")
chunk
class Cell(object):
  def isEqual(self, other):
    return 27
chunk(Cell(), Cell())

rawDescription: Python code chunk generation with instances


code:
def _sub_ip(self, line):
    pattern = r"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)([ (\[]?(\.|dot)[ )\]]?(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})"
    ips = [each[0] for each in re.findall(pattern, line)]
    for item in ips:
        location = ips.index(item)
        ip = re.sub("[ ()\[\]]", "", item)
        ip = re.sub("dot", ".", ip)
        ips.remove(item)
        ips.insert(location, ip)

    for ip in ips:
        line = line.replace(ip, self._ip2db(ip))

    return line

rawDescription: IPv4 address substitution in Python script


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
fig = plt.figure(figsize=(5,5))
ax = plt.axes([0,0,1,1])
triangle1 = mpatches.Polygon(np.array([[0,1],[1,0],[1,1]]), fc="blue")
triangle2 = mpatches.Polygon(np.array([[-0.1,-1],[-2,-2],[-2,-1]]), fc="red")
ax.add_artist(triangle1)
ax.add_artist(triangle2)
ax.set_xlim(-3, 3)
ax.set_ylim(-3, 3)
plt.show()

rawDescription: MatPlotLib coulored triangulars

description: MatPlotLib coulored triangulars


rawDescription: print scapy sniff output to file

description: Print scapy sniff output to file


code:
diff = cv2.matchTemplate(img1, img2, cv2.TM_CCORR_NORMED)
x, y = np.unravel_index(np.argmax(diff), diff.shape)

rawDescription: Find image inside another in SimpleCV

description: Find image inside another in SimpleCV


code:
u'some arabic word' #this will work
u'%s' % word #this will work
'some string' + u'some arabic string' #this will fail
u'some string' + u'some arabic string' #this will work

rawDescription: Python/Django and an Arabic Document Search Application


code:
import pandas

csv = pandas.read_csv('test.csv', sep=',', header=3, skipinitialspace=True)
# header=3 because your header is on the third line
# skipinitialspace is set to True because your example data has spaces after commas
csv_apples = csv[csv['Fruit'] == 'Apple']
csv_bananas = csv[csv['Fruit'] == 'Banana']

csv_apples.to_csv('apples.csv', index=False, sep=',')
csv_bananas.to_csv('bananas.csv', index=False, sep=',')

rawDescription: Split CSV file into multiple files by column-data


code: requests.get("https://api.spotify.com/v1/audio-features/06AKEBrKUckW0KREUWRnvT", headers={"Authorization": "Bearer {your access token}"})

rawDescription: Multi parameter curl request Python, Spotify API


code: send([ARP(op=ARP.who_has, psrc=ip_src, pdst=ip_dst) for ip_src, ip_dst in dict1.viewitems()], loop=1)

rawDescription: Python-2.7 Scapy -- send multiple arp requests simultaniously


code:
from datetime import datetime

date_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

rawDescription: Converting string into datetime

description: Converting string into datetime


rawDescription: How to find matching braces in string?

description: Find matching braces in string


code:
for j in range (15):
    for i in range(10):
            output.append(probability(prob, outcome))
    amount = sum(output)
    outcome1.append(amount)
    output = []

print(outcome1)

rawDescription: Python looping through list and adding sum to new list


code:
from math import factorial
import scipy.misc

def comb(n,k):
  return scipy.misc.comb(n,k,True)

def monepow(n):
  if n % 2 == 0:
    return 1
  else:
    return -1

def B(mu, nu, n, np, l, lp, m):
  B = 0
  beta1 = max( 0, mu - np - l, nu - np - l + m )
  beta2 = min( n - l, nu )
  for beta in range(beta1, beta2+1):
    c1 = comb(n-l, beta)
    beta1p = max( 0, mu - beta - l - lp, nu - beta - l - lp + m )
    beta2p = min( np - lp, nu - beta )
    for betap in range(beta1p, beta2p+1):
      delta = min( mu + nu + l + lp, mu + n + np ) + 1
      c2 = comb(np - lp, betap) * factorial(delta) / factorial (mu + beta + betap + l + lp + 1)
      alpha1 = max( m, nu - beta - betap - lp + m )
      for alpha in range(alpha1, l+1):
        c3 = monepow(alpha) * comb(l, alpha) * comb(l, alpha - m)
        alpha1p = max( m, nu - beta - betap - alpha + m )
        for alphap in range(alpha1p, lp):
          c4 = monepow(alphap) * comb(lp, alphap) * comb(lp, alphap-m) * comb(alpha - alphap - m, nu - beta - betap) * factorial(alpha - alphap + beta + lp) * factorial( alpha - alphap + beta + l)
          for lam in range(0, mu+1):
            c5 = monepow(lam) * comb( alpha - alphap + beta + lp + lam, lam ) * comb (alpha - alphap + betap + l + mu - lam, mu - lam) * comb(mu, lam)
            x = c1*c2*c3*c4*c5
            B += x
  return B

def testAll():
  for mu in range (0,10):
    for nu in range (0,10):
      for n in range(1,5):
        for np in range(1,5):
          for l in range(0,n):
            for lp in range(0,np):
              for m in range(0,l+1):
                b = None
                try:
                  b = B(mu, nu, n, np, l, lp, m)
                except:
                  pass
                if b is not None:
                  print [mu, nu, n, np, l, lp, m], " -> ", b
# print B(1, 1, 6, 6, 0, 4, 3)  # should be == 0
# print B(1, 2, 6, 6, 4, 0, 0)  # should be == 0
# print B(2, 2, 6, 6, 4, 0, 0)  # might be == 0
# print B(3, 2, 6, 6, 4, 0, 0)  # might be == 0
testAll()

rawDescription: Implementation of nested summing in python


code:
root = Tk()

def getFIleName(varName, entryName):
    varName = tkFileDialog.askopenfilename()
    entryName.insert(0, varName)

iconButton = Button(root, text="Browse", command=(lambda: getImageName(campIcon, iconEntry)))
iconButton.pack()

rawDescription: How to make a button that returns the input filename of tkFileDialog.askopenfilename() as a string?

description: Make a button that returns the input filename of tkFileDialog.askopenfilename() as a string


code:
def all_the_same(lst):
    # all values in aList are the same.
    return len(set(lst)) == 1

rawDescription: Compare Values in a List and create Boolean Python


code:
from google.appengine.ext import endpoints

@endpoints.api(...)
class MyApi(...):

    @endpoints.method(...)
    def my_method(self, request):
        current_user = endpoints.get_current_user()
        if current_user is None:
            # This will result in a 401
            raise endpoints.UnauthorizedException('Invalid token.')

rawDescription: EndPoints API authentification on GAE python with an Android client


code:
import re
re.split('[ .]', 'a b.c')

rawDescription: split string on a number of different characters

description: Split string on a number of different characters


code:
class Animal(object):
    ...

rawDescription: different setters for python properties

description: Different setters for python properties


code:
lines = 4
cols  = 4
a = [[['H',' '] for j in range(cols)] for i in range(lines)]

rawDescription: 2D array of 2 cells lists

description: 2D array of 2 cells lists


code:
from PyQt4 import QtCore as core, QtGui as gui
import time

class MyProccess(core.QThread):

    newProgress = core.pyqtSignal(str)

    def __init__(self,i):
        super(MyProccess,self).__init__()
        self.id = i

    def run(self):
        for j in range(10):
            self.newProgress.emit('task %d at %d%%' % (self.id,j*10))
            time.sleep(0.2)

class MySplash(gui.QSplashScreen):

    def __init__(self,mw):
        super(MySplash,self).__init__()
        layout = gui.QVBoxLayout(self)
        self.setLayout(layout)
        self.text = gui.QLabel(self)
        layout.addWidget(self.text)
        self.setGeometry(300,300,100,0)

        self.task1 = MyProccess(1)
        self.task2 = MyProccess(2)
        self.task3 = MyProccess(3)

        self.task1.newProgress.connect(self.showProgress)
        self.task2.newProgress.connect(self.showProgress)
        self.task3.newProgress.connect(self.showProgress)

        self.task1.finished.connect(self.task2.start)
        self.task2.finished.connect(self.task3.start)
        self.task3.finished.connect(mw.show)
        self.task3.finished.connect(self.hide)

    @core.pyqtSlot(str)
    def showProgress(self,msg):
        self.text.setText(msg)

    def event(self,ev):
        if type(ev) == gui.QShowEvent:
            self.task1.start()
        return super(MySplash,self).event(ev)

app = gui.QApplication([])

mw = gui.QMainWindow()

cw = gui.QWidget()
l = gui.QHBoxLayout()
cw.setLayout(l)
welcome = gui.QLabel()
welcome.setText('Welcome back!')
l.addWidget(welcome)

mw.setCentralWidget(cw)
mw.setGeometry(200,200,300,300)

w = MySplash(mw)
w.show()

app.exec_()

rawDescription: Python + QT: How to make non-GUI Blocking loading screen?


code:
class Animal(object):

  def __init__(self, color):
    self.color = color

  @classmethod
  def make_baby(cls):
    return cls(rand_color)   # randomly-chosen color

rawDescription: Python Classes: Variable subclass creation in the base class's methods


code:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,3])
plt.savefig('myfig')

rawDescription: Inserting hyperlinks in pyplot interactive mode


code:
from itertools import islice, izip, cycle

list_1 = ['a','b','c']
list_2 = [1,2]

list(islice(izip(cycle(list_1), cycle(list_2)), len(list_1)*len(list_2)))

rawDescription: Sort distributed couples from two lists

description: Sort distributed couples from two lists


code: setattr(myObject, "key", "value")

rawDescription: Python equivalent to Matlab's set function


code:
import requests

action = "https://sourceforge.net/rest/p/test-sourceforge-api/tickets/new"

url = action + "?access_token=" + token

body = {'access_token':token,
    'ticket_form.description': "Test Description",
    'ticket_form.summary':'Test Title'
    }

files={'ticket_form.attachment':("myfilename","myfilecontents", 'application/octet-stream')}

r = requests.post(url, data=body, files=files)

rawDescription: Create a ticket with an attachment on Sourceforge


code:
import numpy as np
dt = np.dtype([('destID',int),('ATTRACT',float),('other','S10')])
TableArr=np.zeros((10,),dt)
TableArr['destID']=np.random.randint(10,size=(10,))
TableArr['ATTRACT']=np.random.randint(100,size=(10,))
TableArr
Tcopy=TableArr[['destID','ATTRACT']].copy()
Tcopy['ATTRACT'] *= -1  # 'reverse' a field
I=np.argsort(Tcopy,order=['destID','ATTRACT'])
I
TableArr[I]

rawDescription: numpy sort a structured array by two fields, ascending and descending orders

description: Numpy sort a structured array by two fields, ascending and descending orders


code:
import time
tm = time.strftime('%a, %d %b %Y %H:%M:%S %Z(%z)')
tm

rawDescription: python: how do you concatenate time to a string?

description: Python: how do you concatenate time to a string


code:
class Game:
    gameDisplay = pygame.display.set_mode(self.displaySize)
    def __init__(self,w,x,y):
        #{
        # display paramteters
        self.fps = 30
        self.fpsTime = pygame.time.Clock()
        self.displaySize = (0,0)

rawDescription: Python: Trouble accessing class variables of another class


code:
for i in left:
        for j in right:
                a = b = c = 0                               # reinitialize!

                for line in text_file.splitlines():
                        if i in line and j in line:
                                a += 1
                        elif i in line and j not in line:
                                b+= 1
                        elif j in line and i not in line:
                                c+= 1

                bigram.append((i,j,a, b, c))

rawDescription: Loop for items in two files

description: Loop for items in two files


code: listy[nam] = ''.join([encrypt[i] for i in passw])

rawDescription: How to execute a command and put the answer in a dictionary

description: Execute a command and put the answer in a dictionary


code:
myfile = open('angles.txt', 'w')
# Creates numbers.txt file

number.sort()

for e in number:
  myfile.write(str(e))

myfile.close()

rawDescription: Python write random integers to file on newline


code:
import tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        l1 = tk.Label(text="Hello")
        l2 = tk.Label(text="World")
        l1.grid(row=0, column=0, padx=(100, 10))
        l2.grid(row=1, column=0, padx=(10, 100))

app = MyApp()
app.root.mainloop()

rawDescription: Adding padding to a tkinter widget only on one side


rawDescription: Format syntax in Python

description: Format syntax in Python


rawDescription: python: how to use 'import' on character string variable?

description: Python: how to use 'import' on character string variable


rawDescription: Regex version of python string

description: Regex version of python string


code:
import os

from subprocess import call

files = os.listdir("D:\\Media\\TV Shows\\Naruto")

frmt = input('Enter the file format:')

files = [i for i in files if i[-3:]==frmt ]

print(files)
for filegoeshere in files:
    fun = '''"C:\Program Files\MKVToolNix\mkvmerge.exe" -o "D:\\Media\\TV Shows\\Naruto\\'''+filegoeshere[:-4]+'''_jp.mkv"  "--default-track" "0:yes" "--forced-track" "0:no" "--display-dimensions" "0:640x480" "--language" "2:jpn" "--track-name" "2:Japanese" "--default-track" "2:no" "--forced-track" "2:no" "--track-name" "3:English" "--default-track" "3:yes" "--forced-track" "3:no" "-a" "2" "-d" "0" "-s" "3" "-T" "--no-global-tags" "D:\\Media\\TV Shows\\Naruto\\'''+filegoeshere+'''" "--track-order" "0:0,0:2,0:3"'''
    call(fun)

rawDescription: How to delete one specific stream out of two audio streams from multiple video files of same properties using python?

description: Delete one specific stream out of two audio streams from multiple video files of same properties using python


code:
while len(urls)>0 :
    try:
        curl = urls.pop(0)
        thepage1 = requests.get(curl).text
        global ctot
        if "Contact Us" in thepage1:
            slist.write("\n" +curl)
            ctot = ctot + 1
    except:
        pass

rawDescription: Thread memory usage keeps increasing

description: Thread memory usage keeps increasing


code:
def xpath_get(mydict, path):
    elem = mydict
    try:
        for x in path.strip("/").split("/"):
            elem = elem.get(x)
    except:
        pass

    return elem

rawDescription: Xpath like query for nested python dictionaries


code:
import itertools as it
left,right = it.tee((myfilter(x), x) for x in mylist)
filter_true = (x for p,x in left if p)
filter_false = (x for p,x in right if not p)

rawDescription: Nicest, efficient way to get result tuple of sequence items fullfilling and not fullfilling condition


code:
S = [1,2,3,4,5,6]
result = [ (x,y) for x in S for y in S if y%x==0]

rawDescription: Python implementation of set relations

description: Python implementation of set relations


code:
import tkinter

class Prompt:
    def button_action(self):
        self.my_entry = self.ent.get() #this is the variable I wanna use in another function

    def __init__(self, den):
        self.lbl = tkinter.Label(den, text="Write Something")
        self.ent = tkinter.Entry(den)
        self.btn = tkinter.Button(den, text="Get That Something", command=self.button_action)
        self.lbl.pack()
        self.ent.pack()
        self.btn.pack()

den = tkinter.Tk()
den.title("Widget Example")
prompt = Prompt(den)
den.mainloop()

rawDescription: Using the variable from entry/button in another function in Tkinter


code:
json_string = '''{"list":[
            {"issues":{"first_name": "Guido", "last_name":"Rossum"}},
            {"issues":{"first_name": "sss", "last_name":"andsk"}} ]
            }'''
parsed_json = json.loads(json_string)
print(parsed_json)

rawDescription: String to Dictionary conversion in python


code:
import random
no1 =(random.randint(1,20))
function =(random.choice("+-*"))
no2 =(random.randint(1,20))
answer =str(no1) + function + str(no2)
print(str(no1) + function + str(no2) + '=' + str(eval(answer)))

rawDescription: Random sum - python

description: Random sum - python


code:
@route('/image')
def video_image():
    image_buffer = BytesIO()
    pi_camera.capture(image_buffer, format='jpeg') # This works without a problem

    image_buffer.seek(0) # this may not be needed
    bytes = image_buffer.read()
    response.set_header('Content-type', 'image/jpeg')
    return bytes

rawDescription: Returning image using stream instead of static_file in Bottle


code:
#!/usr/bin/env python3
import errno
from io import TextIOWrapper
from subprocess import Popen, PIPE
from threading import Thread

def feed(pipe):
    while True:
        try: # get input
            line = input('Enter input for minecraft')
        except EOFError:
            break # no more input
        else:
            # ... do something with `line` here

            # feed input to pipe
            try:
                print(line, file=pipe)
            except BrokenPipeError:
                break # can't write to pipe anymore
            except OSError as e:
                if e.errno == errno.EINVAL:
                    break  # same as EPIPE on Windows
                else:
                    raise # allow the error to propagate

    try:
        pipe.close() # inform subprocess -- no more input
    except OSError:
        pass # ignore

with Popen(["java", "-jar", "minecraft_server.jar"],
           cwd=r'C:\Users\Derek\Desktop\server',
           stdin=PIPE, stdout=PIPE, bufsize=1) as p, \
     TextIOWrapper(p.stdin, encoding='utf-8',
                   write_through=True, line_buffering=True) as text_input:
    Thread(target=feed, args=[text_input], daemon=True).start()
    for line in TextIOWrapper(p.stdout, encoding='utf-8'):
        # ... do something with `line` here
        print(line, end='')

rawDescription: Python blockless subproccess input with constant output on Windows


code:
import urllib
from xml.etree.ElementTree import parse
from bs4 import BeautifulSoup as bs

# Download the RSS feed and parse it
u = urllib.urlopen('http://planet.python.org/rss20.xml')
doc = parse(u)

# Extract and output tags of interest
for item in doc.iterfind('channel/item'):
    des = item.findtext('description')
    if des:
        soup = bs(des)
        text = soup.get_text()
        print(text.encode('utf-8'))

rawDescription: how to skip <p> <h2 > <a......> while getting data

description: Skip <p> <h2 > <a......> while getting data


code:
# method for communicating with an exchange calendar to see if a person has
# a current appointment marking them as unreachable (i.e. on vacation, out
# sick, attending an all-day offsite meeting, etc).

import datetime
import time
import httplib
import urllib
import base64
import xml.dom.minidom

def is_available(email_address, timestamp):
    '''Query the calendar and see if this person is available at the
    given time.'''

    # assume they are available
    available = True

    # this is a template for the SOAP command which queries the calendar.
    # Address, StartTime and EndTime will be filled in later
    soapTemplate = '''
    <?xml version="1.0" encoding="utf-8"?>
    <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                   xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
      <soap:Body>
        <GetUserAvailabilityRequest xmlns="http://schemas.microsoft.com/exchange/services/2006/messages">
          <TimeZone xmlns="http://schemas.microsoft.com/exchange/services/2006/types">
            <Bias>360</Bias>
            <StandardTime>
              <Bias>0</Bias>
              <Time>02:00:00</Time>
              <DayOrder>1</DayOrder>
              <Month>11</Month>
              <DayOfWeek>Sunday</DayOfWeek>
            </StandardTime>
            <DaylightTime>
              <Bias>-60</Bias>
              <Time>02:00:00</Time>
              <DayOrder>2</DayOrder>
              <Month>3</Month>
              <DayOfWeek>Sunday</DayOfWeek>
            </DaylightTime>
          </TimeZone>
          <MailboxDataArray>
            <MailboxData xmlns="http://schemas.microsoft.com/exchange/services/2006/types">
              <Email>
                <Address>%s</Address>
              </Email>
              <AttendeeType>Required</AttendeeType>
            </MailboxData>
          </MailboxDataArray>
          <FreeBusyViewOptions xmlns="http://schemas.microsoft.com/exchange/services/2006/types">
            <TimeWindow>
              <StartTime>%s</StartTime>
              <EndTime>%s</EndTime>
            </TimeWindow>
            <MergedFreeBusyIntervalInMinutes>5</MergedFreeBusyIntervalInMinutes>
            <RequestedView>FreeBusy</RequestedView>
          </FreeBusyViewOptions>
        </GetUserAvailabilityRequest>
      </soap:Body>
    </soap:Envelope>
    '''.strip()

    # get a SOAP-compatible representation of the given timestamp, and
    # another timestamp for five minutes later.  (the Exchange server
    # requires that the two timestamps be at least five minutes apart.)
    startTime = soap_time(timestamp)
    fiveMinuteDelta = datetime.timedelta(minutes=5)
    endTime = soap_time(timestamp + fiveMinuteDelta)

    # fill in the soap template with times and email address
    soapMessage = soapTemplate % (email_address, startTime, endTime)

    # get the server response as a string
    soapResponse = soap_query(soapMessage)

    # parse the string into an xml node tree structure
    xmldoc = xml.dom.minidom.parseString(soapResponse)

    # do we have a root <Envelope> element?
    root = xmldoc.childNodes[0]
    if root.localName.lower() != 'envelope':
        # punt
        return available

    node = root

    # traverse the xml document, looking for this series of nodes
    element_names = ['body', 'GetUserAvailabilityResponse',
        'FreeBusyResponseArray', 'FreeBusyResponse', 'ResponseMessage']

    for element_name in element_names:
        new_node = find_node(node, element_name)
        if not new_node:
            return available
        node = new_node

    # see if we got a 'success' or 'error' response

    successResponse = False
    errorResponse   = False

    attribs = node.attributes
    for i in range(attribs.length):
        if attribs.item(i).name.lower() == 'responseclass':
            if attribs.item(i).value.lower() == 'success':
                successResponse = True
            elif attribs.item(i).value.lower() == 'error':
                errorResponse = True

    if not successResponse:
        return available

    # since we got a success response, keep traversing
    element_names = ['freeBusyView', 'CalendarEventArray']

    for element_name in element_names:
        new_node = find_node(node, element_name)
        if not new_node:
            return available
        node = new_node

    for item in node.childNodes:
        if item.localName and item.localName.lower() == 'calendarevent':
            for child in item.childNodes:
                if child.localName and child.localName.lower() == 'busytype':
                    if child.childNodes[0].nodeValue.lower() == 'oof':
                        # hallelujah!
                        available = False
                        break

    return available

def soap_query(message):
    '''Send the message to the calendar server and return the response.'''

    host = 'exchange.yourcompany.com' # your calendar server host name
    uri = '/EWS/Exchange.asmx' # your calendar uri
    username = 'foobar' # your calendar user name
    password = 'bazbaz' # your calendar password

    auth = base64.encodestring(username + ':' + password).strip()

    headers = { 'Authorization': 'Basic %s' % auth,
                'Content-type' : 'text/xml; charset="utf-8"',
                'User-Agent'   : 'python' }

    # make the connection
    conn = httplib.HTTPSConnection(host)

    # send the request
    conn.request('POST', uri, message, headers)

    # get the response
    resp = conn.getresponse()

    # get the various parts of the response
    body    = resp.read()
    headers = resp.msg
    version = resp.version
    status  = resp.status
    reason  = resp.reason

    conn.close()

    return body

def soap_time(timestamp):
    '''Return the timestamp as a SOAP-compatible time string.'''

    return timestamp.strftime('%Y-%m-%dT%H:%M:%S')

def find_node(node, name):
    '''Return the first child node with the given name, or return None
    if no children exist by that name.'''

    for child in node.childNodes:
        if child.localName:
            if child.localName.lower() == name.lower():
                return child

    return None

rawDescription: How to get free/busy status for a list of users on outlook (and how to get a list of users)?

description: Get free/busy status for a list of users on outlook (and how to get a list of users)


code:
def __init__(self, *args, **kwargs):
    self.instance = kwargs.pop('instance', None)

    super(CityForm, self).__init__(*args, **kwargs)

    if self.instance:
        self.initial['post_nr'] = self.instance.post_code
        self.initial['city'] = self.instance.name

rawDescription: How override __init__ add instance forms.Form Django


code:
cookie = {'steamLogin': '76561198058933558%7C%7C2553658936E891AAD'}
data = requests.get('http://steamcommunity.com/market/pricehistory/?country=PT&currency=3&appid=730&market_hash_name=Falchion%20Case', cookies=cookie);

rawDescription: How to retrieve steam market price history?

description: Retrieve steam market price history


code: {k: {8: v[8]} for k, v in data_dict.items() if 8 in v}

rawDescription: Python nested dictionary comprehension returns empty dictionaries


code:
with open(infile) as f:
    lines = [line.split()for line in f]
    print(lines)
[['In', 'the', "Grimms'", 'version', 'at', 'least,', 'she', 'had', 'the', 'order', 'from', 'her', 'mother', 'to', 'stay', 'strictly', 'on', 'the', 'path.'], ['A', 'mean', 'wolf', 'wants', 'to', 'eat', 'the', 'girl', 'and', 'the', 'food', 'in', 'the', 'basket.'], [], ['He', 'secretly', 'stalks', 'her', 'behind', 'trees', 'and', 'bushes', 'and', 'shrubs', 'and', 'patches', 'of', 'little', 'grass', 'and', 'patches', 'of', 'tall', 'grass.'], [], ['Then', 'the', 'girl', 'arrives,', 'she', 'notices', 'that', 'her', 'grandmother', 'looks', 'very', 'strange.', 'Little', 'Red', 'then', 'says,', '"What', 'a', 'deep', 'voice', 'you', 'have!"', '("The', 'better', 'to', 'greet', 'you', 'with"),', '"Goodness,', 'what', 'big', 'eyes', 'you', 'have!"']]

rawDescription: reading a text with blank lines in Python

description: Reading a text with blank lines in Python


code:
type(_)
1
type(_)
type(_)

rawDescription: Type of an underscore character in Python


rawDescription: How do I get the correct regex for this string?

description: Get the correct regex for this string


code:
import os, re, Levenshtein as lev, codecs
from SimpleQuiz.quiz.models import Choice, Question
from django.core.management.base import BaseCommand, CommandError
import optparse

class Command(BaseCommand):
    args = '--datapath=/path/to/text/data/'
    can_import_settings = True
    help = 'Imports scanned text into Questions and Choices'
    option_list = BaseCommand.option_list + (
        optparse.make_option('--datapath', action='store', type='string',
                             dest='datapath',
                             help='Path to OCRd text files to be parsed.'),
        )
    requires_model_validation = True
    # Parser REs
    BACKUP_RE = re.compile(r'\~$|bak$|back$|backup$')
    QUEST_RE = re.compile(r'^[0-9]{1,3}[.][ ]')
    CHOICE_RE = re.compile(r'^[a-e][.][ ]')

    def handle(self, *args, **options):
        # get the data path
        try:
            os.path.exists(options['datapath'])
        except Exception as e:
            raise CommandError("None or invalid path provided: %s" % e.message)
        self.datapath = os.path.expanduser(options['datapath'])

        # generate list of text strings from lines in target files
        self.data_lines = []
        for fn in os.listdir(os.path.join(self.datapath, 'questions/')):
            if self.BACKUP_RE.search(fn):
                self.stderr.write("Skipping backup: %s\n" % (fn))
            else:
                for line in codecs.open(os.path.join(self.datapath, 'questions/', fn), 'r', encoding='latin-1'):
                    if not self.is_boilerplate(line):
                        if not line.strip() == '':
                            self.data_lines.append(line)

    #-----------------------------------------------------------------------
    #--------------------- Parse the text lines and create Questions/Choices
    #-----------------------------------------------------------------------
        cur_quest = None
        cur_choice = None
        cur_is_quest = False
        questions = {}
        choices = {}
        for line in self.data_lines:
            if self.is_question(line):
                [n, txt] = line.split('.', 1)
                qtext = txt.rstrip() + " "
                q = Question.objects.create(text=qtext)
                q.save()
                cur_quest = q.pk
                questions[cur_quest] = q
                cur_is_quest = True
            elif self.is_choice(line):
                [n, txt] = line.split('.', 1)
                num = self.char2dig(n)
                ctext = txt.rstrip() + " "
                c = Choice.objects.create(text=ctext, order=num, question=questions[cur_quest])
                c.save()
                cur_choice = c.pk
                choices[cur_choice] = c
                cur_is_quest = False
            else:
                if cur_is_quest:
                    questions[cur_quest].text += line.rstrip() + " "
                    questions[cur_quest].save()
                else:
                    choices[cur_choice].text += line.rstrip() + " "
                    choices[cur_choice].save()
        self.stdout.write("----- FINISHED -----\n")
        return None

    def is_question(self, arg_str):
        if self.QUEST_RE.search(arg_str):
            return True
        else:
            return False

    def is_choice(self, arg_str):
        if self.CHOICE_RE.search(arg_str):
            return True
        else:
            return False

    def char2dig(self, x):
        if x == 'a':
            return 1
        if x == 'b':
            return 2
        if x == 'c':
            return 3
        if x == 'd':
            return 4
        if x == 'e':
            return 5

    def is_boilerplate(self, arg_str):
        boilerplate = [u'MFT PRACTICE EXAMINATIONS',
                       u'BERKELEY TRAINING ASSOCIATES ' + u'\u00A9' + u' 2009',
                       u'BERKELEY TRAINING ASSOCIATES',
                       u'MARRIAGE AND FAMILY THERAPY',
                       u'PRACTICE EXAMINATION 41',
                       u'Page 0', u'Page 1', u'Page 2', u'Page 3', u'Page 4',
                       u'Page 5', u'Page 6', u'Page 7', u'Page 8', u'Page 9',
                       ]
        for bp in boilerplate:
            if lev.distance(bp.encode('utf-8'), arg_str.encode('utf-8')) < 4:
                return True
        return False

rawDescription: How to import data from scanned text into Django models

description: Import data from scanned text into Django models


code: df.loc[df['Project ID'] == 'Project2', 'Cost'].values

rawDescription: Selecting data in Pandas based on a condition