code:
import matplotlib.pyplot as plt

list1 = [1,2,3,4]
list2 = [4,3,2,1]
somecondition = True
plt.figure(1) #create one of the figures that must appear with the chart

if not somecondition:
    ax = plt.subplot(111) #create the first subplot that will ALWAYS be there
    ax.plot(list1) #populate the "main" subplot
else:
    ax = plt.subplot(211)
    ax.plot(list1)
    ax = plt.subplot(223) #create the second subplot, that MIGHT be there
    ax.plot(list2) #populate the second subplot
plt.show()

rawDescription: Python & Matplotlib: creating two subplots with different sizes


rawDescription: Lists in python using itertools (moving only 2 items, permutations)


code:
with open('/tmp/redirect.log', 'a') as log:
    while True: #If you need to continuously check for more.
        for line in sys.stdin:
            if line.startswith(("GET", "User-Agent")):
                log.write(line)

rawDescription: Python reading first four lines from readlines()


code: os.system('sudo -u hadoop bin/hadoop-daemon.sh stop tasktracker')

rawDescription: Changing user in python

description: Changing user in python


code:
import numpy
result = numpy.dot( numpy.array(A)[:,0], B)

rawDescription: What is the pythonic way to calculate dot product?


code:
def f(): return 3
print(dir(f.__code__))
print(f.__code__.co_code)  # raw compiled bytecode

rawDescription: What is function.__code__ behavior across multiple program executions?


code:
middleware.py
from django.conf import settings

class MobileTemplatesMiddleware(object):
    """Determines which set of templates to use for a mobile site"""

    def process_request(self, request):
        # sets are used here, you can use other logic if you have an older version of Python
        MOBILE_SUBDOMAINS = set(['m', 'mobile'])
        domain = set(request.META.get('HTTP_HOST', '').split('.'))
        if request.flavour=='mobile':
            settings.TEMPLATE_DIRS = settings.MOBILE_TEMPLATE_DIRS
        else:
            settings.TEMPLATE_DIRS = settings.DESKTOP_TEMPLATE_DIRS

rawDescription: Django WebApp for Mobile and Desktop

description: Django WebApp for Mobile and Desktop


code:
from django import template
from datetime import date, datetime, timedelta

register = template.Library()

@register.filter(expects_localtime=True)
def is_today(value):
    if isinstance(value, datetime):
        value = value.date()
    return value == date.today()

@register.filter(expects_localtime=True)
def is_past(value):
    if isinstance(value, datetime):
        value = value.date()
    return value < date.today()

rawDescription: compare the date of all DateFields in a model to the current date

description: Compare the date of all DateFields in a model to the current date


code:
d = AttrDict({"a":1, "b":2})
d2 = pickle.loads(pickle.dumps(d, -1)) # serialize and unserialize
d2
d2.b=3
d2

rawDescription: Passing a dict-like Object through multiprocessing.Queue Makes it Unable to be Modified by Attribute


rawDescription: Python 2.7 multiprocessing get process result whithout using pool


code:
from collections import OrderedDict

from itertools import izip
i = iter(list_name)
dic = OrderedDict(izip(i, i))

rawDescription: Convert a list into a dictionary keeping the sequence intact


rawDescription: Whence the 27 digits of extra precision in `decimal.Decimal(1.0/3.0)`?


code:
import multiprocessing as mp

def print_mynumber(foo):
    """This function is obviously more complicated in my script.
    It should be run as a subprocess."""
    print(foo)

if __name__ == '__main__':
    pool = mp.Pool()
    pool.map(print_mynumber, [1,2,3])

rawDescription: How do I make functions run as subprocesses in Python?

description: Make functions run as subprocesses in Python


code: re1_matches and re2_matches and re1_matches + re2_matches

rawDescription: Merge several regular expressions into one RE


rawDescription: Mpmath.meijerg: Order of arguments

description: Mpmath.meijerg: Order of arguments


code:
import test
import test

rawDescription: How to initialise long-lived variables?

description: Initialise long-lived variables


code:
a
b
c
d
e
ab
ac
ad
ae
bc
bd
be
cd
ce
de
abc
abd
abe
acd
ace
ade
bcd
bce
bde
cde
abcd
abce
abde
acde
bcde
abcde

rawDescription: How to find the combinations (probability) for a,b,c,d,e

description: Find the combinations (probability) for a,b,c,d,e


code:
decorator = argument_decorator(True)
@decorator
def foo(): pass

rawDescription: Python dynamic decorators - why so many wraps?


code:
def place_widget(widget, mess):
  if isinstance(mess, (list, tuple)):
    for item in mess:
      place_widget(widget, item)
  elif isinstance(mess, type(lambda:0)):
    if mess.func_code.co_varnames[-1:] == ('widget',):
      mess.func_defaults = mess.func_defaults[:-1] + (widget,)

rawDescription: Specifying TkInter Callbacks In Dictionary For Display Launcher Function


code:
match = re.search(r"^([\d.]+)\s*([^\t?]+\??)", s)
if match:
    mynumbers = match.group(1)
    myline = match.group(2)

rawDescription: How to python regex match the following?

description: Python regex match the following


code: subprocess.call(cmd, stdin=p2.stdout)

rawDescription: Piping into a subprocess.call

description: Piping into a subprocess.call


code:
text = BeautifulSoup(html).find("span",attrs={"class":"a-size-large"}).text
with open("{}.html".format(text), "wb") as file:
    file.write(html)

rawDescription: Automating filename generation from url text


code: cv2.warpPerspective(dist, M, (width, height), cv2.INTER_LINEAR, cv2.BORDER_CONSTANT, 255)

rawDescription: Set background of Python OpenCV warpPerspective


code:
for n in nodes:
    if not lists[n.id]:
        lists[n.parentid].remove(lists[n.id])

rawDescription: Make a python nested list for use in Django's unordered_list


code:
import pygame, sys

#init pygame
pygame.init()

#init screen
screen=pygame.display.set_mode((800,600))
screen.fill((255,0,255))

#loading the images
texture=pygame.image.load("texture.jpg").convert_alpha()
texture_rect=texture.get_rect()
texture_rect.center=(200,300)
mask=pygame.image.load("mask2.png").convert_alpha()
mask_rect=mask.get_rect()
mask_rect.center=(600,300)

textured_mask=mask.copy()
textured_rect=textured_mask.get_rect()
textured_rect.center=400,300

textured_mask.blit(texture,(0,0),None,pygame.BLEND_ADD)

screen.blit(texture,texture_rect)
screen.blit(mask,mask_rect)
screen.blit(textured_mask,textured_rect)

pygame.display.flip()

while 1:
    event=pygame.event.wait()
    if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key in [pygame.K_ESCAPE, pygame.K_q]):
        sys.exit()

rawDescription: Active texturing with pygame (possible? what concepts to look into?)


code:
import requests
from bs4 import BeautifulSoup

url = "http://autoplius.lt/redaguoti/naudoti-automobiliai/"
page = requests.get(url)

# form data fields can be hard coded bar parent_id
data = {"target_id": "model_id",
        "project": "autoplius",
        "category_id": "2",
        "type": "edit",
        "my_anns": "false",
        "__block": "ann_ajax_0_plius",
        "__opcode": "ajaxGetChildsTo"}

soup = BeautifulSoup(page.content, "html.parser")

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36",
    "X-Requested-With": "XMLHttpRequest"}

# first two options hold no ids
car_makes = soup.select("#make_id option + option + option")

for car in car_makes:
    print(car.text)
    # pass  id/value
    data["parent_id"] = car["value"]
    # data for a post not params
    form = requests.post(url, data=data, headers=headers)
    soup11 = BeautifulSoup(form.text, "html.parser")
    print(soup11)

rawDescription: Scraping data which loaded when you select something


code:
from state import _state
if authentication_passed:
    _state.user = user

rawDescription: Store objects at "request scope" in google app engine


code: X_new = rfecv.fit_transform(X, y)

rawDescription: Scikit-learn - feature reduction using RFECV and GridSearch. Where are the coefficients stored?


code:
items
[(x[1]['score'], x[1]['title']) for x in items]

rawDescription: Sort Multi-dimensional dictionary

description: Sort Multi-dimensional dictionary


code:
def quantify(seq, pred=None):
    "Count how many times the predicate is true in the sequence"
    return sum(imap(pred, seq))

rawDescription: Most pythonic way of counting matching elements in something iterable


code:
import fnmatch
import re
import os

with open('badwords.txt','r') as f:
    pat='|'.join(fnmatch.translate(badword)[:-1] for badword in
                 f.read().splitlines())

for fname in os.listdir('.'):
    new_fname=re.sub(pat,'',fname)
    if fname != new_fname:
        print('{o} --> {n}'.format(o=fname,n=new_fname))
        os.rename(fname, new_fname)

# MyMusic.Songname.Artist-mp3.iTunes.mp3 --> Songname.Artist.mp3

rawDescription: batch search and replace strings in filenames with python

description: Batch search and replace strings in filenames with python


code: Session.key = ''

rawDescription: Sending messages from other languages to an IPython kernel


code:
lst = [2, 11]
sorted(lst, key=str)
lst.sort(key=str)
lst

rawDescription: python - change element while in for loop

description: Python - change element while in for loop


code:
MIDDLEWARE_CLASSES = (
    'middleware.apps.schemas.router.SchemaRouterMiddleware',
     ...
)

rawDescription: django-tenant-schemas: How to use with single tenant/without subdomains

description: Django-tenant-schemas: How to use with single tenant/without subdomains


code:
for i in range(len(data)):
    print(data[i])

rawDescription: Stacking multiple columns in a stacked bar plot using matplotlib in python 3


code:
letter='a'
locals()["draw_"+letter]()

rawDescription: How to, in Python, execute function corresponding to each letter in a string?


rawDescription: Find nested sub-classes in a class in the order they're defined


code:
def on_change_bool2(self, cr, uid, ids, bool2):
    return {'value':{'bool2': bool2,'bool1':False}}

rawDescription: on change in boolean

description: On change in boolean


code:
a
b

rawDescription: How to raise a numpy array to a power? (corresponding to repeated matrix multiplications, not elementwise)

description: Raise a numpy array to a power? (corresponding to repeated matrix multiplications, not elementwise)


code:
with open('output.csv', 'wb') as outf:
    with open('input.csv', 'rbU') as inf:
        read = csv.reader(inf)
        outwriter = csv.writer(outf)
        notstrings = ['and', 'or', '&', 'is', 'a', 'the']
        for row in read:
            if not any(w in row[3] for w in notstrings):
                outwriter(row)

rawDescription: No item in list in string Python

description: No item in list in string Python


code:
#!/usr/bin/env python3
import asyncio
import logging
from contextlib import closing
import aiohttp # $ pip install aiohttp

@asyncio.coroutine
def download(url, session, semaphore, chunk_size=1<<15):
    with (yield from semaphore): # limit number of concurrent downloads
        filename = url2filename(url)
        logging.info('downloading %s', filename)
        response = yield from session.get(url)
        with closing(response), open(filename, 'wb') as file:
            while True: # save file
                chunk = yield from response.content.read(chunk_size)
                if not chunk:
                    break
                file.write(chunk)
        logging.info('done %s', filename)
    return filename, (response.status, tuple(response.headers.items()))

urls = [...]
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
with closing(asyncio.get_event_loop()) as loop, \
     closing(aiohttp.ClientSession()) as session:
    semaphore = asyncio.Semaphore(4)
    download_tasks = (download(url, session, semaphore) for url in urls)
    result = loop.run_until_complete(asyncio.gather(*download_tasks))

rawDescription: How to parallelized file downloads?

description: Parallelized file downloads


code:
class Weapon(object):

    def __init__(self, owned, damage, price, accuracy):
        self.owned = owned
        self.damage = damage
        self.price = price
        self.accuracy = accuracy

weapon1 = Weapon(
    owned = True,
    damage = 2,
    price = None,
    accuracy = 75
)

weapon2 = Weapon(
    owned = False,
    damage = 4,
    price = 50,
    accuracy = 50
)

...

rawDescription: Assigning specific things to a class in Python


code: {{ object.M_KG }}

rawDescription: Django : Manipulate Data in a generic.ListView


code:
lst = []
def play(arg):
    if arg:
        lst.append(arg)

rawDescription: Keeping track of arguments passed to a function


code: root = Tk()

rawDescription: Tkinter window not closing after closed file dialog


code:
session = requests.session()
session.get('https://www.google.com/')
session.get('https://www.google.com/')

rawDescription: What is the practical difference between these two ways of making web connections in Python?


rawDescription: What's the best between return the result and print it at the end of the function?


code: m.loc[m[col] >= val, col] = quart

rawDescription: Improve code to replace values above the median by the median value itself in a pandas DataFrame


code:
line = {
    "stroke-width": "1px",
     "stroke": "black",
}
self.css[".link"] = line

rawDescription: How to plot graphs using networkx and d3py

description: Plot graphs using networkx and d3py


code: y = list(set(filter(lambda e: 1 <= e <= 100, x)))

rawDescription: Remove values from list leaving only unique values


code:
res.columns = ['item' + str(i + 1) for i in res.columns]
res.reset_index()

rawDescription: Pandas pivot or groupby for dynamically generated columns


code: not b.mask.all()

rawDescription: Most efficient way to determine if a numpy masked array contains any non-masked values?


code:
import matplotlib.pyplot as plt
import numpy as np
# To make things reproducible...
np.random.seed(1977)

fig, ax = plt.subplots()

# Twin the x-axis twice to make independent y-axes.
axes = [ax, ax.twinx(), ax.twinx()]

# Make some space on the right side for the extra y-axis.
fig.subplots_adjust(right=0.75)

# Move the last y-axis spine over to the right by 20% of the width of the axes
axes[-1].spines['right'].set_position(('axes', 1.2))

# To make the border of the right-most axis visible, we need to turn the frame
# on. This hides the other plots, however, so we need to turn its fill off.
axes[-1].set_frame_on(True)
axes[-1].patch.set_visible(False)

# And finally we get to plot things...
colors = ('Green', 'Red', 'Blue')
for ax, color in zip(axes, colors):
    data = np.random.random(1) * np.random.random(10)
    ax.plot(data, marker='o', linestyle='none', color=color)
    ax.set_ylabel('%s Thing' % color, color=color)
    ax.tick_params(axis='y', colors=color)
axes[0].set_xlabel('X-axis')

plt.show()

rawDescription: matplotlib: overlay plots with different scales?

description: Matplotlib: overlay plots with different scales


rawDescription: Efficient & Pythonic way of finding all possible sublists of a list in given range and the minimum product after multipying all elements in them?


code: [(m.start(0), m.end(0)) for m in re.finditer(pattern, string)]

rawDescription: Find the indexes of all regex matches in Python?


code:
col1, col2 = '{} has scored:','{}/10'

with open('classA.csv', 'a') as fp:
   writer = csv.writer(fp, delimiter=',')
   data = [(col1.format(name), col2.format(score))]
   writer.writerows(data)

rawDescription: Writing to a csv file in python

description: Writing to a csv file in python


code:
from itertools import groupby
from tw2.core import Param
from tw2.forms.widgets import BaseLayout

class FloatLayout(BaseLayout):

    template = "widgets.templates.float_layout"

    aside = Param('All fields aside', default=False)

    def rows(self, children):
        """Create the rows."""
        def row_no(child, no=[0]):
            if not self.aside and not getattr(child, 'aside', False):
                no[0] += 1
            return no[0]
        return groupby(children, row_no)

rawDescription: TurboGears2 - how to customize layout for new user form?


code:
import re, base64

filein = open("examplein.txt", 'r')
fileout = open("exampleout.txt", 'w')

matcher = re.compile("<Message>(?P<text>[^<]*)<End Message>")

for line in filein:
    match = matcher.search(line)
    if match:
        fileout.write("<message> " + base64.b64encode(match.group('text').strip()) + " <End message>\n")
    else:
        fileout.write(line)

filein.close()
fileout.close()

rawDescription: Python - extract and modify part of a specific line of text with a function for all files in folder


code:
['streetA', '15', 'New York']
['street number 2', '35', 'California']
['streetB', '36B', 'Texas']

rawDescription: Python Splitting string by number and space


rawDescription: Using Python in vimscript: How to export a value from a python script back to vim?


code:
import netifaces as ni
import winreg as wr
from pprint import pprint

def get_driver_name_from_guid(iface_guids):
    iface_names = ['(unknown)' for i in range(len(iface_guids))]
    reg = wr.ConnectRegistry(None, wr.HKEY_LOCAL_MACHINE)
    reg_key = wr.OpenKey(reg, r'SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}')
    for i in range(wr.QueryInfoKey(reg_key)[0]):
        subkey_name = wr.EnumKey(reg_key, i)
        try:
            reg_subkey = wr.OpenKey(reg_key, subkey_name)
            guid = wr.QueryValueEx(reg_subkey, 'NetCfgInstanceId')[0]
            try:
                idx = iface_guids.index(guid)
                iface_names[idx] = wr.QueryValueEx(reg_subkey, 'DriverDesc')[0]
            except ValueError:
                pass
        except PermissionError:
            pass
    return iface_names

x = ni.interfaces()
pprint(get_driver_name_from_guid(x))

rawDescription: How to get meaningful network interface names instead of GUIDs with netifaces under Windows?

description: Get meaningful network interface names instead of GUIDs with netifaces under Windows


rawDescription: Send/receive file over LAN with C# to/from Python


rawDescription: How to get count of unpublished commit with GitPython?

description: Get count of unpublished commit with GitPython


code:
diff = lambda a,b: [x for x in a if x not in b]

mergelist = lambda lVals: reduce(lambda res,x: res + x, map(tuple, lVals))

diff(mergelist(A), mergelist(B))
diff(mergelist(B), mergelist(A))

rawDescription: Find a particular list inside a list of lists


code:
d = {'a': '1'}
d.setdefault('b', 'b')
d
d.setdefault('a', 'b')
d

rawDescription: object properties in python

description: Object properties in python


rawDescription: fill in list in multiple steps

description: Fill in list in multiple steps


code:
from io import StringIO

import matplotlib.pyplot as plt
import pandas

data = StringIO("""\
Region  Q1  Q2  Q3  Q4
West    1   5.2 3.1 2.05
Center  3.1 1.2 1.2 3
East    1.9 4.1 1.1 5.3
""")

df = pandas.read_table(data, sep='\s+')
df.plot(kind='bar', x='Region')

rawDescription: Use the header as axis and first column as axis


code:
class Item(Base, DBBase):
    __tablename__ = 'item'
    id = Column(Integer, primary_key = True)
    name = Column(String, nullable = True)
    comments = relationship('ItemComment')
    comms = association_proxy('comments', 'comment',
            creator=lambda comment: ItemComment(comment=comment),
            )

class ItemComment(Base, DBBase):
    __tablename__ = 'itemcomments'
    item_id = Column(Integer, ForeignKey('item.id'), nullable = False, primary_key=True)
    comment = Column(String, nullable = False, primary_key=True)
    def __init__(self, comment):
        self.comment = comment

rawDescription: Sqlalchemy relationship to built-in type


code:
import binascii
binascii.hexlify(struct.pack('<I', 40000))

rawDescription: Writing hex value into file Python

description: Writing hex value into file Python


code:
def stopped():
    """ Toggles pause/play state if Enter is pressed """
    global trig, l
    while not trig:
        if l:
            l = []
            trig = True
            return trig, l

rawDescription: multithreading in Python: extremely high CPU consumption

description: Multithreading in Python: extremely high CPU consumption


code: range(len("patata"))

rawDescription: Lists, conditionals and loops don't give the result expected


code:
class A():
  def __init__(self, bar):
    baz = bar + bar
    self.egg = baz + baz

def B(tuna):
  return A(tuna)

rawDescription: How to tell what is a method and what is an object constructor in this class in Python?

description: Tell what is a method and what is an object constructor in this class in Python


code:
# -*- coding: utf-8 -*-
from ctypes import (
    pythonapi, c_void_p, c_size_t, c_int, c_uint64,
    c_byte, cast, POINTER, memmove, string_at,
)
import errno

mmap = pythonapi.mmap
mmap.restype = c_void_p
mmap.argtypes = [c_void_p, c_size_t, c_int, c_int, c_int, c_uint64]

munmap = pythonapi.munmap
munmap.restype = c_int
munmap.argtypes = [c_void_p, c_size_t]

errno_location = pythonapi.__errno_location
errno_location.restype = POINTER(c_int)

errormessage = lambda: errno.errorcode[errno_location()[0]]

PROT_NONE = 0
PROT_READ = 1
PROT_WRITE = 2
PROT_EXEC = 4

MAP_SHARED = 1
MAP_PRIVATE = 2
MAP_ANONYMOUS = 0x20

class RawData(object):
    "Allocated with mmap -call, no file handles."
    def __init__(self, length, prot):
        flags = MAP_PRIVATE | MAP_ANONYMOUS
        self.address = mmap(None, length, prot, flags, -1, 0)
        if 0 == self.address:
            raise Exception(errormessage())
        self.__length = length
        self.__accessor = cast(self.address, POINTER(c_byte))

    def __len__(self):
        return self.__length

    def __getitem__(self, key):
        assert key < len(self)
        return self.__accessor[key]

    def __setitem__(self, key, value):
        assert key < len(self)
        self.__accessor[key] = value

    def close(self):
        "the mapped memory must be freed manually"
        if 0 != munmap(self.address, len(self)):
            raise Exception(errormessage())

    def poke(self, offset, data):
        "poke data (from a tuple) into requested offset"
        for i, byte in enumerate(data):
            self[offset+i] = byte

    def upload(self, data, offset=0):
        "upload the data from a string"
        data = data.tostring()
        assert offset+len(data) <= len(self)
        memmove(self.address+offset, data, len(data))

    def tostring(self):
        return string_at(self.address, len(self))

__all__ = [
    'PROT_NONE',
    'PROT_READ',
    'PROT_WRITE',
    'PROT_EXEC',
    'RawData',
]

rawDescription: position contents of array.array into heap

description: Position contents of array.array into heap


code:
def sherwood(n):
    N = 2*n+1
    for i in range(N):
        low, high = max(0, i-n), min(i, n)
        w = list(range(low, high+1))
        yield zip(w[::-1], w)

rawDescription: Need a clever way to create a large list for a pygame/pyOpenGL project


code:
import ttk
import Tkinter as tk

class ExampleApp(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.var1 = tk.StringVar()
        self.var2 = tk.StringVar()

        f1 = ttk.Frame(self)
        red_button = ttk.Button(f1, text="Red", command=self.make_red)
        default_button = ttk.Button(f1, text="Default", command=self.make_default)
        default_button.pack(side="left")
        red_button.pack(side="left")

        f2 = ttk.Frame(self)
        self.cb_one = ttk.Checkbutton(f2, text="Option 1", variable=self.var1,
                                      onvalue=1, offvalue=0)
        self.cb_two  = ttk.Checkbutton(f2, text="Option 2", variable=self.var2,
                                       onvalue=1, offvalue=0)
        self.cb_one.pack(side="left")
        self.cb_two.pack(side="left")

        f1.pack(side="top", fill="x")
        f2.pack(side="top", fill="x")

        style = ttk.Style()
        style.configure("Red.TCheckbutton", foreground="red")

    def make_red(self):
        self.cb_one.configure(style="Red.TCheckbutton")
        self.cb_two.configure(style="Red.TCheckbutton")

    def make_default(self):
        self.cb_one.configure(style="TCheckbutton")
        self.cb_two.configure(style="TCheckbutton")

if __name__ == "__main__":
    root = tk.Tk()
    ExampleApp(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Changing ttk widget text color

description: Changing ttk widget text color


rawDescription: Determining whether a condition holds for all members of a list


code:
while True:
 try:
   data = fetch_data_from_output_queue()
   save_to_database(data)
 except EmptyQueue:
   if not stop_flag.is_set():
     # All done
     break
   time.sleep(1)
   continue

rawDescription: python threading Queue producer-consumer with thread-safe

description: Python threading Queue producer-consumer with thread-safe


code:
if span.has_key('id'):
    del span['id']

rawDescription: How to get the values of span tag in html using beautiful soup?

description: Get the values of span tag in html using beautiful soup


code: import itertools as it

rawDescription: Suggestions for writing this small piece of code more elegantly


code:
class Demo:
    def __init__(self):
        self.numbers = list(range(1, 10))

    def increment(self):
        for i, num in enumerate(reversed(self.numbers)):
            if num:
                self.numbers[-i - 1] = 0 if num == 9 else num + 1
                break

demo = Demo()
for _ in range(5):
    print(demo.numbers)
    demo.increment()

rawDescription: How to use a while loop to start at the right end of the list

description: Use a while loop to start at the right end of the list


code:
import datetime
dt = datetime.datetime.now()
dt
dt.time() < datetime.time(12)
dt.hour < 12
dt = dt.replace(hour=20)
dt
dt.time() < datetime.time(12)
dt.hour < datetime.hour

rawDescription: How to check if a date time is before midday

description: Check if a date time is before midday


code:
def paintEvent(self, e):
    """
    Copy the image from the Agg canvas to the qt.drawable.
    In Qt, all drawing should be done inside of here when a widget is
    shown onscreen.
    """

    #FigureCanvasQT.paintEvent(self, e)
    if DEBUG:
        print('FigureCanvasQtAgg.paintEvent: ', self,
            self.get_width_height())

    if self.blitbox is None:
        # matplotlib is in rgba byte order.  QImage wants to put the bytes
        # into argb format and is in a 4 byte unsigned int.  Little endian
        # system is LSB first and expects the bytes in reverse order
        # (bgra).
        if QtCore.QSysInfo.ByteOrder == QtCore.QSysInfo.LittleEndian:
            stringBuffer = self.renderer._renderer.tostring_bgra()
        else:
            stringBuffer = self.renderer._renderer.tostring_argb()

        refcnt = sys.getrefcount(stringBuffer)

        qImage = QtGui.QImage(stringBuffer, self.renderer.width,
                              self.renderer.height,
                              QtGui.QImage.Format_ARGB32)
        rect = qImage.rect()    ### <-- added this line
        p = QtGui.QPainter(self)
        p.eraseRect(rect)       ### <-- added this line
        p.drawPixmap(QtCore.QPoint(0, 0), QtGui.QPixmap.fromImage(qImage))

        # draw the zoom rectangle to the QPainter
        if self.drawRect:
            p.setPen(QtGui.QPen(QtCore.Qt.black, 1, QtCore.Qt.DotLine))
            p.drawRect(self.rect[0], self.rect[1],
                       self.rect[2], self.rect[3])
        p.end()

        # This works around a bug in PySide 1.1.2 on Python 3.x,
        # where the reference count of stringBuffer is incremented
        # but never decremented by QImage.
        # TODO: revert PR #1323 once the issue is fixed in PySide.
        del qImage
        if refcnt != sys.getrefcount(stringBuffer):
            _decref(stringBuffer)
    else:
        bbox = self.blitbox
        l, b, r, t = bbox.extents
        w = int(r) - int(l)
        h = int(t) - int(b)
        t = int(b) + h
        reg = self.copy_from_bbox(bbox)
        stringBuffer = reg.to_string_argb()
        qImage = QtGui.QImage(stringBuffer, w, h,
                              QtGui.QImage.Format_ARGB32)
        pixmap = QtGui.QPixmap.fromImage(qImage)
        p = QtGui.QPainter(self)
        p.drawPixmap(QtCore.QPoint(l, self.renderer.height-t), pixmap)
        p.end()
        self.blitbox = None
    self.drawRect = False

rawDescription: Matplotlib / PyQT4: transparent figure

description: Matplotlib / PyQT4: transparent figure


code:
from subprocess import Popen, PIPE
proc = Popen(["which", "R"],stdout=PIPE,stderr=PIPE)
exit_code = proc.wait()
if exit_code == 0:
    print ("Installed")

rawDescription: Check if R is installed from python

description: Check if R is installed from python


code:
a = np.random.randint(3, size=10)
a
index = np.arange(len(a))
sort_idx = np.argsort(a)
cnt = np.bincount(a)
np.split(index[sort_idx], np.cumsum(cnt[:-1]))

rawDescription: Find the indices of non-zero elements and group by values


code:
def f(i):
   return int(i*10)

DoL=defaultdict(list)
for e in (random.random() for i in xrange(50)):
   DoL[f(e)].append(e)

rawDescription: Pythonic way to partition a list in exactly two groups


code: f = {'start':['first'],'end':['last'], 'groups':['first']}

rawDescription: Pandas - group by consecutive ranges

description: Pandas - group by consecutive ranges


code: result = {key: 'colore{}'.format(i) for i, key in enumerate(set(test_input), 1)}

rawDescription: python dict.fromkeys with function as parameter

description: Python dict.fromkeys with function as parameter


code:
class Shared:
    def __init__(self):
        print("Init shared")

    def do_stuff(self, from_mod):
        print("Do stuff from {0}. I am instance {1}".format(from_mod, self))

shared = Shared()

rawDescription: Good practice sharing resources between modules?


code:
class ComparableMixin:
  def __eq__(self, other):
    return not self<other and not other<self
  def __ne__(self, other):
    return self<other or other<self
  def __gt__(self, other):
    return other<self
  def __ge__(self, other):
    return not self<other
  def __le__(self, other):
    return not other<self

rawDescription: __lt__ instead of __cmp__

description: __lt__ instead of __cmp__


code: filter_props = [k for k, v in Model1._properties.iteritems()]

rawDescription: How do I filter a dict to match the attributes of my ndb.Model subclass

description: Filter a dict to match the attributes of my ndb.Model subclass


code:
dict((k, tuple(str(x) for x in v)) for k, v in d.iteritems())

{k: tuple(str(x) for x in v) for k, v in d.items()}

rawDescription: Python dictionary with objects into dictionary with strings


rawDescription: django one session per user

description: Django one session per user


rawDescription: How to validate user input in python

description: Validate user input in python


code:
class Animal(object):
    def __init__(self, *args, **kwargs):
        # might require more complex condition
        self._is_empty = not (bool(args) or bool(kwargs))
    def is_empty(self):
        return self._is_empty

rawDescription: Create current class default instance in its base class


code:
import numpy as np
mean_CC_age = np.mean([int(D['AGE']) for D in Company.itervalues() if D['Company Car'] == 'Yes'])

rawDescription: Directly calculating conditional averages in a Python Dictionary


rawDescription: python - please help cant figure out how to add up user input of an array

description: Python - please help cant figure out how to add up user input of an array


code:
import itertools

fruits = ['Apple', 'Mango', 'Pineapple', 'Banana', 'Oranges']
sizes = ['small', 'medium', 'big']

for fruit, size in itertools.product(fruits, sizes):
    dot_file = 'main-directory/{fruit}/collateral/{fruit}_{size}.dot'.format(fruit=fruit, size=size)
    text_file = 'main-directory/source/readparamters/readparam/{fruit}_{size}.txt'.format(fruit=fruit, size=size)
    try:
        open(dot_file)  # statement 1
        open(text_file)  # statement 2
    except Exception as e:
        print(e)  # handle erorrs!

rawDescription: How to avoid hard coding in if condition of python script

description: Avoid hard coding in if condition of python script


rawDescription: How to divide sentences based on some special contents, Python,

description: Divide sentences based on some special contents, Python,


code:
if __name__ == '__main__':
    threading.Thread(target=run, kwargs=dict(host='localhost', port=8080)).start()
    method()

rawDescription: threading a bottle app

description: Threading a bottle app


code:
for i in item:
   d[i.oid].append(i.val)

rawDescription: Grouping data by value in first column

description: Grouping data by value in first column


code:
import numpy as np
from scipy.interpolate import interp1d
from scipy.io import wavfile

def apply_transfer(signal, transfer, interpolation='linear'):
    constant = np.linspace(-1, 1, len(transfer))
    interpolator = interp1d(constant, transfer, interpolation)
    return interpolator(signal)

rawDescription: How to amplify sounds without distortion in Python

description: Amplify sounds without distortion in Python


code:
from scrapy.mail import MailSender

mailer = MailSender()
mailer.send(to=["someone@example.com"], subject="Some subject", body="Some body", cc=["another@example.com"])

rawDescription: Sending e-mail after scrape in scrapy

description: Sending e-mail after scrape in scrapy


rawDescription: Fast way to transpose np.arrays and write them to file


rawDescription: Pythonic and efficient way to do an elementwise "in" using numpy


code:
env = Environment()
code_generator = Builder(action = '$CC $CCFLAGS -S $SOURCE -o $TARGET',
                         single_source = 1,
                         suffix = '.s')
env.Replace(CC= 'clang')
env.Append(BUILDERS = {'CodeGenerator' : code_generator})
sources = env.CodeGenerator(file)
env.Program('say_hello', sources)

rawDescription: Configuring SCons to use separate tools for code generation and assembly


code: df[df['name'] == specific_name]

rawDescription: search in pandas series des not work

description: Search in pandas series des not work


code:
max_water_heldover([9, 8, 7, 8, 9, 5, 6])
max_water_heldover([8, 8, 4, 5])
max_water_heldover([3, 1, 2, 1, 3])

rawDescription: Algorithm to solve for water accumulation given building heights


code:
min_x = min(particleCoords.itervalues(),key = itemgetter(0))
max_x = max(particleCoords.itervalues(),key = itemgetter(0))

min_y = min(particleCoords.itervalues(),key = itemgetter(1))
max_y = max(particleCoords.itervalues(),key = itemgetter(1))

rawDescription: Finding Max and Min coordinates for X and Y in a dictionary


code:
df
df['WIKIURL'] = df['WIKIURL'].str.replace('/wiki/','')
df

rawDescription: How to change text in specific column in panda data frame?

description: Change text in specific column in panda data frame


code:
M.rows
M.data

rawDescription: Save a Sparse.LIL matrix to csv in Python


rawDescription: Python: using __getitem__ in a class and using in to find that item


code:
list1=['pH','Absolute Index','Hello']
sring1='lekpH Absolute Index of New'

# Add spaces up front to avoid creating the spaced string over and over
# Do the same for list1 if it will be reused over and over
sringspaced = ' {} '.format(sring1)

for item in list1:
    if ' {} '.format(item) in sringspaced:
        print(item)

rawDescription: Searching in a string in python

description: Searching in a string in python


code: tuple_list = [(a, some_process(b)) for (a, b) in tuple_list]

rawDescription: Iterate a list of tuples

description: Iterate a list of tuples


code:
def f(word):
    vowels = {"a", "e", "i", "o", "u"}
    consonants = {'t', 'b', 'm', 'h', 'y', 'w', 'z', 'p', 'v', 'd', 'g', 'k', 'j', 'n', 'r', 'q', 'x', 'c', 's','f', 'l'}
    return [ele + word[i] for i, ele in enumerate(word[:-1], 1)
            if word[i] in vowels and ele in consonants ]

rawDescription: Splitting the letters of a word based on conditions, and returning in a list (Python)


code:
class Dog(Pet):

   def __init__(self, chases_cats, *args, **kwargs):
      Pet.__init__(self, *args, species="Dog", **kwargs)
      self.chases_cats = chases_cats

class Pet(object):

    def __init__(self, name, species, *args, **kwargs):
       self.name = name
       self.species = species

rawDescription: Python inheritance. Why is it so messy?

description: Python inheritance. Why is it so messy


code:
m,n = a.shape
out = np.arange(m)[:,None] != np.arange(n)

rawDescription: How to get indices of non-diagonal elements of a numpy array?

description: Get indices of non-diagonal elements of a numpy array


code:
class Observer(object):
    def update(self,subject,message): pass

    def deleting(self,subject):
        ''' the subject is being deleted '''
        pass

    def deleted(self,subject):
        pass

rawDescription: Using the observer pattern to delete an Observer when a Subject has been "deleted" in Python


code:
n = 10 # count of values
lis = [int(input("enter value %d: " % x)) for x in range(1, n+1)]

rawDescription: How to get data from a.py to import into b.py

description: Get data from a.py to import into b.py


code:
import matplotlib.dates as mdate
dt = mdate.num2date(num)

rawDescription: Attempting to use a Datetime from a mouseevent from Matplotlib within Tkinter


code:
def my_tag(context):
    context.write("hello world")
    return ''

rawDescription: Is it possible to create new tags in Mako?


code:
# Calculate fraction of variance explained
# for each choice of number of components
r2 = pca.explained_variance_.cumsum() / x.var(0).sum()

rawDescription: How to change parameters of a scikit learn function dynamically i.e. find best parameter

description: Change parameters of a scikit learn function dynamically i.e. find best parameter


code:
num1=raw_input("ENter a number :"); #<= remove the ; here
nam1=raw_input("What is your name:"); #<= remove the ; here

rawDescription: multiple inputs in python

description: Multiple inputs in python


code: np.hstack([dydx, dydx[-1]])

rawDescription: simple but weird vstack/concatenate problems (python)

description: Simple but weird vstack/concatenate problems (python)


code:
import math
def convertToNumber (s):
    return int.from_bytes(s.encode(), 'little')

def convertFromNumber (n):
    return n.to_bytes(math.ceil(n.bit_length() / 8), 'little').decode()

rawDescription: String of text to unique integer method?

description: String of text to unique integer method


code:
class Foo:
    def __init__(self):
        self.x = 10
    def __getattr__(self,name):
        return name
    def __getattribute__(self, name):
        if name == 'bar':
            raise AttributeError
        return 'getattribute'

f = Foo()
f.x    # -> 'getattribute'
f.baz    # -> 'getattribute'
f.bar    # -> 'bar'

rawDescription: What are the differences amongst Python's "__get*__" and "_del*__" methods?


rawDescription: Identify groups of continuous numbers in a list


code:
from twisted.web import client
class MyHTTPClient(client.HTTP11ClientProtocol):
    def connectionMade(self):
        self.transport.setTcpNoDelay(True)
        client.HTTP11ClientProtocol.connectionMade(self) # call the super-class's connectionMade

class MyAgent(client.Agent):
    _protocol = MyHTTPClient

rawDescription: Access socket options for twisted.web.client.Agent


rawDescription: Convert from string to tuple with "\" in python


code: result = [(key, value) for key, value in my_dict.iteritems() if key.startswith("seller_account")]

rawDescription: Python dictionary search values for keys using regular expression


code:
names = {
    9:  ("John", "Smith"),
    11: ("Bob", "Dobbs"),
    14: ("Joe", "Bloggs")
}

jobs = {
    9:  "Builder",
    11: "Baker",
    14: "Candlestick Maker"
}

rawDescription: Join lists by value

description: Join lists by value


code:
with open("outfile.txt", "w") as f:
    f.write("\n".join(([" ".join([str(a[0]), str(a[1])]) for a in zip(col1, col2)])))

rawDescription: how to split a very long row data into two column by python (from txt file)

description: Split a very long row data into two column by python (from txt file)


rawDescription: Python - Function has a list as argument. How to return another list without changing the first?


code:
import theano, numpy
T = theano.tensor.matrix()
o = theano.tensor.concatenate([T[2], T[4], [100, 101, 102, 103, 104]])
f = theano.function([T], o)
f(numpy.arange(25).reshape(5, 5))

rawDescription: Theano Tensor remove element?

description: Theano Tensor remove element


code:
def newickNode(newickString, parent=None):
    String = newickString[1:-1].split(',')
    for x in String:
        splitString = x.split(':')
        nodeName = splitString[0]
        nodeDistance = float(splitString[1])
        node = Node(nodeName, nodeDistance, parent)
        yield node

for node in newickNode('(A:0.1,B:0.2,C:0.3,D:0.4)'):
    node.displayNode()

rawDescription: Python For...loop iteration

description: Python For...loop iteration


code:
John
15
Bob
16

rawDescription: Python data structure for specific storage


code:
class Location(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

rawDescription: updated at field in django model

description: Updated at field in django model


code:
cutoff = data.index[-1] - pd.DateOffset(weeks=5)
mask = data.index < cutoff

rawDescription: Date Time Selection Python

description: Date Time Selection Python


code:
import os
import ujson
import pandas as pd

start_path = '/home/jayaramdas/anaconda3/Thesis/govtrack/bills109/hr'

def get_merged_json(start_path):
    return [ujson.load(open(os.path.join(path, f)))
            for p, _, files in os.walk(start_path)
            for f in files
            if f.endswith('.json')
           ]

df = pd.read_json(ujson.dumps(data))

rawDescription: Pandas: Retrieving nested data from JSON File


code:
input_stream = """
2
8 9
3
asd dsa fff
2
1 2
3 4
"""
tokens = input_stream.split()

rawDescription: Programming contest like input validator


code: dv = seqDic.keys()

rawDescription: Learning Python and using dictionaries

description: Learning Python and using dictionaries


code:
import random
def diceprob(r):
    total_count = 0
    count = 0

    while count < 100:
        roll = random.randrange(1, 7) + random.randrange(1, 7)
        total_count += 1
        if roll == r:
            count += 1
    print("It took {} rolls to get 100 rolls of {}".format(total_count, r))

rawDescription: Simulates repeated rolls of a pair of dice until 100 rolls of r have been obtained; the number of rolls is then printed


code:
import imp
my_module = imp.load_source("My custom module", "my_module.some_extension")
my_module
dir(my_module)
my_module.func()

rawDescription: Is there a python 3 file extension that acts exactly like a *.py extension?


code:
class Game(models.Model):
    name = models.CharField()
    debut = models.DateField()
    max_players = models.IntegerField()

    @classmethod
    def create_from_j(cls, game): # assumed that game is dict already
        j2m = {'title': 'name', 'release': 'debut', 'players': 'max_players'}
        return cls(**{j2m[k]:v for k,v in game.items()})

rawDescription: Django: Map data from an external APIs into a model?


rawDescription: Parent-child relationship efficiency

description: Parent-child relationship efficiency


code:
def protected(method):
    @tornado.web.authenticated
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        self.set_header('Cache-Control', 'no-cache, no-store, must-revalidate')
        self.set_header('Pragma', 'no-cache')
        self.set_header('Expires', '0')
        return method(self, *args, **kwargs)
    return wrapper

rawDescription: tornado.web.authenticated back button issue

description: Tornado.web.authenticated back button issue


code:
import numpy as np

x = np.array([0, 1, 2, 3, 4])
y = np.array([9, 1, 2, 3, 7])

arrays_equal = x == y

rawDescription: Opencv: How to detect pixel color change


code:
class Personage(models.Model):
    prenom = models.CharField(max_length=255)

    @property
    def first_name(self):
        return self.prenom

rawDescription: approaching django model fields through a field name mapping

description: Approaching django model fields through a field name mapping


code:
df.cross.sum()
4

rawDescription: Finding when a value in a pandas.Series crosses/reaches a threshold


rawDescription: Python Pandas: Multiple aggregations of the same column


code:
s = [['Apple','Yes','Edible'], ['Watermellon','Yes','Yes']]

fruit_dict = {l[0]: Fruit(*l) for l in s}
print(fruit_dict['Apple'].seeds)

rawDescription: Breaking down list of list into dictionaries


rawDescription: Specify list of possible values for Pandas get_dummies


code:
def greeting():
    print('Hello world!')
    print('What is your name?')
    myName = input()
    print('It is nice to meet you, ' + myName)

rawDescription: How do i use function call properly. I am gonna do 2 batch python script. The one is in input the other one is output

description: Use function call properly. I am gonna do 2 batch python script. The one is in input the other one is output


code:
def findSubString(raw_string, start_marker, end_marker):
    result = []
    rest = raw_string
    while True:
        head, sep, tail = rest.partition(start_marker)
        if not sep:
            break
        body, sep, tail = tail.partition(end_marker)
        if not sep:
            break
        result.append(head + start_marker + body.strip().replace(' ', '_') + end_marker)
        rest = tail
    result.append(rest)
    return ''.join(result)

rawDescription: Python find all matching substring patterns and replace substring


rawDescription: How do I subtract pandas columns that correspond to different time intervals in python?

description: Subtract pandas columns that correspond to different time intervals in python


code: sij = l*Sum(U[k, k], (k, 0, 2)) * KroneckerDelta(i, j) + mu*(U[i, j] + U[j, i])

rawDescription: Expand index notation equation using sympy


rawDescription: Accessing bitfields while reading/writing binary data structures


code:
class B():
    def __repr__(self):
        return "This is B"

rawDescription: How to invoke __repr__ of parent class?

description: Invoke __repr__ of parent class


message: The command Completed Successfully

key: value

rawDescription: AJAX Posting to Python cgi

description: AJAX Posting to Python cgi


code:
cleartext = ""
for c in msg:
    if c in alphabet:
        pos = alphabet.index(c)
        cleartext += string.ascii_uppercase[pos]
    else:
        cleartext += c

rawDescription: Decrypting Input?

description: Decrypting Input


code: isinstance(o, basestring)

rawDescription: What's the canonical way to check for type in python?


code:
# ---------- settings.py

NAME = "Lance"
DOMAIN = "http://example.com"

# ---------- main.py

import settings

settings.DOMAIN # [...]

rawDescription: How do you define config variables / constants in Google App Engine (Python)?

description: Define config variables / constants in Google App Engine (Python)


rawDescription: Python split string by pattern

description: Python split string by pattern


code:
def stdout_toggle(prefix='pre', msg=False, _s=[None, None]):
    import datetime as dt
    import os
    import sys
    if _s[0] is None:
        now = dt.date.today()
        repname = repnameprefix = prefix + now.strftime("%Y%m%d") + '.txt'
        count = 0
        while os.path.isfile(repname):
            count += 1
            repname = repnameprefix + (".%02d" %(count))
        f = open(repname,'w')
        _s[:] = [sys.stdout, f]
        sys.stdout = f
    else:
        sys.stdout = _s[0]
        _s[1].close()
        if msg:
            print('output to:' + _s[1].name)
        _s[:] = [None, None]

rawDescription: replace class method with simple function

description: Replace class method with simple function


code:
class AnalysisInput(models.Model):
    input_user = models.CharField(max_length=45)
    input_title = models.CharField(max_length=45)
    input_date = models.DateTimeField()
    input_link = models.CharField(max_length=100)

    def as_json(self):
        return dict(
            input_id=self.id, input_user=self.input_user,
            input_title=self.input_title,
            input_date=self.input_date.isoformat(),
            input_link=self.input_link)

rawDescription: How to serialize to JSON a list of model objects in django/python

description: Serialize to JSON a list of model objects in django/python


rawDescription: How do I obtain the reference of a getter/setter method created through @property in Python?

description: Obtain the reference of a getter/setter method created through @property in Python


code: re.sub(r'\d', confirmSub, "Each of the 2 cars is 5 long.")

rawDescription: Interactive substitution - re.sub() with pos?


code:
def stock_sim(price,time,mu,std):
    temp = [price + random.lognormvariate(mu,std) for i in range(time)]
    temp.insert(0,price)
    return temp

rawDescription: I am creating a list and need to return the initial value


rawDescription: Trouble querying ListField with mongoengine


rawDescription: Random sampling and Pandas dataframes

description: Random sampling and Pandas dataframes


code:
1 or 2
0 or 2
0 or False or None or 10
0 or False

rawDescription: Python Logical Operators

description: Python Logical Operators


rawDescription: Python: RegEx assistance

description: Python: RegEx assistance


code:
center_y[nrow-1,:] = 0.5*deltay[nrow-1]
for i in range(nrow-2,-1,-1):
    center_y[i,:] = center_y[i+1,:] + 0.5*deltay[i+1] + 0.5*deltay[i]

rawDescription: Python: Help in optimizing code

description: Python: Help in optimizing code


code: np.in1d(A, bads)

rawDescription: Converting Specified Elements of a NumPy Array by a New Value


code:
class A(object): ...
A = decorate_all_methods(Http500Resistant)(A)

rawDescription: Try/Except Every Method in Class?

description: Try/Except Every Method in Class


code:
df['Gender'] = df.Sex.map(lambda x: 0 if x=='female' else 1)
df['FamilySize'] = df.SibSp + df.Parch

rawDescription: Write to_csv with Python Pandas: Choose which column index to insert new data


rawDescription: How importing works. Why imported modules not inheriting other imported modules


code:
fieldsets = hide_fields(
    (None,
        {'fields':('title', 'content')}
    )
)

rawDescription: How To Collapse Just One Field in Django Admin?


rawDescription: Inserting values into a list whilst looping over it (Python)


code:
for line in open('tests.new', 'r'):
    mail.write(line + '\n')

rawDescription: Add '\n' to each line of an open file in Python


code:
import cv
with open('textFileOfImages.txt','rb') as f:
    img = [line.strip() for line in f]

#load the images at you leisure
for image in img:
    loadedImage = cv.LoadImage(image)
    #manipulate image

rawDescription: Loading multiple images from a text file


code:
# Get the result row from the user.
result_row = self.compute(dates[i], assets, *inputs)
# Copy the user's result into our output buffer.
output[i] = result_row

rawDescription: Quantopian / Zipline: weird pattern in Pipeline package


rawDescription: How to mock chained function calls in python?

description: Mock chained function calls in python


rawDescription: Handle path name with backslash followed by numbers (Python)


code:
cols = list('abc')
df = DataFrame(randn(10, len(cols)), columns=cols)
df.a.quantile(0.95)

rawDescription: Eliminating all data over a given percentile


code:
with open("filename.txt", 'r') as f:
    data = [map(int, line.split()) for line in f]

rawDescription: Python how to read and split a line to several integers


code: url(r'^link-to-fun1$', views.fun1),

rawDescription: Django ajax no refresh:django view without redirecting or refreshing a page


rawDescription: Python : Sort file by arbitrary column, where column contains time values


code:
import itertools

def pairwise(s):
    a,b = itertools.tee(s)
    next(b)
    return zip(a,b)

counts = [[0 for _ in range(52)] for _ in range(52)]  # nothing has occurred yet
with open('path/to/input') as infile:
    for a,b in pairwise(char for line in infile for word in line.split() for char in word):  # get pairwise characters from the text
        given = ord(a) - ord('a')  # index (in `counts`) of the "given" character
        char = ord(b) - ord('a')   # index of the character that follows the "given" character
        counts[given][char] += 1

# now that we have the number of occurrences, let's divide by the totals to get conditional probabilities

totals = [sum(count[i] for i in range(52)) for count in counts]
for given in range(52):
    if not totals[given]:
        continue
    for i in range(len(counts[given])):
        counts[given][i] /= totals[given]

rawDescription: How do I program bigram as a table in python?

description: Program bigram as a table in python


rawDescription: Accessing a variable defined inside a function Python


code:
# Module machines

class Calculator(object):
    def __init__(self, multiplier):
        self._multiplier = multiplier
    def multiply(self, n):
        return self._multiplier * n

def increment(n):
    return n + 1

def decrement(n):
    return n - 1

calculator = Calculator(2)
assert calculator.multiply(3) == 6
assert increment(3) == 4
assert decrement(3) == 2

class Machine(object):
    '''A larger machine that has a calculator.'''
    def __init__(self, calculator):
        self._calculator = calculator
    def mult(self, n):
        return self._calculator.multiply(n)
    def incr(self, n):
        return increment(n)
    def decr(self, n):
        return decrement(n)

machine = Machine(Calculator(3))
assert machine.mult(3) == 9
assert machine.incr(3) == 4
assert machine.decr(3) == 2

rawDescription: How to mock Python static methods and class methods

description: Mock Python static methods and class methods


code:
for col in row[6:]:
    foo()

rawDescription: Python: How to iterate over specific columns in rows in text file


code:
import rpyc
from multiprocessing import Pool
rpyc.core.protocol.DEFAULT_CONFIG['allow_pickle'] = True

def square(x):
    return x*x

class MyService(rpyc.Service):

    def exposed_RemotePool(self, function, arglist):

        pool = Pool(processes = 8)
        result = pool.map(function, arglist)
        pool.close()
        return result

if __name__ == "__main__":
    from rpyc.utils.server import ThreadedServer
    t = ThreadedServer(MyService, port = 18861, protocol_config = rpyc.core.protocol.DEFAULT_CONFIG)
    t.start()

rawDescription: Multiprocessing Python with RPYC "ValueError: pickling is disabled"


code:
foo = None
result = foo and foo(bar)

rawDescription: python or on operator module

description: Python or on operator module


rawDescription: sort an array to fit another array with numpy

description: Sort an array to fit another array with numpy


code:
from itertools import product
[(x, y, fuzz.ratio(x, y)) for (x, y) in product(titles, repeat=2)]

rawDescription: Organization of fuzzy matches

description: Organization of fuzzy matches


code:
a1 = np.array([1, 2, 3])
a2 = np.array([2, 3, 4])
a  = np.array([a1, a2])
a
b1 = np.array([10, 100, 1000])
b2 = np.array([20, 200, 2000])
b  = np.array([b1, b2])
b
a/b
np.std(a/b)             # The standard deviation of the whole matrix
np.std(a/b, 0)          # The standard deviation of each column
np.std(a/b, 1)          # The standard deviation of each row

rawDescription: Python, iterate over multiple arrays to perform tasks


code:
def is_container_iterable(o):
    return hasattr(o, '__iter__') and hasattr(o, '__getitem__')

is_container_iterable([])
is_container_iterable(())
is_container_iterable({})
is_container_iterable(range(5))
is_container_iterable(iter([]))

rawDescription: how to check if an iterable allows more than one pass?

description: Check if an iterable allows more than one pass


code:
import nltk
nltk.__version__
pattern = r'''(?x)               # set flag to allow verbose regexps
              ([A-Z]\.)+         # abbreviations, e.g. U.S.A.
              | \$?\d+(\.\d+)?%? # numbers, incl. currency and percentages
              | \w+([-']\w+)*    # words w/ optional internal hyphens/apostrophe
              | [+/\-@&*]        # special characters with meanings
            '''
from nltk.tokenize.regexp import RegexpTokenizer
tokeniser=RegexpTokenizer(pattern)
line="My weight is about 68 kg, +/- 10 grams."
tokeniser.tokenize(line)

rawDescription: Python: Regular Expression not working properly


code:
win.winHandle.minimize() # minimise the PsychoPy window
win.fullscr = False # disable fullscreen
win.flip() # redraw the (minimised) window

rawDescription: PsychoPy reopen window

description: PsychoPy reopen window


code: eval(str(num1) + operation + str(num2))

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

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


rawDescription: Python Numpy Array Operator x += y Different From x = x + y?


code: [Counter(site) for site in zip(*myDict.values())]

rawDescription: Iterating through tuples to count values in list


code: ''.join('0' if x >= v else ' ' for x in end_location)

rawDescription: The Bean Machine Function - Python

description: The Bean Machine Function - Python


code:
def LoadMyDLL():
    dll = ctypes.CDLL("libmydll.so")
    dll.HelperFunction = HelperFunction
    dll.HelperFunction.dll = dll
    return dll

rawDescription: How to get the object from within an imported member function?

description: Get the object from within an imported member function


code:
class MyView(View):
    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        self.myObj = ...
        self.requester = ...
        return super(MyView, self).dispatch(*args, **kwargs)

rawDescription: daisy-chaining Python/Django custom decorators

description: Daisy-chaining Python/Django custom decorators


code:
bases = "ACGT"

def mutate(orig_string, mutation_rate=0.0066):
    result = []
    mutations = []
    for base in orig_string:
        if random.random() < mutation_rate:
            new_base = bases[bases.index(base) - random.randint(1, 3)] # negatives are OK
            result.append(new_base)
            mutations.append((base, new_base))
        else:
            result.append(base)
    return "".join(result), mutations

rawDescription: Random DNA mutation Generator

description: Random DNA mutation Generator


code:
tuple_wanted(('A', 'C'))
tuple_wanted(('R', 'E'))

rawDescription: Python - using dictionary to count keys and values


code:
# -*- coding: utf-8 -*-

# Scrapy settings for splashtst project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     http://doc.scrapy.org/en/latest/topics/settings.html
#     http://scrapy.readthedocs.org/en/latest/topics/downloader-middleware.html
#     http://scrapy.readthedocs.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'splashtst'

SPIDER_MODULES = ['splashtst.spiders']
NEWSPIDER_MODULE = 'splashtst.spiders'

# Splash stuff
SPLASH_URL = 'http://localhost:8050'
DOWNLOADER_MIDDLEWARES = {
    'scrapy_splash.SplashCookiesMiddleware': 723,
    'scrapy_splash.SplashMiddleware': 725,
    'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware': 810,
}

SPIDER_MIDDLEWARES = {
    'scrapy_splash.SplashDeduplicateArgsMiddleware': 100,
}
DUPEFILTER_CLASS = 'scrapy_splash.SplashAwareDupeFilter'
HTTPCACHE_STORAGE = 'scrapy_splash.SplashAwareFSCacheStorage'

rawDescription: Scrapy bypassing start_urls

description: Scrapy bypassing start_urls


code:
out = open(stdout_log, 'w')
stdout_reset = sys.stdout
sys.stdout = Tee(sys.stdout, out)
from subprocess import Popen,PIPE,STDOUT
process = Popen([list_of_cmds],stdout=PIPE,stderr=STDOUT)
# Stream the output to the console and stdoutfiles
for line in iter(process.stdout.readline,""):
    sys.stdout.write(line)

out.close()

rawDescription: Subprocess displays sys.stdout correctly in PyCharm but not in the console


code:
import pandas
df = pandas.DataFrame(np.random.random(100)*100, columns=['val1'])

pctiles = pandas.qcut(df['val1'],4,retbins=True)
pctile_object = pctiles[0]
pctile_boundaries = pctiles[1]

rawDescription: Pandas assign each row the mean of its bin


code:
def completed_quarter(dt):
    prev_quarter_map = ((4, -1), (1, 0), (2, 0), (3, 0))
    quarter, yd = prev_quarter_map[(dt.month - 1) // 3]
    return (dt.year + yd, quarter)

rawDescription: finding the year and quarter from a datetime object in python

description: Finding the year and quarter from a datetime object in python


code:
def equal_dicts(d1, d2, ignore_keys):
    d1_filtered = dict((k, v) for k,v in d1.iteritems() if k not in ignore_keys)
    d2_filtered = dict((k, v) for k,v in d2.iteritems() if k not in ignore_keys)
    return d1_filtered == d2_filtered

rawDescription: Compare dictionaries ignoring specific keys


code:
from hashlib import md5
h = md5('email@example.com').digest().encode('base64')[:-1]
_
len(h)

rawDescription: Django: Is Base64 of md5 hash of email address under 30 characters?


code: pybench \

rawDescription: What is the fastest way to copy a 2D array in Python?


code:
def do_counting(column_list):
    for column in column_list:
        query = (
            "select count(*) from " + tablename
            + " where " + column + " is not null"
            )
        result = execute_query(qCountsEmployee)
        yield column, result

result_dict = dict(do_counting(['...']))

rawDescription: Is it possible to generate and execute Python code in a Python script? [Dynamic Python code]


code:
def find_key(input_dict, value):
    return next((k for k, v in input_dict.items() if v == value), None)

rawDescription: return key by value in dictionary

description: Return key by value in dictionary


code: re.findall("\d{2}-\d{8}", line)

rawDescription: Python Regex And encode

description: Python Regex And encode


code:
buf = stream.read(1)
if buf:
    raise ValueError("Stream not consumed")

rawDescription: Idiomatic way to struct.unpack from BytesIO?


rawDescription: Django, multiple ModelAdmin for one Model


code:
line = "Isn't ., stackoverflow the - best ?"
' '.join(filter(None, (word.strip(punctuation) for word in line.split())))

rawDescription: python - How to remove punctuation in between words

description: Python - How to remove punctuation in between words


code:
df['Owner'] = ff[ff == df['Owner'].bfill()]
df

rawDescription: Replacing missing values if lag and lead are the same


rawDescription: References to All Defined Objects in a Python Interactive Session


rawDescription: local maximum in lists within list

description: Local maximum in lists within list


code:
import struct
import time

def lastbit(f):
    return struct.pack('!f', f)[-1] & 1

def getrandbits(k):
    "Return k random bits using a relative drift of two clocks."
    # assume time.sleep() and time.clock() use different clocks
    # though it might work even if they use the same clock
    #XXX it does not produce "good" random bits, see below for details
    result = 0
    for _ in range(k):
        time.sleep(0)
        result <<= 1
        result |= lastbit(time.clock())
    return result

rawDescription: Python Random Function without using random module


code:
class Wait:
    timeout = 9
    def __init__(self, timeout=None):
        if timeout is not None:
            self.timeout = timeout

a = Wait()
b = Wait(9)
a.timeout
b.timeout
Wait.timeout = 20
a.timeout
b.timeout

rawDescription: Class attribute or argument's default value


code:
def to_24hour(hour, ampm):
    """Convert a 12-hour time and "am" or "pm" to a 24-hour value."""
    if ampm == 'am':
        return 0 if hour == 12 else hour
    else:
        return 12 if hour == 12 else hour + 12

def to_12hour(hour):
    """Convert a 24-hour clock value to a 12-hour one."""
    if hour == 0:
        return (12, 'am')
    elif hour < 12:
        return (hour, 'am')
    elif hour == 12:
        return (12, 'pm')
    else:
        return (hour - 12, 'pm')

rawDescription: Python - Convert time to different time zone with am/pm


code:
mydict = {}
mydict['a'] = []
mydict['a'].append("enter value here")

rawDescription: Creating a Dictionary with a list of values by appending in python


code:
from elasticsearch_dsl import Index
from mytype import MyType

myindex = Index('myindex')
myindex.doc_type(MyType)
myindex.create()

rawDescription: how to create a nested index in ElasticSearch with Python?

description: Create a nested index in ElasticSearch with Python


code: (True, "one")

rawDescription: Sort python list of dictionaries by key if key exists


code:
from operator import ne
from itertools import count, imap, compress
list1[:next(compress(count(), imap(ne, list1, list2)), 0)]

rawDescription: The fastest way to find common elements at the beginning of 2 python lists?


code:
# We're going to monkey-patch stdin
import sys
from cStringIO import StringIO
old = sys.stdin
sys.stdin = StringIO('hello')

# Now read from stdin
result = raw_input('foo')

# And replace the regular stdin
sys.stdin = old

rawDescription: How to feed in an answer to input in script in Python

description: Feed in an answer to input in script in Python


code:
def customlist_handler(request, resource):
    #You have access to the resource type specified in the URL.
    ...

rawDescription: django Url endswith regex in url path

description: Django Url endswith regex in url path


code:
try:
    return formatfunc(thing)
except:
    return thing

rawDescription: Rounding decimals in nested data structures in Python


code:
M.data
M.row
M.col

rawDescription: is there something like coo_matrix but for sparse vectors?

description: Is there something like coo_matrix but for sparse vectors


code: output.write("{0}\t{1}".format(a, am))

rawDescription: Writing Arrays to a Tab Delimited Text File


code:
df['new_date'] = df.apply(lambda row: str(row['day'])+'/'+str(row['month'])+'/'+str(row['year']), axis=1)
df

rawDescription: Combining rows in DataFrame

description: Combining rows in DataFrame


code:
apple_loads = (float(i['Apples']) for i in fruitLoads)
apples = [v for v in apple_loads if v != 0]

rawDescription: Extracting a list while testing a condition on extracted entries


code:
class Musician(models.Model):
    name = models.CharField(max_length=128)
    band = models.ForeignKey("Band")

class Band(models.Model):
    name = models.CharField(max_length=128)
    genre = models.CharField(max_length=50)

rawDescription: django: is there a black magic on extra fields on many-to-many relationships?

description: Django: is there a black magic on extra fields on many-to-many relationships


code:
import csv
with open('names.csv') as csvfile:
     reader = csv.DictReader(csvfile)
     for row in reader:
         print(row['first_name'], row['last_name'])

rawDescription: Extract information from Excel with python 2.7/ pyMel?


code:
d = {1: ['Spices', 39],
     2: ['Cannons', 43],
     3: ['Tea', 31],
     4: ['Contraband', 46],
     5: ['Fruit', 38],
     6: ['Textiles', 44],
     7: ['Odds and Ends', 100, 9999],
     8: ['Candies', 9999, 'It\'s CANDY!']}
d_max = []

# Iterate over keys of d
for k in d:
    # Length of the key
    if len(d_max) <= 0:
        d_max.append(len(str(k)) + 1)
    elif len(str(k))+ 1 > d_max[0]:
        d_max[0] = len(str(k)) + 1

    # Iterate over the length of the value
    for i in range(len(d[k])):
        # If the index isn't in d_max then this must be the longest
        # Add one to index because index 0 is the key's length
        if len(d_max) <= i+1:
            d_max.append(len(str(d[k][i])))
            continue
        # This is longer than the current one
        elif len(str(d[k][i])) + 1 > d_max[i+1]:
            d_max[i+1] = len(str(d[k][i])) + 1

for k,v in d.items():
    list_var = [k] + v

    # A list of values to unpack into the string
    vals = []
    # Add the value then the length of the space
    for i in range(len(list_var)):
        vals.append(list_var[i])
        vals.append(d_max[i])

    print(("{:<{}} " * len(list_var)).format(*vals))

rawDescription: Variable number of format arguments

description: Variable number of format arguments


code:
for word in wordList:
    posMatch = re.search(r'\b%s\b' % word, string)
    if posMatch:
        print (posMatch.group())

rawDescription: How do I check a string for certain words without getting matches for parts of the words in the string in Python?

description: Check a string for certain words without getting matches for parts of the words in the string in Python


rawDescription: Combining variables from different sources and write them in a CSV (Python)


code:
line='protein_coding other stuff exon more stuff'
"protein_coding" in line and "exon" in line

rawDescription: use regular expression in python to find two strings in line

description: Use regular expression in python to find two strings in line


code:
import datetime
due_date = 735444
due_time = 55800
datetime.datetime.fromordinal(due_date) + datetime.timedelta(seconds=due_time)

rawDescription: convert time in Python

description: Convert time in Python


code:
class Invoice(models.Model):
    ...

    def add_invoice_file(self, uploaded_file):
        self.invoice_files.add(uploaded_file) # error if the Invoice hasn't been saved yet
        for invoice_file in self.invoice_files.all():
            status = invoice_file.locked_status(1)
            if status != 1:
                raise Exception('Blah')

rawDescription: Triggering another model's data to change (M2M) based on this model


code:
while Game == True:

    # some here code

    if x < 0 or x > display_width - spacecore_width:
        break # leave while loop

 # proceed elsewhere
game_over()

rawDescription: Pygame - why my game repeats instead of closing?


rawDescription: Parsing slice information from a slice object?


code: return A == B

rawDescription: Python-New To Python and programming in general-difference of two sets


code:
d = {'Domains': {'Web': ['JavaScript', 'PHP', 'Python'], 'Desktop': ['C#', 'Java', 'Python'], 'Mobile': {'Android': 'Java', 'Windows Phone': 'C#', 'iOS': ['Swift', 'Objective-C']}}}
lookup(d, 'iOS')

rawDescription: Find deeper in dictionary or list

description: Find deeper in dictionary or list


code: random.sample(range(1, 16), 3)

rawDescription: How do you pick "x" number of unique numbers from a list in python?

description: Pick "x" number of unique numbers from a list in python


code:
import ssl

s = SMTP_SSL('smtp.gmail.com', timeout=10,
             ssl_kwargs=dict(cert_reqs=ssl.CERT_REQUIRED,
                             ssl_version=ssl.PROTOCOL_TLSv1,
                             # http://curl.haxx.se/ca/cacert.pem
                             ca_certs='cacert.pem'))
s.set_debuglevel(0)
try:
    s.login(gmail_user, gmail_pwd)
    s.sendmail(msg['From'], [to], msg.as_string())
finally:
    s.quit()

rawDescription: Send e-mail to Gmail with inline image using Python


code: return {'project': 'Register_POST'}

rawDescription: Pyramid self.request.POST is empty - no post data available


code:
fn=np.frompyfunc(setcolor,1,3)
fn(z)

rawDescription: Can Numpy's frompyfunc() return an image?


rawDescription: completely connected subgraphs from a larger graph in networkx

description: Completely connected subgraphs from a larger graph in networkx


code:
def addseven(n):
    return n + 7

a = 9
b = addseven(a)
print(b)        # should be 16

rawDescription: What does return do? Nothing is ever returned


code:
for line in open('really_big_file.dat'):
    process_data(line)

rawDescription: Lazy Method for Reading Big File in Python?


rawDescription: Plotting the difference between two datetime64[ns]


code:
eggs: 2
onions: 1
omelette: 11.0
pileofomelettes: 66.0

rawDescription: How do I replace lines in a file using data contained elsewhere in the same file?

description: Replace lines in a file using data contained elsewhere in the same file


code: df.groupby('A', group_keys=False).apply(lambda x: x.ix[x.B.idxmax()])

rawDescription: python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

description: Python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B


code:
def all_venues(request):
    # note that querying profiles...
    venues = VenueProfile.objects.all().select_related('venue')
    return render_to_response('template.html', {'venues':venues})

def venue(request, venue_id):
    venue = VenueProfile.objects.filter(venue__pk=venue_id).select_related('venue')
    if len(venue) == 1:
        venue = venue[0]
    else:
        raise Http404
    ...

rawDescription: django create profile or page for object

description: Django create profile or page for object


code:
once_more = True
while once_more:
    if not (x < 30):
        once_more = False
    # original loop body here

rawDescription: how to make a while statement run one more time in python 3

description: Make a while statement run one more time in python 3


code:
s = "#abc is a pattern which should match. also abc should match. And finally @ef"
re.findall(r'[@#]?\b(?:abc|ef|ghij)\b', s)

rawDescription: Python regex not matching at word boundary as required


code:
from itertools import groupby
from operator import itemgetter
import csv

with open('f1.csv', newline='') as f_in, open('f2.csv', 'w', newline='') as f_out:
    reader = csv.reader(f_in)
    writer = csv.writer(f_out)
    for i, (key, group) in enumerate(groupby(reader, key=itemgetter(1)), start=1):
        for row in group:
            writer.writerow(row + [i])

rawDescription: Filling a row in a csv file according

description: Filling a row in a csv file according


code:
from itertools import combinations_with_replacement
from pprint import pprint

f = lambda target_sum, length: [sequence for sequence in combinations_with_replacement(range(1, target_sum+1), length) if sum(sequence) == target_sum]

def f2(target_sum, min_length, max_length):
    sequences = {}
    for length in range(min_length, max_length + 1):
        sequence = f(target_sum, length)
        if len(sequence):
            sequences[length] = sequence
    return sequences

if __name__ == "__main__":
    print("f(10,2):")
    print(f(10,2))
    print()
    print("f(10,1,3)")
    pprint(f2(10,1,3))

rawDescription: Return a sequence of a variable length whose summation is equal to a given integer


code:
def neighbor_min(a, c):
    ac = np.concatenate((a[None], c[None]))
    rows, cols = ac.shape[1:]
    ret = np.empty_like(ac)

    # Fill in the center
    win_ac = as_strided(ac, shape=(2, rows-2, cols, 3),
                        strides=ac.strides+ac.strides[1:2])
    win_ac = win_ac[np.ogrid[:2, :rows-2, :cols] +
                    [np.argmin(win_ac[0], axis=2)]]
    win_ac = as_strided(win_ac, shape=(2, rows-2, cols-2, 3),
                        strides=win_ac.strides+win_ac.strides[2:3])
    ret[:, 1:-1, 1:-1] =  win_ac[np.ogrid[:2, :rows-2, :cols-2] +
                                 [np.argmin(win_ac[0], axis=2)]]

    # Fill the top, bottom, left and right borders
    win_ac = as_strided(ac[:, :2, :], shape=(2, 2, cols-2, 3),
                        strides=ac.strides+ac.strides[2:3])
    win_ac = win_ac[np.ogrid[:2, :2, :cols-2] +
                    [np.argmin(win_ac[0], axis=2)]]
    ret[:, 0, 1:-1] = win_ac[:, np.argmin(win_ac[0], axis=0),
                             np.ogrid[:cols-2]]
    win_ac = as_strided(ac[:, -2:, :], shape=(2, 2, cols-2, 3),
                        strides=ac.strides+ac.strides[2:3])
    win_ac = win_ac[np.ogrid[:2, :2, :cols-2] +
                    [np.argmin(win_ac[0], axis=2)]]
    ret[:, -1, 1:-1] = win_ac[:, np.argmin(win_ac[0], axis=0),
                             np.ogrid[:cols-2]]
    win_ac = as_strided(ac[:, :, :2], shape=(2, rows-2, 2, 3),
                        strides=ac.strides+ac.strides[1:2])
    win_ac = win_ac[np.ogrid[:2, :rows-2, :2] +
                    [np.argmin(win_ac[0], axis=2)]]
    ret[:, 1:-1, 0] = win_ac[:, np.ogrid[:rows-2],
                             np.argmin(win_ac[0], axis=1)]
    win_ac = as_strided(ac[:, :, -2:], shape=(2, rows-2, 2, 3),
                        strides=ac.strides+ac.strides[1:2])
    win_ac = win_ac[np.ogrid[:2, :rows-2, :2] +
                    [np.argmin(win_ac[0], axis=2)]]
    ret[:, 1:-1, -1] = win_ac[:, np.ogrid[:rows-2],
                             np.argmin(win_ac[0], axis=1)]
    # Fill the corners
    win_ac = ac[:, :2, :2]
    win_ac = win_ac[:, np.ogrid[:2],
                    np.argmin(win_ac[0], axis=-1)]
    ret[:, 0, 0] = win_ac[:, np.argmin(win_ac[0], axis=-1)]
    win_ac = ac[:, :2, -2:]
    win_ac = win_ac[:, np.ogrid[:2],
                    np.argmin(win_ac[0], axis=-1)]
    ret[:, 0, -1] = win_ac[:, np.argmin(win_ac[0], axis=-1)]
    win_ac = ac[:, -2:, -2:]
    win_ac = win_ac[:, np.ogrid[:2],
                    np.argmin(win_ac[0], axis=-1)]
    ret[:, -1, -1] = win_ac[:, np.argmin(win_ac[0], axis=-1)]
    win_ac = ac[:, -2:, :2]
    win_ac = win_ac[:, np.ogrid[:2],
                    np.argmin(win_ac[0], axis=-1)]
    ret[:, -1, 0] = win_ac[:, np.argmin(win_ac[0], axis=-1)]

    return ret

rawDescription: Numpy: fast calculations considering items' neighbors and their position inside the array


code:
from itertools import zip_longest
def hammingdist(w1,w2): return sum(1 if c1!=c2 else 0 for c1,c2 in zip_longest(w1,w2))
def graph1(words): return {word: [n for n in words if hammingdist(word,n) == 1] for word in words}

rawDescription: Efficiently build a graph of words with given Hamming distance


code: from utils_debug import pv

rawDescription: Printing Variable names and contents as debugging tool; looking for emacs/Python shortcut


code: ['inAngle', 'anotherInAngle']

rawDescription: Python RegEx for exact matches of brackets


code:
class Filter(object):
    def __init__(self, id=None):
        self.id = id

    def __call__(self, func):
        def wrapper(*args, **kwargs):
            id = kwargs.get("id", self.id)
            entity_ids = func(*args)
            result = {}
            for k, v in entity_ids.items():
                if id:
                    if '_' + str(id) in k:
                        result.update({k: v})
            return result
        return wrapper

rawDescription: Pass arguments to decorators when calling decorated function


rawDescription: Python: How can I parse { apple: "1" , orange: "2" } into Dictionary?


code:
import os.path
testSetting = r"C:\Users\bgb\Documents\Brent\Code\Variable\Visual Studio\Local.testsettings"
os.path.basename(testSetting)

rawDescription: Simple string encounter

description: Simple string encounter


code: self.val2 = kwargs.get('val2',"default value")

rawDescription: Proper way to use **kwargs in Python

description: Proper way to use **kwargs in Python


code: matrix[l1:l2,c1:c2].A #or .toarray()

rawDescription: What is the fastest way to slice a scipy.sparse matrix?


rawDescription: How to use the variable from the python in rpy2?

description: Use the variable from the python in rpy2


code:
self.struct1 = self.struct1()
self.struct1 = self.struct2()   # Here you was redefining self.struct1

rawDescription: How to handle data in python similar to IDL structures?

description: Handle data in python similar to IDL structures


rawDescription: Load a list of lists from a file based on a grouping variable?


code:
sizes = df1["b"].value_counts()
sizes

rawDescription: Reassigning strings by value count in Pandas


code: [map(sum, zip(v, y)) for y in product(o, repeat=len(v))]

rawDescription: combinations of the values of two lists

description: Combinations of the values of two lists


code:
e, inds = np.unique(c[:,0], return_index=True)
np.split(c, inds)[1:]

rawDescription: In Python / numpy, how do I unravel / split an array according to its first column, which is an index?


rawDescription: How to append from file into list in Python?

description: Append from file into list in Python


code: 'random text ... C:\somedir\logs\test.log more \nrandom \ntext C:\somedir\test.xls...'

rawDescription: Python Regular Expression Question

description: Python Regular Expression Question


code:
class Person(object):
    def __init__(self,firstname,lastname):
        self.firstname=firstname
        self.lastname=lastname

rawDescription: How can I create a user defined data structure in python

description: Create a user defined data structure in python


code: myproc

rawDescription: Suddenly, I can not run python code

description: Suddenly, I can not run python code


code: obj = cast(id(d), POINTER(PyDictObject)).contents

rawDescription: python 3.3 dict: how to convert struct PyDictKeysObject to python class?

description: Python 3.3 dict: how to convert struct PyDictKeysObject to python class


rawDescription: Making Python display .txt files from directories


code: sites = {name:url for url, name in f()}

rawDescription: Python string comparisons?

description: Python string comparisons


code:
text = 'The first line leads off, With a gap before the next. Then the poem ends.'
chars = ',.!'
splitOnChars(text, chars)

rawDescription: split on char, but leave that char - python

description: Split on char, but leave that char - python


rawDescription: Python Scapy --arp request and response

description: Python Scapy --arp request and response


rawDescription: Weird Data manipulation in Pandas

description: Weird Data manipulation in Pandas


code: uni = ' '.join(rep.split()[:-1])

rawDescription: how to get string values using index method in Python

description: Get string values using index method in Python


code:
finalResult = rdd1.mapValues(lambda v: v[0]/v[1]).collect()
print(finalResult)

rawDescription: Calculating the averages for each KEY in a Pairwise (K,V) RDD in Spark with Python


rawDescription: Elasticsearch - match_phrase query sort by int


code:
import re
text = u"Hello this is a string.\uf8ff-2.34 This is an example1 string."
print(re.split(u'\uf8ff(-*\d+\.*\d+)', text))

rawDescription: Trying to split strings into multiple parts with Python


code:
from keyword import iskeyword
iskeyword('X')
iskeyword('while')

rawDescription: Pythoncially check if a variable name is valid


code:
import glob
your_list = glob.glob('*.xyz')

rawDescription: List *.xyz files from a directory

description: List *.xyz files from a directory


code:
Decorator
def locked_method(method):
    """Method decorator. Requires a lock object at self._lock"""
    def newmethod(self, *args, **kwargs):
        with self._lock:
            return method(self, *args, **kwargs)
    return newmethod

class DecoratorLockedSet(set):
    def __init__(self, *args, **kwargs):
        self._lock = Lock()
        super(DecoratorLockedSet, self).__init__(*args, **kwargs)

    @locked_method
    def add(self, *args, **kwargs):
        return super(DecoratorLockedSet, self).add(elem)

    @locked_method
    def remove(self, *args, **kwargs):
        return super(DecoratorLockedSet, self).remove(elem)

rawDescription: How to make built-in containers (sets, dicts, lists) thread safe?

description: Make built-in containers (sets, dicts, lists) thread safe


code:
a
b
c
d
e
f

rawDescription: Python script loop to assign timeslot to each line in input file


code:
from collections import defaultdict

max_count_by_day = defaultdict(int)
for dt, user_ids in users_by_time.iteritems():
    d = dt.date()
    max_count_by_day[d] = max(max_count_by_day[d], len(user_ids))

rawDescription: Group dictionary by key and find max value


code:
dbf = Dbf5('fake_file_name.dbf')
df = dbf.to_dataframe()

rawDescription: Way to convert dbf to csv in python?

description: Way to convert dbf to csv in python


code:
import sys
import codecs

sys.stdout = codecs.getwriter('utf-8')(sys.stdout)
inData = codecs.getreader('utf-8')(sys.stdin)

(last_key, tot_cnt, v_id) = (None, 0, None)

for line in inData:
    (key, val) = line.strip().split("\t")
    if last_key != key:
        if last_key != None:
            k = last_key.split('|')
            v_id = k[0]

            if v_id == 'a':
                if tot_cnt > 1:
                    sys.stdout.write("%s\t%s\n" % (last_key,tot_cnt))
            else:
                sys.stdout.write("%s\t%s\n" % (last_key,tot_cnt))

        (last_key, tot_cnt) = (key, int(val))
    else:
        (last_key, tot_cnt) = (key, tot_cnt + int(val))

if last_key:
    if v_id == 'a':
        if tot_cnt > 1:
            sys.stdout.write("%s\t%s\n" % (last_key, tot_cnt))
    else:
        sys.stdout.write("%s\t%s\n" % (last_key, tot_cnt))

rawDescription: How to get the Reducer to emit according to key type

description: Get the Reducer to emit according to key type


code:
df = pd.read_table('data', sep='\s{4,}')
df.index = ['a','b','c','d','e','a']
df
to_del = df[df['Type'].isin(['UnweightedBase', 'Base'])].index.tolist()
to_del
df = df.drop(to_del)
df

rawDescription: Delete multiple Pandas DataFrame row where column value is this or that


rawDescription: How to inline ManyToMany fields in JSON with Tastypie?

description: Inline ManyToMany fields in JSON with Tastypie


code:
import example
spam = example.Spam(5)
spams = example.SpamVector()
spams.append(spam)
assert(spams[0].val == 5)
spam.val = 21
assert(spams[0].val == 21)
example.modify_spams(spams)
assert(spam.val == 42)
spams.append(spam)
spam.val = 100
assert(spams[1].val == 100)
assert(spams[0].val == 42) # The container does not provide indirection.

rawDescription: Wrapping an std::vector using boost::python vector_indexing_suite


code:
plt.plot(data1)
plt.show()
plt.subplot(1,2,1)
plt.plot(data2)
plt.subplot(1,2,2)
plt.plot(data3)
plt.show()

rawDescription: Python & Matplotlib: Plot multiple figure in the same line


code: {(i, j): 'G{}{}'.format(i, j) for i, j in product(range(l), repeat=2)}

rawDescription: Best pythonic way of mapping a specific function with multiple arguments


code:
from bs4 import BeautifulSoup
import urllib

urlData = urllib.urlopen('https://twitter.com/USABillOfRights/status/468852515409502210/photo/1')
data = str(urlData.readlines())
bs = BeautifulSoup(data)
imgUrl = bs.find('img', attrs={'alt': 'Embedded image permalink'}).get('src')
urllib.urlretrieve(imgUrl, "cnn.jpg")

rawDescription: Getting actual facebook and twitter image urls using python


code:
def permutations(iterable, r=None):
    # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
    # permutations(range(3)) --> 012 021 102 120 201 210
    pool = tuple(iterable)
    n = len(pool)
    r = n if r is None else r
    if r > n:
        return
    indices = range(n)
    cycles = range(n, n-r, -1)
    yield tuple(pool[i] for i in indices[:r])
    while n:
        for i in reversed(range(r)):
            cycles[i] -= 1
            if cycles[i] == 0:
                indices[i:] = indices[i+1:] + indices[i:i+1]
                cycles[i] = n - i
            else:
                j = cycles[i]
                indices[i], indices[-j] = indices[-j], indices[i]
                yield tuple(pool[i] for i in indices[:r])
                break
        else:
            return

rawDescription: How to generate all permutations of a list in Python

description: Generate all permutations of a list in Python


code:
leg
knee
thigh
shin
ankle
hip
foot
toe
calf
feet
patella
tibia
fibula

rawDescription: Similarities between two csv files

description: Similarities between two csv files


code:
from openerp.osv import fields, osv
class res_partner_users_vip_rel2(osv.osv):
    _inherit = 'res.partner'
    _description = "VIP status for partner (users)"
    def getcount(self, cr, uid,ids,name,arg,context):
        res={}
        sql="""
            SELECT partner_id id, count(*) cnt FROM res_partner_users_vip_rel2
            WHERE partner_id = """+str(ids[0])+""" GROUP BY partner_id """
        cr.execute(sql)
        res.update(dict(cr.fetchall()))
        if res!={}:
            return res
        return {ids[0]:0}
    _columns = {
        'ids_count':fields.function(getcount,type="integer",string='Count'),

        'vip_ids': fields.many2many(
            'res.users',
            'res_partner_users_vip_rel2',
            'partner_id',
            'users_id',
            'VIP status'),
         }

rawDescription: OpenERP: How to hide some fields in Form View if no record found in many2many relationship?


code:
import codecs
string = '\\n    this is a docstring for\\n    the main function.\\n    a,\\n    b,\\n    c\\n    '
codecs.decode(string, 'unicode_escape')
print(codecs.decode(string, 'unicode_escape'))
codecs.decode('\\t\\n\\r\\xa0\\040', 'unicode_escape')

rawDescription: How to convert a python string

description: Convert a python string


code:
with open('yourfile.txt') as f:
  result = ','.join(f)

rawDescription: How to add a comma to the end of a list efficiently?

description: Add a comma to the end of a list efficiently


code: [dict(zip(('x', 'y'), col)) for col in zip(d['x'], d['y'])]

rawDescription: Transposing (pivoting) a dict of lists in python


code:
from functools import partial
map(partial(filter, None), zip(*re.findall(pattern, s, re.VERBOSE)))

rawDescription: RegExp to split string according to different criteria in python


code:
def getsortfunction(values,indices):
    sorts = [sorted(list(set(x[indices[i][0]] for x in values)),reverse=indices[i][1]) for i in range(len(indices))]
    def sortfunction(y):
        return tuple(sorts[i].index(y[indices[i][0]]) for i in range(len(indices)))
    return sortfunction

rawDescription: Sort at various levels in Python

description: Sort at various levels in Python


rawDescription: Pandas : determine mapping from unique rows to original dataframe


code:
g.get_group(0)
g.sum()

rawDescription: Perform function on pairs of rows in Pandas dataframe


rawDescription: importing a JPEG image into an IPython (notebook) program

description: Importing a JPEG image into an IPython (notebook) program


code:
li = LoadImage(root)
filemenu.add_command(label = "Abrir", command = li.abrir)

rawDescription: Problems with zoom and menu (Tkinter)

description: Problems with zoom and menu (Tkinter)


code:
from io import FileIO, BufferedReader
import io
import os

class TestReader(BufferedReader):
    pass

def test(streams):
    for stream in streams:
        b = TestReader(stream)

def test_reset(streams):
    """Will try to leave stream state unchanged"""
    for stream in streams:
        pos = stream.tell()
        b = TestReader(stream)
        do_something(b)
        b.detach()
        stream.seek(pos)

filenames = ['test1.txt', 'test2.txt']

# option 1: just make new streams

streams = [FileIO(name, 'r') for name in filenames]
test(streams)
streams = [io.open(name, 'rb') for name in filenames]
#etc

# option 2: use file descriptors
fds = [os.open(name, os.O_RDONLY) for name in filenames]
#closefd = False means "do not close fd on __del__ or __exit__"
#this is only an option when you pass a fd instead of a file name
streams = [FileIO(fd, 'r', closefd=False) for fd in fds]
test(streams)
streams = []
for fd in fds:
    os.lseek(fd, 0, os.SEEK_SET)
    streams.append(io.open(fd, 'rb', closefd=False))
    # you can also .seek(0) on the BufferedReader objects
    # instead of os.lseek on the fds

# option 3: detach

streams = [FileIO(name, 'r') for name in filenames]
test_reset(streams)
# streams[*] should still be in the same state as when you passed it in

rawDescription: prevent BufferedReader from closing the file for a list of files

description: Prevent BufferedReader from closing the file for a list of files


code:
def getvalues(params):
    getter = itemgetter(*params)
    def deco(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if len(args) == 1 and not kwargs and isinstance(args[0], Mapping):
                return func(*getter(args[0]))
            else:
                return func(*args, **kwargs)
        return wrapper
    return deco

rawDescription: Python decorator to find key exist, and pass it as argument


code: df.sort('col_a', inplace=True)

rawDescription: Enumerate each row for each group in a DataFrame


rawDescription: How to use the value of a global variable to determine the control flow of a function running in separate thread?

description: Use the value of a global variable to determine the control flow of a function running in separate thread


code:
import numpy as np
import cv2

samples = np.array(np.random.random((4,2)), dtype = np.float32)
y_train = np.array([1.,0.,0.,1.], dtype = np.float32)

clf = SVM()
clf.train(samples, y_train)
y_val = clf.predict(samples)

rawDescription: Python OpenCV SVM implementation

description: Python OpenCV SVM implementation


code:
from concurrent.futures import *
from subprocess import *
executor = ThreadPoolExecutor(4)
future = executor.submit(Popen(['echo', 'test'], stdout=PIPE))
future.exception()

rawDescription: concurrent.futures ThreadPoolExecutor fails to wait?

description: Concurrent.futures ThreadPoolExecutor fails to wait


code: all( abs(x) == abs(y) for x,y in zip(a,a_rev) )

rawDescription: Sort list of lists by unique reversed absolute condition


rawDescription: Django Many to Many circular reference?

description: Django Many to Many circular reference


code:
from foo.models import Foo
f = Foo.objects.get(pk=1)
f._meta.get_all_field_names()

rawDescription: In model save() how to get all field starting with 'foo'


code:
with open('/tmp/stream', 'rb') as f:
    dis = DataInputStream(f)
    val = dis.read_int()
    string = dis.read_utf()

rawDescription: Python equivalent of Java DataInputStream.readUTF()


rawDescription: Implementation of functions with very basic scripting


code:
inds = [row['index'] for row in joined]

rect(inds,    # x-coordinate for each rectangle
     inds,    # y-coordinate for each rectangle
     0.9, 0.9, # use 0.9 for both width and height of each rectangle
     color = some_colors, # color for each rect
)

rawDescription: Plot topics with bokeh or matplotlib

description: Plot topics with bokeh or matplotlib


code:
from collections import defaultdict, Counter
sales_per_store_per_day = [
   {'date':'2014-06-01', 'store':'a', 'product1':10, 'product2':3, 'product3':15},
   {'date':'2014-06-01', 'store':'b', 'product1':20, 'product2':4, 'product3':16},
   {'date':'2014-06-02', 'store':'a', 'product1':30, 'product2':5, 'product3':17},
   {'date':'2014-06-02', 'store':'b', 'product1':40, 'product2':6, 'product3':18},
]
by_store = defaultdict(Counter)
for info in sales_per_store_per_day:
    counts = Counter({k: v for k, v in info.items() if k not in ('store', 'date')})
    by_store[info['store']] += counts

[dict(v, store=k) for k, v in by_store.items()]

rawDescription: How to reduce/aggregate a list of dicts per multiple keys in Python?

description: Reduce/aggregate a list of dicts per multiple keys in Python


code: test_array = np.random.randint(100, size=10**6)

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:
a = 'hello^goo^dbye:cat@dog'

splits(a,['^',':','@'])
Out[7]: ['hello', 'goo^dbye', 'cat', 'dog']

rawDescription: Is it possible to split a string on multiple delimiters in order?


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.tctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
        self.tctrl_2 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)

        self.menubar = wx.MenuBar()
        self.test = wx.Menu()
        self.copy = wx.MenuItem(self.test, wx.NewId(), "copy", "is_going to copy", wx.ITEM_NORMAL)
        self.test.AppendItem(self.copy)
        self.paste = wx.MenuItem(self.test, wx.NewId(), "paste", "will paste", wx.ITEM_NORMAL)
        self.test.AppendItem(self.paste)
        self.menubar.Append(self.test, "Test")
        self.SetMenuBar(self.menubar)

        self.__set_properties()
        self.__do_layout()

        self.Bind(wx.EVT_MENU, self.on_copy, self.copy)
        self.Bind(wx.EVT_MENU, self.on_paste, self.paste)

    def __set_properties(self):
        self.SetTitle("frame_1")

    def __do_layout(self):
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_2.Add(self.tctrl_1, 1, wx.EXPAND, 0)
        sizer_2.Add(self.tctrl_2, 1, wx.EXPAND, 0)
        sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        self.Layout()

    def on_copy(self, event):
        widget = self.FindFocus()
        self.copied = widget.GetStringSelection()

    def on_paste(self, event):
        widget = self.FindFocus()
        widget.WriteText(self.copied)

if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    frame = MyFrame(None, -1, "")
    frame.Show()
    app.MainLoop()

rawDescription: wxpython cut copy and paste throughout the application

description: Wxpython cut copy and paste throughout the application


code:
timeit.timeit("list(product(option1, option2, option3))", "from __main__ import option1, option2, option3, product")
timeit.timeit("[(x, y, z) for x in option1 for y in option2 for z in option3]", "from __main__ import option1, option2, option3, product")

rawDescription: all possible combinations from a configuration space model

description: All possible combinations from a configuration space model


code:
import matplotlib.pyplot as plt
from pandas import DataFrame

df = DataFrame({'Parameter': ['A',]*8,
                'Site': ['S1', 'S2', 'S1', 'S2', 'S1', 'S2', 'S1', 'S2'],
                'Value':  [2.34, 2.67, 2.56, 2.89, 3.45, 4.45, 3.67, 4.56]})

df.boxplot(by=['Parameter', 'Site'])
plt.show()

rawDescription: Python Matplotlib Box plot

description: Python Matplotlib Box plot


rawDescription: python pandas filter dataframe by another series, multiple columns

description: Python pandas filter dataframe by another series, multiple columns


code:
client = Client(settings.WSDL_ADDRESS, retxml=True)
raw_reply = client.service.PersonSearch(soapified_search_object)

rawDescription: How to get unparsed XML from a suds response, and best django model field to use for storage

description: Get unparsed XML from a suds response, and best django model field to use for storage


rawDescription: how to do a hexadecimal increment?

description: Do a hexadecimal increment