code:
destroyedStatusIDs = Status.objects.filter(description="destroyed").values_list("id", flat=True)
clients_destroyed_items = StorageItem.objects.filter(client=client,
    itemstatushistory__status__in=destroyedStatusIDs)

rawDescription: Query for items using filter for most recent entry in a related table


code: id = id.strip()

rawDescription: How to remove line breaks and white space from variable in jQuery

description: Remove line breaks and white space from variable in jQuery


code:
from datetime import datetime, timedelta
datetime(1601, 1, 1, 0, 0, 0) + timedelta(seconds = 129893678626216000/1e7)

rawDescription: Python date format?

description: Python date format


code:
class MyMeta(type):
  def __dir__(self):
    return ['a', 'b', 'c']

class A(object, metaclass=MyMeta):
  # __metaclass__ = MyMeta   # in python 2

  def __dir__(self):
    return ['a', 'b', 'c', 'd']

print(dir(A()), dir(A))

rawDescription: How to find hidden attributes of Python objects? (attributes that don't appear in the dir(obj) list)

description: Find hidden attributes of Python objects? (attributes that don't appear in the dir(obj) list)


code:
def wrap_socket(sock, keyfile=None, certfile=None,
                server_side=False, cert_reqs=CERT_NONE,
                ssl_version=PROTOCOL_SSLv23, ca_certs=None,
                do_handshake_on_connect=True):

    return SSLSocket(sock, keyfile=keyfile, certfile=certfile,
                   server_side=server_side, cert_reqs=cert_reqs,
                   ssl_version=ssl_version, ca_certs=ca_certs,
                   do_handshake_on_connect=do_handshake_on_connect)

rawDescription: How to open ssl socket using certificate stored in string variables in python

description: Open ssl socket using certificate stored in string variables in python


code:
import json

test_list = [{'Key' : 'key1', 'List' : [1,2,3]},
        {'Key' : 'key2', 'List' : [4,5,6]}]

with open('/tmp/test_list.json', 'w') as f:
    json.dump(test_list, f)

rawDescription: Import dictionary containings lists from csv


code:
df = pd.DataFrame({"binary": [0,1,1,1,0,0,1,1,0]})
df["consec"] = df["binary"].groupby((df["binary"] == 0).cumsum()).cumcount()
df

rawDescription: python pandas - creating a column which keeps a running count of consecutive values

description: Python pandas - creating a column which keeps a running count of consecutive values


code:
from django.db.models import Sum
most_purchasing_user = User.objects.annotate(purchase_sum=Sum('purchase_set__price')).order_by('-purchase_sum')[0]

rawDescription: Find what customer has spent the most money across multiple payments


code:
def speedup():
    global delay
    delay = int(delay/2)

rawDescription: How to make a text button which speeds up text animation

description: Make a text button which speeds up text animation


code: a = [(i, len(i)) for i in items]

rawDescription: How can I get list of pairs words with their length in Python?

description: Get list of pairs words with their length in Python


code:
s = set()
for tup in lst:
    for el in tup:
        s.add(el)
# or use a set comprehension:
# # s = {el for tup in lst for el in tup}

rawDescription: How to flatten a list of tuples and remove the duplicates?

description: Flatten a list of tuples and remove the duplicates


rawDescription: hosted IronPython: possible to get currently executed source line?

description: Hosted IronPython: possible to get currently executed source line


rawDescription: Sort a list of lists with two index

description: Sort a list of lists with two index


code:
cooccurrence = pd.crosstab(index=[edges['first']], columns=[edges['second']])
items = df['item'].unique()
cooccurrence = cooccurrence.reindex(index=items, columns=items)
cooccurrence = cooccurrence.add(cooccurrence.T, fill_value=0)
cooccurrence = cooccurrence.fillna(0)
diagvals = cooccurrence.sum(axis=0)
arr = cooccurrence.values
i = np.arange(len(diagvals))
arr[i,i] = diagvals
cooccurrence = pd.DataFrame(arr, columns=cooccurrence.columns,
                            index=cooccurrence.index)
print(cooccurrence)

rawDescription: Pandas combine rows that share an association


code:
class MyView(DatatableView):
    model = Post
    datatable_options = {
        'columns': [
            'title',
            'body',
            'created',
            ]
    }

rawDescription: How do you use django-datatable-view

description: Use django-datatable-view


code:
class Investor(object):
    reports = []
    data = []

    def __init__(self, LastName, FirstName, Date, Gender, Title, Rid=1):
        # the following two lines define variables which only exist inside
        # __init__, so they can basically be gotten rid of.
        # reports = []
        # data = []
        # but they *don't need to be initialized*. Actually creating a new list
        # in each constructor is *bad* unless you want one report per instance

        # ... later, be sure to add "self" instead of adding to the local vars
        self.add(self)

    @classmethod
    def report(self, o):
        result = ""
        for x in self.reports:
            # Just use join, that's what you mean anyway.
            result = ', '.join(x)
            # \n should result in \n\n. I think you mean o.write(result)
            o.write(result + "\n")

    @classmethod
    def load(self, f):
        self.reports = []
        self.data = []
        file = open(f)
        # why the extra readline?
        file.readline()
        list = []
        while 1:
            line = file.readline()
            # you need to get rid of the trailing whitespace
            items = line[:-1].split(", ")
            if not line:
                break
            else:
                # self, here, refers to the class, so you can use it as the
                # constructor as well
                # use the * to make a list into an argument list.
                self(*items)
                # No need to add it, the value is added at the end of __init__
                # as things stand.

class Agent(Investor):
    reports = []
    data = []

    def __init__(self, Commission, LastName, FirstName, \
                       Date, Gender, Title, Rid=1):
        super(Agent, self).__init__(self, LastName, FirstName, Date, \
                                          Gender, Title, Rid)
        self.commission = Commission

    def __str__(self):
        # Be lazy! Use super!
        return super(Agent,self).__str__() + ', ' + self.commission

    # this was doing the same thing in the parent class.
    # def __repr__(self):

    # The classmethod methods are not needed unless you want to redefine
    # behavior in a child class.
    @classmethod
    def add(self, i):
        # If you do change something, though, make sure to use super
        # here as well...
        super(Agent, self).add(i)

rawDescription: Python inheritance woes

description: Python inheritance woes


code:
@login_required
def submission_set_rank(request):
    keys = {'rank1': 5, 'rank2': 4, 'rank3': 3, 'rank4': 2, 'rank5': 1}
    ranks = [request.GET.get(key,'') for key in keys]
    for ballot in BallotStats.objects.filter(object_id__in=ranks):
        ballot.score += keys[ballot.object_id]
        ballot.save()

    return HttpResponseRedirect('/submissions/results/film/')

rawDescription: How can I write this with less redundancy/copy-paste?

description: Write this with less redundancy/copy-paste


code:
def setUp(self):
    patcher = patch("__main__.Serial", autospec=True)
    self.mock = patcher.start()
    self.addCleanup(patcher.stop)
    self.mc = MyClass()
    self.mock.reset_mock()

rawDescription: Python Unit testing with mock and patch a foreign modul


code:
with open(path) as fh:
    self.write(fh.read())

rawDescription: Tailon (python web app with tail -f functionality): download full log


rawDescription: Read sparse matrix in python

description: Read sparse matrix in python


code:
def chunk_string(s, n):
    chunks = []
    last_index = len(s) - n
    for i in range(0, last_index + 1):
        chunks.append(s[i:i+n])
    return chunks

rawDescription: Counting multiple letter groups in a string (python)


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

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


code:
from itertools import combinations

def changetwo(s):
    for i,j in combinations(range(len(s)), 2):
        res = list(s)
        res[i], res[j] = res[j], res[i]
        yield ''.join(res)

rawDescription: Python String Permutations Up To 2 Letter Changes Per Permutation


rawDescription: How to Create a Printing Method in Python

description: Create a Printing Method in Python


code:
PositiveInteger("FFF", 16)
PositiveInteger(5)
PositiveInteger(-5)

rawDescription: Value never below zero

description: Value never below zero


code:
df['row'] = range(len(df))
starts = df[['start_date', 'val', 'row']].rename(columns={'start_date': 'date'})
ends = df[['end_date', 'val', 'row']].rename(columns={'end_date':'date'})
df_decomp = pd.concat([starts, ends])
df_decomp = df_decomp.set_index('row', append=True)
df_decomp.sort_index()

rawDescription: Pandas: decompress date range to individual dates


code:
def loop_sequence(seq):
    while True:
        for elem in seq:
            yield elem

rawDescription: Why does Python's itertools.cycle need to create a copy of the iterable?


code:
from decorator import decorator

def convertparameters(*types):
    @decorator
    def wrapper(func, self, *args, **kwargs):
        pass  # return a result
    return wrapper

rawDescription: Pythonic way of converting parameters to the same standard within all methods of a class


code: Word(nums)

rawDescription: python pyparsing word excludeChars

description: Python pyparsing word excludeChars


code:
for i in range(1,10):
    parser.add_option('-l', '--location', value=str(i))

rawDescription: python 2.7 loop's index in quotation marks

description: Python 2.7 loop's index in quotation marks


code:
from functools import wraps
import inspect

def initializer(fun):
    names, varargs, keywords, defaults = inspect.getargspec(fun)
    @wraps(fun)
    def wrapper(self, *args):
        for name, arg in zip(names[1:], args):
            setattr(self, name, arg)
        fun(self, *args)
    return wrapper

class process:
    @initializer
    def __init__(self, PID, PPID, cmd, FDs, reachable, user):
        pass

rawDescription: Python: Automatically initialize instance variables?


code:
main_object_set = set(main_object_list)

objs_in_main_list = set().update(
                           *(o.get_this_object_list() for o in main_object_list))
objs_in_main_list.intersection_update(main_object_set)

rawDescription: how to quickly check if an object is in a list in python

description: Quickly check if an object is in a list in python


code: write.table(data, file = 'test.csv')

rawDescription: Pass R object to Python after running R Script


code:
def recVowelCount(s):
    if not s:
        return 0
    return (1 if s[0] in 'aeiouAEIOU' else 0) + recVowelCount(s[1:])

rawDescription: Counting vowels in a string using recursion


code:
class city(object):
    def __init__(self, city_name, link) :
        self.name = city_name
        self.url = link
        self.high0 = 0
        self.high1 = 0
        self.high2 = 0
        self.high3 = 0
        self.high4 = 0
        self.high5 = 0
        self.high6 = 0
        self.high7 = 0
        self.low1 = 0
        self.low2 = 0
        self.low3 = 0
        self.low4 = 0
        self.low5 = 0
        self.low6 = 0
        self.low7 = 0

    def retrieveTemps(self) :
        filehandle = urllib.urlopen(self.url)

        # get lines from result into array
        lines = filehandle.readlines()
        filehandle.close()

        # (for each) loop through each line in lines
        for line_number, line in enumerate(lines, start=1):
            # find string, position otherwise position is -1
            position0 = line.rfind('title="{}"'.format(date.strftime("%A")))
            position1 = line.rfind('title="{}"'.format(date1.strftime("%A")))
            position2 = line.rfind('title="{}"'.format(date2.strftime("%A")))
            position3 = line.rfind('title="{}"'.format(date3.strftime("%A")))
            position4 = line.rfind('title="{}"'.format(date4.strftime("%A")))
            position5 = line.rfind('title="{}"'.format(date5.strftime("%A")))
            position6 = line.rfind('title="{}"'.format(date6.strftime("%A")))

            if position0 > 0 :
                self.high0 = lines[line_number + 4].split('&')[0].split('>')[-1]
                self.low1 = lines[line_number + 18].split('&')[0].split('>')[-1]

            if position1 > 0 :
                self.high1 = lines[line_number + 4].split('&')[0].split('>')[-1]
                self.low2 = lines[line_number + 19].split('&')[0].split('>')[-1]

            if position2 > 0 :
                self.high2 = lines[line_number + 4].split('&')[0].split('>')[-1]
                self.low3 = lines[line_number + 19].split('&')[0].split('>')[-1]

            if position3 > 0 :
                self.high3 = lines[line_number + 4].split('&')[0].split('>')[-1]
                self.low4 = lines[line_number + 19].split('&')[0].split('>')[-1]

            if position4 > 0 :
                self.high4 = lines[line_number + 4].split('&')[0].split('>')[-1]
                self.low5 = lines[line_number + 19].split('&')[0].split('>')[-1]

            if position5 > 0 :
                self.high5 = lines[line_number + 4].split('&')[0].split('>')[-1]
                self.low6 = lines[line_number + 19].split('&')[0].split('>')[-1]
                self.low7 = lines[line_number + 19].split('&')[0].split('>')[-1]

            if position6 > 0 :
                self.high6 = lines[line_number + 4].split('&')[0].split('>')[-1]
                self.high7 = lines[line_number + 4].split('&')[0].split('>')[-1]
                break # done with loop, break out of it

    def getCities():
        return [
            #BRITISH COLUMBIA CITIES
            city('Prince George', 'http://www.weatheroffice.gc.ca/city/pages/bc-79_metric_e.html'),
            city('Kamloops', 'http://www.weatheroffice.gc.ca/city/pages/bc-45_metric_e.html'),
            city('Blue River', 'http://www.weatheroffice.gc.ca/city/pages/bc-22_metric_e.html'),

            # Alberta
            city('High Level', 'http://www.weatheroffice.gc.ca/city/pages/ab-24_metric_e.html'),
            city('Peace River', 'http://www.weatheroffice.gc.ca/city/pages/ab-25_metric_e.html'),
            city('Jasper', 'http://www.weatheroffice.gc.ca/city/pages/ab-70_metric_e.html'),
            city('Edmonton', 'http://www.weatheroffice.gc.ca/city/pages/ab-50_metric_e.html'),
            city('Calgary', 'http://www.weatheroffice.gc.ca/city/pages/ab-52_metric_e.html'),

            #SASKATCHEWAN CITIES

            city('Biggar', 'http://www.weatheroffice.gc.ca/city/pages/sk-2_metric_e.html'),
            city('Saskatoon', 'http://www.weatheroffice.gc.ca/city/pages/sk-40_metric_e.html'),
            city('Melville', 'http://www.weatheroffice.gc.ca/city/pages/sk-8_metric_e.html'),
            city('Canora', 'http://www.weatheroffice.gc.ca/city/pages/sk-3_metric_e.html'),
            city('Yorkton', 'http://www.weatheroffice.gc.ca/city/pages/sk-33_metric_e.html'),

            #MANITOBA CITIES

            city('Winnipeg', 'http://www.weatheroffice.gc.ca/city/pages/mb-38_metric_e.html'),
            city('Sprague', 'http://www.weatheroffice.gc.ca/city/pages/mb-23_metric_e.html'),

            #ONTARIO CITIES

            city('Thunder Bay', 'http://www.weatheroffice.gc.ca/city/pages/on-100_metric_e.html'),
            city('Sioux Lookout', 'http://www.weatheroffice.gc.ca/city/pages/on-135_metric_e.html'),
            city('Armstrong', 'http://www.weatheroffice.gc.ca/city/pages/on-111_metric_e.html'),
            city('Hornepayne', 'http://www.weatheroffice.gc.ca/city/pages/on-78_metric_e.html'),
            city('Sudbury', 'http://www.weatheroffice.gc.ca/city/pages/on-40_metric_e.html'),
            city('South Parry', 'http://www.weatheroffice.gc.ca/city/pages/on-103_metric_e.html'),
            city('Toronto', 'http://www.weatheroffice.gc.ca/city/pages/on-143_metric_e.html'),
            city('Kingston', 'http://www.weatheroffice.gc.ca/city/pages/on-69_metric_e.html'),
            city('Cornwall', 'http://www.weatheroffice.gc.ca/city/pages/on-152_metric_e.html'),
            city('Sarnia', 'http://www.weatheroffice.gc.ca/city/pages/on-147_metric_e.html'),

            #QUEBEC CITIES

            city('Montreal', 'http://www.weatheroffice.gc.ca/city/pages/qc-147_metric_e.html'),
            city('Quebec', 'http://www.weatheroffice.gc.ca/city/pages/qc-133_metric_e.html'),
            city('La Tuque', 'http://www.weatheroffice.gc.ca/city/pages/qc-154_metric_e.html'),
            city('Saguenay', 'http://www.weatheroffice.gc.ca/city/pages/qc-166_metric_e.html'),
            city('Riviere-du-loup', 'http://www.weatheroffice.gc.ca/city/pages/qc-108_metric_e.html'),

            #NOVA SCOTIA CITIES

            city('Truro', 'http://www.weatheroffice.gc.ca/city/pages/ns-25_metric_e.html'),
            city('Halifax', 'http://www.weatheroffice.gc.ca/city/pages/ns-19_metric_e.html'),

            #NEW BRUNSWICK CITIES

            city('Edmundston', 'http://www.weatheroffice.gc.ca/city/pages/nb-32_metric_e.html'),
            city('Moncton', 'http://www.weatheroffice.gc.ca/city/pages/nb-36_metric_e.html'),
        ]

rawDescription: Exporting All Data in a Loop to Excel in Python


code:
import string
def transcribe(dna):
    return dna.translate(string.maketrans("atgc", "uacg"))

rawDescription: transcribe mRNA code from DNA strand

description: Transcribe mRNA code from DNA strand


code:
from selenium import webdriver
import lxml.html

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

tree = lxml.html.fromstring(driver.page_source)
root = tree.getroottree()

driver.close()

element = tree.xpath("//*[@class='w3-fluid']")[0]
print(root.getpath(element))

rawDescription: Selenium Python Finding actual xPath of current node within loop


code:
def sendMsg(event=''):
    message = inputBox.get()
    message += "\n"
    msg = Message(nickname,0,message,None) #Custom Class
    sock.send(pickle.dumps(msg))
    inputBox.delete(0,END)
    return

rawDescription: GUI Input with select.select() in Python


code:
try:
   from collections import Counter
except ImportError:
    class Counter(dict):
       ...

rawDescription: Subtracting two lists in Python

description: Subtracting two lists in Python


code:
print("%.*f" % (precision, somefloat))
# 0.01235

rawDescription: Limiting floats to a varying number (decided by the end-user) of decimal points in Python


code:
mesh_options = {'type':'mesh', 'long':True }
meshes = cmds.ls(**mesh_options)

rawDescription: Python (Maya) pass flags as variables

description: Python (Maya) pass flags as variables


code:
def do_n(fx, n):
    if n <= 0:
        return
    else:
        fx()
        do_n(fx, n-1)

def print_greeting():
    print("Hello World")

do_n(print_greeting, 3)

rawDescription: Python: Passing a function and calling it recursively


code:
def func(seq):
    for x in seq:
        try:
            if '.' in x:
                yield float(x)
            else:
                yield int(x)
        except ValueError:
            yield x

list1 = ['sandy', 'mike', '3.2', '15', '3.243', 'Washington D.C.']

for i in func(list1):
    print(i)
    print(type(i))
    print()

rawDescription: python: reading a file and storing strings as strings and integers as integers into a list

description: Python: reading a file and storing strings as strings and integers as integers into a list


code:
def at_most(n, elements):
    return sum(1 for _ in islice(elements, n + 1)) <= n
at_most(5, xrange(5))
at_most(2, xrange(5))

rawDescription: How to know a generated sequence is at most a certain length

description: Know a generated sequence is at most a certain length


code:
class Cell:
    # each cell will have exactly two values, so no need for __dict__
    __slots__ = ["row", "col"]

    # set up values at construction time using super().__setitem__()
    def __init__(self, row, col):
        super().__setitem__("row", row)
        super().__setitem__("col", col)
        return self

    # a Cell is intended to be immutable, so __setattr__ always raises an error
    def __setattr__(self, name, value):
        if hasattr(self, name):
            raise AttributeError("{!r} object attribute {!r} is read-only"
                                 .format(self.__class__.__name__, name))
        else:
            raise AttributeError("{!r} object has no attribute {!r}"
                                 .format(self.__class__.__name__, name))

    # comparison operators
    def __eq__(self, other):
        return (isinstance(other, Cell) and
                self.row == other.row and
                self.col == other.col)

    def __ne__(self, other):
        return not self == other

    # hash function, with a value borrowed from a tuple
    def __hash__(self):
        return hash((self.row, self.col))

rawDescription: Game of LIfe Hashing Python

description: Game of LIfe Hashing Python


code: matches = re.findall('^\s{3}(.*)$', contents, re.MULTILINE)

rawDescription: Regular Expression for multiple lines

description: Regular Expression for multiple lines


rawDescription: twisted client transport.write not sending data, even after close

description: Twisted client transport.write not sending data, even after close


code:
# Get indices  for sorted data
sort_idx = np.argsort(data)

# Get duplicate indices and set those in data to 0s
dup_idx = sort_idx[1::][np.diff(np.sort(data))==0]
data[dup_idx] = 0

rawDescription: Set duplicate elements as zeros

description: Set duplicate elements as zeros


code:
class PersonAdmin(admin.ModelAdmin) :
    pass

rawDescription: Define an order for ManyToManyField with django


code:
import Tkinter as tk
from PIL import Image, ImageTk, ImageOps, ImageDraw

class App():
    def __init__(self, master, image_path):
        self.orig_img = Image.open(image_path)
        self.tk_img  = ImageTk.PhotoImage(self.orig_img)

        w, h = self.orig_img.size
        self.canvas = tk.Canvas(master, width=w, height=h)
        self.canvas.pack()

        self.canvas.create_image(0, 0, image=self.tk_img, anchor='nw')
        self.canvas.bind_all("<MouseWheel>", self.zoom)
        self.canvas.bind_all("<Motion>", self.crop)

        self.create_mask()
        self.zoomValue = 0
        self.zimg_id = None

    def create_mask(self):
        self.mask = Image.new('L', (200,200), 0)
        draw = ImageDraw.Draw(self.mask)
        draw.ellipse((0, 0) + self.mask.size, fill=255)

    def zoom(self, event):
        if(event.delta > 0):
            if self.zoomValue != 4 : self.zoomValue += 1
        elif(event.delta < 0):
            if self.zoomValue != 0 : self.zoomValue -= 1
        self.crop(event)

    def crop(self, event):
        if self.zimg_id: self.canvas.delete(self.zimg_id)

        if (self.zoomValue) != 0:
            x, y = event.x, event.y
            if self.zoomValue == 1:
                tmp = self.orig_img.crop((x-45, y-30, x+45, y+30))
            elif self.zoomValue == 2:
                tmp = self.orig_img.crop((x-30, y-20, x+30, y+20))
            elif self.zoomValue == 3:
                tmp = self.orig_img.crop((x-15, y-10, x+15, y+10))
            elif self.zoomValue == 4:
                tmp = self.orig_img.crop((x-6, y-4, x+6, y+4))

            output = ImageOps.fit(tmp, self.mask.size, centering=(0.5, 0.5))
            output.putalpha(self.mask)
            self.zimg = ImageTk.PhotoImage(output)
            self.zimg_id = self.canvas.create_image(event.x, event.y, image=self.zimg)

root = tk.Tk()
App(root, r'C:\Users\user\Desktop\bg.gif')
root.mainloop()

rawDescription: Create circular image PIL Tkinter

description: Create circular image PIL Tkinter


rawDescription: Find k smallest pairs in two lists

description: Find k smallest pairs in two lists


code:
from twisted.internet import defer, task
from twisted.web.client import getPage

PARALLEL_FETCHES = 5
PARALLEL_PARSES = 10

def main_task(reactor):
    parseSemaphore = defer.DeferredSemaphore(PARALLEL_PARSES)

    def parseWhenReady(r):
        def parallelParse(_):
            parse(r).addBoth(
                lambda result: parseSemaphore.release().addCallback(
                    lambda _: result
                )
            )
        return parseSemaphore.acquire().addCallback(parallelParse)

    def fetch_urls():
        for url in get_urls():
            yield getPage(url).addCallback(parseWhenReady)

    coop = task.Cooperator()
    urls = fetch_urls()

    return (defer.DeferredList([coop.coiterate(urls)
                               for _ in xrange(PARALLEL_FETCHES)])
            .addCallback(lambda done:
                         defer.DeferredList(
                            [parseSemaphore.acquire()
                             for _ in xrange(PARALLEL_PARSES)]
                         ))
            .addCallback(task_finished))

task.react(main_task)

rawDescription: Twisted: Waiting for subtasks to finish

description: Twisted: Waiting for subtasks to finish


code:
place = Place.objects.get(name=place_to_land)
reviews = Review.objects.filter(place=place)

rawDescription: Django: Having trouble setting up Many-To-One model


code:
import code
def secret():
    print("What?! I don't even... get out of here.")
def public():
    print("Hello stranger.")
c = code.compile_command("secret(); public()")

rawDescription: Creating a simple scripting language in Python


rawDescription: Efficiently generate all composite numbers less than N (with their factorizations)


code:
import time
moment=time.strftime("%Y-%b-%d__%H_%M_%S",time.localtime())
f = open('output'+moment+'.log', 'w')

rawDescription: new file name each time python run

description: New file name each time python run


code:
def a(x):
   ...

a = my_decorator(a)

rawDescription: Python decorator best practice, using a class vs a function


code:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
subplot_args = {'projection':'3d'}
fig, ax = plt.subplots(subplot_kw=subplot_args)

rawDescription: Hierarchy in matplotlib

description: Hierarchy in matplotlib


code:
import itertools
x = itertools.count(0)
type(x).__name__

rawDescription: Getting the class name of an instance in Python


code:
str1 = 'abc(1),bcd(xxx),ddd(dfk dsaf)'
results = re.findall(r'(\w+)\(([^)]+)\),?',str1)

rawDescription: How to use Python re to parse this string in to list of multiple key value pairs?

description: Use Python re to parse this string in to list of multiple key value pairs


code: car_data = struct.get('List')

rawDescription: Save Json data to csv file

description: Save Json data to csv file


rawDescription: In pandas how to calculate 'Countif' on a moving window basis?


code:
import json
a = '[[X v] -s]'
a = ''.join(map(lambda x: '"{}"'.format(x) if x.isalpha() or x=='-' else x, a))
json.loads(a.replace('[ [', '[[').replace('] ]', ']]').replace(' ', ',').replace('][', '],[').replace('""',''))

rawDescription: how to turn a string of letters embedded in squared brackets into embedded lists

description: Turn a string of letters embedded in squared brackets into embedded lists


code:
bytes(int(b[i:i+8], 2) for i in range(0, len(b), 8))
import struct
b = '1010110000000010'
b''.join(struct.pack('B', int(b[i:i+8], 2)) for i in range(0, len(b), 8))

rawDescription: How can I create a bytes object in python?

description: Create a bytes object in python


code: re.search("abc".upper() + "def", var)

rawDescription: Perl regular expression \U

description: Perl regular expression \U


code:
def update_by_email(email=None, **kwargs):
    print(kwargs)

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


rawDescription: python optparse, how to include additional info in usage output?

description: Python optparse, how to include additional info in usage output


code:
padded_transport = np.zeros((rows + 2, cols + 2), float)
padded_transport[1:-1, 1:-1] = sediment_transport
# The two lines above could be replaced with:
#padded_transport = np.pad(sediment_transport, 1, mode='constant')

for [i, j], flow in np.ndenumerate(flow_direction):
    # Need to take into account the offset in the "padded_transport"
    r, c = i + 1, j + 1

    if flow == 32:
        elevation_change[i, j] = padded_transport[r - 1, c - 1]
    elif flow == 16:
        elevation_change[i, j] = padded_transport[r, c - 1]
    elif flow == 8:
        elevation_change[i, j] = padded_transport[r + 1, c - 1]
    elif flow == 4:
        elevation_change[i, j] = padded_transport[r + 1, c]
    elif flow == 64:
        elevation_change[i, j] = padded_transport[r - 1, c]
    elif flow == 128:
        elevation_change[i, j] = padded_transport[r - 1, c + 1]
    elif flow == 1:
        elevation_change[i, j] = padded_transport[r, c + 1]
    elif flow == 2:
        elevation_change[i, j] = padded_transport[r + 1, c + 1]

rawDescription: Iterating through a numpy array and then indexing a value in another array


code:
class test(np.ndarray):
    __array_priority__ = 100

    def __new__(cls):
        obj = np.int32([1]).view(cls)
        return obj

    def __array_wrap__(self, arr, context) :
        if context is not None :
            ufunc = context[0]
            args = context[1]
            if ufunc == np.subtract :
                if self is args[0] :
                    return args[1]
                elif self is args[1] :
                    return args[0]
        return arr

rawDescription: Argument types differ in normal and reflected operator overload (__sub__ / __rsub__)


code:
TEMP = dict.fromkeys('''FHDosed FHControl FNHDosed FNHControl FTDosed FTControl MHDosed
                      MHControl MNHDosed MNHControl MTDosed MTControl'''.split(), 0)
TR = {key:TEMP.copy() for key in ('TRI_1', 'TRI_2', 'TRV_1', 'TRV_2', 'TRV_3', 'TRV_4')}

dmap = {
    ('G', 'A'): 'TRI_1',
    ('C', 'T'): 'TRI_1',
    ('A', 'G'): 'TRI_2',
    ('T', 'C'): 'TRI_2',
    ('G', 'C'): 'TRV_1',
    ('C', 'G'): 'TRV_1',
    ('A', 'T'): 'TRV_1',
    ('T', 'A'): 'TRV_1',
    }

lst = [
      ['FHControl', 'G', 'A'],
      ['MNHDosed', 'G', 'C']
      ]

for row in lst:
    key, q, s = row
    TR[dmap[q, s]][key] += 1

print(TR)

rawDescription: How to bin many category combinations (72 variables) in python lists

description: Bin many category combinations (72 variables) in python lists


code: resultset = [value for key, value in your_dict.items() if key not in your_blacklisted_set]

rawDescription: Retain all entries except for one key python


code: re.findall(r'\b\w+\b', "This is not is, clearly is: weird")

rawDescription: Stripping punctuation from unique strings in an input file


code:
scores = Vote.objects.get_score_in_bulk(posts_list)
posts_list = sorted(posts_list, key=lambda post: (scores[post.id]['score'], post.datetime))

rawDescription: Is it possible to sort using sorted() with attributes from two different models?


code:
from collections import Counter
most_common_imdb_value = Counter(d['imdb'] for d in myList).most_common(1)[0]

rawDescription: Getting the most common key value in a list of dictionaries


code:
# Notify not_empty whenever an item is added to the queue; a
# thread waiting to get is notified then.
self.not_empty = _threading.Condition(self.mutex)

rawDescription: efficient python raw_input and serial port polling

description: Efficient python raw_input and serial port polling


code:
from FunctionLibrary import *
foo()
bar()

rawDescription: Difference in ways of importing modules

description: Difference in ways of importing modules


code:
class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
    '''Preemptive basic auth.

    Instead of waiting for a 403 to then retry with the credentials,
    send the credentials if the url is handled by the password manager.
    Note: please use realm=None when calling add_password.'''
    def http_request(self, req):
        url = req.get_full_url()
        realm = None
        # this is very similar to the code from retry_http_basic_auth()
        # but returns a request object.
        user, pw = self.passwd.find_user_password(realm, url)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.b64encode(raw).strip()
            req.add_unredirected_header(self.auth_header, auth)
        return req

    https_request = http_request

rawDescription: Fetching a URL from a basic-auth protected Jenkins server with urllib2


code:
import numpy as np
import pandas as pd

def nan_all_but_min(df):
    arr = df.values
    idx = np.argmin(arr, axis=1)
    newarr = np.full_like(arr, np.nan, dtype='float')
    newarr[np.arange(arr.shape[0]), idx] = arr[np.arange(arr.shape[0]), idx]
    df = pd.DataFrame(newarr, columns=df.columns, index=df.index)
    return df

df = pd.DataFrame(np.random.random((4,3)))
print(df)
#           0         1         2
# 0  0.542924  0.499702  0.058555
# 1  0.682663  0.162582  0.885756
# 2  0.389789  0.648591  0.513351
# 3  0.629413  0.843302  0.862828

df = nan_all_but_min(df)
print(df)

rawDescription: keep only lowest value per row in a Python Pandas dataset

description: Keep only lowest value per row in a Python Pandas dataset


code: AUTH_USER_MODEL = 'app.CustomUser'

rawDescription: how to extend model User?

description: Extend model User


code:
class Variables(object):
    numbers = {
        "num{}".format(i): "Text {}".format(i)
        for i in range(100)
    }

rawDescription: Python: Assigning Random Integer to Variables in a Class


code: self.parent.after(10, self.atur)

rawDescription: Change the color widget by using GPIO in Raspberry


code:
M = np.searchsorted([1,3,4],A.ravel(),'left') != \
    np.searchsorted([1,3,4],A.ravel(),'right')

rawDescription: How to find all elements in a numpy 2-dimensional array that match a certain list?

description: Find all elements in a numpy 2-dimensional array that match a certain list


code:
intersection = list_of_sets[0]
for s in list_of_sets[1:]:
    intersection = set.intersection(intersection, s)

rawDescription: Why are methods so slow?

description: Why are methods so slow


code:
def select(lst, *indices):
    return (lst[i] for i in indices)
L = range(0,101,10)
a, b = select(L, 2, 5)
a, b

rawDescription: Accessing non-consecutive elements of a list or string in python


code:
Button(root, text='File Open', command = openFile).pack(fill=X)
#      ^^^^

rawDescription: Tkinter window not closing after closed file dialog


code: min1, min2 = min(zip(list1, list2), key=lambda ee: e[0][1])

rawDescription: What is faster? minimum of list then index of minimum, vs iterating through list


code:
row = database.db_session.query(User.name, User.api_key)\
    .filter(User.user_id==user_id).first()

rawDescription: SQLAlchemy: Getting a single object from joining multiple tables


rawDescription: Pattern matching and compiling

description: Pattern matching and compiling


code: (x if x is not None else y for x,y in my_data)

rawDescription: Flatten Sequence With Boolean Expression Generator


code:
def main():
    # passed_list inside useTheList is set to what is returned from defineAList
    useTheList(defineAList())

rawDescription: Python: Passing variables between functions


code: s in ['true', '1', 't', 'y', 'yes', 'yeah', 'yup', 'certainly', 'uh-huh']

rawDescription: Converting from a string to boolean in Python?


code:
phrase3 = 'bla bla word1 bla word2 bla word7 word6, word4 word3failed'
match(phrase3)

rawDescription: searching string containing 6 words for real words

description: Searching string containing 6 words for real words


code:
# import section
from django.utils.safestring import mark_safe
# ...

@page_template("app/profession.html") # just add this decorator
def profile(request, template="app/profession.html", extra_context=None):

    employ_v_obj = Employees.objects.get(id=45)
    testim_v_obj = Testimonial.objects.get(id=45)
    skills_v_qs = Skills.objects.filter(id=45)

    skills_v_json_list = [obj.as_dict() for obj in skills_v_qs]

    context = {
        'employ_V': employ_v_obj,
        'testim_V': testim_v_obj,
    }

    context['skills_V_json'] = mark_safe(json.dumps(skills_v_json_list, ensure_ascii=False))

    if extra_context is not None:
        context.update(extra_context)

    return render_to_response(template, context, context_instance=RequestContext(request))

rawDescription: How to return table data as different format types via views in Django

description: Return table data as different format types via views in Django


code: open_files = [open(path) for path in grouped[0]]

rawDescription: How to check size of the files in a directory with python?

description: Check size of the files in a directory with python


rawDescription: Python - how to ignore escape chars in regexp


code:
class SessionMiddleware(object):
    def process_request(self, request):
        engine = import_module(settings.SESSION_ENGINE)
        session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None)
        request.session = engine.SessionStore(session_key)

rawDescription: Django: How to extend SessionBase to have access to the Request Object


code:
['product', 'shampoo']
['nothing', 'random']

rawDescription: Comparing two list and getting result a list with some checks


code:
import tempfile
import os

class RenamedTemporaryFile(object):
    """
    A temporary file object which will be renamed to the specified
    path on exit.
    """
    def __init__(self, final_path, **kwargs):
        tmpfile_dir = kwargs.pop('dir', None)

        # Put temporary file in the same directory as the location for the
        # final file so that an atomic move into place can occur.

        if tmpfile_dir is None:
            tmpfile_dir = os.path.dirname(final_path)

        self.tmpfile = tempfile.NamedTemporaryFile(dir=tmpfile_dir, **kwargs)
        self.final_path = final_path

    def __getattr__(self, attr):
        """
        Delegate attribute access to the underlying temporary file object.
        """
        return getattr(self.tmpfile, attr)

    def __enter__(self):
        self.tmpfile.__enter__()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is None:
            self.tmpfile.delete = False
            result = self.tmpfile.__exit__(exc_type, exc_val, exc_tb)
            os.rename(self.tmpfile.name, self.final_path)
        else:
            result = self.tmpfile.__exit__(exc_type, exc_val, exc_tb)

        return result

rawDescription: Threadsafe and fault-tolerant file writes


code:
def _processDictEntries(var1=None,var2=None,**kwargs):
    ...

def processDictEntries(d):
    return _processDictEntries(**d)

rawDescription: Adding variables "by name" to local namespace


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

wait = WebDriverWait(driver, 10)
district = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input[label=District]")))
print(district.get_attribute("value"))

rawDescription: How to check if form filled in python selenium

description: Check if form filled in python selenium


code:
import matplotlib
from pylab import *
import numpy as np

#Create test data with zero valued diagonal:
data = np.random.random_sample((25, 25))
rows, cols = np.indices((25,25))
data[np.diag(rows, k=0), np.diag(cols, k=0)] = 0

#Create new colormap, with white for zero
#(can also take RGB values, like (255,255,255):
colors = [('white')] + [(cm.jet(i)) for i in xrange(1,256)]
new_map = matplotlib.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256)

pcolor(data, cmap=new_map)
colorbar()
savefig('map.png')
show()

rawDescription: Make reverse diagonals white in heatmap

description: Make reverse diagonals white in heatmap


code:
s = a - b[:, None]
TOL = 1.e-6
ind = np.where(~(np.abs(s) <= TOL).any(axis=1))[0]

rawDescription: Search for value from one array in another array and modify array if not found - numpy


code:
from django.db import transaction

def viewfunc(request):
    # This code executes in autocommit mode (Django's default).
    do_stuff()

    with transaction.atomic():
        # This code executes inside a transaction.
        do_more_stuff()

rawDescription: What is an efficent way of inserting thousands of records into an SQLite table using Django?


code:
from . import config
class Myclass(object):
    def __getattr__(self, key):
        return getattr(config, key)

rawDescription: python initialization of constants in separate file

description: Python initialization of constants in separate file


code:
import csv
first_input = raw_input('Enter Filename:')
data = first_input
author = raw_input('Enter Author Name:')
title = raw_input('Enter Title Name:')
year= raw_input('Enter year:')
Journal = raw_input('Enter Journal:')

with open(data,"a") as f:
    wr = csv.writer(f,delimiter="\t")
    wr.writerow([author+".",title+".",year+".",Journal+"."])

rawDescription: How to output a Tab delimated file in a particular format

description: Output a Tab delimated file in a particular format


code:
import random
import csv

with open("input.csv") as infile:
    csvreader = csv.reader(infile)
    with open("output.csv", 'w') as outcsv:
        csvwriter = csv.writer(outcsv)
        with open("output.txt", 'w') as outtxt:
            for row in csvreader:
                random_pairs = [(row[2*i], row[2*i + 1]) for i in range(int(len(row)/2))]
                random.shuffle(random_pairs)
                outline = []
                for pair in random_pairs:
                    outtxt.write('' + pair[1] + '')
                    outline.append(pair[0])
                    outline.append(pair[1])
                outtxt.write('\n')
                csvwriter.writerow(outline)

rawDescription: Python Output Random Order From ReadLines()


code: p.DataFrame(map(None, l1, l2))

rawDescription: Two ways to join lists in dataframe: as rows and columns


code: image.shape[:2] # gives you (height, width) tuple

rawDescription: OpenCV cv2 image to PyGame image?

description: OpenCV cv2 image to PyGame image


code:
def formatmonthname(self, theyear, themonth, width, withyear=True):
    with TimeEncoding(self.locale) as encoding:
        s = month_name[themonth]
        if encoding is not None:
            s = s.decode(encoding)
        if withyear:
            s = "%s %r" % (s, theyear)
        return s.center(width)

rawDescription: Python calendar: day/month names in specific locale


rawDescription: Python: How to evaluate a function which is string?


code: timeseries['timeblock'] = timeseries['timeblock'].map(lambda x: int(x/300))

rawDescription: Create five minute time blocks (Pandas/Python)


code:
class ReviewAttribute(models.Model):
    review = models.ForeignKey(Review, related_name='attributes')
    name = models.CharField(max_length=100)
    value = models.IntegerField()

rawDescription: Database design for Django review website


code:
class Queue():
    __slots__ = ('stack1', 'stack2')

    def __init__(self): # You need to define an initialize method
        self.stack1 = []
        self.stack2 = []

    # staticmethods are the only kinds of class methods that take no arguments
    @staticmethod
    def mkQueue():
        return Queue()

rawDescription: Queue, stack python

description: Queue, stack python


code:
import re
thingToSplit = 'a1b2c'
re.split('\d+', thingToSplit)

rawDescription: Python: split a string delimited by given object type


code:
def _find_x12(x12path=None, prefer_x13=True):
    """
    If x12path is not given, then either x13as[.exe] or x12a[.exe] must
    be found on the PATH. Otherwise, the environmental variable X12PATH or
    X13PATH must be defined. If prefer_x13 is True, only X13PATH is searched
    for. If it is false, only X12PATH is searched for.
    """

rawDescription: ARIMA seasonal prediction with Python: x12a and x13as not found on path


rawDescription: How to get top-level protobuf enum value name by number in python?

description: Get top-level protobuf enum value name by number in python


code:
import random

l = []
for _ in range(10):
    n = random.randint(0, 10)
    print(n)
    if n not in l:
        print("New item.")
        l.append(n)
    else:
        print("Item found at index {0}.".format(l.index(n)))
print(l)

rawDescription: Randint number into a Dict

description: Randint number into a Dict


code:
from subprocess import call
call(["notepad"])

rawDescription: Emulating a Windows shortcut in Python

description: Emulating a Windows shortcut in Python


code:
from timeit import Timer
t_old = Timer('calc_polygons_orig(1, 1, 100, 100, 10)', 'from hexagons import calc_polygons_orig')
t_new = Timer('calc_polygons_new(1, 1, 100, 100, 10)', 'from hexagons import calc_polygons_new')
t_old.timeit(20000)
t_new.timeit(20000)
t_old_large = Timer('calc_polygons_orig(1, 1, 1000, 1000, 10)', 'from hexagons import calc_polygons_orig')
t_new_large = Timer('calc_polygons_new(1, 1, 1000, 1000, 10)', 'from hexagons import calc_polygons_new')
t_old_large.timeit(200)
t_new_large.timeit(200)

rawDescription: Faster way to calculate hexagon grid coordinates


code: a = numpy.frombuffer(buffer, float)

rawDescription: Getting data from ctypes array into numpy


code:
import A
A.main('arg1', 'arg2')

rawDescription: passing arguments without commandline

description: Passing arguments without commandline


code:
import inspect
def f(x: int, y: int) -> type(None):
    pass

def g(a: object, b: int) -> type(None):
    pass

inspect.getfullargspec(f)
inspect.getfullargspec(f).args
inspect.getfullargspec(g).args

rawDescription: Given the name of a positional parameter to a function, can the parameter's position be determined?


code: mydict["Pepsi"]["rating"]

rawDescription: What is the best Python data structure for named 2D array


rawDescription: How do I get the instance method's next-in-line parent class from `super()` in Python

description: Get the instance method's next-in-line parent class from `super()` in Python


code:
from datetime import datetime
s = '2-1-2013'
datetime.strptime(s, '%m-%d-%Y')
s = '2/1/2013'
datetime.strptime(s, '%m/%d/%Y')

rawDescription: How to allow users to pick dates using Python

description: Allow users to pick dates using Python


code: data2 = np.asarray(data2)

rawDescription: Writing wav file in Python with wavfile.write from SciPy


code:
indexItem = self.model.index(index.row(), 0, index.parent())

fileName = self.model.fileName(indexItem)
filePath = self.model.filePath(indexItem)

rawDescription: About QTreeView and change selected index


code:
import matplotlib.pyplot as plt
plt.ion()

import menpo.io as mio

bb = mio.import_builtin_asset.breakingbad_jpg()
bb.view()

rawDescription: Can't get menpo to display images in Pycharm


code:
open('tmpfile', 'w').write(x)
y = open('tmpfile', 'r').read()
struct.unpack('2q', y)

rawDescription: How to unpack a struct in Python?

description: Unpack a struct in Python


code: directory = os.path.join('inbox','*')

rawDescription: Know when directory copy is complete

description: Know when directory copy is complete


code: X = X.tocsr()

rawDescription: Python - The best way to read a sparse file into a sparse matrix


code: dfIn.apply(expand, axis=1).stack()

rawDescription: Iterate over rows and expand pandas dataframe


rawDescription: Remove arrays from nested arrays based on first element of each array


code:
from django.template.loader import render_to_string

def my_serialize(query_set):
    xml = render_to_string('xml_template.xml', {'query_set': query_set})

    return xml

rawDescription: Generate XML file from model data

description: Generate XML file from model data


code:
resp = requests.get(url, stream=True)
tmp = io.BytesIO()
for chunk in resp.iter_content(4*KB):
    tmp.write(chunk)
archive = zipfile.ZipFile(tmp)
archive.extractall(path)

rawDescription: writing decompressed file to disk fetched from web server

description: Writing decompressed file to disk fetched from web server


rawDescription: How to set first column to a constant value of an empty np.zeros numPy matrix?

description: Set first column to a constant value of an empty np.zeros numPy matrix


code:
def on_change(self, cr, uid, ids, context=None):
    # do something
    return {'value': { 'field_name': newValue},
            'warning': {'title': _("Warning"),
                        'message': _("warning message")
                       }
           }

rawDescription: Client side validation in openerp

description: Client side validation in openerp


code: players_table = soup.find_all("tr",{"class" : re.compile(r"\d+$")})

rawDescription: Getting names from HTML file via python

description: Getting names from HTML file via python


rawDescription: Regex to extract multiline hash comments


code: itemList = self.request.get("items")

rawDescription: Read each line of HTML form submission Python


code:
import matplotlib.pyplot as plt
from matplotlib import colors, cm

a = np.random.randn(10,10)

norm = colors.normalize()
cmap = cm.hsv
a_colors = cmap(norm(a))

col1 = colors.colorConverter.to_rgba('w')
col2 = colors.colorConverter.to_rgba('k')

a_colors[a<-0.1,:] = col1
a_colors[a>0.1,:] = col2
plt.imshow(a_colors, interpolation='nearest')
plt.show()

rawDescription: Displaying multiple masks in different colours in pylab


code: any(x.startswith("%s/" % name.rstrip("/")) for x in z.namelist())

rawDescription: Check if a directory exists in a zip file with Python


code:
import sys
import gzip

s = 'foo'*100

sys.stdout.buffer.write(gzip.compress(s.encode()))

rawDescription: Compressing JSON sent via CGI in Python

description: Compressing JSON sent via CGI in Python


code: firefox = selenium.webdriver.remote.webdriver.WebDriver (command_executor=my_url, desired_capabilities=DesiredCapabilities.FIREFOX, browser_profile=profile)

rawDescription: Using Selenium/WebDriver and Python, how do I suppress the prompt to share my camera and microphone?


code: isbn = list(map(int, input("Enter ISBN: ")))

rawDescription: Getting type error in python when using for loop


code: x, y = coordinates

rawDescription: how to manipulate a list in python

description: Manipulate a list in python


rawDescription: How to download a file using Python

description: Download a file using Python


code:
scenes = {
    'central_corridor': CentralCorridor(),
    'laser_weapon_armory': LaserWeaponArmory(),
    'the_bridge': TheBridge(),
    'escape_pod': EscapePod(),
    'death': Death()
}

rawDescription: Learn Python the Hard Way Exercise 43

description: Learn Python the Hard Way Exercise 43


code:
total = sum(x.values(), 0.0)
for key in x:
    x[key] /= total

rawDescription: How to normalize a Counter and combine 2 normalized Counters? - python

description: Normalize a Counter and combine 2 normalized Counters? - python


code:
from socket import *
cs = socket(AF_INET, SOCK_DGRAM)
cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
cs.sendto('This is a test', ('255.255.255.255', 54545))

rawDescription: Python UDP Broadcast not sending

description: Python UDP Broadcast not sending


code: fruit_chosen = next((fruit['fruit'] for fruit in lst if fruit['color'] == 'yellow'), None)

rawDescription: How to get a value from a dict in a list of dicts

description: Get a value from a dict in a list of dicts


code:
time_delta = TIME[apply_after_index:] - TIME[apply_after_index]
TEMP[apply_after_index:] = TEMP[apply_after_index:] * np.exp(-0.05 * time_delta)

rawDescription: Numpy time based vector operations where state of preceding elements matters - are for loops appropriate?


code:
def sync(ts):
    vals = ts.values
    n, k = len(vals), np.where(vals == 0)[0][0]
    return Series(vals, np.arange(-k, n - k))

rawDescription: Time series normalization by event

description: Time series normalization by event


code:
import csv

with open('input.csv') as f_input, open('output.csv', 'wb') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)

    for row in csv_input:
        try:
            mi = row.index('Mi')
            row[:] = row[:mi] + [''] * (len(row) - mi)
        except ValueError:
            pass

        csv_output.writerow(row)

rawDescription: Delete or remove unexpected records and strings based on multiple criteria by python or R script


rawDescription: Python: How can I get the previous 5 values in a Pandas dataframe after skipping the very last one?


code: lowui = user_input.lower

rawDescription: Python if with many or in a contracted form


code:
anything = dict()
for k in dic: # for each key in dic
    v = dic[k]
    anything[v] = k

rawDescription: Decode High Level Python to easier code

description: Decode High Level Python to easier code


code: form.fields['somekey'].initial = value

rawDescription: Django Assigning BoundField Value

description: Django Assigning BoundField Value


code:
import random
import string
data = ''.join(random.choice(string.ascii_uppercase) for i in range(100))

from io import StringIO

s = StringIO(data)
chunk = s.read(20)  # Set to 200KB
while chunk:
    print(chunk)    # Do something with chunk
    chunk = s.read(20)

rawDescription: How to fragment a large python object into smaller chunks

description: Fragment a large python object into smaller chunks


code:
from multiprocessing import Process

for filename in files_to_process:
    p = Process(target=process_file, args=(filename,))
    p.start()
    p.join()

rawDescription: Python process keeps growing in django db upload script


code:
from Tkinter import *
import Image, ImageDraw

width = 400
height = 300
center = height//2
white = (255, 255, 255)
green = (0,128,0)

root = Tk()

# Tkinter create a canvas to draw on
cv = Canvas(root, width=width, height=height, bg='white')
cv.pack()

# PIL create an empty image and draw object to draw on
# memory only, not visible
image1 = Image.new("RGB", (width, height), white)
draw = ImageDraw.Draw(image1)

# do the Tkinter canvas drawings (visible)
cv.create_line([0, center, width, center], fill='green')

# do the PIL image/draw (in memory) drawings
draw.line([0, center, width, center], green)

# PIL image can be saved as .png .jpg .gif or .bmp file (among others)
filename = "my_drawing.jpg"
image1.save(filename)

root.mainloop()

rawDescription: How can I convert canvas content to an image?

description: Convert canvas content to an image


rawDescription: How does Python interpreter look for types?


rawDescription: Removing intersection between data frame based on multiple columns


rawDescription: Iteration and replace trough double array


code:
def frontend(data):
  return [reduce(lambda a, b: a*b, data[:-1]), data[-1]]

rawDescription: Get a 3D or 4D array as input and reshape it to 2D array in a function from external script


rawDescription: Locating index of item via REGEX in Python


code:
df = pd.DataFrame({ 'x':[0, 0, 1, 0, 0, 3, 0, 0, 0, 5, 0],
                    'y':[0, 2, 0, 0, 0, 3, 0, 1, 0, 0, 0] })

sdf = df.to_sparse(fill_value=0)

df + sdf                 # works

df['x'] + sdf['x']       # works

df['x'] + sdf['y']       # doesn't work, b/c shapes different?

rawDescription: sparse versions of Pandas DataFrame

description: Sparse versions of Pandas DataFrame


rawDescription: all combination of a complicated list

description: All combination of a complicated list


code:
mylist=[[1,2,3],[3,4,5]]
rows=[]
for row in mylist:
    rows.append("\t".join(map(str,row)))
rows
['1\t2\t3', '3\t4\t5']

rawDescription: List Comprehension to For Loop

description: List Comprehension to For Loop


code:
#coding: utf8
import re
s = 'abcῶἤÜὰὔdef'
s = re.sub(r'[\x80-\U0010FFFF]', lambda x: '&#x{:04X};'.format(ord(x.group(0))), s)
print(s)

rawDescription: Convert unicode symbol to unicode entity


code:
import sqlalchemy
from sqlalchemy import Column, Table, create_engine, MetaData, Integer
from sqlalchemy import func, select
from sqlalchemy.pool import StaticPool
from random import randrange
import numpy
import sqlite3

class NumpyVarAggregate(object):
  def __init__(self):
    self.values = []
  def step(self, value):
    self.values.append(value)
  def finalize(self):
    return numpy.array(self.values).var()

def sqlite_memory_engine_creator():
    con = sqlite3.connect(':memory:')
    con.create_aggregate("np_var", 1, NumpyVarAggregate)
    return con

e = create_engine('sqlite://', echo=True, poolclass=StaticPool,
                  creator=sqlite_memory_engine_creator)
m = MetaData(bind=e)
t = Table('mytable', m,
            Column('id', Integer, primary_key=True),
            Column('number', Integer)
          )
m.create_all()

rawDescription: How can i write my own aggregate functions with sqlalchemy?

description: Write my own aggregate functions with sqlalchemy


code:
def mvee(points, tol = 0.001):
    """
    Find the minimum volume ellipse.
    Return A, c where the equation for the ellipse given in "center form" is
    (x-c).T * A * (x-c) = 1
    """
    points = np.asmatrix(points)
    N, d = points.shape
    Q = np.column_stack((points, np.ones(N))).T
    err = tol+1.0
    u = np.ones(N)/N
    while err > tol:
        # assert u.sum() == 1 # invariant
        X = Q * np.diag(u) * Q.T
        M = np.diag(Q.T * la.inv(X) * Q)
        jdx = np.argmax(M)
        step_size = (M[jdx]-d-1.0)/((d+1)*(M[jdx]-1.0))
        new_u = (1-step_size)*u
        new_u[jdx] += step_size
        err = la.norm(new_u-u)
        u = new_u
    c = u*points
    A = la.inv(points.T*np.diag(u)*points - c.T*c)/d
    return np.asarray(A), np.squeeze(np.asarray(c))

rawDescription: Port MATLAB bounding ellipsoid code to Python


code:
if code:
    # Replaces <gco_CharacterString> text
    code[0].text = '{0328cb65-b564-495a-b17e-e49e04864ab7}'
    # Save back to the XML file
    etree.ElementTree(root).write('D:\test.xml', pretty_print=True)

rawDescription: Change text value with lxml

description: Change text value with lxml


code:
import lxml.etree as ET
import textwrap
import io

def setup_ABC():
    content = textwrap.dedent('''\
      <root>
        <A1>
          <B1></B1>
          <C>1<D1></D1></C>
          <E1></E1>
        </A1>
        <A2>
          <B2></B2>
          <C>2<D></D></C>
          <E2></E2>
        </A2>
      </root>
        ''')
    return content

def study_fast_iter():
    def orig_fast_iter(context, func, *args, **kwargs):
        for event, elem in context:
            print('Processing {e}'.format(e=ET.tostring(elem)))
            func(elem, *args, **kwargs)
            print('Clearing {e}'.format(e=ET.tostring(elem)))
            elem.clear()
            while elem.getprevious() is not None:
                print('Deleting {p}'.format(
                    p=(elem.getparent()[0]).tag))
                del elem.getparent()[0]
        del context

    def mod_fast_iter(context, func, *args, **kwargs):
        """
        http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
        Author: Liza Daly
        See also http://effbot.org/zone/element-iterparse.htm
        """
        for event, elem in context:
            print('Processing {e}'.format(e=ET.tostring(elem)))
            func(elem, *args, **kwargs)
            # It's safe to call clear() here because no descendants will be
            # accessed
            print('Clearing {e}'.format(e=ET.tostring(elem)))
            elem.clear()
            # Also eliminate now-empty references from the root node to elem
            for ancestor in elem.xpath('ancestor-or-self::*'):
                print('Checking ancestor: {a}'.format(a=ancestor.tag))
                while ancestor.getprevious() is not None:
                    print(
                        'Deleting {p}'.format(p=(ancestor.getparent()[0]).tag))
                    del ancestor.getparent()[0]
        del context

    content = setup_ABC()
    context = ET.iterparse(io.BytesIO(content), events=('end', ), tag='C')
    orig_fast_iter(context, lambda elem: None)
    # Processing <C>1<D1/></C>
    # Clearing <C>1<D1/></C>
    # Deleting B1
    # Processing <C>2<D/></C>
    # Clearing <C>2<D/></C>
    # Deleting B2

    print('-' * 80)
    """
    The improved fast_iter deletes A1. The original fast_iter does not.
    """
    content = setup_ABC()
    context = ET.iterparse(io.BytesIO(content), events=('end', ), tag='C')
    mod_fast_iter(context, lambda elem: None)
    # Processing <C>1<D1/></C>
    # Clearing <C>1<D1/></C>
    # Checking ancestor: root
    # Checking ancestor: A1
    # Checking ancestor: C
    # Deleting B1
    # Processing <C>2<D/></C>
    # Clearing <C>2<D/></C>
    # Checking ancestor: root
    # Checking ancestor: A2
    # Deleting A1
    # Checking ancestor: C
    # Deleting B2

study_fast_iter()

rawDescription: Using Python Iterparse For Large XML Files


code:
import itertools
# parameters
P_peak_all = [100, 200]
idle_ratio_all = [0., 0.3, 0.6]
# iterate through these parameters and call the notebook's logic
for P_peak, idle_ratio in itertools.product(P_peak_all, idle_ratio_all):
    print(P_peak, idle_ratio, P_peak*idle_ratio)
    print('========================')
    m_synth, m_synth_ns = build_synth_measurement(P_peak, idle_ratio)
    compare_measurements(m_synth, m_synth_ns, "Peak pauser", "No scheduler", file_note="-%d-%d" % (P_peak, int(idle_ratio*100)))

rawDescription: Run parts of a ipython notebook in a loop / with different input parameter


code:
import copy
temp=copy.deepcopy(board)

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


rawDescription: Python struct.pack dropping a byte.

description: Python struct.pack dropping a byte.


code:
my_dict = {
    'suchy': 'such',
    'anotherarray': ['something', 'else']
}

rawDescription: Turning an existing array into a multidimensional


code:
while pages >= 1:
    pages -= 1

rawDescription: Is there a nicer way to write this while loop in Python?


code:
def __init__(self):
    # ...
    self.frame = tk.Frame(self.root).grid(row=0, column=0)
    self.label = tk.Label(self.frame)
    self.label.grid()
    self.root.bind('q', self.toggle)

def toggle(self, event):
    self.counter += 1
    # ...
    # the tk.Label call is not assigned to a variable on purpose
    self.label.config(text=text, bg=bg)

rawDescription: How to erase the contents of a Frame

description: Erase the contents of a Frame


code:
for x in range(n, 37, 7):
    for j in range(x,  x + 7):
        print("{:>2}".format(j), end=" ")
    print()

rawDescription: How to generate rows and columns in Python 3

description: Generate rows and columns in Python 3


code:
a_instance.z  #instance variable 'z'
A.z           #class variable 'z'

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


code: lines = [line.strip() for line in open('temp.dat')]

rawDescription: how do I pass many php variables to python

description: Pass many php variables to python


code:
cache = {}

def Opt(n):
    # tuple objects are hashable and can be put in the cache.
    n = tuple(n)

    if n in cache:
        return cache[n]

    if len(n) == 1:
        result = 0
    else:
        result = sum(n) + min(Opt(n[:i]) + Opt(n[i:])
                              for i in range(1, len(n)))

    cache[n] = result
    return result

rawDescription: More on dynamic programming

description: More on dynamic programming


code:
def group_by_extension(filenames):
    '''Puts the filenames in the given iterable into a dictionary where
    the key is the last component of the filename and the value is
    a list of the filenames with that extension.'''
    keyfunc = lambda f: f.split('.', 1)[1]
    return dict( (k, list(g)) for k,g in groupby(
               sorted(filenames, key=keyfunc), key=keyfunc
           ) )

rawDescription: Python: finding files with matching extensions or extensions with matching names in a list


rawDescription: Smooth contour plot in matplotlib from 3 lists of different size


code: out = [float(f_interp(XX,YY)) for XX,YY in zip(X,Y)]

rawDescription: SciPy interp2D for pairs of coordinates

description: SciPy interp2D for pairs of coordinates


rawDescription: Choose two tuples from a list and calculate every possible pair in Python


code:
for key, value in data.iteritems():
    setattr(property_selected, key, value)

rawDescription: Iterating through a data list and edit an object's attribute based on the list


code:
import six
import pandas as pd

data = """\
  Surname Knownas        TB
0   K      S             79.3
1   T      J             79.1
2   I      S             78.3
3   P      B             78.2
4   W      A             78.1
"""

df1 = pd.read_csv(six.StringIO(data), sep='\s+', index_col=0)
print(df1)

data = """\
Mathematics           Name
0          A*           H,E
1          A*           P,E
2          A*           L,J
3          A*           W,D
4          A            C,K
5          A            K,S
"""
df2 = pd.read_csv(six.StringIO(data), sep='\s+', index_col=0)
print(df2)
df2[['Surname', 'Knownas']] = df2.Name.str.split(',', expand=True)
print(df2)

merge = pd.merge(df1, df2, on=['Surname','Knownas'])
print(merge)

rawDescription: How to join two tables while merging column names

description: Join two tables while merging column names


code:
def chunk(input, size):
    return map(None, *([iter(input)] * size))

rawDescription: Tuple with nested list into dictionary

description: Tuple with nested list into dictionary


code:
def print_decimal(n):
    print(n)

def print_hex(n):
    print(hex(n))

# in Python 2.x, use raw_input
hex_output_wanted = input("do you want hex output? ")

if hex_output_wanted.lower() in ('y', 'yes'):
    printint = print_hex
else:
    printint = print_decimal

# the variable printint now holds a function that can be used to print an integer
printint(42)

rawDescription: Python - Why doesn't this instance method need parentheses when called inside another instance method?


code:
import sys
import bz2
import glob
import time
import threading
import subprocess

output_filename = '../whatever.bz2'
input_filenames = glob.glob(time.strftime("xyz_%F_*.log"))
p = subprocess.Popen(['filter', 'args'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output = open(output_filename, 'wb')
output_compressor = bz2.BZ2Compressor()

def data_reader():
    for filename in input_filenames:
        f = open(filename, 'rb')
        p.stdin.writelines(iter(lambda: f.read(8192), ''))
    p.stdin.close()

input_thread = threading.Thread(target=data_reader)
input_thread.start()

with output:
    for chunk in iter(lambda: p.stdout.read(8192), ''):
        output.write(output_compressor.compress(chunk))

    output.write(output_compressor.flush())

input_thread.join()
p.wait()

rawDescription: how to concatenate multiple files for stdin of Popen

description: Concatenate multiple files for stdin of Popen


rawDescription: List with tuples in python

description: List with tuples in python


code:
terms = [[float(x) for x in term.as_coeff_exponent(z)] for term in G_F.as_ordered_terms()]
terms.sort(key=lambda x: x[1])
terms

rawDescription: Getting a list of coefficient/exponent pairs in sympy


code:
def faces(n):
    def iter_faces():
        f = [0] * n
        for i in range(n):
            for x in (-1, 1):
                f[i] = x
                yield tuple(f)
            f[i] = 0
    return list(iter_faces())

rawDescription: What is the pythonic way of generating this type of list? (Faces of an n-cube)


code:
import  glob, shutil, os.path

# glob.glob returns a list with all pathes according to the given pattern
for path in glob.glob("music_folder/*.mp3"):

     # os.path.dirname gives the directory name, here it is "music_folder"
     dirname = os.path.dirname(path)

     # example: 01_artist_name_-_album_title_-_song_title_somethingelse.mp3
     # split returns "_song_title_somethingelse.mp3"
     interesting = path.split("-")[2]

     # titlepart is a list with ["song", "title"], the beginning "_" and the
     # 'somehting' string is removed by choosing the slice 1:-1
     titlepart = interesting.split("_")[1:-1]

     # capitalize converts song -> Song, title -> title
     # join gluest both to "Song_Title"
     new_name = "_".join(p.capitalize() for p in titlepart)+".mp3"

     # shutil.move renames the given file
     shutil.move(path, os.path.join(dirname, new_name))

rawDescription: File Renaming by Convention - All within a folder


code:
import itertools
a = []
seed = (0,1,2,3)
for c in itertools.combinations_with_replacement(range(4), 6):
    valid = True
    for i in range(4):
        if c.count(i) > 4:
            valid = False
            break
    if valid:
        a.append(c+seed)
a

rawDescription: itertools cominbations with replacement with limitations

description: Itertools cominbations with replacement with limitations


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

fig, axes = plt.subplots(nrows=2, ncols=2, sharey=True, sharex=True)
for i, ax in enumerate(axes.flat, start=1):
    ax.set(aspect=1)
    ax.plot(np.arange(0, i * 4, i))

plt.show()

rawDescription: matplotlib: aspect ratio in subplots with various y-axes

description: Matplotlib: aspect ratio in subplots with various y-axes


code:
Hexagon(0,0,10)
HexagonRing(0,0,10,1)
HexagonRing(0,0,10,2)
HexagonRing(0,0,10,3)

rawDescription: Draw a hexagon tessellation animation in Python


code:
import re

blacklist = re.compile('|'.join([re.escape(word) for word in B]))

rawDescription: Delete item from list if it contains a substring from a "blacklist"


rawDescription: Python What's type for open(file)

description: Python What's type for open(file)


code:
import datetime

delta = datetime.timedelta(days=dayslater, hours=hourslater, minutes=minuteslater)
alarmTime = datetime.datetime.now() + delta

rawDescription: What is the best way to handle datetime value overflow


code:
for ingredient in sandwich:
    ingredient = ingredient.strip()

rawDescription: How to normalize text in a list that is itself in a column of Pandas dataframe?

description: Normalize text in a list that is itself in a column of Pandas dataframe


code:
def mixins(*args):
    return type('Foo', args, {})

rawDescription: Factory function to create a class with an unknown number of mixins


code:
from copy import deepcopy

def merge(a, b):
    if isinstance(b, dict) and isinstance(a, dict):
        a_and_b = a.viewkeys() & b.viewkeys()
        every_key = a.viewkeys() | b.viewkeys()
        return {k: merge(a[k], b[k]) if k in a_and_b else
                   deepcopy(a[k] if k in a else b[k]) for k in every_key}
    return deepcopy(b)

rawDescription: Merging hierarchy of dictionaries in Python


rawDescription: How to customize display url after jquery POST?

description: Customize display url after jquery POST


code:
l = [1,2,3,4,5]
TheFunction(*l)
l = [1,2]
TheFunction(*l)

rawDescription: Function call with a variable number of parameters?


code:
matches = []
for ip1 in phase1_hits:
    subdict1 = phase1_hits[ip1]
    internal_ips = [subdict1['internal']] + subdict1['internal_additional']
    hits = subdict1['hits']
    color_list = subdict1['list']
    for ip2 in phase2_hits:
        subdict2 = phase2_hits[ip2]
        phase2_ips = subdict2['ip.dst'] + subdict2['ip.src']
        overlap = [i for i in internal_ips if i in phase2_ips]
        if len(overlap) > 0:
            temp = (ip1, overlap, hits, color_list, ip2, [i for i in phase2_ips if i in overlap])
            matches.append(temp)

rawDescription: Extracting Data From Multiple Dictionaries


code:
if field not in stats:
    stats[field] = very_expensive_initializer(field)

rawDescription: How do I initialize values in a dictionary?

description: Initialize values in a dictionary


code:
import re

new_value = "'1999-12-31'"
with open("temp.txt") as infile:
    data = infile.read()
    data = re.sub(r"(var beforeDate = new Date\().*?(\))", "\\1"+new_value+"\\2", data)
with open("output.txt", "w") as outfile:
    outfile.write(data)

rawDescription: Replacing a string whose surroundings are known but the value of the string is not known Python


code:
def varied_step_range(start,stop,stepiter):
    step = iter(stepiter)
    while start < stop:
        yield start
        start += next(step)

rawDescription: Change step value in range function

description: Change step value in range function


code: r = requests.post(url, data=data, verify = os.path.join(appdata,'cacert.pem'))

rawDescription: Error using Requests in a frozen app

description: Error using Requests in a frozen app


code:
magic_reverse_mapping = {}

def magic_register(cls):
   magic_reverse_mapping[cls._internal_attribute] = cls
   return cls

@magic_register
class A(object):
    _internal_attribute = 'A attribute'

afoo = magic_reverse_mapping['A attribute']()

rawDescription: Reverse mapping class attributes to classes in Python


code:
# On Python 2x
probabilityDict['Root'].iterkeys()
probabilityDict['Root'].itervalues()
probabilityDict['Root'].iteritems()

# On Python 3x
probabilityDict['Root'].keys()
probabilityDict['Root'].values()
probabilityDict['Root'].items()

rawDescription: Convert list to dictionary with probability in each entity


code:
def foo(func, *args, **kwargs):
    retVal = None
    retries = 5
    success = False
    while retries > 0 and success == False:
        try:
            retVal = func(*args, **kwargs)
            success = True
        except:
            retries = retries-1
            logging.info('Facebook put_event timed out.  Retrying.')
    return success, retVal

rawDescription: Python: Pass execution statement as function parameter


code:
def admin_method_attributes(**outer_kwargs):
    """ Wrap an admin method with passed arguments as attributes and values.
    DRY way of extremely common admin manipulation such as setting short_description, allow_tags, etc.
    """
    def method_decorator(func):
        for kw, arg in outer_kwargs.items():
            setattr(func, kw, arg)
        return func
    return method_decorator

# usage
class ModelAdmin(admin.ModelAdmin):
    @admin_method_attributes(short_description='Some Short Description', allow_tags=True)
    def my_admin_method(self, obj):
        return '''obj.id'''

rawDescription: How can I rename a column label in Django Admin for a field that is a method//property?

description: Rename a column label in Django Admin for a field that is a method//property


code:
def threaded_rmq():
    channel.queue_declare(queue="my_queue")
    logging.info('consumer ready, on my_queue')
    channel.basic_consume(consumer_callback, queue="my_queue", no_ack=True)
    channel.start_consuming()

rawDescription: Easiest way to push RabbitMQ events to browser using WebSockets in Python?


code:
class F:
    def __dir__(self):
            return set(['1'])

dir(F())

rawDescription: Implementing `__dir__` in Python: Does it need to return a list and does the list need to be sorted?


code:
key = operator.itemgetter(0)
grouped = itertools.groupby(sorted(fileListCode, key=key), key=key)
[(i, {k[1]: n for n, k in enumerate(j, 1)}) for i, j in grouped]

rawDescription: How can I split a 2D array into an array with unique values and a dictionary?

description: Split a 2D array into an array with unique values and a dictionary


code: trip["Num"] = trip["Num"] + 1

rawDescription: Python: How to access the dictionary that has specific key-values in a list


code:
import os
import csv

def go():
    search_strings = ('value1', 'value2', 'value3')    # target strings to be found in file name
    data = []
    folder = folderentry.get()  # reads path for 'folder'

    for path, subdirs, files in os.walk(folder):
        for name in files:
            data.append([s if s in name else 'NOT FOUND!' for s in search_strings])

    with open('some.csv', 'wb') as f:
        writer = csv.writer(f)
        writer.writerows(data)

rawDescription: Write multiple lists into csv. file in Python


code:
cls, method = dictionary_map[key]
getattr(cls(), method)()

rawDescription: How to create dictionary mapping keys to class methods and initialize this object in the same time

description: Create dictionary mapping keys to class methods and initialize this object in the same time


code:
import numpy as np
from scipy.spatial.distance import pdist, squareform, correlation
x = np.random.rand(2000, 20)
np.allclose(pair_correlation(x), squareform(pdist(x, "correlation")))

rawDescription: Calculate special correlation distance matrix faster


code: 'some test	'.replace('', '')

rawDescription: Stripping chars in python

description: Stripping chars in python


code: [a+x+c for a, b, c in (m.groups() for m in it) for x in b.split(',')]

rawDescription: Python - Parse strings with variable repeating substring


rawDescription: Output object attributes and values in alphabetical order


code:
rx = re.compile('(.)(?=(.))')
x = rx.finditer("abcdefgh")
[y.groups() for y in x]

rawDescription: Overlapping matches with finditer() in Python


code:
def layers(data):
    try:
        keys = [data.keys()]
    except ValueError:
        return
    rest = layers(next(iter(data.values())))
    return keys + rest if rest else keys

rawDescription: Parsing Python Dictionary Keys

description: Parsing Python Dictionary Keys


code:
val = 0
for i in range(len(arrs)):
    if i % 20 == 0:
        arrs[i][5] = str( int(arr[i][5]) + val )
        val += 1

rawDescription: increment 1 in the sixth column after every twenty lines

description: Increment 1 in the sixth column after every twenty lines


code:
class AllDoneException(Exception): pass

def worker():
    #insert some working process here using selenium webdriver
    print("Worker happened!")
    global first_time_happening
    if first_time_happening:
        first_time_happening = False
    elif not first_time_happening:
        global relay_to_timer
        relay_to_timer = scheduler.enter(5, 2, timer)
        try:
            scheduler.run()
        except AllDoneException:
            pass

rawDescription: Having trouble quitting sched.scheduler module?


code: obj = brain.getObject()

rawDescription: Plone: How to change ownership of an archetype content?


code:
testmapping = {'dog': 1, 'cat': 2, ' ': 0}
testmapping[x]

rawDescription: possible to set variable with multiple if statments?

description: Possible to set variable with multiple if statments


code:
with open('thefile.csv', 'w') as f:
    writer = csv.writer(f)
    while True:
        row = cursor.fetchone()
        if row is None: break
        writer.writerow(row)

rawDescription: Convert the mysql table details to an Excel (.xls) or comma separated file (.csv) using Python


code:
import re
input_keys = [key for key in request.POST if re.match(r"^inputs_", key)]

rawDescription: Select POST/GET parameters with regular expression


code:
class Foo(object):
    def __init__(self):
        self.bar = [1,2,3]

    @property
    def baz(self):
        return max(self.bar)

rawDescription: Set Python class variable equal to the output of class function


rawDescription: An elegant way to make a 2d array with all possible columns


code:
if section == 'A':
    if tickets >= 0 and tickets <= 300:
        getSectionA(tickets)
    else:
        while tickets < 0 or tickets > 300:
            print('Invalid, enter a value from  0 to 300')
            tickets = int(input('Enter amount of tickets sold: '))
        getSectionA(tickets)

rawDescription: Values aren't stored in python program

description: Values aren't stored in python program


code: dict((key, sum(d[key] for d in dictList)) for key in dictList[0])

rawDescription: How to create single Python dict from a list of dicts by summing values with common keys?

description: Create single Python dict from a list of dicts by summing values with common keys


rawDescription: Change specific value in CSV file via Python


code:
d = {}
e = d
assert d == {}     # Empty dictionaries equal each other
assert d is not {} # .. but are not identical
assert d is e      # d and e refer to the same object

rawDescription: A Few Python questions

description: A Few Python questions


rawDescription: Python bokeh modify axis scale

description: Python bokeh modify axis scale


code:
from models import session, Address
addr = Address('123 Test St.', 'Sometown', 'NY', '12345', some_user)
addr.insert(session)

rawDescription: Python: define object variable without initialization


code:
np.count_nonzero(simfourty48 > 350)
np.count_nonzero(simfourty48 > 510)

rawDescription: How do I get a count of values in an array, in a range or above a threshold value?

description: Get a count of values in an array, in a range or above a threshold value


code:
from . import pep8 # optional "as pep8"
# The rest of your code, using this pep8 module.

rawDescription: Elegant/proper way to wrap a python module


code:
import colorsys
import numpy as np
from matplotlib import pyplot as plt

def get_color(color):
    for hue in range(color):
        hue = 1. * hue / color
        col = [int(x) for x in colorsys.hsv_to_rgb(hue, 1.0, 230)]
        yield "#{0:02x}{1:02x}{2:02x}".format(*col)

x = 0.3 * np.array(range(40))

color = get_color(15)

for group in range(15):
    # generates a collection of points
    y = np.exp2(x + 0.5 * group)
    # fit to a polynomial
    z = np.polyfit(x, y, 6)
    p = np.poly1d(z)

    acolor = next(color)

    plt.scatter(x, y, color=acolor, marker='o')
    plt.plot(x, p(x), color=acolor, linestyle='dashed', label=str(group))

plt.legend()
plt.xlim((0, 15))
plt.show()

rawDescription: Color and Line writing using MatPlotLib

description: Color and Line writing using MatPlotLib


rawDescription: python `list` and `for` return different results

description: Python `list` and `for` return different results


code: dict([(e,loadings[e]) for e in loadings])

rawDescription: Python scoping issue with dictionary comprehension inside class level code


code:
from collections import Counter

with open('test.csv','r') as in_file, open('final.csv','w') as out_file:
    seen = set() # set for fast O(1) amortized lookup
    lines = Counter(file.readlines())
    seen = set(k for k in lines if lines[k] == 1)
    for itm in seen:
        out_file.write(itm)

rawDescription: Python extract unique values from CSV

description: Python extract unique values from CSV


code:
# really verbose
new = {}
for (key, value) in data:
    if key in new:
        new[key].append( value )
    else:
        new[key] = [value]

# easy with setdefault
new = {}
for (key, value) in data:
    group = new.setdefault(key, []) # key might exist already
    group.append( value )

# even simpler with defaultdict
new = defaultdict(list)
for (key, value) in data:
    new[key].append( value ) # all keys have a default already

rawDescription: Use cases for the 'setdefault' dict method


rawDescription: Have Win32 MessageBox appear over other programs


rawDescription: pythonic way to parse/split URLs in a pandas dataframe

description: Pythonic way to parse/split URLs in a pandas dataframe


code:
class UserResource(ModelResource):
    usersubs = fields.ToManyField('test.api.UserSubResource', attribute = 'usersubs', full=True, null=True)
    specialUsersub = fields.ToOneField('test.api.UserSubResource', attribute = 'special_user_sub', full=True, null=True)
    class Meta:
        object_class = User
        fields = ['username', 'first_name', 'last_name', 'password', 'email']
        detail_allowed_methods = ['get', 'post', 'put']
        authentication = Authentication()
        authorization = Authorization()
        queryset = User.objects.all()
        resource_name = 'users'
        excludes = ['id']

class UserSubResource(ModelResource):
    amigos= fields.ToManyField('test.api.UserSubResource', attribute = 'amigos', null=True)
    class Meta:
        object_class = UserSub
        fields = ['title']
        detail_allowed_methods = ['get', 'post', 'put', 'patch']
        authentication = Authentication()
        authorization = Authorization()
        always_return_data = True
        queryset = UserSub.objects.all()
        resource_name = 'usersub'
        excludes = ['id']

rawDescription: Django Tastypie Many to Many (self) field update using a PATCH or PUT request?


rawDescription: Extract tuple from list

description: Extract tuple from list


rawDescription: import csv matrix to create a weighted and directed network in networkx python

description: Import csv matrix to create a weighted and directed network in networkx python


code:
class Subscriber(models.Model):
    ...
    def __unicode__(self):
        return u'%s: %s' % (self.name, self.application_number)

rawDescription: Django admin site : Help needed

description: Django admin site : Help needed


code:
class Tab(QWidget):
    def __init__(self, parent=None):
        super(Tab, self).__init__(parent)
        self.editThisLine = QLineEdit()
        self.aButton = QPushButton("Stuff")
        self.aButton.clicked.connect(self.runThisWhenButtonClicked)
        ...

    def runThisWhenButtonClicked(self):
        print(self.editThisLine.text())

rawDescription: Python PyQt - How to edit a variable in another function when function is run multiple times


code: outarr = np.column_stack((out))

rawDescription: Find indices of specific rows in a 3d numpy array


rawDescription: stripping the zeros in csv with python

description: Stripping the zeros in csv with python


code: d = [[] for x in xrange(n)]

rawDescription: Python: fastest way to create a list of n lists


code:
cookies = [{
    "name": "username",
    "value": "USERNAME",
    "domain": "domain",
    "path": "path",
    "secure": "secure",
}]

rawDescription: Python import cookies

description: Python import cookies


rawDescription: How to solve sin(z)=2 in Sympy?

description: Solve sin(z)=2 in Sympy


rawDescription: Sorting Counter collection in python with secondary term (tie breaker)


rawDescription: Function name convention for "convert foo to bar"


code: registry.registerAdapter(lambda o: 'adapter from data to IA', [data], IA)

rawDescription: How to use zope.interface.directlyProvides with instances of build in types (dict, string, ...)

description: Use zope.interface.directlyProvides with instances of build in types (dict, string, ...)


code:
import foo
import bar.foo
import sys

rawDescription: I'd like Python to look into a package first for imports


code:
@admin.register(Cliente)
class ClienteAdmin(admin.ModelAdmin):
    list_display = [
        'ragione_sociale', 'forma_societaria', 'titolare', 'partita_iva', ]
    list_filter = ['forma_societaria', ]
    search_fields = ['ragione_sociale', ]
    inlines = [RecapitoInline, SedeInline]
    def get_form(self, request, obj=None, **kwargs):    # Just added this override
        form = super(ClienteAdmin, self).get_form(request, obj, **kwargs)
        form.base_fields['prodotto'].widget.can_add_related = False
        return form

rawDescription: Django 1.7 removing Add button from inline form


rawDescription: Reorganise list in list python

description: Reorganise list in list python


rawDescription: Create new list based on values taken from sublist


code:
def store_roots(start, end):
    with open("rootsPrefixesSuffixes.txt") as fs:
        lst = [line.split()[0] for line in map(str.strip, fs)
                       if '#' not in line and line]
        return lst, dict.fromkeys(lst[start:end], 0)

lst, sfx_dict = store_roots(22, 30) # List, SuffixList

rawDescription: count suffixes appearing in the word file

description: Count suffixes appearing in the word file


code:
from zope.component.hooks import getSite
from collective.zamqp.interfaces import IMessageArrivedEvent
from plone.dexterity.utils import createContentInContainer

@grok.subscribe(ICreateItemMessage, IMessageArrivedEvent)
def createItem(message, event):
    """Consume item creation message"""

    portal = getSite()
    obj = createContentInContainer(
        portal, "Document", checkConstraints=True, **message.body)

    message.ack()

rawDescription: Using RabbitMQ with Plone - Celery or not?


code:
word_counts =pd.DataFrame(X.todense(),columns = vect.get_feature_names()).T.sum(axis=1)
word_counts.sort(ascending=False)
word_counts[:3]

rawDescription: Python/Pandas aggregation combined with NLTK


code:
from collections import defaultdict
d = defaultdict(int)
for anchor_tag in soup.findAll('a'):
  d[anchor_tag.contents[0]] += 1

d

rawDescription: Python: Fetching and parsing text from html files


code:
sigmoid_grad(-500)
logistic._pdf(-500)

rawDescription: Numpy Pure Functions for performance, caching


rawDescription: Matching everything after series of hyphens


rawDescription: Getting Raw Binary Representation of a file in Python


code:
upsample_factor = 2
c = b(np.linspace(0,x,x*upsample), np.linspace(0,y,y*upsample))

rawDescription: Array from interpolated plot in python

description: Array from interpolated plot in python


code: mydict = {}

rawDescription: How does the dictionary add keys in python?


code: table_1=pd.crosstab(f_dtflt.EW_REGIONCOLLSITE, f_dtflt.COLLECTION_DATE.apply(lambda x: x.strftime("%y %m_%b %y")), margins=True)

rawDescription: Pandas Crosstab: Change Order of Columns That Are Named as Formatted Dates (mmm yy)


rawDescription: Python Bit Operations on a list of Int's


code:
import tkinter as tk
root = tk.Tk()
w = 500 # replace 500 with the width of your photo
h = 600 # replace 600 with the height of your photo
canvas = tk.Canvas(root, width=w, height=h)
canvas.pack()
img = tk.PhotoImage(file='vault_ext.gif')
img_ref = canvas.create_image(w//2, h//2, image=img)

rawDescription: Simplest code to import a .gif

description: Simplest code to import a .gif


code:
convert = {"tab1_name": tab1, "tab2_name": tab2, "tab3_name": tab3}
a = mainframe.tab(mainframe.select(), "text")
b = convert[a]
w = b.winfo_reqwidth()
h = b.winfo_reqheight()
mainframe.configure(width=w, height=h)

rawDescription: Convert string into a Tkinter notebook frame


code:
tmp = something.action
something.action = apply(something.action)

rawDescription: Is there any way you can get back to the original function?


code: df.loc[:, 'Auto loan']

rawDescription: Pandas: parse merged header columns from Excel


code:
# assuming isinstance(data, bytes) is True
with open('foo.csv', 'wb') as f:
    f.write(data)

rawDescription: Saving a string with \x01 characters to disk


rawDescription: Continuous Fourier Transform with Python / Sympy (Analytical Solution)


rawDescription: How to pass a function to another function in order to create an action listener

description: Pass a function to another function in order to create an action listener


code:
def findLetters(wordlist):
    return [word for word in wordlist if all(letter in 'abcdef' for letter in word)]

rawDescription: Python text file. Finding strings that contain only characters 'abcdef'


code:
# Copy up to this stage
combined_data = combined_data.groupby(level=0).filter(filter_func)

# My code from here
combined_data.reset_index(inplace=True, drop=False)
combined_data.rename(columns={'index': 'Date'}, inplace=True)

# This line assumes you want datetime, ignore if you don't
combined_data['Date'] = pd.to_datetime(combined_data['Date'])

result = pd.melt(combined_data, id_vars=['Date'])

result['Currency'] = 'GBP'

rawDescription: Restructuring Dataframe

description: Restructuring Dataframe


code:
my_list = [
 {'delim_type': '', 'arcana_list': 'Life 3'},
 {'delim_type': ' and/or ', 'arcana_list': 'Mind 3'},
 {'delim_type': ' and/or ', 'arcana_list': 'Prime 3'},
]

rawDescription: Reduce a list of 2-dicts, to a list unique by the one item, concatenating the other items in python3


rawDescription: Fetch specific data from JSON

description: Fetch specific data from JSON


code: report = "Total gold acquired: " + str(self.gold_total())

rawDescription: Why does this python method return a memory address?


code:
from lepl import (AnyBut, Digit, Drop, Eos, Integer, Letter,
                  NON_GREEDY, Regexp, Space, Separator, Word)

# EBNF
# name = ( letter | "_" ) , { letter | "_" | digit } ;
name = Word(Letter() | '_',
            Letter() | '_' | Digit())
# words = word , space+ , word , { space+ , word } ;
# two or more space-separated words (non-greedy to allow comment at the end)
words = Word()[2::NON_GREEDY, ~Space()[1:]] > list
# value = integer | word | words  ;
value = (Integer() >> int) | Word() | words
# comment = "#" , { all characters - "\n" } , ( "\n" | EOF ) ;
comment = '#' & AnyBut('\n')[:] & ('\n' | Eos())

with Separator(~Regexp(r'\s*')):
    # statement = name , "=" , value ;
    statement = name & Drop('=') & value > tuple
    # suite     = "{" , { comment | statement } , "}" ;
    suite     = Drop('{') & (~comment | statement)[:] & Drop('}') > dict
    # block     = name , suite ;
    block     = name & suite > tuple
    # config    = { comment | block } ;
    config    = (~comment | block)[:] & Eos() > dict

from pprint import pprint

pprint(config.parse(open('input.cfg').read()))

rawDescription: What's the best way(error proof / foolproof) to parse a file using python with following format?


rawDescription: Variables not receiving amounts? Python

description: Variables not receiving amounts? Python


code: nb.tab(nb.select(), "text")

rawDescription: Finding the currently selected tab of Ttk Notebook


code:
summed_values = 0
for post in post:
    ... # rest of code snippet you posted
    summed_values += value

rawDescription: How to add up scraped strings representing integers?

description: Add up scraped strings representing integers


code:
def f_wo_append():
    '''Function without append'''
    P = 75
    numcustomers = 0
    for person in popn.people:
        person.customer = iscust = person.utility >= P
        numcustomers += iscust
    return numcustomers

rawDescription: Increasing speed of python code

description: Increasing speed of python code


code:
import os
mypid = os.getpid()

rawDescription: Killing all python interpreters but the one which launches kill command


rawDescription: numpy.array boolean to binary?

description: Numpy.array boolean to binary


code:
df2 = df.reindex(multi_index)
df2.sortlevel(level=1)

rawDescription: Re-index dataframe by new range of dates


code: coeffs[len(coeffs) - k - 1]

rawDescription: Energy for 1-D wavelet in Python

description: Energy for 1-D wavelet in Python


code: func=make_model(a=3, b=1)

rawDescription: Dynamically define a function

description: Dynamically define a function


code: set(self, key, val, time=0, min_compress_len=0)

rawDescription: Which Python module to use for Memcached?


code:
new = {}
for key, value in old.items():
    values = []
    for isspace, group in itertools.groupby(value, key=lambda x: x[0] == " "):
        if not isspace:
            letters, coords = zip(*group)
            values.append(("".join(letters), next(iter(coords))))
    new[key] = values

rawDescription: Python dictionary merge values and delete previous


code: from __future__ import division

rawDescription: Python Percentage-complete calculator

description: Python Percentage-complete calculator


code:
def getRandom(self, start, end, quantity):
    temp = range(start, end)
    return [random.choice(temp) for _ in range(quantity)]

rawDescription: Python: Preventing elements being appended to the same list over and over


code:
import foo

generatedClass = superClassCreator()
setattr(foo, generatedClass.__name__, generatedClass)

rawDescription: python how to register dynamic class in module

description: Python how to register dynamic class in module


code:
import csv
import StringIO
results = "sku\tdelivered-price-gbp\tdelivered-price-euro\tid\n32850238\t15.53\t35.38\t258505\n10395850\t35.21\t46.32\t3240582\n"

data = {entry['sku']: [entry['delivered-price-gbp'], entry['delivered-price-euro']]
        for entry in csv.DictReader(StringIO.StringIO(results), delimiter='\t')}
print(data)

rawDescription: Building a dictionary from a tab delimited file in a pythonic way


code: driver_value = (model_value + adder)*scaler

rawDescription: Paraboloid optimization requiring scaling


rawDescription: Extract all URLS from a page matching a particular pattern in BeautifulSoup


code:
import ctypes  # An included library with Python install.
ctypes.windll.user32.MessageBoxA(0, "Your text", "Your title", 1)

rawDescription: How can I create a simple message box in Python?

description: Create a simple message box in Python


code:
data = struct.pack('2I',12, 30)
[hex(ord(c)) for c in data]

rawDescription: How to display a byte array as hex values

description: Display a byte array as hex values


code:
class MyContainerClass(list):
    """ For now, I'm inheriting from list. Is this my problem? """
    def __init__(self, data_array):
        list.__init__(self, data_array)

    def my_method(self):
        """
        Will act on entire list, but I want it to act on only what's
        returned by the slice (which may be the entire list in some cases).
        """
        return "a, ".join([str(_i) for _i in self])

    def __getitem__(self, index):
        retval = super(MyContainerClass, self).__getitem__(index)
        if isinstance(index, slice):
            retval = type(self)(retval)
        return retval

    def __getslice__(self, i, j):
        # Python 2 built-in types only
        return self.__getitem__(slice(i, j))

rawDescription: Python: Is is possible to have a class method that acts on a slice of the class?


code: Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1})

rawDescription: python - find the occurrence of the word in a file

description: Python - find the occurrence of the word in a file


code:
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'a':[23, 13, 20, 17, 14, 22],
                   'b':[25, 21, 19, 14, 23, 11]},
                   index=['bob', 'john', 'paul', 'david', 'michael', 'neil'])

a_vals = df.a
b_vals = df.b
ind = np.arange(df.shape[0])
width = 0.35

# Set the colors
colors = ['b', 'g', 'r', 'c', 'm', 'y', 'g']

def autolabel(bars):
    # attach some text labels
    for bar in bars:
        width = bar.get_width()
        ax.text(width*0.95, bar.get_y() + bar.get_height()/2,
                '%d' % int(width),
                ha='right', va='center')

# make the plots
fig, ax = plt.subplots()
a = ax.barh(ind, a_vals, width, color = colors) # plot a vals
b = ax.barh(ind + width, b_vals, width, color = colors, alpha=0.5)  # plot b vals
ax.set_yticks(ind + width)  # position axis ticks
ax.set_yticklabels(df.index)  # set them to the names
ax.legend((a[0], b[0]), ['a', 'b'], loc='center right')

autolabel(a)
autolabel(b)

plt.show()

rawDescription: different colors for rows in barh chart from pandas dataframe python

description: Different colors for rows in barh chart from pandas dataframe python