code: sorted(d.items(), key=lambda v: (v[1], len(v[0])), reverse=True)

rawDescription: Sort a dictionary 'd' by d.values(), then by length of the corresponding keys


code: out = {f1(*M):tuple(map(f2, N)) for M,N in zip(keys, values)}

rawDescription: Make a dictionary from two lists after applying a function


code:
class Test():
    def __init__(self):
        self.value_1 = 42
    def __eq__(self, other):
        return self.__dict__ == other.__dict__

rawDescription: How to do a deepequals on a object in python

description: Do a deepequals on a object in python


rawDescription: Formatting a replacement from dictionary


code:
def trans(string):
    result = ""
    do_upper = False
    for character in string:
        if character == "*":
            do_upper = not do_upper  # change state; false to true and true to false
            continue  # no need to add the star to the output
        result += character.upper() if do_upper else character
    return result

trans('S*t*a*r*s are every*where*')

rawDescription: Upper case between a char python

description: Upper case between a char python


code: Match(a=3, b=4, size=13)  # value that 'match' variable holds

rawDescription: Use Regular Expressions (or another python module) to compare text/characters?


code:
x, y = pa(lon, lat)
cop = {"type": "Polygon", "coordinates": [zip(x, y)]}
from shapely.geometry import shape
shape(cop).area  # 268952044107.43506

rawDescription: How to calculate the area of a polygon on the earth's surface using python?

description: Calculate the area of a polygon on the earth's surface using python


code: VIstring = ','.join(['%.5f' % num for num in VI])

rawDescription: Convert a numpy array to a CSV string and a CSV string back to a numpy array


code:
import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.CreateStatusBar()

        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel, label="Test")
        self.button.SetToolTipString("This is for testing purposes!")

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.button)

        self.panel.SetSizerAndFit(self.sizer)
        self.Show()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: Wxpython Description of event in status bar


code:
import os
import urllib
path = 'D:%5CMedia%5CMusic%20Videos%5CAlexis%20Jordan%20-%20Good%20Girl%2Emkv'
path = urllib.unquote(path)
path
filename = os.path.splitext(os.path.basename(path))[0]
filename

rawDescription: Python - Getting Filename from Long Path


code:
def binary_search(master_row, source_data,master_search_index, source_search_index):
    lower_bound = 0
    upper_bound = len(source_data) - 1
    found = False
    while lower_bound <= upper_bound and not found:
        middle_pos = (lower_bound + upper_bound) // 2

        if source_data[middle_pos][source_search_index] < master_row[master_search_index]:

            if search([source_data[middle_pos][source_search_index]],[master_row[master_search_index]]):
                return {"result": True, "index": middle_pos}
                break
            lower_bound = middle_pos + 1

        elif source_data[middle_pos][source_search_index] > master_row[master_search_index] :

            if search([master_row[master_search_index]],[source_data[middle_pos][source_search_index]]):
                return {"result": True, "index": middle_pos}
                break
            upper_bound = middle_pos - 1
        else:

            if len(source_data[middle_pos][source_search_index]) > 5:

                return {"result": True, "index": middle_pos}
            else:
                break

rawDescription: Python Linear Search Better Efficiency

description: Python Linear Search Better Efficiency


code:
import re
re._pattern_type
isinstance(re.compile('abc'), re._pattern_type)

rawDescription: Determine whether Python object is regex or string


rawDescription: How can I replace LaTeX $...$ and $$...$$ notations by something like <div>$...$</div>?

description: Replace LaTeX $...$ and $$...$$ notations by something like <div>$...$</div>


rawDescription: PyQt4 new modul

description: PyQt4 new modul


code: ClientThread(arg1, arg2, kwarg1="three times!").start()

rawDescription: Globally-scoped variable: can its value change before it is picked up by the thread?


code:
def f(x):
    y = np.dot(A, x) - b
    return np.dot(y, y)

cons = ({'type': 'eq', 'fun': lambda x: x.sum() - 1})
res = optimize.minimize(f, [0, 0, 0], method='SLSQP', constraints=cons,
                        options={'disp': False})

rawDescription: Solving system using linalg with constraints


rawDescription: Nested for loops in Python compared to map function


code:
import ipdb
import __builtin__

def open(name, mode='', buffer=0):
    if name == 'myfile.txt':
        ipdb.set_trace()  ######### Break Point ###########
    return __builtin__.open(name, mode, buffer)

f = open('myfile.txt', 'r')

rawDescription: Breaking the python code when particular file is being opened


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from bs4 import BeautifulSoup

my_username = "volatil3_"
my_password = "thisispassword"

driver = webdriver.Firefox()
driver.get("http://www.twitch.tv/user/login")
elem_user = driver.find_element_by_id("login_user_login")
elem_passwd = driver.find_element_by_id("user[password]")
elem_user.send_keys(my_username)
elem_passwd.send_keys(my_password + Keys.RETURN)
# In case it need some time to populate the content.
#time.sleep(5)

html = driver.page_source
soup = BeautifulSoup(html)
logginTag = soup.find("a", {"id" : "user_display_name"})
print(logginTag)
driver.close()

rawDescription: Unable to login Twitch TV via script

description: Unable to login Twitch TV via script


code:
def binomial_random_sample(n, p):
    return sum(random.random() < p for j in range(n))

rawDescription: Rewriting numpy.random.binomial using a For loop


code:
[sublist for i, sublist in enumerate(yourlist)
    if i + 1 == len(yourlist) or (sublist[0], sublist[4]) != (yourlist[i+1][0], yourlist[i + 1][4])]

rawDescription: How to remove an entry in a list based on a value in the sublist

description: Remove an entry in a list based on a value in the sublist


code:
def make_inverse_arg(parser, *args, **kwargs):
    parser.add_argument(*args, **kwargs)
    # define inverse
    arg1 = '--no-'+args[1][2:]
    parser.add_argument(arg1, action='store_true')
    # could be more robust, but you get the idea
    def post_test():
         ...
    return post_test

rawDescription: How can I easily create a python argparse argument with an inverse?

description: Easily create a python argparse argument with an inverse


code:
class ProductsHandler(webapp.RequestHandler):
    def get(self, resource):
        self.response.headers['Content-Type'] = 'text/plain'
        table = self.request.url
        self.response.out.write(table)
        self.response.out.write("\n")
        self.response.out.write(resource)

def main():
    application = webapp.WSGIApplication([
        ('/products/(.*)', ProductsHandler)
        ],
        debug=True)
    util.run_wsgi_app(application)

rawDescription: app-engine: Request Data

description: App-engine: Request Data


code:
fields = ['title', 'description', 'name']

foo = Foo()
for field in fields:
    setattr(foo, field, "value")
foo.save()

rawDescription: Using variables when referring to an objects datamember


code:
MEDIA_URL = 'http://192.168.0.1/gallery/media/'
ADMIN_MEDIA_PREFIX = '/gallery/admin_media/'
SESSION_COOKIE_PATH = '/gallery'
LOGIN_REDIRECT_URL = '/gallery/'
LOGIN_URL = '/gallery/accounts/login/'
LOGOUT_URL = '/gallery/accounts/logout/'

rawDescription: multiple instances of django on a single domain

description: Multiple instances of django on a single domain


code:
df = pd.DataFrame([[ 1,  0, 12],
                   [ 1,  0,  1],
                   [ 1,  1,  2],
                   [ 1,  1,  3],
                   [ 2,  1,  3],
                   [ 2,  0,  4],
                   [ 2,  1,  1],
                   [ 3,  0,  2],
                   [ 3,  0,  3],
                   [ 3,  1,  4]],
                  columns=['User', 'Enrolled', 'Time'])

def filter_enrollment(df):
    enrolled = df[df.Enrolled == 1].index.min()
    return df[df.index <= enrolled]

result = df.groupby('User').apply(filter_enrollment).reset_index(drop=True)

rawDescription: Remove all data in a DF by group based on a condition (pandas,python3)


code:
x = 'London, ENG, United Kingdom / Melbourne, VIC, Australia / Palo Alto, CA USA'
re.findall(r'(?:\w+(?:\s+\w+)*,\s)+(?:\w+(?:\s\w+)*)', x)

rawDescription: Regex for location matching - Python

description: Regex for location matching - Python


code:
from itertools import chain
print(list(chain.from_iterable(zip(*array))))

rawDescription: Python: How to change the location of multiple values in a csv file into a single line values?


code:
cdic = default_attribute_dict.from_dictionaries(dic, default=lambda: 100)
cdic.keys
cdic['keys']
cdic.keys
cdic.keys()

rawDescription: Python 2.7 how to define a super powerful class-style dict object?


code:
def binary_search(collection, x):
    while collection:
        center = len(collection) / 2

        if collection[center] == x:
            return True
        elif collection[center] < x:
            collection = collection[center + 1:]
        else:
            collection = collection[:center]
    else:
        return False

rawDescription: Infinite Loop i don't know why ( DichotomySearch )


rawDescription: PySpark: How to remove duplicates from a RDD by first occurance?


code:
class ModelBase(models.Model):
    def __unicode__(self):
        # I choose `unicode` here since it is a superset of __str__ ...
        return self.__str__()

class A(ModelBase):
    def __str__(self):
        return 'Hello World!'

rawDescription: is it possible to dynamically define a method's name?

description: Is it possible to dynamically define a method's name


code:
{'Adj': 'fine |delicious |perplexed |pickled ',
 'DT': 'the |a | every ',
 'NP': 'DT Noun |NP PP ',
 'Noun': 'Adj Noun |president |sandwich |pickle |chief of staff |floor ',
 'PP': 'Prep NP ',
 'Prep': '   with |on |under |   in ',
 'ROOT': 'S . |S ! |is it true that S ? ',
 'S': '  NP VP ',
 'VP': ' Verb NP ',
 'Verb': 'ate |wanted |kissed |understood |pickled '}

rawDescription: List to Dictionary

description: List to Dictionary


code:
import sys
import tkinter as tk
TITLE_FONT = ("Helvetica", 18, "bold")

class SampleApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        menubar = tk.Menu(self)
        file_menu = tk.Menu(menubar)
        file_menu.add_command(label='Quit', command=sys.exit)
        menubar.add_cascade(label='File', menu=file_menu)
        self.config(menu=menubar)

        self.frames = {}
        for F in (StartPage, PageOne,
                  # PageTwo
                  ):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, c):
        frame = self.frames[c]
        frame.tkraise()

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="This is the start page", font=TITLE_FONT)
        label.pack(side="top", fill="x", pady=10)
        button1 = tk.Button(self, text="Go to Page One",
                                command=lambda: controller.show_frame(PageOne))
        button1.pack()

class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="This is page 1", font=TITLE_FONT)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame(StartPage))
        button.pack()

if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

rawDescription: menu tk in python

description: Menu tk in python


code:
year = range(2006,2011)
month = range(1,13)
day = range(1,31)

rawDescription: Convenient way to slice from multiindexed rows based on range of keys at different levels with pandas dataframe


code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from scrapy.item import Item, Field

class MyItem(Item):
    url=Field()

class someSpider(CrawlSpider):
  name = "My script"
  domain=raw_input("Enter the domain:\n")
  allowed_domains = [domain]
  starting_url=raw_input("Enter the starting url with protocol:\n")
  start_urls = [starting_url]
  items={} #dictionary with your URLs as keys
  f=open("items.txt","w")

  rules = (Rule(LxmlLinkExtractor(allow_domains=(domain)), callback='parse_obj', follow=True),)

  def parse_obj(self,response):
    for link in LxmlLinkExtractor(allow_domains=(self.domain)).extract_links(response):
        if link not in self.items: #check if it's already parsed
            self.items[link]=1  #add to dictionary as key if it's not parsed yet (stored value can be anything)
            #do your job on adding it to a file
            item = MyItem()
            item['url'] = link.url
            self.f.write(item['url']+"\n")

rawDescription: How to stop my crawler from logging duplicates?

description: Stop my crawler from logging duplicates


code:
with open('bigfile.log','r') as inF:
   for line in inF:
       elements = line.split()
       if sites.intersection(elements):
           count += 1

rawDescription: python: searching a text file for values in a list

description: Python: searching a text file for values in a list


code:
while True:
    line = f.readline().strip()
    if line == '':
        # either end of file or just a blank line.....
        # we'll assume EOF, because we don't have a choice with the while loop!
        break

rawDescription: How to while loop until the end of a file in Python without checking for empty line?

description: While loop until the end of a file in Python without checking for empty line


code:
import numpy as np
ar = np.array([['replaceme', 1,2], ['replaceme', 3,4],['replaceme', 5,6]], dtype=object)
ar
ar == "replaceme"

rawDescription: Using mask to replace string in numpy

description: Using mask to replace string in numpy


code: Sparcy Libs Darwin Aaple

rawDescription: Dynamically creating classes in python and __repr__


code:
from django.template.defaulttags import register

@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

rawDescription: Django, creating variables in a Template and assigning a value


code: pd.concat([df2, df], axis=1)

rawDescription: Concatenate 2 dataframes with uneven lengths and no index


code:
import re

from selenium.webdriver.support.expected_conditions import _find_element

class text_match(object):
    def __init__(self, locator, regexp):
        self.locator = locator
        self.regexp = regexp

    def __call__(self, driver):
        element_text = _find_element(driver, self.locator).text
        return re.search(self.regexp, element_text)

rawDescription: Perform a WebDriverWait() or similar check on a Regular Expression in Python


rawDescription: Adding binary header

description: Adding binary header


code:
from euclid import *
circ = Circle(Point2(3., 2.), 2.)
line = Line2(Point2(0., 0.), Point2(-1., 1.))
line.distance(circ)

rawDescription: Closest point on a circle to a line segment python


code:
class Test(object):
    def __init__(self, c = SomeDefaultValue):
        self.__c = SomeDefaultValue
    @property
    def c(self):
        return self.__c
    @c.setter
    def c(self,value):
        self.__c = value

rawDescription: Dynamically update attributes of an object that depend on the state of other attributes of same object


code:
d = {row[0]: row[1:] for row in zip(a['columns'], *a['data'])}
d

rawDescription: How to get max value for a specific key from a python dictionary

description: Get max value for a specific key from a python dictionary


code:
pipe = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, stderr=sys.stderr)
while True:
   chunk = pipe.stdout.read(4096)
   if not chunk:
       break
   # ... process chunk of data ...

rawDescription: Recieving multiple files from ffmpeg via subprocesses.PIPE


code:
import sre_parse
import sys

class PseudoStdout:
    def __init__(self):
        self.contents = ''
    def __enter__(self): # this and __exit__ are for context management
        self.old_stdout = sys.stdout
        sys.stdout = self
    def __exit__(self, type_, value, traceback):
        sys.stdout = self.old_stdout
    def write(self, text): # magic method that makes it behave like a file
        self.contents += text

pattern = r"(?P<TEST>test)\s+\w*(?P=TEST)|abcde"
parsedpattern = sre_parse.parse(pattern)

ps = PseudoStdout()
with ps:
    parsedpattern.dump()

print(repr(ps.contents))

rawDescription: REGEX - String version of the parsing of a pattern done by `sre_parse`


code:
def isNonStringIterable(x):
  if isinstance(x, basestring):
    return False
  try: iter(x)
  except: return False
  else: return True

rawDescription: What is the pythonic way of checking if an object is a list?


code:
import MySQLdb

host = '192.168.99.100'
user = 'myuser'
password = 'secret'
port = 3306
db = 'test'

conn = MySQLdb.Connection(
    host=host,
    user=user,
    passwd=password,
    port=port,
    db=db
)

# Example of how to insert new values:
conn.query("""INSERT INTO mytable VALUES ('foo3', 'bar2')""")
conn.commit()

# Example of how to fetch table data:
conn.query("""SELECT * FROM mytable""")
result = conn.store_result()
for i in range(result.num_rows()):
    print(result.fetch_row())

rawDescription: best way for python to interface with MySQL

description: Best way for python to interface with MySQL


rawDescription: Python fill matrix with specific values

description: Python fill matrix with specific values


code: "Exclusion: ANT100Y5"

rawDescription: XPath: Select Current and Next Node's text by Current Node Attributes


code: lists[0] is list1

rawDescription: Print a name of a list within a list

description: Print a name of a list within a list


code:
# call object pool for account.invoice
invoice_pool = self.pool.get("account.invoice")

# here you need the invoice_id to get the data.
# you can get it by parsing the parameter context
found_invoices = invoice_pool.read(cr, uid, [invoice_id,], ["invoice_line_ids"], context)

# It returns a list, but i gave only one invoice_id.
# the list has maximun one element. we need the frist element
found_invoice = found_invoices[0] if found_invoices else None

invoice_line_ids = found_invoice["invoice_line_ids"]

# the same with "account.invoice.line"
invoice_line_pool = self.pool.get("account.invoice.line")
invoice_lines = invoice_line_pool.read(cr, uid, invoice_line_ids, ["product_id"], context)

# Here you have the product ids
# I don't need to get the first element, because it returns a int
product_ids = [line["product_id"] for line in invoice_lines]

rawDescription: How to fetch values from a one2many field in odoo

description: Fetch values from a one2many field in odoo


code:
def foo2(indexable):
    return indexable.__getitem__

rawDescription: Inverse of `operator.itemgetter`

description: Inverse of `operator.itemgetter`


code: diff = diff.reshape(-1)

rawDescription: Best approach for getting the first differential in all directions and all elements


rawDescription: How to parse text in multiple body tags with BeautifulSoup in Python?

description: Parse text in multiple body tags with BeautifulSoup in Python


code: dv = list(seqDic)

rawDescription: Learning Python and using dictionaries

description: Learning Python and using dictionaries


code:
link = 'login'
if user.is_authenticated:  link = 'vote'

rawDescription: Django: is variables in templates a good idea?


code:
from datetime import datetime, timedelta
s = "20120213"
# you could also import date instead of datetime and use that.
date = datetime(year=int(s[0:4]), month=int(s[4:6]), day=int(s[6:8]))

rawDescription: How to convert integer into date object python?

description: Convert integer into date object python


code:
import collections
import datetime as DT
import pytz

tzones = collections.defaultdict(set)
abbrevs = collections.defaultdict(set)

for name in pytz.all_timezones:
    tzone = pytz.timezone(name)
    for utcoffset, dstoffset, tzabbrev in getattr(
            tzone, '_transition_info', [[None, None, DT.datetime.now(tzone).tzname()]]):
        tzones[tzabbrev].add(name)
        abbrevs[name].add(tzabbrev)

rawDescription: Python: All possible Timezone Abbreviations for given Timezone Name (and vise versa)


rawDescription: Recursively walking a Python inheritance tree at run-time


code:
c4data = [header3, r1c3data, r2c3data]
for i, row in enumerate(list_of_lists):
    row.append(c4data[i])

rawDescription: Add specific columns to a single row list (might be a little basic)


code:
{
    u'YYY Intl 20150903': {u'CA desktopfeed': 4.0},
    u'XXX 20160314': {
        u'Carnival desktopfeed': 4.0,
        u'PYS Broad desktopfeed': 742.0,
        u'PYS Broad mobilefeed': 2384.0,
        u'Carnival mobilefeed': 1176.0
    }
}

rawDescription: Applying dictionary comprehension to a defaultdict


code:
for w in G[v]:
    if w < s:
        G[v].pop(G[v].index(w))

rawDescription: Enumerating cycles in a graph using Tarjan's algorithm


rawDescription: Managing big point lists, best approach?

description: Managing big point lists, best approach


code:
phrases = open("phrase.txt").readLines()

for phrase in phrases:
    search= phrase.lower()
    words = open("text.txt", "r")
    for word in words:
        if search in word:
            print(search)
    words.close()

rawDescription: Find phrases from one text file in another text file with python


code:
def grouper(iterable, chunksize):
    i = iter(iterable)
    while True:
        chunk = Wrap(list(itertools.islice(i, int(chunksize))))
        if not chunk.val:
            break
        yield chunk.unlink()

rawDescription: Python: yield-and-delete

description: Python: yield-and-delete


code:
for parsed_hand in parse_preflop_hand(unparsed_hand):
    ...

rawDescription: Python: Best way to parse the following

description: Python: Best way to parse the following


code:
import sqlite3
conn = sqlite3.connect('serials.db') #Will create a new table as it doesn't exist right now
cur = conn.cursor() #We will use this to execute commands
cur.execute('''CREATE TABLE serials_tb (serial text)''') #for more than one column add a comma, as in a tuple, and write '[COL_NAME] [COL_TYPE]' without the apostrophes. You might want (as I suppose you only want a serial to be used once) to define it as a primary key
conn.commit()
conn.close()

rawDescription: Copycating static variables (file scope) behavior


rawDescription: Return random value from list tuple

description: Return random value from list tuple


code:
def settings(request):
    user = request.user.get_profile()
    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance = user)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('')

    form = UserProfileForm(instance = user)
    return render(request, "settings.html", {'form': form})

rawDescription: Question about Django and User Auth

description: Question about Django and User Auth


rawDescription: Solving a task in cosmology using Python 2.7.5


rawDescription: Getting the Index of a multi-line pattern in Python


code:
# 2.6+ property for 2.5-
if sys.version_info[:2] < (2, 6):
    # define our own property type
    class property():
        "2.6 properties for 2.5-"
        def __init__(self, fget=None, fset=None, fdel=None, doc=None):  ...
        def __call__(self, func):  ...
        def __get__(self, obj, objtype=None):  ...
        def __set__(self, obj, value):  ...
        def __delete__(self, obj):  ...
        def setter(self, func):  ...
        def deleter(self, func):  ...

rawDescription: Future Development in Python 2.4

description: Future Development in Python 2.4


code:
import difflib

def diff(a, b):
    add, remove = [], []
    for line in difflib.ndiff(a, b):
        d, line = line[0], line[2:]
        if d in '+-':
            (add if d=='+' else remove).append(line)
        elif add or remove:
            yield remove, add
            add, remove = [], []
    if add or remove:
        yield remove, add

rawDescription: Finding locations where two strings differ


code:
parser1 = argparse.ArgumentParser(add_help=False)
parser1.add_argument("first")
args1, remaining_args = parser1.parse_known_args(["arg1","arg2"])

parser2 = argparse.ArgumentParser() #parents=[parser1]) #NO PARENT!
parser2.add_argument("second")
args2 = parser2.parse_args(remaining_args,args1)

assert args2.first == "arg1" and args2.second == "arg2"

rawDescription: How ca I get Python ArgParse to stop overwritting positional arguments in child parser


code: zip(*t)

rawDescription: Python zip single list element

description: Python zip single list element


rawDescription: What's the best way to split a string into fixed length chunks and work with them in Python?


rawDescription: Any better algorithm possible here?

description: Any better algorithm possible here


code:
import pymc as pm

import random
import numpy as np
import matplotlib.pyplot as plt

with pm.Model() as model:
    # Prior is uniform: all cases are equally likely
    p = pm.Uniform('p', lower=0, upper=1)

    # set constants
    p_true = 0.05  # remember, this is unknown.
    N = 1500

    # sample N Bernoulli random variables from Ber(0.05).
    # each random variable has a 0.05 chance of being a 1.
    # this is the data-generation step
    occurrences = []  # pm.rbernoulli(p_true, N)
    for i in xrange(N):
        occurrences.append((random.uniform(0.0, 1.0) <= p_true))
    occurrences = np.array(occurrences)
    obs = pm.Bernoulli('obs', p, observed=occurrences)

    start = pm.find_MAP()
    step = pm.Metropolis()
    trace = pm.sample(18000, step, start)

pm.traceplot(trace);

rawDescription: Porting pyMC2 Bayesian A/B testing example to pyMC3


rawDescription: Calculating pixel in array

description: Calculating pixel in array


code:
def strip_defaults(dct, defaults):
    return {key:value for key,value in dct.items() if value != defaults[key]}

res = [strip_defaults(d, defaults) for d in data]
pp(res)

rawDescription: Converting an unknown data structure to a known data structure in Python


rawDescription: Background process that will kill the current process


code:
x = linspace(0, 2, 100)
f = lambda x: 2**x
fig, ax = subplots()
ims = []
for delta in range(15):
    ims.append(list(ax.plot(x, f(x) + delta, c='r') +
                    ax.plot(x, (f(x) + delta)**2, c='b'))
    )
im_ani = ArtistAnimation(fig, ims)
show()

rawDescription: Matplotlib save individual "ims" (animation parts) as image


code:
class MonstersMeta(type):
    def __new__(metaclass, name, bases, namespace):
        cls = super(MonstersMeta, metaclass).__new__(metaclass, name, bases, namespace)
        if issubclass(cls, Monster) and not cls is Monster:
            Monster.monsters.append(cls)
        return cls

class Monster(object):
    __metaclass__ = MonstersMeta
    monsters = []

class Lochness(Monster):
    pass

class Yeti(Monster):
    pass

rawDescription: Executing code after construction of class object


code:
items = re.findall('([A-Z])(\d+)', 'P600F600')
{key: int(value) for key, value in items}

rawDescription: Build a dictionary with a regular expression


code:
A=np.genfromtxt(txt, delimiter=' ,',dtype=str)
A
A.shape

rawDescription: 2D Numpy Array of Strings WITH column access


rawDescription: Changing the __name__ of a generator

description: Changing the __name__ of a generator


code:
def player(l):
    return min(player(l[:-1]), player(l[:-2])) + l[-1] if l else 0

rawDescription: Need Help Writing Recursive function that find cheapest route through a list of numbers


code:
g.last()-g.first()
result = g.last()-g.first()
result['ts'] = result['ts'] / Timedelta('1m')
result

rawDescription: Calculating time elapsed on a groupby object


code:
def my_func(word_set):
    with open('file_name') as f:
        for line in f:
            if any(i in line for i in word_set):
                return True
        return False

rawDescription: Filtering for multiple strings on f.read


code: ' '.join(reversed(s.split()))

rawDescription: Reverse String order

description: Reverse String order


rawDescription: find the set of integers for which two linear equalities holds true

description: Find the set of integers for which two linear equalities holds true


code: self.gauge_1 = wx.Gauge(self.notebook_1_pane_1, -1, 100)

rawDescription: Wxpython's gauge not refreshing

description: Wxpython's gauge not refreshing


code: df['pct_ch'] = df.groupby('product_desc')['prod_count'].apply(lambda x: x.pct_change() + 1)

rawDescription: How to create rolling percentage for groupby DataFrame

description: Create rolling percentage for groupby DataFrame


rawDescription: Convert binary to ASCII and vice versa

description: Convert binary to ASCII and vice versa


code:
from sklearn.linear_model import LogisticRegression
# generating some dataset
from hep_ml.commonutils import generate_sample
X, y = generate_sample(n_samples=1000, n_features=10)
trained_regressor = LogisticRegression().fit(X, y)

rawDescription: How do I view a model produced using scikit-learn?

description: View a model produced using scikit-learn


code:
import pandas as pd
pd.read_csv(r'my_path_to_file/my_file.csv', sep=';').sum().values

rawDescription: Sum Each Column of CSV file

description: Sum Each Column of CSV file


code: xlwt.Utils.rowcol_to_cell(5, 2)

rawDescription: Python xlwt - Convert column integer into excel cell references. Eg (3,6) to C6


rawDescription: Freezing all but one positional arguments


code: lev = Level.LevelMgr(window)

rawDescription: Namespaces and Accessing Tkinter

description: Namespaces and Accessing Tkinter


code:
from .module1 import __all__ as _all1
from .module2 import __all__ as _all2
from .module1 import *
from .module2 import *

__all__ = _all1 + _all2

rawDescription: Python - Can I import specific classes when importing all from a package


rawDescription: Why is target.write ignoring my %r formatting?


code:
from operator import itemgetter

max(inputlist, key=itemgetter(1))[0]

rawDescription: Find the top value from a list of tuples


code:
name = 'Bob'
type(name)
salary = 50000
type(salary)

rawDescription: "For each attribute, give the class it is."


code:
import sys
from PyQt4 import QtGui

class PermanentMenu(QtGui.QMenu):
    def hideEvent(self, event):
        self.show()

class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.menu = PermanentMenu()

        self.menu.addAction('one')
        self.menu.addAction('two')

        self.submenu = self.menu.addMenu('submenu')
        self.submenu.addAction('sub one')
        self.submenu.addAction('sub two')

        self.submenu2 = self.menu.addMenu('submenu 2')
        self.submenu2.addAction('sub 2 one')
        self.submenu2.addAction('sub 2 two')

        layout = QtGui.QHBoxLayout()
        layout.addWidget(self.menu)
        self.setLayout(layout)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    w = Window()
    w.show()

    sys.exit(app.exec_())

rawDescription: Qt/PyQt: How do I use a QMenu as a permanent widget?


code:
from curses import wrapper
def main(stdscr):
    stdscr.clear()  # clear above line.
    for r in range(5,10):
      for c in range(10, 20):
        stdscr.addstr(r, c, '#')
    stdscr.addstr(11, 0, 'Press Key to exit: ')
    stdscr.refresh()
    stdscr.getkey()

wrapper(main)

rawDescription: What's the short way to add same symbol at the specified place in ncurses?


rawDescription: Error in writing Python dictionary to a file


code:
# This is a class method to my ScheduledRun class that has
# a foreign key to a PeriodicTask.  PeriodicTask has a
# FK to a CrontabSchedule, which I'd like to "trim"
# if nothing points to that FK anymore.
@classmethod
def _post_delete(cls, instance, **kwargs):
    instance.periodic_task.delete()
    # Delete the crontab if no other tasks point to it.
    # This could cause a cascade if we don't check all related...
    filter = dict(id=instance.crontab.id)
    for related in instance.crontab._meta.get_all_related_objects():
        filter[related.var_name] = None
    assert('id' in filter)
    assert('schedule' in filter)
    assert('periodictask' in filter)
    CrontabSchedule.objects.filter(**filter).delete()

rawDescription: How to Cleanup Django Orphan Foreign Key Values?


code: [b.index(i) for i in a if i in b]

rawDescription: Check if items in list a are found in list b and return list c with matching indexes of list b in Python


code:
Person().bound()
Person().unbound()

rawDescription: Why isn't self being automatically passed to a method that is set on an object after its instantiation?


rawDescription: How do I save a mode 'F' image? (Python/PIL)

description: Save a mode 'F' image? (Python/PIL)


rawDescription: reading Lotus Notes documents via COM

description: Reading Lotus Notes documents via COM


code:
my_func = lambda x, y: x+y
result = my_func(1, 2)
print(result) #=>3

rawDescription: python: Primary school Arithmetic quiz- saving results to a .txt file

description: Python: Primary school Arithmetic quiz- saving results to a .txt file


code:
unmatched = [l for l in link_ids if l not in {getattr(f,'fname') for f in files}]
# -> ['111', '333']

rawDescription: Python efficient way to compare list item with partial item from other list


code:
def getelements(lst, key, res=None):
    if res is None:
        res = []
    for e in lst:
        if isinstance(e, list):
            if e[0] == key:
                res.append(e)
            else:
                getelements(e, key, res)
    return res

rawDescription: Python Navigate Through Nested List Like Tree


code:
a = 1
b = 2
s = 0
while b <= 4000000:
    if not b % 2:
        s += b
    a, b = b, a + b
print(s)

rawDescription: Project Euler #2

description: Project Euler #2


code:
list(split_subsequences([1, 2, 3, 4], length=2))
list(split_subsequences([1, 2, 3, 4], length=2, overlap=1))

rawDescription: Python Equivalent to Ruby's #each_cons?

description: Python Equivalent to Ruby's #each_cons


code:
hndl = sys.dllhandle
pythondll = ctypes.CDLL('python dll',  handle=hndl)

rawDescription: How to get current Python DLL?

description: Get current Python DLL


rawDescription: Trying to figure out the run time of my function


code: [classes_inverse.get(t, "No Match") for t in tags]

rawDescription: Unable to match tuples items to list items


code:
def change_value1(self, val): # new value is passed as an argument
    # so no need for this
    # val = self.spinbox1.value()

    new_val = round(val*5)/5 # one way to fix
    if val != new_val:       # if value is changed, put it in the spinbox
        self.spinbox1.setValue(new_val)

    self.lcd1.display(new_val)

rawDescription: Fix values that are typed into a doublespinbox in PyQt


code:
joedict = {}
for item in joe:
    joedict.setdefault(item[0], []).append(item[1])

rawDescription: How can I access and sort lists within lists in python?

description: Access and sort lists within lists in python


code: [tuple(map(str, xs)) for xs in lst]

rawDescription: Convert list of tuples of mixed data types into all string


code:
from sqlalchemy.types import VARCHAR
from sqlalchemy import func

class HashColumn(VARCHAR):

    def bind_expression(self, bindvalue):
        # convert the bind's type from String to HEX encoded
        return func.HEX(bindvalue)

    def column_expression(self, col):
        # convert select value from HEX encoded to String
        return func.UNHEX(col)

rawDescription: Python-Sqlalchemy Binary Column Type HEX() and UNHEX()


code:
from struct import pack

for i, token in enumerate(b"foo bar bazq".split()):
    print(pack('@B%ds' % len(token), i, token))

rawDescription: Increment efficiently over a sequence of integers in byte representation


rawDescription: Pandas Dataframe: get index of max element


code:
li=[['boy','121','is a male child'],['boy','121','is male'],['boy','121','is a child'],['girl','122','is a female child'],['girl','122','is a child']]

d={}

for i,j,k in li:
  d.setdefault((i,j),[]).append(k)

d

rawDescription: Reduce list of lists if entries match

description: Reduce list of lists if entries match


rawDescription: Given an iterable, how to apply a function in every possible combination?


code:
capitalLetters = 0
for letter in word:
    if letter.isupper():
        capitalLetters += 1

rawDescription: Counting if the word entered is a capital letter in a loop in Python 3


code:
Node = namedtuple_with_defaults('Node', 'val left right')
Node()
Node = namedtuple_with_defaults('Node', 'val left right', [1, 2, 3])
Node()
Node = namedtuple_with_defaults('Node', 'val left right', {'right':7})
Node()
Node(4)

rawDescription: Named tuple and optional keyword arguments


rawDescription: Unable to perform join in the inner lists of a list of lists


code:
class Counter:
   def __init__(self, initial=0):
      self.value = initial

   def increment(self, amount=1):
      self.value += amount
      return self.value

   def __iter__(self, sentinal=False):
      return iter(self.increment, sentinal)

rawDescription: Incrementing a counter using ipython widgets


code:
import codecs
codecs.decode('АБВ\\u003d\\"res', 'unicode_escape').encode('latin1').decode('utf8')

rawDescription: Python: decoding a string that consists of both unicode code points and unicode text


code:
todefine = [('MyAbcClass', AbcClass), ...]
for name, base in todefine:
    globals()[name] = type(name, (MyMixin, base), {})

rawDescription: Defining same method override on lots of classes: DRY?


code:
class MyItem(QObject):

    nameChanged = pyqtSignal()

    def __init__(self, name, parent=None):
        QObject.__init__(self, parent)
        self._name = name

    @pyqtProperty('QString', notify=nameChanged)
    def name(self):
        return self._name

class MyModel(QAbstractListModel):
    NameRole = Qt.UserRole + 1
    _roles = {NameRole: "name"}

    def __init__(self, parent=None):
        super().__init__(parent)
        self._items = [MyItem('one'), MyItem('two'), MyItem('three')]
        self._column_count = 1

    def roleNames(self):
        return self._roles

    def rowCount(self, parent=QModelIndex()):
        return len(self._items)

    def data(self, index, role=Qt.DisplayRole):
        try:
            item = self._items[index.row()]
        except IndexError:
            return QVariant()

        if role == self.NameRole:
            return item.name

        return QVariant()

rawDescription: Use a QSortFilterProxyModel from QML with PyQt5


code:
myDict = {'A':[1,2,3,4], 'B':[5,6,7,8], 'C':'str', 'D':'str'}
myDict = {key:np.array(val) if key not in {'C', 'D'} else val for key, val in myDict.iteritems()}

rawDescription: Python Dictionary value assignment with list comprehension


code:
from PyQt4 import QtGui, QtCore

class MainWindow(QtGui.QMainWindow):

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

        btn = QtGui.QPushButton(self)
        btn.setStyleSheet("border-image: url('somepicture.png');")  # Scaled
        #btn.setStyleSheet("background-image: url('somepicture.png');")  # Not scaled

        self.setCentralWidget(btn)

        self.show()

app = QtGui.QApplication([])
window = MainWindow()

app.exec_()

rawDescription: PyQt: How can i set stylesheet contents on scaled mode?


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

store['df'] = df  # save it
store['df']  # load it

rawDescription: How to store data frame using PANDAS, Python

description: Store data frame using PANDAS, Python


rawDescription: arithmetic comparisons on numpy arrays

description: Arithmetic comparisons on numpy arrays


code:
sample = [1, 3, 6, 7, 7, 7, 7, 8]
set(sample)
newsample = 'LollaPAloOza'
set(newsample)

rawDescription: Count all characters, then print how many of which characters


code:
#!/usr/local/opt/python/bin/python2.7
import sys
sys.path[0:0] = [
  '/path/to/awesome/parts/google_appengine',
  '/path/to/awesome/app',
  ]
import dev_appserver
dev_appserver.fix_sys_path()
...

rawDescription: How can I generate a custom python interpreter using zc.buildout that includes my initialization code?

description: Generate a custom python interpreter using zc.buildout that includes my initialization code


rawDescription: Getting the closest date to a given date


code:
a=np.array([1,2,3,4,5])
b=np.array([6,7,8,9,10])
c=[np.complex(x,y) for x,y in zip(a,b)]

for x in c:
    c[np.abs(c-x)<5]

rawDescription: Numpy data points region/circle

description: Numpy data points region/circle


rawDescription: Tensor multiplication with numpy tensordot


rawDescription: Grouping data by frequency

description: Grouping data by frequency


code: df2.resample('10A', how='mean')  # 'A'=Annual, '10A'=TenYears

rawDescription: How to use Pandas to take multi year average in Python

description: Use Pandas to take multi year average in Python


rawDescription: Suppressing scientific notation in pandas?


code:
vals = [-0.7, -3.7, -2.1, -5.8, -1.2 ]
label_inds_vals = sorted([thing for thing in enumerate(vals)], key=lambda x: x[1])

rawDescription: How can you get the order back after using argsort?

description: Get the order back after using argsort


code:
l = sc.recv(1024)

imageDict = pickle.dumps(l)

rawDescription: Send multiple data (text and images) to a server through a socket


rawDescription: Get the subdictionary based on range

description: Get the subdictionary based on range


code:
Input:         Module(body=[Assign(targets=[Name(id='t', ctx=Store())], value=BinOp(left=Name(id='r', ctx=Load()), op=Mult(), right=Name(id='p', ctx=Load())))])
Substituted:   Module(body=[Assign(targets=[Name(id='t', ctx=Store())], value=BinOp(left=Call(func=Name(id='sqrt', ctx=Load()), args=[BinOp(left=BinOp(left=Name(id='x', ctx=Load()), op=Pow(), right=Num(n=2)), op=Add(), right=BinOp(left=Name(id='y', ctx=Load()), op=Pow(), right=Num(n=2)))], keywords=[], starargs=None, kwargs=None), op=Mult(), right=Name(id='p', ctx=Load())))])
t = r*p
t = 3.60555127546

rawDescription: Parsing an equation with sub-formulas in python


code:
self.radioButtons = []
for x in range(2, randInt):
        self.radioButtons.append(Radiobutton(self, text = "Button", variable = self.RadVar, value = x))
        self.radioButtons[-1].grid(row = x) # layout the most recent one

rawDescription: How to delete (or de-grid) Tkinter GUI objects stored in a list (Python)

description: Delete (or de-grid) Tkinter GUI objects stored in a list (Python)


code:
import os
import multiprocessing as mp
import contextlib
import time
import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as UI
import selenium.webdriver.support.expected_conditions as EC
import psutil

def worker(browsername, args, N):
    start_mem = psutil.virtual_memory()
    Driver = getattr(webdriver, browsername)
    drivers = [Driver(*args) for i in range(N)]
    end_mem = psutil.virtual_memory()
    for driver in drivers:
        driver.quit()
    return end_mem.used - start_mem.used

if __name__ == '__main__':
    N = 10
    pool = mp.Pool(1)

    for driver, args in [('Firefox', ()),
                         ('Chrome', ()),
                         ('PhantomJS', ('phantomjs',))]:
        used = pool.apply(worker, [driver, args, N])
        print('{:>10}: {}'.format(driver, used))
        time.sleep(5)

    pool.close()
    pool.join()

rawDescription: Benchmarking memory consumption of Firefox vs Chrome in webdriver


code:
import pyqrcode
qr = pyqrcode.create("HORN O.K. PLEASE.")
qr.png("horn.png", scale=6)

rawDescription: How to decode a QR-code image in (preferably pure) Python?

description: Decode a QR-code image in (preferably pure) Python


code:
def pad_list(input_string, pad_length, pad_char='0'):
    base_version = input_string.split('.')[:pad_length]
    missing_entries = [pad_char] * pad_length - len(base_version)
    return base_version + missing_entries

rawDescription: String split with minimum size

description: String split with minimum size


code:
your_async_function.apply_async(args=(your, args, tuple),
                                kwargs={your: kwargs},
                                countdown=15 * 60)

rawDescription: Python/Django: Schedule task in realtime


code: cur.execute("UPDATE student_Data SET attendance = 1 WHERE bluetooth_Id = '%s"%(bluetoothId)+"'")

rawDescription: Python Update in MySQL

description: Python Update in MySQL


code:
person = Person('john')
person = Person('james')
# Whoops! 'john' has died!

people = []
people.append(Person('john'))
# ...
# All 'Persons' live in people
people = []
# Now all 'Persons' are dead (including the list that referenced them)

class House():
    def setOwner(self, person):
        self.owner = person

house.setOwner(people[0])
# Now a House refers to a Person
people = []
# Now all 'Persons' are dead, except the one that house.owner refers to.

rawDescription: How to give object away to python garbage collection?

description: Give object away to python garbage collection


code: paths[w]=paths[v]+[w]

rawDescription: Python: how to compute the number of shortest paths passing through one node?


code:
import sqlite3

def insert_or_replace():
    # https://sqlite.org/lang_insert.html
    connection=sqlite3.connect(':memory:')
    cursor=connection.cursor()
    cursor.execute('CREATE TABLE foo (bar INTEGER UNIQUE, baz INTEGER)')
    cursor.execute('INSERT INTO foo (bar,baz) VALUES (?, ?)',(1,2))
    cursor.execute('INSERT OR REPLACE INTO foo (bar,baz) VALUES (?, ?)',(1,3))
    cursor.execute('SELECT * from foo')
    data=cursor.fetchall()
    print(data)
    # [(1, 3)]

def on_conflict():
    # https://sqlite.org/lang_insert.html
    connection=sqlite3.connect(':memory:')
    cursor=connection.cursor()
    cursor.execute('CREATE TABLE foo (bar INTEGER UNIQUE, baz INTEGER)')
    cursor.execute('INSERT INTO foo (bar,baz) VALUES (?, ?)',(1,2))
    cursor.execute('INSERT OR IGNORE INTO foo (bar,baz) VALUES (?, ?)',(1,3))
    cursor.execute('SELECT * from foo')
    data=cursor.fetchall()
    print(data)
    # [(1, 2)]

insert_or_replace()
on_conflict()

rawDescription: insert into sqlite table with unique column

description: Insert into sqlite table with unique column


code:
funcDict={}
for record in fullDict:
    if fullDict[record]['Type']=='FUNC':
        funcDict[record]=fullDict[record]

rawDescription: Parse a .txt file

description: Parse a .txt file


code: spyder

rawDescription: How to run Spyder in virtual environment?

description: Run Spyder in virtual environment


rawDescription: Python - Save user inputs in new variables


code:
import subprocess
diffs = subprocess.check_output(['git', 'diff', '--name-status'],
                                stderr=subprocess.STDOUT)
diff_dict = dict(list(reversed(item.split('\t')))
                 for item in diffs.split('\n') if item != '')

rawDescription: How to get access to git commit variables (python)?

description: Get access to git commit variables (python)


rawDescription: Order list of multiple items in Python by value


rawDescription: python convert string of lists into a list of lists

description: Python convert string of lists into a list of lists


code: np.row_stack(np.broadcast_arrays([1, 2, 3], 0, [3, 2, 1]))

rawDescription: How to stack arrays and scalars in numpy?

description: Stack arrays and scalars in numpy


rawDescription: Numpy: Replace every n element in the first half of an array


code:
import unittest

from bisect import bisect_left, bisect_right

def find_range(array, a, b):
    start = bisect_right(array,a)
    end = bisect_left(array,b)
    return (start, end)

class TestCase(unittest.TestCase):
    Y = [1, 3, 5, 10, 15]
    givenY = [3, 4, 5, 6, 7, 8, 9, 10, 11]

    def test_empty_array(self):
        self.assertEqual( (0, 0), find_range([], 1, 2) )

    def test_all_values_larger(self):
        self.assertEqual( (0, 0), find_range([4,5,6], 1, 3) )

    def test_all_values_larger_or_equal(self):
        self.assertEqual( (0, 0), find_range(self.givenY, self.Y[0], self.Y[1]) )

    def test_both_endpoints_inside_list(self):
        self.assertEqual( (1, 2), find_range(self.givenY, self.Y[1], self.Y[2]))
        self.assertEqual( [4], self.givenY[1:2])

    def test_2(self):
        self.assertEqual( (3, 7), find_range(self.givenY, self.Y[2], self.Y[3]) )
        self.assertEqual( [6, 7, 8, 9], self.givenY[3:7])

    def test_no_values_larger_or_equal_to_upper_limit(self):
        self.assertEqual( (8, 9), find_range(self.givenY, self.Y[3], self.Y[4]) )
        self.assertEqual( [11], self.givenY[8:9])

if __name__=="__main__":
    unittest.main()

rawDescription: Finding elements of an array lying between two values


code:
# projectname/appname/context_processors.py

def booleans():
    return {
        'True': True,
        'False': False,
    }

rawDescription: Django custom template tag which accepts a boolean parameter


code:
import pickle
a=np.arange(12).reshape(3,4)
s=pickle.dumps(a*2)
s
pickle.loads(s)

rawDescription: how to read numpy 2D array from string?

description: Read numpy 2D array from string


code:
def do_something(attribute, objects):
    return [getattr(o, attribute) for o in objects if hasattr(o, attribute)]

rawDescription: Passing a Django model attribute name to a function


code:
import shutil
import urllib2
from contextlib import closing

with closing(urllib2.urlopen('ftp://server/path/to/file')) as r:
    with open('file', 'wb') as f:
        shutil.copyfileobj(r, f)

rawDescription: Python: download a file over an FTP server


code:
print(a.nbytes/2)
print(a.dtype.fields)

rawDescription: How to create struct for passing between nodes using mpi4py

description: Create struct for passing between nodes using mpi4py


code:
for table in alltables:
    links = table.find_all('a')
    top100 = [link.string for link in links]
    print(top100)

rawDescription: Python 3 Beautiful Soup Data type incompatibility issue


code:
file_read = csv.DictReader(open('/tmp/test.csv', 'rb'),
    ['name','street','area'], delimiter=';')
file_write = csv.DictWriter(open('/tmp/test-headers.csv', 'wb'),
    ['name','street','area'], delimiter=';')
file_write.writeheader()
file_write.writerows(file_read)

rawDescription: Python adding headers to CSV

description: Python adding headers to CSV


code:
myStr = "01 02 03 04 11 12 13 14 21 22 23 24"
myStr= [int(n) for n in myStr.split()]
myList=[]
for i in xrange(0,len(myStr),4):
    myList.append(myStr[i:i+4])

rawDescription: What is the easiest but not fastest way to format this string into a list? Python


code:
import csv

d = {
    'key_1':['item_1','item_2','item_3'],
    'key_2':['2_item_1','2_item_2','2_item_3'],
}

with open('output.csv', 'w') as f:
    w = csv.writer(f)
    w.writerow(d.keys())
    w.writerows(zip(*d.values()))

rawDescription: Save a dict with lists as csv file

description: Save a dict with lists as csv file


code: print (df.b.groupby(df.index.month).apply(lambda x: x[x.first_valid_index()]))

rawDescription: Applying custom function while grouping returns NaN


rawDescription: Dictionary help in Python

description: Dictionary help in Python


code: irange, ixrange = range, xrange

rawDescription: Is it OK to re-use the names of Python's built-in functions?


rawDescription: Pandas: get the most count label

description: Pandas: get the most count label


code:
def extract_padding(self, s):
    return '', s

rawDescription: Scapy: Adding new protocol with complex field groupings


rawDescription: Python equivalent of R "split"-function

description: Python equivalent of R "split"-function


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://jsfiddle.net/falsetru/mLGnB/show/')
elem = driver.find_element_by_css_selector('div.dijitReset>input[type=hidden]')
driver.execute_script('''
    var elem = arguments[0];
    var value = arguments[1];
    elem.value = value;
''', elem, '2013-11-26')

rawDescription: Selenium (Python): How to insert value on a hidden input?


code:
loop = asyncio.get_event_loop()
task_factory = lambda loop, coro: TimedTask(coro, loop=loop)
loop.set_task_factory(task_factory)

rawDescription: How to measure Python's asyncio code performance?

description: Measure Python's asyncio code performance


code:
def call_tesseract(input_filename, output_filename):
    """Calls external tesseract.exe on input file (restrictions on types),
    outputting output_filename+'txt'"""
    devnull = open(os.devnull, 'w')
    args = [tesseract_exe_name, input_filename, output_filename]
    proc = subprocess.Popen(args, stderr=devnull)
    retcode = proc.wait()
    if retcode!=0:
        errors.check_for_errors()

rawDescription: How to remove "Tesseract Open Source OCR Engine v3.02 with Leptonica" message

description: Remove "Tesseract Open Source OCR Engine v3.02 with Leptonica" message


rawDescription: refactor code in order to use 3 values to make plot & tuple indices must be integers, not float

description: Refactor code in order to use 3 values to make plot & tuple indices must be integers, not float


code:
#header file1
foo
bar

rawDescription: concatenate several file remove header lines

description: Concatenate several file remove header lines


code: s, thetime = timed_input('Type now: ')

rawDescription: Timing/Recording input() in Python 3.1

description: Timing/Recording input() in Python 3.1


code:
import collections
data = collections.defaultdict(list)
for k, v in (('a', 'b'), ('a', 'c'), ('b', 'c')):
    data[k].append(v)

data

rawDescription: Is there a way to preserve duplicate keys in python dictionary


code:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([7,8,9,10], [1,4,9,16], 'yo')
ax.plot([1,9,11,12], [1,4,9,16], 'ro')
ax.set_xlim(xmin=7)
plt.show()

rawDescription: Matplotlib: Plotting two graphs within a specified x-axis range


code:
import doctest
doctest.testmod()

rawDescription: round off float to nearest 0.5 in python

description: Round off float to nearest 0.5 in python


code:
def register_user(request):
    #...
    if request.method == "POST":
        user_form = UserCreationForm(request.POST, prefix="user")
        profile_form = ProfileForm(request.POST, prefix="profile")
        if user_form.is_valid() and profile_form.is_valid():
            user = user_form.save(commit=False)
            user.save()
            profile = profile_form.save(commit=False)
            profile.user = user
            profile.save()
            return redirect('/')
    else:
        user_form = UserCreationForm(prefix="user")
        profile_form = ProfileForm(prefix="profile")
    context = {
        "user_form": user_form,
        "profile_form": profile_form
    }
    return render(request, 'register.html', context)

rawDescription: How to create a profile registration form in Django?

description: Create a profile registration form in Django


code:
M=sparse.lil_matrix((10,10))
m=sparse.eye(3)
M[4:7,5:8]=m
m
M
M.data
M.rows

rawDescription: Scipy sparse matrix assignment using only stored elements


code: {'id': 1, 'book_written_by': {'id': 1, 'name': 'somebody'}}

rawDescription: What is the easiest way to get custom serialized model with ForeignKey field


code:
def run_forever(self):
    """Run until stop() is called."""
    if self._running:
        raise RuntimeError('Event loop is running.')
    self._running = True
    try:
        while True:
            try:
                self._run_once()
            except _StopError:
                break
    finally:
        self._running = False

rawDescription: python asyncio run event loop once?

description: Python asyncio run event loop once


code: A = [x for x in itertools.product([0, 1], repeat=n) if sum(x)*2<=n]

rawDescription: Make all tuples with no more 1s than 0s

description: Make all tuples with no more 1s than 0s


code:
from itertools import product, chain, imap

def all_prod(s):
    return imap(''.join, chain.from_iterable(product(s, repeat=i) for i in range(len(s)+1)))

print(list(all_prod('ABC')))

for s in all_prod('abc'):
    print(s)

rawDescription: using python itertools to generate custom iteration

description: Using python itertools to generate custom iteration


code:
class_names = [w.capitalize() for w in
            random.sample(WORDS, snippet.count("%%%"))]

rawDescription: Confused about a function in Learn Python the Hard Way ex41?


code:
from collections import OrderedDict
d=OrderedDict()
for i,j in [(1,'a'),(2,'b')]:
   d[i]=j

d
d=OrderedDict([(3,'t')]+d.items())
d

rawDescription: Add object to start of dictionary

description: Add object to start of dictionary


code:
lis=[(101, 153), (255, 827), (361, 961)]
from operator import itemgetter
max(lis,key=itemgetter(1))[0]    #faster solution

rawDescription: Find the maximum value in a list of tuples in Python


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, sharex=True)
yranges = [(-1000, 100), (-0.001, 0.002), (0, 5), (0, 20)]
labels = ['$P_{EUC}[mm]$', '$P_z[mm]$', '$P_Y[mm]$', '$P_X[mm]$']

for ax, yrange, label in zip(axes, yranges, labels):
    ax.set(ylim=yrange, ylabel=label)

plt.show()

rawDescription: Python Numpy Matplotlib Set Y-Label inline


rawDescription: String splitting in Python

description: String splitting in Python


code:
@timed
def somefunction(countto):
  for i in xrange(countto):
    pass
  return "Done"

rawDescription: how to measure execution time of functions (automatically) in Python

description: Measure execution time of functions (automatically) in Python


code:
while np.amax(abs(velocity)) > 0.01:
    position += velocity
    velocity *= 0.995

    # Masks for particles beyond the boundary
    xmax = position[:, 0] > limit_x
    xmin = position[:, 0] < 0
    ymax = position[:, 1] > limit_y
    ymin = position[:, 1] < 0

    # flip velocity
    velocity[xmax | xmin, 0] *= -1
    velocity[ymax | ymin, 1] *= -1

rawDescription: Many particles in box - physics simulation


code: df = pd.read_csv('file.csv', (...), converters={'d': readD})

rawDescription: How do I get nan_values in pandas' read.csv to say "Set as NaN if it contains the character 'C' in any cell"

description: Get nan_values in pandas' read.csv to say "Set as NaN if it contains the character 'C' in any cell"


code:
if date.utcoffset().total_seconds() == utcoffset:
    result.append(name)

rawDescription: Python - Timezone name given timestamp UTC and UTC offset


code:
def maybe_replace_corgi(corgi):
    if corgi.cuteness > treshold:
        corgi.will_keep = true
    else:
        corgi.__init__(name="Woofus")

rawDescription: How do I change where a variable is pointing to within a function?

description: Change where a variable is pointing to within a function


code:
import random
def main(n):
    """ Returns number of flips needed
    to get n heads in a row """
    mylist = ['heads','tails']
    cnt = 0
    while 1:
        if [random.choice(mylist) for _ in range(n)].count('heads') == n:
            return cnt
        else:
            cnt +=1

rawDescription: Simulate multiple coin toss streak

description: Simulate multiple coin toss streak


code: v = [int(x) for x in v]

rawDescription: Declare and assign an amount of variables from an input?


code: min(x[1] for x in lists if x[0] > 10000)

rawDescription: minimum of list of lists

description: Minimum of list of lists


rawDescription: Why implement two so similar data structures like List and Tuple


code:
for testrec in testrecord:
    for t in testrec['testdata']:
        if t.get('color') == 'green':
            #include
            t

rawDescription: Nested list of dicts comprehension syntax


code:
import unittest
import unittest.runner
import itertools
import collections

class CustomTextTestResult(unittest.runner.TextTestResult):
    """Extension of TextTestResult to support numbering test cases"""

    def __init__(self, stream, descriptions, verbosity):
        """Initializes the test number generator, then calls super impl"""

        self.test_numbers = itertools.count(1)

        return super(CustomTextTestResult, self).__init__(stream, descriptions, verbosity)

    def startTest(self, test):
        """Writes the test number to the stream if showAll is set, then calls super impl"""

        if self.showAll:
            progress = '[{0}/{1}] '.format(next(self.test_numbers), self.test_case_count)
            self.stream.write(progress)

            # Also store the progress in the test itself, so that if it errors,
            # it can be written to the exception information by our overridden
            # _exec_info_to_string method:
            test.progress_index = progress

        return super(CustomTextTestResult, self).startTest(test)

    def _exc_info_to_string(self, err, test):
        """Gets an exception info string from super, and prepends 'Test Number' line"""

        info = super(CustomTextTestResult, self)._exc_info_to_string(err, test)

        if self.showAll:
            info = 'Test number: {index}\n{info}'.format(
                index=test.progress_index,
                info=info
            )

        return info

class CustomTextTestRunner(unittest.runner.TextTestRunner):
    """Extension of TextTestRunner to support numbering test cases"""

    resultclass = CustomTextTestResult

    def run(self, test):
        """Stores the total count of test cases, then calls super impl"""

        self.test_case_count = test.countTestCases()
        return super(CustomTextTestRunner, self).run(test)

    def _makeResult(self):
        """Creates and returns a result instance that knows the count of test cases"""

        result = super(CustomTextTestRunner, self)._makeResult()
        result.test_case_count = self.test_case_count
        return result

class TestSequenceFunctions(unittest.TestCase):
    """Dummy test case to illustrate usage"""

    fail_1 = 0
    fail_2 = 0

    def test_choice(self):
        pass

    def test_sample(self):
        self.fail_1 += 1
        if self.fail_1 == 2:
            raise Exception()

    def test_shuffle(self):
        self.fail_2 += 1
        if self.fail_2 == 3:
            raise Exception()

def get_tests():
    test_funcs = ['test_choice', 'test_sample', 'test_shuffle']
    return [TestSequenceFunctions(func) for func in test_funcs]

if __name__ == '__main__':
    test_suite = unittest.TestSuite()

    repetitions = 3
    tests = get_tests()
    for __ in xrange(0, repetitions):
        test_suite.addTests(tests)

    CustomTextTestRunner(verbosity=2).run(test_suite)

rawDescription: Show progress while running python unittest?


code:
max = w.count(w[0])
min = w.count(w[0])

rawDescription: Program that counts most and least common non-space characters


code:
import ctypes
import struct
import win32con
import win32gui
import win32ui

from PIL import Image

def RGB(r, g, b):
    return r | (g << 8) | (b << 16)

def native_bmp_to_pil(hdc, bitmap_handle, width, height):
    bmpheader = struct.pack("LHHHH", struct.calcsize("LHHHH"),
                            width, height, 1, 24) #w,h, planes=1, bitcount)
    c_bmpheader = ctypes.c_buffer(bmpheader)

    #3 bytes per pixel, pad lines to 4 bytes
    c_bits = ctypes.c_buffer(" " * (height * ((width*3 + 3) & -4)))

    res = ctypes.windll.gdi32.GetDIBits(
        hdc, bitmap_handle, 0, height,
        c_bits, c_bmpheader,
        win32con.DIB_RGB_COLORS)
    if not res:
        raise IOError("native_bmp_to_pil failed: GetDIBits")

    im = Image.frombuffer(
        "RGB", (width, height), c_bits,
        "raw", "BGR", (width*3 + 3) & -4, -1)
    return im

class Win32Font:
    def __init__(self, name, height, weight=win32con.FW_NORMAL,
                 italic=False, underline=False):
        self.font = win32ui.CreateFont({
            'name': name, 'height': height,
            'weight': weight, 'italic': italic, 'underline': underline})

        #create a compatible DC we can use to draw:
        self.desktopHwnd = win32gui.GetDesktopWindow()
        self.desktopDC = win32gui.GetWindowDC(self.desktopHwnd)
        self.mfcDC = win32ui.CreateDCFromHandle(self.desktopDC)
        self.drawDC = self.mfcDC.CreateCompatibleDC()

        #initialize it
        self.drawDC.SelectObject(self.font)

    def renderText(self, text):
        """render text to a PIL image using the windows API."""
        self.drawDC.SetTextColor(RGB(255,0,0))

        #create the compatible bitmap:
        w,h = self.drawDC.GetTextExtent(text)

        saveBitMap = win32ui.CreateBitmap()
        saveBitMap.CreateCompatibleBitmap(self.mfcDC, w, h)
        self.drawDC.SelectObject(saveBitMap)

        #draw it
        self.drawDC.DrawText(text, (0, 0, w, h), win32con.DT_LEFT)

        #convert to PIL image
        im = native_bmp_to_pil(self.drawDC.GetSafeHdc(), saveBitMap.GetHandle(), w, h)

        #clean-up
        win32gui.DeleteObject(saveBitMap.GetHandle())

        return im

    def __del__(self):
        self.mfcDC.DeleteDC()
        self.drawDC.DeleteDC()
        win32gui.ReleaseDC(self.desktopHwnd, self.desktopDC)
        win32gui.DeleteObject(self.font.GetSafeHandle())

    def __del__(self):
        win32gui.DeleteObject(self.font.GetSafeHandle())

rawDescription: python: use windows api to render text using a ttf font

description: Python: use windows api to render text using a ttf font


code: A2, B2 = zip(*sorted(zip(A,B), key=lambda x: x[1]))

rawDescription: Merge two arrays into a matrix in python and sort


code:
from array import *
a = array('u', u"unicode string")

rawDescription: initializing Arrays in python

description: Initializing Arrays in python


code:
import urllib
from scrapy.selector import HtmlXPathSelector
from pprint import pprint

url = 'http://www.fetise.com'
data = urllib.urlopen(url).read()
hxs = HtmlXPathSelector(text=data)

lista = hxs.select('//ul[@class="categoryMenu"]/li/ul/li/a/@href').extract()

acb = ["http://www.fetise.com/" + i if "http://www.fetise.com/" not in i else i for i in lista] + [u"http://www.fetise.com/sale"]

pprint(acb)

rawDescription: How to use scrapy request class

description: Use scrapy request class


code:
for plan_main in root.findall('./plan_main'):
    for plan in plan_main:
        name = plan.find('name').text
        if name.lower() != "john":
            plan_main.remove(plan)

rawDescription: Python: Find and Remove Child from XML file and output to new file


code:
xyz = {k: v for k, v in abc.iteritems() if not k.startswith('s_') and not k.startswith('b_')}
s_values = extract_keys(abc, 's')
if s_values is not None:
    xyz['s'] = s_values
b_values = extract_keys(abc, 'b')
if b_values is not None:
    xyz['b'] = b_values

rawDescription: dictionary that contains list

description: Dictionary that contains list


code:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect

@login_required
def account_redirect(request):
    return redirect('account-landing', pk=request.user.pk, name=request.user.username)

rawDescription: Django - Login and redirect to user profile page


code:
class ApiTestMixin:
    def test_account_get(self):
        rv = self.client.get(self.base_url + '/account', headers=self.headers)
        r = self.basic_checks(rv)
        account = r.get('account')
        eq_(account.get('fullName'), account_register.get('fullName'))
        assert r.get('correlationID') is not None

rawDescription: Run Flask tests against a remote server

description: Run Flask tests against a remote server


code:
self.helper.layout = Layout(
    Field('email', placeholder=_("Email")),
    Field('password1', placeholder=_("Password")),
    Field('billing_secret', value=billing_secret, type="hidden"),
)

if billing_secret is 'apples':
    self.helper.layout.append(InlineRadios('termsandcond'))
else:
    self.helper.layout.append(InlineRadios('termsandcond', initial="1", type="hidden"))
self.helper.layout.append(Submit("save", _("Get Started"),css_class="pull-right", style='display: none;'))

rawDescription: if statement in Django crispy form, conditional form layout

description: If statement in Django crispy form, conditional form layout


code:
with daemon.DaemonContext():
    do_main_program()

rawDescription: Can you use python-daemon with Python 2.4?

description: Use python-daemon with Python 2.4


rawDescription: Get permutation with specified degree by index number


code:
for i in xrange(10):
   (evens,odds)[i%2].append(i)

rawDescription: Complement of list comprehension in python


code:
class MemoizeJac(object):
    def __init__(self, fun):
        self.fun = fun
        self.value, self.jac = None, None
        self.x = None

    def _compute(self, x, *args):
        self.x = numpy.asarray(x).copy()
        self.value, self.jac = self.fun(x, *args)

    def __call__(self, x, *args):
        if self.value is not None and numpy.alltrue(x == self.x):
            return self.value
        else:
            self._compute(x, *args)
            return self.value

    def derivative(self, x, *args):
        if self.jac is not None and numpy.alltrue(x == self.x):
            return self.jac
        else:
            self._compute(x, *args)
            return self.jac

rawDescription: How to return cost, grad as tuple for scipy's fmin_cg function

description: Return cost, grad as tuple for scipy's fmin_cg function


code:
Explanation
[f for f in os.listdir(dr) if f.endswith(".tag")]

rawDescription: Code for coyping specific lines from multiple files to a single file (and removing part of the copied lines)


code:
match = brown.search(s, m_over.end())
match.group()
print(match)

rawDescription: Find length of string matched by regex

description: Find length of string matched by regex


code: result = numpy.rollaxis(X.dot(Y), axis=X.ndim-2, start=X.ndim+Y.ndim-3)

rawDescription: Multiplying matrix A times multi-dimensional matrix "matrix-wise?"


code:
from lxml import etree
d = etree.HTML('
text1 (asdftext2)
')
block = d.xpath('/html/body/p')[0]
# etree.strip_tags apparently takes a list of tags to strip, but it wasn't working for me
for tag in set(x.tag for x in block.iterdescendants() if x.tag != 'a'):
  etree.strip_tags(block,tag)

block.xpath('./text()|a')

rawDescription: How to select only certain tag and text using xpath?

description: Select only certain tag and text using xpath


rawDescription: all subsets of a set append Nonetype Error

description: All subsets of a set append Nonetype Error


code:
if x == 0: pass
elif x == 1: pass
else: pass

rawDescription: Condition always evaluates to else branch


code: WordLenLi = map(len,st.split())

rawDescription: how to implement a list of paragraph word lengths using a for loop

description: Implement a list of paragraph word lengths using a for loop


code:
for row in csv.reader("foo.csv", delimiter=known_delimiter):
   row = [item.decode(encoding) for item in row]

rawDescription: Python: A resilient, actually working CSV implementation for non-ascii?


code:
with open('dates.txt') as f:
    lines = f.readlines()

months = [date[4:6] for line in lines for date in line.split()]

print(months)

rawDescription: Splitting YYYYMMDD format date into months?


code:
s = '''...\nIXMLSerializerAlt._methods_ = [\n    COMMETHOD([helpstring(u'Loads an object from an XML string.')], HRESULT, 'LoadFromString',\n              ( ['in'], BSTR, 'XML' ),\n              ( ['in'], BSTR, 'TypeName' ),\n              ( ['in'], BSTR, 'TypeNamespaceURI' ),\n              ( ['retval', 'out'], POINTER(POINTER(IUnknown)), 'obj' )),\n]\n...'''
import re
re.findall(r'^\w+\._methods_\s=\s\[$.*?^\]$', s, re.DOTALL | re.MULTILINE)

rawDescription: How can i do this using a Python Regex?

description: Do this using a Python Regex


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('email', help='Email to be used in testing')

args = parser.parse_args()
EMAIL = args.email

rawDescription: Calling a script that contains solely an email address


code:
days_since(datetime.now())
days_since(date(2013, 5, 12))
days_since(date(2014, 12, 12))
days_since(date(2014, 7, 19))

rawDescription: Django built-in timesince filter to show only Days


code:
column_property(
    select([case([(roles_table.c.is_admin, 1),
                  (roles_table.c.id == 1, 1)], else_=0)],
           roles_table.c.id == persons_table.c.role_id))

rawDescription: Sqlalchemy select condition

description: Sqlalchemy select condition


code:
array_ = np.array([0,0,0,1,0,0,2,0,0,1,2,0])
_, inverse = np.unique(array_, return_inverse=True)
np.bincount(inverse)[inverse]

rawDescription: numpy fastest way to transform an array's elements to their frequency

description: Numpy fastest way to transform an array's elements to their frequency


code:
def sameChars(s1, s2):
    return set(s1) == set(s2)

rawDescription: Function sameChars doesn't work properly


code:
import pycode

pycode.init("address")

rawDescription: Handling default parameters in cython

description: Handling default parameters in cython


rawDescription: The activities in abaqus/viewer's query>probe values is not recorded in the macro?


code:
index = pandas.MultiIndex.from_product([y.index, z.index])
s = pandas.Series([y.loc[i[0], '{}'] * z.loc[i[1], '{}'] for i in index], index=index)

rawDescription: pandas - how do I produce cartesian product of both indices and data?

description: Pandas - how do I produce cartesian product of both indices and data


code:
xml_doc = lxml.etree.parse(StringIO.StringIO(r.content))
xml_dict = recursive_dict(xml_doc.getroot())

rawDescription: Why doesn't recursive_dict from the lxml FAQs work?


code:
data = [['John', 973], ['Jim', 99], ['Jason', 912345]]
sorted(data, key=lambda x:x[1], reverse=True)

rawDescription: Using the python sorted function?

description: Using the python sorted function


rawDescription: Events passing in python with kivy

description: Events passing in python with kivy


rawDescription: Extracting XML Element and Attribute Data with Python 3


code:
example = 'Foo \'" \\ Bar'
print(example)
print(example.encode('unicode_escape'))
example.encode('unicode_escape')

rawDescription: Escape string to be valid python expression


code:
import pkg_resources

def get_pkg_license(pkgname):
    """
    Given a package reference (as from requirements.txt),
    return license listed in package metadata.
    NOTE: This function does no error checking and is for
    demonstration purposes only.
    """
    pkgs = pkg_resources.require(pkgname)
    pkg = pkgs[0]
    for line in pkg.get_metadata_lines('PKG-INFO'):
        (k, v) = line.split(': ', 1)
        if k == "License":
            return v
    return None

rawDescription: Can pip (or setuptools, distribute etc...) list the license used by each installed package?


code: pua = [chr(i) for i in range(0xE000, 0xf900)]

rawDescription: List all unicode codes between U+E000–U+F8FF using Python


code:
if k > 0:
    del full_df
    full_df = pd.DataFrame()

rawDescription: Slow Data analysis using pandas

description: Slow Data analysis using pandas


rawDescription: String creation: Differences between two syntaxes ' ' and " "?


code:
import os
import csv

for filename in os.listdir(path):
    with open(os.path.join(path, filename), 'r') as f:
        for row in csv.reader(f):
            cells = [ cell.replace('www', 'vvv').replace('..', '--')
                      for cell in row ]
            # now you have a list of cells within one row
            # with all strings modified.

rawDescription: How to iterate over files and replace text

description: Iterate over files and replace text


rawDescription: numpy.convolve python old numbers cant change

description: Numpy.convolve python old numbers cant change


code:
payload = {
# Form contents
}
r = requests.post(url, data=payload, stream=True)
with open(filename, 'wb') as output:
    for chunk in r.iter_content():
        output.write(chunk)

rawDescription: How to download file from website

description: Download file from website


rawDescription: wxPython: access sizer of GUI generated by wxFormBuilder and replace child

description: WxPython: access sizer of GUI generated by wxFormBuilder and replace child


code:
from collections import Iterable

def recursive_key(func, fargs=(), fkwargs={}):
    def key_func(target):
        if isinstance(target, str) or not isinstance(target, Iterable):
            return func(target, *fargs, **fkwargs)
        return tuple(key_func(item) for item in target)
    return key_func

rawDescription: How to apply key function on tuple elems in sorted()?

description: Apply key function on tuple elems in sorted()


code:
{u'Data1': {'data': [u'other data', u'Another paragraph under the first heading.']},
 u'Data2': {'data': [u'other data2', u'This paragraph is NOT a sibling of the header']}}

rawDescription: How can I iterate through tags using Python?

description: Iterate through tags using Python


code:
temp = {a['category_name']: dict(a) for a in a_list}
for b in b_list:
    temp[b['category_name']].update(b)
c_list = list(temp.values())    # list() unnecessary in py2.X

rawDescription: Combine two lists which have the same item in dict


rawDescription: Python regexp to capture numbers and dashes separated by spaces and comma


code:
def index(request):
    latest_book = Book.objects.all().order_by('-pub_date')[:5]
    top_items = Book.objects.all().order_by('-score')[:100]
    return render_to_response('books/index.html', {
                            'latest_books': latest_books, # latest_book
                            'top_books' : top_books}, # top_items
                            context_instance=RequestContext(request))

rawDescription: Check if current user has voted

description: Check if current user has voted


code:
for el in results_a:
  if el in results_b:
     ...

rawDescription: SQLite compare query Python

description: SQLite compare query Python


code: y3 = integrate.odeint(df, f0, x, tcrit = [0])

rawDescription: scipy.odeint strange behavior

description: Scipy.odeint strange behavior


code:
import random as RND
import string
import itertools as IT

rawDescription: Pairwise Set Intersection in Python

description: Pairwise Set Intersection in Python


code:
fobj_in = io.StringIO("""Name1, Surname1  Team1
                  Team2
                  Team3
Name2, Surname2  Team2
                  Team4
Name3, Surname3  Team1
                  Team5""")

fobj_out = io.StringIO()

from collections import defaultdict

teams = defaultdict(list)

for line in fobj_in:
    items = line.split()
    if len(items) == 3:
        name = items[:2]
        team = items[2]
    else:
        team = items[0]
    teams[team].append(name)

for team_name in sorted(teams.keys()):
    fobj_out.write(team_name + ', ')
    for name in teams[team_name][:-1]:
        fobj_out.write('{} {}, '.format(name[0], name[1]))
    name = teams[team_name][-1]
    fobj_out.write('{} {}\n'.format(name[0], name[1]))

fobj_out.seek(0)
print(fobj_out.read())

rawDescription: Aggregate text field from several lines (javascript/python)


code:
from threading import Thread
def postpone(function):
  def decorator(*args, **kwargs):
    t = Thread(target = function, args=args, kwargs=kwargs)
    t.daemon = True
    t.start()
  return decorator

rawDescription: Multithreading for Python Django

description: Multithreading for Python Django


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup('''\

    2
    3
    4
    ...
    31
    32
    33
    Next »

''')
max(int(link.text) for link in soup.find('div', class_='pagination').find_all('a') if link.text.strip().isdigit())

rawDescription: List comprehension to return highest value


rawDescription: Get dict key by max value

description: Get dict key by max value


code:
with open('somefile.txt') as f:
   next(f) # Skips the first line, which doesn't have =
   numbers = [line.split('=')[0] for line in f if len(line.strip())]

print(numbers)

rawDescription: python plain text regex parsing

description: Python plain text regex parsing


code:
import time
import os
outfile = 'mpgoutput.txt' # record of mpg results
infile = 'mpglist.txt' # list of all mpg to calculate avg
GALLON = float(0.219969) # 1 litre, used to calculate litres into gallons
TIME = (time.strftime("%H:%M:%S"))
DATE = (time.strftime("%d/%m/%Y"))
print('enter litres...')
litre = input()
litre = float(litre)
gallonsUsed = litre * GALLON # work out litres into gallons
print('Enter miles')
milesDriven = input()
milesDriven = float(milesDriven)
mpg = milesDriven / gallonsUsed # mpg calculated
if os.path.isfile(infile) == False: # check if file exists if not create it
     print('File does not exist')
     print('   Making File')
     open(infile, 'w')
mpglistread = open(infile, "r")
originalList = mpglistread.read()
mpglistread.close()
mpglistwrite = open(infile, "w")
mpglistwrite.write(''+str(mpg)+'\n' + originalList)
mpglistwrite.close()
mpgList = open(infile, "r")
listData = mpgList.read()
mpgList.close()
listData=listData.split()
listLength = (len(listData))
data = sum(map(float, listData))
avg = data /listLength

def checkFile():
    if os.path.isfile(outfile) == True:
        readFile()
    else:
        print('File does not exist')
        print('   Making File')
        open(outfile, 'w')
        readFile()

def readFile():

    file = open(outfile, "r")
    filedata = file.read()
    file.close()
    newLine = " ====================== \n     Your mpg is...\n ---------------------- \n  "+str([mpg])+"   \n ---------------------- \n   Time - "+str(TIME)+" \n   Date - "+str(DATE)+" \n ====================== \n \n" + filedata
    file = open(outfile, "w")
    file.write(newLine)
    file.close()
    file = open(outfile, "r")
    filedata = file.read()
    file.close()
    print('\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n')
    print(" ====================== \n     Your mpg is...\n ++++++++++++++++++++++ \n  "+str([mpg])+"   \n ---------------------- \n Your average mpg is...\n ++++++++++++++++++++++ \n  "+str(avg)+"   \n ---------------------- \n   Time - "+str(TIME)+" \n   Date - "+str(DATE)+" \n ====================== \n \n")

checkFile()

rawDescription: Trying to extract text from a txt file between 2 symbols and store in a list


code: result = [np.median(a[a[:,0]==ii,1]) for ii in np.unique(a[:,0])]

rawDescription: dealing with arrays: how to avoid a "for" statement

description: Dealing with arrays: how to avoid a "for" statement


code:
import subprocess
subprocess.call(u'cat <<< "\u0061"', shell=True)
subprocess.call(u'cat <<< "\u0061"', shell=True, executable='/bin/bash')

rawDescription: Using subprocess to get output

description: Using subprocess to get output


rawDescription: Culling list to find greatest non-intersecting members in Python


code:
# Generic pubsub event handlers for all nodes
xmpp.add_event_handler('pubsub_publish', handler)
xmpp.add_event_handler('pubsub_retract', handler)
xmpp.add_event_handler('pubsub_purge', handler)
xmpp.add_event_handler('pubsub_delete', handler)

# Use custom-named events for certain nodes, in this case
# the User Tune node from PEP.
xmpp['xep_0060'].map_node_event('http://jabber.org/protocol/tune', 'user_tune')
xmpp.add_event_handler('user_tune_publish', handler)
# ...
# The same suffixes as the pubsub_* events.
# These events are raised in addition to the pubsub_* events.

rawDescription: sleekxmpp pubsub example

description: Sleekxmpp pubsub example


rawDescription: Python vs PHP speed

description: Python vs PHP speed


code:
df["delta"]
df["delta"] >= 5
(df["delta"] >= 5).cumsum()

rawDescription: Python: Create an incrementing variable that changes based on a condition


rawDescription: pyqt4 python QLabel show when push button clicked

description: Pyqt4 python QLabel show when push button clicked


code:
menu = wx.Menu()
item_id = 1
item_name = 'My menu item\tCtrl+T'
help_text = 'Clicking this does something interesting.'
item = menu.Append(item_id, item_name, help_text)

rawDescription: wxPython menu text alignment

description: WxPython menu text alignment


code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException

rawDescription: How to use Selenium with Python?

description: Use Selenium with Python


code:
class Foo(Bar): ... # no decorations

@decorator
def f(*a, **k): ...

Foo.f = f   # "a killer"... function becomes method!

rawDescription: How to differentiate between method and function in a decorator?

description: Differentiate between method and function in a decorator


code: os.system("bulkloader.py --download --config_file=bulkloader.yaml --kind=kind --url=http://my_app_name.appspot.com/_ah/remote_api --filename=CSV_files/table_name.csv")

rawDescription: Can I get data from my MSSql server and upload it to app engine via some python scripts?

description: Get data from my MSSql server and upload it to app engine via some python scripts


code: np.mgrid[[slice(row[0], row[1], n*1j) for row, n in zip(bounds, n_bins)]]

rawDescription: How to create multidimensional array with numpy.mgrid

description: Create multidimensional array with numpy.mgrid


code:
import dis
dis.dis(compile("a = 1; a, b = 0, a", "<string>", "exec"))

rawDescription: How Python's a, b = b, a works?

description: How Python's a, b = b, a works


code:
class Point(object):
    __slots__= ("x", "y", "z", "data", "_classification")
    def __init__(self, x, y, z):
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)
        self.data = [self.x,self.y,self.z]

    @property
    def classification(self):
        return getattr(self, '_classification', None)

    @classification.setter
    def classification(self, value):
        self._classification = value
        if value:
            self.data = self.data[:3] + [value]
        else:
            self.data = self.data[:3]

rawDescription: Resolving how to give an attribute in a class in Python


code:
class QuotesView(webapp.RequestHandler):
    """Super class for quotes that can accommodate common functionality"""
    pass

class QuotesViewSingle(QuotesView):
    def get(self):
        ...

class QuotesViewRandom(QuotesView):
    def get(self):
        ...

class QuotesViewAll(QuotesView):
    def get(self):
        ...

def main():
    application = webapp.WSGIApplication([('/quote/new',NewQuote),
                                          (r'/quotes/single',QuotesViewSingle),
                                          (r'/quotes/all',QuotesViewAll),
                                          (r'/quotes/random',QuotesViewRandom),
                                          ...
                                          ('/', MainHandler)],
                                         debug=True)

rawDescription: Is this the correct way of doing/handling url rewrite in App Engine/ Python?


code:
import sys
reload(sys)
sys.setdefaultencoding('utf8')

rawDescription: Unable to process accented words using NLTK tokeniser


code: SUCCESS

rawDescription: Python lambda self composing function: How to return a function that is repeated n amount of times?


rawDescription: Multiply scipy.lti transfer functions

description: Multiply scipy.lti transfer functions


code:
df.columns = ['Date', 'Sales']
df

rawDescription: Pandas reset index on series to remove multiindex


code:
class MyList(list):
    def __getattr__(self, attr):
        return getattr(self[0], attr)

rawDescription: How to have a list in python which returns a default item on an invalid index or no index at all

description: Have a list in python which returns a default item on an invalid index or no index at all


code:
def test_foo(datadir):
    expected_config_1 = datadir.join('expected_config_1.ini')
    expected_config_2 = datadir.join('expected_config_2.ini')

rawDescription: Pytest where to store expected data

description: Pytest where to store expected data


code:
import random

d = 3
n = 1000

f = open('input.txt', 'w')

for i in range(n):
    nums = [str(round(random.uniform(0, 1000), 3)) for j in range(d)]
    f.write(' '.join(nums))
    f.write('\n')

f.close()

rawDescription: How to create a big file quickly with Python

description: Create a big file quickly with Python


code:
max_ratios = find_max_ratio(t)
average = sum(max_ratios.values())/float(len(max_ratios))
average

rawDescription: Calculate the greatest distance between any two strings in a group, using Python


code:
counts = {}
for row in my_reader:
    counts[row[3]] = counts.get(row[3], 0) + 1

rawDescription: Count numbers from row in CSV file

description: Count numbers from row in CSV file


code:
import re

_range = re.compile(r'(.)-(.)')
def _range_expand(match):
    start, stop = ord(match.group(1)), ord(match.group(2)) + 1
    if start < stop:
        return ''.join([chr(i) for i in range(start, stop)])
    return match.group(0)

def expand(s1):
    return _range.sub(_range_expand, s1)

rawDescription: converting a C function into Python3 form?

description: Converting a C function into Python3 form


code: uniq_d = list(map(dict, frozenset(frozenset(i.items()) for i in d)))

rawDescription: How to make values in list of dictionary unique?

description: Make values in list of dictionary unique


code:
print('\u01c1')
ǁ = SinkInto
df >> ǁ(select, 'one') >> ǁ(rename, one='new_one')

rawDescription: "Piping" output from one function to another using Python infix syntax


rawDescription: Special Vector and Element-wise Multiplication


rawDescription: How to strip unicode "punctuation" from Python string

description: Strip unicode "punctuation" from Python string


code: Foo.query.join(Bar, Foo.bar_no == Bar.bar_no).filter(Bar.status == filters['status']).all()

rawDescription: Sql filter query with join objects

description: Sql filter query with join objects


code:
#!/usr/bin/env python
"""Play a fixed frequency sound."""
from __future__ import division
import math

from pyaudio import PyAudio # sudo apt-get install python{,3}-pyaudio

try:
    from itertools import izip
except ImportError: # Python 3
    izip = zip
    xrange = range

def sine_tone(frequency, duration, volume=1, sample_rate=22050):
    n_samples = int(sample_rate * duration)
    restframes = n_samples % sample_rate

    p = PyAudio()
    stream = p.open(format=p.get_format_from_width(1), # 8bit
                    channels=1, # mono
                    rate=sample_rate,
                    output=True)
    s = lambda t: volume * math.sin(2 * math.pi * frequency * t / sample_rate)
    samples = (int(s(t) * 0x7f + 0x80) for t in xrange(n_samples))
    for buf in izip(*[samples]*sample_rate): # write several samples at a time
        stream.write(bytes(bytearray(buf)))

    # fill remainder of frameset with silence
    stream.write(b'\x80' * restframes)

    stream.stop_stream()
    stream.close()
    p.terminate()

rawDescription: Python library for playing fixed-frequency sound


code:
with open('test1.txt', 'r') as file1, open('test2.txt', 'r') as file2:
    print("line\tfile1\tfile2\n")
    for i, (line1, line2) in enumerate(zip(file1, file2), 1):
        if line1 != line2:
            print("{}:\t\t{}\t{}".format(i, line1.strip(), line2.strip()))

rawDescription: python create variable from first x letters in each line of a text file

description: Python create variable from first x letters in each line of a text file


code:
from dateutil.parser import parse
parse('April 12, 2013')
parse('04/12/13')

rawDescription: Python: Parsing out publication dates from html pages


code: l3 = blist.sortedlist(l2)

rawDescription: Constant time random selection and deletion


code: self.assertIn('Edit your profile admin', rv.data, msg=rv.data)

rawDescription: Is there a way to configure Python logging to log content or context of assert failures?


code: [all_options[option] for option in selected_options if option in all_options]

rawDescription: Python: Check if any list element is a key in a dictionary


code:
list_of_tuples = [(1,2),(3,4)]
list_of_tuples

rawDescription: Can I put a tuple into an array in python?

description: Put a tuple into an array in python


rawDescription: How can I match regular expression for this url?

description: Match regular expression for this url


code:
import maya.cmds as cmds
keyFrame = (cmds.keyFrame("myAnimCurve", q=True))[-1]

rawDescription: How do I find the time of a particular keyframe using cmds.selectKey?

description: Find the time of a particular keyframe using cmds.selectKey


code: hands = [[] for _ in range(Nplayers)]

rawDescription: Card Deal Function Issue

description: Card Deal Function Issue


code:
channelLayout = cmds.formLayout("GE_ui_scriptedPanelOutlineEdForm", query=True, ca=True)[0] #Get the channel box's layout
filterLayout = cmds.formLayout("GE_ui_scriptedPanelOutlineEdForm", query=True, ca=True)[1] #Get the filter's layout

myRowLayout=cmds.rowLayout(numberOfColumns=3, p="GE_ui_scriptedPanelOutlineEdForm") #Create a row layout
cmds.button(label="Café", h=100, p=myRowLayout) #Add some buttons
cmds.button(label="Clope", p=myRowLayout)
cmds.button(label="Caca", p=myRowLayout)

#This will reorder the content of the left formLayout
cmds.formLayout("GE_ui_scriptedPanelOutlineEdForm", edit=True, af=[ \
            (channelLayout, "bottom", 0), \
            (channelLayout, "right", 0),  \
            (filterLayout, "top", 0),  \
            (myRowLayout, "left", 0),  \
            (myRowLayout, "right", 0)],  \
            ac=[(myRowLayout, "top", 0, filterLayout), \
            (channelLayout, "top", 0, myRowLayout)])

rawDescription: How do I parent new, user-created buttons inside the Graph Editor window?

description: Parent new, user-created buttons inside the Graph Editor window


code:
from operator import add,sub,mul,div
funcs = [add,sub,mul,div]
die = [1,2,3,4,5,6]

results = [f(x,y) if y != 0 else None for x in die for y in [g(z,w) for z in die for w in die for g in funcs] for f in funcs]

rawDescription: Building a variable that combines several enumerations in an enormous list


code:
from datetime import datetime, date, time
import pytz

date = date(2016, 12, 25)
time = time(12, 0, 0, tzinfo=pytz.timezone('Europe/London'))
aware_datetime = datetime.combine(date, time)

rawDescription: In python, how do I create a timezone aware datetime from a date and time?


rawDescription: Filtering DataFrame using the length of a column


code:
class Actor(object):
    #(...)
    def update(self, dt=1):
        # Step 1 - assumes a constant movement to the top right
        self.vel.x = 1
        self.vel.y = 1

        # Step 2 - cube is your collision tested object
        cube = Cube()
        new_pos = self.pos + (self.vel * dt)
        if new_pos.x > cube.left and new_pos.x < cube.right:
            self.vel.x = 0
        if new_pos.y > cube.bottom and new_pos.y < cube.top:
            self.vel.y = 0

        # Step 3
        self.pos += self.vel * dt

rawDescription: 3D Collision detection not functioning properly


rawDescription: How Can I Set the Interpolation of a F-Curve via Python? (Blender)


code:
person = Person("Walter")
person.friends.append(Person("Suzie"))       # add a friend
person.friends.pop(0)                        # remove and get first friend, friends is now empty
person.friends.index(Person("Barbara"))      # -1, Barbara is not one of Walter's friends

rawDescription: Implementing Java object creation in Python


code:
a = [ ["id1", 123], ["id2", 1], ["id3", 6] ]
from operator import itemgetter
sorted(a, key=itemgetter(1), reverse=True)

rawDescription: Ordering a multidimensional array in python


code:
q = SomeQueueClass.connect('some.ip.address.0')
url = q.pop()

rawDescription: Send url seed to EC2 instances using Python


code:
def new_timer(self, *args, **kwargs):
    """
    Creates a new backend-specific subclass of :class:`backend_bases.Timer`.
    This is useful for getting periodic events through the backend's native
    event loop. Implemented only for backends with GUIs.

    optional arguments:

    *interval*
      Timer interval in milliseconds
    *callbacks*
      Sequence of (func, args, kwargs) where func(*args, **kwargs) will
      be executed by the timer every *interval*.
    """
    return TimerTk(self._tkcanvas, *args, **kwargs)

rawDescription: Where do timers live in matplotlib

description: Where do timers live in matplotlib


code: df

rawDescription: Filter, group, and calculate statistics for Numpy matrix data


rawDescription: Python remove couple of duplicates from List


code:
from itertools import groupby
my_list = [[1,2,3,1,2],[1,0,3,1,2],[1,0,0,0,2],[1,0,3,0,2]]
new_list = [[len(list(g)) for k, g in groupby(inner, bool) if k] for inner in my_list]

rawDescription: Python list traversal with gaps

description: Python list traversal with gaps


code:
newcols
' or '.join('%s > 1' % c for c in newcols)

rawDescription: Using dynamic lists in query in Pandas

description: Using dynamic lists in query in Pandas


code: sentences = re.findall("[A-Z].*?(?=[\.!?;])", stripped_value, re.MULTILINE | re.DOTALL | re.UNICODE)

rawDescription: python, regex find a subsentence, exclude bounaries

description: Python, regex find a subsentence, exclude bounaries


code:
# dblink is an object that knows how to connect to the database
with dblink.CommittingSession() as session:
  session.add(...)
  # do anything else
# at this point, session.commit() has been called

rawDescription: How to manage this pattern this sqlalchemy

description: Manage this pattern this sqlalchemy


code:
if st_a.intersection(st_b):
     print("There is an overlap")
else:
    print("There is no overlap")

rawDescription: How to check for common elements between two lists in python

description: Check for common elements between two lists in python


code: tuple([e for e in l[:3] if e] for l in data)

rawDescription: Removing blank objects within a tuple

description: Removing blank objects within a tuple


code: (cdf(b) - cdf(a))*n

rawDescription: Scaling the fitted PDF of a log-normal distribution to the histrogram in python


rawDescription: Can't get Scrapy to return text in Div

description: Can't get Scrapy to return text in Div


code:
import threading
import time

stop_thread = False

def thread_main():
    while not stop_thread:
        time.sleep(10)
t = threading.Thread(target=thread_main)
t.start()

stop_thread = True

t.join()

rawDescription: Difference between thread.join and thread.abort in python multithreading