code:
# Used to guarantee to use at least Wx2.8
import wxversion
wxversion.ensureMinimal('2.8')

import numpy as np
import wx

import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.figure import Figure

class MyFileDropTarget(wx.FileDropTarget):
    def __init__(self, window):
        wx.FileDropTarget.__init__(self)
        self.window = window

    def OnDropFiles(self, x, y, filenames):
        fig = self.window.figure
        inaxes = fig.get_axes()[0]
        h_pix = int(fig.get_figheight() * fig.get_dpi()) # fig height in pixels
        message = "%d file(s) dropped at (%d,%d):\n" % (len(filenames), x, y)
        for file in filenames:
            message += file + "\n"
        inaxes.annotate(message, (x, h_pix-y), xycoords='figure pixels')
        self.window.draw()

class CanvasPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.figure = Figure()
        self.axes = self.figure.add_subplot(111)
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)
        self.SetSizer(self.sizer)
        self.add_toolbar()
        self.Fit()

        win_target = self.canvas
        dt = MyFileDropTarget(win_target)
        win_target.SetDropTarget(dt)

    def draw(self):
        t = np.linspace(0.0, 2., 100)
        s = np.sin(2 * np.pi * t)
        self.axes.plot(t, s)

    def add_toolbar(self):
        self.toolbar = NavigationToolbar2Wx(self.canvas)
        self.toolbar.Realize()
        if wx.Platform == '__WXMAC__':
            # Mac platform (OSX 10.3, MacPython) does not seem to cope with
            # having a toolbar in a sizer. This work-around gets the buttons
            # back, but at the expense of having the toolbar at the top
            self.SetToolBar(self.toolbar)
        else:
            # On Windows platform, default window size is incorrect, so set
            # toolbar width to figure width.
            tw, th = self.toolbar.GetSizeTuple()
            fw, fh = self.canvas.GetSizeTuple()
            # By adding toolbar in sizer, we are able to put it at the bottom
            # of the frame - so appearance is closer to GTK version.
            # As noted above, doesn't work for Mac.
            self.toolbar.SetSize(wx.Size(fw, th))
            self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)
        # update the axes menu on the toolbar
        self.toolbar.update()

if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = wx.Frame(None, title='File drop test')
    panel = CanvasPanel(frame)
    panel.draw()
    frame.Show()
    app.MainLoop()

rawDescription: Matplotlib Drag and Drop File

description: Matplotlib Drag and Drop File


code:
from Tkinter import *

class Input(Frame):
    def __init__(self, parent=None, **kw):
        Frame.__init__(self, parent, background="white")
        self.parent = parent
        self.entdat = StringVar()
        self.makeWidgets()

    def makeWidgets(self):
        self.ol = Label(text="Objective:")
        self.ol.pack(side=TOP)
        self.ew = Entry(textvariable=self.entdat)
        self.ew.pack(side=TOP)
        self.b = Button(text="OK", command=self.clicked)
        self.b.pack(side=TOP)

    def clicked(self):
        self.dat = Label(self, textvariable=self.entdat )
        self.dat.pack(side=TOP)
        self.distroy_Widget()

    def distroy_Widget(self):
        self.ew.destroy()
        self.ol.destroy()
        self.b.destroy()

def main():
    root = Tk()
    root.geometry("240x135+25+50")
    tm = Input(root)
    tm.pack(side=TOP)

    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Receiveing input from Python's tkinter entry widget and displaying it in a label


code:
import pandas as pd

dbase1_df = pd.DataFrame.from_csv('dbase1_file.csv',index_col=False)
sgo_df = pd.DataFrame.from_csv('sgo_df.csv',index_col=False)
merged_df = pd.DataFrame.from_csv('merged_df.csv',index_col=False)

#you need to use the same column names for common columns to be able to do the merge operation in pandas , so we changed the column name to mkey

dbase1_df.columns = [u'VALUE', u'COUNT', u'GRID', u'mkey']

#Below operation merges the two dataframes
Step1_Merge = pd.merge(dbase1_df,sgo_df)

#We need to add a new column to concatenate ST and type
Step1_Merge['type_2'] = Step1_Merge['type'].map(lambda x: 'ST'+str(x))

# We need to change the shape of merged_df and move columns to rows to be able to do another merge operation
id = merged_df.ix[:,['GRID']]
a = pd.merge(merged_df.stack(0).reset_index(1), id, left_index=True, right_index=True)

# We also need to change the automatically generated name to type_2 to be able to do the next merge operation
a.columns = [u'type_2', 0, u'GRID']

result = pd.merge(Step1_Merge,a,on=[u'type_2',u'GRID'])

rawDescription: Speed up vlookup like operation using pandas in python


code:
#!/usr/bin/python

# How to get log axis with a 2D colormap (i.e. an "image") ??
#############################################################
#############################################################

import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import math

# Data file containing 2D data in log-log coordinates.
# The format of the file is 3 columns : x y v
# where v is the value to plotted for coordinate (x,y)
# x and y are already log values
# For instance, this can be a 2D histogram with log bins.
input_file="histo2d.dat"

# Parameters to set space for the plot ("bounding box")
x1_bb, y1_bb, x2_bb, y2_bb = 0.125, 0.12, 0.8, 0.925

# Parameters to set space for colorbar
cb_fraction=0.15
cb_pad=0.05

# Return unique values from a sorted list, will be required later
def uniq(seq, idfun=None):
    # order preserving
    if idfun is None:
        def idfun(x): return x
    seen = {}
    result = []
    for item in seq:
        marker = idfun(item)
        # in old Python versions:
        # if seen.has_key(marker)
        # but in new ones:
        if marker in seen: continue
        seen[marker] = 1
        result.append(item)
    return result

# Read data from file. The format of the file is 3 columns : x y v
# where v is the value to plotted for coordinate (x,y)

Data = np.genfromtxt(input_file)
x = Data[:,0]
y = Data[:,1]
v = Data[:,2]

# Determine x and y limits and resolution of data

x_uniq = np.array(uniq(np.sort(x)))
y_uniq = np.array(uniq(np.sort(y)))

x_resolution = x_uniq.size
y_resolution = y_uniq.size

x_interval_length = x_uniq[1]-x_uniq[0]
y_interval_length = y_uniq[1]-y_uniq[0]

xmin = x.min()
xmax = x.max()+0.5*x_interval_length
ymin = y.min()
ymax = y.max()+0.5*y_interval_length

# Reshape 1D data to turn it into a 2D "image"

v = v.reshape([x_resolution, y_resolution])
v = v[:,range(y_resolution-1,-1,-1)].transpose()

# Plot 2D "image"
# ---------------

# I use imshow which only work with linear axes.
# We will have to change the axes later...

axis_lim=[xmin, xmax, ymin, ymax]

fig = plt.figure()
ax = fig.add_subplot(111)
extent = [xmin, xmax, ymin, ymax]
img = plt.imshow(v, extent=extent, interpolation='nearest', cmap=cm.Reds, aspect='auto')
ax.axis(axis_lim)

# Make space for the colorbar
x2_bb_eff = (x2_bb-(cb_fraction+cb_pad)*x1_bb)/(1.0-(cb_fraction+cb_pad))
ax.set_position([x1_bb, y1_bb, x2_bb_eff-x1_bb, y2_bb-y1_bb])
position = ax.get_position()

# Remove axis ticks so that we can put log ticks on top
ax.set_xticks([])
ax.set_yticks([])

# Add colorbar
cb = fig.colorbar(img,fraction=cb_fraction,pad=cb_pad)
cb.set_label('Value [unit]')

# Add logarithmic axes
# --------------------

# Empty plot on top of previous one. Only used to add log axes.
ax = fig.add_subplot(111,frameon=False)
ax.set_xscale('log')
ax.set_yscale('log')
plt.plot([])
ax.set_position([x1_bb, y1_bb, x2_bb-x1_bb, y2_bb-y1_bb])

axis_lim_log=map(lambda x: 10.**x, axis_lim)
ax.axis(axis_lim_log)

plt.grid(b=True, which='major', linewidth=1)
plt.ylabel('Some quantity [unit]')
plt.xlabel('Another quantity [unit]')

plt.show()

rawDescription: How to get log axes for a density plot with matplotlib?

description: Get log axes for a density plot with matplotlib


code: collections.Counter(i[1] for i in L).most_common()

rawDescription: Counting frequency of second elements in list? (Python)


code:
global IS_SETUP
IS_SETUP = False
def setuplogger(filename = 'python.log', directory = None, format = 'L:%(name)s M:%(module)s T:%(asctime)s > %(levelname)s: %(message)s'):
   global IS_SETUP
   if directory == None:
      fd, fname = tempfile.mkstemp()
      directory = os.path.dirname(fname)

   logging.basicConfig(filename = directory + '/' + filename, format = format)
   IS_SETUP = True

def getlog(logname, level = logging.INFO):
   '''returns a logger with logname that will print to filename and directoryname.'''
   if IS_SETUP == False:
      setuplogger()

   mylog = logging.getLogger(logname)

   mylog.setLevel(level)
   mylog.info('NEW LOGGER STARTED')
   return mylog

rawDescription: Logging Handlers: How do I make sure I am not making two?


code:
import xlwt

data = """
  4.20985      17.1047
  4.82755      16.4046
  3.17238      12.1246
  4.50796      18.0955
  6.04241      21.1016
  4.62863      16.4974
  4.32245      14.6536
  6.48382      19.7664
  5.66514      20.1288
  6.11072      22.6859
  5.55167      15.7504
"""

# prepare two-dimensional list
data = [map(float, item.split()) for item in data.split('\n') if item]

# create workbook and add sheet
workbook = xlwt.Workbook()
sheet = workbook.add_sheet('Test')

# loop over two-dimensional list and write data
for index, (value1, value2) in enumerate(data):
    sheet.write(index, 0, value1)
    sheet.write(index, 1, value2)

# save a workbook
workbook.save('test.xls')

rawDescription: Two columns of data need to be saved as an excel file


code:
import webbrowser

...

self.entryfield = Entry(self.frame)

...
mybutton = Button(self.frame, text="Open site",
command= lambda: webbrowser.open(self.entryfield.get()))

rawDescription: How to make document names to be clickable hyperlinks?

description: Make document names to be clickable hyperlinks


code:
import re
pat = r"\b([^\W\d_])([^\W\d_]*)([^\W\d_])\b"
s = "Testers"
print(re.sub(pat, (lambda m: "{0}{1}{2}".format(m.group(1), len(''.join(set(m.group(2)))), m.group(3))), s))

rawDescription: Python String Dissection

description: Python String Dissection


code:
class SpecificAttribute(GeneralAttribute) :

    def __init__(self, attribute1, attribute2, attribute3, attribute4, attribute5, attribute6, attribute7):
        super(SpecifcAttribute, self).__init__(attribute1, attribute2, attribute3)
        self.Attribute4 = attribute4
        self.Attribute5 = attribute5
        self.Attribute6 = attribute6
        self.Attribute7 = attribute7

item = SpecificAttribute(1, 2, 3, 4, 5, 6, 7)

rawDescription: Class Inheritance [Beginner]

description: Class Inheritance [Beginner]


rawDescription: List of tuples to Numpy recarray

description: List of tuples to Numpy recarray


rawDescription: Multiplying All Combination in Lists in Python


rawDescription: What does Python treat as reference types?


code:
import operator as op

f = op.methodcaller('X','a','b')
f(client.service)

rawDescription: Method selector with suds

description: Method selector with suds


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

x = np.array([[0,1,2],[3,4,5],[6,7,8]])

fig = plt.figure()
cmap_custom = matplotlib.cm.Greens
cmap_custom.set_under('r')
plt.imshow( x, interpolation='nearest' ,cmap = cmap_custom, vmin=0.01)
plt.colorbar(extend='min')
plt.show()

rawDescription: Custom colour maps Matplotlib, make one value a prescribed colour


code:
from tkinter import Text, Tk

r = Tk()
r.geometry("400x400")

t = Text(r, height=20, width=40)
t.pack()

r.mainloop()

rawDescription: tkinter python entry height

description: Tkinter python entry height


rawDescription: Convert a string to a dictionary in Python?


code:
from datetime import datetime
from scrapy import log
from scrapy.spider import BaseSpider

class ExampleSpider(BaseSpider):
    name = "example"
    allowed_domains = ["example.com"]
    start_urls = ["http://www.example.com/"]

    def __init__(self, name=None, **kwargs):
        LOG_FILE = "scrapy_%s_%s.log" % (self.name, datetime.now())
        # remove the current log
        # log.log.removeObserver(log.log.theLogPublisher.observers[0])
        # re-create the default Twisted observer which Scrapy checks
        log.log.defaultObserver = log.log.DefaultObserver()
        # start the default observer so it can be stopped
        log.log.defaultObserver.start()
        # trick Scrapy into thinking logging has not started
        log.started = False
        # start the new log file observer
        log.start(LOG_FILE)
        # continue with the normal spider init
        super(ExampleSpider, self).__init__(name, **kwargs)

    def parse(self, response):
        ...

rawDescription: scrapy log issue

description: Scrapy log issue


code:
for idx, image in enumerate(imgPath):
    #img resizing goes here

    count_remaining = len(imgPath) - (idx+1)
    if count_remaining > 0:
        print("There are {} images left to resize.".format(count_remaining))
        response = input("Resize image #{}? (Y/N)".format(idx+2))
        #use `raw_input` in place of `input` for Python 2.7 and below
        if response.lower() != "y":
            break

rawDescription: Python Resize Multiple images ask user to continue


code:
import numpy as np
import matplotlib.pyplot as plt
import collections as co
buffer=[]
for i in range(10):
    buffer.append(co.deque(maxlen=15))

def refresh(n):
    for t in range(10*n):
        x=np.random.rand()+t%10
        buffer[t%10].append(x)

refresh(15) # init
buff=np.asarray(buffer)
fig = plt.figure()
ax = fig.add_subplot(111)
line = ax.plot(buff.T)

def main():
    while True:
        refresh(1)
        buff=np.asarray(buffer)
        print (buff.mean(axis=1))
        for i in range(10) :
            line[i].set_ydata(buff[i])
        fig.canvas.draw()
        for t in range(10**6):pass #tempo

rawDescription: Circular buffer of vectors

description: Circular buffer of vectors


code:
def _(message):
    return my_gettext(__name__, message)

rawDescription: What is the best way to internationalize a Python app with multiple i18n domains?


code:
package_data = {
        'module_1': [files],
        'module_2': [files],
        'example': [files],
}

rawDescription: How to package example scripts using distribute?

description: Package example scripts using distribute


code: #define NGROUPS_MAX 16  /* max number of groups for a user */

rawDescription: Python NGROUPS_MAX staying at 16 for Solaris


code:
class MockOpen(object):
    def __call__(self, *args, **kwargs):
        #print('mocked')
        return self.__open(TEST_FILE) #it would be better to return a file-like object instead
    def __enter__(self):
        global open
        self.__open = open
        open = self
    def __exit__(self, exception_type, exception_value, traceback):
        global open
        open = self.__open

with MockOpen():
    # here you run your test
    ...

rawDescription: How to mock the open function for unit test

description: Mock the open function for unit test


code:
from collections import defaultdict

def parse_data(line):
    # Returns a list of values from line of text.
    return line[1:-2].split(',')

with open('newfile.txt', 'wb') as new_file, open('file1.txt', 'rb') as f1, open('file2.txt', 'rb') as f2:
    mapping = defaultdict(list)
    # Zero-based indexing.
    CERTAIN_COLUMN = 1
    for line in f1:
        # Remove new-lines and get comma-separated values.
        line = line.strip()
        columns = parse_data(line)
        mapping[columns[CERTAIN_COLUMN]].append(line)

    for line in f2:
        line = line.strip()
        columns = parse_data(line)
        for matched in mapping[columns[CERTAIN_COLUMN]]:
            new_file.write('{},{},\n'.format(matched, line))

rawDescription: Map elements in two lists and add one to the other list


code:
from threading import Thread
from Queue import Queue

def task(queue):
    while True:
        item = queue.get()  # blocks until an item is available
        # process item

queue = Queue()
t = Thread(target=task, args=(queue, ))
t.daemon = True
t.start()

rawDescription: Having a global queue (or list) that is available to all threads


code:
x = theano.tensor.matrix()
y = theano.tensor.matrix()
z = theano.dot(x, y)
f = theano.function(inputs=[x, y], outputs=z)
a = numpy.array([[1,2,3],[4,5,6]])
b = numpy.array([[1,2],[3,4],[5,6]])
c = f(a, b)

rawDescription: Lazy evaluation of .dot or other theano function


code:
import requests

def update_other(self, data):
    r = requests.post("http://127.0.0.1:5000", data=data)
    ...

rawDescription: pass information between client and server using flask

description: Pass information between client and server using flask


code:
for i, tag in enumerate(tag):
    tagDict[tag] = i

rawDescription: python dictionary update method

description: Python dictionary update method


code:
def get_template_names(self):
    return ['default_template_name.html', self.get_fallback()]

rawDescription: Django 1.8 check if template exists in view


code: pc.setfilter('not ip6')

rawDescription: Sniffer that filters IPv6 packets

description: Sniffer that filters IPv6 packets


code:
pylab.seed(0)
pylab.weibull(2)
pylab.seed(0)
pylab.weibull(2)

rawDescription: Seed Pylab's random number generator?

description: Seed Pylab's random number generator


code:
import multiprocessing

multiprocessing.cpu_count()

rawDescription: How can I determine sensible thread number in python?

description: Determine sensible thread number in python


code:
keeper_rows = df.ix[[i for i,x in enumerate(df.itertuples()) if 'GE' in x[0:2]]]
for row_as_tuple in df.itertuples():
    from_other, to_other, val = row_as_tuple
    if "GE" not in (from_other, to_other):
        new_rows = {"From":["GE", from_other],
                    "To"  :[to_other, "GE"],
                    "Val" :[val, val]}
        keeper_rows = pandas.concat([keeper_rows, pandas.DataFrame(new_rows)],
                                    ignore_index=True)

rawDescription: Duplicating some rows and changing some values in pandas


code: rows_xpath = XPath("//*[@id='content-primary']/table/tbody/tr[td[1]/span/span//text()='%s']" % (date))

rawDescription: Better way of getting information from a table using XPath in python?


code:
sourcefile = open(filein, "r")
targetfile = open(pathout, "w")

p = Popen([SCRIPT], stdout=targetfile, stdin=PIPE)
while True:
    data = sourcefile.read(1024)
    if len(data) == 0:
        break
    p.stdin.write(data)
sourcefile.close()
p.stdin.close()

p.wait()
targetfile.close()

rawDescription: Sending large file to PIPE input in python


code:
# instead of parrot(voltage=5, 'dead'):
parrot(voltage=5, state='dead')

# or:
parrot(5, state='dead')

# or:
parrot(5, 'dead')

rawDescription: Function parameters - Python

description: Function parameters - Python


rawDescription: Defining a custom pandas aggregation function using Cython


code:
tour1 = tuple(tuple((a,b) for a in nodes )for b in nodes)
tour1

rawDescription: What's the difference between "()" and "[]" when generating in Python?


code:
whole = open('my_file','r').read()
for x in whole.split('\n'):
    buf = x[10:28] + x[34:49] # adjust these values accordingly

open('out_file','w').write(buf)

rawDescription: Get the value in ( ) from a text file and write it to a text file using python


code:
data = map(list, zip(*myDict.keys())) + [myDict.values()]
df = DataFrame(zip(*data)).set_index([0, 1])[2].unstack()
df.combine_first(df.T).fillna(0)

rawDescription: Write 2d dictionary into a dataframe or tab-delimited file using python


code:
# Features are length-100 vectors of floats
feature_input = tf.placeholder(tf.float32, shape=[100])
# Labels are scalar integers.
label_input = tf.placeholder(tf.int32, shape=[])

# Alternatively, could do:
# feature_batch_input = tf.placeholder(tf.float32, shape=[None, 100])
# label_batch_input = tf.placeholder(tf.int32, shape=[None])

q = tf.FIFOQueue(100, [tf.float32, tf.int32], shapes=[[100], []])
enqueue_op = q.enqueue([label_input, feature_input])

# For batch input, do:
# enqueue_op = q.enqueue_many([label_batch_input, feature_batch_input])

label_batch, feature_batch = q.dequeue_many(BATCH_SIZE)
# Build rest of model taking label_batch, feature_batch as input.
# [...]
train_op = ...

sess = tf.Session()

def load_and_enqueue():
  with open(...) as feature_file, open(...) as label_file:
    while True:
      feature_array = numpy.fromfile(feature_file, numpy.float32, 100)
      if not feature_array:
        return
      label_value = numpy.fromfile(feature_file, numpy.int32, 1)[0]

      sess.run(enqueue_op, feed_dict={feature_input: feature_array,
                                      label_input: label_value})

# Start a thread to enqueue data asynchronously, and hide I/O latency.
t = threading.Thread(target=load_and_enqueue)
t.start()

for _ in range(TRAINING_EPOCHS):
  sess.run(train_op)

rawDescription: How to prefetch data using a custom python function in tensorflow

description: Prefetch data using a custom python function in tensorflow


code:
while (i < int(x)):
     if i%26 == 0 and i!= 0:
            end_char = (65)
            start_char += 1

            print((chr(start_char))+(chr(end_char)))
            end_char =end_char + 1
     i = i + 1  #move incrementation outside of if
     for plate_code in (range(1000)):
         print(str(plate_code)  + ((chr(start_char))+(chr(end_char))))

rawDescription: How to specify the amount of numbers needed in a range with user input

description: Specify the amount of numbers needed in a range with user input


rawDescription: Word frequency analysis in Python returning letter frequency


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

leaf1 = Node()
leaf2 = Node()
parent = Node(leaf1, leaf2)

rawDescription: Python: recursive creation of objects

description: Python: recursive creation of objects


code:
source
import logging, Queue, sys, threading, time

import urwid

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)-4s %(threadName)s %(message)s",
    datefmt="%H:%M:%S",
    filename='trace.log',
)

class Interface:
    palette = [
        ('body', 'white', 'black'),
        ('ext', 'white', 'dark blue'),
        ('ext_hi', 'light cyan', 'dark blue', 'bold'),
        ]

    header_text = [
        ('ext_hi', 'ESC'), ':quit        ',
        ('ext_hi', 'UP'), ',', ('ext_hi', 'DOWN'), ':scroll',
        ]

    def __init__(self, msg_queue):
        self.header = urwid.AttrWrap(urwid.Text(self.header_text), 'ext')
        self.flowWalker = urwid.SimpleListWalker([])
        self.body = urwid.ListBox(self.flowWalker)
        self.footer = urwid.AttrWrap(urwid.Edit("Edit:  "), 'ext')
        self.view = urwid.Frame(
            urwid.AttrWrap(self.body, 'body'),
            header = self.header,
            footer = self.footer)
        self.loop = urwid.MainLoop(self.view, self.palette,
            unhandled_input = self.unhandled_input)
        self.msg_queue = msg_queue
        self.check_messages(self.loop, None)

    def unhandled_input(self, k):
        if k == 'esc':
            raise urwid.ExitMainLoop()

    def check_messages(self, loop, *_args):
        """add message to bottom of screen"""
        loop.set_alarm_in(
            sec=0.5,
            callback=self.check_messages,
            )
        try:
            msg = self.msg_queue.get_nowait()
        except Queue.Empty:
            return
        self.flowWalker.append(
            urwid.Text(('body', msg))
            )
        self.body.set_focus(
            len(self.flowWalker)-1, 'above'
            )

def update_time(stop_event, msg_queue):
    """send timestamp to queue every second"""
    logging.info('start')
    while not stop_event.wait(timeout=1.0):
        msg_queue.put( time.strftime('time %X') )
    logging.info('stop')

if __name__ == '__main__':

    stop_ev = threading.Event()
    message_q = Queue.Queue()

    threading.Thread(
        target=update_time, args=[stop_ev, message_q],
        name='update_time',
    ).start()

    logging.info('start')
    Interface(message_q).loop.run()
    logging.info('stop')

    # after interface exits, signal threads to exit, wait for them
    logging.info('stopping threads')

    stop_ev.set()
    for th in threading.enumerate():
        if th != threading.current_thread():
            th.join()

rawDescription: urwid - output screen for endless loop

description: Urwid - output screen for endless loop


code:
students = []
student_abs = []
for i in range(10):
    students.append(raw_input("Enter Student %d's name: " % i+1))
    student_abs.append(raw_input("Enter Student %d's absences: " % i+1))

rawDescription: Can I print each value in a for loop?

description: Print each value in a for loop


code:
import win32file
isNetworkDrive = win32file.GetDriveType("Z:\\") == win32file.DRIVE_REMOTE

rawDescription: Programatically check whether a drive letter is a shared/network drive


code:
import git
r = git.Repo(path_to_repo)
diff_index = r.commit(lhs_hexsha).diff(rhs_hexsha, create_patch=True)
# find all modified paths you are interested in
for diff_info in diff_index.iter_change_type('M'):
    if diff_info.a_blob.path == my_path:
        print(str(diff_info))

rawDescription: git diff hexsha:directorypath/file

description: Git diff hexsha:directorypath/file


code:
lst = [((u'die', u'die'), (u'welt', u'WELT')),
 ((u'welt', u'WELT'), (u'ist', u'ist'))]
[tuple(zip(*x)) for x in lst]

rawDescription: How to transform a list of tuples with Python in the most pythonic way (perhaps with zip)

description: Transform a list of tuples with Python in the most pythonic way (perhaps with zip)


rawDescription: Lettuce django integration

description: Lettuce django integration


code:
def outer(x=1):
    def inner(y=2):
        return x+y

rawDescription: Are Python inner functions compiled?

description: Are Python inner functions compiled


rawDescription: Change Axis for Historgram with PyPlot

description: Change Axis for Historgram with PyPlot


code:
pkt = Ether() / Dot1Q() / IP() / TCP()
payload = pkt.getlayer(1).payload
payload
pkt.getlayer(1).remove_payload()
pkt
newPkt = pkt / Dot1Q() / payload
newPkt

rawDescription: Scapy - insert packet layer between two other layers


code:
def cart(request):
    if request.user.is_authenticated():
        cart = Cart.objects.filter(user=request.user.id, active = True)
        orders = BookOrder.objects.filter(cart=cart)
        total = 0
        count = 0
        for order in orders:
            total += order.book.price * order.quantity
            count += order.quantity
        #Indentation needs to be offset by one level from here on
        context = {
            'cart': orders,
            'total': total,
            'count': count,
        }
        return render(request, 'store/cart.html', context)
    else:
        return redirect('index')

rawDescription: Updating Items In A Shopping Cart With Django


code:
from flask import Response

@app.route("/<arg1>")
def route1(arg1):
    dict1 = {"prop1": "p1", "prop2": "p2"}
    return Response(json.dumps(dict1), mimetype='application/json')

rawDescription: Get Python Flask to return application/json using json.dumps


code:
class Bar:
    def __init__(self, iterable):
        self.list = list(iterable)
    def __contains__(self, item):
        return item in self.list

b = Bar([1,2,3])
b.list
4 in b
2 in b

rawDescription: Redeclaration of the method "in" within a class


code:
string = '82,000,00'
int(price_result.replace(',', ''))

rawDescription: Convert python string into integer without commas in them


code: self.fe.font_size = '20sp'

rawDescription: How to change font size of a label when a new string replaces the old

description: Change font size of a label when a new string replaces the old


code:
form = PortfolioForm()
tuple((field_name, form.fields[field_name].widget.__class__) for field_name in form.fields)

rawDescription: Get list of fields and widgets from django form


code:
from os import system
system('taskkill /fi "WindowTitle eq taskeng.exe"')

rawDescription: Python Scheduled Task Close taskeng.exe

description: Python Scheduled Task Close taskeng.exe


code:
class FieldPlayer(models.Model):

    speed_score = models.IntegerField() # or FloatField() etc
    another_score = ...

    def save_scores(self):
        self.speed_score = calculate_speed_score(...)
        self.another_score = calculate_another_score(...)

        self.save()

rawDescription: How to save compute results in Models without re-computing to each call?

description: Save compute results in Models without re-computing to each call


rawDescription: Mapping two list without looping

description: Mapping two list without looping


code:
import re
pattern = re.compile(
    "(?<=\:)"   # Look for :
    " "         # Match space
    "([0-9]+)"  # Number to keep \1
    "(?:\.0)?") # Optional .0
pattern.sub("\\1", "Name: 33 KG: 5.0 Name: 19 KG: 424.0 Name: 93 KG: 17.0")

rawDescription: Python - Remove a specific after a specific character?


code:
import pandas as pd
def importdict(filename):#creates a function to read the csv
    #create data frame from csv with pandas module
    df=pd.read_csv(filename+'.csv', names=['systemtime', 'Var1', 'var2'],sep=';',parse_dates=[0]) #or:, infer_datetime_format=True)
    fileDATES=df.T.to_dict().values()#export the data frame to a python dictionary
    return fileDATES #return the dictionary to work with it outside the function
if __name__ == '__main__':
    fileDATES = importdict('dates') #start the function with the name of the file

rawDescription: Python date reading from a csv file

description: Python date reading from a csv file


code:
data = (0.25, 0.25)
'and'.join([str(item).replace('.','') for item in data])

rawDescription: Python convert decimal number in a string without "."


rawDescription: Convert str with percents (url) to usual str


code: import site; site.getsitepackages()

rawDescription: How do I find the location of my Python site-packages directory?

description: Find the location of my Python site-packages directory


code: ctypes.cast(s, ctypes.c_void_p).value

rawDescription: How to get the pointer address of a ctypes.c_char_p instance

description: Get the pointer address of a ctypes.c_char_p instance


code:
total = float(sum(v for k,v in example))
example_dict = {}
for k,v in example:
     example_dict[k] = example_dict.get(k, 0) + v * 100 / total

rawDescription: Summing List of values with similar keys to dictionary


code:
# Code by Jake Stringer
# 2014

import os
restart = 'yes'
while restart in ('yes', 'Yes', 'y', 'Y'):
    print("                       Hailstone Numbers ")
    print("")
    print("An interesting area of Maths - demonstrated by Jake Stringer")
    print("")
    input("Please press enter to continue.")

    os.system('CLS')

    print("Hailstone Numbers:")
    print("")
    print("RULE 1: Start with any number.")
    print("If it is even > divide it by 2.")
    print("If it is odd > multiply it by 3, then add 1")
    print("")
    print("RULE 2: Keep going")
    print("")
    print("RULE 3: You will always end up at 1.")
    print("")
    print ("Let's put Hailstone Numbers into action.")
    print("")

    user = int(input("Please enter any number: "))

    print("")

    os.system('CLS')

    print (user)
    print("")

    if user % 2 == 0 :

        print("What you entered is an even number.")
        print("")

        print("So, according to RULE 1, we must now divide it by 2.")

        user = int(user)/2
        thing2 = "So, now we're left with " + str(user) + "."

        print (thing2)
    else :

        print("What you entered is an odd number.")
        print("")

        print("So, according to RULE 1, we must now multiply it by 3, and add 1.")

        user = int(user)*3
        user += 1

        thing2 = "So, now we're left with " + str(user) + "."
        print (thing2)

    input("Please press enter to continue.")
    os.system('CLS')

    print("According to RULE 2, we need to keep on going.")

    while user > 1:
        thing3 = "We are currently on the number " + str(user) + "."
        print (thing3)

        if user % 2 == 0 :

            print("This number is an even number.")
            print("")

            print("So, according to RULE 1, we must now divide it by 2.")

            user = int(user)/2
            thing2 = "So, now we're left with " + str(user) + "."

            print (thing2)
        else :

            print("This number is an odd number.")
            print("")

            print("So, according to RULE 1, we must now multiply it by 3, and add 1.")

            user = int(user)*3
            user += 1

            thing2 = "So, now we're left with " + str(user) + "."
            print (thing2)
        print("Now we will continue.")
        input("Please press the enter key.")
        os.system('CLS')
        print("")

    print(user)
    print("")
    print("As you can see, you have ended up on the number 1.")
    print("")
    print("                       Hailstone Numbers ")
    print("")
    print("An interesting area of Maths - demonstrated by Jake Stringer")
    print("")
    restart = input("Would you like a try the program again??")

rawDescription: Restarting a Python Program

description: Restarting a Python Program


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import StringProperty, NumericProperty, ListProperty
from kivy.graphics.context import Clock
from kivy.uix.widget import Widget

class Controls(BoxLayout):
    def __init__(self, **kwargs):
        self.temp_solar=NumericProperty()
        self.temp_pool=NumericProperty()
        self.delta_value=NumericProperty()
        self.max_value=NumericProperty()
        self.hysteresis=NumericProperty()
        #super(Controls, self).__init__(**kwargs)
        #Clock.schedule_interval(self.set_value, 1)

    def PID_an_aus(self, instance, value):
        if value is True:
           pass
        else:
            pass

    def set_value(self, *args):
        print("Temperature",self.temp_solar, self.temp_pool )
        print("Delta",self.delta_value)
        print("Max", self.max_value)
        print(self.hysteresis)

class Tempar():
    def __init__(self):
        self.temperature=[111,222]
        self.temp_sensor = []
        self.temp_solar=NumericProperty(0.0)
        self.temp_pool=NumericProperty(0.0)
        #self.temp_sensor.start()
        #Clock.schedule_interval(self.read_temperature, 0)

    def read_temperature(self, temperature):
        self.temp_solar=self.temperature[0]
        self.temp_pool=self.temperature[1]
        self.tmp=[self.temp_solar,self.temp_pool]
        return self.tmp

class PoolApp(App):
    #create object for each class and exchange values
    t=Tempar()
    c=Controls()
    c.temp_solar=t.read_temperature(t.temperature)[0]
    c.temp_pool=t.read_temperature(t.temperature)[1]
    print(c.temp_solar)
    print(c.temp_pool)
    #and here are your printouts
    c.set_value()

if __name__ == '__main__':
    PoolApp().run()

rawDescription: How to bind the values between two classes

description: Bind the values between two classes


code:
import subprocess
import copy
import pprint

def get_rows(output_to_parse, whitelist_keys):
    lines = output_to_parse.split("\n")
    rows = []
    while lines:
        row = _get_new_row(lines, whitelist_keys)
        rows.append(row)
    return rows

def _get_new_row(lines, whitelist_keys):
    new_row_keys = set()
    output = {}
    repeat = False
    while lines and repeat is False:
        line = lines.pop()
        if line == '':
            continue
        key = line[0]
        if key not in whitelist_keys:
            raise(ValueError(key))
        value = line[1:]
        if key not in new_row_keys:
            new_row_keys.add(key)
            output[key] = value
        else:
            repeat = True
    return output

if __name__ == "__main__":
    identifiers = subprocess.Popen(["lsof", "-F", "?"], stderr=subprocess.PIPE).communicate()

    keys = set([line.strip()[0] for line in identifiers[1].split("\n") if line != ''][1:])

    lsof_output = subprocess.check_output(["lsof", "-F"])
    rows = get_rows(lsof_output, whitelist_keys=keys)
    pprint.pprint(rows[:20])

rawDescription: Parse a variable row in python

description: Parse a variable row in python


code:
timeit.timeit("pickle.dumps([1,2,3])","import pickle",number=10000)
timeit.timeit("json.dumps([1,2,3])","import json",number=10000)
timeit.timeit("pickle.dumps([1,2,3])","import cPickle as pickle",number=10000)
timeit.timeit("marshal.dumps([1,2,3])","import marshal", number=10000)

rawDescription: Python: performance comparison of using `pickle` or `marshal` and using `re`


code:
list_iter = iter([])
iter(list_iter) is list_iter

rawDescription: How do I check if an iterator is actually an iterator container?

description: Check if an iterator is actually an iterator container


code:
def duplicate(self):
    kwargs = {}
    for field in self._meta.fields:
        kwargs[field.name] = getattr(self, field.name)
        # or self.__dict__[field.name]
    kwargs.pop('id')
    new_instance = self.__class__(**kwargs)
    new_instance.save()
    # now you have id for the new instance so you can
    # create related models in similar fashion
    fkeys_qs = self.fkeys.all()
    new_fkeys = []
    for fkey in fkey_qs:
        fkey_kwargs = {}
        for field in fkey._meta.fields:
            fkey_kwargs[field.name] = getattr(fkey, field.name)
        fkey_kwargs.pop('id')
        fkey_kwargs['foreign_key_field'] = new_instance.id
        new_fkeys.append(fkey_qs.model(**fkey_kwargs))
    fkeys_qs.model.objects.bulk_create(new_fkeys)
    return new_instance

rawDescription: Duplicate Django Model Instance and All Foreign Keys Pointing to It


code:
from distutils.core import setup
import py2exe

setup(console=['myscript.py'])

rawDescription: Best way to get Python script as an executable file?

description: Get Python script as an executable file


code:
table = pd.crosstab(df.A,[df.B,df.C], colnames=['topgroup','bottomgroup'])
table / table.sum(axis=1, level=0)

rawDescription: How to get row percentages with pandas crosstab in a three-way table?

description: Get row percentages with pandas crosstab in a three-way table


code:
wanted_envs={'HOME':'', 'USER':'', 'BANANA':''}
for env in wanted_envs.iterkeys():
    if env in os.environ:
        wanted_envs[env] = os.environ[env]

rawDescription: Can I pass a list to os.getenv()?

description: Pass a list to os.getenv()


code:
def get(url):
    run("wget '{}'".format(url))

rawDescription: How do i download things through fabric

description: Download things through fabric


code: print(r'text \" text2')

rawDescription: Unwanted quotes exception in String in Python


code:
def get_parameters_required(parameters=None):

    def _get_parameters_required(view_func):
        def _decorator(request, *args, **kwargs):
            missing_parameter = False
            if parameters is not None:
                for parameter in parameters:
                     if request.GET.get(parameter) is None:
                         missing_parameter = True

            if missing_parameter:
                return HttpResponse(status=400)

            response = view_func(request, *args, **kwargs)
            return response

        return wraps(view_func)(_decorator)
    return _get_parameters_required

rawDescription: Getting request object and extra parameters into custom decorator


code:
class WSGIHandler(base.BaseHandler):
  # ...
  def __call__(self, environ, start_response):
    # ...
    if self._request_middleware is None:
        self.load_middleware()

rawDescription: How does Django guarantee a middleware's __init__ to be called only once?


code:
import json
json.dumps(json.loads("""
{"node0":{
    "node1":{
        "attr0":"foo",
        "attr1":"foo bar",
        "attr2":"value with        long        spaces"
    }
}}
"""))

rawDescription: Crunching json with python

description: Crunching json with python


code:
text(0, 1,'matplotlib', horizontalalignment='center',
     verticalalignment='center',
     transform=ax.transAxes)

rawDescription: How to add equation of a line onto a plot in python

description: Add equation of a line onto a plot in python


code:
df
df.loc[[1],'A'].values #Works for `.ix` as well.
df.loc[[2],'A'].values #Works for `.ix` as well.

rawDescription: Pandas dataframe indexing: Use of '.values' for different index occurrence frequencies


code:
index = np.argmin(A, axis=1)
A_mins[:,0] = A[np.arange(len(A)), index]
A_mins[:,1:] = B[np.arange(len(A)), index]

rawDescription: Return elements in a location corresponding to the minimum values of another array


code:
a = ['\\Mango\\stone\\forest\\', '\\Orange\\sand\\house\\', '\\Rabbit\\cage\\village\\']
[x.split('\\')[1] for x in a]

rawDescription: Get the string between first two \ and \


code:
import turtle

radius = 100
turtle.speed(0)

for rings in range(10):
    turtle.penup()
    turtle.goto(0, -radius)
    turtle.pendown()
    turtle.circle(radius)
    radius += 10

rawDescription: How do you make a circle from origin

description: Make a circle from origin


code: a - a.loc['2005'].values.squeeze()

rawDescription: Subtract first row from all rows in Pandas DataFrame


code:
import itertools as it

x = [['a','b'],['c','d']]

print(' '.join(it.chain.from_iterable(x)))

rawDescription: How can I print the rows of a 2D-array in one line?

description: Print the rows of a 2D-array in one line


code:
df = df.set_index(["probe", "gene"])
df.groupby(lambda x: x.split(".")[0], axis=1).mean()
df.groupby(lambda x: x.split(".")[0], axis=1).mean().reset_index()

rawDescription: How to average values from columns that shared the same substring in column names

description: Average values from columns that shared the same substring in column names


code:
q1 = select([func.count(Tbl1.c.id).label("xxx")]
            ).where(Tbl1.c.user_id == some_id)
q2 = select([func.count(Tbl2.c.id).label("xxx")]
            ).where(Tbl2.c.user_id == some_id)
union = q1.union(q2).alias('uni')
query = select([func.sum(union.c.xxx).label("total_xxx")], from_obj=union)

rawDescription: Define name for column func.count in sqlalchemy


rawDescription: python struct unpack: Int PIN; char verified; time_t time_second; char status;

description: Python struct unpack: Int PIN; char verified; time_t time_second; char status;


code:
import matplotlib.pyplot as plt
import matplotlib.patheffects as pe

plt.figure()
ax = plt.gca()
txt = ax.text(0.5, 0.5, "test",
              size=20,
              color='white',
              path_effects=[pe.withStroke(linewidth=4, foreground="red")])
plt.show()

rawDescription: matplotlib: How to buffer label text?

description: Matplotlib: How to buffer label text


code:
x=linspace(0,10,100)
H0 = 71
omegas = [1.01,1.1,1.5,2.0,3.0]
rcs = [0.5*(omega0/(omega0-1))*(1-cos(x)) for omega0 in omegas]
tcs = [(0.5/H0)*(omega0/(omega0-1)**(3/2))*(x-sin(x)) for omega0 in omegas]
for pair in zip(tcs,rcs):
    plot(pair[0],pair[1])
show()

rawDescription: Plotting multiple functions using values in a list


code:
import operator
result = reduce(operator.and_, b)

rawDescription: What is an elegant way to perform Bitwise operation on a list of binaries in Python?


code: H = G.to_undirected()

rawDescription: Directed to undirected graph

description: Directed to undirected graph


code:
if not (licence_plate[:2].isalpha()
        and licence_plate[2:4].isdigit()
        and licence_plate[5:].isalpha()):
            fo = open("ishouldstudymore.txt", "aw")
            fo.write(licence_plate)
            fo.close()

rawDescription: Python File handling. Detecting license plates that don't match the british system


rawDescription: Combine set values into single set

description: Combine set values into single set


code:
[build_ext]
inplace=1

rawDescription: Making build --inplace without providing to python setup.py build_ext


code:
def __str__(self):
    return "{},{},{}".format(self.name, self.min_value, self.max_value)

rawDescription: Getting specific fields of a model in another, via relationships between them


code:
import numpy as np
a=np.random.random(100)*6
hist=np.histogram(a,bins=np.linspace(0,6,num=61))

rawDescription: python: using numpy.histogram

description: Python: using numpy.histogram


code:
#!/usr/bin/python
from reportlab.graphics.charts.lineplots import LinePlot
from reportlab.graphics.shapes import Drawing
from reportlab.lib import colors
from random import randint
from datetime import date, timedelta

# Generate some testdata
data = [
    [(x,randint(90,100)) for x in range(0,2001,100)],
    [(x,randint(30,80)) for x in range(0,2001,100)],
    [(x,randint(5,20)) for x in range(0,2001,100)],
    ]

# Create the drawing and the lineplot
drawing = Drawing(400, 200)
lp = LinePlot()
lp.x = 50
lp.y = 50
lp.height = 125
lp.width = 300
lp._inFill = 1
lp.data = data
for i in range(len(data)):
    lp.lines[i].strokeColor = colors.toColor('hsl(%s,80%%,40%%)'%(i*60))

# Specify where the labels should be
lp.xValueAxis.valueSteps = [5, 500, 1402, 1988]
# Create a formatter that takes the value and format it however you like.
def formatter(val):
    #return val
    #return 'x=%s'%val
    return (date(2010,1,1) + timedelta(val)).strftime('%Y-%m-%d')

# Use the formatter
lp.xValueAxis.labelTextFormat = formatter
drawing.add(lp)

from reportlab.graphics import renderPDF
renderPDF.drawToFile(drawing, 'example.pdf', 'lineplot with dates')

rawDescription: Adding date labels to a reportlab LinePlot chart


code:
to_find = 'MG'
old_list =  ['ADMISSION' ,'Colace','100','mg', 'b.i.d.' , 'insulin','Lente','12']
new_list = [item.lower() for item in old_list]
new_list.index(to_find.lower())

rawDescription: find the index of a string ignoring cases

description: Find the index of a string ignoring cases


code:
ip = self.request.remote_addr

if ip in allowed_ip_list:
    allow_access = True
else:
    allow_access = False

rawDescription: Restrict IP addresses to access your application on GAE?


code:
import sqlite3
conn = sqlike3.connect("testDb.DB")
c = conn.cursor()

def createUsr():
    global usrName_
    usrName_ = input('Enter your desired username: ')
    sql = """SELECT usrName FROM usrInfo WHERE usrName = ?"""
    usrName_Search = c.execute(sql, (usrName_,)).fetchone()
    if not usrName_Search:  #same as if usrName_Search ==None
        print('username created')
        sql = """INSERT INTO usrInfo (usrName) VALUES (?)"""
        c.execute(sql, (usrName_,))
    else:
        print('Username taken')
        createUsr()

createUsr()

rawDescription: How to search (or select) all rows in selected column in SQLite3 with Python?

description: Search (or select) all rows in selected column in SQLite3 with Python


code:
a1 = np.random.random((100,100))
a2 = np.random.nandom((100,100))

a1 = np.ma.array(a1, mask=a1<0.5)
a2 = np.ma.array(a2, mask=a2<0.5)

umask = np.logical_or(a1.mask, a2.mask) # <-- union of the masks

test = a1.data - a2.data
test[umask] = a1.data[umask] # <-- "canceling" the operation according to the
                             #     combined mask

np.allclose((a1-a2), test)
#True

rawDescription: Operations in Masked Numpy Arrays

description: Operations in Masked Numpy Arrays


code:
import os
import csv

with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=' ',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])
    spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
    csvfile.seek(-2, os.SEEK_END) # <---- 2 : len('\r\n')
    csvfile.truncate()            # <----

rawDescription: How write csv file without new line character in last line?


code:
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm.collections import attribute_mapped_collection
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.orm import relation, sessionmaker

metadata  = MetaData()
Base = declarative_base(metadata=metadata, name='Base')

class Item(Base):

    __tablename__ = 'Item'
    UniqueId = Column(Integer, ForeignKey('ItemSet.UniqueId'),
                      primary_key=True)
    ItemSet = relation('ItemSet')
    ItemName = Column(String(10), primary_key=True)
    ItemValue = Column(Text) # Use PickleType?

def _create_item(ItemName, ItemValue):
    return Item(ItemName=ItemName, ItemValue=ItemValue)

class ItemSet(Base):

    __tablename__ = 'ItemSet'
    UniqueId = Column(Integer, primary_key=True)
    _items = relation(Item,
                      collection_class=attribute_mapped_collection('ItemName'))
    items = association_proxy('_items', 'ItemValue', creator=_create_item)

engine = create_engine('sqlite://', echo=True)
metadata.create_all(engine)

session = sessionmaker(bind=engine)()
data = {"UniqueId": 1, "a": 23, "b": "Hello", "c": "World"}
s = ItemSet(UniqueId=data.pop("UniqueId"))
s.items = data
session.add(s)
session.commit()

rawDescription: SQLAlchemy Column to Row Transformation and vice versa -- is it possible?


code:
string1 = "foo"
string2 = "bar"

re.findall(r'{}(.*?){}'.format(string1, string2), text, re.DOTALL)

rawDescription: Can regex read user specified strings?

description: Can regex read user specified strings


code:
def replace(value, find, rep):
    if isinstance(value, tuple):
        return tuple(rep if val==find else val for val in value)
    return value

new_array = [replace(val, 'a', 'z') for val in array]

rawDescription: Replacing items in nested array and list-tuple


code:
driver = webdriver.PhantomJS()
driver.get('http://exampelurl/')
driver.find_element_by_id("Email").send_keys("user@gmail.com")
driver.find_element_by_id("Passwd").send_keys("password")
driver.find_element_by_id("signIn").click()

rawDescription: Python scraping by executing inpage Javascript


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

import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

from PyQt4.QtCore import *
from PyQt4.QtGui import *

class testDialogs(QWidget):
    def __init__(self, parent=None):
        super(testDialogs, self).__init__(parent)

        self.verticalLayout = QVBoxLayout(self)

        self.pushButton = QPushButton(self)
        self.pushButton.setText("Open a Dialog")

        self.pushButton1 = QPushButton(self)
        self.pushButton1.setText("Add a Text Edit")

        self.plainTextEdit = QPlainTextEdit(self)
        self.plainTextEdit.appendPlainText("This is a Widget")

        self.verticalLayout.addWidget(self.pushButton)
        self.verticalLayout.addWidget(self.pushButton1)
        self.verticalLayout.addWidget(self.plainTextEdit)

        self.pushButton.clicked.connect(self.on_pushButton_clicked)
        self.pushButton1.clicked.connect(self.on_pushButton1_clicked)

    @pyqtSlot()
    def on_pushButton_clicked(self):
        dialog = QDialog(self)
        verticalLayout = QVBoxLayout(dialog)

        plainTextEdit = QPlainTextEdit(dialog)
        plainTextEdit.appendPlainText("This is a Dialog")

        buttonBox = QDialogButtonBox(dialog)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        buttonBox.setObjectName("buttonBox")

        verticalLayout.addWidget(plainTextEdit)
        verticalLayout.addWidget(buttonBox)

        buttonBox.accepted.connect(dialog.close)
        buttonBox.rejected.connect(dialog.close)
        dialog.show()

    @pyqtSlot()
    def on_pushButton1_clicked(self):
        plainTextEdit = QPlainTextEdit(self)
        plainTextEdit.appendPlainText("This is another Text Edit")

        self.verticalLayout.addWidget(plainTextEdit)
        plainTextEdit.show()

if __name__ == "__main__":
    import  sys

    app = QApplication(sys.argv)
    main = testDialogs()
    main.show()
    sys.exit(app.exec_())

rawDescription: What is an idiomatic way of executing code AFTER the QDialog is shown in PyQT?


code:
def contact_create(request):
    if request.method == 'POST':
        form = ContactForm(request.POST)
        if form.is_valid():
            new_contact = form.save()
            return HttpResponseRedirect(reverse(contact_details, args=(new_contact.pk,)))
    else:
        form = ContactForm()

rawDescription: Get Primary Key after Saving a ModelForm in Django


code:
import time
print("Hello,", end="")
time.sleep(1)
print("World!")

rawDescription: Pause during print python 3.x

description: Pause during print python 3.x


code:
from Xlib import X, display
from OpenGL import GL, GLX
from OpenGL.raw._GLX import struct__XDisplay
from ctypes import *

# some python-xlib code...
pd = display.Display()
pw = pd.screen().root.create_window(50, 50, 200, 200, 0,
                                    pd.screen().root_depth,
                                    X.InputOutput, X.CopyFromParent)
pw.map()

# ensure that the XID is valid on the server
pd.sync()

# get the window XID
xid = pw.__resource__()

# a separate ctypes Display object for OpenGL.GLX
xlib = cdll.LoadLibrary('libX11.so')
xlib.XOpenDisplay.argtypes = [c_char_p]
xlib.XOpenDisplay.restype = POINTER(struct__XDisplay)
d = xlib.XOpenDisplay("")

# use GLX to create an OpenGL context on the same window XID
elements = c_int()
configs = GLX.glXChooseFBConfig(d, 0, None, byref(elements))
w = GLX.glXCreateWindow(d, configs[0], c_ulong(xid), None)
context = GLX.glXCreateNewContext(d, configs[0], GLX.GLX_RGBA_TYPE, None, True)
GLX.glXMakeContextCurrent(d, w, w, context)

# some python-opengl code....
GL.glShadeModel(GL.GL_FLAT)
GL.glClearColor(0.5, 0.5, 0.5, 1.0)

GL.glViewport(0, 0, 200, 200)
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glLoadIdentity()
GL.glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)

GL.glClear(GL.GL_COLOR_BUFFER_BIT)
GL.glColor3f(1.0, 1.0, 0.0)
GL.glRectf(-0.8, -0.8, 0.8, 0.8)

# assume we got a double buffered fbConfig and show what we drew
GLX.glXSwapBuffers(d, w)

# a terrible end to a terrible piece of code...
raw_input()

rawDescription: How do I use the xlib and OpenGL modules together with python?

description: Use the xlib and OpenGL modules together with python


code:
class SignupForm(authtoolsforms.UserCreationForm):
    captcha = CaptchaField()

    def __init__(self, *args, **kwargs):
        super(SignupForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.fields["email"].widget.input_type = "email"

        self.helper.layout = Layout(
            Field('email', placeholder="Enter Email", autofocus=""),
            Field('name', placeholder="Enter Full Name"),
            Field('password1', placeholder="Enter Password"),
            Field('password2', placeholder="Re-enter Password"),
            Field('gender', placeholder="Gender"),
            Field('captcha ', placeholder="Enter captcha"),
            Submit('sign_up', 'Sign up', css_class="btn-warning"),
            )

rawDescription: How to add a CaptchaField() in a Crispy Form in Django?

description: Add a CaptchaField() in a Crispy Form in Django


code:
count = 0
prices = item.find_all("span", {"class": "price"})
for price in prices:
    price_end = price.text.strip().replace(",","")[2:]
    count += 1
    print(price_end)
print(count, " prices found")

rawDescription: How to count the amount of prices python

description: Count the amount of prices python


code:
#!/usr/bin/env python
import socket
import subprocess
import sys
from pipes import quote

def main():
    print(socket.gethostname())
    print(sys.argv)

if __name__=="__main__":
   if '--remote-run' in sys.argv:
      sys.argv.remove('--remote-run')
      command = ' '.join(map(quote, ['python'] + sys.argv))
      sys.exit(subprocess.call(['ssh', '%s@%s' % (user, server), command]))
   else:
      main()

rawDescription: Spawning a process with inherited python optparse options


code:
a = np.random.random((4,4,4))
np.indices(a.shape).reshape((a.ndim, -1)).T

rawDescription: Simpler way to create a matrix/list of indices?


code:
import math

def sqpent(n):
    counter = 0
    i = 0
    l = []
    while counter < n:
        x = (i*(3*i-1)//2)
        #print(x)
        if(int(math.sqrt(x))**2 == x):
            #print("APPENDED: " + str(x))
            l.append(x)
            counter += 1
        i += 1
    return l

rawDescription: Calculating Polygonal Numbers Taking A While To Calculate


code: list(set(s))

rawDescription: An interesting code for obtaining unique values from a list


code:
np.allclose(mat, np.tril(mat)) # check if lower triangular
np.allclose(mat, np.triu(mat)) # check if upper triangular
np.allclose(mat, np.diag(np.diag(mat))) # check if diagonal

rawDescription: Check Upper or Lower Triangular Matrix

description: Check Upper or Lower Triangular Matrix


code:
from collections import Counter

counts = Counter(tuple(el) for el in nested_list)
#Counter({('time', 'company', 'language', 'price', 'description'): 2, ('quantity', 'time', 'date', 'description'): 1, ('date', 'language', 'price', 'quantity'): 1})

rawDescription: Is there a way to count number of appearances (nested list) using Counter


code:
time_waited = 0
then = time.time()
for p in processes:
    if time_waited >= DURATION:
        p.join(0)
        p.terminate()
    p.join(DURATION - time_waited)
    time_waited = time.time() - then

rawDescription: Join a group of python processes with a timeout


rawDescription: pandas - More efficient way to calculate two Series with circular dependencies

description: Pandas - More efficient way to calculate two Series with circular dependencies


rawDescription: Django: Default ordering based on a many-to-many related field values and counts


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

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

x = np.random.random(10)
y = np.random.random(10)
ax.scatter(x, y)

ax.fill_between(ax.get_xlim(), min(y), max(y), color='k', alpha=0.2)

rawDescription: Matplotlib - Plot line with width equivalent to a range of values, not just one single


code:
import sys
import os
'sys' in sys.modules
'os' in sys.modules
sys.modules['sys'].__dict__.keys()

rawDescription: Get a dictionary's key by value

description: Get a dictionary's key by value


code:
import sys
import os
from PyQt4 import QtGui

class AnExample(QtGui.QMainWindow):
    def __init__(self):
        super(AnExample, self).__init__()

        self.buildUi()

    def buildUi(self):

        self.listWidget = QtGui.QListWidget()
        self.listWidget.addItems(['one',
                                  'two',
                                  'three'])

        warning = QtGui.QLabel("Warning, this progam can write to disk!")
        saveButton = QtGui.QPushButton('Save to location...')
        justSaveButton = QtGui.QPushButton('Just save!')
        saveButton.clicked.connect(self.onSave)
        justSaveButton.clicked.connect(self.onJustSave)

        grid = QtGui.QGridLayout()
        grid.addWidget(warning, 0, 0)
        grid.addWidget(self.listWidget, 1, 0)
        grid.addWidget(saveButton, 2, 0)
        grid.addWidget(justSaveButton, 3, 0)

        central = QtGui.QWidget()
        central.setLayout(grid)

        self.setCentralWidget(central)

    def onSave(self):
        self.saveFile(True)

    def onJustSave(self):
        self.saveFile(False)

    def saveFile(self, showDialog):
        """
        Function that will save list items to file.
        """
        # save to TESTING.txt in current working directory
        savePath = os.path.join(os.getcwd(),
                                'TESTING.txt')

        # allow user to override location if requested
        if showDialog:
            savePath = QtGui.QFileDialog.getSaveFileName(self,
                                                         'Save text file',
                                                         savePath,
                                                         'TESTING.txt')

        # if just saving, or user didn't cancel, make and save file
        if len(savePath) > 0:
            with open(savePath, 'w') as theFile:
                for i in xrange(self.listWidget.count()):
                    theFile.write(''.join([str(self.listWidget.item(i).text()),
                                           '\n']))

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = AnExample()
    ex.show()
    sys.exit(app.exec_())

rawDescription: PyQt4: Save a QListWidget

description: PyQt4: Save a QListWidget


rawDescription: Rearrange a python list into n lists, by column


code:
import os
import fnmatch

filenamels = []
inputExtension = ".nc"
outputExtension = ".img"
inputDir = "C:\\Users\\"
for filename in os.listdir(inputDir):
    if fnmatch.fnmatch(filename, '*' + inputExtension):
        filenamels.append(filename[:-len(inputExtension)])

for fn in filenamels:
    inputDataset = 'NETCDF:\"'+ fn + inputExtension +'\":sf'
    outputFile = inputDir + 'Nx.' + fn + '.SUB' + outputExtension
    gdalcmd='gdal_translate -of "ENVI" '+ inputDataset + ' '+ outputFile
    os.system( gdalcmd)

rawDescription: How to extract the name of inputfile for the outputfile when using python?

description: Extract the name of inputfile for the outputfile when using python


code:
alpha1Order = {token: i for i, token in enumerate(alpha1Order)}
alpha2Order = {token: i for i, token in enumerate(alpha2Order)}

def keyfunction(filename):
    num, alpha1, alpha2 = tokenize(filename)
    return int(num), alpha1Order[alpha1], alpha2Order[alpha2]

rawDescription: Custom Sort Complicated Strings in Python


code: df.rename(columns={'sales' : 'CurrentSales', 'cash' : 'US$' })

rawDescription: Recoding Pandas Index Objects from a Dictionary (for Non-Ordered Replacement)


code:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Firefox()
driver.get("http://whatever")
driver.find_element_by_link_text("link-text").click()

rawDescription: Using Python to automate the use of online file converter


code:
tests=(
    ('fck','fc kopenhavn',True),
    ('fco','fc kopenhavn',False),
    ('irl','in real life',True),
    ('irnl','in real life',False),
    ('ifk','ifk gotebork',True),
    ('ifko','ifk gotebork',False),
    ('aik','allmanna idrottskluben',True),
    ('aid','allmanna idrottskluben',True),
    ('manu','manchester united',True),
    ('fz','faz zoo',True),
    ('fzz','faz zoo',True),
    ('fzzz','faz zoo',False),
    )

def is_abbrev(abbrev, text):
    abbrev=abbrev.lower()
    text=text.lower()
    words=text.split()
    if not abbrev:
        return True
    if abbrev and not text:
        return False
    if abbrev[0]!=text[0]:
        return False
    else:
        return (is_abbrev(abbrev[1:],' '.join(words[1:])) or
                any(is_abbrev(abbrev[1:],text[i+1:])
                    for i in range(len(words[0]))))

for abbrev,text,answer in tests:
    result=is_abbrev(abbrev,text)
    print(abbrev,text,result,answer)
    assert result==answer

rawDescription: Check if a string is a possible abbrevation for a name


code: cmd ='ps -ef | grep "Admin|%s"' % appid

rawDescription: Passing local variable in python sshClient command


code:
import urllib2
url = "webservice"
s = urllib2.urlopen(url)
contents = s.read()
file = open("export.xml", 'w')
file.write(contents)
file.close()

rawDescription: Python saving xml from webservice

description: Python saving xml from webservice


code:
from BeautifulSoup import BeautifulSoup
myform = MyForm()
rendered_form = myform.as_p()
soup = BeautifulSoup(rendered_form)
values = {}
for input in soup.findAll('input'):
    value = input.get('value')
    if value:
        values[input['name']] = value
for select in soup.findAll('select'):
    selected = select.find(selected='selected')
    if selected:
        values[select['name']] = selected['value']

rawDescription: Posting a form back with it's default values in the Django TestClient


code:
gmt_offset_str = time_string[-3:]
gmt_offset_seconds = int(gmt_offset_str)*60*60
timestamp = time.strptime(time_string[:-4], '%Y-%m-%d %H:%M:%S')
return time.localtime(time.mktime(timestamp)-gmt_offset_seconds)

rawDescription: How do I parse timezones with UTC offsets in Python?

description: Parse timezones with UTC offsets in Python


code:
c = Client()
with open('wishlist.doc') as fp:
    c.post('/customers/wishes/', {'name': 'fred', 'attachment': fp})

rawDescription: How to write unit test for file upload class in django?

description: Write unit test for file upload class in django


code:
for tablename in list_of_tablenames:
    cursor.execute('SELECT DISTINCT zone FROM {}'.format(tablename))
    zones = [r[0] for r in cursor]

rawDescription: List of values from sqlite3 database

description: List of values from sqlite3 database


code:
class BindableHTTPHandler(urllib2.HTTPHandler):
    def http_open(self, req):
        return self.do_open(BindableHTTPConnectionFactory('10.91.56.4'), req)

rawDescription: python equivalent for curl --interface

description: Python equivalent for curl --interface


code:
df['label'] = 'F'
df.loc[df[df['V1'] > df['V1'].mean()].sample(1).index,'label'] = 'T'
df.loc[df[df['V1'] <= df['V1'].mean()].sample(1).index,'label'] = 'T'
df

rawDescription: Python Pandas: Creating New Variable Based On Sampling Results


code:
import re

r = re.compile(r"(\w+)\[(\d+)(?::(\d+))?\]")

def expand_seq(seq):
    result = []
    for item in seq:
        m = r.match(item)
        name, start, end = m.group(1), int(m.group(2)), m.group(3)
        rng = xrange(start, int(end)) if end else (start,)
        t = name + "["
        result.extend(t + str(i) + "]" for i in rng)
    return result

rawDescription: Large list generation optimization

description: Large list generation optimization


code:
def main():

    def configure_logging():
        logging_config = {
            'formatters': {
                'f': {
                    'format': '%(processName)-10s %(name)s'
                              ' %(levelname)-8s %(message)s',
                },
            },
            'handlers': {
                'h': {
                    'level':'INFO',
                    'class':'logging.StreamHandler',
                    'formatter':'f',
                },
            },
            'loggers': {
                '': {
                    'handlers': ['h'],
                    'level':'INFO',
                    'propagate': True,
                },
            },
            'version': 1,
        }

        pname = mp.current_process().name
        if pname != 'MainProcess':
            logging_config['handlers'] = {
                'h': {
                    'level':'INFO',
                    'formatter':'f',
                    'class':'logging.FileHandler',
                    'filename': pname + '.log',
                },
            }

        logging.config.dictConfig(logging_config)

    configure_logging() # MainProcess
    def pool_initializer():
        configure_logging()

    n_cores = 4
    pool = mp.Pool(n_cores, initializer=pool_initializer)
    pool.map(do_log, range(100))
    pool.close()
    pool.join()

rawDescription: How can I prevent the inheritance of python loggers and handlers during multiprocessing based on fork?

description: Prevent the inheritance of python loggers and handlers during multiprocessing based on fork


code:
from collections import defaultdict

d = defaultdict(int)

with open(file.txt) as f:
    for line in f:
        d[line]+=1

rawDescription: sort and count occurences of 12 giga text file

description: Sort and count occurences of 12 giga text file


code:
zipfile = ZipFile(os.path.join(dest_dir, zip_name), 'w', ZIP_DEFLATED)
sys.path.insert(0, '.')
finder = ModuleFinder()
finder.run_script(source_name)

for name, mod in finder.modules.iteritems():
    filename = mod.__file__
    if filename is None:
        continue
    if "python" in filename.lower():
        continue

    subprocess.call('"%s" -OO -m py_compile "%s"' % (python_exe, filename))

    zipfile.write(filename, dest_path)

rawDescription: Cross-platform alternative to py2exe

description: Cross-platform alternative to py2exe


code:
import codecs
import sys

input_file_name    = sys.argv[1]
input_column_index = int(sys.argv[2]) - 1
match_file_name    = sys.argv[3]
match_column_index = int(sys.argv[4]) - 1
output_file_name   = sys.argv[5]

# create a set of all unique values in the match_column of match_file_name
matching_values = set()
with codecs.open(match_file_name, encoding='utf-8', mode="rb") as match_file:
    for cols in (line.split() for line in match_file):
        matching_values.add(cols[match_column_index])

with codecs.open(output_file_name, encoding='utf-8', mode="wb") as output_file:
    # copy lines from input_file to output file whose value in the input_column
    # is one of the ones in the match column of the match_file
    with codecs.open(input_file_name, encoding='utf-8', mode="rb") as input_file:
        for line in input_file:
            cols = line.split()
            if cols[input_column_index] in matching_values:
                output_file.write(line)

rawDescription: Python to eliminate rows whose nth column doesn't exist in mth column of another file


rawDescription: Does anyone see why the first part of my regex isn't working in Python?


code:
from collections import Counter

def __repr__(self):
    counter = Counter(self.data)
    items = ', '.join('%s (%s)' % (name, count) for name, count in counter.iteritems())
    return "<Bag: '{}' with {} >".format(self.name, items)

rawDescription: Defining a proper __repr__ in Python

description: Defining a proper __repr__ in Python


code: config.has_option(section, option)

rawDescription: Python ConfigParser Section Key Value

description: Python ConfigParser Section Key Value


code:
functions = {
        'app_server.php':self.app_server,
        'dcrm2nlyte.php':self.dcrm2nlyte,
        'export.php':self.export,
        'host_server.php':self.host_server,
        'spc.php':self.spc,
        'spc_approved.php':self.spc_approved,
        'spc_approved_by_dc.php':self.spc_approved_by_dc,
        'spc_by_dc.php':self.spc_by_dc,
        'spc_complete.php':self.spc_complete,
        'spc_summary.php':self.spc_summary
}

rawDescription: How to retrieve dictionary values in Python?

description: Retrieve dictionary values in Python


code:
widget = QWidget()
layout = QVBoxLayout()

btn = QPushButton("To be removed")
layout.addWidget(btn)
widget.setLayout(layout)

# later
btn.setParent(None)

rawDescription: pyqt: how to remove elements from a QVBoxLayout?

description: Pyqt: how to remove elements from a QVBoxLayout


code:
import threading

t = threading.Thread(target=ctypes_call, args=[arg1, arg2, ...])
t.daemon = True
t.start()
while t.is_alive(): # wait for the thread to exit
    t.join(.1)

rawDescription: CTRL+C doesn't interrupt call to shared-library using CTYPES in Python


code:
for n in range(5):
    nprint(chop(taylor(lambda x: legendre(n, x), 0, n)))

rawDescription: Generating Legendre Polynomials in Sympy


code:
MONTH = r'(?P<month>Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)'
DAY = r'(?P<day>\d{2})'
TIME = r'(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})'
SPC = r'\s'
HOST = r'(?<host>\w+)'
PREFIX = SPC.join(MONTH, DAY, TIME, HOST)
foobar_patterns = {
    'pattern1': re.compile(PREFIX + r'\s(?<payload>blahbla hbla h blah)'),
    'pattern2': re.compile(PREFIX + r'\s(?<payload>bla h blahbla hblah)'),
}

rawDescription: Python regex - reduce redundancy in patterns?


code:
S = 'http://1.8.1.1:5000/student/<studentid>/student_details/<rollnumber>'
import re
k = re.sub(r'<.*?>', '{}', S)
k
x="myid"
y="myrollnumber"
k.format(x, y)

rawDescription: Replace string elements inside a tag

description: Replace string elements inside a tag


code:
def print_to_string(*objects, sep=' ', end='\n'):
     return sep.join(str(obj) for obj in objects) + end

rawDescription: Is there a standard-library "print_to_string" function in Python?


code:
UPDATE_Statement = "Update paste set paste_content = %s where paste_id=%s"

cursor.execute(UPDATE_Statement, content)

rawDescription: python sqlite3 Double quotes resulting query failure

description: Python sqlite3 Double quotes resulting query failure


code:
from tkinter import *

import time

class Game:
    def __init__(self):
        self.__window = Tk()

        self.gifdir = "./"

        self.igm = PhotoImage(file=self.gifdir+"empty.gif")

        self.btn = Button(self.__window, image=self.igm, command = self.change_picture)
        self.btn.grid(row=1, column=2, sticky=E)

        self.__window.mainloop()

    def change_picture(self):
        self.igm = PhotoImage(file=self.gifdir+"new.gif")
        self.btn.configure(image = self.igm)

def main():
    Game()

main()

rawDescription: Python tkinter: Replacing an image button with an image label


code:
os.environ['PATH'] = '%s;%s' % (os.environ['PATH'], os.path.abspath('./driver/i386'))
os.environ['PATH'] = '%s;%s' % (os.environ['PATH'], os.path.abspath('./driver/amd64'))

rawDescription: Py2Exe + FTDI driver

description: Py2Exe + FTDI driver


code:
from sense_hat import SenseHat
import time
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
sense = SenseHat()

Broker = "192.168.1.252"

sub_topic = "sensor/instructions"    # receive messages on this topic

pub_topic = "sensor/data"       # send messages to this topic

############### sensehat inputs ##################

def read_temp():
    t = sense.get_temperature()
    t = round(t)
    return t

def read_humidity():
    h = sense.get_humidity()
    h = round(h)
    return h

def read_pressure():
    p = sense.get_pressure()
    p = round(p)
    return p

def display_sensehat(message):
    sense.show_message(message)
    time.sleep(10)

############### MQTT section ##################

# when connecting to mqtt do this;

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe(sub_topic)

# when receiving a mqtt message do this;

def on_message(client, userdata, msg):
    message = str(msg.payload)
    print(msg.topic+" "+message)
    display_sensehat(message)

def on_publish(mosq, obj, mid):
    print("mid: " + str(mid))

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(Broker, 1883, 60)
client.loop_start()

while True:
    sensor_data = [read_temp(), read_humidity(), read_pressure()]
    client.publish("monto/solar/sensors", str(sensor_data))
    time.sleep(1*60)

rawDescription: python mqtt script on raspberry pi to send and receive messages

description: Python mqtt script on raspberry pi to send and receive messages


code:
int(float(-1)/2)
int(float(-3)/2)
int(float(1)/2)
int(float(3)/2)

rawDescription: In Python, what is a good way to round towards zero in integer division?


code:
path = '/book/html/wa/foo/bar/'
path[path.find('/wa'):]

rawDescription: How to remove a path prefix in Python?

description: Remove a path prefix in Python


code:
import filesystem.directory

class File(object):

   def __init__(self):
       self._Directory = filesystem.directory.Directory

   def foo(self):
       some_dir = self._Directory(...)

rawDescription: Python Package Design And Circular Imports


rawDescription: Getting arguments from code

description: Getting arguments from code


code:
import operator
...
for item in sorted(t, key=operator.itemgetter(0)):
    ...

rawDescription: Sorting a tuple in python

description: Sorting a tuple in python


code:
import argparse
parser = argparse.ArgumentParser()

parser.add_argument('--char', type=int,
                   help='number of characters')

args = parser.parse_args()
char = args.char

rawDescription: Use argparse module in python to parse a single argument


code:
leg = ax.legend()
for t in leg.texts:
    t.set_multialignment('center')

rawDescription: Multiline alignment of Matplotlib legend LaTeX text


code:
scheduler.add_job(func, 'cron', day='1st tue')
scheduler.add_job(func, 'cron', day='1st mon,3rd mon')
scheduler.add_job(func, 'cron', day='1st fri,last fri')

rawDescription: Running APScheduler Job Every nth Day of Month


rawDescription: How do i make a list change like this?

description: Make a list change like this


code:
label = QtGui.QLabel()
layout.addWidget(label)
verticalSpacer = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QSizePolicy.Expanding)
layout.addItem(verticalSpacer)

rawDescription: How to use spacers in Qt

description: Use spacers in Qt


code:
comp3 = [set(L[1:]) for L in comp3]
comp4 = [set(L[1:]) for L in comp4]

comp3 == comp4  # this should do the trick

rawDescription: Python: Comparing Two lists

description: Python: Comparing Two lists


code:
for obj in bpy.data.objects:
    obj.tag = True

bpy.import_scene.obj(filepath="somefile.obj")

imported_objects = [obj for obj in bpy.data.objects if obj.tag is False]

rawDescription: How to mark last imported *obj in blender

description: Mark last imported *obj in blender


code:
import matplotlib.pyplot as plt
ax = plt.gca()  # or any other way to get an axis object
ax.plot(x, y, label=r'$\sin (x)$')

ax.legend()

rawDescription: How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?

description: Write a Latex formula in the legend of a plot using Matplotlib inside a .py file


rawDescription: matplotlib 3dbars: trouble with axes

description: Matplotlib 3dbars: trouble with axes


code:
data = {}
def set(key, val):
    data[key] = val

def get(key):
    return data[key]

mock_redis_set.side_effect = set
mock_redis_get.side_effect = get

rawDescription: How to mock a redis client in Python?

description: Mock a redis client in Python


code:
table = soup.find('table', id='submission')
accepted = table.tbody.find('label', class_='AC')
if accepted:
    row = accepted.parent.parent  # row with accepted column

rawDescription: ReGex with Python cant find the correct Regular Expression


code:
import telnetlib
import os

host_ip = "1.1.1.1"
user = "user"
password = "password"

tnet_hndl = telnetlib.Telnet(host_ip)
print (tnet_hndl.read_until(b"login: "))
tnet_hndl.write(user.encode('ascii') + b"\n")
print (tnet_hndl.read_until(b"Password: "))
tnet_hndl.write(password.encode('ascii') + b"\n")
print (tnet_hndl.read_until(b"# "))
#tnet_hndl.set_debuglevel(1) #enable this if you want to debug more
tnet_hndl.write(b"<enter some windows cmd here>" + b"\n")
print (tnet_hndl.read_until(b"# "))
tnet_hndl.close()

rawDescription: Telnet not working for os.system call

description: Telnet not working for os.system call


code:
ax = df2.plot(lw=2,colormap='jet',marker='.',markersize=10,title='Video streaming dropout by category')
ax.set_xlabel("x label")
ax.set_ylabel("y label")

rawDescription: Add x and y labels to a pandas plot

description: Add x and y labels to a pandas plot


code:
data = ""
while True:
    chunk = conn.recv(2048).decode()
    if not data:
        break
    # try to separate the chunk by newline, to see if you got one.
    while True:
        split = chunk.split("\r\n", num=1)
        data += split[0]
        if len(split) == 1:
            break
        # Now we have a completed newline, so send the response
        replay = 'OK....' + data
        conn.sendall(replay.encode())
        data = ""
conn.close()

rawDescription: socket pogramming for beginer - server creating

description: Socket pogramming for beginer - server creating


code: format = self.get_argument("format")

rawDescription: Get the content of an <input> textbox with Python


code: app.add_url_rule('/posts1_add', methods['POST'], 'posts1_add', posts.post1.add)

rawDescription: Colliding Namespace in Python Module with Flask


code:
from pyparsing import CaselessKeyword, quotedString, removeQuotes
from dateutil.parser import parse as parse_date

dp = (
    CaselessKeyword('from') + quotedString.setParseAction(removeQuotes)('from') +
    CaselessKeyword('to') + quotedString.setParseAction(removeQuotes)('to')
)

res = dp.parseString('from "jan 20" to "apr 5"')
from_date = parse_date(res['from'])
to_date = parse_date(res['to'])
# from_date, to_date == (datetime.datetime(2015, 1, 20, 0, 0), datetime.datetime(2015, 4, 5, 0, 0))

rawDescription: Build a simple parser that is able to parse different date formats using PyParse


code:
conn  = session.connection().connection
cursor = conn.cursor()  # get mysql db-api cursor
cursor.execute(sql, multi=True)

rawDescription: Enable executing multiple statements while execution via sqlalchemy


code:
csvinput = 'mainfile.csv'
reader = csv.reader(open(r'{0}'.format(csvinput)), delimiter=',')

for word in wordlist:
    filtered = filter(lambda p: word == p[6], reader)
    csv.writer(open("{}\{}.csv".format(word, word),'w', newline = ''),delimiter=',').writerows(filtered)
    time.sleep(0.1)

rawDescription: How to go through a list of files

description: Go through a list of files


rawDescription: Integer list join using string.format

description: Integer list join using string.format


code:
bill = float(input('What whas the bill amount? '))
tip = (float(input('What whas the tip percentage? '))/100)*bill
total = bill+tip
print('The tip amount is $'+str(tip))
print('The total amount is $'+str(total))

rawDescription: Python Multiplication Tips For Bills

description: Python Multiplication Tips For Bills


code:
import re
inp = "val = 20 MORE @#$TEXT.!!??"
res = re.sub(r'(^val\s*=\s*\d+)|[^A-Z]', lambda m: m.group(1) if m.group(1) else "", inp)
print(res)

rawDescription: How to Find Certain Characters When They Are Not Part of a String? (Regex, Python)


code: lframe = [x for x in [e.encode('utf-8') for e in frame.split(',')][0]]

rawDescription: convert unicode into list

description: Convert unicode into list


rawDescription: (Python 3.x) How do I add a space before the first variable in a print function?


code:
import itertools, copy

def infinite_copies(some_iterable):
    master, copy1 = itertools.tee(some_iterable)
    yield copy1
    while True:
        yield copy.copy(master)

rawDescription: In python, can I lazily generate copies of an iterator using tee?


code:
action = Gio.SimpleAction.new('my-action', None)
action.set_enabled(False) # This makes it insensitive

rawDescription: Setting sensitivity of menu item associated with Gio.Action


code:
import random
'{0:05}'.format(random.randint(1, 100000))

rawDescription: generate a random number with fixed length

description: Generate a random number with fixed length


code:
# perform filtering and get the first 'A' object
obj = A.objects.filter(name__exact='xyz',slot_hours__start_time__gte=780)[0]

# get the relavent 'SlotTime' objects
slot_time_objs = [x for x in obj.slot_hours if x.start_time >= 780]

rawDescription: Greater than (gte) query in MongoEngine for EmbeddedDocumentListField


code:
import subprocess

for v in range(1000):
    cmdLine = r"c:\path\to\my\app.exe"
    subprocess.Popen(subprocess)
    subprocess.Popen(r"move output.txt ./acc/output-%d.txt" % (v))

rawDescription: Run a C# application from python script

description: Run a C# application from python script


code:
data = {'string': username + '|' + password}
r = requests.post(url, data=data)

rawDescription: How do I send a query string in post request in Python using pipe delimiters?

description: Send a query string in post request in Python using pipe delimiters


code: proj_dir = os.getenv('PROJECT_DIR')

rawDescription: Xcode Pre-actions run python script environment variables not setting ${PROJECT_DIR} properly


code:
import matplotlib.pyplot as plt
from matplotlib import gridspec

def plot_data(avg_rel_track, sd_rel_track_sum, sd_index, sd_grad):

    fig = plt.figure(figsize=(15,10))
    gs  = gridspec.GridSpec(4, 1, height_ratios=[1, 1 ,1.5, 1])
    ax0 = plt.subplot(gs[0])
    ax1 = plt.subplot(gs[1])
    ax2 = plt.subplot(gs[2])
    ax3 = plt.subplot(gs[3])

    fig.subplots_adjust(top=0.85)
    lineObjects = ax0.plot(avg_rel_track_nan)

    if len(sd_index)>1:
        for i in xrange(1, len(sd_index)):
            if sd_grad[i]==1:
                ax0.axvspan(sd_index[i-1], sd_index[i],
                            edgecolor='#FFCC66', facecolor='#FFCC66',
                            alpha=1)

    #The following plot has 5 plots within it.
    ax0.set_title('Averaged Relative Track',fontsize=11)
    ax0.legend(lineObjects, (1,2,3,4,5))

    ax1.plot(sd_rel_track_sum)
    ax1.set_title('RT Standard Deviation',fontsize=11)
    ax1.set_ylim([0,250])

    ax2.plot(splitpre)
    ax2.set_title('Track Split',fontsize=11)

    ax3.plot(ts_sd)
    ax3.set_title('Track Split Standard Dev',fontsize=11)
    ax3.set_ylim([0,100])

    fig.tight_layout()
    plt.show()

rawDescription: Resizing a single subplot in matplotlib

description: Resizing a single subplot in matplotlib


code:
import tempfile, subprocess
installpip="echo 'hello'\n"

with tempfile.TemporaryFile() as scriptfile:
        scriptfile.write(installpip)
        scriptfile.flush()
        scriptfile.seek(0)
        subprocess.call(['/bin/bash', '-s'], stdin=scriptfile)

rawDescription: Bash+Python - encoded script's source shows up temporarily under /tmp


code:
from django.core.urlresolvers import reverse

def logout(request):
    auth.logout(request)
    return HttpResponseRedirect(reverse('index'))

rawDescription: how to get url of app in django

description: Get url of app in django


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

xtrue = 2 # unknown in the real application
prior = rnormal(0,1,10000) # initial guess is inaccurate
for i in range(5):
  x = stochastic_from_data('x', prior)
  y = x*x
  obs = Normal('obs', y, 0.1, xtrue*xtrue + rnormal(0,1), observed=True)

  model = Model([x,y,obs])
  mcmc = MCMC(model)
  mcmc.sample(10000)

  Matplot.plot(mcmc.trace('x'))
  plt.show()

  prior = mcmc.trace('x')[:]

rawDescription: Solving inverse problems with PyMC

description: Solving inverse problems with PyMC


rawDescription: Python scripts that depend on binaries... how to distribute?


code: tally = {k: sum(d.get(k) if k != 'count' else 1 for d in data if d.get('code') == code and d.get('type') == type and d.get('color') == color) for k in ('count', 'amount', 'cost')}

rawDescription: How can I count the number of elements given to a column sum from a list of dictionaries quickly?

description: Count the number of elements given to a column sum from a list of dictionaries quickly


code:
import re
s = "107S33M15H\n33M100S\n12M100H33M"
print(re.findall(r"(\d+)M", s))

rawDescription: Extract Number before a Character in a String Using Python


code:
if not gameover:

    playground.fill(...)

    # draw normal game

else:

    playground.fill(...)

    # draw gameover text

playground.flip()

rawDescription: Blinking endscreen - pygame

description: Blinking endscreen - pygame


code:
import argparse
parser = argparse.ArgumentParser()

# Init sub-command
parser_init = subparsers.add_parser('init', help='initialize the things')
parser_init.add_argument(...)

# Help sub-command
parser_help = subparsers.add_parser('help', help='help me!')
parser_help.add_argument(...)

rawDescription: multiple level arguments processing with `optparse`

description: Multiple level arguments processing with `optparse`


code:
bShowInline = True  # Set = False for document generation

def makeplot( plt, figlabel, figcaption):
    figname = figlabel+'.png'

    plt.savefig(figname)

    if bShowInline:
        plt.show()
    else:
        plt.close()

    strLatex="""
    \\begin{figure}[b]
    \centering
        \includegraphics[totalheight=10.0cm]{%s}
        \caption{%s}
        \label{fig:%s}
    \end{figure}"""%(figname, figcaption, figlabel)
    return display(Latex(strLatex))

rawDescription: How to add latex figure captions below jupyter / matplotlib figures

description: Add latex figure captions below jupyter / matplotlib figures


code:
import glob
import ipywidgets as widgets
from IPython.display import display
from IPython.html.widgets import interactive

csvs = sorted(glob.glob('*/*csv'))

def plot(x=csvs[0]):
    dfs = pd.read_csv(x, sep=',')
    dfs.plot(figsize=(12, 8))

w = widgets.Select(options=csvs)
interactive(plot, x=w)

rawDescription: Ipywidget dropdown menu to select figure from list


code:
__gsignals__ = {
  "some-signal": (gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ()),
}

rawDescription: How to create a gsignal without parameters in pygtk

description: Create a gsignal without parameters in pygtk


code:
from flask import Flask
from werkzeug.routing import BaseConverter

class WildcardConverter(BaseConverter):
    regex = r'(|/.*?)'
    weight = 200

app = Flask(__name__)
app.url_map.converters['wildcard'] = WildcardConverter

@app.route('/users<wildcard:path>')
def users(path):
    return path

c = app.test_client()
print(c.get('/users').data)  # b''
print(c.get('/users-no-prefix').data)  # (404 NOT FOUND)
print(c.get('/users/').data)  # b'/'
print(c.get('/users/400617/edit').data)  # b'/400617/edit'

rawDescription: Match an arbitrary path, or the empty string, without adding multiple Flask route decorators


code:
import random
file = open("primes.txt", "w")
i=0
while(i<=100):
    temp=str(random.randint(1,500))
    file.write(temp  + "\n")  #add a newline after each number
    i+=1
file.close()

rawDescription: How do I use writelines() correctly?

description: Use writelines() correctly


code:
def getPath(var):
  return "/Users/check/" + str(var) + ".html"

print(getPath(1))
print(getPath(2))

rawDescription: Declare global variables in python and access locally


code:
extract_dates = re.compile("[0-9]{8}").findall
dates = [dates[0] for dates in sorted(
    extract_dates(filename) for filename in os.listdir('.')) if dates]

rawDescription: Extract substring from filename in Python?


code:
new_lines = []
with open("test.txt") as f:
    for line in f:
        new_line = list(line)
        new_line[1] = "k"
        new_lines.append(''.join(new_line))

with open("test.txt", "w") as f:
    f.writelines(new_lines)

rawDescription: Change content of the same column and write to the same file


code:
import pymysql
import sys
conn = pymysql.connect(host="localhost",
            user="test",
            passwd="",
            db="test")
cursor = conn.cursor()
text = conn.escape(request[1])
cursor.execute("SELECT * FROM `Codes` WHERE `ShortCode` =  {}".format(text))

cursor.close()
conn.close()

rawDescription: How can I escape the input to a MySQL db in Python3?(Solved)

description: Escape the input to a MySQL db in Python3?(Solved)


code:
from urlparse import urlparse
o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
o   # doctest: +NORMALIZE_WHITESPACE
o.scheme
o.port
o.geturl()

rawDescription: Does the Python standard library contain a module for manipulating URIs?


code:
ax.plot_surface(X, Y, Z1, color='w', alpha=0.2, linewidth=0)
ax.plot_surface(X, Y, Z2, color='b', alpha=0.2, linewidth=0)

rawDescription: Getting rid of artifacts/grid-lines when plotting 3d surfaces


code:
from django.contrib import admin

class PostInline(admin.StackedInline):
    model = Post
    show_change_link = True
    ...

class BlogAdmin(admin.ModelAdmin):
    inlines = [PostInline]
    ...

class ImageInline(admin.StackedInline):
    # Assume Image model has foreign key to Post
    model = Image
    show_change_link = True
    ...

class PostAdmin(admin.ModelAdmin):
    inlines = [ImageInline]
    ...

admin.site.register(Blog, BlogAdmin)
admin.site.register(Post, PostAdmin)

rawDescription: How do I add a link from the Django admin page of one object to the admin page of a related object?

description: Add a link from the Django admin page of one object to the admin page of a related object


code:
_url = request.url.replace(request.url_root,'')
url = urllib.unquote(_url)

rawDescription: How to pass URL with parameters in GET request in Flask?

description: Pass URL with parameters in GET request in Flask


rawDescription: Convert sparse dictionary representation into a dense dataframe


code:
import binascii
hexstr = 'FF0000FF'
binstr = binascii.unhexlify(hexstr)

rawDescription: Write a hex string as binary data in Python


rawDescription: python threading.Timer start immediately not at specified time

description: Python threading.Timer start immediately not at specified time


code:
def testLogonCookie(self):
    self.cli.connect()
    self.cli.request("POST", '/login', b'user=GUI&pass=Junkie')
    res = self.cli.getresponse()
    heads = res.getheader('Set-Cookie')
    txt = str(res.readall())
    self.assertGreater(txt.find('Lorum ipsum'), -1, 'testLogin')
    head = {'Cookie': heads}
    self.cli.request('GET', '/loggedon', headers=head)
    res = self.cli.getresponse()
    txt = str(res.readall())
    self.assertGreater(txt.find('user=GUI_Junkie'), -1, 'testLogonCookie')

rawDescription: Unit testing http session cookies python3


code:
class CheckFileSize(formencode.validators.FormValidator):
    __unpackargs__ = ('upload_field', 'max_file_size')

    def validate_python(self, value_dict, state):
        log.info('test')
        if value_dict.get(self.upload_field) is None:
            return value_dict
        fileobj = getattr(value_dict.get(self.upload_field), 'file', None)
        fileobj.seek(0, os.SEEK_END)
        if int(fileobj.tell()) > int(self.max_file_size):
            raise formencode.Invalid(
                _('File too big'),
                value_dict, state,
                error_dict={self.upload_field:
                    formencode.Invalid(_('File too big'), value_dict, state)})
        return value_dict

class CreateNewCaseForm(formencode.Schema):
    ...
    chained_validators = [
        CheckFileSize('file', max_upload_size),
    ]

rawDescription: Is there a way to validate file size using python formencode?


code:
from SimPy.Simulation import *
from random import Random, expovariate, uniform

class ATM(Process):
    def Run(self):
        while 1:
            if self.atm_line.customers is 0:
                yield waitevent, self, self.atm_line.new_customer
            yield hold, self, random.expovariate(.05)
            self.atm_line.customers -= 1

class ATM_Line(Process):
    def __init__(self):
        self.customers = 0
        self.new_customer = SimEvent()
        Process.__init__(self)

    def Run(self):
        while 1:
            yield hold, self, random.expovariate(.07)
            self.new_customer.signal()
            self.customers += 1

initialize()
a = ATM()
a.atm_line = ATM_Line()
activate(a, a.Run())
activate(a.atm_line, a.atm_line.Run())
simulate(until=50)

rawDescription: Yield hold until other line > 0

description: Yield hold until other line > 0


code: start.add_argument('-s', '--start', action=StartAction, nargs=0)

rawDescription: Argparse - Custom Action With No Argument?


code:
class Event(object):
    def __init__(self, method_name, *args):
        self.method_name = method_name
        # Store args unconditionally.
        self.args = args

    def __call__(self, obj):
        # Now you can always use *self.args without checking its type.
        getattr(obj, self.method_name)(*self.args)

class A(object):
    def method(self, args):
        print(args)

a = A()
Event('method', [1, 2, 3])(a)

rawDescription: How to return the arguments in constructor as they were entered

description: Return the arguments in constructor as they were entered


code: f = ContactForm(initial={'subject': 'Hi there!'})

rawDescription: Django: How to pre-populate a form when using non-model data?


code:
import collections
import string

def me():
    info = input("what file would you like to select? ")
    filehandle = open(info, "r")
    data = filehandle.read().upper()
    char_counter = collections.Counter(data)
    for char, count in char_counter.most_common():
        if char in string.ascii_uppercase:
            print(char, count)

me()

rawDescription: Sorting and Organization of letter frequency - python


code:
def join_with_timeout(self, timeout):
    self.all_tasks_done.acquire()
    try:
        endtime = time() + timeout
        while self.unfinished_tasks:
            remaining = endtime - time()
            if remaining <= 0.0:
                raise NotFinished
            self.all_tasks_done.wait(remaining)
    finally:
        self.all_tasks_done.release()

rawDescription: Add timeout argument to python's Queue.join()


code:
def monitor_results(func):
    def print(*args):
        customprinter.print(*args)
    def wrapper(*func_args, **func_kwargs):
        print('function call ' + func.__name__ + '()')
        retval = func(*func_args,**func_kwargs)
        print('function ' + func.__name__ + '() returns ' + repr(retval))
        return retval
    wrapper.__name__ = func.__name__
    return wrapper

rawDescription: python decorator to print return values

description: Python decorator to print return values


code:
import os
import base64
s = str(os.urandom(10000))
encs=base64.b64encode(s)
s2 = base64.b64decode(encs)
cmp(s,s2)

rawDescription: How do I save this variable to a new text file?

description: Save this variable to a new text file


code:
pcap_process = subprocess.Popen(['tcpdump', '-s', '0', '-w', '-', 'tcp'],
                                  stdout=subprocess.PIPE, stderr=subprocess.PIPE)

rawDescription: Getting stdout from a tcpdump subprocess after terminating it


code:
if values is None:
    self.values = {}
else:
    self.values = values

rawDescription: Python: Dictionary as instance variable

description: Python: Dictionary as instance variable


code:
import webbrowser

# firstly you need to make write to an html file that will have the top 20 lines
# you can do that using

top_lines_file = open("shows.html", "w")
i = 1
while i in range(1,21):
    top_lines_file.write("write something to the file")
    i += 1
    # this will iterate over the file and write to it 20 times
top_lines_file.close() # close the file

# now you need to pass the path of the html file to the webbrowser object
webbrowser.open("file://" + path/to/the/html/file)
# this will open the webbrowser with your html file

rawDescription: read contents of a file and display it on browser

description: Read contents of a file and display it on browser


rawDescription: Switching characters in a list for different numbers in a list


code:
for index, error in enumerate(errors_list):
    print(index + ".", error, end=", ")

rawDescription: Python:embedded for loops: numbering list output


code:
def collision(x1, y1, x2, y2):
    return x1 == x2 or y1 == y2 or abs(x1-x2) == abs(y1-y2)

rawDescription: Checking 2-dimensional array (like eight queens puzzle)