code:
def yield_files(root):
    for root, dirs, files in os.walk(root):
        for filename in files:
            filename = os.path.join(root, filename)
            if os.path.isfile(filename) or os.path.isdir(filename):
                yield FileInfo(filename)

rawDescription: looping thru Python's os.walk() confusion

description: Looping thru Python's os.walk() confusion


code:
MAX_SIZE = 300 * 1024 * 1024
LOG_PATH = fdoc_log + "/plus_dig_cname.log"
fh = logging.handlers.RotatingFileHandler(LOG_PATH, maxBytes=MAX_SIZE, backupCount=5)

rawDescription: How to clear the log file and write it again?

description: Clear the log file and write it again


code:
text = '''
  Heading
  =======
  .. raw:: html

Test

'''
docutils.core.publish_parts(text, writer_name='html')['html_body']

rawDescription: Don't escape HTML with docutils.core.publish_parts(writer_name="html")


code:
def foo(**kwargs):
    pass

foo(**{ 'foo' : 123, 'bar' : 456 })

rawDescription: How to generate a `kwargs` list?

description: Generate a `kwargs` list


code:
class classinstancemethod(object):
    """
    Acts like a class method when called from a class, like an
    instance method when called by an instance.  The method should
    take two arguments, 'self' and 'cls'; one of these will be None
    depending on how the method was called.
    """

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

    def __get__(self, obj, type=None):
        return _methodwrapper(self.func, obj=obj, type=type)

class _methodwrapper(object):

    def __init__(self, func, obj, type):
        self.func = func
        self.obj = obj
        self.type = type

    def __call__(self, *args, **kw):
        assert 'self' not in kw and 'cls' not in kw, (
            "You cannot use 'self' or 'cls' arguments to a "
            "classinstancemethod")
        return self.func(*((self.obj, self.type) + args), **kw)

    def __repr__(self):
        if self.obj is None:
            return ('<bound class method %s.%s>'
                    % (self.type.__name__, self.func.func_name))
        else:
            return ('<bound method %s.%s of %r>'
                    % (self.type.__name__, self.func.func_name, self.obj))

rawDescription: Duck typing and class methods (or, how to use a method from both a class and an instance?)


code:
class MyClass(object):
    def __init__(self, v1, v2, v3, v4):
        self.var1 = v1
        self.var2 = v2
        self.var3 = v3
        self.var4 = v4

    def run(self):
        while True:
            self.foo()
            self.bar()
            self.tar()

    def foo(self):
        """does something with var2, var3 and var4"""
        return self.var2, self.var3, self.var4

    def bar(self):
        """does something with var1 and var3"""
        return self.var1, self.var3

    def tar(self):
        """does something with var4 and var1"""
        return self.var4, self.var1

if __name__ == "__main__":
    mc = MyClass('x', [], {}, 'y')
    mc.run()

rawDescription: Python: Access all Parent Variables in Nested Function


rawDescription: How to store values of double in a single list

description: Store values of double in a single list


code:
import os
def accessible(dir):
    try:
        os.listdir(dir)
    except OSError:
        return False
    return True
print(accessible('/root'))

rawDescription: Checking Linux Directory Permissions with Python


code:
from flask import Flask, render_template, request, jsonify
import redis, pickle

app = Flask(__name__)
r = redis.Redis("localhost")

@app.route("/")
def main():
    return render_template('index.html')

@app.route('/saveMap',methods=['POST'])
def saveMap():
    if request.method == "POST":
        r.set("test", pickle.dumps(request.json))
        result = pickle.loads(r.get("test"))
        return jsonify(result)

if __name__ == "__main__":
    app.run(debug=True)

rawDescription: Round-trip passing of data from Javascript to Redis (via Python) and back?


code:
from sys import argv

script, input_file = argv

def make_one_line(f):
    uncommented_lines = (line.rstrip('\n\r').split('#')[0] for line in f) #
    return ';'.join(uncommented_lines)

#print "This will rewrite the file, press CTRL-C to cancel."
#raw_input('Press any key (but CTRL-C) to continue.')

current_file = open(input_file, 'rU') # Open in universal newline mode
final = make_one_line(current_file)
current_file.close()
outfile = open("out_"+input_file, "wt") # Save the output in a new file
outfile.write(final)
outfile.write('\n')
outfile.close()

rawDescription: My one-line-rewriter only rewrites part of a script


code:
dispatch = {0: level0, 1: level1, 2:level2}
dispatch[offset].calc_algorithm

rawDescription: Aliasing a class in Python

description: Aliasing a class in Python


code:
p = subprocess.Popen("yourcmd" + " yourarg", shell=True, cwd="c:/your/path")
sts = os.waitpid(p.pid, 0)[1]

rawDescription: Python: Is it possible to change the Windows command line shell current directory without changing the actual current directory?


code:
def wszarray_to_list(array):
    offset = 0
    while offset < ctypes.sizeof(array):
        sz = ctypes.wstring_at(ctypes.addressof(array) + offset*2)
        if sz:
            yield sz
            offset += len(sz)+1
        else:
            break

rawDescription: Python ctypes - how to handle arrays of strings


code:
class Business(db.Model):
    __tablename__ = 'business'
    id = db.Column(db.Integer, primary_key=True)

    name = db.Column(db.String, nullable=False)
    latitude = db.Column(db.Float, nullable=True)
    longitude = db.Column(db.Float, nullable=True)

    @db.validates('latitude')
    def validate_lat(self, key, value):
        assert value is None or (-90 <= value <= 90)
        return value

    @db.validates('longitude')
    def validate_lon(self, key, value):
        assert value is None or (-180 <= value <= 180)
        return value

rawDescription: Python ORMs with attribute constraints such as required / optional?


code:
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class Image(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

rawDescription: ForeignKey with multiple models

description: ForeignKey with multiple models


code:
class MultiTabNavTool(qt.QWidget):

    def __init__(self, canvases, tabs, parent=None):
        qt.QWidget.__init__(self, parent)
        self.canvases = canvases
        self.tabs = tabs
        self.toolbars = [NavigationToolbar(canvas, parent) for canvas in self.canvases]
        vbox = qt.QVBoxLayout()
        for toolbar in self.toolbars:
            vbox.addWidget(toolbar)
        self.setLayout(vbox)
        self.switch_toolbar()
        self.tabs.currentChanged.connect(self.switch_toolbar)

    def switch_toolbar(self):
        for toolbar in self.toolbars:
            toolbar.setVisible(False)
        self.toolbars[self.tabs.currentIndex()].setVisible(True)

rawDescription: python matplotlib and PyQT for multi-tab plotting - navigation

description: Python matplotlib and PyQT for multi-tab plotting - navigation


code:
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_yticks((2,5,7))
labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))

def on_draw(event):
   bboxes = []
   for label in labels:
       bbox = label.get_window_extent()
       # the figure transform goes from relative coords->pixels and we
       # want the inverse of that
       bboxi = bbox.inverse_transformed(fig.transFigure)
       bboxes.append(bboxi)

   # this is the bbox that bounds all the bboxes, again in relative
   # figure coords
   bbox = mtransforms.Bbox.union(bboxes)
   if fig.subplotpars.left < bbox.width:
       # we need to move it over
       fig.subplots_adjust(left=1.1*bbox.width) # pad a little
       fig.canvas.draw()
   return False

fig.canvas.mpl_connect('draw_event', on_draw)

plt.show()

rawDescription: Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?


code:
from collections import Counter, defaultdict
genredict = defaultdict(Counter)
genredict
genredict['rock']['good'] += 1  # increment appropriate genre/rating
genredict['blues']['normal'] += 1
genredict
genredict['rock']['good']  # retrieve current score

rawDescription: Saving a variable and a constant in a dictionary on Python


code:
set.seed(12345)
n <- 35000
dataset <- data.frame(Number = runif(n, min = -200, max = 50000))
library(ggplot2)
ggplot(dataset, aes(x = Number)) + geom_histogram(binwidth = 200)

rawDescription: Binning the data & plotting the histogram


code:
files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path,f))]
for fname in files:
    fpath = os.path.join(path, fname)
    os.remove(fpath)

rawDescription: How to delete all files in a directory, keeping sub-directories intact

description: Delete all files in a directory, keeping sub-directories intact


code:
d={"key" : (100,"edge_list")}
for i,(time,edge_list) in d.items():
 d[i] = time+1, edge_list

d

rawDescription: Python : updating values in a dictionary


code:
import numpy as np
import matplotlib.cm as cm

def Draw(self, visibility = None):
    nlines = len(self._data)
    # Choose whichever colormap you like here instead of jet
    colours = cm.jet(np.linspace(0,1,nlines))  # a list of colours the same length as your data
    self._axes.lines = []
    # if no visibility data, draw all
    if visibility is None:
        visibility = []
        for i in range(len(self._data)):
            visibility.append(True)
    else:
        # check if length match
        if len(self._data) != len(visibility):
            raise AttributeError('Visibility list length does not match plot count')
    # draw the lines you want
    for i in range(len(self._data)):
        if visibility[i]:
            plotName = 'FFD ' + str(i + 1)
            # pick a colour from the colour list using the color kwarg
            self._axes.plot(self.timebase, self._data[i], picker=5, color=colours[i], label = plotName)
    #if there are any lines, draw a legend
    if len(self._axes.lines):
        self._axes.legend(prop={'size':9})

    #update the canvas
    self._canvas.draw()

rawDescription: Hide Lines from Matplotlib Plot without redrawing them?


rawDescription: Selecting rows if at least values in one column satisfy a condition using Pandas any


code:
import subprocess
import sys

cmd = ['/media/sf_git/test-automation/src/SalesVision/mswm/shell_test.sh', '4', '2']
print('running command: "{0}"'.format(cmd))  # output the command.
# Here, we join the STDERR of the application with the STDOUT of the application.
process = subprocess.Popen(cmd, bufsize=1, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for line in iter(process.stdout.readline, ''):
    line = line.replace('\n', '')
    print(line)
    sys.stdout.flush()
process.wait()                   #  Wait for the underlying process to complete.
errcode = process.returncode      #  Harvest its returncode, if needed.
print( 'Script ended with return code of: ' + str(errcode) )

rawDescription: python subprocess.call output is not interleaved

description: Python subprocess.call output is not interleaved


code:
def _unidiff_output(expected, actual):
    """
    Helper function. Returns a string containing the unified diff of two multiline strings.
    """

    import difflib
    expected=expected.splitlines(1)
    actual=actual.splitlines(1)

    diff=difflib.unified_diff(expected, actual)

    return ''.join(diff)

rawDescription: How to print the comparison of two multiline strings in unified diff format?

description: Print the comparison of two multiline strings in unified diff format


rawDescription: how to run vcvarsall.bat from python subprocess

description: Run vcvarsall.bat from python subprocess


code:
def get_non_touching(ref_node):
    qry = session.query(Node)
    qry = qry.filter(~Node.lower_edges.any(Edge.higher_id == ref_node.node_id))
    qry = qry.filter(~Node.higher_edges.any(Edge.lower_id == ref_node.node_id))
    qry = qry.filter(Node.node_id != ref_node.node_id) # exclude node "a" itself as well
    return qry.all()

a = session.query(Node).get(1)
res = get_non_touching(a)

rawDescription: With graphs in SQLAlchemy, how can one find nodes that are not connected to some specific other node by an edge?


code:
import collections, re

d = {"key1" : 'object', "key11" : 'object', "key2" : 'object', "key22" : 'object', "jay1" : 'object', "jay2" : 'object'}

my_fun = lambda k,v: [k, int(v)]

d2 = collections.OrderedDict(sorted(d.items(), key=lambda t: my_fun(*re.match(r'([a-zA-Z]+)(\d+)',t[0]).groups())))

print(d2)
#reslt: OrderedDict([('jay1', 'object'), ('jay2', 'object'), ('key1', 'object'), ('key11', 'object'), ('key2', 'object'), ('key22', 'object')])

rawDescription: Sort Dictionary Keys in natural order

description: Sort Dictionary Keys in natural order


rawDescription: What is the most efficient way to sort a list of dates in string format in Python?


rawDescription: python replace special characters except dashes and periods

description: Python replace special characters except dashes and periods


code:
class Day (db.Model):
    courtday = db.ReferenceProperty(CourtDays)
    startTime = db.TimeProperty()
    endTime = db.TimeProperty()
    startTimeLunch = db.TimeProperty()
    endTimeLunch = db.TimeProperty()
    name = db.StringProperty()

days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
for dayname in days:
  newday = Day(name=dayname)
  newday.put()

rawDescription: dynamically constructing appengine model names in python

description: Dynamically constructing appengine model names in python


rawDescription: python and ctypes cdll, not getting expected return from function

description: Python and ctypes cdll, not getting expected return from function


code:
def subseq(s1,s2):
    if s1 in s2: return True
    if not s1: return True
    if not s2: return False
    #everything else
    if s1[0] == s2[0]: return subseq(s1[1:],s2[1:])
    return subseq(s1,s2[1:])

rawDescription: Using recursion to find subsequences

description: Using recursion to find subsequences


code:
L = ['AAG', 'AGA', 'GAT', 'ATT', 'TTC', 'TCT', 'CTC', 'TCT', 'CTA', 'TAA', 'AAG', 'AGA']
L2 = zip(L, L[1:])
from collections import defaultdict
D = defaultdict(list)
for i, j in L2:
    D[i].append(j)

for k in sorted(D):
    print(k, "->", ",".join(D[k]))

rawDescription: make tuple pairs from list's element Python

description: Make tuple pairs from list's element Python


code:
text_fields = {
    'city': request.POST.get('city'),
    'state': request.POST.get('state'),
    'province': request.POST.get('province'),
    'used_teargas': request.POST.get('teargas'),
    'victim_1_name': request.POST.get('victim_name'),
    'victim_1_ethnicity': request.POST.get('victim_ethnicity'),
    'victim_1_age': request.POST.get('victim_age'),
    'victim_1_sex': request.POST.get('victim_sex'),
    'victim_1_status': request.POST.get('victim_status'),
}

boolean_fields = {
    'used_taser': request.POST.get('taser'),
    'used_teargas': request.POST.get('teargas'),
    'victim_1_armed': request.POST.get('victim_armed')
}

q_objects = Q()

for field, value in text_fields.iteritems():
    if value:
        q_objects |= Q(**{field+'__contains': value})

for field, value in boolean_fields.iteritems():
    if value:
        q_objects |= Q(**{field: True})

incidents = Incident.objects.filter(
    Q(datepicker__range=[date_start, date_end]),
    Q(country__contains=country),
    q_objects
)

rawDescription: Python Django "and/or" searching in database


code:
from ua_parser import user_agent_parser
parsing_dict = {}
os_stats = {}
browser_stats = {}
target = 'tindex.ru'
def grep(filename, pattern):
    def parse_ua(ua):
            p = ua_parser.user_agent_parser.Parse(ua)
            return [p.get('os').get('family'), p.get('user_agent').get('family')]

    for n,line in enumerate(open(filename)):
        if target in line:
            ua_start = line.find(pattern) + len(pattern)
            ua_end = line.find('\t', ua_start)
            ua = line[ua_start:ua_end]
            try:
                parsing_dict[ua] += 1
            except KeyError:
                parsing_dict[ua] = 1

    for key, value in parsing_dict.iteritems():
        ua = parse_ua(key)
        try:
                os_stats[ua[0]] += value
                browser_stats[ua[1]] += value
        except KeyError:
                os_stats[ua[0]] = value
                browser_stats[ua[1]] = value
grep('data/data.tsv', 'user_agent=')

rawDescription: Python & BigData. Alternative to user_agents (works really slow with large datasets)?


code:
df = pd.DataFrame(np.random.randint(0, 2, (10, 4)))
df
df[df.duplicated()]

rawDescription: Viewing duplicated rows in Pandas

description: Viewing duplicated rows in Pandas


rawDescription: Aggregation on pandas datetime series only returns as datetime series


code:
def count(lst, target):
    n = 0
    for i in lst:
        if i == target:
            n += 1
        elif type(i) is list:
            n += count(i, target)
    return(n)

rawDescription: Recursively counting occurrences in a nested list of numbers


code: value = struct.unpack("<d", data[:8])

rawDescription: How can I store the value from a python socket in a double?

description: Store the value from a python socket in a double


code:
import numpy as np

N = 100
b = np.random.random_integers(-2000,2000,size=(N,N))
b_symm = (b + b.T)/2

rawDescription: Generating Symmetric Matrices in Numpy

description: Generating Symmetric Matrices in Numpy


code:
import pythoncom, pyHook

def uMad(event):
    return False

hm = pyHook.HookManager()
hm.MouseAll = uMad
hm.KeyAll = uMad
hm.HookMouse()
hm.HookKeyboard()
pythoncom.PumpMessages()

rawDescription: disable or lock mouse and keybord in python?

description: Disable or lock mouse and keybord in python


code:
def match(pattern, string, flags=0):
    return _compile(pattern, flags).match(string)

def _compile(*key):

    # Does cache check at top of function
    cachekey = (type(key[0]),) + key
    p = _cache.get(cachekey)
    if p is not None: return p

    # ...
    # Does actual compilation on cache miss
    # ...

    # Caches compiled regex
    if len(_cache) >= _MAXCACHE:
        _cache.clear()
    _cache[cachekey] = p
    return p

rawDescription: Is it worth using Python's re.compile?

description: Is it worth using Python's re.compile


code:
def Startup():
    global PasswordSkip

rawDescription: Booleans in If Statements in Python

description: Booleans in If Statements in Python


code:
class SplitterFrame (wx.Frame):
    def __init__(self):
        #Create a master window
        wx.Frame.__init__(self,None,title = 'some frame')
        self.splitter = wx.SplitterWindow(self,-1, style = wx.SP_LIVE_UPDATE)
        self.splitter2 = wx.SplitterWindow(self.splitter,-1, style = wx.SP_LIVE_UPDATE)
        self.splitter.SetMinimumPaneSize(20)
        self.splitter2.SetMinimumPaneSize(20)

        self.panel1 = wx.Panel(self.splitter,-1)
        self.panel1.SetBackgroundColour(wx.WHITE)

        self.panel2 = wx.Panel(self.splitter2,-1)
        self.panel2.SetBackgroundColour(wx.WHITE)

        self.panel3 = wx.Panel(self.splitter2, -1)
        self.panel3.SetBackgroundColour(wx.WHITE)

        #Splitter window attributes
        self.splitter2.SplitVertically(self.panel2,self.panel3, 100)
        self.splitter.SplitVertically(self.panel1,self.splitter2, 100)
        self.splitter.SetSashGravity(0)
        self.splitter2.SetSashGravity(1)
        self.Centre()
        self.Layout()
        self.Maximize(True)
        self.Bind(wx.EVT_SIZE, self.OnSize)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.splitter,2,wx.ALL|wx.EXPAND)
        self.SetSizer(sizer)

    def OnSize(self, evt):
        evt.Skip()
        # here you will change the sash positions to your liking
        self.splitter.SetSashPosition(100,redraw = True)
        self.splitter2.SetSashPosition(200,redraw = True)

rawDescription: Sizers for wx.SplitterWindow not working wxPython


rawDescription: How to do "insert if not exist else update" with mongoengine?

description: Do "insert if not exist else update" with mongoengine


code:
from bottle import response

@route('/', method='GET')
def homepage():
    response.status = 202
    return {'foo' : 'bar'}

rawDescription: Send dict as response in Python Bottle with custom status code


code:
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

x, n = np.mgrid[0:20:0.01, 1:100:1]

mu = 0
sigma = np.sqrt(2)/n

f = norm.cdf(x, mu, sigma)

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(x, n, f, rstride=x.shape[0]//20, cstride=x.shape[1]//20, alpha=0.3)

plt.show()

rawDescription: Algorithm equalivence from Matlab to Python


code:
dates = sorted(list(set(day_date)))
# Plot
fig, ax = plt.subplots()
for name, group in df_tmp.groupby('country_code'):
    xvals = [dates.index(d) for d in group.day_date]
    ax.plot(xvals, group.val, label=name)

plt.xticks(range(len(dates)),dates,rotation = 45)

rawDescription: Prevent from converting string to int in xaxis in plot by groups


code:
size = 2        # sample size
replace = True  # with replacement
fn = lambda obj: obj.loc[np.random.choice(obj.index, size, replace),:]
df.groupby('Group_Id', as_index=False).apply(fn)

rawDescription: Python: Random selection per group

description: Python: Random selection per group


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

def plotter ( ax, col ):
    data = np.random.normal( size=(50, 2 ) )
    x, y = data[:, 0], data[:, 1 ]
    ax.scatter( x, y, color=col )

fig = plt.figure()
ax = fig.add_axes([0.2, 0.2, 0.7, 0.6])

plotter( ax, 'Blue' )
plotter( ax, 'Red' )
fig.show( )

rawDescription: Draw several graphs in matplotlib, python


code:
for i in range(0, 1024):
    writer.writerow([iData[i], qData[i]])

rawDescription: How to export multiple arrays from IronPython to CSV

description: Export multiple arrays from IronPython to CSV


code:
def drawfig_1(ax1):
    ax1.plot(range(10))
    return ax1

# Setup plots for analysis
fig2 = plt.figure(figsize=(12, 8))

# Set up 2 axes, one for a pixel map, the other for an image
ax_map = plt.subplot2grid((3, 3), (0, 0), rowspan=3)
ax_image = plt.subplot2grid((3, 3), (0, 1), colspan=2, rowspan=3)

# Plot the image
ax_image.imshow(image, vmin=0.00000001, vmax=0.000001, cmap=cm.gray)
# Plot the map:
drawfig_1(ax_map)

rawDescription: Using passed axis objects in a matplotlib.pyplot figure?


code:
def tiger(inval, start, end):
    base = list(inval[start: end])
    spaces = 0
    while spaces < 2 and end < len(inval):
        char = inval[end]
        if char == " ":
            spaces += 1
        base.append(char)
        end += 1
    return "".join(base).strip()
tiger(_string, 0, 8)
tiger(_string, 23, 35)
tiger(_string, 45, 85)

rawDescription: Extracting sub-strings with an extension of the last character


code:
# since the string value of `message` itself isn't a valid json string
# discard it, and parse it with json again
brow_eventdetails = json.loads(json_data['message'].replace('brow_eventdetails:', ''))

brow_eventdetails['ATime']
Out[6]: 5

brow_eventdetails['SBTime']
Out[7]: 391

brow_eventdetails['CTime']
Out[8]: 425

...

rawDescription: Extracting values form nested JSON document


code:
a = np.arange(50)
b = a[10:20]
print (b.base is a)

rawDescription: find parent array of numpy slice array

description: Find parent array of numpy slice array


code:
import operator

ops = {
    '+' : operator.add,
    '-' : operator.sub,
    '*' : operator.mul,
    '/' : operator.truediv,
    '%' : operator.mod,
}

precedence = [
    set(['*', '/', '%']),
    set(['+', '-']),
]

def evaluate(expr):
    # if len == 3 then just return result of expression
    if len(expr) == 3:
        l, op, r = expr
        return ops[op](l, r)
    else:
        for op_list in precedence:
            for op in expr:
                if op in op_list:
                    # find index of first operation
                    idx = expr.index(op)-1
                    # pop off and evaluate first matching operation in expr
                    result = evaluate([expr.pop(idx) for i in range(3)])
                    # insert result back into expr
                    expr.insert(idx, result)
                    return evaluate(expr)

rawDescription: Is there a better way to implement this?

description: Is there a better way to implement this


rawDescription: Build a graph as a subset of another, larger, graph [iGraph, Python]


code:
str = "FieldStorage('myfile', 'file.exe', 'hello\\n')"
obj = eval(str)

rawDescription: How can I get a FileStorage object from string

description: Get a FileStorage object from string


code:
#!/usr/bin/env python3

modules = [
  [ 'my_aux', '''
def my_aux():
  return 7
'''],
  ['my_func', '''
from my_aux import my_aux
def my_func():
  print("and I'm my_func: {0}".format(my_aux()))
'''],
  ['my_script', '''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import (unicode_literals, division, absolute_import, print_function)
import sys
def main(my_name):
  import my_aux
  print("Hello, I'm my_script: {0}".format(my_name))
  print(my_aux.my_aux())
  import my_func
  my_func.my_func()
if (__name__ == '__main__'):
  sys.exit(main(__file__))
'''],
]

import sys, types
for m in modules:
  module = types.ModuleType(m[0])
  exec(m[1], module.__dict__)
  sys.modules[m[0]] = module
del modules

from my_script import main

main(__file__)

rawDescription: Distributing set of python files as a single executable


code:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout

class TestApp(App):
    def build(self):
        root = FloatLayout()
        layout = BoxLayout(orientation='vertical', size=(200,200), size_hint=(None, None))
        btn1 = Button(text='Hello', size=(50,50), size_hint=(None, None))
        btn2 = Button(text='World', size=(50,50), size_hint=(None, None))
        layout.add_widget(btn1)
        layout.add_widget(btn2)
        root.add_widget(layout)
        return root
TestApp().run()

rawDescription: Can't set layout size in Kivy

description: Can't set layout size in Kivy


code:
def __copy__(self):
  newone = type(self)()
  newone.__dict__.update(self.__dict__)
  return newone

rawDescription: What is the right way to override the copy/deepcopy operations on an object in Python?


code:
for items in data:
  id, salary, title, lastname, firstname = items
  employee(lastna,e, firstname, id, title, salary)

rawDescription: Python rearranging a list into a tuple

description: Python rearranging a list into a tuple


code:
for model_field in SOA_detail._meta._fields():
  if isinstance(model_field, CharField):
      char_fields.append(model_field.name)
  elif isinstance(model_field, IntegerField):
      num_fields.append(model_field.name)
  elif isinstance(model_filed, DateTimeField):
      date_field.append(model_field.name)

rawDescription: How to check django model data type?

description: Check django model data type


code:
import matplotlib.pyplot as pyplot

x = [0, 1, 2, 3, 4]
y = [xx*xx for xx in x]

fig = pyplot.figure(figsize=(3,3))
ax  = fig.add_subplot(111)

#box = ax.get_position()
#ax.set_position([0.3, 0.4, box.width*0.3, box.height])
# you can set the position manually, with setting left,buttom, witdh, hight of the axis
# object
ax.set_position([0.1,0.1,0.5,0.8])
ax.plot(x, y)
leg = ax.legend(['abc'], loc = 'center left', bbox_to_anchor = (1.0, 0.5))

fig.savefig('aaa.png')

rawDescription: Matplotlib savefig with a legend outside the plot


code:
from struct import *
from itertools import chain
a = [(1, 67), (213, 455), (9009, 8887)]
# converts 3x2 list to 6x1 list
b = list(chain(*a))
size=6
qq = pack('=h'+'L'*size,size,*b)
# peak to get the list length
mysize = unpack('=h',qq[:2])
mysize = mysize[0]
unpack('=L',qq[2:6])
unpack('=h'+'L'*mysize,qq)
unpack('=' + 'L'*mysize, qq[2:])   # does not work
unpack('=' + 'L'*mysize, qq[2:2+mysize*4])  # works

rawDescription: python: struct pack size longer than expected -- why does this happen?

description: Python: struct pack size longer than expected -- why does this happen


code:
lst = []
lst.extend("foo")
lst
lst.append("foo")
lst

rawDescription: CSV Columns to Arrays in Python

description: CSV Columns to Arrays in Python


code: i = 7*int(round(x/7))

rawDescription: how to set interval by using widgets slider in mabplotlib

description: Set interval by using widgets slider in mabplotlib


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib
import json

import cherrypy
import voluptuous as volu

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  },
  '/' : {
    'recaptcha' : {
        # By default, all keys work on localhost
       'siteKey' : '6LeYIbsSAAAAACRPIllxA7wvXjIE411PfdB2gt2J',
       'secret'  : '6LeYIbsSAAAAAJezaIq3Ft_hSTo0YtyeFG-JgRtu'
     }
  }
}

def validateRecaptcha(value):
  '''https://developers.google.com/recaptcha/docs/verify'''

  if 'g-recaptcha-response' not in cherrypy.request.params:
    raise volu.Invalid('Recaptcha response is missing')

  payload = urllib.urlencode({
    'secret'   : cherrypy.request.config['recaptcha']['secret'],
    'remoteip' : cherrypy.request.headers['remote-addr'],
    'response' : cherrypy.request.params['g-recaptcha-response']
  })

  url      = 'https://www.google.com/recaptcha/api/siteverify'
  response = json.load(urllib.urlopen(url, payload))
  if not response['success']:
    cherrypy.log(str(response))
    raise volu.Invalid(response['error-codes'])

class App:

  @cherrypy.expose
  def index(self, **kwargs):
    form = dict(form = {'value': ''}, errors = '')

    if cherrypy.request.method == 'POST':
      schema = volu.Schema({
        'value'                : volu.All(unicode, volu.Length(min = 8, max = 16)),
        'g-recaptcha-response' : validateRecaptcha,
      }, required = True, extra = True)
      try:
        kwargs = schema(kwargs)
      except volu.MultipleInvalid as ex:
        form = dict(form = kwargs, errors = {e.path[0] for e in ex.errors})
      else:
        raise cherrypy.HTTPRedirect('#success')

    return '''<!DOCTYPE html>

          <title>reCAPTCHA demo</title>

          <form action="/" method="POST">

{errors}

Name

            <input type="text" name="value" value="{form[value]}"/>

            <input type="submit" value="Submit"/>
          </form>

    '''.format(cherrypy.request.config['recaptcha']['siteKey'], **form)

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: How to integrate Captcha (Recaptcha) for WTForms in CherryPy

description: Integrate Captcha (Recaptcha) for WTForms in CherryPy


code:
import matplotlib.pyplot as plt

tPlot, axes = plt.subplots(
        nrows=4, ncols=1, sharex=True, sharey=False,
        gridspec_kw={'height_ratios':[2,2,1,1]}
        )

tPlot.suptitle('node', fontsize=20)

axes[0].plot(range(10),'ro-')
axes[1].plot(range(10),'bo-')
axes[2].plot(range(10),'go-')
axes[3].plot(range(10),'mo-')

plt.show()

rawDescription: How to use `GridSpec()` with `subplots()`

description: Use `GridSpec()` with `subplots()`


code:
image_path = 'http://img.hb.aicdn.com/3e32a8b101e515b9e7dbe8f5a2e47afff5ec6bcf4e4a-OTvsuu_fw192'
with open(r'<path_to_file>.jpg', 'wb') as image:
    image.write(urllib2.urlopen(image_path).read())

rawDescription: How to download all pics in this website: huaban.com

description: Download all pics in this website: huaban.com


code:
for field in self.fields:
    if isinstance(field, forms.IntegerField):
        field.widget.attrs['class'] = 'biggerWidth'

rawDescription: Get all fields from model that are of specific type in django


code:
from uwsgidecorators import *
from gevent.queue import Queue

channels = []

@filemon('/tmp',target='workers')
def trigger_event(signum):
    for channel in channels:
        try:
            channel.put_nowait(True)
        except:
            pass

def application(e, sr):
    sr('200 OK', [('Content-Type','text/html')])
    yield "Hello and wait..."
    q = Queue()
    channels.append(q)
    q.get()
    yield "event received, goodbye"
    channels.remove(q)

rawDescription: trigger WebSocket in Flask from external event

description: Trigger WebSocket in Flask from external event


code:
textfromfile = '102'
defaultobject = 101
value = (type(defaultobject))(textfromfile)

rawDescription: In python, detect type, then cast to that type


code: popt, pcov = cf(model, Ts, ts, p0 = (10, 7, 6))

rawDescription: Curve Fitting in Python not fitting my curve


code:
four_letter_intersection = {
    word for word in set(list_a).intersection(list_b) if len(word) == 4
    }

rawDescription: Intersection of lists, look for on length


code:
import socket

HOST='127.0.0.1'
PORT=9003
BUFFER=4096
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

sock.bind((HOST,PORT))

sock.listen(0)
print('tcpServer listen at: %s:%s\n\r' %(HOST,PORT))
while True:
  client_sock,client_addr=sock.accept()
  print('%s:%s connect' %client_addr)
  recv=client_sock.recv(BUFFER)
  if not recv:
    client_sock.close()
    break
  print('[Client %s:%s said]:%s' % (client_addr[0],client_addr[1],recv))
  client_sock.send('HTTP/1.1 200 OK \n Content-type:text/html\r\n\r\n tcpServer has received your message')
  client_sock.close()
sock.close()

rawDescription: a issue about python socket

description: A issue about python socket


code: num1 = intvalue or 10

rawDescription: One line if assignment in python

description: One line if assignment in python


rawDescription: linear interpolation in scipy

description: Linear interpolation in scipy


code:
my_string = "Value1=Product Registered;Value2=Linux;Value3=C:5;C++:5;Value4=43;"
r = re.compile(r'([^;]+)=([^=]+);(?=[^;=]*(?:=|$))')
r.findall(my_string)

rawDescription: Parsing a string using regular expression?


code:
def compare(E1, E2):
    i, j = 0, 0
    I, J = len(E1), len(E2)
    while i < I:
        if j >= J or E1[i] < E2[j]:
            print(E1[i], "is not in E2")
            i += 1
        elif E1[i] == E2[j]:
            print(E1[i], "is in E2")
            i, j = i + 1, j + 1
        else:
            j += 1

rawDescription: Best way to compare two large sets of strings in Python

description: Compare two large sets of strings in Python


code: plt.pcolormesh(xedges, yedges, Z, cmap=CM.RdBu_r, vmin=-7, vmax=7)

rawDescription: matplotlib: How can you specify colour levels in a 2D historgram

description: Matplotlib: How can you specify colour levels in a 2D historgram


code:
fig, ax = plt.subplots()
df.plot(kind='barh', stacked=True, ax=ax)
ax.set_yticklabels(['A', 'B', 'C', 'D', 'E', 'F'])
time = pd.date_range(start=pd.to_datetime('07:00', format='%H:%M'), end=pd.to_datetime('13:00', format='%H:%M'),freq='H')
time_x = [dt.strftime('%H:%M') for dt in time]
ax.set_xticklabels(time_x)
fig.autofmt_xdate()
plt.show()

rawDescription: Pandas - Stacked horizontal barchat for timeline?


code:
try:
    from _datetime import *
except ImportError:
    pass

rawDescription: Why can't I access the private variables of the superclass in Python?


code:
import textwrap
textwrap.wrap("... this is a test , and so on...", 10)

rawDescription: Proper word wrapping of long text

description: Proper word wrapping of long text


code:
def func2(b=None):
    if b is None:
        return func1()
    else:
        return func1(b)

rawDescription: Wrap function without clobbering default arguments


code:
class my_build(build):
    def run(self):
        self.run_command("build_qt")
        build.run(self)

cmdclass['build'] = my_build

rawDescription: Hook to add commands to distutils build?

description: Hook to add commands to distutils build


code:
import tkinter as tk

''' catch two (or more) keys pressed in short time and tread it as one text '''
''' http://pastebin.com/WHQKcJkW '''

# --- functions ---

# keys buffer
keybuf = []

def test_after():

    # check if buffer is not empty
    if keybuf:

        # get all keys in buffer as one text
        text = ''.join(keybuf)

        # clear buffer
        keybuf.clear()

        # run some function here
        print('after:', text)

def get_key(event):

    # save key in buffer
    keybuf.append(event.char)

    # check buffer after 500ms (0.5s)
    root.after(500, test_after)

# --- main ---

root = tk.Tk()

root.bind('<Key>', get_key)

root.mainloop()

rawDescription: Inputting double digit numbers from keyboard on Tkinter, Python


code:
df = pd.DataFrame({'c_0337':list('aaba'), 'c_0348':list('fkpf')})
df
pd.get_dummies(df)

rawDescription: How to reformat categorical Pandas variables for Sci-kit Learn

description: Reformat categorical Pandas variables for Sci-kit Learn


rawDescription: quotes within a string

description: Quotes within a string


code:
if myType not in [e[0] for e in Library.EXPERIMENT_TYPES]:
    library_errors.append('...')

rawDescription: Get a list of all values in a model

description: Get a list of all values in a model


rawDescription: numpy broadcast from first dimension

description: Numpy broadcast from first dimension


code:
filename = 'text_file_example.txt'
myfile = open(filename,'r')
file_lines = myfile.readlines()
for line in file_lines[:5]:
    print(line)
myfile.close()

rawDescription: Reading document lines to the user (python)


code:
from matplotlib.dates import DateFormatter
formatter = DateFormatter('%H:%M')
plt.gcf().axes[0].xaxis.set_major_formatter(formatter)

rawDescription: Removing the seconds from x-axis time labels in matplotlib


code:
import nltk
import string
nltk.word_tokenize("I've found a medicine for my disease.")
tokens = nltk.word_tokenize("I've found a medicine for my disease.")
"".join([" "+i if not i.startswith("'") and i not in string.punctuation else i for i in tokens]).strip()

rawDescription: Python Untokenize a sentence

description: Python Untokenize a sentence


code:
import os
print(os.path.abspath(__file__))
print(os.path.split(os.path.abspath(__file__)))

rawDescription: How do I find the exact location of a file in python with pygame?

description: Find the exact location of a file in python with pygame


code:
import unicodedata
a = u"STRING GOES HERE" # using an actual string would break stackoverflow's code formatting.
u"".join( x for x in a if not unicodedata.category(x).startswith("M") )

rawDescription: Strip unicode character modifiers

description: Strip unicode character modifiers


code:
class SQLiteAlchemy(SQLAlchemy):
    def apply_driver_hacks(self, app, info, options):
        options.update({
            'isolation_level': 'AUTOCOMMIT',
            'encoding': 'latin1',
            'echo': True
        })
        super(SQLiteAlchemy, self).apply_driver_hacks(app, info, options)

db = SQLiteAlchemy(app)

rawDescription: Flask-Sqlalchemy setup engine configuration


code:
def initData(self):
    self.blockSignals(True)
    super(MoreSpecific, self).initData()
    self.blockSignals(False)

rawDescription: Overriding PyQt signals in child class

description: Overriding PyQt signals in child class


code: sys.path = sorted(sys.path, key=lambda x: x.startswith(prefix), reverse=True)

rawDescription: Sorting sys.path: first virtualenv, then /usr


code:
labels = [
    "Last Name: ",
    "First Name: ",
    "Street Address: ",
    "City: ",
    "State: ",
    "Zip Code: ",
    "Phone: ",
    "Email: "
]
contact = [raw_input(label) for label in labels]
cur.execute("INSERT INTO Contacts VALUES(?, ?, ?, ?, ?, ?, ?, ?)", contact)

rawDescription: How can I insert array elements into SQLite table by index?

description: Insert array elements into SQLite table by index


rawDescription: Hide all warnings in ipython

description: Hide all warnings in ipython


code:
class AvailsDBManager(models.Manager):
    def get_query_set(self):
        return super(AvailsDBManager, self).get_query_set().using('avails')

class Language(models.Model):
    code = models.CharField(max_length=6, primary_key=True)
    language = models.CharField(max_length=20)
    objects = AvailsDBManager()

rawDescription: Permanently specify using for a model

description: Permanently specify using for a model


rawDescription: How to copy a table from excel to word using pythonCOM

description: Copy a table from excel to word using pythonCOM


code:
def is_end( s ) :
    end_re = re.compile(r'([\d]*,?[\d]*) of \1 results')
    return bool(end_re.search(s))

rawDescription: Python: test regular expression for end of a sequence of results


rawDescription: How to write a list to a text file exactly as it appears in python?

description: Write a list to a text file exactly as it appears in python


code:
import os
rand_string = os.urandom(8)

rawDescription: Python - how to create a random string 8 bytes long?


code:
_missing = object()

class cached_property(object):
    """A decorator that converts a function into a lazy property.  The
    function wrapped is called the first time to retrieve the result
    and then that calculated result is used the next time you access
    the value::

        class Foo(object):

            @cached_property
            def foo(self):
                # calculate something important here
                return 42

    The class has to have a `__dict__` in order for this property to
    work.
    """

    # implementation detail: this property is implemented as non-data
    # descriptor.  non-data descriptors are only invoked if there is
    # no entry with the same name in the instance's __dict__.
    # this allows us to completely get rid of the access function call
    # overhead.  If one choses to invoke __get__ by hand the property
    # will still work as expected because the lookup logic is replicated
    # in __get__ for manual invocation.

    def __init__(self, func, name=None, doc=None):
        self.__name__ = name or func.__name__
        self.__module__ = func.__module__
        self.__doc__ = doc or func.__doc__
        self.func = func

    def __get__(self, obj, type=None):
        if obj is None:
            return self
        value = obj.__dict__.get(self.__name__, _missing)
        if value is _missing:
            value = self.func(obj)
            obj.__dict__[self.__name__] = value
        return value

rawDescription: Python - Lazy loading of class attributes


code:
alpha = atan2(A.y-B.y, A.x-B.x) - theta
C.x = B.x + BC * cos(alpha)
C.y = B.y + BC * sin(alpha)

rawDescription: Python - Pygame Drawing Angle

description: Python - Pygame Drawing Angle


code:
from Tkinter import *   # Python 3.x: from tkinter import *
from ttk import *       # Python 3.x: from tkinter.ttk import *

D = {'d1': {'a':'1'}, 'd2': {'b':'2'}, 'd3': {'c':'3'}}

root = Tk()
lb = Label(root, text='')
lb['text'] = '\n'.join('{} {}'.format(k, d) for k, d in D.items()) # <---
# OR lb.config(text=....)
# OR lb.configure(text=...)
lb.pack()
root.mainloop()

rawDescription: Print Dictionary in Python ttk

description: Print Dictionary in Python ttk


code:
import urlparse
url = 'https://www.yoursite.com/drive/team-real-431/pepe-ozil-R323/anyway-jim-james-hi-bye-hi-321312/;jsessionid=DBDE454034B0EE325FC100112EF2E123.56AC29295781342F53AB242D03EE33'
url_parts = urlparse.urlparse(url)
jsessionid = dict(urlparse.parse_qsl(url_parts.params)).get('jsessionid')
print(jsessionid)

rawDescription: Regular expression in python with urlParse


rawDescription: OS X Server: Using wsgi Python on Non-Standard Ports


code: ct = web.ctx.env.get('CONTENT_TYPE')

rawDescription: web.py obtain request headers

description: Web.py obtain request headers


code:
import collections

def new3ElementDeque():
   return collections.deque([], 3)

userTop3 = collections.defaultdict(new3ElementDeque)

with open("Class1.txt") as f:
    for line in f:
        user, score = line.split(':')
        userTop3[user].append(score)

rawDescription: How to save last three entries

description: Save last three entries


code:
import urlparse # if we're pre-2.6, this will not include parse_qs
try:
    from urlparse import parse_qs
except ImportError: # old version, grab it from cgi
    from cgi import parse_qs
    urlparse.parse_qs = parse_qs

rawDescription: What can be used instead of parse_qs function


code:
...
def main():
    jobQueue = Queue()
    jobQueue.put("http://google.com")
    d = Downloader(jobQueue)
    p = Process(target=d.start)
    p.start()

if __name__ == '__main__':
    freeze_support()
    main()

rawDescription: Python Multiprocessing Question

description: Python Multiprocessing Question


code:
from bokeh.models import SingleIntervalTicker, LinearAxis

plot = bp.figure(plot_width=800, plot_height=200, x_axis_type=None)
ticker = SingleIntervalTicker(interval=5, num_minor_ticks=10)
xaxis = LinearAxis(ticker=ticker)
plot.add_layout(xaxis, 'below')

rawDescription: how to adjust # of ticks on Bokeh axis (labels are overlapping on small figures)

description: Adjust # of ticks on Bokeh axis (labels are overlapping on small figures)


code:
index=pd.date_range('2011-1-1 00:00:00', '2011-12-31 23:50:00', freq='1h')
df=pd.DataFrame(np.random.randn(len(index),3).cumsum(axis=0),columns=['A','B','C'],index=index)

df2 = df.groupby(lambda x: x.month)
for key, group in df2:
    ax = group[['A', 'B']].plot()
    group[['C']].plot(secondary_y=True, ax=ax)

rawDescription: Plot groupby data using secondary_y axis


code:
x = np.array([1,2,3,4,5])
index = np.argwhere(x==3)
y = np.delete(x, index)
print(x, y)

rawDescription: How to delete an object from a numpy array without knowing the index

description: Delete an object from a numpy array without knowing the index


code:
form = EntryForm(request.POST, instance=instance)
if form.is_valid():
    url = form.cleaned_data['url']

rawDescription: Getting string from CharField

description: Getting string from CharField


code:
engines = []
sessions = []
for dbconninfo in databases:
    engine = create_engine(dbconninfo)
    engines.append(engine)
    sessions.append(sessionmaker(bind=engine)())

rawDescription: How to use SQLAlchemy to seamlessly access multiple databases?

description: Use SQLAlchemy to seamlessly access multiple databases


code:
words = []
with open('dictionary.txt', encoding='utf-8') as dictionary:
    for line in dictionary:
        words.extend(line.split())

rawDescription: *SOLVED* Is there any way to improve the speed of reading a text file in Python?


code:
def interactive(code):
    try:
        result = eval(code)
        if result is not None:
            print(repr(result))
    except SyntaxError:
        exec(code)

rawDescription: Interpreter-style output in Python 3 (maybe about sys.displayhook?)


code:
tuple = Tuple(blah)
t0 = Property(depends_on="tuple", fget=lambda self: self.tuple[0])

rawDescription: Python (Enthought) Tuple / List Trait: how to access a specific element?


rawDescription: how to enhance the features of builtin functions in python?

description: Enhance the features of builtin functions in python


code:
def sums(it):
    """
    >>> sums(1)
    1
    >>> sums([1,2,3])
    6
    >>> sums([1,2,3,[4,5]])
    15
    >>> sums(['a','b'])
    Traceback (most recent call last):
    ...
    TypeError: unsupported operand type(s) for +: 'int' and 'str'
    """
    if getattr(it, "__iter__", None):
        return sum(map(sums, it))
    else:
        return it

if __name__ == "__main__":
    import doctest
    doctest.testmod()

rawDescription: Pythonic way of summing lists and lists of lists


code:
from datetime import datetime

def load_with_datetime(pairs, format='%Y-%m-%d'):
    """Load with dates"""
    d = {}
    for k, v in pairs:
        if isinstance(v, basestring):
            try:
                d[k] = datetime.strptime(v, format).date()
            except ValueError:
                d[k] = v
        else:
            d[k] = v
    return d

dump = json.dumps(A, default = f)
json.loads(dump, object_pairs_hook=load_with_datetime)

# {u'date': datetime.date(2013, 1, 1), u'price': 100}

rawDescription: How to deserialize the datetime in a json object in python?

description: Deserialize the datetime in a json object in python


rawDescription: Can I dynamically modify (monkey patch) an existing python class method to add a decorator

description: Dynamically modify (monkey patch) an existing python class method to add a decorator


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

# Declare t array
t = np.arange(0.0,2.0,0.01) # change your end point and step as you want it

# Compute x(t) with numpy
x = np.cos(2*np.pi*10*t) + np.cos(2*np.pi*25*t) + np.cos(2*np.pi*50*t) + np.cos(2*np.pi*100*t)

# Plot t with x
plt.plot(t,x)
plt.show()

rawDescription: Matplotlib(python) - drawing stationary signal


code:
import urllib
import json
data = urllib.urlopen('https://www.reddit.com/r/wallpapers/.json')
wallpaper_dict = json.loads(data.read())
wallpaper_dict['data']['children'][1]['data']['url']
wallpaper_dict['data']['children'][1]['data']['title']
wallpaper_dict['data']['children'][1]['data']['domain']

rawDescription: Getting the top wallpaper from reddit

description: Getting the top wallpaper from reddit


code:
def xml_to_pd(self, xml):
    tree = ET.fromstring(xml)
    self.xmltag = tree.tag
    doc_dict = {}
    res = []
    for doc in tree.iter():
        if doc.tag in doc_dict.keys():
            res.append (doc_dict)
            doc_dict = {}
        if doc.attrib:
            if doc_dict!= {} and doc_dict not in res:
                for k in doc.attrib.keys():
                    if k in doc_dict:
                        res.append (doc_dict)
                        doc_dict = {}

                doc_dict.update (doc.attrib)
            else:
                doc_dict.update(doc.attrib)
        if doc.text:
                key = doc.tag
                value = doc.text
                doc_dict[key] = value
    if doc_dict not in res and doc_dict != {}:
        res.append (doc_dict)
        doc_dict = {}
    return res

rawDescription: Pythonic way to quickly parse XML stream to list of dicts


code:
from Tkinter import *

class PropertyDialog(Toplevel):
    def __init__(self, root, string):
        Toplevel.__init__(self)
        self.wm_overrideredirect(1)
        self.root = root #CHANGED# save a reference to the root
        self.\
             geometry('+%d+%d' %
                      (root.winfo_pointerx(),
                       root.winfo_pointery()))
        try:
            self.tk.call('::Tk::unsupported::MacWindowStyle',
                                         'style', self._w,
                                         'help', 'noActivates')
        except TclError:
            pass
        window_frame = Frame(self)
        window_frame.pack(side=TOP, fill=BOTH, expand=True)
        exit_frame = Frame(window_frame, background='#ffffe0')
        exit_frame.pack(side=TOP, fill=X, expand=True)
        button = Button(exit_frame, text='x', width=3, command=self.free,
               background='#ffffe0', highlightthickness=0, relief=FLAT)
        button.pack(side=RIGHT)
        text_frame = Frame(window_frame)
        text_frame.pack(side=TOP, fill=BOTH, expand=True)
        label = Label(text_frame, text=string, justify=LEFT,
                      background='#ffffe0',
                      font=('tahoma', '8', 'normal'))
        label.pack(ipadx=1)

    def free(self): #CHANGED# this method significantly
        self.destroy() # first we destroy this one
        for val,widget in enumerate(dialogs): # go through the dialogs list
            if widget is self: # when we find this widget
                dialogs.pop(val) # pop it out
                break # and stop searching
        if dialogs: # if there are any dialogs left:
            for widget in dialogs: # go through each widget
                widget.lift(aboveThis=self.root) # and lift it above the root

def bind():
    """
    toggle property window creation mode
    """
    root.bind('<ButtonPress-1>', create)

def create(event): #CHANGED# this to store the widget in a list
    """
    Create actual window upon mouse click
    """
    dialogs.append(PropertyDialog(root, 'help me'))

root = Tk()
dialogs = [] #CHANGED# to initialize a list
root.geometry('%dx%d' % (300,400))

Button(root, text='create', command=bind).pack()

root.mainloop()

rawDescription: Tkinter destroying a toplevel window also destroys other windows


code:
PrependedText(
    'password',
    '<i class="fa fa-key"></i>',
    placeholder='Password',
    widget=PasswordInput,
    autocomplete='off',
)

rawDescription: Password type filed in crispy forms, how?


code:
from PIL import Image, ImageChops

x = Image.open('input.png')
width, height = x.size
c = ImageChops.offset(x, 10, 20)
c.paste((255, 255, 255), (0, 0, 10, height))
c.paste((255, 255, 255), (0, 0, width, 20))
c.save('output.png')

rawDescription: How can I prevent ImageChops.offset from wrapping data?

description: Prevent ImageChops.offset from wrapping data


code:
import pandas as pd
import scipy.stats
import numpy as np
df_a = pd.read_clibpoard()
df_b = df_a + np.random.randn(5, 7)
df_c = df_a + np.random.randn(5, 7)
_, p_b = scipy.stats.ttest_ind(df_a.dropna(axis=0), df_b.dropna(axis=0))
_, p_c = scipy.stats.ttest_ind(df_a.dropna(axis=0), df_c.dropna(axis=0))
pd.DataFrame([p_b, p_c], columns = df_a.columns, index = ['df_b', 'df_c'])

rawDescription: t test on Pandas dataframes and make a new matrix of resulting p values

description: T test on Pandas dataframes and make a new matrix of resulting p values


code:
TCP_REVERSE = dict((TCP_SERVICES[k], k) for k in TCP_SERVICES.keys())
TCP_REVERSE[80]

rawDescription: python-scapy: how to translate port numbers to service names?

description: Python-scapy: how to translate port numbers to service names


code:
with open("format_file.fmt") as f:
    # csv.reader parses away the commas for us
    # and we get rows as nice lists
    reader = csv.reader(f)
    # this will give us a list of lists that looks like
    # [["ID", "2", "n"], ...]
    row_definitions = list(reader)

# iterate and just unpack the headers
# this gives us ["ID", "NAME", "CODE"]
header = [name for name, length, dtype in row_definitions]
# [2, 8, 2]
lengths = [int(length) for name, length, dtype in row_definitions]

# define a generator (possibly as a closure) that simply slices
# into the string bit by bit -- this yields, for example, first
# characters 0 - 2, then characters 2 - 10, then 8 - 12
def parse_line(line):
    start = 0
    for length in lengths:
        yield line[start: start+length]
        start = start + length

with open(data_file) as f:
     # iterating over a file pointer gives us each line separately
     # we call list on each use of parse_line to force the generator to a list
     parsed_lines = [list(parse_line(line)) for line in data_file]

# prepend the header
table = [header] + parsed_lines

# use the csv module again to easily output to csv
with open("my_output_file.csv", 'w') as f:
    writer = csv.writer(f)
    writer.writerows(table)

rawDescription: Programically convert a fixed width .dat file with a .fmt file into a .csv file using Python or Python/Pandas


code:
xopt = find_max_f()
xopt
xopt[0]
type(xopt[0])

rawDescription: how to extract value from a numpy.ndarray

description: Extract value from a numpy.ndarray


code:
my_dict = {'a1':2,'a2':3,'b1':1,'b2':5,'b3':8}

def filtered(d):
    for key in d:
        if not key.startswith('a'):
            continue

        b_key = "b" + key[1:]

        if b_key not in d:
            continue

        yield d[key], d[b_key]

sum(a * b for a, b in filtered(my_dict))

rawDescription: lambda function to sum products of values from a dictionary

description: Lambda function to sum products of values from a dictionary


code:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=username, password=password, timeout=10)
sftp = ssh.open_sftp()
sftp.get(remotepath, localpath)
sftp.close()

rawDescription: Timeout in paramiko (python)

description: Timeout in paramiko (python)


code:
admin.py
from import_export.admin import ImportExportActionModelAdmin

class MyModelAdmin(ImportExportActionModelAdmin):
    # ...
    #Your configs and code
    def get_export_filename(self, file_format):
        filename = "%s.%s" % ("your_custom_filename",
                             file_format.get_extension())
        return filename

rawDescription: Django: django-import-export, change file name


rawDescription: Python, numpy, matrix

description: Python, numpy, matrix


code:
from swab import Swab
s = Swab('/tmp/.swab-test-data')
s.addexperiment('button-size', ['default', 'larger'], 'order-completed')

rawDescription: What resources are there for A/B split-testing in Python?


code:
values = set(map(lambda x:x[1], list))
newlist = [[y[0] for y in list if y[1]==x] for x in values]

rawDescription: Group list by values

description: Group list by values


rawDescription: Python: randomly assigning titles to documents in a corpus


code:
@pymc.stochastic(dtype=int)
def switchpoint(value=1900, t_l=1851, t_h=1962):
    """The switchpoint for the rate of disaster occurrence."""
    if value > t_h or value < t_l:
        # Invalid values
        return -np.inf
    else:
        # Uniform log-likelihood
        return -np.log(t_h - t_l + 1)

rawDescription: Understanding code with decorators in pymc, Python


rawDescription: Django: how do I code methods in abstract class which rely on a manager?


code:
import urllib
import webbrowser
import time
from xml.etree.ElementTree import parse

u = urllib.urlopen("http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route=22")
data = u.read()

with open("rt22.xml", "wb") as f:
    f.write(data)
    f.close()

office_lat = 41.980262
doc = parse("rt22.xml")

def distance(lat1, lat2):
    'Return approx miles between lat1 and lat2'
    return 69 * abs(lat1 - lat2)

def check_bus_location():
    for bus in doc.findall("bus"):
        if bus.findtext("lat") >= office_lat:
            latitude = float(bus.findtext("lat"))
            longitude = float(bus.findtext("lon"))
            bus_id = (bus.findtext("id"))
            direction = bus.findtext("d")
            north_buses = [[bus_id, latitude, longitude]]
            if direction.startswith("North"):
                print('%s %s %0.2f miles' % (bus_id, direction, distance(latitude, office_lat)))
                for bus in north_buses:
                    if distance(float(latitude), office_lat) < 0.5:
                        print(webbrowser.open(
                            'http://maps.googleapis.com/maps/api/staticmap?size=500x500&sensor=false&markers=|%f,%f' % (
                                latitude, longitude)))

while True:
    check_bus_location()
    time.sleep(10)

rawDescription: python script from youtube video doesn't work

description: Python script from youtube video doesn't work


code:
import os, sys, cgi, json, cookielib
sys.path.append("lib")
import jinja2, webapp2, urllib, urllib2

from google.appengine.api import users, oauth, urlfetch
from webapp2_extras import sessions

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True)

class BaseHandler(webapp2.RequestHandler):
    def dispatch(self):
        # Get a session store for this request.
        self.session_store = sessions.get_store(request=self.request)

        try:
            # Dispatch the request.
            webapp2.RequestHandler.dispatch(self)
        finally:
            # Save all sessions.
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        # Returns a session using the default cookie key.
        return self.session_store.get_session()

class ConsoleLogin(BaseHandler):
    def get(self):
        # Set variables to avoid problems later
        code = ''
        url = ''
        access_token = ''
        scope = ''
        username = ''

        google_user = users.get_current_user()

        if google_user:
            url = self.request.url
            if ('code' not in url and not self.session.get('access_token')):
                # First time user coming to site. Redirect to GH for code
                url = 'https://github.com/login/oauth/authorize?scope=user,repo&client_id=' + os.environ.get('CLIENT_ID')
                self.redirect(url)
            elif 'code' in url:
                # User has been to GH, continue with auth process
                code = url.replace('http://localhost:8080/?code=', '')

                # We have code, now get Access Token
                fields = {
                    "client_id" : os.environ.get('CLIENT_ID'),
                    "client_secret" : os.environ.get('CLIENT_SECRET'),
                    "code" : code
                }
                url = 'https://github.com/login/oauth/access_token'
                data = urllib.urlencode(fields)
                result = urlfetch.fetch(url=url,
                    payload=data,
                    method=urlfetch.POST
                )

                # Get the query string
                query_string = str(result.content)

                # Get the access token out of the full query string
                access_token = query_string[13:]
                end_access = access_token.find('&')
                access_token = access_token[:end_access]

                # Get the scope out of the full query string
                start_scope = query_string.find('scope')
                end_scope = query_string.find('token_type')
                start_scope = start_scope + 6   # remove the word 'scope='
                end_scope = end_scope - 1       # remove the & symobol
                scope = query_string[start_scope:end_scope]
                scope = scope.split('%2C')

            # Store the Access Token in a Session Variable
            self.session['access_token'] = access_token
            self.session['scope'] = scope

            # And redirect to the base URL for neatness and to avoid other issues
            self.redirect('/')

            access_token = self.session.get('access_token')
            scope = self.session.get('scope')

            context = {
                'access_token' : access_token,
                'scope' : scope,
                'username' : username,
            }

            # Template Settings
            temp = 'templates/index.html'

            template = JINJA_ENVIRONMENT.get_template(temp)
            self.response.write(template.render(context))

config = {}
config['webapp2_extras.sessions'] = {
    'secret_key': 'the-beatles-will-always-rule',
}

application = webapp2.WSGIApplication([
    ('/', ConsoleLogin),
], debug=True, config=config)

rawDescription: Authenticating with the Github API using Python on GAE


code:
subset = data_set[['data_date', 'data_1', 'data_2']]
tuples = [tuple(x) for x in subset.values]

rawDescription: Pandas convert dataframe to array of tuples


code:
from collections import defaultdict
from csv import csvreader

result = defaultdict(float)
with open("<datafile>") as f:
    data = csvreader(f, delimiter='\t')
    for a,b,c in data:
        result[(a,b)] += float(c)

for (a,b),c in result.items():
    print(a, b, c)

rawDescription: (python) add elements in consecutive rows if the condition holds true


code: ans = [myreadfunction(filename) for filename in filenames]

rawDescription: Functional way to create new list by processing elements of another list?


code: df3.to_csv('df3.csv', index = False)

rawDescription: Values in Wrong Columns After Pandas DataFrame.to_csv()


code:
from flask import Flask, session, abort, request, render_template

@app.route('/results', methods=['POST'])
def results():
    if request.form['channelname'] in ALLOWED_CHANNELS:
        session['channel'] = request.form['channelname']
    if 'channel' in session:
        return render_template('results.html', channel=session['channel'])
    else:
        abort(400)

rawDescription: basic python flask two page form input and update

description: Basic python flask two page form input and update


rawDescription: PyBrain Reinforcement Learning - Maze and Graph


code:
now = time.localtime()[0:6]
dirname = dirfmt % now
csvafile = os.path.join(dirname, csvafmt % now)
csvbfile = os.path.join(dirname, csvbfmt % now)
logfile = os.path.join(dirname, logfmt % now)

rawDescription: Create dir with datetime name and subfiles within directory (Python)


code:
import os, time
size = os.stat(file).st_size
time.sleep(600)
fh = open(file)
fh.seek(size)
newData = fh.read()

rawDescription: Python script to extract new data from file since it was last read


code:
import sys
import fileinput
for line in fileinput.input([filename], inplace=True):
    if line.strip().startswith('initial_mass = '):
        line = 'initial_mass = 123\n'
    sys.stdout.write(line)

rawDescription: Python: replace line in file starting with a pattern


rawDescription: Python: Split string by pattern

description: Python: Split string by pattern


code:
repeat = True
while repeat:
    Number = int(input("Number Required"))

    if Number >= 1 and Number<=50:
      add =(Number * 5)
      print("The Number amount it", add)

    elif Number <= 80 and Number >= 50:
       add =(Number * 4)
       print("The Number amount it", add)

    elif Number <= 100 and Number >= 80:
       add =(Number * 2.5)
       print("The Number amount it", add)

    run = input("would you like to check again type yes or no")
    if run == 'no': repeat = False

rawDescription: How do I make a loop in Python?

description: Make a loop in Python


code:
# Starts encoding in a subprocess
proc = subprocess.Popen(['ffmpeg', '-i' 'myinput', 'myoutput'])

duration = 3
sleeptime = 0
while proc.poll() is None and sleeptime < 3:
    # Wait for the specific duration or for the process to finish
    sleep(1)
    sleeptime += 1

# If process is not terminated
if proc.poll() is None:
    # Cancels process, waits for it to complete
    proc.communicate("q")

rawDescription: How to terminate an infinite process with an specific time duration

description: Terminate an infinite process with an specific time duration


code:
import csv

csv_output = csv.writer(open("output.csv", "wb"))   # output.csv is the output file name!
csv_output.writerow(["Col1","Col2","Col3","Col4"]) # Setting first row with all column titles

temp = []
deats = soup.find_all('p')
for n in deats:
    temp.append(str(n.text))
csv_output.writerow(temp)

rawDescription: Writing for loop outputs to CSV columns

description: Writing for loop outputs to CSV columns


code:
class MyModel(models.Model):
    ...

    def save(self):
        super(DocumentTemplate, self).save(*args, **kwargs)

        # retrieve the old version of the object
        try:
           old = DocumentTemplate.objects.get(id=self.id)
        except MyModel.DoesNotExist:
           # object is being created
           customize_function_create(self)

        # check if something has changed
        if self.interesting_field != old.interesting_field:
            # the field has been changed
            customize_function_update(self)

        return

rawDescription: Customize admin.py

description: Customize admin.py


code:
a
a.swapaxes(0,1)

rawDescription: What's the numpy equivalent of python's zip(*)?


code:
from obspy.imaging.spectrogram import spectrogram
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height]
ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1)
ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6])

#make time vector
t = np.arange(spl1[0].stats.npts) / spl1[0].stats.sampling_rate

#plot waveform (top subfigure)
ax1.plot(t, spl1[0].data, 'k')

#plot spectrogram (bottom subfigure)
spl2 = spl1[0]
fig = spl2.spectrogram(show=False, axes=ax2)
mappable = ax2.images[0]
plt.colorbar(mappable=mappable, cax=ax3)

rawDescription: Adding Colorbar to a Spectrogram

description: Adding Colorbar to a Spectrogram


code: format(number, '03')

rawDescription: convert number to formatted string in python with prefix 0s

description: Convert number to formatted string in python with prefix 0s


code:
print('Would that be all?')
answer = input()
if answer.lower().startswith('y'):
    return

rawDescription: why does my line of code seem to ignore calling my function?

description: Why does my line of code seem to ignore calling my function


code: {{ 'Update' if files else 'Continue' }}

rawDescription: Python jinja2 shorthand conditional

description: Python jinja2 shorthand conditional


code:
def hexbin(x, y, color, **kwargs):
    cmap = sns.light_palette(color, as_cmap=True)
    plt.hexbin(x, y, gridsize=15, cmap=cmap, **kwargs)

g = sns.FacetGrid(tips, hue="time", col="time", size=4)
g.map(hexbin, "total_bill", "tip", extent=[0, 50, 0, 10])

rawDescription: Seaborn pairwise matrix of hexbin jointplots


rawDescription: Set operations in python

description: Set operations in python


code:
friend_data = response.read()
friend_json = json.loads(friend_data)

if 'education' in friend_json.keys():
    for school_id in friend_json['education']:
        friendedu = []
        try:
            friendedu.append(school_id['school']['id'])
            friendedu.append(school_name['school']['name'])
            friendedu.append(school_type['school']['type'])
        except:
            friendedu.append('School ID, NAME, or type not found')
        print(" ".join(friendedu))

rawDescription: Parsing complex and changing JSON data in Python, several levels deep


code:
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(filehandle.read())
titleTag = soup.html.head.title

rawDescription: Python: Read HTML source from URL and get date into program


code:
from collections import namedtuple
example = namedtuple('_', ['NameOfClass1', 'NameOfClass2'], verbose=True)

rawDescription: Does using an '_' for typename in a namedtuple do anything special?


code:
#!/usr/bin/python

import re

filename = 'editme.txt' #name of the file you want to edit

def edit(filename):
    f = open(filename, 'rU') #reads your file
    text = f.read() #puts everything in file into a string under var text
    f.close() #closes file
    text = re.sub(r'\s[Pp]reload="\w+"', '', text) #delete preload tag
    text = re.sub(r'\s[Jj]umpable="\w+"', '', text) #delete jumpable tag
    text = re.sub(r'<tween.+>\s+', '', text) #delete tween tag
    text = re.sub(r'slide', 'title', text) #replaces slide with title tag
    text = re.sub(r'\s\w+offset\w+=".+"', '', text) #delete offset/type tags
    text = re.sub(r'<presenter.+>\s+', '', text) #deletes presenter tag
    text = re.sub(r'\s+<controls.+>', '', text) #deletes controls tag
    text = re.sub(r'<title flv', '<title src', text) #replaces flv with src in title tag
    f = open(filename, 'w')
    f.write(text) #replaces all text in file with the edited text
    f.close()

edit(filename)

rawDescription: How to write Python or PHP script to edit this XML file?

description: Write Python or PHP script to edit this XML file


code:
# enter = 1    This line doesn't serve any purpose.
count = 1
ctr = 0
max_input = 3
input_list = []

while ctr < max_input:

    for enter in range(0, max_input):
        if enter < ctr:
            print("input " + str(enter+1) + ": " + str(input_list[enter]))
        else:
            print("input " + str(enter+1) + ": ___________" )

    user_input = int(input("enter number " + str(count) + ": "))
    input_list.append(user_input)

    # enter += 1      This line doesn't serve any purpose.
    ctr += 1

rawDescription: how to keep previous input

description: Keep previous input


code:
def detectDelimiter(csvFile):
    with open(csvFile, 'r') as myCsvfile:
        header=myCsvfile.readline()
        if header.find(";")!=-1:
            return ";"
        if header.find(",")!=-1:
            return ","
    #default delimiter (MS Office export)
    return ";"

rawDescription: python: import csv file (delimiter ";" or ",")

description: Python: import csv file (delimiter ";" or ",")


code:
new_d = []
for x in d:
    if x not in new_d:
        new_d.append(x)

rawDescription: Remove duplicates from the list of dictionaries


rawDescription: File upload with Django via PUT

description: File upload with Django via PUT


rawDescription: How can I round up numbers to the next half-integer?

description: Round up numbers to the next half-integer


code: return super(Test, cls).__new__(cls, *args, **kwargs)

rawDescription: Correct way to implement standard __new__ in Python


code:
A.objects.filter(name='name_a', type='type_a',
                 b__name='name_b', b__type='type_b').distinct()

rawDescription: A complex model query in django concerning related objects


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.ticker as ticker
import datetime as DT

dates = mdates.num2date(mdates.drange(DT.datetime(2012, 11, 30),
                                      DT.datetime(2012, 12, 4),
                                      DT.timedelta(days=1)))
print(dates)
# [datetime.datetime(2012, 11, 30, 0, 0, tzinfo=<matplotlib.dates._UTC object at 0x8c8f8ec>), datetime.datetime(2012, 12, 1, 0, 0, tzinfo=<matplotlib.dates._UTC object at 0x8c8f8ec>), datetime.datetime(2012, 12, 2, 0, 0, tzinfo=<matplotlib.dates._UTC object at 0x8c8f8ec>), datetime.datetime(2012, 12, 3, 0, 0, tzinfo=<matplotlib.dates._UTC object at 0x8c8f8ec>)]

vals = np.random.randint(10, size=len(dates))
fig, ax = plt.subplots()
ax.bar(dates, vals, align='center')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
plt.xticks(rotation=25)
ax.set_xticks(dates)
plt.show()

rawDescription: Generating an array of dates in python

description: Generating an array of dates in python


code: dict(line.strip().split('/') for line in open("address.txt", "r"))

rawDescription: Read a file into a string, then split the string by the "/" character, and put the results into a dictionary


code:
from IPython.html import widgets
from IPython.display import display
import numpy as np

class Test(object):
    def __init__(self, arraylen):
        self.a = np.random.randn(arraylen)
        self.button = widgets.Button(description = 'Show')
        self.button.on_click(self.show)
        display(self.button)

    def show(self, ev = None):
        display(self.a)
        self.button.disabled = True

test = Test(10)

rawDescription: Is there a way to make an IPython Notebook output interactivly create an input and execute it?


code:
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

if 1:

    host = host_subplot(111, axes_class=AA.Axes)
    plt.subplots_adjust(right=0.75)

    par1 = host.twinx()
    par2 = host.twinx()

    offset = 60
    new_fixed_axis = par2.get_grid_helper().new_fixed_axis
    par2.axis["right"] = new_fixed_axis(loc="right",
                                        axes=par2,
                                        offset=(offset, 0))

    par2.axis["right"].toggle(all=True)

    host.set_xlim(0, 2)
    host.set_ylim(0, 2)

    host.set_xlabel("Distance")
    host.set_ylabel("Density")
    par1.set_ylabel("Temperature")
    par2.set_ylabel("Velocity")

    p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
    p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
    p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")

    par1.set_ylim(0, 4)
    par2.set_ylim(1, 65)

    host.legend()

    host.axis["left"].label.set_color(p1.get_color())
    par1.axis["right"].label.set_color(p2.get_color())
    par2.axis["right"].label.set_color(p3.get_color())

    plt.draw()
    plt.show()

    #plt.savefig("Test")

rawDescription: multiple axis in matplotlib with different scales

description: Multiple axis in matplotlib with different scales


code:
import time
import os

mtime_last = 0
while True:
    time.sleep(5)
    mtime_cur = os.path.getmtime("/path/to/your/file")
    if mtime_cur != mtime_last:
        do_stuff()
    mtime_last = mtime_cur

rawDescription: How to watch a file for modifications OS X and Python

description: Watch a file for modifications OS X and Python


code:
a = set(range(30))
b = set(range(25,50))
a.intersection(b)

rawDescription: Finding intersect values using Python matplotlib-venn


code:
def process_request(self, request):
    full_path = request.get_full_path()
    if full_path.startswith('/users/login'):
        return

rawDescription: Python middleware call on a particular request


code:
class import_data:
    def import_csv(self, filename_csv, data_name):

            #set dynamic named item to default value
            #not required if this will happen anyway (in this example it does)
            setattr(self,data_name,[])

            #preparation activities
            datafile = open(filename_csv, 'r')
            datareader = csv.reader(datafile)

            #do required work using a temporary local variable
            temp = []
            for row in datareader:
                temp.append(row)

            #copy the temporary local variable into the dynamically named one
            setattr(self, data_name, temp)

            #tidy up activities
            datafile.close()
            print("finished importing data")

rawDescription: Set a list name in a class, using a function


code:
values = [
    ["SomeValue1", "Key1"],
    ["SomeValue2", "Key2"],
]
{x[1]: x for x in values}

rawDescription: Python dictionary: set value as the key string


code:
import numpy as np
y1 = np.array([5, 6 , 4, 1])
x1 = np.array([0.0, 0.3, 0.8, 1.1])
period = 0.4
x2 = period * np.arange(len(x1))
x2
np.interp(x2, x1, y1)

rawDescription: Irregular sample frequency to regular sample frequency in Python


code:
if metric.empty:
    sheet = writer.book.add_worksheet('y')
    sheet.write_string('A1', 'Nothing here')

rawDescription: How to print "Nothing here" to excel if df or groupby is blank?

description: Print "Nothing here" to excel if df or groupby is blank


code:
def somestring(**kwargs):
  return ', '.join('%s=%r' % x for x in kwargs.iteritems())

rawDescription: how can I convert a dictionary to a string of keyword arguments?

description: Convert a dictionary to a string of keyword arguments


code: cursor = conn.cursor (MySQLdb.cursors.DictCursor)

rawDescription: Python, MySQL and SELECT output to dictionary with column names for keys


code: [i for i in my_list if '91' not in i and '18' not in i]

rawDescription: Is there a way to use two if conditions in list comprehensions in python


code:
@app.route('/order', methods=['POST'])
def order_entry():
    # the following line creates a 'cursor' which you need to retrieve data
    # from the database
    cur = g.db.execute('select title, text from entries order by id desc')

    # the following line uses that cursor ("cur"), fetches the data,
    # turns it into a (unsorted) list of dictionaries
    entries = [dict(title=row[0], text=row[1]) for row in cur.fetchall()]

    # let's sort the list by the 'title' attribute now
    entries = sorted(entries, key=lambda d: d['title'])
    # or if you prefer, you could say: "entries.sort(key=lambda d:d['title']"

    # return the template with the sorted entries in
    return render_template('show_entries.html', entries=entries)

rawDescription: How can I sort posts alphabetically in flask?

description: Sort posts alphabetically in flask


code:
messages = SSEClient(sparkURL)

for msg in messages:
    outputMsg = msg.data
    if type(outputMsg) is not str:
        outputJS = json.loads(outputMsg)
        FilterName = "data"
        #print( FilterName, outputJS[FilterName] )
        print(outputJS[FilterName])

rawDescription: How to parse output from sse.client in Python?

description: Parse output from sse.client in Python


code:
import csv
from glob import iglob

unique_headers = set()
for filename in iglob('*.csv'):
    with open(filename, 'rb') as fin:
        csvin = csv.reader(fin)
        unique_headers.update(next(csvin, []))

rawDescription: How can I read only the header column of a CSV file using Python?

description: Read only the header column of a CSV file using Python


code:
import wx

TAB = 4

TEST = "".join([" "*i*TAB + "|\n" + "\t"*i + "|\n" for i in range(1, 30, 2)])

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)
        self.text = wx.TextCtrl(self.panel, style=wx.TE_PROCESS_TAB | wx.TE_RICH | wx.TE_MULTILINE)

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.text, 1, wx.ALL | wx.EXPAND)

        self.text.Bind(wx.EVT_SIZE, self.SetTabs)

        self.panel.SetSizerAndFit(self.sizer)
        self.Show()

        self.text.SetValue(TEST)

    def SetTabs(self, e):
        pixel_width_in_mm = 25.4 / wx.ScreenDC().GetPPI()[0]
        space_width_in_pixels = self.text.GetTextExtent(" ")[0]
        tab_width_in_tenth_of_mm = (10 * TAB * space_width_in_pixels * pixel_width_in_mm)
        textctrl_width_in_mm = (10 * self.text.GetSize()[0] * (1 / pixel_width_in_mm))
        nr_of_tabs = int(textctrl_width_in_mm / tab_width_in_tenth_of_mm)
        tabs = [int((i+1)*tab_width_in_tenth_of_mm) for i in range(nr_of_tabs)]
        attr = wx.TextAttr()
        attr.SetTabs(tabs)
        self.text.SetDefaultStyle(attr)

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: wxPython wx.TextCtrl tab width

description: WxPython wx.TextCtrl tab width


code:
import sys
sys.path.append('/your/dir/goes/here')
from base import foo

rawDescription: Python Imports From The Directory Above

description: Python Imports From The Directory Above


code:
def reverse_dictionary(input_dict):
    D=lower(input_dict)
    reverse_dict = {}
    for key, value in D.iteritems():
        if not isinstance(value, (list, tuple)):
            value = [value]
        for val in value:
            reverse_dict[val] = reverse_dict.get(val, [])
            reverse_dict[val].append(key)
    for key, value in reverse_dict.iteritems():
        if len(value) > 1:
            reverse_dict[key] = sorted(value)

rawDescription: Sorting list of values in the returned dictionary in ascending order-Python


code:
import ctypes
...
x, y = ctypes.c_int(0), ctypes.c_int(0) # Create two ctypes values
# Pass x and y as references (pointers) to SDL_GetMouseState()
buttonstate = sdl2.mouse.SDL_GetMouseState(ctypes.byref(x), ctypes.byref(y))
# Print x and y as "native" ctypes values
print(x, y)
# Print x and y as Python values
print(x.value, y.value)

rawDescription: How to get mouse position using PySDL2?

description: Get mouse position using PySDL2


code:
r = np.ones((10,), dtype=[('x', int), ('y', int), ('value', int)])
s=np.vstack((r,r,r,r))
s
s['x']
s['x'].sum(axis=1)

rawDescription: Numpy Record Matrix: Sum only one field of all columns in record matrix


code:
# Option one
older_method_string = "%.9f" % numvar

# Option two
newer_method_string = "{:.9f}".format(numvar)

rawDescription: Convert floating point number to certain precision, then copy to String


code:
f = lambda x: x.method_foo
f.func_code.co_names
f.func_code.co_names[0]

rawDescription: Determining the method called within a lambda function


code:
import json

api_result = '{"username":"wawa","age":20}'

class User(object):
    def __init__(self, api_result):
        userinfo = json.loads(api_result)
        self.__dict__.update(userinfo)

import unittest

class DefaultTestCase(unittest.TestCase):
    def test_default(self):
        user = User(api_result)
        self.assertEqual(user.username, 'wawa')
        self.assertEqual(user.age, 20)

if __name__ == '__main__':
    unittest.main()

rawDescription: How to create attributes dynamically in python?

description: Create attributes dynamically in python


code:
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk
Gdk.__path__
Gdk.atom_intern
Gdk.atom_intern_static_string

rawDescription: Create Gtk.Atom with PyGobject Introspection and Gtk+3


code:
import ast
x = u'[ "A","B","C" , " D"]'
x = ast.literal_eval(x)
x
x = [n.strip() for n in x]
x

rawDescription: Convert string representation of list to list in Python


code:
import asyncio
from aiohttp import web

class MyApp(web.Application):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.process_task = self.loop.create_task(self.process())
        self.on_shutdown.append(lambda app: app.process_task.cancel())

    async def process(self):
        while True:
            print(await asyncio.sleep(1, result='ping'))

if __name__ == '__main__':
    web.run_app(MyApp())

rawDescription: How to maintain multiple run_forever handlers simultaneously?

description: Maintain multiple run_forever handlers simultaneously


code:
class Container(object):
  def __init__(self):
    self.data = []
    self.byid = {}

  def setData(self, listofdicts):
    for item in listofdicts:
      id = item['id'] # Something here that's meaningful.
      self.data.append(item)
      self.byid[id] = item

  def getByPos(self, idx):
    return self.data[idx]

  def getById(self, itemid):
    return self.byid[itemid]

rawDescription: Implementing a datatree using class lists and dicts in Python


code:
from scipy.io import wavfile
from scipy.signal import argrelmax
from matplotlib.mlab import specgram

sr, x = wavfile.read(path)                                    # read in a mono wav file
spec, freqs, time = specgram(x, NFFT=4096, Fs=sr, mode='psd') # compute power spectral density spectogram
spec2 = np.diff(spec, axis=1)                                 # discrete difference in each frequency bin
spec2[spec2<0] = 0                                            # half-wave rectification
diff = np.sum(spec2, axis=0)                                  # sum positive difference in each time bin

for peak in argrelmax(diff)[0]:                               # find peaks
    print("onset between %f and %f." % (time[peak], time[peak+1]))

rawDescription: Find timestamps of notes played in wav file


code:
db.define_table('mytable',
    Field('myfield', type='string',
          widget=lambda f, v: SQLFORM.widgets.string.widget(f, v, _disabled=True)))

rawDescription: How to disable input fields in Web2Py

description: Disable input fields in Web2Py


code:
from warnings import warn

class Foo(object):
    """
    Instantiating Foo always gives a warning:

    >>> import sys; sys.stderr = sys.stdout
    >>> foo = Foo() # doctest:+ELLIPSIS
    /.../testdocs.py:14: UserWarning: Boo!
      warn("Boo!", UserWarning)
    """

    def __init__(self):
        warn("Boo!", UserWarning)

if __name__ == '__main__':
    import doctest
    doctest.testmod()

rawDescription: Testing warnings with doctest

description: Testing warnings with doctest


code:
substrs = [...]
def f(cell_value):
    return {k: v for k, v in ((s, cell_value.count(s)) for s in substrs) if v}
df.column.apply(f)

rawDescription: Counting appearances of multiple substrings in a cell pandas


code:
import re
import ast
a="[(u'porta', 'NN'); (u'scuola', 'NN'); (u'ragazzo', 'NN')]"
my_list = ast.literal_eval(re.sub(';',',',a))
my_list
type(my_list)

rawDescription: How to read a list saved in a file.txt as a list

description: Read a list saved in a file.txt as a list


code:
import requests
import sys

EMAIL = ''
PASSWORD = ''

URL = 'http://friends.cisv.org'

def main():
    # Start a session so we can have persistant cookies
    session = requests.session(config={'verbose': sys.stderr})

    # This is the form data that the page sends when logging in
    login_data = {
        'loginemail': EMAIL,
        'loginpswd': PASSWORD,
        'submit': 'login',
    }

    # Authenticate
    r = session.post(URL, data=login_data)

    # Try accessing a page that requires you to be logged in
    r = session.get('http://friends.cisv.org/index.cfm?fuseaction=user.fullprofile')

if __name__ == '__main__':
    main()

rawDescription: Login to website using python

description: Login to website using python


code:
import numpy as np
a = np.array([1,2,3],float)  # float argument is used so that / operator does float division rather than integer division
b = np.array([4,5,6],float)
a*b
a/b

rawDescription: Memberwise operator in python

description: Memberwise operator in python


rawDescription: List comprehensions in python

description: List comprehensions in python


rawDescription: Selenium Python webdriver: driver.get() won't accept a variable?


code:
cbar  = mpl.colorbar.ColorbarBase( ax,
                                   cmap = cm,
                                   norm = mpl.colors.Normalize( vmin = -0.20,
                                                                vmax =  0.20
                                                                )
                                   )
cbar.set_clim( -0.20, 0.20 )

cbar2 = mpl.colorbar.ColorbarBase( ax1,
                                   cmap = cm,
                                   norm = mpl.colors.Normalize( vmin = -20.0,
                                                                vmax =  30.0
                                                                )
                                   )
cbar2.set_clim( -20.0, 30.0 )

rawDescription: 2 different surface charts with matplotlib python


code: [textEditor.clear() for textEditor in myGroupBox.findChildren(QtGui.QTextEdit)]

rawDescription: act on all children at once on pyqt widget

description: Act on all children at once on pyqt widget


code:
from Tkinter import *
import ttk

root = Tk()
root.minsize(500,300)
root.maxsize(550,310)

class MyListbox:
    def __init__(self, parent, title):
        self.parent = parent
        self.parent.title(title)
        self.parent.protocol("WM_DELETE_WINDOW", self.closes)

        self.myData= (
            ["1", "Jhon Doe", "Madrid", "0341-672541", "6 SD"],
            ["2", "Mike Grant", "Barcelona", "0341-435271", "7 SD"],
            ["3", "Steven Mc Fly", "Rome", "0341-123456", "8 SD"],
            ["4", "Joao Pontes", "Rio", "0341-234567", "9 SD"],
            ["5", "Kenji S.", "Tokyo", "0341-213212", "10 SD"])

        self.establishment()

    def combobox_handler(self, event):
        current = self.combobox.current()
        self.entNumber.delete(0, END)
        self.entName.delete(0, END)
        self.entCity.delete(0, END)
        self.entTel.delete(0, END)
        self.entAddress.delete(0, END)

        self.entNumber.insert(END, self.myData[current][0])
        self.entName.insert(END, self.myData[current][1])
        self.entCity.insert(END, self.myData[current][2])
        self.entTel.insert(END, self.myData[current][3])
        self.entAddress.insert(END, self.myData[current][4])

    def establishment(self):
        mainFrame = Frame(self.parent)
        mainFrame.pack(fill=BOTH, expand=YES)

        self.statusBar = Label(mainFrame, text="App",relief=SUNKEN, bd=1)
        self.statusBar.pack(side=BOTTOM, fill=X)

        fr_left = Frame(mainFrame, bd=10)
        fr_left.pack(fill=BOTH, expand=YES, side=LEFT)

        names = [person[1] for person in self.myData]
        self.combobox = ttk.Combobox(fr_left, values=names)
        self.combobox.bind('<<ComboboxSelected>>', self.combobox_handler)
        self.combobox.pack()

        fr_right = Frame(mainFrame, bd=10)
        fr_right.pack(fill=BOTH, expand=YES, side=RIGHT)

        fr_up = Frame(fr_right)
        fr_up.pack(side=TOP, expand=YES)

        Label(fr_up, text='List Number').grid(row=0, column=0, sticky=W)
        self.entNumber = Entry(fr_up)
        self.entNumber.grid(row=0, column=1)

        Label(fr_up, text='Name').grid(row=1, column=0, sticky=W)
        self.entName = Entry(fr_up)
        self.entName.grid(row=1, column=1)

        Label(fr_up, text='City').grid(row=2, column=0, sticky=W)
        self.entCity = Entry(fr_up)
        self.entCity.grid(row=2, column=1)

        Label(fr_up, text='No. Tel').grid(row=3, column=0, sticky=W)
        self.entTel = Entry(fr_up)
        self.entTel.grid(row=3, column=1)

        Label(fr_up, text='Address').grid(row=4, column=0, sticky=W)
        self.entAddress = Entry(fr_up)
        self.entAddress.grid(row=4, column=1)

    def closes(self, event=None):
        self.parent.destroy()

if __name__ == '__main__':
    app = MyListbox(root, "Main Window")
    root.mainloop()

rawDescription: entries get data from combobox selection using tkinter and python

description: Entries get data from combobox selection using tkinter and python


code:
@app.before_request
def set_client_session():
    if 'client' in request.args:
        session['client'] = request.args['client']

rawDescription: Flask: Set session variable from URL Param


code:
for key in dict1:
    for index, element in enumerate(dict1[key]):
        if element in dict2[key]:
            print("Match found for", element)
        else:
            print("Match not found for", element)

rawDescription: i am having two dictionaries, i want to compare these. and if match found then it should print match found else match not found

description: I am having two dictionaries, i want to compare these. and if match found then it should print match found else match not found


code:
in_str  = "1, 2, 3, 4"
listed = [int(x) for x in in_str.split(',')]

rawDescription: Putting integers in lists in python

description: Putting integers in lists in python


code:
def load_pdf(self):
    self.doc = poppler.document_new_from_file (uri, None)
    # the number of pages in the pdf
    self.n_pgs = self.document.get_n_pgs()
    # the current page of the pdf
    self.curr_pg = 0
    # the current page being displayed
    self.curr_pg_disp = self.document.get_page(self.curr_pg)
    # the scale of the page
    self.scale = 1
    # the document width and height
    self.doc_width, self.doc_height = self.curr_pg_disp.get_size()

def render_pdf(self):
    cr = self.pdfda.window.cairo_create()
    cr.set_source_rgb(1, 1, 1)
    if self.scale != 1:
        cr.scale(self.scale, self.scale)
    cr.rectangle(0, 0, self.doc_width, self.doc_height)
    cr.fill()
    self.curr_pg_disp.render(cr)

def on_next_btn_clicked(self, widget, data=None):
    if self.curr_pg < self.n_pgs:
        self.curr_pg = self.curr_pg + 1
        self.curr_pg_disp = self.doc.get_page(self.curr_pg)
        self.render_page()

def on_prev_btn_clicked(self, widget, data=None):
    if self.curr_pg > 0:
        self.curr_pg = self.curr_pg - 1
        self.curr_pg_disp = self.doc.get_page(self.curr_pg)
        self.render_page()

rawDescription: Issues Viewing PDF's

description: Issues Viewing PDF's


code:
value = 150
coll.update({},
    {'$pull': {'values': {'value_type': 'type1', 'value': {'$lt': value}}}},
    multi=True)

rawDescription: Finding nested values in pymongo

description: Finding nested values in pymongo


code:
def format_Dollar_sign(list):

    lines=['book, 400.2\n', 'pen, 5\n', 'food,  200.5\n', 'gas, 20\n',
            'food, 100\n', 'pen, 10\n', 'insurance, 171.35\n', 'gas, 35\n',
            'book, 100\n', 'pen, 12\n', 'food, 320\n',
            'gas,23.55\n', 'insurance, 110.25']

    my_dictionary = {}
    for line in lines:
        item, price= line.strip().split(',')

        my_dictionary[item.strip()] = my_dictionary.get(item.strip(),0) + float(price)

    dic={}
    for k,v in my_dictionary.items():
        dic[k]='${0:.2f}'.format(round(v,2))

    L=([(k,v) for k, v in dic.iteritems()])
    L.sort()

    return L
print(format_Dollar_sign(list))

rawDescription: Return a list of lines as list of tuple with formatting the value with $


code:
import datetime, time
dt = datetime.datetime(2012, 2, 10, 15, 18, 15, 234567)
seconds = time.mktime(dt.timetuple())
seconds += (dt.microsecond/1000000.0)
seconds
datetime.datetime.fromtimestamp(seconds)

rawDescription: How to parse time.time()?

description: Parse time.time()


code:
class test_password(unittest.TestCase):
    """ Contiene los test para la funcionalidad de contraseña.
    """
    def test_success_password(self):
        mock_render = mock.MagicMock()
        mock_request = mock.MagicMock()
        with mock.patch.multiple('interface.views', render=mock_render):
            from interface.views import success_password
            success_password(mock_request)
            context = mock_render.call_args[0][2]
            self.assertEqual(context['message']['data'],
                             'Cambio exitoso de contrase\xc3\xb1a')

    def test_len_password_true(self):
        """llamado al método de validación debe devolver la misma
        contraseña.
        """
        mock_auth_form = mock.MagicMock()
        from interface.forms import ValidatingPasswordChangeForm
        form = ValidatingPasswordChangeForm(mock_auth_form)
        form.cleaned_data = {'new_password1': 'hola5'}
        self.assertEquals(form.clean_new_password1(), 'hola5')

    def test_len_password_error(self):
        """llamado al método de validación con una contraseña, de menos de 5
        caracteres, debe levantar un error de validación.
        """
        mock_auth_form = mock.MagicMock()
        from interface.forms import ValidatingPasswordChangeForm
        form = ValidatingPasswordChangeForm(mock_auth_form)
        form.cleaned_data = {'new_password1': 'hol4'}
        with self.assertRaises(forms.ValidationError):
            form.clean_new_password1()

rawDescription: How test method inside the class

description: How test method inside the class


code:
# -*- encoding: utf8 -*-
import sys
import Image, ImageDraw, ImageFont

im = Image.new("RGBA", (1000, 1000), 'white')
draw = ImageDraw.Draw(im)

start_y = 7
text = u'\u00d1\u00d3yŻ\u00d4Ćgp\u010c\u0137'
for i in xrange(28, 46, 2):
    font = ImageFont.truetype('Junicode-Bold.ttf', i)
    width, height = font.getsize(text)
    draw.rectangle((0, start_y, width, height + start_y), outline='blue')
    draw.text((0, start_y), text, font=font, fill='black')
    start_y += height + 7

im.crop((0, 0, width + 1, start_y + 2)).save(sys.argv[1])

rawDescription: PIL cut off letters

description: PIL cut off letters


code: sensor_id = ':'.join("%02X" % ord(b) for b in add)

rawDescription: Storing xbee source addr into database in Python


code:
import ast
actual_list = ast.literal_eval(myList)

rawDescription: Python convert list to JSON then back to list


code:
...
parser.add_argument('--val', dest='val', action='store',
                      choices=['a','b','c'],
                      help='Special testing value')

args = parser.parse_args(sys.argv[1:])

rawDescription: Allowing a specific value for an Argparse argument


rawDescription: save stocks historical data into stock name.csv using python

description: Save stocks historical data into stock name.csv using python


code:
for name in pre_vars:
    globals()[name]= []

rawDescription: List of strings. New variables with those name (without classes). Python