code:
import sys, pymouse
from PyQt4.QtGui import *
from PyQt4.QtCore import *

class printImage(QWidget):
    def __init__(self, *args):
        apply(QWidget.__init__,(self, ) + args)
        QWidget.__init__(self)

        self.winId = QApplication.desktop().winId()
        self.mouse = pymouse.PyMouse()
        self.timer = QTimer()

        self.x = self.y = self.cX = self.cY = 0

        self.createLabel()
        self.show()
        self.startListening()

    def createLabel(self):
        self.label = QLabel(self)
        self.label.move(10, 15)
        self.label.resize(150, 130)

    def startListening(self):
        self.timer.connect(self.timer, SIGNAL('timeout()'), self.sendData)
        self.timer.start(0)

    def sendData(self):
        pos = self.mouse.position()
        x = pos[0]
        y = pos[1]

        if (self.cX != x) and (self.cY != y):
            self.x = self.cX = x
            self.y = self.cY = y

            self.label.setPixmap(
                self.cropScreenArea()
            )

    def cropScreenArea(self):
        return QPixmap.grabWindow(
            self.winId,
            x = self.x - 80,
            y = self.y - 60,
            width = 150,
            height = 130
        )

    def keyPressEvent(self, e):
        if e.key() == Qt.Key_Escape:
            self.close()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    view = printImage()

    sys.exit(app.exec_())

rawDescription: How to detect (view) an area of the screen surrounding a mouse pointer

description: Detect (view) an area of the screen surrounding a mouse pointer


rawDescription: Python Remove the repeat element

description: Python Remove the repeat element


code:
var = input("Enter the path for the Excel file you want to use: ")
import pandas as pd
xl = pd.ExcelFile(var)
df = xl.parse(sheetname=0)
df.head()

rawDescription: Dynamically Parsing a worksheet in Pandas using Python 3


code:
def dostuff():
    stuff

def dootherstuff():
    otherstuff

def doevenmorestuff():
    evenmorestuff

actions = ((regex1, dostuff), (regex2, dootherstuff), (regex3, doevenmorestuff))

for regex, action in actions:
    m = re.match(regex, line)
    if m:
        action()
        break

rawDescription: Python regex matching in conditionals

description: Python regex matching in conditionals


code:
import numpy as np
my_list = [[1,2,3],[4,5,6],[7,8,9]]
x = np.array(my_list)
np.transpose(x).tolist()

rawDescription: python column split

description: Python column split


code:
from Tkinter import *

class MessageItem(Frame):
    """A message to be contained inside a scrollableContainer"""

    def __init__(self, master, message, **kwds):
        Frame.__init__(self, master, **kwds)
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.text = Label(self, text=message, anchor='w', bg='gold')
        self.text.grid(row=0, column=0, sticky='nsew')

class scrollableContainer(Frame):
    """A scrollable container that can contain a number of messages"""

    def __init__(self, master, **kwargs):
        Frame.__init__(self, master, **kwargs) #holds canvas & scrollbars
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        self.canv = Canvas(self, bd=0, highlightthickness=0)
        self.hScroll = Scrollbar(self, orient='horizontal',
                                 command=self.canv.xview)
        self.hScroll.grid(row=1, column=0, sticky='we')
        self.vScroll = Scrollbar(self, orient='vertical',
                                 command=self.canv.yview)
        self.vScroll.grid(row=0, column=1, sticky='ns')
        self.canv.grid(row=0, column=0, sticky='nsew')
        self.canv.configure(xscrollcommand=self.hScroll.set,
                            yscrollcommand=self.vScroll.set)

        self.frm = Frame(self.canv, bd=2, bg='green') #holds messages
        self.frm.grid_columnconfigure(0, weight=1)

        self.canv.create_window(0, 0, window=self.frm, anchor='nw', tags='inner')

        self.messages = []
        for i in range(20):
            m = MessageItem(self.frm, 'Something Profound', bd=2, bg='black')
            m.grid(row=i, column=0, sticky='nsew', padx=2, pady=2)
            self.messages.append(m)

        self.update_layout()
        self.canv.bind('<Configure>', self.on_configure)

    def update_layout(self):
        self.frm.update_idletasks()
        self.canv.configure(scrollregion=self.canv.bbox('all'))
        self.canv.yview('moveto','1.0')
        self.size = self.frm.grid_size()

    def on_configure(self, event):
        w,h = event.width, event.height
        natural = self.frm.winfo_reqwidth()
        self.canv.itemconfigure('inner', width= w if w>natural else natural)
        self.canv.configure(scrollregion=self.canv.bbox('all'))

    def add_message(self, message):
        m = MessageItem(self.frm, message, bd=2, bg='red')
        m.grid(row=self.size[1], column=0, padx=2, pady=2, sticky='we')
        self.messages.append(m)
        self.update_layout()

root = Tk()
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
sc = scrollableContainer(root, bd=2, bg='black')
sc.grid(row=0, column=0, sticky='nsew')

def new_message():
    test = 'Something Profane'
    sc.add_message(test)

b = Button(root, text='New Message', command=new_message)
b.grid(row=1, column=0, sticky='we')

root.mainloop()

rawDescription: Dynamically changing scrollregion of a canvas in Tkinter


code:
def max_margin(int_list):
    if len(int_list)==0:
        return None,None
    if len(int_list)==1:
        return int_list[0],None
    max_val = max(int_list)
    int_list2 = list(int_list)
    int_list2.remove(max_val)
    max_val2 = max(int_list2)
    return max_val,max_val-max_val2

rawDescription: Max Margin of List python

description: Max Margin of List python


code:
import operator
sorted(
    reduce(operator.add,
    [[(k, k1, sampleDict[k][k1]['size']) for k1 in v.keys()]
             for k,v in sampleDict.items()]
    ),
    key=lambda x: x[2], reverse=True)

rawDescription: Sorting nested defaultdicts in Python

description: Sorting nested defaultdicts in Python


code:
import re
input = ser.read()
m = re.search(r'(?P<num>\d+\.\d+)', input)
if m:
    num = float(m.group('num'))

rawDescription: Reading bytes from ser.read()

description: Reading bytes from ser.read()


code:
with open('dictionary.txt') as infile:
    dictionary = {line.strip().lower() for line in infile}

print("----Linear search-----")
with open('AliceInWonderLand200.txt') as infile:
    for i,line in enumerate(infile, 1):
        line = line.strip()
        words = split_line(line) # your split_line function
        for word in words:
            if word.lower() not in dictionary:
                print("Line ", i, ": probably misspelled: ", word)

rawDescription: My spelling checker cannot compare words correctly


code: list(range(0,1)) == list(range(0,1))

rawDescription: How to test equivalence of ranges

description: Test equivalence of ranges


code:
def construct_path(file_list, directory):
    file_path_list = []
    for dir, subdir, files in os.walk(directory):
        for name in files:
            if name in file_list:
                file_path_list.append(os.path.join(dir, name))
                file_list.remove(name)
            if (len(file_list)==0): return file_path_list
    return file_path_list

rawDescription: Fastest way to search for a list of files in directory


code: re.findall('abc(de)fg(123)', 'abcdefg123 and again abcdefg123')

rawDescription: Capturing group with findall?

description: Capturing group with findall


code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
from PyQt4 import QtCore, QtGui

class MyWindow(QtGui.QWidget):
    _buttons = []

    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.pushButtonRemove = QtGui.QPushButton(self)
        self.pushButtonRemove.setText("Remove A Button!")
        self.pushButtonRemove.clicked.connect(self.on_pushButtonRemove_clicked)

        self.widgetButtons = QtGui.QWidget(self)

        self.layoutButtons = QtGui.QHBoxLayout(self.widgetButtons)

        self.layout = QtGui.QVBoxLayout(self)
        self.layout.addWidget(self.pushButtonRemove)
        self.layout.addWidget(self.widgetButtons)

        for buttonNumber in range(3):
            pushButton = QtGui.QPushButton()
            pushButton.setText("Button {0}".format(buttonNumber))

            self._buttons.append(pushButton)
            self.layoutButtons.addWidget(pushButton)

    @QtCore.pyqtSlot()
    def on_pushButtonRemove_clicked(self):
        if self._buttons:
            pushButton = self._buttons[-1]

            self._buttons.pop()
            self.layoutButtons.removeWidget(pushButton)

            pushButton.deleteLater()

            self.widgetButtons.adjustSize()
            self.adjustSize()

if __name__ == "__main__":
    import sys

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

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())

rawDescription: Resize a QVBoxLayout

description: Resize a QVBoxLayout


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

data = np.random.rand(5, 4)
heatmap = plt.pcolor(data)

for y in range(data.shape[0]):
    for x in range(data.shape[1]):
        plt.text(x + 0.5, y + 0.5, '%.4f' % data[y, x],
                 horizontalalignment='center',
                 verticalalignment='center',
                 )

plt.colorbar(heatmap)

plt.show()

rawDescription: how to annotate heatmap with text in matplotlib?

description: Annotate heatmap with text in matplotlib


code:
temp = X.SOME_IDENTIFIER.value_counts()
temp2 = temp.head(10)
if len(temp) > 10:
    temp2['remaining {0} items'.format(len(temp) - 10)] = sum(temp[10:])
temp2.plot(kind='pie')

rawDescription: Plot top 10 verse all other values

description: Plot top 10 verse all other values


code:
from Crypto.PublicKey import RSA

key = RSA.importKey(open("privatekey.pem").read())
der = key.publickey().exportKey("DER")

rawDescription: Printing .pem key DER form in python

description: Printing .pem key DER form in python


code:
class Base64PickleAdapter:
  def __init__(self, base64_input):
    ...

  def read(size=-1):
    ...

  def readline():
    ... # Can be implemented in terms of read.

rawDescription: Reading and writing pickles to an encoded stream


code:
lista=[1,2,3]
listb=['a','b','c']
["%s|%s" % (a,b) for a,b in zip(lista, listb)]

rawDescription: merge two lists and join them accordingly with a seperator in python

description: Merge two lists and join them accordingly with a seperator in python


code:
from collections import Counter
l = [1,1,2,2,2,3,3,3,3]
c = Counter(l)
c.keys()
c.values()

rawDescription: count unique values within nested list in python

description: Count unique values within nested list in python


code:
from setuptools.command import easy_install
easy_install.main( ["pythonModule"] )

rawDescription: How can I install Python modules programmatically / through a Python script?

description: Install Python modules programmatically / through a Python script


code:
def CombineJson(JSON_List):
      #Jsonlist should be a list of tuples, with the dictionary key and the json file to go with that.
      #eg: [('json1', 'some json string'), ('json2', 'some other json string')]
      Python_Dict = {}
      for tup in JSON_List:
            parsed_json = json.loads(tup[1])
            Python_Dict[tup[0]] = parsed_json
      BigJson = json.dumps(Python_Dict)
      return BigJson

rawDescription: How to convert Google Charts Data Table into python dictionary?

description: Convert Google Charts Data Table into python dictionary


code:
import urllib2

url = "http://www.cmegroup.com/CmeWS/mvc/ProductSlate/V1/List/500/1?sortField=oi&sortAsc=false&venues=3&page=1&cleared=1&group=1&r=eSxQS2SI"
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }

req = urllib2.Request(url, headers=headers)

response = urllib2.urlopen(req)

your_json = response.read()
response.close()

rawDescription: Python access server urlopen()

description: Python access server urlopen()


code:
from Tkinter import *
root = Tk()
canvas = Canvas(root)
canvas.pack()
rect = canvas.create_rectangle(10,10,70,70, outline="blue", fill="red")
def switch():
    # Use the itemconfig method of a Canvas to alter specific items
    canvas.itemconfig(rect, outline="green", fill="blue")
Button(root, text="switch", command=switch).pack()
root.mainloop()

rawDescription: Alter tkinter canvas objects after drawing


code:
import wx
import wx.lib.mixins.listctrl as listmix

class TestListCtrl(wx.ListCtrl, listmix.CheckListCtrlMixin, listmix.ListCtrlAutoWidthMixin):
    def __init__(self, *args, **kwargs):
        wx.ListCtrl.__init__(self, *args, **kwargs)
        listmix.CheckListCtrlMixin.__init__(self)
        listmix.ListCtrlAutoWidthMixin.__init__(self)
        self.setResizeColumn(3)

    def OnCheckItem(self, index, flag):
        print(index, flag)

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)
        self.panel = wx.Panel(self)
        self.list = TestListCtrl(self.panel, style=wx.LC_REPORT)
        self.list.InsertColumn(0, "No.")
        self.list.InsertColumn(1, "Progress")
        self.list.InsertColumn(2, "Description")
        self.list.Arrange()
        for i in range(1, 6):
            self.list.Append([str(i), "", "It's the %d item" % (i)])
        self.button = wx.Button(self.panel, label="Test")
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.list, proportion=1, flag=wx.EXPAND | wx.ALL, border=5)
        self.sizer.Add(self.button, flag=wx.EXPAND | wx.ALL, border=5)
        self.panel.SetSizerAndFit(self.sizer)
        self.Show()

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

rawDescription: Use arbitrary wx objects as a column in a wx.ListCtrl


code:
out = np.empty((4, 4))
for colnb, col in d.items():
    out[:, colnb-1] = col
with open("Result.tsv", 'wb') as f:
    np.savetxt(f, out, delimiter=',')

rawDescription: How to write a dictionary with numpy array in a file

description: Write a dictionary with numpy array in a file


code:
import numpy as np
import wavio
rate = 22050             # samples per second
T = 3                    # sample duration (seconds)
f = 440.0                # sound frequency (Hz)
t = np.linspace(0, T, T*rate, endpoint=False)
sig = np.sin(2 * np.pi * f * t)
wavio.write("sine24.wav", sig, rate, sampwidth)

rawDescription: How do I write a 24-bit WAV file in Python?

description: Write a 24-bit WAV file in Python


code:
from sympy import *
sin(pi)
pi

rawDescription: Exact Sine/Cosine/Tangent of Various Angles


code:
grouped = df.sort(columns='date').groupby('home')
grouped['score_h'].apply(pd.expanding_mean)

rawDescription: Applying cumulative mean function to a grouped object


code:
class Link(object):
    def __init__(self, value=0.0):
        self.next = None
        self.value = value

class LinkedRing(object):
    def __init__(self, length):
        self.sum = 0.0
        self.length = length
        self.current = Link()

        # Initialize all the nodes:
        last = self.current
        for i in xrange(length-1):  # one link is already created
            last.next = Link()
            last = last.next
        last.next = self.current  # close the ring

    def add_val(self, val):
        self.sum -= current.value
        self.sum += val
        self.current.value = val
        self.current = self.current.next

    def average(self):
        return self.sum / self.length

# Test example:
rolling_sum = LinkedRing(5)
while True:
    x = float(raw_input())
    rolling_sum.add_val(x)
    print(">> Average: %f" % rolling_sum.average())

rawDescription: How can I create a running average of the last N items in a time series?

description: Create a running average of the last N items in a time series


code:
def test_folders(self):
    tfolders = glob.iglob(os.environ['testdir'] + '/test_*')

    failures = []
    for testpath in tfolders:
        testname = os.path.basename(testpath)
        if not self.runTest(testname):
            failures.append[testname]

    self.assertEqual([], failures)

rawDescription: Python unittest: Run multiple assertions in a loop without failing at first one, but continue


code: [o for o,n in zip(old[0], new[0]) if float(o) > float(n)]

rawDescription: Comparing values from different tuples, list comprehension


code:
class ApikeyView(sqla.ModelView):

    form_excluded_columns = ('user_id')

    def on_model_change(self, form, model, is_created):

        if is_created:
            model.user_id = current_user.id

rawDescription: Flask-Admin / Flask-SQLAlchemy: set user_id = current_user for INSERT


code:
import pydoc
pydoc.apropos('Zip')
# output: zipimport - zipimport provides support for importing Python modules from Zip archives.

rawDescription: Python docstring search - similar to MATLAB `lookup` or Linux `apropos`


code:
import imp
modl = imp.load_source('modulename', '/path/to/module.py')

rawDescription: import a file from different directory

description: Import a file from different directory


code:
from datetime import date, timedelta
from models import Item

groups = []
for i in range(0, 10):
    items = Item.objects.filter(date_created=date.today() - timedelta(i))
    groups.append(items.order_by('-points'))

rawDescription: Get the 'top' records within every set of records created within 4 days


rawDescription: Groupby by a column and unique in another column


code:
def method1():
    return 'hello world'

def method2(methodToRun):
    result = methodToRun()
    return result

method2(method1)

rawDescription: How do I pass a method as a parameter in python

description: Pass a method as a parameter in python


code:
def get_ctx():
    thread_data = threading.local()
    if not hasattr(thread_data, "ctx"):
         thread_data.ctx = Ctx()
    return thread_data.ctx

rawDescription: How are global objects handled in threading?


code:
def convert(x, base):
  res = []
  while x:
    res.append(x%base)
    x //= base # this line depends on Python's version!
  res.reverse()
  return res

rawDescription: Python: breaking down integers into exponents?


code:
import math
import operator

def dirichlet_pdf(x, alpha):
  return (math.gamma(sum(alpha)) /
          reduce(operator.mul, [math.gamma(a) for a in alpha]) *
          reduce(operator.mul, [x[i]**(alpha[i]-1.0) for i in range(len(alpha))]))

rawDescription: Calculating pdf of Dirichlet distribution in python


code:
import cherrypy

class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True

cherrypy.quickstart(HelloWorld())

rawDescription: Simple webserver or web testing framework


code:
from itertools import islice

def window(seq, n=2):
    """
    Returns a sliding window (of width n) over data from the iterable
    s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...
    """
    it = iter(seq)
    result = list(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + [elem]
        yield result

def contains_sequence(all_values, seq):
    return any(seq == current_seq for current_seq in window(all_values, len(seq)))

test_iterable = [1,2,3]
search_sequence = [1,2]

result = contains_sequence(test_iterable, search_sequence)

rawDescription: Is there a Python builtin for determining if an iterable contained a certain sequence?


code:
def f(*args, **kwargs):
    return lambda: a(*args, **kwargs)
f(10, 0)()

rawDescription: Intercepting return

description: Intercepting return


code:
set1 = set(list1)
set2 = set(list2)
total = sorted(set1|set2)

new_list1 = [x if x in set1 else "MISSING" for x in total]
new_list2 = [x if x in set2 else "MISSING" for x in total]

rawDescription: Align two lists by adding special values for missing entries


code:
def display():
    messagebox.showinfo(title="Message", message=e1.get())

rawDescription: Python tkinter entry() doesnt return any value to variable


code: coord = tuple(sum(x) for x in zip(coord, change))

rawDescription: Adding Values From Tuples of Same Length


code:
Deal.objects.filter(
  Q(deal_day_start__lte=current_day, deal_day_end__gte=current_day) |
  Q(deal_day_start__lte=current_day, deal_day_end__lt=F("deal_day_start")) |
  Q(deal_day_start__gte=current_day, deal_day_end__gte=current_day, deal_day_end__lt=F("deal_day_start"))
)

rawDescription: Comparing day ranges with Django

description: Comparing day ranges with Django


code:
def readslice(inputfilename,nx,ny,timeslice):
   f = open(inputfilename,'rb')
   f.seek(8*timeslice*nx*ny)
   field = np.fromfile(f,dtype='float64',count=nx*ny)
   field = np.reshape(field,(nx,ny))
   f.close()
   return field

rawDescription: Reading a direct access fortran unformatted file in Python


code:
inserter = table_object.insert().prefix_with("OR REPLACE")
inserter.execute([{'column1':'value1'}, {'column1':'value2'}])

rawDescription: SQLAlchemy INSERT IGNORE

description: SQLAlchemy INSERT IGNORE


rawDescription: Remove backslash instances from a file in Python


code:
from gi.repository import Gtk, Gdk

class ColorSample(Gtk.Application):
    def __init__(self):
        Gtk.Application.__init__(self, application_id="org.app.ColorSample")

        style_provider = Gtk.CssProvider()
        css = '''
        #MainWindow { background-color: #F00; }
        '''
        style_provider.load_from_data(css)

        Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(),
                                    style_provider,
                                    Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)

    def do_activate(self):
        main_window = Gtk.Window(Gtk.WindowType.TOPLEVEL)
        main_window.set_name('MainWindow')
        main_window.props.border_width = 4

        button = Gtk.Button("Doing Nothing")
        main_window.add(button)

        self.add_window(main_window)
        main_window.set_position(Gtk.WindowPosition.CENTER)
        main_window.show_all()

if __name__ == "__main__":
    colorsample = ColorSample()
    colorsample.run(None)

rawDescription: How to create border any widget in pygtk

description: Create border any widget in pygtk


code:
import numpy as np

...

# compute your 'params' over vectors of z-values
param1s = func1(z_all)
param2s = func2(x, z_all)
param3s = func3(x, z_all)  # you don't seem to be using this for anything...

# compute 'M_11, ... M_22'
M_11 = param1s + param2s
M_12 = param1s - param2s
M_21 = param1s * param2s
M_22 = param1s / param2s

# we construct a (2, 2, nz) array from these
M_all = np.array([[M_11, M_12], [M_21, M_22]])

# roll the 'nz' axis to the front so that its shape is (nz, 2, 2)
M_all = np.rollaxis(M_all, -1, 0)

# initialize output with the identity
M_out = np.eye(2)

# loop over each (2, 2) subarray in 'M_all', update the output with the
# corresponding dot product
for mm in M_all:
    M_out = M_out.dot(mm)

rawDescription: Optimizing numpy matrix operations (currently using a for loop)


code:
from matplotlib import pyplot
import math

def setLabelExample():
    fig = pyplot.figure()
    x = [i for i in range(200)]
    y = [xi**2 for xi in x]

    ax = fig.add_subplot(1,1,1)
    ax.plot(x, y)
    ax.tick_params(axis='x', labelsize=30)
    fig.suptitle('Matplotlib xticklabels Example')
    pyplot.show()

if __name__ == '__main__':
    setLabelExample()

rawDescription: How do I change the font size of the scale in matplotlib plots?

description: Change the font size of the scale in matplotlib plots


code:
buf = mmap.mmap(fd, mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_WRITE)
int_pointer = ctypes.c_int.from_buffer(buf)

rawDescription: How to get the address of mmap-ed memory in Python?

description: Get the address of mmap-ed memory in Python


code:
def _cdf(self, x, min, max):
    k = floor(x)
    return (k-min+1)*1.0/(max-min)
def _ppf(self, q, min, max):
    vals = ceil(q*(max-min)+min)-1
    vals1 = (vals-1).clip(min, max)
    temp = self._cdf(vals1, min, max)
    return where(temp >= q, vals1, vals)

rawDescription: ppf(0) of scipy's randint(0, 2) is -1.0

description: Ppf(0) of scipy's randint(0, 2) is -1.0


code:
# Ugly hack to allow absolute import from the root folder
# whatever its name is. Please forgive the heresy.
if __name__ == "__main__" and __package__ is None:
    from sys import path
    from os.path import dirname as dir

    path.append(dir(path[0]))
    __package__ = "examples"

import api

rawDescription: Sibling package imports

description: Sibling package imports


code:
import pandas as pd

df = pd.DataFrame()

#####

with open(file_name, 'r') as my_file:
    my_file.readlines()

rawDescription: What does the 'as' operator do?

description: What does the 'as' operator do


code: eventD = MyDict({'rrule_end':None})

rawDescription: Can I overload the {} operators for creating dictionaries?

description: Overload the {} operators for creating dictionaries


code:
text = '"A,B,C,Be,F,Sa,Su"'
'A' in text.strip('"').split(',')
'S' in text.strip('"').split(',')

rawDescription: Find specific string

description: Find specific string


code:
def largestPowerOfTwoThatIsAFactorOf(num):
    if num % 2 != 0: return 1
    factor = 0
    while num % 2 == 0:
        num /= 2
        factor += 1
    return 2 ** factor
    ## or return factor; as per your requirement

rawDescription: Finding the largest power of 2?

description: Finding the largest power of 2


code:
for a, b in itertools.product(list1, list2):
  foo(a, b)

rawDescription: Python multi-lists iteration

description: Python multi-lists iteration


code:
class a_traffic(anyIF_traffic):
    def __init__(self, *args, **kwargs):
        if len(args) == 5:
            args[4] = '6161'
        else:
            kwargs['port'] = '6161'
        super(a_traffic, self).__init__(*args, **kwargs)

rawDescription: Understanding inheritance and passing child variable to the parent class


code:
week1 = xrange(1, 101) #for column1
week2 = xrange(1, 101) #for column2

cur.executemany("INSERT INTO stud (classID, othercolumn) VALUES(%s, %s)", zip(week1, week2))
db.commit()

rawDescription: Inserting data into multiple columns in MySQL table from python


code:
import pickle

model = pickle.load(path)

def predict(val):
    return model.predict(val)

rawDescription: How to load a scikit-learn machine learning module in memory?

description: Load a scikit-learn machine learning module in memory


rawDescription: Increase performance of script (current method of using np.putmask)


code:
import numpy as np
np.random.uniform(-10,10)
np.random.uniform(-10,10,size=(2,3))
np.random.uniform(-10,10,size=(1,5,1))

rawDescription: How to generate n dimensional random variables in a specific range in python

description: Generate n dimensional random variables in a specific range in python


code:
mypath = "foo"
myfile = "bar.ext"
os.path.join( mypath, myfile)
os.path.join( "many", "path", "components", "beforethefile.ext" )

rawDescription: python different slashes based upon operating system

description: Python different slashes based upon operating system


code: from itertools import cycle as endless_s

rawDescription: How can I restart a string iterator endlessly?

description: Restart a string iterator endlessly


code:
from BeautifulSoup import BeautifulSoup
doc = "
Heading

Text"
soup = BeautifulSoup(doc)

str(soup)

rawDescription: Using md5 on BeautifulSoup result

description: Using md5 on BeautifulSoup result


code:
def transform(functions, arguments):
  return [f(a) for f, a in zip(functions, arguments)]

rawDescription: Transform items from iterable with a sequence of unary functions


rawDescription: Make code with differentiation by cases work for arrays and numbers


rawDescription: Select Distinct Years and Months for Django Archive Page


code:
def makeOpener(pdf, page):
    '''makes a pyw file to use to hyperlink in excel'''
    t = 'c:/temp'
    if not os.path.isdir(t):
        os.makedirs(t)
    tempfile.tempdir = t
    py = tempfile.NamedTemporaryFile(suffix='.pyw', delete=False)

    lst = ['import subprocess, win32api',
           'pdf = r"' + pdf + '"',
           'page = "' + str(int(page)) + '"',
           '_, exe = win32api.FindExecutable(pdf)',
           'opts = "page=" + page',
           'clst = [exe, "/A", opts, "/N", pdf]',
           'DP = 0x00000008',
           'subprocess.Popen(clst, shell=False, creationflags=DP)'
           ]
    py.write('\n'.join(lst))
    py.close()
    return py.name

rawDescription: Script to generate other scripts

description: Script to generate other scripts


code:
class Base(models.Model):
    _name = models.CharField(max_length=200)
    user = models.ForeignKey(User, related_name="some_set")
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    strategy = GenericForeignKey()

    #used as a property
    def value():
        def fget(self):
            return self.strategy.value

class Strategy1(models.Model):
    #some other definitions
    def value():
        def fget(self):
            return some_var

class Strategy2(models.Model):
    #some other definitions
    def value():
        def fget(self):
            return some_other_var

rawDescription: Any way to use a Django Model as an Interface?


code:
from itertools import izip_longest
groups_of_six = izip_longest(*[iter(my_list_of_tuples)]*6)
for a_group in groups_of_six:
    do_some_processing_on(a_group)

rawDescription: How to iterate through every six tuples in a list in python

description: Iterate through every six tuples in a list in python


code:
result = [[]]
for l in lists:
    tmp = []
    for x in result:
        for y in l:
            tmp.append(x+[y])
    result = tmp

rawDescription: how can I turn this list comprehension into for loops

description: Turn this list comprehension into for loops


code:
def reformat(artist,beg):
  if artist.startswith(beg):
    artist = artist[len(beg):] + ', ' + beg.strip()
  return artist
reformat('The Beatles','The ')
reformat('An Officer and a Gentleman','An ')

rawDescription: string.replace('the','') is leaving white space

description: String.replace('the','') is leaving white space


rawDescription: How to print a list in the format of a set. In Python3

description: Print a list in the format of a set. In Python3


code: cur.execute("INSERT INTO name (first, middle, last) VALUES (%s, %s, %s)", (f, m, l))

rawDescription: Correct python code to insert NULL value into MySQL


code: cmd=Popen(['identify', '-format', '%b:%w:%h:%r:%#', 'myimage.jpg'])

rawDescription: Python create a Popen shell command list


code:
attr_getter = operator.attrgetter('name')
names = map(attr_getter, l)
if most_common(names) in set(map(attr_getter, [a1, a2])):
    pass # do smth here

rawDescription: Having itemgetter and attrgetter at the same time


rawDescription: How to pull a random record using Django's ORM?

description: Pull a random record using Django's ORM


code:
def commit(originalcommit, ui, repo, **opts):
    return originalcommit(ui, repo, **opts)

def uisetup(ui):
    entry = extensions.wrapcommand(commands.table, "commit", commit)
    entry[1].append(('', 'newcommitoption', None, ('Description for the new commit option')))

rawDescription: How do I add a command option to an existing command in a Mercurial extension?

description: Add a command option to an existing command in a Mercurial extension


code:
for _ in (number+1 for number in range(5)):
    print(_)

rawDescription: Pythonic way to iterate through a range starting at 1


code:
Builder.load_string('''
<CustomPopup>:
    BoxLayout:
        orientation: 'vertical'
        # some settings stuff here
        BoxLayout:
            orientation: 'horizontal'
            Button:
                text: 'New Game'
                on_press: root.do_new_game()
''')

class CustomPopup(Popup):
    settings_widget = ObjectProperty()
    new_game = ObjectProperty()

    def do_new_game(self):
        self.settings_widget.some_property = some_value
        self.dismiss()
        self.new_game()

p = CustomPopup(settings_widget=my_widget, new_game=mygame.newGame)
p.open()

rawDescription: Kivy: accessing a method on a different class


code:
import numpy as np
import pylab as p
xv=np.ones(4)*.5
yv=np.arange(0,4,1)
xv1=np.ones(4)*-.5
yv1=np.arange(0,4,1)

#red vertical line on the right
yv2=np.arange(0,1.5,0.1)
xv2=np.ones_like(yv2)*.7

#red vertical line on the left
yv3=np.arange(0,2,0.01)
xv3=np.ones_like(yv3)*-0.7

###
xc=np.arange(-1.4,2,0.05)
yc=np.ones_like(xc)*1

fig = p.figure()
ax1 = fig.add_subplot(111)
#adjustprops = dict(left=0.12, bottom=0.2, right=0.965, top=0.96, wspace=0.13, hspace=0.37)
#fig.subplots_adjust(**adjustprops)
ax1.plot(xv,yv, color='blue', lw=1, linestyle='dashed')
ax1.plot(xv1,yv1, 'green', linestyle='dashed')
ax1.plot(np.r_[-1:1:0.2],np.r_[-1:1:0.2],'red')
ax1.plot(xc,yc, 'k.', markersize=3)

p.savefig('colored_image.png')

import matplotlib.image as mpimg
import matplotlib.cm as cm
import Image

figprops = dict(figsize=(10,10), dpi=100)
fig1 = p.figure(**figprops)
#fig1 = p.figure()
#ax1 = fig.add_subplot(111)
adjustprops = dict()
image=Image.open('colored_image.png').convert("L")
arr=np.asarray(image)
p.figimage(arr,cmap=cm.Greys_r)
p.savefig('grayed.png')
p.savefig('grayed.pdf',papertype='a4',orientation='portrait')

rawDescription: Save matplotlib plot in grayscale

description: Save matplotlib plot in grayscale


rawDescription: Group values based on range of number in python


code:
try:
    from images.serializers import SimplifiedImageSerializer
except ImportError:
    import sys
    SimplifiedImageSerializer = sys.modules[__package__ + '.SimplifiedImageSerializer']

rawDescription: Circular dependency in Django Rest Framework serializers


code:
import wx

class myframe(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, title='Test', size=(200,200))

        self.aPanel = wx.Panel(self, style = wx.RAISED_BORDER )
        self.aLabel = wx.StaticText( self.aPanel, -1, 'Bar' )
        self.aBox = wx.StaticBox(self.aPanel, -1, 'Foo')

        self.aSizer = wx.BoxSizer( wx.HORIZONTAL )
        self.aSizer.Add( self.aLabel, 0, wx.ALIGN_CENTER | wx.ALL )

        self.aBoxSizer = wx.StaticBoxSizer( self.aBox, wx.VERTICAL )
        self.aBoxSizer.Add( self.aSizer, 0, wx.ALIGN_LEFT | wx.ALL )

        vbox = wx.BoxSizer(wx.VERTICAL)
        vbox.Add(self.aBoxSizer, 1, wx.EXPAND | wx.ALL, 20)
        self.aPanel.SetSizer( vbox )

        self.Show()

if __name__ == '__main__':

    app = wx.PySimpleApp(0)
    frame = myframe()
    app.MainLoop()

rawDescription: How can I add a border/padding around a wx.StaticBox?

description: Add a border/padding around a wx.StaticBox


code:
from functools import partial
from multiprocessing import Manager, Pool

def select_star(table, counts, type_):  # counts and type_ will always be the counts dict and "prod", respectively
   pass

def main():
    mgr = Manager()
    counts = mgr.dict()

    p = Pool()
    func = partial(select_star, counts, "prod")  # Using a partial lets us pass extra parameters to select_start
    p.map(func, get_table_list())  # No need to use a manager for the list, since you're not passing the whole thing to the children.

if __name__ == "__main__":
    main()

rawDescription: How does Python multiprocessing.Process() know how many concurrent processes to open?


rawDescription: How SIGINT gets passed to grandchild (and how to do this programmatically)


code:
new_df = df.transpose()
new_df['Group'] = new_df.index / 4
new_df = new_df.groupby('Group').sum().transpose()

rawDescription: Combining multiple columns in a DataFrame


rawDescription: Python write web scrapper to get pdf files without several logins


code:
from collections import defaultdict

example_list = [[1,2,4], [1,2,3], [3,4,3], [1,3,2], [5,7,1], [3,4,3], [5,6,1]]

d = defaultdict(list)

for item in example_list:
    d[tuple(item)].append(item)

groupedlist = sorted(d[x] for x in d)

rawDescription: Finding and grouping same values, (float vectors) in nested lists


code:
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator # added

def create31fig(size,xlabel,ylabel,title=None):
    fig = plt.figure(figsize=(size,size))
    ax1 = fig.add_subplot(311)
    ax2 = fig.add_subplot(312)
    ax3 = fig.add_subplot(313)
    plt.subplots_adjust(hspace=0.001)
    plt.subplots_adjust(wspace=0.001)
    ax1.set_xticklabels([])
    ax2.set_xticklabels([])
    xticklabels = ax1.get_xticklabels() + ax2.get_xticklabels()
    plt.setp(xticklabels, visible=False)
    ax1.set_title(title)
    nbins = len(ax1.get_xticklabels()) # added
    ax2.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='upper')) # added
    ax2.set_ylabel(ylabel)
    ax3.yaxis.set_major_locator(MaxNLocator(nbins=nbins,prune='upper')) # added
    ax3.set_xlabel(xlabel)
    return ax1,ax2,ax3

create31fig(5,'xlabel','ylabel',title='test')

rawDescription: remove overlapping tick marks on subplot in matplotlib

description: Remove overlapping tick marks on subplot in matplotlib


code:
import glob
glob.glob('./[0-9].*')
glob.glob('*.gif')
glob.glob('?.gif')

rawDescription: Casting regex arguments into a list

description: Casting regex arguments into a list


code:
userName1 = input('What is your name?')
scores = input('User scores, comma seperated')
print("user %s has max score %d"%(userName1, max(map(scores.split(','),int))))

rawDescription: How to find the maximum number in a list with numbers and strings in Python?

description: Find the maximum number in a list with numbers and strings in Python


code: getattr(np, 'max')(values, axis=0)

rawDescription: Apply numpy function based on string

description: Apply numpy function based on string


rawDescription: Why do two algorithms for finding primes differ in speed so much even though they seem to do the same number of iterations?


code:
class ValidInputTest4(unittest.TestCase):
    def setUp(self):
        self.app = wx.App()
        self.frame = FoodCalories(None)

    def tearDown(self):
        self.frame.Destroy()

rawDescription: How do you programmatically close a wxPython frame?

description: Programmatically close a wxPython frame


code:
class Person:

    def __init__(self, person_name, health, ranged_weapon):
        self.person_name = person_name
        self.health = health
        self.weapon = ranged_weapon

    def display_person_info(self):
        print('Name: %s' %self.person_name)
        # display_weapon_name already calls print; but
        # you probably don't need this method at all.
        self.weapon.display_weapon_name()
        # Instead, do this (actually, you already do this
        # in ranged_attack())
        # print('Weapon: %s' % self.weapon.weapon_name)

    def ranged_attack(self, ranged_weapon, target):
        target.health -= self.weapon.weapon_damage
        print("Weapon: %s" % self.weapon.weapon_name)
        print(target.person_name + "'s Health: "+str(target.health))

rawDescription: Passing a class to another class (Python)


rawDescription: How to prevent running the __main__ guard when using execfile?

description: Prevent running the __main__ guard when using execfile


code:
from random import randint
lst = [1, 2, 3, 4, 5]
index = randint(0, len(lst)-2)
pair = lst[index:index+2]  # return [4, 5] or [1, 2], etc..

rawDescription: Python - Take a list and return random elements in ordered pairs (must be mutable)


code:
from stat import S_ISDIR

def isdir(path):
  try:
    return S_ISDIR(sftp.stat(path).st_mode)
  except IOError:
    #Path does not exist, so by definition not a directory
    return False

rawDescription: Recursive directory download with Paramiko?


code:
def GetLineHeight(rtc):
    tallString = "\n".join([str(i) for i in xrange(200)])
    rtc.SetValue(tallString)
    rtc.SetInsertionPoint(0)
    rtc.PageDown()
    pos = rtc.GetInsertionPoint()
    end = tallString.find("\n",pos)
    lineHeight=int(tallString[pos:end])
    return lineHeight

rawDescription: Finding out how many lines can be displayed in wx.richtext.RichTextCtrl without scrolling


code:
qObj = None
for field in fields:
    newQ = Q(**{field :  Null})
    if qObj is None:
        qObj = newQ
    else:
        qObj = qObj | newQ

rawDescription: Django, build long queryset automatically


code:
# remove previous selection, if any
text_widget.tag_remove(Tkinter.SEL, "1.0", Tkinter.END)
# select all
text_widget.tag_add(Tkinter.SEL, "1.0", Tkinter.END)
# place cursor
text_widget.mark_set(Tkinter.INSERT, Tkinter.END)

rawDescription: How do I undo/redo something in a Tkinter text widget?

description: Undo/redo something in a Tkinter text widget


code:
df
df.loc[0]
type(df.loc[0])
df.loc[[0]]
type(df.loc[[0]])

rawDescription: Sometimes get a dataframe returned instead of a Series


code:
def someView(request):
  surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 100, 100)
  context = cairo.Context(surface)
  # Draw something ...

  response = HttpResponse(mimetype="image/png")
  surface.write_to_png(response)
  return response

rawDescription: Using Pycairo to generate images dynamically and serve in Django


code:
for l in _lst:
    l.append(7)

rawDescription: Append value to each sublist in a list

description: Append value to each sublist in a list


rawDescription: Where to define the about box in a OSx app


code:
def func(iFile):
    with open(iFile) as iF:
        with open("DOB.txt", "a") as oF1:
            with open("POSTCODE.txt", "a") as oF2:
                for line in iF:
                    chars = line.split(',')
                    oF1.write(chars[0] + ',' + chars[2])
                    oF1.write('\n')
                    if chars[2] == "2000":
                        oF2.write(chars[0] + ',' + chars[3])
                        oF2.write('\n')

rawDescription: Python - Writing from a file to two files


rawDescription: Python: Want to use a string as a slice specifier


code:
random.seed(123)
plot1
random.seed(123)
plot2

rawDescription: How to plot the same graph in iGraph two times with two different colorings

description: Plot the same graph in iGraph two times with two different colorings


code:
# Plot
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1, axisbg='white')

# Plot actual data
plt.plot_date(x=x1, y=y1, fmt='o-')

# Now append the extra data
x1.append(date_end)
x2 = mdates.date2num(x1)

plt.plot(x1,p(x2),'r--') #add trendline to plot

plt.title('Cash Bucks')
plt.ylabel('Cash Bucks')
plt.xlabel('Date')

fig.autofmt_xdate() # This tidies up the x axis
plt.show()

rawDescription: Add future dates to plot for trendline

description: Add future dates to plot for trendline


access_token: the-token-value

rawDescription: Where in database does python-social-auth store access token?


code:
toUse = df['col1'].str.contains(Val)
valsIwant = df['col2'][toUse]

rawDescription: python pandas - string matching

description: Python pandas - string matching


code:
for myid in ids_high:
    getgeom = FloodHazard.objects.get(id=myid).geom
    response_high = list(BuildingStructure.objects.filter(geom__intersects=getgeom).values(
        'brgy_locat','bldg_type','bldg_name').annotate(counthigh=Count('brgy_locat')))
    for entry in response_high:
         entry['type'] = 'high'
    to_json.append(response_high)

rawDescription: Append list with dict in Django

description: Append list with dict in Django


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

plt.ion()

conf_arr_hs = [[90, 74],
                [33, 131]]
norm_conf_hs = []
for i in conf_arr_hs:
    a = 0
    tmp_arr = []
    a = sum(i, 0)
    for j in i:
        tmp_arr.append(float(j)/float(a))
    norm_conf_hs.append(tmp_arr)

confmatmap=plt.cm.binary
fig = plt.figure()

plt.clf()
ax = fig.add_subplot(111)
res = ax.imshow(np.array(norm_conf_hs), cmap=confmatmap, interpolation='nearest')
res.set_clim(0,1) # set the limits for your color map

for x in xrange(2):
    for y in xrange(2):
        textcolor = 'black'
        if norm_conf_hs[x][y] > 0.5:
            textcolor = 'white'
        ax.annotate("%0.2f"%norm_conf_hs[x][y], xy=(y, x),  horizontalalignment='center', verticalalignment='center', color=textcolor)

rawDescription: matplotlib colormap: do not resize

description: Matplotlib colormap: do not resize


code:
class BasicActivity(object):
    pass

rawDescription: python method resolution order and diamond inheritance

description: Python method resolution order and diamond inheritance


code: test = [[] for e in range(len(foobar)/2)]

rawDescription: creating list of empty lists - Python

description: Creating list of empty lists - Python


code: r = requests.get('https://api.github.com/user', auth=('user', 'pass'))

rawDescription: Custom opener or Request headers

description: Custom opener or Request headers


code:
s = 'jxjrxxtzxz'

# Remove first occurrence of 'x'
ix = s.find('x')
if ix > -1:
   s = s[:ix]+s[ix+1:]

# Remove last occurrence of 'x'
ix = s.rfind('x')
if ix > -1:
   s = s[:ix]+s[ix+1:]

rawDescription: Delete specific characters from a string (Python)


code:
my_string = "%s is my name, and %s is my hair color"
my_string.count('%') - 2 * my_string.count('%%')

rawDescription: Number of Arguments for String Formatting


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

x = np.linspace(-20, 20, 1000)
y = ((3*x**2) + 12/(x**3) - 5)
mask = np.abs(y) > 100
y[mask] = np.nan
plt.plot(x, y)
plt.grid()
plt.show()

rawDescription: Problems while plotting on Matplotlib

description: Problems while plotting on Matplotlib


code:
for key, values in sequencelist.items():
    with open(key, 'w') as out:
        for value in values:
            out.write('\n'.join(value.split()))

rawDescription: Python - Manipulation of values before writing to output


code:
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy.optimize import bisect

data = '''0   0
0.1 0.1
0.2 0.2
0.3 0.3
0.4 0.31
0.5 0.32
0.6 0.35'''
data = [line.split() for line in data.split('\n')]
data = np.array(data, dtype = 'float')

strain = data[:,0]
stress = data[:,1]

E = 1
y = [0, 0.5]
x = 0.2, ((y[1] - y[0])/E+0.2)
#use interp1d to get interpolated points
y = interp1d(x, y)
stress = interp1d(strain, stress)
#set starting points
x1 = max(x[0], strain[0])
x2 = min(x[-1], strain[-1])
max_err = .01
#create function
f = lambda x : stress(x) - y(x)
#find x1 where f(x1) = 0
x1 = bisect(f, x1, x2, xtol = .001)
y1 = stress(x1)

plt.figure(num=None, figsize=(10, 6), dpi=100, facecolor='w', edgecolor='k')
plt.plot(strain, stress(strain))
plt.plot(x, y(x))
plt.scatter(x1, y1)
plt.show()

rawDescription: python plot intersection of line and data

description: Python plot intersection of line and data


code:
import operator
from functools import reduce    # Python 3
search_params = reduce(operator.or_, search_params, Q())

rawDescription: Python list to bitwise operations

description: Python list to bitwise operations


code:
class Calendar(Resource):
   def getChild(self, name, request):
       return YearPage(int(name))

rawDescription: Handling All Resources in a Twisted Web Server


code:
df.ix[df['subid']== '456', 'grade'] = df.grade.replace({'3rd':'4th'})
df

rawDescription: Python/ Pandas - Updating Data for a Group of Records


code:
# First, define the Manager subclass.
class ActiveManager(models.Manager):
    def get_query_set(self):
        return super(ActiveManager, self).get_query_set().filter(active=True)

# Then hook it into the Record model explicitly.
class Record(models.Model):
    active = BooleanField()

    objects = models.Manager() # The default manager.
    active_objects = ActiveManager() # The specific manager.

#to filter for all active records you can do:
Record.active_objects.all()

rawDescription: QuerySet automatic/aspect filtering

description: QuerySet automatic/aspect filtering


code:
data = list()
with open("data.txt", "r") as f:
    for line in f.readlines():
        if line != '\n':
            listLine = line.split(";")
            data.append("0;{}\n".format(listLine[0]))

with open('data.txt', 'w') as f:
    for line in data:
        f.write(line)

rawDescription: Python writing lines from list causes IndexError


code:
c = concatenate((a,b))
c.sort(kind='mergesort')

rawDescription: numpy merge sorted array to an new array?

description: Numpy merge sorted array to an new array


code:
index_joined = a.index
index_joined = index_joined.union(b.index)
a.reindex(index=index_joined, method='ffill')
b.reindex(index=index_joined, method='ffill')

rawDescription: Join datetimes of DataFrames and forward fill data


code:
import urlparse

class EasyURL(object):
    def __init__(self, parse_result):
        self.scheme = parse_result.scheme
        self.netloc = parse_result.netloc
        self.path = parse_result.path
        self.params = parse_result.params
        self.query = parse_result.query
        self.fragment = parse_result.fragment

    @classmethod
    def from_url(cls, url):
        return cls(urlparse.urlparse(url))

if __name__ == '__main__':
    url = 'http://foo.bar.com:8888/path/to/script.php?a=1&b=2'

    # Call from_url class method, which is very convenient
    easy_url = EasyURL.from_url(url)

    # Or, do it yourself
    easy_url = EasyURL(urlparse.urlparse(url))

rawDescription: Manipulating attributes from a namedtuple() derived class


rawDescription: How to convert 64-bit to double decimal in Python?

description: Convert 64-bit to double decimal in Python


code:
def method(self, alpha, beta, gamma, delta, epsilon, zeta, eta,
        theta, iota, kappa):
    pass

rawDescription: Pythonic way to functions/methods with a lot of arguments


code:
import numpy as np

class ComplexOrder(Object):
    def __lt__(self, other):
        return np.absolute(self) < np.absolute(other)
    # ... keep want you want (including or not eq and ne)
    def __ge__(self, other):
        return np.absolute(self) >= np.absolute(other)

class OrderedComplex(ComplexOrder, complex):
    def __init__(self, real, imag = 0):
        complex.__init__(self, real, imag)

class NPOrderedComplex64(ComplexOrder, np.complex64):
    def __init__(self, real = 0):
        np.complex64.__init__(self, real)

rawDescription: Implementing complex number comparison in Python?


code:
from enthought.chaco.scales.formatters import TimeFormatter
TimeFormatter._formats['days'] = ('%d/%m', '%d%a',)

rawDescription: Dealing with timeseries gaps in Chaco

description: Dealing with timeseries gaps in Chaco


code:
import os

outFile = 'C:/CompanyFiles/Matrix.txt'
folder = 'C:/CompanyFiles'

with open(outFile, 'w') as wfp:
    for f in os.listdir(inFolder):
        tmp = [line.rstrip() for line in open(os.path.join(folder, f), 'r')]
        arr = tmp[0].split('-')
        arr = [arr[0]] + arr[1].split('_')
        arr += [t.split(':')[1].strip() for t in tmp[1:]]
        wfp.write(','.join(["'" + e + "'" for e in arr]) + '\n')

rawDescription: Comma separated Matrix from txt files - continued


rawDescription: Assigning a RGB column array to an arbitrary number of columns in an image array


code:
#!/usr/bin/env python
# encoding: utf-8
"""
logClient2.py
Created by Allister on 2010-11-30.
"""

import wx
import sqlite3

WINDOW_SIZE = (900,400)

class logClient(wx.Frame):
    def __init__(self, parent, id, title):

        wx.Frame.__init__(self, parent, id, title, size=WINDOW_SIZE)

        self.toolbar = self.CreateToolBar()
        self.startLiveUpdate(None)

        self.Show(True)

    def startLiveUpdate(self, event):
        self.createToolbarItem("Refresh", "refresh.jpg", self.stopLiveUpdate)

    def stopLiveUpdate(self, event):
        self.createToolbarItem("Stop", "refresh2.jpg", self.startLiveUpdate)

    def createToolbarItem(self, label, imageName, method):
        self.toolbar.RemoveTool(1)
        self.toolbar.AddLabelTool(1, label, wx.Bitmap(imageName))
        self.toolbar.Realize()
        self.Bind(wx.EVT_TOOL, method, id=1)

if __name__ == '__main__':
    app = wx.App(False)
    logClient(None, -1, "Log Event Viewer")
    app.MainLoop()

rawDescription: Changing Label in toolbar using wxPython


rawDescription: Merging whilst keeping order in R and pandas


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import norm
linalg = np.linalg

N = 100
mean = [1,1]
cov = [[0.3, 0.2],[0.2, 0.2]]
data = np.random.multivariate_normal(mean, cov, N)
L = linalg.cholesky(cov)
# print(L.shape)
# (2, 2)
uncorrelated = np.random.standard_normal((2,N))
data2 = np.dot(L,uncorrelated) + np.array(mean).reshape(2,1)
# print(data2.shape)
# (2, 1000)
plt.figure()
plt.scatter(data2[0,:], data2[1,:], c='green')
plt.scatter(data[:,0], data[:,1], c='yellow')
plt.show()

# Plotting histograms and fitting normal distributions
plt.subplot(211)
plt.hist(data[:,0], bins=20, normed=1, alpha=0.5, color='green')
plt.hist(data2[0,:], bins=20, normed=1, alpha=0.5, color='yellow')
x = np.arange(-1, 3, 0.001)
plt.plot(x, norm.pdf(x, *norm.fit(data[:,0])), color='green')
plt.plot(x, norm.pdf(x, *norm.fit(data2[0,:])), color='yellow')
plt.title('Var 1')

plt.subplot(212)
plt.hist(data[:,1], bins=20, normed=1, alpha=0.5, color='green')
plt.hist(data2[1,:], bins=20, normed=1, alpha=0.5, color='yellow')
x = np.arange(-1, 3, 0.001)
plt.plot(x, norm.pdf(x, *norm.fit(data[:,1])), color='green')
plt.plot(x, norm.pdf(x, *norm.fit(data2[1,:])), color='yellow')
plt.title('Var 2')

plt.tight_layout()

rawDescription: Histogram based probability density estimation


code:
def test_bucket_name(self):
    self.test_app = app.test_client()

    with open('/home/linux/Pictures/natural-scenery.jpg', 'rb') as img1:
        imgStringIO1 = StringIO(img1.read())

    response = self.test_app.post('/add_item',content_type='multipart/form-data',
                                    data={'name':'test_item',
                                          'user_id':'1',
                                          'username':'admin',
                                          'image': (imgStringIO1, 'img1.jpg')})
    self.assertEquals(response.status, "200 OK")

rawDescription: How to send image with form data in test case with unittest in flask application?

description: Send image with form data in test case with unittest in flask application


code:
from __future__ import print_function
print("These \n linebreaks don't work:\n", 1)

rawDescription: Python linebreak '\n' is not working when I include something at end


code:
import numpy as np
from scipy import stats
from datetime import datetime

dt1 = [datetime(2000, 12, 15), datetime(2001, 12, 16), datetime(2002,12,20), datetime(2004,1,2) , datetime(2005,1,1)]
dt2 = [datetime(2000, 12, 15), datetime(2001, 12, 16), datetime(2002,12,20), datetime(2003,12,31), datetime(2004,12,30)]
doys1 = np.array([dt.timetuple().tm_yday for dt in dt1])
doys2 = np.array([dt.timetuple().tm_yday for dt in dt2])
stats.circmean(doys1, high=365)
stats.circmean(doys2, high=365)

rawDescription: Average day of the year across December-January


rawDescription: Dictionaries and lists appear immutable when passed to function


code:
settings = QSettings(...);
settings.setValue("lastGeometry", self.geometry())

# and to retrieve the value
lastGeometry = settings.value("lastGeometry")
if lastGeometry.isValid():
    self.setGeometry(lastGeometry)

rawDescription: Return contents of geometry() as a list in PySide


rawDescription: How do you use kwargs to map (k, v) pairs in a dict to a given sqlalchemy table?

description: Use kwargs to map (k, v) pairs in a dict to a given sqlalchemy table


code:
import os
os.system('eog {0}'.format(r'path/to/your/gif'))

rawDescription: Display .GIF from directory

description: Display .GIF from directory


code:
import importlib
# Load the module as `module'
module = importlib.import_module("os")
# Now extract the attributes into the locals() namespace, as `from ..
# import *' would do
if hasattr(module, "__all__"):
    # A module can define __all__ to explicitly define which names
    # are imported by the `.. import *' statement
    attrs = { key: getattr(module, key) for key in module.__all__ }
else:
    # Otherwise, the statement imports all names that do not start with
    # an underscore
    attrs = { key: value for key, value in module.__dict__.items() if
              key[0] != "_" }
# Copy the attibutes into the locals() namespace
locals().update(attrs)

rawDescription: Dynamically load all names from module in Python


rawDescription: Applying matplotlib color map to opencv image


code:
import lxml.html

doc = lxml.html.document_fromstring("""

   Onesome text1

   Мирsome text2

""")

txt1 = doc.xpath('/html/body/span[@class="text"]/following-sibling::text()[1]')
txt2 = doc.xpath('/html/body/span[@class="cyrillic"]/following-sibling::text()[1]')

rawDescription: How can I parse html using lxml , python

description: Parse html using lxml , python


code:
from wtforms.widgets import HTMLString, TextArea

pagedown_pre_html = '''
<div class="form-group">
'''

pagedown_post_html = '''
</div>
<script type="text/javascript">
f = function() {
    if (typeof flask_pagedown_converter === "undefined")
        flask_pagedown_converter = Markdown.getSanitizingConverter().makeHtml;
    var textarea = document.getElementById("flask-pagedown-%s");
    var preview = document.createElement('div');
    preview.className = 'help-block';
    textarea.parentNode.insertBefore(preview, textarea.nextSibling);
    textarea.onkeyup = function() { preview.innerHTML = flask_pagedown_converter(textarea.value); }
    textarea.onkeyup.call(textarea);
}
if (document.readyState === 'complete')
    f();
else if (window.addEventListener)
    window.addEventListener("load", f, false);
else if (window.attachEvent)
    window.attachEvent("onload", f);
else
    f();
</script>
'''

class PageDownBootstrap(TextArea):
    def __call__(self, field, **kwargs):
        html = super(PageDownBootstrap, self).__call__(field, id = 'flask-pagedown-' + field.name, class_ = 'form-control', **kwargs)
        return HTMLString(pagedown_pre_html + html + pagedown_post_html % field.name)

rawDescription: Python's __call__ method gets multiple values - error


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

#----- Numerical integration of ODE via fixed-step classical Runge-Kutta -----

def RK4Step(yprime,t,y,dt):
    k1 = yprime(t       , y          )
    k2 = yprime(t+0.5*dt, y+0.5*k1*dt)
    k3 = yprime(t+0.5*dt, y+0.5*k2*dt)
    k4 = yprime(t+    dt, y+    k3*dt)
    return y + (k1+2*k2+2*k3+k4)*dt/6.

def RK4(yprime,times,y0):
    y = np.empty(times.shape+y0.shape,dtype=y0.dtype)
    y[0,:] = y0                 # enter initial conditions in y
    steps = 4
    for i in range(times.size-1):
        dt = (times[i+1]-times[i])/steps
        y[i+1,:] = y[i,:]
        for k in range(steps):
            y[i+1,:] = RK4Step(yprime, times[i]+k*dt, y[i+1,:], dt)
    return y

#====================================================================
#----- Parameters for PDE -----
L       = 20
n       = 64
delta_t = 1.
tmax    = 10
miu     = 1e-6

#----- Constructing the grid and kernel functions
x2      = np.linspace(-L/2,L/2, n+1)
x       = x2[:n]                         # periodic B.C. #0 = #n
y       = x

kx     = np.linspace( -n/2  , n/2-1, n)
kx      = (2.*math.pi/L)*np.concatenate((np.arange(0,n/2),np.arange(-n/2,0)));
kx[0] = 1e-6
ky      = kx;

X, Y    = np.meshgrid(x, y)
KX,KY   = np.meshgrid(kx,ky)
K       = KX**2 + KY**2

#----- Initial Condition -----
vorticity = np.exp(-0.25*X**2 - 2.*Y**2)
wt0       = np.fft.fft2(vorticity)

#----- Define ODE -----
def wprime(t,wt):
    global miu, K, K2,n,KX, KY
    psit = -wt / K
    psix = np.real(np.fft.ifft2(1j*KX*psit))
    psiy = np.real(np.fft.ifft2(1j*KY*psit))
    wx   = np.real(np.fft.ifft2(1j*KX*wt))
    wy   = np.real(np.fft.ifft2(1j*KY*wt))
    return  -miu * K * wt + np.fft.fft2(wx*psiy - wy*psix)

#====================================================================
#----- Compute the numerical solution -----
TimeStart = 0.
TimeEnd   = tmax+delta_t
TimeSpan  = np.arange(TimeStart, TimeEnd, delta_t)
wt_sol    = RK4(wprime,TimeSpan, wt0)

#----- Animate the numerical solution -----
fig = plt.figure()
ims = []
for i in TimeSpan:
    w = np.real(np.fft.ifft2(wt_sol[i,:]))
    im = plt.pcolor(X,Y,w,edgecolors='none',cmap='jet')
    ims.append([im])

ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True,
    repeat_delay=1000)

#ani.save('PDE-animation.mp4')

plt.show()

rawDescription: Complex-valued ODE from PDE in python

description: Complex-valued ODE from PDE in python


rawDescription: Shortest/Best way to do this list task in Python


code:
money_map = {}
sites = sel.css(".info")
for site in sites:
    money = site.xpath("./h2[@class='money']/text()").extract()[0]
    people = int(site.xpath("//p[@class='poeple']/text()").extract()[0])
    if money not in money_map:
        money_map[money] = 0

    money_map[money] += people

import json
output = [{'money': key, 'people': value} for key, value in money_map.items()]
json_output = json.dumps(output)

rawDescription: for loop adding same value together and make JSON format

description: For loop adding same value together and make JSON format


code:
mylist = [1,2,3,2,3,5,6,3,7,8,6]
[i+1 for i in range(len(mylist)-1) if mylist[i]>mylist[i+1]]

rawDescription: python list sequential numbers

description: Python list sequential numbers


code:
roundvalue = True
rounds = 0
while roundvalue == True:
    rounds= input("Pick a number of rounds (3 or 5)")
    try:
        rounds = int(rounds)
    except ValueError:
        print ("This is not a number")

    if rounds  ==  3:
        print("You chose three rounds!")
        roundvalue = False
    elif rounds == 5:
        print ("You chose 5 rounds")
        roundvalue = False
    else:
        print ("Input again!")

rawDescription: Try function in code

description: Try function in code


code:
class MyAppRouter(object):
    """A router to control all database operations on models in
    the myapp application"""

    def db_for_read(self, model, **hints):
        "Point all operations on myapp models to 'other'"
        if model._meta.app_label == 'myapp':
            return 'other'
        return None

    def db_for_write(self, model, **hints):
        "Point all operations on myapp models to 'other'"
        if model._meta.app_label == 'myapp':
            return 'other'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        "Allow any relation if a model in myapp is involved"
        if obj1._meta.app_label == 'myapp' or obj2._meta.app_label == 'myapp':
            return True
        return None

    def allow_syncdb(self, db, model):
        "Make sure the myapp app only appears on the 'other' db"
        if db == 'other':
            return model._meta.app_label == 'myapp'
        elif model._meta.app_label == 'myapp':
            return False
        return None

rawDescription: how can I use separate database for every application in django

description: Use separate database for every application in django


code:
import threading
from scapy.all import *
from datetime import datetime

directory = str(datetime.now().strftime("%Y%m%d%H%M%S"))
os.makedirs(directory)

DatasetSnifferExit = 0

class DatasetSniffer(threading.Thread):
    def __init__(self, iface, local_dir='.', filename=str(datetime.now())):
        self.iface = iface
        self.filename = filename
        self.local_dir = local_dir
        self.stop_sniffing = False
        self.writer = PcapWriter(local_dir+"/"+filename+".pcap", append=True, sync=True)
        threading.Thread.__init__(self)

    def run(self):
        sniff_interface(self.writer.write, self.iface)

def stop_filter(p):
    if DatasetSnifferExit:
        return True
    else:
        return False

def sniff_interface(write, iface):
    sniff(store=0, prn=write, iface=iface, stop_filter=stop_filter)

if __name__ == "__main__":
    DatasetSnifferExit = False
    # Create new threads
    pcap1 = DatasetSniffer('en3', directory, "master")
    pcap2 = DatasetSniffer('en0', directory, "slave")

    # Start new Threads
    pcap1.start()
    pcap2.start()

    # Do stuff
    time.sleep(10)

    # Finished doing stuff
    DatasetSnifferExit = True

rawDescription: Instance variables not being updated Python when using Multiprocessing


code:
import random

# this will choose one and remove it
def choose_and_remove( items ):
    # pick an item index
    if items:
        index = random.randrange( len(items) )
        return items.pop(index)
    # nothing left!
    return None

rawDescription: How can you select a random element from a list, and have it be removed?

description: Select a random element from a list, and have it be removed


code:
import decimal
decimal.getcontext().prec = 20
a = decimal.Decimal(321.12345)
a
TWO_PLACES = decimal.Decimal("0.01")
a.quantize(TWO_PLACES)

rawDescription: How to round a Python Decimal to 2 decimal places?

description: Round a Python Decimal to 2 decimal places


rawDescription: Is there a quick/optimal way to get a list of unique values for particular key?


code: [dict(zip(letter, names))]

rawDescription: Build dictionary from list contents (values) and sequential letters as keys


code: all(0 < n < 50 for n in thetuple)

rawDescription: condition of tuple of integers

description: Condition of tuple of integers


code:
from xxx import ContactAPI
from xxx.models import Contact

# self.app is my Flask app
# self.session is SQLAlchemy Session

api_name = 'contact'
instance_endpoint = '/%s/<int:instid>' % api_name
collection_endpoint = '/%s' % api_name

methods = ['GET']

api_view = ContactAPI.as_view(api_name, self.session,
                              Contact, app)

self.app.add_url_rule(instance_endpoint, methods=methods,
                      view_func=api_view)

self.app.add_url_rule(collection_endpoint, methods=methods,
                      defaults={'instid': None},
                      view_func=api_view)

rawDescription: Using defaults with app.add_url_rule in Flask


code:
from numpy import array
a=array(['NONRBP', 'RBP', 'NONRBP', 'RBP'], dtype=object)
mask=array([int(x=='RBP') for x in a])
mask

rawDescription: Masking two-values numpy array into 0-1 binary array


code:
sorted_df = df.sort_index(by = 'rth' , ascending=False)

sorted_df.groupby('date' , as_index = False).apply(meets_criteria)

def meets_criteria(df):
    # Check for each value in column whether it satisfies your condition or not , simply concatenate results into one data frame we will use this later
    criteria_df = pd.concat([df['abc'] > 50 , df['xyz'] > 700] , axis = 1)
    # we want all conditions to be met for each row this can be achieved by the next line of code
    meets_criteria = np.all(criteria_df , axis = 1)
    # slice only the data that matches your criteria
    df_meets_criteria = df[meets_criteria]
    # this handles the case where there is matched criteria
    if len(df_meets_criteria) > 0:
        vals = np.zeros(len(df))
        vals[0] = 1
        df['meets_criteria'] = vals
    # this handles the case where there is no matched criteria
    else:
        df['meets_criteria'] = np.zeros(len(df))
    return df.reset_index()

rawDescription: Flag rows based on criteria

description: Flag rows based on criteria


code:
def __html__(self):
    return unicode(self)

rawDescription: Mark string as safe in Mako

description: Mark string as safe in Mako


rawDescription: Using asfreq shows only one ticker at the time


code:
# METHOD 1
FA_dict1 = {d:2 for v in FA[0][u'child'] for d in v.values()}
FA_dict1.update({FA[0][u'pdesc']: 2})

# METHOD 2
from itertools import chain
FA_dict = {d:2 for v in FA[0][u'child'] for d in chain(v.values(), [FA[0][u'pdesc']])}

# METHOD 3
FA_DICT = {d:2 for v in FA[0][u'child'] for d in list(v.values())+[FA[0][u'pdesc']]}

rawDescription: Nested loops in dictionary comprehension


code:
from functools import partial

self.connect(self.Option1,SIGNAL("clicked()"), partial(self.myFunction, 1))
self.connect(self.Option2,SIGNAL("clicked()"), partial(self.myFunction, 2))
self.connect(self.Option3,SIGNAL("clicked()"), partial(self.myFunction, 3))

rawDescription: how to pass arguments to a function using a predefined SIGNAL in PyQT

description: Pass arguments to a function using a predefined SIGNAL in PyQT


code:
res = grp['ColA'].reset_index()
# res is now a DataFrame with key and ColA as the columns

rawDescription: Pandas select index from grouped dataframe


code:
def BusRoute():
    path = "C:\\"
    ext = ".txt"

    lines = ""
    stopname = ""
    miles = 0
    prevmiles = 0
    milest = 0
    fuel = 0.0
    mpg = 0.0
    i = 0

    filename = input("Please enter the file name (no extension)").strip()

    inFile = open(path + filename + ext, "r")

    stopname, prevmiles, fuel = inFile.readline().split()
    prevmiles = float(prevmiles)
    fuel = float(fuel)

    for lines in inFile:
        stopname, miles, fuel = lines.split(" ")

        miles = float(miles)
        fuel = float(fuel)

        milest = miles - prevmiles

        prevmiles = miles

        miles += 1

        print("Since last stop:", float(milest), "miles")

rawDescription: Reading from a file, storing values, and math operations


rawDescription: Gdb Python API - Most efficient way to get the value of PC?


code:
import datetime

d1 = datetime.datetime.utcfromtimestamp(sub.created_utc)
print(sub.created_utc)
print(d1)
result = datetime.datetime.utcnow() - d1
print(result.days)

rawDescription: Get difference in days between today's date and previous date


code:
def nearest(pixel_color, mem={}):
    if pixel_color in mem:
        return mem[pixel_color]
    n = min(floss_palette, key=lambda fc:delta_e_cie2000(pixel_color, fc))
    mem[pixel_color] = n
    return mem[pixel_color]

result = [nearest(pixel_color) for pixel_color in image]

rawDescription: How to reduce image palette to specific colors?

description: Reduce image palette to specific colors


code:
user = users.get_current_user()
assets = SharableUserAsset.gql("WHERE users = :1", user)

rawDescription: How do I use a ListProperty(users.user) in a djangoforms.ModelForm on Google AppEngine?

description: Use a ListProperty(users.user) in a djangoforms.ModelForm on Google AppEngine


code: a[trim_left:-trim_right or None]

rawDescription: numpy negative indexing a[:-0]

description: Numpy negative indexing a[:-0]


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

x = np.array([0,1,2,3])
y = np.array([0.650, 0.660, 0.675, 0.685])
my_xticks = ['a', 'b', 'c', 'd']
plt.xticks(x, my_xticks)
plt.yticks(np.arange(y.min(), y.max(), 0.005))
plt.plot(x, y)
plt.grid(axis='y', linestyle='-')
plt.show()

rawDescription: Python Matplotlib - how to specify values on y axis?


code:
_menu = QMenu()

#Define action
_add_action     = _menu.addAction(QIcon("images\add.png"),"Add")
_remove_action  = _menu.addAction(QIcon("images\remove.png"),"Remove")

#Asign events to actions
self.connect(_add_action, SIGNAL("triggered()"), self._add_handle)
self.connect(_remove_action, SIGNAL("triggered()"), self._remove_handle)

rawDescription: Override addAction() to modify string and QIcon in pyqt


code:
maxLen = reduce(lambda a,b : max(a, b.shape[0]),
                dSets, 0)
all = N.ma.zeros((maxLen,)+ dSets[0].shape[1:] + (len(dSets),),
                     dtype=float)      # set the dtype to whatever
all.mask = True
for i, set in enumerate(dSets):
    all.mask[:len(set),...,i] = False
    all[:len(set),...,i] = set

mean = all.mean(axis=-1)

rawDescription: Using Numpy to find average value across data sets, with some missing data


code:
def iterate_tree4(tree, depth, callback):
    iterators = [iter(tree.items())]
    args = []
    while iterators:
        while depth:
            for k, v in iterators[-1]:
                args.append(k)
                iterators.append(iter(v.items()))
                depth -= 1
                break
            else:
                break
        else:
            for k, v in iterators[-1]:
                yield callback(*(args + [k, v]))
        depth += 1
        del iterators[-1]
        del args[-1:]

rawDescription: Efficiently iterating arbitrary depth dict tree in Python


code: newlist = [sublist[:2] for sublist in mylist]

rawDescription: Return a range of elements of each list inside a list of lists


code:
import Tkinter as tk

class application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.can = tk.Canvas(master, width=200, height=200)
        #######################################
        self.can.bind('<Button-2>', self.draw)
        #######################################
        self.can.grid()
    #######################
    def draw(self, event):
    #######################
        self.can.create_rectangle(50, 50, 100, 100, fill='red')

app = application()
app.mainloop()

rawDescription: Tkinter mouse event initially triggered

description: Tkinter mouse event initially triggered


code:
all = ("this line has no hits",
       "a letter to tom from peter",
       "today bonny went to school",
       "harry made some cake")

mydict = {'harry':'sally','tom':'jerry','bonny':'clyde'}

output = []
for line in all:
    for search, replace in mydict.items():
        line = re.sub(search, replace, line)
    output.append(line)

print(output)

rawDescription: Using list comprehension and a dict for regex substitution


code:
def configure(cfg):
    cfg.env.append_value('INCLUDES', ['include'])

rawDescription: Adding include path to Waf configuration (C++)


code:
# object model
t_userfriend = Table("user_friend", Base.metadata,
    Column("user_id", Integer, ForeignKey("users.id"), primary_key = True),
    Column("friend_id", Integer, ForeignKey("users.id"), primary_key = True),
)

class User (Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True)
    name = Column(String(50), unique = True)
    # ...
    friends = relationship("User",
                          secondary = t_userfriend,
                          primaryjoin = (id == t_userfriend.c.user_id),
                          secondaryjoin = (id == t_userfriend.c.friend_id),
                          backref = "friend_of",
                          )

rawDescription: Filed in SQLAlchemy of user's list

description: Filed in SQLAlchemy of user's list


code:
import cv2
from cv2 import cv

method = cv.CV_TM_SQDIFF_NORMED

# Read the images from the file
small_image = cv2.imread('small_image.png')
large_image = cv2.imread('large_image.jpeg')

result = cv2.matchTemplate(small_image, large_image, method)

# We want the minimum squared difference
mn,_,mnLoc,_ = cv2.minMaxLoc(result)

# Draw the rectangle:
# Extract the coordinates of our best match
MPx,MPy = mnLoc

# Step 2: Get the size of the template. This is the same size as the match.
trows,tcols = small_image.shape[:2]

# Step 3: Draw the rectangle on large_image
cv2.rectangle(large_image, (MPx,MPy),(MPx+tcols,MPy+trows),(0,0,255),2)

# Display the original image with the rectangle around the match.
cv2.imshow('output',large_image)

# The image is only displayed if we call this
cv2.waitKey(0)

rawDescription: How do I find an image contained within an image?

description: Find an image contained within an image


code:
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_edge(1,2,weight=7)
G.add_edge(2,3,weight=42)
labels = {}
for u,v,data in G.edges(data=True):
    labels[(u,v)] = data['weight']

pos = nx.spring_layout(G)
nx.draw(G,pos)
nx.draw_networkx_edge_labels(G, pos, edge_labels=labels)

plt.show()

rawDescription: How to remove an attribute from the edge label in a networkx graph?

description: Remove an attribute from the edge label in a networkx graph


code:
i = 1
nestedTuple = [('a','b','c'), ('d','e','f'), ('g','h','i')]
nestedTuple[1] = nestedTuple[1][:i] + ('xXXXXx', ) + nestedTuple[1][i+1:]
nestedTuple

rawDescription: Replacing a single element in a tuple nested within a list - Is their a better way?


code:
struct.pack("=H??LLLLH",
            socket.ntohs(v1),
            v2,
            v3,
            socket.ntohl(v5),
            socket.ntohl(v6),
            socket.ntohl(v7),
            socket.ntohl(v8),
            socket.ntohs(v9))

rawDescription: stack.pack() or socket.ntohl() converts 4Byte into 8Byte Python

description: Stack.pack() or socket.ntohl() converts 4Byte into 8Byte Python


code: print ("Total cost is: ${:,.2f}".format(TotalAmount))

rawDescription: Python Add Comma Into Number String

description: Python Add Comma Into Number String


code: BeautifulSoup(markup, "html.parser")

rawDescription: Same code different result on different computers


code:
import re
import sys

with open('somefile.csv', 'r') as filehandle:
    for text in filehandle:
        b = re.search("([a-zA-Z]+);([a-z\sA-Z]+);([a-zA-Z]*);([0-9^-]+)\n?",text)
        print (b.group(2),b.group(1),b.group(3),b.group(4))

rawDescription: Python Regular Expression loop

description: Python Regular Expression loop


rawDescription: Joining every four strings in a list

description: Joining every four strings in a list


code:
import turtle
wn = turtle.Screen()

tess = turtle.Turtle()

def draw(x, y): # x, y are mouse position arguments passed by onclick()

    tess.clear() # Clear out the drawing (if any)
    tess.reset() # Reset the turtle to original position
    tess.hideturtle()

    tess.left(36)
    tess.forward(100)
    for a in range(4):
        tess.left(144)
        tess.forward(100)
    tess.right(36) # to go to original place

draw(0, 0) # Draw the first time

wn.onclick(draw) # Register function draw to the event mouse_click
wn.onkey(wn.bye, "q") # Register function exit to event key_press "q"

wn.listen() # Begin listening to events like key_press & mouse_clicks
wn.mainloop()

rawDescription: Python turtle after drawing , click mouse, clear screen and redraw


code:
import config
import subprocess
import shlex
import timeit
import MySQLdb
import collections
import matplotlib.pyplot as plt

Popen = subprocess.Popen
PIPE = subprocess.PIPE
sql = 'select * from table limit {n}'

def using_subprocess(n):
    p1 = Popen(
        shlex.split(
            'echo {s}'.format(s=sql.format(n=n))), stdout=PIPE, close_fds=True)

    p2 = Popen(
        shlex.split(
            'mysql --host={h} -u {u} --password={p} --database={d}'.format(
                h=config.HOST,
                u=config.USER,
                p=config.PASS,
                d=config.MYDB
                )),
        stdin=p1.stdout, stdout=PIPE, close_fds=True)

    p1.stdout.close()
    out, err = p2.communicate()
    return out

def using_mysqldb(n):
    connection = MySQLdb.connect(
        host = config.HOST, user = config.USER,
        passwd = config.PASS, db = config.MYDB)
    cursor = connection.cursor()

    cursor.execute(sql.format(n=n))
    rows = cursor.fetchall()
    return rows

times = collections.defaultdict(list)
ns = [10**i for i in range(5)]
for n in ns:
    times['using_mysqldb'].append(
        timeit.timeit('m.using_mysqldb({n})'.format(n=n),
                      'import __main__ as m',
                      number = 10))
    times['using_subprocess'].append(
        timeit.timeit('m.using_subprocess({n})'.format(n=n),
                      'import __main__ as m',
                      number = 10))

for name, time in times.iteritems():
    plt.plot(ns, time, label=name)
    # print('{n}: {t}'.format(n=name, t=time))
plt.legend(loc='best')
plt.show()

rawDescription: how ineffecient is it using Popen with pipes vs mysql module in python?

description: How ineffecient is it using Popen with pipes vs mysql module in python


code:
class A:
    _tmp = {"A" : 1,
             "B" : 2}
    def tmp(self):
        return self._tmp

class B(A):
    _tmp = {"A" : 10,
             "B" : 20}
    def __init__(self):
        super().__init__()

b = B()
print(b.tmp()) # Works as expected

rawDescription: Python: Hide member of base class in derived class


rawDescription: Can Python win32com use Visio (or any program) without popping up a GUI?


code:
class Expando(object):
    pass

ex = Expando()
ex.foo = 17
ex.bar = "Hello"

rawDescription: How to create a new unknown or dynamic/expando object in Python

description: Create a new unknown or dynamic/expando object in Python


code:
import csv

with open('c.csv', 'wb') as outcsv:
    # Python 3: use open('c.csv', 'w', newline='') instead
    writer = csv.writer(outcsv)

    # copy a.csv across, adding a 3rd column
    with open('a.csv', 'rb') as incsv:
        # Python 3: use open('a.csv', newline='') instead
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    # copy b.csv across, inserting a 2nd column
    with open('b.csv', 'rb') as incsv:
        # Python 3: use open('b.csv', newline='') instead
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

rawDescription: Python - merging of csv files with one axis in common


code:
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
#>>> datetime.datetime(2013, 9, 28, 20, 30, 55, 782000)

rawDescription: how to convert a string date into datetime format in python?

description: Convert a string date into datetime format in python


code:
import itertools
import string
numbers = set(range(10))
letters = set(string.ascii_letters)
print([x for x in itertools.combinations([0,1,2,3,4,'a','b','c','d'], 4)
       if set(x) & letters and set(x) & numbers])

rawDescription: Python Itertools permutations only letters and numbers


code:
from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^my-view$', MyViewClass.as_view(), name='my_view'),
)

reverse('my_view')

rawDescription: Django - using reverse() on Class-based views


code:
import Tkinter as tk

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.canvas = tk.Canvas(width=400, height=400)
        self.canvas.pack(fill="both", expand=True)

        self._create_token((100, 100), "white")
        self._create_token((200, 300), "pink")
        self._create_arc((100,100), (200, 300))

    def _create_token(self, coord, color):
        '''Create a token at the given coordinate in the given color'''
        (x,y) = coord
        self.canvas.create_oval(x-5, y-5, x+5, y+5,
                                outline=color, fill=color, tags="token")

    def _create_arc(self, p0, p1):
        extend_x = (self._distance(p0,p1) -(p1[0]-p0[0]))/2 # extend x boundary
        extend_y = (self._distance(p0,p1) -(p1[1]-p0[1]))/2 # extend y boundary
        startAngle = math.atan2(p0[0] - p1[0], p0[1] - p1[1]) *180 / math.pi # calculate starting angle
        self.canvas.create_arc(p0[0]-extend_x, p0[1]-extend_y ,
                               p1[0]+extend_x, p1[1]+extend_y,
                               extent=180, start=90+startAngle, style=tk.ARC)

        '''use this rectangle for visualisation'''
        #self.canvas.create_rectangle(p0[0]-extend_x, p0[1]-extend_y,
        #                                p1[0]+extend_x, p1[1]+extend_y)

    def _distance(self, p0, p1):
        '''calculate distance between 2 points'''
        return sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2)

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

rawDescription: Draw an arc between two points on a tkinter canvas


code:
import pylab as plt
import pandas as pd
from random import sample

atype = list('abc'*2)
asize = sample(xrange(100), 6)

df = pd.DataFrame({'type': atype, 'size': asize})
df_grouped = df.groupby('type').sum() # sum sizes for same types
df_grouped.plot(kind='bar')
plt.show()

rawDescription: making matplotlib with pandas dataframe data

description: Making matplotlib with pandas dataframe data


code:
def findtoptwo(d):
    toptwo = sorted(d.values())[-2:]
    return {k:v for k,v in d.items() if v in toptwo}

newdict = {k:findtoptwo(v) for k,v in bigdict.items()}
newdict

rawDescription: Grab 2 keys with highest values for nested dictionary


code:
@property
def number(self):
     # do extra logic if necessary
    return self.count

rawDescription: "Method overloading" in python

description: "Method overloading" in python


rawDescription: Timestamp in a json file

description: Timestamp in a json file


code:
import datetime

cursor_table1.execute('SELECT part, min, max, unitPrice, NOW() from table1')
for row in cursor_table1.fetchall():
    part, min, max, unitPrice, now = row
    cursor_table2.execute("INSERT INTO table2 VALUES (%s,%s,%s,%s,'%s')" % (part, min, max, unitPrice, now.strftime('%Y-%m-%d %H:%M:%S') ))

rawDescription: Python MySQLdb select from and insert into another database


code: regexp = re.compile(r"\d+(.*?)(\bfahrenheit\b|\bf\b)", re.IGNORECASE)

rawDescription: Regex does not work as expected in interpreter


rawDescription: How to keep certain levels of a categorical variable and set remaining as "other" in pandas data frame

description: Keep certain levels of a categorical variable and set remaining as "other" in pandas data frame


code:
import webbrowser
with open("filename","r") as f:
    for url in f:
        webbrowser.open_new_tab(url)

rawDescription: Iterate through a text file and open the URL on everyline


code:
import matplotlib.pyplot as plt

coords = [(0.0, 0.0), (1.0, 1.0), (1.0, 0.0), (2.0, 1.0), (2.0, 0.0), (3.0, 1.0)]
connectivity = {0: (1,2),     #coords[0] <--> coords[1], coords[2]
                1: (0, 2, 3), #coords[1] <--> coords[0], coords[2], coords[3]
                2: (0, 1, 4), #coords[2] <--> coords[0], coords[1], coords[4]
                3: (1, 3, 5), #coords[3] <--> coords[1], coords[3], coords[5]
                4: (2, 3, 5), #coords[4] <--> coords[2], coords[3], coords[5]
                5: (3, 4)     #coords[5] <--> coords[3], coords[4]
                }
x, y = zip(*coords)
plt.plot(x, y, 'o')  # plot the points alone
for k, v in connectivity.iteritems():
    for i in v:  # plot each connections
        x, y = zip(coords[k], coords[i])
        plt.plot(x, y, 'r')
plt.show()

rawDescription: Connect scatter plot points in specific order matplotlib


code:
function_list = {0:{"func":power_off},
                 1:{"func":image_capture, "args":(100,1000,100,100)},
                 2:{"func":video_record, "args":(100,100)},
                 3:{"func":image_settings},
                 4:{"func":video_settings},
                 5:{"func":device_settings} }

f = function_list[current_selection]
if "args" in f:
    f["func"](*f["args"])
else:
    f["func"]()

rawDescription: Python: How to create a dictionary that contains some functions, without running them on assignment?


code:
def remove_last_odd_row(fr):
    nrow = fr.shape[0]
    if nrow % 2 > 0:
        return fr[:(nrow - 1)]
    else:
        return fr

fr = fr.groupby("fruitname").apply(remove_last_odd_row).reset_index(drop=True)

rawDescription: python pandas dataframe : removing selected rows

description: Python pandas dataframe : removing selected rows


rawDescription: gtk+ checkbutton settings

description: Gtk+ checkbutton settings


code:
import sys

text = sys.stdin.read()

rawDescription: Multiple lines user input in command-line Python application


code:
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
from django.http import HttpResponse
from django.http import Http404

@csrf_exempt
def handler(request):
    if request.is_ajax():
        pos = request.POST['pos']
        return HttpResponse(2)
    else:
        raise Http404

rawDescription: use of ajax with django for passing information

description: Use of ajax with django for passing information


code:
from django.test import Client
import base64
auth_headers = {
    'HTTP_AUTHORIZATION': 'Basic ' + base64.b64encode('username:password'),
}
c = Client()
response = c.get('/my-protected-url/', **auth_headers)

rawDescription: Using Basic HTTP access authentication in Django testing framework


code:
import collections
class MinimalMapping(collections.Mapping):
    def __init__(self, *items ):
        self.elements = dict(items)
    def __getitem__(self, key):
        return self.elements[key]
    def __len__(self):
        return len(self.elements)
    def __iter__(self):
        return iter(self.elements)

t = MinimalMapping()
print (t.iteritems, t.keys, t.itervalues, t.get)

rawDescription: Python std methods hierarchy calls documented?


rawDescription: Increase numpy array elements using array as index


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_doc)

tables = soup.find_all( 'table' )
for table in tables:
    contents = str( table.contents )
    new_contents = transform( contents )
    table.replaceWith( new_contents )

rawDescription: How can I iterate over specific elements in HTML file and replace them?

description: Iterate over specific elements in HTML file and replace them


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

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

# my random data
scale = 10
np.random.seed(101)
x = np.random.random(10)*scale
y = np.random.random(10)*scale

# spacing of arrows
aspace = .1 # good value for scale of 1
aspace *= scale

# r is the distance spanned between pairs of points
r = [0]
for i in range(1,len(x)):
    dx = x[i]-x[i-1]
    dy = y[i]-y[i-1]
    r.append(np.sqrt(dx*dx+dy*dy))
r = np.array(r)

# rtot is a cumulative sum of r, it's used to save time
rtot = []
for i in range(len(r)):
    rtot.append(r[0:i].sum())
rtot.append(r.sum())

arrowData = [] # will hold tuples of x,y,theta for each arrow
arrowPos = 0 # current point on walk along data
rcount = 1
while arrowPos < r.sum():
    x1,x2 = x[rcount-1],x[rcount]
    y1,y2 = y[rcount-1],y[rcount]
    da = arrowPos-rtot[rcount]
    theta = np.arctan2((x2-x1),(y2-y1))
    ax = np.sin(theta)*da+x1
    ay = np.cos(theta)*da+y1
    arrowData.append((ax,ay,theta))
    arrowPos+=aspace
    while arrowPos > rtot[rcount+1]:
        rcount+=1
        if arrowPos > rtot[-1]:
            break

# could be done in above block if you want
for ax,ay,theta in arrowData:
    # use aspace as a guide for size and length of things
    # scaling factors were chosen by experimenting a bit
    axes.arrow(ax,ay,
               np.sin(theta)*aspace/10,np.cos(theta)*aspace/10,
               head_width=aspace/8)

axes.plot(x,y)
axes.set_xlim(x.min()*.9,x.max()*1.1)
axes.set_ylim(y.min()*.9,y.max()*1.1)

plt.show()

rawDescription: How do I specify an arrow-like linestyle in Matplotlib?

description: Specify an arrow-like linestyle in Matplotlib


code:
# I've changed the name to float_list because l should not be
# used as a variable name in Python according to the standard
# style recommendations
print(*('{0:.2f}'.format(x) for x in float_list), sep="\t")

rawDescription: py3k print significant figures

description: Py3k print significant figures


code:
max_length = 30
for i in xrange(0, len(emails), max_length):
    current_array = emails[i:i+max_length]
    # query this array

rawDescription: Breaking up Python list into smaller lists?


code:
from xml.dom import minidom

doc = minidom.parse(myXmlFile)
for element in doc.getElementsByTagName('MyElementName'):
    if element.getAttribute('name') in ['AttrName1', 'AttrName2']:
        parentNode = element.parentNode
        parentNode.insertBefore(doc.createComment(element.toxml()), element)
        parentNode.removeChild(element)
f = open(myXmlFile, "w")
f.write(doc.toxml())
f.close()

rawDescription: How to comment out an XML Element (using minidom DOM implementation)

description: Comment out an XML Element (using minidom DOM implementation)


code:
if sys.version_info < (3, 0):
    data = bytes(data)
else:
    data = bytes(data, 'utf8')

rawDescription: String to bytes in both Python 2 and 3

description: String to bytes in both Python 2 and 3


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

number_of_bins = 20
number_of_data_points = 1000

ax = plt.subplot(111)

data_set = [np.random.normal(0, 1, number_of_data_points),
            np.random.normal(6, 1, number_of_data_points),
            np.random.normal(-3, 1, number_of_data_points)]

MID_VALUES = [0, 200, 400]
labels = ["v1", "v2", "v3"]

for MID_VAL, y in zip(MID_VALUES, data_set):

    hist, bin_edges = np.histogram(y, bins=number_of_bins)

    bottom = bin_edges[:-1]
    heights = np.diff(bin_edges)
    lefts = MID_VAL - .5 * hist

    ax.barh(bottom, hist, height=heights, left=lefts)

ax.set_xticks(MID_VALUES)
ax.set_xticklabels(labels)

plt.show()

rawDescription: Multiple side-by-side histograms with matplotlib?


code:
_temp = __import__('foo.bar', globals(), locals(), ['object'], -1)
object = _temp.object

rawDescription: How to use python's import function properly __import__()

description: Use python's import function properly __import__()


code:
class fake_module(object):
    def __init__(self, name, *args):
        self.name = name
        self.__all__ = []
        all_objects = globals()
        for name in args:
            self.__dict__[name] = all_objects[name]
            self.__all__.append(name)
    def register(self):
        sys.modules["%s.%s" % (__name__, self.name)] = self

    fake_module('api', 'class1', 'class2', 'func3', 'exception4').register()

rawDescription: How to define a `from ... import *' api seperate from __all__ in a module?

description: Define a `from ... import *' api seperate from __all__ in a module


code:
import ast
a,b = ast.literal_eval("[12.45,56.78]")
a
b

rawDescription: Getting the float numbers from this string (Python)


code: raw_input('Please enter in the length of the first side: ')

rawDescription: Allow User Input Without Moving to New Line - Python 2.7


code:
@app.task(name='report_task')
def reportTask(self, link):
    pass

rawDescription: Where should you update Celery settings? On the remote worker or sender?


code:
def getinstances(struct):
    if isinstance(struct, luigi.Task):
        return struct.instantiate()
    elif isinstance(struct, dict):
        return {k: getinstances(v) for k, v in six.iteritems(struct)}
    else:
        # Remaining case: assume r is iterable...
        try:
            s = list(struct)
        except TypeError:
            raise Exception('Cannot map %s to Task/dict/list' % str(struct))
    return [getinstances(r) for r in s]

class MyParentTask(luigi.Task):
    def requires(self):...
    def output(self):...
    def run(self):...
    def instantiate(self):
        with self.output().open() as outfile:
            reader = csv.reader(outfile)
            outdata = [row for row in reader]
        return outdata

class MyChildTask(luigi.Task):
    def requires(self):
        return MyParentTask()
    def output(self):...
    def run(self):
        indata = getinstances(self.requires())
        ...

rawDescription: Automatic instantiate in luigi?

description: Automatic instantiate in luigi


code:
from django.core.urlresolvers import set_urlconf

set_urlconf('module.path.urls')

rawDescription: Changing Django's ROOT_URLCONF

description: Changing Django's ROOT_URLCONF


code:
import csv
import pandas

pandas.read_table(fn, quoting=csv.QUOTE_NONE, names=('word', 'tag'))

rawDescription: Reading in TSV with unescaped character in Pandas


code:
import sys
import cdecimal
assert "sqlalchemy" not in sys.modules
assert "decimal" not in sys.modules
sys.modules["decimal"] = cdecimal

rawDescription: cdecimal and SQLAlchemy actually stores `decimal.Decimal`?

description: Cdecimal and SQLAlchemy actually stores `decimal.Decimal`


code:
a = ['ibm','dell']
b = ['strength', 'weakness']
c = ['url1.com', 'url2.com']

moo = {}
for k in a:
    moo[k] = dict((kk, c) for kk in b)

print(moo)
{'dell': {'strength': ['url1.com', 'url2.com'],
  'weakness': ['url1.com', 'url2.com']},
 'ibm': {'strength': ['url1.com', 'url2.com'],
  'weakness': ['url1.com', 'url2.com']}}

rawDescription: create and iterate over dictionary of dictonaries

description: Create and iterate over dictionary of dictonaries


code:
import subprocess
def backupOperation():
    p = subprocess.Popen(["pg_dump","-v","-Fc","-d","database_name","--file","output.dump"],
                         stderr=subprocess.PIPE)
    output, err = p.communicate()
    print(output)
    print(err)
    with open("log.txt", "w") as fo:
        fo.write(err)

backupOperation()

rawDescription: How to write console output of pg_dump to a file in python

description: Write console output of pg_dump to a file in python


code:
import seaborn as sns
sns.set_color_codes()
tips = sns.load_dataset("tips")
pal = {day: "r" if day == "Sat" else "b" for day in tips.day.unique()}
sns.boxplot(x="day", y="total_bill", data=tips, palette=pal)

rawDescription: Color seaborn boxplot based in DataFrame column name


code:
with open('input.txt') as input, open('output.txt', 'w') as output:
    for line in input:
        output.write(line.replace('glVertex3f', 'glColor3f'))
        output.write(line)

rawDescription: Replace Ctr+H copy row and change it

description: Replace Ctr+H copy row and change it


code:
def gettext(request):
  if request.method == 'POST':
    form = UploadFileForm(request.POST, request.FILES)
    if form.is_valid():
        f = request.FILES['file']
        for chunk in f.chunks():
            text = chunk
            text = preprocessing(text)
        return render(request, 'ecs/index.html', {'text': text, 'form': form})
    else:
        form = UploadFileForm()
return render_to_response('ecs/index.html', {'form': form})

rawDescription: Q: Django - how to return data from other function on views.py


code:
d
dict(zip(d.Stuff, d.Stuff.map(ord)))

rawDescription: Get a Dictionary by applying function to pandas Series


code:
import subprocess

def preprocess(fname, output_dir):
    subprocess.check_call([
        'java',
        '-cp',
        'stanford-corenlp-2012-07-09.jar:stanford-corenlp-2012-07-06-models.jar:xom.jar:joda-time.jar',
        '-Xmx3g', 'edu.stanford.nlp.pipeline.StanfordCoreNLP'
        '-annotators', 'tokenize,ssplit,pos,lemma,ner',
        '-filelist', fname,
        '-outputDirectory', output_dir
    ])

rawDescription: How to make system call in python and store the output in a given output directory?

description: Make system call in python and store the output in a given output directory


code: struct.unpack('>q', s)[0]

rawDescription: Shortest way to convert these bytes to int in python?


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

df = pd.DataFrame(np.random.random([100,5]),columns='A B C D E'.split())

sc1 = plt.scatter(x=df['A'], y=df['B'], c=df['C'], s=50*df['D'], cmap='summer')
plt.colorbar(sc1)
sc2 = plt.scatter(x=df['A'], y=df['C'], c=df['D'], s=50*df['B'], cmap='winter')
plt.colorbar(sc2)

rawDescription: pandas plot - multiple colorbars

description: Pandas plot - multiple colorbars