code:
def myRange1(start, stop, step=1, ans=None):
    assert step >= 0;
    ans = ans or [];
    if (start >= stop):
        return ans;
    # Otherwise...
    ans.append(start);
    return myRange1(start + step, stop, step, ans);

def myRange2(start, stop, step=1):
    assert step >= 0;
    if (start >= stop):
        return [];
    # Otherwise...
    return [start] + myRange2(start + step, stop, step);

rawDescription: Python range function in terms of itself


code:
img = Image.open("withAlpha.png")
p = img.load()

for y in range(2):
    for x in range(img.size[0]):
        t = list(p[x,y])
        t[3] = 0
        p[x,y] = tuple(t)

img.save("result.png")

rawDescription: Python Image Library - Make area of image transparent


code:
import gtk
w = gtk.Window()
w.show_all()
gw = w.get_window()
gw
gw.ensure_native()
gw.has_native()

rawDescription: PyGtk equivalent of gdk_window_ensure_native?


rawDescription: Socket set source port number

description: Socket set source port number


code:
import string
digs = string.digits + string.letters

def int2base(x, base):
  if x < 0: sign = -1
  elif x == 0: return digs[0]
  else: sign = 1
  x *= sign
  digits = []
  while x:
    digits.append(digs[x % base])
    x /= base
  if sign < 0:
    digits.append('-')
  digits.reverse()
  return ''.join(digits)

rawDescription: convert integer to a string in a given numeric base in python

description: Convert integer to a string in a given numeric base in python


code:
if form.is_valid():
    d_data = Information.objects.filter(name=form.cleaned_data.get('full_name'))

    if len(d_data) == 1:
        d_data.delete()
        d_data = None
else:
    d_data = None

context = {
    'form': form,
    'd_data': d_data,
}

return render(request, 'delete.html', context)

rawDescription: Using Django ----If there are more than 1 record then displaying it and if there is only 1 record then i am deleting it


code:
distances = [[euclidean(points[a], points[b]), a, b]
             for a, b in itertools.combinations(range(len(points)), 2)]
distances.sort() # distance is already first element, so no key function required

rawDescription: euclidean distance between values in a array - result ordered asc in new array

description: Euclidean distance between values in a array - result ordered asc in new array


code:
import matplotlib.pyplot as plt
import scipy.io
data = scipy.io.loadmat('arrytmia_data_bad.mat')
x = data['data']

plt.plot(x, linestyle='', marker='x')
plt.show()

rawDescription: To plot this .Mat list data in Python

description: To plot this .Mat list data in Python


code:
seg_length = 3
a = range(10)
[a[x:x+seg_length] for x in range(0,len(a),seg_length)]

rawDescription: Segment a list in Python

description: Segment a list in Python


code:
while True:
    snum = input("Please enter a decimal number:")
    try:
        num = float(snum)
        break
    except ValueError:
        print("This is not a valid decimal number!")
print("This number, rounded to two places, is: {:0.2f}".format(num))

rawDescription: Python Ask For Decimal Number

description: Python Ask For Decimal Number


rawDescription: How to replace values in a numpy array based on another column?

description: Replace values in a numpy array based on another column


code: address = "http://www.blekko.com/?q='%(query)s'+/html&auth=<mykey>" % dict(query=request.vars.query)

rawDescription: Displaying results from search API

description: Displaying results from search API


code:
# Karvonens formel
#
print(
"""
Kalkulere dine treningssoner for lett lping, anaerob terskel (AT) og VO2 Max treningskter.

Instruksjoner

1. Fyll inn din alder, hvilepuls og kjnn.
2. Skriv inn din maksimale hjertefrekvens, hvis du vet det, ellers trykk enter - deretter beregnet programmet det selv som flger:
(Menn 214 - (0,8 * alder) Kvinner:. 209 - (0,7 * alder).

3. Treningssonenes verdier beregnes ved hjelp av Karvonen formelen:
X% = (Maksimal hjertefrekvens hvilepuls) * x/100) + hvilepuls
"""
)

kjonn=' '
alder=0
hvilepuls=0
makpuls=' '

def check_positive(n):
    if n > 0:
        return True
    else:
        print("@@@@@ Cannot enter a negative or 0 value! @@@@@")
        return False
def check_positive_or_zero(n):
    if n >= 0:
        return True
    else:
        print("@@@@@ Cannot enter a negative value! @@@@@")
        return False

def get_input_int(s_mesg, fn_validate, default=None):
    while True:
        s = input(s_mesg).strip()
        if not s and default is not None:
            return default
        # not a default value; try it as an int
        try:
            n = int(s)
        except ValueError:
            print("@@@@@ Not even an integer! @@@@@")
            continue
        # works as an int; is it valid?
        if fn_validate(n):
            return n

while kjonn not in ('m', 'd'):
    kjonn = input("Hvilken kjnn er du? (M)ann/(D)ame\t").strip().lower()

alder = get_input_int("Hvor mange r er du?\t", check_positive)
hvilepuls = get_input_int("Hva er din hvilepuls?\t", check_positive)
makspuls = get_input_int("Hva er din makspuls?\t", check_positive_or_zero, default=0)

if not makspuls:
    if kjonn == 'm':
        makspuls = int(214 - 0.8*int(alder))
    else:
        makspuls = int(209 - 0.7*int(alder))

prosent60 = (makspuls-hvilepuls)*0.6 + hvilepuls
prosent75 = (makspuls-hvilepuls)*0.75 + hvilepuls
prosent85 = (makspuls-hvilepuls)*0.85 + hvilepuls
prosent90 = (makspuls-hvilepuls)*0.9 + hvilepuls

# Remove decimals
prosent60 = round(prosent60)
prosent75 = round(prosent75)
prosent85 = round(prosent85)
prosent90 = round(prosent90)

print("\n\n")
if kjonn == 'm':
    print("Din kjnn  er:\t\tMann")
else:
    print("Din kjnn  er:\t\tDame")

print("Din alder er:\t\t", alder)
print("Din hvilepuls er:\t", hvilepuls," slag/min")
print("Din makspuls er:\t", makspuls," slag/min")

print("\n\n")
print("Din lavsone er:\t",prosent60,"-",prosent75," slag/min")
print("Din ATsone er:\t",prosent85,"-",prosent90," slag/min")
print("Din VO2max er:\t",prosent90,"-",makspuls," slag/min")

input("\n\nTrykk enter for avslutte")

rawDescription: How to check an input is not blank and is a number greater than zero in python

description: Check an input is not blank and is a number greater than zero in python


code:
from collections import defaultdict
votes = defaultdict(int)
vote = raw_input("Enter who you vote for: ")
votes[vote] += 1

rawDescription: Keep a tally based on input value - different "variables"?


code:
s = ['sox', '-m', 'path/to/silence.wav',
     '|sox path/to/audio1.wav -p pad 0',
     '|sox path/to/audio2.wav -p pad 5',
     '|sox path/to/audio3.wav -p pad 10',
     'path/to/output.wav']
subprocess.call(s)

rawDescription: How to Execute A Complex SoX Command-Line String In Python


rawDescription: How to extract specific digits after underscore from filename in python

description: Extract specific digits after underscore from filename in python


code:
df['y'] = np.select([df['x'] < 4, 6 < df['x']], [0, 1], np.nan)
df['y'] = df['y'].fillna(method='ffill').astype('int')
df

rawDescription: Create a column in a pandas DataFrame using the previously computed value


code:
print(b'Newline\nAnother line')
print(b'Newline\nAnother line'.decode('utf8'))

rawDescription: Python-unexpected behavior when I don't decode to utf-8


code: re.findall(r'Start of test(.+?)Start of test', curfile, re.S)

rawDescription: Python regular expression, repeating data


code:
x
pandas.Series(x).unstack()

rawDescription: How to construct pandas DataFrame from dictionary with key as column and row index

description: Construct pandas DataFrame from dictionary with key as column and row index


code:
import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write('Hello, World')

app = webapp2.WSGIApplication([('/', MainPage)])

def main():
    application = webapp.WSGIApplication([("/", MainPage)], debug=True)
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

rawDescription: Adding new app in appengine

description: Adding new app in appengine


code: spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')

rawDescription: How to use quote characters python 3

description: Use quote characters python 3


code:
def sort_last(tuples):
    return sorted(tuples, key = lambda t: t[-1])

rawDescription: How do I make a function that returns a list of tuples sorted by the last element in the tuple?

description: Make a function that returns a list of tuples sorted by the last element in the tuple


code:
from myproject.main import main
sys.path.append(os.path.join("..", "myproject"))

rawDescription: import a module from a directory, not from the installed module

description: Import a module from a directory, not from the installed module


code:
my_list = ['abc', 'dog', 'cat', 'bird', ...]
my_dict = dict(enumerate(my_list))

rawDescription: How to convert a Python list into a dictionary with "default" key values?

description: Convert a Python list into a dictionary with "default" key values


code:
import os
import sys

f = open(os.devnull, 'w')
x = sys.stdout # save sys.stdout
sys.stdout = f

print("a")

sys.stdout = x # re-assign sys.stdout
print("b") # print 'b'

rawDescription: Python-Undoing stdout redirect

description: Python-Undoing stdout redirect


code:
import numpy as np

alpha = np.array([1e5, 1e3, 1e5, 1e7, 1e3])
dz = 0.001
zeta = alpha / dz**2

rawDescription: Array Operation Equivalent Python and Matlab


code: users = client.get('/users', g ='keyword')

rawDescription: soundcloud api python user information

description: Soundcloud api python user information


code:
try: import elementtree.ElementTree as ET
except ImportError:
    try: import cElementTree as ET
    except ImportError:
        try: import lxml.etree as ET
        except ImportError:
            import xml.etree.ElementTree as ET # Python 2.5 and up

rawDescription: Best way to import version-specific python modules

description: Import version-specific python modules


code:
from PIL import Image
from StringIO import StringIO

LargeData = urllib2.urlopen(PosterURL).read()

# read data from string
LargePoster = Image.open(StringIO(LargeData))

# After editing the image, turn it back into a string
# for saving in the database:
result = StringIO()
format = 'JPEG' # or whatever you want
SmallPoster.save(result, format)
SmallPosterString = result.getvalue()

rawDescription: Fetch image from internet, modify and insert to database in python


code:
from time import time, sleep
from Tkinter import *

def empty_textbox():
    textbox.delete("1.0", END)

root = Tk()

frame = Frame(root, width=300, height=100)
textbox = Text(frame)

frame.pack_propagate(0)
frame.pack()
textbox.pack()

textbox.insert(END, 'This is a test')
textbox.after(5000, empty_textbox)

root.mainloop()

rawDescription: Python time.sleep

description: Python time.sleep


code:
def submit(self):

    if self.name.get() == "":
        messagebox.showerror(title="No name",message="No name")
        return

    driver = webdriver.Firefox()
    driver.get("http://stackoverflow.com/")

rawDescription: make person enter something before executing command(Tkinter,Python,Selenium)

description: Make person enter something before executing command(Tkinter,Python,Selenium)


code:
replacers = {1: '1=Y', 0: '0=Y', 2: '2=M'}
g.replace(replacers)

rawDescription: Relabeling pivot tables

description: Relabeling pivot tables


code:
from PySide import QtGui, QtCore, QtWebKit

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.view = QtWebKit.QWebView(self)
        self.view.settings().setAttribute(
            QtWebKit.QWebSettings.WebAttribute.DeveloperExtrasEnabled, True)
        self.inspector = QtWebKit.QWebInspector(self)
        self.inspector.setPage(self.view.page())
        self.inspector.hide()
        self.splitter = QtGui.QSplitter(self)
        self.splitter.addWidget(self.view)
        self.splitter.addWidget(self.inspector)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.splitter)
        QtGui.QShortcut(QtGui.QKeySequence('F7'), self,
            self.handleShowInspector)

    def handleShowInspector(self):
        self.inspector.setShown(self.inspector.isHidden())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.view.load(QtCore.QUrl('http://www.google.com'))
    window.show()
    sys.exit(app.exec_())

rawDescription: PySide how to get QWebInspector same window


code:
from gi.repository import Gtk, GLib

class MyWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self)
        self.set_default_size(50, 20)
        label = Gtk.Label("test")
        self.add(label)
        GLib.timeout_add_seconds(3, label.destroy)

win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

rawDescription: GTK Python display message for given time


code: setattr(row, key, value)

rawDescription: Python insert variable in loop into SQLite database using SQLAlchemy


code:
colorCenter = easyxf('pattern: pattern solid, fore_colour yellow;'
                      'align: horiz center;')

rawDescription: put style and background color python excel

description: Put style and background color python excel


code:
import sys
in_console = sys.__stdin__.isatty()

rawDescription: Detect how I run Python script

description: Detect how I run Python script


code:
def countPar(s):
    s=s[1:-1]
    openPar=0
    for (i,c) in enumerate(s):
        if c=="(":
            openPar+=1
        elif c==")":
            openPar-=1
        if openPar==0:
            break
    return [s[0:i+1],s[i+2:]]

rawDescription: How to split with multiple bracket

description: Split with multiple bracket


code:
class MyDict(dict):
    def __setitem__(self, key, val):
        #Test for proper interface
        if val.pass_the_test:
            dict.__setitem__(self, key, val)
        else:
            raise SomeKindOfException()

rawDescription: Type safe Python 3.2 dictionary

description: Type safe Python 3.2 dictionary


code:
pyplot.hist(
    df['Average time taken(line items)'].values,
    weights=df['Number of line items.1'].values);

rawDescription: Repeating a dataframe value N times based on another column


code:
def onKeyboardEvent(event):
    if event.KeyID == 115:      #F4
        startTimer(doTimer, 2)
    if event.KeyID == 113:
        stopTimer()

def doTimer():
    selectAndCopy(468,722)
    getClipboard()

rawDescription: How can I make a while True break if certain key is pressed? [Python]

description: Make a while True break if certain key is pressed? [Python]


rawDescription: Python Spliting extracted CSV Data

description: Python Spliting extracted CSV Data


rawDescription: How to add widgets dynamically after parent is created

description: Add widgets dynamically after parent is created


code:
from itertools import izip
single = ['key1', 'value1', 'key2', 'value2', 'key3', 'value3']
si = iter(single)
dict(izip(si, si))

rawDescription: single list to dictionary

description: Single list to dictionary


code:
class MyViewModel(models.Model):
    field1 = models.IntegerField()
    [...]

    class Meta:
        managed = False
        db_table = 'MyView' # your view name

rawDescription: How to use MySQL view in django?

description: Use MySQL view in django


code:
import time
results = []
while True:
    mark = time.time()
    newobjs = dig_more_objects(obj)
    elapsed = time.time() - mark
    results.append((newobjs, elapsed))
    count = 0
    threshhold = 0
    for objs, elapsed in results[::-1]:
        count += len(objs)  # or +1 of dig_more_objects only returns one at a time
        threshhold += elapsed
        if threshhold > 60.0 and count < 10:
            break

rawDescription: using an asymptote for program completion

description: Using an asymptote for program completion


code:
import os
import pygame

images = {str(i)[:-4]:pygame.image.load("images/"+i) for i in os.listdir("images") if os.path.isfile("images/"+i)}

rawDescription: How do I load a folder of images in automatically?

description: Load a folder of images in automatically


code:
import datetime

now = datetime.datetime.now()
then = now - datetime.timedelta(days=90)

rawDescription: timestamp from 3months ago

description: Timestamp from 3months ago


code:
cvlock.acquire()
while attribute_val in attribute_val_list:
  cvlock.wait()
attribute_val_list.append(attribute_val)
cvlock.release()

# Do your thing.

cvlock.acquire()
attribute_val_list.remove(attribute_val)
cvlock.notifyAll()
cvlock.release()

rawDescription: Locking only a subset of threats in Python


code:
from scipy.optimize import curve_fit,fsolve

v = np.array([1.1,2.6,3.1,4.9,5.4,6.0])
la = np.array([1,4,8,9,10,20])

def func(x, a, b):
        return a*np.exp(b*x)

popt, pcov = curve_fit(func, v, la)
yn = func(v, *popt)
fig,ax1 = plt.subplots()
l = ax1.plot(v, la, 'rx')
ax1.plot(v, func(v,*popt))

#exact match, as the value 4 appears in your original data
index = where(la==4)[0]
vla4exact = v[index]#array([ 2.6])

#by finding the zero of the fit curve. This works for any value
x0=2 #choose this initial guess for fsolve with care
vla4fsolve = fsolve(lambda x: func(x,*popt)-4,x0)#array([ 2.6])

rawDescription: find individual point on curve (exponential function)

description: Find individual point on curve (exponential function)


code:
import networkx as nx
square = nx.Graph()
square.add_cycle([1,2,3,4])
triangle = nx.Graph()
triangle.add_cycle([10,20,30])
shapes = nx.Graph()
shapes.add_edge(triangle,square)
shapes.edges()
shapes.nodes()[0].edges()
shapes.nodes()[1].edges()

rawDescription: In NetworkX is it possible to define a node as a subgraph?


code:
@myapp.route('/foo')
def bar():
    # start tasks
    task_1 = a_long_process.delay(x, y)
    task_2 = another_long_process.delay(x, y)
    task_3 = yet_another_long_process.delay(x, y)
    # fetch results
    try:
        task_1_result = task_1.get(timeout=1)
        task_2_result = task_2.get(timeout=1)
        task_3_result = task_3.get(timeout=1)
    except TimeoutError:
        # Handle this or don't specify a timeout.
        raise
    # combine results
    return task_1 + task_2 + task_3

rawDescription: Concurrent asynchronous processes with Python, Flask and Celery


code:
def bdh(sec_list, fld_list, start_date,
    end_date=dt.date.today().strftime('%Y%m%d'), periodicity='DAILY',
    verbose=False, **kwargs):
    """ Sends a historical request to Bloomberg.
    Parameters:
        sec_list: tuple or list of valid Bloomberg tickers.
        fld_list: tuple or list of valid Bloomberg fields.
        start_date: string formatted YYYYMMDD.
        end_date: string formatted YYYYMMDD (default = Today()).
        periodicity: string (default: DAILY).
        verbose: boolean to log Bloomberg response messages (default: False)
        **kwargs: any valid parameter.
    Returns a panda.Panel object.
    """

rawDescription: Pandas wrapper for Bloomberg api?

description: Pandas wrapper for Bloomberg api


code: from spiderA import theMethod

rawDescription: Scrapy Import Method from another Spider


code: df = df[new_index]

rawDescription: Pandas time series resample

description: Pandas time series resample


code:
from django.core.exceptions import ValidationError

class MyModel(models.Model):
     ...
     def clean(self):
         if self.call_me and not self.telephone.strip():
             raise ValidationError('Telephone is required')

rawDescription: Django models - field dependency

description: Django models - field dependency


rawDescription: Python: introspection, How would I verify that values in a series are strings?


code:
import sys
from PySide import QtGui , QtCore

class MyStatusBar(QtGui.QStatusBar):
    def __init__(self, parent=None):
        super(MyStatusBar, self).__init__(parent)
    #Override any functions, or define new function for our status bar here

class MyMainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        #Set the size of the window
        self.setMinimumSize(300,300)
        #Create a status bar, from our OWN class
        self.status_bar = MyStatusBar(self)
        self.status_bar.setGeometry(QtCore.QRect(0, 0, 50, 50))
        self.status_bar.showMessage('Ready')
        #Add a simple quit button, from the DEFAULT class
        self.quit_button = QtGui.QPushButton(self)
        self.quit_button.clicked.connect(self.close)
        self.quit_button.setGeometry(QtCore.QRect(100, 100, 100, 35))
        self.quit_button.setText("Close")

#Start the application
app = QtGui.QApplication(sys.argv)
top = MyMainWindow()
top.show()
app.exec_()

rawDescription: How to add a Status to this PySide based ui

description: Add a Status to this PySide based ui


rawDescription: Merge two objects in Python

description: Merge two objects in Python


code:
from cStringIO import StringIO
import sys

old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

# blah blah lots of code ...

sys.stdout = old_stdout

# examine mystdout.getvalue()

rawDescription: Can I redirect the stdout in python into some sort of string buffer?

description: Redirect the stdout in python into some sort of string buffer


code:
## {{{ http://code.activestate.com/recipes/578019/ (r15)
#!/usr/bin/env python

"""
Bytes-to-human / human-to-bytes converter.
Based on: http://goo.gl/kTQMs
Working with Python 2.x and 3.x.

Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com>
License: MIT
"""

# see: http://goo.gl/kTQMs
SYMBOLS = {
    'customary'     : ('B', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'),
    'customary_ext' : ('byte', 'kilo', 'mega', 'giga', 'tera', 'peta', 'exa',
                       'zetta', 'iotta'),
    'iec'           : ('Bi', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi', 'Yi'),
    'iec_ext'       : ('byte', 'kibi', 'mebi', 'gibi', 'tebi', 'pebi', 'exbi',
                       'zebi', 'yobi'),
}

def bytes2human(n, format='%(value).1f %(symbol)s', symbols='customary'):
    """
    Convert n bytes into a human readable string based on format.
    symbols can be either "customary", "customary_ext", "iec" or "iec_ext",
    see: http://goo.gl/kTQMs

      >>> bytes2human(0)
      '0.0 B'
      >>> bytes2human(0.9)
      '0.0 B'
      >>> bytes2human(1)
      '1.0 B'
      >>> bytes2human(1.9)
      '1.0 B'
      >>> bytes2human(1024)
      '1.0 K'
      >>> bytes2human(1048576)
      '1.0 M'
      >>> bytes2human(1099511627776127398123789121)
      '909.5 Y'

      >>> bytes2human(9856, symbols="customary")
      '9.6 K'
      >>> bytes2human(9856, symbols="customary_ext")
      '9.6 kilo'
      >>> bytes2human(9856, symbols="iec")
      '9.6 Ki'
      >>> bytes2human(9856, symbols="iec_ext")
      '9.6 kibi'

      >>> bytes2human(10000, "%(value).1f %(symbol)s/sec")
      '9.8 K/sec'

      >>> # precision can be adjusted by playing with %f operator
      >>> bytes2human(10000, format="%(value).5f %(symbol)s")
      '9.76562 K'
    """
    n = int(n)
    if n < 0:
        raise ValueError("n < 0")
    symbols = SYMBOLS[symbols]
    prefix = {}
    for i, s in enumerate(symbols[1:]):
        prefix[s] = 1 << (i+1)*10
    for symbol in reversed(symbols[1:]):
        if n >= prefix[symbol]:
            value = float(n) / prefix[symbol]
            return format % locals()
    return format % dict(symbol=symbols[0], value=n)

def human2bytes(s):
    """
    Attempts to guess the string format based on default symbols
    set and return the corresponding bytes as an integer.
    When unable to recognize the format ValueError is raised.

      >>> human2bytes('0 B')
      0
      >>> human2bytes('1 K')
      1024
      >>> human2bytes('1 M')
      1048576
      >>> human2bytes('1 Gi')
      1073741824
      >>> human2bytes('1 tera')
      1099511627776

      >>> human2bytes('0.5kilo')
      512
      >>> human2bytes('0.1  byte')
      0
      >>> human2bytes('1 k')  # k is an alias for K
      1024
      >>> human2bytes('12 foo')
      Traceback (most recent call last):
          ...
      ValueError: can't interpret '12 foo'
    """
    init = s
    num = ""
    while s and s[0:1].isdigit() or s[0:1] == '.':
        num += s[0]
        s = s[1:]
    num = float(num)
    letter = s.strip()
    for name, sset in SYMBOLS.items():
        if letter in sset:
            break
    else:
        if letter == 'k':
            # treat 'k' as an alias for 'K' as per: http://goo.gl/kTQMs
            sset = SYMBOLS['customary']
            letter = letter.upper()
        else:
            raise ValueError("can't interpret %r" % init)
    prefix = {sset[0]:1}
    for i, s in enumerate(sset[1:]):
        prefix[s] = 1 << (i+1)*10
    return int(num * prefix[letter])

if __name__ == "__main__":
    import doctest
    doctest.testmod()
## end of http://code.activestate.com/recipes/578019/ }}}

rawDescription: bytes to human readable, and back. without data loss

description: Bytes to human readable, and back. without data loss


code:
from django.views.decorators.http import condition

@condition(etag_func=None)
def stream_response(request):
    resp = HttpResponse( stream_response_generator(), mimetype='text/html')
    return resp

def stream_response_generator():
    yield "\n"
    for x in range(1,11):
        yield "
%s
\n" % x
        yield " " * 1024  # Encourage browser to render incrementally
        time.sleep(1)
    yield "\n"

rawDescription: How to stream an HttpResponse with Django

description: Stream an HttpResponse with Django


code:
rects = [] # contains rects

def callback(event):
    for rect in rects:
        if rect.a <= event.x <= rect.c:
            if rect.b <= event.y <= rect.d:
                rect.change()

window.bind('<ButtonPress-1>', callback)

rawDescription: Can you add a callback / command on a shape in tkinter

description: Add a callback / command on a shape in tkinter


rawDescription: Convert cStringIO variable into file

description: Convert cStringIO variable into file


code:
ascii = '!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
mapped = '\'-!"#$%&()*,./:;?@[\\]^_`{|}~+<=>0123456789aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ'
trans = str.maketrans(mapped, ascii)
print("".join(sorted(ascii, key=lambda s: s.translate(trans)))) # prints mapped

rawDescription: Unknown character ordering

description: Unknown character ordering


code:
with open("inFile") as f, open("outFile", "w") as g:
    json.dump(json.load(f), g, indent=4)

rawDescription: Read JSON file and Pretty-Print it to another file


code:
s2 = s.copy()
s2.index = pd.Timestamp(datetime.date.today()) + pd.TimedeltaIndex(s.index, unit='s')
s2

rawDescription: Converting a generic float64 index to Timestamp in Pandas


code:
def hello(event):
    print("hello")
    return "break"
...
notes.bind("<Button-1>", hello)

rawDescription: Detect click on border of widget in tkinter 3


code:
def resize(self,n):
        while self.size < n:
            new = self.copy()
            self.__init__(int(round(self.size, 2)) * 2)
            self.left = new

        print("size in resize",self.size)

def copy(self):
        new = tree(1)
        new.left = self.left
        new.right = self.right
        new.size = self.size
        new.free = self.free
        return new

rawDescription: References in python classes on self

description: References in python classes on self


code:
def map_dict_to_bq_schema(source_dict, schema, dest_dict):
    #iterate every field from current schema
    for field in schema['fields']:
        #only work in existant values
        if field['name'] in source_dict:
            #nested field
            if field['type'].lower()=='record' and 'fields' in field:
                #list
                if 'mode' in field and field['mode'].lower()=='repeated':
                    dest_dict[field['name']] = []
                    for item in source_dict[field['name']]:
                        new_item = {}
                        map_dict_to_bq_schema( item, field, new_item )
                        dest_dict[field['name']].append(new_item)
                #record
                else:
                    dest_dict[field['name']] = {}
                    map_dict_to_bq_schema( source_dict[field['name']], field, dest_dict[field['name']] )
            #list
            elif 'mode' in field and field['mode'].lower()=='repeated':
                dest_dict[field['name']] = []
                for item in source_dict[field['name']]:
                    dest_dict[field['name']].append(item)
            #plain field
            else:
                dest_dict[field['name']]=source_dict[field['name']]

                format_value_bq(source_dict[field['name']], field['type'])

new_dict = {}
map_dict_to_bq_schema (my_dict, schema, new_dict)

rawDescription: How to map a Python Dict to a Big Query Schema

description: Map a Python Dict to a Big Query Schema


code:
from test_mod1 import Test as Test1
from test_mod2 import Test as Test2

rawDescription: Aggregating multiple test cases from multiple modules to run in PyDev TestRunner


code:
class Brick(object): pass

class StrongBrick(Brick): pass

class House(object):
    def __init__(self, brick_factory, num_bricks):
        self.bricks = [brick_factory() for i in range(num_bricks)]

house = House(Brick, 10000)
strong_house = House(StrongBrick, 10000)

rawDescription: Replacing member objects with subclasses in Python


code:
with open("font.txt") as fi:
    lines = fi.readlines()

for character in tx:
    var1 = int(cd[character])
    ra1 = (var1 * int(hi))
    ra1n = (ra1 + int(hi))
    print(''.join(lines[ra1:ra1n]), end='')

rawDescription: Loop exits unexpectedly Python

description: Loop exits unexpectedly Python


code: print("{Name},{FirstName},{LastName}".decode().format(**player)) # gets values of keys specified in format args from player

rawDescription: Remove spaces between items returned in a list


code:
legal_ids = '^ltd|ltd$|^gmbh|gmbh$|^gesmbh|gesmbh$'

def foo(name, legal_ids):
    #initialize re (company id at beginning or end of string)
    re_code = re.compile(legal_ids)
    #remove spaces from name
    name_stream = name.replace(' ','')
    #search for matches
    comp_id_re = re_code.search(name_stream)
    if comp_id_re:
        #match was found, extract the matching company id
        company_id = comp_id_re.group()
        #remove the id from the string without spaces
        name_stream = re.sub(re_code, '', name_stream).strip()
        if comp_id_re.start()>0:
            #the legal id was NOT at the beginning of the string, proceed normally
            name_stream_it = iter(name_stream)
            final_name = ''.join(next(name_stream_it) if e != ' ' else ' ' for e in name)
        else:
            #the legal id was at the beginning of the string, so do the same as above, but with the reversed strings
            name_stream_it = iter(name_stream[::-1])
            final_name = ''.join(next(name_stream_it) if e != ' ' else ' ' for e in name[::-1])
            #reverse the string to get it back to normal
            final_name = final_name[::-1]
    else:
        company_id = ''
        final_name = name
    return (final_name.strip(), company_id)

rawDescription: Regex match when spaces are removed, how to delete the matched chars from the original string with spaces?


code:
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shell.SendKeys("^a") # CTRL+A may "select all" depending on which window's focused
shell.SendKeys("{DELETE}") # Delete selected text?  Depends on context. :P
shell.SendKeys("{TAB}") #Press tab... to change focus or whatever

rawDescription: Which is the easiest way to simulate keyboard and mouse on Python?


code:
import random

#turns string to list
list=[]
#gets the sentence to count and what to count and deletes punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
sentence=input("Enter sentence to count: ")
sentence=sentence.lower()

no_punct = ""
for char in sentence:
   if char not in punctuations:
      no_punct = no_punct + char

list=no_punct.split()

#this shows whether it is there or not
index=[index+1 for index,list in enumerate(list)]
print("the indices are ",index)

print(index)
random.shuffle(index)
print(index)

rawDescription: how do I shuffle the index of a variable list?

description: Shuffle the index of a variable list


rawDescription: dump files from bash script in different directory from where python script ran it

description: Dump files from bash script in different directory from where python script ran it


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

def draw_rect(x, y, z):
    rect = patches.Rectangle((x,y), 1, 1, color = jet(z))
    ax.add_patch(rect)

jet = plt.get_cmap('jet')
fig = plt.figure()
ax = fig.add_subplot(111)

darray = np.array([[2, 3, 7, 7],
                   [4, 8, 2, 3],
                   [6, 1, 9, 5],
                   [3, 4, 8, 4]], dtype = 'float')
darray_norm = darray/darray.max()

posarray = [3.767, 1.85, 0.762]
x = np.cumsum(np.hstack((0, np.array(posarray)+1)))

for j, i in np.ndindex(darray.shape):
    draw_rect(x[j], i, darray_norm[i, j])
ax.set_xlim(x.min(),x.max()+1)
ax.set_ylim(0,len(darray))
ax.invert_yaxis()
m = cm.ScalarMappable(cmap = jet)
m.set_array(darray)
plt.colorbar(m)
plt.show()

rawDescription: Broadcasting columns from a 2D numpy array to a larger 2D array based on an array of floats


code:
import urllib2
f = urllib2.urlopen('http://www.python.org/')
f.headers['content-type']

rawDescription: How do I get the content-type from return of urlopen(url) in python2.x?

description: Get the content-type from return of urlopen(url) in python2.x


code:
with open('testfilefolder/wssnt10.txt') as f:
 file_contents = f.read().lower().split(' ') # split line on spaces to make a list
 filtered = fnmatch.filter(file_contents, 'th*')

rawDescription: Python: Regex a dictionary using user input wildcards


code:
qs = MyModel.objects.filter(title__icontains=query)
qs.sort(key=lambda x: mydict[x])

rawDescription: How to sort model by values in a dictionary?

description: Sort model by values in a dictionary


code:
class App:
    generating = False
    def __init__(self, master):
        self.master=master

        #Initializing frames
        self.buttonFrame = Frame(master, background='light gray')
        self.loadingFrame = Frame(master, background='light gray')
        self.loadingFrame.grid(row=0)
        self.buttonFrame.grid(row=1)
        self.anim = Gif(self.loadingFrame, '4Y9UJ.gif')
        self.anim.pack()
##        self.update_Thread = threading.Thread(target=time.sleep, args=(5,))

        self.buttonSetup()

    def buttonSetup(self):
        #ALL THE BUTTONS
        self.generateBt = Button(self.buttonFrame, text="Generate!", command=self.generate, background='light gray', highlightbackground='light gray')
        self.generateBt.pack(side=LEFT)
        self.quitBt = Button(self.buttonFrame, text="Quit!", fg="red", command=self.buttonFrame.quit, background='light gray', highlightbackground='light gray')
        self.quitBt.pack(side=LEFT)

    def wait_generate(self):
        if self.update_Thread.isAlive():
            self.master.after(500, self.wait_generate)
        else:
            tkMessageBox.showinfo("Complete", "Report generation completed!")
            self.reset()

    def generate(self):
        self.hideForGen()
        self.update_Thread = threading.Thread(target=time.sleep, args=(5,))
        self.update_Thread.start()
##        while(self.update_Thread.isAlive()):
##            self.master.update_idletasks()
##        self.reset()
##        self.master.update_idletasks()
##        tkMessageBox.showinfo("Complete", "Report generation completed!")
        self.wait_generate()

    def hideForGen(self):
        self.buttonFrame.grid_forget()

    def reset(self):
        self.buttonFrame.grid(row=1)

rawDescription: Python: Have gifs animate with TKinter while a thread is running


rawDescription: Python / Remove special character from string


code:
import re
s = "sample_sample_sample_2.18.14"
re.sub(r'[^a-zA-Z0-9]', '', s)

rawDescription: remove special character in scrapy python

description: Remove special character in scrapy python


code:
# Pages Settings
PAGE_URL = "{slug}/"
PAGE_SAVE_AS = "{slug}/index.html"

# Articles Settings
ARTICLE_URL = "blog/{slug}/"
ARTICLE_SAVE_AS = "blog/{slug}/index.html"

rawDescription: Pelican, articles and pages lead to 404 status code


code:
SpeedList = ["25","30"]
NameList = ["John Smith","Tom Smith"]
for name, speed in zip(NameList, SpeedList):
    print (name)," Was driving at ",(speed), " mph."

rawDescription: Printing two lists on one line

description: Printing two lists on one line


code:
class LogicPerformer:
    def performLogic(self):
        # No call to super; the buck stops here, because object
        # doesn't have this method
        print("In LogicPerformer")

class InheritedClass1(LogicPerformer):

    def performLogic(self):
        print("In InheritedClass1")
        super().performLogic()

class InheritedClass2(LogicPerformer):

    def performLogic(self):
        print("In InheritedClass1")
        super().performLogic()

class SomeClass(InheritedClass1, InheritedClass2):

    def performLogic(self):
        print("In SomeClass")
        super().performLogic()

a = SomeClass()
print(SomeClass.__mro__)
a.performLogic()

rawDescription: Python super() with multiple inheritance


code:
#Calculate new x,y positions of extents
tx = osr.CoordinateTransformation(obs_proj,mod_proj)
  #Projection corrected extent of area in question
corr_ext = [0,0,0,0]  #[min,max,ymin,ymax]
(corr_ext[0],corr_ext[2],ignore_z) = tx.TransformPoint(ext[0],ext[2]) #Ignore z componenet - data is 2D
(corr_ext[1],corr_ext[3],ignore_z) = tx.TransformPoint(ext[1],ext[3])

rawDescription: How to reproject and area match a netCDF and shapefile

description: Reproject and area match a netCDF and shapefile


code:
source = cv2.imread() # source is numpy array
bitmap = cv.CreateImageHeader((source.shape[1], source.shape[0]), cv.IPL_DEPTH_8U, 3)
cv.SetData(bitmap, source.tostring(),
           source.dtype.itemsize * 3 * source.shape[1])

rawDescription: OpenCV: Converting from NumPy to IplImage in Python


code:
line = lowerBound
while line < lineNumber:
    ...
    if conditions:
        ...
        for lineIDX in range(line, line+6):
           ...
        line = line + 6
    else:
        line = line + 1

rawDescription: Update iteration value in Python for loop


code:
import datetime

X = 65
result = datetime.datetime.now() - datetime.timedelta(seconds=X)

rawDescription: Subtract seconds from datetime in python


code:
import shutil, errno

def copyanything(src, dst):
    try:
        shutil.copytree(src, dst)
    except OSError as exc: # python >2.5
        if exc.errno == errno.ENOTDIR:
            shutil.copy(src, dst)
        else: raise

rawDescription: Copy file or directory in Python

description: Copy file or directory in Python


code:
subprocess.call(["find_info", image, json_file],
                env=dict(TEST__LIB_PATH="/path/requried/for/test",
                         **os.environ))

rawDescription: Importing creating an environment variable in Python?


code: EntryResult = dataentry.py.Ui_DataEntry() #considering that the UI class in dataentry.py is Ui_DataEntry

rawDescription: How to wait for execution in other window in python

description: Wait for execution in other window in python


code:
from datetime import datetime
d = datetime.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
day_string = d.strftime('%Y-%m-%d')

rawDescription: Convert a string with date and time to a date


code:
class Proposal(models.Model):
    scheduled_time = models.DateTimeField()
    duration = IntegerField()
    end = models.DateTimeField(default=self.scheduled_time + timedelta(minutes=self.duration))

rawDescription: Sum of F() expression and timedelta created from F() expression


code:
import random
r = random.random()
x = [1, 2, 3, 4, 5, 6]
random.shuffle(x, lambda: r)
x
x = [1, 2, 3, 4, 5, 6]
random.shuffle(x, lambda: r)
x

rawDescription: python shuffling with a parameter to get the same result

description: Python shuffling with a parameter to get the same result


code:
for line in fileOutput:
    var1, var2, var3, var4, var5, var6, var7 = line.rstrip().split(' ')

rawDescription: Is there a way in python to assign variables values from a line that's read in


code:
brokenlist = sorted(range(1, 44), key=str)
brokenmap = [x[0] for x in sorted(enumerate(sorted(range(1, 44), key=str)), key=lambda x: x[1])]
fixedlist = [brokenlist[x] for x in brokenmap]

rawDescription: Reordering python list based on an algorithm or pattern


code:
from django.apps import apps

myapp = apps.get_app_config('myapp')
for model in myapp.get_models():
    admin.site.register(model)

rawDescription: Add all models to admin site django 1.9

description: Add all models to admin site django 1.9


code:
import sys

from PySide import QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super().__init__()

        self.resize(720, 480)
        central_widget = QtGui.QWidget(self)
        self.setCentralWidget(central_widget)

        layout = QtGui.QHBoxLayout(central_widget)

        self.text_edit = QtGui.QTextEdit(central_widget)
        layout.addWidget(self.text_edit)

        self.drop_list = QtGui.QListWidget(central_widget)
        self.drop_list.setSelectionMode(QtGui.QAbstractItemView.MultiSelection)
        self.drop_list.addItems(['one', 'two', 'three', 'four'])
        self.drop_list.itemSelectionChanged.connect(self.show_List)
        layout.addWidget(self.drop_list)

        statusbar = QtGui.QStatusBar(self)
        self.setStatusBar(statusbar)

        action_ShowList = QtGui.QAction(self)
        action_ShowList.triggered.connect(self.show_List)

        self.show()

    def show_List(self):
        self.text_edit.setText(repr(self.drop_list.selectedItems()))

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    frame = MainWindow()
    sys.exit(app.exec_())

rawDescription: How to get currently selected item from QListWidget and not what it remembers

description: Get currently selected item from QListWidget and not what it remembers


code:
from dateutil import parser
parse_time = lambda s: parser.parse(s, ignoretz = True)

func_map = """
function() {
    if (this.hasOwnProperty("time"))
        emit(this.time.getUTCFullYear() + "/" + (this.time.getUTCMonth() + 1) + "/" + this.time.getUTCDate(),
        {
            count: 1,
            not_deleted: (1 - this.deleted)
        });
}
"""

func_reduce = """
function(key, values) {
    var result = {count: 0, not_deleted: 0};

    values.forEach(function(value) {
        result.count += value.count;
        result.not_deleted += value.not_deleted;
    });

    return result;
}
"""

with my_mongo() as m:
    result = m.data.inline_map_reduce(func_map, func_reduce)
    dataset = {parse_time(day['_id']): day['value']['not_deleted'] for day in result}
    dataset2 = {parse_time(day['_id']): day['value']['count'] for day in result}

rawDescription: Mongodb data statistics visualization using matplotlib


rawDescription: sqlalchemy create a foreign key?

description: Sqlalchemy create a foreign key


code:
try:
  setup(..., ext_modules=...)
except SystemExit: ...

rawDescription: How to create Python module distribution to gracefully fall-back to pure Python code

description: Create Python module distribution to gracefully fall-back to pure Python code


code: re.split('(\W)', 'foo/bar spam\neggs')

rawDescription: In Python, how do I split a string and keep the separators?


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

data = np.random.random([10,10]) * 40

hot2 = pl.cm.get_cmap('hot', 20)

pl.figure()
pl.subplot(121)
pl.pcolormesh(data, cmap=pl.cm.hot, vmin=0, vmax=20)
pl.colorbar()
pl.subplot(122)
pl.pcolormesh(data, cmap=hot2, vmin=0, vmax=20)
pl.colorbar()

rawDescription: Matplotlib discretize colorbar between given values


code:
setup(name=project_name,
    packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
    include_package_data=True,
    zip_safe=False,
    entry_points="""
    [console_scripts]
    sound-run = sound.run:start
    sound-resume = sound.run:resume
    """
    # Other setuptools stuff
    )

rawDescription: Running a python package from terminal

description: Running a python package from terminal


code:
import sys

flag = False

VERSION_NAME = r'version'

CONFIG_NAME = r'config-register'

end = ('@\n', 'monitor 6\n', 'end\n')

FILE_NAME = sys.argv[1]

# find the config-register
with open(FILE_NAME, "r") as file:
    start = CONFIG_NAME
    config_found = False

    for line in file:
        if line.startswith(start) and not config_found:
            flag = True                   # correction

        if flag:
            sys.stdout.write(line)
        if flag and line.endswith(end):
            print("Found Break")
            break                          # correction

        if line.startswith(start):
            config_found = True

# find the version
with open(FILE_NAME, "r") as file:
    start = VERSION_NAME
    config_found = False

    for line in file:
        if line.startswith(start) and not config_found:
            flag = True

        if flag:
            sys.stdout.write(line)

        if flag and line.endswith(end):
            print("Found Break")
            break

        if line.startswith(start):
            config_found = True

rawDescription: Save one part of a text file

description: Save one part of a text file


code:
WRAPPER_ASSIGNMENTS = ('__module__', '__name__', '__doc__')
WRAPPER_UPDATES = ('__dict__',)

def update_wrapper(wrapper,
                   wrapped,
                   assigned = WRAPPER_ASSIGNMENTS,
                   updated = WRAPPER_UPDATES):
    for attr in assigned:
        setattr(wrapper, attr, getattr(wrapped, attr))
    for attr in updated:
        getattr(wrapper, attr).update(getattr(wrapped, attr, {}))
    # Return the wrapper so this can be used as a decorator via partial()
    return wrapper

def wraps(wrapped,
          assigned = WRAPPER_ASSIGNMENTS,
          updated = WRAPPER_UPDATES):
    return partial(update_wrapper, wrapped=wrapped,
                   assigned=assigned, updated=updated)

rawDescription: Make a wrapper appear as the function it wraps in help()


code:
import matplotlib.pyplot as mp

mp.figure(0)
# Create first chart here.

mp.figure(1)
# Create second chart here.

mp.show() #show all figures

rawDescription: Multiple pie charts using matplotlib

description: Multiple pie charts using matplotlib


code:
x1 = np.random.uniform(size=2**17-1)
x2 = np.random.uniform(size=2**17)

np.fft.fft(x1)
np.fft.fft(x2)

rawDescription: Convolution computations in Numpy/Scipy

description: Convolution computations in Numpy/Scipy


code:
packed = np.packbits(db_bool.view(np.uint8))

unpacked = np.unpackbits(packed)[:db_bool.size].reshape(db_bool.shape).view(np.bool)

print(np.all(db_bool == unpacked))
# True

rawDescription: packing boolean array needs go throught int (numpy 1.8.2)

description: Packing boolean array needs go throught int (numpy 1.8.2)


code:
for key, data_list in data_dict.items():
    dates_str, values = zip(*data_list)  # Unpack
    dates = convert_str_to_dates(dates_str)  # Not handled in example
    plt.plot(dates, values, label=key)
plt.legend()

rawDescription: plotting all keys of a dictionary which contains list as values (python)

description: Plotting all keys of a dictionary which contains list as values (python)


code:
file = urllib.request.urlopen(i)
filename = i.split('/')[-1]
with open(filename, 'wb') as out:
    out.write(file.read())

rawDescription: read a file and download the links in that file use urllib.request in python 3

description: Read a file and download the links in that file use urllib.request in python 3


code:
data['zipcode'] = 85055
data['zipcode'] = [zipc[:3] + '00' for zipc in data['zipcode'].astype(str).values]
data['zipcode']

rawDescription: Converting data frame into str in python


code: python_datetime = datetime.fromordinal(int(matlab_datenum)) + timedelta(days=matlab_datenum%1) - timedelta(days = 366)

rawDescription: Converting Matlab's datenum format to Python


code:
vals = ["a","b","c"]
def main():
    test = input()
    if validate(test):
        print("Valid entry")
    else:
        print("did not enter valid info")
def validate(val):
    for i in vals:
        if val == i:
            return True
    return False
main()

rawDescription: Lists for validation

description: Lists for validation


code:
import numpy as np
import pylab as plt

# Create a sample matrix like your image
A = np.random.random((100,100)) * .52
A = np.rint(A)
for idx in np.ndindex(A.shape):
    if idx[0]>idx[1]: A[idx] = 0

plt.subplot(1,2,1)
plt.imshow(A,interpolation='none')

# Make a new matrix B = A + A.T - diagonal(A)
B = A + A.T - np.diag(np.diag(A))
plt.subplot(1,2,2)
plt.imshow(B,interpolation='none')
plt.tight_layout()
plt.show()

rawDescription: How do I reflect a matrix in matplotlib?

description: Reflect a matrix in matplotlib


code:
comments = re.split("(\d{4}/\d{2}/\d{2})",open("some_file.txt").read().strip())
date_comment_pairs = zip(*[iter(comments)]*2)
comments_and_users = [x[1].split("More")[0].strip() for x in date_comment_pairs]
comments_alone = ["\n".join(x.splitlines()[1:]) for x in comments_and_users]

rawDescription: Get the specific lines in unstructured text files and make them structured in Python


code:
class unpackable_dict(dict):
    def __iter__(self):
        return (self[key] for key in sorted(self.keys()))

d = unpackable_dict(a=1, b=2)
a, b = d

rawDescription: Python: overloading tuple multi-assignment capabilities?


code:
import requests
from bs4 import BeautifulSoup

body = {'username':'xxxx@hotmail.com','password':'xxxxx','submit':'Login','mod':'www','dest':'community'}
con = requests.post('https://secure.runescape.com/m=weblogin/login.ws', data=body)
s = BeautifulSoup(con.content)
print(s)

rawDescription: Python3 How would I log in Facebook using requests


code: all( word in d for word in [ 'somekey', 'someotherkey', 'somekeyggg' ] )

rawDescription: Multiple 'in' operators in Python?

description: Multiple 'in' operators in Python


code:
x = 'abc'
v = itertools.combinations_with_replacement(x, len(x))
ans = [''.join(map(str, x)) for x in v]
ans

rawDescription: Missing a sequence when using itertools combonations_with_replacement


code:
from io import StringIO

filename = 'ham.egg'
vfile = StringIO(u'[Pseudo-Sectio]\n%s'  % open(filename).read())

rawDescription: Is there a version of ConfigParser that deals with files with no section headers?


code:
null_terminated_unicode_string = data.decode('utf-16le')
unicode_string = null_terminated_unicode_string[:-1]

rawDescription: How do I figure out the format for struct.unpack (because I didn't pack in Python)?

description: Figure out the format for struct.unpack (because I didn't pack in Python)


code:
import pygtk
pygtk.require("2.0")
import gtk, gobject
class clTableTree(gtk.Table):
    def __init__(self):
        super(clTableTree, self).__init__(15,15,True)

        self.set_row_spacings(5)
        self.btnStartTest = gtk.Button("Start testing Process")
        self.attach(self.btnStartTest,6,9,13,14)

        self.btnActivate = gtk.Button("Activate")
        self.attach(self.btnActivate,12,14,3,4)

        self.btnDeactivate = gtk.Button("Deactivate")
        self.attach(self.btnDeactivate,12,14,4,5)

        self.btnDuplicateNode = gtk.Button("Duplicate Node")
        self.attach(self.btnDuplicateNode,12,14,5,6)

        self.btnDeleteNode = gtk.Button("Delete Node")
        self.attach(self.btnDeleteNode,12,14,6,7)

class clTableLog(gtk.Table):
    def __init__(self):
        super(clTableLog, self).__init__(15,15,True)

        self.set_row_spacings(5)
        self.btnSaveLogAs = gtk.Button("Save log as...")
        self.attach(self.btnSaveLogAs,6,9,13,14)
        self.btnSaveLogAs.show()

        self.btnRefresh = gtk.Button("Refresh")
        self.attach(self.btnRefresh,12,14,5,6)
        self.btnRefresh.show()

        self.btnClearALL = gtk.Button("Clear all")
        self.attach(self.btnClearALL,12,14,6,7)
        self.btnClearALL.show()

class PyApp(gtk.Window):

    def __init__(self):
        super(PyApp, self).__init__()

        self.set_title("Utilities Testing Tool")
        self.set_size_request(700, 500)
        #self.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(6400, 6400, 6440))
        self.set_position(gtk.WIN_POS_CENTER)

        mb = gtk.MenuBar()

        treem = gtk.MenuItem("Tree Window")
        treem.connect("button_press_event", self.open_tree_widget)
        logm = gtk.MenuItem("Log Window")
        logm.connect("button_press_event", self.open_log_widget)
        exit = gtk.MenuItem("Exit")
        exit.connect("button_press_event", gtk.main_quit)
        mb.append(treem)
        mb.append(logm)
        mb.append(exit)

        self.vbox = gtk.VBox(False, 2)
        self.vbox.pack_start(mb, False, False, 0)

        self.tableTreeWindow = self.create_table_tree()
        self.tableLogWindow = self.create_table_log()
        self.tableLogWindow.show()

        self.vbox.pack_start(self.tableTreeWindow)
        self.add(self.vbox)
        self.connect("destroy", gtk.main_quit)
        self.show_all()

    def create_table_tree(self):
        return clTableTree()

    def create_table_log(self):
        return clTableLog()

    def open_tree_widget(self, arg0, arg1):
        self.replace_widget(self.tableLogWindow, self.tableTreeWindow)

    def open_log_widget(self,  arg0, arg1):
        self.replace_widget(self.tableTreeWindow, self.tableLogWindow)

    def replace_widget(self, current, new):

        container = current.parent
        assert container # is "current" inside a container widget?

        props = {}
        for pspec in gtk.container_class_list_child_properties(container):
            props[pspec.name] = container.child_get_property(current, pspec.name)

        gtk.Container.remove(container, current)
        container.add(new)

        for name, value in props.items():
            container.child_set_property(new, name, value)

PyApp()
gtk.main()

rawDescription: Python GTK - switch between widgets - embed a tree in widget or window


code:
class HomePageTest(unittest.TestCase):
    def __init__(self):
        self.driver = webdriver.Firefox()
        self.driver.implicitly_wait(30)
        self.base_url = "https://somewebsite.com"
        self.verificationErrors = []

    ...

    def tearDown(self):
        self.driver.quit()

rawDescription: python selenium multiple test cases

description: Python selenium multiple test cases


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

# Generate some data...
# Note that all of these are _2D_ arrays, so that we can use meshgrid
# You'll need to "grid" your data to use pcolormesh if it's un-ordered points
theta, r = np.mgrid[0:2*np.pi:20j, 0:1:10j]
z = np.random.random(theta.size).reshape(theta.shape)

fig, (ax1, ax2) = plt.subplots(ncols=2, subplot_kw=dict(projection='polar'))

ax1.scatter(theta.flatten(), r.flatten(), c=z.flatten())
ax1.set_title('Scattered Points')

ax2.pcolormesh(theta, r, z)
ax2.set_title('Cells')

for ax in [ax1, ax2]:
    ax.set_ylim([0, 1])
    ax.set_yticklabels([])

plt.show()

rawDescription: Shade 'cells' in polar plot with matplotlib


code:
from django.db.models.signals import pre_save
from django.dispatch import receiver
from django.template.defaultfilters import slugify

@receiver(pre_save)
def my_callback(sender, instance, *args, **kwargs):
    instance.slug = slugify(instance.title)

rawDescription: Populating django field with pre_save()?

description: Populating django field with pre_save()


code:
cbar = fig.colorbar(cax, ticks=[-1, 0, 1])
cbar.ax.set_xticklabels(['Low', 'Medium', 'High'])

rawDescription: Matplotlib Colorbar Display Digtis

description: Matplotlib Colorbar Display Digtis


rawDescription: retrieving current drive letters in windows (from python)

description: Retrieving current drive letters in windows (from python)


rawDescription: How do I save .py files in IPython notebook with the .ipynb files

description: Save .py files in IPython notebook with the .ipynb files


code:
with open('r.0', 'r') as IRR, open('tt', 'w') as fd_w:
    lines = []
    for line in IRR:
        line = line.strip()
        if line:
            lines.append(line)
        else:
            # empty line, found a complete block, test for status line
            if 'status:         ASSIGNED PA' in lines:
                for line in lines:
                    fd_w.write(line + '\n')
            lines = []

rawDescription: Writing lines from a file

description: Writing lines from a file


code: counter = cls(key_name=name)

rawDescription: Why would a model instance not be found when committing count using write-behind or sharded counters in App Engine?


rawDescription: Adding a single label to the legend for a series of different data points plotted inside a designated bin in Python using matplotlib.pyplot.plot()


code: staffButton = Button(..., command=lambda btn=i:self.openTabHere(isLeft,btn))

rawDescription: How can I get TK button commands to take in a parameter with a variable (Python)

description: Get TK button commands to take in a parameter with a variable (Python)


code:
# setup.py
from distutils.core import setup
from distutils.extension import Extension
setup(name="getting_started1",
    ext_modules=[
        Extension("getting_started1", ["getting_started1.cpp"],
        include_dirs=['boost_1_48_0'],
        libraries = ['boost_python-vc90-mt-1_48'],
        extra_compile_args=['/EHsc', '/FD', '/DBOOST_ALL_DYN_LINK=1']
        )
    ])

rawDescription: Importing python boost module

description: Importing python boost module


code:
def repair(file,fsplit):
    parser = configparser.ConfigParser()
    parser.optionxform = str
    with open(file) as f:
        parser.read_file(f)
    ...

rawDescription: Python: configparser remembers values from previous files


code:
#-*- coding: UTF-8 -*-
from gi.repository import Gtk

class App(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title='ComboBoxEntry Test')

        model = Gtk.ListStore(str, str)
        for i in [['One', '1'], ['Two', '2'], ['Three', '3'], ['Four', '4']]:
            model.append(i)

        combo = Gtk.ComboBoxText.new_with_entry()
        combo.set_model(model)

        #combo.set_active(0)
        combo.get_child().set_text('Five')

        self.add(combo)

win = App()
win.connect('delete-event', Gtk.main_quit)
win.show_all()
Gtk.main()

rawDescription: PyGObject: Setting ComboBoxText's Active Text


rawDescription: Python3 — replacing a dynamically chosen namedtuple field


rawDescription: Index into a string in a list

description: Index into a string in a list


code:
class MyDict(collections.MutableMapping):
    def __init__(self):
        self.d = {}
        # other initializations ...

    def __setitem__(self, key, value):
        self.d[key] = value
        self.modified = true
    ...

rawDescription: How to detect dict modification?

description: Detect dict modification


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

import sys
from PyQt4.QtCore import QObject, SIGNAL
from PyQt4.QtGui import QApplication, QTextEdit, QTextDocument

app = QApplication(sys.argv)

def findText():
    flag = QTextDocument.FindBackward
    print(textEdit.toPlainText(), textEdit.find('A', flag))

textEdit = QTextEdit()
textEdit.show()
QObject.connect(textEdit, SIGNAL('textChanged()'), findText)
sys.exit(app.exec_())

rawDescription: QTextEdit.find() doesn't work in Python

description: QTextEdit.find() doesn't work in Python


code:
import uno
import socket  # only needed on win32-OOo3.0.0

# get the uno component context from the PyUNO runtime
localContext = uno.getComponentContext()

# create the UnoUrlResolver
resolver = localContext.ServiceManager.createInstanceWithContext(
                       "com.sun.star.bridge.UnoUrlResolver", localContext )

# connect to the running office
ctx = resolver.resolve( "uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext" )
smgr = ctx.ServiceManager
# get the central desktop object
desktop = smgr.createInstanceWithContext( "com.sun.star.frame.Desktop",ctx)

# access the current writer document
model = desktop.getCurrentComponent()

try:
    sheets = model.getSheets()
except Exception:
    raise TypeError("Model retrived was not a spreadsheet")

sheet1 = getattr(sheets, sheets.ElementNames[0])

# At this point, you can use "dir" to check the methods and
# attributes available for the sheet
# the methots "getCellByPosition, to retrieve a cell object,
# which has "getFormula" and "setFormula"
# methods.

for i in xrange(10):
    for j in xrange(10):
        cell = sheet1.getCellByPosition(i, j)
        cell.setFormula(str(i * j))

c1 = sheet1.getCellByPosition(1,1)

rawDescription: Writing/Reading arrays of Data in Open Office using Python. Anyone have any example code?


code:
import os

def print_directory_listing(directory = '.'):
    files_list=[]

    for file_structure in os.listdir(directory):
        file_structure_path = os.path.join(directory, file_structure)
        if os.path.isdir(file_structure_path):
            files_list+=print_directory_listing(file_structure_path)
        else:
            files_list.append(file_structure_path)

    return files_list

rawDescription: how to make a recursive function that builds a list

description: Make a recursive function that builds a list


code:
def iscrizione():
    form = model_form(User, only=['email', 'nickname', 'password', 'categoria'])(request.form)
    form.categoria.label_attr='descrizione'  #<< add this line
    if request.method == 'GET':
        ctx = {
        'form': form
    }
    return render_template('users/iscrizione.html', **ctx)

rawDescription: Mongoengine, Flask and ReferenceField in WTForms


code:
for name in soup.find_all("td", class_="sortcell"):
    salary = name.parent.find_all('td')[-1]  # last cell in the row
    print(name.get_text())
    print(salary.get_text())

rawDescription: Grabbing a certain <td> class with BeautifulSoup


code:
point1 = random_x + (radius * math.cos(random_pi))
point2 = random_y + (radius * math.cos(random_pi))

rawDescription: Triangle with points on perimeter of circle, python


code:
import subprocess

p = subprocess.Popen(["tee", "out"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.communicate("abc")  # This will end up in the process's stdin.

rawDescription: Using python to pipe data to input of a currently running process


code:
import time
import sys
blah = "This is written slowly\n"
for l in blah:
  sys.stdout.write(l)
  sys.stdout.flush()
  time.sleep(0.2)

rawDescription: Printing a string with a little delay between the chars


code: ['.'.join(str(octet) for octet in addr['ip']) for addr in hosts]

rawDescription: Python List comprehension one declaration and 2 Comprehensions


code:
#!/usr/bin/python
import matplotlib.pyplot as plt
from matplotlib import rc

rc('text', usetex=True)
rc('font', family='serif')

r = 1
v = 2
i = 3

plt.plot([1,2,3],[2,3,4],'ro-')

plt.text(2,2,r"\begin{eqnarray*}R_L&= 0\\ V_2&= 1\\ I_2&= 2\end{eqnarray*}")

#notes = r"\noindent$$R_L = {0}\\ V_2 = {1}\\ I_2 = {2}$$".format(r, v, i)
#plt.annotate(notes, xy=(5,5), xytext=(7,7))
plt.show()

rawDescription: Align TeX equations in matplotlib

description: Align TeX equations in matplotlib


code:
from django import forms

class DateInput(forms.DateInput):
    input_type = 'date'

class MyModelForm(ModelForm):
    class Meta:
        model = MyModel
        fields = '__all__'
        widgets = {
            'my_date': DateInput()
        }

rawDescription: Django form.as_p DateField not showing input type as date


code:
import sys
sys.setrecursionlimit(9000)

rawDescription: Modifying the recursion depth allocated in python


code:
from BeautifulSoup import BeautifulSoup, Tag

soup = BeautifulSoup(html)
images = []
image = {}

img_list = soup.findAll('meta', {"property":'og:image'})
for og_image in img_list:
    if not og_image.get('content'):
        continue

    image = {'url': og_image['content']}
    next = og_image.nextSibling.nextSibling # calling once returns end of line char '\n'

    if next and isinstance(next, Tag) and next.get('property', '').startswith('og:image:'):
        dimension = next['content']
        prop = next.get('property').rsplit(':')[-1]
        image[prop] = dimension

        next = next.nextSibling.nextSibling
        if next and isinstance(next, Tag) and next.get('property', '').startswith('og:image:'):
            dimension = next['content']
            prop = next.get('property').rsplit(':')[-1]
            image[prop] = dimension

    images.append(image)

rawDescription: How to parse array of HTML tags with python beautifulsoup

description: Parse array of HTML tags with python beautifulsoup


code:
import re
my_string='SYS           W$_FIasdfLESTATXS               TABLE PARTITION           0    '
re.sub(r'([^ ]) ([^ ])',r'\1_\2',my_string)

rawDescription: replace single space but not multiple space python

description: Replace single space but not multiple space python


rawDescription: Sorting an array based on another array

description: Sorting an array based on another array


code:
def get_spans(angle):
    spans = Spans.objects.values_list('span', flat=True).filter(
        max_roof_angle=angle,
    )
    max_span = max(spans)
    return max_span

rawDescription: Django/ Python - max() of list returns a tuple


code:
import hashlib
fn = lambda xs: hashlib.sha1(xs).hexdigest()
m = np.apply_along_axis(fn, 1, M)
l = np.apply_along_axis(fn, 1, L[:,:-1])
L[np.in1d(l, m)]

rawDescription: Indices in a numpy array where slice in another array


code:
def insert(bst,key):
    if bst == []:
        bst[:] = tree_node(key)
    elif key < bst[0]:
        insert(bst[1],key)
    else:
        insert(bst[2],key)

rawDescription: Insertion into Binary Search Tree

description: Insertion into Binary Search Tree


code:
buf = create_string_buffer("\x22\x0F\x61", 64)
ldv_read = windll.wldv32.ldv_read
ldv_read.restype = c_int
ldv_read.argtypes = [c_int,c_void_p,c_uint]
res = ldv_read( handle, buf, len(buf) )
print(buf.raw)

rawDescription: C char array to Python List

description: C char array to Python List


rawDescription: Python fill list up to certain number

description: Python fill list up to certain number


code:
a = raw_input('Type anything.\n')
foo = [a]
b = raw_input('Another questions? Y/N\n')

while b != 'N':
    b = raw_input('Type and to continue, N for stop\n')
    if b == 'N': break
    foo.append(b)

rawDescription: while with raw_input creating an infinite loop

description: While with raw_input creating an infinite loop


code:
from tempfile import SpooledTemporaryFile

class CustomSpooled(SpooledTemporaryFile):

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

        # This dict will be passed on to the NamedTempFile constructor one we
        # roll over our file. We are adding the delete=False argument.
        self._TemporaryFileArgs = {'mode': mode, 'buffering': buffering,
                                   'suffix': suffix, 'prefix': prefix,
                                   'encoding': encoding, 'newline': newline,
                                   'dir': dir, 'delete': False}

    def rollover(self):
        # This is overidden to get that NamedTemperoraryFile
        # Everythng else is just the same
        if self._rolled: return
        file = self._file
        newfile = self._file = NamedTemporaryFile(**self._TemporaryFileArgs)
        del self._TemporaryFileArgs

        newfile.write(file.getvalue())
        newfile.seek(file.tell(), 0)

        self._rolled = True

rawDescription: Avoiding deletion of SpooledTemporaryFile


code:
import subprocess
import shlex
process = subprocess.Popen(
    shlex.split("""x-terminal-emulator -e 'bash -c "test.py"'"""), stdout=subprocess.PIPE)
process.wait()
print (process.returncode)

rawDescription: launch program in new shell window from python

description: Launch program in new shell window from python


code:
index_list = [set() for i in range(4)]
index_list[0].update({1,2,3,4,5})
index_list[1].update({3,4,5,6,7})
index_list[2].update({4,5,6,7})

shortest_list = index_list[2]

print(shortest_list.intersection(*index_list[:2]))
set([4, 5])

rawDescription: Python: check if item exists in variable amount of lists


rawDescription: Neutral numpy array index

description: Neutral numpy array index


code: LOG.info('attr=%s, content=%s', dir(context), context.__dict__)

rawDescription: Printing the class object in python

description: Printing the class object in python


code:
matrix = [[1,2,3],[4,5,6],[7,8,9]]
# make matrix2 a (shallow) copy of matrix
matrix2 = matrix[:]
matrix2.remove(matrix[0])
print(matrix2)

rawDescription: Remove row from matrix in python

description: Remove row from matrix in python


code:
kill_list = []
try:
    while True:
        kill_list.append(1)
except MemoryError:
    pass

rawDescription: Memory intensive Python program

description: Memory intensive Python program


code:
class FlowQuerySets(models.QuerySet):
    def top_ip_in(self, with_filter=False):
        queryset = self.values('ip_dst', 'ip_proto')
        if with_filter:
            queryset = queryset.filter(stamp_updated__lt=half_hour)
        queryset = queryset.annotate(traffic=Sum('bytes')).order_by('-traffic')[:10]
        return queryset

rawDescription: Django Change queryset with a function

description: Django Change queryset with a function


rawDescription: Python selecting elements in a list by indices


code:
import itertools as IT
if __name__ == "__main__":
    data = records(100)
    with Pool(2) as pool:
        chunksize = ...
        for chunk in iter(lambda: list(IT.islice(data, chunksize)), []):
            writer(pool.imap_unordered(process, chunk, chunksize=5))

rawDescription: multiprocessing.Pool.imap_unordered with fixed queue size or buffer?

description: Multiprocessing.Pool.imap_unordered with fixed queue size or buffer


code: id, fname, lname, email, pswd, whatever = result

rawDescription: MySQLdb Results

description: MySQLdb Results


code:
root=Tk()

imgw = BitmapImage(file='Question.xbm')            # no 'root' parameter
imgLabel = Label(root,image=imgw)                  # wrap the BitmapImage
imgLabel.grid(rowspan=2,padx=5,pady=5,sticky=NSEW) # layout the label

msgw=Label(root,text="Question")
msgw.grid(column=1,padx=10,pady=5,sticky=NSEW,columnspan=2)
button1=Button(root,text='Yes')
button1.grid(column=1,row=1,padx=5,pady=5,sticky=NSEW)
button2=Button(root,text='No')
button2.grid(column=2,row=1,padx=5,pady=5,sticky=NSEW)
root.mainloop()

rawDescription: Why can't I grid a bitmap image or photo image tkinter?


code:
def add_pdr(process, userid, log):
    """ Create and perform the target account operation PDR

    If the function/method is complex, I'd put a short one-line
    summary in the first line above, and a more detailed explanation
    here.

    :param dict process: dict of process details
    :param str userid: userid to perform actions on
    :param obj log: log object to perform logging to

    :raises KeyError: if the userid doesn't exist
    :raises APIError: if process dict is invalid

    :return: True on success, False upon failure

    """

rawDescription: What is the use of PyCharm's docstring template? How do I use it effectively?


code:
from collections import Counter

with open('file1', 'r') as f1, open('file2', 'r') as f2, open('newfile', 'w') as output:
    f1_lines = [line.rstrip().lower() for line in f1.readlines()]
    f2_lines = [line.rstrip().lower() for line in f2.readlines()]
    diff = Counter(f2_lines) - Counter(f1_lines)
    for msg, n in diff.iteritems():
        output.writelines((msg + '\n') * n)

rawDescription: Comparing two files in python, with each file having duplicate data


code:
l = ['hello (abd)', 'goodbye (aab)', 'leave (aaa)']
sorted(l, key=lambda x: x[x.find('(')+1:x.find(')')])

rawDescription: Sort by a specific part of an element which is a string inside a list


code:
import gmpy2

n = 590632926550117049

a = gmpy2.isqrt(n) + 1
b2 = a * a - n

while not gmpy2.is_square(b2):
    a = a + 1
    b2 = a * a - n

b = gmpy2.isqrt(b2)

p = a + b
q = a - b

print("p =", p)
print("q =", q)

rawDescription: Fermat Factorization not work (python)

description: Fermat Factorization not work (python)


rawDescription: If possible, how can one stop a print to stdout from interrupting what's been typed?


code:
plt.figure()

CS = plt.contour(X, Y,log_mu,levels = [-7,-8],
                 colors=('k',),linestyles=('-',),linewidths=(2,))
CSF = plt.contourf(X, Y,log_mu)
plt.clabel(CS, fmt = '%2.1d', colors = 'k', fontsize=14) #contour line labels
CB = plt.colorbar(CSF, shrink=0.8, extend='both')

plt.xscale('log')
plt.yscale('log')

plt.show()

rawDescription: Mark a specific level in contour map on matplotlib


code:
f_in = open('file2.txt', 'r')
f_out = open('out.txt', 'w')
for line in f_in.readlines():
    f_out.write(prefix + ' ' + line.strip().replace(","," ") + \
    " " + suffix + " " +         line.split(",")[1]+"\n")
f_in.close()
f_out.close()

rawDescription: Append data file to CSV file and output to another CSV file


code:
import subprocess

subprocess.call(['/usr/bin/open', '~'])

rawDescription: What is a more crossplatform way of opening Explorer/file manager shell with the current directory?


code:
from celery import Celery

app = Celery('tasks', broker='amqp://guest@localhost//')

@app.task
def add(x, y):
    return x + y

rawDescription: Is there a way to make a SOAP call in Python and not wait for the return?


code:
import random
import psutil # $ pip install psutil

p = psutil.Process(random.choice(psutil.pids()))
print(p.name())
print(p.cpu_times())
print(p.memory_info())

rawDescription: Cross-platform resource usage on subprocess.Popen


code:
self._connection = pycurl.Curl()
self._connection.setopt(pycurl.PROXY, PROXY_HOST)
self._connection.setopt(pycurl.PROXYPORT, PROXY_PORT)
self._connection.setopt(pycurl.PROXYUSERPWD,
                        "%s:%s" % (PROXY_USER, PROXY_PASS))
...

rawDescription: Python urllib2 HTTPS and proxy NTLM authentication


code:
result = template.render({'a' : "value-1" })
# in the template {% set b = "value-2" %}
b = template.module.b

rawDescription: How to to read a jinja context variable

description: To read a jinja context variable


code:
LARGE_FONT = ("Verdana", 12)
NORM_FONT = ("Verdana", 10)
SMALL_FONT = ("Verdana", 8)

label = tk.Label(popup, text=msg, font=NORM_FONT, bg='white', justify='left')
B1 = tk.Button(popup, text="Okay", command=popup.destroy, bg='#000000', fg='#ffffff')

rawDescription: How can I set the font and the colour for a Button's text in Tkinter?

description: Set the font and the colour for a Button's text in Tkinter


rawDescription: Getting all objects referenced in a foreign key field


code:
class myClass:
    proxies = []
    def doIt(self):
        myClass.proxies.append(1)

rawDescription: How to use static variables inside functions?

description: Use static variables inside functions


code:
from sympy.interactive import printing
printing.init_printing(use_latex=True)

rawDescription: iPython Notebook output latex or mathjax

description: IPython Notebook output latex or mathjax


code: bool(a) != bool(b)

rawDescription: How do you get the logical xor of two variables in Python?

description: Get the logical xor of two variables in Python


code: [{'CrimeDate': g[0], 'Total Incidents': sum(map(lambda x: int(x['Total Incidents']), g[1]))} for g in itertools.groupby(d, lambda x: x['CrimeDate'])]

rawDescription: Sum the values of a list of dictionaries


code: ret = os.system('cp -fr "%s" "%s"' % (src_abs_path, dst_abs_path))

rawDescription: cp copy in wxPython spaces

description: Cp copy in wxPython spaces


code:
def read_xml():
    dict1 = create_dict_from_xml()
    return dict1

rawDescription: Importing XML to a dictionary, then accessing that dictionary from another module - Python


code:
def mygenerator():
    while True:
        yield randint(0, 9)

mygenerator = mygenerator()

rawDescription: Is there a built-in way (e.g., a decorator) to instantiate a Python generator at definiton?


code:
def kill():
    if self.health < 0:
        del self

rawDescription: Python class instances deleting themselves


code:
import matplotlib
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import pandas as pd
import Tkinter as tk
import ttk

root = tk.Tk()

lf = ttk.Labelframe(root, text='Plot Area')
lf.grid(row=0, column=0, sticky='nwes', padx=3, pady=3)

t = np.arange(0.0,3.0,0.01)
df = pd.DataFrame({'t':t, 's':np.sin(2*np.pi*t)})

fig = Figure(figsize=(5,4), dpi=100)
ax = fig.add_subplot(111)

df.plot(x='t', y='s', ax=ax)

canvas = FigureCanvasTkAgg(fig, master=lf)
canvas.show()
canvas.get_tk_widget().grid(row=0, column=0)

root.mainloop()

rawDescription: Python: Embed pandas plot in Tkinter GUI


code:
return min(itertools.chain((x[length_2] for x in distances),
  distances[length_1]))

rawDescription: Translate Pseudocode into python

description: Translate Pseudocode into python


code:
import requests
payload = {'USER': 'user@email.com',
           'PASSWORD': 'password123',
           'TMBNX': 'ISO-8859-1',
           'smauthreason': 0,
           'smretries': 1,
           'bacmonitoring': 'LOG ON',
           'target': 'http://fix-tt.mary.com/tmtrack/tmtrack.dll',

           }
r = requests.post("http://path-to-login-page.com", data=payload)
print(r.text)

rawDescription: How to login in a website using POST in Python?

description: Login in a website using POST in Python


code:
class Test:
    def func(*args):
        if len(args) == 1:
           return args[0] * args[0]
        elif len(args) == 2:
            return args[1] * args[0]
        elif len(args) == 3:
            return sum(args)
        else:
            raise "Unexpected number of arguments"

rawDescription: method overloading in Python with more than two functions

description: Method overloading in Python with more than two functions


code:
import matplotlib.pylab as plt
import scipy.sparse as sps
A = sps.rand(10000,10000, density=0.00001)
M = sps.csr_matrix(A)
plt.spy(M)
plt.show()

# Returns here '1.3.0'
matplotlib.__version__

rawDescription: scipy equivalent for MATLAB spy

description: Scipy equivalent for MATLAB spy


code:
gnames1 = list(A.objects.values_list('gname',flat=True).distinct())
gnames2 = list(B.objects.values_list('gname',flat=True).distinct())

gnames = list(set(gnames1+gnames2))
render(request, 'sampletemplate.html', {'gnames':gnames})

rawDescription: Combining two similar columns from 2 different tables with no relationship


rawDescription: Finding minimum value in dictionary

description: Finding minimum value in dictionary


code:
df[0]['Unnamed: 17']
df[0].rename(columns = {'Away':'Awayy2'}, inplace = True)

rawDescription: Is it possible to modify a df from pandas function read_html before pasting into a csv file?


rawDescription: Shorting down many if clauses

description: Shorting down many if clauses


code:
from django.test import TestCase
from django.template import Context, Template

class TagTests(TestCase):
    def tag_test(self, template, context, output):
        t = Template('{% load multifor %}'+template)
        c = Context(context)
        self.assertEqual(t.render(c), output)
    def test_for_tag_multi(self):
        template = "{% for x in x_list; y in y_list %}{{ x }}:{{ y }}/{% endfor %}"
        context = {"x_list": ('one', 1, 'carrot'), "y_list": ('two', 2, 'orange')}
        output = u"one:two/1:2/carrot:orange/"
        self.tag_test(template, context, output)

rawDescription: Testing a custom Django template filter

description: Testing a custom Django template filter


code:
import os, sys

def GetUserCfgDir():
    """Return a filesystem directory for storing user config files.

    Creates it if required.
    """
    cfgDir = '.idlerc'
    userDir = os.path.expanduser('~')
    if userDir != '~': # expanduser() found user home dir
        if not os.path.exists(userDir):
            warn = ('\n Warning: os.path.expanduser("~") points to\n ' +
                    userDir + ',\n but the path does not exist.')
            try:
                print(warn, file=sys.stderr)
            except OSError:
                pass
            userDir = '~'
    if userDir == "~": # still no path to home!
        # traditionally IDLE has defaulted to os.getcwd(), is this adequate?
        userDir = os.getcwd()
    userDir = os.path.join(userDir, cfgDir)
    if not os.path.exists(userDir):
        try:
            os.mkdir(userDir)
        except OSError:
            warn = ('\n Warning: unable to create user config directory\n' +
                    userDir + '\n Check path and permissions.\n Exiting!\n')
            print(warn, file=sys.stderr)
            raise SystemExit
    # TODO continue without userDIr instead of exit
    return userDir

print(GetUserCfgDir())

rawDescription: Where is the .idlerc folder for Python IDLE on Mac?


rawDescription: Qt LineTextEdit

description: Qt LineTextEdit


code:
from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt

X = [[6], [8], [10], [14],   [18]]
y = [[7], [9], [13], [17.5], [18]]

model = LinearRegression()
model.fit(X, y)

z = np.array([12]).reshape(-1,1)

print ('A 12" pizza should cost: $%.2f' % model.predict(z)[0])
print ("\n" + "_" * 50 + "\n")

plt.figure()
plt.title('Pizza price plotted against diameter')
plt.xlabel('Diameter in inches')
plt.ylabel('Price in dollars')
plt.scatter(X, y, z, 'k')

y0, y25 = model.predict(0)[0][0], model.predict(25)[0][0]
plt.plot((0, 25), (y0, y25), 'g')

plt.axis([0, 25, 0, 25])
plt.grid(True)
plt.show()

rawDescription: Display a line in matplotlib, so that my results match up with my textbook


code:
df1 = DataFrame(dict([ ("t{0}".format(i),date_range('20130101 01:0{0}'.format(i*3),periods=5,freq='T')) for i in range(2) ]))
df2 = DataFrame(dict([ ("t{0}".format(i+3),date_range('20130101 01:0{0}'.format(i*5),periods=5,freq='T')) for i in range(2) ]))
df = df1.join(df2)
df
(df.T-df.T.shift()).T.astype('timedelta64[s]')

rawDescription: numpy possible bug? doing timedeltas on columns

description: Numpy possible bug? doing timedeltas on columns


rawDescription: Sort a dict by numeric value of dict.values


code:
def signedOn(self):
    pMess = "IDENTIFY %s" % self.password
    self.msg("NickServ",pMess)
    time.sleep(10)
    for channel in self.factory.channels:
        self.join(channel)
    lc = task.LoopingCall(self._5_mins)
    lc.start(self.timeout)

rawDescription: Recurring function call with twisted

description: Recurring function call with twisted


code:
import re
input = ["xkcd", "word", "xml-"]
output = [i for i in input if re.match(r'(?=^[^aeiou]+$)^[a-z]+$', i)]

rawDescription: Regular expressions: How to filter for two things at once


code:
from django.forms.models import modelformset_factory

TimeActionFormset = modelformset_factory(TimeActionModel)

rawDescription: Better ways to handle dynamically generated forms in Django


code:
attributesToModify = ['cost', 'type', 'speed']
for e in attributesToModify:
    setattr(obj, e, getattr(obj, e) + 1)

rawDescription: Performing the same operation on many attributes of a python object


rawDescription: Make a list out of variables

description: Make a list out of variables


code:
q = list("aaabbbbcc")
q
r = set(q)
r
[x for x in r if all([q.count(x) >= q.count(y) for y in r])]

rawDescription: how to find the most common elements in a list (using all())

description: Find the most common elements in a list (using all())


code:
lists = [[]]
for num in BigList:
    if num in lists[-1]:
        lists.append([])
    lists[-1].append(num)

rawDescription: How to make sublists comprised of unique values from a larger list - python

description: Make sublists comprised of unique values from a larger list - python


code:
import argparse

parser = argparse.ArgumentParser()

# Put common subparser arguments here. Each sub parser will have
# its own -h option, so disable it on the shared base.
subbase = argparse.ArgumentParser(add_help=False)
subbase.add_argument('config', metavar='CONFIG', action='store', help='the config to use')

subparsers = parser.add_subparsers(help='', dest='command',  metavar='COMMAND', title='required arguments',
                                   description='two arguments are required')

# Add subbase to the parent list for each subparser.
cmda_parser = subparsers.add_parser('cmdA', parents=[subbase],  help='a first command')
cmdb_parser = subparsers.add_parser('cmdB', parents=[subbase], help='the second operation')
cmdc_parser = subparsers.add_parser('cmdC', parents=[subbase], help='yet another thing')

print(parser.parse_args())

rawDescription: How do I specify two required arguments, including a subcommand, using 'argparse'?

description: Specify two required arguments, including a subcommand, using 'argparse'


code: axes.set_xlim(0, 70)

rawDescription: Making the axis bigger or autoadjust to allow more ticks in matplotlib


code:
x = np.linspace(min(aSample),
                max(aSample),
                int((max(aSample) - min(aSample)) / step))

rawDescription: matplotlib: ways of drawing a CDF

description: Matplotlib: ways of drawing a CDF


code:
import string
alphabet = list(string.ascii_uppercase)
for i in range(2, len(alphabet), 2):
    alphabet[i], alphabet[i-1] = alphabet[i-1], alphabet[i]

alphabet

rawDescription: How can I switch the positions of each element in a list with Python?

description: Switch the positions of each element in a list with Python


rawDescription: Matplotlib auto chemical formula subscript use without italicizing text


code: np.concatenate([get_spam(foo) for item in foo])

rawDescription: How to append dynamically generated values into NumPy array?

description: Append dynamically generated values into NumPy array


code:
cur.executemany("INSERT INTO my_table(ID, vegetables, fruits) VALUES (?,?,?)",
    ((i, v, f) for (i, (v, f)) in enumerate(zip(vegetables, fruits), 1)))

rawDescription: Insert lists in SQLite database

description: Insert lists in SQLite database


code:
ip = urllib.urlopen('http://www.samair.ru/proxy/time-01.htm').read()
clientIp = re.findall(r"\d+\.\d+\.\d+\.\d+", ip)

rawDescription: Getting an external list of ip and turning in to variable dic in Python


code:
import inspect
inspect.stack()[1][0]
inspect.stack()[1][0].__sizeof__()

rawDescription: Recursive functions memory usage

description: Recursive functions memory usage


code:
def autoSolve():
    y = []
    for i in range(5):
        z = random.randrange(1, 10)
        y.append(z)
    print(y, end="")

rawDescription: List append in loop question

description: List append in loop question


code:
ax = fig.add_subplot(111, rasterized=True)
ax.plot(ts[0], ys.T, color='r', lw=0.5, alpha=0.5)

rawDescription: Rasterizing multiple elements in matplotlib


rawDescription: how to get subset of matrix in class numpy.matrix.defmatrix.matrix

description: Get subset of matrix in class numpy.matrix.defmatrix.matrix


code: [chr(i) for i in range(10,20,1)]

rawDescription: replace element of a list by appending escape character to each element

description: Replace element of a list by appending escape character to each element


code:
import datetime
trade_date = datetime.date(2005, 7, 25)
effective_date = datetime.datetime(2005, 7, 27, 11, 26, 38)
termination_date = datetime.datetime(2010, 7, 26, 11, 26, 38)
d = vars() # You can access the variable as d['name']
tradedates = {
    name: d[name].strftime('%Y-%m-%d')
    for name in ('trade_date', 'effective_date', 'termination_date')
}
tradedates

rawDescription: convert variables into dictonaries

description: Convert variables into dictonaries


rawDescription: Python Numpy: Sub-arrays to one list

description: Python Numpy: Sub-arrays to one list


code:
def adjlist_find_paths(a, n, m, path=[]):
  "Find paths from node index n to m using adjacency list a."
  path = path + [n]
  if n == m:
    return [path]
  paths = []
  for child in a[n]:
    if child not in path:
      child_paths = adjlist_find_paths(a, child, m, path)
      for child_path in child_paths:
        paths.append(child_path)
  return paths

def paths_from_to(graph, source, dest):
  "Find paths in graph from vertex source to vertex dest."
  a = graph.get_adjlist()
  n = source.index
  m = dest.index
  return adjlist_find_paths(a, n, m)

rawDescription: All possible paths from one node to another in a directed tree (igraph)


code:
def data_file(fname):
    """Return the path to a data file of ours."""
    return os.path.join(os.path.split(__file__)[0], fname)

rawDescription: Accessing data files before and after distutils/setuptools


code:
degree_of_contact = 0
for tmp1, tmp2 in [(p1, p2), (p2, p1)]:
    for x,y in tmp1:
        if point_inside_polygon(x, y, tmp2):
            degree_of_contact += 1

rawDescription: combine two loops in python

description: Combine two loops in python


code:
@given('Workspace has the following structure')
def step_impl(context):
    feature = context.feature

    name = os.path.splitext(os.path.basename(feature.filename))[0]
    if name == "delete":
        # do something
        ...
    elif name == "new_directory":
        # do something else
        ...
    else:
        raise Exception("can't determine how to run this step")

rawDescription: Behave, multiple steps with same name

description: Behave, multiple steps with same name


code:
import fileinput,sys,os
files=[os.path.join('HTML',filename) for filename in os.listdir("HTML/")]
for line in fileinput.input(files, inplace=True):
    line = filter(lambda x: x in string.printable, line)
    sys.stdout.write(line)

rawDescription: How do I do this in Python (File Manipulation)?

description: Do this in Python (File Manipulation)


code:
from __future__ import print_function

DEBUG = False

def dprint(*args,**kwargs):
    '''Debug print'''
    print(*args,**kwargs)

_blocked = False
def nodebug(name='dprint'):
    '''Decorator to remove all functions with name 'name' being a separate expressions'''
    def helper(f):
        global _blocked
        if _blocked:
            return f

        import inspect, ast, sys

        source = inspect.getsource(f)
        a = ast.parse(source) #get ast tree of f

        class Transformer(ast.NodeTransformer):
            '''Will delete all expressions containing 'name' functions at the top level'''
            def visit_Expr(self, node): #visit all expressions
                try:
                    if node.value.func.id == name: #if expression consists of function with name a
                        return None #delete it
                except(ValueError):
                    pass
                return node #return node unchanged
        transformer = Transformer()
        a_new = transformer.visit(a)
        f_new_compiled = compile(a_new,'<string>','exec')

        env = sys.modules[f.__module__].__dict__
        _blocked = True
        try:
            exec(f_new_compiled,env)
        finally:
            _blocked = False
        return env[f.__name__]
    return helper

@nodebug('dprint')
def f():
    dprint('f() started')
    print('Important output')
    dprint('f() ended')
    print('Important output2')

f()

rawDescription: Replacing parts of the function code on-the-fly


code:
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName(_fromUtf8("Dialog"))
        Form.resize(151, 67)
        self.verticalLayout = QtGui.QVBoxLayout(Form)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.pushButton = QtGui.QPushButton(Form)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.verticalLayout.addWidget(self.pushButton)
        self.lineEdit = QtGui.QLineEdit(Form)
        self.lineEdit.setReadOnly(True)
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
        self.verticalLayout.addWidget(self.lineEdit)

        self.retranslateUi(Form)
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), Form.changeText)

    def retranslateUi(self, Form):
        Form.setWindowTitle(_translate("Form", "Form", None))
        self.pushButton.setText(_translate("Form", "Click me", None))
        self.lineEdit.setPlaceholderText(_translate("Form", "functionvalue", None))

class MyForm(QtGui.QDialog, Ui_Form):
    def __init__(self, z=0):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.z = z

    def myfunc1(self):
        self.z+=1
        print (self.z)

    def changeText(self):
        self.myfunc1()
        self.lineEdit.setText(str(self.z))

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Form = MyForm()
    Form.show()
    sys.exit(app.exec_())

rawDescription: TypeError: changeText() takes exactly 2 arguments (0 given)


code:
import pandas as pd
pd.read_csv('http://vincentarelbundock.github.io/Rdatasets/csv/datasets/BJsales.csv')

rawDescription: How to use Python Web Scraping to download CSV file then convert it to Pandas Dataframe?

description: Use Python Web Scraping to download CSV file then convert it to Pandas Dataframe


code:
class Company(models.Model):
  name = models.CharField(max_length=100, null=True)
  address = models.CharField(max_length=100, null=True)
  lat = models.DecimalField(max_digits=20, decimal_places=10, null=True)
  long = models.DecimalField(max_digits=20, decimal_places=10, null=True)
  phone = models.CharField(max_length=15, null=True)
  website = models.UrlField(max_length=50, null=True)
  email = models.EmailField(max_length=50, null=True)
  hiring = models.BooleanField(default=False)
  about_us = models.CharField(max_length=500, null=True)
  approved = models.BooleanField(default=False)

rawDescription: need help "translating" these sql into django models

description: Need help "translating" these sql into django models


code:
import os
import glob
import collections

dirpath = r"C:\Python32\test"
os.chdir(dirpath)
cnt = collections.Counter()
for filename in glob.glob("*"):
    name, ext = os.path.splitext(filename)
    cnt[ext] += 1
print(cnt)

rawDescription: Python counting file extensions

description: Python counting file extensions


rawDescription: how do i extract a partial value from a string in python?

description: Extract a partial value from a string in python


code: pattern = re.compile(r"(Item$\s*4.*)Item$\s*5", re.S | re.M)

rawDescription: Regex passes in Rubular but not in Python


rawDescription: is there a multiple format specifier in Python?

description: Is there a multiple format specifier in Python


code:
def hello_function():
    """Returns 'hello' string."""
    return 'hello'

rawDescription: Python PEP: blank line after function definition?


code:
import timeit
from django.http import QueryDict
query_string = '&'.join('key%d=%s' % (i, 'xxx'*100*i) for i in range(100))
len(query_string)
POST = QueryDict(query_string)
def func1():
    foo_1 = POST['key1']
    foo_2 = POST['key1']
    foo_3 = POST['key1']

def func2():
    foo = POST['key1']
    foo_1 = foo
    foo_2 = foo
    foo_3 = foo

timeit.timeit(func1, number=1000000)
timeit.timeit(func2, number=1000000)

rawDescription: Django : recursive use of "request.POST" caching?


code:
import urllib.parse
parsed = urllib.parse.urlparse(sys.argv[1])
mail_addr = parsed.path
fields = urllib.parse.parse_qs(parsed.query)

rawDescription: Making a Python program handle mailto links


code:
import warnings
import traceback

_formatwarning = warnings.formatwarning

def formatwarning_tb(*args, **kwargs):
    s = _formatwarning(*args, **kwargs)
    tb = traceback.format_stack()
    s += ''.join(tb[:-1])
    return s

warnings.formatwarning = formatwarning_tb
logging.captureWarnings(True)

rawDescription: Log stack trace for python warning

description: Log stack trace for python warning


code:
tennis_sets
tennis_sets["pA_wins"] = tennis_sets["player_A"] > tennis_sets["player_B"]
tennis_sets["pB_wins"] = tennis_sets["player_B"] > tennis_sets["player_A"]
tennis_sets
matches = tennis_sets.groupby("date").sum()
matches[["pA_wins", "pB_wins"]]

rawDescription: Using pandas group operations

description: Using pandas group operations


code:
import numpy as np

def cartesian(arrays, out=None):
    """
    Generate a cartesian product of input arrays.

    Parameters
    ----------
    arrays : list of array-like
        1-D arrays to form the cartesian product of.
    out : ndarray
        Array to place the cartesian product in.

    Returns
    -------
    out : ndarray
        2-D array of shape (M, len(arrays)) containing cartesian products
        formed of input arrays.

    Examples
    --------
    >>> cartesian(([1, 2, 3], [4, 5], [6, 7]))
    array([[1, 4, 6],
           [1, 4, 7],
           [1, 5, 6],
           [1, 5, 7],
           [2, 4, 6],
           [2, 4, 7],
           [2, 5, 6],
           [2, 5, 7],
           [3, 4, 6],
           [3, 4, 7],
           [3, 5, 6],
           [3, 5, 7]])

    """

    arrays = [np.asarray(x) for x in arrays]
    dtype = arrays[0].dtype

    n = np.prod([x.size for x in arrays])
    if out is None:
        out = np.zeros([n, len(arrays)], dtype=dtype)

    m = n / arrays[0].size
    out[:,0] = np.repeat(arrays[0], m)
    if arrays[1:]:
        cartesian(arrays[1:], out=out[0:m,1:])
        for j in xrange(1, arrays[0].size):
            out[j*m:(j+1)*m,1:] = out[0:m,1:]
    return out

rawDescription: Using numpy to build an array of all combinations of two arrays


code:
def post(self, request, *args, **kwargs):
   form= self.form_class(request.POST)
   if form.is_valid():
      user_email= form.cleaned_data['email']
      user_of_campaign= Campaign.objects.filter(email= user_email)
      if len(user_of_campaign)>0:
         return redirect('/login', user_of_campaign[0].id)
      else:
         return redirect('/register')
      return super(CampaignView, self).form_valid(form)
   return super(CampaignView, self).form_invalid(form)

rawDescription: Where to place logic in a Class Base View?