code:
from itertools import product
# define W, X, Y, Z...
menus = [
    {'fruit': fruit, 'food': food, 'vegetable': vegetable, 'drink': drink}
    for fruit, food, vegetable, drink in product(W, X, Y, Z)
]

rawDescription: Python: How to get these lists transformed in a dictionary?


code:
import paramiko
import socket
import os
from stat import S_ISDIR

class SSHSession(object):
    # Usage:
    # Detects DSA or RSA from key_file, either as a string filename or a
    # file object.  Password auth is possible, but I will judge you for
    # using it. So:
    # ssh=SSHSession('targetserver.com','root',key_file=open('mykey.pem','r'))
    # ssh=SSHSession('targetserver.com','root',key_file='/home/me/mykey.pem')
    # ssh=SSHSession('targetserver.com','root','mypassword')
    # ssh.put('filename','/remote/file/destination/path')
    # ssh.put_all('/path/to/local/source/dir','/path/to/remote/destination')
    # ssh.get_all('/path/to/remote/source/dir','/path/to/local/destination')
    # ssh.command('echo "Command to execute"')

    def __init__(self,hostname,username='root',key_file=None,password=None):
        #
        #  Accepts a file-like object (anything with a readlines() function)
        #  in either dss_key or rsa_key with a private key.  Since I don't
        #  ever intend to leave a server open to a password auth.
        #
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.sock.connect((hostname,22))
        self.t = paramiko.Transport(self.sock)
        self.t.start_client()
        keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
        key = self.t.get_remote_server_key()
        # supposed to check for key in keys, but I don't much care right now to find the right notation
        if key_file is not None:
            if isinstance(key,str):
                key_file=open(key,'r')
            key_head=key_file.readline()
            key_file.seek(0)
            if 'DSA' in key_head:
                keytype=paramiko.DSSKey
            elif 'RSA' in key_head:
                keytype=paramiko.RSAKey
            else:
                raise Exception("Can't identify key type")
            pkey=keytype.from_private_key(key_file)
            self.t.auth_publickey(username, pkey)
        else:
            if password is not None:
                self.t.auth_password(username,password,fallback=False)
            else: raise Exception('Must supply either key_file or password')
        self.sftp=paramiko.SFTPClient.from_transport(self.t)

    def command(self,cmd):
        #  Breaks the command by lines, sends and receives
        #  each line and its output separately
        #
        #  Returns the server response text as a string

        chan = self.t.open_session()
        chan.get_pty()
        chan.invoke_shell()
        chan.settimeout(20.0)
        ret=''
        try:
            ret+=chan.recv(1024)
        except:
            chan.send('\n')
            ret+=chan.recv(1024)
        for line in cmd.split('\n'):
            chan.send(line.strip() + '\n')
            ret+=chan.recv(1024)
        return ret

    def put(self,localfile,remotefile):
        #  Copy localfile to remotefile, overwriting or creating as needed.
        self.sftp.put(localfile,remotefile)

    def put_all(self,localpath,remotepath):
        #  recursively upload a full directory
        os.chdir(os.path.split(localpath)[0])
        parent=os.path.split(localpath)[1]
        for walker in os.walk(parent):
            try:
                self.sftp.mkdir(os.path.join(remotepath,walker[0]))
            except:
                pass
            for file in walker[2]:
                self.put(os.path.join(walker[0],file),os.path.join(remotepath,walker[0],file))

    def get(self,remotefile,localfile):
        #  Copy remotefile to localfile, overwriting or creating as needed.
        self.sftp.get(remotefile,localfile)

    def sftp_walk(self,remotepath):
        # Kindof a stripped down  version of os.walk, implemented for
        # sftp.  Tried running it flat without the yields, but it really
        # chokes on big directories.
        path=remotepath
        files=[]
        folders=[]
        for f in self.sftp.listdir_attr(remotepath):
            if S_ISDIR(f.st_mode):
                folders.append(f.filename)
            else:
                files.append(f.filename)
        print (path,folders,files)
        yield path,folders,files
        for folder in folders:
            new_path=os.path.join(remotepath,folder)
            for x in self.sftp_walk(new_path):
                yield x

    def get_all(self,remotepath,localpath):
        #  recursively download a full directory
        #  Harder than it sounded at first, since paramiko won't walk
        #
        # For the record, something like this would gennerally be faster:
        # ssh user@host 'tar -cz /source/folder' | tar -xz

        self.sftp.chdir(os.path.split(remotepath)[0])
        parent=os.path.split(remotepath)[1]
        try:
            os.mkdir(localpath)
        except:
            pass
        for walker in self.sftp_walk(parent):
            try:
                os.mkdir(os.path.join(localpath,walker[0]))
            except:
                pass
            for file in walker[2]:
                self.get(os.path.join(walker[0],file),os.path.join(localpath,walker[0],file))
    def write_command(self,text,remotefile):
        #  Writes text to remotefile, and makes remotefile executable.
        #  This is perhaps a bit niche, but I was thinking I needed it.
        #  For the record, I was incorrect.
        self.sftp.open(remotefile,'w').write(text)
        self.sftp.chmod(remotefile,755)

rawDescription: paramiko recursive directory copy python

description: Paramiko recursive directory copy python


code: c.sort(key=lambda x: getattr(x, 'creation_time', None) or getattr(x, 'creation_date', None))

rawDescription: Sort list of different model objects by different fields


code:
class MyArgumentParser(argparse.ArgumentParser):
    def parse_subargs(self, *args, **kw):
        # parse as usual
        args = argparse.ArgumentParser.parse_args(self, *args, **kw)

        # extract the destination names for top-level arguments
        topdest = [action.dest for action in parser._actions]

        # loop over all arguments given in args
        subargs = {}
        for key, value in args.__dict__.items():

            # if sub-parser argument found ...
            if key not in topdest:

                # ... remove from args and add to dictionary
                delattr(args,key)
                subargs[key] = value

        return args, subargs

rawDescription: How to have sub-parser arguments in separate namespace with argparse?

description: Have sub-parser arguments in separate namespace with argparse


code:
class Foo(object):
    def __new__(cls, value=True):
        if cls != Foo:
            return super(Foo, cls).__new__(cls)
        elif value:
            return super(Foo, cls).__new__(Bar)
        else:
            return super(Foo, cls).__new__(Zoo)

class Bar(Foo):
    pass

class Zoo(Foo):
    pass

z = Foo(True)  # instance of Bar() class

rawDescription: Change self of parent class to subClass

description: Change self of parent class to subClass


code:
from cStringIO import StringIO

img_string = png_print_formatter(weblogoData, weblogoFormat)
fake_file = StringIO(img_string)
plt.imread(fake_file)

rawDescription: Plot png file encoded as string without saving to file


code:
r.replace('7E21', '9E21')

file = open('YAC.IN', 'w')
file.write(r)
file.close()

rawDescription: Change values in Python file (tab-delimited list)


code:
img=cv2.imread("img.bmp")
img_hsv=cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# lower mask (0-10)
lower_red = np.array([0,50,50])
upper_red = np.array([10,255,255])
mask0 = cv2.inRange(img_hsv, lower_red, upper_red)

# upper mask (170-180)
lower_red = np.array([170,50,50])
upper_red = np.array([180,255,255])
mask1 = cv2.inRange(img_hsv, lower_red, upper_red)

# join my masks
mask = mask0+mask1

# set my output img to zero everywhere except my mask
output_img = img.copy()
output_img[np.where(mask==0)] = 0

# or your HSV image, which I *believe* is what you want
output_hsv = img_hsv.copy()
output_hsv[np.where(mask==0)] = 0

rawDescription: Finding red color using Python & OpenCV

description: Finding red color using Python & OpenCV


code:
...
tkMessageBox.showwarning("Danger, Will Robinson!",
                         parent=self.destruct_button)
...

rawDescription: Tkinter, tkmessagebox keeps sending me to the root


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

d = np.ones((100, 100, 4), dtype=np.uint8)*255
d[:, :, 3] = np.linspace(0, 255, num=100)
plt.imshow(d, interpolation='none')
plt.show()

rawDescription: How does imshow handle the alpha channel with an M x N x 4 input?


code:
def readMatrix(file):
    with open(file) as contents:
        return [[int(item) for item in line.split()] for line in contents]

rawDescription: Trying to use list comprehension to convert list of strings to integers?


code:
class Messages(ListResource):
    name = "Messages"
    key = "messages"
    instance = Message

    def create(self, from_=None, **kwargs):
        """
        Create and send a Message.

        :param str to: The destination phone number.
        :param str `from_`: The phone number sending this message
            (must be a verified Twilio number)
        :param str body: The message you want to send,
            limited to 1600 characters.
        :param list media_url: A list of URLs of images to include in the
            message.
        :param status_callback: A URL that Twilio will POST to when
            your message is processed.
        :param str application_sid: The 34 character sid of the application
            Twilio should use to handle this phone call.
        """
        kwargs["from"] = from_
        return self.create_instance(kwargs)

rawDescription: twilio API: Make a function sending SMSs with python

description: Twilio API: Make a function sending SMSs with python


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

df = pd.read_csv('data.csv', sep=None, names=('Datetime', 'values'),
                 parse_dates=['Datetime'])

fig = plt.figure(figsize=(12,5))
ax = plt.subplot(111)
plt.plot(df['Datetime'], df['values'], color = 'green' )
years = mdates.YearLocator()
months = mdates.MonthLocator()
yearsFmt = mdates.DateFormatter('%Y')
monthsFmt = mdates.DateFormatter('%b')
ax.xaxis.set_major_locator(years)
ax.xaxis.set_major_formatter(yearsFmt)
ax.xaxis.set_minor_formatter(monthsFmt)
ax.xaxis.set_minor_locator(months)
ax.grid(which='both', axis='x')
for tick in ax.get_xaxis().get_major_ticks():
    tick.set_pad(15)
plt.show()

rawDescription: Missing default matplotlib labels with matplotlib.dates


code:
rs = (grequests.get(u) for u in urls)
for response in grequests.map(rs):
    print('{}: {}'.format(response.url, len(response.content)))

rawDescription: Python Grequests xml responses

description: Python Grequests xml responses


rawDescription: Split a string (on whitespace or punctuation) to get all numbers


code:
# load OpenSSL.crypto
from OpenSSL import crypto

# open it, using password. Supply/read your own from stdin.
p12 = crypto.load_pkcs12(open("/path/to/cert.p12", 'rb').read(), passwd)

# get various properties of said file.
# note these are PyOpenSSL objects, not strings although you
# can convert them to PEM-encoded strings.
p12.get_certificate()     # (signed) certificate object
p12.get_privatekey()      # private key.
p12.get_ca_certificates() # ca chain.

rawDescription: Python: reading a pkcs12 certificate with pyOpenSSL.crypto


code:
def __init__(self, *args, **kwargs):
    super(Fruit, self).__init__(*args, **kwargs)

    # The attribute name was changed in Python 3; pick whichever line matches
    # your Python version.
    callback = self.print_callback.im_func  # Python 2
    callback = self.print_callback.__func__ # Python 3

    callback("Message from Fruit: ")

rawDescription: Writing a class that accepts a callback in Python?


code: option1 = tkinter.Button(opt1, wraplength=80, justify=LEFT, text='This is the text')

rawDescription: multi line Tkinter button?

description: Multi line Tkinter button


code:
from pylab import *

figure()
plot(arange(5))
ax = gca()
ax.yaxis.tick_right()
ax.yaxis.set_ticks_position('both')

rawDescription: Restore left ticks in matplotlib

description: Restore left ticks in matplotlib


code:
class Locale(Action):
    def __init__(self, loc, **kwargs):
        super().__init__(**kwargs)
    def __call__(self, parser, namespace, value= False, option_string= None):
        l= getenv("LANG", "en")[0:2].lower()
        if l != "en":
            if path.isdir(path.join(namespace.dir, l)):
                value= path.join(namespace.dir, l)
            else:
                parser.error("%s %s" % (option_string, "directory not found or $LANG not valid"))
        namespace.loc= value

def parsing():
    parser= ArgumentParser("")
    parser.add_argument("-dir", type= directory, action= "store", default= "/home")
    parser.add_argument("-loc", action= Locale, loc= None, nargs= "?", default= False)
    namespace, other= parser.parse_known_args()
    return namespace, other

rawDescription: Validate an argument over another

description: Validate an argument over another


code:
from django import db

def subprocess_task():
    db.close_connection()

rawDescription: Python multiprocessing: DB connection not available


code:
def change(obj):
    obj.x = 10
class Point(object): x,y = 0,0
p = Point()
p.x
change(p)
p.x

rawDescription: How to pass values by ref in Python?

description: Pass values by ref in Python


code:
l = [ f._raw_value('type') for f in formset_sample.forms ]
l.count('2') # I am assuming 2 is a string, or
l.count(2)   # if the number is stored as an integer

rawDescription: Python - How to count occurrences of a number inside of an object?


code:
dict1 = {"good authors": {"john" : {}, "jack" : {}}, "average authors" : {"kim" : {}, "peter" : {}} }
dict2 = {"john" : [{"2008" : "book1"}, {"2009" : "book2"}], "peter" : [{"2008" : "book3"}, {"2009" : "book4"}]}
for key, value in dict1.items():
    for dict2key, dict2value in dict2.items():
        if dict2key in value:
            value[dict2key] = dict2value
dict2

rawDescription: adding dict2 to dict1 in python

description: Adding dict2 to dict1 in python


code:
def homogeneous_lines (file_name):
    with open(file_name) as fd:
        for line in fd:
            if line.islower() or line.isupper():
                yield line

rawDescription: Read all lines in .txt that are all upper or all lower case Python 2.7.1?


code:
resources = [file_obj
             for file_obj in (obj.get("file") for obj in iterator)
             if file_obj is not None]

rawDescription: Caching values in Python list comprehensions


rawDescription: Non-recursive os.walk()

description: Non-recursive os.walk()


code: myfunc(*mylist)

rawDescription: passing one list of values instead of mutiple arguments to a function?

description: Passing one list of values instead of mutiple arguments to a function


code:
import csv

data = {}
with open("myfile", "rb") as f:
    reader = csv.DictReader(f)
    for row in reader:
        d = data.setdefault(row["system"], {})
        # Here, you may want to handle invalid values in the version field
        d[row["component"]] = int(row["version"])

rawDescription: python how to iterate cells in the same column in a CSV file?

description: Python how to iterate cells in the same column in a CSV file


code:
import importlib.machinery

modulename = importlib.machinery.SourceFileLoader('modulename','/Path/To/module.py').load_module()

rawDescription: Python 3.4: How to import a module given the full path?


code:
import types

class A:
    def meth1(self, par1):
        print("in A.meth1: par1 =", par1)

a = A()
s = '''def meth1(self, par1):
    print("in recompiled A.meth1: par1 = ", par1)'''

code = compile(s, __file__, "exec")

environment = {}
exec(code, environment)
a.meth1 = types.MethodType(environment["meth1"], A)

a.meth1("via meth1")

rawDescription: How to compile a function at run-time?

description: Compile a function at run-time


code:
import cairo

def text_extent(font, font_size, text, *args, **kwargs):
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0)
    ctx = cairo.Context(surface)
    ctx.select_font_face(font, *args, **kwargs)
    ctx.set_font_size(font_size)
    return ctx.text_extents(text)

text='Example'
font="Sans"
font_size=55.0
font_args=[cairo.FONT_SLANT_NORMAL]
(x_bearing, y_bearing, text_width, text_height,
 x_advance, y_advance) = text_extent(font, font_size, text, *font_args)
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(text_width), int(text_height))
ctx = cairo.Context(surface)
ctx.select_font_face(font, *font_args)
ctx.set_font_size(font_size)
ctx.move_to(-x_bearing, -y_bearing)
ctx.text_path(text)
ctx.set_source_rgb(0.47, 0.47, 0.47)
ctx.fill_preserve()
ctx.set_source_rgb(1, 0, 0)
ctx.set_line_width(1.5)
ctx.stroke()

surface.write_to_png("/tmp/out.png")

rawDescription: How can I draw text with different stroke and fill colors on images with python?

description: Draw text with different stroke and fill colors on images with python


code:
import Tkinter as Tk #tkinter

def toggle():
    if frame1.winfo_ismapped():
        frame1.grid_remove()
    else:
        frame1.grid()

root = Tk.Tk()
root.geometry('-450+250')
frame1 = Tk.Frame(root, width=200, height=100, bg='red')
frame1.grid(row=0, column=0)
frame2 = Tk.Frame(root, width=200, height=100, bg='blue')
frame2.grid(row=0, column=1)
Tk.Button(root, text='toggle', command=toggle).grid(row=1, column=1)

root.mainloop()

rawDescription: Resize Tkinter Window FROM THE RIGHT (python)


code:
new_files = [] #list of files newer than 1 day
for f in os.listdir(path):
   fn = os.path.join(path,f)
   ctime = os.stat(fn).st_ctime
   if ctime > now - 1 * 86400:
        countit=new_files.count(fn)  #count previous occurence
        #this is a new file
        new_files.append(fn)
        if new_files.count(fn)>countit:
             sendmail #calls sendmail script that sends email

rawDescription: Checking if list was appended before sending email


code: self.rules[a] = [{b:{'f_expr': c, 'c_expr': d}}]

rawDescription: List of dictionaries, in a dictionary - in Python


code:
cluster_count = np.max(clusters)+1
doc_freq = np.zeros((cluster_count, dataset.shape[1]), dtype=dataset.dtype)
for j in xrange(cluster_count):
    doc_freq[j] = np.sum(dataset[clusters == j], axis=0)

doc_freq

rawDescription: Numpy array filtering by two criteria

description: Numpy array filtering by two criteria


code:
def f(x): return -2 * x**2 + 4 * x
max_x = scipy.optimize.fmin(lambda x: -f(x), 0)
# array([ 1.])

rawDescription: Finding the maximum of a function

description: Finding the maximum of a function


code: gurl = 'http://toolbarqueries.google.com/tbr?client=navclient-auto&ch=%s&features=Rank&q=info:%s' % (hsh,urllib.quote(URL))

rawDescription: Pagerank for locally stored google search results


code:
#Import the required modules
from twython import Twython
import json
import csv

#Set parameters
keyword = 'kittens'; #The desired keyword(s)
tweetsXiteration = 100; #Where 100 is the max
dateFrom = '2014-02-01'; #Inclusive (YYYY-MM-DD)
dateTo = '2014-02-02'; #Exclusive (YYYY-MM-DD)
done = False; #Must be false

#Setting the OAuth
Consumer_Key = 'XXX';
Consumer_Secret = 'XXX';
Access_Token = 'XXX';
Access_Token_Secret = 'XXX';

#Connection established with Twitter API v1.1
twitter = Twython(Consumer_Key, Consumer_Secret, Access_Token, Access_Token_Secret);

#Twitter is queried
response = twitter.search(q = keyword, count = tweetsXiteration, since = dateFrom, until = dateTo, result_type = 'mixed');

#Results (partial)
countTweets = len(response['statuses']);

#If all the tweets have been fetched, then we are done
if not ('next_results' in response['search_metadata']):
    done = True;

#If not all the tweets have been fetched, then...
while (done == False):

    #Parsing information for maxID
    parse1 = response['search_metadata']['next_results'].split("&");
    parse2 = parse1[0].split("?max_id=");
    parse3 = parse2[1];
    maxID = parse3;

    #Twitter is queried (again, this time with the addition of 'max_id')
    response = twitter.search(q = keyword, count = tweetsXiteration, since = dateFrom, until = dateTo, max_id = maxID, include_entities = 1, result_type = 'mixed');

    #Updating the total amount of tweets fetched
    countTweets = countTweets + len(response['statuses']);

    #If all the tweets have been fetched, then we are done
    if not ('next_results' in response['search_metadata']):
        done = True;

print(countTweets);

rawDescription: Count number of results for a particular word on Twitter (API v1.1)


code:
class AdvertModel(ndb.Model):
    daily_used = ndb.FloatProperty()
    daily_budget = ndb.FloatProperty()
    in_money = ndb.ComputedProperty(lambda self: self.daily_used < self.daily_budget)

rawDescription: Is the following possible with ndb: query(AdModel.daily_used < AdModel.daily_budget)


code:
try:
    os.rename('/etc/foo', '/etc/bar')
except IOError as e:
    if (e[0] == errno.EPERM):
       print >> sys.stderr, "You need root permissions to do this, laterz!"
       sys.exit(1)

rawDescription: What is the best practices for checking if the user of a Python script has root-like privileges?


code:
re.split(' OR | AND ', 'word1 AND word2 word3 OR "word4 word5" OR word6 AND word7 word8')
['word1', 'word2 word3', '"word4 word5"', 'word6', 'word7 word8']

rawDescription: Python Regexp: find all words/phrases within a querystring containing OR and AND


code:
import crypt # Interface to crypt(3), to encrypt passwords.
import getpass # To get a password from user input.
import spwd # Shadow password database (to read /etc/shadow).

def login(user, password):
    """Tries to authenticate a user.
    Returns True if the authentication succeeds, else the reason
    (string) is returned."""
    try:
        enc_pwd = spwd.getspnam(user)[1]
        if enc_pwd in ["NP", "!", "", None]:
            return "user '%s' has no password set" % user
        if enc_pwd in ["LK", "*"]:
            return "account is locked"
        if enc_pwd == "!!":
            return "password has expired"
        # Encryption happens here, the hash is stripped from the
        # enc_pwd and the algorithm id and salt are used to encrypt
        # the password.
        if crypt.crypt(password, enc_pwd) == enc_pwd:
            return True
        else:
            return "incorrect password"
    except KeyError:
        return "user '%s' not found" % user
    return "unknown error"

if __name__ == "__main__":
    username = raw_input("Username:")
    password = getpass.getpass()
    status = login(username, password)
    if status == True:
        print("Logged in!")
    else:
        print("Login failed, %s." % status)

rawDescription: Python Enter Password And Compare to Shadowed Password Database


code: old = {change.get(k,k):v for k,v in old.items()}

rawDescription: Rename dictionary keys according to another dictionary


code:
import json
import tkinter as tk
from tkinter import ttk
from pprint import pprint as pprint

# opt_name: (from_, to, increment)
IntOptions = {
    'age': (1.0, 200.0, 1.0),
}

def close_ed(parent, edwin):
    parent.focus_set()
    edwin.destroy()

def set_cell(edwin, w, tvar):
    value = tvar.get()
    w.item(w.focus(), values=(value,))
    close_ed(w, edwin)

def edit_cell(e):
    w = e.widget
    if w and len(w.item(w.focus(), 'values')) > 0:
        edwin = tk.Toplevel(e.widget)
        edwin.protocol("WM_DELETE_WINDOW", lambda: close_ed(w, edwin))
        edwin.grab_set()
        edwin.overrideredirect(1)
        opt_name = w.focus()
        (x, y, width, height) = w.bbox(opt_name, 'Values')
        edwin.geometry('%dx%d+%d+%d' % (width, height, w.winfo_rootx() + x, w.winfo_rooty() + y))
        value = w.item(opt_name, 'values')[0]
        tvar = tk.StringVar()
        tvar.set(str(value))
        ed = None
        if opt_name in IntOptions:
            constraints = IntOptions[opt_name]
            ed = tk.Spinbox(edwin, from_=constraints[0], to=constraints[1],
                increment=constraints[2], textvariable=tvar)
        else:
            ed = tk.Entry(edwin, textvariable=tvar)
        if ed:
            ed.config(background='LightYellow')
            #ed.grid(column=0, row=0, sticky=(tk.N, tk.S, tk.W, tk.E))
            ed.pack()
            ed.focus_set()
        edwin.bind('<Return>', lambda e: set_cell(edwin, w, tvar))
        edwin.bind('<Escape>', lambda e: close_ed(w, edwin))

def JSONTree(Tree, Parent, Dictionery, TagList=[]):
    for key in Dictionery :
        if isinstance(Dictionery[key], dict):
            Tree.insert(Parent, 'end', key, text=key)
            TagList.append(key)
            JSONTree(Tree, key, Dictionery[key], TagList)
            pprint(TagList)
        elif isinstance(Dictionery[key], list):
            Tree.insert(Parent, 'end', key, text=key) # Still working on this
        else:
            Tree.insert(Parent, 'end', key, text=key, value=Dictionery[key])

if __name__ == "__main__" :
    # Setup the root UI
    root = tk.Tk()
    root.title("JSON editor")
    root.columnconfigure(0, weight=1)
    root.rowconfigure(0, weight=1)
    # Setup Data
    Data = {
        "firstName": "John",
        "lastName": "Smith",
        "gender": "man",
        "age": 32,
        "address": {
            "streetAddress": "21 2nd Street",
            "city": "New York",
            "state": "NY",
            "postalCode": "10021"},
        "phoneNumbers": [
            { "type": "home", "number": "212 555-1234" },
            { "type": "fax", "number": "646 555-4567" },
        ]}
    # Setup the Frames
    TreeFrame = ttk.Frame(root, padding="3")
    TreeFrame.grid(row=0, column=0, sticky=tk.NSEW)
    # Setup the Tree
    tree = ttk.Treeview(TreeFrame, columns=('Values'))
    tree.column('Values', width=100, anchor='center')
    tree.heading('Values', text='Values')
    tree.bind('<Double-1>', edit_cell)
    tree.bind('<Return>', edit_cell)
    JSONTree(tree, '', Data)
    tree.pack(fill=tk.BOTH, expand=1)
    # Limit windows minimum dimensions
    root.update_idletasks()
    root.minsize(root.winfo_reqwidth(), root.winfo_reqheight())
    root.mainloop()

rawDescription: Python : Display a Dict of Dicts using a UI Tree for the keys and any other widget for the values


code:
import re

string = 'aaaa bbbb cccc:dd eeee:ff ggg hhhh iiii:jjjj kkkk:llll:mm nnn:ooo pppp qqqq:rrr'
result = []

# split the string at each word followed by a colon
# wrap regex pattern as group so it is added to result list
parts = re.split("(\w+:)", string)

# if anything was previous to first delimitation token
# add it to results
if parts[0]:
    result.append(parts[0].strip())

# create pairs of a delimitation token and next string
# start from first delimitation token (list index 1)
groups = zip(*[parts[i+1::2] for i in range(2)])

# join each pair to one string and strip spacing
result.extend(["".join(group).strip() for group in groups])

print(result)

rawDescription: regex split at start of word ending in character

description: Regex split at start of word ending in character


code:
import operator
a = 1
operator.iadd(a, 2)
# a is still 1, because ints don't have __iadd__; iadd returned 3

b = ['a']
operator.iadd(b, ['b'])
# lists do have __iadd__, so b is now ['a', 'b']

rawDescription: How are Python in-place operator functions different than the standard operator functions?


code:
def filteriternum(seq):
    num = 0
    for item in seq:
        if not item:
            continue
        num += 1
        yield num, item

rawDescription: to perform addition operation on forloop.counter in django template

description: To perform addition operation on forloop.counter in django template


code:
import json
j = json.loads('{"one" : "1", "two" : "2", "three" : "3"}')
print(j['two'])

rawDescription: In Python, is there a way I can download all/some the image files (e.g. JPG/PNG) from a **Google Images** search result?


code:
import cv2
im = cv2.imread('1_tree_small.jpg')
im[im >= 128]= 255
im[im < 128] = 0
cv2.imwrite('out.jpg', im)

rawDescription: Adobe Photoshop-style posterization and OpenCV


code:
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
# For color mapping
import matplotlib.colors as colors
import matplotlib.cm as cmx

G=nx.Graph()
G.add_node("kind1")
G.add_node("kind2")
G.add_node("kind3")
G.add_node("kind4")
G.add_node("kind5")
G.add_node("kind6")

# You were missing the position.
pos=nx.spring_layout(G)
val_map = {'kind1': 2,'kind2': 2,'kind3': 2,'kind4': 1,'kind5':4,'kind6': 3}
#I had this list for the name corresponding t the color but different from the node name
ColorLegend = {'Obsolete': 2,'Initialisation': 1,'Draft': 4,'Release': 3}
values = [val_map.get(node, 0) for node in G.nodes()]
# Color mapping
jet = cm = plt.get_cmap('jet')
cNorm  = colors.Normalize(vmin=0, vmax=max(values))
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)

# Using a figure to use it as a parameter when calling nx.draw_networkx
f = plt.figure(1)
ax = f.add_subplot(1,1,1)
for label in ColorLegend:
    ax.plot([0],[0],color=scalarMap.to_rgba(ColorLegend[label]),label=label)

# Just fixed the color map
nx.draw_networkx(G,pos, cmap = jet, vmin=0, vmax= max(values),node_color=values,with_labels=True,ax=ax)

# Setting it to how it was looking before.
plt.axis('off')
f.set_facecolor('w')

plt.legend()

f.tight_layout()
plt.show()

rawDescription: legend in python networkx

description: Legend in python networkx


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

# fake up some data
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low), 0)

# Make the figure and axes
fig,ax = plt.subplots(1)

# Add you twin axes
ax2 = ax.twinx()

# Set the ticks to the outside on the right only
ax2.tick_params(axis='y',direction='out')

# Make sure the ticks and axes limits are shared between the left and right
ax.get_shared_y_axes().join(ax,ax2)

# basic boxplot
ax.boxplot(data)

plt.show()

rawDescription: Matplotlib tick dirrection for different sides of boxplot


code:
def _send_file_response(self, filepath):
    user_filename = '_'.join(filepath.split('/')[-2:])
    file_size = os.path.getsize(filepath)

    headers = [('Content-Disposition', 'attachment; filename=\"' + user_filename + '\"'),
               ('Content-Type', 'text/plain'),
               ('Content-Length', str(file_size))]

    from paste.fileapp import FileApp
    fapp = FileApp(filepath, headers=headers)

    return fapp(request.environ, self.start_response)

rawDescription: Stream a file to the HTTP response in Pylons


code:
a = """
!
interface blah
a
ssid test1
v
ssid test2
v
ssid test3
"""
p = r'(?<=ssid )\S+' # non-whitespace character chunk after ssid
match = re.findall(p, a)

rawDescription: Method to find word in string

description: Method to find word in string


code: self.writer.writerow([s.encode('utf-8') for s in row])

description: Self.writer.writerow([s.encode('utf-8') for s in row])


code: clientImage = np.asarray(bitmapBits, dtype=np.uint8).reshape(height, width, 4)

rawDescription: NumPy - Efficient conversion from tuple to array?


code:
maxval = max(dict.iteritems(), key=operator.itemgetter(1))[1]
keys = [k for k,v in dict.items() if v==maxval]

rawDescription: Get the Key correspond to max(value) in python dict


code:
from scipy import stats
my_noise=stats.distributions.norm.rvs(0,2,size=your_array.shape)
your_array+=my_noise

rawDescription: Adding RMS noise to an image

description: Adding RMS noise to an image


code:
count = 0
for p in getPixels(picture):
    r = getRed(p)
    b = getBlue(p)
    g = getGreen(p)
    if (r,g,b) == (0,0,0):
        count = count + 1
    return count

rawDescription: JYTHON Calculating the number of pixels in a picture


code:
def qsort(inlist):
    if inlist == []:
        return []
    else:
        pivot = inlist[0]
        lesser = qsort([x for x in inlist[1:] if x < pivot])
        greater = qsort([x for x in inlist[1:] if x >= pivot])
        return lesser + [pivot] + greater

rawDescription: Fastest way to sort in Python

description: Fastest way to sort in Python


rawDescription: Python equation solver (max and min)

description: Python equation solver (max and min)


code:
fileHandle = open('file', 'r')

for line in fileHandle:
    fields = line.split('|')

    print(fields[0]) # prints the first fields value
    print(fields[1]) # prints the second fields value

fileHandle.close()

rawDescription: Parsing a pipe delimited file in python

description: Parsing a pipe delimited file in python


code:
while True:
    name= input("What do you want the main character to be called?")
    gender = input("Are they a boy or girl?")

    if gender == "boy" or gender == "girl":
        print("Lets get on with the story.")
        break

    print("Sorry. You cant have that. Type boy or girl.")

print("Press any key to exit")
input()

rawDescription: How can I restart my python 3 script?

description: Restart my python 3 script


rawDescription: Select columns in a pandas DataFrame

description: Select columns in a pandas DataFrame


code:
reverse_lookup = defaultdict(list)
for k, v in now_playing.items():
    reverse_lookup[v].append(k)

rawDescription: Merging dictionary keys if values the same


code:
from django.utils.encoding import force_text
from django.template.defaultfilters import slugify

class UserProfile(models.Model):
    [...]
    slug = models.SlugField(blank=True, db_index=True, unique=True)

    def get_unique_slug(self, value):
        """
        Generate a valid slug for a for given string.
        """
        qs = self.__class__.objects.all()
        used = qs.values_list('slug', flat=True)
        i = 1
        baseslug = slugify(value)
        while slug in used:
            slug = '%s-%s' % (baseslug, i)
            i += 1
        return slug

    def save(self, *args, **kwargs):
        if not self.slug and self.user:
          self.slug = self.get_unique_slug(force_text(self.user.username))
        super(UserProfile, self).save(*args, **kwargs)

rawDescription: Unable to autopopulate a Django admin field using an attribute from a OneToOne relationship


rawDescription: How to get p-value from numpy.linalg.lstsq?

description: Get p-value from numpy.linalg.lstsq


code:
# Recurse and process files.
import os
import sys
from fnmatch import fnmatch
import shutil

def process(src_dir, dst_dir, pattern='*'):
    """Iterate through src_dir, processing all files that match pattern and
    store them, including their parent directories in dst_dir.
    """
    assert src_dir != dst_dir, 'Source and destination dir must differ.'
    for dirpath, dirnames, filenames in os.walk(src_dir):
        # Filter out files that match pattern only.
        filenames = filter(lambda fname: fnmatch(fname, pattern), filenames)

        if filenames:
            dir_ = os.path.join(dst_dir, dirpath)
            os.makedirs(dir_)
            for fname in filenames:
                in_fname = os.path.join(dirpath, fname)
                out_fname = os.path.join(dir_, fname)

                # At this point, the destination directory is created and you
                # have a valid input / output filename, so you'd call your
                # function to process these files.  I just copy them :D
                shutil.copyfile(in_fname, out_fname)

if __name__ == '__main__':
    process(sys.argv[1], sys.argv[2], '*.txt')

rawDescription: python write files and maintain folder structure

description: Python write files and maintain folder structure


rawDescription: How to access pandas groupby dataframe by key

description: Access pandas groupby dataframe by key


code:
import itertools

arrs = [[1,2,3], [2,3], [1]]

for x in itertools.product(*arrs):
    if len(set(x)) < len(arrs): continue
    AddAnswer(x)

rawDescription: How to form an unique collection with one element taken from each array?

description: Form an unique collection with one element taken from each array


code:
d = { '10.8.68.192': 9, '10.8.69.42': 9}
min(d, key=lambda x: (d[x], map(int, x.split('.'))))
import socket
min(d, key=lambda x: (d[x], socket.inet_aton(x)))

rawDescription: Python sorting a dictionary

description: Python sorting a dictionary


code:
import itertools

def f(n,d):

    for i in range(n):
        l = ([ range(1,d-1) for _ in range(i)] +
             [[0,d-1]] +
             [ range(d) for _ in range(n-i-1)]
            )
        for r in itertools.product(*l):
            yield r

print(list(f(4,3)))

rawDescription: Grid search over a cube/sphere in R^n

description: Grid search over a cube/sphere in R^n


code:
url = 'http://example.com:8080/testAPI/testAPIServlet'
params = {'id': '123|345.....................................|789',
          'rows': 200}
response = requests.post(url, data=params)

rawDescription: How to post a very long URL using Python - Requests module

description: Post a very long URL using Python - Requests module


code:
class MyBuild(build):
  sub_commands = [('build_clib', build.has_c_libraries),
                  ('build_ext', build.has_ext_modules),
                  ('build_py', build.has_pure_modules),
                  ('build_scripts', build.has_scripts),
                 ]

setup(..., cmdclass={'build': MyBuild, 'build_ext': MyBuildExt})

rawDescription: Adding output file to Python extension

description: Adding output file to Python extension


code:
def fun(lst, key):
    for index, item in enumerate(lst):
        if key == item["_id"]:
            return index
    return -1

rawDescription: How to improve this for in python?

description: Improve this for in python


code:
apis = itertools.cycle([api1, api2, api3, api4, api5, api6, api7])
for s,usera in enumerate(all_users):
         if (s % 50) == 0:
             current_api = apis.next()
         name = usera.nickname
         name_id = usera.id
         print(s)
         current_api.request(example)
         ...

rawDescription: repetition of the compounds in the loop python

description: Repetition of the compounds in the loop python


code:
from django.db.models import Count
Song.objects.values('author','author__instrument').annotate(Count("id"))

rawDescription: Django aggregate and grouping : code cleanliness problem


code:
from PyQt4 import QtGui, QtWebKit
from PyQt4.QtCore import Qt
a = QtGui.QApplication([])
view = QtWebKit.QWebView()
view.setAttribute(Qt.WA_TranslucentBackground)
# Works with and without that following line
view.setAttribute(Qt.WA_OpaquePaintEvent, False)
page = view.page()
palette = page.palette()
palette.setBrush(QtGui.QPalette.Base, Qt.transparent)
page.setPalette(palette)
page.currentFrame().documentElement().setInnerXml("text")
view.show()
a.exec_()

rawDescription: PyQt4.QtWebKit + Background Transparency


code:
txt = """Hello. It's good to meet you.
My name is Bob."""
txt.split('.')
[x for x in map(str.strip, txt.split('.')) if x]

rawDescription: Divide string by line break or period with Python regular expressions


code:
token = Session.query(AuthToken).options(eagerload('user')).filter(...).one()
user = token.user

rawDescription: querying relation does not give back related object in sqlalchemy

description: Querying relation does not give back related object in sqlalchemy


code:
import pandas as pd
import numpy as np
from sklearn.neighbors import NearestNeighbors
df = pd.DataFrame(np.random.randint(0, 5, (10, 5)), columns=list("ABCDE"))
neigh = NearestNeighbors(n_neighbors=3)
neigh.fit(df.T) # Fit the data
model = neigh.kneighbors(df.T, return_distance=False)
pd.DataFrame(df.columns[model])

rawDescription: How to replace values in pandas with column names

description: Replace values in pandas with column names


code:
def give_winner(first_selection, second_selection):
    rules = {
        1: lambda x: x in (3, 4),
        2: lambda x: x in (1, 5),
        3: lambda x: x in (2, 4),
        4: lambda x: x in (2, 5),
        5: lambda x: x in (3, 1)
    }
    return rules[first_selection](second_selection)

rawDescription: A more python efficient way to write a code


code:
nonzero = norms > 0
x[nonzero] /= norms[nonzero]

rawDescription: Dealing with zeros in numpy array normalization


code:
import random
d = {"xtest": "yblob", "xtest1": "yblob1", "xtest2": "yblob2", "xtest3": "yblob3", "xtest4": "yblob4", "None": "None"}

#choose a random x
x = random.choice(d.keys())
if x == "None":
    proxy = None
else:
   y = d[x]
   proxy = {"http": "%s:%s" % (x, y)}

rawDescription: Randomly select from a dictionary for proxy use


code: engine.execute("SHOW VARIABLES LIKE 'wsrep_cluster_address'").fetchone()

rawDescription: Find the nodes in the percona cluster

description: Find the nodes in the percona cluster


code:
class VISA:
    def __init__(self, tty_name):
        self.ser = serial.Serial()
        self.ser.port = tty_name
        # If it breaks try the below
        #self.serConf() # Uncomment lines here till it works

        self.ser.open()
        self.ser.flushInput()
        self.ser.flushOutput()

        self.addr = None
        self.setAddress(0)

    def cmd(self, cmd_str):
        self.ser.write(cmd_str + "\n")
        sleep(0.5)
        return self.ser.readline()

    def serConf(self):
        self.ser.baudrate = 9600
        self.ser.bytesize = serial.EIGHTBITS
        self.ser.parity = serial.PARITY_NONE
        self.ser.stopbits = serial.STOPBITS_ONE
        self.ser.timeout = 0 # Non-Block reading
        self.ser.xonxoff = False # Disable Software Flow Control
        self.ser.rtscts = False # Disable (RTS/CTS) flow Control
        self.ser.dsrdtr = False # Disable (DSR/DTR) flow Control
        self.ser.writeTimeout = 2

    def close(self):
        self.ser.close()

rawDescription: Python reading and writing to tty

description: Python reading and writing to tty


code: sum(record_block) & 0xff

rawDescription: Compute the checksum of an Intel Hex record in Python 3


code: print("Nice to meet you "+name)

rawDescription: Python 3.5 printing user inputs

description: Python 3.5 printing user inputs


code:
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_position(('data', 0))

rawDescription: Placing the x-axes at a different y-value


code: unique_data = [list(x) for x in set(tuple(x) for x in testdata)]

rawDescription: Python: Uniqueness for list of lists

description: Python: Uniqueness for list of lists


rawDescription: How do you alias a python class to have another name without using inheritance?

description: Alias a python class to have another name without using inheritance


code:
def cb_check():
    if random_cards.get():
        randomize_stacks_checkbutton.config(state=DISABLED)
    else:
        randomize_stacks_checkbutton.config(state=NORMAL)

top=Tk()
random_cards = IntVar()
random_stacks = IntVar()
flip_cards = IntVar()
wildcard = IntVar()

randomize_cards_checkbutton = Checkbutton(top, text="Randomize cards",
                              variable=random_cards, command=cb_check)
randomize_cards_checkbutton.grid(row=0, column=0, sticky=W)

randomize_stacks_checkbutton = Checkbutton(top, text="Randomize stacks",
                               variable=random_stacks, bg="lightblue",
                               disabledforeground="gray")
randomize_stacks_checkbutton.grid(row=1, column=0, sticky=W)

top.mainloop()

rawDescription: Disable checkboxes by other checkboxes in Tkinter


code:
import argparse

def some_function(foo, bar):
    pass

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--foo", type=int, default=0,
                        help="foo")
    parser.add_argument("-b", "--bar", type=int, default=1,
                        help="bar")

    args = parser.parse_args()
    some_function(args.foo, args.bar)

if __name__ == '__main__':
    main()

rawDescription: Is there a pythonic way of assigning values to variables when passed in from the command line?


code:
if x: # evaluate boolean value implicitly
  pass
if x is 0: # compare object identity, see also id() function
  pass
if x == 0: # compare the object value
  pass

rawDescription: If-statement in Python

description: If-statement in Python


code:
import numpy
import pandas

# create an index containing all time stamps
idx1 = pandas.Index(sensor1.Time)
idx2 = pandas.Index(sensor2.Time)
idx3 = pandas.Index(sensor3.Time)
df = pandas.DataFrame(index=idx1.union(idx2).union(idx3))

# create a (constant) Series for each sensor
df['Sensor1'] = df.index.to_series().apply(lambda x: 3 if x >= sensor1.Time.min() and x <= sensor1.Time.max() else numpy.NaN)
df['Sensor2'] = df.index.to_series().apply(lambda x: 2 if x >= sensor2.Time.min() and x <= sensor2.Time.max() else numpy.NaN)
df['Sensor3'] = df.index.to_series().apply(lambda x: 1 if x >= sensor3.Time.min() and x <= sensor3.Time.max() else numpy.NaN)

# plot
p = df.plot(ylim=[0, 4], legend=False)
p.set_yticks([1., 2., 3.])
p.set_yticklabels(['Sensor3', 'Sensor2', 'Sensor1'])

rawDescription: How to plot a time range as a value from Pandas or MatPlotLib

description: Plot a time range as a value from Pandas or MatPlotLib


rawDescription: Pandas: Get unique MultiIndex level values by label


code:
import time
import threading
class App:
    def function1(self):
        pb = ttk.Progressbar(self.detail_frame1, orient='horizontal', mode='indeterminate')
    pb.pack()
    pb.start(1)

    #get the paper code of the paper to be checked
    input1 = self.input1.get()

    # system call based on the value of input1
    t = threading.Thread(target=call, args="")
    t.start()

    self.function2()

    def function2(self):
        self.detail_frame1.pack_forget()
        self.detail_frame2.pack()
def call():
    time.sleep(2)

rawDescription: Show Progress Bar during a system call in tkinter


code:
from collections import defaultdict

D = defaultdict(list)

a = ['sky', 'ocean', 'grass', 'tomato', 'leaf']

for item in a:
  D[color(item)].append(item)

rawDescription: grouping list of objects according to a certain characteristic

description: Grouping list of objects according to a certain characteristic


code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
table1 = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, ".calCell #cal1 #table1")))

rawDescription: python selenium unable to locate a table id which exists

description: Python selenium unable to locate a table id which exists


code:
with open('path','r') as f:
    content = f.readlines()[1:]
output="".join(content)

rawDescription: How can I remove first line from fasta file?

description: Remove first line from fasta file


code:
#!/usr/bin/env python
import logging
import multiprocessing as mp
from contextlib import closing

def init(shared_array_):
    # globals that should be available in worker processes should be
    # initialized here
    global shared_array
    shared_array = shared_array_

def f(interval, a=None, b=None):
    mp.get_logger().info("interval=%r, a=%r, b=%r" % (interval, a, b))
    shared_array[interval] = [a + interval.start]*b # fake computations

def mp_f(arg_kwargs):
    try:
        arg, kwargs = arg_kwargs
        return f(arg, **kwargs) # pass keyword args to f()
    except Exception:
        mp.get_logger().error("f%r failed" % (arg_kwargs,))

def main():
    mp.log_to_stderr().setLevel(logging.INFO)

    N = 10**6
    array = mp.RawArray('i', N) # create shared array

    # create workers pool; use all available CPU cores
    with closing(mp.Pool(initializer=init, initargs=(array,))) as p:
        options = dict(a=5, b=N//4) # dummy options
        step = options['b']
        args = ((slice(i, i+step), options) for i in range(0, N, step))
        for _ in p.imap_unordered(mp_f, args): # submit jobs
            pass
    p.join()
    mp.get_logger().info(array[::step])

if __name__=="__main__":
    mp.freeze_support() # for py2exe and the-like on Windows
    main()

rawDescription: Python Multiprocessing - Cannot Join Current Thread


code:
import re
import os

directory=r'C:\Users\Doug\Desktop'
fileName='sampleDeck'

file_fullPathName=os.path.join(directory, fileName + '.inp')

with open(file_fullPathName, 'r') as inpDeck:
    lines = inpDeck.read()

lines=re.findall(r"^\*Dflux(|,\s*amplitude=[^,]*?)\n([^,]*?),\s*BF\s*,([^,]*?\n)",lines, flags=re.IGNORECASE|re.MULTILINE)

file_fullPathName=os.path.join(directory, fileName + '-out.txt')
with open(file_fullPathName, "w") as outp:
    for line in lines:
        outp.write(','.join(line))  #Write text file

rawDescription: Pull Information from Abaqus Input File

description: Pull Information from Abaqus Input File


code:
sortkey = lambda i: [int(e) for e in i[0].split(':')]
collections.OrderedDict(sorted(observation_values.items(), key=sortkey))

rawDescription: Python order a dict by key value

description: Python order a dict by key value


code:
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

imageSize = (400,100) # 2x size of the image you originally wanted.

img = Image.new("RGB", imageSize, "white")
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("Verdana.ttf", 15 * 2) # 2x of the font you wanted.
draw.text((10, 4),"mimail@hotmail.com",(0,79,255), font=font)

# downsample with Antialias by 2
img.thumbnail( (imageSize[0]/2, imageSize[1]/2), Image.ANTIALIAS)

img.save('texto.png')

rawDescription: The text printed by the PIL library does not have the best definition


code:
from django.core.urlresolvers import reverse

class QuestionAdmin(admin.ModelAdmin):
    list_display = ['question', 'date', 'view_answers']

    def view_answers(self, obj):
        url = reverse("admin:app_answer_changelist")
        return 'View answers' % (url, obj.pk)
    view_answers.short_description = 'View answers'
    view_answers.allow_tags = True

rawDescription: Need to add view list anchor tag for another model in django admin


code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt

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

x =[0, 1, 2, 3, 4, 0]
y =[11, 1, 5, 2, 9, 0]
z =[1, 2, 3, 4, 5, 6]  # this array contained one value too many. (I padded the other two arrays)

ax.scatter(x, y, z, c='r', marker='o')

ax.set_xlabel('Days since last interaction')
ax.set_ylabel('Number of conversions')
ax.set_zlabel('Total number of interactions')

plt.show()

rawDescription: Resizing 3D scatter plot

description: Resizing 3D scatter plot


code:
import threading

#...

def playSound():
    global start
    start = time.clock()

    def func():
        winsound.PlaySound('SystemAsterisk', winsound.SND_ALIAS)

    threading.Thread(target=func).start()

rawDescription: Executing an keypress event while playing a sound in python(tkinter)


code:
def __getattr__(self, name):
    if name in self.items:
         return self.items[name]
    else:
         raise AttributeError()

rawDescription: Set class (self) variables from variables?


code:
from sqlalchemy import select

def alias_dups(join):
    dups = set(col.key for col in join.left.columns) & \
                set(col.key for col in join.right.columns)
    columns = []
    for col in join.columns:
        if col.key in dups:
            col = col.label('%s_%s' % (col.table.name, col.key))
        columns.append(col)
    return select(columns, from_obj=[join]).alias()

class ST2(Base):
    __table__ = alias_dups(t1.join(t2))

rawDescription: Is there a convenient way to alias only conflicting columns when joining tables in SQLAlchemy?


code:
#!/usr/bin/python3

import os
import glob
import re
from datetime import datetime, timezone
import time
from pprint import pprint

class logState():

    def __init__(self, log_path, glob_patt, re_patt, dt_fmt):

        self.dt = datetime.now(timezone.utc)
        self.log_path = log_path
        self.glob_patt = glob_patt
        self.re_patt = re_patt
        self.dt_fmt = dt_fmt
        self.empty_logs = []
        self.nonempty_logs = []

        # Retrieve only files from glob
        self.files = [  f for f in
                glob.glob(self.log_path + self.glob_patt)
                if os.path.isfile(f) ]

        for f in self.files:

            unq_fname = f.split('/')[-1]

            if unq_fname == None:
                continue

            # Tighter pattern matching
            if re.match(re_patt, unq_fname) == None:
                continue

            # Get the datetime portion of the file name
            f_dtstamp = unq_fname.split('.')[-1]

            # Make sure the datetime stamp represents
            # a valid date
            if datetime.strptime(f_dtstamp, self.dt_fmt) == None:
                continue

            # Check file size, add to the appropriate
            # list
            if os.path.getsize(f) <= 0:
                self.empty_logs.append(f)
            else:
                self.nonempty_logs.append(f)

def alert(msg):
    print("ALERT!: {0}".format(msg))

if __name__ == "__main__":

    # How long to sleep
    SLEEP_SECS = 5

    # How many samples to keep
    KEEP_SAMPLES = 5

    log_states = []

    # Definition for what logs states we'll look for
    log_path = './'
    glob_patt = 'nfcapd.[0-9]*'
    re_patt = 'nfcapd.([0-9]{12})'
    dt_fmt = "%Y%m%d%H%M"

    print("-- Setup --")
    print("Sample files in '{0}'".format(log_path))
    print("\t{0} samples kept:".format(KEEP_SAMPLES))
    print("\tglob pattern: '{0}'".format(glob_patt))
    print("\tregex pattern: '{0}'".format(re_patt))
    print("\tdatetime string: '{0}'".format(dt_fmt))
    print("")

    # Collect the initial state
    log_states.append(logState(log_path,
                               glob_patt,
                               re_patt, dt_fmt))

    while True:

        # Print state inventory and current state detail
        print( "-- Log States Stored --")
        for i, log_state in enumerate(log_states):
            print("Log state {0} @ {1}".format(i, log_state.dt))

        print(" -- Logs size > 0 --")
        pprint(log_states[-1].nonempty_logs)
        print(" -- Logs size <= 0 --")
        pprint(log_states[-1].empty_logs)
        print("")

        time.sleep(SLEEP_SECS)
        log_states = log_states[-KEEP_SAMPLES+1:]

        log_states.append(logState(log_path,
                                   glob_patt,
                                   re_patt,
                                   dt_fmt))

        # p = previous sample, c = current
        p = set(log_states[-2].empty_logs)
        c = set(log_states[-1].empty_logs)

        # only report the items in the current sample
        # not in the last
        if len(c.difference(p)) > 0:
            alert("\nNew zero length logs: " + str(c.difference(p)) + "\n")

rawDescription: Python script to alert on empty/missing logs


code:
def convert(x):
    if x >= 512:
        x -= 1024
    return x

rawDescription: Cast a 10 bit unsigned integer to a signed integer in python


code:
b='4'
formula = "2*x"
formula = formula.replace("x", "%d")
Result = eval(formula % int(b))

rawDescription: How to convert string into an variable in python

description: Convert string into an variable in python


code:
import msvcrt
import time
import winsound

notes = {'a': 440, 's': 935, 'd': 1039}

while True:
    key = msvcrt.getch()
    try:
        note = notes[key]
    except KeyError:
        note = 0

    winsound.Beep(note, 10)
    time.sleep(0.01)

rawDescription: Basic Python Sound Programming

description: Basic Python Sound Programming


code:
with open(self.save_path, "wb") as file:
    writer = csv.writer(file, delimiter = ',')

rawDescription: Use wxPython.FileDialog to save file

description: Use wxPython.FileDialog to save file


code:
from difflib import SequenceMatcher
s_1 = 'Mohan Mehta'
s_2 = 'Mohan Mehte'
print(SequenceMatcher(a=s_1,b=s_2).ratio())
0.909090909091

rawDescription: Finding if two strings are almost similar


code:
"0x%02X" % 42                     # the old way
"0x{:02X}".format(42) == "0x2A"   # the new way

rawDescription: Using python to dump hexidecimals into YAML


code:
list_a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list_b = [4, 2, 5, 6, 1, 7, 3, 9, 0, 8]

import operator
[k for k, v in sorted(zip(list_a, list_b), key=operator.itemgetter(1))]

rawDescription: python sorting based on parallel arrays

description: Python sorting based on parallel arrays


code:
import uuid
from django.db import models

class MyUUIDModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)

rawDescription: How can auto create uuid column with django


code:
P=gs.plot()
P.set_axis_bgcolor('g') #or any HTML colorcode, (R,G,B) tuple, (R,G,B,A) tuple, etcetc.

rawDescription: Change pandas plot backgournd color

description: Change pandas plot backgournd color


code:
import Image
import ImageDraw
im = Image.open("image.png")
transparent_area = (50,80,100,200)

mask=Image.new('L', im.size, color=255)
draw=ImageDraw.Draw(mask)
draw.rectangle(transparent_area, fill=0)
im.putalpha(mask)
im.save('/tmp/output.png')

rawDescription: Python PIL: how to make area transparent in PNG?


code:
Ipath = raw_input("Enter the input file :- ")
Opath = raw_input("Enter the output directory :- ")
Ipath = Ipath.replace("\\", "/") # Python requirement for paths
Opath = Opath.replace("\\", "/")
copyfile(str(Ipath) + ".prj", str(Opath) + "/" + "Out_Lines" + ".prj") # Copying projection file

sf = shapefile.Reader(str('Input Path'))
shapes = sf.shapes()
Box = shapes[0].bbox
Spc = input("Enter the grid spacing :- ") # Grid Spacing read

x_min = Box[0] # Save the coordinates of the right-bottom, left-top bounding box
y_min = Box[1]
x_max = Box[2]
y_max = Box[3]

A_bbox = [x_min, y_min] # First assignment of coordinates
B_bbox = [x_max, y_max]
C_bbox = [x_min, y_max]
D_bbox = [x_max, y_min]

w = shapefile.Writer(shapefile.POLYLINE) # Shapefile writer
w.line(parts = [[A_bbox, C_bbox]])
w.field('Path number', 'C', '50')
w.record(str(1)) # Writes the first line, that is the left 'side' of the bounding box

# Increasing the X coordinate to generate a line at a specified spacing
i = 2
while (A_bbox[0] <= x_max):
    A_bbox = [A_bbox[0] + Spc, A_bbox[1]]
    C_bbox = [C_bbox[0] + Spc, C_bbox[1]]
    w.line(parts = [[A_bbox, C_bbox]])
    w.record(str(i))
    i = i+1

w.save(str(Opath) + "/" + "Out_Lines")

rawDescription: Vertical lines in a polygon shapefile

description: Vertical lines in a polygon shapefile


rawDescription: self.connect() vs QMainWindow.connect()

description: Self.connect() vs QMainWindow.connect()


code:
from bottle import route, run

@route('/')
def index():
    return 'Hello, world!'

run(host = 'localhost', port = 8080, quiet=True)

rawDescription: How to prevent Python Bottle from reporting every request to the console?

description: Prevent Python Bottle from reporting every request to the console


code: text = os.linesep.join([s for s in text.splitlines() if s])

rawDescription: What's a quick one-liner to remove empty lines from a python string?


code:
context.lower()
counts = {word: context.count(word)
          for word in links}

rawDescription: Find frequency of array strings in a file sized string, using Python


code:
from django.contrib.sites.models import Site
Site.objects.get_current().domain

rawDescription: Get Root URL/Domain Name in Email Template


code:
from collections import Counter, OrderedDict

class OrderedCounter(Counter, OrderedDict):
    'Counter that remembers the order elements are first encountered'

    def __repr__(self):
        return '%s(%r)' % (self.__class__.__name__, OrderedDict(self))

    def __reduce__(self):
        return self.__class__, (OrderedDict(self),)

words = ["oranges", "apples", "apples", "bananas", "kiwis", "kiwis", "apples"]
c = OrderedCounter(words)
print(c)
# OrderedCounter(OrderedDict([('oranges', 1), ('apples', 3), ('bananas', 1), ('kiwis', 2)]))

rawDescription: how to get count dict of items but maintain the order in which they appear?

description: Get count dict of items but maintain the order in which they appear


code:
payload_before = len(pkt[TCP].payload)

pkt[TCP].payload = str(pkt[TCP].payload).replace("Heading","Other string")

payload_after = len(pkt[TCP].payload)

payload_dif = payload_after - payload_before

pkt[IP].len = pkt[IP].len + payload_dif

rawDescription: Change TCP Payload with nfqueue/scapy

description: Change TCP Payload with nfqueue/scapy


code:
import zipfile

root_path = 'C:/data/'

def zipping_sql_database():
    zf = zipfile.ZipFile(root_path + 'file.zip', mode='w')
    try:
        zf.write(root_path + "file.db", "file.db")
    finally:
        zf.close()

rawDescription: How do I zip a file in Python without adding folders?

description: Zip a file in Python without adding folders


code:
import re
import urllib2
import lxml.html
page = urllib2.urlopen("http://maps.google.com/maps/place?cid=2860002122405830765").read()
mo = re.search(r'
.*?
', page)
div = lxml.html.fromstring(mo.group(0))
href = div.find("a").attrib["href"]

rawDescription: Fetching href of a link

description: Fetching href of a link


code:
f = open('test_parsing.txt', 'rU')
f1 = open('test_parsing_out.txt', 'a')
for line in f:
    match = re.search('\w+\s+(\w+)\s+\w+\s+\w+\:', line)
    match1 = re.findall('GO:\d+', line)
    f1.write('%s %s \n'%(match.group(1), ''.join(match1)))
f1.close()

rawDescription: how to parse a file and write to a output file in python

description: Parse a file and write to a output file in python


rawDescription: Elementwise operations over tuples in Python


code:
def thesplit(s):
    result = []

    for each in s.split(', '):
        name, chars = each.split(' ')
        result.append(chars.lower() + name[0])

    return ', '.join(result)

rawDescription: SQL / Python - String replacement pattern with commas


code:
import numpy as np
import pylab as plt

S  = np.random.randn(100,100)

# Make symmetric so everything is real
S += S.T
W,V = np.linalg.eigh(S)

import pylab as plt
plt.imshow(V,interpolation="none")
plt.show()

rawDescription: Function for ploting a matrix in ipython using matplotlib


code:
class MaxDateListFilter(SimpleListFilter):
    title = _('maximum date')
    parameter_name = 'max_date'

    def lookups(self, request, model_admin):
        return [(str(year.year), year.year) \
                 for year in Entry.objects.dates('pub_date', 'year')]

    def queryset(self, request, queryset):
        return queryset.filter(pub_date__year__lte=self.value())

rawDescription: Custom SimpleListFilter Subclass for DjangoAdmin


code:
def encode(string, probabilities):
    getcontext().prec = 28
    start = Decimal('0.0')
    width = Decimal('1.0')
    for ch in string:
        d_start, d_width = probabilities[ch]
        start += Decimal(d_start)*width
        width *= Decimal(d_width)
    return random.uniform(float(start), float(start + width))

rawDescription: Python set decimal precision

description: Python set decimal precision


code:
a = np.ones((95, 300))
b = np.ones((95, 3)) * 2
a.shape
b.shape
c = np.hstack((a,b))
c
c.shape

rawDescription: Concatenate each line of two arrays into a single one


code: currentCommand = "cmd /c " & Chr(34) & source_code_path & " " & variable1 & " " & variable2 & Chr(34)

rawDescription: Calling Python script with arguments from VBscript


rawDescription: Python Regular expression

description: Python Regular expression


code:
import os.path

LOCATION = os.path.dirname(os.path.abspath(__file__))
pathToScript = os.path.join(LOCATION, 'bashscript.sh')

rawDescription: Include bash script in python compilation


code:
@login_required(login_url=reverse_lazy('login'), redirect_field_name=None)
def my_view(request): ...

rawDescription: Using @login_required without "?next=/" appended to the URL


code:
names_set = set(lst_names)
# ...
name_match = re.search('@(\w+)\b', text)
if name_match:
  name = name_match.group(1)
  if name in names_set:
    return name

rawDescription: Line by line check for large amount of keywords with python


code:
number_scales = 5          # scale resolution
number_orientations = 8    # orientation resolution
N = 128                    # image dimensions
def getFilter(f_0, theta_0):
    # filter configuration
    scale_bandwidth =  0.996 * math.sqrt(2/3)
    angle_bandwidth =  0.996 * (1/math.sqrt(2)) * (np.pi/number_orientations)

    # x,y grid
    extent = np.arange(-N/2, N/2 + N%2)
    x, y = np.meshgrid(extent,extent)

    mid = int(N/2)
    ## orientation component ##
    theta = np.arctan2(y,x)
    center_angle = ((np.pi/number_orientations) * theta_0) if (f_0 % 2) \
                else ((np.pi/number_orientations) * (theta_0+0.5))

    # calculate (theta-center_theta), we calculate cos(theta-center_theta)
    # and sin(theta-center_theta) then use atan to get the required value,
    # this way we can eliminate the angular distance wrap around problem
    costheta = np.cos(theta)
    sintheta = np.sin(theta)
    ds = sintheta * math.cos(center_angle) - costheta * math.sin(center_angle)
    dc = costheta * math.cos(center_angle) + sintheta * math.sin(center_angle)
    dtheta = np.arctan2(ds,dc)

    orientation_component =  np.exp(-0.5 * (dtheta/angle_bandwidth)**2)

    ## frequency componenet ##
    # go to polar space
    raw = np.sqrt(x**2+y**2)
    # set origin to 1 as in the log space zero is not defined
    raw[mid,mid] = 1
    # go to log space
    raw = np.log2(raw)

    center_scale = math.log2(N) - f_0
    draw = raw-center_scale
    frequency_component = np.exp(-0.5 * (draw/ scale_bandwidth)**2)

    # reset origin to zero (not needed as it is already 0?)
    frequency_component[mid,mid] = 0

    return frequency_component * orientation_component

rawDescription: Implementing log Gabor filter bank

description: Implementing log Gabor filter bank


code:
import os
os.chdir('/path/to/dir')

rawDescription: how to do shell navigation using python

description: Do shell navigation using python


rawDescription: unsupported operand type(s) for +: 'numpy.ndarray' and 'str'

description: Unsupported operand type(s) for +: 'numpy.ndarray' and 'str'


code:
fileNameTemplate = r'C:\documents\Plot{0:02d}.png'

for subdir,dirs,files in os.walk(rootdir):
    for count, file in enumerate(files):
        # Generate a plot in `pl`
        pl.savefig(fileNameTemplate.format(count), format='png')
        pl.clf()  # Clear the figure for the next loop

rawDescription: Saving multiple plots

description: Saving multiple plots


code:
import mechanize
import urllib

browser = mechanize.Browser()
#These are the parameters you've got from checking with the aforementioned tools
parameters = {'parameter1' : 'your content',
              'parameter2' : 'a constant value',
              'parameter3' : 'unique characters you might need to extract from the page'
             }
#Encode the parameters
data = urllib.urlencode(parameters)
#Submit the form (POST request). You get the post_url and the request type(POST/GET) the same way with the parameters.
browser.open(post_url,data)
#Submit the form (GET request)
browser.open(post_url + '%s' % data)

rawDescription: Submit without the use of a submit button, Mechanize


code:
df = pd.DataFrame([[1, 2], [1, 4], [1, 6], [2, 8]], columns=['A', 'B'])
df
df.head(2)  # the first two rows
df.groupby('A').head(2)  # the first two rows in each group

rawDescription: Keeping the N first occurrences of

description: Keeping the N first occurrences of


code:
from __future__ import print_function

import pydoc
import os
import sys
import time
import webbrowser

import warnings as _warnings
import os as _os

from tempfile import mkdtemp
from contextlib import contextmanager

@contextmanager
def suppress_stdout():
    """ Suppresses output of all functions called as follows:
    with suppress_stdout():
        functioncall()
    source: http://thesmithfam.org/blog/2012/10/25/temporarily-suppress-console-output-in-python/
    """
    with open(os.devnull, "w") as devnull:
        old_stdout = sys.stdout
        sys.stdout = devnull
        try:
            yield
        finally:
            sys.stdout = old_stdout

class TemporaryDirectory(object):
    """Create and return a temporary directory.  This has the same
    behavior as mkdtemp but can be used as a context manager.  For
    example:

        with TemporaryDirectory() as tmpdir:
            ...

    Upon exiting the context, the directory and everything contained
    in it are removed.
    """

    def __init__(self, suffix="", prefix="tmp", dir=None):
        self._closed = False
        self.name = None # Handle mkdtemp raising an exception
        self.name = mkdtemp(suffix, prefix, dir)

    def __repr__(self):
        return "<{} {!r}>".format(self.__class__.__name__, self.name)

    def __enter__(self):
        return self.name

    def cleanup(self, _warn=False):
        if self.name and not self._closed:
            try:
                self._rmtree(self.name)
            except (TypeError, AttributeError) as ex:
                # Issue #10188: Emit a warning on stderr
                # if the directory could not be cleaned
                # up due to missing globals
                if "None" not in str(ex):
                    raise
                print("ERROR: {!r} while cleaning up {!r}".format(ex, self,),
                      file=_sys.stderr)
                return
            self._closed = True
            if _warn:
                self._warn("Implicitly cleaning up {!r}".format(self),
                           ResourceWarning)

    def __exit__(self, exc, value, tb):
        self.cleanup()

    def __del__(self):
        # Issue a ResourceWarning if implicit cleanup needed
        self.cleanup(_warn=True)

    # XXX (ncoghlan): The following code attempts to make
    # this class tolerant of the module nulling out process
    # that happens during CPython interpreter shutdown
    # Alas, it doesn't actually manage it. See issue #10188
    _listdir = staticmethod(_os.listdir)
    _path_join = staticmethod(_os.path.join)
    _isdir = staticmethod(_os.path.isdir)
    _islink = staticmethod(_os.path.islink)
    _remove = staticmethod(_os.remove)
    _rmdir = staticmethod(_os.rmdir)
    _warn = _warnings.warn

    def _rmtree(self, path):
        # Essentially a stripped down version of shutil.rmtree.  We can't
        # use globals because they may be None'ed out at shutdown.
        for name in self._listdir(path):
            fullname = self._path_join(path, name)
            try:
                isdir = self._isdir(fullname) and not self._islink(fullname)
            except OSError:
                isdir = False
            if isdir:
                self._rmtree(fullname)
            else:
                try:
                    self._remove(fullname)
                except OSError:
                    pass
        try:
            self._rmdir(path)
        except OSError:
            pass

def help(thing):
    """ Create and show HTML page of module documentation,
    It should accept anything that the regular help() accepts.
    """

    # Create temporary directory to store documentation in
    with TemporaryDirectory() as temp_folder:
        orignal_cwd = os.getcwd()

        # Change working directory to temporary folder
        os.chdir(temp_folder)

        # Create HTML page of doc
        object, name = pydoc.resolve(thing)
        pydoc.writedoc(thing)
        with suppress_stdout():
            filepath = os.path.join(temp_folder, name + ".html")

        # Reset working directory
        os.chdir(orignal_cwd)

        # Open default program to view HTML files
        webbrowser.open_new(filepath)

        # Sleep for 2 seconds so browser can open before deleting file
        time.sleep(2)

if __name__ == "__main__":
    help(os)

rawDescription: Producing a single HTML help page for a module, function, class similar to R


code:
class GenericAPIView(views.APIView):
    ...

    # If you want to use object lookups other than pk, set this attribute.
    # For more complex lookup requirements override `get_object()`.
    lookup_field = 'pk'

rawDescription: Django rest framework serializer: how to update table with auto_increment pk?


code:
class UserProfileCreate(CreateView):
    model = UserProfile
    form_class = UserProfileForm
    queryset = UserProfile.objects.all()
    success_url = '/sites/list'
    def form_valid(self, form):
        self.object = form.save()
        self.object.set_password(self.object.password)
        return super(UserProfileCreate, self).form_valid(form)

rawDescription: Django: unable to login with new users

description: Django: unable to login with new users


code: options['1'] = pluto

rawDescription: Python: How can I rename a dictionary item and still use it as case statement option?


code:
import re

reg = r'\d+\-\d+\-\d+'
data='C:/Users/pivo/work/Data/Black_try\\2015-12-03_14-41-00_TrData.txt'
a=re.findall(reg, data)
print(a[1])

rawDescription: Python: Extract time from a file path

description: Python: Extract time from a file path


code:
query = meta.session.query(Transaction)
if day != 'all':
    query = query.filter(Transaction.day == day)
records = query.all()

rawDescription: sqlalchemy filter using in_

description: Sqlalchemy filter using in_


code:
class B(object):
    class _Meta(type):
        def __getitem__(cls, t):
            from System.Collections.Generic import List as A # just an example
            class _B(A[t]):
                pass
            return _B
    __metaclass__ = _Meta

class C(B[object]):
    pass

rawDescription: IronPython create generic class

description: IronPython create generic class


code:
mysentence = ('i have a dog and a cat', 'i have a cat and a dog', 'i have a cat', 'i have a dog')
import re
pattern = re.compile("(dog|cat) ")
[x for x in mysentence if not pattern.search(x)]

rawDescription: Select strings by positions of words

description: Select strings by positions of words


rawDescription: How do I make a dynamically expanding array in python

description: Make a dynamically expanding array in python


rawDescription: Opening pdf file

description: Opening pdf file


code:
supplied_list = [0, 1]
list(set(range(3)) - set(supplied_list))

rawDescription: pythonic way of finding a value in a list which hasn't been supplied

description: Pythonic way of finding a value in a list which hasn't been supplied


rawDescription: How to get multiple parameters with same name from a URL in Pylons?

description: Get multiple parameters with same name from a URL in Pylons


code:
import xml.etree.ElementTree as ET
import pandas as pd
root=ET.fromstring('<dict><key>Track ID</key><integer>3636</integer></dict>')
#parsing into a dictionary
d={}
k=''
for t in root:
  if t.tag=='key':
    k=t.text
    continue
  d[k]=t.text
#transforming to a DataFrame
df=pd.DataFrame(d.items(),columns=['key','value'])
print (df)

rawDescription: Unpacking list of dictionary elements into pandas data frame


code:
def make_autocad_script(outfile_name, contour):
    '''
    Creates an Autocad script which contains polylines for each contour.
    Args
    outfile_name: the name of the Autocad script file.
    contour: the contour plot that needs to be exported to Autocad.
    '''

    with open(outfile_name, 'w', newline='') as outfile:
        writer = csv.writer(outfile, delimiter=',', )
        # each collection is associated with a contour level
        for collection in contour.collections:

            # If the contour level is never reached, then the collection will be an empty list.
            if collection:
                # Set color for contour level
                outfile.write('COLOR {}\n'.format(random.randint(1,100)))
                # Each continuous contour line in a collection is a path.
                for path in collection.get_paths():

                    vertices = path.vertices

                    # pline is an autocad command for polyline.  It interprets
                    # the next (x,y) pairs as coordinates of a line until
                    # it sees a blank line.
                    outfile.write('pline\n')
                    writer.writerows(vertices)
                    outfile.write('\n')

rawDescription: Can I convert a contour plot in matplotlib to a format that can be imported and edited in AutoCAD?

description: Convert a contour plot in matplotlib to a format that can be imported and edited in AutoCAD


code:
from tkinter import *

def iterate_lines():
    for line in t.get('1.0', 'end-1c').splitlines():
        # Iterate lines
        if line:
            print('path: {}'.format(line))

root = Tk()
t = Text(root)
t.insert(END, '/path/to/file/1.txt\n/path/to/file/2.txt\n/path/to/file3.txt\n')
t.pack()
Button(root, text='iterate', command=iterate_lines).pack()
root.mainloop()

rawDescription: Tkinter Text Widget, iterating over lines


code:
class CustomWidget(BoxLayout):
    def __init__(self, *args, **kwargs):
        super(CustomWidget, self).__init__(*args, **kwargs)
        Clock.schedule_once(self.init_ui, 0)
    def init_ui(self, dt=0):
        self.ids['text_input'].bind(insert_text=numeric_filter)

rawDescription: Kivy Widget ids access in __init__

description: Kivy Widget ids access in __init__


code:
from tkinter import *

class App:
    def __init__(self, parent):
        self.__setup_gui(parent) # Call Helper
        parent.title('To be changed')

    def __setup_gui(self, parent):

        # First Row
        self.rowframe = Frame(parent)
        self.rowframe.grid()
        self.cs_label = Label(self.rowframe, text='Change Set: ')
        self.cs_label.grid(row=0, column=0, padx=2, pady=2)

        self.cs_val = Entry(self.rowframe, width=10)
        self.cs_val.grid(row=0, column=1, padx=2, pady=2)

        self.get_button = Button(self.rowframe, text='Get', command=self.get_content)
        self.get_button.grid(row=0, column=2, padx=2, pady=2)
        parent.update_idletasks()
        parent.minsize(width=self.rowframe.winfo_width(), height=self.rowframe.winfo_height())

        # Text area and scrollbars
        self.textframe = Frame(parent)
        self.textframe.grid(row=1, columnspan=2, padx=2, pady=2, sticky=N+S+E+W)

        self.hscroll = Scrollbar(self.textframe, orient=HORIZONTAL)
        self.vscroll = Scrollbar(self.textframe)
        self.text_area = Text(self.textframe, height=10, width=50, wrap=NONE, background='white', yscrollcommand=self.vscroll.set, xscrollcommand=self.hscroll.set)
        self.text_area.grid(row=0, column=0, sticky=N+S+E+W)
        self.hscroll.config(command=self.text_area.xview)
        self.hscroll.grid(row=1, column=0, sticky=E+W)
        self.vscroll.config(command=self.text_area.yview)
        self.vscroll.grid(row=0, column=1, sticky=N+S)

        # Row 0 defaults to 0
        parent.rowconfigure(1, weight=1)
        parent.columnconfigure(1, weight=1)

        # Textarea setup
        self.textframe.rowconfigure(0, weight=1)
        self.textframe.columnconfigure(0, weight=1)

        self.clipboard_var = IntVar()
        self.notepad_var = IntVar()

    def get_content(self):
        print(self.clipboard_var.get())
        print(self.notepad_var.get())

###################################################################################################

if __name__ == '__main__':
    root = Tk()
    app = App(root)
    root.mainloop()

rawDescription: Python 3.1 Tkinter layout help. I am close, please help me finish this


code:
def log_function(handler):
    info = {
        'Status_Code': handler.get_status(),
        'Method': handler.request.method,
        'URL': handler.request.uri,
        'Remote_IP': handler.request.remote_ip,
        'Elapsed_Time': '%.2fms' % (handler.request.request_time()*1000)
    }
    tornado.log.access_log.info(json.dumps(info, indent=4))

# try it out with a dummy application
app = Application([], log_function=log_function)
app.listen(8888)
IOLoop.current().run_sync(lambda: AsyncHTTPClient().fetch(
    'http://localhost:8888/', follow_redirects=False, raise_error=False))

rawDescription: Format Default Python Logging for tornado.access


code: np.einsum('ij, ijkl-> ijkl', x, y)

rawDescription: Numpy: multiplying matrix elements with array of matrices


code:
even = []
odd = []
for i in my_list:
    (odd if i % 2 else even).append(i)

rawDescription: Is it possible to compile results into unique lists from inside of a comprehension?


code:
class BooleanDescriptor(object):
    def __init__(self, attr):
        self.attr = attr

    def __get__(self, instance, owner):
      return getattr(instance, self.attr)

    def __set__(self, instance, value):
      if value in (True, False):
        return setattr(instance, self.attr, value)
      else:
        raise TypeError

class Foo(object):
    _bar = False
    bar = BooleanDescriptor('_bar')

rawDescription: Use a Descriptor (EDIT: Not a single decorator) for multiple attributes?


code:
class MyRegForm(ParentForm):
    def clean_email(self):
        email = self.cleaned_data['email']
        # If the parent class already cleans the email, you might want to do
        # email = super(MyRegForm, self).clean_email()
        # Then check email here, and raise forms.ValidationError()
        # if the email is not in the whitelist
        return email

rawDescription: Right way to implement email whitelist solution for Django-registration-redux?


rawDescription: Creating a variable number of list in Python


code:
src = "Folder1/Folder2/file1"
dst = "Folder3"+src
dstfolder = os.path.dirname(dst)
if not os.path.exists(dstfolder):
    os.makedirs(dstfolder)
shutil.copy(src,dst)

rawDescription: How to copy a file in python recreating the directory structure?

description: Copy a file in python recreating the directory structure


code:
class Foo:

   def run(self):
      responses = [func(self) for func_name, func in Foo.foo_dict.items()]

   def foo1(self):
      return True

   def foo2(self):
      return False

   foo_dict = {'foo1':foo1,'foo2':foo2}

rawDescription: calling a method/function from a class variable

description: Calling a method/function from a class variable


code:
import csv
def on_status(self, status):
    with open('file.txt', 'w') as f:
        f.write('Author,Date,Text')
        writer = csv.writer(f)
        writer.writerow([status.author.screen_name, status.created_at, status.text])

rawDescription: Save Streaming Twitter Data to CSV

description: Save Streaming Twitter Data to CSV


code:
table = a.pivot_table(index='category', columns='age', aggfunc='size')
table.plot(kind='bar', stacked=True)

rawDescription: Turn pandas DataFrame with two columns into stacked barplot


rawDescription: Replacing '=' with '==' in a string

description: Replacing '=' with '==' in a string


code:
months = ['January', 'Feburary', 'March', 'April', 'May', 'June', 'July',
          'August', 'September', 'October', 'November', 'December']

def open_weather():
    weather = open('yearly_temperatures.txt')
    year_weather = weather.readlines()
    return year_weather

def month_temp(year_weather, months):
    output = []
    for i in range(len(months)):
        output.append((months[i], set(year_weather[i].lstrip(months[i] + ":").strip("\n").split(","))))
    return output

yw = open_weather()
print(month_temp(yw, months))

rawDescription: Text File of Monthly Temps into Set

description: Text File of Monthly Temps into Set


code:
import matplotlib.pyplot
from numpy import arange
from numpy import meshgrid

delta = 0.025
xrange = arange(-3.0, 3.0, delta)
yrange = arange(-2.0, 2.0, delta)
X, Y = meshgrid(xrange,yrange)
F = X**2 + Y**2 -4
G = 0
matplotlib.pyplot.contour(X,Y,(F-G),[0])
matplotlib.pyplot.show()

rawDescription: How to plot 2 variables on a plane

description: Plot 2 variables on a plane


code:
import re
txt = '''#|\n this is some sort of foo bar\n that I don't care about|#\nthen there is a foo bar sentence that I want but i don't want that foo bar in within the hex pipe pipe hex comment block.#| and even so, i don't want this section to appear|#\n with some crazy sentence...'''
txt2 = re.sub(r'#\|.*?\|#', '', txt, flags=re.DOTALL)  # remove multiline comment
txt2

rawDescription: Remove comment blocks bounded by `#|...|#` in textfile - python


code:
import re
re.split(r'\n{2,}', string)

rawDescription: Python Regular Expression to Split Blocks of Text with Varying Newline Separation


code:
from collections import Counter
import re
Counter(re.findall("\w+", line_arr)).most_common()[:5]

rawDescription: python find all common patterns in an array

description: Python find all common patterns in an array


code:
index = pd.date_range(freq='66T', start=ts.first_valid_index(), periods=5)
ts.reindex(set(ts.index).union(index)).sort_index().interpolate('time').ix[index]
index = pd.date_range(freq='65T', start=ts.first_valid_index(), periods=5)
ts.reindex(set(ts.index).union(index)).sort_index().interpolate('time').ix[index]

rawDescription: Strange behavior of pandas resampling

description: Strange behavior of pandas resampling


code:
from lxml import etree
from StringIO import StringIO
your_string = "

 Random Other Text
Example Text

Coachella Valley Music & Arts Festival
Random Text:Random Date
"
parser = etree.HTMLParser()
document = etree.parse(StringIO(your_string), parser)
elements = document.xpath('//*[text()="Example Text"]')
elements[0].tag

rawDescription: Identify characters in a string by their relative position to a searched string?


code:
filter(lambda x: '-ba' in x, tab2.columns)
tab2[filter(lambda x: '-ba' in x, tab2.columns)]

rawDescription: Exporting Pandas DataFrame with MultiIndex


code:
class App(Frame):

    def __init__(self, root):
        Frame.__init__(self, root)
        self.option_add('*Font', 'Verdana 10 bold')
        self.grid()
        self.create_widgets()
        self.show()

    def create_widgets(self):
        self.whichOne = IntVar()
        self.output = StringVar()
        self.whichOne.set(0)
        Radiobutton(self, text = 'Ethernet', padx = 10, pady = 10, variable = self.whichOne, value =0, command=self.show).grid(row=0, column=0, sticky=W)
        Radiobutton(self, text = 'Wi-Fi', padx = 10, pady = 10, variable = self.whichOne, value =1, command=self.show).grid(row=1, column=0, sticky=W)
        Button(self, text='QUIT', fg='red', command=self.quit).grid(row=0, column=1, sticky=W, rowspan=2, columnspan=2)

    def show(self):
        self.hexInt = interfaces()
        if True:
            self.nic = self.nicInfo(self.whichOne.get())
            selection = 'The MAC address of your device is %s\n' % (self.nic[0]) + '\nThe IP address of your device is %s\n' % (self.nic[1])
            Label(text=selection).grid(row=2, column=0, columnspan=2)

    def nicInfo(self, index):
        self.mac = 'unknown'
        for mainKey in ifaddresses(self.hexInt[index]): # a DICT which contains a LIST, in which is a DICT
            for subKey in ifaddresses(self.hexInt[index])[mainKey][0]: #this zero has to be here
                if match(r'([0-9a-f]{2}[:-]){5}([0-9a-f]{2})', ifaddresses(self.hexInt[index])[mainKey][0][subKey]):
                    self.mac = ifaddresses(self.hexInt[index])[mainKey][0][subKey].upper()
                elif match(r'((2[0-5]|1[0-9]|[0-9])?[0-9]\.){3}((2[0-5]|1[0-9]|[0-9])?[0-9])',
                           ifaddresses(self.hexInt[0])[mainKey][0][subKey]) and\
                           subKey == 'addr':
                    self.ip = ifaddresses(self.hexInt[index])[mainKey][0][subKey]
        return self.mac, self.ip

if __name__ == '__main__':
    root = Tk()
    root.title('MAC')
    app = App(root)
    app.mainloop()

rawDescription: Unable to switch between options

description: Unable to switch between options


code:
import re
help(re.split)
re.split('\s+', 'The   quick brown\t fox')

rawDescription: Regex: How to make a group for each word in a sentence?


code: some_list.sort(key=lambda x: float(x[0]) )

rawDescription: How to sort a list of lists (non integers)?

description: Sort a list of lists (non integers)


code:
import re
test_str = "test 1:\nhello op1 yviphf\nhello op2 vipqwe\ntest 2:\nhello op3\nhello op4 vipgt\nhello op5 zcv"
res1 = [y for y in re.findall(r'test\s*(\d+)', test_str) if y]
res2 = [re.findall(r'(?m)^hello\s*(\S+)', b) for b in re.split(r'test\s*\d+', test_str) if b]
print(zip(res1, res2))

rawDescription: Extracting repetitions through regex in Python


code:
for key,value in dic.iteritems():
    if key == datetime.today(): # or (datetime.today() - key).seconds == <any value you expect>
        # since value is a tuple(not a dict) and you want to get the first item you can use index 0
        slug = value[0]

rawDescription: iterating dictionary and fetching values from inner dictionaries

description: Iterating dictionary and fetching values from inner dictionaries


code:
cube = np.random.random(100000).reshape(10,100,100)
simple = cube / np.median(cube,axis=[1,2])[:,None,None]

brute = cube.copy()
for i in range(10):
    brute[i, :, :] /= np.median(cube[i, :, :])

np.allclose(brute, simple)

rawDescription: Divide each plane of cube by its median without loop


code:
class inheritedclass(initialclass):
    def __init__(self):
        initialclass.__init__(self)
        self.attr3 = 'three'

rawDescription: python __init__ method in inherited class

description: Python __init__ method in inherited class


code:
import shutil

with open(outfilename, 'wb') as outfile:
    for filename in glob.glob('*.txt'):
        if filename == outfilename:
            # don't want to copy the output into the output
            continue
        with open(filename, 'rb') as readfile:
            shutil.copyfileobj(readfile, outfile)

rawDescription: python script to concatenate all the files in the directory into one file

description: Python script to concatenate all the files in the directory into one file


code:
# Assuming that A and B are mapped objects that point to tables a and b from
# your example.
q = db.session.query(
    db.cast(A.product_id, db.BigInteger),
    db.cast(db.count(A.product_id), db.BigInteger).label('itemsSold'),
    db.cast(B.product_name, db.String)
# If relationship between A and B is configured properly, explicit join
# condition usually is not needed.
).outerjoin(B, A.product_id == B.product_id).\
group_by(A.product_id, B.product_name).\
order_by(db.desc('itemsSold'))

rawDescription: Select with count in Flask-SQLAlchemy

description: Select with count in Flask-SQLAlchemy


code:
def splitter(str):
    for i in range(1, len(str)):
        start = str[0:i]
        end = str[i:]
        yield (start, end)
        for split in splitter(end):
            result = [start]
            result.extend(split)
            yield result

combinations = list(splitter(str))

rawDescription: Find all list permutations of a string in Python


rawDescription: extract data using regular expression between three fixed characters

description: Extract data using regular expression between three fixed characters


code:
from urllib2 import urlopen
from lxml import html
page = urlopen('http://www.amazon.co.uk/')
page_source = html.parse(page)
from pprint import pprint
pprint(page_source.xpath('//img/@src'))

rawDescription: Extract path and file name from <img > tag


code: dev = usb.core.find(idVendor=int(vendor, 16), idProduct=int(product, 16))

rawDescription: Converting hex string to hex integer

description: Converting hex string to hex integer


rawDescription: python write 40 times loops results in text

description: Python write 40 times loops results in text


code:
tn = telnetlib.Telnet()
tn.set_debug_level(0)
tn.open(host)
tn.write(command.encode('ascii') + b"\n")
# etc.

rawDescription: Clear the output buffer in telnetlib on Python 3.2


code:
def set_aspect_ratio_log(plot, aspect_ratio):
        x_min, x_max = plot.get_xlim()
        y_min, y_max = plot.get_ylim()
        return plot.set_aspect(aspect_ratio * ((math.log10(x_max / x_min)) / (math.log10(y_max / y_min))))

rawDescription: How to create square log-log plots in matplotlib?

description: Create square log-log plots in matplotlib


code:
for value in Session.query(Table.column).distinct():
     pass

rawDescription: Selecting distinct column values in SQLAlchemy/Elixir


code:
res = numpy.empty_like(X)
for i, A in enumerate(X):
    res[i] = numpy.linalg.inv(A)

rawDescription: Numpy linalg on multidimentional arrays

description: Numpy linalg on multidimentional arrays


code:
import operator
ops = {'*': operator.mul, '/': operator.div, '+': operator.add, '-': operator.sub}

op = input("Please enter  *,  /,  +,  or  - : ")
result = ops[op](x, y)

rawDescription: Strings, ints, and operators in Python

description: Strings, ints, and operators in Python


code:
if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-k", dest = "foo",  action='store_true')
    args = parser.parse_args()
    # do things...

rawDescription: python import of script with argparse

description: Python import of script with argparse


rawDescription: Scipy Sparse Row/Column Dot Products

description: Scipy Sparse Row/Column Dot Products


code:
def myfunk( inHole, outHole):
    for keys in inHole.keys():
        is_list = isinstance(inHole[keys],list);
        is_dict = isinstance(inHole[keys],dict);
        if is_list:
            element = inHole[keys];
            new_element = {keys:element};
            outHole.append(new_element);
        if is_dict:
            element = inHole[keys].keys();
            new_element = {keys:element};
            outHole.append(new_element);
            myfunk(inHole[keys], outHole);
        if not(is_list or is_dict):
            new_element = {keys:inHole[keys]};
            outHole.append(new_element);
    return outHole.sort();

rawDescription: Parsing Google Custom Search API for Elasticsearch Documents


code:
proc =  subprocess.Popen( ["python" , path + "/pythonChild.py"], preexec_fn=os.setsid, stdout=subprocess.PIPE ,stdin=subprocess.PIPE)
os.killpg( proc.pid, 9 )

rawDescription: Can't close processes using selenium threads


code:
import csv

def splitit(inputfilename):
  with open(inputfilename, 'rb') as inf:
    inrd = csv.reader(inf)
    names = next(inrd)
    outfiles = [open(n+'.csv', 'wb') for n in names]
    ouwr = [csv.writer(w) for w in outfiles]
    for w, n in zip(ouwr, names):
      w.writerow([n])
    for row in inrd:
      for w, r in zip(ouwr, row):
        ouwr.writerow([r])
    for o in outfiles: o.close()

rawDescription: How to break a large CSV data file into individual data files?

description: Break a large CSV data file into individual data files


code:
from gaesessions import get_current_session
session = get_current_session()
if session.is_active():
    c = session.get('counter', 0)
    session['counter'] = c + 1
    session['blah'] = 325
    del session.blah  # remove 'blah' from the session

rawDescription: Preserve POST variables during login redirect in GAE?


code:
import time
import serial
import sys
import os
import tkinter as tk
from tkinter import ttk
from tkinter import *
try:
  import Tkinter
  import ttk
except ImportError:
  import tkinter as Tkinter
  import tkinter.ttk as ttk
import time
mGui = Tk()
mGui.title("GUI")
mGui.geometry('120x450+100+100')
BarVolSyringe1 = ttk.Progressbar(mGui, orient='vertical', length=78, mode='determinate', value = 0)
BarVolSyringe2 = ttk.Progressbar(mGui, orient='vertical', length=78, mode='determinate', value = 0)
BarVolSyringe1.place(x=52,y=38)
BarVolSyringe2.place(x=30,y=38)
SFg=0
SFd=0
SyringeSize = 1000
Sy = SyringeSize/100
SVV_1 = 500
def mAspire():
 global SFg,SFd, BarVolSyringe2,BarVolSyringe1
 if SVV_1<=SyringeSize:
  while 0<=SFg<SVV_1:
    SFg=SFg+1
    SFd=SFd+1
    time.sleep(0.0001)
    BarVolSyringe1.step(1/Sy)
    BarVolSyringe2.step(1/Sy)
    mGui.update()
    print (SFg)
  else:
    mGui.update()
    SFg=0
    print (SFd)
  if (SFd >= SyringeSize):
    BarVolSyringe1.stop()
    BarVolSyringe2.stop()
    BarVolSyringe1 = ttk.Progressbar(mGui, orient='vertical', length=78, mode='determinate', value = 100)
    BarVolSyringe2 = ttk.Progressbar(mGui, orient='vertical', length=78, mode='determinate', value = 100)
    BarVolSyringe1.place(x=52,y=38)
    BarVolSyringe2.place(x=30,y=38)
    SFg=SVV_1
 else:
  messagebox.showerror("ERROR", "Please Select a valve")
mButtonAs = Button(mGui, text = "up", command = mAspire, fg = 'Black').place(x=10,y=60)

def dw():
  global SFg,SFd, BarVolSyringe2,BarVolSyringe1
  SFg=0
  while 0<=SFg<SVV_1:
    SFg=SFg+1
    SFd=SFd-1
    time.sleep(0.0001)
    BarVolSyringe1.step(-(1/Sy))
    BarVolSyringe2.step(-(1/Sy))
    mGui.update()
    print (SFg)
  else:
    mGui.update()
    SFg=0
    print (SFd)
  if (SFd == 0):
    BarVolSyringe1.stop()
    BarVolSyringe2.stop()
    BarVolSyringe1 = ttk.Progressbar(mGui, orient='vertical', length=78, mode='determinate', value = 0)
    BarVolSyringe2 = ttk.Progressbar(mGui, orient='vertical', length=78, mode='determinate', value = 0)
    BarVolSyringe1.place(x=52,y=38)
    BarVolSyringe2.place(x=30,y=38)

mButtonAs = Button(mGui, text = "dw", command = dw, fg = 'Black').place(x=10,y=90)

rawDescription: Progressbar is not going down python 3.4 tkinter


rawDescription: Convert Python ctypes.Structure into str


code:
MYDIR = '/tmp/log'
LOGGING_CONFIG = {
    'version': 1,
    'disable_existing_loggers': True,
    'incremental': False,

    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'stream': 'ext://sys.stdout'
        },
        'rotatingfile': {
            'class': 'logging.handlers.RotatingFileHandler',
            'filename': os.path.join(MYDIR, 'application.log'),
            'maxBytes': 5e6,
            'backupCount': 10
        }
    },

    'loggers': {
        'device': {
            'handlers': [
                'console',
                'rotatingfile'
            ],
            'level': 'DEBUG',
           'propagate': True
        },
    }
}

rawDescription: Defining handler in-line when defining logger


code:
def parse(self, response):
    hxs = HtmlXPathSelector(response)
    titles = hxs.select('//td[@class="title"]')
    items = []
    for title in titles:
        item = HackernewsItem()
        item["title"] = title.select("a/text()").extract()
        item["url"] = title.select("a/@href").extract()
        item["score"] = title.select('../td[@class="subtext"]/span/text()').extract()
        items.append(item)
    return items

rawDescription: Python: Scrapy CSV exports incorrectly?

description: Python: Scrapy CSV exports incorrectly