code:
filename_queue = tf.train.string_input_producer(['/Users/HANEL/Desktop/tf.png']) #  list of files to read

reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)

my_img = tf.image.decode_png(value) # use png or jpg decoder based on your files.

init_op = tf.initialize_all_variables()
with tf.Session() as sess:
  sess.run(init_op)

# Start populating the filename queue.

coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)

for i in range(1): #length of your filename list
  image = my_img.eval() #here is your image Tensor :)

print(image.shape)
Image.show(Image.fromarray(np.asarray(image)))

coord.request_stop()
coord.join(threads)

rawDescription: Tensorflow image reading & display

description: Tensorflow image reading & display


code:
import sys
from PyQt4 import QtGui, QtCore

class Tinter(QtGui.QWidget):
    def __init__(self, image, parent=None):
        super(Tinter, self).__init__(parent)

        self.pixmap = QtGui.QPixmap(image)

        self.normal = QtGui.QLabel()
        self.normal.setPixmap(self.pixmap)
        self.tinted = QtGui.QLabel()

        self.red = QtGui.QSlider(QtCore.Qt.Horizontal)
        self.red.setRange(0, 255)
        self.red.sliderMoved.connect(self.applyTint)
        self.green = QtGui.QSlider(QtCore.Qt.Horizontal)
        self.green.setRange(0, 255)
        self.green.sliderMoved.connect(self.applyTint)
        self.blue = QtGui.QSlider(QtCore.Qt.Horizontal)
        self.blue.setRange(0, 255)
        self.blue.sliderMoved.connect(self.applyTint)
        self.alpha = QtGui.QSlider(QtCore.Qt.Horizontal)
        self.alpha.setRange(0, 255)
        self.alpha.setValue(128)
        self.alpha.sliderMoved.connect(self.applyTint)

        controlLayout = QtGui.QFormLayout()
        controlLayout.addRow('red', self.red)
        controlLayout.addRow('green', self.green)
        controlLayout.addRow('blue', self.blue)
        controlLayout.addRow('alpha', self.alpha)

        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.normal)
        layout.addWidget(self.tinted)
        layout.addLayout(controlLayout)
        self.setLayout(layout)

        self.applyTint()

    def applyTint(self):
        temp = QtGui.QPixmap(self.pixmap)
        color = QtGui.QColor(self.red.value(),
                             self.green.value(),
                             self.blue.value(),
                             self.alpha.value())
        painter = QtGui.QPainter(temp)
        painter.setCompositionMode(painter.CompositionMode_Overlay)
        painter.fillRect(temp.rect(), color)
        painter.end()
        self.tinted.setPixmap(temp)

app = QtGui.QApplication(sys.argv)

main = Tinter('so.jpg')
main.show()

sys.exit(app.exec_())

rawDescription: Qt4: tinting a QIcon

description: Qt4: tinting a QIcon


code:
#!/usr/bin/python

import Gnuplot as gp
import numpy as np

g = gp.Gnuplot(debug=1)

m = np.matrix('4 4 4 1; 3 2 1 1; 1 2 3 1; 0 0 0 0')
gdat = gp.GridData(m, inline=True, binary=False)
g('set style data image')
g.plot(gdat)

rawDescription: How do I do image plots in the gnuplot module for python?

description: Do image plots in the gnuplot module for python


code:
def browse_for_file_1(label_1):
  file_name_1 = tkFileDialog.askopenfilename(parent=root,title='Open 1st File')
  label_1.config(text=file_name_1)
  # or label_1.config({'text':file_name_1})

rawDescription: How do I change a label's text to a file name on button press in Python?

description: Change a label's text to a file name on button press in Python


code:
from collections import defaultdict

r = defaultdict(lambda: defaultdict(int))
for t in time:
    week = t.date.isocalendar()[1]
    day = t.date.isoweekday()
    r[week][day] += t.hours

rawDescription: Python/Django - Build list by Sum by day and Week


rawDescription: Resample and resize numpy array

description: Resample and resize numpy array


code:
d = {'age': 27,
 'name': 'Joe',
 'numbers': [1,
             2,
             3,
             4,
             5],
 'subdict': {
             'first': 1,
             'second': 2,
              'third': 3
             }
}

from pprint import pprint
pprint(d)

rawDescription: Python human readable object serialization


code:
import tensorflow as tf

C_int = tf.constant(134)
V_mat = tf.Variable(tf.zeros([2,3]))
C_str = tf.constant("ABC")

sess = tf.Session()
sess.run(C_int)
#134
sess.run(V_mat)
#array([[ 0.,  0.,  0.],
#       [ 0.,  0.,  0.]])
sess.run(C_str)
#ABC

sess.close()

rawDescription: Get original value of Tensor in Tensorflow


code: (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),

rawDescription: How to handle a HTTP GET request to a file in Tornado?

description: Handle a HTTP GET request to a file in Tornado


code:
from Tkinter import *

root = Tk()
top = Toplevel()
top.title('TopLevel window')
top.transient(root) # <------

root.mainloop()

rawDescription: How to prevent Toplevel() from closing both windows python?

description: Prevent Toplevel() from closing both windows python


code: selected = train_spam[np.random.randint(train_spam.shape[0], size=1000)]

rawDescription: Selecting random arrays from multidimensional numpy array with replacement


code:
x = numpy.datetime64('2005-02-25T03:30Z', 'ms')
x
numpy.datetime64(x, 'ns')

rawDescription: Casting datetime64 to different time unit


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

s1_values = [6,8,6,3,7,9]
s1_times =  [1,3,6,7,8,12]

s2_values = [3,8,7,2,5,4,6,2]
s2_times =  [2,4,5,7,8,9,10,13]

df1 = pd.DataFrame(zip(s1_times, s1_values), columns=['Time', 's1 values'])
df2 = pd.DataFrame(zip(s2_times, s2_values), columns=['Time', 's2 values'])

df = df1.merge(df2, how='outer', on='Time', sort='Time')
df.fillna(method='pad', inplace=True)  # or df.interpolate(inplace=True)

df.plot(kind='scatter', x='s1 values', y='s2 values')
plt.show()

rawDescription: Plot values of two time series with different dates


code:
DY=T
Y=T

rawDescription: Why is my Runge-Kutta Python script defining elements of an array in this abnormal way?


code:
from datetime import datetime
from datetime import timedelta
from calendar import timegm

utc_dt = datetime.utcfromtimestamp(self.__modified_time)
from_zone = tz.tzutc()
to_zone = tz.tzlocal()

utc = utc_dt.replace(tzinfo=from_zone)
central = utc.astimezone(to_zone)
unix_time_central = timegm(central.timetuple())

rawDescription: Convert datetime to unix timestamp in python


code:
from bottle import static_file

@route('/download/<filename:path>')
def download(filename):
    return static_file(filename, root='/path/to/static/files', download=filename)

rawDescription: Binary file download

description: Binary file download


code:
arr = np.asarray(mtx)
np.repeat(arr[:,:2], arr[:,2].astype(int), axis=0)

rawDescription: Expand numpy matrix

description: Expand numpy matrix


code:
import shelve

shelf = shelve.open(filename)
shelf['key1'] = value1
shelf['key2'] = value2

shelf.close()
 # next run
shelf.open(filename)

value1 = shelf['key1']
#etc

rawDescription: Storing user data in a Python script

description: Storing user data in a Python script


code:
import inspect

def get_input_names(function):
    '''get arguments names from function'''
    return inspect.getargspec(function)[0]

def filter_dict(dict_,keys):
    return {k:dict_[k] for k in keys}

def filter_kwargs(func):
   def func_wrapper(**kwargs):
       return func(**filter_dict(kwargs, get_input_names(func)))
   return func_wrapper

@filter_kwargs
def foo(a,b):
    return a + b

d = {'a':1,
     'b':2,
     'c':3}

print(foo(**d))

rawDescription: How to call a function with a dictionary that contains more items than the function has parameters?

description: Call a function with a dictionary that contains more items than the function has parameters


code:
from heapq import *
a = [2,7,4,0,8,12,14,13,10,3,4]
heapify(a)
b = a[:]
heappushpop(a, -1)
heapreplace(b, -1)

rawDescription: python, heapq: difference between heappushpop() and heapreplace()

description: Python, heapq: difference between heappushpop() and heapreplace()


code:
import wx

class size:
    def __init__(self, id, name):
        self.id = id
        self.name = name

class type:
    def __init__(self, id, name):
        self.id = id
        self.name = name

class GUI(wx.Frame):
    def __init__(self, parent, id, title):
        self.dirname = ''
        self.content = ''

        wx.Frame.__init__(self, parent, id, title, size=(700, 400))
        self.panel = wx.Panel(self)

        #UI stuff
        #panelControl = wx.Panel(self, 1, style=wx.MAXIMIZE)
        sizerControl = wx.BoxSizer(wx.VERTICAL)

        self.menu()
        #buttons
        if not self.content == '':
            self.myButtons(sizerControl)

        self.panel.SetSizer(sizerControl)
        self.panel.Layout()

        self.Show()

    def myButtons(self, sizerControl):
        listOfObjects = self.content #list if lists
        #content of the dropdown lists
        sizes = [size(0, 'very small'), size(1, 'small'), size(2, 'medium'), size(3, 'large'), size(4,'very large')]
        types = [type(0, 'UI'), type(1, 'text'), type(2, 'I/O'), type(3, 'calculation'),
            type(4, 'set-up'), type(5,  'logic'), type(6, 'data')]

        for i in listOfObjects:
            lista = [] #save the dropdown list selections
            panel = wx.Panel(self.panel, wx.ID_ANY)
            nested_sizer = wx.BoxSizer(wx.VERTICAL)
            self.labelthing = wx.StaticText(panel, label="Object name: %s LOC: %s Method amount: %s Mean: %s"%(i[0], i[1], i[2], i[3]))
            nested_sizer.Add(self.labelthing, 0, wx.ALL, 5)

            self.sizeDrop = wx.ComboBox(panel,
                          size=wx.DefaultSize,
                          choices=lista)
            nested_sizer.Add(self.sizeDrop, 0, wx.ALL, 5)

            self.typeDrop = wx.ComboBox(panel,
                          size=wx.DefaultSize,
                          choices=lista)
            nested_sizer.Add(self.typeDrop, 0, wx.ALL, 5)
            panel.SetSizer(nested_sizer)

            #self.widgetMaker(self.sizeDrop, self.typeDrop)
            sizerControl.Add(panel, 1, wx.EXPAND, 5)

    def widgetMaker(self, widget1, widget2):
        widget1.Bind(wx.EVT_COMBOBOX, self.onSelect)
        widget2.Bind(wx.EVT_COMBOBOX, self.onSelect)

    def onSelect(self, event):
        #wait for the both dropdown list values, then do stuff
        pass

    def menu(self):
        #do other stuff too
        self.content = [['foo1', 1 , 'bar1', 1],['foo2', 1 , 'bar2', 1]]

if __name__ == "__main__":
    app = wx.App(False)
    frame = GUI(None, -1, "")
    app.MainLoop()

rawDescription: generating buttons after a if statement in wxPython

description: Generating buttons after a if statement in wxPython


code:
class MyException(Exception):
    """Expect a custom message here."""
    def __init__(self, err_msg):
        super(MyException, self).__init__(err_msg)
        self.err_msg = err_msg

    def __str__(self):
        return self.err_msg

def CustomExceptionA(MyException):
    pass

def CustomExceptionB(MyException):
    pass

rawDescription: Custom Python Exceptions: Different name but same task


code:
import numpy as np

no_index_df = df.reset_index()
no_index_df['LONGITUDE'] = no_index_df['LONGITUDE'].apply(lambda x: [e for e in range(0, 361, longitude_bin) if e <= x][-1])
no_index_df['LATITUDE'] = no_index_df['LATITUDE'].apply(lambda x: [e for e in range(-90, 91, latitude_bin) if e <= x][-1])

avg_data = no_index_data.groupby(
    ['DATETIME', 'PLATFORM', 'OBTYPE', 'LONGITUDE', 'LATITUDE', 'PRESSURE']
).mean()

rawDescription: Averaging geo data in 2D with pandas

description: Averaging geo data in 2D with pandas


code:
from IPython.display import display, Image

path1 = "/some/path/to/image1.png"
path2 = "/some/path/to/image2.png"

for path in path1, path2:
    img = Image(path)
    display(img)

rawDescription: image does not display in ipython

description: Image does not display in ipython


code:
from time import sleep
import datetime
sleep(60*(60-datetime.datetime.now().minute))
while True:
    do_smth()
sleep(60*60)

rawDescription: Exectue function every one hour in Python


code:
pathToWin32Environment = os.getcwd() + "/environment-win32/libmagic/"
pathToDll = pathToWin32Environment + "magic1.dll"
if not os.path.exists(pathToDll):
    #Give up if none of the above succeeded:
    raise Exception('Could not locate ' + pathToDll)
curr_dir_before = os.getcwd()
os.chdir(pathToWin32Environment)
libmagic = ctypes.CDLL('magic1.dll')
os.chdir(curr_dir_before)

rawDescription: python cdll can't find module

description: Python cdll can't find module


code:
p = datetime.datetime.strptime("23:59", "%H:%M")
p = p.replace(year=2011)
p

rawDescription: Problem setting time.struct_time properties in Python


code:
from numpy import *
def f(x):
    # Takes a complex-valued vector of size 2 and outputs a complex-valued vector of size 2
    return [x[0]-3*x[1]+1j+2, x[0]+x[1]]  # <-- for example

def real_f(x1):
    # converts a real-valued vector of size 4 to a complex-valued vector of size 2
    # outputs a real-valued vector of size 4
    x = [x1[0]+1j*x1[1],x1[2]+1j*x1[3]]
    actual_f = f(x)
    return [real(actual_f[0]),imag(actual_f[0]),real(actual_f[1]),imag(actual_f[1])]

rawDescription: Finding complex roots from set of non-linear equations in python


rawDescription: Python is this a string or a string array?


code:
import sys
from subprocess import Popen, PIPE

# populate list of arguments
args = ["mytool.py"]
for opt, optname in zip("-a -x -p".split(), "address port pass".split()):
    args.extend([opt, str(servers[server][optname])])
args.extend("some additional command".split())

# run script
p = Popen([sys.executable or 'python'] + args, stdout=PIPE)
# use p.stdout here...
p.stdout.close()
p.wait()

rawDescription: Passing Variables to Subprocess.Popen

description: Passing Variables to Subprocess.Popen


code:
def Map(L):
    ret = 0;
    for i in range(5000):
        ret += len(L)
        ret %= 50
    return ret

def Main():
    pool = Pool()
    lst = [random.sample(range(1, 100), random.randint(1, 50)) for i in repeat(None, 100000)]

    print("Start")
    start_time = time.time()
    #...

rawDescription: Multi-process map-reduce on python 3.x/Windows 7 running on a single core


code: df = pd.read_excel('new.xlsx', dayfirst=True)

rawDescription: How to read_excel with a dayfirst condition?

description: Read_excel with a dayfirst condition


code:
logline = 'Feb 26 14:20:04 laptop kernel: [19.392640] ip_tables: (C) 2000-2006 Netfilter Core Team'
logline.split(' ')[0:4]

rawDescription: Separate the fields in python

description: Separate the fields in python


code: r'The file (.+?) in successfully uploaded'

rawDescription: python match variable text using regular expression

description: Python match variable text using regular expression


code: OutputList = [xs + ('TestStr',) for xs in List]

rawDescription: Add string to end of every tuple in a list of tuples


code:
...
publication = form.save()
#assuming that these records are in order! They may not be
order_idx = 0
for author in request.POST.getlist('authors'):
    authorship = Authorship(author=author, publication=publication, ordering=order_idx)
    authorship.save()
    order_idx += 1

rawDescription: Django: saving a ModelForm with custom many-to-many models


code:
SOUTH_MIGRATION_MODULES = {
    'eav': 'ignore',
}

rawDescription: django-eav and south

description: Django-eav and south


code: individual_bytes = struct.unpack("BB", struct.pack("<H", 1024))

rawDescription: Converting int to byte streams in python


code:
@register.filter
def alignboxes(boxes, cls):

    r = ""
    i = 0
    for box in boxes.field.choices.queryset:
        checked = "checked=checked" if i in boxes.form.initial[boxes.name] else ""
        r += "<label for=\"id_%s_%d\" class=\"%s\"><input type=\"checkbox\" name=\"%s\" value=\"%s\" id=\"id_%s_%d\" %s /> %s</label>\n" % (
            boxes.name,
            i,
            cls,
            boxes.name,
            box.pk,
            boxes.name,
            i,
            checked,
            box.name
        )
        i = i + 1

    return r

rawDescription: How to get a template tag to auto-check a checkbox in Django

description: Get a template tag to auto-check a checkbox in Django


code:
def pytest_generate_tests(metafunc):
    [...]
    if warning_condition:
        metafunc.config._warn("Warning condition encountered.")
    [...]

rawDescription: How do I write to the console from a pytest plugin during the collection phase?

description: Write to the console from a pytest plugin during the collection phase


code:
import random
choices = set(["salad", "steak", "soup"])
rand_choice = random.choice(choices)

# do stuff with the choice

rawDescription: How can I search random variables that I put into the code? Python

description: Search random variables that I put into the code? Python


code:
ps = subprocess.Popen(('ps', '-A'), stdout=subprocess.PIPE)
output = subprocess.check_output(('grep', 'process_name'), stdin=ps.stdout)
ps.wait()

rawDescription: Python subprocess command with pipe

description: Python subprocess command with pipe


code: d[:,None,None] * c

rawDescription: mutiplying an array of matrices with a vector

description: Mutiplying an array of matrices with a vector


code:
# map applies str to the outputted list
order_type = map(str,form.cleaned_data['order_type'])
if len(order_type) > 1:
    delineated = ', a '.join(order_type[0:-1])
    # You are free to include or omit the oxford comma
    # ... unless you feel otherwise.
    order_type = 'a {0}, and a {1}'.format(delineated,order_type[-1])
else:
    order_type = 'a {0}'.format(order_type[0])

rawDescription: Display 'readable' list for output of MultipleChoiceField in email subject


code:
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *

import sys
pyt_path = r'C:\Program Files (x86)\IronPython 2.7\Lib'
sys.path.append(pyt_path)
import os

# Import DocumentManager and TransactionManager
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

doc = DocumentManager.Instance.CurrentDBDocument
uiapp = DocumentManager.Instance.CurrentUIApplication
app = uiapp.Application

clr.ClearProfilerData()
uiPath = r'C:\Program Files\Autodesk\Revit 2016\RevitAPIUI.dll'
clr.AddReferenceToFileAndPath(uiPath)

from Autodesk.Revit.UI import *

def pickSomething():
    from Autodesk.Revit.UI.Selection import ObjectType
    picked = uiapp.ActiveUIDocument.Selection.PickObject(ObjectType.Element)
    return picked

#Assign your output to the OUT variable.
OUT = pickSomething()

rawDescription: Postable Commands from Revit API using Dynamo for Revit(2015)


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

fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
ax.grid(False)

r = np.arange(0,1,0.001)
theta = 2*2*np.pi*r

ax.plot(theta,r)
plt.show()

rawDescription: Polar plot without grid in matplotlib

description: Polar plot without grid in matplotlib


code: os.system("screen -dmS RealmD top")

rawDescription: Executing *nix binaries in Python

description: Executing *nix binaries in Python


code:
import csv

# collect the fruits of both CSV files
with open('c:/Test/test1.csv', 'rb') as test1:
    reader = csv.reader(test1)
    next(reader, None)  # ignore header
    test1_fruit = set(row[3] for row in reader)
with open('c:/Test/test2.csv', 'rb') as test2:
    reader = csv.reader(test2)
    next(reader, None)  # ignore header
    test2_fruit = set(row[0] for row in reader)

# Read all the fruit from Append
with open("C:/Test/Append.txt", 'r') as append:
    fruit = set(line.strip() for line in append if line.strip())

# add all fruit that are in both test1 and test2
fruit |= test1_fruit & test2_fruit

# write out a sorted list
with open("C:/Test/Append.txt", 'w') as append:
    append.write('\n'.join(sorted(fruit)))

rawDescription: Compare values from two csv files, append value to text file


code:
import re

string = "2x83u0x7u8i9lkueieueue8"

print(sum(map(int, re.findall("\d+", string))))

rawDescription: Sum of digits in a string to take care of whole number


code:
from urlparse import urljoin
url = "https://www.example.com/thing1/thing2/thing3"
urljoin(url, "thing4")
urljoin(url + "/", "thing4")

rawDescription: How do I get urljoin to work as expected in Python?

description: Get urljoin to work as expected in Python


code:
arrow.get(timezone='UTC')
str(arrow.get())
arrow.get(tz='UTC').format('YYYY-MM-DDTHH:mm:ss.SSS') + 'Z'

rawDescription: Date String conversion in Python and momentjs


code:
import numpy as np
complete_matrix = np.array([
    [0, 1, 2, 4],
    [1, 0, 3, 5],
    [2, 3, 0, 6],
    [4, 5, 6, 0]])
np.argmax(np.mean(complete_matrix, axis=1))

rawDescription: Finding the row with the highest average in a numpy array


code:
import pywintypes, win32file, win32con
def changeFileCreationTime(fname, newtime):
    wintime = pywintypes.Time(newtime)
    winfile = win32file.CreateFile(
        fname, win32con.GENERIC_WRITE,
        win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
        None, win32con.OPEN_EXISTING,
        win32con.FILE_ATTRIBUTE_NORMAL, None)

    win32file.SetFileTime(winfile, wintime, None, None)

    winfile.close()

rawDescription: How do I change the file creation date of a Windows file from Python?

description: Change the file creation date of a Windows file from Python


code:
import shlex
shlex.split('echo "hello bob"')

rawDescription: Splitting strings in complicated ways?

description: Splitting strings in complicated ways


code:
import maya.OpenMaya as OpenMaya
from pymel.core import *

geo = PyNode('pSphere1')
pos = PyNode('locator1').getRotatePivot(space='world')

nodeDagPath = OpenMaya.MObject()
try:
    selectionList = OpenMaya.MSelectionList()
    selectionList.add(geo.name())
    nodeDagPath = OpenMaya.MDagPath()
    selectionList.getDagPath(0, nodeDagPath)
except:
    warning('OpenMaya.MDagPath() failed on %s' % geo.name())

mfnMesh = OpenMaya.MFnMesh(nodeDagPath)

pointA = OpenMaya.MPoint(pos.x, pos.y, pos.z)
pointB = OpenMaya.MPoint()
space = OpenMaya.MSpace.kWorld

util = OpenMaya.MScriptUtil()
util.createFromInt(0)
idPointer = util.asIntPtr()

mfnMesh.getClosestPoint(pointA, pointB, space, idPointer)
idx = OpenMaya.MScriptUtil(idPointer).asInt()

faceVerts = [geo.vtx[i] for i in geo.f[idx].getVertices()]
closestVertex = None
minLength = None
for v in faceVerts:
    thisLength = (pos - v.getPosition(space='world')).length()
    if minLength is None or thisLength < minLength:
        minLength = thisLength
        closestVertex = v
select(closestVertex)

rawDescription: Find closest point on mesh in specific axis (maya)


code:
n = int(input('How many steps? '))

print("__") # top

for i in range(n-1):
    print("  "*(i+1) + "|" + "_")

print("__" * n + "|") # last step

rawDescription: Python - program to print steps

description: Python - program to print steps


code:
X = np.array([(1, 2, 3.5)], dat_dtype)
S = np.vstack((S[:,None], X, X, X))

rawDescription: Creating a numpy matrix with dtypes

description: Creating a numpy matrix with dtypes


code:
from __future__ import print_function

from sys import stdout

from twisted.python.log import startLogging
from twisted.internet import reactor
from twisted.internet.protocol import DatagramProtocol

class SomeUDP(DatagramProtocol):
    def datagramReceived(self, datagram, address):
        print(u"Got a datagram of {} bytes.".format(len(datagram)))

    def sendFoo(self, foo, ip, port):
        self.transport.write(
            (u"Foo datagram: {}".format(foo)).encode("utf-8"),
            (ip, port))

class SomeSender(object):
    def __init__(self, proto):
        self.proto = proto

    def start(self):
        reactor.callLater(3, self._send)

    def _send(self):
        self.proto.sendFoo(u"Hello or whatever", b"127.0.0.1", 12345)
        self.start()

startLogging(stdout)

proto = SomeUDP()
reactor.listenUDP(12345, proto)

SomeSender(proto).start()

reactor.run()

rawDescription: Python asyncore UDP server

description: Python asyncore UDP server


rawDescription: Non-greedy operator on re.sub

description: Non-greedy operator on re.sub


code:
def click_and_drag(locator, x_from, y_from, x_to, y_to):
    element = driver.find_element_by_css_selector(locator)
    actions.move_to_element(element)
    actions.move_by_offset(x_from, y_from)
    actions.click_and_hold(on_element=None)
    actions.move_by_offset(x_to, y_to)
    actions.release(on_element=None)
    actions.perform()

rawDescription: Using (Python) Webdriver to select text without using an element (i.e. click and drag to highlight from one set of coordinates to another set)


code:
import decimal

decimal.getcontext().prec = 46 # Change 46 to the precision you want.
result = decimal.Decimal(1.6) / decimal.Decimal(7)

print(result)
Decimal('0.2285714285714285841168345671446461762700762068')

rawDescription: Compare between two very Big floating point number


rawDescription: Python - Spawn/Run a New Process Using Shell's stdin and stdout


code: sorted(L, reverse=True)

rawDescription: rank lists in python by their elements

description: Rank lists in python by their elements


rawDescription: Using scipy sparse matrices to solve system of equations


code:
def put(d, keys, item):
    if "." in keys:
        key, rest = keys.split(".", 1)
        if key not in d:
            d[key] = {}
        put(d[key], rest, item)
    else:
        d[keys] = item

def get(d, keys):
    if "." in keys:
        key, rest = keys.split(".", 1)
        return get(d[key], rest)
    else:
        return d[keys]

rawDescription: Checking a Dictionary using a dot notation string


code:
def rem0(data):
    for x in data:
        yield x.lstrip('0').replace(".0", ".")

rawDescription: Python: Mulitple yield statements in generator


code:
is_even = lambda i: i % 2 == 0
even = [i for i in range(1, n) if is_even(i)]

rawDescription: Confusion about efficiencies after evaluating list comprehension performance


code:
def entry_icon_event(self, widget, icon, event):
    if icon == gtk.ENTRY_ICON_PRIMARY:
        ...
    elif icon == gtk.ENTRY_ICON_SECONDARY:
        ...

rawDescription: Differentiate gtk.Entry icons

description: Differentiate gtk.Entry icons


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

histogram_data = np.random.rand(1000)
heatmap_data = np.random.rand(10, 100)

# Set up figure and axes
fig = plt.figure()
fig.suptitle("These are my two plots")
top_ax = fig.add_subplot(211) #2 rows, 1 col, 1st plot
bot_ax = fig.add_subplot(212) #2 rows, 1 col, 2nd plot
# This is the same as doing 'fig, (top_ax, bot_ax) = plt.subplots(2)'

# Histogram
weights = np.ones_like(histogram_data) / histogram_data.shape[0]
hist, bins = np.histogram(histogram_data, bins=50, weights=weights)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2

# Use top_ax to modify anything with the histogram plot
top_ax.bar(center, hist, align='center', width=width)
# ax.text(x, y, str). Make sure x,y are within your plot bounds ((0, 1), (0, .5))
top_ax.text(0.5, 0.5, "Here is text on the top plot", color='r')

# Heatmap
heatmap_params = {'cmap':plt.cm.Blues, 'alpha':0.8, 'vmin':0, 'vmax':1}

# Use bot_ax to modify anything with the heatmap plot
heatmap = bot_ax.pcolor(heatmap_data, **heatmap_params)
cbar = fig.colorbar(heatmap, shrink=0.8, aspect=10, fraction=.1,pad=.01)

# See how it looks
plt.show()

rawDescription: Laying out several plots in matplotlib + numpy


code:
user_input = "Kean,Peter,john"
user_input.split(',')

rawDescription: how to convert strings given by the user into a list

description: Convert strings given by the user into a list


code:
import sys

with open(sys.argv[1]) as test_cases:
    for test in test_cases:
        if test:
            team_supporters = {}
            for nation, nation_teams in enumerate(test.strip().split("|"), start=1):
                for team in map(int, nation_teams.split()):
                    team_supporters.setdefault(team, []).append(nation)
            print(*("{}:{};".format(team, ",".join(map(str, sorted(nations))))
                    for team, nations in sorted(team_supporters.items())))

rawDescription: Codeeval Challenge 230: Football, Answer Only Partially Correct


code:
import os
str = 'getcwd()'
eval(str,os.__dict__)

rawDescription: Importing a python module into a dict (for use as globals in execfile())?


code:
sr=session.xenapi.SR.get_by_name_label("DVD drives")
record_dvd=session.xenapi.SR.get_record(sr[0])
VDI_dvd=record_dvd["VDIs"]
vbdconnectcd={'VDI':VDI_dvd[0],
                  'VM':VM_ref,
                  'userdevice':"1",
                  'mode':"RO",
                  'type':"cd",
                  'bootable':True,
                  'unpluggable':True,
                  'empty':False,
                  'other_config':{},
                  'qos_algorithm_type':'',
                  'qos_algorithm_params':{}}
vbdref1=session.xenapi.VBD.create(vbdconnectcd)

rawDescription: How to add DVD drive to VM in XenServer using Python

description: Add DVD drive to VM in XenServer using Python


code:
with open('rooms') as f:
    chunks = f.read().split('\n\n')

people_by_id = {}

for chunk in chunks:
    data = dict(row.split('=', 1) for row in chunk.split('\n'))
    people_by_id[data['id']] = data
    del data['id']

def get_person_by_id(id):
    return people_by_id.get(id)

rawDescription: Finding a line in a file then reading next few lines in Python


rawDescription: How to a turn a list of strings into complex numbers in python?

description: A turn a list of strings into complex numbers in python


code:
class Test:
   @staticmethod
   def call(method):
      getattr(Test, method)()

   @staticmethod
   def method1():
      print('method1')

   @staticmethod
   def method2():
      print('method2')

Test.call("method1")

rawDescription: Python: Invoke class & class methods by name with using eval


code: fields = {key: [] for key in 'ABCD'}

rawDescription: How to create multiple (but individual) empty lists in Python?

description: Create multiple (but individual) empty lists in Python


code:
from pandas import *
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime as dt

#The following part is just for generating something similar to your dataframe
date1 = "20140605"
date2 = "20140606"

d = {'date': Series([date1]*5 + [date2]*5), 'template': Series(range(5)*2),
'score': Series([random() for i in range(10)]) }

data = DataFrame(d)
#end of dataset generation

fig, ax = plt.subplots()

for temp in range(5):
    dat = data[data['template']==temp]
    dates =  dat['date']
    dates_f = [dt.datetime.strptime(date,'%Y%m%d') for date in dates]
    ax.plot(dates_f, dat['score'], label = "Template: {0}".format(temp))

plt.xlabel("Date")
plt.ylabel("Score")
ax.legend()
plt.show()

rawDescription: Plotting multiple line graph using pandas and matplotlib


code:
for sh in self.doc.Worksheets: #explicitly specify print areas and titles
    for name in sh.Names:
        if name.Name.endswith("!Print_Area"):
            sh.PageSetup.PrintArea = name.RefersTo
        elif name.Name.endswith("!Print_Titles"):
            #protect comma symbol in sheet name
            chunks = name.RefersTo.replace(sheet.Name, "[sheet_name]").split(",")
            chunks = [i.replace("[sheet_name]", sheet.Name) for i in chunks]
            if len(chunks) == 1:
                try: sh.PageSetup.PrintTitleColumns = chunks[0]
                except: sh.PageSetup.PrintTitleRows = chunks[0]
            else: sh.PageSetup.PrintTitleColumns, sh.PageSetup.PrintTitleRows = chunks

rawDescription: Excel COM object ignores print area

description: Excel COM object ignores print area


code:
from Tkinter import *

class SampleApp(Tk):

    def __init__(self, s):

        Tk.__init__(self)
        self.title("GUI")
        x = 200
        y = s*30
        self.geometry(str(x) + "x" + str(y))

        for i in range(1, s+1):

            self.button = Button(self, text="Button " + str(i))
            self.button.pack()

app = SampleApp(5)
app.mainloop()

rawDescription: Dynamic number of input boxes Tkinter?

description: Dynamic number of input boxes Tkinter


code:
if my_dict.setdefault(my_key, my_value) != my_value:
     raise ValueError

rawDescription: Insert into dictionary or fail if key already present without hashing twice


code:
#define PY_MAJOR_VERSION        2
#define PY_MINOR_VERSION        7

rawDescription: PyObject_AsReadBuffer porting issue

description: PyObject_AsReadBuffer porting issue


code:
import csv
import os

for root, dirs, files in os.walk(BASEDIR):
    for filename in files:
        basename, ext = os.path.splitext(filename)
        if ext.lower() != ".csv":
            continue
        path = os.path.join(root, filename)
        with open(path) as f:
            reader = csv.DictReader(f)
            for row in reader:
                if row['newColor'] == 'blue':
                    print(row)  # maybe? What's your output?

rawDescription: Find a .csv file in directory with header newColor value = 'blue' and return other columns(oldColor, length)


code:
def flatten_list(l):
    new_l = []
    for item in l:
        if type(item) == type([]):
            new_l += flatten_list(item)
        else:
            new_l.append(item)
    return new_l

rawDescription: Python: How to put unknow Multidimentional array in 1D array


code:
class LockableDict(dict):
    def __init__(self, *args, **kwargs):
        from threading import Lock
        self.lock = Lock()
        dict.__init__(self, *args, **kwargs)

    @property
    def locked(self):
        return self.lock.locked()

    def lock(self):
        self.lock.acquire()

    def unlock(self):
        self.lock.release()

# and then
my_dict = LockableDict({1:2, 3:4})
my_dict.lock()
# do modifications
my_dict.unlock()

rawDescription: In python (django) how can I stop access to a global dictionary data structure when it's being updated?


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

from PyQt4 import QtGui, QtCore

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

    def animate(self):
        animation = QtCore.QPropertyAnimation(self, "size", self)
        animation.setDuration(3333)
        animation.setStartValue(QtCore.QSize(self.width(), self.height()))
        animation.setEndValue(QtCore.QSize(333, 333))
        animation.start()

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.setBrush(QtGui.QBrush(QtCore.Qt.red))
        painter.drawEllipse(0, 0, self.width() - 1, self.height() - 1)
        painter.end()

    def sizeHint(self):
        return QtCore.QSize(111, 111)

if __name__ == "__main__":
    import sys

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

    main = MyWindow()
    main.show()
    main.animate()

    sys.exit(app.exec_())

rawDescription: My paintEvent method is not painting anything with PySide


code:
import sys

filename = sys.argv[1]
fp = open(filename)
data = fp.read()
words = data.split()
fp.close()

unwanted_chars = ".,-_ (and so on)"
wordfreq = {}
for raw_word in words:
    word = raw_word.strip(unwanted_chars)
    if word not in wordfreq:
        wordfreq[word] = 0
    wordfreq[word] += 1

rawDescription: Counting word frequency and making a dictionary from it


rawDescription: determining repeated values in numpy array and adding them in another column python

description: Determining repeated values in numpy array and adding them in another column python


rawDescription: Pairing data in python pandas

description: Pairing data in python pandas


code:
df = df.stack().to_frame().T
df.columns = ['{}_{}'.format(*c) for c in df.columns]

rawDescription: Convert a dataframe with multiple rows into one row using pandas?


code:
from robot.api import TestSuite

suite = TestSuite('Activate Skynet')
suite.imports.library('OperatingSystem')
test = suite.tests.create('Should Activate Skynet', tags=['smoke'])
test.keywords.create('Set Environment Variable', args=['SKYNET', 'activated'], type='setup')
test.keywords.create('Environment Variable Should Be Set', args=['SKYNET'])

rawDescription: Using the robot framework in python

description: Using the robot framework in python


code:
class A(object):
    def __init__(self, init=True):
        if init:
            self.field1 = generate_a_list_of_ints()
    def __copy__(self):
        result = A(init=False)
        result.fiel1[:] = self.field1[:]
        return result

rawDescription: How to skip the initialization when copying objects in python?

description: Skip the initialization when copying objects in python


code:
import json

class RawJson(unicode):
    pass

# patch json.encoder module
for name in ['encode_basestring', 'encode_basestring_ascii']:
    def encode(o, _encode=getattr(json.encoder, name)):
        return o if isinstance(o, RawJson) else _encode(o)
    setattr(json.encoder, name, encode)

print(json.dumps([1, RawJson(u'["abc", 2]'), u'["def", 3]']))
# -> [1, ["abc", 2], "[\"def\", 3]"]

rawDescription: In Python, have json not escape a string


code:
from random import shuffle
x = [[i] for i in range(10)]
shuffle(x)

# print x  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
# of course your results will vary

rawDescription: Shuffling a list of objects in python

description: Shuffling a list of objects in python


code:
from os.path import exists
if exists(my_file_path):
    my_file = open(my_file_path, 'w+')

rawDescription: In Python, how to open a file for writing, but do not create it if the file does not exist?


code:
ADict = dict((x.get('key'), x.find('A').text) for x in fields)
BDict = dict((x.get('key'), x.find('B').text) for x in fields)

rawDescription: Is this the fastest way to build dict?

description: Is this the fastest way to build dict


rawDescription: How to select DataFrame columns based on partial matching?

description: Select DataFrame columns based on partial matching


code: insert_client = db.insert('clients', **dict)

rawDescription: Insert multiples values of dict into db

description: Insert multiples values of dict into db


code:
import pandas as pd

df = pd.read_csv('abc.csv')

#filter dataframe
males = df.loc[(df['Sex'] == 'male') & (df['Alive'] == 1)]
females  = df.loc[(df['Sex'] == 'female') & (df['Alive'] == 1)]

#get number of rows
len(males.index)
len(females.index)

rawDescription: Multiple IF conditions on dataframe columns in Python


code: concat_str = '-' * len(title)

rawDescription: How to properly generate a variable string pattern in Python

description: Properly generate a variable string pattern in Python


code:
import heapq

def tph():
    tg = triangle_generator()
    pg = pentagonal_generator()
    hg = hexagonal_generator()
    count = 0
    last_n = 0
    for n in heapq.merge(tg, pg, hg):
        if n == last_n:
            count += 1
        else:
            count = 1

        if count == 3:
            print(n)

        last_n = n

rawDescription: Project Euler: 45 (or More Python Generators)


code:
rows, cols, centerx, centery = 6, 6, 2.5, 2.5
[p[1:] for p in sorted((((x - centerx) ** 2 + (y - centery) ** 2, x, y)
                        for x in xrange(rows) for y in xrange(cols)))]

rawDescription: Ordering cells by their distance from center cell(s)


code:
with open('test.hgx') as f:  lines = f.read().splitlines()
with open('test.hgx', 'w') as f:
  for line in lines:
    if line.startswith('height') or line.startswith('RATIO'):
      f.write(line.rsplit(' ', 1)[0] + ' 8\n')
    else:
      f.write(line + '\n')

rawDescription: How to search a word in a file and replace the entire line with a new line?

description: Search a word in a file and replace the entire line with a new line


code:
import os

try:
    with open("/tmp/myproc.pid") as pidfile:
        pidfile.write(str(os.getpid()))
    main()
finally:
    os.remove("/tmp/myproc.pid")

rawDescription: scheduling jobs using python apscheduler

description: Scheduling jobs using python apscheduler


rawDescription: how to use a flag to return only one group using findall- Python

description: Use a flag to return only one group using findall- Python


code:
s = ' '.join(['5bloc', 'ksoft', 'extte', 'st'])
print(s)

rawDescription: Python - how to remove commas, square brackets and quotation marks from list


code:
import csv

with open('/Users/stephan/Desktop/cities.csv', "r") as f:
    mycsv = csv.DictReader(f)
    for row in mycsv:
        for col in FIELDS:
            try:
                print(row[col])
            except KeyError:
                pass

rawDescription: Extracting Columns of a .csv file and finding their index


rawDescription: Convert a vector to a mask matrix using numpy


code:
import matplotlib.pyplot as plt
import numpy as np
np.random.seed(1977)

# Generate some very noisy but interesting data...
num = 1e7
x = np.linspace(0, 10, num)
y = np.random.random(num) - 0.5
y.cumsum(out=y)
y += 0.3 * y.max() * np.random.random(num)

fig, ax = plt.subplots()

# Wrap the array into a 2D array of chunks, truncating the last chunk if
# chunksize isn't an even divisor of the total size.
# (This part won't use _any_ additional memory)
chunksize = 10000
numchunks = y.size // chunksize
ychunks = y[:chunksize*numchunks].reshape((-1, chunksize))
xchunks = x[:chunksize*numchunks].reshape((-1, chunksize))

# Calculate the max, min, and means of chunksize-element chunks...
max_env = ychunks.max(axis=1)
min_env = ychunks.min(axis=1)
ycenters = ychunks.mean(axis=1)
xcenters = xchunks.mean(axis=1)

# Now plot the bounds and the mean...
ax.fill_between(xcenters, min_env, max_env, color='gray',
                edgecolor='none', alpha=0.5)
ax.plot(xcenters, ycenters)

fig.savefig('temp.png', dpi=600)

rawDescription: Matplotlib Agg Rendering Complexity Error


code:
from selenium import webdriver

fp = webdriver.FirefoxProfile()
fp.set_preference('app.update.auto', False)
fp.set_preference('app.update.enabled', False)
browser = webdriver.Firefox(firefox_profile=fp)

rawDescription: How to avoid WebDriverException caused by Firefox updates

description: Avoid WebDriverException caused by Firefox updates


code:
from itertools import product
list(product('abcdef', repeat=2))

rawDescription: Permutation with redundant overlaps? Python


rawDescription: Python using exec with custom globals

description: Python using exec with custom globals


code:
s = "hello cats"
print(re.search(r"(he)l(lo)",s).groups())

rawDescription: Why does this return an empty tuple?

description: Why does this return an empty tuple


code:
#!python3

class Context:
    pass

def f1(context):
    a = context.a
    print("a:", a)

def f2(context):
    b = context.b
    print("b:", b)

c = Context()
c.a = 1
c.b = "alfalfa"

f1(c)
f2(c)

rawDescription: python: how to pass a context to a function

description: Python: how to pass a context to a function


code:
import xml.etree.ElementTree as ET
tree = ET.fromstring('<part> <part_id>151</part_id> <part_name>BBa_B0034</part_name>     <part_short_name>B0034</part_short_name> <part_short_desc>RBS (Elowitz 1999) -- defines RBSefficiency</part_short_desc> <part_type>RBS</part_type> <release_status>Released HQ 2013</release_status> <sample_status>In stock</sample_status> <part_results>Works</part_results> <part_nickname/> <part_rating>1</part_rating> <part_url>http://parts.igem.org/Part:BBa_B0034</part_url> <part_entered>2003-01-31</part_entered></part>')
tree.findall('./part_name')[0].text

rawDescription: Parsing XML node values with ElementTree in Python


code:
def abspath(path):
    """Return an absolute path."""
    if not isabs(path):
        if isinstance(path, _unicode):
            cwd = os.getcwdu()
        else:
            cwd = os.getcwd()
        path = join(cwd, path)
    return normpath(path)

rawDescription: Why does python have os.path.curdir

description: Why does python have os.path.curdir


code:
def partial_dict_index(dicts, dict_part):
    for i, current_dict in enumerate(dicts):
        # if this dict has all keys required and the values match
        if all(key in current_dict and current_dict[key] == val
                for key, val in dict_part.items()):
            return i
    raise ValueError("...")

rawDescription: Find the index of a partial dictionary element in a list


code:
def foo(max_depth = 10, cur_depth=0):
    if cur_depth >= max_depth:
        return BASE_CASE

    else:
        return foo(max_depth, cur_depth+1)

rawDescription: Timeout for recursion Python

description: Timeout for recursion Python


code:
import numpy as np
k = np.array([True, False, False, True, False])
np.where(k, 2, 5)

rawDescription: Convert a numpy boolean array to int one with distinct values


code:
profile.set_preference('browser.helperApps.neverAsk.saveToDisk',
                       'application/pdf,text/csv')

rawDescription: Python, Selenium, download all MIME types


code:
from rpy2.robjects.packages import importr
e1071 = importr('e1071')

from rpy2.robjects.conversion import py2ri

# your model's data are in 'm_data'
# here conversion is happening
r_m_data = py2ri(m_data)

for test_data in many_test_data:
    # r_m_data is already a pointer to an R data structure
    # (it was converted above - no further copying is made)
    res = e1071.knn(r_m_data, test_data)

rawDescription: model as r function's parameter, when calling the r function using rpy2 from multithreads

description: Model as r function's parameter, when calling the r function using rpy2 from multithreads


code:
from itertools import tee

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

def cons(x, xs):
    yield x
    yield from xs

def take(count, l):
    it = iter(l)

    for i in range(count):
        yield next(it)

def lazy_yield_from(get_iterable):
    yield from get_iterable()

infinite_fibonacci, _if = tee(
    cons(1, cons(1, lazy_yield_from(lambda: (a + b for a, b in pairwise(_if))))))

print(list(take(5, infinite_fibonacci)))

rawDescription: Is pairwise from itertools recipes always giving the same results as zip(a, a[1:])?


code:
allkeys = frozenset().union(*L)
for i in L:
   for j in allkeys:
       if j not in i:
           i[j]=0
L

rawDescription: Adding missing keys in dictionary in Python


code:
class PrivateList(Sequence):

    def __init__(self):
        self._list = []

    def __getitem__(self, index):
        return self._list[index]

    def __len__(self):
        return len(self._list)

class Calendar:
    def __init__(self):
        self._dict = defaultdict(PrivateList)

    def add_event(self, date, event):
        self._dict[date]._list.append(event.id)

    def get_event_ids(self, date):
        return self._dict[date]

rawDescription: Return mutable attribute as inmutable object in Python


code:
from distutils.core import setup
import py2exe, sys, os
from glob import glob

sys.argv.append('py2exe')
data_files = [("Microsoft.VC90.CRT", glob(r'C:\Program Files\Microsoft Visual Studio 9.0\VC\redist\x86\Microsoft.VC90.CRT\*.*'))]
setup(
    data_files=data_files,
    windows = ["cashflowSim.py"],
    options={
       "py2exe":{"includes":["dumbdbm"]}},
       zipfile = None
)

rawDescription: python shelve ... bsddb deprecated ... how to get shelve to use another database?

description: Python shelve ... bsddb deprecated ... how to get shelve to use another database


code:
strings
re.match(r"(RED[0-9]+)", strings[0])
re.findall(r"(RED[0-9]+)", strings[0])
re.findall(r"(RED[0-9]+)", strings[1])
re.findall(r"(RED[0-9]+)", strings[2])
re.search(r"(RED[0-9]+)", strings[0])

rawDescription: How to retrieve substring form a string using regular expression in python

description: Retrieve substring form a string using regular expression in python


code:
import matplotlib
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
rect1 = matplotlib.patches.Rectangle((-200,-100), 400, 200, color='yellow')
rect2 = matplotlib.patches.Rectangle((0,150), 300, 20, color='red')
rect3 = matplotlib.patches.Rectangle((-300,-50), 40, 200, color='#0099FF')
circle1 = matplotlib.patches.Circle((-200,-250), radius=90, color='#EB70AA')
ax.add_patch(rect1)
ax.add_patch(rect2)
ax.add_patch(rect3)
ax.add_patch(circle1)
plt.xlim([-400, 400])
plt.ylim([-400, 400])
plt.show()

rawDescription: How do I set color to Rectangle in Matplotlib?

description: Set color to Rectangle in Matplotlib


code:
from subprocess import Popen, PIPE

p = Popen(["/path/to/FORTRAN/program"], stdin=PIPE,
          bufsize=1, close_fds=True)
p.communicate("INPUT_FILE1\r\nINPUT_FILE2")
rc = p.returncode

rawDescription: Python subprocess not executing program correctly


code:
data = { 'text': 'important text',
       'timestamp': 'an iso timestamp' }

headers = {'Content-Type': 'application/json; charset=UTF-8'}

request = tornado.httpclient.HTTPRequest(URL, method = 'PUT', headers = headers, body = simplejson.dumps(data))

response = yield Task(tornado.httpclient.ASyncHTTPClient().fetch, request)

rawDescription: Tornado PUT Request Missing Body

description: Tornado PUT Request Missing Body


code:
class SelectDateWidget(object):
  FORMAT_CHOICES = {
    '%d': [(x, str(x)) for x in range(1, 32)],
    '%m': [(x, str(x)) for x in range(1, 13)]
  }

  FORMAT_CLASSES = {
    '%d': 'select_date_day',
    '%m': 'select_date_month',
    '%Y': 'select_date_year'
  }

  def __init__(self, years=range(1930, 2014)):
    super(SelectDateWidget, self).__init__()
    self.FORMAT_CHOICES['%Y'] = [(x, str(x)) for x in years]

  def __call__(self, field, **kwargs):
    field_id        = kwargs.pop('id', field.id)
    html            = []
    allowed_format  = ['%d', '%m', '%Y']

    for format in field.format.split():
      if (format in allowed_format):
        choices     = self.FORMAT_CHOICES[format]
        id_suffix   = format.replace('%', '-')
        id_current  = field_id + id_suffix

        kwargs['class'] = self.FORMAT_CLASSES[format]
        try: del kwargs['placeholder']
        except: pass

        html.append('<select %s>' % html_params(name=field.name, id=id_current, **kwargs))

        if field.data:
            current_value = int(field.data.strftime(format))
        else:
            current_value = None

        for value, label in choices:
          selected = (value == current_value)
          html.append(Select.render_option(value, label, selected))
        html.append('</select>')
      else:
        html.append(format)
        html.append('<input type="hidden" value="'+format+'" %s></input>' % html_params(name=field.name, id=id_current, **kwargs))

      html.append(' ')

    return HTMLString(''.join(html))

rawDescription: How to render DateField with 3 selects

description: Render DateField with 3 selects


code:
def address_of_buffer(buf):
    return ctypes.addressof(ctypes.c_char.from_buffer(buf))

rawDescription: Porting Python 2 code that uses _multiprocessing


code:
from datetime import datetime, timedelta
day = '12/01/15'
date = datetime.strptime(day, '%m/%d/%y')
start_of_week = date - timedelta(days = (date.weekday() + 1) % 7)
print(start_of_week.strftime('%m/%d/%Y'))

rawDescription: Create 'week of' variable in Python

description: Create 'week of' variable in Python


code:
self.buttonGroup = QtGui.QButtonGroup(self)
for button in self.buttonBox.findChildren(QtGui.QAbstractButton):
    self.buttonGroup.addButton(button)

rawDescription: Grabbing all QPushButton in a PyQt Python ui File


code: key=lambda a: (-len(a), a)

rawDescription: Sort python list based on length, and then based on content


code:
import csv

with open(outputfilename, 'wb') as out:
    writer = csv.writer(out, delimiter='\t')
    writer.writerow(['20120305', 'xxxxx', pickle.dumps(result)])

rawDescription: python cPickle.dumps contain newlines

description: Python cPickle.dumps contain newlines


code:
import urllib2
import urllib
import urlparse

# this was the header and data strings you already had
headers = 'baz=3&foo=1&bar=2'
data = 'baz=3&foo=1&bar=2'

header_dict = dict(urlparse.parse_qsl(headers))

r = urllib2.Request('http://www.foo.com', data, headers)
resp = urllib2.urlopen(r)

rawDescription: Python: Send a POST request using just a raw string


code:
#At the beginning
import threading

#Instead of def getKeyPress()
class getKeyPress(threading.Thread):
    def run(self):
        import pygame
        pygame.init()
        global targets
        global status
        while not status:
               pygame.event.pump()
               keys = pygame.key.get_pressed()
               targets, status = processOutputs(targets, keys)
        targets = np.array(targets)
        targets = flattenMatrix(targets)
        sio.savemat('targets.mat', {'targets':targets})

#Instead of
#targetProcess = multiprocessing.Process(target=getKeyPress)
#targetProcess.daemon = True
#targetProcess.start()
gkp = getKeyPress()
gkp.start()

rawDescription: Concurrent functions running in separate process using pygame and multiprocessing


code:
clusterZip = zip(group, L)
clusterSubset = [list() for _ in xrange(np.unique(group))]
for row in clusterZip:
    c = row[0]
    v = row[1]
    clusterSubset[c].append(v)

rawDescription: Subset a list of np.array based on another array


code:
#!/usr/bin/env python
# coding: utf8
from __future__ import absolute_import, division, print_function
from collections import defaultdict
from functools import partial
from pprint import pprint

def main():
    records = [
        {
            'time': '2015/03/27',
            'author_id': 'abc_123',
            'id': '4585',
            'id_number': 123
        },
        {
            'time': '2015/03/30',
            'author_id': 'abc_123',
            'id': '7776',
            'id_number': 122
        },
        {
            'time': '2015/03/22',
            'author_id': 'abc_123',
            'id': '8449',
            'id_number': 111
        },
        {
            'time': '2012/03/30',
            'author_id': 'def_456',
            'id': '4585',
            'id_number': 90
        }
    ]

    id2record = defaultdict(partial(defaultdict, list))
    for record in records:
        merged_record = id2record[record['id']]
        for key, value in record.iteritems():
            merged_record[key].append(value)

    result = list()
    for record in id2record.itervalues():
        if len(record['id']) == 1:
            result.append(dict((k, vs[0]) for k, vs in record.iteritems()))
        else:
            record['id'] = record['id'][0]
            result.append(dict(record))

    pprint(result)

if __name__ == '__main__':
    main()

rawDescription: Merge a list of json based on a particular and combining its value into list python


code:
group1 = A[A> threshold]
group2 = A[A<=threshold]

rawDescription: Python performance, or bad usage of PIL?

description: Python performance, or bad usage of PIL


code:
x = sympy.Symbol('x')
sympy.Poly.from_list([1, -2, 1], gens=x)

rawDescription: List of coefficients to polynomial

description: List of coefficients to polynomial


rawDescription: Ending a Program Mid-Run

description: Ending a Program Mid-Run


code:
bookuser_key_name = "%s:%s" % (str(book_key.id_or_name()), str(user_key.id_or_name()))
bookuser = BookUser.get_or_insert(bookuser_key_name)
# set your values...
bookuser.put()

rawDescription: Get or Create matching Key and User (Python - App Engine)


code:
avaluos= ( Avaluo.objects
           .filter(Estatus='CONCLUIDO')
           .filter(Q(Factura='')|Q(Factura__isnull=True))
           .filter(Q(Pagado=False)|Q(Pagado__isnull=True)) )

rawDescription: Django Filter Query Solution

description: Django Filter Query Solution


code:
import numpy as np
V = np.array([vx, vz]).T      # create numpy array and transpose
V[0, 0]
V[1, 0]
V[0, 1]

rawDescription: Combining two arrays into 1 in Python

description: Combining two arrays into 1 in Python


code:
langs = OrderedDict([
    ("af_ALL", "Afrikaans"),
    ("az_ALL", "Azərbaycanca"),
    ("id_ALL", "Bahasa Indonesia"),
    ("ca_ALL", "Català"),
    ("si_ALL", "සිංහල"),
])

rawDescription: Why is my dictionary unorder in django template?


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap

data = np.array(
             [[ 0.000, 0.120, 0.043, 0.094, 0.037, 0.045],
              [ 0.120, 0.000, 0.108, 0.107, 0.105, 0.108],
              [ 0.043, 0.108, 0.000, 0.083, 0.043, 0.042],
              [ 0.094, 0.107, 0.083, 0.000, 0.083, 0.089],
              [ 0.037, 0.105, 0.043, 0.083, 0.000, 2.440],
              [ 0.045, 0.108, 0.042, 0.089, 2.440, 0.000]])
mask = np.tri(data.shape[0], k=-1)
data = np.ma.masked_where(mask, data)

vmax = 3.0
cmap = LinearSegmentedColormap.from_list('mycmap', [(0 / vmax, 'blue'),
                                                    (1 / vmax, 'white'),
                                                    (3 / vmax, 'red')]
                                        )

fig, ax = plt.subplots()
im = ax.pcolor(data, cmap=cmap, vmin=0, vmax=vmax, edgecolors='black')
cbar = fig.colorbar(im)

cbar.set_ticks(range(4)) # Integer colorbar tick locations
ax.set(frame_on=False, aspect=1, xticks=[], yticks=[])
ax.invert_yaxis()

plt.show()

rawDescription: Making a custom colormap using matplotlib in python


code:
combobox = ttk.Combobox(parent)
combobox['values'] = five_last_dirs_tuple
combobox['state'] = 'normal'

# later...

path = combobox.get()

rawDescription: Optionmenu/Entry combination in Tkinter

description: Optionmenu/Entry combination in Tkinter


code:
for filename in os.listdir(target):
    os.rename(filename, datetime.fromtimestamp(
                         os.path.getmtime(filename)).strftime(
                          '{0}-%Y-%m-%d-%H:%M:%S.jpeg'.format(prefix)))

rawDescription: Python File Creation Date & Rename - Request for Critique


code:
#===================================================================
# Module with functions to save & restore qt widget values
# Written by: Alan Lilly
# Website: http://panofish.net
#===================================================================

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import inspect

#===================================================================
# save "ui" controls and values to registry "setting"
# currently only handles comboboxes editlines & checkboxes
# ui = qmainwindow object
# settings = qsettings object
#===================================================================

def guisave(ui, settings):

    #for child in ui.children():  # works like getmembers, but because it traverses the hierarachy, you would have to call guisave recursively to traverse down the tree

    for name, obj in inspect.getmembers(ui):
        #if type(obj) is QComboBox:  # this works similar to isinstance, but missed some field... not sure why?
        if isinstance(obj, QComboBox):
            name   = obj.objectName()      # get combobox name
            index  = obj.currentIndex()    # get current index from combobox
            text   = obj.itemText(index)   # get the text for current index
            settings.setValue(name, text)   # save combobox selection to registry

        if isinstance(obj, QLineEdit):
            name = obj.objectName()
            value = obj.text()
            settings.setValue(name, value)    # save ui values, so they can be restored next time

        if isinstance(obj, QCheckBox):
            name = obj.objectName()
            state = obj.checkState()
            settings.setValue(name, state)

#===================================================================
# restore "ui" controls with values stored in registry "settings"
# currently only handles comboboxes, editlines &checkboxes
# ui = QMainWindow object
# settings = QSettings object
#===================================================================

def guirestore(ui, settings):

    for name, obj in inspect.getmembers(ui):
        if isinstance(obj, QComboBox):
            index  = obj.currentIndex()    # get current region from combobox
            #text   = obj.itemText(index)   # get the text for new selected index
            name   = obj.objectName()

            value = unicode(settings.value(name))

            if value == "":
                continue

            index = obj.findText(value)   # get the corresponding index for specified string in combobox

            if index == -1:  # add to list if not found
                obj.insertItems(0,[value])
                index = obj.findText(value)
                obj.setCurrentIndex(index)
            else:
                obj.setCurrentIndex(index)   # preselect a combobox value by index

        if isinstance(obj, QLineEdit):
            name = obj.objectName()
            value = unicode(settings.value(name))  # get stored value from registry
            obj.setText(value)  # restore lineEditFile

        if isinstance(obj, QCheckBox):
            name = obj.objectName()
            value = settings.value(name)   # get stored value from registry
            if value != None:
                obj.setCheckState(value)   # restore checkbox

        #if isinstance(obj, QRadioButton):

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

if __name__ == "__main__":

    # execute when run directly, but not when called as a module.
    # therefore this section allows for testing this module!

    #print "running directly, not as a module!"

    sys.exit()

rawDescription: Python PyQt4 functions to save and restore UI widget values?


code:
class TMapCell(Structure):

    _pack_ = 1

    _fields_ = [
        ('Tile', c_ushort),
        ('Z', c_byte),
    ]

rawDescription: How do I represent a packed Delphi record with Python ctypes?

description: Represent a packed Delphi record with Python ctypes


code:
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.pushButton = QtWidgets.QPushButton(Form)
        self.pushButton.setGeometry(QtCore.QRect(70, 50, 75, 23))
        self.pushButton.setObjectName("pushButton")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.pushButton.setText(_translate("Form", "PushButton"))

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_())

rawDescription: Qt5: AttributeError: 'module' object has no attribute 'QApplication'


code:
import sympy as sy

def myformula(formula, **kwargs):
    expr = sy.sympify(formula)
    return expr.evalf(subs=kwargs)

print(myformula(x=2,y=2,z=1,formula="x+2*y/z"))
# 6.00000000000000

print(myformula(x=2,y=2,z=1,formula="sin(x+y-z)"))
# 0.141120008059867

rawDescription: Pass a formula as a function parameter in python


code: example.sort(key=int, reverse=True)

rawDescription: Python sorting number only according to their first index?


code:
import xlrd, webbrowser

workbook = xlrd.open_workbook('websites.xls')
sheet = workbook.sheet_by_name('Sheet1')

# Suppose your URLs are in column 5, rows 2 to 30
url_column = 5
for row in range(2, 31):
    url = sheet.cell_value(row, url_column)
    webbrowser.open_new_tab(url)

rawDescription: Script to open a bunch of browser tabs, based on data from an Excel spreadsheet?


rawDescription: Python print unique arrays from an array


code:
#!/usr/bin/python

import os
import pwd
import grp

# Show only filders in /home
path = "/home/"
folderu = [f for f in os.listdir(path)
    if os.path.isdir(os.path.join(path, f))]

for somevar in folderu:
    uid = pwd.getpwnam(somevar).pw_uid
    gid = grp.getgrnam(somevar).gr_gid
    os.chown(somevar, uid, gid)

rawDescription: Python - chown folder by username

description: Python - chown folder by username


code:
import re
re.sub(r'(\("Exercises.*?\))', r'\1)', '("Exercises, 31" "#42")')
re.sub(r'(\("Chapter.*?)\)', r'\1', '("Chapter 2 I Positive Borel Measures, 33" "#44")')

rawDescription: How to match the following strings using Python Regex?

description: Match the following strings using Python Regex


rawDescription: How to calculate percent change compared to the beginning value using pandas?

description: Calculate percent change compared to the beginning value using pandas


code:
import urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://74.125.228.100',timeout=1)
        return True
    except urllib2.URLError as err: pass
    return False

rawDescription: Checking network connection

description: Checking network connection


code:
import hashlib

def compare_files(a,b):
    fileA = hashlib.sha256(open(a, 'rb').read()).digest()
    fileB = hashlib.sha256(open(b, 'rb').read()).digest()
    if fileA == fileB:
        return True
    else:
        return False

rawDescription: [Python]Function that compares two zip files, one located in FTP dir, the other on my local machine


code:
parameters = {'a':1.0, 'b':2.0, 'c':3.0}
f = netCDF4.Dataset('test.nc', 'w')
parms = f.createGroup('parameters')
for k,v in parameters.items():
    setattr(parms, k, v)

rawDescription: Saving Python dictionary to netCDF4 file


code:
A = []
seq = ['oz_', A, 'ab']
[value for values in seq
 for value in (values if isinstance(values, str)
               else [values])]

rawDescription: Convert a list of strings and lists into a list of chars and lists?


code:
pattern = '(\.?/|/)|(^:?[^:]*$)'
re.match(pattern, ":home/test") # match, is a local path
re.match(pattern, "user@host:blah") # no match

rawDescription: How to distinguish between local filesystem path and file system path over SSH?

description: Distinguish between local filesystem path and file system path over SSH


code:
from random import randint
colors = []

for i in range(10):
    colors.append('%06X' % randint(0, 0xFFFFFF))

rawDescription: Array of colors in python

description: Array of colors in python


code:
RANGE_SIZE = 255-100
for index in range(256):
     array[index] = 100 + int( RANGE_SIZE * float(index) / 255.0 )

rawDescription: Remapping an array of integers

description: Remapping an array of integers


code:
from datetime import *

def convproxy(methods,converter):
    def f(cls):
        def _proxyfactory(method):
            def _convproxy(self,*args,**kwargs):
                return converter(getattr(super(cls,self),method)(*args,**kwargs))
            return _convproxy
        for m in methods:
            setattr(cls,m,_proxyfactory(m))
        return cls
    return f

@convproxy(('__add__','__sub__'),lambda d:mydatetime(d.timetuple()[:6]))
class mydatetime(datetime):
    pass

@convproxy(('__add__','__sub__','__div__','__rmul__','__mul__'),\
        lambda t:mytimetuple(t.days,t.seconds))
class mytimedelta(timedelta):
    pass

rawDescription: Subclassing datetime: Is there a better way to maintain resulting object type after arithmetic operations?


code: return "filename: " + fn.func_code.co_filename

rawDescription: How can I get the file name of the function that is passed to my decorator in python?

description: Get the file name of the function that is passed to my decorator in python


rawDescription: Selecting a specific number in Python

description: Selecting a specific number in Python


code:
def number_function():
    desired = set()
    for x in range(0, 10):
        before_hyphen = number_variable[x].split('-', 1)[0]
        desired.add(before_hyphen)
    for x in desired:
        print("Number", x)

rawDescription: Compare each item in a list with all previous items, print only unique items


code:
Y = np.array([2, 0, 1, 1])
X = np.zeros((len(Y), 3))
X[np.arange(len(Y)), Y] = 1
X

rawDescription: Construct two dimensional numpy array from indices and values of a one dimensional array


code:
index = 0
while index < linCirc.length:
   if linCirc[index][0] == 0:
       index = index + linCirc[index][1]
   else:
       index = index + 1

rawDescription: Is there a 'skip-range' technique in FOR-loops in Python?


code:
import re

nextline = "DD:MM:YYYY INFO - 'WeeklyMedal: Hole = 1; Par = 4; Index = 2; Distance = 459; Score = { Player1 = 4; Player2 = 6; Player3 = 4 };"

# compiles the regular expression to get the info you want
my_regex = re.compile(r'\w+ \= \w+')

# builds the structure of the dict you expect to get
final_dict = {'Hole':0, 'Par':0, 'Index':0, 'Distance':0, 'Score':{}}

# uses the compiled regular expression to filter out the info you want from the string
filtered_items = my_regex.findall(nextline)

for item in filtered_items:
    # for each filtered item (string in the form key = value)
    # splits out the 'key' and handles it to fill your final dictionary
    key = item.split(' = ')[0]
    if key.startswith('Player'):
        final_dict['Score'][key] = int(item.split(' = ')[1])
    else:
        final_dict[key] = int(item.split(' = ')[1])

rawDescription: split a line into a dictionary with multiple layers of key value pairs

description: Split a line into a dictionary with multiple layers of key value pairs


code:
#!/usr/bin/env python3
import subprocess

def run_command(command, **kwargs):
    with subprocess.Popen(command,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT,
                          bufsize=1,
                          **kwargs) as p:
        yield from p.stdout
    # close p.stdout, call p.wait() automatically

for line in run_command(r'java -jar c:\jar\minecraft.jar',
                        cwd=r'D:\working directory',
                        universal_newlines=True):
    print(line, end='')

rawDescription: Python Change Output Folder of Java Executable


code:
from csv import reader

total_status = 0
count = {'happy': 0, 'sad': 0, 'angry':0}

for sentiment, status in reader(open(filepath, 'rb'), delimiter=',', quotechar='|'):
    total_status += 1
    count[sentiment] += 1

rawDescription: (Python) CSV Reader omits a line

description: (Python) CSV Reader omits a line


code:
import csv

f = open('file.csv', 'rb')
reader = csv.reader(f)
your_list = list(reader)

f = open('file.csv', 'wb')
writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)

for line in your_list:
   line[2] = line[2].replace(",","")
   line[3] = line[3].replace(",","")
   writer.writerow(line)

rawDescription: Delete specific characters from only two columns in a CSV file using Python 3.5


code:
import numpy as np
a = np.arange(9).reshape((3,3))
b = np.asmatrix(a)
b.base is a
a[0] = 3
b

rawDescription: Can I avoid using `asmatrix`?

description: Avoid using `asmatrix`


code:
import collections

def revert_dict(d):
    rd = collections.defaultdict(list)

    for key, value in d.iteritems():
        rd[value].append(key)

    return rd

rawDescription: smarter "reverse" of a dictionary in python (acc for some of values being the same)?

description: Smarter "reverse" of a dictionary in python (acc for some of values being the same)


code:
vec = np.asarray(l).reshape((1,-1))
vec.shape

rawDescription: Numpy - asarray of a list, dimension not automatically set in the vector


code:
from textblob import TextBlob
blob = TextBlob("Humpty dumpty sat on a wall i.e. humpty was sitting on a wall! Then, he fell down. Dr. John (BA in Medical Engineering) helped reconstruct humpty?")
blob.sentences

# [Sentence("Humpty dumpty sat on a wall i.e."),
#  Sentence("humpty was sitting on a wall!"),
#  Sentence("Then, he fell down."),
#  Sentence("Dr. John (BA in Medical Engineering) helped reconstruct humpty?")]

rawDescription: Python: Approaches to parse English sentences: Regex?


code:
class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        # hide every other field apart from url
        # if we are adding
        if obj is None:
            kwargs['fields'] = ['url']
        return super(MyModelAdmin, self).get_form(request, obj, **kwargs)

rawDescription: Define a Custom Form for use in Django's ModelAdmin Add View


code:
#! /usr/bin/python
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import random

def init():
    imobj.set_data(np.zeros((100, 100)))
    line_simu.set_data([], [])
    time_text.set_text('time = 0.0')

    return imobj , line_simu,  time_text,  l

def animate(i):
    global data
    imobj.set_data( data + np.random.random((100,1)) * 0.5 )

    imobj.set_zorder(0)
    y_simu = np.linspace(-100,-10, 100)
    x_simu = np.linspace(-10, 10, 100)
    line_simu.set_data(x_simu, y_simu)
    time_text.set_text('time = %.1f' % i )

    return imobj , line_simu, time_text,  l

def forceAspect(ax,aspect=1):
    im = ax.get_images()
    extent =  im[0].get_extent()
    ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)

fig = plt.figure()
ax = plt.axes(xlim=(-15,15), ylim=(-110, 0) , aspect=1)

data = np.random.random((100,100)) - .5
imobj = ax.imshow( data , extent=[-15,15, -110, 0.0], origin='lower', cmap=plt.cm.gray, vmin=-2, vmax=2, alpha=1.0, zorder=1, aspect=1)

line_simu, = ax.plot([], [],"r--", lw=2, markersize=4 , label = "Some curve" ,  zorder= 1 )
time_text = ax.text(-14.0, -108, '', zorder=10)

forceAspect(ax,aspect=1)

l = plt.legend(loc='lower right', prop={'size':8} )

anim = animation.FuncAnimation(fig, animate, init_func=init,  frames=range( 50), interval=500, blit=True)

plt.show()

rawDescription: Pyplot zorder lost with animation

description: Pyplot zorder lost with animation


code:
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

class test:
    def show(self):
        return "aaaa"

class http_server:
    def __init__(self, t1):
        myHandler.t1 = t1
        server = HTTPServer(('', 8080), myHandler)
        server.serve_forever()

class myHandler(BaseHTTPRequestHandler):
    t1 = None
    def do_GET(self):
        self.send_response(200)
        self.send_header('Content-type','text/html')
        self.end_headers()
        self.wfile.write(self.t1.show()) #Doesnt work
        return

class main:
    def __init__(self):
        self.t1 = test()

        self.server = http_server(self.t1)

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

rawDescription: BaseHTTPRequestHandler with custom instance


code: np.cumsum(boolarr,axis=1) - boolarr

rawDescription: Numpy: Quickly count True instances item-wise in 2D bool array


code:
from django.template import Template, Context

def process_template(tasks, student_var):
    new_tasks = []
    for team_task in tasks:
        template = Template(team_task.task.description)
        context = Context({'student_var': student_var})
        rendered_template = template.render(context)
        team_task.task.description = rendered_template
        new_tasks.append(team_task)
    return new_tasks

def render_team(request, team):
    tasks = process_template(TeamFlag.objects.filter(team=team))

rawDescription: Django: variable in variable in templates


code:
from gensim import corpora, models, similarities

documents = ["Human machine interface for lab abc computer applications",
             "A survey of user opinion of computer system response time",
             "The EPS user interface management system",
             "System and human system engineering testing of EPS",
             "Relation of user perceived response time to error measurement",
             "The generation of random binary unordered trees",
             "The intersection graph of paths in trees",
             "Graph minors IV Widths of trees and well quasi ordering",
             "Graph minors A survey"]

# remove common words and tokenize
stoplist = set('for a of the and to in'.split())
texts = [[word for word in document.lower().split() if word not in stoplist]
         for document in documents]

# remove words that appear only once
all_tokens = sum(texts, [])
tokens_once = set(word for word in set(all_tokens) if all_tokens.count(word) == 1)

texts = [[word for word in text if word not in tokens_once] for text in texts]

dictionary = corpora.Dictionary(texts)
corp = [dictionary.doc2bow(text) for text in texts]

# extract 400 LSI topics; use the default one-pass algorithm
lsi = models.lsimodel.LsiModel(corpus=corp, id2word=dictionary, num_topics=400)

# print the most contributing words (both positively and negatively) for each of the first ten topics
lsi.print_topics(10)

rawDescription: Clustering Using Latent Symantic Analysis


rawDescription: pyparsing results as a JSON

description: Pyparsing results as a JSON


code:
from copy import deepcopy
import json
import re
import urllib

from BeautifulSoup import BeautifulStoneSoup, Tag, NavigableString

results = json.load(urllib.urlopen("http://www.kimonolabs.com/api/4v1t8lgk?apikey=880a9bdbfb8444e00e2505e1533970a7"))

class named_list(list):
    def __init__(self, name, *args, **kwargs):
        self.name = name
        super(named_list, self).__init__(*args, **kwargs)

    def __repr__(self):
        return "<named_list %s: %s>" % (self.name, super(named_list, self).__repr__())

def dict_recurse(obj, obj_parent, nameless_default = "product"):
    olist = []
    if isinstance(obj, list):
        for x in obj:
            olist.extend(dict_recurse(x, obj))
    elif isinstance(obj, dict):
        for x in sorted(obj.keys()):
            olist.append(named_list(x, dict_recurse(obj[x], obj)))
        if isinstance(obj_parent, list):
            olist = [named_list(nameless_default, olist)]
    else:
        olist.append(obj)
    return olist

def tag_tree_build(ilist, top_tag, soup):
    if isinstance(ilist, named_list):
        cur_tag = Tag(soup, ilist.name)
        for q in ilist:
            tag_tree_build(q, cur_tag, soup)
        top_tag.insert(len(top_tag), cur_tag)
    elif isinstance(ilist, list):
        for q in ilist:
            tag_tree_build(q, top_tag, soup)
    else:
        cur_str = NavigableString(re.sub("\s+", " ", unicode(ilist)))
        top_tag.insert(len(top_tag), cur_str)

nested = dict_recurse(results, results)
soup = BeautifulStoneSoup()
tag_tree_build(nested, soup, soup)
file("finnish.xml", "w").write(soup.prettify())
file("finnish.json", "w").write(json.dumps(results, sort_keys = True, indent = 4))

rawDescription: writing xml data to file using python

description: Writing xml data to file using python


code:
def spans(X, v):
    n, = X.shape
    i = 0
    total = 0
    for j in xrange(0, n):
        total += X[j]
        while total >= v:
            yield (i, j+1)
            total -= X[i]
            i += 1

rawDescription: Python/Numpy find length variable spans

description: Python/Numpy find length variable spans


code: array( [ [ i*j for j in xrange(5)] for i in xrange(5)] )

rawDescription: Create a numpy matrix with elements a function of indices


code:
grid_x_mesh, grid_y_mesh = pyproj.transform(wgs84, nplaea, grid_lons, grid_lats)

# The coordinates must be ordered in the order they are to be drawn
[grid_x.append(i) for i in grid_x_mesh[0,:]]
[grid_x.append(i) for i in grid_x_mesh[1:-1,-1]]
# Note that these two sides of the polygon are appended in reverse
[grid_x.append(i) for i in (grid_x_mesh[-1,:])[::-1]]
[grid_x.append(i) for i in (grid_x_mesh[1:-1,0])[::-1]]

[grid_y.append(i) for i in grid_y_mesh[0,:]]
[grid_y.append(i) for i in grid_y_mesh[1:-1,-1]]
[grid_y.append(i) for i in (grid_y_mesh[-1,:])[::-1]]
[grid_y.append(i) for i in (grid_y_mesh[1:-1,0])[::-1]]

grid_poly = Polygon(zip(grid_x, grid_y))

rawDescription: Ordering polygon coordinates for plotting


code:
import numpy as np
from scipy.ndimage.measurements import center_of_mass

a = np.zeros((10,10), dtype=np.int)
# add some labels:
a[3:5, 1:3] = 1
a[7:9, 0:3] = 2
a[5:6, 4:9] = 3
print(a)

num_obj = 3
surface_areas = np.bincount(a.flat)[1:]
centers = center_of_mass(a, labels=a, index=range(1, num_obj+1))
print(surface_areas)
print(centers)

rawDescription: find mean position and area of labelled objects

description: Find mean position and area of labelled objects


code:
events = np.split(df, np.where(np.isnan(df.value))[0])
# removing NaN entries
events = [ev[~np.isnan(ev.value)] for ev in events if not isinstance(ev, np.ndarray)]
# removing empty DataFrames
events = [ev for ev in events if not ev.empty]

rawDescription: How to split a pandas time-series by NAN values

description: Split a pandas time-series by NAN values


rawDescription: Double letter matching using python regex


code:
@property
def lib_vers(self):
    """Get shared library version information.

    :return: The shared library version string.
    :rtype: String
    """
    if self.lib.LibVers.argtypes is None:
        self.lib.LibVers.restype = c_char_p
        self.lib.LibVers.argtypes = []
    return self.lib.LibVers()

rawDescription: python ctype string pointer 32b vs 64b: segmentation fault (core dumped)

description: Python ctype string pointer 32b vs 64b: segmentation fault (core dumped)


code:
import mod_wsgi

process_group = mod_wsgi.process_group

rawDescription: Adding parameters to the wsgi script alias


code: [x for x in correct_order if x in messed_order] + [x for x in messed_order if x not in correct_order]

rawDescription: Python: Sort list using another list order, having different lengths, and without 'sorted'


code:
['',
 '/usr/lib/python3.4',
 '/usr/lib/python3.4/plat-x86_64-linux-gnu',
 '/usr/lib/python3.4/lib-dynload',
 '/home/me/.local/lib/python3.4/site-packages',
 '/usr/local/lib/python3.4/dist-packages',
 '/usr/lib/python3/dist-packages']

rawDescription: importing beautiful soup in python3

description: Importing beautiful soup in python3


code:
import maya.cmds
from functools import partial
temp_var=None
a_Window=None
def im_PrimaryFunc():
    imSecondary_func()

def imSecondary_func():
    global a_Window
    global temp_var
    a_Window=maya.cmds.window(title="Something")
    a_layout=maya.cmds.columnLayout(adj=1,rs=10)
    temp_var=maya.cmds.createNode("polySphere")
    maya.cmds.button(label="call_aFunc",align="center",command = partial(a_calledFunc,temp_var, a_Window))
    maya.cmds.showWindow(a_Window)

def a_calledFunc(arg00,arg01, part):
    print(arg00)
    print(arg01)

im_PrimaryFunc()

rawDescription: Cannot pass Global Variables to Multiple Functions inside a Module in Python


code:
from datetime import datetime, timedelta
from django import template
from django.utils.timesince import timesince

register = template.Library()

@register.filter
def timesince_threshold(value, days=7):
    """
    return timesince(<value>) if value is more than <days> old. Return value otherwise
    """

    if datetime.now() - value < timedelta(days=days):
        return timesince(value)
    else:
        return value
timesince_threshold.is_safe = False

rawDescription: How to compare datetime in django template

description: Compare datetime in django template


code:
from subprocess import Popen, STDOUT, PIPE
from time import sleep

def connected(sock):
    try:
        sock.send(b'')
    except:
        return False
    return True

handle = Popen(['ffmpeg', '-y', '-i', 'udp://streamurl:streamport', '-acodec', 'copy', '-f', 'mp3', 'filename.mp3'], shell=False, stdout=PIPE, stdin=PIPE, stderr=STDOUT)

output = ''
while handle.poll() is None and connected(socket): # No exit code given, ergo command still running
    output += handle.stdout.readline()
    sleep(0.025)

if not connected(socket):
    handle.terminate()

output += handle.stdout.read()
handle.stdout.close()
handle.stdin.close()
print(output)

rawDescription: terminate comand executing by subprocess

description: Terminate comand executing by subprocess


code:
encrypted = 'pbkdf2_sha256$15000$fmX24...'

if check_password(request.POST['pass'], encrypted):
    print("Login successful")

rawDescription: How to use make_password and check_password manually?

description: Use make_password and check_password manually


code:
def encode(value):
    #Your logic for the new dict vals
    return 'foo!'

class MixInRequest(Request):
    max_content_length = 1024 * 1024 * 4

    @cached_property
    def lcl_data(self):
        if self.method in ['POST','PUT','PATCH']:
            fields = dict([(key, encode(val)) for (key,val) in self.form.items()])
            return ImmutableMultiDict(fields)
        return None

rawDescription: Python Werkzeug: modify Request values (forms and args) prior to retrieval


code:
class Enemy(object):
    def init (self, name, attack, defence, gold, health, experience):
        self.name = name
        self.attack = attack
        self.defence = defence
        self.gold = gold
        self.health = health
        self.experience = experience

class Application(object):
    def __init__(self):
        self.enemy1 = Enemy("Enemy Soldier", "5", "1", "10", "10", "30")
        self.enemyLabel = tkinter.Label(text=self.enemy1.name)
        self.enemyLabel.pack()

rawDescription: How to use variables from one class in another class

description: Use variables from one class in another class


code:
{
    "NTUser": {
        "appcompat": {
            "description": "(NTUSER.DAT, Software) Extracts AppCompatFlags for Windows.",
            "location": "Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags",
            "data": [
                        {"date": "Fri Jul 10 11:00:24 2015", "result": "E:\VMware-player-4.0.6-1035888.exe"},
                        {"date": "Fri Jul 10 11:00:24 2015", "result": "E:\AdbeRdr11000_mui_Std\Setup.exe"}
            ]
        },
        "some_other_plugin": {},
    },
    "SomeOtherRegistry": {}
}

rawDescription: Pythonic approach to nested data?

description: Pythonic approach to nested data


rawDescription: Dataframe Merge in Pandas

description: Dataframe Merge in Pandas


code:
import os
len(os.environ)
'USER' in os.environ
os.environ.fromkeys

rawDescription: Is it safe to use os.environ.setdefault?

description: Is it safe to use os.environ.setdefault


code:
import matplotlib.pyplot as plt
plt.plot([1,2,3,])
plt.ylabel('some numbers')
plt.show()

rawDescription: Python Matplotlib crashes on ploting

description: Python Matplotlib crashes on ploting


code:
game_active = True

def round():
    global board, alarm, game_active

    if not game_active:
      return

    board_copy = [[x for x in row] for row in board]
    for row in range(n):
        for col in range(n):
            if countNeighbors(row,col) == 3:
                board_copy[row][col] = LIVE
                canvas.itemconfigure(rect[row][col],fill='red')
            elif countNeighbors(row,col) > 3 or countNeighbors(row,col) < 2:
                board_copy[row][col] = DEAD
                canvas.itemconfigure(rect[row][col],fill='black')
    board = board_copy

    alarm = window.after(500, round)

def start():
    global game_active
    game_active = True
    round()

def stop():
    global alarm, game_active
    window.after.cancel(alarm)
    game_active = False

rawDescription: Do I/Am I making it the function recursive?


code:
import bpy
import bmesh

obj=bpy.context.object
if obj.mode == 'EDIT':
    bm=bmesh.from_edit_mesh(obj.data)
    for v in bm.verts:
        if v.select:
            print(v.co)
else:
    print("Object is not in edit mode.")

rawDescription: Blender scripting: Indices of selected vertices


code:
from pandas import DataFrame
import matplotlib.pyplot as plt

if __name__ == '__main__':
    lower_bound = [0, 1, 2, 3]
    value = [1, 2, 3, 4]
    upper_bound = [2, 3, 4, 5]
    d = {'Lower bound': lower_bound, 'Value': value, 'Upper bound': upper_bound}
    df = DataFrame(data=d)
    ax = df.plot(color=["Blue", "Blue", "Red"])
    lines, labels = ax.get_legend_handles_labels()
    ax.legend([lines[0], lines[2]], ["Bounds", "Value"])
    plt.show()

rawDescription: pandas and matplotlib: Combine two plots into one legend item

description: Pandas and matplotlib: Combine two plots into one legend item


code: image.cmap   : gray               # gray | jet etc...

rawDescription: How to avoid automatic pseudo coloring in matplotlib.pyplot imshow()

description: Avoid automatic pseudo coloring in matplotlib.pyplot imshow()


code:
class hold_dict:
    pass

d = hold_dict()
d.d = {"key":"item"}
d.d

rawDescription: Is it possible create a new dict (dictionary) in a python class?


code:
ans = np.zeros(len(df))

for i, (col1, col2) in enumerate(df.itertuples(index=False)):
    ...
    if i == 0:
        guess = 0.1
    else:
        guess = ans[i-1]
    ans[i] = optimize(...)

df['newValue'] = ans

rawDescription: Pandas: How to structure row-wise apply which requires previous output as input


code:
key = None

def start():
    global key
    # and so on...

rawDescription: Local Variables to Global Variables within a function


code:
root = {
    'etc': {
        'passwd': None,
        'shadow': None,
        'ssh': {
            'config': None}
    },
    'lib': {
    }
}

rawDescription: How to store a directory structure in python from an ftp site

description: Store a directory structure in python from an ftp site


code:
list_of_objects = [Object_1, Object_2, Object_3]
[x.time for x in list_of_objects]

rawDescription: Create list of object attributes in python


code:
def autolog(message):
    "Automatically log the current function details."
    import inspect, logging
    # Get the previous frame in the stack, otherwise it would
    # be this function!!!
    func = inspect.currentframe().f_back.f_code
    # Dump the message + the name of this function to the log.
    logging.debug("%s: %s in %s:%i" % (
        message,
        func.co_name,
        func.co_filename,
        func.co_firstlineno
    ))

rawDescription: Python Logging (function name, file name, line number) using a single file


code:
class FormViewForFunction(FormView):
   template_name = '...'
   func = None

   def get_form_class(self):
       a = inspect.getargspec(self.func)
       class _FunctionForm(forms.Form):
           def __init__(self, *args, **kwargs):
               super(_FunctionForm, self).__init__(*args, **kwargs)
               for argname in a['args']:
                   self.fields[argname] = forms.CharField()
       return _FunctionForm

rawDescription: Failure when using setattr to add field to Django form class


code:
# setting up the model
tree = QtGui.QTreeView()
model = QtGui.QStandardItemModel()
tree.setModel(model)
# accessing data
# To get item "a"
a = tree.model().index(0, 0)
a
# to get item "a, 0"
a0 = a.child(0, 0)
a0

rawDescription: Select row and column in pyqt QTreeView

description: Select row and column in pyqt QTreeView


code: eigvals, eigvecs = eigsh(A, k=10, which='LM', sigma=1.)

rawDescription: Finding largest eigenvalue in sparse matrix


code:
def remove_names(names_to_remove, info_list):
    return [info
            for info in info_list
            if info.getName() not in names_to_remove]

rawDescription: Remove element in a list with condition

description: Remove element in a list with condition


code:
ModelFormSet = modelformset_factory(MyModel)
if request.method == 'POST':
    formset = ModelFormSet(request.POST, request.FILES, queryset=MyModel.objects.none())
    if formset.is_valid():
        formset.save()
        # do something.
else:
    formset = ModelFormSet(queryset=MyModel.objects.none())

rawDescription: Django ModelForm's insertion form also shows existing records


code:
def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
        desired_format = self.determine_format(request)
        serialized = self.serialize(request, data, desired_format)
        response = response_class(content=serialized, content_type=build_content_type(desired_format), **response_kwargs)
        response['Content-Length'] = len(response.content)
        return response

rawDescription: Django Tastypie add Content-Length header


code:
title = data.get('title')
label = data.get('label')

parent = filter(None, [title, label])

rawDescription: Python - Optional list values - A more pythonic way?


code:
from operator import attrgetter
pop.population.sort(key=attrgetter('score'))

rawDescription: Order by members' properties in class

description: Order by members' properties in class


code:
import sys
import time
from PySide.QtGui import *
from PySide.QtCore import *

class frmMain(QDialog):
    def __init__(self):
        QDialog.__init__(self)
        self.btStart = QPushButton('Start')
        self.btStop = QPushButton('Stop')
        self.counter = QSpinBox()
        self.layout = QVBoxLayout()
        self.layout.addWidget(self.btStart)
        self.layout.addWidget(self.btStop)
        self.layout.addWidget(self.counter)
        self.setLayout(self.layout)
        self.btStart.clicked.connect(self.start_thread)
        self.btStop.clicked.connect(self.stop_thread)

    def stop_thread(self):
        self.th.stop()

    def loopfunction(self, x):
        self.counter.setValue(x)

    def start_thread(self):
        self.th = thread(2)
        #self.connect(self.th, SIGNAL('loop()'), lambda x=2: self.loopfunction(x), Qt.AutoConnection)
        self.th.loop.connect(self.loopfunction)
        self.th.setTerminationEnabled(True)
        self.th.start()

class thread(QThread):
    loop = Signal(object)

    def __init__(self, x):
        QThread.__init__(self)
        self.x = x

    def run(self):
        for i in range(100):
            self.x = i
            self.loop.emit(self.x)
            time.sleep(0.5)

    def stop(self):
        self.terminate()

app = QApplication(sys.argv)
win = frmMain()

win.show()
sys.exit(app.exec_())

rawDescription: how to terminate qthread in python

description: Terminate qthread in python


code:
locator = Empty().setParseAction(lambda s,l,t: l)
def locatedExpr(expr):
    return Group(locator("location") + expr("value"))

class Shell(object):
    def __init__(self):
        # Simplified grammar of the command line
        # path command parameters
        #command = Word(alphanums + '_').setResultsName('command')
        command = locatedExpr(Word(alphanums + '_'))('command')
        bookmark = Regex('@([A-Za-z0-9:_.]|-)+')
        pathstd = Regex('([A-Za-z0-9:_.]|-)*' + '/' + '([A-Za-z0-9:_./]|-)*') \
                | '..' | '.'
        #path = (bookmark | pathstd | '*')('path')
        path = locatedExpr(bookmark | pathstd | '*')('path')
        parser = Optional(path) + Optional(command) # + Optional(parameters)
        self.parser = parser

rawDescription: Pyparsing: get token location in results name


code:
def find_fully_correct(answer, guess):
    res = []
    for x, y in zip(guess, answer):
        if x == y:
            res.append("b")
    return res if res else None

rawDescription: Python using booleans to return a list for each item in the a list that is the same as another list


code:
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get(
    'DATABASE_URL', 'sqlite:////tmp/test.db')

rawDescription: How to require different packages on Heroku to local box?

description: Require different packages on Heroku to local box


rawDescription: pyOpenSSL set_cipher_list does not have effect on traffic

description: PyOpenSSL set_cipher_list does not have effect on traffic


code:
from Tkinter import *
import random

tk = Tk()

canvas = Canvas(tk, width=400, height=400)
canvas.pack()

Option = StringVar()
Option.set("None")
menu = OptionMenu(tk, Option,"None", "Colored Outlines", "Colored Fills")
menu.pack()

colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']

def random_rectangle(width, height):
    x1 = random.randrange(width)
    y1 = random.randrange(height)
    x2 = x1 + random.randrange(width)
    y2 = y1 + random.randrange(height)
    canvas.create_rectangle(x1, y1, x2, y2)

def random_outline_rectangle(width, height):
    x1 = random.randrange(width)
    y1 = random.randrange(height)
    x2 = x1 + random.randrange(width)
    y2 = y1 + random.randrange(height)
    color = random.choice(colors)
    canvas.create_rectangle(x1, y1, x2, y2, outline=color)

def random_color_rectangle(width, height):
    x1 = random.randrange(width)
    y1 = random.randrange(height)
    x2 = x1 + random.randrange(width)
    y2 = y1 + random.randrange(height)
    color = random.choice(colors)
    canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline=color)

def Generate():
    global option
    canvas.delete("all")
    if Option.get() == "None":
        for x in range(0,100):
            random_rectangle(400, 400)
    elif Option.get() == "Colored Outlines":
        for x in range(0,100):
            random_outline_rectangle(400,400)
    elif Option.get() == "Colored Fills":
        for x in range(0,1000):
            random_color_rectangle(400,400)

button = button = Button(tk, text="Generate", command=Generate)
button.pack()

tk.mainloop()

rawDescription: Script not working (Tkinter and Functions)


code:
import webbrowser
webbrowser.open('file://%s' % path)

rawDescription: Launching default application for given type of file, OS X


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

plt.figure(1)
# Create room on the right
plt.gcf().subplots_adjust(right=0.8)

plt.subplot (121)
plt.title('1')
plt.imshow(np.random.rand(10,10), interpolation='bilinear', cmap=plt.cm.jet)
plt.subplot(122)
plt.title('2')
plt.imshow(np.random.rand(10,10), interpolation='bilinear', cmap=plt.cm.jet)

# Make a new Axes instance
cbar_ax = plt.gcf().add_axes([0.85, 0.15, 0.05, 0.7])
plt.colorbar(cax=cbar_ax)

plt.show()

rawDescription: Problems with colorbar and multiple subplot


code:
V = {}
p = Pool(4)
for i in range(N):
    V[i] = {}
    results = []
    for j in range(10):
        if should_skip(i,j):
            continue
        results.append(p.apply_async(do_something, (V,)))
    for result in results:
        r = result.get() # This will block until `result` is available.
        V[i][r[1]] = r[0]

rawDescription: A better practice than spawning, using, and closing multiple python multiprocessing pools?


code:
def CreateImage(imageName, imageData):
    """Create a GCS file with GCS client lib.

    Args:
      filename: GCS filename.

    Returns:
      The corresponding string blobkey for this GCS file.
    """
    # Create a GCS file with GCS client.
    with gcs.open(imageName, 'w') as f:
        f.write(imageData)

    # Blobstore API requires extra /gs to distinguish against blobstore files.
    blobstore_filename = '/gs' + imageName
    # This blob_key works with blobstore APIs that do not expect a
    # corresponding BlobInfo in datastore.
    return blobstore.create_gs_key(blobstore_filename)

rawDescription: how to store an image on Google Cloud Storage sent by Android using Python

description: Store an image on Google Cloud Storage sent by Android using Python