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

# Firstly, modules can be documented using docstring, so drop the comments
"""
 Create the videos directory in the current directory
 If the directory exists ignore it.

 Moves all files with the .wmv extension to the
 videos folder for file structure

 Crawl the videos directory then change to videos directory
 create the videos.csv file in the videos directory
 create output.csv replace any drive letter A:-Y: with Z:
"""

# not useful to import os and os.path as the second is contain in the first one
import os
import shutil
import csv
# import glob, it will be handy
import glob
import ntpath # this is to split the drive

# don't really need to use a function

# Here, don't bother checking if the directory exists
# and you don't need add any slash either
directory = "videos"
ext = "*.wmv"
try :
    os.mkdir(directory)
except OSError :
    pass

listDirectory = [] # creating a buffer so no need to list the dir twice

for file in glob.glob(ext): # much easier this way, isn't it ?
        shutil.move(file, os.path.join(directory, file)) # good catch for shutil :-)
        listDirectory.append(file)

os.chdir(directory)

# you've smartly imported the csv module, so let's use it !
f = open("videos.csv", "w")
vid_csv = csv.writer(f)
w = open('output.csv', 'w')
out_csv = csv.writer(w)

# let's do everything in one loop
for file in listDirectory :
    file_path = os.path.abspath(file)
    # Python includes functions to deal with drive letters :-D
    # I use ntpath because I am under linux but you can use
    # normal os.path functions on windows with the same names
    file_path_with_new_letter = ntpath.join("Z:", ntpath.splitdrive(file_path)[1])
    # let's write the csv, using tuples
    vid_csv.writerow((file_path, ))
    out_csv.writerow((file_path_with_new_letter, ))

rawDescription: Python - Strip all drive letters from csv file and replace with Z:


code:
class ListSerializer (serializers.HyperlinkedModelSerializer):
    title = serializers.CharField(write_only=True)

rawDescription: DjangoRestFramework - Loading specific columns, and saving an entire object


code:
a,b,c = 1,2,3
while i<n:
    a,b,c = myfunction(a,b,c)
    i +=1

rawDescription: Calling function and passing arguments multiple times


code:
def json_handler(obj):
    if hasattr(obj, 'isoformat'):
        return obj.isoformat()
    elif isinstance(obj, Event):
        attrs = dict(data=obj.data, timestamp=obj.timestamp)
        return {obj.__class__.__name__: attrs}
    else:
        raise TypeError("Unserializable object {} of type {}".format(obj, type(obj)))

rawDescription: workaround for python json <= 2.7 datetime serializer not working

description: Workaround for python json <= 2.7 datetime serializer not working


code:
def openPage():
    web = QWebView()
    web.load(QUrl('http://www.google.com'))
    web.setFixedSize(500, 500)
    web.show()
    return web

if __name__ == '__main__':
    app = QApplication(sys.argv)
    web = openPage()
    sys.exit(app.exec_())

rawDescription: QWebView in PyQt4 doesn't open when I put it in a function


code: d3 = {key: d1[key] - d2.get(key, 0) for key in d1.keys()}

rawDescription: How to subtract values from dictionaries

description: Subtract values from dictionaries


code:
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?')
parser.add_argument('-f', dest='file_opt')
args = parser.parse_args()
if args.file_opt:
    args.file = args.file_opt

rawDescription: Python: how to handle the exceptions of argparse?


rawDescription: PyQt acess selectionChanged Content

description: PyQt acess selectionChanged Content


code:
import xml.etree.ElementTree as ET
try:
    from cStringIO import StringIO
except:
    from StringIO import StringIO

o = file('out.txt', 'w')

tree = ET.parse('read.vtu')
root = tree.getroot()

for Piece in root.iter('Piece'):
  nr = Piece.get('NumberOfPoints')
  o.write(nr+ '\n')

piece = root.iter('Piece')
piece = piece.next()
point = piece.getchildren()[0]
dataArr = point.getchildren()
data = dataArr[0]

# Writing to a buffer
output = StringIO()
output.write(data.text)

# Retrieve the value written
crds = output.seek(1)

for l in output:
  ls = l.split( );
  o.write(ls[0]+ '\n')
  o.write(ls[1]+ '\n')

output.close()
o.close()

rawDescription: extract values and construct new file

description: Extract values and construct new file


code:
parser = argparse.ArgumentParser()
parser.add_argument('-ip', '--ip')
parser.add_argument('-t','--trigger', nargs='*')
args = parser.parse_args()

rawDescription: python 2.7 check if argument has been passed from command prompt

description: Python 2.7 check if argument has been passed from command prompt


code:
import re

pattern = re.compile(r'\<name key="(.*)">(.*)<\/name>')
def sorter(pair):
    return pattern.match(pair).groups()

print(sorted(list_of_lines, key=sorter))

rawDescription: Python sorting by special characters (+/-)


code:
def rawProducts(repeat=2):
  return product([0, 1], repeat=repeat)

def toNumber(seq):
  # here's the trick: the last parameter to reduce() is the initial value;
  # we pretend that we already have a 1 before we started iterating
  # over seq, instead of prepending the 1 to seq.
  return reduce(lambda acc, x: 10 * acc + x, seq, 1)

result = [toNumber(prod) for prod in rawProducts()]

rawDescription: Cleaner way to do itertools product combination in Python?


rawDescription: Django queryset filter from two models

description: Django queryset filter from two models


rawDescription: How to convert ctypes' c_long to Python's int?

description: Convert ctypes' c_long to Python's int


code:
from kivy.app import App
from kivy.factory import Factory
from kivy.uix.carousel import Carousel
from kivy.clock import Clock

class Logo(App):
    def build(self):

        carousel = Carousel(direction='right', loop=True)
        for i in range(2):
            image = Factory.Label(text=str(i))
            carousel.add_widget(image)

        Clock.schedule_interval(carousel.load_next, 1)
        return carousel

if __name__ == '__main__':
    Logo().run()

rawDescription: How to make a carousel in Kivy?

description: Make a carousel in Kivy


code:
from kivy.app import App
def change_screen(*args):
    App.get_running_app().root.current = 'main'

from kivy.uix.button import Button
btn = Button(text='abc')
btn.bind(on_press=change_screen)

rawDescription: How to add on_press to change the screen in python using kivy?

description: Add on_press to change the screen in python using kivy


code:
df.loc[max(df.index)+1, :] = None
df.x2 = df.x2.shift(1)

rawDescription: How to shift a column in Pandas DataFrame without losing value

description: Shift a column in Pandas DataFrame without losing value


code:
def ssh_edit_file(h, u, file_in, file_out, key, new):
    """
    SSH_EDIT_FILE - replace a line in a remote file
    """

    import warnings

    try:
        s = new.replace("'","\'")
        if file_in == file_out:
            ssh_exe('sed -i "s/.*' + key + '.*/' + s + '/g" ' + file_out,
                    h = h, u = u )
        else:
            ssh_exe('sed -e "s/.*' + key + '.*/' + s + '/g" ' +
                    file_in + '>|' +  file_out,
                    h = h, u = u )
    except:
        warnings.warn('key not found')

def ssh_exe(cmd, client=None, h=None,u=None):
    """
    SSH_EXE - Run command via ssh
    """

    import paramiko, os

    if h:
        if client:
              raise RuntimeError('Please specify either client of h and u')
        client = paramiko.SSHClient()
        client.load_system_host_keys(os.environ["HOME"] + "/.ssh/known_hosts")
        client.connect(h,username=u)
    else:
        if h or u:
              raise RuntimeError('Please specify either client of h and u')

    stdin, stdout, stderr = client.exec_command(cmd)

    if stdout.channel.recv_exit_status():
        e = stderr.readlines()
        if not e == []:
            raise RuntimeError('Error in executing ' + cmd + '\n'.join(e))

    if h:
        client.close()

rawDescription: Modification of text files over ssh with Python - performance


code:
name = raw_input("Name the variable:")
value = raw_input("And the value?")
exec("{} = {}".format(name, value))

rawDescription: Create Variables Inside Program

description: Create Variables Inside Program


code:
user = User.objects.get(username="jamie")
sorted(Task.objects.all(), key = lambda task, user=user: task.date_for_display(user))

rawDescription: Sort Django objects by method with arguments


code:
import json
import re

import scrapy

class OlxSpider(scrapy.Spider):
    name = "olx"
    rotate_user_agent = True
    allowed_domains = ["olx.pt"]
    start_urls = [
        "https://olx.pt/imoveis/"
    ]

    def parse(self, response):
        for href in response.css('.link.linkWithHash.detailsLink::attr(href)'):
            url = response.urljoin(href.extract())
            yield scrapy.Request(url, callback=self.parse_house_contents)

        for next_page in response.css('.pager .br3.brc8::attr(href)'):
            url = response.urljoin(next_page.extract())
            yield scrapy.Request(url, self.parse)

    def parse_house_contents(self, response):
        property_id = re.search(r"ID(\w+)\.", response.url).group(1)

        phone_url = "https://olx.pt/ajax/misc/contact/phone/%s/" % property_id
        yield scrapy.Request(phone_url, callback=self.parse_phone)

    def parse_phone(self, response):
        phone_number = json.loads(response.body)["value"]
        print(phone_number)

rawDescription: Scrapy + Splash + ScrapyJS

description: Scrapy + Splash + ScrapyJS


code:
#!/usr/bin/python
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
ax1.plot(x, y)
ax1.set_title('Sharing Y axis')
ax2.scatter(x, y)
f.gca().invert_xaxis()
f.subplots_adjust(wspace=0.0)
plt.show()

rawDescription: Matplotlib & Excel: How to evenly slice the x-axis of a plot?


code:
from matplotlib.backends.backend_pdf import PdfPages
import numpy as np
import matplotlib.pyplot as plt

x1 = np.arange(10)
y1 = x1**2

x2 = np.arange(20)
y2 = x2**2

pp = PdfPages('test.pdf')

def function_plot(X,Y):
    plt.figure()
    plt.clf()

    plt.plot(X,Y)
    plt.title('y vs x')
    plt.xlabel('x axis', fontsize = 13)
    plt.ylabel('y axis', fontsize = 13)
    pp.savefig()

function_plot(x1,y1)
function_plot(x2,y2)

pp.close()

rawDescription: Saving plots to pdf files using matplotlib


code:
next = 1
modulo = 2**32
def myrand():
    global next
    next = ((next * 1103515245) + 12345) % modulo
    return (next / 65536) % 32768

rawDescription: Simple PRNG algorithm has different Python/C output - integer overflow differences?


code:
import json
s = '["SU15AM","SU3AM","SU4AM","SU45AM","SU4PM","M3AM"]'
l = json.loads(s)
l
type(l)

rawDescription: Converting a JSON string (sent via ajax) into a Python list


code: numbers = [num for num in numbers if num % 2 == 0]

rawDescription: How to filter a list

description: Filter a list


rawDescription: Getting all field names from a protocol buffer?


code:
from gi.repository import Gtk, Gdk, GLib
import socket

# create the connection
sock= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('localhost', 10000))

def send(button):
    text= entry.get_text() # get the text to send from the GtkEntry
    # send the stuff
    remaining= len(text)
    while True:
        sent= sock.send(text)
        remaining-= sent
        if not remaining:
            break
        text= text[sent:]
    # wait for the server's response
    response= sock.recv(50)
    # and put it into a label
    Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT, label.set_text, response)

# spawn the GUI
window= Gtk.Window()
vbox= Gtk.VBox()
entry= Gtk.Entry()
button= Gtk.Button('send')
# when the user clicks the button, send something to the server
button.connect('clicked', send)
label= Gtk.Label()
vbox.pack_start(entry, False, False, 0)
vbox.pack_start(button, False, False, 0)
vbox.pack_start(label, False, False, 0)
window.add(vbox)

window.connect('delete-event', Gtk.main_quit)
window.show_all()
Gtk.main()

rawDescription: how can i get a message from TCP/IP and continously print it in a text frame

description: Get a message from TCP/IP and continously print it in a text frame


rawDescription: Python regex: find lines where period is missing in


rawDescription: How to make try-except-KeyError shorter in python?

description: Make try-except-KeyError shorter in python


code:
# returns a df grouped by ArtistID and Tag
tag_counts = artists_tags.groupby(['ArtistID', 'Tag'])
# sum up tag counts and sort in descending order
tag_counts = tag_counts.sum().sort('Count', ascending=False).reset_index()
# keep only the top ranking tag per artist
top_tags = tag_counts.groupby('ArtistID').first()
# top_tags is now a dataframe which contains the top tag for every artist
# We can simply lookup the top tag for Nirvana via it's index:
top_tags.ix['5b11f4ce-a62d-471e-81fc-a69a8278c7da'][0]
# 'Grunge'

rawDescription: Python : Separating a .txt file into columns and finding the most frequent data item in one of the columns


code:
for key in account.keys():
    print(key)
    print(account[key])

rawDescription: How to access my dictionary

description: Access my dictionary


code:
def truncate_after(s, needle):
    partition_pos = s.index(needle)+len(needle)
    return s[:partition_pos]

rawDescription: Python splitting but keeping the split string


code:
@app.context_processor
def inject_template_globals():
    return {
        'nowts': datetime.datetime.utcnow(),
    }

rawDescription: How to update timestamp as a global variable in Jinja2?

description: Update timestamp as a global variable in Jinja2


code:
class CustomLocaleMiddleware(LocaleMiddleware):
    def process_request(self, request):
        ...
        lang = languages.objects.get(identifier=translation.get_language())
        if lang:
            if not lang.active:
                request.LANGUAGE_CODE = 'en'
            else:
                request.LANGUAGE_CODE = translation.get_language()
        else:
            request.LANGUAGE_CODE = translation.get_language()

rawDescription: Django load LANGUAGES parameter from the database


code:
open('test_newlines.txt', 'rb').read()
list(open('test_newlines.txt'))
list(open('test_newlines.txt', 'U'))
open('test_newlines.txt').readlines()
open('test_newlines.txt', 'U').readlines()
open('test_newlines.txt').read().split()

rawDescription: Python . How to get rid of '\r' in string?


code:
import datetime

tomorrow = datetime.datetime.today()+datetime.timedelta(days=1)

upcoming_obj = Events.objects.filter(start_date__gt = tomorrow)

rawDescription: Retrive data where date and time are more than tomorrow


rawDescription: Numpy remove column in array if first value in column is larger than last


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

colors = ['red', 'green', 'orange', 'blue', 'yellow', 'purple']
bounds = [0,1,2,3,4,5,6]

cmap = mpl.colors.ListedColormap(colors)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

plt.imshow(my_array, interpolation='none', cmap=cmap, norm=norm)

rawDescription: How to determine the colours when using matplotlib.pyplot.imshow()?

description: Determine the colours when using matplotlib.pyplot.imshow()


code:
program_button = [elem.control for elem in self.program_buttons]
progId = list()
posX = list()
posY = list()
prog_id_list = list()
prog_index_list = list()

for elem in program_button:
    progId.append(elem.getId())
    posX.append(elem.getX())
    posY.append(elem.getY())
progId = map(str, progId)
posX = map(str, posX)
posY = map(str, posY)

for i in range(len(posX)):
    pos_X = posX[i]
    if pos_X == '375':
        prog_id_list.append( progId[i] )
        prog_index_list.append( i )

rawDescription: create the for loop to find the string in the variable

description: Create the for loop to find the string in the variable


code:
import re
s = 'foo bar (baz)'
re.sub(r'(?<=\().*?(?=\))', lambda m: '*'*len(m.group()), s)

rawDescription: Python regex: Replace individual characters in a match


code:
name, timestamp = oldfilename.split('_', 1)
day, month, timestamp = timestamp.split('-', 2)

newfilename = '%s_%s-%s-%s' % (name, day, month, timestamp)

rawDescription: Better way, than this, to rename files using Python


code:
mapping = {X1: Y1, X2: Y2, X3: Y3}
mapping[X4] = Y4
mapping[X5] = Y5

for X,Y in mapping.items():
    if Y is not None:
        obj[X][0] = Y

rawDescription: Condensing code in Python with Mappings

description: Condensing code in Python with Mappings


code:
from PythonMagick import Image
Image("img.png").write("clipboard:")

rawDescription: Storing a file in the clipboard in python


code:
import tarfile, io
byte_array = client.read_bytes()
file_like_object = io.BytesIO(byte_array)
tar = tarfile.open(fileobj=file_like_object)
# use "tar" as a regular TarFile object
for member in tar.getmembers():
    f = tar.extractfile(member)
    print(f)

rawDescription: How to construct a TarFile object in memory from byte buffer in Python 3?

description: Construct a TarFile object in memory from byte buffer in Python 3


code:
myQTreeWidget = QtGui.QTreeWidget()
listsHeader = ['A', 'B', 'C']
myQTreeWidget.setHeaderItem(QtGui.QTreeWidgetItem(listsHeader))
dataQTreeWidgetItem = QtGui.QTreeWidgetItem(myQTreeWidget) # assgin QTreeWidget
for i in range(len(listsHeader)):
    dataQTreeWidgetItem.setText(0, 'INDEX ' + str(i)) # Test text in column
    myQTreeWidget.setItemWidget(dataQTreeWidgetItem, i, QtGui.QComboBox())

rawDescription: How to set Item Widget if Item was not yet addet to TreeWidget using .addTopLevelItem()

description: Set Item Widget if Item was not yet addet to TreeWidget using .addTopLevelItem()


rawDescription: Generate following subsets from list in efficient/pythonic manner


code:
for class_name in list_:
   import class_name
   runner_method = getattr(class_name, "runner", None) # if it staticmethod
   if callable(runner_method):
      runner_method()

rawDescription: how to load files dynamically in the same directory python

description: Load files dynamically in the same directory python


code:
import os
import subprocess

CHROME = os.path.join('C:\\', 'Program Files (x86)', 'Google', 'Chrome', 'Application', 'chrome.exe')

os.system('taskkill /im chrome.exe')
subprocess.call([CHROME, '--kiosk'])

rawDescription: How to open Google Chrome using Python and pass in arguments?

description: Open Google Chrome using Python and pass in arguments


code:
from xml.dom import minidom

doc = minidom.parse(svg_file)  # parseString also exists
path_strings = [path.getAttribute('d') for path
                in doc.getElementsByTagName('path')]
doc.unlink()

rawDescription: Python SVG parser

description: Python SVG parser


code:
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import axes3d, Axes3D
import pylab as p

vima=0.5

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(0, 16.67, vima)
Y = np.arange(0, 12.5, vima)
X, Y = np.meshgrid(X, Y)

Z = np.sqrt(((1.2*Y+0.6*X)**2+(0.2*Y+1.6*X)**2)/(0.64*Y**2+0.36*X**2))
Z = np.nan_to_num(Z) # added this line

surf = ax.plot_surface(X, Y, Z,rstride=1, cstride=1, alpha=1,cmap=cm.jet,  linewidth=0)
fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

rawDescription: Normalizing colors in matplotlib

description: Normalizing colors in matplotlib


code:
from networkx.readwrite import json_graph
import networkx as nx
import json
G = nx.DiGraph([(1,2)])
data = json_graph.tree_data(G,root=1)
s = json.dumps(data)

rawDescription: Print networkx DiGraph to Nested JSON format


code:
def take_screenshot(x=0, y=0, width=None, height=None):
    window = gtk.gdk.get_default_root_window()
    if not (width and height):
        size = window.get_size()
        if not width:
            width = size[0]
        if not height:
            height = size[1]
    pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, width, height)
    pixbuf = pixbuf.get_from_drawable(window, window.get_colormap(),
                                      x, y, 0, 0, width, height)
    array = pixbuf.get_pixels_array()
    return Image("screenshot", array=array,
                 width=array.shape[1], height=array.shape[0])

rawDescription: Fastest Way to Load a Screenshot Into Memory for CV Template Matching


code: str(myPacket)[:(myPacket[IP].ihl * 4)]

rawDescription: Scapy: how do I get the full IP packet header?


code:
def reduced(dictionary):
    keys = set(dictionary.iterkeys())
    subkeys = set()
    for key in keys:
        for n in range(1, len(key)):
            for i in range(len(key) + 1 - n):
               subkey = key[i:i+n]
               if subkey in keys:
                   subkeys.add(subkey)

    return {k: v
            for (k, v) in dictionary.iteritems()
            if k not in subkeys}

rawDescription: Performance of my function removing keys from a dictionary which are substrings of other keys


code: [inverted_function(random.random()) for x in range(1000)]

rawDescription: Fast arbitrary distribution random sampling


code:
import datetime, calendar
year = 2014
month = 1
num_days = calendar.monthrange(year, month)[1]
days = [datetime.date(year, month, day) for day in range(1, num_days+1)]
days

rawDescription: How to get all days in current month?

description: Get all days in current month


code:
import sounddevice as sd

def callback(indata, outdata, *stuff):
    outdata[:] = indata * [1, 0.5]

with sd.Stream(channels=2, callback=callback):
    input()

rawDescription: How to control a sound card programmatically?

description: Control a sound card programmatically


code:
x = 'my first arg'
y = 'my second arg'

workflow = chain(task1.s(x, y), group(task2.s(x, y), task3.s(x, y)))
result = workflow.delay()

rawDescription: Pass parent task arguments to all celery subtasks


code:
import numpy as np
from itertools import combinations

t = np.random.rand(4,3) # dummy example np.array
n_cols = t.shape[1] # number of columns

# all the combinations in a tuple:
combs = tuple( t[:, comb] for n in range(n_cols+1) for comb in combinations(range(n_cols), n) )

rawDescription: How to find different combinations of numpy array?

description: Find different combinations of numpy array


code:
import urllib2
import time
import random

MAX_WAIT = 5
ids = ...
agents = ...
proxies = ...

for id in ids:
    url = 'http://abc.com/view_page.aspx?ID=%d' % id
    opener = urllib2.build_opener(urllib2.ProxyHandler({'http' : proxies[0]}))
    html = opener.open(urllib2.Request(url, None, {'User-agent': agents[0]})).read()
    open('%d.html' % id, 'w').write(html)
    agents.append(agents.pop()) # cycle
    proxies.append(proxies.pop())
    time.sleep(MAX_WAIT*random.random())

rawDescription: Intelligent screen scraping using different proxies and user-agents randomly?


code: s.rfind(re.findall(pattern, s)[-1])

rawDescription: How to get the position of the last match of a regex?

description: Get the position of the last match of a regex


code:
import requests as req

url = 'https://www.youtube.com/results?search_query=clippers+vs+lakers'

response = req.get(url)

headers = response.headers

html = response.text

rawDescription: How to find the raw header of a website using python?

description: Find the raw header of a website using python


code:
from distutils.core import setup
import py2exe

setup(
    console=
    [
        'pywinauto_sample.py'
    ],
    options=
    {
        "py2exe":
        {
            "includes":
            [
                "pywinauto.tests.truncation",
                "pywinauto.tests.translation",
                "pywinauto.tests.repeatedhotkey",
                "pywinauto.tests.overlapping",
                "pywinauto.tests.missingextrastring",
                "pywinauto.tests.missalignment",
                "pywinauto.tests.miscvalues",
                "pywinauto.tests.leadtrailspaces",
                "pywinauto.tests.comparetoreffont",
                "pywinauto.tests.comboboxdroppedheight",
                "pywinauto.tests.asianhotkey",
                "pywinauto.tests.allcontrols",
            ]
        }
    }
)

rawDescription: ImportError: No module named allcontrols with pywinauto and py2exe


code:
from traits.api import HasTraits, Enum, Instance, Button
from traitsui.api import View, Item, VGroup
from enable.api import ComponentEditor
from chaco.api import Plot, ArrayPlotData, PlotAxis

from numpy import arange

class PlotApp(HasTraits):

    plotdata = Instance(ArrayPlotData)
    returns_plot = Instance(Plot)

    plot_type = Enum('line', 'scatter')

    add_points = Button

    traits_view = View(
                VGroup(Item("add_points"),
                    Item('returns_plot', editor=ComponentEditor(),
                        show_label=False),
                    orientation = "vertical"),
                resizable=True, title="Test"
                )

    def _returns_plot_default(self):
        self.plotdata = ArrayPlotData(index=arange(100), value=arange(100))
        plot = Plot(self.plotdata)
        plot.legend.visible = True
        plot.x_axis = None
        x_axis = PlotAxis(plot, orientation="bottom")
        plot.overlays.append(x_axis)

        plot.plot(("index", "value"), type="scatter", name = "Mediciones")
        return plot

    def _add_points_fired(self):
        current_length = len(self.plotdata["index"])
        self.plotdata.set_data("index", arange(current_length+1))
        self.plotdata.set_data("value", arange(current_length+1))

if __name__ == "__main__":
    app = PlotApp()
    app.configure_traits()

rawDescription: Dynamical plot with Chaco

description: Dynamical plot with Chaco


rawDescription: Rename columns based on another DataFrame


code:
import matplotlib.pyplot as plt
import pandas
import seaborn as sns
import numpy as np

data = pandas.DataFrame({"x": [1, 2, 4],
                        "y": [10,20,40],
                        "s": [10,10,10]}) # I increased your errors so I could see them

# Create a figure instance, and the two subplots
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)

# Tell pointplot to plot on ax1 with the ax argument
sns.pointplot(x="x", y="y", data=data, ax=ax1)

# Plot the errorbar directly on ax1
ax1.errorbar(np.arange(len(data["x"])), data["y"], yerr=data["s"])

# Tell the factorplot to plot on ax2 with the ax argument
# Also store the FacetGrid in 'g'
g=sns.factorplot(x="x", y="y", data=data, ax=ax2)

# Close the FacetGrid figure which we don't need (g.fig)
plt.close(g.fig)

plt.show()

rawDescription: seaborn produces separate figures in subplots

description: Seaborn produces separate figures in subplots


code: string.replace(your_string, '\b', ' ')

rawDescription: replacing the backspace ascii in python

description: Replacing the backspace ascii in python


code:
def test_anagram():
    strings = [("foo","bar"),("foo","oof"),("python","jython"),("tear","tare"),("foobar","bar"),("nod","don")] # create pairs of test strings
    for s1,s2 in strings: # ("foo","bar") -> s1 = "foo",s2 = "bar"...
        print(s1,s2) # print each string
        anagram(s1,s2) # call anagram, anagram("foo","bar") ...

In [17]: test_anagram() # call test_anagram()
('foo', 'bar')
False
('foo', 'oof')
True
('python', 'jython')
False
('tear', 'tare')
True
('foobar', 'bar')
False
('nod', 'don')
True

rawDescription: How to define a procedure to call a function in python 3

description: Define a procedure to call a function in python 3


rawDescription: Is there a way to view the source code of a function, class, or module from the python interpreter?


code:
from pymongo import MongoClient
client = MongoClient('host', port, maxPoolSize=200)

rawDescription: How to increase connection pool size for Mongodb using python

description: Increase connection pool size for Mongodb using python


code:
import numpy as np
def show_field(field1,field2):

    combined_data = np.array([field1,field2])
    #Get the min and max of all your data
    _min, _max = np.amin(combined_data), np.amax(combined_data)

    fig = plt.figure()
    ax = fig.add_subplot(2, 1, 1)
    #Add the vmin and vmax arguments to set the color scale
    ax.imshow(field1,cmap=plt.cm.YlGn, vmin = _min, vmax = _max)
    ax.set_adjustable('box-forced')
    ax.autoscale(False)
    ax2 = fig.add_subplot(2, 1, 2)
    ax2.set_adjustable('box-forced')
    #Add the vmin and vmax arguments to set the color scale
    ax2.imshow(field2,cmap=plt.cm.YlGn, vmin = _min, vmax = _max)
    ax2.autoscale(False)
    plt.show()

rawDescription: Set two matplotlib imshow plots to have the same color map scale


rawDescription: numpy tensordot related issue

description: Numpy tensordot related issue


code:
kwargs = dict((k, getattr(self, k)) for k in ('c', 'd') if getattr(self, k))
print_something(a, b, **kwargs)

rawDescription: How to default to the default argument in Python

description: Default to the default argument in Python


code:
sentence = 'I    live in  Virginia   and it is  raining     today'
' '.join([segment for segment in sentence.split()])

rawDescription: removing random whitespace

description: Removing random whitespace


code:
def hedge(s):
    for i, word in enumerate(s.split()):
        if i > 0 and i % 3 == 0:
            yield 'like'
        yield word

sentence1 = "his palms are sweaty, knees weak, arms are heavy. there's vomit on his sweater already, mom's spaghetti."
sentence2 = "his palms are like sweaty, knees weak, like arms are heavy. like there's vomit on like his sweater already, like mom's spaghetti."
assert ' '.join(hedge(sentence1)) == sentence2

rawDescription: Inserting elements into a list while iterating


code:
import os

print ("Hello")
print ("Press any key to exit")
ex = raw_input ("")
os._exit(0)

rawDescription: Python Close Shell with no popup

description: Python Close Shell with no popup


rawDescription: Creating a pandas DataFrame from columns of other DataFrames with similar indexes


code:
import os
from couchdbkit import Server, designer
__serv = Server(uri = 'http://192.168.11.13:5984')
website = os.path.join(os.getcwd(), "path_to_website")
database = __serv.get_or_create_db("website")
designer.push(website, database, atomic = False)

rawDescription: Couchdbkit designer.push is uploading documents as base64


code:
def clean(self):
    cleaned_data = self.cleaned_data
    user = User.objects.filter(email=cleaned_data['email'])
    if user:
        cleaned_data['username'] = user.username
    else:
        raise forms.ValidationError(_("Incorrect email or password."))
    return cleaned_data

rawDescription: Overiding the auth module's AuthticationForm to allow logging in via email


rawDescription: how to custom format on print from a regex match using python

description: Custom format on print from a regex match using python


code: return int(float(value) / float(total) * 100.0)

rawDescription: pyschool is wrong ?

description: Pyschool is wrong


code:
import pygame, sys
from pygame.locals import *

TIMER = 30
SCREEN_X = 200
SCREEN_Y = 200

screen = pygame.display.set_mode((SCREEN_X, SCREEN_Y))
clock = pygame.time.Clock() #tick-tock

ending = button1 = button2 = False

corner1 = (28,18)  #Top Left corner of button 1
corner2 = (56,18)  #Top Left corner of button 2

image_length = 100 #length of the buttons
image_height = 100 #height of the buttons

counter = 0

#Main Loop:
while ending==False:
    counter+=1
    clock.tick(TIMER)
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                ending=True # Time to leave
                print("Game Stopped Early by user")
        elif event.type == MOUSEBUTTONDOWN:
            if event.button == 1:
                mouse_x, mouse_y = event.pos
                if (mouse_x >= corner1[0]) and (mouse_x <= corner1[0]+image_length) and (mouse_y >= corner1[1]) and (mouse_y <= corner1[1]+image_height):
                    print ("Button one is selected")
                    button1=True
                    button2=False
                elif (mouse_x >= corner2[0]) and (mouse_x <= corner2[0]+image_length) and (mouse_y >= corner2[1]) and (mouse_y <= corner2[1]+image_height):
                    print ("Button two is selected")
                    button1=False
                    button2=True
                else:
                    print ("That's not a button")
                    button1=False
                    button2=False
    if counter == TIMER:  #prints the statements once a second
        counter=0
        if button1==True:
            print ("Button one is currently selected")
        elif button2==True:
            print ("Button two is currently selected")
        else:
            print ("No buttons currently selected")

rawDescription: change image based on click in pygame

description: Change image based on click in pygame


code:
class FooMiddleware(object):
    def process_request(self, request):
        if request.user.is_authenticated():
            request.urlconf = 'myproject.authed_urls2'

rawDescription: Get http request data in Django Url Dispatcher? Is this possible? If so, how?


code:
def test(val1, val2):
    val1 = c_void_p(val1)
    val2 = c_void_p(val2)
    dll.test(byref(val1), byref(val2))

rawDescription: How to access a python variable's data inside a C function? (Argument type: void *)

description: Access a python variable's data inside a C function? (Argument type: void *)


code: a[i:j] = map(f, a[i:j])

rawDescription: Modifying list elements in a for loop

description: Modifying list elements in a for loop


code:
admin.py
class CustomUserCreationForm(UserCreationForm):
    """ A form for creating new users. Includes all the required fields, plus a repeated password. """
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password Confirmation', widget=forms.PasswordInput)

    class Meta(UserCreationForm.Meta):
        model = AuthUser
        fields = ('username', 'email', 'first_name', 'last_name', 'user_bio')

    def clean_username(self):
        username = self.cleaned_data["username"]

        try:
            AuthUser._default_manager.get(username=username)
        except AuthUser.DoesNotExist:
            return username
        raise forms.ValidationError(self.error_messages['duplicate_username'])

    def clean_password2(self):
        #Check that the two password entries match
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")

        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords do not match.")
        return password2

    def save(self, commit=True):
        #Save the provided password in hashed format
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class CustomUserChangeForm(UserChangeForm):
    password = ReadOnlyPasswordHashField(label="password",
                                         help_text="""Raw passwords are not stored, so there is no way to see this
                                         user's password, but you can change the password using
                                         this form.""")

    class Meta(UserChangeForm.Meta):
        model = AuthUser
        fields = ('username', 'email', 'password', 'is_active', 'is_staff', 'is_superuser', 'user_permissions')

    def clean_password(self):
        # Regardless of what the user provides, return the initial value.
        # This is done here, rather than on the field, because the
        # field does not have access to the initial value
        return self.initial["password"]

views.py
def CustomUserCreationView(request):
    if request.method == 'POST':
        form = CustomUserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect("/recipes/")
    else:
        form = CustomUserCreationForm()
    return render(request, 'recipes/signup.html',
                  {'form' : form})

rawDescription: Django user accounts: creating view from model


code:
import bpy

# data_path='location' with an index=1 is the y location curve
fc = bpy.context.object.animation_data.action.fcurves.find('location', index=1)

for m in bpy.context.scene.timeline_markers:
    nmod = fc.modifiers.new(type='NOISE')
    nmod.strength = 1.5
    nmod.use_restricted_range = True
    nmod.frame_start = m.frame
    nmod.frame_end = m.frame + 10

rawDescription: (Python) (Blender) How can I take the number of every frame on which there are markers?


code:
s = "elephant"
print (s.index("ph"))
3

if s[i] in l[currentchar:]: #Just checking if a string is in a string...
    currentchar = l[currentchar:].index(s[i])

rawDescription: How do I find which character "var in var" is in in python

description: Find which character "var in var" is in in python


code:
import time

a = 0
while True:
  a += 1
  print(a, flush=True)
  time.sleep(1)

rawDescription: Piping a Python script output continuosly to another program


code:
"this is a long sentence".split()
"this is a long sentence".split()[0]

rawDescription: square brackets after a function call

description: Square brackets after a function call


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

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.list = QtGui.QListWidget(self)
        self.button = QtGui.QPushButton('Choose Directory', self)
        self.button.clicked.connect(self.handleSetDirectory)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.list)
        layout.addWidget(self.button)
        self.watcher = QtCore.QFileSystemWatcher(self)
        self.watcher.directoryChanged.connect(self.handleDirectoryChanged)
        self.timer = QtCore.QTimer(self)
        self.timer.setInterval(500)
        self.timer.timeout.connect(self.handleTimer)
        self.handleSetDirectory(QtCore.QDir.tempPath())

    def handleDirectoryChanged(self):
        self.timer.stop()
        print('Directory Changed')
        self._changed = True
        self.timer.start()

    def handleSetDirectory(self, directory=None):
        if not directory:
            directory = QtGui.QFileDialog.getExistingDirectory(self)
        if directory:
            self.timer.stop()
            self.watcher.removePaths(self.watcher.directories())
            self._changed = False
            self.watcher.addPath(directory)
            self.updateList()
            self.timer.start()

    def handleTimer(self):
        if self._changed:
            self._changed = False
            self.updateList()

    def updateList(self):
        print('Update List')
        self.list.clear()
        for directory in self.watcher.directories():
            self.list.addItems(os.listdir(directory))

if __name__ == '__main__':

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

rawDescription: How to only emit one directoryChanged signal with QFileSystemWatcher

description: Only emit one directoryChanged signal with QFileSystemWatcher


code:
from twisted.internet import protocol, reactor
from twisted.protocols import basic

class SomeServerProtocol(basic.LineReceiver):
    def lineReceived(self, line):
        host, port = line.split()
        port = int(port)
        factory = protocol.ClientFactory()
        factory.protocol = SomeClientProtocol
        reactor.connectTCP(host, port, factory)

class SomeClientProtocol(basic.LineReceiver):
    def connectionMade(self):
        self.sendLine("Hello!")
        self.transport.loseConnection()

def main():
    import sys
    from twisted.python import log

    log.startLogging(sys.stdout)
    factory = protocol.ServerFactory()
    factory.protocol = SomeServerProtocol
    reactor.listenTCP(12345, factory)
    reactor.run()

if __name__ == '__main__':
    main()

rawDescription: How to write a twisted server that is also a client?

description: Write a twisted server that is also a client


code:
class App(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()

        box = Text(width=90, height=50)
        box.pack()     #instead of self.pack()

rawDescription: Why won't my text box show up in the GUI?


code:
for x in ['condition', 'model', 'color', 'mpg']:
    print(getattr(my_car, x))

rawDescription: Printing class variables with a for loop


rawDescription: Python - Pandas: Get a group of mean values of a daily range in a longer range period


code:
class Server(object):
    servers = []

    def __init__(self, name, host, port, pipe):
        self.name = name.lower()
        self.host, self.port = host, port
        self.pipe = pipe

    @staticmethod
    def register(server):
        Server.servers.append(server)

    @staticmethod
    def unregister(server):
        Server.servers.remove(server)

def start_waitress(host='0.0.0.0', port=8080):
    args = ['--port={}'.format(port),
         '--host={}'.format(host), 'yarr.wsgi:application']

    return subprocess.Popen(['waitress-serve'] + args)

...

host, port = '0.0.0.0', 8080
Server.register(Server('waitress', host, port, start_waitress()))

...

for server in Server.servers:
  if server.name == 'waitress':
      server.pipe.terminate()
      server.pipe.wait()
      Server.unregister(server)
      break

rawDescription: Can't terminate child process

description: Can't terminate child process


code:
from scipy.integrate import ode
obj = ode(lambda t, y: -y)
obj.set_initial_value(1)
while obj.t < 1:
    y_new = obj.integrate(1, step=True)
print(obj.t) # prints 1.037070648009345

rawDescription: Taking a single ODE step

description: Taking a single ODE step


code:
request_with_cookies = Request(url="http://www.example.com",
                           cookies={'currency': 'USD', 'country': 'UY'})

rawDescription: How to export a cookie in a file to use with python scrapy

description: Export a cookie in a file to use with python scrapy


code:
from Tkinter import *

root = Tk()
root.geometry("+1120+110") # x and y coordinates on a screen
root.mainloop()

rawDescription: Place on a determinated position of the screen : Tkinter


code:
import operator
d={'d':1,'b':2,'c':2,'a':3}
sorted(d.items(),key=operator.itemgetter(1,0))

rawDescription: Sorting the content of a dictionary by the value and by the key


code: max([option['type'] for option in programmes_by_type], key=len)

rawDescription: The list with most elements

description: The list with most elements


rawDescription: Optimizing a nested for loop

description: Optimizing a nested for loop


code:
#import modules
import random as randy
import numpy as np
import pandas as pd

#create sample dataset
idx=randy.sample(pd.date_range(start='1/1/2015',end='5/5/2015',freq='T'),2000)
idx.sort()
dfm=pd.DataFrame({'data':np.random.randint(0,2,len(idx))},index=idx)

#resample to fill in the gaps and groupby day of the week (0-6) and time
dfm=dfm.resample('T')
dfm=dfm.groupby([dfm.index.dayofweek,dfm.index.time]).count()

#Select monday (the '0th' day of the week)
dfm=dfm.loc[0]

#plot
dfm.plot(title="Number of observations on Mondays",figsize=[12,5])

rawDescription: Matplotlib: plot number of observations per minute across all Mondays in a year


code:
from collections import Counter
data = 3 * ('x ',  (1,), u'x')
[k for k, c in Counter(data).iteritems() if c > 1]

rawDescription: What is a good pythonic way of finding duplicate objects?


code:
def choose():
    with open('/usr/share/dict/words') as f:
        content = [line.strip() for line in f]

rawDescription: Where To Put str.strip

description: Where To Put str.strip


code: key = lambda x: sum(x[1])

rawDescription: Sort a dictionary by value(list) applying function to it


code:
def checkMargingForTheta(alpha, beta, theta):
    low = beta - alpha
    high = beta + alpha

    if(high > 2*pi):
        high = high - 2*pi
    if(low < 0):
        low = 2*pi + low
    if(low > high):
        return (theta > low)
    else:
        return (low < theta and high > theta)

rawDescription: Finding objects within specific angle from another object


code:
class B:
  def __init__(self, someinfo, a_instance):
    self.someinfo = someinfo
    self.a_instance = a_instance

  def send_message_to_a(self):
     self.a_instance.a_function(self.someinfo)

a = A()
bs = [B('hi', a) for i in range(random.randint(1, 10))]
for b in bs:
    b.send_message_to_a() # calls the a function passing someinfo

rawDescription: Sending information from one instance to another instance with a specific name in python


code:
browser.get("https://www.facebook.com/groups/GNexus5/")
import os
os.system("path_to_script.ahk/script.ahk")

rawDescription: How to open chrome developer console using Selenium in Python?

description: Open chrome developer console using Selenium in Python


code:
bases=['A','T','G','C']
k = 2
[''.join(p) for p in itertools.product(bases, repeat=k)]
k = 3
[''.join(p) for p in itertools.product(bases, repeat=k)]

rawDescription: Generating all DNA kmers with Python

description: Generating all DNA kmers with Python


code:
def update(self,walls):
    old_x = self.rect.x
    new_x = self.change_x + old_x
    old_y = self.rect.y
    new_y = self.change_y + old_y
    self.rect.x = new_x
    self.rect.y = new_y
    collide = pygame.sprite.spritecollide(self,walls,False)
    if collide:
            #Hit a wall go back to old position
            self.rect.x = old_x
            self.rect.y = old_y
    #updates location of x and y coordinates

rawDescription: Why isn't my collision detection working properly in pygame?


rawDescription: Calculations on Python lists?

description: Calculations on Python lists


code:
user = User.objects.get(username='their_username')
user.delete()

rawDescription: Simple way to delete users account?

description: Simple way to delete users account


code:
from django.db.models import Sum
my_plan.investment_set.filter(
    maturity_date__gte=whenever
).values('financial_institution').annotate(Sum('value'))

rawDescription: Using Django to summarize Report

description: Using Django to summarize Report


rawDescription: PYTHON how to make as many variables as needed


code:
special_operators = {'=': 'DEFINE',
                     '=>': 'PRODUCES'}

def t_OPERATOR(t):
    r'[<>=/*+-]+'
    t.type = special_operators.get(t.value, t.type)
    return t

rawDescription: special-case lexer rule in ply

description: Special-case lexer rule in ply


code:
@asyncio.coroutine
def do_work(envelope, body):
    yield from asyncio.sleep(int(body))
    print("consumer {} recved {} ({})".format(envelope.consumer_tag, body, envelope.delivery_tag))

@asyncio.coroutine
def callback(body, envelope, properties):
    loop = asyncio.get_event_loop()
    loop.create_task(do_work(envelope, body))

@asyncio.coroutine
def receive_log():
    try:
        transport, protocol = yield from aioamqp.connect('localhost', 5672, login="login", password="password")
    except:
        print("closed connections")
        return

    channel = yield from protocol.channel()
    exchange_name = 'cloudstack-events'
    exchange_name = 'test-async-exchange'
    queue_name = 'async-queue-%s' % random.randint(0, 10000)
    yield from channel.exchange(exchange_name, 'topic', auto_delete=True, passive=False, durable=False)
    yield from asyncio.wait_for(channel.queue(queue_name, durable=False, auto_delete=True), timeout=10)

    binding_keys = ['mykey']

    for binding_key in binding_keys:
        print("binding", binding_key)
        yield from asyncio.wait_for(channel.queue_bind(exchange_name=exchange_name,
                                                       queue_name=queue_name,
                                                       routing_key=binding_key), timeout=10)

    print(' [*] Waiting for logs. To exit press CTRL+C')
    yield from channel.basic_consume(queue_name, callback=callback)

loop = asyncio.get_event_loop()
loop.create_task(receive_log())
loop.run_forever()

rawDescription: Asynchronous RabbitMQ consumer with aioamqp


code:
class PopUpDLG(QtGui.QDialog):
    def __init__(self):
        super(PopUpDLG, self).__init__()
        self.setObjectName("self")
        self.resize(200, 71)
        self.setMinimumSize(QtCore.QSize(200, 71))
        self.setMaximumSize(QtCore.QSize(200, 71))
        self.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("Icons/Plus-32.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)
        self.gridLayout = QtGui.QGridLayout(self)
        self.gridLayout.setObjectName("gridLayout")
        self.text_link = QtGui.QLineEdit(self)
        self.text_link.setObjectName("text_link")
        self.gridLayout.addWidget(self.text_link, 0, 0, 1, 2)
        self.add_link = QtGui.QPushButton(self)
        self.add_link.setObjectName("add_link")
        self.gridLayout.addWidget(self.add_link, 1, 0, 1, 1)
        self.cancel_link = QtGui.QPushButton(self)
        self.cancel_link.setObjectName("cancel_link")
        self.gridLayout.addWidget(self.cancel_link, 1, 1, 1, 1)
        self.retranslateUi(self)
        self.cancel_link.clicked.connect(self.reject)
        self.add_link.clicked.connect(self.get_link)
        self.retrunVal = None

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("Dialog", "Add link"))
        self.add_link.setText(_translate("Dialog", "Add"))
        self.cancel_link.setText(_translate("Dialog", "Cancel"))

    def get_link(self):
        self.retrunVal = self.text_link.text()
        self.accept()

    def exec_(self):
        super(PopUpDLG, self).exec_()
        return self.retrunVal

class MainDialog(QtGui.QMainWindow):
    def __init__(self):
        super(self.__class__, self).__init__()
        centralwidget = QtGui.QWidget(self)
        self.layout = QtGui.QHBoxLayout(centralwidget)
        self.button = QtGui.QPushButton("Open")
        self.valText = QtGui.QLabel("")
        self.layout.addWidget(self.button)
        self.layout.addWidget(self.valText)
        self.setCentralWidget(centralwidget)
        self.button.clicked.connect(self.open_dialog)

    def open_dialog(self):
        dialog = PopUpDLG()
        value = dialog.exec_()
        if value:
            self.valText.setText(value)

def main():
     app = QtGui.QApplication(sys.argv)
     form = MainDialog()
     form.show()
     app.exec_()

if __name__ == '__main__':
     main()

rawDescription: Close and get data from a custom dialog PyQT5


code:
def generateTuples(N, M):
  done = 0
  counters = {}
  for C in range(3, N + 3):
    for B in range(2, C):
      for A in range(1, B):
        if (counters.get('A%i' % A, 0) < M and
            counters.get('B%i' % B, 0) < M and
            counters.get('C%i' % C, 0) < M):
          yield (A, B, C)
          counters['A%i' % A] = counters.get('A%i' % A, 0) + 1
          counters['B%i' % B] = counters.get('B%i' % B, 0) + 1
          counters['C%i' % C] = counters.get('C%i' % C, 0) + 1
          done += 1
          if done >= N:
            return

for (A, B, C) in generateTuples(8, 3):
  print (A, B, C)

rawDescription: Algorithm for generating list of unique tuples with specific properties


code:
if f.is_valid():
    for group in f.cleaned_data['group']:
        calentry.groups.add(group)

rawDescription: how can I save a form with ModelMultipleChoiceField?

description: Save a form with ModelMultipleChoiceField


code:
def weighted_avg_and_std(values, weights):
    """
    Return the weighted average and standard deviation.

    values, weights -- Numpy ndarrays with the same shape.
    """
    average = numpy.average(values, weights=weights)
    variance = numpy.average((values-average)**2, weights=weights)  # Fast and numerically precise
    return (average, math.sqrt(variance))

rawDescription: Weighted standard deviation in NumPy?

description: Weighted standard deviation in NumPy


code:
anArray = []
for i in range(0, 101, 1):
    z = float(i)/10
    #print "x: ", x
    y = 10 - z
    #print "y: ", y
    for a in range(0, 101, 1):
        anArray.append([float(a)/10, y, z])
    #endfor
#endfor
verts = np.array(anArray)
ax.plot(verts[:,0],verts[:,1],verts[:,2], zdir='y')

rawDescription: Matplotlib 2D polygon in 3D axes

description: Matplotlib 2D polygon in 3D axes


code:
for idx, val in enumerate(ints):
    print(idx, val)

rawDescription: Accessing the index in Python for loops

description: Accessing the index in Python for loops


rawDescription: How do I find the position of a value in a pandas.DataFrame?

description: Find the position of a value in a pandas.DataFrame


code:
container = wx.BoxSizer(wx.VERTICAL)
container.Add(self.nb, 1, wx.EXPAND)

login = wx.BoxSizer(wx.VERTICAL)
login.Add(self.userLabel)
login.Add(self.userText)

# ... clip, rest of login form additions here

bottom = wx.BoxSizer(wx.HORIZONTAL)
bottom.Add(image)
bottom.Add((0, 0), 1, wx.EXPAND)
bottom.Add(login)

container.Add(bottom, 1, wx.EXPAND)

rawDescription: Sizers... - wxPython

description: Sizers... - wxPython


code:
from datetime import datetime

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 17:31:22', fmt)

print (d2-d1).days * 24 * 60

rawDescription: python date difference in minutes

description: Python date difference in minutes


rawDescription: Is there a way to make rfind() case insensitive?


code:
def remove_adjacent(nums):
  removed_list = []
  numberHolder = None
  for number in nums:
    if number != numberHolder:
       removed_list.append(number)
       numberHolder = number
  return removed_list

rawDescription: Trouble with this Python newbie exercise. Using Lists and finding if two adjacent elements are the same


rawDescription: Is there a nice idiom for adding a new list or appending to a list (if present) in a dictionary?


code:
INPUT = 'file.txt'
OUTPUT = 'calc.txt'

def main():
    with open(INPUT, 'r') as reader, open(OUTPUT, 'a') as writer:
        last_value = 0
        for line in reader:
            column_1, *remaining_columns = map(float, line.split())
            column_2 = column_1 - last_value
            last_value = column_1
            print(column_1, column_2, sep='\t', file=writer)

if __name__ == '__main__':
    main()

rawDescription: Python - Calculating the second column from the first one in a file


code:
def none(*args):
    """Converts any arguments to None."""
    return None

rawDescription: Can I modify the type of an object in python

description: Modify the type of an object in python


code:
ax = df.plot(kind='bar',  title='Scores')
ax.set_ylim(0, 12)
for i, label in enumerate(list(df.index)):
    score = df.ix[label]['Score']
    ax.annotate(str(score), (i, score + 0.2))

rawDescription: Python pandas / matplotlib annotating labels above bar chart columns


code:
import jinja2
env = jinja2.Environment()
t = env.from_string('{{ codes.get(mycode) }}')
t.generate(codes={'a': '123'}, mycode='a').next()

rawDescription: How to get values from dictionary in jinja when key is a variable?

description: Get values from dictionary in jinja when key is a variable


code:
openSet   = set()
closedSet = set()

rawDescription: Python - Speed up an A Star Pathfinding Algorithm


code:
from ast import literal_eval
import numpy as np
s=u'[(12520, 12540), (16600, 16620)]'

arr= np.array(literal_eval(s))

rawDescription: convert unicode array to numpy

description: Convert unicode array to numpy


code:
def word_map(string):
    word_dict = {}
    for word in string.split():
        word = ''.join(filter(str.isalnum, word)).lower()
        if word.strip():
            if word in word_dict:
                word_dict[word] +=1
            else:
                word_dict[word] = 1
    return word_dict

rawDescription: Why does my word counter output the line ` 1`?


code: import matplotlib.pyplot as plt

rawDescription: Equal axis labels and ranges for all subplots


code:
from json import dumps
from sqlalchemy.orm import class_mapper

def serialize(model):
  """Transforms a model into a dictionary which can be dumped to JSON."""
  # first we get the names of all the columns on your model
  columns = [c.key for c in class_mapper(model.__class__).columns]
  # then we return their values in a dict
  return dict((c, getattr(model, c)) for c in columns)

# we can then use this for your particular example
serialized_labels = [
  serialize(label)
  for label in session.query(LabelsData).filter(LabelsData.deleted == False)
]
your_json = dumps(serialized_labels)

rawDescription: How to create sqlalchemy to json

description: Create sqlalchemy to json


code:
import json
import requests

adaccounts = [1337845464515, 13464645456566]
audienceid = ['6018213515', '601816526']

params = {adaccounts: json.dumps(adaccounts)}

for id_ in audienceid:
    url = 'https://graph.facebook.com/{}/adaccounts'.format(id_)
    response = requests.post(url, data=params)

rawDescription: how to make post requests using with list as parameters in python?

description: Make post requests using with list as parameters in python


code: df['beyer_shifted'] = df.groupby(level=0)['beyer'].shift(1); df

rawDescription: How do you shift Pandas DataFrame with a multiindex?

description: Shift Pandas DataFrame with a multiindex


code: version = func1() or func2()

rawDescription: how to use python's any

description: Use python's any


code:
class _DelegateIO(object):
    """This class defines an object that captures whatever is written to
    a stream or file.
    """

    def __init__(self, delegate):
        self._captured = StringIO()
        self.delegate = delegate

    def write(self, text):
        self._captured.write(text)
        self.delegate.write(text)

def _patch_standard_output(self):
        """Replaces stdout and stderr streams with string-based streams
        in order to capture the tests' output.
        """
        sys.stdout = _DelegateIO(sys.stdout)
        sys.stderr = _DelegateIO(sys.stderr)

rawDescription: Printing to stdout and XML file using Python unittest-xml-reporting


code:
def plot_countour(x,y,z):
    # define grid.
    xi = np.linspace(-2.1, 2.1, 100)
    yi = np.linspace(-2.1, 2.1, 100)
    ## grid the data.
    zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='cubic')
    levels = [0.2, 0.4, 0.6, 0.8, 1.0]
    # contour the gridded data, plotting dots at the randomly spaced data points.
    CS = plt.contour(xi,yi,zi,len(levels),linewidths=0.5,colors='k', levels=levels)
    #CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet)
    CS = plt.contourf(xi,yi,zi,len(levels),cmap=cm.Greys_r, levels=levels)
    plt.colorbar() # draw colorbar
    # plot data points.
    # plt.scatter(x, y, marker='o', c='b', s=5)
    plt.xlim(-2, 2)
    plt.ylim(-2, 2)
    plt.title('griddata test (%d points)' % npts)
    plt.show()

# make up some randomly distributed data
seed(1234)
npts = 1000
x = uniform(-2, 2, npts)
y = uniform(-2, 2, npts)
z = gauss(x, y, Sigma=np.asarray([[1.,.5],[0.5,1.]]), mu=np.asarray([0.,0.]))
plot_countour(x, y, z)

rawDescription: Matplotlib: Making 2D Gaussian contours with transparent outermost layer


code:
import maya.cmds as cmds
import glob

files = cmds.ls(type=["file", "imagePlane"])
result = []
for i in files:
    if cmds.objectType(i) == "file":
        #animated ?
        testAnimated = cmds.getAttr("{0}.useFrameExtension".format(i))
        if testAnimated:
            # Find the path
            fullpath= cmds.getAttr("{0}.fileTextureName".format(i))

            # Replace /path/img.padding.ext by /path/img.*.ext
            image = fullpath.split("/")[-1]
            imagePattern = image.split(".")
            imagePattern[1] = "*"
            imagePattern = ".".join(imagePattern)

            # You could have done a REGEX with re module with a pattern name.padding.ext
            # We join the path with \\ in order to be Linux/Windows/Apple format
            folderPath = "\\".join(fullpath.split("/")[:-1] + [imagePattern])

            # Find all image on disk
            result+=(glob.glob(folderPath))
        else:
            result.append(cmds.getAttr("{0}.fileTextureName".format(i)))
    elif cmds.objectType(i) == "imagePlane":
        #animated ?
        testAnimated = cmds.getAttr("{0}.useFrameExtension".format(i))
        if testAnimated:
            # Find the path
            fullpath= cmds.getAttr("{0}.imageName".format(i))
            # Replace /path/img.padding.ext by /path/img.*.ext
            image = fullpath.split("/")[-1]
            imagePattern = image.split(".")
            imagePattern[1] = "*"
            imagePattern = ".".join(imagePattern)

            # You could have done a REGEX with re module with a pattern name.padding.ext
            # We join the path with \\ in order to be Linux/Windows/Apple format
            folderPath = "\\".join(fullpath.split("/")[:-1] + [imagePattern])

            # Find all image on disk
            result+=(glob.glob(folderPath))
        else:
            result.append(cmds.getAttr("{0}.imageName".format(i)))
#clear multiple instance
result = list(set(result))

rawDescription: List all external assets in maya

description: List all external assets in maya


code:
"""Compare two sequences of strings.

Test data:
>>> from pprint import pprint
>>> delimiter = '||'
>>> expected = (
...     delimiter.join(("one", "fish", "two", "fish")),
...     delimiter.join(("red", "fish", "blue", "fish")),
...     delimiter.join(("I do not like them", "Sam I am")),
...     delimiter.join(("I do not like green eggs and ham.",)))
>>> actual = (
...     delimiter.join(("red", "fish", "blue", "fish")),
...     delimiter.join(("one", "fish", "two", "fish")),
...     delimiter.join(("I do not like spam", "Sam I am")),
...     delimiter.join(("I do not like", "green eggs and ham.")))

The results:
>>> pprint([analyze(v) for v in iter_delim_sets(delimiter, expected, actual)])
[DelimAnalysis(index=0, correct=2, incorrect=1, count_diff=0),
 DelimAnalysis(index=1, correct=2, incorrect=1, count_diff=0),
 DelimAnalysis(index=2, correct=1, incorrect=0, count_diff=0),
 DelimAnalysis(index=3, correct=0, incorrect=1, count_diff=1)]

What they mean:
>>> pprint(delim_analysis_doc)
(('index',
  ('The number of the lines from expected and actual',
   'used to perform this analysis.')),
 ('correct',
  ('The number of delimiter placements in ``actual``',
   'which were correctly placed.')),
 ('incorrect', ('The number of incorrect delimiters in ``actual``.',)),
 ('count_diff',
  ('The difference between the number of delimiters',
   'in ``expected`` and ``actual`` for this line.')))

And a trace of the processing stages:
>>> def dump_it(it):
...     '''Wraps an iterator in code that dumps its values to stdout.'''
...     for v in it:
...         print v
...         yield v

>>> for v in iter_delim_sets(delimiter,
...                          dump_it(expected), dump_it(actual)):
...     print v
...     print analyze(v)
...     print '======'
one||fish||two||fish
red||fish||blue||fish
DelimLocations(index=0, expected=set([9, 3, 14]), actual=set([9, 3, 15]))
DelimAnalysis(index=0, correct=2, incorrect=1, count_diff=0)
======
red||fish||blue||fish
one||fish||two||fish
DelimLocations(index=1, expected=set([9, 3, 15]), actual=set([9, 3, 14]))
DelimAnalysis(index=1, correct=2, incorrect=1, count_diff=0)
======
I do not like them||Sam I am
I do not like spam||Sam I am
DelimLocations(index=2, expected=set([18]), actual=set([18]))
DelimAnalysis(index=2, correct=1, incorrect=0, count_diff=0)
======
I do not like green eggs and ham.
I do not like||green eggs and ham.
DelimLocations(index=3, expected=set([]), actual=set([13]))
DelimAnalysis(index=3, correct=0, incorrect=1, count_diff=1)
======
"""
from collections import namedtuple

# Data types

## Here ``expected`` and ``actual`` are sets
DelimLocations = namedtuple('DelimLocations', 'index expected actual')

DelimAnalysis = namedtuple('DelimAnalysis',
                           'index correct incorrect count_diff')
## Explanation of the elements of DelimAnalysis.
## There's no real convenient way to add a docstring to a variable.
delim_analysis_doc = (
    ('index', ("The number of the lines from expected and actual",
               "used to perform this analysis.")),
    ('correct', ("The number of delimiter placements in ``actual``",
                 "which were correctly placed.")),
    ('incorrect', ("The number of incorrect delimiters in ``actual``.",)),
    ('count_diff', ("The difference between the number of delimiters",
                    "in ``expected`` and ``actual`` for this line.")))

# Actual functionality

def iter_delim_sets(delimiter, expected, actual):
    """Yields a DelimLocations tuple for each pair of strings.

    ``expected`` and ``actual`` are sequences of strings.
    """
    from re import escape, compile as compile_
    from itertools import count, izip
    index = count()

    re = compile_(escape(delimiter))
    def delimiter_locations(string):
        """Set of the locations of matches of ``re`` in ``string``."""
        return set(match.start() for match in re.finditer(string))

    string_pairs = izip(expected, actual)

    return (DelimLocations(index=index.next(),
                           expected=delimiter_locations(e),
                           actual=delimiter_locations(a))
            for e, a in string_pairs)

def analyze(locations):
    """Returns an analysis of a DelimLocations tuple.

    ``locations.expected`` and ``locations.actual`` are sets.
    """
    return DelimAnalysis(
        index=locations.index,
        correct=len(locations.expected & locations.actual),
        incorrect=len(locations.actual - locations.expected),
        count_diff=(len(locations.actual) - len(locations.expected)))

rawDescription: Python - Best way to compare two strings, record stats comparing serial position of particular item?


code:
d = {'key1': [1,2,3], 'key2': [1,2,6], 'key3': [1,2,3]}
d2 = {tuple(v): k for k, v in d.items()}  # exchange keys, values
d = {v: list(k) for k, v in d2.items()}   # exchange again
d

rawDescription: Python remove keys with the same value on a dictionary


code:
import lxml.html as lh
data = lh.parse('http://query.nictusa.com/cgi-bin/can_ind/2011_P80003338/1/A')
name = data.xpath('/html/body/table[2]/tr[5]/td[1]/a/text()')
name
name = data.xpath('//table[2]/*/td[1]/a/text()')
len(name)
name[499]

rawDescription: Scraping webdata from a website that loads data in a streaming fashion


rawDescription: Matplotlib: Assign Colors to Lines

description: Matplotlib: Assign Colors to Lines


code:
d = {}
val = 0
bigrams = [ ('wealth', 'gain'), ('gain', 'burnt'), ('burnt', 'will'), ('will', 'fire') ]
for word in bigrams:
    s = '-'.join(word)
    if s in d:
        d[s] += 1
    else:
        d[s] = val

rawDescription: how to insert values into a list in python.. with a few extra conditions

description: Insert values into a list in python.. with a few extra conditions


code:
cool = "Sam!"
'!' in cool
'?' in cool

rawDescription: Presence of a particular character in a string


rawDescription: Calculating minimum length among the lists inside a list


code: a = Arrow3D([0,1],[0,1],[0,1], mutation_scale=20, lw=1, arrowstyle="-|>", color="k", linestyle="dashed")

rawDescription: matplotlib Dashed arrow in 3D plots

description: Matplotlib Dashed arrow in 3D plots


code:
from __future__ import print_function

import random
import timeit

def test():
    randomize = [random.randint(0, 30) for y in range(50)]
    function1(randomize)

def function1(item):
    return sorted(item)  # something to do

timer = timeit.Timer('test()', setup='from __main__ import test')

print(timer.repeat(4, 200))

rawDescription: How to use setup with timeit in Python?

description: Use setup with timeit in Python


code:
import paramiko

def get_sftp():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('localhost', username='root', password='B4nan-purr(en)')
    return client

def test2():
    client = get_sftp()
    sftp = client.open_sftp()
    sftp.stat('/tmp')
    sftp.close()

if __name__ == "__main__":
    test2()

rawDescription: What is the difference between calling open_sftp() locally and via a separate function?


code:
class Database(object):

    def __init__(self, **kwargs):
        self.connect(**kwargs)

    def connect(self, **kwargs):
        pass

class Couch(Database):

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

    def connect(self, username=None, password=None):
        if username and password:
            # connect this way
            pass
        else:
            # connect that way
            pass

rawDescription: How to begin writing a python wrapper around another wrapper?

description: Begin writing a python wrapper around another wrapper


code:
for root, dirs, files in os.walk(apkLocation + apkFolder):
    for name in files:
        if name.endswith(("lib", ".so")):
            os.path.join(root, name)

rawDescription: Searching a directory for folders and files using python


rawDescription: How to unzip a list of tuples into individual lists?

description: Unzip a list of tuples into individual lists


code:
ids = {}
with open('/Users/Zebrafish/Desktop/ASHISH/IDs.txt') as f:
    for line in f:
       if len(line.strip()):
           # This makes sure you skip blank lines
           id,start,end = line.split('\t')
           ids[id] = (int(start),int(end))

# Here, I assume your `complete.txt` is a file with one long line.
with open('/Users/Zebrafish/Desktop/ASHISH/complete.txt') as f:
    sequence = f.readline()

# For each id, fetch the sequence "chunk:
for id,value in ids.iteritems():
    start, end = value
    print('{} {}'.format(id,sequence[start-1:end]))

rawDescription: how to retrieve string from a large file

description: Retrieve string from a large file


rawDescription: scrapy does not return text

description: Scrapy does not return text


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

wait = WebDriverWait(driver, 10)
wait.until(EC.text_to_be_present_in_element((By.XPATH, "/html/body/div[3]/h3/span"), ExpectedUTCMessage))

rawDescription: python selenium how best to detect blinking text?

description: Python selenium how best to detect blinking text


rawDescription: Pandas- Create a new column filled with the number of observations in another column


code: return Distance(inch=l)

rawDescription: return distance objects in Django

description: Return distance objects in Django


code:
a = "<some_tag>Characters_with_different_len_to_split</some_tag>"
re.sub(r'<[^<>]*>', '', a)

rawDescription: Splitting string from character to character


code:
import tkinter as tk

class FrameGroup(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.all_instances = []
        self.counter = 0

    def Add(self):
        self.counter += 1
        name = "Frame %s" % self.counter
        subframe = Subframe(self, name=name)
        subframe.pack(side="left", fill="y")
        self.all_instances.append(subframe)

    def Remove(self, instance):
        # don't allow the user to destroy the last item
        if len(self.all_instances) > 1:
            index = self.all_instances.index(instance)
            subframe = self.all_instances.pop(index)
            subframe.destroy()

    def HowMany(self):
        return len(self.all_instances)

    def ShowMe(self):
        for instance in self.all_instances:
            print(instance.get())

class Subframe(tk.Frame):
    def __init__(self, parent, name):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.e1 = tk.Entry(self)
        self.e2 = tk.Entry(self)
        self.e3 = tk.Entry(self)
        label = tk.Label(self, text=name, anchor="center")
        add_button = tk.Button(self, text="Add", command=self.parent.Add)
        remove_button = tk.Button(self, text="Remove", command=lambda: self.parent.Remove(self))

        label.pack(side="top", fill="x")
        self.e1.pack(side="top", fill="x")
        self.e2.pack(side="top", fill="x")
        self.e3.pack(side="top", fill="x")
        add_button.pack(side="top")
        remove_button.pack(side="top")

    def get(self):
        return (self.e1.get(), self.e2.get(), self.e3.get())

class GUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.master_frame = tk.Frame(self)
        self.master_frame.grid()
        self.all_instances = FrameGroup(self.master_frame)
        self.all_instances.grid()

        # create the first frame
        self.all_instances.Add()

root = GUI()
root.mainloop()

rawDescription: Adding and removing tkinter frames - keeping track of instances


code:
s = "Name: John Surname: Legend"
re.search('Name:\s+(.+)\sSurname:\s+(.+)',s).groups()
re.search('Name:\s+(.+)\sSurname:\s+(.+)',s).group(1)

rawDescription: Regex on Python 2.7 causing problems on finding text in a string


code: self.fp = sock.makefile("rb")

rawDescription: how do I read a socket stream dynamically with python

description: Read a socket stream dynamically with python


code:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import numpy as np
import cv2
import math

class Painter(object):
    def __init__(self, ax, img):
        self.showverts = True
        self.figure = plt.figure(1)
        self.button_pressed = False
        self.img = img
        self.brush_size = 50
        self.ax = ax
        self.color = 255

        canvas = self.figure.canvas
        canvas.mpl_connect('button_press_event', self.button_press_callback)
        canvas.mpl_connect('button_release_event', self.button_release_callback)
        canvas.mpl_connect('motion_notify_event', self.on_move)

    def button_press_callback(self, event):
        if(event.button == 1):
            self.button_pressed = True
            x = int(math.floor(event.xdata))
            y = int(math.floor(event.ydata))
            cv2.circle(self.img, (x, y), int(self.brush_size / 2), (self.color, self.color, self.color), -1)
            #update the image

    def button_release_callback(self, event):
        self.button_pressed = False
        self.ax.images.pop()
        self.ax.imshow(self.img, interpolation='nearest', alpha=0.6)
        plt.draw()
        cv2.imwrite('test.png', self.img)

    def on_move(self, event):
        if(self.button_pressed):
            x = int(math.floor(event.xdata))
            y = int(math.floor(event.ydata))
            cv2.circle(self.img, (x, y), int(self.brush_size / 2), (self.color, self.color, self.color), -1)
            #update the image

def draw_demo():
    global imgMain
    imgOver = np.zeros((717,1465,3), np.uint8)
    imgMain = mpimg.imread('zebra.png')
    #imgMain = np.random.uniform(0, 255, size=(500, 500))

    ax = plt.subplot(111)
    ax.imshow(imgMain, interpolation='nearest', alpha=1)
    ax.imshow(imgOver, interpolation='nearest', alpha=0.6)

    pntr = Painter(ax, imgOver)
    plt.title('Click on the image to draw')
    plt.show()

if __name__ == '__main__':
    draw_demo()

rawDescription: Drawing on image with matplotlib and opencv2, update image?


code: form = JobRecordForm( {'supervisor':request.user} )

rawDescription: Django Forms, set an initial value to request.user


code:
class StaticContentHandler(webapp.RequestHandler):
  def output_content(self, content, serve=True):
    self.response.headers['Content-Type'] = content.content_type
    last_modified = content.last_modified.strftime(HTTP_DATE_FMT)
    self.response.headers['Last-Modified'] = last_modified
    self.response.headers['ETag'] = '"%s"' % (content.etag,)
    if serve:
      self.response.out.write(content.body)
    else:
      self.response.set_status(304)

  def get(self, path):
    content = get(path)
    if not content:
      self.error(404)
      return

    serve = True
    if 'If-Modified-Since' in self.request.headers:
      last_seen = datetime.datetime.strptime(
          self.request.headers['If-Modified-Since'],
          HTTP_DATE_FMT)
      if last_seen >= content.last_modified.replace(microsecond=0):
        serve = False
    if 'If-None-Match' in self.request.headers:
      etags = [x.strip('" ')
               for x in self.request.headers['If-None-Match'].split(',')]
      if content.etag in etags:
        serve = False
    self.output_content(content, serve)

rawDescription: Send a "304 Not Modified" for images stored in the datastore


rawDescription: How to convert list to multiline string?

description: Convert list to multiline string


code:
import abc
from Queue import Empty, Queue
from threading import Thread

class AbstractTask(object):
    """
        The base task
    """
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def run_task(self):
        pass

class TaskRunner(object):

    def __init__(self, queue_size, num_threads=1, stop_on_exception=False):
        super(TaskRunner, self).__init__()
        self.queue              = Queue(queue_size)
        self.execute_tasks      = True
        self.stop_on_exception  = stop_on_exception

        # create a worker
        def _worker():
            while self.execute_tasks:

                # get a task
                task = None
                try:
                    task = self.queue.get(False, 1)
                except Empty:
                    continue

                # execute the task
                failed = True
                try:
                    task.run_task()
                    failed = False
                finally:
                    if failed and self.stop_on_exception:
                        print('Stopping due to exception')
                        self.execute_tasks = False
                    self.queue.task_done()

        # start threads
        for i in range(0, int(num_threads)):
            t = Thread(target=_worker)
            t.daemon = True
            t.start()

    def add_task(self, task, block=True, timeout=None):
        """
            Adds a task
        """
        if not self.execute_tasks:
            raise Exception('TaskRunner is not accepting tasks')
        self.queue.put(task, block, timeout)

    def wait_for_tasks(self):
        """
            Waits for tasks to complete
        """
        if not self.execute_tasks:
            raise Exception('TaskRunner is not accepting tasks')
        self.queue.join()

rawDescription: Can't get multiprocessing to run processes concurrently


code:
if datetime.datetime.now().hour >= 17:
    pass

rawDescription: Python After 5:00pm

description: Python After 5:00pm


code: emails = FieldList(StringField('email'), min_entries=1, max_entries=5)

rawDescription: WTForms - POSTing text fields to an array


code:
from xml.etree import ElementTree

doc = ElementTree.fromstring(xmlstring)
for tag in doc.findall('.//text'):
  print(tag.text)

rawDescription: How to print only certain xml elements

description: Print only certain xml elements


code:
import random

num = 100
prob_a = 0.6
prob_b = 0.3
prob_c = 0.1

As = int(num*prob_a) * 'A'
Bs = int(num*prob_b) * 'B'
Cs = int(num*prob_c) * 'C'

# create a list with 60 As, 30 Bs, and 10 Cs
chars = list(As + Bs + Cs)
random.shuffle(chars)

print("".join(chars))

rawDescription: Random non-uniform distribution with given proportion


rawDescription: Python regex

description: Python regex


code:
import threading
import time

def cold_temp():
    # Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before.
    with open("/sys/bus/w1/devices/28-021571bf69ff/w1_slave") as tfile:
        # skip first line, keep second line
        next(tfile)
        secondline = next(tfile)
    # Split the line into words, referring to the spaces, and select the 10th word (counting from 0).
    temperaturedata = secondline.split(" ")[9]
    # The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
    temperature = float(temperaturedata[2:])
    # Put the decimal point in the right place and display it.
    temperature = temperature / 1000
    return temperature

while True:
    output = cold_temp()
    with open('/var/www/html/coldtemp.html', 'w') as f:
        print >> f, output
    time.sleep(1)

rawDescription: Python not running every second

description: Python not running every second


code:
from django.db import transaction

def myview(request):
    #Some Code
    with transaction.atomic():
             a.save()
             b.save()
             c.save()

rawDescription: Django View : Either save(update) all objects or None of them


code:
import chardet
from lxml import html
content = urllib2.urlopen(url).read()
encoding = chardet.detect(content)['encoding']
if encoding != 'utf-8':
    content = content.decode(encoding, 'replace').encode('utf-8')
doc = html.fromstring(content, base_url=url)

rawDescription: Encoding in python with lxml - complex solution


code:
for i in a:
    if i[0] in (j[0] for j in b):
        print("{} {}".format(i[1],i[2]))

rawDescription: Check if list element in list is in another list in list in Python


code:
import readline

def completer(text, state):
    options = [i for i in commands if i.startswith(text)]
    if state < len(options):
        return options[state]
    else:
        return None

readline.parse_and_bind("tab: complete")
readline.set_completer(completer)

rawDescription: How to make a python, command-line program autocomplete arbitrary things NOT interpreter

description: Make a python, command-line program autocomplete arbitrary things NOT interpreter


code:
indices = [index for index, i in enumerate(m) if i == 4]
h = [d[i][0] for i in indices]

rawDescription: Python - Acquire value from dictionary depending on location/index in list


code: ['%s:%d' % (e, i) for e in mylist for i in (1, 2)]

rawDescription: Applying constants in list comprehension


code:
import re
s = 'habcabcabcj'
re.findall(r'(?:abc)+', s)

rawDescription: How to match sequential string in text using regular expression?

description: Match sequential string in text using regular expression


code:
payload = {}
payload['factory_id'] = "XXXX-YYYYY"
payload['name'] = "Dance Room"
payload['latitude'] = XX.XXXXXX
payload['longitude'] = YY.YYYYYY
payload['config_id'] = abcd
payload['visibility'] = "private"

data = json.dumps(payload)

rawDescription: ModelForm data to JSON String

description: ModelForm data to JSON String


code:
import re
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(my_html)
nodes_to_censor = soup.findAll(text=re.compile('.*SECRET.*'))
for node in nodes_to_censor:
    node.replaceWith('###')

rawDescription: python : Replacing a HTML element depending on its content

description: Python : Replacing a HTML element depending on its content


code:
result=[]
for item in POINTS:
    res=DISTANCE(*item)
    result.append(res)
print(sum(result))

rawDescription: How to use the values of a list that is inside another list as arguments of a function in Python

description: Use the values of a list that is inside another list as arguments of a function in Python


code:
from astropy.table import Table
tab = Table.read('file.tex')

rawDescription: Reading a LaTex table into an array in Python


code:
def f(result):
  return (dict((symbols[abs(lit) - 1], lit > 0) for lit in sol) for sol in result)

rawDescription: Return an iterator after modification

description: Return an iterator after modification


code:
col = collections.LineCollection(nlist,
   linewidths = width,
   linestyle = lstyle,
   alpha=self.alpha,zorder=100)

rawDescription: How to format contour lines from Matplotlib

description: Format contour lines from Matplotlib


code:
from django.template.defaultfilters import date as _date
from datetime import datetime

_date(datetime.now(), "d b, D")

rawDescription: Localized date strftime in Django view

description: Localized date strftime in Django view


code:
from django.db.models import FloatField, ExpressionWrapper, F

template = '%(function)s(%(expressions)s AS FLOAT)'
fv1 =  Func(F('value1'), function='CAST', template=template)
fv2 =  Func(F('value2'), function='CAST', template=template)
ew = ExpressionWrapper(fv1/fv2, output_field = FloatField())

q = MyModel.objects.order_by('-value1').annotate(res = ew)

rawDescription: Django F() division - How to avoid rounding off


code:
def verify_fonts_are_installed_for_statements():
    import subprocess
    from os import path
    potential_locations = [
        '/usr/bin/fc-list',
        '/usr/sbin/fc-list',
        '/usr/local/sbin/fc-list',
        '/usr/local/bin/fc-list',
    ]
    valid_path = None
    for file_path in potential_locations:
        if path.exists(file_path):
            valid_path = file_path
            break
    if valid_path is None:
        raise IOError('could not find fc-list to verify fonts exist.')

    cmd = [valid_path]
    output = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]

    if 'Helvetica Neue' not in output:
        raise FontNotInstalledException('Helvetica Neue')
    if 'Courier' not in output:
        raise FontNotInstalledException('Courier')

    log.debug('Courier and Helvetica Neue were found to be installed.')

rawDescription: Using tkFont from tkinter to identify if a font (Helvetica-Light) is available/installed


code:
for i in range(326):
    for j in range(898):
        for k in range(31):
            j_dis=((lat[i+1,j]-lat[i,j])*1852.)/(1/60.) #distance from i to i+1 in meters
            i_dis=((lon[i,j+1]-lon[i,j])*1852.)/(1/60.) #distance from i to i+1 in meters
            z_dis=(zz[k+1,i,j]-zz[k,i,j])
        # Volume
        vol[k,i,j]=i_dis*j_dis*z_dis

rawDescription: calculating a variable using loop over a multdimensional array python

description: Calculating a variable using loop over a multdimensional array python


code:
import subprocess

cmd = "security unlock-keychain -p".split()
cmd += [keychain_password, path_to_keychain]
subprocess.call(cmd)

rawDescription: Unlock the key-chain in mac through python


rawDescription: Can you get the selected leaf from a DecisionTreeRegressor in scikit-learn

description: Get the selected leaf from a DecisionTreeRegressor in scikit-learn


code:
import os
import csv

csvfile = open('outputFileName.csv', 'wb')
writer = csv.writer(csvfile)

for filename in os.listdir('/'): # or C:\\ if on Windows
    writer.writerow([filename, len(filename)])

csvfile.close()

rawDescription: writing .csv files from for loops and lists

description: Writing .csv files from for loops and lists


code:
def __iadd__(self, other):
    self.number += other.number
    return self

rawDescription: Overriding "+=" in Python? (__iadd__() method)


code:
from django.core.exceptions import ValidationError

# extend the validation
def clean(self):
    # run the base validation
    super(YOUR_CLASS_NAME, self).clean(*args, **kwargs)

    # Don't allow dates older than now.
    if self.start_time < datetime.datetime.now():
        raise ValidationError('Start time must be later than now.')

rawDescription: Set minimum value for a DateTimeField

description: Set minimum value for a DateTimeField


code:
from recaptcha.client import captcha

if req.method == 'POST':
    response = captcha.submit(
        req.args['recaptcha_challenge_field'],
        req.args['recaptcha_response_field'],
        self.private_key,
        req.remote_addr,
        )
    if not response.is_valid:
        say_captcha_is_invalid()
    else:
        do_something_useful()
else:
    data['recaptcha_javascript'] = captcha.displayhtml(self.public_key)
    data['recaptcha_theme'] = self.theme
    return 'recaptchaticket.html', data, n

rawDescription: How to use Python plugin reCaptcha client for validation?

description: Use Python plugin reCaptcha client for validation


code:
textdel = u'\u00FE'
len(textdel)                      # -> 1
type(textdel)                     # -> unicode
len(textdel.encode('utf-16-le'))  # -> 2
type(textdel.encode('utf-16-le')) # -> str

rawDescription: Writing to UTF-16-LE text file with BOM

description: Writing to UTF-16-LE text file with BOM


code:
import turtle
import Tkinter as tk

def keypress(event):
    global xx, canvas, t, speed
    ev = event.keysym
    if ev == 'Left':
        xx += speed
    else:
        xx -= speed

    canvas.place(x=xx)
    t.setposition((-canvas.winfo_width() / 4) - (xx + 250), 0)
    return None

def drawCircle(_):
    global t
    t.pendown()
    t.fillcolor(0, 0, 1.0)
    t.fill(True)
    t.circle(100)
    t.fill(False)
    t.fillcolor(0, 1, 0)
    t.penup()

# Set the main window
window = tk.Tk()
window.geometry('500x500')
window.resizable(False, False)

# Create the canvas. Width is larger than window
canvas = turtle.Canvas(window, width=2000, height=500)
xx = -500
canvas.place(x=xx, y=0)

# Bring the turtle
t = turtle.RawTurtle(canvas)
t.shape('turtle')  # nicer look
t.speed(0)
t.penup()
t.setposition((-canvas.winfo_width() / 4) - (xx + 250), 0)

# key binding
window.bind('<KeyPress-Left>', keypress)
window.bind('<KeyPress-Right>', keypress)
window.bind('<KeyPress-space>', drawCircle)

drawCircle(None)
speed = 3  # scrolling speed
window.mainloop()

rawDescription: Changing canvas scroll region on Python turtle canvas


rawDescription: How can I separate list from list in python?

description: Separate list from list in python


code:
import re
with open("C:\\Users\\Suleiman JK\\Desktop\\test\\Hello.pdf","rb") as fh:
    stuff = fh.read()
stuff = re.sub("#(..)", lambda match: chr(int(match.group(1), 16)), stuff)
with open("C:\\Users\\Suleiman JK\\Desktop\\test\\Hello.pdf","wb") as fh:
    fh.write(stuff)

rawDescription: using Python to modify in PDF files

description: Using Python to modify in PDF files


code:
import pylab as plt
import numpy as np

# Read image from disk and filter all grayscale
im = plt.imread("14154233_input.png")[:,:,:3]
im -= im.mean(axis=2).reshape(im.shape[0], im.shape[1], 1).repeat(3,axis=2)
im_maxnorm = im.max(axis=2)

# Find y-position of remaining line
ypos = np.ones((im.shape[1])) * np.nan
for i in range(im_maxnorm.shape[1]):
    if im_maxnorm[:,i].max()<0.01:
        continue
    ypos[i] = np.argmax(im_maxnorm[:,i])

# Pick only values that are set
ys = 1-ypos[np.isfinite(ypos)]
# Normalize to 0,1
ys -= ys.min()
ys /= ys.max()

# Create x values
xs = np.linspace(0,1,ys.shape[0])

# Create plot of both
# read and filtered image and
# data extracted
plt.figure(figsize=(4,8))
plt.subplot(211)
plt.imshow(im_maxnorm)
plt.subplot(212, aspect="equal")
plt.plot(xs,ys)
plt.show()

rawDescription: image analysis curve fitting

description: Image analysis curve fitting


code:
from backend import db
from werkzeug.security import generate_password_hash, check_password_hash

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)
    password_hash = db.Column(db.String(120))
    handle = db.Column(db.String(120))
    type_user = db.Column(db.String(50))
    display_pic = db.Column(db.String(100))
    posts = db.relationship('Post', backref='user', lazy='dynamic')

    def __init__(self, handle, email, raw_password):
        self.handle = handle
        self.email = email
        # Save the hashed password
        self.set_password(raw_password)

    def __repr__(self):
        return '<User %r>' % self.username

    def set_password(self, raw_password):
        self.password_hash = generate_password_hash(raw_password)

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    likes = db.Column(db.Integer)
    body = db.Column(db.Text)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

rawDescription: Flask migrate ignoring foreign key

description: Flask migrate ignoring foreign key


code:
import urllib2

def download(link, filename):
  try:
    req=urllib2.urlopen(link)
  except urllib2.HTTPError:
    pass
  if req.has_data():
    open(filename,"wb").write(req.get_data())

#here goes your function that loops over
uri="http://example.com/"
for x in xrange(1, 101):
  download(uri+str(x), str(x))

rawDescription: Downloading a list of files from a website


code:
from myapp.forms import MyCustomFormField

#create a custom model field
class EditAreaField(models.TextField):
  def formfield(self, **kwargs):
    defaults={'form_class': MyCustomFormField}#pass our custom field as form_class
    defaults.update(kwargs)
    super (EditAreaField, self).formfield(**defaults)

rawDescription: When is the formfield() method called in Django?


code: subprocess.call(['/usr/texbin/pdflatex', filename], shell = False)

rawDescription: dropbox Unicode Encoding Conflict

description: Dropbox Unicode Encoding Conflict


code:
f = open("myfile.csv", 'r')
data = f.read().split('\n') #separates the contents into lines with while leaving out the newline characters
myDict = {}
for x in range(len(data)):
    data[x] = data[x].split(',') #makes each line a list of variables. If the data is contain extra white spaces use the strip() method
    myDict[data[x][0]] = (data[x][1], data[x][2]) #this will make the dictionary like you described in the question

rawDescription: How to extract contents of a csv file and place them in a dict file type without using csv module. [python]

description: Extract contents of a csv file and place them in a dict file type without using csv module. [python]


code:
from taggit.models import TaggedItem
related_items = TaggedItem.objects.none()
for tag in current_item.tags.all():
    #build queryset of all TaggedItems
    related_items |= tag.taggit_taggeditem_items.all()

#TaggedItem doesn't have a direct link to the object, have to grab ids
ids = related_items.values_list('object_id', flat=True)
return Item.objects.filter(id__in=ids, sites=current_site).exclude(id=item.id).order_by('-publish_date')[:3]

rawDescription: django taggit similar_objects very slow query

description: Django taggit similar_objects very slow query


code:
html_sidebars = {'**[!i][!n][!d][!e][!x]': ['non-index-sidebar.html'],
                 '**index': ['index-sidebar.html'],
}

rawDescription: Mapping custom sidebar template to any document named "index.rst"


code:
data = pl.loadtxt("20100101.txt")
density = data[:,0]
for i in range(1, 1001):
    densities = np.random.normal(loc=density, scale=30)
    np.savetxt(str(i) + '.txt', densities)

rawDescription: How to produce multiple output files with a single input file using the command 'np.random.normal'?

description: Produce multiple output files with a single input file using the command 'np.random.normal'


code:
import numpy as np
from scipy import ndimage
from matplotlib import pyplot as plt

# generate some lowpass-filtered noise as a test image
gen = np.random.RandomState(0)
img = gen.poisson(2, size=(512, 512))
img = ndimage.gaussian_filter(img.astype(np.double), (30, 30))
img -= img.min()
img /= img.max()

# use a boolean condition to find where pixel values are > 0.75
blobs = img > 0.75

# label connected regions that satisfy this condition
labels, nlabels = ndimage.label(blobs)

# find their centres of mass. in this case I'm weighting by the pixel values in
# `img`, but you could also pass the boolean values in `blobs` to compute the
# unweighted centroids.
r, c = np.vstack(ndimage.center_of_mass(img, labels, np.arange(nlabels) + 1)).T

# find their distances from the top-left corner
d = np.sqrt(r*r + c*c)

# plot
fig, ax = plt.subplots(1, 2, sharex=True, sharey=True, figsize=(10, 5))
ax[0].imshow(img)
ax[1].hold(True)
ax[1].imshow(np.ma.masked_array(labels, ~blobs), cmap=plt.cm.rainbow)
for ri, ci, di in zip(r, c, d):
    ax[1].annotate('', xy=(0, 0), xytext=(ci, ri),
                   arrowprops={'arrowstyle':'<-', 'shrinkA':0})
    ax[1].annotate('d=%.1f' % di, xy=(ci, ri),  xytext=(0, -5),
                   textcoords='offset points', ha='center', va='top',
                   fontsize='x-large')
for aa in ax.flat:
    aa.set_axis_off()
fig.tight_layout()
plt.show()

rawDescription: How to locate a particular "region" of values in a 2D numpy array?

description: Locate a particular "region" of values in a 2D numpy array


code:
my_session = dryscrape.Session(base_url = 'https://stackoverflow.com')
my_session.set_proxy('127.0.0.1', 9000)

rawDescription: How to set proxy To hide my IP address for scraping the webpage using dryscrape

description: Set proxy To hide my IP address for scraping the webpage using dryscrape


code:
dan = 'dan|warrior|54'
dan.split('|')[1]

rawDescription: Splitting strings using a delimiter in python


rawDescription: Multivariate Root Finding in Python

description: Multivariate Root Finding in Python


rawDescription: String to binary python

description: String to binary python


code:
from tkinter import *
import threading

class MyApp:
    def __init__(self, root):
        self.root = root
        self.timer_evt = threading.Event()
        cf = Frame(root, borderwidth=1, relief="raised")
        cf.pack()
        Button(cf, text="Run", command=self.Run).pack(fill=X)
        Button(cf, text="Pause", command=self.Pause).pack(fill=X)
        Button(cf, text="Kill", command=self.Kill).pack(fill=X)

    def process_stuff(self):        # processing threads
        while self.go:
            print("Spam... ")
            self.timer_evt.wait()
            self.timer_evt.clear()

    def Run(self):                  # start another thread
        self.go = 1
        threading.Thread(target=self.process_stuff, name="_proc").start()
        self.root.after(0, self.tick)

    def Pause(self):
        self.go = 0

    def Kill(self):                 # wake threads up so they can die
        self.go = 0
        self.timer_evt.set()

    def tick(self):
        if self.go:
            self.timer_evt.set()    # unblock processing threads
            self.root.after(1000, self.tick)

def main():
    root = Tk()
    root.title("ProcessingThread")
    app = MyApp(root)
    root.mainloop()

main()

rawDescription: Working the function in the background - how? Python and PyQT


code:
with open('somefile.txt', 'w') as f:
    for k in keys:
        print>>f, '%s' % (d[k]),
    print>>f, ""

rawDescription: Convert print followed by comma into writelines in python


code:
mystr = "I like Python!!!"
[c for c in mystr if c != " "]
[c for c in mystr if not c.isspace()] # alternately

rawDescription: How can I make a list from the string

description: Make a list from the string


code:
from selenium.webdriver.common.by import By

trs = driver.find_elements(By.TAG_NAME, "tr")

tds = trs[1].find_elements(By.TAG_NAME, "td")

rawDescription: Iterate through table in Selenium 2 WebDriver (python)