code:
from scrapy.http import Request
from scrapy.item import Item, Field
from scrapy.selector import HtmlXPathSelector
from scrapy.spider import BaseSpider

class VoucherItem(Item):
    voucher_id = Field()
    code = Field()

class CuponationSpider(BaseSpider):
    name = "cuponation"
    allowed_domains = ["cuponation.in"]
    start_urls = ["https://www.cuponation.in/babyoye-coupons"]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)

        crawled_items = hxs.select('//div[@class="six columns voucher-btn"]/a')
        for button in crawled_items:
            voucher_id = button.select('@data-voucher-id').extract()[0]

            item = VoucherItem()
            item['voucher_id'] = voucher_id
            request = Request("https://www.cuponation.in/clickout/index/id/%s" % voucher_id,
                              callback=self.parse_code,
                              meta={'item': item})
            yield request

    def parse_code(self, response):
        hxs = HtmlXPathSelector(response)

        item = response.meta['item']
        item['code'] = hxs.select('//div[@class="code-field"]/span/text()').extract()

        return item

rawDescription: How to scrape coupon code of coupon site (coupon code comes on clicking button)

description: Scrape coupon code of coupon site (coupon code comes on clicking button)


code:
divisors = np.power(0.01, np.arange(number_of_cols-1, -1, -1))
x = np.mod(np.floor(divisors*codes.reshape((codes.shape[0], 1))), 100)

rawDescription: Converting an array to a float, how to reverse the process?


code: ((1 in i) and (2 in i))

rawDescription: or statement in list python 3

description: Or statement in list python 3


code:
def get_coords():
    while True:
        s = input("Enter coordinates (x y z): ")
        try:
            x, y, z = map(float, s.split())
        except ValueError: # wrong number or can't be floats
            print("Invalid input format.")
        else:
            return x, y, z

rawDescription: create python list of exactly three elements

description: Create python list of exactly three elements


rawDescription: How to send a file through Soap in python?

description: Send a file through Soap in python


code:
mydict = {'Car':'BMW','Speed':'kph','Range':33}
from itertools import islice
def take(n, iterable):
    return list(islice(iterable, n))

n_items = take(2, mydict.iteritems())
print(n_items)

rawDescription: Return only a few keys in a dictionary? Python


code:
date_str = '2015-01-01'
dt = pytz.timezone('Europe/London').localize(dateutil.parser.parse(date_str))

rawDescription: How to convert date string to a datetime object in a specified timezone

description: Convert date string to a datetime object in a specified timezone


code:
from julia import Julia
j = Julia()
arr = j.run('[1:10]')
type(arr) # numpy.ndarray

rawDescription: Best way to run Julia code in an IPython notebook (or Python code in an IJulia notebook)

description: Run Julia code in an IPython notebook (or Python code in an IJulia notebook)


code:
import random
from easygui import *

def rollDice(): # simulate a dice roll
    return random.randrange(1,7) + random.randrange(1,7)

def craps(): # roll dice and evaluate results
    firstRoll= rollDice()
    if firstRoll in (7,11):
        return 1 # initial winning condition
    if firstRoll in (2,3,12):
        return 0 #initial losing condition

    while True:
        newRoll = rollDice()
        if newRoll == firstRoll:
            return 1 #secondary winning condition
        if newRoll == 7:
            return 0 #secondary losing condition

ans = boolbox("Would you like to play Craps?")
while ans == True:
    result = craps()
    string = ""
    if( result == 1 ):
        string += ("WIN!")
    else:
        string += ("LOSS!")
    msgbox(string)
    ans = boolbox("Would you like to play Craps?")

rawDescription: Craps simulator on python

description: Craps simulator on python


code:
class SVN_Path(Form):
    prev_svn_url=StringField('Previous SVN_Path',[validators.URL()])
    new_svn_url=StringField('New SVN_Path',[validators.URL()])

rawDescription: Submit Button Confusion and Request being sent Twice (Using Flask)


code:
#!/usr/bin/env python

def readdata(filename):
    last = []
    count = 0

    with open(filename, "r") as fd:
        for line in fd:
            tokens = line.strip().split()
            tokens[2] = int(tokens[2])

            if not last:
                last = tokens

            if tokens[:2] != last[:2]:
                yield last[:2], count or 1, last[2]
                last = tokens
                count = 1
            else:
                count += 1

            tokens[2] = min(tokens[2], last[2])

        yield last[:2], count, last[2]

with open("output.txt", "w") as fd:
    for words, count, year in readdata("data.txt"):
        fd.write(
            "{0:s} {1:s} ({2:d} {3:d})\n".format(
                words[0], words[1], count, year
            )
        )

rawDescription: Count duplicate pairs in file with constraint


code:
# do this once, outside the loop
alphabet=set(string.ascii_lowercase)
# inside the loop, just 1 line:
missingletter=(alphabet-set(yourlist)).pop()

rawDescription: python: finding a missing letter in the alphabet from a list - least lines of code

description: Python: finding a missing letter in the alphabet from a list - least lines of code


code: ['image1.png', 'image2.png', 'image3.png', 'image3.jpg']

rawDescription: compare two lists of files, ignoring file extension in one list

description: Compare two lists of files, ignoring file extension in one list


code: from scipy.special import expit

rawDescription: Numpy Pure Functions for performance, caching


rawDescription: How to filter a list based on another list's values

description: Filter a list based on another list's values


code: unicode_truncate(u'абвгд', 5)

rawDescription: Truncating unicode so it fits a maximum size when encoded for wire transfer


code:
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
s = Serializer('sekrit', expires_in=3600)
token = s.dumps({'id': 'foobar'})
token
s.loads(token)
s = Serializer('sekrit', expires_in=0)
token = s.dumps({'id': 'foobar'})
token
s.loads(token)

rawDescription: python: API token generation with itsdangerous

description: Python: API token generation with itsdangerous


code:
a = [[279, 629, 590], [382, 825, 279], [629, 569, 113], [382, 785, 296]]
from collections import defaultdict
elements = defaultdict(list)
for row_index in range(len(a)):
    for col_index in range(len(a[row_index])):
        elements[a[row_index][col_index]].append([row_index, col_index])

rawDescription: Index duplicates in a multidimensional array


code:
df1.loc[0] = pd.DataFrame(s).T.loc['A']
df1
df = pd.DataFrame([[1,2],[3,4]],columns=['A','B'])
df
df1 = pd.DataFrame(index = np.arange(0,1),columns = s.index)
df1
s = df['A']
df1.loc[0] = pd.DataFrame(s).T
df1.loc[0] = pd.DataFrame(s).T.loc['A']
df1

rawDescription: ValueError when adding row to Dataframe

description: ValueError when adding row to Dataframe


code:
list1 = list_of_list[0]
list2 = list_of_list[1]
list3 = list_of_list[2]

rawDescription: Python: How do I make n new lists from n inputs?


code:
top2_by_date = df.groupby('date').apply(lambda x:  x.sort('size', ascending=False).head(2))
top2_by_date

rawDescription: Trying to create a stacked bar chart of the top 10 issues per month


code:
unique_key_dict = {}
for date in file_dict:
  for key in file_dict[date]:
    if key not in unique_key_dict: unique_key_dict[key] = {}
    if date not in unique_key_dict[key]: unique_key_dict[key][date] = []
    unique_key_dict[key][date].append(file_dict[date][key])

rawDescription: How to change dictionary from one format into another?

description: Change dictionary from one format into another


code: final = [(y, x.lower()) for x, y in a]

rawDescription: Python list comprehension. Alternative/Better way to write this code?


code:
import numpy as np

def line_tuple(filename,cols=(0,1)):
    return np.loadtxt(filename,usecols=cols,unpack=True)

#parse each line from the datafile into a tuple of the form (xvals,yvals)
#store that tuple in a list.
data = [line_tuple(fname) for fname in ("line1.txt","line2.txt","line3.txt","line4.txt","line5.txt")]

#This is the minimum and maximum from all the datapoints.
xmin = min(line[0].min() for line in data)
xmax = max(line[0].max() for line in data)

#100 points evenly spaced along the x axis
x_points = np.linspace(xmin,xmax,100)

#interpolate your values to the evenly spaced points.
interpolated = [np.interp(x_points,d[0],d[1]) for d in data]

#Now do the averaging.
averages = [np.average(x) for x in zip(*interpolated)]

#put the average value along with it's x point into a file.
with open('outfile','w') as fout:
    for x,avg in zip(x_points,averages):
        fout.write('{0} {1}\n'.format(x,avg))

rawDescription: Plotting an 'average' graph of 5 graphs

description: Plotting an 'average' graph of 5 graphs


code:
from Tkinter import *

root = Tk()

choices = ['GB', 'MB', 'KB']
variable = StringVar(root)
variable.set('GB')

w = OptionMenu(root, variable, *choices)
w.pack(); root.mainloop()

rawDescription: Tkinter: How to create choice box

description: Tkinter: How to create choice box


code:
for key1,key2 in itertools.combinations(d,2):
    compare(d[key1],d[key2])

rawDescription: Compare a dictionary to itself in Python


code:
import numpy as np
import matplotlib.pyplot as plt
from moviepy.video.io.bindings import mplfig_to_npimage
import moviepy.editor as mpy

fig = plt.figure(facecolor="white") # <- ADDED FACECOLOR FOR WHITE BACKGROUND
ax = plt.axes()
x = np.random.randn(10, 1)
y = np.random.randn(10, 1)
p = plt.plot(x, y, 'ko')
time = np.arange(2341973, 2342373)

last_i = None
last_frame = None

def animate(t):
    global last_i, last_frame

    i = int(t)
    if i == last_i:
        return last_frame

    xn = x + np.sin(2 * np.pi * time[i] / 10.0)
    yn = y + np.cos(2 * np.pi * time[i] / 8.0)
    p[0].set_data(xn, yn)

    last_i = i
    last_frame = mplfig_to_npimage(fig)
    return last_frame

duration = len(time)
fps = 15
animation = mpy.VideoClip(animate, duration=duration)
animation.write_videofile("test.mp4", fps=fps)

rawDescription: Difficulty animating a matplotlib graph with moviepy


rawDescription: Finding minimum value element-wise in three 2d submatrices


rawDescription: Converting one string to a int in a list


code:
for item in data['members'][0]:
    print(item['member_amt_pledged'])
    print(item['member_amt_recvd'])
    print(item['member_id'])
    print(item['name'])

rawDescription: Retrieving items from a dictionary data type created from a JSON request


rawDescription: Python String to hex

description: Python String to hex


code:
for row in iter(cursor.fetchone, None):
    process(row)

rawDescription: How to use Python list comprehension (or such) for retrieving rows when using MySQLdb?

description: Use Python list comprehension (or such) for retrieving rows when using MySQLdb


rawDescription: replace more than one pattern python

description: Replace more than one pattern python


code:
l = ['ttyUSB0', 'ttyUSB1', 'ttyUSB2', 'ttyUSB3', 'ttyUSB4', 'ttyUSB5', 'ttyUSB6', 'ttyUSB7', 'ttyUSB8']
l[1::3]

rawDescription: Separate list in equal steps

description: Separate list in equal steps


code:
import collections
import itertools

s1 = set(['asd', '123', 'uniq','all'])
s2 = set(['asd', '123', 'all'])
s3 = set(['asd', 'all'])
s4 = set(['all'])

l = [s1, s2, s3, s4]
nrof_lists = len(l)

result = {k : v*1.0/nrof_lists for k, v in collections.Counter(itertools.chain.from_iterable(l)).items()}

print(result)
{'uniq': 0.25, 'all': 1.0, '123': 0.5, 'asd': 0.75}

rawDescription: Combining boolean operators

description: Combining boolean operators


code: from sqlalchemy.types import Binary

rawDescription: Storing UUIDs in sqlite using Pylons and SQLalchemy


code:
import ast
ast.literal_eval("[{u'f1': 1000, u'f2': 500}]")

rawDescription: how to pandas parse json that was previously saved

description: Pandas parse json that was previously saved


code: urlencode(items)

rawDescription: Escaping string in Python

description: Escaping string in Python


code:
import os
from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference('network.proxy.Kind','Direct')
webdriver.Firefox(profile)

rawDescription: Setting default setting to 'no proxy' in Selenium Firefox


code:
class MapFilter:
    def __init__(self, aiterable, p, func):
        self.aiterable = aiterable
        self.p = p
        self.func = func

    async def __aiter__(self):
        return self

    async def __anext__(self):
        while True:
            payload = await self.aiterable.__anext__()  # StopAsyncIteration would be raise here on no new values
            if self.p(payload):
                return self.func(payload)

rawDescription: how can I asynchronously map/filter an asynchronous iterable?

description: Asynchronously map/filter an asynchronous iterable


code:
def updatesdisplay(root, t=0):
    def _updatesdisplay(func):
        def driver(iterator):
            try: next(iterator)
            except StopIteration: pass
            else:
                if t: root.after(t, driver, iterator)
                else: root.after_idle(driver, iterator)
        def wrapped():
            driver(func())
        return wrapped
    return _updatesdisplay

@updatesdisplay(master, 100) # 100 because we want to slow things down a bit
def f():
    for i in range (0,numLights):
        renderGUI(a)
        yield # window gets updated here
        for n in range(0,numLights):
            if a[n]>1:
                a[n] = a[n]-1
            elif a[n] == 1:
                    #then its about to become nought, right?
                    a[n-1] = speed[n]
                    speed[n-1] = speed[n]
                    a[n] = a[n]-1
                    continue
            continue

btn = Button(master, text='Stop', width=20, command=master.destroy)
btn.pack()
master.after(1, f)
master.mainloop()

rawDescription: Tkinter need to update canvas mid process. It only updates when finished


code:
s = "this is a sample string that I want to highlight using my filter"
l = ['sam', 'ring']
re.sub('(?i)(' + '|'.join(map(re.escape, l)) + ')', r'<mark>\1</mark>', s)

rawDescription: python replace multiple words retaining case

description: Python replace multiple words retaining case


code:
from __future__ import print_function

# ...

for line in lines:
    print(line, end='')

rawDescription: In Python how can I print the rows in my text file in a random order?


code:
test = StringVar()
eBox = Entry(self, textvariable=test)

rawDescription: Store data from Entry widget tkinter

description: Store data from Entry widget tkinter


code:
mu, sigma = 0, 500

x = np.arange(1,100,0.1) # x axis
z = np.random.normal(mu, sigma, len(x)) # noise
y = x ** 2 + z # data
plt.plot(x, y, linewidth=2, linestyle="-", c="b") # it include some noise

rawDescription: Reducing noise on Data

description: Reducing noise on Data


code:
import multiprocessing.pool as mpool

def worker(target, isbn):
    return target(isbn)

def amazon(isbn):
    ...

def bookadda(isbn):
    ...

def infibeam(isbn):
    #b_price and b_avail are obtained from some where else
    return [b_price, b_avail]

pool = mpool.ThreadPool()
isbn = str(9789382711056)
args = [(target, isbn) for target in (amazon,bookadda,infibeam)]
result = pool.map(worker, args)

rawDescription: Distinguishing the return values from threads when a queue is used


code:
var = 'puppy'
var.index('p')

rawDescription: Replacing every instance of a character in Python string


code:
mylist = []
while 1:
    mylist.append(raw_input(': '))
    if mylist[-1] == '': break

rawDescription: PYTHON - Add on to list

description: PYTHON - Add on to list


rawDescription: Removing repeated characters from a list in python


code: my_string = my_string[-x:] + my_string[:-x]

rawDescription: Python - How to move characters in string by X amount


code: d = dict((y,x) for x,y in enumerate(t))

rawDescription: pythonic way to associate list elements with their indices

description: Pythonic way to associate list elements with their indices


code:
def IdSet(self, value):
    if not isinstance(value, basestring):
        raise TypeError('ID must be a string.')
    self.caseful_id = value
    self.UpdateFromKey(ndb.Key(self.__class__, value.lower()))

rawDescription: Making id case-insensitive but case-preserving in endpoints-proto-datastore


code: variable = value

rawDescription: invalid syntax, how to fix?

description: Invalid syntax, how to fix


rawDescription: Two assignments in single python list comprehension


code:
import re

input_list = ['Lo']
converted_list = [re.compile(q, re.I) for q in input_list]

print(Blah.objects(__raw__={"someList": {"$all": converted_list}}).count())

rawDescription: Mongoengine - using icontains with all

description: Mongoengine - using icontains with all


code:
import Tkinter as tk

def configure_ok_button(event):
    content = event.widget.get(1.0, "end-1c")
    state = "active" if content else "disabled"
    button.configure(state=state)

root = tk.Tk()
text = tk.Text(root)
button = tk.Button(root, text="Ok", state="disabled")
text.bind("<KeyRelease>", configure_ok_button)
text.pack()
button.pack()
root.mainloop()

rawDescription: Validation on Tkinter.Text widget?

description: Validation on Tkinter.Text widget


code:
li = soup.select_one("li.hover.propertyCard.property-data-elem.clickable")
lat, lon = li.select_one("meta[itemprop=latitude]")["content"], li.select_one("meta[itemprop=longitude]")["content"]
print(lat,lon)

rawDescription: get attribute value BeautifulSoup

description: Get attribute value BeautifulSoup


rawDescription: re match a pattern

description: Re match a pattern


code:
import urllib2
import csv
from bs4 import BeautifulSoup
from multiprocessing.dummy import Pool  # This is a thread-based Pool
from multiprocessing import cpu_count

def crawlToCSV(URLrecord):
    OpenSomeSiteURL = urllib2.urlopen(URLrecord)
    Soup_SomeSite = BeautifulSoup(OpenSomeSiteURL, "lxml")
    OpenSomeSiteURL.close()

    tbodyTags = Soup_SomeSite.find("tbody")
    trTags = tbodyTags.find_all("tr", class_="result-item ")

    placeHolder = []

    for trTag in trTags:
        tdTags = trTag.find("td", class_="result-value")
        tdTags_string = tdTags.string
        placeHolder.append(tdTags_string)

    return placeHolder

if __name__ == "__main__":
    fileName = "SomeSiteValidURLs.csv"
    pool = Pool(cpu_count() * 2)  # Creates a Pool with cpu_count * 2 threads.
    with open(FileName, "rb") as f:
        results = pool.map(crawlToCSV, f)  # results is a list of all the placeHolder lists returned from each call to crawlToCSV
    with open("Output.csv", "ab") as f:
        writeFile = csv.writer(f)
        for result in results:
            writeFile.writerow(result)

rawDescription: Multithreading in Python/BeautifulSoup scraping doesn't speed up at all


code: store = pd.HDFStore('test.h5')

rawDescription: Is it possible to directly rename pandas dataframe's columns stored in hdf5 file?


code:
params = ["%s"] * len(field_values)         # create a list with the correct number of parameter markers
sql = "insert into %s (%s) values (%s)" % ( # here we're using string interpolation, but not with the values
    configData["table"],
    sqlFieldMappingString,
    ', '.join(params)
)

rawDescription: How to handle apostrophes in MySQL-Python?

description: Handle apostrophes in MySQL-Python


code:
from django.shortcuts import render
from django.http import HttpResponse

from myapp.myclasses import Alphabet  #<*** Import your class.
from django.template import RequestContext, loader  #<*** Import stuff for the template.

# Create your views here.

def index(request):
    alph = Alphabet()
    result = alph.change('hello')  #Your class produces some result here.

    template = loader.get_template("myapp/index.html")
    context = RequestContext(request, {
        'x' : result   #<*** Make a variable named x available in your template.
    })

    return HttpResponse(template.render(context))

rawDescription: Where to implement python classes in Django?


code:
from inspect import signature
list(signature(c.f).parameters)

rawDescription: Is there a way to get function parameter names, including bound-methods excluding `self`?


code:
x = [1,2,3,4]
lis = [ item for item in y if item not in x]
x.extend(lis)
x

rawDescription: Appending new values to a python list

description: Appending new values to a python list


code:
fig, ax = plt.subplots()

ax.plot(var.index.to_datetime(), var.total, 'b', label='Variance')
ax.set_ylabel('Variance of log wages')

ax2 = ax.twinx()
ax2.plot(shares.index.to_datetime(), shares.average, 'g' , label='Average Age')
ax2.set_ylabel('Average age')

lines = ax.get_lines() + ax2.get_lines()
ax.legend(lines, [line.get_label() for line in lines], loc='upper center')

ax.set_title('Wage Variance and Mean Age')
plt.show()

rawDescription: Legend only shows one label when plotting with pandas


code:
dic={gene:{iso:exon} for gene, iso, exon in zip(Genes, Isoforms, ExonPos)}
dic

rawDescription: Nested dictionary - python

description: Nested dictionary - python


code:
from itertools import izip
powers = [1, 2, 3]
numbers = (n**p for n, p in izip(base, powers) if p != 0)
reduce(mul, numbers , 1)

rawDescription: Python: optimizing the product of a chain of factor-to-the-nth if n is not zero


rawDescription: Looking for a replacement for i18ndude, or an improved version


rawDescription: Summation of every row, column and diagonal in a 3x3 matrix numpy


code:
class x(float):
    def __new__(cls, value, prec=6):
        self = float.__new__(cls, value)
        self.prec = prec
        return self

    def __str__(self):
        return "{:.{}e}".format(self, self.prec)

print (float(101))  # 101.0
print (x(101))      # 1.010000e+02
print (x(101, 2))   # 1.01e+02

rawDescription: in Python 3, how to create a number-like object?

description: In Python 3, how to create a number-like object


code:
mask_idx = ~((cdist(pairs.reshape(-1,3),positions)==0).any(1).reshape(-1,2).all(1))
out = pairs[mask_idx]

rawDescription: Efficient Python implementation of numpy array comparisons


code: age = df.groupby("age")

rawDescription: Quick way to find all permutations of a pandas DataFrame that preserves a sort?


code:
for line in f:
  line = re.compile('[\W_]+') # overwrites the line you just read??
  line.sub('', string.printable)

rawDescription: Extract specific lines from file and create sections of data in python


code:
{ "keys": ["alt+s"], "command": "toggle_in_selection", "context":
    [
        { "key": "setting.is_widget", "operator": "equal", "operand": true }
    ]
},

rawDescription: Expand multiple selection to all suggestions (boxes,hints) in Sublime Text 2


code:
def not_a_float(s):
    try:
        float(s)
        return False
    except:
        return True

res = filter(not_a_float, ["word", '2.134123'])

rawDescription: Why doesn't this Python code remove a digit from a list?


code:
import tempfile
import joblib
memory = joblib.Memory(cachedir=tempfile.mkdtemp(), verbose=0)
@memory.cache
def run(x):
    print('called with {}'.format(x))  # for debug
    return x
run(1)
run(2)
run(3)
run(2)  # Cached
run.call(2)  # Force call of the original function

rawDescription: Selective Re-Memoization of DataFrames

description: Selective Re-Memoization of DataFrames


code:
import keyword
keyword.iskeyword("in")
keyword.kwlist

rawDescription: How to check if a string is a valid python identifier? including keyword check?

description: Check if a string is a valid python identifier? including keyword check


code:
sublime = subprocess.POpen(['sublime'], stdout=subprocess.PIPE, stdin=subprocess.PIPE)
data = open("foo.txt", 'rb').read()
out, err = sublime.communicate(data)

rawDescription: Why does cat works and file open object doesn't?


code:
from itertools import product
list(product([0,1,5], repeat=2))
list(product([2,3], repeat=3))

rawDescription: how to permute n elements from list recursively in python?

description: Permute n elements from list recursively in python


rawDescription: Alternative to python's .sort() (for inserting into a large list and keeping it sorted)


code:
#! /usr/bin/python3.2

pages_id_list = [ (22, 4),(45,1),(1,1), (4,4),(566,45),(7,7),(783,566), (66,1),(300,8),(8,4),(101,7),(80,22), (17,17),(911,66) ]

class Node:
    def __init__ (self, article):
        self.article = article
        self.children = []
        self.parent = None

    def print (self, level = 0):
        print ('{}{}'.format ('\t' * level, self.article) )
        for child in self.children: child.print (level + 1)

class Tree:
    def __init__ (self): self.nodes = {}

    def push (self, item):
        article, parent = item
        if parent not in self.nodes: self.nodes [parent] = Node (parent)
        if article not in self.nodes: self.nodes [article] = Node (article)
        if parent == article: return
        self.nodes [article].parent = self.nodes [parent]
        self.nodes [parent].children.append (self.nodes [article] )

    @property
    def roots (self): return (x for x in self.nodes.values () if not x.parent)

t = Tree ()
for i in pages_id_list: t.push (i)
for node in t.roots: node.print ()

rawDescription: Sorting data hierarchically

description: Sorting data hierarchically


code:
tb_items = Table('items', meta,
        Column('id', Integer, primary_key=True),
        Column('name', String(20)),
        Column('description', String(100)),
    )
tb_notes = Table('notes', meta,
        Column('id_item', Integer, ForeignKey('items.id'), primary_key=True),
        Column('name', String(20), primary_key=True),
        Column('value', String(100)),
    )
meta.create_all()

rawDescription: SQLAlchemy - Dictionary of tags

description: SQLAlchemy - Dictionary of tags


code:
from MySQLdb.cursors import DictCursor
MySQLconnection = MySQLdb.connect(host=cherrypy.request.app.config['Database']['host'],
                                  passwd=cherrypy.request.app.config['Database']['passwd'],
                                  db=cherrypy.request.app.config['Database']['db'],
                                  user=cherrypy.request.app.config['Database']['user'],
                                  port=cherrypy.request.app.config['Database']['port'],
                                  cursorclass=DictCursor)
MySQLcursor = MySQLconnection.cursor()

rawDescription: how to set up config file to access mysql database parameter

description: Set up config file to access mysql database parameter


code:
import json
with open('input.json') as inf, \
     open('output.json', 'w') as outf:
    init_data = json.load(inf)
    appData = init_data['appData']
    for key in appData:
        abc = appData[key]['ABC']
        for subkeys in abc:
            if subkeys in ['condition', 'decision']:
                abc[subkeys] = abc[subkeys]['$numberLong']
            if subkeys in ['trackeddata', 'iconData']:
                for element in abc[subkeys]:
                    element['timestamp'] = element['timestamp']['$numberLong']
    json.dump(init_data, outf)

rawDescription: Change json object data by reference in Python


rawDescription: How to get ordered dictionaries in pymongo?

description: Get ordered dictionaries in pymongo


code:
response = urllib2.urlopen(URL)
data = json.load(response)

rawDescription: What is recommended way to store dictionaries and json file type in python


code:
import sys
import time
import getpass
import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('127.0.0.1',
            username='apsuser',
            password=getpass.getpass('Password: '))
shell = ssh.invoke_shell()
shell.settimeout(0.25)

shell.send('picocom /dev/ttyS0\n')
time.sleep(2)
sys.stdout.buffer.write(shell.recv(10000))
sys.stdout.buffer.flush()

shell.send('\x01')
shell.send('\x11')

time.sleep(2)
sys.stdout.buffer.write(shell.recv(10000))
sys.stdout.buffer.flush()
print()
time.sleep(2)

rawDescription: Python send control + Q then control + A (special keys)


code: weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']

rawDescription: In Python i need a day_name function

description: In Python i need a day_name function


code: datapoints = json1_data['datapoints']

rawDescription: Converting JSON String to Dictionary, Not List (Python)


code:
while True:
    tmp = operation(tmp)
    iterations += 1

    if tmp == origin_matrix:
        break  # Or you could return here.

rawDescription: how to determine the period of a function

description: Determine the period of a function


code:
better = lambda x, y: x if sum (x) > sum (y) else y

def subsets_with_sum(lst, target, with_replacement=False):

    x = 0 if with_replacement else 1
    def _a(idx, l, r, t):
        if t >= sum(l):
            r = better (r, l)
            for u in range(idx, len(lst)):
                r = better (r, _a(u + x, l + [lst[u]], r, t))
        return r
    return _a(0, [], [], target)

rawDescription: Finding largest numbers that go into target leaving smallest remainder


code: photo = ImageTk.PhotoImage(img)

rawDescription: How do I save an image in python 3 using PIL?

description: Save an image in python 3 using PIL


rawDescription: General Ledger Concurrency (django atomic operations)


code:
def nonScript(tag):
    return tag.name != 'script'

def getStrings(root):
   for s in root.childGenerator():
     if hasattr(s, 'name'):    # then it's a tag
       if s.name == 'script':  # skip it!
         continue
       for x in getStrings(s): yield x
     else:                     # it's a string!
       yield s

rawDescription: Extracting readable text from HTML using Python?


code:
import sys
import functools
from optparse import OptionParser

bad_option = 'BAD OPTION'

def store(option, opt, value, parser, dest, val):
    """Set option's destination *dest* to *val*  if there are no conflicting options."""
    list_name = dest + '_options_list'
    try:
        # if this option is a conflict, save its name and set the value to bad_option
        getattr(parser.values, list_name).append(opt)
        setattr(parser.values, dest, bad_option)
    except AttributeError:
        # no conflicts, set the option value and add the options list
        setattr(parser.values, dest, val)
        setattr(parser.values, list_name, [opt])

store_true = functools.partial(store, val=True)
store_false = functools.partial(store, val=False)

parser = OptionParser()
parser.add_option('-v', '--verbose',
                  action='callback', callback=store_true,
                  help='Increase output verbosity',
                  callback_kwargs={'dest': 'verbose'})

parser.add_option('-q', '--quiet',
                  action='callback', callback=store_false,
                  help='Decrease output verbosity',
                  callback_kwargs={'dest': 'verbose'})

opts, args = parser.parse_args()

# detects all conflicting options for all destinations
found = False
for dest in ('verbose',):
    if getattr(opts, dest) == bad_option:
        conflicting_opts = ', '.join(getattr(opts, dest + '_options_list'))
        print('Conflicting options %s for destination %s'
              % (conflicting_opts, dest))
        found = True

if found:
    parser.print_usage()
    sys.exit(2)

rawDescription: Detecting if any command-line options were specified more than once with optparse or argparse


code: line.replace(':',',').replace(' ','')

rawDescription: Python: Split, strip, and join in one line


code:
def is_printable(data):
    return all(c in string.printable for c in data)

rawDescription: How to detect undecoded characters in python?

description: Detect undecoded characters in python


rawDescription: get escaped unicode code from string

description: Get escaped unicode code from string


code:
class number:
    def __init__(self, number):
        self.number = number
    @property
    def double(self):
        return self.number * 2

print(number(42).double) # 84

rawDescription: Python - How use properties without creating an object


code:
fivehundreds = 0
while 500 <= amount:
    amount -= 500
    fivehundreds += 1
print("500 USD x", fivehundreds)

twohundreds = 0
while 200 <= amount:
    amount -= 200
    twohundreds += 1
print("200 USD x", twohundreds)

onehundreds = 0
while 100 <= amount:
    amount -= 100
    onehundreds += 1
print("100 USD x", onehundreds)

rawDescription: All cash change is only for one bill

description: All cash change is only for one bill


code:
import re
s="I liiiiked it, thaaaaaaank you"
re.sub(r"(.)(\1{3})(\1+)", r"\1\2", s)

rawDescription: How to reduce the duplicated characters in a string using Python

description: Reduce the duplicated characters in a string using Python


code:
coords_sorted_by_x = sorted(coords,key=lambda c:c[0])
[(3, 1, 2), (7, 8, 1), (9, 5, 1)]
coords_sorted_by_y = sorted(coords,key=lambda c:c[1])
[(3, 1, 2), (9, 5, 1), (7, 8, 1)]
coords_sorted_by_z = sorted(coords,key=lambda c:c[2])
[(9, 5, 1), (7, 8, 1), (3, 1, 2)]

rawDescription: how to sort the following

description: Sort the following


code:
df
#     Value2  Value
#Name
#A         x    8.8
#B         y    6.6
#A         x    6.6
#A         x    8.8

df.reset_index(inplace=True)
#  Name Value2  Value
#0    A      x    8.8
#1    B      y    6.6
#2    A      x    6.6
#3    A      x    8.8

rawDescription: Pandas DataFrame - Combining one column's values with same index into list


rawDescription: plotting imshow and line plot together in python

description: Plotting imshow and line plot together in python


code:
DONT_RESOLVE_DLL_REFERENCES         = 0x00000001
LOAD_LIBRARY_AS_DATAFILE            = 0x00000002
LOAD_WITH_ALTERED_SEARCH_PATH       = 0x00000008
LOAD_IGNORE_CODE_AUTHZ_LEVEL        = 0x00000010  # NT 6.1
LOAD_LIBRARY_AS_IMAGE_RESOURCE      = 0x00000020  # NT 6.0
LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE  = 0x00000040  # NT 6.0

# These cannot be combined with LOAD_WITH_ALTERED_SEARCH_PATH.
# Install update KB2533623 for NT 6.0 & 6.1.
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR    = 0x00000100
LOAD_LIBRARY_SEARCH_APPLICATION_DIR = 0x00000200
LOAD_LIBRARY_SEARCH_USER_DIRS       = 0x00000400
LOAD_LIBRARY_SEARCH_SYSTEM32        = 0x00000800
LOAD_LIBRARY_SEARCH_DEFAULT_DIRS    = 0x00001000

rawDescription: Python | accessing dll using ctypes

description: Python | accessing dll using ctypes


code: fracs = {str(Fraction(x, y)) for x, y in zip(ilist1, ilist2)}

rawDescription: How to make a character in a list appear only once?

description: Make a character in a list appear only once


code:
y=[]
for i in range(4):
    y.append(np.arange(i,2*i))

rawDescription: Simpler code to combine multiple lists into one array? I actually wish "lists" are still "lists" in that array


rawDescription: last_login field is not updated when authenticating using Tokenauthentication in Django Rest Framework

description: Last_login field is not updated when authenticating using Tokenauthentication in Django Rest Framework


code:
@stopper
def fetch_one(n):
    lst = [[1,2,3], [4,5,6], [7,8,9]][n]
    #lst = [[1,2,3], [], [4,5,6], [7,8,9]][n]   # uncomment to test for/else
    for x in lst:
        yield x

def work():
    n = 0
    while not fetch_one.finished:
        for x in fetch_one(n):
            print('x =', x)
        n += 1

rawDescription: What do you call an iterator with two different "done" states?


code:
from itertools import product
reel = list(range(1, 11))
for i in product(zip(reel, reel[1:], reel[2:]), repeat=3):
    print(i)

rawDescription: Python algorithm to sequentially generate all possible outcomes of slot machine


code:
from sparse_list import SparseList
from random import randint

class RandomSparseList(SparseList):
    def __init__(self, size, min_bits, max_bits):
        super(RandomSparseList, self).__init__(size, 0)
        self.bits = randint(min_bits, max_bits)
        while self.bits > len(self.elements):
            self.elements[randint(0, self.size)] = 1

rawDescription: Populating a sparse list with random 1's


code:
class BreedSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Breed

class DogSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Dog

    breed = HybridPrimaryKeyRelatedField(queryset=Breed.objects,
                                         view_name='breed-detail')

rawDescription: Create resource via POST specifying related field ID


rawDescription: Python Nested lists and iteration

description: Python Nested lists and iteration


rawDescription: Using a Python dict to replace/clean data in a Pandas DataFrame


code:
from StringIO import StringIO
import pandas as pd
data = '''A, 1, 2013-10-10, .5
A, 1, 2013-10-18, .75
A, 2, 2013-10-20, 2.5
B, 1, 2013-10-09, .25
B, 2, 2014-10-20, .8'''

df = pd.read_csv(StringIO(data), names=['person','itemCode','transDate','amount'], skiprows=0)
df
grouped = df.groupby(['person'])
res = df.groupby(['person']).apply(lambda x: pd.Series(x.groupby('itemCode').sum()['amount']))
res

rawDescription: Transformation of transactions to numpy array


code:
ld = [{'prop': 'foo', 'size': 100}, {'prop': 'boo', 'size': 200}]
max(xrange(len(ld)), key=lambda index: ld[index]['size'])
ld[1]

rawDescription: Python list of dicts, get max value index


code:
z.swapaxes(1,2).ravel()
desired.ravel()

rawDescription: numpy reshaping multdimensional array through arbitrary axis

description: Numpy reshaping multdimensional array through arbitrary axis


code:
d = {"a": {"b": {"c": 4}}}
l = ["a", "b", "c"]
from operator import getitem
reduce(getitem, l, d)

rawDescription: Any Functional Programming method of traversing a nested dictionary?


code:
def autoScroll(self):
    QtCore.QTimer.singleShot(0, self.view.scrollToBottom)

rawDescription: Keep QTableView scrolling to the last row when the model is growing


code:
df = pd.DataFrame(np.random.randint(1, 10, (5, 3)))
df
df.prod(axis=1)

rawDescription: Multiply all columns in a Pandas dataframe together


rawDescription: Efficient way of appending / extracting list elements


code: myAnimation.frames[10].grid[2][3] = 'f'

rawDescription: Python Class / Instance /Object Organization Question


rawDescription: replace with regular expression python

description: Replace with regular expression python


code:
sum(letterGoodness.get(c,0) for c in yourstring.upper())
#                                             #^.upper for defensive programming

rawDescription: A value in a list, python

description: A value in a list, python


code: pd.DataFrame(d.values(), index=pd.MultiIndex.from_tuples(d.keys(), names=['id', 'act_type']))

rawDescription: Converting tuples to multiple indices in a Pandas Dataframe


code:
def get_class_name(full_module_name):
    """
    Pull out the class name from the full_module_name
    """
    #split the full_module_name by "."'s
    return full_module_name.split('.')[-1]

def process_docstring(app, what, name, obj, options, lines):
    classname = get_class_name(name)

    # loop through each line in the docstring and replace |class| with
    # the classname
    for i in xrange(len(lines)):
        lines[i] = lines[i].replace('|class|', classname)

def setup(app):
    app.connect('autodoc-process-docstring', process_docstring)

rawDescription: Have sphinx replace docstring text

description: Have sphinx replace docstring text


code:
def initialize_user_interface(self):
        """Draw a user interface allowing the user to type
        MySQL server credentials
        """
        self.parent.title("DB operations")
        self.parent.grid_rowconfigure(0,weight=1)
        self.parent.grid_columnconfigure(0,weight=1)
        self.parent.config(background="lavender")

        self.label_user=Tkinter.Label(self.parent,text="DB User: ",anchor=Tkinter.W,background="dark slate gray",foreground="white", font="Helvetica 8  bold")
        self.label_password=Tkinter.Label(self.parent,text="DB Password:", anchor=Tkinter.W,background="dark slate gray",foreground="white", font="Helvetica 8  bold")

        self.label_user.grid(row=0,column=0,sticky=Tkinter.E+Tkinter.W)
        self.label_password.grid(row=1,column=0, sticky=Tkinter.E+Tkinter.W)

        self.dbuser=Tkinter.Entry(self.parent)
        self.dbpassword=Tkinter.Entry(self.parent,show="*")

        self.dbuser.grid(row=0,column=1,sticky=Tkinter.E+Tkinter.W)
        self.dbpassword.grid(row=1,column=1,sticky=Tkinter.E+Tkinter.W)

        self.connectb=Tkinter.Button(self.parent,text="Log in",font="Helvetica 10 bold",command=self.dbconnexion)
        self.cancelb=Tkinter.Button(self.parent,text="Cancel",command=self.parent.quit,font="Helvetica 10 bold")

        self.connectb.grid(row=2,column=1,sticky=Tkinter.W)
        self.cancelb.grid(row=2,column=2)

rawDescription: how to connect to mysql database from gui made in python

description: Connect to mysql database from gui made in python


code: shapes['actuals dates'].dt.hour.head()

rawDescription: How can I get the timezone-aware year, month, day, hour etc. from a Python datetime?

description: Get the timezone-aware year, month, day, hour etc. from a Python datetime


code:
# this thing always called in a green thread; forget about pools and queues.
def on_message(msg):
    # you're in a green thread now; just process away!
    benefit_from("all the gevent goodness!")
    spawn_and_join_10_sub_greenlets()

rabbitmq_channel.register_callback(lambda msg: gevent.spawn(on_message, msg))

rawDescription: How to wakeup thread from thread pool in python?

description: Wakeup thread from thread pool in python


code:
hours = int(time_string.split(":")[0]) * 3600
mins  = int(time_string.split(":")[1]) * 60
secs  = int(time_string.split(":")[2])

return hours + mins + secs

rawDescription: Python time format with three-digit hour


code:
print( ("%d.%0"+str(c_s)+"d") % ( c // 100 , c % 100 ) )  # Which is the same as...
print( ("%d.%02d") % ( c // 100 , c % 100 ) )  # The case c_s < 0 requires a different expression

rawDescription: Rounding Error in Python

description: Rounding Error in Python


rawDescription: how to extract asin from an amazon product page

description: Extract asin from an amazon product page


rawDescription: Python: Combining two CSV files with header row and matched values with DictReader and DictWriter


code:
#if defined(SWIGPYTHON)
PY_HASHABLE(Foo)
PY_HASHABLE(Bar)
#endif

rawDescription: Is there a way to extend all classes in swig/python?


rawDescription: Python dict of dicts with default value

description: Python dict of dicts with default value


rawDescription: drop values on datetime difference, with revision

description: Drop values on datetime difference, with revision


code:
#convert column datum to period
df['datum'] = pd.to_datetime(df['datum']).dt.to_period('M')
#convert columns to datetime
df['m_taxd'] = pd.to_datetime(df['m_taxd'])
df['m_tand'] = pd.to_datetime(df['m_tand'])

rawDescription: pandas selection from a specific year

description: Pandas selection from a specific year


rawDescription: How to build arguments for a python function in a variable

description: Build arguments for a python function in a variable


code:
def FindSubstringMatch(target, key):
    PositionList = 0
    result = []
    while PositionList < len(target):
        PositionList = target.find(key, PositionList)
        if PositionList == -1:
            break
        result.append(PositionList)
        PositionList += 2
    return tuple(result)

rawDescription: I need this Substring counting program to return a Tuple


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

x = np.linspace(0, 10, 5)

fig, ax = plt.subplots()
for i in range(1, 6):
    ax.plot(x, i*x + x, marker='o', markersize=20,
            label='$y={i}x + {i}$'.format(i=i))
ax.legend(loc='upper left')
plt.show()

rawDescription: How to adjust the size of matplotlib legend box?

description: Adjust the size of matplotlib legend box


code:
print(zenJSONObj['custom_fields'][0])
zenJSONObj['custom_fields'][0]['value'] = 'something new'
print(zenJSONObj['custom_fields'][0])

rawDescription: Getting Deeper Level JSON Values in Python


code:
"abc"
["abc"]
abc = "abc"
abc
[abc]
"I am a string".split("!@#$%^&*") == ["I am a string"]

rawDescription: Convert a string to a list of length one


rawDescription: Constructing a special matrix in numpy dynamically


code: ser = ser.sort_values()

rawDescription: Plotting CDF of a pandas series in python


code:
ADAPTER = "APPNAME.FILENAME.MyAccountAdapter"
ACCOUNT_ADAPTER = "APPNAME.FILENAME.MyAccountAdapter"

rawDescription: Next query parameter doesn't work with django allauth for facebook login


code: pd.DataFrame([f.val for f in allFoo], columns=['val'])

rawDescription: python class attributes to pandas dataframe

description: Python class attributes to pandas dataframe


code:
# ... as before up to 'from itertools import chain'
sorted_ab = list(zip(*sorted(chain(keyed_a, keyed_b), key=lambda t: t[0])))[1]
sorted_ab

rawDescription: Iterate over a pair of iterables, sorted by an attribute


code:
fprintf(stderr, "Python %s on %s\n",
    Py_GetVersion(), Py_GetPlatform());

rawDescription: Where is the Python startup banner defined?


code:
try:
    highscores[name].append(score)
except:
    highscores[name] = [score]

rawDescription: Appending a value to a key in Python?

description: Appending a value to a key in Python


code:
list(set(["dog", "cat", "elephant"]))
list(set([1, 2, 3]))

rawDescription: What are the pythonic way to replace a specific set element?


code: size = fields.IntegerRangeField(min_value=1, max_value=50)

rawDescription: How to limit the maximum value of a numeric field in a Django model?

description: Limit the maximum value of a numeric field in a Django model


code:
@dec
def foo():
    pass

rawDescription: Is it possible to apply my own decorators to builtin methods in Python?


rawDescription: Displaying matrix-like image with RGB-colored cells in matplotlib


code:
for i in range(0, 10+1):
    string = (''.join(chr(ord('A')+(d-1)%26) if d else ''
              for d in range(0, i+1))+ "%d")
    length = len(string) - len('%d') + len("%d" % len(string))
    correction = len(string)+1 in POWERS_OF_TEN
    string2 = string % (length+correction)
    print('{!r}, len: {} -> {!r}, length actual: {} vs computed: {}'.format(
          string, len(string), string2, len(string2), length))

rawDescription: Using len() in a string

description: Using len() in a string


rawDescription: Replace values of a group with group aggregate in numpy/pandas


rawDescription: How can I select all DataFrame rows that are within a certain distance of a given value in a specific column?

description: Select all DataFrame rows that are within a certain distance of a given value in a specific column


rawDescription: How to unset or disable hyperlinkctrl in wxpython only on some conditions

description: Unset or disable hyperlinkctrl in wxpython only on some conditions


code: (z * a).sum(axis=1)

rawDescription: Reduce array over ranges

description: Reduce array over ranges


code: urlencode([("var", "value"), ("var", "value2")])

rawDescription: Python urllib2 sending POST data

description: Python urllib2 sending POST data


code:
import os

cwd = os.getcwd()
_, files, directories = next(os.walk(cwd))

rawDescription: How to get only the subfolders of my cwd in python

description: Get only the subfolders of my cwd in python


rawDescription: Organize 3d points and found them by distance from a position


code:
my_list = ['c1','c2','c3']
for x in my_list:
    globals()[x] = []

c1
c2
c3

rawDescription: Create new empty lists from items within a Python list?


code: df

rawDescription: Pandas: Convert DataFrame to Mean and Standard Deviation of Each Cell


rawDescription: Django custom login never authenticates why?


code: tuple(s[i:i + 2] for i in range(0, len(s), 2))

rawDescription: Split a string and add into `tuple`

description: Split a string and add into `tuple`


code: [k for k,v in G.degree().iteritems() if v == 0]

rawDescription: How to list specific node/edge in networkx?

description: List specific node/edge in networkx


code:
post_data = {'access_token':access_token, 'message':'hey this is a test!'}
request_path = str(facebook_id)+'/feed'
post_data = urllib.urlencode(post_data)
response = urllib2.urlopen('https://graph.facebook.com/%s' % request_path, post_data)

rawDescription: Automatically posting to facebook page with python


code:
class Room:
    registry = {}
    def __init__(self, name):
        self.registry[name] = self
        # the rest of your __init__ code

rawDescription: How to reference an existing class object with no defined variable?

description: Reference an existing class object with no defined variable


code: import foo

rawDescription: Where does __import__ get alias names from?


code:
list1 = ['e', 'd', 'u', 'd']
list2 = ['m', 'o', 'b', 'b', 'e', 'd']
def reverse(L, num):
    return L[:num][::-1] + L[num:]

reverse(list1, 4)
reverse(list2, 3)

rawDescription: Returns a copy of the list with the first number of items reversed


code:
di = {}
for i in range(1000):
    di["Name{}".format(i)] = {'Location': 'result{}'.format(i), 'LocationB':'result{}B'.format(i)}

def get_dictionary_value():
    di.get("Name999").get("LocationB")

rawDescription: Python - get object - Is dictionary or if statements faster?


code:
def number_of_ones(stack,column):
    return sum([ (value>>column)&1 for value in stack ])

def most_significant_bit(x):
    return len(bin(x))-2

def get_multiplier(n):
    assert n&1, "Must be an odd number input"
    stack = []
    column = 0
    m = 0
    carry_bit = 0
    while len(stack)==0 or column<most_significant_bit(stack[-1]):
        column_sum = number_of_ones(stack,column) + carry_bit
        if (column_sum&1)==0:
            stack.append(n<<column)
            m += (1<<column)
        # Edited to include bug fix :-)
        carry_bit = column_sum>>1
        column += 1
    return m

rawDescription: Finding a multiple of some N from a binary series under certain restrictions


rawDescription: numpy matrix multiplication to triangular/sparse storage?

description: Numpy matrix multiplication to triangular/sparse storage


code:
# main.py (some stuff omitted for clarity)
import logging
import wsgiref.handlers
from google.appengine.ext import webapp

urlmap = [(r"/log/(.+)", handlers.LoggingHandler),]
application = webapp.WSGIApplication(urlmap)
wsgiref.handlers.CGIHandler().run(application)

rawDescription: AppEngine: logging events from the browser (JavaScript)


code: wts = defaultdict(lambda x: 1 if x[1] == somevalue else 0)

rawDescription: How to use defaultdict to create a dictionary with a lambda function?

description: Use defaultdict to create a dictionary with a lambda function


code:
import datetime
s = "2010-01-01 18:48:14.631829"
datetime.datetime.strptime(s, "%Y-%m-%d %H:%M:%S.%f")

rawDescription: Python reading logfile with timestamp including microseconds


code: result = minimize(fcn2min, params, args=(x, y), xtol=1e-12)

rawDescription: Python lmfit - how come the intercept's estimation in a linear regression depends on the starting value?


code:
text= "I say what I mean. I mean what I say. i do."
sentences = text.lower().split('.')
dic = {}
for i, sen in enumerate(sentences):
    for word in sen.split():
        if word not in dic:         # you just need these
            dic[word] = set()       # two extra lines
        dic[word].add(i)

dic

rawDescription: word/pair list using dictionaries and strings

description: Word/pair list using dictionaries and strings


code:
def get_download_url(user):
    download_urls = {
        'user1': '/downloads/user1/',
        'user2': '/downloads/user2/',
    }
    return download_urls.get(user.username)

rawDescription: Django restrict pages to certain users

description: Django restrict pages to certain users


code:
import string
list1 = [1, 2, 1, 2, 3, 2, 4, 1]
list2 = list(string.ascii_lowercase[:16])
list2
list(divvy_up(list2, list1))

rawDescription: create lists of tuples from two lists

description: Create lists of tuples from two lists


code: A if C else B

rawDescription: How can I closely achieve ?: from C++/C# in Python?

description: Closely achieve ?: from C++/C# in Python


rawDescription: Is it possible to reproduce randn() of MATLAB with NumPy?


code:
def rates_with_new_base(rates, old_base, new_base):
    new_rates = {curr: rate/rates[new_base] for curr, rate in rates.items()}
    # only needed if old base was not in rates table
    new_rates[old_base] = 1.0 / rates[new_base]
    return new_rates

rawDescription: Curency Rate Conversion Wrong Base Currency


code: print (H1 == H2).sum()

rawDescription: Numpy sum function returns 1.67772e+07

description: Numpy sum function returns 1.67772e+07


rawDescription: logger configuration to log to file and print to stdout

description: Logger configuration to log to file and print to stdout


code:
with open('words.txt', 'r') as file:
    file_contents = file.read()

    print('Total words:   ', len(file_contents.split()))
    print('total stops:    ', file_contents.count('.'))

rawDescription: how to count the amount of sentences in a paragraph in python

description: Count the amount of sentences in a paragraph in python


rawDescription: assign output of print to a variable in python

description: Assign output of print to a variable in python


rawDescription: Loop through netcdf files and run calculations - Python or R


code:
from pprint import pprint
pprint([(k, list(g)) for k, g in groupby(strs)])

rawDescription: Counting runs in a string

description: Counting runs in a string


rawDescription: Generating raw_inputs based on user input? [Python]


rawDescription: How to get record numpy array with dates from pandas data frame?

description: Get record numpy array with dates from pandas data frame


code: region = Region(x,y,w,h)

rawDescription: How do I click on an image outside the defined region?

description: Click on an image outside the defined region


rawDescription: How to simplify an expression for a complex constant using sympy?

description: Simplify an expression for a complex constant using sympy


code:
position_of_ngram(['the', 'book'],hyp)

position_of_ngram(['because', 'he'],hyp)

rawDescription: How to find position of an ngram in a sentence?

description: Find position of an ngram in a sentence


code:
import shlex, subprocess
cmd = "/usr/bin/nmap -sn -Pn todd.ns.cloudflare.com --script dns-check-zone --script-args='dns-check-zone.domain=www.macmonster.com'"
args = shlex.split(cmd)
output = subprocess.check_output(args)

rawDescription: python subprocess issue with Nmap

description: Python subprocess issue with Nmap


code: a = locals().get('b', 0)

rawDescription: Python : How to set a variable to something such as "None" or "0" when there is no value from the request


code:
from bs4 import BeautifulSoup
import sys

soup = BeautifulSoup(open(sys.argv[1], 'r'), 'xml')

allergies = []
for allergy in soup.find_all('Allergy'):
    d = {
        'name': allergy.Allergen.Name.string,
        'reaction': allergy.Reaction.string,
        'on_set_date': allergy.OnsetDate.string,
    }
    allergies.append(d)

## Use 'allergies' array of dictionaries as you want.
## Example:
print(allergies[1]['reaction'])

rawDescription: Use BeautifulSoup to Iterate over XML to pull specific tags and store in variable


rawDescription: Removing rows by count from Pandas DataFrame


code:
for char in code:
    decode = decode + decoded(char, shift)

rawDescription: How to decode a coded sentence?

description: Decode a coded sentence


rawDescription: python : generate sublists depending on the elements values

description: Python : generate sublists depending on the elements values


code:
soup = BeautifulSoup("""

        USB 2 ports

        Firewire ports

        HDMI ports

""")
import re
pattern = re.compile(r'\s*%s\s*' % 'USB 2 ports')
soup.find(text=pattern)

rawDescription: How to find a string in a HTML document, ignoring whitespace?

description: Find a string in a HTML document, ignoring whitespace


rawDescription: Mqtt : Publish the last line from a file that is periodically updated


code:
def __len__(self):
    return 42

rawDescription: Is it possible to modify the behavior of len()?


code:
for e in self.emitter:
    e.draw(screen, self.camera.apply)

rawDescription: How to implement a particle engine

description: Implement a particle engine


code:
class Disk(object):
    def __init__(self, test1=None, test2=None, test3=None):
        self.test1 = test1
        self.test2 = test2
        self.test3 = test3

rawDescription: How to create a object of variables, and return it, in Python?

description: Create a object of variables, and return it, in Python


code:
POST /test_index/_search
{
   "query": {
      "range": {
         "timestamp": {
            "gt": "now-1h"
         }
      }
   }
}
...
{
   "took": 3,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 5,
      "max_score": 1,
      "hits": [
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "_AaKzzXLQuiLyBAjT9YDqA",
            "_score": 1,
            "_source": {
               "timestamp": "2015-03-07T19:35:51.914612"
            }
         },
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "rCSziknqTKWXfoY7hRJiIw",
            "_score": 1,
            "_source": {
               "timestamp": "2015-03-07T19:35:51.919175"
            }
         },
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "5yXtPWGATwe4n3kAVbwRfg",
            "_score": 1,
            "_source": {
               "timestamp": "2015-03-07T19:35:51.909425"
            }
         },
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "fwNb4iVVQFmPi9jo8PZxhA",
            "_score": 1,
            "_source": {
               "timestamp": "2015-03-07T19:35:51.912478"
            }
         },
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "PGHXxzvKRrakvJWMRtVQXQ",
            "_score": 1,
            "_source": {
               "timestamp": "2015-03-07T19:35:51.916854"
            }
         }
      ]
   }
}

rawDescription: Elasticsearch date range returns no hits


code: yield (line[prevpos:pos], len(stack))

rawDescription: Python 3 - Different way of writing a print statement


code:
db.define_table('mytable',
    Field('field1', requires=IS_IN_SET(['a', 'b', 'c'])),
    Field('field2', requires=IS_IN_SET(['x', 'y', 'z'], multiple=True),
          widget=SQLFORM.widgets.checkboxes.widget))

rawDescription: web2py: how to customize add.edit forms in SQLFORM.smartgrid?

description: Web2py: how to customize add.edit forms in SQLFORM.smartgrid


code:
try:
    aa = foo()
except Exception:
    try:
        aa = bar()
    except Exception:
        aa = 0

rawDescription: Best way to write "try elsetry" in python?

description: Write "try elsetry" in python


code:
import argparse
parser = argparse.ArgumentParser(description='Process some floats.')
parser.add_argument("-e", nargs=6, metavar=('a', 'b', 'c', 'd', 'e', 'f'),
                        help="my help message", type=float,
                        default=None)
try:
    parser.parse_args('-e 1.0 2.0 3.33 4.45 5.15 6.0'.split())
except SystemExit:
    pass

try:
    parser.parse_args('-e foo bar baz spam ham eggs'.split())
except SystemExit:
    pass

rawDescription: specify list of floats in argparse

description: Specify list of floats in argparse


code: return obj or otherobj

rawDescription: How can i omit the redundant words in python condition loop

description: Omit the redundant words in python condition loop


rawDescription: scipy.sparse dot extremely slow in Python

description: Scipy.sparse dot extremely slow in Python


code:
s = Session()
s.query(Role).join(User.groups).join(Group.roles).filter(User.id==1).all()

rawDescription: Select through multiple many to many relationships via SQLAlchemy


code:
def corect_change(nickles, pennies, summ):
    i = 0
    while i <= nickles:
        if summ - (i * 5) < 5:
            break
        i += 1
    j = 0
    while j <= pennies:
        if summ == (i * 5) + j:
            break
        j += 1
    return summ == (i * 5) + j

rawDescription: Change calculator nickels pennies

description: Change calculator nickels pennies


code:
class PageOne(tk.Frame):
    ...
    def menubar(self, root):
        menubar = tk.Menu(root)
        pageMenu = tk.Menu(menubar)
        pageMenu.add_command(label="PageOne")
        menubar.add_cascade(label="PageOne", menu=pageMenu)
        return menubar

rawDescription: Tkinter add menu bar in Frames

description: Tkinter add menu bar in Frames


code: "".join(chr(x) for x in range(128))

rawDescription: Python: How to import ascii characters

description: Python: How to import ascii characters


code:
classes = {'FourLegs': FourLegs, 'TwoOrNoLegs': TwoOrNoLegs}

for k, v in dc.items():
    clsname, name, age = v
    an = classes[clsname](name, age)
    print(an, an.name, an.age)
    zoo[an.name] = an

rawDescription: Dynamically create class instances from given strings and save deep copy in dictionary


rawDescription: Is there a more vectorized way to perform numpy.outer along an axis?


code:
MyTable.__table__.insert().execute([{'color': 'blue'},
                                    {'color': 'red'},
                                    {'color': 'green'}])

rawDescription: bulk insert list values with SQLAlchemy Core

description: Bulk insert list values with SQLAlchemy Core


code:
dict2 = dict1
for key, value in dict2.items():
    dict2[key] = value[0]

print(dict2) # good so far
print(dict1) # oh no!

rawDescription: Dictionary comprehension containing dictionary elements


code:
idx1 = np.where(b[1:] * b[:-1] < 0)[0]
idx2 = idx1 + 1

x0 = a[idx1] + np.abs(b[idx1] / (b[idx2] - b[idx1])) * (a[idx2] - a[idx1])

a2 = np.insert(a, idx2, x0)
b2 = np.insert(b, idx2, 0)

m = b2 < 0
plot(np.ma.array(a2, mask=m), np.ma.array(b2, mask=m), 'b-', lw=2)
m = b2 > 0
plot(np.ma.array(a2, mask=m), np.ma.array(b2, mask=m), 'r--', lw=2)

rawDescription: How to plot with different linestyles in pylab

description: Plot with different linestyles in pylab


rawDescription: Python: Index an array using the colon operator in an arbitrary dimension


code: numpy.array(list(numpy.broadcast(*numpy.ix_(x, y, z)))).reshape((2, 3, 2, 3))

rawDescription: numpy non-integer grid

description: Numpy non-integer grid


rawDescription: Python join elements with same index

description: Python join elements with same index


code:
from Crypto.Hash import HMAC
secret_key = "Don't tell anyone"
h = HMAC.new(secret_key)
text = "whatever you want in the file"
## or: text = open("your_file_without_hash_yet").read()
h.update(text)
with open("file_with_hash") as fh:
    fh.write(text)
    fh.write(h.hexdigest())

rawDescription: Calculate and add hash to a file in python


code:
Obj1.serial = "000123"

('%0'+str(len(Obj1.serial))+'d') % (1+int(Obj1.serial))

rawDescription: Strings, ints and leading zeros

description: Strings, ints and leading zeros


rawDescription: SQL table for protein database

description: SQL table for protein database


rawDescription: How to format axis number format to thousands with a comma in matplotlib

description: Format axis number format to thousands with a comma in matplotlib


code:
request3
app/data/mydata_c.csv

rawDescription: how to loop list to pass string to function name in python

description: Loop list to pass string to function name in python


rawDescription: random.sample and "selection order"

description: Random.sample and "selection order"


rawDescription: mean average on the contents of a list

description: Mean average on the contents of a list


code: a.__class__.d = {'blah': 'blah'}

rawDescription: Python: Static objects in a class

description: Python: Static objects in a class


rawDescription: naming collision in namespaces in modules of python

description: Naming collision in namespaces in modules of python


code: np.any(cc, 0)

rawDescription: Python: Comparing all elements of two arrays and modifying 2nd array


rawDescription: Regarding ascii and python packing

description: Regarding ascii and python packing


rawDescription: Merging of two dictionaries

description: Merging of two dictionaries


code: vertex_builder = vertex_drawer.VisualVertexBuilder(graph.vs, kwds)

rawDescription: How to use igraph python's metamagic class?

description: Use igraph python's metamagic class


code: executor = TaskExecutor()

rawDescription: deadlock because of blocking Queue.get() method

description: Deadlock because of blocking Queue.get() method


code:
phrase = list(phrase)
for i, c in punct:
    phrase.insert(i, c)
phrase = "".join(phrase)

rawDescription: Ignoring noncharacters in cypher text

description: Ignoring noncharacters in cypher text


code:
df = sc.parallelize([row(1, "2"), row(2, "3")]).toDF()
df.printSchema()

## root
##  |-- foo: long (nullable = true)
##  |-- bar: string (nullable = true)

new_df = df.withColumn('new_column', lit(None).cast(StringType()))
new_df.printSchema()

## root
##  |-- foo: long (nullable = true)
##  |-- bar: string (nullable = true)
##  |-- new_column: string (nullable = true)

new_df.show()

## +---+---+----------+
## |foo|bar|new_column|
## +---+---+----------+
## |  1|  2|      null|
## |  2|  3|      null|
## +---+---+----------+

rawDescription: Add an empty column to spark DataFrame

description: Add an empty column to spark DataFrame


code:
if request.method == 'POST':
    form = RegistrationFormTeacher(request.POST)
    if form.is_valid():
        new_teacher = form.save(commit=False)
        new_teacher.user = request.user #get the user object however you want - you
            #can pass the user ID to the view as a parameter and do
            #User.objects.get(pk=id) or some such, too.
        new_teacher.save()
        form.save_m2m()

rawDescription: Django, register extended user model

description: Django, register extended user model


code:
def func(a):
    return 1 if a > 0 else -1

rawDescription: how to use return in Python

description: Use return in Python


code: int("".join("".join(x) for is_number, x in itertools.groupby("dfsd98sd8f68as7df56", key=str.isdigit) if is_number is True))

rawDescription: Splitting a string where it switches between numeric and alphabetic characters


code:
if hasattr(callable, '__doc__'):
    self.__doc__ = callable.__doc__

rawDescription: Using sphinx autodoc for a fabfile

description: Using sphinx autodoc for a fabfile


code:
# goodbye.py
import webapp2

class GoodbyePage(webapp2.RequestHandler):

    def get(self):
        self.response.headers['Content-Type'] = 'text/html'
        self.response.write('Goodbye!')

app = webapp2.WSGIApplication([
    ('/goodbye', GoodbyePage),
], debug=True)

rawDescription: App Engine - Python - Open local HTML file from script


code:
clr = {names[i]: colors[i] for i in range(len(names))}
ax.scatter(x, y, z, c=clr)

rawDescription: Elegant way to match a string to a random color matplotlib


rawDescription: How do I escape closing '/' in HTML tags in JSON with Python?

description: Escape closing '/' in HTML tags in JSON with Python


code:
now = time.localtime()
if now.tm_hour >= 22 or now.tm_hour < 9:
    text_bomb()

rawDescription: python script to check between 10pm and 9am

description: Python script to check between 10pm and 9am


code:
def memoize(func):
    memo = {}

    def wrapper(*args):
        if args not in memo:
            memo[args] = func(*args)
        return memo[args]

    return helper

@memoize
def f(arg):
    # expensive operations
    return result

x = f('arg that will take 10 seconds')  # takes 10 seconds
y = f('arg that will take 10 seconds')  # virtually instant

rawDescription: optimize function evaluations caching partial result

description: Optimize function evaluations caching partial result


code:
from bs4 import BeautifulSoup as bs
soup = bs("""Market Cap (intraday)
5:
33.57B
""")

soup.find("sup", text="5").parent.parent.find_next_sibling("td").find("span").text
# u'33.57B'

rawDescription: beautifulsoup parsing - dealing with superscript?

description: Beautifulsoup parsing - dealing with superscript


code:
ind = pd.Index([1, 2, 3])
ind2 = pd.Index([3, 4, 5])
ind - ind2

rawDescription: DataFrame algebra in Pandas

description: DataFrame algebra in Pandas


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

Builder.load_string('''
<MyWidget>:
    CheckBox:
        active: False
    CheckBox:
        active: True
''')

class MyWidget(BoxLayout):
    pass

class MyApp(App):
    def build(self):
        return MyWidget()

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

rawDescription: How do I initialise CheckBox state in kivy

description: Initialise CheckBox state in kivy


rawDescription: Palindrome generator

description: Palindrome generator


rawDescription: sorting a graph by its edge weight. python

description: Sorting a graph by its edge weight. python


code:
from itertools import product

def multiletters(seq, max_length):
    for n in range(1, max_length+1):
        for s in product(seq, repeat=n):
            yield ''.join(s)

rawDescription: All strings with list of characters?

description: All strings with list of characters


code:
from cpppo.server.enip import client
from cpppo.server.enip.getattr import attribute_operations

HOST = "192.168.1.100"
TAGS = ["@4/100/3"]

with client.connector(host=HOST) as conn:
    for index, descr, op, reply, status, value in conn.synchronous(
        operations=attribute_operations(
            TAGS, route_path=[], send_path='' )):
        print(": %20s: %s" % (descr, value))

rawDescription: Read/write values using Ethernet/IP

description: Read/write values using Ethernet/IP


code: {'Gilliam': 'actors', 'Cleese': 'actors', 'parrot': 'sketch', 'spam': 'sketch', 'Palin': 'actors', 'cheese_shop': 'sketch'}

rawDescription: Python many-to-one mapping (creating equivalence classes)


code: I = np.where(test); out = b.copy(); out[I] = a[I]

rawDescription: Numpy: vectorizing two-branch test (ternary-operator like)


code:
import pkg_resources
pkg_resources.require('FooPackage==1.2')
import FooPackage

rawDescription: Python: If there are multiple egg versions of the same package installed, how do I import specifically the version I need?


code:
import numpy as np
import pandas as pd

results = pd.DataFrame({'Contractor':[1,1,0,0,0,1],
                    'President':[1,0,0,0,1,1],
                   'Item 1':[1,1,0,0,1,np.nan],
                   'Item 2':[1,0,0,1,0,1]})
reference =  pd.DataFrame({'Position':['Contractor','President'],
                           'Item(s)':[(1,), (1,2)]})

longref = pd.DataFrame([('Item {}'.format(item), row['Position'])
                        for index, row in reference.iterrows()
                        for item in row['Item(s)']], columns=['Item', 'Position'])
melted = pd.melt(results, id_vars=['Item 1','Item 2'], var_name='Position')
melted = melted.loc[melted['value']==1]
melted = pd.melt(melted, id_vars=['Position'],
                 value_vars=['Item 1','Item 2'], var_name='Item')
merged = pd.merge(longref, melted, how='left')
grouped = merged.groupby(['Position'])
result = (grouped['value'].sum() / grouped['value'].count())*100
result = result.rename('Overall%').reset_index()
print(result)

rawDescription: Pandas Pivot Table with Fancy Stacking

description: Pandas Pivot Table with Fancy Stacking


rawDescription: Map list onto dictionary

description: Map list onto dictionary


code:
def get_pending_users(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        pending_users = user.company.users.filter(User.account_approved == False).all()
        if g.pending_users is None:
           g.pending_users = pending_users
        return f(*args, **kwargs)
    return decorated_function

rawDescription: Pass SQLAlchemy Query to Base Jinja Template


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

dists = [np.random.normal(i, 1, 100) for i in range(0, 10, 2)]

fig, ax = plt.subplots()
ax.boxplot(dists, positions=[0, 1, 2, 0, 1])
plt.show()

rawDescription: Pyplot boxplots centered around xticks

description: Pyplot boxplots centered around xticks


code:
_list = [i for i in range(1, 6)]
for i in _list:
     popped = [_list.pop(j) for j in range(len(_list)) if not _list[j]**2 < 25]
     print(len(_list), i)

rawDescription: Updating list with a for loop

description: Updating list with a for loop


code:
idx = A.argsort()
C = B[idx].cumsum()[idx.argsort()]

rawDescription: Efficient 1D array comparison, scaling and summation


code:
class User_Friend(models.Model):
    objects = BulkInsertManager() # assign a custom manager to handle bulk insert

    id = models.CharField(max_length=255)
    user = models.ForeignKey(User, null=False, blank=False)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    city = models.CharField(max_length=50, null=True, blank=True)
    province = models.CharField(max_length=50, null=True, blank=True)
    country =  models.CharField(max_length=30, null=True, blank=True)

rawDescription: MySQL INSERT ... ON DUPLICATE KEY UPDATE with django 1.4 for bulk insert


code: delimiter='  '   #two spaces

rawDescription: Combine two columns under one header in Numpy array


code: mac = input("Enter the MAC of the phone: "+".cfg")

rawDescription: Creating new text files with names from an array in Python


code:
unique_words = set(new.split())
unique_words2 = set(new2.split())
common_words = set.intersection(unique_words, unique_words2)
print('\n'.join(sorted(common_words)))

rawDescription: How do I find all unique words(no duplicates)?

description: Find all unique words(no duplicates)


code:
if rlabels:
    rlabels = DictFormatter(rlabels)

grid_helper = GridHelperCurveLinear(tr,
                                    extremes=(th0, th1, r0, r1),
                                    grid_locator1=theta_grid_locator,
                                    grid_locator2=r_grid_locator,
                                    tick_formatter1=theta_tick_formatter,
                                    tick_formatter2=rlabels)

rawDescription: How to change ticklabels within figure created with axisartist

description: Change ticklabels within figure created with axisartist


code:
for x in xrange(1, 9):
    cmd = "text" + str(x) + ".someFunction()"
    eval(cmd)

rawDescription: Cycling through a group of variables with similar names


code:
# find point around :
latitude = 46.2037010192871
longitude = 5.20353984832764
query= "SELECT ID, NOM, LAT, LON, 3956 * 2 * ASIN(SQRT(POWER(SIN((%s - LAT) * 0.0174532925 / 2), 2) + COS(%s * 0.0174532925) * COS(LAT * 0.0174532925) * POWER(SIN((%s - LON) * 0.0174532925 / 2), 2) )) as distance from POI  having distance < 50 ORDER BY distance ASC " % ( latitude, latitude, longitude)

rawDescription: Django - determining if geographic coordinates are inside of an circle


code:
env.UNIQUE_ID.value = 0
env.DUP_LOCKER = Lock()

rawDescription: fabric assign unique index to each task

description: Fabric assign unique index to each task


code: request = update_by_email(email, **{field: field_value})

rawDescription: Using variable as keyword passed to **kwargs in Python


rawDescription: Parsing an existing config file

description: Parsing an existing config file


code:
class Foo(object): pass
type(Foo())()

rawDescription: Python3 - default keyword for default values for type?


code:
timeit.timeit('filter(None, myList)', 'from __main__ import myList')
timeit.timeit('[t for t in myList if t]', 'from __main__ import myList')
timeit.timeit('[t for t in myList if t != ()]', 'from __main__ import myList')

rawDescription: Python 3: Removing an empty tuple from a list of tuples


code:
def primes(prime_max):
    prime_flags = numpy.ones(prime_max, dtype=bool)
    prime_flags[0] = prime_flags[1] = False
    for i in range(2, prime_max):
        if prime_flags[i]:
            prime_flags[2*i::i] = False
    return prime_flags.nonzero()[0]

rawDescription: Array initialized with numpy is much slower in a loop with if statement


code: result = [first_el for first_el in first if first_el in second]

rawDescription: Comprehensive `for...in` different from standard loops


rawDescription: how do I add homepage to Django sitemap?

description: Add homepage to Django sitemap


code: return len(Account.objects.filter(expiration_date__lte=timezone.now())) > 0

rawDescription: Django templatetag return True or False

description: Django templatetag return True or False


code:
from datetime import *
import pandas as pd

from_day = 15
plus_days = 18

df = pd.DataFrame.from_records([
(datetime(2013, 2, 16),2),
(datetime(2013, 2, 18),5),  #
(datetime(2013, 2, 19),6),  #
(datetime(2013, 3, 1), 7),  #
(datetime(2013, 3, 17),1),
(datetime(2013, 3, 20),3),  #
(datetime(2013, 3, 25),4),  #
(datetime(2013, 4, 1), 8)],
columns=["time_slot", "data"],
index=["time_slot"])

df.insert(0,'days',df.index)
df.days = df.days.apply(lambda x: x.day)

rawDescription: Select day of month as start of date range using Pandas


code:
class MyClass(object):

    def myMethod(self):
        pass

MyClass.myMethod.__func__.__doc__ = "A really cool method"

rawDescription: Explicitly set docstring of a method

description: Explicitly set docstring of a method


code:
for name in sorted(entries):
    ave_score = total_scores[name] / entries[name]
    print(name,ave_score) #sep=", ")

rawDescription: Sorting data from a csv alphabetically, highest to lowest and average


code:
request.session['name1'] = dynamic_variable1
request.session['name2'] = dynamic_variable2

rawDescription: Passing variables to a function

description: Passing variables to a function


code:
import sometype

@datashape.discover.register(SomeType)
def discover_some_type(data):
    return sometype.discover_some_type(data)

rawDescription: How do I patch a method registered by a decorator in Python's datashape?

description: Patch a method registered by a decorator in Python's datashape


code: media = InstagramFeed.get_media(user_name=user_name, count=8)

rawDescription: python instagram api user_recent_media returns None

description: Python instagram api user_recent_media returns None


code:
class my_sprite_class(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__()
        #Etc...

    #Add this draw function so we can draw individual sprites
    def draw(self, screen):
        screen.blit(self.image, self.rect)

rawDescription: pygame: draw() currently draws all sprites in a group. How can I just draw a specific one

description: Pygame: draw() currently draws all sprites in a group. How can I just draw a specific one


code:
@docstring("copyright by nobody")
def testme():
    "This function does nothing"
    pass

rawDescription: Setting the docstring to an expression inside def


code: shutil.copytree(srcpath, dstpath)

rawDescription: Python: folder creation when copying files


code:
@classmethod
def Func2(cls):
    return cls.z

rawDescription: What is the proper way to access python class variables?


code:
functions = [globals()[name] for name in names]
# [<function __main__.call_some_function_A>, <function __main__.call_some_function_B>, <function __main__.call_some_function_Z>]

rawDescription: Executing a function in reverse in Python


code:
import urllib2
import urllib
import json

url = 'http://nominatim.openstreetmap.org/search?'
place = 'MCRAE, GA'
params = urllib.urlencode(dict(q=place, format='json'))
# print(url+params)
response = urllib.urlopen(url+params)
data = json.loads(response.read())[0]
print(data['lon'], data['lat'])

rawDescription: How does NOAA convert City,St to lat long?


code:
df
df['a'] = df.a.str.replace(r'\bHi\b', 'hi')
df

rawDescription: How to correct typos in pandas dataframe

description: Correct typos in pandas dataframe


code:
def solve(a):
    assert a >= -0.625, "No real solution"

    x = a - 3

    yoffs = (0.25 * a) ** 0.5
    ylo = 0.5 - yoffs
    yhi = 0.5 + yoffs

    zoffs = (0.015625 + 0.25 * a) ** 0.5
    zlo = 0.125 - zoffs
    zhi = 0.125 + zoffs

    return [
        (x, ylo, zlo),
        (x, ylo, zhi),
        (x, yhi, zlo),
        (x, yhi, zhi)
    ]

rawDescription: Pythonic Way to Solve this Matrix

description: Pythonic Way to Solve this Matrix


code:
(mx, my) = np.meshgrid(np.arange(img.shape[1]), np.arange(img.shape[0]))
ox = (mx - offsetx).astype(np.float32)
oy = (my - offsety).astype(np.float32)
out_translate = cv2.remap(out, ox, oy, cv2.INTER_LINEAR)

rawDescription: Extracting polygon given coordinates from an image using OpenCV


code:
rec='Lorem ipsum dolor sit amet consectetur adipiscing elit In vitae neque nec magna tristique ornare Cras faucibus risus eu odio pharetra interdum Nunc dui mi'
print(giveme(rec, testposition)[-1])

rawDescription: Python - Conditionally split line

description: Python - Conditionally split line


code: shutdown /l

rawDescription: How to make a python script which can logoff, shutdown, and restart a computer?

description: Make a python script which can logoff, shutdown, and restart a computer


rawDescription: Comparing two lists items in python

description: Comparing two lists items in python


code:
def average():
    inputnum = 0
    numlist = []
    while inputnum <=100:
        inputnum = input("Please input a number: ")
        inputnum = float(inputnum)
        numlist.append(inputnum)
    average = sum(numlist)/len(numlist)
    print(average)

average() # finally call the function

rawDescription: Average function in Python

description: Average function in Python


code:
#!/usr/bin/python

import subprocess
import string

def backquotes(cmdwords):
        output = subprocess.Popen(cmdwords, stdout=subprocess.PIPE).communicate()[0]
        return output.strip()

pid = backquotes(['pgrep', 'your_program'])

gdb.execute("attach " + str(pid))

rawDescription: How to script gdb (with python)? Example add breakpoints, run, what breakpoint did we hit?

description: Script gdb (with python)? Example add breakpoints, run, what breakpoint did we hit


code: dfc + timedelta(hours=24)

rawDescription: converting time data from unicode in pandas

description: Converting time data from unicode in pandas


code: selection = filter(is_group, selection)

rawDescription: How to isolate group nodes in maya with python

description: Isolate group nodes in maya with python


rawDescription: Efficiently re-indexing one level with "forward-fill" in a multi-index dataframe


code: from lyricCheck import lyricCheck

rawDescription: Python Module Package with no methods

description: Python Module Package with no methods


code:
Final_List = [[server, ','.join(environments), account]
              for (server, account), environments in sorted(grouped.items())]

rawDescription: Grouping of list of list for elments of inner list in python


code:
from github3 import repository

commits = repository('sigmavirus24', 'github3.py').iter_commits()
c = next(commits)
print(len(c.files))  # => 0
print(c.refresh())  # => <Repository Commit [0eec5f6]>
print(len(c.files))  # => 1
print(c.files)
# [{u'status': u'modified', u'deletions': 0, ... }]

rawDescription: github3.py. Empty list of commited files

description: Github3.py. Empty list of commited files


code:
freq, bw = pi/4, pi/8
R = e ** (-bw / 2)
c = cos(freq) * 2 * R / (1 + R ** 2) # AudioLazy included the cosine
gain = (1 - R ** 2) * sqrt(1 - c ** 2)

rawDescription: Applying time-variant filter in Python

description: Applying time-variant filter in Python


code:
print(m[0])
# => [Honda]

print(m[1])
# => [VTEC]

rawDescription: Capture the text inside square brackets using a regex


rawDescription: Python code to open image in browser?

description: Python code to open image in browser


code:
def my_all_v3(a_list):
  for i in a_list:
    if not i:
      return False
  return True

def my_any_v3(a_list):
  for i in a_list:
    if i:
      return True
  return False

rawDescription: How to apply a logical operator to all elements in a python list

description: Apply a logical operator to all elements in a python list


rawDescription: Converting Snake Case to Lower Camel Case (lowerCamelCase)


rawDescription: What is going on with the "return fibonacci... " in this program?


code:
dateobject = datetime.date.today()
datetime.datetime.combine(dateobject, datetime.time())

rawDescription: How do I convert a datetime.date object into datetime.datetime in python?

description: Convert a datetime.date object into datetime.datetime in python


code: use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))

rawDescription: Is there a simple way to increment a datetime object one month in Python?


code:
from lxml import etree

e1 = etree.fromstring(xml1)
ids = e1.xpath('//id/text()')

rawDescription: XML Cross Reference

description: XML Cross Reference


rawDescription: Grouping, calculating, and sorting scoring data


rawDescription: NumPy load file interspersed with headers


rawDescription: How to get the seconds since epoch from the time + date output of gmtime() in Python?

description: Get the seconds since epoch from the time + date output of gmtime() in Python


code:
class FeedExporter(object):

    ...

    def open_spider(self, spider):
        file = TemporaryFile(prefix='feed-')
        exp = self._get_exporter(file)  # <-- this is where the exporter is instantiated
        exp.start_exporting()
        self.slots[spider] = SpiderSlot(file, exp)

    def _get_exporter(self, *a, **kw):
        return self.exporters[self.format](*a, **kw)  # <-- not passed in :(

rawDescription: Modifiying CSV export in scrapy

description: Modifiying CSV export in scrapy


rawDescription: Need help thinking through splitting lists at integer divisions in Python


rawDescription: Is there a better more readable way to coalese columns in pandas


code:
configobj = None

def getconfigobj():
  global configobj
  if not configobj:
    configObj = config.Config()
  return configobj

rawDescription: How to pass global variables between files in python

description: Pass global variables between files in python


code:
from numpy.core.defchararray import add
test_list = np.tile(np.array([[1,2],[3,4],[5,6]]),(100000,1)).astype(str)

def stringy_arr(points):
    return add(add('X coordinate is ', points[:,0]),add(' and y coordinate is ', points[:,1]))

rawDescription: Creating list of strings from numpy array (non-loop solution)


code:
print(sum(ord(i) for i in '{0} {1}'.format(a, b)))
# 727

rawDescription: Converting String to Ordinal Value

description: Converting String to Ordinal Value


rawDescription: stack, push and pop in python

description: Stack, push and pop in python


code: ['NAMETHEFIRST', 'NAMEANOTHERNAME ']

rawDescription: Using csv modele to extract specific lines of text from a larger file


rawDescription: Pandas column values to columns?

description: Pandas column values to columns


rawDescription: How can I make my code more readable and DRYer when working with XML namespaces in Python?

description: Make my code more readable and DRYer when working with XML namespaces in Python


code: soup.find_all("div", id=lambda value: value and value.startswith("span3"))

rawDescription: How to find all divs who's class starts with a string in BeautifulSoup?

description: Find all divs who's class starts with a string in BeautifulSoup


code:
import re

NUMBERS_SEQ = (
    ('dieci', '10'),
    ('undici', '11'),
    ('dodici', '12'),
    ('tredici', '13'),
    ('quattordici', '14'),
    ('quindici', '15'),
    ('sedici', '16'),
    ('diciasette', '17'),
    ('diciotto', '18'),
    ('diciannove', '19'),
    ('venti', '20'),
    ('trenta', '30'),
    ('quaranta', '40'),
    ('cinquanta', '50'),
    ('sessanta', '60'),
    ('settanta', '70'),
    ('ottanta', '80'),
    ('novanta', '90'),
    ('cento', '100'),
    ('mille', '1000'), ('mila', '1000'),
    ('milione', '1000000'), ('milioni', '1000000'),
    ('miliardo', '1000000000'), ('miliardi', '1000000000'),
    ('uno', '1'), ('un', '1'),
    ('due', '2'),
    ('tre', '3'),
    ('quattro', '4'),
    ('cinque', '5'),
    ('sei', '6'),
    ('sette', '7'),
    ('otto', '8'),
    ('nove', '9'),
    )

NUMBERS = dict(NUMBERS_SEQ)

TOKEN_REGEX = re.compile('|'.join('(%s)' % num for num, val in NUMBERS_SEQ))

def normalize_text(num_repr):
    '''Return a normalized version of *num_repr* that can be passed to let2num.'''

    return num_repr.lower().translate(None, ' \t')

def let2num(num_repr):
    '''Yield the numeric representation of *num_repr*.'''

    result = ''

    for token in (tok for tok in TOKEN_REGEX.split(num_repr) if tok):
        try:
            value = NUMBERS[token]
        except KeyError:
            if token not in ('di', 'e'):
                raise ValueError('Invalid number representation: %r' % num_repr)
            continue

        if token == 'miliardi':
            result += '0'*9
        elif token in ('mila','milioni'):
            zeros = '0' * value.count('0')
            piece = result[-3:].lstrip('0')
            result = (result[:-len(piece)-len(zeros)] +
                      piece +
                      zeros)
        elif not result:
            result = value
        else:
            length = len(value)
            non_zero_values = len(value.strip('0'))
            if token in ('cento', 'milione', 'miliardo'):
                if result[-1] != '0':
                    result = (result[:-length] +
                              result[-1] +
                              '0' * value.count('0'))
                    continue
            result = (result[:-length] +
                      value.rstrip('0') +
                      result[len(result) -length + non_zero_values:])
    return add_thousand_separator(result)

def add_thousand_separator(s, sep='.'):
    '''Return the numeric string s with the thousand separator.'''

    rev_s = s[::-1]
    tokens = [rev_s[i:i+3][::-1] for i in range(0, len(s), 3)][::-1]
    return sep.join(tokens)

rawDescription: Convert number to Italian and Italian to number in python


code:
def get_uniq_by_value(data, val_name):
    return {val for value in data.values() for val in value.get(val_name,[])}
data = {
"top1": {
    "key1": [
        "there is no spoon", "but dictionaries are hard",
    ],
    "key2": [
        "mad max fury road was so good",
    ]
},
"top2": {
    "key1": [
        "my item", "foo bar"
    ],
    "key2": [
        "blah", "more junk"
    ]
}}
get_uniq_by_value(data,"key1")

rawDescription: Get unique list items by nested dictionary key


code:
from boto.ec2 import connect_to_region
images = sorted(connect_to_region('us-west-1').get_all_images(owners='self'))
for candidates in images[30:]:
    candidates.deregister()

rawDescription: Deleting the AMI Image

description: Deleting the AMI Image


code:
from sys import modules
modules['sys']
sys

rawDescription: difference between various import statements in python

description: Difference between various import statements in python


code:
def yield_first(iterable):
    for item in iterable or []:
        yield item
        return

rawDescription: Python idiom to return first item or None


code:
terms = [t.lstrip('\u2022 ') for t in terms_elements.stripped_strings
         if t.startswith('\u2022')]

rawDescription: Scrape text after every <br> - BeautifulSoap


code:
sample = np.random.rand(5)
sample

rawDescription: Make Numpy.where stop after first true encountered


code: dict(x.split(":") for x in  re.findall(r"\w+:\s\w+",strs))

rawDescription: Extract categories from text using regular expression


rawDescription: create csv file on each run

description: Create csv file on each run


rawDescription: How to read csv file into Python 2d array?

description: Read csv file into Python 2d array


rawDescription: Compare tuple values in Two lists

description: Compare tuple values in Two lists


code:
def secondary_function(var):
    return var + 1

variable = 1
variable = secondary_function(variable) # variable is now 2

rawDescription: Function within a function to alter a variable


code:
import matplotlib.pyplot as plt
xs = np.linspace(1, 10)
ys = bekkers_cdf(xs,my_a,my_m,my_d,my_start,my_end)
theoretical, =plt.plot(xs,ys,linewidth=2)
x2s = [1,1.5,1.6,1.8,2.1,2.2,3.3,4,6,8,9,10]
y2s = [0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1,1]
data, =plt.plot(x2s,y2s,linewidth=2)
plt.legend([theoretical,data],['theoretical','data'])

rawDescription: How to perform a Kolmogorov-Smirnov goodness of fit test on a custom probability density function in python?

description: Perform a Kolmogorov-Smirnov goodness of fit test on a custom probability density function in python


code:
def supports_slices_and_editing(thing):
    if hasattr(thing, '__setitem__') and hasattr(thing, '__delitem__'):
        try:
            thing[:0]
            return True
        except TypeError:
            pass
    return False

rawDescription: Duck typing trouble. Duck typing test for "i-am-like-a-list"


rawDescription: Python - Why cmp( ) is useful?

description: Python - Why cmp( ) is useful


code:
source = open('myfile', 'r')
processed_lines = []
for line in source:
    line = ','.join(line.split()).replace('\n', 'yes\n')
    processed_lines.append(line)
output = open('out', 'w')
output.write(''.join(processed_lines))

rawDescription: Edit and save file

description: Edit and save file


rawDescription: Python 3: How to create a text progress bar for downloading files?


code: issubclass(bool,int)

rawDescription: Why does concatenating a boolean value return an integer?


code:
class Person(Document):
     @ViewField.define('people')
     def by_name(doc):
         yield doc['name'], doc

rawDescription: Meaning of the map function in couchdb-pythons ViewField


code: [' MESSAGE HIDDEN IN HERE ']

rawDescription: Python Regex Alphabet and spaces

description: Python Regex Alphabet and spaces


rawDescription: Converting items in a tuple Python

description: Converting items in a tuple Python


code: func.__dict__ = getattr(self, 'dict', {})

rawDescription: Reassign a function attribute makes it 'unreachable'


code:
# Vertex
class Vertex:
   def __init__(self):
      self.label = str()
      self.ID = int()
      self.outEdges = list()
      self.inEdges = list()

rawDescription: What good are python classes?

description: What good are python classes


code:
import sys
import sdl2.ext

def run():
    sdl2.ext.init()
    W = sdl2.ext.Window("Default",size=(400,300), flags=sdl2.SDL_WINDOW_BORDERLESS)
    W.show()
    running = True
    while running:
        events = sdl2.ext.get_events()
        for event in events:
            if event.type == sdl2.SDL_QUIT:
                running = False
                break
        W.refresh()
    return 0

if __name__ == "__main__":
    sys.exit(run())

rawDescription: PySDL2: Creating a borderless window

description: PySDL2: Creating a borderless window


rawDescription: using dictionaries and linked list python

description: Using dictionaries and linked list python


code:
c = a[:, :, None] * b[None, None, :]
c.shape

rawDescription: broadcasting — multiply a (NxN) array by a (M) array to have a (NxNxM) array

description: Broadcasting — multiply a (NxN) array by a (M) array to have a (NxNxM) array


code:
expr
expr.xreplace(Transform(split, lambda i: isinstance(i, Integral)))

rawDescription: Distribute integral over a summation in sympy


rawDescription: How do I find the distance between two points?

description: Find the distance between two points


code:
from itertools import islice
from pprint import pprint

def split(seq, l):
    count = sum(len(x[1]) for x in m)
    seq = [(a, iter(b)) for a, b in seq]
    while count > 0:
        group = []
        current_count = 0
        for x in seq:
            data = list(islice(x[1], l-current_count))
            count -= len(data)
            if data:
                if current_count  + len(data) > l:
                    yield group
                    group = [(x[0], data)]
                    current_count = len(data)
                    break
                else:
                    group.append((x[0], data))
                    current_count += len(data)
        yield group

out1 = list(split(m, 3))
out2 = list(split(m, 10))
pprint(out1)
pprint(out2)

rawDescription: Python - Group arrays by limiting number of elements in sub array


rawDescription: Performance bottleneck in creating network with igraph in Python


code:
def interp_piecewise_constant(times,values):
  interpolator = sp.interpolate.interp1d(times, values, kind='zero')
  newTimes = range(times[0], times[-1])
  return(newTimes, interpolator(newTimes))

rawDescription: Function that copies last value for each second until next datapoint in Python 2.7, piecewise constant interpolation (Solved)


code:
filteredDates = []
for day, times in groupby(dates, lambda x: x.date()):
    first, *mid, last = times
    filteredDates.append(first)
    filteredDates.append(last)

rawDescription: Remove certain dates in list. Python 3.4


code: l = [x * 2 for x in l]

rawDescription: How to multiply all integers inside list

description: Multiply all integers inside list


code:
import random

messages = {
    1: ['Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
        'Maecenas eu risus a arcu rutrum vehicula vel in neque.'
        'Curabitur ante sapien, cursus nec diam non, porttitor sagittis leo.',
    ],
    2: ['Nunc et nisi nec ligula placerat accumsan.',
        'In lacinia, neque rutrum aliquet luctus, odio ligula accumsan risus.',
    ],
    3: ['....'],
    # ...
}

def random_by_type(type_number):
    return random.choice(messages[type_number])

rawDescription: Python - most efficient way to select a random message according to a type


code:
ax = 2 # the axis you want to have all values in
np.rollaxis(a, ax, a.ndim)[tuple(np.r_[b,c])]

rawDescription: How to return a subarray of a multidimensional array in Python?

description: Return a subarray of a multidimensional array in Python


code:
def print_monthly_totals (input_csv_filename):
    data = open(input_csv_filename).readlines()
    print('Rainfall totals for each month')
    for line in data:
        columns = line.split(',')
        month, num_days = int(columns[0]), int(columns[1])
        daily_rainfalls = [float(x) for x in columns[2:2+num_days]]
        total_rainfall = sum(daily_rainfalls)

        print('Month {:2}: {:.1f}'.format(month, total_rainfall))

rawDescription: Python more functions

description: Python more functions