code:
import subprocess
firefox_path = "C:/Program Files/Mozilla Firefox/firefox.exe"
cmdline = [firefox_path]
with open('url_list.txt', 'r') as url_file:
    for url in url_file:
        cmdline.append(url)
subprocess.Popen(cmdline)

rawDescription: Opening several tabs in Firefox using Python


code:
def create_app(name):
    app = Flask(name)
    for url in urls:
        app.add_url_rule(url[0], methods=url[1], view_func=url[2])
    return app

app = create_app(__name__)

rawDescription: Django-styled Flask URL pattern for large application


code:
from django.http import StreamingHttpResponse

@csrf_exempt
def display_text(request):
    content = open('/your/file', 'r').read()
    response = StreamingHttpResponse(content)
    response['Content-Type'] = 'text/plain; charset=utf8'
    return response

rawDescription: Serving a django static text file

description: Serving a django static text file


code:
import matplotlib.pyplot as plt
import scipy.stats as stats

lower, upper = 3.5, 6
mu, sigma = 5, 0.7
X = stats.truncnorm(
    (lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma)
N = stats.norm(loc=mu, scale=sigma)

fig, ax = plt.subplots(2, sharex=True)
ax[0].hist(X.rvs(10000), normed=True)
ax[1].hist(N.rvs(10000), normed=True)
plt.show()

rawDescription: How to specify upper and lower limits when using numpy.random.normal

description: Specify upper and lower limits when using numpy.random.normal


code:
ta, tb = [], []
for i in range(min(len(a), len(b))):
    if a[i] is None or b[i] is None:
        continue
    ta.append(a[i])
    tb.append(b[i])

rawDescription: python: eliminate positions of nan in multiple lists

description: Python: eliminate positions of nan in multiple lists


code:
import AddressBook
from AddressBook import *

ab = AddressBook.ABAddressBook.sharedAddressBook()
p = ABPerson.alloc().init()
p.setValue_forProperty_('JOE', kABFirstNameProperty)
p.setValue_forProperty_('TEST', kABLastNameProperty)

phoneNumberMultiValue = ABMultiValueCreateMutable()
ABMultiValueAdd(phoneNumberMultiValue, '555-555-1212', kABPhoneMobileLabel, None);
ABMultiValueAdd(phoneNumberMultiValue, '555-555-1213', kABPhoneWorkLabel, None);
p.setValue_forProperty_(phoneNumberMultiValue, kABPhoneProperty);

ab.addRecord_(p)
ret = ab.save()

rawDescription: How do I add two phone numbers to the addressbook using pyObjc?

description: Add two phone numbers to the addressbook using pyObjc


code:
blockData = np.fromfile(ReadFile.fid, np.int16, num_receivers*num_channels*num_samples*2)
blockData = blockData.reshape((num_receivers, num_channes, num_samples, 2))
return np.hypot(blockData[:,:,:,0], blockData[:,:,:,1])

rawDescription: Python: Fastest way to iterate this through a large file


code:
class Dog(Animal):
    WOOF, YAP, HUSH = 'woof', 'yap', 'hush_puppy'
    def __init__(self, name, weight, bark=WOOF, **kwargs):
        self.bark = bark
        super(Dog, self).__init__(name, weight, **kwargs)

class Cat(Animal):
    HAIR_LONG, HAIR_SHORT = 'long', 'short'
    def __init__(self, name, weight,hair=HAIR_LONG, **kwargs):
        self.hair = hair
        super(Cat, self).__init__(name, weight, **kwargs)

dog = Dog("Snoopy", 60, bark=Dog.HUSH)
cat = Cat("Tigger", 50, kind="Tiger",hair=Cat.HAIR_SHORT)

rawDescription: Pythonic way to reduce the number of small subclasses in a base class?


rawDescription: Aggregate a column by only some keys in Pandas dataframe?


code:
ids = [random.randrange(100) for _ in range(200)]
from collections import Counter
counts = Counter(ids)
dupids = [id for id in ids if counts[id] > 1]

rawDescription: Remove unique values from a list and keep only duplicates


code: userinfo = models.ForeignKey(Userinfo, db_column='id')

rawDescription: How to manually define one to one key of legacy database in Django

description: Manually define one to one key of legacy database in Django


code:
def get_version_created_time(item):
    u = model_to_dict(item)
    meta_data = json.loads(u['meta_data'])
    for key, value in meta_data.iteritems():
        try:
            if value['current'] == True:
                return value['timestamp']
        except TypeError:
            pass

res_sorted = sorted(res, key=get_version_created_time, reverse=True)

rawDescription: python sort django models by value in json field

description: Python sort django models by value in json field


code:
from google.appengine.tools import dev_appserver
allowed_modes = dev_appserver.FakeFile.ALLOWED_MODES
dev_appserver.FakeFile.ALLOWED_MODES = frozenset(['w'])
f = open('test.txt', 'w')
f.write('this is a test')
f.close()
dev_appserver.FakeFile.ALLOWED_MODES = allowed_modes

rawDescription: AppEngine: restore original builtin open/file function


code:
import re
keywords = ['S0414', 'GT213', 'AT3423', 'PR342'] # etc - you probably get those from some source
pattern = re.compile('|'.join(keywords))

for line in inf:
    if pattern.search(ln):
        outf.write(line)

rawDescription: Extract specific text lines?

description: Extract specific text lines


code: before.pivot_table(index=['Email','Person'],columns=['Car'], aggfunc=lambda x: True).fillna(False).reset_index()

rawDescription: Flatten a Pandas DataFrame

description: Flatten a Pandas DataFrame


code:
from osgeo import gdal
help(gdal.ReprojectImage)

rawDescription: How can I change the resolution of a raster using GDAL?

description: Change the resolution of a raster using GDAL


code:
import random
import time
name = input("whats your name? ")
numOfNums = int(input("ok " + name + " how many numbers do you want to randomize? "))

def randomGenerator():
    randomFinal = random.randint(1, numOfNums)
    print (randomFinal)
    rerun = input("Do you want to pick another random number? ")
    if rerun == "yes":
        time.sleep(0.05)
        randomGenerator()
    else:
        print("you may now close this windows")

randomGenerator()

rawDescription: random.randomint with variables

description: Random.randomint with variables


code:
a = np.arange(10)
b = 'git push'
np.savez('file',a=a,b=b)
data = np.load('file.npz')
data.keys()
data['a']
str(data['b'])

rawDescription: Can I annotate a numpy array when saving it with savez

description: Annotate a numpy array when saving it with savez


code:
from xml.etree.ElementTree import Element, SubElement, Comment, tostring

# Configure one attribute with set()
root = Element('opml')
root.set('version', '1.0')

root.append(Comment('Generated by ElementTree_csv_to_xml.py for PyMOTW'))

rawDescription: Modify an XML file in Python

description: Modify an XML file in Python


code: {{ mylist|slice:"3:8" }}

rawDescription: Slicing a list in Django template

description: Slicing a list in Django template


code:
df
countries
df.countries.isin(countries)
df[df.countries.isin(countries)]
df[~df.countries.isin(countries)]

rawDescription: How to implement 'in' and 'not in' for Pandas dataframe

description: Implement 'in' and 'not in' for Pandas dataframe


code:
title0 = '{:#^{width}}'.format(' USA ', width=19)
title1 = '{:#^{width}}'.format(' Canada ', width=19)

rawDescription: Formatting a string to be a constant length in Python


code: file = str(QFileDialog.getExistingDirectory(self, "Select Directory"))

rawDescription: how to have a directory dialog in Pyqt

description: Have a directory dialog in Pyqt


code:
import ast
mylist = ast.literal_eval("['foo', ['cat', ['ant', 'bee'], 'dog'], 'bar', 'baz']")
mylist

rawDescription: How do I parse a string representing a nested list into an actual list?

description: Parse a string representing a nested list into an actual list


code:
import pylab
import matplotlib.colors
import numpy

im = pylab.imread('lena.png').sum(axis=2) # make grayscale
pylab.imshow(im, cmap=pylab.cm.gray)
pylab.title('orig')
imvals = numpy.sort(im.flatten())
lo = imvals[0]
hi = imvals[-1]
steps = (imvals[::len(imvals)/256] - lo) / (hi - lo)
num_steps = float(len(steps))
interps = [(s, idx/num_steps, idx/num_steps) for idx, s in enumerate(steps)]
interps.append((1, 1, 1))
cdict = {'red' : interps,
         'green' : interps,
         'blue' : interps}
histeq_cmap = matplotlib.colors.LinearSegmentedColormap('HistEq', cdict)
pylab.figure()
pylab.imshow(im, cmap=histeq_cmap)
pylab.title('histeq')
pylab.show()

rawDescription: Histogram Equalization of matplotlib color tables


code: prod['A'][(prod['A'] < targetA['A']) & (prod['A'] > targetB['A'])]

rawDescription: Pandas Dataframe Comparisons

description: Pandas Dataframe Comparisons


rawDescription: Specify variable as a value for starts with regex operator '^'


rawDescription: How to map numbers in range <0;99> to range <-1.0;1.0>?

description: Map numbers in range <0;99> to range <-1.0;1.0>


code:
@app.route('/process/<user_id>/<file_format>/<download>')
def download(user_id, file_format, download):
    return redirect(url_for('static', filename='documents/'+download))

rawDescription: Download file from local folder

description: Download file from local folder


code:
import nltk

text = 'Na casa de meu Pai há muitos aposentos; se não fosse assim, eu lhes teria dito. Vou preparar-lhes lugar.'
tokens = nltk.word_tokenize(text)

c = nltk.ConcordanceIndex(tokens, key=lambda s: s.lower())
result = []
for offset in c.offsets('Pai'):
    result += tokens[offset - 2: offset]
    result += tokens[offset + 1: offset + 3]

print(result)

rawDescription: Regex: get accented letters with spaces

description: Regex: get accented letters with spaces


code:
with open(infile, 'r') as f:
    polite_f = politer(f)
    current_id = None
    while True:
        id_dict = {}
        for i, line in enumerate(polite_f):
            id = get_id_from_line(line)
            if id != current_id:
                polite_f.send(line)
                break
            else:
                id_dict[i] = process_line(line)
        if current_id is not None:
            yield id_dict
        current_id = id

rawDescription: Read initially unknown number of N lines from file in a nested dictionary and start in next iteration at line N+1


code:
for url in url_input_file:
    while len(q) >= 100000:
        time.sleep(5)
    q.put(url)

rawDescription: Converting a Recursive program to loop based only


code:
import matplotlib
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt

matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['ytick.direction'] = 'out'

##################################################
# Define our surface
##################################################
delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

CS = plt.contour(X, Y, Z)

fmt = {}
strs = [ '54%', '10%', '3%', '47%', '51%', '66%', '7%' ]
for l,s in zip( CS.levels, strs ):
    fmt[l] = s

# Label every other level using strings
plt.clabel(CS,CS.levels[::2],inline=True,fmt=fmt,fontsize=10)

plt.show()

rawDescription: Contour plot python, how to change labels


code:
threads = []
while len(threads) < threadLimit:
    t=threading.Thread(target=run_command)
    threads.append(t)
    t.daemon = True
    t.start()
[thread.join() for thread in threads]

rawDescription: Multi threading and subprocess not spawning correct number of threads in python


rawDescription: Doing math to a list in python

description: Doing math to a list in python


code:
# In your settings
CACHES = {
    'images': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'images',
    }
}

# In your view, on the submit
from django.core.cache import caches
caches['images'].set('some-unique-cache-key', image_file.read(), 60)

'''Note: You'd probably want to set the cache key in the session,
so the other view can read it.'''

# In the other view, after the caption is set
from django.core.cache import caches
from django.core.files import File
import StringIO
tmp_file = StringIO.StringIO()
tmp_file.write(caches['images'].get('some-unique-cache-key'))

image_file = File(tmp_file)  # Now you have the image from the other view

rawDescription: Temporarily keeping image in memory before committing it to database in Django application


code:
lst = ['150', '200', '300']
lst[0] # Remember that indexing is 0-based in Python
lst[1]
lst[2]

rawDescription: Python: extract str value from list

description: Python: extract str value from list


code:
class Tree:
    def __init__(self, node, cargo, parent=None):
        self.node = node
        self.cargo = cargo
        self.parent  = parent
    def __str__(self):
        return str(self.cargo)

from copy import copy
def just_part(y):
    z = copy(y)
    for k,v in z.items():
        if isinstance(v, list):
            del z[k]
    return z

def rt(y):
    tt = []
    s = Tree( id(y), just_part(y) )
    tt.append(s)
    def recurse(y):
        for k,v in y.iteritems():
            if isinstance(v, list):
                [tt.append( Tree(id(i), just_part(i), id(y) ) ) for i in v]
                [recurse(i) for i in v]
            else:
                pass
    recurse(y)
    return tt

rawDescription: recursing a dictionary of lists of dictionaries, etc et al (python)

description: Recursing a dictionary of lists of dictionaries, etc et al (python)


rawDescription: finding and replacing elements in a list (python)

description: Finding and replacing elements in a list (python)


code:
themutex.acquire()
try:
    print('Do some stuff')
finally:
    themutex.release()

rawDescription: Python multithread basic questions

description: Python multithread basic questions


code:
i = 1

file.write('' + linecache.getline('support_files/sub_page_top_links.txt', i) + '')
i += 1

rawDescription: linecache.getline and how to loop to the next line

description: Linecache.getline and how to loop to the next line


code:
my_list = list(range(1, 11))
while my_list:  # no need for len(lst) > 0 here, list are falsey when empty
    index = int(input()) % len(my_list)  # get index from the user, wrap if necessary
    print(my_list[index])                # print out the value at the requested index
    my_list = my_list[index+1:] + my_list[:index]  # rebuild the list without that value

rawDescription: pythonic way to use circular list

description: Pythonic way to use circular list


code:
class XmlObj(dict):
    def __init__(self,xml,*args,**kwargs):
        super(dict,self).__init__(*args,**kwargs)
        if xml.firstChild.nodeName == '#text':
            self.__setattr__( 'text', xml.firstChild.nodeValue )
            return
        else:
            for node in xml.childNodes:
                if self.has_key( node.nodeName ):
                    item = self.__getitem__(node.nodeName)
                    if type( item ) is not type( [] ):
                        item = [item]
                        item.append( XmlObj( node ))
                    self.__setitem__(node.nodeName, item )
                else:
                    self.__setitem__(node.nodeName, XmlObj(node) )

    def __repr__(self):
        if hasattr(self,'text'):
            return self.__getattribute__('text')
        else:
            result = ["%r: %r" % (key, self[key]) for key in sorted(self)]
            return "{" + ", ".join(result) + "}"

    __str__ = __repr__

rawDescription: Complete representation of a dict extended superclass


code:
import ast
x = {}
x['hello'] = 'world'
x['num'] = 42
x['values'] = {'a': 1, 'b': 2, 'c': 3}
repr(x)
with open('/tmp/test.py', 'w') as f: f.write(repr(x))
with open('/tmp/test.py', 'r') as f: y = ast.literal_eval(f.read())
y

rawDescription: How to serialize a python dict to text, in a human-readable way?

description: Serialize a python dict to text, in a human-readable way


code:
import pyparsing as pp

text = '''\
///
/// foobar
///
blah blah
/// /// bar ///
///  /// /// baz  /// ///
'''

comment=pp.nestedExpr("///","///")
for match in comment.searchString(text):
    print(match)
    # [['///', 'foobar']]
    # [['///', 'bar']]
    # [[['///', 'baz']]]

rawDescription: pyparsing - parse xml comment

description: Pyparsing - parse xml comment


code:
@api_view('GET')
@permission_classes((IsAuthenticated, ))
def example_view(request, format=None):
    content = {
        'status': 'request was permitted'
    }
    return Response(content)

rawDescription: Django - Custom permissions for function based views


code:
import pandas as pd
import numpy as np
import itertools
import seaborn as sns

methods=['method 1', 'method2', 'method 3', 'method 4']
times = range(0, 100, 10)
data = pd.DataFrame(list(itertools.product(methods, times, times)))
data.columns = ['method', 'dtsi','rtsi']
data['nw_score'] = np.random.sample(data.shape[0])

def facet_heatmap(data, color, **kws):
    data = data.pivot(index="dtsi", columns='rtsi', values='nw_score')
    sns.heatmap(data, cmap='Blues', **kws)  # <-- Pass kwargs to heatmap

with sns.plotting_context(font_scale=5.5):
    g = sns.FacetGrid(data, col="method", col_wrap=2, size=3, aspect=1)

cbar_ax = g.fig.add_axes([.92, .3, .02, .4])  # <-- Create a colorbar axes

g = g.map_dataframe(facet_heatmap,
                    cbar_ax=cbar_ax,
                    vmin=0, vmax=1)  # <-- Specify the colorbar axes and limits

g.set_titles(col_template="{col_name}", fontweight='bold', fontsize=18)
g.fig.subplots_adjust(right=.9)  # <-- Add space so the colorbar doesn't overlap the plot

rawDescription: Getting a legend in a seaborn FacetGrid heatmap plot


code:
keep = lambda x: not isinstance(x, mpl.patches.FancyArrowPatch)
ax.patches = [patch for patch in ax.patches if keep(patch)]

rawDescription: deleting streamplots (matplotlib) without clearing the graph

description: Deleting streamplots (matplotlib) without clearing the graph


code:
d = {'Bill': 4, 'Alex' : 4, 'Bob' : 3, "Charles": 7}
sorted(d, key=lambda k: (d[k], k))

rawDescription: Sort dictionary by multiple values

description: Sort dictionary by multiple values


code:
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://factfinder.census.gov/faces/nav/jsf/pages/searchresults.xhtml?refresh=t")

wait = WebDriverWait(driver, 10)
actions = ActionChains(driver)

# click "Topics"
topics = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a#topic-overlay-btn")))
driver.execute_script("arguments[0].click();", topics)

# click "Dataset"
dataset = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span[title=Dataset]")))
dataset.click()

rawDescription: Interacting with javascript scrollable container from python/selenium


code:
from collections import Counter
l = [1,2,2,3,1,1,2,3,4,5,6]
Counter(l)

rawDescription: frequency of all elements of list in Python

description: Frequency of all elements of list in Python


code:
LIVING_CELL = 'A'
DEAD_CELL = '.'

#Get the alive cells from the user
def getBoard(rows, cols):
    myList = [[0]*cols for i in range(rows)]
    while True:
        raw = input('Please enter "row <space> column", of a cell to turn on (RETURN to exit): ')
        if raw == '':
            break
        splitted = raw.split()
        if len(splitted) != 2:
            print("Invalid input")
        else:
            row, col = int(splitted[0]), int(splitted[1])
            if row >= rows or col >= cols:
                print("Invalid row/column value")
            else:
                myList[row][col] = 1
                printBoard(rows, cols, myList)
    return myList

#next board cells
def getNxtIter(rows, cols, cur, nxt):
    for i in range(rows):
        for j in range(cols):
            nxt[i][j] = getNeighbors(rows, cols, i, j, cur)

#Processing the neighbor cells
def getNeighbors(rows, cols, x, y, boardList):
    nCount = 0
    for j in range(y-1,y+2):
        for i in range(x-1,x+2):
            if not(i == x and j == y):
                itest, jtest = i, j
                if itest == rows:
                    itest = 0
                if jtest == cols:
                    jtest = 0
                nCount += boardList[itest][jtest]
    if nCount == 3 or (boardList[x][y] == 1 and nCount == 2):
        return 1
    return 0

#Printing and forming the actual board
def printBoard(rows, cols, boardList):
    for i in range(rows):
        line = []
        for j in range(cols):
            if boardList[i][j] == 1:
                line.append(LIVING_CELL)
            else:
                line.append(DEAD_CELL)
        print("".join(line))

def main():
    #Getting and validating the number of rows and columns
    while True:
        rows = int(input("Please enter the number of rows: "))
        if rows > 0 and rows <= 50:
            break

    while True:
        cols = int(input("Please enter the number of columns: "))
        if rows > 0 and rows <= 50:
            break

    boardList = getBoard(rows, cols)
    newBoardList = [x[:] for x in boardList]

    print()

    #Getting iterations to run, and validating if <= 0
    while True:
        iterations = int(input("How many iterations should I run? "))+1
        if iterations > 0:
            break

    for count in range(iterations):
        print()
        print("Iteration:", count)
        print()
        printBoard(rows, cols, boardList)
        getNxtIter(rows, cols, boardList, newBoardList)
        boardList, newBoardList = newBoardList, boardList

main()

rawDescription: Python - Conways Game of life

description: Python - Conways Game of life


code:
from pprint import pprint
a = [0, 1, ['a', 'b', 'c'], 2, 3, 4]
pprint(a)

rawDescription: Is there a pretty printer for python data?


code: dictionary['foo' if otherset == 'bar' else 'bar'].discard(element)

rawDescription: Remove a given element from the other set in a dict of two sets


code:
from sqlalchemy import and_, or_

db.query(ShippingRate).filter(or_( \
    and_(ShippingRate.minimum == None, ShippingRate.maximum == None), \
    and_(ShippingRate.minimum != None, ShippingRate.maximum != None,  literal(myVal).between(ShippingRate.minimum, ShippingRate.maximum)), \
    and_(ShippingRate.minimum == None, myVal < ShippingRate.maximum), \
    and_(ShippingRate.maximum == None, myVal > ShippingRate.minimum)))

rawDescription: How to filter based on two columns where one column may not be defined using SQLAlchemy?

description: Filter based on two columns where one column may not be defined using SQLAlchemy


code:
from subprocess import call
if arg2:
    call(["python", "myscript.py", "--arg1"])

rawDescription: Python script that calls itself

description: Python script that calls itself


code:
def find_spam(xml):
    for event, element in xml.etree.ElementTree.iterparse(xml):
        if element.tag == "spam":
            print("We found a spam!")
            # Potentially do something
            yield element

rawDescription: How to return data from a Python SAX parser?

description: Return data from a Python SAX parser


code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class AppForm(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.create_main_frame()

    def create_main_frame(self):
        page = QWidget()

        self.button = QPushButton('joy', page)
        self.edit1 = QLineEdit()
        self.edit2 = QLineEdit()

        vbox1 = QVBoxLayout()
        vbox1.addWidget(self.edit1)
        vbox1.addWidget(self.edit2)
        vbox1.addWidget(self.button)
        page.setLayout(vbox1)
        self.setCentralWidget(page)

        self.connect(self.button, SIGNAL("clicked()"), self.clicked)

    def clicked(self):
        QMessageBox.about(self, "My message box", "Text1 = %s, Text2 = %s" % (
            self.edit1.text(), self.edit2.text()))

if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    form = AppForm()
    form.show()
    app.exec_()

rawDescription: How to display a message box on PyQT4?

description: Display a message box on PyQT4


code:
def main():
    # take input from the user
    num = float(input("Enter a number: "))
    if (num%1 != 0):
        print("Bad entry, only integers are accepted.")
        return

    num = int(num)
    factorial = 1
    if num > 100:
        print("Bad entry. It should be an integer less than or equal to 100!")
        print("Please try again: ")
    elif num == 0:
        print("The factorial of 0 is 1")
    elif num < 0:
        print("Bad entry. It should be an integer superior than or equal to 0!")
        print("Please try again: ")
    else:
        for i in range(1,num + 1):
            factorial = factorial*i
        print("The factorial of",num,"is",factorial)

main()

rawDescription: How can i stop my python program from crashing

description: Stop my python program from crashing


code:
# create the firefox driver
driver = webdriver.Firefox()

# navigate to the app url
driver.get('http://www.google.com')

# keep a watch on jQuery 'active' attribute
WebDriverWait(driver, 10).until(lambda s: s.execute_script("return jQuery.active == 0"))

# page should be stable enough now, and we can perform desired actions
elem = WebDriverWait(driver, 10).until(expected_conditions.visibility_of_element_located((By.ID, 'id')))

elem.send_keys('some text')

rawDescription: Alternative of visibility of element located in selenium 2.0 that checks the presence of an element on the DOM?


code:
user_callback = None

def register_callback(callback):
    global user_callback
    user_callback = callback

def main():
    while 1:
        text=irc.recv(4096)
        user_callback(text)

rawDescription: Send data from module to script

description: Send data from module to script


code: sorted(inputlist, key=lambda e: (len(e[0]), e[0], e[1]))

rawDescription: Python sorting by multiple criteria

description: Python sorting by multiple criteria


rawDescription: Auto reloading python Flask app upon code changes


code:
from itertools import groupby

d = [['John'],['is'],['smart'],[','],['John'],['Kenneddy'],['is'],[','],['John'],['Fitzgerald'],['Kennedy'],['is'],['best']]

sum(([[x[0] for x in g]] if k else list(g)
     for k, g in groupby(d, key=lambda x: x[0][0].isupper())),
    [])

rawDescription: Python - Join Two List Object Eachother If Their First Name Uppercase


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

# Set the default color cycle
mpl.rcParams['axes.color_cycle'] = ['r', 'k', 'c']

# Alternately, we could use rc:
# mpl.rc('axes', color_cycle=['r','k','c'])

x = np.linspace(0, 20, 100)

fig, axes = plt.subplots(nrows=2)

for i in range(10):
    axes[0].plot(x, i * (x - 10)**2)

for i in range(10):
    axes[1].plot(x, i * np.cos(x))

plt.show()

rawDescription: default color cycle with matplotlib

description: Default color cycle with matplotlib


code:
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[:2], labels[:2])

rawDescription: Avoiding repeated legend in seaborn boxplot overlaid by swarmplot


code:
L = [0, 0, 1, 3, 0, 3]
import collections
d = collections.defaultdict(list)
for index, item in enumerate(L):
  d[item].append(index)

d
[d[i] for i in xrange(1 + max(d))]

rawDescription: Whats the most efficient pythonic way to do this :


code:
cur.execute("""INSERT INTO mytable
('number','name','prename','id','number_a','location_num','team')
VALUES('',?,?,'','',?,'')""",
(thename, theprename, thelocation_num))

rawDescription: Making sqlite3 inserts using python variable


code:
from operator import and_
np.ma.array(arr1.data+arr2.data,mask=map(and_,arr1.mask,arr2.mask))

rawDescription: Add together two numpy masked arrays

description: Add together two numpy masked arrays


code:
from IPython.display import display
from IPython.core.display import HTML

class buttons(object):
    def __init__(self):

        self.buttons = []
        for i in xrange(6):

            self.buttons.append( widgets.Button(description = str(i)))
            self.buttons[-1].on_click(self.handle_submit)
            self.buttons[-1].margin=20

        self.text = widgets.Text(value="21")

        self.header = widgets.HTML(description='',value='<h1> Heading </h1>')
        self.everything = widgets.VBox([self.header,widgets.HBox((self.buttons)),self.text])
        display(self.everything)

        #display(HTML("<h1> Heading </h1>"))

        #display( widgets.HBox((self.buttons)) )

        #display(self.text)

    def handle_submit(self, sender):
        self.show(int(self.text.value))

    def show(self, x=None):
        print(1+1)

b = buttons()

rawDescription: Is there a way to display HTML code in an IPython notebook before widgets in the same output cell?


rawDescription: Extract part of 2D-List/Matrix/List of lists in Python


code:
from threading import Timer
from flask import Flask

app = Flask(__name__)
DATA = "data"

def update_data(interval):
    Timer(interval, update_data, [interval]).start()
    global DATA
    DATA = DATA + " updating..."

# update data every second
update_data(1)

@app.route("/")
def index():
    return DATA

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

rawDescription: How to run a function once per second separated from the requests on Flask?

description: Run a function once per second separated from the requests on Flask


code:
def displayNextForm(self):
    self.close()
    self.extr=FormMakeImage(self,"FormMakeImage",1,Qt.WStyle_DialogBorder)
    self.extr.exec_loop()
def displayPrevForm(self):
    from DialogSelectFile import *
    self.close()
    self.ext=DialogSelectKernelFile(self,"SelectKernel",1,Qt.WStyle_DialogBorder)
    self.ext.exec_loop()

rawDescription: Help Me: Loading Qt dialogs from python Scripts


code: p = subprocess.Popen( args=["script.sh", "-p", p_opt, "-v", v_opt, arg1, arg2] )

rawDescription: How to execute an arbitrary shell script and pass multiple variables via Python?

description: Execute an arbitrary shell script and pass multiple variables via Python


code:
from scipy.stats import poisson, lognorm
myShape = 5;myMu=10
ln = lognorm(myShape)
p = poisson(myMu)
ln.rvs((10,)) #generate 10 RVs from ln
p.rvs((10,)) #generate 10 RVs from p
ln.pdf(3) #lognorm PDF at x=3

rawDescription: Does anyone have example code of using scipy.stats.distributions?


code:
from urllib import urlopen
from bs4 import BeautifulSoup

def re_crawler(pages):
    page = 1
    while page <= pages:
        url = 'http://www.reaa.govt.nz/Pages/PublicRegisterSearch.aspx?pageNo=' + str(page) + '&name=a*&orgName=&location=&licenceNo=&itemsPerPage=100&sortExpression=2'
        code = urlopen(url)
        soup = BeautifulSoup(code)
        for link in soup.select('tr.alternate td a[id*=ctl00_]'):
            href = link.get('href')
            print (href)
        page += 1

re_crawler(2)

rawDescription: Stuck with this web scraper

description: Stuck with this web scraper


code: pd.DataFrame({'norte' : valor_norte, 'este' : valor_este},index=dtime)

rawDescription: Pandas DataFrame including three numpy arrays


rawDescription: passing a variable with colon in function python

description: Passing a variable with colon in function python


code:
import weakref

class InstanceTracker(object):
    def __init__(self):
        self.instances = {}
    def new(self, cls, *args, **kwargs):
        instance = cls(*args, **kwargs)
        self.instances.setdefault(cls, weakref.WeakSet()).add(instance)
        return instance
    def iter_instances(cls):
        return iter(self.instances[cls])

rawDescription: How do I create a proper metaclass for my task?

description: Create a proper metaclass for my task


code:
class Student(object):
    def __init__(self, student_id, lname, fname):
        self.studid = student_id
        self.lname = lname
        self.fname = fname
        self.courses = []

    def addcourse(self, course, grade, mode):
        self.courses.append((course, grade, mode))

students = {}

fh = open('students.txt').readlines()
header = fh.pop(0)

for line in fh:
    row = line.split(',')
    if len(row) < 6:
        continue

    student_id, fname, lname, course, grade, mode = [i.strip() for i in row]

    student = students.get(student_id, Student(student_id, lname, fname))
    student.addcourse(course, grade, mode)
    students[student_id] = student

rawDescription: Python creating an Object while reading file


code:
for div in tree.iter('div'):
    title = div.xpath('.//child::*')
    if title[0].text == 'Source:':
        print(title[0].tail.strip())

rawDescription: retrieve text in the div tag with lxml in python

description: Retrieve text in the div tag with lxml in python


code:
print(nextaction, end=' ', flush=True)
time.sleep(2)
print(nextplayer, end="'s", flush=True)
time.sleep(1)
print(nextitem+'!', flush=True) # there is a newline, so no need to flush it
time.sleep(3)

rawDescription: time.sleep() working differently in python shell than in command window

description: Time.sleep() working differently in python shell than in command window


rawDescription: Python: CSV write by column rather than row


code:
def decode_ber_int(data, offset):
    value = 0
    while True:
        tmp = ord(data[offset])
        value = (value<<7) | (tmp&0x7f)
        offset += 1
        if tmp & 0x80 == 0:
            break
    return value, offset

rawDescription: Python equivalent of Perl's 'w' packing format


code:
for root, dirs, files in os.walk(some_directory):
    for fn in files:
        path = os.path.join(root, fn)
        size = os.stat(path).st_size # in bytes

        # ...

rawDescription: Get file size during os.walk

description: Get file size during os.walk


code:
import urllib
import urllib2

request_data = urllib.urlencode({"DATA": xml})
response = urllib2.urlopen("https://url of the virtual bank POS", request_data)

response_data = response.read()
data = response_data.split('\n')

rawDescription: Python and curl question

description: Python and curl question


code:
from htmldom import htmldom
dom = htmldom.HtmlDom().createDom( """

long text.

click here

""");
nodes = dom.find( "p" ).children( all_children = True ) # this makes all text nodes to be in the set.
for node in nodes:
    if node._is( "a" ):
        print( node.attr( "href" ).strip() )
    elif node._is( "text" ):
        print( node.getNode().text, end = '', sep = ' ' )

rawDescription: I want to parse HTML in python

description: I want to parse HTML in python


code:
# read port-list
with open('ports.txt') as inf:
    ports = [int(i) for line in inf for i in line.split(',')]

# display ports
for port in ports:
    print(port)

# recreate file
ports.append(myPort)
ports.sort()
with open('ports.txt', 'w') as outf:
    outf.write(','.join(str(p) for p in ports))

rawDescription: Python - read, write and append to a file


code:
commands = [cmd1, cmd2, cmd3, cmd4]        # omit the parenthesis (call)
current_command = random.choice(commands)
current_command()

rawDescription: Is it possible to run a command that is in a list?


code:
import collections

def walk(j):
    lifo = collections.deque(j)

    while lifo:
        for k in dists[lifo.pop()].keys():
            if labels[k] == -1:
               labels[k] = labels[j]
               lifo.append(k)

rawDescription: Avoiding maximum recursion depth in connected component analysis?


code:
from itertools import groupby

s = "    Mary    had    a little lamb  "
res = ''.join(' ' if is_space else ''.join(chars) for is_space, chars in groupby(s, str.isspace))
#  Mary had a little lamb

rawDescription: Without regex reduce multiple spaces in a string to one in Python


rawDescription: Python regular expression for matching 3 and 16 characters


rawDescription: Obtain part of a string using regular expresions in Python


rawDescription: Python - Unicode Converter

description: Python - Unicode Converter


code:
Tags.all().filter('tag =', 'foo')
Tags.all().filter('tag =', 'bar')
Tags.all().filter('tag =', 'baz')

rawDescription: 3 Models Entity Joins in AppEngine Python


code:
import numpy as np

# the grain table must be an array, fill in the numbers you want
graintable = np.array([100,200,300,400,500,600,700,800,900,-9999])

def V_get_grain(*images):
    # create the cumulative sum buffer (empty at this point)
    csum = np.zeros_like(images[0])
    # create the counter for number of samples needed to reach .5
    cnt = np.zeros(images[0].shape, dtype='uint8')

    # iterate through the images:
    for img in images:
        # add the image into the cumulative sum buffer
        csum += img
        # add 1 to the counter if the sum of a pixel is < .5
        cnt += csum < .5

    # now cnt has a number for each pixel:
    # 0: the first image >= .5
    # ...
    # 9: all images together < .5

    return graintable[cnt]

rawDescription: Improving memory efficiency of a vectorised function


code:
from multiprocessing import Pool
from flask import Flask

app = Flask(__name__)
_pool = None

def expensive_function(x):
        # import packages that is used in this function
        # do your expensive time consuming process
        return x*x

@app.route('/expensive_calc/<int:x>')
def route_expcalc(x):
        f = _pool.apply_async(expensive_function,[x])
        r = f.get(timeout=2)
        return 'Result is %d'%r

if __name__=='__main__':
        _pool = Pool(processes=4)
        try:
                # insert production server deployment code
                app.run()
        except KeyboardInterrupt:
                _pool.close()
                _pool.join()

rawDescription: Shared list among celery workers and Flask using python's multiprocessing


code:
from Tkinter import *

root = Tk()
root.geometry("300x400")

message_list = ["testing on file 0 successfull\n",
                "testing on file 1 successfull\n",
                "testing on file2 successfull\n"]

message_list_idx = 0;

def startProgram():
    global message_list_idx

    if message_list_idx >= len(message_list):
        return
    t3 = message_list[message_list_idx]
    text.insert('1.0', t3)
    message_list_idx += 1

text = Text(root, height=8, width=25)
text.grid(row=10, column=0, padx=20, pady=5)

label = Label(root, text="Status",font=12)
label.grid(row=9, column=0, padx=5, pady=5)

button2=Button(root,text="Start Program", width=20,font=12,
               command=startProgram)

button2.grid(row=7, column=0, padx=20, pady=10)

button3=Button(root, text='Exit Program',width=20,font=12,
                    command=root.destroy)
button3.grid(row=8, column=0,padx=20, pady=10)

root.mainloop()
button2=Button(root,text="Start Program", width=20,font=12,
               command=startProgram)

button2.grid(row=7, column=0, padx=20, pady=10)

button3=Button(root, text='Exit Program',width=20,font=12,
                    command=root.destroy)
button3.grid(row=8, column=0,padx=20, pady=10)

root.mainloop()

rawDescription: Text and Button Python Tk GUI

description: Text and Button Python Tk GUI


code:
for k in (1, -1):
  sample_func(*(i, j)[::k])

rawDescription: How to change order of arguments within a cycle in python

description: Change order of arguments within a cycle in python


code: ferms=[DF for DF in ferms if '["FC.PV [EFT (h)"]' in DF.columns]

rawDescription: Skip missing column header in pandas dataframe?


code:
import random, time

DURATION = 5 * 86400  # five days
EXECS = 100

now = time.time()
points = sorted(random.random() * DURATION + now
                for i in xrange(EXECS))

for p in points:
   now = time.time()
   if p > now:
       time.sleep(p - now)
   # run your loop here

rawDescription: Python - Loop 100 times over a specified time


code:
try:
    some_object
except NameError:
    do_something()
else:
    do_something_else()

rawDescription: Python: check if object exists in scope

description: Python: check if object exists in scope


code:
import cx_Oracle
import pandas as pd
import xlwt as xls_write

writer = pd.ExcelWriter('<Excel File>')
conn = cx_Oracle.connect('<Connection String')

def executeSQL(tab, SQL, connection):

    df = pd.read_sql(SQL,connection)
    df.to_excel(writer, tab, index=False)

executeSQL('Tab 1', "<SQL Statement>")
executeSQL('Tab 2', "<SQL Statement>")
executeSQL('Tab 3', "<SQL Statement>")
executeSQL('Tab 4', "<SQL Statement>")
executeSQL('Tab 5', "<SQL Statement>")

conn.close()

rawDescription: NameError: name is not defined function

description: NameError: name is not defined function


code:
from Bio import SeqIO

input_file = 'a.fasta'
merge_file = 'original.fasta'
output_file = 'results.fasta'
exclude = set()
fasta_sequences = SeqIO.parse(open(input_file),'fasta')
for fasta in fasta_sequences:
    exclude.add(fasta.id)

fasta_sequences = SeqIO.parse(open(merge_file),'fasta')
with open(output_file, 'w') as output_handle:
   for fasta in fasta_sequences:
        if fasta.id not in exclude:
            SeqIO.write([fasta], output_handle, "fasta")

rawDescription: How to filter out sequences based on a given data using Python?

description: Filter out sequences based on a given data using Python


code:
import os

# change this, obviously
root_dir = r'C:\Users\ben\Documents\Python Scripts\tmp'

keep = 'keep'

for root, dirs, files in os.walk(root_dir):
    for name in files:
        # make sure what you want to keep isn't in the full filename
        if (keep not in root and keep not in name):
            print(os.path.join(root, name)) #change to os.remove once sure
    for name in dirs:
        if (keep not in root and keep not in name):
            print(os.path.join(root, name)) # change to os.rmdir once sure

rawDescription: Python recursively remove files/folders in a directory, but not the parent directory or a specific folder


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

data = np.random.rand(4,4)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data,interpolation='none')

fig.savefig('test.eps')
fig.savefig('test.pdf')
fig.savefig('test.png')

rawDescription: Matplotlib EPS export ignores interpolation='nearest'


code:
def debug(request):
    "Returns context variables helpful for debugging."
    context_extras = {}
    if settings.DEBUG and request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
        context_extras['debug'] = True
        from django.db import connection
        context_extras['sql_queries'] = connection.queries
    return context_extras

rawDescription: How do I make the DEBUG variable in my settings.py available in my templates in Django?

description: Make the DEBUG variable in my settings.py available in my templates in Django


code:
import matplotlib.pyplot as plt
import seaborn  as sns
x =  range(10)
y =  range(10)
plt.bar(x,y,color= sns.color_palette("BuGn_r", len(x)))
plt.show()

rawDescription: generate non-repeating sequential color plot with matplotlib

description: Generate non-repeating sequential color plot with matplotlib


code:
TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

rawDescription: django auth: password change template customization

description: Django auth: password change template customization


code:
import json

tables = ["a", "b", "c", "d"]
data = {}

for t in tables:
    results = sf.query("select id from %s" % t)["records"]
    data[t] = [r["id"] for r in results]

with open("Dataset.json", "w") as f:
    json.dump(data, f)

rawDescription: How to create json file having array in Python

description: Create json file having array in Python


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

x = np.arange(0, 8, .1)
np.random.shuffle(x)
y = np.sin(x)

sx = np.argsort(x)  # find the order for sorting x
x2 = x[sx]          #    apply this to x
y2 = y[sx]          #    apply this to y

plt.plot(x, y, 'y')
plt.plot(x2, y2, 'r', linewidth=4)

plt.show()

rawDescription: Specify join order in matplotlib

description: Specify join order in matplotlib


code:
lists = List.objects.exclude(picture_url='') \
        .exclude(picture_url__icontains='google') \
        .select_related('city','city__country', 'user', 'user__profile') \
        .annotate(items_added=Count('item')) \
        .filter(items_added__gt=5)[:10]

rawDescription: Exclude count of annotate items in Django Query


rawDescription: How to check for empty fields

description: Check for empty fields


code:
from tkinter import *
from tkinter import ttk

def main():
    gMaster = Tk()
    w = ttk.Treeview(gMaster, show="headings", columns=('Column1', 'Column2'))
    w.heading('#1', text='Column1', anchor=W)
    w.heading('#2', text='Column2', anchor=W)

    w.column('#1', minwidth = 70, width = 70, stretch = False)
    w.column('#2', minwidth = 70, width = 70, stretch = True)  # Try to change the value of stretch here.

    # The following 2 lines will make the Treeview `w` fill the window horizontally.
    w.grid(row = 0, column = 0, sticky='we')
    gMaster.grid_columnconfigure(0, weight=1)

    mainloop()

if __name__ == "__main__":
    # Try to change the width of the application window use your mouse and you will see
    # the width of column #2 will:
    # 1. keep unchanged when strech=False
    # 2. change when strech=True
    main()

rawDescription: python treeview column "stretch=False" not working

description: Python treeview column "stretch=False" not working


code:
BinaryFile = np.zeros((272543,901), dtype=np.uint8)

count = 0

for j in xrange(0,272543):

    #SOIL IMAGE ADJOINT
    b = temp[j,0,:,:]
    g = temp[j,1,:,:]
    r = temp[j,2,:,:]
    n = tempnir[j,:,:,:]

    g = g.reshape(1,225)
    r = r.reshape(1,225)
    b = b.reshape(1,225)
    n = n.reshape(1,225)

    BinaryFile[count,1:901] = np.concatenate( (r,g,b,n), axis=1 )
    #BinaryFile[count,1:962] = ndvi
    #BinaryFile[count,0]= 0
    BinaryFile[count,0]= indexes[count,1]
    #BinaryFile[count,1]= indexes[count,1]

    #print(BinaryFile[count,1])
    #print(BinaryFile[count,2])

    count = count +1

newFile = open ("yourfile.bin", "wb")
newFileByteArray = bytearray(BinaryFile)
newFile.write(newFileByteArray)

rawDescription: Image recognition using TensorFlow

description: Image recognition using TensorFlow


code:
from Tkinter import *

master=Tk()

w=Canvas(master, width=200, height=100)
########
w.pack()
########

w.create_line(0,0,200,100)
w.create_line(0,100,200,0, fill="red", dash=(4,4))

w.create_rectangle(50,25,150,75, fill="blue")

mainloop()

rawDescription: Gedit problems with python

description: Gedit problems with python


code:
def is_url(name):
    """Returns true if the name looks like a URL"""
    if ':' not in name:
        return False
    scheme = name.split(':', 1)[0].lower()
    return scheme in ['http', 'https', 'file', 'ftp'] + vcs.all_schemes

rawDescription: How is Pip able to install packages by name or URL?


code:
import itertools
lists = [[1], [2, 3], [4, 5]]
list(itertools.product(*lists))

rawDescription: List of lists: find combinations of elements


code:
def interlock(s1, s2):

    r = 1
    l1 = list(s1)
    l2 = list(s2)
    inters = ''
    if len(s2) == len(s1):
        for i in range(len(s1)):
            inters += s1[i]
            inters += s2[i]

    elif len(s1) < len(s2):
        for i in range(len(s1)):
            inters += s2[i]
            inters += s1[i]
            r = i+1
        inters += s2[r]

    elif len(s2) < len(s1):
        for i in range(len(s2)):
            inters += s1[i]
            inters += s2[i]
            r = i+1

        inters += s1[r]

    else:
        pass

    return inters

a = interlock('abalone','hammer')
print (a)
print (a[::2])
print (a[1::2])
a = interlock('hammer','abalone')
print (a)
print (a[::2])
print (a[1::2])
a = interlock('ab','siy')
print (a)

rawDescription: Interlocking Two Strings in Python ProblemSetQuestion (Self-Taught)


code:
config = configparser.ConfigParser()
config['general'] = {'default-option': 'blah'}
config.read(configFile)
# Logging configuration
logging.config.fileConfig(config, disable_existing_loggers=False)

rawDescription: Include logging configuration in file read by configparser


code:
def obj_get_list(self, bundle, **kwargs):
    if bundle.request.method == 'GET':
        related_id = bundle.request.GET['entity']
        # create new object if it doesn't exist and populate with `related_id`
        # ...
    objects = ModelResource.obj_get_list(self, bundle, **kwargs)
    return objects

rawDescription: Tastypie get_or_create object

description: Tastypie get_or_create object


rawDescription: Checking if matrix has a value

description: Checking if matrix has a value


code:
def dot(v1, v2):
    return sum(x*y for x,y in zip(v1,v2))

dot([1,2,3], [4,5,6])

rawDescription: Dot Product in Python without NumPy

description: Dot Product in Python without NumPy


code:
# content of test_class.py
class TestClass:
    def test_one(self):
        x = "this"
        assert 'h' in x

    def test_two(self):
        x = "hello"
        assert hasattr(x, 'check')

rawDescription: py.test does not find tests under a class

description: Py.test does not find tests under a class


code:
def run(self, edit, target):
    if not target or target == "":
        return

    content = self.view.substr(sublime.Region(0, self.view.size()))
    begin = content.find(target)
    if begin == -1:
        return
    end = begin + len(target)
    target_region = sublime.Region(begin, end)
    self.view.sel().clear()
    self.view.sel().add(target_region)

rawDescription: sublime plugin: find and select text

description: Sublime plugin: find and select text


code:
with constructor(args) as a:
    # do stuff with a
    pass
# here a is closed even if you had an error above

rawDescription: Pythonic way of closing/terminating an object


rawDescription: change data type of a array in python

description: Change data type of a array in python


code:
def my_function():
    if not hasattr(my_function,'first_time'):
        my_function.first_time = 1 # Dummy value
        import pdb; pdb.set_trace()
    ...

rawDescription: How to ignore the next pdb-like breakpoints, including set_trace() calls?

description: Ignore the next pdb-like breakpoints, including set_trace() calls


code:
def _parse_metadata(self, meta):
    """Return the dict containing document metadata"""
    formatted_fields = self.settings['FORMATTED_FIELDS']

    output = {}
    for name, value in meta.items():
        name = name.lower()
        if name in formatted_fields:
            # handle summary metadata as markdown
            # summary metadata is special case and join all list values
            summary_values = "\n".join(value)
            # reset the markdown instance to clear any state
            self._md.reset()
            summary = self._md.convert(summary_values)
            output[name] = self.process_metadata(name, summary)

rawDescription: How do I format title text using Pelican?

description: Format title text using Pelican


code:
#Project urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'Sayth.views.home', name='home'),
    # url(r'^Sayth/', include('Sayth.foo.urls')),

    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^rango/', include('rango.urls')),
)

#rango/urls.py
from django.conf.urls import patterns, url
from rango import views

urlpatterns = patterns('',
            url(r'^$', views.index, name='index'),
            url(r'^about/$', views.about, name='about'),
            )

rawDescription: Get different views to display different content


code: row_val = [str(w) for w in row_val]

rawDescription: Replace specific character from the list of string


code:
def split_padded(a,n):
    padding = (-len(a))%n
    return np.split(np.concatenate((a,np.zeros(padding))),n)

rawDescription: python numpy split array into unequal subarrays

description: Python numpy split array into unequal subarrays


rawDescription: since X variables are in a list, call a function with X parameters

description: Since X variables are in a list, call a function with X parameters


code:
def __setattr__(self, name, value):
    # set the value like usual and then update the modified attribute too
    self.__dict__[name] = value
    self.__dict__['__modified'] = datetime.now().isoformat()

rawDescription: Class design: Last Modified

description: Class design: Last Modified


code:
import requests
import suds

r = requests.get(SERVICE_WSDL_HTTPS_URL)
with open('/tmp/service.wsdl', 'w') as file:
    file.write(r.text)
client = suds.client.Client('file:///tmp/service.wsdl', location=SERVICE_HTTP_URL)

rawDescription: how consume via Suds a webservice that expose wsdl via https and service via http

description: How consume via Suds a webservice that expose wsdl via https and service via http


rawDescription: Adding cookies to a cookiejar

description: Adding cookies to a cookiejar


code:
rawData = open("foo.raw" 'rb').read()
imgSize = (x,y)
# Use the PIL raw decoder to read the data.
# the 'F;16' informs the raw decoder that we are reading
# a little endian, unsigned integer 16 bit data.
img = Image.fromstring('L', imgSize, rawData, 'raw', 'F;16')
img.save("foo.png")

rawDescription: how to convert raw images to png in python?

description: Convert raw images to png in python


code: {k: v for k, v in my_dict.items() if v['baz'] == 'abc'}

rawDescription: Find keys in multidimensional dict based on value


code:
for tbl in reversed(meta.sorted_tables):
    engine.execute(tbl.delete())

rawDescription: How to clean the database, dropping all records using sqlalchemy?

description: Clean the database, dropping all records using sqlalchemy


code:
{(k1,v):k2 for k1 in dict1 for k2 in dict2
           for v in dict2[k2] if k2 in dict1[k1]}

rawDescription: How to readjust defaultdict(list)s - Python

description: Readjust defaultdict(list)s - Python


code:
class Foo(AnotherClass):
    id_counter = 0
    def __init__(self):
        super().__init__()
        self.id = type(self).id_counter
        type(self).id_counter += 1

rawDescription: Python keyword to access class variable

description: Python keyword to access class variable


code:
class StopFunction(object):

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

    def __call__(self, symbol, _):
        if symbol == getattr(pyglet.window.key, self.stop_key):
            pyglet.app.exit()

    def __eq__(self, other):
        try:
            return self.stop_key == other.stop_key
        except AttributeError:
            return False

StopFunciton('ENTER') == StopFunciton('ENTER')
# True
StopFunciton('ENTER') == StopFunciton('FOO')
# False

rawDescription: Workaround for equality of nested functions


code:
def mix_up(first, second):
    new_first = second[:2] + first[2:]
    new_second = first[:2] + second[2:]
    return " ".join((new_first, new_second))

assert mix_up('mix','pod') == 'pox mid'
assert mix_up('dog','dinner') == 'dig donner'

rawDescription: How to mix strings in Python

description: Mix strings in Python


code:
from Tkinter import Tk, BOTH, StringVar, IntVar
from ttk import Frame, Button, Style, Label, Entry

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def showMe(self):
        print(self.value.get())

    def initUI(self):
        self.parent.title("Get Value")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        valueLabel = Label(self, text="Value: ")
        valueLabel.place(x=10, y=10)
        self.value=StringVar(None)
        self.value.set("this is the default value")
        valueEntry=Entry(self, textvariable=self.value)
        valueEntry.place(x=70, y=10)

        quitButton = Button(self, text="Quit", command=self.quit)
        quitButton.place(x=10, y=50)

        okButton = Button(self, text="OK", command=self.showMe)
        okButton.place(x=120, y=50)

def main():

    root = Tk()
    root.geometry("220x100+300+300")
    app = Example(root)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Python: Tkinter OK button callback function


code:
from Tkinter import *
import tkFont
class App(Frame):
    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.apple = Button(self,
                            text="Apple", command=self.write_apple)
        self.apple.pack(side=LEFT)
        self.top_dict = dict()

    def destroy_top(self, event):
        # event.widget is the instance of Label that was clicked
        # Get the instance of Toplevel
        top = self.top_dict[event.widget]
        # Destroy the instance of Toplevel
        top.destroy()
        # Remove the instance of Toplevel from the list
        del self.top_dict[event.widget]

    def write_apple(self):
        self.customFont = tkFont.Font(family="Helvetica", size=80)
        # Create an instance of Toplevel
        top = Toplevel(self)
        top.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
        label = Label(top, text="This is a green apple.",font=self.customFont)
        label.pack(side="top", fill="both", expand=True)
        # Bind the destroy_top method to the mouse-button-1 click
        label.bind('<Button-1>', self.destroy_top)
        # Save the instance of Toplevel using the label as the key
        self.top_dict[label] = top

if __name__ == "__main__":
    root = Tk()
    main = App(root)
    main.pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: Create a 'close/exit' option for a child frame that is created using tkinter in python


code:
import jinja2
from tempfile import NamedTemporaryFile

def return_hosts():
    'return a list of host names'
    with open('./tfhosts') as hosts:
        return [host.split()[1].strip() for host in hosts]

inventory = """
[master1]
{{ host_master01 }}
[master2]
{{ host_master02 }}
"""

gethosts = return_hosts()

inventory_template = jinja2.Template(inventory)

rendered_inventory = inventory_template.render({
    'host_master01': gethosts[0],
    'host_master02': gethosts[1],
  })

hosts = NamedTemporaryFile(delete=False)
hosts.write(rendered_inventory)
hosts.close()

rawDescription: Using Python loops with Jinja template

description: Using Python loops with Jinja template


code:
def post(self):
    payload = json.loads(self.request.body)
    assert isinstance(payload, dict), 'Bad payload'

    myCustomClass = CustomClass()
    myCustomClass.populate(**payload)
    myCustomClass.put()

rawDescription: Python Appengine initialize ndb model object with JSON


code:
import time

val_list = []

prev_time = time.time()

for i in xrange(iterations):
    val = (i*(1/2)) * pi
    val2 = np.linalg.pinv(val)
    # print or write to log val2 after every half second (or 1 second)
    dt = time.time() - prev_time
    if dt > 1:
        # print or write to log here
        prev_time = time.time()
    val_list.append(val2)

rawDescription: python - printing something in a for loop every n seconds

description: Python - printing something in a for loop every n seconds


code:
import tkinter as tk
root = tk.Tk()
canvas = tk.Canvas(root)
canvas.pack()
iptext = canvas.create_text(100, 100, width=100,
                          font=("courier", 15, "bold"))
ips = (t for t in ('111', '222', '333', '444'))
def update_ip():
    try:
        canvas.itemconfigure(iptext, text=next(ips))
        root.after(1000, update_ip)
    except StopIteration:
        pass
update_ip()
root.mainloop()

rawDescription: How do I refresh a text object on a canvas using a loop?

description: Refresh a text object on a canvas using a loop


code:
import subprocess,os
startupinfo = None
if os.platform == 'win32':
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
VAL = subprocess.check_output(['adb.exe', 'version'], shell=False, startupinfo=startupinfo).decode()

rawDescription: Python subprocess command to run silent, prevent cmd from appearing


code: my_serialized_object = cPickle.dumps(my_object, cPickle.HIGHEST_PROTOCOL)

rawDescription: Python: preventing caching from slowing me down


code:
from copy import deepcopy
import json
from pprint import pprint
from StringIO import StringIO

json_str = \
'''
{
    "Resource": [
        {
            "@name": "Bravo",
            "@signature": "h#Bravo",
            "@type": "ESX_5.x",
            "@typeDisplayName": "ESX Server",
            "PerfList": {
                "@attrId": "cpuUsage",
                "@attrName": "Usage",
                "Data": [
                    {
                        "@data": "26.00",
                        "@end": "01:05:00",
                        "@interval": "60",
                        "@start": "01:04:00"
                    },
                    {
                        "@data": "24.00",
                        "@end": "01:04:00",
                        "@interval": "60",
                        "@start": "01:03:00"
                    },
                    {
                        "@data": "36.00",
                        "@end": "01:03:00",
                        "@interval": "60",
                        "@start": "01:02:00"
                    },
                    {
                        "@data": "38.00",
                        "@end": "01:02:00",
                        "@interval": "60",
                        "@start": "01:01:00"
                    },
                    {
                        "@data": "37.00",
                        "@end": "01:01:00",
                        "@interval": "60",
                        "@start": "01:00:00"
                    }
                ]
            },
            "Resource": [
                {
                    "@name": "Tango",
                    "@signature": "vm#Tango",
                    "@type": "vm",
                    "@typeDisplayName": "Virtual Machine",
                    "PerfList": {
                        "@attrId": "cpuUsage",
                        "@attrName": "Usage",
                        "Data": {
                            "@data": "12.00",
                            "@end": "04:05:00",
                            "@interval": "60",
                            "@start": "04:04:00"
                        }
                    }
                },
                {
                    "@name": "Charlie",
                    "@signature": "vm#Charlie",
                    "@type": "vm",
                    "@typeDisplayName": "Virtual Machine",
                    "PerfList": {
                        "@attrId": "cpuUsage",
                        "@attrName": "Usage",
                        "Data": [
                            {
                                "@data": "12.00",
                                "@end": "04:20:00",
                                "@interval": "60",
                                "@start": "04:19:00"
                            },
                            {
                                "@data": "12.00",
                                "@end": "04:19:00",
                                "@interval": "60",
                                "@start": "04:18:00"
                            }
                        ]
                    }
                }
            ]
        },
        {
            "@name": "Alpha",
            "@signature": "h#Alpha",
            "@type": "ESX_5.x",
            "@typeDisplayName": "ESX Server",
            "PerfList": [
                {
                    "@attrId": "cpuUsage",
                    "@attrName": "Usage",
                    "Data": {
                        "@data": "9",
                        "@end": "06:10:00",
                        "@interval": "60",
                        "@start": "06:09:00"
                    }
                },
                {
                    "@attrId": "cpuUsagemhz",
                    "@attrName": "Usage MHz",
                    "Data": {
                        "@data": "479",
                        "@end": "06:10:00",
                        "@interval": "60",
                        "@start": "06:09:00"
                    }
                }
            ]
        }
    ]
}
'''

def walk_fun_lim(ilist, func=None):
    '''
    Recursively walk a nested list and dict structure, running func on all dicts
    '''
    def walk_fun_lim_helper(ilist, func=None, count=0):
        tlist = []
        ttlist = []
        if(isinstance(ilist, list)):
            ttlist = filter(lambda x: x, func(filter(lambda x: isinstance(x, dict), ilist)))
            if(ttlist):
                tlist += ttlist
            for q in ilist:
                ttlist = filter(lambda x: x, walk_fun_lim_helper(q, func, count+1))
                if(ttlist):
                    tlist += ttlist
        elif(isinstance(ilist, dict)):
            ttlist = filter(lambda x: x, func([ilist]))
            if(ttlist):
                tlist += ttlist
            for q in ilist:
                ttlist = filter(lambda x: x, walk_fun_lim_helper(ilist[q], func, count+1))
                if(ttlist):
                    tlist += ttlist
        return [tlist] if(count != 0) else tlist
    if(func != None and hasattr(func, "__call__")):
        return walk_fun_lim_helper(ilist, func)
    else:
        return []

def transformers_robots_in_disguise(x):
    for idict in x:
        plist = idict.pop("PerfList", [])
        plist = plist if(isinstance(plist, list)) else [plist]
        for sub_dict in plist:
            sub_name = sub_dict.pop("@attrId")
            dlist = sub_dict.pop("Data", [])
            dlist = dlist if(isinstance(dlist, list)) else [dlist]
            new_dict = {}
            for sub_dict in dlist:
                new_dict["from_%(@start)s_to_%(@end)s" % sub_dict] = sub_dict["@data"]
                new_dict["@interval"] = sub_dict["@interval"]
            idict[sub_name] = new_dict
        rlist = idict.pop("Resource", [])
        rlist = rlist if(isinstance(rlist, list)) else [rlist]
        for sub_dict in rlist:
            sub_type = sub_dict.pop("@type")
            sub_name = sub_dict.pop("@name")
            idict.setdefault(sub_type, {})[sub_name] = sub_dict
    return []

json_data = json.load(StringIO(json_str))
data_copy = deepcopy(json_data)
walk_fun_lim(data_copy, transformers_robots_in_disguise)
pprint(data_copy)

rawDescription: Complex Python JSON object to custom dictionary conversion


code:
import os

def get_latest_image(dirpath, valid_extensions=('jpg','jpeg','png')):
    """
    Get the latest image file in the given directory
    """

    # get filepaths of all files and dirs in the given dir
    valid_files = [os.path.join(dirpath, filename) for filename in os.listdir(dirpath)]
    # filter out directories, no-extension, and wrong extension files
    valid_files = [f for f in valid_files if '.' in f and \
        f.rsplit('.',1)[-1] in valid_extensions and os.path.isfile(f)]

    if not valid_files:
        raise ValueError("No valid images in %s" % dirpath)

    return max(valid_files, key=os.path.getmtime)

rawDescription: How to read the latest image in a folder using python?

description: Read the latest image in a folder using python


code:
def next(self):
    if len(self._sofar) == len(self._data):
        yield self._sofar[:]
    else:
        for elem in self._data:
            if elem not in self._sofar:
                self._sofar.append(elem)
                for v in self.next():
                    yield v
                self._sofar.pop()

rawDescription: Explain Python code for listing all permutations


code:
#!/usr/bin/python

import csv
import smtplib
from email.mime.text import MIMEText
from email.Header import Header

def sendmail(info_list):
    msg = MIMEText(info_list[2], "html", "utf-8")
    msg['Subject'] = Header("YOUR SUBJECT", "utf-8")
    msg['From'] = "FROM_WHOM@XXX.com"
    msg['To'] = info_list[1]
    s = smtplib.SMTP("smtp.XXX.com")
    s.ehlo()
    s.starttls()
    s.login("YOUR EMAIL USERNAME", "YOUR EMAIL PASSWORD")
    s.sendmail("FROM_WHOM", info_list[1], msg.as_string())

def main():
    with open("msg.csv", "rb") as csvfile:
        msg_reader = csv.reader(csvfile)
        msg_reader.next()
        map(lambda x: sendmail(x), msg_reader)

if __name__ == "__main__":
    main()

rawDescription: Python send email from a csv list

description: Python send email from a csv list


code:
x = np.random.random_sample((10,))
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x,x)
ax.grid()
a = ax.get_xgridlines()
b = a[2]
b.set_color('red')
b.set_linewidth(3)

rawDescription: Matplotlib: Change color of individual grid lines


code:
import matplotlib.pyplot as plt

cpu1_t = [0,1,1,3,3,4,5]
cpu1_p = [1,1,0,0,1,1,0]
cpu2_t = [0,1,1,3,3,4,5]
cpu2_p = [0,0,1,1,0,0,1]

fig = plt.figure()
# plot 1
ax1 = fig.add_subplot(211)
ax1.fill_between(cpu1_t, cpu1_p,0, color='b', edgecolor='k')
ax1.set_ylabel(r'$\tau_1$', size=14, rotation=0)
# plot 2
ax2 = fig.add_subplot(212)
ax2.fill_between(cpu2_t, cpu2_p,0, color='r', edgecolor='k')
ax2.set_ylabel(r'$\tau_2$', size=14, rotation=0)

# customize axis
for ax in [ax1, ax2]:
    ax.set_ylim(0,2)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.yaxis.set_ticks_position('left')
    ax.xaxis.set_ticks_position('bottom')

rawDescription: Visualization of scheduling algorithms with matplotlib


code:
self.cur.execute('SELECT English,Ybanag FROM Words WHERE English IN (%s)' % (",".join('?'*len(lists))), lists)
resultDict=dict(self.cur.fetchall())
outList=[]
for word in lists:
    outList.append(resultDict[word])

rawDescription: How to sort lists of tuples from a query according to the lists value?

description: Sort lists of tuples from a query according to the lists value


code: query = Upload.query.filter(Upload.id == UploadFile.upload_id)

rawDescription: SQLAlchemy find all rows with existing relationship


code: df1.merge(df2, on=['id','desc','year'])

rawDescription: Python Dataframe merge with more than 1 index


code:
class Npc:
    def __init__(self, place):
        self.place = place

    def move(self, destination):
        self.place.matrix[self.position[0]][self.position[1]] = False
        ...

place = SomePlace()
npc = Npc(place)
npc.move("foo")
npc.place = SomeOtherPlace()
npc.move("bar")

rawDescription: Regarding the usage of exec

description: Regarding the usage of exec


code:
import urlparse
import webbrowser

artist_name = 'virt'
url = urlparse.urljoin('http://www.last.fm/music/', artist_name)

# Will open http://www.last.fm/music/virt in your browser.
webbrowser.open(url)

rawDescription: Open a specific page on a website

description: Open a specific page on a website


code:
import datetime as DT
d = DT.datetime(1900,1,1,2,0)
m = DT.datetime(1900,1,1,6,0)
delta = d - DT.datetime(1900,1,1,0,0)
m + delta

rawDescription: add datetime with datetime in python

description: Add datetime with datetime in python


rawDescription: Python regular expression grabbing a middle number


code:
def authGSSServerInit(service):
    """
    Initializes a context for GSSAPI server-side authentication with the given service principal.
    authGSSServerClean must be called after this function returns an OK result to dispose of
    the context once all GSSAPI operations are complete.

    @param service: a string containing the service principal in the form 'type@fqdn'
        (e.g. 'imap@mail.apple.com').
    @return: a tuple of (result, context) where result is the result code (see above) and
        context is an opaque value that will need to be passed to subsequent functions.
    """

rawDescription: authGSSServerInit looks for wrong entry from keytab

description: AuthGSSServerInit looks for wrong entry from keytab


code:
from django.conf import settings

text = u'<img src="%simages/%s"> %s' % (settings.STATIC_URL, ball_file, val)

rawDescription: Django's STATIC_URL and Ajax requests

description: Django's STATIC_URL and Ajax requests


code:
sorted_list = sorted(unsorted.split(), key=lambda x: x.split('@')[1])

print(sorted_list)
#['sge@grg.lt', 'ggrge@yahoo.com']

rawDescription: How to sort a string of email addresses to a list

description: Sort a string of email addresses to a list


code:
from easygui import fileopenbox

def word_count(filename):
    if not filename.endswith(('.txt', '.py', '.java')):
        print('Are you trying to annoy me? How about giving me a TEXT or SOURCE CODE file, genius?')
        return

    with open(filename) as f:
        n_lines = 0
        n_words = 0
        for line in f:
            n_lines += 1
            n_words += len(line.split())
    print('Your file has {} lines, and {} words'.format(n_lines, n_words))

filename = fileopenbox()
word_count(filename)

rawDescription: Python EasyGUI Word Count

description: Python EasyGUI Word Count


code:
results = [0, 0]
with open("\path\to\file.txt") as f:
    for line in f:
        values = line.split("|")
        results[0] += int(values[1])
        results[1] += int(values[2])

print("field 1 = " + str(results[0]), "field 2 = " + str(results[1]))

rawDescription: Parsing and adding content of a file in Python


code:
def pingTime(self):
    then = reactor.seconds()
    def pung(ignored):
        now = reactor.seconds()
        return now - then
    return self.callRemote(Ping).addCallback(pung)

rawDescription: Get "Ping Time" with Twisted Server

description: Get "Ping Time" with Twisted Server


rawDescription: python - how to check if matrix is sparse or not

description: Python - how to check if matrix is sparse or not


code:
d = {'a':'first', 'b':'second'}
d == eval('d')

rawDescription: Can I variabalize an object like a dictionary reference in python

description: Variabalize an object like a dictionary reference in python


code:
model_classes = [WorkAttachment, WorkAttachmentFileBased, WorkAttachmentPicture, ...]

def update_attachment_count_on_save(sender, instance, **kwargs):
    instance.work.attachment_count += 1
    instance.work.save()

for model_class in model_classes:
    post_save.connect(update_attachment_count_on_save,
                      sender=model_class,
                      dispatch_uid="att_post_save_"+model_class.__name__)

rawDescription: How to use Django model inheritance with signals?

description: Use Django model inheritance with signals


code: k1 = lambda x: (x['coords'][0], -x['coords'][1])

rawDescription: Python, itemgetter sort list of dictionaries values from nested list of elements


code:
import sys
from tkinter import *
import time

def tick():
    global time1
    # get the current local time from the PC
    time2 = time.strftime('%H:%M:%S')
    # if time string has changed, update it
    if time2 != time1:
        time1 = time2
        clock.config(text=time2)
        # calls itself every 200 milliseconds
        # to update the time display as needed
        # could use >200 ms, but display gets jerky
    clock.after(200, tick)

root = Tk()
time1 = ''

status = Label(root, text="v1.0", bd=1, relief=SUNKEN, anchor=W)
status.grid(row=0, column=0)

clock = Label(root, font=('times', 20, 'bold'), bg='green')
clock.grid(row=0, column=1)

tick()
root.mainloop()

rawDescription: Digital clock in status bar in python 3 and tkinter


code:
def walk1(dir):
    res = []
    # for all entries in the folder,
    for name in os.listdir(dir):
        # compute the path relative to `dir`
        path = os.path.join(dir,name)
        # include entries recursively.
        if os.path.isfile(path):
            # the path points to a file, save it.
            res.append(path)
        else:
            # the path points to a directory, so we need
            # to fetch the list of entries in there too.
            res.extend(walk1(path))
    # produce all entries at once.
    return res

rawDescription: Filenames and paths trouble

description: Filenames and paths trouble


rawDescription: Python requests from google return in hebrew


code:
class CheckCredentials(Validator):
  '''Checks credentials and creates an account object'''

  def validate(self, element, state):
    username = element['username']
    password = element['password']
    if not (username.all_valid and password.all_valid):
      return false

    self.account = Account(username.u, password.u)
    return self.account.valid()

class doSomethingForm(Form):
  '''Do an action with account credentials'''
  username = String.using(default='',
    validators=[Present(), UsernameFormat()])
  password = String.using(default='',
    validators=[Present(), PasswordFormat()])
  action = String.using(default='',
    validators=[Present(), ActionFormat()])

  validators = (CheckCredentials(),)

@expose('/do_something')
def doSomething(request):
  form = doSomethingForm.from_defaults()
  form.set_flat(request.form)

  result_html = ''
  method = request.method
  if method == 'POST' and not form.validate():
    method = 'GET'
    errors = []
    if form.errors: errors.extend(form.errors)
    for el in form.all_children:
      if el.errors: errors.extend(el.errors)
    result_html = errorsToHtml(errors)

  if method == 'POST':
    result_html = form.account.action(form['action'].u)

  return render_template('do_something.html',
    result=result_html, **form.value)

rawDescription: How do I add form-level validation to a Flatland Form class?

description: Add form-level validation to a Flatland Form class


code:
from nltk import pos_tag, word_tokenize
pos_tag(word_tokenize("John's big idea isn't all that bad."))

rawDescription: Extract product name from english text

description: Extract product name from english text


code: df['Total'] = df.groupby(['Fullname', 'Zip'])['Amount'].transform('sum')

rawDescription: Pandas Sum of Duplicate Attributes

description: Pandas Sum of Duplicate Attributes


code:
re.findall('\w+', u'單語')
re.findall('\w+', u'單語', flags=re.UNICODE)

rawDescription: How to do re.findall('\w+', fin.read()) for unicode? python

description: Do re.findall('\w+', fin.read()) for unicode? python


code:
def foo(a):
    b = 1
    c = 2
    def bar(b,c):
        b = b + a
        c = c + a
        return b, c
    b, c = bar(b,c)
    return (b,c)

print(foo(1))

rawDescription: How does Python handle inner functions with nonlocal effects on their parameters?


code:
from numpy import cos, sin, e, pi, linspace
import matplotlib.pyplot as plt

z = linspace(-228,0,1000)
V0 = 0.1314
alpha = 0.013738
u = V0*cos(alpha*z + 3*pi/4)*e**(alpha*z)
v = V0*sin(alpha*z + 3*pi/4)*e**(alpha*z)

plt.plot(u,v)
plt.show()

rawDescription: Two-dimensional Ekman Spiral in python

description: Two-dimensional Ekman Spiral in python


code:
from traits.api import *
from traitsui.api import *
from traitsui.ui_editors.array_view_editor import ArrayViewEditor
import numpy as np

class DContainer(HasTraits):
    _dict=Dict
    def __getattr__(self, k):
        if k in self._dict:
            return self._dict[k]

class SmallPartOfLargeApplication(HasTraits):
  d=Instance(DContainer)

  def _d_default(self):
    d=DContainer()
    d._dict={'a_stat':np.random.random((10,1)),
            'b_stat':np.random.random((10,10))}

    return d

  def traits_view(self):
    v=View(
        Item('object.d.a_stat',editor=ArrayViewEditor()))
    return v

SmallPartOfLargeApplication().configure_traits()

rawDescription: Defining view elements from dictionary elements in TraitsUI


code:
import click

links_visited = 0
links_detected = 100

with click.progressbar(length=1000) as bar:
    for link in link_elements_list:

        # ... do stuff ...

        links_visited += 1
        links_detected += 0 # Increment how many more new links were found

        progress = float(links_visited) / float(links_detected)
        bar.pos = int(progress * 999) + 1
        bar.update(0)

rawDescription: Python progress bar with dynamic length

description: Python progress bar with dynamic length


code:
import re
sample = 'this is a sample text'
third_word = re.compile(r'\S+ \S+ (?P<word>\S+) .*')
ms = third_word.match(sample)
ms.groupdict()

rawDescription: Grabbing parts of a regular expression

description: Grabbing parts of a regular expression


code:
def my_post_save_handler(sender, instance, **kwargs):
    post_save.disconnect(my_post_save_handler, sender=sender)
    instance.do_stuff()
    instance.save()
    post_save.connect(my_post_save_handler, sender=sender)
post_save.connect(my_post_save_handler, sender=Order)

rawDescription: Django post_save preventing recursion without overriding model save()


code:
from PyQt4 import QtGui

class Window(QtGui.QComboBox):
    def __init__(self):
        QtGui.QComboBox.__init__(self)
        self.resize(200, 25)
        pixmap = QtGui.QPixmap(20, 20)
        for color in 'red orange yellow green blue grey violet'.split():
            pixmap.fill(QtGui.QColor(color))
            self.addItem(QtGui.QIcon(pixmap), color.title())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    win = Window()
    win.show()
    sys.exit(app.exec_())

rawDescription: Constructing a QIcon through a QPainter in PyQT


code:
import time
import sys
from PyQt4 import QtCore, QtGui

class TimeSleep(QtCore.QThread):
    def __init__(self, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.parent = parent

    def run(self):
        print("start sleep")
        time.sleep(5)
        print("stop sleep")
        self.parent.glabel.setText(u"Done")

class AnyWidget(QtGui.QWidget):
    def __init__(self, *args):

        QtGui.QWidget.__init__(self, *args)
        self.setWindowTitle("PETHARD")
        boxlay = QtGui.QHBoxLayout(self)
        frame = QtGui.QFrame(self)  # Фрейм
        frame.setFrameShape(QtGui.QFrame.StyledPanel)
        frame.setFrameShadow(QtGui.QFrame.Raised)

        gridlay = QtGui.QGridLayout(
            frame)  # Менеджер размещения элементов во фрейме
        label = QtGui.QLabel(u"Welcome", frame)  # Текстовая метка.
        self.glabel = label
        gridlay.addWidget(label, 0, 0)
        button1 = QtGui.QPushButton(u"Load From MC", frame)
        self.connect(button1, QtCore.SIGNAL("clicked()"), self.ts)
        gridlay.addWidget(button1, 1, 0)
        boxlay.addWidget(frame)

    def ts(self):
        self.glabel.setText(u"Waiting...")
        self.thread = TimeSleep(parent=self)
        self.thread.start()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    aw = AnyWidget()
    aw.show()
    sys.exit(app.exec_())

rawDescription: Problems with the order execution functions when use PyQT4


rawDescription: How can I add a column from one dataframe to another dataframe?

description: Add a column from one dataframe to another dataframe


code:
from collections import defaultdict
dic = defaultdict(int)
for j, f in enumerate(field):
    dic[f] += counts[j]

field_counts = np.array([dic[f] for f in field])

rawDescription: Python/Numpy - calculate sum of equal array elements


code:
class EventAdmin(admin.ModelAdmin):

  def get_queryset(self, request):
    qs = super(EventAdmin, self).get_queryset(request)
    qs = qs.prefetch_related('eventdate_set')
    qs = qs.extra(
      select={
        'next_date': """SELECT MIN(events_eventdate.date)
          FROM events_eventdate
          WHERE events_event.id == events_eventdate.event_id AND
          events_eventdate.date >= '{}'
          """.format(now().date().isoformat())
      }
    )
    return qs

  def next_date(self, obj):
      try:
        return obj.next_date
      except IndexError:
        return 'abgelaufen'

  next_date.short_description = 'Nächster Termin'
  next_date.admin_order_field = 'next_date'

rawDescription: Django Admin: How to sort by data from another model?


code:
filenumber = 0
outfile = None
with open('source_file.txt') as f:
    for line in f:
        if line.strip() == 'DOCUMENTS':
            filenumber += 1
            outfile = open('result%03d.txt' % filenumber, 'w')
        elif line.strip().startswith('Copyright') and outfile:
            outfile.close()
            outfile = None
        elif outfile:
            outfile.write(line)
if outfile:
    outfile.close()

rawDescription: Splitting 25mb .txt file into smaller files using text delimiter


code:
import numpy as np
a = np.array([[1, 2, 3], [2, 3, 4], [1, 2, 3], [3, 4, 5]])
a
np.array([np.array(x) for x in set(tuple(x) for x in a)]) # or "list(x) for x in set[...]"

rawDescription: How can I use the unique(a, 'rows') from MATLAB in Python?

description: Use the unique(a, 'rows') from MATLAB in Python


code: from foreign_code import useful_function

rawDescription: Calling a function in a separate file in Python


code:
def show_header_context_menu(self, position):
    column = self.headers.logicalIndexAt(position)

rawDescription: Getting Header Column on Right Click for QTableWidget


code: df[df > current_date]

rawDescription: Pandas: Filtering only headers, first cell value, and cell value: if a cell(s) in row meets condition


code:
from telnetlib import IAC, NOP

...

telnet_object.sock.sendall(IAC + NOP)

rawDescription: Detect a closed connection in python's telnetlib


code:
var = {'upper_scope':None}
def first(var=var):
    var = {'upper_scope': var}
    def second(var=var):
        var = {'upper_scope': var }
        def third(var=var):
             var = ...

rawDescription: How can I implement Javascript closures in Python?

description: Implement Javascript closures in Python


code:
import re
url = 'http://stackoverflow.com'
pat = re.compile(re.escape(url))
pat.match('http://stackoverflow.com')
pat.match('http://foo.com') is None

rawDescription: Python regex to go match any string that starts with a string


rawDescription: SQLAlchemy Eager Loading with Relationships


code:
def initUI(self):
    self.parent.title("HOME SCREEN")

    frame = Frame(self)

    self.pack(fill=BOTH, expand=1)
    label1=Label(frame,text="USERNAME",)
    label2=Label(frame,text="PASSWORD")
    text1=Entry(frame, show="*", width=15,)
    text2=Entry(frame,width=15)
    login=Button(self,text="Login",command=self.load)
    register=Button(self,text='Register',command=self.dump)
    Quit=Button(self,text='Quit',command=self.quit)
    delete=Button(self,text='Delete Account',command=self.delete)
    showb=Button(self,text='Show Accounts',command=self.show)

    label1.pack(side=LEFT)
    text2.pack(side=LEFT, padx=5, pady=5)
    label2.pack(side=LEFT )
    text1.pack(side=LEFT, padx=5, pady=5)
    frame.pack(fill=BOTH, expand=1)

    Quit.pack(side=RIGHT ,padx=5, pady=5)
    register.pack(side=RIGHT)
    login.pack(side=RIGHT)
    delete.pack(side=RIGHT)
    showb.pack(side=RIGHT)
    global text1
    global text2
def dump(self):

    z=(text1.get())
    a=(text2.get())

rawDescription: 'get' returning blank value python

description: 'get' returning blank value python


code:
def execute(command):
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

    # Poll process for new output until finished
    while True:
        nextline = process.stdout.readline()
        if nextline == '' and process.poll() is not None:
            break
        sys.stdout.write(nextline)
        sys.stdout.flush()

    output = process.communicate()[0]
    exitCode = process.returncode

    if (exitCode == 0):
        return output
    else:
        raise ProcessException(command, exitCode, output)

rawDescription: Constantly print Subprocess output while process is running


rawDescription: Rearranging list containing dates in chronological order


code: ''.join(t[0] for t in tuples)

rawDescription: Have a list of tuples with strings, want to turn into a single string in Python


code:
Process(target=readMeter1).start()  # fork a new process, call readMeter1
Process(target=readMeter2).start()  # fork a new process, call readMeter2

rawDescription: Python multiprocessing second process doesn't start


code:
from pkg_resources import resource_stream

_log_config_file = 'logging.conf'
_log_config_location = resource_stream(__name__, _log_config_file)
logging.config.fileConfig(_log_config_location)
_log = logging.getLogger('package.module')

rawDescription: Problem accessing config files within a Python egg


code:
out = None
oldfile = None
with open("entry.txt") as f:
    for line in f:
        newfile = l.split("\t")[0]
        if newfile != oldfile:
            if out: out.close()
            out = open(newfile + ".txt", "w")
            oldfile = newfile
        out.write("\t".join(line.split("\t")[1:]))

rawDescription: How to split text file into number of text files using python

description: Split text file into number of text files using python


code:
if details:
    print(details)
    print("Customer number: ", details[0][0])
    print("Date of payment: ", details[0][1])
    print("Payment Amount: ", details[0][2])
    print("Paid Amount: ", details[0][4])
    break

rawDescription: Printing a list within a list

description: Printing a list within a list


code:
def parse(request):
    encoding = ... #get encoding from headers
    return json.load(TextIOWrapper(request.body, encoding=encoding))

rawDescription: Handling application/json data with bottle


rawDescription: How can I place a panel in another panel?

description: Place a panel in another panel


code:
def online_only(func):
    def f(self, *args, **kwargs):
        if self.running:
            return func(self, *args, **kwargs)
        else:
            return False
    return f

rawDescription: Get class in Python decorator

description: Get class in Python decorator


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

# Random points between 50000 and 51000
x, y = 1000 * np.random.random((2, 10)) + 50000

# A 10x10 "image"...
image = np.arange(100).reshape((10,10))

# In a lot of cases, image data will be "flipped" vertically, so you may need
# use the `origin` kwarg, as well (or just swap the ymin and ymax ordering).
plt.imshow(image, extent=[x.min(), x.max(), y.min(), y.max()])
plt.plot(x, y, 'ro')

plt.show()

rawDescription: Matplotlib imshow offset to match axis?

description: Matplotlib imshow offset to match axis


rawDescription: Inserting into postgres on heroku executes but doesn't stay


rawDescription: Converting a hex-string representation to actual bytes in Python


code:
class X(object):
  print("Loading X")

rawDescription: python observer pattern

description: Python observer pattern


code:
string_variable2 = file2.replacefunction('Some text','a_unique_key', string_variable1)
string_variable2 = file2.replacefunction('Other text','another_unique_key', string_variable2)
file2.replacefunction('More text','unique_key_3', string_variable2)

rawDescription: Is there any way to access a variable from outside a function, explicitly as a variable and not via assignment to a function?


code:
check_names = ["Snagit", "Camtasia", "GotoMeeting"]
variables = []
for name in check_names:
    variables.append(IntVar())
    Checkbutton(text=name, variable=variables[-1]).pack()

app.mainloop()
checks = [variable.get() for variable in variables]

rawDescription: How to write this more "Pythonically"

description: Write this more "Pythonically"


code:
# ...
import datetime
# ...
class MyModel(Base):
    __tablename__ = "my_table"
    # ...
    created_at = Column(DateTime, default=datetime.date.today)
    last_updated_at = Column(DateTime, onupdate=datetime.datetime.now)

rawDescription: Is it possible to set some columns automatically in sqlalchemy


code:
import os, glob
files = glob.glob('*.txt')

all_lines = []
for f in files:
    with open(f,'r') as fi:
        all_lines += fi.readlines()
all_lines = set(all_lines)

with open('combinedfile.txt','w') as fo:
    fo.write("\n".join(all_lines))

rawDescription: fastest way to combine several text files without duplicate lines

description: Fastest way to combine several text files without duplicate lines


code:
import calendar
zip(list(calendar.day_abbr), range(7))

rawDescription: python datetime, convert weekday's abbrv to number?

description: Python datetime, convert weekday's abbrv to number


code:
my_dict = {i:i+1 for i in range(10)} # build a module-level dict

def function(data):
    # Do stuff with the global (module-level) dict
    my_dict[2] = data[-1]
    data.append(my_dict[9])
    return data

if __name__ == '__main__':
    result = function([1,2,3,4,5])
    print(result)
    print(my_dict)

rawDescription: making a python dictionary accessible inside a function

description: Making a python dictionary accessible inside a function


code:
class TweakToolbar(plugins.PluginBase):
    """Plugin for changing toolbar"""

    JAVASCRIPT = """
    mpld3.register_plugin("tweaktoolbar", TweakToolbar);
    TweakToolbar.prototype = Object.create(mpld3.Plugin.prototype);
    TweakToolbar.prototype.constructor = TweakToolbar;
    function TweakToolbar(fig, props){
        mpld3.Plugin.call(this, fig, props);
    };

    TweakToolbar.prototype.draw = function(){
      // the toolbar svg doesn't exist
      // yet, so first draw it
      this.fig.toolbar.draw();

      // then change the toolbar as desired

      // show toolbar
      this.fig.toolbar.buttonsobj.transition(750).attr("y", 0);

      // remove event triggers
      this.fig.canvas
        .on("mouseenter", null)
        .on("mouseleave", null)
        .on("touchenter", null)
        .on("touchstart", null);

      // then remove the draw function,
      // so that it is not called again
      this.fig.toolbar.draw = function() {}
    }
    """
    def __init__(self):
        self.dict_ = {"type": "tweaktoolbar"}

rawDescription: Unhide toolbar in MPLD3

description: Unhide toolbar in MPLD3


code:
class TransparentText(wx.StaticText):
  def __init__(self, parent, id=wx.ID_ANY, label='', pos=wx.DefaultPosition,
             size=wx.DefaultSize, style=wx.TRANSPARENT_WINDOW, name='transparenttext'):
    wx.StaticText.__init__(self, parent, id, label, pos, size, style, name)

    self.Bind(wx.EVT_PAINT, self.on_paint)
    self.Bind(wx.EVT_ERASE_BACKGROUND, lambda event: None)
    self.Bind(wx.EVT_SIZE, self.on_size)

  def on_paint(self, event):
    bdc = wx.PaintDC(self)
    dc = wx.GCDC(bdc)

    font_face = self.GetFont()
    font_color = self.GetForegroundColour()

    dc.SetFont(font_face)
    dc.SetTextForeground(font_color)
    dc.DrawText(self.GetLabel(), 0, 0)

  def on_size(self, event):
    self.Refresh()
    event.Skip()

rawDescription: What are my options for drawing controls with transparent/translucent backgrounds in wxPython?


code:
prime_factors = factorize(N)      # [2,2,2,3,3,17,19]
clusters = [p**e for p, e in collections.Counter(prime_factors).items()]  # [8,9,17,19]
R = max(prod(group) for group in powerset(clusters) if prod(group) < math.sqrt(N))
F = N // R

rawDescription: Find the largest divisor of N that is less than sqrt(N)


code:
from collections import namedtuple
coords = namedtuple("Coords", ['x', 'y'])
coords
coords(1,2)
coords(1.235445,2.2345345)
coords(1.2354451241234214,2.234534512412414134)

rawDescription: What is the ideal data type to store latitude and longitude values in Python?


code:
total = 0
for i in range(1,10):
   if num/i*i == num:
     total += dec(num/i, num_dig-1)
return total

rawDescription: Need help understanding a Python snippet.


code:
def object_to_dict(obj, found=None):
    if found is None:
        found = set()
    mapper = class_mapper(obj.__class__)
    columns = [column.key for column in mapper.columns]
    get_key_value = lambda c: (c, getattr(obj, c).isoformat()) if isinstance(getattr(obj, c), datetime) else (c, getattr(obj, c))
    out = dict(map(get_key_value, columns))
    for name, relation in mapper.relationships.items():
        if relation not in found:
            found.add(relation)
            related_obj = getattr(obj, name)
            if related_obj is not None:
                if relation.uselist:
                    out[name] = [object_to_dict(child, found) for child in related_obj]
                else:
                    out[name] = object_to_dict(related_obj, found)
    return out

rawDescription: Convert SqlAlchemy orm result to dict

description: Convert SqlAlchemy orm result to dict


code:
import xml.etree.ElementTree as ET
import json

s= '''
<root>
    <abc>
        <doc id="12" url="example.com" title="Anarchism"> Anarchism .... </doc>
    </abc>
    <doc id="123" url="example2" title="Laptop"> Laptop .... </doc>
    <def>
        <doc id="3">Final text</doc>
    </def>
</root>
'''

tree = ET.fromstring(s)
j = []
# use iterfind will iterate the element tree and find the doc element
for node in tree.iterfind('.//doc'):
    # manually build the dict with doc attribute and text
    attrib = {}
    attrib.update(node.attrib)
    attrib.update({'text': node.text})
    d = {'doc': [ attrib ] }
    j.append(d)

json.dumps(j)
'[{"doc": [{"url": "example.com", "text": " Anarchism .... ", "id": "12", "title": "Anarchism"}]}, {"doc": [{"url": "example2", "text": " Laptop .... ", "id": "123", "title": "Laptop"}]}, {"doc": [{"text": "Final text", "id": "3"}]}]'

# to write to a json file
with open('yourjsonfile', 'w') as f:
    f.write(json.dumps(j))

rawDescription: Parse error with same name nested tags using python xml to json


code:
# Sequential wait to finish before moving onto the next script
try:
    execfile("SUBSCRIPTS/TESTSCRIPT.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

# Semi-Sequential (Don't wait for it to finish before moving onto the third script)
p1 = subprocess.Popen(["pythonw", "SUBSCRIPTS/TEST.py", "0"], shell=True)

# Sequential wait to finish before moving onto the next script
try:
    execfile("SUBSCRIPTS/TEST.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

#Do you want to kill the "pythonw", "SUBSCRIPTS/TEST.py", "0" command after the "SUBSCRIPTS/TEST.py" call or do you want to allow the pythonw command to continue running until after the "SUBSCRIPTS/TESTSCRIPT.py"

#you need to put this code depending on where the subprocess.Popen(["pythonw", "SUBSCRIPTS/TEST.py", "0"], shell=True) #script needs to be killed
currentStatus = p1.poll()
if currentStatus is None: #then it is still running
  try:
    p1.kill() #maybe try os.kill(p1.pid,2) if p1.kill does not work
  except:
    #do something else if process is done running - maybe do nothing?
    pass

# Sequential wait to finish before moving onto the next script
try:
    execfile("SUBSCRIPTS/TESTSCRIPT.py", {})
except Exception:
    errors.write(traceback.format_exc() + '\n')
    errors.write("\n\n")

#or put the code snippet here if you want to allow the pythonw command to continue running until after the SUBSCRIPTS/TESTSCRIPT.py command

rawDescription: Timeout on an execfile call function for windows? (Signal Alternative?)


code:
import itertools
a = range(1, 11)
a
b = itertools.cycle([1,2,3])
b
ans = [i*j for i,j in zip(a,b)]
ans

rawDescription: Mapping using a generator

description: Mapping using a generator