code:
class Entry(object):
    __slots__ = ('id', 'name')  # save some memory
    def __init__(self, id, name):
        self.id = id
        self.name = name
    def __eq__(self, other):
        if not isinstance(other, Entry): return NotImplemented
        return self.id == other.id
    def __hash__(self):
        return id(self.id)
    def __repr__(self):
        return '<{0}({1[0]!r}, {1[1]!r})>'.format(type(self).__name__, self)
    def __getitem__(self, index):
        return getattr(self, ('id', 'name')[index])

rawDescription: Searching for tuples in python based on the first part


code: start(Etest)

rawDescription: Multiple arguments in parameter in def_name() and function's name as variable


code:
from nltk.tag import pos_tag
from nltk.tokenize import word_tokenize
pos_tag(word_tokenize("John's big idea isn't all that bad."))

[('John', 'NNP'),
("'s", 'POS'),
 ('big', 'JJ'),
 ('idea', 'NN'),
 ('is', 'VBZ'),
 ("n't", 'RB'),
 ('all', 'DT'),
 ('that', 'DT'),
 ('bad', 'JJ'),
 ('.', '.')]

rawDescription: Part of speech tagging and entity recognition - python


code:
# Distributions to check, shape constants were taken from the examples on the scipy.stats distribution documentation pages.
DISTRIBUTIONS = [
    stats.alpha(a=3.57, loc=0.0, scale=1.0), stats.anglit(loc=0.0, scale=1.0),
    stats.arcsine(loc=0.0, scale=1.0), stats.beta(a=2.31, b=0.627, loc=0.0, scale=1.0),
    stats.betaprime(a=5, b=6, loc=0.0, scale=1.0), stats.bradford(c=0.299, loc=0.0, scale=1.0),
    stats.burr(c=10.5, d=4.3, loc=0.0, scale=1.0), stats.cauchy(loc=0.0, scale=1.0),
    stats.chi(df=78, loc=0.0, scale=1.0), stats.chi2(df=55, loc=0.0, scale=1.0),
    stats.cosine(loc=0.0, scale=1.0), stats.dgamma(a=1.1, loc=0.0, scale=1.0),
    stats.dweibull(c=2.07, loc=0.0, scale=1.0), stats.erlang(a=2, loc=0.0, scale=1.0),
    stats.expon(loc=0.0, scale=1.0), stats.exponnorm(K=1.5, loc=0.0, scale=1.0),
    stats.exponweib(a=2.89, c=1.95, loc=0.0, scale=1.0), stats.exponpow(b=2.7, loc=0.0, scale=1.0),
    stats.f(dfn=29, dfd=18, loc=0.0, scale=1.0), stats.fatiguelife(c=29, loc=0.0, scale=1.0),
    stats.fisk(c=3.09, loc=0.0, scale=1.0), stats.foldcauchy(c=4.72, loc=0.0, scale=1.0),
    stats.foldnorm(c=1.95, loc=0.0, scale=1.0), stats.frechet_r(c=1.89, loc=0.0, scale=1.0),
    stats.frechet_l(c=3.63, loc=0.0, scale=1.0), stats.genlogistic(c=0.412, loc=0.0, scale=1.0),
    stats.genpareto(c=0.1, loc=0.0, scale=1.0), stats.gennorm(beta=1.3, loc=0.0, scale=1.0),
    stats.genexpon(a=9.13, b=16.2, c=3.28, loc=0.0, scale=1.0), stats.genextreme(c=-0.1, loc=0.0, scale=1.0),
    stats.gausshyper(a=13.8, b=3.12, c=2.51, z=5.18, loc=0.0, scale=1.0), stats.gamma(a=1.99, loc=0.0, scale=1.0),
    stats.gengamma(a=4.42, c=-3.12, loc=0.0, scale=1.0), stats.genhalflogistic(c=0.773, loc=0.0, scale=1.0),
    stats.gilbrat(loc=0.0, scale=1.0), stats.gompertz(c=0.947, loc=0.0, scale=1.0),
    stats.gumbel_r(loc=0.0, scale=1.0), stats.gumbel_l(loc=0.0, scale=1.0),
    stats.halfcauchy(loc=0.0, scale=1.0), stats.halflogistic(loc=0.0, scale=1.0),
    stats.halfnorm(loc=0.0, scale=1.0), stats.halfgennorm(beta=0.675, loc=0.0, scale=1.0),
    stats.hypsecant(loc=0.0, scale=1.0), stats.invgamma(a=4.07, loc=0.0, scale=1.0),
    stats.invgauss(mu=0.145, loc=0.0, scale=1.0), stats.invweibull(c=10.6, loc=0.0, scale=1.0),
    stats.johnsonsb(a=4.32, b=3.18, loc=0.0, scale=1.0), stats.johnsonsu(a=2.55, b=2.25, loc=0.0, scale=1.0),
    stats.ksone(n=1e+03, loc=0.0, scale=1.0), stats.kstwobign(loc=0.0, scale=1.0),
    stats.laplace(loc=0.0, scale=1.0), stats.levy(loc=0.0, scale=1.0),
    stats.levy_l(loc=0.0, scale=1.0), stats.levy_stable(alpha=0.357, beta=-0.675, loc=0.0, scale=1.0),
    stats.logistic(loc=0.0, scale=1.0), stats.loggamma(c=0.414, loc=0.0, scale=1.0),
    stats.loglaplace(c=3.25, loc=0.0, scale=1.0), stats.lognorm(s=0.954, loc=0.0, scale=1.0),
    stats.lomax(c=1.88, loc=0.0, scale=1.0), stats.maxwell(loc=0.0, scale=1.0),
    stats.mielke(k=10.4, s=3.6, loc=0.0, scale=1.0), stats.nakagami(nu=4.97, loc=0.0, scale=1.0),
    stats.ncx2(df=21, nc=1.06, loc=0.0, scale=1.0), stats.ncf(dfn=27, dfd=27, nc=0.416, loc=0.0, scale=1.0),
    stats.nct(df=14, nc=0.24, loc=0.0, scale=1.0), stats.norm(loc=0.0, scale=1.0),
    stats.pareto(b=2.62, loc=0.0, scale=1.0), stats.pearson3(skew=0.1, loc=0.0, scale=1.0),
    stats.powerlaw(a=1.66, loc=0.0, scale=1.0), stats.powerlognorm(c=2.14, s=0.446, loc=0.0, scale=1.0),
    stats.powernorm(c=4.45, loc=0.0, scale=1.0), stats.rdist(c=0.9, loc=0.0, scale=1.0),
    stats.reciprocal(a=0.00623, b=1.01, loc=0.0, scale=1.0), stats.rayleigh(loc=0.0, scale=1.0),
    stats.rice(b=0.775, loc=0.0, scale=1.0), stats.recipinvgauss(mu=0.63, loc=0.0, scale=1.0),
    stats.semicircular(loc=0.0, scale=1.0), stats.t(df=2.74, loc=0.0, scale=1.0),
    stats.triang(c=0.158, loc=0.0, scale=1.0), stats.truncexpon(b=4.69, loc=0.0, scale=1.0),
    stats.truncnorm(a=0.1, b=2, loc=0.0, scale=1.0), stats.tukeylambda(lam=3.13, loc=0.0, scale=1.0),
    stats.uniform(loc=0.0, scale=1.0), stats.vonmises(kappa=3.99, loc=0.0, scale=1.0),
    stats.vonmises_line(kappa=3.99, loc=0.0, scale=1.0), stats.wald(loc=0.0, scale=1.0),
    stats.weibull_min(c=1.79, loc=0.0, scale=1.0), stats.weibull_max(c=2.87, loc=0.0, scale=1.0),
    stats.wrapcauchy(c=0.0311, loc=0.0, scale=1.0)
]

rawDescription: What do all the distributions available in scipy.stats look like?


code:
XX, YY = numpy.atleast_2d(x, y)
YY = YY.T # transpose to allow broadcasting
ZZ = XX + YY

rawDescription: Mesh grid functions in Python (meshgrid mgrid ogrid ndgrid)


code:
def example(*multi_values, **kwargs):
    var1 = kwargs.pop("var1", None)
    var2 = kwargs.pop("var2", None)
    var3 = kwargs.pop("var3", None)
    if kwargs:
        raise TypeError("Unknown keyword arguments")
    # whatever

rawDescription: How to use optional named parameters and *mulit_vars in same function call?

description: Use optional named parameters and *mulit_vars in same function call


rawDescription: Replicating Javascript bitwise operation in Python


code:
MyModel.objects.all()
MyModel.objects.extra(select={'cnt': 'SELECT COUNT (*) FROM myapp_mymodel B WHERE B.text LIKE "%%" || myapp_mymodel.text || "%%"'}, where=['cnt = 1'])

rawDescription: How to compare field values across instances in a Django queryset?

description: Compare field values across instances in a Django queryset


code:
def PID(value):
    ''' Mixin Class Generator For Polymorphic Identity Inheritance '''
    class MixinClassForPolymorphicIdentityInheritance:
        __mapper_args__ = {'polymorphic_identity': value}
    return MixinClassForPolymorphicIdentityInheritance

rawDescription: SQLAlchemy Class Decoration for __mapper_args__


code: x.vtype = GRB.BINARY

rawDescription: Gurobi, How to change a continuous variable to a binary variable


code:
from cms.menu_bases import CMSAttachMenu
from menus.base import NavigationNode
from menus.menu_pool import menu_pool
from django.utils.translation import ugettext_lazy as _

menuNodes = []

class EventMenu(CMSAttachMenu):
    name = _("Event Sub-Menu")
    def get_nodes(self, request):
        return menuNodes
menu_pool.register_menu(EventMenu)

def add_menu_node(text, url):
    # only add a given url once
    if len(list(n for n in menuNodes if n.url == url)) == 0:
        menuNodes.append(NavigationNode(text, url, 1 + len(menuNodes), 0))
        menu_pool.clear()

rawDescription: Get view pk from django-cms CMSAttachMenu


code:
def time_pgcopy(dat, table, binary):
    print('Processing copy object for ' + table)
    tstart = datetime.now()
    if binary:
        cpy = prepare_binary(dat)
    else:  # text
        cpy = prepare_text(dat)
    tendw = datetime.now()
    print('Copy object prepared in ' + str(tendw - tstart) + '; ' +
          str(cpy.tell()) + ' bytes; transfering to database')
    cpy.seek(0)
    if binary:
        curs.copy_expert('COPY ' + table + ' FROM STDIN WITH BINARY', cpy)
    else:  # text
        curs.copy_from(cpy, table)
    conn.commit()
    tend = datetime.now()
    print('Database copy time: ' + str(tend - tendw))
    print('        Total time: ' + str(tend - tstart))
    return

time_pgcopy(data, 'num_data_text', binary=False)
time_pgcopy(data, 'num_data_binary', binary=True)

rawDescription: Use binary COPY table FROM with psycopg2


rawDescription: How can I pythonically print and write the same string (two operations on one object)

description: Pythonically print and write the same string (two operations on one object)


code: print([dict2.get(item, dict1.get(item)) for item in dict1.keys() | dict2])

rawDescription: Match lists and write result to new list


code: len(set(map(tuple,M)))==len(M)

rawDescription: How to test if all rows are distinct in numpy

description: Test if all rows are distinct in numpy


code:
words = {}
for i, line in enumerate(input_file, 1):
    words[line.strip()] = i

rawDescription: For line in : not returning all lines

description: For line in : not returning all lines


code:
tolerance = 0.05
matches = {gene_id: gene_master[(gene_master.div(genes.ix[gene_id].values) - 1)
                    .abs()
                    .lt(tolerance)
                    .gt(0)  # prevents inclusion of identical gene.
                    .all(axis=1)].index.tolist()
           for gene_id in genes.index}

rawDescription: Pandas Dataframe Iterating

description: Pandas Dataframe Iterating


code:
import os.path
for dir, file in zip(directories, files):
    print(os.path.join(dir, file))                      # for directories, files

rawDescription: Python loops with multiple lists?

description: Python loops with multiple lists


code:
class check1:
    def helloworld(self):
        self.j = 5

check_instance=check1()
print (hasattr(check_instance,'j'))  #False -- j hasn't been set on check_instance yet
check_instance.helloworld()          #add j attribute to check_instance
print(check_instance.j)  #prints 5

rawDescription: using variables in class functions in another class (python)

description: Using variables in class functions in another class (python)


code:
import struct

def invert(x):
    return bytes(c ^ 255 for c in x)

def tobin(x):
    binx = struct.pack('>d', x)
    if binx > b'\x80': #negative
        return invert(binx)
    else:
        return struct.pack('>d', -x)

data = [float('-inf'), -100.0, -2.0, -.9, -.1, -0.0,
    0.0, .1, .9, 2.0, 100.0, float('inf'), float('nan')]

print(sorted(data, key=tobin))
#[-inf, -100.0, -2.0, -0.9, -0.1, -0.0, 0.0, 0.1, 0.9, 2.0, 100.0, inf, nan]

rawDescription: How to efficiently serialize 64-bit floats so that the byte arrays preserve natural numeric order?

description: Efficiently serialize 64-bit floats so that the byte arrays preserve natural numeric order


rawDescription: wxPython - How to get the ID of a widget when you passed in -1?

description: WxPython - How to get the ID of a widget when you passed in -1


code:
class MyFormClass(forms.Form):
    def __init__(self, *args, **kwargs):
        self.is_add = kwargs.pop("is_add", False)
        super(MyFormClass, self).__init__(*args, **kwargs)

    @property
    def helper(self):
        helper = FormHelper()
        helper.layout = Layout(
            FormActions(
                Submit('submit', 'Add Thing' if self.is_add else 'Edit thing', css_class='btn-primary')
            )
        )
        return helper

rawDescription: How to change Submit button text from a view in crispy-forms?

description: Change Submit button text from a view in crispy-forms


code:
from nltk.util import ngrams

lm = {n:dict() for n in range(1,6)}
def extract_n_grams(sequence):
    for n in range(1,6):
        ngram = ngrams(sentence, n)
        # now you have an n-gram you can do what ever you want
        # yield ngram
        # you can count them for your language model?
        for item in ngram:
            lm[n][item] = lm[n].get(item, 0) + 1

rawDescription: extracting n grams from huge text

description: Extracting n grams from huge text


code: ['Example text here', 'Example text here', 'Example text here']

rawDescription: Regular expression to return list in Python?


code:
acceptable = 'scale_', 'shift_', 'reject_', 'dev_'
kwds = {key[:-1]: {k.split('_', 1)[-1]: v for k, v in kwargs.items() if k.startswith(key)} for key in acceptable}

rawDescription: Split one dict into many dicts by startswith condition


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

delta = 0.025
x = np.arange(-3.0, 3.0, delta)
y = np.arange(-2.0, 2.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
# difference of Gaussians
Z = 10.0 * (Z2 - Z1)

plt.figure()
N = 24
CS = plt.contour(X, Y, Z, N)
plt.clabel(CS, inline=1, fontsize=10)
plt.title('{} levels'.format(N))
plt.xlim(0, 3)
plt.ylim(0, 2)
plt.show()

rawDescription: Adding extra contour lines using matplotlib 2D contour plotting


code:
def read_utf(self, callback):
    def _utf_length(data):
        length = struct.unpack('>H', data)[0]
        self.stream.read_bytes(length, _read_utf)
    def _read_utf(data):
        callback(data)
    self.stream.read_bytes(2, _utf_length)

rawDescription: Tornado's equivalent to native socket's recv() method


code: sample = kernel.resample(size=50000)

rawDescription: Different integration results using Monte Carlo vs scipy.integrate.nquad


code:
a = Foo((5,))
b = Foo((5,))
c = a + b # BAD
c.flags.owndata
c = Foo((5,))
c[:] = a + b # BETTER
c.flags.owndata
np.add(a, b, out=c) # BEST
c.flags.owndata

rawDescription: Transfer ownership of numpy data

description: Transfer ownership of numpy data


code:
def argmax(some_list):
    return max(enumerate(some_list), key=lambda x:x[1])[0]

rawDescription: Calculating the gap between pairs of twin primes in python


code:
from subprocess import Popen, PIPE, DEVNULL, STDOUT

p = Popen(["mysql", "-u", "root", "-p", password],
          stdin=PIPE, stdout=DEVNULL, stderr=STDOUT)
p.communicate(b"exit")
if p.returncode != 0:
    print('incorrect password')

rawDescription: Testing connection to MySQL with Python using subprocess


code: handler_map={rects1[0]: HandlerSquare(), rects2[0]: HandlerSquare()}

rawDescription: matplotlib: make legend keys square

description: Matplotlib: make legend keys square


code:
res = g["comp"].value_counts().unstack(1)
res.columns = ['det%s' % i for i, _ in enumerate(df.columns)]

rawDescription: Turn dataframe into frequency list with two column variables in Python


rawDescription: Get complete list of all possible Class Attributes


code:
from flask import current_app

class DataIOExtension(object):
    def __init__(self, app=None):
        self._app_cache = {}

        if app is not None:
            self.init_app(app)

    def init_app(self, app):
        # an instance is created once per app
        self._app_cache[app] = DataIO()

    @property
    def client(self):
        return self._app_cache[current_app._get_current_object()]

    def __getattr__(self, name):
        return getattr(self.client, name)

data_service = DataIOExtension()
data_service.init_app(app)

@app.route('/hello')
def hello():
    full_list = data_service.get_case_list()

rawDescription: Can't access attribute set on g object in request


code: hsh = reduce(lambda x, y: ord(x) + ord(y), list(s))

rawDescription: What is the equivalent C/C++ loselose algorithm in python


code:
import asyncio
from concurrent.futures import ProcessPoolExecutor
import functools
import time

def do_work(eventloop, value):
    future = eventloop.run_in_executor(executor, functools.partial(process_action, value))
    future.add_done_callback(run_job_success)

def process_action(value):
    print("Processing %i" % value)
    time.sleep(1)
    return value

def run_job_success(f):
    print("Success : %s" % f.result())

if __name__ == "__main__":
    executor = ProcessPoolExecutor(max_workers=3)
    loop = asyncio.get_event_loop()
    for i in range(5):
        loop.call_soon(do_work, loop, i)
    loop.run_forever()

rawDescription: Running asyncio in two different threads to process actions on-the-fly


code:
from itertools import chain
list(chain(*zip(l0, l1, l2)))

rawDescription: Merge sliced lists

description: Merge sliced lists


code:
for key, value in ITEMS.items():
    #print value
    print(key, len(filter(bool, value)))

rawDescription: Counting how many values were attributed to a key an a python (3.2) dictionary


code:
import heapq

def key(kv):
    return kv[0]

top_per_partition = rdd.mapPartitions(lambda iter: heapq.nlargest(n, iter, key))
top_per_partition.sortByKey().zipWithIndex().filter(lambda xi: xi[1] < n).keys()

rawDescription: Return RDD of largest N values from another RDD in SPARK


code:
__all__ = []

import pkgutil
import inspect

for loader, name, is_pkg in pkgutil.walk_packages(__path__):
    module = loader.find_module(name).load_module(name)

    for name, value in inspect.getmembers(module):
        if name.startswith('__'):
            continue

        globals()[name] = value
        __all__.append(name)

rawDescription: Python: how to import from all modules in dir?


code:
funcA = make_func('A', ctypes.uint64)
funcB = make_func('B', bool)

rawDescription: Automatic code generation in python

description: Automatic code generation in python


code:
import inspect

# First import the embed function
from IPython.terminal.embed import InteractiveShellEmbed
from IPython.config.loader import Config

# Configure the prompt so that I know I am in a nested (embedded) shell
cfg = Config()
prompt_config = cfg.PromptManager
prompt_config.in_template = 'N.In <\\#>: '
prompt_config.in2_template = '   .\\D.: '
prompt_config.out_template = 'N.Out<\\#>: '

# Messages displayed when I drop into and exit the shell.
banner_msg = ("\n**Nested Interpreter:\n"
"Hit Ctrl-D to exit interpreter and continue program.\n"
"Note that if you use %kill_embedded, you can fully deactivate\n"
"This embedded instance so it will never turn on again")
exit_msg = '**Leaving Nested interpreter'

# Wrap it in a function that gives me more context:
def ipsh():
    ipshell = InteractiveShellEmbed(config=cfg, banner1=banner_msg, exit_msg=exit_msg)

    frame = inspect.currentframe().f_back
    msg   = 'Stopped at {0.f_code.co_filename} at line {0.f_lineno}'.format(frame)

    # Go back one level!
    # This is needed because the call to ipshell is inside the function ipsh()
    ipshell(msg,stack_depth=2)

rawDescription: Step-by-step debugging with IPython

description: Step-by-step debugging with IPython


code: foo, bar = find_text(x, y)

rawDescription: How to return elements of a list as variables?

description: Return elements of a list as variables


code:
import re

data = '''
12asA   1  A    4  A  330
12asB   1  B    4  B  330
12caA   1  A    5  A  260
12e8H   1  H    1  H  113   1  H  114  H  212   H  213  H  214  (2)
12e8L   1  L    1  L  107   1  L  108  L  211   L  212  L  214  (3)
'''
lines = filter(None, data.split('\n')) # filter to remove blank lines

def process_line(line):
    line = re.sub(r'D0\d|F0\d|-', '', line)
    for char in "'[],":
        line = line.replace(char, '')
    seq = line.split()
    if len(seq) == 6:
        return '{}|{}-{}'.format(seq[0], seq[3], seq[5])
    elif len(seq) == 16:
        return '{}|{}-{},{}-{}'.format(seq[0], seq[3], seq[5], seq[8], seq[10])

result = [process_line(line) for line in lines]
for r in result:
    print(r)

rawDescription: difficulty in selecting elements in a python list

description: Difficulty in selecting elements in a python list


code: ingredientList = {'flour': [500,"grams"], 'tomato':[10], 'mozzarella' :[250, "grams"]}

rawDescription: Python: How to store multiple values for one dictionary key


code:
def addTable (self, newTable, **kwargs):
    setattr(self, newTable, PrettyTable(kwargs.values()))

rawDescription: Using Class method to add a Class variable


code:
from wand.color import Color
from wand.drawing import Drawing
from wand.image import Image

# -size 320x100 xc:lightblue
with Image(width=320, height=100, background=Color('lightblue')) as image:
    with Drawing() as draw:
        # -font Candice
        draw.font = 'Candice'
        # -pointsize 72
        draw.font_size = 72.0
        draw.push()
        # -fill black
        draw.fill_color = Color('black')
        # -draw "text 28,68 'Anthony'"
        draw.text(28, 68, 'Anthony')
        draw.pop()
        draw.push()
        # -fill white
        draw.fill_color = Color('white')
        # -draw "text 25,65 'Anthony'"
        draw.text(25, 65, 'Anthony')
        draw.pop()
        draw(image)
    # font_shadow.jpg
    image.save(filename='font_shadow.jpg')

rawDescription: python wand: creating text dropshadow

description: Python wand: creating text dropshadow


code:
for i in range(LOWER, UPPER + 1):
    fname = file_name+str(i)+".txt"

    cur_resfile = np.genfromtxt(fname, delimiter = ",", skiprows = 1)

    m_ongoing += cur_resfile.clip(0,1)

rawDescription: Numpy change elements based on threshold and then do element by element addition


code:
import posix
posix.open('fifo', posix.O_RDWR)

rawDescription: Can I open a named pipe on Linux for non-blocked writing in Python?

description: Open a named pipe on Linux for non-blocked writing in Python


code:
blist = []
for i in range(1, height+1):
    tmpList = []
    for j in range(1, width+1):
        btn = tk.Button(playfield, text = '   ')
        tmpList.append(btn)

        def handler(event, i=i, j=j):
            return floodfill(event, field, blist, j, i)
        btn.bind('<ButtonRelease-1>', handler)
        btn.bind('<Button-3>', iconToggle)
        btn.grid(row=i-1, column=j-1)

    blist.append(tmpList)

rawDescription: hiding a widget according to x, y coordinates

description: Hiding a widget according to x, y coordinates


code:
True in {1: 'foo'}
1 in {True: 'foo'}

rawDescription: Adding 1 to a set containing True does not work


code:
def create_inner_list(string):
    prev = 0
    current_list = mainlist = []
    for each in string:
        if int(each) <= prev:
            if current_list is mainlist:
                current_list = []
                mainlist.append(current_list)
        else:
            current_list = mainlist
        prev = int(each)
        current_list.append(prev)
    return mainlist

rawDescription: python list within list - why is the sublist repeated

description: Python list within list - why is the sublist repeated


code: grid_dict[(x, y)] = data

rawDescription: Is there something in python i can use to represent any positive whole number


code:
formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
                              datefmt='%Y-%m-%d %H:%M:%S')

rawDescription: Print timestamp for logging in Python

description: Print timestamp for logging in Python


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

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


code:
from bisect import bisect

class Meeting:
    # save about 500 bytes of memory
    #  by not having a __dict__
    __slots__ = ("start", "end")

    def __init__(self, start, end):
        self.start = start
        self.end = end

    def __lt__(self, other):
        return self.end < other.end

def max_meetings(meetings):
    meetings.sort()    # Meeting.__lt__ provides a natural sort order by meeting.end

    # -1 is just a "lower than any actual time" gatepost value
    lst = [-1]

    for m in meetings:
        # find the longest chain of meetings which this meeting can follow
        i = bisect(lst, m.start)

        if i == len(lst):
            # new most-meetings value
            lst.append(m.end)
        elif m.end < lst[i]:
            # new earliest finish-time for
            lst[i] = m.end

    # what is the most meetings we can attend?
    # print(lst)
    return len(lst) - 1

rawDescription: Schedule Maximum Number Tasks That have Fixed Start and End times


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

def main():
    x, y = np.loadtxt('spectrum.dat').T

    logx, logy = np.log(x), np.log(y)
    smooth_log = detrend_zero_phase(logx, logy)
    smooth = np.exp(smooth_log)

    fig, ax = plt.subplots()
    ax.loglog(x, y, 'k-')
    ax.loglog(x, smooth, 'r-')
    plt.show()

def zero_phase(y):
    # Low-pass filter...
    b, a = signal.butter(3, 0.05)

    # Filtfilt applies the filter twice to avoid phase shifts.
    return signal.filtfilt(b, a, y)

def detrend_zero_phase(x, y):
    # Fit a second order polynomial (Can't just use scipy.signal.detrend here,
    # because we need to know what the trend is to add it back in.)
    model = np.polyfit(x, y, 2)
    trend = np.polyval(model, x)

    # Apply a zero-phase filter to the detrended curve.
    smooth = zero_phase(y - trend)

    # Add the trend back in
    return smooth + trend

main()

rawDescription: Smooth a curve in python with no error at the boundaries?


code:
class C(object):
    f1 = f1

rawDescription: What is the difference between a function, an unbound method and a bound method?


code:
def merge_lists(l1, l2):
    result = []
    d1 = convert_list(l1)
    d2 = convert_list(l2)
    for index, l2_nums in d2.items():
        if index not in d1:
            #no matching index
            continue
        l1_nums = d1[index]
        sub_nums = [l2_num for l2_num in l2_nums if l2_num - 1 in l1_nums]
        if sub_nums:
            result.append([index] + sorted(list(sub_nums)))
    return result

rawDescription: Merge two lists based on condition

description: Merge two lists based on condition


code:
songs = {'artists': [
                        {'name': 'Adele', 'titles': ['Hello', ]},
                        {'name': 'Rihanna', 'titles': ['Umbrella', ]}
                    ]
        }

rawDescription: How do you iterate tuple values in a dictionary for django context

description: Iterate tuple values in a dictionary for django context


code:
r['guiprop'] = urllib.quote(u'groups|merged|unattached')
r['guiuser'] = urllib.quote(u'$cammer')

rawDescription: Python url construction: escape characters other than regular letters


code:
fs = [lambda: x for x in range (10) ]
for f in fs: print (f () )

rawDescription: For Python 3.3, how can I make a list of functions using one lambda statement?


code:
def outer(**outer_kwargs):
    def inner(**inner_kwargs):
        kwargs = inner_kwargs or outer_kwargs
        return kwargs
    return inner

rawDescription: How to pass kwargs to another kwargs in python?

description: Pass kwargs to another kwargs in python


code:
MERGE|temp_st_rx_wk_str_ip_rpt
SELECT|rx_ov_ord_excep_str_sku
SELECT|ndc
SELECT|fiscal
SELECT|store
SELECT|dss_saf_user01.rx_ov_ord_exclu_str
SELECT|rx_osv_invoice_str_ndc
DROP|temp_extract;
CREATE|temp_build_extract
SELECT|temp_st_rx_wk_Str_ip_rpt

rawDescription: Extract pattern from sql script

description: Extract pattern from sql script


code:
entry_list = [child for child in root_widget.winfo_children()
              if isinstance(child, Entry)]

rawDescription: How do I check if any entry boxes are empty in Tkinter?

description: Check if any entry boxes are empty in Tkinter


code:
import csv

def getnext(csvfile, key=lambda row: int(row[0], 16)):
    row = csvfile.next()
    return key(row),row

with open('file1.dat','rb') as inf1, open('file2.dat','rb') as inf2, open('merged.dat','wb') as outf:
    a = csv.reader(inf1, delimiter='|')
    b = csv.reader(inf2, delimiter='|')
    res = csv.writer(outf, delimiter='|')

    a_key, b_key = -1, 0
    try:
        while True:
            while a_key < b_key:
                a_key, a_row = getnext(a)
            while b_key < a_key:
                b_key, b_row = getnext(b)
            if a_key==b_key:
                res.writerow(a_row + b_row[1:])
    except StopIteration:
        # reached the end of an input file
        pass

rawDescription: Compare files line by line to see if they are the same, if so output them


code:
@sequify
def map_and_discard_none(func, it):
    for elem in imap(func, it):
        if elem is not None:
            yield elem

rawDescription: `map`-like function preserving sequence-type


code:
from Tkinter import *
import Tkinter
global B4
top = Tkinter.Tk()
B1 = Tkinter.Button(top, text ="circle", relief=RAISED,\
                         cursor="circle")
B2 = Tkinter.Button(top, text ="plus", relief=RAISED,\
                         cursor="plus")
B3 = Tkinter.Button(top, text=u"good !",relief=RAISED,\
                         cursor="plus")
def initialise(self):
    global B4
    self.grid()
    B4 = Tkinter.Button(self,text=u"Click me !",
                                command=OnButtonClick(self))
    B4.grid(column=1,row=0)
def OnButtonClick(self):
    print( "You clicked the button" )

initialise(top)
B1.pack()
B2.pack()
B3.pack()
B4.pack()
#initialise()
top.mainloop()

rawDescription: python:Merging button yields "not defined"

description: Python:Merging button yields "not defined"


code:
from django.conf.urls.defaults import *

urlpatterns = patterns('',
    url(r'^search/', 'search.views.search', name="search"),
)

rawDescription: Logging Django Haystack search keyword

description: Logging Django Haystack search keyword


rawDescription: Linear Regression with 3 input vectors and 4 output vectors?


code: print (lambda x: (lambda f: lambda x: f(f,x))(lambda f, x: x if str(x) == str(x)[::-1] else f(f, x + int(str(x)[::-1])))(x + int(str(x)[::-1])))(29)

rawDescription: Generating list until certain condition is met using a single line


code: (x for l in range(2, len(arr)) for x in itertools.combinations(arr, l))

rawDescription: In Python how do I create variable length combinations or permutations?


code:
import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

def func(event):
    print("You hit return.")
root.bind('<Return>', func)

def onclick():
    print("You clicked the button")

button = tk.Button(root, text="click me", command=onclick)
button.pack()

root.mainloop()

rawDescription: Can't figure out how to bind the enter key to a function in tkinter


code:
d = {value:{} for key,value in dict1.items()}
d['Three']['a'] = 1

rawDescription: Set the name of dictionary in Python

description: Set the name of dictionary in Python


rawDescription: mutable objects changed in-place means what?

description: Mutable objects changed in-place means what


code:
def SaveToFile(fileToSave, textToSave):
    with open(fileToSave, "r+") as datafile:
        for line in datafile:
            if textToSave in line:
                break
        else:
            datafile.write(textToSave + '\n')

rawDescription: Python - How to check if the text is in a file txt?


code:
connection = MySQLdb.connect('localhost', 'root', '*****', 'test')
cur = connection.cursor()

unit_ids = ('0A1', '0A2', '0A3', '0A4')
attr = 'sample'

cur.execute("""SELECT COUNT(*) FROM test WHERE attribute = %s AND unit_id IN %s""", (a, unit_ids))

rawDescription: How can I prevent extra quotations being inserted into MySQLdb statement from Python?

description: Prevent extra quotations being inserted into MySQLdb statement from Python


code:
foo = (1) #integer
foo = (1,) #1 element tuple
foo = 1, #1 element tuple

rawDescription: Work with tuple of dictionaries

description: Work with tuple of dictionaries


code: other_matrix = [[0 for x in range(2)] for x in range(2)]

rawDescription: Python - Erroneous result for two different matrixes in nested for loop


code:
def f(objects):
    list_type = "string_x"
    other = "string_y"
    return [(list_type if isinstance(x[1], list) else other, x[1])
            for x in objects]

rawDescription: python optimize function without looping

description: Python optimize function without looping


rawDescription: Transpose and copy column data to each row


code:
import cmd
import signal
from player import MPlayer

class PlayCommand(cmd.Cmd, object):

    def __init__(self, *args, **kwargs):

        # (...)

        self.p = MPlayer()
        signal.signal(signal.SIGUSR1, self._song_end_handler)

    def _song_end_handler(self, signum, frame):
        print('SIGUSR1!!!!!!!!!!111!1')
        # HERE: Fetch new track URL
        self.p.load()

rawDescription: Python parallelization of tasks (event loop?)


code:
a = [[2,3,4,5],[1,3,2,7]]
[[sum(sublist[i:i+2]) for i in xrange(0,len(sublist),2)] for sublist in a]

rawDescription: How to add paired values in sub-lists separately?

description: Add paired values in sub-lists separately


code:
parser = argparse.ArgumentParser(
    prog='PROG',
    formatter_class=PreserveWhiteSpaceWrapRawTextHelpFormatter)
parser.add_argument('--foo', type=int, default=42, help="""Just Normal Bullet Point with Some Enter in there

    1. Lorem Ipsum has been the industry's standard dummy text ever since
    2. the 1500s, when an u
    3. Lorem Ipsum is simply dummy text of the printing and typesetting industry

Some other Bullet POint

    - Ipsum is simply dummy text of the printing and typesetting industry
    - Ipsum is simply dummy text of the printing and typesetting industry

And No BulletPoint
    Ipsum is simply dummy text of the printing and typesetting industry
    Ipsum is simply dummy text of the printing and typesetting industry
    """)
parser.add_argument('bar', nargs='*', default=[1, 2, 3], help="BAR! FOO! Lorem Ipsum is simply dummy text of the printing and typesetting industry.")
parser.print_help()

rawDescription: Python argparse.RawTextHelpFormatter with line wrap


code:
for i, v in enumerate(a):
    a[i]= v+1

rawDescription: Pythonic Referenced For Loop

description: Pythonic Referenced For Loop


code:
q = SequencedQueue()
d1 = q.get()
d2 = q.get()
# Nothing in particular happens
q.put(1, "second result")
# d1 fires with "first result" and afterwards d2 fires with "second result"
q.put(0, "first result")

rawDescription: Twisted wait for event in loop

description: Twisted wait for event in loop


code:
# want to train using fewer features so remove 'BodyLength'
basic_feature_names.remove('BodyLength')

clf.fit(fea[basic_feature_names], orig_data['OpenStatusMod'].values)

rawDescription: Ignore a column while building a model with SKLearn


code: f = open(server,"a")

rawDescription: Python: Write to new file line

description: Python: Write to new file line


code:
for entry in scantree(entry.path):
    yield entry

rawDescription: How do I use os.scandir() to return DirEntry objects recursively on a directory tree?

description: Use os.scandir() to return DirEntry objects recursively on a directory tree


code:
def PassengerForm(exclude_list, *args, **kwargs):
    class MyPassengerForm(ModelForm):
        class Meta:
            model = Passenger
            exclude = exclude_list

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

    return MyPassengerForm()

form = PassengerForm(('field1', 'field2'))

rawDescription: Dynamically update ModelForm's Meta class


rawDescription: combining and looping through lists python

description: Combining and looping through lists python


code: segments

rawDescription: Slice Array Given Range from another array in Python


code:
array = [4,2,7,1,1,2]
rankdict = {v: k for k,v in enumerate(sorted(set(array)))}
rankdict
ranked = [rankdict[a] for a in array]
ranked

rawDescription: Ranking data in python without numpy

description: Ranking data in python without numpy


code:
def autocorrelation(x):
    """
    Compute autocorrelation using FFT
    """
    x = np.asarray(x)
    N = len(x)
    x = x-x.mean()
    s = fft.fft(x, N*2-1)
    result = np.real(fft.ifft(s * np.conjugate(s), N*2-1))
    result = result[:N]
    result /= result[0]
    return result

rawDescription: Statistical Scaling of autocorrelation using numpy.fft


code:
ln, = plot(x, y)  # plot actually returns a list of artists, hence the ,
im = imshow(Z)

rawDescription: Matplotlib - How to remove a specific line or curve


code:
from pyspark.sql import Row
from pyspark.sql.types import StructType, StructField, LongType

row = Row("char")
row_with_index = Row("char", "index")

df = sc.parallelize(row(chr(x)) for x in range(97, 112)).toDF()
df.show(5)

## char
## a
## b
## c
## d
## e

# This part is not tested but should work and save some work later
schema  = StructType(
    df.schema.fields[:] + [StructField("index", LongType(), False)])

indexed = (df.rdd # Extract rdd
    .zipWithIndex() # Add index
    .map(lambda ri: row_with_index(*list(ri[0]) + [ri[1]])) # Map to rows
    .toDF(schema)) # It will work without schema but will be more expensive

indexed.where(col("index").inSet(indexes))

rawDescription: PySpark DataFrames - way to enumerate without converting to Pandas?


code:
import operator
import math
import numpy as np

#example dict has N keys (integers), each value is a list of n random HxW 'arrays', in list form:
test_shape = 10, 2, 4, 4          # small example for testing
timing_shape = 100, 5, 48, 48     # bigger example for timing
N, n, H, W = timing_shape
example = dict(enumerate(np.random.rand(N, n, H, W).tolist()))

def my_init(master_dict, normalization=np.exp):
    full_tensor = np.concatenate(master_dict.values())
    centering = np.mean(full_tensor, 0)
    return {key: my_center(np.array(value), centering, normalization)
                     for key,value in master_dict.iteritems()} #use iteritems here
    #self.normalization = normalization

def my_normalize(a):
    a -= a.min(1, keepdims=True).min(2, keepdims=True)
    a /= a.max(1, keepdims=True).max(2, keepdims=True)
    return a

def my_center(arrays, centering_factor, normalization_scheme):
    """
    Centering scheme for arrays
    """
    arrays -= centering_factor
    return normalization_scheme(my_normalize(arrays))

#### sethMMorton's original improvement ####

def seth_init(master_dict, normalization = np.exp):
    """
    master_dict should be a dictionary mapping classes to lists of matrices

    example = {
        "cats": [[[]...], [[]...]...],
        "dogs": [[[]...], [[]...]...]
    }

    have to be python lists, not numpy arrays

    normalization represents the 0-1 normalization scheme used. Defaults to simple linear
    """
    full_tensor = np.array(reduce(operator.add, master_dict.values()))
    centering = np.sum(full_tensor, axis=0)/len(full_tensor)
    return {key: seth_center(np.array(value), centering, normalization) for key,value in master_dict.items()}
    #self.normalization = normalization

def seth_center(list_of_arrays, centering_factor, normalization_scheme):
    """
    Centering scheme for arrays
    """
    def seth_normalize(a):
        a_min = np.min(a)
        return (a - a_min) / (np.max(a) - a_min)
    arrays = list_of_arrays - centering_factor
    return normalization_scheme([seth_normalize(array) for array in arrays])

#### Original code, by slater ####

def slater_init(master_dict, normalization = lambda x: math.exp(x)):
    """
    master_dict should be a dictionary mapping classes to lists of matrices

    example = {
        "cats": [[[]...], [[]...]...],
        "dogs": [[[]...], [[]...]...]
    }

    have to be python lists, not numpy arrays

    normalization represents the 0-1 normalization scheme used. Defaults to simple linear
    """
    normalization = np.vectorize(normalization)
    full_tensor = np.array(reduce(operator.add, master_dict.values()))
    centering = np.sum(np.array(reduce(operator.add, master_dict.values())), axis=0)/len(full_tensor)
    return {key: slater_center(np.array(value), centering, normalization) for key,value in master_dict.items()}
    #self.normalization = normalization

def slater_center(list_of_arrays, centering_factor, normalization_scheme):
    """
    Centering scheme for arrays
    """
    arrays = list_of_arrays - centering_factor
    slater_normalize = lambda a: (a - np.min(a)) / (np.max(a) - np.min(a))
    return normalization_scheme([slater_normalize(array) for array in arrays])

rawDescription: Numpy normalization code is strangely slow


code: execfile("proga.py", {})

rawDescription: Python: How do you repeatedly call programs from a base program?


code:
import theano
import theano.tensor as T

xx = T.fvector()
yy = (xx.reshape((-1, 3)).mean(axis=1).reshape((-1, 1)) * T.ones(3)).ravel()

print(yy.eval({xx: x.astype('float32')}))

rawDescription: Traversing theano vector slice by slice

description: Traversing theano vector slice by slice


rawDescription: How to make a sorted dictionary class?

description: Make a sorted dictionary class


code:
# Session is modified.
request.session['foo'] = 'bar'

# Session is modified.
del request.session['foo']

# Session is modified.
request.session['foo'] = {}

# Gotcha: Session is NOT modified, because this alters
# request.session['foo'] instead of request.session.
request.session['foo']['bar'] = 'baz'

rawDescription: Django Session Variable resetting

description: Django Session Variable resetting


code:
import platform
platform.architecture()

rawDescription: How to determine 'word' size in Python

description: Determine 'word' size in Python


code:
while True:
    stringToWrite, pauseSeconds = gatherSomeInformation()
    writeAndPause(stringToWrite, pauseSeconds)

rawDescription: How to change function parameters during runtime?

description: Change function parameters during runtime


code:
#Create the graph (see question above)
A=nx.adjacency_matrix(G, nodelist=range(N*N))
A=A.todense()

rawDescription: NetworkX: Adjacency Matrix of partially failed graphs/networks


rawDescription: SQLAlchemy relationships, when to use which relationship?


code:
from module1 import cool_func
import module2
cool_func() #module1
module2.cool_func()

rawDescription: Some confusion regarding imports in Python


code:
def generate():
    """
    CSV generator.
    """
    for i, row in enumerate(database.get_all_rows()):
        if i == 0:
            yield CSV_HEADERS

        csv_res = ','.join(row) + '\n'
        yield csv_res

rawDescription: python flask generate csv without losing first row

description: Python flask generate csv without losing first row


code:
a = '{"message":"Hello there, wayfaring stranger"}'
import json
d = json.loads(a)
d.items()

rawDescription: Pushover Acknowlage in python

description: Pushover Acknowlage in python


rawDescription: Parsing a tweet to extract hashtags into an array in Python


code:
def create(self, validated_data):
    return SearchRequest(**validated_data)

rawDescription: Django REST serializer: create object without saving


code:
from random import choice

def Number_recursive(N,initialN=None):
    initialN = initialN or N
    if N < 0:
        raise ValueError('N must be positive')
    if N == 0:
        return []
    return [[choice((0, 1)) for _ in range(initialN)]] + Number_recursive(N-1,initialN)

rawDescription: Recursive List containing Lists

description: Recursive List containing Lists


code:
a1a1a1a = letter.lower
a1a1a1 = a1a1a1a()
a1a1a = a1a1a1 in word
a1a1 = (a1a1a)
a1a = not a1a1
a1b1a1a = letter.lower
a1b1a1 = a1b1a1a()
a1b1a = a1b1a1 in guessedletters
a1b1 = (a1b1a)
a1b = not a1b1
a1 = a1a or a1b
a = (a1)
b = letter != ' '
result = a and b

rawDescription: if statement syntax - different than taught

description: If statement syntax - different than taught


code:
def sum_values(data):
    if type(data.values()[0]) != dict:
        return sum(data.values())
    else:
        return sum(sum_values(v) for v in data.values())

def depth_values(data, depth = 0):
    if depth == 0:
        return sum_values(data)
    else:
        return dict(
            (k, depth_values(v, depth-1))
            for k, v in data.items()
        )

rawDescription: Python: get a value count at various dict depths


code:
counts = group["Quality"].value_counts()
counts
counts['usefulness-useful']

rawDescription: How to perform functions over groupby results in pandas in python?

description: Perform functions over groupby results in pandas in python


code:
utc_to_local_datetime( datetime.datetime(2010, 6, 6, 17, 29, 7, 730000) )
utc_to_local_datetime( datetime.datetime(2010, 12, 6, 17, 29, 7, 730000) )

rawDescription: How to convert a python utc datetime to a local datetime using only python standard library?

description: Convert a python utc datetime to a local datetime using only python standard library


code: s = 'ABCD' + u''.join(unichr(0x2713 + i) for i in range(10))

rawDescription: How to iterate a Unicode string in Python?

description: Iterate a Unicode string in Python


code: sum( (n>>shift)&1 for shift in range(32) )

rawDescription: count the the number of 1s in its binary representation -- shift right don't work?

description: Count the the number of 1s in its binary representation -- shift right don't work


code:
global SCREEN
pygame.draw.circle(SCREEN, self.color, (self.x, self.y), self.r)
pygame.display.flip()

rawDescription: why I'm getting a square instead of a circle in pygame?

description: Why I'm getting a square instead of a circle in pygame


rawDescription: Combine two columns under one header in Numpy array


code:
import re
re.sub("\\bor", "*", "organization")

rawDescription: regular expression pattern about word boundary in python

description: Regular expression pattern about word boundary in python


code:
def even_only(iter):
    return [x for x in iter if is_even(x)]

rawDescription: even numbers python list

description: Even numbers python list


code:
class MySlottedClassMeta(type):
    def __init__(cls, name, bases, attrs):
        super(MySlottedClassMeta, cls).__init__(name, bases, attrs)

    def __new__(metacls, name, bases, attrs):
        assert "__slots__" in attrs
        attrs["_ordered_slots"] = tuple(sorted(attrs["__slots__"]))

        attrs["__init__"] = create_init(attrs["__slots__"])
        attrs["__eq__"] = create_eq()
        attrs["__str__"] = create_str()

        cls = super(MySlottedClassMeta, metacls).__new__(metacls, name, bases, attrs)
        return cls

def create_init(slots):
    args = ", ".join(slots)
    assignments = "\n    ".join("self.{0} = {0}".format(attr) for attr in slots)
    init_source = """
def __init__(self, {}):
    {}
""".format(args, assignments)
    exec(init_source, globals(), None)
    return __init__

def create_eq():
    def __eq__(self, other):
        try:
            same_slots = self._ordered_slots == other._ordered_slots
        except AttributeError:
            return False
        if not same_slots:
            return False
        return all(getattr(self, attr) == getattr(other, attr)
                for attr in self._ordered_slots)
    return __eq__

def create_str():
    def __str__(self):
        attr_values = ", ".join("{}={}".format(s, getattr(self, s)) for s in self.__slots__)
        return "{}({})".format(self.__class__.__name__, attr_values)
    return __str__

class MySlottedClassXY(object):
    __slots__ = ['x', 'y']
    __metaclass__ = MySlottedClassMeta

class MySlottedClassYX(object):
    __slots__ = ['y', 'x']
    __metaclass__ = MySlottedClassMeta

xy1 = MySlottedClassXY(x=1,y=2)
xy2 = MySlottedClassXY(1, 2)
yx = MySlottedClassYX(x=1, y=2)
print(xy1.__slots__)
print(yx.__slots__)
assert xy1 == xy1
assert xy1 == xy2
assert xy1 == yx

rawDescription: More Pythonic way to define custom __eq__ method using try, assert, except


code:
complete
vendor
per
mfg/recommend
complete

rawDescription: How to remove dates from a list in Python

description: Remove dates from a list in Python


code:
pos_charges = charges > 0
neg_charges = charges < 0
f,(ax,ax1) = plt.subplots(1,2)
ax.plot(positions[0, pos_charges], positions[1, pos_charges], 'ro ')
ax.plot(positions[0, neg_charges], positions[1, neg_charges], 'bo ')
ax.streamplot(x,y, Ex, Ey, color='k')
ax.set_aspect('equal', adjustable='box')
ax.set_title('Electric field')
ax.set_xticks([])
ax.set_yticks([])

rawDescription: Most Pythonic way to plot a vector function


code: json.dump(data, outfile)

rawDescription: Is there an easy way to edit a json file with python


code:
def __setitem__(self, key, value):
    if key in self.fields:
        self._values[key] = value
    else:
        raise KeyError("%s does not support field: %s" %\
              (self.__class__.__name__, key))

rawDescription: Scraping data without having to explicitly define each field to be scraped


code:
def factory(description):
    classDict = {"It's flat":Line("It's flat"), "It's spiky":Triangle("It's spiky"), "It's big":Rectangle("It's big")}
    return classDict[description]

rawDescription: Python virtual classes: doing it right?

description: Python virtual classes: doing it right


code:
from bs4 import BeautifulSoup

content = '''
not interested in
interesting 1
interesting 2
'''

soup = BeautifulSoup(content)
desired_tags = [tag for tag in soup.find_all('span') if 'three-project' not in tag.attrs['class']]
print(desired_tags)

rawDescription: beautifulsoup 4 multiple class values regex

description: Beautifulsoup 4 multiple class values regex


code:
y = [0, 0, 0, 0, 1, 2]
np.concatenate((np.arange(-5, 6)[None,...], np.correlate(x, y, 'full')[None,...]), axis=0)

rawDescription: Interpreting (and comparing) output from numpy.correlate


code: a.shape = a = a.reshape((a.shape[0], -1, n))

rawDescription: Block mean of numpy 2D array

description: Block mean of numpy 2D array


code: shop_id = get_shop_id(request)

rawDescription: Django Global function and variable

description: Django Global function and variable


code:
def locate(filename, s):
    with open(filename) as f:
        return [i for i, line in enumerate(f, 1) if s in line]

rawDescription: Finding string in a file

description: Finding string in a file


code:
def vowelCount(input1):
    d = {'halfVowels': [], 'mostlyConsonant': [], 'mostlyVowels': []}
    input1 = input1.split(' ')  # split sentence at spaces
    vowels = 'aeiou'
    for word in input1:
        con = 0  # reset counter for every word
        for letter in word: # iterating over the vowels would give wrong results here
            if letter in vowels:
                con += 1
        if con > len(word)-con:  # sort everythin in
            d['mostlyVowels'].append(word)
        elif con == len(word)-con:
            d['halfVowels'].append(word)
        else:
            d['mostlyConsonant'].append(word)
    return d  # return the dictionary

rawDescription: Counting vowels and appending to a dictionary


code: d

rawDescription: Python quickly hash mutable object

description: Python quickly hash mutable object


code:
[item for pair in d.iteritems() for item in pair]
[item for pair in d.viewitems() for item in pair]

rawDescription: How to convert a dictionary to a flat list?

description: Convert a dictionary to a flat list


code:
sizer_31 = wx.BoxSizer(wx.VERTICAL) # page (panel) sizer for outer border
gs = wx.GridSizer(0,4,7,7) # content sizer

for i in self.Panel_Others.keys():
    gs.Add(self.Panel_Others[i],0,wx.EXPAND|wx.ALL,5)
    # + wx.EXPAND: allow the content to fill the 'cells'
    #              (proportion is ignored here so it can be 0)
sizer_31.Add(gs,1,wx.EXPAND|wx.ALL,5)
# + 1, wx.EXPAND: allow the grid to expand to the main sizer
#                 which in turn fits to the page
self.Panel3.SetSizer(sizer_31) # set the sizer to page, not the notebook

rawDescription: wxpython Gridsizer not fitting to panel

description: Wxpython Gridsizer not fitting to panel


code:
try:
    clean_unicode = dirty_string.decode('utf-8')
except UnicodeDecodeError:
    clean_unicode = dirty_string.decode('latin-1')

rawDescription: python :same character, different behavior

description: Python :same character, different behavior


code:
import paramiko
import StringIO

my_key = """\
-----BEGIN RSA PRIVATE KEY-----
<your key here>
-----END RSA PRIVATE KEY-----"""

pkey = paramiko.RSAKey.from_private_key(StringIO.StringIO(my_key))

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='host', username='user', pkey=pkey)

...

ssh.close()

rawDescription: Embedding public key as string in Paramiko Application


code:
def getColumn(filename, column):
    results = csv.reader(open(filename), delimiter="\t")
    return [result[column] for result in results]

rawDescription: Python: Reading CSV file and plotting a scatter


code:
targ_a = ['a','b','c']
targ_b = ['d','e','f']
targ_d = ['g','h','i']
targ_c = ['j','k','l']
w = next(n for n,v in filter(lambda t: isinstance(t[1],list) and t[0].startswith('targ_'), globals().items()) if value in v)
print(w)

rawDescription: Find if value exists in multiple lists

description: Find if value exists in multiple lists


code:
with open("inp.txt", "r") as inp, open("out.txt", "w") as out:
    no_of_cases = int(inp.readline())
    for line in inp:
        a,b = map(int,line.split())
        out.write("%s\n" % (a + b))

rawDescription: Python: Reading input from a file?

description: Python: Reading input from a file


code:
import matplotlib.pyplot as plt

#add text
plt.text(0.01, 0.8, r'$\alpha > \beta$',fontsize=50)

#hide axes
fig = plt.gca()
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.draw() #or savefig

rawDescription: Render equation to .png file using Python


code: type(exit).__repr__ = lambda s: setattr(s.shell, 'exit_now', True) or ''

rawDescription: exit from ipython

description: Exit from ipython


code: cuda_env.Program('foo', Glob('*.cu'))

rawDescription: Strange behaviour appending/removing from array with SCons


code:
def movie():
    global movie_returns
    movie_returns = [movie.strip() for movie in movies_list]
    movie_explorer()
    # No return

def rand():  # No argument
    movies_list = next((globals()[v] for v in globals() if v=='movies_return'))
    rand_item = random.choice(movies_list)

rawDescription: Using name of strings in different functions


code:
[{'address': u'2a00:2384:0:208f::13',
  'hostname': u'static.abc.com',
  'ports': {80: {'reason': u'syn-ack', 'state': u'open'},
            443: {'reason': u'syn-ack',
                  'ssl_cert': u'place holder',
                  'state': u'open'}}},
 {'address': u'2a00:2384:0:208f::15',
  'hostname': u'static.xyz.com',
  'ports': {80: {'reason': u'syn-ack', 'state': u'open'},
            443: {'reason': u'syn-ack',
                  'ssl_cert': u'place holder',
                  'state': u'open'}}},
 {'address': u'2a00:2384:0:208f::16',
  'hostname': u'static.edf.com',
  'ports': {80: {'reason': u'syn-ack', 'state': u'open'},
            443: {'reason': u'syn-ack',
                  'ssl_cert': u'place holder',
                  'state': u'open'}}}]

rawDescription: Python - Iterating lists and dictionaries


code: df

rawDescription: Resample Pandas Dataframe with "bin size"/"frequency"


code: from gi.repository import Gdk

rawDescription: How to change background of textview in pygobject "gtk3"?

description: Change background of textview in pygobject "gtk3"


code: max(chain([word1],nwords),key=len)  #assuming you're comparing based on length.

rawDescription: Python: Unpack individual strings from tuple using Unpacking asterisk argument


code:
import sys
foo.__globals__ is sys.modules['test'].__dict__

rawDescription: How does from ... import ... statement import global variables


code: term = urllib.quote("'" + term + "'")

rawDescription: Enclose a variable in single quotes in Python


code:
import re
list_of_urls = [u'/home.html', u'browse_settings.html', u'browse.html?', u'test.html?uid=5415292833', u'test.html?uid=5968723334', u'test.html?uid=5968723334', u'test.html?uid=5453943714', u'test.html?uid=5453943714', u'test.html?uid=6740871094', u'test.html?uid=6740871094', u'test.html?uid=5991868792', u'test.html?uid=5991868792', u'test.html?uid=25072413', u'test.html?uid=25072413', u'test.html?uid=6739965683', u'test.html?uid=6739965683', u'test.html?uid=7272910004', u'test.html?uid=7272910004', u'test.html?uid=13179298', u'test.html?uid=13179298', u'test.html?uid=5392816266', u'test.html?uid=5392816266', u'test.html?uid=5992588819', u'test.html?uid=5992588819', u'test.html?uid=6727114420', u'test.html?uid=6727114420', u'test.html?uid=7263648884', u'test.html?uid=7263648884', u'test.html?uid=5447240210', u'test.html?uid=5447240210', u'test.html?uid=5460515002', u'test.html?uid=5460515002', u'test.html?uid=5400731231', u'test.html?uid=5400731231', u'browse.html?params=_F_18_24_GB_0___grid_1', u'/home.html?t=1374068507', u'/account_info.html', u'http://www.example.com/browse.html?params=_F_18_24_GB_0___grid_0', u'http://www.example.com/contact.html', u'/logout.html', u'#top', u'/terms_of_service.html', u'http://safety.example.com']
uid = re.compile(r"uid=(\d*)")
[match.group(1) for match in filter(None, map(uid.search, list_of_urls))]

rawDescription: Python extract value beautifulsoup regex


code:
b = B('does not raise error')
b.change_value('does not raise error')
b.value = 'raises error'

rawDescription: Discriminate between callers inside and outside class hierarchy


code:
daily_users = data2.groupby('date').uid.nunique()
daily_annotations = data2.groupby('date').count().uid
anno_per_user_perday2 = daily_annotations / daily_users.map(float)

rawDescription: Averaging over different levels in pandas


rawDescription: Pass coordinates of 2D Numpy pixel array to distance function


code:
import hashlib
import base64
p = hashlib.sha1('password')
base64.b64encode(p.digest())

rawDescription: Create a dovecot SHA1 digest using bash or python or some other linux command-line tool


code:
import os
import sys
import tarfile

def untar(path, root='/'):
    mode = 'r'
    _, ext = os.path.splitext(path)
    if ext in ('.gz', '.bz2'):
        mode += ':' + ext[1:]
    th = tarfile.open(path, mode)
    for info in th.getmembers():
        th.extract(info, root)
    th.close()

untar(sys.argv[1])

rawDescription: Move required files where they need to go


code:
def perform_create(self, serializer):
    now = timezone.now()
    serializer.save(initial_creation=now, last_changed=now)

def perform_update(self, serializer):
    serializer.save(last_changed=timezone.now())

rawDescription: When are create and update called in djangorestframework serializer?


rawDescription: Most efficient way to bin a pandas series of date strings by day/month/year?


code:
def get_unique_index():
    env.DUP_LOCKER.acquire()
    result = env.UNIQUE_ID.value
    env.UNIQUE_ID.value = result + 1
    env.DUP_LOCKER.release()
    return result

rawDescription: fabric assign unique index to each task

description: Fabric assign unique index to each task


code:
class D(B):pass

A.__subclasses__()

rawDescription: Calling class method as part of initialization


code:
Ml=M.tolil()
Ml.data
Ml.rows
[np.random.choice(x) for x in Ml.rows if x]
[np.random.choice(x.nonzero()[1]) for x in M if len(x.nonzero()[1])]

rawDescription: Efficiently select random non-zero column from each row of sparse matrix in scipy


code: figure(figsize = (10,10)) # creates a figure 10 inches by 10 inches

rawDescription: Change resolution of imshow in ipython

description: Change resolution of imshow in ipython


code: li = [line.strip()[1:-1].split() for line in file]

rawDescription: parsing a file into a list of lists

description: Parsing a file into a list of lists


code: [x[1] for x in data.dtype.descr]

rawDescription: Numpy: use dtype from genfromtxt() when exporting with savetxt()


rawDescription: Python: Suppress exponential format (i.e. 9e-10) in float to string conversion?


code: {'name': 'joe'}

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


rawDescription: Pandas - Creating a new column, the value of which increases on each occurrence of value X in an old column


rawDescription: Django Group By relation's data

description: Django Group By relation's data


code:
url(r'^film_chart_view/$', 'home.views.film_chart_view', name ='film_chart_view'),
url(r'^film_chart_view/(?P<is_random>.*)/$', 'home.views.film_chart_view', name ='film_chart_view_random'),
url(r'^random/$', 'home.views.random_person'),

def random_person(request):
    return HttpResponseRedirect(
        reverse('home.views.film_chart_view', kwargs={'is_random': '1'}) + \
        "?q=" + get_person.short
    )

rawDescription: Django optional view parameter with HttpResponseRedirect


code:
def recent_users(days=1):
    return active_users().filter(lambda u: u.last_visit > datetime.now() - timedelta(days))

rawDescription: Writing select functions for customized Pony


code:
df = pd.concat(dfs,axis=0)
df = df.groupby(df.index).mean()

rawDescription: pandas read dataframes in a loop and get the mean

description: Pandas read dataframes in a loop and get the mean


code: mask[mask] = range(1,mask.sum()+1)

rawDescription: Slicing array in regions - Python

description: Slicing array in regions - Python


rawDescription: python: how to create interactions between objects- reference to object doesn't seem to work

description: Python: how to create interactions between objects- reference to object doesn't seem to work


code:
i = 42
f = lambda i=i: i
dis.dis(f)

rawDescription: Python: lambda function behavior with and without keyword arguments?


code: [a for a, b in zip(array1, array2) if b]

rawDescription: python numpy.where function for lists

description: Python numpy.where function for lists


code:
from collections import OrderedDict

def write_roman(num):

    roman = OrderedDict()
    roman[1000] = "M"
    roman[900] = "CM"
    roman[500] = "D"
    roman[400] = "CD"
    roman[100] = "C"
    roman[90] = "XC"
    roman[50] = "L"
    roman[40] = "XL"
    roman[10] = "X"
    roman[9] = "IX"
    roman[5] = "V"
    roman[4] = "IV"
    roman[1] = "I"

    def roman_num(num):
        for r in roman.keys():
            x, y = divmod(num, r)
            yield roman[r] * x
            num -= (r * x)
            if num > 0:
                roman_num(num)
            else:
                break

    return "".join([a for a in roman_num(num)])

rawDescription: Basic Python program to convert integer to Roman numerals?


code:
class ViewBsin(generic.ListView):

    def get_queryset(self):
        queryset = super(ViewBsin, self).get_queryset()
        for obj in queryset:
            if obj.M_G and obj.M_G >= 1000:
                obj.M_KG = obj.M_G / 1000
            # Make any other changes to the obj here
            # Don't save the obj to the database -- ListView should be read only
        return queryset

rawDescription: Django : Manipulate Data in a generic.ListView


code:
df = load_data()
df.to_csv("file_name.csv")

rawDescription: scraping data from a dynamic graph using python+beautifulSoup4

description: Scraping data from a dynamic graph using python+beautifulSoup4


code:
class Foo(object):
    def __init__(self, foo='bar', spam='eggs'):
        self.foo = foo
        self.spam = spam

f = Foo()
f.__dict__

rawDescription: Automatically making a class hashable

description: Automatically making a class hashable


code:
def sample_data(n_i, n_j, z_shape) :
    x = np.random.rand(n_i, n_j) * 1000
    x.sort()
    x[:,0] = 0
    x[:, -1] = 1000
    y = np.random.rand(n_i, n_j)
    z = np.random.rand(*z_shape) * 1000
    return x, y, z

rawDescription: Scipy Fast 1-D interpolation without any loop


code:
s = "Hello"
t = "Worl"

if abs(len(s) - len(t)) > 1:
    print("string lengths differ by more than 1")

rawDescription: Fastest way to compare one string of two lengths


code:
import numpy as np
from matplotlib import use
use('AGG')
from matplotlib.pylab import *
from PySide import QtCore,QtGui
# Following are used for the generation of the image but you have your own imports so you don't need them
from matplotlib.transforms import Bbox
from matplotlib.path import Path
from matplotlib.patches import Rectangle

# Generation of the figure (you can skip all that and use your stuff)
rect = Rectangle((-1, -1), 2, 2, facecolor="#aaaaaa")
gca().add_patch(rect)
bbox = Bbox.from_bounds(-1, -1, 2, 2)

for i in range(12):
    vertices = (np.random.random((4, 2)) - 0.5) * 6.0
    vertices = np.ma.masked_array(vertices, [[False, False], [True, True], [False, False], [False, False]])
    path = Path(vertices)
    if path.intersects_bbox(bbox):
        color = 'r'
    else:
        color = 'b'
    plot(vertices[:,0], vertices[:,1], color=color)

# The conversion and display of the plot
app = QtGui.QApplication(sys.argv)
gcf().canvas.draw() # IMPORTANT!

stringBuffer = gcf().canvas.buffer_rgba() # IMPORTANT!
l, b, w, h = gcf().bbox.bounds

qImage = QtGui.QImage(stringBuffer,
                      w,
                      h,
                      QtGui.QImage.Format_ARGB32)

scene = QtGui.QGraphicsScene()
view = QtGui.QGraphicsView(scene)
pixmap = QtGui.QPixmap.fromImage(qImage)
pixmapItem = QtGui.QGraphicsPixmapItem(pixmap)
scene.addItem(pixmapItem)
view.show()

app.exec_()

rawDescription: How do I output a colormap in a scene using pyqt?

description: Output a colormap in a scene using pyqt


code:
import cStringIO
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg

fig = Figure(figsize=[4,4])
ax = fig.add_axes([.1,.1,.8,.8])
ax.scatter([1,2], [3,4])
canvas = FigureCanvasAgg(fig)

# write image data to a string buffer and get the PNG image bytes
buf = cStringIO.StringIO()
canvas.print_png(buf)
data = buf.getvalue()

# pseudo-code for generating the http response from your
# webserver, and writing the bytes back to the browser.
# replace this with corresponding code for your web framework
headers = {
    'Content-Type': 'image/png',
    'Content-Length': len(data)
    }
response.write(200, 'OK', headers, data)

rawDescription: Plot matplotlib on the Web

description: Plot matplotlib on the Web


rawDescription: How to do a non-greedy match

description: Do a non-greedy match


code:
db.define_table('mytable',
          Field('image', type='upload'))

# I do not recommend calling a table 'table' it is can be a reserved keyword

rawDescription: How can I put an image from DB table in Web2py?

description: Put an image from DB table in Web2py


code: mask = disp > disp.min()

rawDescription: Understanding the OpenCV Sample stereo_match.py code


code:
def equivalent(team1, team2):
    teams = [("Arsenal", "ARS"), ("Manchester United", "MNU", "ManUtd"), ...]
    for names in teams:
        if team1 in names and team2 in names:
            return True
    return False

rawDescription: Finding equality between different strings that should be equal


code:
def update_json_data(self, json_data=False, update_data={}):
    ''' It updates JSON data. It gets JSON data, converts it to a Python
    dictionary, updates this, and converts the dictionary to JSON data
    again. '''
    dict_data = json.loads(json_data) if json_data else {}
    dict_data.update(update_data)
    return json.dumps(dict_data, ensure_ascii=False)

def set_modifiers(self, element=False, modifiers_upd={}):
    ''' It updates the JSON modifiers with the specified data to indicate
    if a XML tag is readonly or invisible or not. '''
    if element is not False:  # Do not write only if element:
        modifiers = element.get('modifiers') or {}
        modifiers_json = self.update_json_data(
            modifiers, modifiers_upd)
        element.set('modifiers', modifiers_json)

def is_accountant(self):
    return self.env.ref(
        'my_module.group_accountant').id in \
        self.env.user.groups_id.mapped('id')

rawDescription: How to allow an user of a group to modify specific parts of a form in Odoo?

description: Allow an user of a group to modify specific parts of a form in Odoo


code:
def calc_add():
    add_result = (user_input_1 + user_input_2)
    print(add_result)

rawDescription: Issue with my 'very simple' Python Calculator


code:
df_2 = DataReader("AAPL",  "yahoo", datetime(1984,9,7), datetime(2013,10,1))
df_2

rawDescription: How to get ALL historical data from Yahoo without specifying a start date in pandas?

description: Get ALL historical data from Yahoo without specifying a start date in pandas


code: carIndex = 0 if any("VW" in car.name or "Poodle" in car.name for car in cars) else -1

rawDescription: Python: How to re-use list comprehensions after they are created in an expression


rawDescription: Blurring in PyGame

description: Blurring in PyGame


code:
from colorama import init  # pip install colorama
init(strip=not sys.stdout.isatty())  # strip colors if stdout is redirected
from termcolor import colored  # pip install termcolor

highlight = lambda s: colored(s, on_color='on_red', attrs=['bold', 'reverse'])

...
regex = re.compile("|".join(r"\b%s\b" % re.escape(w) for w in words),
                   flags=re.I if case_insensitive else 0)

for line in file:
    if regex.search(line): # line contains words
       line = regex.sub(lambda m: highlight(m.group()), line)
       yield line

rawDescription: Search for words (exact matches) in multiple texts using Python


code:
targetlines = [5, 7]
for line in lines:
    if line[0] in targetlines:
        print(line[1])

rawDescription: How to read multiple specific lines from a txt file (python)

description: Read multiple specific lines from a txt file (python)


code:
class Vector(object):
    def __init__(self, vec):
        self.data = vec[:]
    def __iter__(self):
        return iter(self.data)

Vector([1,2,3])
list(Vector([1,2,3]))

rawDescription: How to use an object with 'for-in' in python?

description: Use an object with 'for-in' in python


code:
source = """\
refs/changes/44/1025744/3
refs/changes/62/1025962/5
refs/changes/45/913745/2
"""
output = [line.split('/', 3)[-1] for line in source.splitlines()]
output[0]
output[1]

rawDescription: how to write a regex to parse refs/changes

description: Write a regex to parse refs/changes


code: html.find_all(lambda tag: tag.name == 'a' and tag.text.startswith('ABCD0000000'))

rawDescription: BeautifulSoup 4: Dealing with urls containing <br />


code:
def infinitenumbers():
    count = 0
    while True:
        yield count
        count += 1

rawDescription: list with infinite elments

description: List with infinite elments


code:
if L is not None:
    L = L.string

rawDescription: Is there a `?.` operator in Python?

description: Is there a `?.` operator in Python


code:
class Player(Collidable, Movable, Drawable, Controllable):
    pass

rawDescription: Pythonic way to have code-reuse in game Entity classes


code:
#global variables and libraries
import numpy as np

#returns cosine similairty of two vectors
def similarity(document,query):
    vectorA=np.array(document)
    vectorB=np.array(query)
    return np.dot(vectorA,vectorB)/(np.linalg.norm(vectorA)*np.linalg.norm(vectorB))

#calculate document and query similarities for all documents in corpus
def similarityForCorpus(documentList,query):
    global sim
    for doc in documentList:
        sim.append([similarity(doc,query),doc])

sim=[]
similarityForCorpus([[3,4,5],[0,8,10]],[3,4,5])

#rank similarities highest to lowest
sim.sort(reverse=True)

#print similarities
for s in sim:
    print('%0.16f %s' % (s[0], s[1]))

def similarityForCorpus(documentList,query):
    global sim
    for doc in documentList:
        sim.append(similarity(doc,query))

sim=[]
similarityForCorpus([[3,4,5],[0,8,10]],[3,4,5])

#rank similarities highest to lowest
sim.sort(reverse=True)

for s in sim:
    print('%0.16f' % (s))

rawDescription: Why does the value of a variable changes on appending to python list as a list?


code: a =  map(ord, s)

rawDescription: Converting a hexadecimal character to an int in Python


rawDescription: Logarithmic list range construction

description: Logarithmic list range construction


rawDescription: Weird string stripping

description: Weird string stripping


code:
Null = None
list1 = [(12, "AB"), (12, "AB"), (12, "CD"), (13, Null), (13, "DE"), (13, "DE")]

keys = []
for k,v in list1:
    if k not in keys:
        keys.append(k)
list2 = []
for k in keys:
    values = []
    for k2, v in list1:
        if k2 == k:
            if v not in values:
                values.append(v)
    list2.append([k] + values)

print(list2)

rawDescription: How to create a new list out of an existing list by removing duplicates and shifting values?

description: Create a new list out of an existing list by removing duplicates and shifting values


rawDescription: How do I get tag info from text?

description: Get tag info from text


code:
#!python3

import csv
import itertools

fname1 = 'file1.csv'
fname2 = 'file2.csv'
fname_out = 'output.csv'
with open(fname1, newline='') as f1,\
     open(fname2, newline='') as f2,\
     open(fname_out, 'w', newline='') as fout:

    reader1 = csv.reader(f1)
    reader2 = csv.reader(f2)
    writer = csv.writer(fout)

    for row1, row2 in itertools.zip_longest(reader1, reader2, fillvalue=['0', '0', '0']):
        row_out = [int(a) + int(b) for a, b in zip(row1, row2)]
        writer.writerow(row_out)

rawDescription: Combine data from csv files

description: Combine data from csv files


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

rawDescription: Sum Each Column of CSV file

description: Sum Each Column of CSV file


code:
import wx

class KhPanel(wx.Panel):

    def __init__(self, parent, configSet):
        wx.Panel.__init__(self, parent=parent)
        self.frame = parent
        self.configSet = configSet
        self.configWindow()

    def configWindow(self):
        gaugeWidth = (1/5.0)*self.configSet["width"]
        gaugeHeight = (1/10.0)*self.configSet["height"]
        gaugeMax = 100
        topBuffer = (8/10)*self.configSet["height"]
        itemSep = (1/16)*self.configSet["height"]

        vSizer = wx.BoxSizer(wx.VERTICAL)
        textSizer = wx.BoxSizer(wx.HORIZONTAL)
        progressSizer = wx.BoxSizer(wx.HORIZONTAL)

        configText = wx.StaticText(self, label="STUFF", style=wx.ALIGN_CENTER)
        configProgressBar = wx.Gauge(self, range=gaugeMax, size=(gaugeWidth, gaugeHeight))

        textSizer.Add(configText, 1, wx.ALIGN_CENTER, 0)
        progressSizer.Add(configProgressBar, 1, wx.ALIGN_CENTER, 1)
        vSizer.Add(textSizer, 1, wx.TOP, topBuffer)
        vSizer.Add(progressSizer, 1, wx.TOP, itemSep)

        self.SetSizer(vSizer)
        vSizer.Fit(self)

class MyFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title="Test")
        config = {'width':340, 'height':270}
        panel = KhPanel(self, config)

        self.Show()

if __name__ == "__main__":
    app = wx.App()
    frame = MyFrame()
    app.MainLoop()

rawDescription: wxPython -- BoxSizers not placing things correctly

description: WxPython -- BoxSizers not placing things correctly


code:
import requests

url = 'http://localhost:8080/***/***/concerts/008'
files = {
    'file': open('/home/tester/Desktop/memo.txt','rb'),
    'name': 'memo.txt'
}
params = {'access_token': 'YWMtraI2DF21EeWx_Rm4tdnmrwAAAVACjcyGG8TpdXJBXdjnRJ2SeqIAZI1T8Xk'}
r = requests.post(url, files=files, params=params)

rawDescription: unable to post file on usergrid using requests

description: Unable to post file on usergrid using requests


code:
import argparse

args = ('foo','bar','baz','qux')

#This is not the order the get printed in, so it's not using a dict...
print (set(args))

parser = argparse.ArgumentParser()
for x in args:
    parser.add_argument('--{0}'.format(x),help=x)

parser.parse_args(['-h'])

rawDescription: Python: display order of in input arguments with argparse


code:
from heapq import *
l = []
heappush(l, (4, 'element')) # priority, element
l
heappush(l, (3, 'element2'))
l
heappush(l, (5, 'element3'))
l
heappop(l)
heappop(l)
heappop(l)

rawDescription: PriorityQueue is very slow

description: PriorityQueue is very slow


code:
def passMethod(obj, method):
    return method(obj)

passMethod('Hi', str.lower)

rawDescription: Passing a method in python

description: Passing a method in python


code:
if __name__ == '__main__':
    db.create_all()
    create_example_data()
    app.run(debug=True)

rawDescription: Creating flask form with selects from more than one table


code:
dumped = cPickle.dumps(mydict, 0)
timeit.timeit('cPickle.loads(dumped)', 'from __main__ import cPickle, dumped')
dumped = cPickle.dumps(mydict, 1)
timeit.timeit('cPickle.loads(dumped)', 'from __main__ import cPickle, dumped')
dumped = cPickle.dumps(mydict, 2)
timeit.timeit('cPickle.loads(dumped)', 'from __main__ import cPickle, dumped')

rawDescription: Why does it take longer to dump and load with pickle.HIGHEST_PROTOCOL?


rawDescription: Indexing an array using mac address

description: Indexing an array using mac address


rawDescription: What is best way to remove duplicate lines matching regex from string using Python?


code:
norm = MidPointNorm(midpoint=3)
imshow(X, norm=norm)

rawDescription: Defining the midpoint of a colormap in matplotlib


code:
class MyClassFactory(object):
    Counter = 0
    LastValue = None

    @classmethod
    def Build(cls, name):
        inst = MyClass(name)
        cls.Counter += 1
        cls.LastValue = inst.Name
        return inst

rawDescription: (Usage of Class Variables) Pythonic - or nasty habit learnt from java?


code:
df_weekdays = df.loc[df.ts.apply(lambda ts: ts.weekday() < 5), :]
df_weekends = df.loc[df.ts.apply(lambda ts: ts.weekday() >= 5), :]

rawDescription: Pandas group by several values in a single column


code:
for line in sys.stdin:
    data = line.split(',')

rawDescription: MapReduce using hadoop streaming via python - Pass a list from mapper to reducer and Read it as a list


code:
import urllib
value = "kindle fire"
params = {'query': value, 'country_id': '1'}
urllib.urlencode(params)

rawDescription: URL call with string keyword substitution


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

x = np.linspace(-np.pi, np.pi, 100)
y = np.sin(x) + 1
plt.plot(x, y)
plt.yticks([0, 0.5, 1, 1.5, 2], ['foo', 'bar', 'baz', 'boo', 'bam'])

rawDescription: words as y-values in pyplot/matplotlib

description: Words as y-values in pyplot/matplotlib


code:
import itertools

lists = [['hello'], ['world', 'foo', 'bar']]
combined = list(itertools.chain.from_iterable(lists))

rawDescription: Python list comprehension to join list of lists


code:
{'Job ID': 'EE-1213256',
 'Manages Others': 'Not Specified',
 'Job Type': 'Information Technology,  Engineering,  Professional Services',
 'Relocation': 'No',
 'Education': '4 Year Degree',
 'Base Pay': '$140,000.00 - $160,000.00 /Year',
 'Experience': 'At least 5 year(s)',
 'Industry': 'Computer Software, Banking - Financial Services, Biotechnology',
 'Employment Type': 'Full-Time',
 'Required Travel': 'Not Specified'}

rawDescription: Getting crawled information in dictionary format


code: df.query("(value < 10) or (value != value)")

rawDescription: Querying for NaN and other names in Pandas


rawDescription: What is a correct way to filter different loggers using python logging?


code:
import operator
itertools.starmap(operator.gt, itertools.product(a, b))

rawDescription: Comparing each variable in a list to each variable in another list


code:
import matplotlib.pyplot as plt
import scipy.spatial as spatial
import numpy as np
pi = np.pi
cos = np.cos

def fmt(x, y):
    return 'x: {x:0.2f}\ny: {y:0.2f}'.format(x=x, y=y)

class FollowDotCursor(object):
    """Display the x,y location of the nearest data point.
    http://stackoverflow.com/a/4674445/190597 (Joe Kington)
    http://stackoverflow.com/a/13306887/190597 (unutbu)
    http://stackoverflow.com/a/15454427/190597 (unutbu)
    """
    def __init__(self, ax, x, y, tolerance=5, formatter=fmt, offsets=(-20, 20)):
        try:
            x = np.asarray(x, dtype='float')
        except (TypeError, ValueError):
            x = np.asarray(mdates.date2num(x), dtype='float')
        y = np.asarray(y, dtype='float')
        mask = ~(np.isnan(x) | np.isnan(y))
        x = x[mask]
        y = y[mask]
        self._points = np.column_stack((x, y))
        self.offsets = offsets
        y = y[np.abs(y-y.mean()) <= 3*y.std()]
        self.scale = x.ptp()
        self.scale = y.ptp() / self.scale if self.scale else 1
        self.tree = spatial.cKDTree(self.scaled(self._points))
        self.formatter = formatter
        self.tolerance = tolerance
        self.ax = ax
        self.fig = ax.figure
        self.ax.xaxis.set_label_position('top')
        self.dot = ax.scatter(
            [x.min()], [y.min()], s=130, color='green', alpha=0.7)
        self.annotation = self.setup_annotation()
        plt.connect('motion_notify_event', self)

    def scaled(self, points):
        points = np.asarray(points)
        return points * (self.scale, 1)

    def __call__(self, event):
        ax = self.ax
        # event.inaxes is always the current axis. If you use twinx, ax could be
        # a different axis.
        if event.inaxes == ax:
            x, y = event.xdata, event.ydata
        elif event.inaxes is None:
            return
        else:
            inv = ax.transData.inverted()
            x, y = inv.transform([(event.x, event.y)]).ravel()
        annotation = self.annotation
        x, y = self.snap(x, y)
        annotation.xy = x, y
        annotation.set_text(self.formatter(x, y))
        self.dot.set_offsets((x, y))
        bbox = ax.viewLim
        event.canvas.draw()

    def setup_annotation(self):
        """Draw and hide the annotation box."""
        annotation = self.ax.annotate(
            '', xy=(0, 0), ha = 'right',
            xytext = self.offsets, textcoords = 'offset points', va = 'bottom',
            bbox = dict(
                boxstyle='round,pad=0.5', fc='yellow', alpha=0.75),
            arrowprops = dict(
                arrowstyle='->', connectionstyle='arc3,rad=0'))
        return annotation

    def snap(self, x, y):
        """Return the value in self.tree closest to x, y."""
        dist, idx = self.tree.query(self.scaled((x, y)), k=1, p=1)
        try:
            return self._points[idx]
        except IndexError:
            # IndexError: index out of bounds
            return self._points[0]

fig, ax = plt.subplots()
x = np.linspace(0.1, 2*pi, 10)
y = cos(x)
markerline, stemlines, baseline = ax.stem(x, y, '-.')
plt.setp(markerline, 'markerfacecolor', 'b')
plt.setp(baseline, 'color','r', 'linewidth', 2)
cursor = FollowDotCursor(ax, x, y, tolerance=20)
plt.show()

rawDescription: Possible to make labels appear when hovering over a point in matplotlib in stem plot?


code:
def find2LetterWords():
     #this generates all possible 2-letter combos with a list comprehension
     words = [first + second for second in alphabet for first in alphabet]
     #create a new list with only those words that are in your_dictionary (a list)
     real_words = [word for word in words if word in your_dictionary]
     return real_words

rawDescription: How to generate 2 letter words using a function in python?

description: Generate 2 letter words using a function in python


code:
expression = Forward()
if_statement = Literal('if') + nestedExpr("{", "}", expression)
expression << ZeroOrMore(Or(if_statement, Regex('.')))

rawDescription: Using regular expressions to denote the opener of nestedExpr


code:
s = """bruce
chung
bruce@outlook.com
8893243
costarricense
divisa del informe colones
['nokia', 5277100.0, 'china']
['samsung', 10554200.0, 'turkey']
['apple', 52771000.0, 'argentina']""".splitlines()
import ast
registros = [ast.literal_eval(x) for x in s if x.startswith('[')]
registros

rawDescription: How to read just lists in a text file in Python?

description: Read just lists in a text file in Python


rawDescription: Finding first non-zero value along axis of a sorted two dimensional numpy array


code:
@register.assignment_tag
def my_mobile(*args, **kwargs):
    m_mobile = ("%d" %int(kwargs['mobile']))
    return {'m_mobile': m_mobile }

rawDescription: In django how to access 2 field values in custom django modeladmin...includes/fieldset.html?


code:
from bs4 import BeautifulSoup

html = '''<time>June 2010</time> – <time>August 2010</time> (3 months)New York
<time>October 2015</time> – Present (7 months)
<time>May 2010</time> – <time>October 2011</time> (6 months)'''

soup = BeautifulSoup(html)
for e in soup.find_all('span', {'class': 'experience-date-locale'}):
    if e.span:
        _ = e.span.extract()
    print(e.text)

rawDescription: BeautifulSoup - find class AND exclude another class


code:
c = collections.Counter([2, 2, 5])
d = collections.Counter([2, 3, 7])
list((c | d).elements())

rawDescription: python - merge two lists but keep same number of occurrences

description: Python - merge two lists but keep same number of occurrences


code:
added
deleted
changed

rawDescription: Differences in lists of lists using Python


code:
def staticmethod_example(func):
    def wrapper(self, *args, **kwargs):
        return func(*args, **kwargs) # Notice how *self* is thrown away
    return wrapper

rawDescription: Function inside of Object generating different print output than stand-alone function in Python 3.5


code:
import re
lst = ['foo000bar111', 'foo000bar1112', 'foo000bar1113']
[re.search(r'(\d+$)',i).group() for i in lst]

rawDescription: Pythonic way to select characters after specific character sequence in string


code:
final_list = []
for i in [[(i, k) for k in re.findall('\(.+?\)', j)] for i, j in l]:
    final_list.extend(i)

print(final_list)

rawDescription: how to make regex go line by line to match two strings at the same time?

description: Make regex go line by line to match two strings at the same time


code:
select_make = driver.find_element_by_id('vehical-make')
for option in select_make.find_elements_by_tag_name('option'):
    if option.text == 'BMW':
        option.click() # select() in earlier versions of webdriver
        break

rawDescription: Select option from dynamic dropdown list using selenium


code: sign = hmac.new(secret, post_data, hashlib.sha512).hexdigest()

rawDescription: Go and Python HMAC libraries give different results


code: _NUM_ALPHA_PAIR_RE = re.compile(r'[0-9/]+(?!st|nd|rd|th)[,a-z]+', re.I)

rawDescription: Ignore ordinals within an address in python


code:
s = 'Something M6'
'M' in s and s[s.rfind('M') + 1].isdigit()
s = 'Something M1'
'M' in s and s[s.rfind('M') + 1].isdigit()
s = 'Something Mx'
'M' in s and s[s.rfind('M') + 1].isdigit()

rawDescription: Find index of string + integer in python


code:
f = tables.open_file(filename, mode='r')
print(f.root.data[1:10,2:20]) # e.g. read from disk only this part of the dataset

rawDescription: save numpy array in append mode

description: Save numpy array in append mode


code:
@app.route('/stats/charts/count/<attribute>', methods=['GET'])
@cut_data
def count_attribute(attribute, data=None):
    counter = collections.Counter()
    for x in data:
        counter[attribute] += 1
    return counter

@app.route('/stats/charts/filter/<attribute>/<value>', methods=['GET'])
@cut_data
def filter_attribute(attribute, value, data=None):
    filtered = []
    for entry in data:
        if getattr(entry, attribute) != value:
            filtered.append(entry)
    return filtered

rawDescription: handle events in flask before they propagate to more specific approutes

description: Handle events in flask before they propagate to more specific approutes


code:
def create_user(strategy, details, user=None, *args, **kwargs):
    if user:
        return {'is_new': False}

    fields = dict((name, kwargs.get(name) or details.get(name))
              for name in strategy.setting('USER_FIELDS',
                                           USER_FIELDS))
    if not fields:
        return

    user_type = strategy.session_get('type')

    if user_type != 'cordova':
        return {
            'is_new': True,
            'user': strategy.create_user(**fields)
        }
    else:
        return {
            'is_new': True,
            'user': create_cordova_user(**fields)
        }

rawDescription: Custom pipeline for Cordova social auth

description: Custom pipeline for Cordova social auth


code:
cursor.execute("SELECT * FROM pg_class WHERE 1=2")
cursor.fetchall()

rawDescription: Python Postgres return result when it is none


code:
uniq=df['id'].unique()
random.shuffle(uniq)
groups=np.split(uniq,2)
dfr=df.set_index(df['id'])

for gp in groups : print (dfr.loc[gp])

rawDescription: Randomly combine pandas group objects

description: Randomly combine pandas group objects


code:
data
data.shape
data.transpose(2,0,1).reshape(-1,data.shape[1])
data.transpose(2,0,1).reshape(-1,data.shape[1]).shape

rawDescription: Python Reshape 3d array into 2d

description: Python Reshape 3d array into 2d


rawDescription: How can i find next highest value in django query

description: Find next highest value in django query


code:
import pandas as pd
spl = d["visualLogs"][0]

from io import StringIO
df = pd.read_csv(StringIO(spl))

rawDescription: how to extract python data frame from JSON string

description: Extract python data frame from JSON string


code:
def simplehash(x, y):
    return (x * y) % 20 - 10

rawDescription: A fast way of getting a consistent random result without setting a new seed every time


code:
{'GR': 'Hellas', 'NO': 'Norge', 'SE': 'Sverige'}
{'GR': 'Greece', 'NO': 'Norway', 'SE': 'Sweden'}

rawDescription: Python: Compare lists and combine in common fields


code:
import Image
import math

imgsize = (250, 250) #The size of the image

image = Image.new('RGB', imgsize) #Create the image

innerColor = [80, 80, 255] #Color at the center
outerColor = [0, 0, 80] #Color at the corners

for y in range(imgsize[1]):
    for x in range(imgsize[0]):

        #Find the distance to the center
        distanceToCenter = math.sqrt((x - imgsize[0]/2) ** 2 + (y - imgsize[1]/2) ** 2)

        #Make it on a scale from 0 to 1
        distanceToCenter = float(distanceToCenter) / (math.sqrt(2) * imgsize[0]/2)

        #Calculate r, g, and b values
        r = outerColor[0] * distanceToCenter + innerColor[0] * (1 - distanceToCenter)
        g = outerColor[1] * distanceToCenter + innerColor[1] * (1 - distanceToCenter)
        b = outerColor[2] * distanceToCenter + innerColor[2] * (1 - distanceToCenter)

        #Place the pixel
        image.putpixel((x, y), (int(r), int(g), int(b)))

image.save('circlegradient.jpg')

rawDescription: Plot gradients using PIL in Python

description: Plot gradients using PIL in Python


code:
import matplotlib.pyplot as plt
# Based on http://stackoverflow.com/a/8531491/190597 (Andrey Sobolev)

fig = plt.figure()
ax = fig.add_subplot(111)
y = [1, 2, 3, 4, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1]
col_labels = ['col1', 'col2', 'col3']
row_labels = ['row1', 'row2', 'row3']
table_vals = [[11, 12, 13], [21, 22, 23], [31, 32, 33]]

the_table = plt.table(cellText=table_vals,
                      colWidths=[0.1] * 3,
                      rowLabels=row_labels,
                      colLabels=col_labels,
                      loc='center right')
the_table.set_fontsize(24)
the_table.scale(2, 2)

plt.plot(y)
plt.show()

rawDescription: How to change the table's fontsize with matplotlib.pyplot?

description: Change the table's fontsize with matplotlib.pyplot


rawDescription: Multiple values JSON string Python (Django)


code:
rpsls("rock")
rpsls("Spock")
rpsls("paper")
rpsls("lizard")

rawDescription: Why this code gives me error?

description: Why this code gives me error


code: import module_name

rawDescription: Python package import own files, without knowing the package name at compile time


rawDescription: Creating a Python dictionary

description: Creating a Python dictionary


code: result_list = [t for t in input_list if t not in elimination_list]

rawDescription: Simple way to delete nested (list of 2 elements) from a list?


code:
class Person(object):
    def say(self, stuff):
        return stuff

class Lecturer(Person):
    def lecture(self, stuff):
        return self.say(str(stuff) + " - you should be taking notes")

class Professor1(Lecturer):  # 'is a' Lecturer
    def profess(self, stuff):
        return self.lecture("Its intuitively obvious that "+str(stuff))

class Professor2(Person):  # 'has a' lecturer
    def __init__(self):
        super(Professor2,self).__init__()
        self.lecturer = Lecturer()

    def profess(self, stuff):
        return self.lecturer.lecture("Its intuitively obvious that "+str(stuff))

p1 = Professor1()
print(p1.profess('Earth is flat'))

p2 = Professor2()
print(p2.profess('Earth is flat'))

rawDescription: OK so i dont get how to make this professor class call on this lecturer class


code:
a[numpy.isnan(a)] = 0
a

rawDescription: How to iterate a 3D numpy array

description: Iterate a 3D numpy array


code:
i1, i0 = np.meshgrid(range(10), range(10), sparse=True)
c = a[i0, i1, b]

rawDescription: Index numpy nd array along last dimension


code:
import re

st = '''
var arrayA = new Array();
arrayA[0] = new customItem("1","Name1","description1",1.000,2.000);arrayA[1] = new customItem("2","Name2","description2",4.000,8.000);
'''

dict1, dict2 = {}, {}
matches = re.findall('\"(\d+)\",\"(.*?)\",\"(.*?)\",(\d+.\d+),(\d+.\d+)', st, re.DOTALL)
for m in matches:
    key = m[1] + m[2]
    dict1[key] = float(m[3])
    dict2[key] = float(m[4])

print(dict1)
print(dict2)

# {'Name1description1': 1.0, 'Name2description2': 4.0}
# {'Name1description1': 2.0, 'Name2description2': 8.0}

rawDescription: Parsing javaScript arrays in the Python dictionaries


rawDescription: Find adjacent elements in a 2D numpy grid


code:
app = webapp2.WSGIApplication([('/', MainPage),
                               ('/signup', Register),
                               ('/login', Login),
                               ('/logout', Logout),
                               ('r/profile/(\w+)', Profile)
                              ],
                              debug=True)

rawDescription: Adding usernames to the path of the url

description: Adding usernames to the path of the url


code:
time
length
ordinate = np.array([[l,t] for l in length for t in time]).T
ordinate
time2D,length2D = np.meshgrid(time,length)
ordinate_vectorized

description: Numpy-native "nested-for-like" structrue


code:
def align(array):
    col_size = {}
    for row in array:
        for i, col in enumerate(row):
            col_size[i] = max(col_size.get(i, 0), len(col))
    ncols = len(col_size)
    result = []
    for row in array:
        row = list(row) + [''] * (ncols - len(row))
        for i, col in enumerate(row):
            row[i] = col.ljust(col_size[i])
        result.append(row)
    return result

rawDescription: how to normalize list of lists of strings in python?

description: Normalize list of lists of strings in python


code: lamb = (lambda a, real_co = co : self.StartGame(8, real_co))

rawDescription: Python closures, default argument isn't equal solution as using functools.partial?


code: df

rawDescription: Pandas DataFrame Display Without Dimensions


code:
boxCenterLat = (i + 0.5) * 50 * latPxSz + miny
boxCenterLon = (j + 0.5) * 50 * lonPxSz + minx

rawDescription: calculate latitude and longitude from a geotiff image

description: Calculate latitude and longitude from a geotiff image


code: "\\n".join(["\\t".join([a for a in x]) for x in new_lines])+"\\n"

rawDescription: Python List Comprehension for a list with lists


code:
import subprocess
subprocess.check_call('python', 'my_script.py', 'arg1', 'foo=bar')

rawDescription: check_call and command line arguments on Windows

description: Check_call and command line arguments on Windows


rawDescription: What's the ufunc to do floor division in numpy with python3.x?


code:
result = db.collection.aggregate([
    { "$match": {
        "impressions.service": "furniture"
    }},
    { "$unwind": "$impressions" },
    { "$match": {
        "impressions.service": "furniture"
    }},
    { "$group": {
        "_id": "$impressions.id"
    }}
])

rawDescription: Conditions in Find, Mongo

description: Conditions in Find, Mongo


code:
import md5
word="g4m3"
md5.new(word).hexdigest()        # no newline
md5.new(word + '\n').hexdigest() # with a newline

rawDescription: MD5 Encrypting Woes

description: MD5 Encrypting Woes


code:
xstep = 10
ystep = 50

df['in_bins'] = (   (pd.cut(df.loc_x, np.arange(-500, 500, xstep)).isin(df_loc.loc_x_bin))
                    &
                    (pd.cut(df.loc_y, np.arange(-500, 500, ystep)).isin(df_loc.loc_y_bin))
                )

rawDescription: Are values in one dataframe in bins of another dataframe?


code:
size = 20
nested = [L[size*i : size*(i+1)] for i in xrange(len(L)/size)]

rawDescription: divide the list into rows (create a nested list from a list)

description: Divide the list into rows (create a nested list from a list)


rawDescription: Filtering and sorting data with pandas

description: Filtering and sorting data with pandas


code:
def add_done_callback(self, fn):
    """Attaches a callable that will be called when the future finishes.

    Args:
        fn: A callable that will be called with this future as its only
            argument when the future completes or is cancelled. The callable
            will always be called by a thread in the same process in which
            it was added. If the future has already completed or been
            cancelled then the callable will be called immediately. These
            callables are called in the order that they were added.
    """
    with self._condition:
        if self._state not in [CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED]:
            self._done_callbacks.append(fn)
            return
    fn(self)

rawDescription: Python ThreadPoolExecutor - is the callback guaranteed to run in the same thread as submitted func?


rawDescription: How to search & replace in Python?

description: Search & replace in Python


code:
def format_dt(t):
    tr = t + timedelta(milliseconds=0.5)
    return tr.strftime('%H:%M:%S,%f')[:-3]

rawDescription: How to get real three digits of microseconds in Python?

description: Get real three digits of microseconds in Python


code:
for x_val, y_val in zip(xvalues, yvalues):
    if 100 < y_val < 150:
        edge1 = x_val
        break

rawDescription: Python 2.7 plotting query

description: Python 2.7 plotting query


code:
import pandas as pd
df = pd.DataFrame({'fld1': ['apple', 'apple', 'bear','bear','car','car','car','dee','dee','eagle','eagle']
        ,  'fld2': ['bear', 'car', 'car','eagle','bear','dee','eagle','eagle','foo','dee','foo']
        , 'value': [.3,.3,.2,.1,.3,.3,.2,.4,.1,.3,.2]})
gsums = df.groupby("fld1").sum()  # source group sums
df.set_index("fld1", inplace=True)  # set index to source column
df["sums"] = gsums  # new column sums in dataframe for next operation
df["rval"] = df["value"] / df["sums"]  # divide the columns
df.drop("sums", axis=1, inplace=True)  # drop the sums column
df.reset_index(inplace=True)  # reset index to the original

rawDescription: While Loop and Pandas Iterrows

description: While Loop and Pandas Iterrows


rawDescription: getting pixels value in a checkerboard pattern in python

description: Getting pixels value in a checkerboard pattern in python


code:
import numpy as np
tickets = np.array([(start1, duration1), (start2, duration2),...])

def activity(t,tickets):
    t1 = tickets[tickets[:,0]<t] #start times before t
    return t2[t2[:,0]+t2[:,1]>t]   #start+duration after t

rawDescription: Numpy : find number of active tickets at time t given a list of start and duration