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

D = np.random.uniform(0, 100, size=(5, 5))
fig, ax = plt.subplots()
h, w = D.shape
img = ax.pcolormesh( np.arange(h+1), np.arange(w+1), D)

D2 = img.get_array().reshape(img._meshWidth, img._meshHeight)
assert  np.array_equal(D, D2)

rawDescription: Matplotlib: `pcolormesh.get_array()` returns flattened array - how to get 2D data back?


code:
import sys
from PyQt4 import QtGui, QtCore

class MyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(MyDialog, self).__init__(parent)

        scrolllayout = QtGui.QVBoxLayout()

        scrollwidget = QtGui.QWidget()
        scrollwidget.setLayout(scrolllayout)

        scroll = QtGui.QScrollArea()
        scroll.setWidgetResizable(True)  # Set to make the inner widget resize with scroll area
        scroll.setWidget(scrollwidget)

        self.groupboxes = []  # Keep a reference to groupboxes for later use
        for i in range(8):    # 8 groupboxes with textedit in them
            groupbox = QtGui.QGroupBox('%d' % i)
            grouplayout = QtGui.QHBoxLayout()
            grouptext = QtGui.QTextEdit()
            grouplayout.addWidget(grouptext)
            groupbox.setLayout(grouplayout)
            scrolllayout.addWidget(groupbox)
            self.groupboxes.append(groupbox)

        self.buttonbox = QtGui.QDialogButtonBox()
        self.buttonbox.setOrientation(QtCore.Qt.Vertical)
        self.buttonbox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)

        layout = QtGui.QHBoxLayout()
        layout.addWidget(scroll)
        layout.addWidget(self.buttonbox)
        self.setLayout(layout)

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

rawDescription: How to associate a horizontal scrollbar to multiple groupbox.?

description: Associate a horizontal scrollbar to multiple groupbox.


code:
import matplotlib.pyplot as plt
for fig, fig_name in zip(fig_data, fig_names):
    plt.clf()
    plt.pie(fig, labels=titles, shadow=True)
    plt.savefig(fig_name + '.png')

rawDescription: Python Matplotlib - saved images getting overwritten while using for loop


code:
def retrieve_url(url):
    os.system('cclive %s' % url)

pool = multiprocessing.Pool(4)
pool.map(retrieve_url, list_of_urls)

rawDescription: Run os.system() multiple times simultaneously in Python?


code:
from sqlalchemy import func

q = db_session.query(
    func.IF(func.substr(Table.order_id, 1, 8) == 'STRING', Table1.name, Table2.type)
)

rawDescription: SQLAlchemy add condition to query

description: SQLAlchemy add condition to query


code:
for key, val in list(mydict.items()):
    if val == value:
        del mydict[key]
        break # unless you want to remove multiple occurences

rawDescription: How to remove dictionary key with known value?

description: Remove dictionary key with known value


code:
import re
s = 'aaa  bbb   bbb    aaa'
re.findall(r'aaa.*?bbb|bbb.*?aaa', s)

rawDescription: Python regex match two string at two different order?


code:
def primes(n): # sieve of eratosthenes
    ps, sieve = [], [True] * (n + 1)
    for p in range(2, n + 1):
        if sieve[p]:
           ps.append(p)
           for i in range(p * p, n + 1, p):
               sieve[i] = False
    return ps

rawDescription: My sieve of eratosthenes implementation in Python


code: body = '\n'.join('%s, %s' % pair for pair in mylist)

rawDescription: Send formatted list of tuples as body of an email


code:
def is_subsequence(x, y):
    """Test whether x is a subsequence of y"""
    x = list(x)
    for letter in y:
        if x and x[0] == letter:
            x.pop(0)

    return not x

rawDescription: How to test if one string is a subsequence of another?

description: Test if one string is a subsequence of another


code:
def read_file():
    user_input = raw_input("please put date needed in x.xx form: ")
    path = r'C:\\Users\\CP\\documents\\' + user_input
    allFiles = glob.glob(path + '/*.csv')
    frame = pd.DataFrame()
    list = []
    for file in allFiles:
        df = pd.read_csv(file,index_col=None,header=0)
        list.append(df)
    frame =pd.concat(list,ignore_index=True)
    return(frame) #YOUR FUNCTION WILL BE RETURNING THE READ FRAME

def cost_channelID(read_frame): #YOU WILL BE RECEIVING A DIFFERENT FRAME EVERY TIME
    numbers =r'[0,1,2,3,4,5,6,7,8,9]'
    Ads = read_frame['Ad']
    ID = []
    for ad in Ads:
        num = ''.join(re.findall(numbers,ad)[1:7])
        ID.append(num)
    ID = pd.Series(ID)
    pieces = [frame,ID]

    frame2 = pd.concat(pieces,ignore_index=True,axis=1)
    frame2 = frame2.rename(columns={0:'Ad',1:'Ad Impressions',2:'Total Ad Spend',3:'eCPM (Total Ad Spend/Ad)',4:'Ad Attempts',5:'ID'})
#HERE YOU MEANT TO USE FRAME2 WITHIN THE FUNCTION? IT IS WHAT HAPPENING BECAUSE OF THE INDENTATION

frame1 = read_file() #YOU CAN READ AS MANY FRAMES AS YOU WANT AND THEY'LL BE KEPT IN SEPARATED FRAMES
frame2 = read_file()
#...framexx = read_file()
#AND YOU CAN JUST CALL cost_channelID in any of them (or any other function)

const_channelID(frame1)
const_channelID(frame2)
#... AND SO ON

rawDescription: How to use user-defined functions in python?

description: Use user-defined functions in python


code:
r.db('my_db').table('my_table').filter(lambda row:
    row["some_key"].contains(lambda key:
        key.match(".\*some_given_string.\*")
    )
)

rawDescription: RethinkDB: matching a substring in a list of strings


code:
from pymongo.bulk import BulkUpsertOperation
bulk=clientConn.db.table.initialize_ordered_bulk_op()

for i in someList:
    bulk.find({'uid':i,"dt":datetime(y,m,d)}).upsert().update({'$inc': {'count': 1}})
res=bulk.execute()

rawDescription: MongoDb pymongo how to increment multiple documents


code:
df
df = df.set_index(['country', 'countrycode', 'varname'])
df.columns.name = 'year'
df.stack().unstack('varname')

rawDescription: Pandas DataFrame from WB WDI data: combine year columns into "year" variable and merge rows


code: df1.total[df2.index] += df2.total

rawDescription: Faster alternative to Series.add function in pandas


code: {namelist[i] : namelist[i : i + 3] for i in xrange(0, len(namelist), 3)}

rawDescription: List in dictionary in python,combination of list elements in a Key


code:
from pdfminer.layout import LAParams
from pdfminer.converter import PDFPageAggregator

# Set parameters for analysis.
laparams = LAParams()
# Create a PDF page aggregator object.
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
for page in doc.get_pages():
    interpreter.process_page(page)
    # receive the LTPage object for the page.
    layout = device.get_result()

rawDescription: Python Image Detection PDF

description: Python Image Detection PDF


code:
class Person(object):
    def __init__(self, name, city):
        self.name = name
        self.city = city
names = ['Bob', 'Alex', 'John']
cities = ['New York', 'London', 'Rome']

persons = {n: Person(n,c) for n,c in zip(names, cities)}

print(persons['Bob'].city)

rawDescription: How do I check values in a list of class in python?

description: Check values in a list of class in python


code:
import inspect

class BadSignatureException(Exception):
    pass

class SignatureCheckerMeta(type):
    def __new__(cls, name, baseClasses, d):
        #For each method in d, check to see if any base class already
        #defined a method with that name. If so, make sure the
        #signatures are the same.
        for methodName in d:
            f = d[methodName]
            for baseClass in baseClasses:
                try:
                    fBase = getattr(baseClass, methodName).__func__
                    if not inspect.getargspec(f) == inspect.getargspec(fBase):
                        raise BadSignatureException(str(methodName))
                except AttributeError:
                    #This method was not defined in this base class,
                    #So just go to the next base class.
                    continue

        return type(name, baseClasses, d)

def main():

    class A(object):
        def foo(self, x):
            pass

    try:
        class B(A):
            __metaclass__ = SignatureCheckerMeta
            def foo(self):
                """This override shouldn't work because the signature is wrong"""
                pass
    except BadSignatureException:
        print("Class B can't be constructed because of a bad method signature")
        print("This is as it should be :)")

    try:
        class C(A):
            __metaclass__ = SignatureCheckerMeta
            def foo(self, x):
                """This is ok because the signature matches A.foo"""
                pass
    except BadSignatureException:
        print("Class C couldn't be constructed. Something went wrong")

if __name__ == "__main__":
    main()

rawDescription: How to enforce method signature for child classes?

description: Enforce method signature for child classes


code:
def json_encode(value):
    return json.dumps(value).replace("</", "<\\/")

def json_decode(value):
    return json.loads(to_basestring(value))

def to_basestring(value):
    if isinstance(value, _BASESTRING_TYPES):
        return value
    assert isinstance(value, bytes_type)
    return value.decode("utf-8")

rawDescription: What is the difference between json.dumps/loads and tornado.escape.json_encode/json_decode?


rawDescription: Create HDF5 Group /Table if it does not exist


code:
c = docker.Client(base_url='unix://var/run/docker.sock',
                  version='1.12', timeout=10)
c.copy(container, resource)

rawDescription: Load data from host machine to docker hive container


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

x = np.arange(10)
np.random.seed(101)
y = np.random.rand(10)

small = [i for i in range(len(x)) if y[i] < .5 ]
big = [i for i in range(len(x)) if y[i] > .5 ]

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

ax.scatter(x,y)
# user wants to plot lines connecting big values (>.5)
ax.plot(x[big],y[big])

#plt.show()
# now user wants to delete the first (and only) line
del ax.lines[0]

# so that they can plot a line only showing small values
ax.plot(x[small],y[small])

plt.show()

rawDescription: Erase previously drawn content from a pyplot drawing


code:
UserFileRW = open("UserScoreFile.txt","r+")
UserFileLines = UserFileRW.readlines()
UserLevelLine = UserFileLines[lev]
UserLevelScore = int(UserLevelLine[2:])
UserFileRW.close()

if LevelScore > UserLevelScore:
    UserFileWR = open("UserScoreFile.txt","w+")
    UserFileLines[lev] = "T " + str(LevelScore) + "\n"
    UserFileRW.writelines(UserFileLines)
    UserFileRW.close()

rawDescription: Want to overwrite specific character on a specific line in a text file with new characters in Python


code:
Simple[:,0,1] = 4
Simple

rawDescription: Python Array Indices Switch - What's Going On?


code:
from itertools import product
list(product(*[[1, 2], [3, 4], [5, 6], [7, 8]]))

rawDescription: Python - List Comprehension of List of Lists


code:
class UserAdmin(UserAdmin):
    list_display = ('email', 'first_name', 'last_name', 'phone')
    inlines = (UserProfileInline,)

    def phone(self, obj):
        try:
            phone = obj.userprofile.phone #Or change this to how you would access the userprofile object - This was assuming that the User, Profile relationship is OneToOne
            return phone
        except:
            return ""

    phone.short_description = 'Phone'

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

rawDescription: Displaying a UserProfile field in Django Admin outside listing


code:
from pprint import pprint
pprint(sums)

rawDescription: Python: how to print dict in separate line?


rawDescription: Generating IDs how to make IDs same length using zeroes?


code: filename = str(colorHair) + str(colorEye) + str(styleHair) + str(colorSkin) + ".png"

rawDescription: How do I load a specific image based on variables?

description: Load a specific image based on variables


code:
import pylab as pl

pl.Artist.get_rasterized = lambda self:True

fig, ax = pl.subplots()
ax.plot([1,2,3,2])
fig.savefig("test.pdf")

rawDescription: How to declare a default boolean parameter to be used by all plots in matplotlib?

description: Declare a default boolean parameter to be used by all plots in matplotlib


code:
import scipy.stats as ss
import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-10, 11)
xU, xL = x + 0.5, x - 0.5
prob = ss.norm.cdf(xU, scale = 3) - ss.norm.cdf(xL, scale = 3)
prob = prob / prob.sum() #normalize the probabilities so their sum is 1
nums = np.random.choice(x, size = 10000, p = prob)
plt.hist(nums, bins = len(x))

rawDescription: How to generate a random normal distribution of integers

description: Generate a random normal distribution of integers


rawDescription: Connector/python slow insertion with tripled quotes


code:
df
df.reset_index(drop=True)

rawDescription: In a python pandas DataFrame, how do you shift row indexes up to fill empty rows?


code:
def fib(k=100):
    """ Generate fibonacci numbers up to k. """
    a, b = 1, 2
    while a <= k:
        yield a
        a, b = b, a + b

print(' '.join(map(str, fib())))
# prints: '1 2 3 5 8 13 21 34 55 89'

rawDescription: Is a, b = b, a + b good python?

description: Is a, b = b, a + b good python


code:
data = []
count = 1
with open("veggies_2014.dat") as f:
    line = f.readline()
    while line and int(line) == count:
        score = 0
        entry = []
        entry.append(f.readline())   #read line with c_name
        for i in range(3):
            score += float(f.readline())     #add scores
        entry.append(score)
        data.append(entry)
        line = f.readline()
        count += 1

print(data)
data = sorted(data, key = lambda l:l[1], reverse = True)
print()
print(data)

rawDescription: Python-2: Assign line in text file to a variable


code:
from functools import partial

def actual_handler(page):
    return u'hello'

for page in session.query(Page):
    route = u'/{0}/{1}/{2}'.format(page.id1, page.id2, page.id3)
    app.add_url_rule(
        route,
        page.name,  # this is the name used for url_for
        partial(actual_handler, page=page),
    )

rawDescription: python/Flask: Route with dynamic first component

description: Python/Flask: Route with dynamic first component


code: my_file = io.open("myfile.txt", "w", encoding="utf-8")

rawDescription: Reading UTF-8 file with universal newlines in Python 2


code:
from PyQt4 import QtCore, QtGui, QtXml

class XmlHandler(QtXml.QXmlDefaultHandler):
    def __init__(self, root):
        QtXml.QXmlDefaultHandler.__init__(self)
        self._root = root
        self._item = None
        self._text = ''
        self._error = ''

    def startElement(self, namespace, name, qname, attributes):
        if qname == 'folder' or qname == 'item':
            if self._item is not None:
                self._item = QtGui.QTreeWidgetItem(self._item)
            else:
                self._item = QtGui.QTreeWidgetItem(self._root)
            self._item.setData(0, QtCore.Qt.UserRole, qname)
            self._item.setText(0, 'Unknown Title')
            if qname == 'folder':
                self._item.setExpanded(True)
            elif qname == 'item':
                self._item.setText(1, attributes.value('type'))
        self._text = ''
        return True

    def endElement(self, namespace, name, qname):
        if qname == 'title':
            if self._item is not None:
                self._item.setText(0, self._text)
        elif qname == 'folder' or qname == 'item':
            self._item = self._item.parent()
        return True

    def characters(self, text):
        self._text += text
        return True

    def fatalError(self, exception):
        print('Parse Error: line %d, column %d:\n  %s' % (
              exception.lineNumber(),
              exception.columnNumber(),
              exception.message(),
              ))
        return False

    def errorString(self):
        return self._error

class Window(QtGui.QTreeWidget):
    def __init__(self):
        QtGui.QTreeWidget.__init__(self)
        self.header().setResizeMode(QtGui.QHeaderView.Stretch)
        self.setHeaderLabels(['Title', 'Type'])
        source = QtXml.QXmlInputSource()
        source.setData(xml)
        handler = XmlHandler(self)
        reader = QtXml.QXmlSimpleReader()
        reader.setContentHandler(handler)
        reader.setErrorHandler(handler)
        reader.parse(source)

xml = """\
<root>
    <folder>
        <title>Folder One</title>
        <item type="1">
            <title>Item One</title>
        </item>
        <item type="1">
            <title>Item Two</title>
        </item>
        <item type="2">
            <title>Item Three</title>
        </item>
        <folder>
            <title>Folder Two</title>
            <item type="3">
                <title>Item Four</title>
            </item>
            <item type="0">
                <title>Item Five</title>
            </item>
            <item type="1">
                <title>Item Six</title>
            </item>
        </folder>
    </folder>
    <folder>
        <title>Folder Three</title>
        <item type="0">
            <title>Item Six</title>
        </item>
        <item type="2">
            <title>Item Seven</title>
        </item>
        <item type="2">
            <title>Item Eight</title>
        </item>
    </folder>
</root>
"""

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.resize(400, 300)
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQt - XML to QTreeWidget

description: PyQt - XML to QTreeWidget


code:
def add_after_every_n(iterator, item_to_add='\n', after_every=3):
    for i, element in enumerate(iterator, 1):  # i counts from 1
         yield element
         if i % after_every == 0:
            yield item_to_add

pairs = [[1,2] for i in range(10)]
pairs = [str(p) + ', ' for p in pairs]
pairs_string = ''.join(add_after_every_n(pairs))
pairs_string = pairs_string[:-2]  # remove last ', '

rawDescription: Python: add new line every n strings in a list


code:
rootItem = self.ui.comboBox.model().invisibleRootItem()
for rowNum in xrange(rootItem.rowCount()):
    item = rootItem.child(rowNum, 0)
    ...

rawDescription: Items disappears from combo box when I read them from model


code:
file=open('output.txt', "r")
array = []
for line in file:
    array.append(float(line.rstrip()))
file.close()

rawDescription: How do I save this text file into a list in python

description: Save this text file into a list in python


code:
import xlrd
import xlwt

# open first excel file, store number of rows,cols and sheet name
wb_1 = open_workbook("file1.xls")
sheet_1 = wb.sheet_by_index(0)
maxRows_1 = sheet_1.nrows
maxCols_1 = sheet_1.ncols
sName_1 = sheet_1.name

i = 0
j = 0

# create output excel file
wb_out = xlwt.Workbook()
sheet_out_1 = wb_out.add_sheet(sName_1)

# Loop through writing each cell value
while i<maxRows_1:
    while j<maxCols_1:
        sheet_out_1.write(i,j, sheet_1.cell(i,j).value)
        j += 1
    j = 0
    i += 1

# repeat for second excel file
# then save your new excel

wb_out.save("newFile.xls")

rawDescription: Python append excel sheet from another workbook xlwt


code:
lst = [5, 10, 10, 20, 50, 50, 20]

# Convert (and build reverse mapping)
mapping = {}
reverse_mapping = {}
conv = []
for i in lst:
    v = mapping.setdefault(i, len(mapping))
    reverse_mapping[v] = i
    conv.append(v)

# Convert back
back = [reverse_mapping[v] for v in conv]

rawDescription: Converting (and back) discontinuous values to continuous values in Python 2


code:
class A():
    def __init__(self):
        ...
        b_instance = B()
        ...

class B():
    def __init__(self):
        ...
    def function1(self):
        ...
    def function2(self):
        C().run(self) # pass class B instance to C instance run method
        ...

class C():
    def __init__(self):
        ...
    def run(self, classB): # note additional parameter
        classB.function1()

rawDescription: Access to the methods of the class from which it was instantiated another class


code:
s = Series(randn(6), index=pd.date_range('2013-01-01 11:25:00', freq='5T', periods=6), dtype=object)
s.iloc[1:3] = nan
s
s.interpolate(method='time')
s.astype(float).interpolate(method='time')

rawDescription: pandas.Series.interpolate() does nothing. Why?

description: Pandas.Series.interpolate() does nothing. Why


code:
import collections
with open('file1') as f1, open('file2') as f2:
    my_dict = collections.defaultdict(list)
    for x in f1:
        x = x.strip().split()
        my_dict[x[0]].append(x[1])
    for x in f2:
        x = x.strip().split()
        if x[0] in my_dict:
            my_dict[x[0]].append(x[1])

rawDescription: Match common words in two files, and add info from one file to the other


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

x = [datetime.datetime(2010, 12, 1, 0, 0),
    datetime.datetime(2011, 1, 1, 0, 0),
    datetime.datetime(2011, 5, 1, 1, 0)]
y = [4, 9, 2]

ax = plt.subplot(111)
barWidth=20
ax.bar(x, y, width=barWidth, align='center') #< added align keyword
ax.xaxis_date()

plt.savefig('baralign.png')
plt.show()

rawDescription: matplotlib centered bar chart with dates

description: Matplotlib centered bar chart with dates


code:
import base64
import struct
import pymysql.cursors
import sys
import datetime
from contextlib import closing

collectData = []
connection = pymysql.connect(host='localhost',
                user='xxx',
                password='xxx',
                db='xxx',
                charset='utf8mb4',
                cursorclass=pymysql.cursors.DictCursor)

with closing(connection.cursor()) as cursor:
 sql = "SELECT * FROM CFC_xxxx"
 cursor.execute(sql)
 for row in cursor:
  check = struct.unpack('>15x2f4B1L1x', base64.b64decode(row['Value']))

  if check[6] > 20000 or check[6] < 10000:
   continue
  else:
   xxGatewayId = int(row['Node_ID'])
   qqqGatewayId = int(row['Gateway_ID'])
   treeDiameter = int(check[0])
   temperature = int(check[1])
   recordTime = str(row['Timestamp'])
   year = datetime.datetime.fromtimestamp(row['Timestamp']).strftime('%Y')
   if check[2] == 0:
    hours = '00'
   else:
    hours = str(check[2])

   if check[3] == 0:
    minute = '00'
   else:
    minute = str(check[3])

   if check[4] < 10:
    day = '0'+str(check[4])
   else:
    day = str(check[4])

   if check[5] < 10:
    month = '0'+str(check[5])
   else:
    month = str(check[5])

   dateTime = str(year + '-' + month + '-' + day + ' ' + hours + ':' + minute + ':00')
   treeHuggerID = int(check[6])
   collectData.append(xxGatewayId,qqqGatewayId,treeDiameter,temperature,recordTime,dateTime,treeHuggerID)

  c1 = connection.cursor()
  sqlInsert = "INSERT INTO  SENSOR_TREEHUGGERS(`xx_Gateway_Id`,`qqq_Gateway_Id`,`treeDiameter`,`temperature`,`recordTime`,`dateTime`,`TreeHuggerId`) VALUES (%s,%s,%s,%s,%s,%s,%s)"
  c1.executemany(sqlInsert, collectData)
  connection.commit()

rawDescription: Python3 after cursor.execute it stopped?

description: Python3 after cursor.execute it stopped


code:
results = []
if regex_search:
    p = re.compile(__searchtext__)
for dir, subdirs, subfiles in os.walk('c:/docs/2009'):
    for name in fnmatch.filter(subfiles, '*.txt'):
        fn = os.path.join(dir, name)
        with open(fn, 'r') as f:
            if regex_search:
                results += [(fn,lineno) for lineno, line in enumerate(f) if p.search(line)]
            else:
                results += [(fn,lineno) for lineno, line in enumerate(f) if line.find(__searchtext__) >= 0]

rawDescription: find in files using ruby or python

description: Find in files using ruby or python


rawDescription: Is it possible to have race conditions at App Engine while updating ListProperty?


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

fig = plt.figure(figsize=plt.figaspect(1))  # Square figure
ax = fig.add_subplot(111, projection='3d')

coefs = (1, 2, 2)  # Coefficients in a0/c x**2 + a1/c y**2 + a2/c z**2 = 1
# Radii corresponding to the coefficients:
rx, ry, rz = 1/np.sqrt(coefs)

# Set of all spherical angles:
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)

# Cartesian coordinates that correspond to the spherical angles:
# (this is the equation of an ellipsoid):
x = rx * np.outer(np.cos(u), np.sin(v))
y = ry * np.outer(np.sin(u), np.sin(v))
z = rz * np.outer(np.ones_like(u), np.cos(v))

# Plot:
ax.plot_surface(x, y, z,  rstride=4, cstride=4, color='b')

# Adjustment of the axes, so that they all have the same span:
max_radius = max(rx, ry, rz)
for axis in 'xyz':
    getattr(ax, 'set_{}lim'.format(axis))((-max_radius, max_radius))

plt.show()

rawDescription: Plotting Ellipsoid with Matplotlib

description: Plotting Ellipsoid with Matplotlib


code:
rng = date_range('1/1/2011', periods=5, freq='H')
df = DataFrame({'price':[1,2,3,4,5]},index = rng)
df
df.index
df.index.values

rawDescription: Time series through pandas

description: Time series through pandas


code:
import csv

with open('linklist.csv', 'rb') as input_file, \
        open('Link Statements9.txt', 'w') as output_file:

    for row in csv.reader(input_file, delimiter=',', quoting=csv.QUOTE_NONE):
        link_name, from_unit, to_unit, rate = row
        output_file.write("Establish link %s at %s Kbps to Unit %s.\n"
                          % (link_name, rate, to_unit))
        output_file.write("Establish link %s at %s Kbps from Unit %s.\n"
                          % (link_name, rate, from_unit))

rawDescription: Python: Trying to identify specific row/column in csv and store it as a variable, then print to a txt file in a sentence.


code:
def __radd__(self, other):
    return other + self

rawDescription: Python user define magic method

description: Python user define magic method


rawDescription: Simultaneously inserting and extending a list?


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

df1 = pd.DataFrame(np.random.rand(100))
df2 = pd.DataFrame(np.random.rand(100))

df1.hist(bins=10,color='b')
df2.hist(bins=10,ax=plt.gca(),alpha=0.5,color='r')

plt.show()

rawDescription: overlay two densities in one plot

description: Overlay two densities in one plot


code:
import numpy
import skimage
import skimage.io

img = skimage.io.imread('uY173.png')

import skimage.transform

img50_order0 = skimage.img_as_ubyte( skimage.transform.rescale(img, 0.5, order=0, clip=True) )
img50_order1 = skimage.img_as_ubyte( skimage.transform.rescale(img, 0.5, order=1, clip=True) )

img50_lm = numpy.rint( skimage.transform.downscale_local_mean(img, (2,2,1), clip=True) )

import scipy.ndimage.interpolation

img50_nd = scipy.ndimage.interpolation.zoom(img, (0.5, 0.5, 1))

# plot section of green channel along horizontal axis
plot(img50_order0[50, :, 1])
plot(img50_order1[50, :, 1])
plot(img50_lm[50, :, 1])
plot(img50_nd[50, :, 1])

rawDescription: Image gradients become inaccurate when downscaling using a variety of different methods


code:
combined_dict = defaultdict(set)

# first add all the values from MyDict
for key, value in MyDict.iteritems():
    combined_dict[int(key)].add(value)

# then add the values from the file
infile = open('FileWithTheData.csv', 'r')
for line in infile.readlines():
    spl_line = line.split(',')
    combined_dict[int(sp_line[0])].update(spl_line[1:])

rawDescription: Converting dict values into a set while preserving the dict


code:
from lxml import etree

tree = etree.parse("input.xml")
print(tree.find(".//ETH0_IP").text)
print(tree.findtext(".//ETH0_IP"))
print(tree.xpath("//ETH0_IP")[0].text)

rawDescription: Python XML Grab IP from File Between CDATA


code:
import graphics
from graphics import color_rgb
import random

window= graphics.GraphWin("x", 600, 400)
stripes = input("How many stripes should be on the flag")
stripes = int(stripes)
#count = 0
#count = int(count)
#P1=graphics.Point(0,0) #left corner - anchor point
stepdim = 400/stripes #size of divisions
for x in range(stripes): #loop for number of stripes
    #col= random.randint(1,255)
    #stepdim = int(stepdim)
    #shrink = count*stepdim
    #shrink = int(shrink)
    #stepdim = stepdim*10 #enlarge to an increment below the last
    #stepdim = stepdim-shrink
    #stepdim = int(stepdim)
    #P2=graphics.Point(600,stepdim) #bottom right corner - ever shrinking
    P1=graphics.Point(0, stepdim * x) #left corner - anchor point
    P2=graphics.Point(600,stepdim * (x + 1)) #bottom right corner - ever shrinking
    outsiderec=graphics.Rectangle(P1,P2)
    #outsiderec.setFill(color_rgb(100, col, 0))
    red = random.randint(1, 255)
    green = random.randint(1, 255)
    blue = random.randint(1, 255)
    outsiderec.setFill(color_rgb(red, green, blue))
    outsiderec.draw(window)
    #count= count + 1
    #count= int(count)
window.getMouse()
window.close()

rawDescription: Colors not varying - python graphics

description: Colors not varying - python graphics


code:
from tkinter import *

root = Tk()

class App:
    def __init__(self):
        root.title("Start up page")
        root.geometry("1920x1080")
        self.beginB = Button(root, text="Begin", command=self.begin,
                        bg="green", height=10, width=30)
        self.beginB.grid(sticky = W)
    def begin(self):
        root.title("main window")
        self.beginB.destroy()
        del self.beginB
        self.goB = Button(root, text='Go on', command=self.go_on,
                                bg='red')
        self.goB.grid(sticky=E)
    def go_on(self):
        self.label = Label(root, text="you have continued")
        self.label.grid(row=1, sticky=S)

App()
root.mainloop()

rawDescription: Tkinter - How would I create buttons in a new window, which has been created by a function being called? Python 3


code:
from django.template.defaultfilters import slugify
class SomeModel(models.Model):
    title = models.CharField(max_length=100)
    def video_filename(instance, filename):
        fname, dot, extension = filename.rpartition('.')
        slug = slugify(instance.title)
        return '%s.%s' % (slug, extension)
    video = models.FileField(upload_to=video_filename)

rawDescription: How to update the filename of a Django's FileField instance?

description: Update the filename of a Django's FileField instance


code:
def get_indicator_form(indicator, patient):
    class IndicatorForm(forms.Form):
        indicator_id = forms.IntegerField(initial=indicator.id, widget=forms.HiddenInput())
        patient_id = forms.IntegerField(initial=patient.id, widget=forms.HiddenInput())

        def __init__(self, *args, **kwargs):
            forms.Form.__init__(self, *args, **kwargs)
            self.indicator = indicator
            self.patient = patient

    for field in indicator.indicatorfield_set.all():
        IndicatorForm.base_fields[field.name] = field.get_field_type()

    return IndicatorForm

rawDescription: Why don't these class attributes register?


code:
def look_around(self):
    max_sugar_point = self.point
    max_sugar = self.world.sugar_map[self.point].level
    min_range = 0

    selfx = self.point[0]
    selfy = self.point[1]
    wlength = self.world.surface.length
    wheight = self.world.surface.height
    occupied = self.world.occupied
    sugar_map = self.world.sugar_map
    all_directions = self.all_directions

    random.shuffle(all_directions)
    for r in range(1, self.vision+1):
        for dx,dy in all_directions:
            p = ((selfx + r * dx) % wlength,
                (selfy + r * dy) % wheight)
            if occupied(p): # checks if p is in a lookup table (dict)
                continue
            if sugar_map[p].level > max_sugar:
                max_sugar = sugar_map[p].level
                max_sugar_point = p
    if max_sugar_point is not self.point:
        self.move(max_sugar_point)

rawDescription: agent-based simulation: performance issue: Python vs NetLogo & Repast

description: Agent-based simulation: performance issue: Python vs NetLogo & Repast


code:
import asyncio
import weakref

def ensure_weakly_binding_future(method):
    class Canceller:
        def __call__(self, proxy):
            self.future.cancel()

    canceller = Canceller()
    proxy_object = weakref.proxy(method.__self__, canceller)
    weakly_bound_method = method.__func__.__get__(proxy_object)
    future = asyncio.ensure_future(weakly_bound_method())
    canceller.future = future

class ClassWithTimer:
    def __init__(self):
        ensure_weakly_binding_future(self.update)

    def __del__(self):
        print("deleted ClassWithTimer!", flush=True)

    async def update(self):
        while True:
            await asyncio.sleep(1)
            print("IN update of object " + repr(self), flush=True)

async def run():
    foo = ClassWithTimer()
    await asyncio.sleep(5.5)
    del foo
    await asyncio.sleep(2.5)

loop = asyncio.get_event_loop()
loop.run_until_complete(run())

rawDescription: Creating a temporary async timer callback to a bound method with python-asyncio


code:
from bson import json_util
json_util.dumps(MyDoc._collection_obj.find(MyDoc.objects()._query))

rawDescription: Return MongoEngine Documents as JSON

description: Return MongoEngine Documents as JSON


code: A, B = [matrix(zeros(shape=(3,3), dtype=complex)) for _ in range(2)]

rawDescription: Python is there an easier way to define multiple zeroed matrices?


code: plt.ylim(min(y_pos)-1, max(y_pos)+1)

rawDescription: manipulating top and bottom margins in pyplot horizontal stacked bar chart (barh)

description: Manipulating top and bottom margins in pyplot horizontal stacked bar chart (barh)


code:
from bokeh.io import vform
from bokeh.models import HoverTool, CustomJS
from bokeh.models.widgets import TextInput
from bokeh.plotting import output_file, figure, show, ColumnDataSource

output_file("plot.html")

words = ["werner", "herbert", "klaus"]
x, y = [1,2,3], [1,2,3]
color = ['green', 'blue', 'red']

source = ColumnDataSource(data=dict(x=x, y=y, words=words, color=color))

hover = HoverTool(tooltips=[("word", "@words")])

p = figure(plot_height=600, plot_width=800, title="word2vec", tools=[hover])
p.circle('x','y', radius=0.1, fill_color='color', source=source, line_color=None)

callback = CustomJS(args=dict(source=source), code="""
    var data = source.get('data')
    var value = cb_obj.get('value')
    var words = data['words']
    for (i=0; i < words.length; i++) {
        if ( words[i]==value ) { data.color[i]='yellow' }
    }
    source.trigger('change')
""")

word_input = TextInput(value="word", title="Point out a word", callback=callback)

layout = vform(word_input, p)

show(layout)

rawDescription: How to change the color of a glyph using callback?

description: Change the color of a glyph using callback


rawDescription: Numpy Multiply Size

description: Numpy Multiply Size


code:
df
pages
df.isin(pages)

rawDescription: Creating an inclusion table

description: Creating an inclusion table


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

a = -2
b = 2

x = (b - a) * np.random.random(50) + a
y = (b - a) * np.random.random(50) + a
z = (b) * np.random.random(50)

fig = plt.figure()
hdl = plt.scatter(x,y,s=20,c=z,marker='o',vmin=0,vmax=2)
ax = plt.gca()
ax.set_xlim([-2,2])
ax.set_ylim([-2,2])

#[(lower left x, lower left y), (upper right x, upper right y)] of the desired colorbar:
dat_coord = [(-1.5,1.5),(-0.5,1.75)]
#transform the two points from data coordinates to display coordinates:
tr1 = ax.transData.transform(dat_coord)
#create an inverse transversion from display to figure coordinates:
inv = fig.transFigure.inverted()
tr2 = inv.transform(tr1)
#left, bottom, width, height are obtained like this:
datco = [tr2[0,0], tr2[0,1], tr2[1,0]-tr2[0,0],tr2[1,1]-tr2[0,1]]
#and finally the new colorabar axes at the right position!
cbar_ax = fig.add_axes(datco)
#the rest stays the same:
clevs = [0, 1 , 2]
cb1 = plt.colorbar(hdl, cax=cbar_ax, orientation='horizontal', ticks=clevs)

plt.show()

rawDescription: Python matplotlib: position colorbar in data coordinates


rawDescription: How can I check with boto if a python (django) app is running in EC2?

description: Check with boto if a python (django) app is running in EC2


code:
df = pd.read_csv("eye.csv",sep="\s+")
df["duration"] = df.dropna().groupby("event")["time"].transform("ptp")
df

rawDescription: Calculating the duration an event in a time series data frame (python 2.7)


code:
import wx

class GaugeFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "Gauge example",
                          size=(350, 150))
        panel = wx.Panel(self, -1)
        self.count = 0
        self.gauge = wx.Gauge(panel, -1, 50, (20, 50), (250, 25))
        self.update_gauge()

    def update_gauge(self):
        self.count = self.count + 1
        if self.count >= 50:
            self.count = 0
        self.gauge.SetValue(self.count)
        wx.CallLater(100, self.update_gauge)

app = wx.PySimpleApp()
GaugeFrame().Show()
app.MainLoop()

rawDescription: wxPython gauge problem (skipping)

description: WxPython gauge problem (skipping)


code: re.compile(r'\b(?:#|@|)[0-9]*%s[0-9]*\b' % re.escape(term), re.IGNORECASE)

rawDescription: Using Python regex for twitter data

description: Using Python regex for twitter data


code:
import multiprocessing
import cStringIO

import matplotlib.pyplot as plt
import numpy as np

import itertools

def main():
    """Generates 1000 random plots and saves them as .png's in RAM"""
    pool = multiprocessing.Pool()
    same_title = itertools.repeat('Plot %i')
    fig_files = pool.map(plot, itertools.izip(xrange(1000), same_title))

def plot(args):
    """Make a random plot"""
    # Unfortunately, pool.map (and imap) only support a single argument to
    # the function, so you'll have to unpack a tuple of arguments...
    i, titlestring = args

    outfile = cStringIO.StringIO()

    x = np.cumsum(np.random.random(100) - 0.5)

    fig = plt.figure()
    plt.plot(x)
    fig.savefig(outfile, format='png', bbox_inches='tight')
    plt.title(titlestring % i)
    plt.close()

    # cStringIO files aren't pickelable, so we'll return the string instead...
    outfile.seek(0)
    return outfile.read()

main()

rawDescription: Threading to quickly create a large number of charts


code:
def listify(fn=None, wrapper=list):
    """
    A decorator which wraps a function's return value in ``list(...)``.

    Useful when an algorithm can be expressed more cleanly as a generator but
    the function should return an list.

    Example::

        >>> @listify
        ... def get_lengths(iterable):
        ...     for i in iterable:
        ...         yield len(i)
        >>> get_lengths(["spam", "eggs"])
        [4, 4]
        >>>
        >>> @listify(wrapper=tuple)
        ... def get_lengths_tuple(iterable):
        ...     for i in iterable:
        ...         yield len(i)
        >>> get_lengths_tuple(["foo", "bar"])
        (3, 3)
    """
    def listify_return(fn):
        @wraps(fn)
        def listify_helper(*args, **kw):
            return wrapper(fn(*args, **kw))
        return listify_helper
    if fn is None:
        return listify_return
    return listify_return(fn)

rawDescription: Is there a library function in Python to turn a generator-function into a function returning a list?


code:
def longest_sentence_length(text):
    return max(len(sentence.split()) for sentence in text.split('.'))

rawDescription: Find the longest sentence (in words) of a given string


code: [match.start() for match in re.finditer(r"[^\s]+", words)]

rawDescription: Matching word boundries with non alnums included


code:
#!/usr/bin/env python3
from gi.repository import Gtk, WebKit, GLib, GdkPixbuf

svg = """
 <svg width="350" height="110">
   <rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
   </svg>
"""

class Window(Gtk.Window):
    def __init__(self):
        super().__init__()
        self.connect('delete-event', Gtk.main_quit)

        loader = GdkPixbuf.PixbufLoader()
        loader.write(svg.encode())
        loader.close()
        pixbuf = loader.get_pixbuf()
        image = Gtk.Image.new_from_pixbuf(pixbuf)

        self.add(image)
        self.show_all()

if __name__ == "__main__":
    Window()
    Gtk.main()

rawDescription: Create pixbuf in PyGtk3 from svg as string


code:
volumes = conn.get_all_volumes()
for volume in volumes:
    if not 'is_managed' in volume.tags:
      volume.add_tag('is_managed', True)

rawDescription: How to match a specific tag for a given volume in AWS with boto?

description: Match a specific tag for a given volume in AWS with boto


code:
inputs=T.dmatrix()
temp=self.layers[0].forwardPass(inputs)
for i in range(1,len(self.layers[:-1])):
    temp=self.layers[i].forwardPass(T.dot
    (temp,self.weights[i-1].transpose())+self.bias[i-1])
    output=self.layers[-1].forwardPass(T.dot(temp,self.weights[-1].
    transpose())+self.bias[-1])
self.activate=theano.function([inputs],output)

label=T.dmatrix()
reg_lambda=T.dscalar()
alpha=T.dscalar()
momentum=T.dscalar()
cost=T.nnet.categorical_crossentropy(output,label).mean()
for i,j in zip(self.weights,self.bias):
    cost+=T.sum(i**2)*reg_lambda
    cost+=T.sum(j**2)*reg_lambda
parameters=self.weights+self.bias
rates=[(alpha*T.grad(cost,parameter)+momentum*prev_rate)
for parameter,prev_rate in zip(parameters,self.prev_rate)]
updates=[(weight,weight-rate) for weight,rate
 in zip(parameters,rates)]+[(prev_rate,rate)
for prev_rate,rate in zip(self.prev_rate,rates)]
self.backprop=theano.function([inputs,label,reg_lambda,alpha,momentum],
cost,updates=updates)

rawDescription: MLP classifier in theano settles at local minima


code:
import sys
from music21 import *
import os
# input ("Please make sure that you have places all the krn files in a subdirectory called data. Press enter to continue")
for filename in os.listdir('./data'):
 s = converter.parse('./data/' + filename)
 sys.stdout.write('Processing ' + filename + '... ')
 numcant = -1
 nums = list()
 try:
  length = len(s.parts)
 except:
  length = 0
 if (length > 0):
  for num in range(0,length):
      # sys.stdout.write(s.parts[num].flat.getElementsByClass('SpineComment')[0].comment + ' - ')
      if (s.parts[num].flat.getElementsByClass('SpineComment')[0].comment == "Cantus"):
        numcant = num
        # print "cant "
        # print numcant
      else:
        # print "nums"
        nums.append(num)
        # print num
 else:
    # sys.stdout.write(' - no parts present.')
    sys.stdout.write('\n')

 try:
  length = len(nums)
 except:
  length = 0
 if (length > 0):
  sys.stdout.write('\n')
  if (numcant != -1):
    for num in nums:
      sys.stdout.write(' - ' + filename[:-4] + '_' + str(num) + '.mid written.\n')
      # print "cantus present"
      s2 = stream.Stream()
      s2.insert(0, s.parts[num])
      s2.insert(0, s.parts[numcant])
      # write the midi file
      s2.write('midi', './midi/' + filename[:-4] + '_' + str(num) + '.mid')
      # sys.stdout.write('I')
  else:
     sys.stdout.write(' - no cantus specified for this file.\n')
 else:
  sys.stdout.write(' - not enough parts in this file.\n')
 sys.stdout.write('\n')

rawDescription: Check which label or name a part (from krn) has in music21


code:
#!/usr/bin/env python
from multiprocessing import Process, Queue
from Queue import Empty
from PIL import Image
import cv2
import cv2.cv as cv
import numpy as np

def image_display(taskqueue):
   cv2.namedWindow ('image_display', cv2.CV_WINDOW_AUTOSIZE)
   while True:

      image = taskqueue.get()              # Added
      if image is None:  break             # Added
      cv2.imshow ('image_display', image)  # Added
      cv2.waitKey(10)                      # Added
      continue                             # Added

      if taskqueue.get()==None:
         continue
      else:
         image = taskqueue.get()
         im = Image.fromstring(image['mode'], image['size'], image['pixels'])
         num_im = np.asarray(im)
         cv2.imshow ('image_display', num_im)

if __name__ == '__main__':
   taskqueue = Queue()
   vidFile = cv2.VideoCapture('doppler.wmv')
   p = Process(target=image_display, args=(taskqueue,))
   p.start()
   while True:
      flag, image=vidFile.read()

      taskqueue.put(image)  # Added
      import time           # Added
      time.sleep(0.010)     # Added
      continue              # Added

      if flag == 0:
         break
      im = Image.fromarray(image)
      im_dict = {
      'pixels': im.tostring(),
      'size': im.size,
      'mode': im.mode,
      }
      taskqueue.put(im_dict)

taskqueue.put(None)
p.join()
cv.DestroyAllWindows()

rawDescription: Opencv multiprocessing in python - queue sync


code:
import re
text = "I was searching my source to make a big desk yesterday."
re.findall(r'\bs\w+', text)

rawDescription: How to find a word that starts with a specific character

description: Find a word that starts with a specific character


code:
mydict = {a:'foo', b:'bar', c:'spam', d:'eggs'}

boxes = [a, b, c]

for box in boxes:
   print('text=%s' % mydict[box])

rawDescription: Trouble creating Python loop

description: Trouble creating Python loop


code:
def __init__(self, l=None):
    if l is None:
        l = []
    self.mylist = l

rawDescription: Values of instance variables of superclass persist across instances of subclass


code:
self.var = IntVar(root)
self.var.set(1)
optionsmenu.add_checkbutton(label='Pop Up set to on??', command=self.togglePopUp,
                            variable=self.var, onvalue=1, offvalue=0)

rawDescription: Setting default value of a checkbutton in a menu to True


code:
# api.py
class CustomCommentResource(ModelResource):
    children = fields.ToManyField('self', lambda bundle: bundle.obj.customcomment_set.all(), null=True, blank=True, full=True)

    class Meta:
        queryset = CustomComment.objects.filter(parent_comment=None, active=True)
        resource_name = 'comment'

rawDescription: Django Tastypie: including relationship with the same model


code:
from bs4 import BeautifulSoup
stupid_html = "<html><p> Hello </p><table> </table></html>"
soup = BeautifulSoup(stupid_html )
list_of_tables = soup.find_all("table")
print( list_of_tables[0].previous )

rawDescription: python lxml.html: pull preceding text in html docstring

description: Python lxml.html: pull preceding text in html docstring


code:
from sklearn.svm import LinearSVC
from nltk.classify.scikitlearn import SklearnClassifier
classif = SklearnClassifier(LinearSVC())

rawDescription: Import SVM light file format in NLTK

description: Import SVM light file format in NLTK


code:
from traits.api \
    import HasTraits, Button, Range, Float
from traitsui.api \
    import View, Item, Group, RangeEditor
from traitsui.qt4.extra.bounds_editor import BoundsEditor

class Parameters(HasTraits):
    rgb_range = Range(0.,1.0)
    range1 = rgb_range
    range2 = rgb_range
    low_val = Float(0.0)
    high_val = Float(1.0)
    eval_button = Button("Eval")

    traits_view= View(
        Item('range1', editor=RangeEditor()),
        Item('range2', editor=BoundsEditor(low_name = 'low_val', high_name = 'high_val')),
        Item('eval_button'))

    def _range1_changed(self, value):
        print(value)

    def _low_val_changed(self):
        print(self.low_val)

    def _high_val_changed(self):
        print(self.high_val)

    def _eval_button_fired(self):
        print(self.range1)
        print(self.low_val)
        print(self.high_val)

if __name__ == '__main__':
    alg = Parameters()
    alg.configure_traits()

rawDescription: Usage of BoundsEditor in TraitsUI

description: Usage of BoundsEditor in TraitsUI


rawDescription: Python : csv.writer writing each character of word in separate column/cell


code:
for i, s in enumerate(lst_times):
    #print(s)
    f.write( str() + " " + str(s)+ " " + "\n" )

rawDescription: Use number of iteration in for-loop instead of element of list


code:
import itertools
[sum(x)/len(x) for x in itertools.izip(*a)]

rawDescription: Python: Finding average of a nested list


rawDescription: How does python perform variable assignment?


code:
from subprocess import *
readBody = Popen(["/bin/echo", varWithBody], stdout=PIPE)
mail = Popen(["/bin/mail", "-s", subjVariable, recipVariable], stdin=readBody.stdout, stdout=PIPE)
output = mail.communicate()[0]

rawDescription: Python subprocess: why won't the list of arguments work analogous to the full shell string?


code:
from time import sleep

action = webdriver.ActionChains(driver)
action.move_to_element(menu)
sleep(5)
action.click(hidden_submenu).perform()

rawDescription: Specify wait time between Actions when using Selenium Actionchains


code:
class MyTreeWidget(QtGui.QTreeWidget):
    itemDropped = QtCore.pyqtSignal()

    def dropEvent(self, event):
        if (event.mimeData().hasFormat('application/x-icon-and-text')):
            ...
            self.itemDropped.emit()

rawDescription: pyqt QTreeWidget signal on item drop

description: Pyqt QTreeWidget signal on item drop


code:
def at_least_fifty_rep(user):
    my_profile = ... # get the user profile
    return my_profile.reputation > 50

@user_passes_test(at_least_fifty_rep)
def my_custom_view(request):
    ...

rawDescription: Restrict certain users from adding new tags , django-taggit?


code:
def binary_search(x, a):
    lo = 0
    hi = len(a)

    while lo < hi:
        mid = (lo + hi) // 2

        if a[mid] < x:
            lo = mid + 1
        elif a[mid] > x:
            hi = mid
        elif mid > 0 and a[mid-1] == x:
            hi = mid
        else:
            return mid

    return -1

rawDescription: find lowest index of a given value in a presorted array

description: Find lowest index of a given value in a presorted array


code:
cipher_functions = lambda afile:swap_joker2(swap_joker1(afile))
def cipher_functions(afile):
    return swap_joker2(swap_joker1(afile))

import functional #third party, not maintained. Alternatives exist
cipher_functions = functional.compose(swap_joker1, swap_joker2)

rawDescription: how to compose two or more functions in python

description: Compose two or more functions in python


code: somedate = somedate.replace(day=1)

rawDescription: Alter day or month of datetime.date without subclass or helper functions that use the constructor


code:
widget = waitForObject(':Test Widget')

metaObject = widget.metaObject();
methodCount =  metaObject.methodCount()

for x in range(0, methodCount):
    method = metaObject.method(x)
    test.log(method.signature())

rawDescription: How to get method signatures of Qt object from Squish test script?

description: Get method signatures of Qt object from Squish test script


code:
proxy = bus.get_object('org.mpris.MediaPlayer2.rhythmbox','/org/mpris/MediaPlayer2')
properties_manager = dbus.Interface(proxy, 'org.freedesktop.DBus.Properties')
properties_manager.Set('org.mpris.MediaPlayer2.Player', 'Volume', 100.0)
curr_volume = properties_manager.Get('org.mpris.MediaPlayer2.Player', 'Volume')

rawDescription: MPRIS + Python (dbus): reading and writing properties


code:
for index, item in enumerate(biglist):
    if item == String1:
        list1.append(biglist[index + 1])

rawDescription: What is the most efficient way to to replace switch statement in my case?


rawDescription: How to specify string variables as unicode strings for pattern and text in regex matching?

description: Specify string variables as unicode strings for pattern and text in regex matching


code:
from sympy import Symbol
x = Symbol('s')
y = Symbol('s')
x == y
y = Symbol('s', complex=True)
x == y

rawDescription: Sympy substitutions using strings subs('x', 'w') instead of symbols subs(x, w)


code:
import os
os.system('net use')

rawDescription: Python Access Denied When Renaming A File


code:
s = 'one two three'
s.split()
lst = s.split()
len(lst)

rawDescription: how to find how many strings when .split is used

description: Find how many strings when .split is used


code:
class Bank(models.Model):
    name = models.Charfield()
    money = models.IntegerField()
    members = models.ManyToManyField(StockShares, through='Sale')

class StockShares(models.Model):
    name = models.Charfield()
    price = models.Charfield()

class Sale(models.Model):
    bank = models.ForeignKey(Bank)
    stockshares = models.ForeignKey(StockShares)
    date = models.DateField()

rawDescription: Django: many to many relationship model definition


code:
a=[1,2,3]
b=['a','b']
c=[1,2,3,4]
d=[1,2,3]

a==b    #returns False
a==c    #returns False
a==d    #returns True

rawDescription: how to compare two arrays in python?

description: Compare two arrays in python


code:
def my_sqrt(x):
    root1 = math.sqrt(x)
    root2 = -root1
    return root1,root2

rawDescription: Square roots in python

description: Square roots in python


code:
def is_palindrome(s):
   return s == s[::-1]

rawDescription: What possible improvements can be made to a palindrome program?


code:
import collections

animals = [['dog','cat'],['bird','cat'],['dog','squirrel']]
print(list(x[0] for x in collections.Counter(x[0] for x in animals).most_common()))

rawDescription: What is a way to return a list of most common item in a list of lists?


code:
import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = s.connect_ex(('127.0.0.1', 3306))

if result == 0:
    print('socket is open')
s.close()

rawDescription: Identifying listening ports using Python


code:
import numpy as np
import cv2

lower = np.array([175, 155, 186], np.uint8) # Note these ranges are BGR ordered
upper = np.array([195, 165, 230], np.uint8)
binary = cv2.inRange(im, lower, upper) # im is your BGR image
moments = cv2.moments(binary, True)
cx = moments['m10'] / moments['m00']
cy = moments['m01'] / moments['m00']

rawDescription: time lag in program for centroid calculation

description: Time lag in program for centroid calculation


code:
# From the csv reader, save it to a list
dlist=[]
for row in reader:
    # store only the non empty lines
    if any(row):
        dlist.append(row)
firstTime={}
for row in dlist:
    if row[1] not in firstTime: firstTime[row[1]] = row[0]
d={}
for row in dlist:
    d.setdefault(row[1],[]).append([row[0],row[2],firstTime[row[1]]])

rawDescription: Counting first appearance of a field in a CSV file


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

ax1 = plt.subplot2grid((4,4),(0, 0),rowspan=1,colspan=1)
ax2 = plt.subplot2grid((4,4),(1, 0),rowspan=1,colspan=1)
ax3 = plt.subplot2grid((4,4),(2, 0),rowspan=1,colspan=1)
ax4 = plt.subplot2grid((4,4),(3, 0),rowspan=1,colspan=1)

ax5 = plt.subplot2grid((4,4),(0, 1),rowspan=2,colspan=3)
ax6 = plt.subplot2grid((4,4),(2, 1),rowspan=2,colspan=3)

ax1.plot(range(100),np.random.randint(-100,100,100)/np.arange(1,101,1)**1,color='green')
ax1.axhline(10,color='orange',linestyle='--')
ax1.axhline(-10,color='orange',linestyle='--')
ax1.set_ylim(-20,20)
ax1.set_xticks([])
ax1.set_ylabel('D4',rotation=0)

ax2.plot(range(100),np.random.randint(-100,100,100)/np.arange(1,101,1)**1,color='green')
ax2.axhline(10,color='orange',linestyle='--')
ax2.axhline(-10,color='orange',linestyle='--')
ax2.set_ylim(-20,20)
ax2.set_xticks([])
ax2.set_ylabel('D3',rotation=0)

ax3.plot(range(100),np.random.randint(-100,100,100)/np.arange(1,101,1)**1,color='green')
ax3.axhline(10,color='orange',linestyle='--')
ax3.axhline(-10,color='orange',linestyle='--')
ax3.set_ylim(-20,20)
ax3.set_xticks([])
ax3.set_ylabel('D2',rotation=0)

ax4.plot(range(100),np.random.randint(-100,100,100)/np.arange(1,101,1)**1,color='green')
ax4.axhline(10,color='orange',linestyle='--')
ax4.axhline(-10,color='orange',linestyle='--')
ax4.set_ylim(-20,20)
#ax4.set_xticks([])
ax4.set_ylabel('D1',rotation=0)

X,Y = np.meshgrid(range(1000),range(4))
Z = np.random.randint(0,100,(4,1000))

ax5.pcolormesh(X,Y,Z,cmap = 'copper')
ax5.set_yticks([i for i in range(4)])

Zm = np.ma.masked_where(Z<90,Z)
ax6.pcolormesh(X,Y,Zm,cmap = 'copper')
ax6.set_yticks([i for i in range(4)])

plt.show()

rawDescription: Visualization of wavelets coefficients for different deconstruction levels


code:
import re
def mysplit(mystr):
    return re.split("([+-/*])", mystr.replace(" ", ""))
mysplit("A7*4")
mysplit("Z3+8")
mysplit("B6 / 11")

rawDescription: Splitting a Python String by math expressions


rawDescription: How to perform a calculation involving values from multiple rows?

description: Perform a calculation involving values from multiple rows


code:
from django.contrib.humanize.templatetags.humanize import naturalday
natural_day = naturalday(value)

rawDescription: Django humanize outside of template?

description: Django humanize outside of template


code:
import sys
sys.path.insert(0, 'example.zip')  # Add .zip file to front of path
import foobar

rawDescription: import python packages from a zip file in c/c++ standalone application

description: Import python packages from a zip file in c/c++ standalone application


code:
process=subprocess.Popen(['command','--option','foo'],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
inputdata="This is the string I will send to the process"
stdoutdata,stderrdata=process.communicate(input=inputdata)

rawDescription: Python execute command line,sending input and reading output


code:
from IPython.display import display
import sympy as sy

sy.init_printing()  # LaTeX like pretty printing for IPython

r = sy.Symbol('r', real=True)
c1 = sy.Symbol('c_1', positive=True)

f = sy.exp(-c1*r)
F = sy.integrate(f, (r, 0, sy.oo))
display(F)

rawDescription: Evaluation float('inf') times symbolic variable with Python


code:
import arabic_reshaper
from bidi.algorithm import get_display

reshaped_text = arabic_reshaper.reshape(u'اللغة العربية رائعة')
bidi_text = get_display(reshaped_text)

rawDescription: Kivy Text Input for Arabic Text

description: Kivy Text Input for Arabic Text


code:
class Patient(models.Model):
    primary_physician = models.ForeignKey('Physician', related_name='primary_patients')
    attending_physicial = models.ForeignKey('Physician', related_name='attending_patients')

rawDescription: How would you model this database relationship?


code:
other_lists = {
    'bannana': ["white", "red", "blue"],
    'tomato': ["red", "shiny", "grey"],
    'peach': ["séché", "mure", "moisi"]
}

randomlist = random.choice(['bannana', 'tomato', 'peach'])
for i in other_lists[randomlist]:
    if i in ab:
        if 'bannana' == randomlist:  # use 'in' for substring
            ...

rawDescription: How to find the name of a list

description: Find the name of a list


code:
l = [{'id':1,'name':'Foo'},{'id':2,'name':'Bar'}]
[tuple(d.values()) for d in l]

rawDescription: Python converting the values from dicts into a tuples


rawDescription: Pandas use groupby to apply a different function for each value of the groupby variable


code:
def delete_used_id():
    # open and save all ids
    id_file_r = open('C:/Users/my.name/Documents/IDs.txt', 'r')
    lines = id_file_r.readlines()
    first_line_unf = lines[0][3:]
    first_line = first_line_unf.strip()
    id_file_r.close()
    # reopen in write mode
    id_file_w = open('C:/Users/my.name/Documents/IDs.txt','w')
    for line in lines[1:]:
        id_file_w.write(line)
    id_file_w.close()
    print("Deleting used ID: " + first_line)

rawDescription: Python won't rewrite file with first line removed using readlines() and for loop


code:
import numpy as np
from scipy.interpolate import RectBivariateSpline
from matplotlib import pyplot as plt

x, y = np.ogrid[-1:1:10j,-1:1:10j]
z = (x + y)*np.exp(-6.0 * (x * x + y * y))

spl = RectBivariateSpline(x, y, z)

xi = np.linspace(-1, 1, 50)
yi = np.linspace(-1, 1, 50)
zi = spl(xi, yi, grid=False)

fig, ax = plt.subplots(1, 1)
ax.hold(True)
ax.imshow(z, cmap=plt.cm.coolwarm, origin='lower', extent=(-1, 1, -1, 1))
ax.scatter(xi, yi, s=60, c=zi, cmap=plt.cm.coolwarm)

rawDescription: How to use scipy.interpolate.interp2d for a vector of data?

description: Use scipy.interpolate.interp2d for a vector of data


rawDescription: How to generate a dict from an 2 dimensional array?

description: Generate a dict from an 2 dimensional array


code:
from sympy import *
from sympy.abc import x
p = Poly(x+1, x, domain='QQ')
p.diff(x)
diff(p, x)
diff(p, x).doit()

rawDescription: Why does sympy.diff not differentiate sympy polynomials as expected?


code:
example = 'My email is John@gmail.com. My name is John. Her email is Anna@gmail.com .I am sam'
s = '''Kaminey (English: (The) (Sc)oundrels()hggg) asd (sa) dsad is a 2009 Indian caper thriller film directed by Vishal Bhardwaj and featuring Shahid Kapoor, Priyanka Chopra and Amol Gupte in the lead (roles). Set against the backdrop of the Mumbai underworld, Kaminey follows a rivalry between a pair of twins, one with a lisp and the other with a stutter, over the course of a single day..'''
import re
re.findall(r'\((?:\([^()]*\)|[^()])*\)', s)

rawDescription: How to get string from parenthesis using regular expression in python

description: Get string from parenthesis using regular expression in python


code:
from some_module import SomeClass

import ctypes

my_c_func = do_the_ctypes_stuff() # see ctypes doc (linked above)

class WrappedClass(SomeClass):
    def added_method(self, *args, **kwargs):
        cargs = my_process_py_args(*args, **kwargs)
        cret = my_c_func(*cargs)
        my_apply_c_result(self, *cret)
        return my_make_py_result(self, *cret)

rawDescription: Attach C method to existing Python class


rawDescription: Problem reading hex data from image - python automatically converts to a string


code:
from Spotfire.Dxp.Application.Filters import ValueRange, RangeFilter
from datetime import datetime, timedelta

#these are both CaSeSeNsItIvE
data_table_name = "Compliance Items"
column_name = "EventTimestamp"
days_ahead = 60

start = datetime.now().strftime('%Y-%m-%d') # today's date
end = (datetime.now() + timedelta(days = days_ahead)).strftime('%Y-%m-%d') # days_ahead in the future

filter_range = ValueRange(start, end) # create a ValueRange to set the filter

dt = Document.Data.Tables[data_table_name] # get data table reference by name

# get filter reference by column name
filter = Document.FilteringSchemes.DefaultFilteringSchemeReference[dt][column_name].As[RangeFilter]()

filter.ValueRange = filter_range

rawDescription: How can I automatically update a filter when my analysis is opened?

description: Automatically update a filter when my analysis is opened


code:
def f(x):
  return reduce(lambda a, b: math.log(a+b), xrange(10**5), x)

rawDescription: Python multiprocessing.Pool() doesn't use 100% of each CPU


code: len(myArray)

rawDescription: Counting array elements in Python

description: Counting array elements in Python


code:
import os, sys

dataDir = 'fullpath of directory with images'
os.chdir(dataDir)

os.system('SETLOCAL EnableDelayedExpansion')
#This is the path of the imagemagick installation convert command.
#The invalid parameter I was  getting was because the computer was trying to
#use a different convert command.  This code sets convert as a different
#variable and then calls that new variable as the convert command.
os.system('SET IMCONV="C:\Program Files\ImageMagick-6.9.1-Q16\Convert"')
os.system('%IMCONV% *.jpg animated.gif')

rawDescription: Creating a gif in python using ImageMagick


code:
futures = set(futures)
while futures:
    f = ndb.Future.wait_any(futures)
    futures.remove(f)
    yield f

rawDescription: ndb aysnc "yield next" to consume get_multi_async

description: Ndb aysnc "yield next" to consume get_multi_async


rawDescription: Sum of Square Differences (SSD) in numpy/scipy


code: new_ingredients = [(name, quantity*multiplier, unit) for name,quantity,unit in ingredients]

rawDescription: How can I multiply all the numbers from a list to display a new list?

description: Multiply all the numbers from a list to display a new list


code:
class BaseMessage(object):
    def __init__(self, sender, receiver, read_only=True):
        self._sender = sender
        self._receiver = receiver
        self.read_only = read_only

    def __setattr__(self, name, value):
        # Have to use gettattr - read_only may not be defined yet.
        if getattr(self,"read_only",False):
            raise AttributeError("Can't set attributes as message is read only.")
        else:
            self.__dict__[name] = value

    def get_sender(self):    # Is a "get" and not "set" call, so it should be callable
        return self._sender  # disregarding self.read_only's value.

    def get_receiver(self):
        return self._receiver

class ImmutableMessage(BaseMessage):
    def __init__(self, sender, receiver, topic):  # read_only=True !
        # Have to make it read-write to start with
        super().__init__(sender=sender, receiver=receiver, read_only=False)
        # ... so we can set the topic
        self.topic = topic
        # Now make it read-only
        self.read_only = True

    # this call should fail as super's property is read_only=True.
    def set_topic_after_init(self,new_topic):
        self.topic = new_topic

rawDescription: Allow super to control __setattr__ on subclasses


rawDescription: Best way to save availability of user over days of week in python/django

description: Save availability of user over days of week in python/django


code:
import datetime
HelpRequest.objects.filter(creation_time__gte=(datetime.datetime.now() - datetime.timedelta(minutes=5)))

rawDescription: Django query a model since its creation to an X time


code:
def derivs(l):
  return [l[i + 1] - l[i] for i in range(len(l) - 1)]

rawDescription: How to calculate numerical trend lines in python

description: Calculate numerical trend lines in python


code:
df_col_list = []
def fileinput(files):
    for f in files:
        df = pd.read_csv(f, usecols=['DeltaS'])
        df.rename(columns={'DeltaS':f}, inplace=True)
        df_col_list.append(df)

concat = pd.concat(df_col_list, axis = 1)
concat.to_csv(your_output_path)

rawDescription: select column from files and write to new file with file name as column name

description: Select column from files and write to new file with file name as column name


code:
box1s = soup.find_all('div', class_='members_box1')
box2s = soup.find_all('div', class_='members_box2')
for box1, box2 in zip(box1s, box2s):
    data =  [re.sub('\s+', '', text).strip().encode('utf8') for text in box1.find_all(text=True) + box2.find_all(text=True) if text.strip()]
    print(','.join(data))

rawDescription: Scrape data and write in single line for every iteration BS4 python


code:
with open(append_file,'a+b') as writeFile:
    need_headers = True
    for input_file in lstFiles:
        with open(input_file,'rU') as readFile:
            headers = readFile.readline()
            if need_headers:
                # Write the headers only if we need them
                writeFile.write(headers)
                need_headers = False
            # Now write the rest of the input file.
            for line in readFile:
                writeFile.write(line)

rawDescription: Using CSV module to append multiple files while removing appended headers


code:
import pylab as p

t = p.arange(0.0, 2.0, 0.01)
s = p.sin(2*p.pi*t)

ax=p.subplot(111)
ax.plot(t, s, color='r',linewidth=1.0)
ax.set_ylim(-1,1)
ax.plot(t, s+1, color='g',linewidth=1.0, label="Graph2")
p.show()

ax=p.subplot(111)
ax.plot(t, s, color='r',linewidth=1.0)
ax.set_ybound(-1,1)
ax.plot(t, s+1, color='g',linewidth=1.0, label="Graph2")
p.show()

rawDescription: In matplotlib, what is the difference betweent set_xlim and set_xbound?


code:
import wx
import matplotlib
matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.patches import Rectangle
import matplotlib.cm as cm
import matplotlib.pyplot as plt

class Frame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent=parent)
        self.boxSizer1 = wx.BoxSizer(orient=wx.VERTICAL)
        self.SetSizer(self.boxSizer1)
        self.figure = Figure()
        self.canvas = FigureCanvas(self, -1, self.figure)
        self.boxSizer1.Add(self.canvas, 1, wx.EXPAND)
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None
        self.axes   = [self.figure.add_subplot(111), ]
        self.axes[0].plot(range(100), range(100))
        self.canvas.Bind(wx.EVT_ENTER_WINDOW, self.ChangeCursor)
        self.canvas.mpl_connect('button_press_event', self.on_press)
        self.canvas.mpl_connect('button_release_event', self.on_release)
        self.canvas.mpl_connect('motion_notify_event', self.on_motion)
        self.rect = Rectangle((0,0), 1, 1, fill=False, ec='r')
        self.axes[0].add_patch(self.rect)
        #store a property of whether the mouse key is pressed
        self.pressed = False

    def ChangeCursor(self, event):
        '''Change cursor into crosshair type when enter the plot area'''
        self.canvas.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))

    def on_press(self, event):
        '''Draw ROI rectangle'''
        self.pressed = True
        self.x0 = int(event.xdata)
        self.y0 = int(event.ydata)

    def on_release(self, event):
        '''When mouse is on plot and button is released, redraw ROI rectangle, update ROI values'''
        self.pressed = False
        self.redraw_rect(event)

    def redraw_rect(self, event):
        '''Draw the ROI rectangle overlay'''
        try:
            self.x1 = int(event.xdata)
            self.y1 = int(event.ydata)
            self.rect.set_xy((self.x0, self.y0))
            self.rect.set_width(self.x1 - self.x0)
            self.rect.set_height(self.y1 - self.y0)
        except:
            pass
        self.canvas.draw()

    def on_motion(self, event):
        '''If the mouse is on plot and if the mouse button is pressed, redraw ROI rectangle'''
        if self.pressed:
            # redraw the rect
            self.redraw_rect(event)

class App(wx.App):
    def OnInit(self):
        frame = Frame(None)
        self.SetTopWindow(frame)
        frame.Show(True)
        return True

if __name__=='__main__':
    app=App(0)
    app.MainLoop()

rawDescription: Matplotlib B1-Motion (mouse motion with key held down) equivalent?


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

#plot
r = np.arange(0, 3.0, 0.01)
theta = 2 * np.pi * r
rmax = 2.0
n_th = 6
th_pos = np.linspace(0.0, 2 * np.pi, n_th, endpoint=False)
n_r = 5
r_pos = np.linspace(0, rmax, n_r)

ax = plt.subplot(111, polar=True)

## Plot the grid
for pos in th_pos:
    ax.plot([th_pos]*2, [0, rmax], 'k:', lw=2)
for pos in r_pos[1:-1]:
    x = np.linspace(0, 2*np.pi, 50)
    y = np.zeros(50)+pos
    ax.plot(x, y, 'k:', lw=2)

## Plot your data
ax.plot(theta, r, color='r', linewidth=20)
ax.set_rmax(rmax)
ax.grid(False)

#set ticks and labels
ax.set_xticks(th_pos)
label_cols = ['Label ' + str(num) for num in np.arange(n_th)]
ax.set_xticklabels(label_cols, size=24)
ax.set_yticks(r_pos[1:])

plt.show()

rawDescription: In matplotlib, Is there a way to set gridlines below bars/lines/patches while retaining ticklabels above?


code:
import pandas as pd
# add this
import matplotlib.pyplot as plt
BabyDataSet = [('Bob', 968), ('Jessica', 155), ('Mary', 77), ('John', 578), ('Mel', 973)]
df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births'])
df['Births'].plot()
# add this too
plt.show()

rawDescription: Expect to get a plot, but just get axes coordinates with Pandas


code:
def scanFiles(dir):
    fout = open("animals.las", "w")
    for root, dirs, files in os.walk(dir):
        for file in files:
            if '.las' in file:
            # read the file
                fin = open(file, "r")
                str2 = fin.read()
                fin.close()
            # call the function and get the changed text
                str3 = replace_words(str2, word_dic)
            # write changed text back out
                fout.write(str3)
                #time.sleep(1)
    fout.close()

rawDescription: How can I change this script to also include a rename functionality?

description: Change this script to also include a rename functionality


code:
import gevent
from gevent import socket
from gevent.server import StreamServer
import redis

r = redis.Redis('localhost')

def handle_echo(sock, address):
    def read_loop(sock):
        while True:
            try:
                socket.wait_read(sock.fileno())
            except socket.error:
                break
            # read from socket

    def write_loop(sock):
        while True:
            try:
                socket.wait_write(sock.fileno())
            except socket.error:
                break
            # write to socket

    jobs = [gevent.spawn(func, sock) for func in (read_loop, write_loop)]
    gevent.joinall(jobs)

server = StreamServer(('', 8045), handle_echo)
server.serve_forever()

rawDescription: Waiting for both gevent socket and redis blocking blpop


code:
A=sparse.csr_matrix(np.arange(12).reshape(3,4))
A==10
(A==10).nonzero()
(A.A==10).nonzero()

rawDescription: SciPy Sparse Array: Get index for a data point


code:
df = pd.DataFrame([1, 0, 2, 3, 0], columns=['a'])
df = df.replace(0, np.NaN)
df.mean()

rawDescription: mean calculation in pandas excluding zeros

description: Mean calculation in pandas excluding zeros


code:
import datetime
def tmp_f(dt,x=None):
    return datetime.datetime.fromtimestamp(dt).isoformat()
mf = matplotlib.ticker.FuncFormatter(tmp_f)

ax = gca()
ax.get_xaxis().set_major_formatter(mf)
draw()

rawDescription: Quiver or Barb with a date axis

description: Quiver or Barb with a date axis


code:
#!/usr/bin/env python
import os
import signal
import subprocess

p = subprocess.Popen(['gnome-terminal', '--disable-factory', '-e', 'bash'],
                     preexec_fn=os.setpgrp)
# do something here...
os.killpg(p.pid, signal.SIGINT)

rawDescription: Terminate a gnome-terminal opened with subprocess


code: np.sum(Rxy, axis=0)

rawDescription: Add up all Subarrays together

description: Add up all Subarrays together


code:
class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
x = Complex(3.0, -4.5)
x.r, x.i

rawDescription: Which of the languages does Python resemble in its class syntax?


code:
def green(brightness):
    brightness = round(255 * brightness) # convert from 0.0-1.0 to 0-255
    return [255 - brightness, 255, 255 - brightness]

def blue(brightness):
    brightness = round(255 * brightness) # convert from 0.0-1.0 to 0-255
    return [255 - brightness, 255 - brightness, 255]

# etc., green(1.0) -> [0, 255, 0]

rawDescription: Converting 0-1 number to RGB blue scale (Python)


code:
import sys
sys.path.insert(0, 'your_path_here')
import custom_module

rawDescription: How to import custom python package by name

description: Import custom python package by name


code: outputfile.write(re.sub( re.compile('^\d{6}$', re.MULTILINE), "", inputfile.read()));

rawDescription: Regex does not work in

description: Regex does not work in


code:
condition = 'Symbol == "abcd"'
indices = table.getWhereList(condition)  # get indices
rows_array = table[indices]  # get values
new_rows = compute(rows_array)   # compute new values
table[indices] = new_rows  # update the indices with new values

rawDescription: PyTables batch get and update

description: PyTables batch get and update


code:
import socket
import sys

def main():
    if len(sys.argv) < 2:
        print("Usage: dnscheck hostname [hostname...]")
    else:
        for host in sys.argv[1:]:
            try:
                ip = socket.gethostbyname(host)
                print("{} resolves to {}".format(host, ip))
            except socket.gaierror:
                print("Could not resolve {}".format(host))

if __name__=="__main__":
    main()

rawDescription: Python: DNS Query: Pydns? Dig? Socket?

description: Python: DNS Query: Pydns? Dig? Socket


code:
def update_weights(w,x,y, learning_rate):
    inner_product = 0.0
    for f_ in range(len(x)):
        inner_product += (w[f_] * x[f_])
    dloss = inner_product - y
    for f_ in range(len(x)):
        w[f_] += (learning_rate * (-x[f_] * dloss))
    return w

rawDescription: SGD - loss starts increasing after some iterations


code:
searchtext='lost computer'
searchwords = searchtext.split()
query = "SELECT * FROM RedownloadList WHERE" + " AND ".join(["column like %s"]*len(searchwords))
self.db.query(query, searchwords)

rawDescription: python using torndb to search text

description: Python using torndb to search text


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

df = pd.DataFrame(np.random.rand(37,4), columns=list('ABCD'))
columns_my_order = ['C', 'A', 'D', 'B']
fig, ax = plt.subplots()
for position, column in enumerate(columns_my_order):
    ax.boxplot(df[column], positions=[position])

ax.set_xticks(range(position+1))
ax.set_xticklabels(columns_my_order)
ax.set_xlim(xmin=-0.5)
plt.show()

rawDescription: How to apply custom column order to boxplot?

description: Apply custom column order to boxplot


rawDescription: How to sample pandas DataFrame with replacement?

description: Sample pandas DataFrame with replacement


rawDescription: How do I get the values of a parsed query string in python?

description: Get the values of a parsed query string in python


rawDescription: How to re-match a group that did not capture anything?

description: Re-match a group that did not capture anything


code:
import re
original_string = "(black && green) || (red && blue)"
re.findall(r'\w+', original_string)

rawDescription: Regex Remove Character Sets From String and Add Them To An Array


code:
dd = pd.DataFrame(b.map(lambda x: tuple(x)), columns=['itemID']).reset_index()
dd['code'] = codes
dd.drop_duplicates(cols=["code", "itemID"])

rawDescription: Turn user/item interactions into sparse list removing duplicates


rawDescription: Efficiency between two sorting functions


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
CHI = np.linspace(-45, 45, 35);
M = np.linspace(0, 1, 35)
CHI, M = np.meshgrid(CHI, M)
R = 2*M*np.sin(  2 * np.deg2rad(CHI) )
surf = ax.plot_surface(CHI, M, R, rstride=1, cstride=1, cmap=cm.hsv,linewidth=0, antialiased=False)
surf.set_clim([-2, 2]) # <- this is the important line
ax.set_xlim(-45,45)
cbar = plt.colorbar(surf, shrink=1, aspect=12, ticks=[-2,-1,0,1,2])
plt.show()

rawDescription: End ticks in colorbar - matplotlib

description: End ticks in colorbar - matplotlib


code:
import IPython
# lots of code
# even more code
IPython.embed()

rawDescription: How can I start an interactive python/ipython session from the middle of my python program?

description: Start an interactive python/ipython session from the middle of my python program


code:
form = LoginForm() if request.method == 'POST' else LoginForm(request.args)
if form.validate_on_submit():
    if login_user(form.user, remember=form.remember_me.data) is True:
        flash(_('Logged in successfully.'))
    return redirect(form.next.data or url_for('index'))
return render_template('users/login.html', form=form)

rawDescription: Flask-WTF form not getting data

description: Flask-WTF form not getting data


code:
import csv

stopWords = getStopWordList('stopwords.txt')

def get_tweets(csv_file):
    "return list of tweet items"
    with open(csv_file, 'rb') as f:
        tweets = csv.reader(f, delimiter='"', quotechar='|')
        return tweets

def process_score(tweet):
    "compute score for given tweet text"
    score = 0
    processedTweet = processTweet(tweet)
    featureVector = getFeatureVector(processedTweet, stopWords)
    for feature in featureVector:
        score = score + get_scores("SentiWordNet_3.0.0_20130122.txt", feature)

    return score

def save_scores(csv_file, tweet_scores):
    "save given iterable to csv file"
    with open(csv_file, 'wb' ) as f:
        writer = csv.writer(f)
        writer.writerows(tweet_scores)

tweet_scores = [(tweet[1],process_score(tweet[1])) for tweet in get_tweets('semeval80.csv')]
save_scores('semevalSenti80.csv', tweet_scores)

rawDescription: Can't save dataset in CSV file using Python


code:
r = lxml.objectify.fromstring('<root><item>1</item><item>2</item></root>')
lxml.etree.tostring(r.item)

rawDescription: Turn element of lxml.objectify back into XML


code: target = open(target_path, "wb")

rawDescription: How do I capture an mp3 stream with python

description: Capture an mp3 stream with python


code: content = html.read()

rawDescription: Beautiful Soup and extracting a string part of an array


code:
class AreaCode(db.Model):
    __tablename__ = 'areacodes'

    area_code = db.Column(db.Integer, primary_key=True)

class Exchange(db.Model):
    __tablename__ = 'exchanges'

    exchange = db.Column(db.Integer, primary_key=True)
    area_code_pk = db.Column(db.Integer, db.ForeignKey('areacodes.area_code'),
                             primary_key=True)
    area_code = db.relationship('AreaCode', backref=db.backref('exchanges', lazy='dynamic'))

class PhoneNumber(db.Model):
    __tablename__ = 'phonenumbers'
    __table_args__ = (
        db.ForeignKeyConstraint(
            ['exchange_exchange', 'exchange_area_code_pk'],
            ['exchanges.exchange', 'exchanges.area_code_pk'],
        ),
    )

    phone_number = db.Column(db.Integer, primary_key=True)
    exchange_exchange = db.Column(db.Integer, primary_key=True)
    exchange_area_code_pk = db.Column(db.Integer, primary_key=True)
    exchange = db.relationship('Exchange', backref=db.backref('phone_numbers', lazy='dynamic'))

rawDescription: How Can I Build a ForeignKey to a Table Which Has Composite Primary Key?


rawDescription: verbose_name for a model's method

description: Verbose_name for a model's method


code:
dates = []
rawdates = ['2015-04-26 00:00:48', '2015-04-26 00:00:49']
for i in range(len(rawdates)):
  the_date = rawdates[i].split()
  dates.append(the_date)

dates

rawDescription: How to split dates from weather data file

description: Split dates from weather data file


code:
thingies = ['link.description', 'button.text]] </li>']
different_thingies = [thingy.split(']')[0] for thingy in thingies]
different_thingies

rawDescription: Getting text between brackets using regex and re


code:
class Survey(models.Model):
    survey_type = models.CharField(max_length=1, choices=SURVEY_TYPES)

    def __init__(self, *args, **kwargs):
        super().__init__(self, *args, **kwargs)
        self._old_survey_type = self.survey_type

    def clean(self):
        if (self.survey_type != self._old_survey_type) \
                and survey_typeself.response_set.exists():
            raise ValidationError('Cannot modify the type of a started survey')

rawDescription: Prevent change of field if related objects exist?


code:
# Retrieve root nodes and their immediate children only
SomeModel.tree.filter(level__lte=1)

rawDescription: Django MPTT : Filter by depth?

description: Django MPTT : Filter by depth


code:
# cancel current task
activation = current_task.activate()
if activation.undo.can_proceed():
   activation.undo()
   activation.cancel()

# allow to re-execute previous task
activation = previous_task.activate()
if activation.undo.can_proceed():
   activation.undo()

rawDescription: viewflow.io: What is the recommended pattern to go a step back in a flow?

description: Viewflow.io: What is the recommended pattern to go a step back in a flow


code:
from PIL import Image, ImageFont, ImageDraw

img = Image.open('my_chart.png')
w,h= img.size

# put pixels into 2D array for ease of use
data = list(img.getdata())
xy_data = []
for y in xrange(h):
    temp = []
    for x in xrange(w):
        temp.append(data[y*w + x])
    xy_data.append(temp)

# get the title
title = raw_input("Title:")

# load the font
font_size = 20
font = ImageFont.truetype("/path/to/font.ttf",font_size)

#  Get the required height for you images
height_needed = font.getsize(title)[1] + 2  # 2 px for padding

# get the upperleft pixel to match color
bg = xy_data[0][0]

# add rows to the data to prepare for the text
xy_data = [[bg]*w for i in range(height_needed+5)] + xy_data  # +5 for more padding

# resize image
img = img.resize((w,h+height_needed+5))

# convert data back to 1D array
data = []
for line in xy_data:
    data += line

# put the image back in the data
img.putdata(data)

# get the ImageDraw item for this image
draw = ImageDraw.Draw(img)

# draw the text
draw.text((5,0),title,font=font,fill=(0,0,0))  # fill is black

img.save('titled_plot.png')

rawDescription: Automate png formatting with python

description: Automate png formatting with python


code:
proc = subprocess.Popen('python /path/to/my/program/myProgram.py %s %s' % (date, time),
                        stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True,
                        env = {'PYTHONPATH': '~/:$PYTHONPATH',
                               'environment': '/path/to/environment/'})

rawDescription: Running external program using pipes and passing arguments in python


code:
import pathos.pp as pp
import pathos.multiprocessing as mp

def squared(x):
  return x**2

pppool = pp.ParallelPythonPool()
mppool = mp.ProcessingPool()

res = pppool.amap(squared, xrange(1000))
sqd = mppool.map(squared, xrange(1000))
sqd[:10], sqd[-10:]

sq = res.get()
sq[:10], sq[-10:]

thpool = mp.ThreadingPool()
s = thpool.imap(squared, xrange(1000))
s = list(s)
s[:10], s[-10:]

rawDescription: way too slow in retrieving results in parallel python (pp)

description: Way too slow in retrieving results in parallel python (pp)


code: data = pickle.load(open("\path\filename.txt","r")) # For only read file

rawDescription: I Want to know how to use a save file

description: I Want to know how to use a save file


code:
import gtk
import webkit

gtk.rc_parse_string("""style "hide-scrollbar-style"
{
  GtkScrollbar::slider_width = 0
  GtkScrollbar::min-slider-length = 0
  GtkScrollbar::activate_slider = 0
  GtkScrollbar::trough_border = 0
  GtkScrollbar::has-forward-stepper = 0
  GtkScrollbar::has-backward-stepper = 0
  GtkScrollbar::stepper_size = 0
  GtkScrollbar::stepper_spacing = 0
  GtkScrollbar::trough-side-details = 0
  GtkScrollbar::default_border = { 0, 0, 0, 0 }
  GtkScrollbar::default_outside_border = { 0, 0, 0, 0 }
  GtkScrolledWindow::scrollbar-spacing = 0
  GtkScrolledWindow::scrollbar-within-bevel = False
}
widget_class "*Scrollbar" style "hide-scrollbar-style"
widget_class "*ScrolledWindow" style "hide-scrollbar-style"
""")

view = webkit.WebView()
sw = gtk.ScrolledWindow()
sw.add(view)
sw.set_policy(gtk.POLICY_ALWAYS, gtk.POLICY_ALWAYS)

win = gtk.Window(gtk.WINDOW_TOPLEVEL)
win.add(sw)
win.set_default_size(200, 200)
win.show_all()

view.open("http://www.blackle.com/")

gtk.main()

rawDescription: Completely disable scrollbars on GTK webkit webview?


code:
@app.route('/')
def show_entries():
    entries = get_all_entries()
    for entry in entries:
        entry['text'] = markdown.markdown(entry['text'], extensions=['codehilite'])
    return render_template('list_entries.html', entries=entries)

rawDescription: Only Format <code> Tags w/ pygments

description: Only Format <code> Tags w/ pygments


rawDescription: Python find numbers not in set

description: Python find numbers not in set


rawDescription: Automaticaly update image in IPython notebook


rawDescription: retrieving list items from request.POST in django/python

description: Retrieving list items from request.POST in django/python


code:
import urllib2, mimetypes
from django.http import HttpResponse

def ForwardToSocketIO(request):
    # Capture the URL pattern
    path = request.get_full_path()

    # Create a URL opener
    response = urllib2.urlopen('http://localhost:20000%s' % path)

    # Capture and return response
    django_response = HttpResponse(response.read())
    django_response['Content-Type'] = 'octet-stream'

    return django_response

rawDescription: Redirect an octet stream in Apache using PHP or Django


code:
#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# generated by wxGlade HG on Sat Jan 21 15:09:27 2012

import wx

# begin wxGlade: extracode
# end wxGlade

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.notebook_1 = wx.Notebook(self, -1, style=0)
        self.notebook_1_pane_1 = wx.Panel(self.notebook_1, -1)
        self.notebook_2 = wx.Notebook(self.notebook_1_pane_1, -1, style=0)
        self.notebook_2_pane_1 = wx.Panel(self.notebook_2, -1)
        self.button_1 = wx.Button(self.notebook_2_pane_1, -1, "button_1")
        self.notebook_2_pane_2 = wx.Panel(self.notebook_2, -1)
        self.panel_1 = wx.Panel(self.notebook_1_pane_1, -1)
        self.notebook_1_pane_2 = wx.Panel(self.notebook_1, -1)
        self.notebook_1_pane_3 = wx.Panel(self.notebook_1, -1)

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: MyFrame.__set_properties
        self.SetTitle("frame_1")
        self.panel_1.SetBackgroundColour(wx.Colour(255, 255, 0))
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: MyFrame.__do_layout
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_3 = wx.BoxSizer(wx.VERTICAL)
        sizer_3.Add(self.button_1, 0, 0, 0)
        self.notebook_2_pane_1.SetSizer(sizer_3)
        self.notebook_2.AddPage(self.notebook_2_pane_1, "tab1")
        self.notebook_2.AddPage(self.notebook_2_pane_2, "tab2")

        sizer_2.Add(self.notebook_2, 0, wx.EXPAND, 0)      #<- notebook,proportion 0
        sizer_2.Add(self.panel_1, 1, wx.EXPAND, 0)         #<- panel,   proportion 1

        self.notebook_1_pane_1.SetSizer(sizer_2)
        self.notebook_1.AddPage(self.notebook_1_pane_1, "tab1")
        self.notebook_1.AddPage(self.notebook_1_pane_2, "tab2")
        self.notebook_1.AddPage(self.notebook_1_pane_3, "tab3")
        sizer_1.Add(self.notebook_1, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        self.Layout()
        # end wxGlade

# end of class MyFrame

if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    frame_1 = MyFrame(None, -1, "")
    app.SetTopWindow(frame_1)
    frame_1.Show()
    app.MainLoop()

rawDescription: wxPython: Resizing a notebook within a notebook

description: WxPython: Resizing a notebook within a notebook


code:
import grequests

urls = [
    'http://www.heroku.com',
    'http://tablib.org',
    'http://httpbin.org',
    'http://python-requests.org',
    'http://kennethreitz.com'
]

rs = (grequests.get(u) for u in urls)
grequests.map(rs)

rawDescription: Ideal method for sending multiple HTTP requests over Python?


code:
import random

sides = int (input ('Which die? ') )
count = int (input ('How many dice? ') )
print ( [random.randint (1, sides) for _ in range (count) ] )

rawDescription: Print More than one random number

description: Print More than one random number


code: AdminApp.edit(appName, ['-MapResRefToEJB', [[module, bean, URI, jndi, type]]])

rawDescription: Mapping resources to an application already installed


code:
import networkx as nx
import matplotlib.pyplot as plt

def load_nodes():
    text = '''  Node    Size
                1        523
                2        231
                3        102
                4         72
                1+2      710
                1+3      891
                1+3+4    621'''
    # load nodes into list, discard header
    # this may be replaced by some appropriate output
    # from your program
    data = text.split('\n')[1:]
    data = [ d.split() for d in data ]
    data = [ tuple([ d[0],
                    dict( size=int(d[1]) )
                    ]) for d in data]
    return data

def load_edges():
    text = '''  From   To
                1+2    1
                1+2    2
                1+3    1
                1+3    3
                1+3+4    1
                1+3+4    3
                1+3+4    4'''
    # load edges into list, discard header
    # this may be replaced by some appropriate output
    # from your program
    data = text.split('\n')[1:]
    data = [ tuple( d.split() ) for d in data ]
    return data

if __name__ == '__main__':
    scale_factor = 5
    G = nx.Graph()
    nodes = load_nodes()
    node_sizes = [ n[1]['size']*scale_factor
                  for n in nodes ]

    edges = load_edges()
    G.add_edges_from( edges )

    nx.draw_networkx(G,
                     pos=nx.spring_layout(G),
                     node_size = node_sizes)
    plt.axis('off')
    plt.show()

rawDescription: Proportional venn diagram for more than 3 sets


code:
def change_window(browser):
    """
    Simple window switcher without the need of playing with ids.
    @param browser: Current browser instance
    """
    curr = browser.current_window_handle
    all_handles = browser.window_handles
    for handle in list(set([curr]) - set(all_handles)):
        return browser.switch_to_window(handle)

rawDescription: Convert Selenium IDE Syntax to Python Webdriver


rawDescription: Average elements in sublists

description: Average elements in sublists


code:
import win32gui
import win32con

hwnd = win32gui.FindWindow('Notepad', None)
win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 100, 100, 300, 200, 0)

rawDescription: Set another program to always be on top?

description: Set another program to always be on top


rawDescription: Python stdin filename

description: Python stdin filename


code:
def get_ffmpeg_bin():
    ffmpeg_dir = helper_functions.get_ffmpeg_dir_path()
    FFMPEG_BIN = os.path.join(ffmpeg_dir, "ffmpeg.exe")
    return FFMPEG_BIN

def split_vid_from_path(video_file_path, start_time, end_time):
    ffmpeg_binary =  get_ffmpeg_bin()
    output_file_name = get_next_file_name(video_file_path)
    pipe = sp.Popen([ffmpeg_binary,"-v", "quiet", "-y", "-i", video_file_path, "-vcodec", "copy", "-acodec", "copy",
                 "-ss", start_time, "-t", end_time, "-sn", output_file_name ])

    pipe.wait()
    return True

sample_vid = os.path.join(get_sample_vid_dir_path(), "Superman-01-The_Mad_Scientist.mp4")
split_vid_from_path(sample_vid, "00:00:00", "00:00:17")

rawDescription: Python video editing -- How to trim videos


code:
from itertools import product, izip
from pprint import pprint

a = ['a_one', 'a_two', 'a_three']
b = ['b_one', 'b_two', 'b_three']

pprint(list(product(a, b)))
[('a_one', 'b_one'),
 ('a_one', 'b_two'),
 ('a_one', 'b_three'),
 ('a_two', 'b_one'),
 ('a_two', 'b_two'),
 ('a_two', 'b_three'),
 ('a_three', 'b_one'),
 ('a_three', 'b_two'),
 ('a_three', 'b_three')]

pprint(list(izip(a, b)))
[('a_one', 'b_one'), ('a_two', 'b_two'), ('a_three', 'b_three')]

rawDescription: Why does this for loop multiplies everything?


code:
db.query("""
    SELECT *
    FROM employee, department
    WHERE employee.DepartmentID = department.DepartmentID;
""")

rawDescription: What is the use of """...""" in python instead of "..." or '...', especially in MySQLdb cursor.execute


code:
class Workshop(object):
  def __init__(self, week, stream, strand, day, name):
    self.week = week
    self.stream = stream
    self.day = day
    self.strand = strand
    self.name = name

...
for row in workshop_reader:
  workshops['name'] = Workshop(...)

rawDescription: Python - Nested dict, versus hashing a tuple?


code:
import pickle
d1 = {1:'one', 2:'two', 3:'three'}
d2 = {1:'eleven', 2:'twelve', 3:'thirteen'}
d3 = {1:'twenty-one', 2:'twenty-two', 3:'twenty-three'}
data = [d1, d2, d3]
out = open('data.pickle', 'wb')
pickle.dump(data, out)
out.close()
input = open('data.pickle')
data2 = pickle.load(input)
data == data2

rawDescription: Does anyone know where there is a recipe for serializing data and preserving its order in the output?


code:
class JsonWriterPipeline(object):
    def __init__(self):
        self.file = (open(filepath, 'a'))
    def process_item(self, item, spider):
        self.file.write(json.dumps(dict(item)) + '\n')
        return item

rawDescription: Linux python read output from a running python script


code:
import re

def videoNameExists(vidName):
    vidName = vidName.encode("utf-8")
    # bugFixVidName = vidName.replace(":", "")
    bugFixVidName = re.sub(r'[:|]', "", vidName)
    search_url ='http://cdn-api.ooyala.com/v2/syndications/49882e719/feed?pcode=1xeGMxOt7GBjZPp2'.format(bugFixVidName) #this URL is altered to protect privacy for this post

rawDescription: Alternatives to string.replace() method that allows for multiple sub-string search and replace


rawDescription: Add zeros as prefix to a calculated value based on the number of digits


code:
import Tkinter as tk

class CustomPanedWindow(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.panes = []

    def add(self, widget, weight=1):
        '''Add a pane with the given weight'''
        self.panes.append({"widget": widget, "weight": weight})
        self.layout()

    def layout(self):
        for child in self.place_slaves():
            child.place_forget()

        total_weight = sum([pane["weight"] for pane in self.panes])
        rely= 0

        for i, pane in enumerate(self.panes):
            relheight = pane["weight"]/float(total_weight)
            # Note: relative and absolute heights are additive; thus, for
            # something like 'relheight=.5, height=-1`, that means it's half
            # the height of its parent, minus one pixel.
            if i == 0:
                pane["widget"].place(x=0, y=0, relheight=relheight, relwidth=1.0)
            else:
                # every pane except the first needs some extra space
                # to simulate a sash
                pane["widget"].place(x=0, rely=rely, relheight=relheight, relwidth=1.0,
                                     height=-2, y=2)
            rely = rely + relheight

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        paned = CustomPanedWindow(self)
        paned.pack(side="top", fill="both", expand=True)

        f1 = tk.Frame(self, background="red", width=200, height=200)
        f2 = tk.Frame(self, background="green", width=200, height=200)
        f3 = tk.Frame(self, background="blue", width=200, height=200)

        paned.add(f1, 1)
        paned.add(f2, 2)
        paned.add(f3, 4)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.geometry("400x900")
    root.mainloop()

rawDescription: Tkinter PanedWindow.sash_place() fails

description: Tkinter PanedWindow.sash_place() fails


code:
def multimap(value, f, count):
    for _ in range(count):
        value = f[value]
        yield value

print(list(multimap('a', {'a': 'b', 'b': 'c', 'c': 'd', 'd': 'a'}, 4)))

rawDescription: Multi-mapping a value while saving intermediate values