code:
import nltk
tokenizer = nltk.tokenize.RegexpTokenizer(r'\w+')
lemmatizer = nltk.stem.WordNetLemmatizer()
test = "That aggressive person walk by the house over there, one of many houses aggressively"
tokens = tokenizer.tokenize(test)
lemmas = [lemmatizer.lemmatize(t) for t in tokens]
fdist = nltk.FreqDist(lemmas)
common = fdist.most_common(100)

rawDescription: nltk frequency combining singular and plural, verb and adverb when tokenizing

description: Nltk frequency combining singular and plural, verb and adverb when tokenizing


code:
newlist = [u[3].strip() for u in list]
s = set(newlist)

rawDescription: Extracting the number of different elements of a specific column in a 2D list


code:
def func2(x, y, z):
    return np.sin(y * x)+z

xaxis = np.linspace(0, 4, 10)
yaxis = np.linspace(-1, 1, 20)
zaxis = np.linspace(0, 1, 20)
result2 = func2(xaxis[:,None,None], yaxis[None,:,None],zaxis[None,None,:])

rawDescription: numpy - evaluate function on a grid of points

description: Numpy - evaluate function on a grid of points


code: hasfactors = any(guess % n == 0 for n in numbers)

rawDescription: Python - Check if numbers in list are factors of a number


code:
def strIntersection(s1, s2):
  out = ""
  for c in s1:
    if c in s2 and not c in out:
      out += c
  return out

rawDescription: Python - Intersectiing strings

description: Python - Intersectiing strings


code:
import numpy as np
import scipy as sp

rawDescription: SciPy/NumPy import guideline

description: SciPy/NumPy import guideline


code:
for col in l:
    df[col] = 0

rawDescription: Add multiple columns with zero values from a list to a Pandas data frame


code:
from django import forms

class QuestionForm(forms.ModelForm):
    class Meta:
        model = Question

rawDescription: How do I update an instance of a Django Model with request.POST if POST is a nested array?

description: Update an instance of a Django Model with request.POST if POST is a nested array


code:
A,B,C,D = [],[],[],[]
for this_,next_ in zip(matrix_x,matrix_x[1:]):
    A.append(this_[:n])
    B.append(this_[n:])
    C.append(next_[:n])
    D.append(next_[n:])

rawDescription: Better way to do multiple list comprehensions over the same range?


code:
df = pd.DataFrame(['a|b', 'c|d'])
s = df[0].apply(lambda x: x.split('|'))
df['left'] = s.apply(lambda x: x[0])
df['right'] = s.apply(lambda x: x[1])

rawDescription: Split pandas column into two

description: Split pandas column into two


code:
code_str = """
print "this is my global x = " + x
print "And another line is done"
print param
"""

compiled = compile(code_str, "<string>", "exec")
func_template = lambda p=None: eval(compiled, globals(), {'param': p})

x = "1"
func_template()
func_template("2")

rawDescription: Python dynamic functions from strings

description: Python dynamic functions from strings


rawDescription: best practice for user preferences in $HOME in Python

description: Best practice for user preferences in $HOME in Python


code: total_sentiment = sum(scores.get(word,0) for word in text.split())

rawDescription: how to properly loop through two files comparing strings in both files against each other

description: Properly loop through two files comparing strings in both files against each other


code:
text = """301 my name is joe
303 whatsup
306 how are you doing today
308 what happened?
308 going home
309 let's go""".splitlines()

import re
names = {}
replacer = lambda x: str(names.setdefault(x.group(), len(names) + 1))
for line in text:
    replaced = re.sub(r'^\d+', replacer, line)
    print(replaced)

rawDescription: How to rename labels in list?

description: Rename labels in list


code:
import pandas as pd
df = pd.read_excel('data_so.xlsx', skiprows=3)

columns = pd.MultiIndex.from_tuples([('A', 'Price'), ('A', 'Quantity'),
                                     ('B', 'Price'), ('B', 'Quantity'),
                                     ('C', 'Price'), ('C', 'Quantity')],
                                    names=['letters', 'index'])

index = pd.MultiIndex.from_arrays(df.ix[:,:2].values.T,names=('Item', 'Code'))
df2 = pd.DataFrame(df.ix[:,2:].values, columns=columns, index=index)
df3 = df2.stack('letters').reset_index()

rawDescription: Excel Table into Organized Pandas Dataframe


code: thelist = ast.literal_eval(next(open('file.txt', 'r')))

rawDescription: Strip outside quotes from text when writing to list in Python


code: [list(e) for e in zip(*[fl[i::2] for i in range(2)])]

rawDescription: How to replace the nth element of multi dimension lists in Python?

description: Replace the nth element of multi dimension lists in Python


code:
for val in foo:
    print(val)

rawDescription: Using iter on a list with a default value


code: addressBook.contactsList.sort(key=lambda c: (c.lastName, c.firstName) if c.lastName else (c.firstName, ''))

rawDescription: Python - sort method parameter takes same precedence


code: letter_freq_all.columns = pd.Series(letter_freq_all.columns).str.replace('\[\d+\]', '').str.strip()

rawDescription: How to use Python's Str.Replace() Method on all columns in a Pandas DataFrame?

description: Use Python's Str.Replace() Method on all columns in a Pandas DataFrame


rawDescription: Conditionally replace data in a pandas multi-indexed dataframe


code:
Ndx = np.array([np.arange(grid_size[0])]) * dx
x_offsets = XX - Ndx.T
x_offset = np.median(x_offsets)

Ndy = np.array([np.arange(grid_size[1])]) * dy
y_offsets = YY - Ndy.T
y_offset = np.median(y_offsets)

rawDescription: Constructing a 2D grid from potentially incomplete list of candidates


code:
import argparse
class AllAction(argparse.Action):
    def __call__(self, parser, args, values, option_string = None):
        # print '{n} {v} {o}'.format(n = args, v = values, o = option_string)
        for param in ['a', 'b', 'c', 'd']:
            setattr(args, param, True)

parser = argparse.ArgumentParser()
parser.add_argument('-b', action="store_true")
parser.add_argument('-c', action="store_true")
parser.add_argument('-d', action="store_true")
parser.add_argument('-a', action = AllAction, nargs = '?')
args = parser.parse_args()
print(args)

rawDescription: python - argparse one argument instead of several others

description: Python - argparse one argument instead of several others


code:
B = A[ sorted( ind[ :6 ] ), : ]
C = A[ sorted( ind[ 6: ] ), : ]

rawDescription: Randomly selecting rows from numpy array


property_predicate: comment

property_object: bleh

rawDescription: Flask + WTForms, dynamically generated list of fields


rawDescription: Formatting floats in a numpy array

description: Formatting floats in a numpy array


code:
import numpy as np
a = np.ones([5, 4])
b = np.diff(a, axis=1)

rawDescription: Python - sobel x derivative

description: Python - sobel x derivative


code:
rwsteps = counted(rwsteps)

rwsteps(5, 0, 10)
rwsteps.count

rawDescription: Recursive function counting number of calls for another function


code:
using_filters            : 0.130
using_eight_shifts       : 0.340
using_quadratic_loop     : 18.794

rawDescription: Retrieve position of elements with setting some criteria in numpy


code:
def coarsegrain_wrap(x,w=2):
    N = len(x)
    M = int(ceil(N/w))
    y = zeros((M,M))
    for i in range(M):
        for j in range(M):
            y[i,j] = np.nanmean(numpy.take(x,[list(range(w*i,(w*i+w))),list(range(w*j,(w*j+w)))],mode="wrap"))
    return y

rawDescription: average of elements within a window of size NbyN of an array

description: Average of elements within a window of size NbyN of an array


code:
def function1(n,d):
    if n not in d:
        length = 0
        seen = []
        while n > 1:
            seen.append(n)
            if n % 2 == 0:
                n //= 2
            else:
                n = 3 * n + 1
            length += 1
            if n in d:
                length += d[n]
                break
        for num in seen:
            d[num] = length
            length -= 1

rawDescription: Improving speed of large dictionary in Python 3.4


code:
mylist = [3,4,9,2,5,6]

from itertools import cycle
from itertools import cycle,islice
c=cycle(mylist)
list(islice(c,4,7))

rawDescription: Python list that loops to beginning

description: Python list that loops to beginning


rawDescription: list comprehension question

description: List comprehension question


code:
def configure(self, pathname, cnf={}, **kw):
    """Queries or modifies the configuration options of the
    widget.

    If no option is specified, the command returns a list
    describing all of the available options for def (see
    Tk_ConfigureInfo for information on the format of this list).
    If option is specified with no value, then the command
    returns a list describing the one named option (this list
    will be identical to the corresponding sublist of the value
    returned if no option is specified).  If one or more
    option-value pairs are specified, then the command modifies
    the given widget option(s) to have the given value(s); in
    this case the return value is an empty string.  option may
    have any of the values accepted by the tablelist::tablelist
    command.
    """
    return self.tk.call((pathname, "configure") +
                 self._options(cnf, kw))

rawDescription: Configuring values of combobox in a tablelist using tablelist wrapper in python


rawDescription: How to replace all occurrences of regex as if applying replace repeatedly

description: Replace all occurrences of regex as if applying replace repeatedly


code: soup

rawDescription: How do I sort an unordered list using BeautifulSoup 4 by a child element

description: Sort an unordered list using BeautifulSoup 4 by a child element


code:
def to_json(obj):
    return json.dumps(dict((c, getattr(obj, c)) for c in obj.sqlmeta.columns))

rawDescription: Easier way to create a JSON object from an SQLObject


code:
import csv, re
from collections import defaultdict

lookup = defaultdict(list)
with open('humsavar.txt', 'rb') as humsavarTxt:
    reader = csv.reader(humsavarTxt, delimiter=" ", skipinitialspace=True)
    for line in reader:
        code = re.search(r'(\d+)', line[3])
        lookup[line[1]].append(int(code.group(1)))

rawDescription: look up dictionary in python

description: Look up dictionary in python


rawDescription: python 3.4 multiprocessing does not work with unittest

description: Python 3.4 multiprocessing does not work with unittest


code:
from collections.abc import Mapping
def rec_key_replace(obj):
    if isinstance(obj, Mapping):
        return {key.replace('.', '_'): rec_key_replace(val) for key, val in obj.items()}
    return obj

rawDescription: Recursively replace characters in a dictionary


code: lst1, lst2 = zip(*zipped_list)

rawDescription: What is the inverse function of zip in python?


code:
my_slice[0].start
my_slice[0].stop

rawDescription: How to get coordinates from a numpy slice object

description: Get coordinates from a numpy slice object


rawDescription: Assign HTML content after stripping tags using Python (regex parse)


code:
import os
import re

def prune(regex,top='.'):
    sep=os.path.sep
    matcher = re.compile(regex)
    pieces=regex.split(sep)
    partial_matchers = map(
        re.compile,
        (sep.join(pieces[:i+1]) for i in range(len(pieces))))
    for root, dirs, files in os.walk(top,topdown=True):
        for i in reversed(range(len(dirs))):
            dirname=os.path.relpath(os.path.join(root,dirs[i]), top)
            dirlevel=dirname.count(sep)
            # print(dirname,dirlevel,sep.join(pieces[:dirlevel+1]))
            if not partial_matchers[dirlevel].match(dirname):
                print('pruning {0}'.format(
                    os.path.relpath(os.path.join(root,dirs[i]), top)))
                del dirs[i]

        for filename in files:
            filename=os.path.relpath(os.path.join(root,filename))
            # print('checking {0}'.format(filename))
            if matcher.match(filename):
                print(filename)

if __name__=='__main__':
    prune(r'foo/\w+/bar/\d+-\w+.dat')

rawDescription: "find . -regex ..." in Python or How to find files whose whole name (path + name) matches a regular expression?


code:
import wave
import contextlib
fname = '/tmp/test.wav'
with contextlib.closing(wave.open(fname,'r')) as f:
    frames = f.getnframes()
    rate = f.getframerate()
    duration = frames / float(rate)
    print(duration)

rawDescription: Get .wav file length or duration

description: Get .wav file length or duration


rawDescription: Performing operations on each item in a multilevel list


code:
next((el for el in reversed(lst) if isinstance(el, given_type)), None)
# Gives the last element if there is one, else None

rawDescription: Get last element of type string in a list


code:
import numpy as np
recs = [('Bill', '31', 260.0), ('Fred', 15, '145.0')]
r = np.rec.fromrecords(recs, formats = 'S30,i2,f4', names = 'name, age, weight')
print(r)
# [('Bill', 31, 260.0) ('Fred', 15, 145.0)]

rawDescription: How to change the dtype of a numpy recarray?

description: Change the dtype of a numpy recarray


code: processDictEntries(**dict)

rawDescription: Adding variables "by name" to local namespace


code:
from django.db import transaction

@transaction.atomic
def viewfunc(request):
    # This code executes inside a transaction.
    do_stuff()

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


code:
x = b'\x5e\x2e\x6d'
print(''.join(map(r'\x{:x}'.format, bytearray(x))))

rawDescription: How to print hex to the screen in python

description: Print hex to the screen in python


code:
from operator import itemgetter
map( itemgetter(1), lis)

rawDescription: How to access the nth element of every list inside another list?

description: Access the nth element of every list inside another list


code:
self.day = tk.Entry(self,width=2)
self.day.grid(row=4,column=1,sticky="W",padx=2,pady=5)

rawDescription: Python 3.4 tkinter checkbutton variable handling not working / responding


code:
import StringIO
import tarfile

tar = tarfile.open('example.tar.gz', 'w:gz')

# create a file record
data = StringIO.StringIO('this is some text')
info = tar.tarinfo()
info.name = 'foo.txt'
info.uname = 'pat'
info.gname = 'users'
info.size = data.len

# add the file to the tar and close it
tar.addfile(info, data)
tar.close()

rawDescription: Python: create a compressed tar file for streamed writing


code:
@staticmethod
def main_loop(root):
    "Process all GUI events according to tkinter's settings."
    target = time.clock()
    while True:
        try:
            root.update()
        except tkinter.TclError:
            break
        target += tkinter._tkinter.getbusywaitinterval() / 1000
        time.sleep(max(target - time.clock(), 0))

rawDescription: Updating a TKinter GUI from a multiprocessing calculation


code:
fw = open('/home/name/db/str/dir/numbers/str.phy.parsed', 'w') # Name this whatever makes sense

with open('/home/name/db/str/dir/numbers/str.phy') as fr:
    for line in fr:
        if line.startswith('ENS'):
            linepars = re.sub ('ENS([A-Z]+)0+([0-9]{6})','\\1\\2',line)
            fw.write(linepars)
        else:
             fw.write(line)

fw.close()

rawDescription: Python Overwriting files after parsing

description: Python Overwriting files after parsing


code:
def foo():
    string = """line one
             line two
             line three"""

rawDescription: Proper indentation for Python multiline strings


rawDescription: ast.literal_eval not working (python string of list to list)

description: Ast.literal_eval not working (python string of list to list)


code:
"""
helpers.py
Import all webhelpers that you want to have access to
"""
from webhelpers.html.tags import stylesheet_link

rawDescription: Webhelpers with Python Bottle

description: Webhelpers with Python Bottle


code:
from django.contrib import admin
from polls.models import Choice, Poll

class PollAdmin(admin.ModelAdmin):
    fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
    ]

admin.site.register(Choice)
admin.site.register(Poll, PollAdmin)

rawDescription: Add button not showing up in Django tutorial 02


code:
def convert_encoding(self, source_encoding, input_filename, output_filename):
    tree = etree.parse(input_filename)
    with open(output_filename, 'w') as destination:
        tree.write(destination, encoding='utf-8', xml_declaration=True)

rawDescription: Writing an XML header with LXML

description: Writing an XML header with LXML


code:
def xls_to_response(xls, fname):
    response = HttpResponse(mimetype="application/ms-excel")
    response['Content-Disposition'] = 'attachment; filename=%s' % fname
    xls.save(response)
    return response

rawDescription: django excel xlwt

description: Django excel xlwt


rawDescription: How can I make a "tuple of an ndarray of ndarrays"?

description: Make a "tuple of an ndarray of ndarrays"


code: label = tk.Label(text=i+1, width=6, bg='red')

rawDescription: Basic Python methods & GUI assistance

description: Basic Python methods & GUI assistance


code:
def create_id_generator(multiplier=1000):
    """Returns an id generator."""
    i = 0
    while True:
        yield i * multiplier
        i += 1

rawDescription: Python best practices for functions

description: Python best practices for functions


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

# @file: setup.py

from distutils.core import setup
import py2exe

# http://msdn.microsoft.com/en-us/library/ms648009%28v=vs.85%29.aspx
RT_MANIFEST = 24

# http://en.wikipedia.org/wiki/Side-by-side_assembly
manifest = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<dependency>
  <dependentAssembly>
    <assemblyIdentity
      type="win32"
      name="Microsoft.Windows.Common-Controls"
      version="6.0.0.0"
      processorArchitecture="*"
      publicKeyToken="6595b64144ccf1df"
      language="*"
    />
  </dependentAssembly>
</dependency>
<dependency>
  <dependentAssembly>
    <assemblyIdentity
      type="win32"
      name="Microsoft.VC90.CRT"
      version="9.0.21022.8"
      processorArchitecture="*"
      publicKeyToken="1fc8b3b9a1e18e3b"
      language="*"
    />
  </dependentAssembly>
</dependency>
</assembly>
"""

setup(
  windows = [{
    "script" : "example.pyw",
    # "icon_resources" : [(1, "icon.ico")] # have an icon?
    "other_resources" : [(RT_MANIFEST, 1, manifest)]
  }]
)

rawDescription: Hiding command prompt in wxpython app

description: Hiding command prompt in wxpython app


rawDescription: Python: Easygui Window Size

description: Python: Easygui Window Size


code:
import package.foo as foo
foo.fct(7)

rawDescription: Import a module from a package

description: Import a module from a package


code: soup.find("span", class_="unique name 1").next_sibling.strip()

rawDescription: Find the next span and print the text

description: Find the next span and print the text


rawDescription: How to retrieve object by foreign key in the url using Django and rest_framework

description: Retrieve object by foreign key in the url using Django and rest_framework


code:
import pandas as pd; import numpy as np
x = pd.Series([1, np.nan, 2, np.nan, np.nan, 3, np.nan, np.nan, np.nan, 4])
x.fillna(method='ffill', limit=1)
x.fillna(method='ffill', limit=2)

rawDescription: Working with NaN values in matplotlib

description: Working with NaN values in matplotlib


code: lst = pickle.loads(pickle_string)

rawDescription: Embed list into python file

description: Embed list into python file


code:
if axis == 'x':
    value = grid[i][j]
else:
    value = grid[j][i]

rawDescription: Conditionally swap axes in for loop for multidimensional list Python


code: ['examine','table']

rawDescription: How to split a variable into two different variables?

description: Split a variable into two different variables


code:
import re
with open('file') as f:
    mylist = list(map(int, re.findall('\d+', f.read())))

rawDescription: File of lists, import as individual lists in python 2.7


rawDescription: Python(3.x) - Opening File and Removing the Quotation Marks when reading file


code:
x = x[x.dayofweek<5]
x

rawDescription: Python Pandas business day range bdate_range doesn't take 1min freq?


code: [[k, len(list(g))] for k, g in groupby(strs)]

rawDescription: Counting consecutive characters in a string


code: route1 = min(a, b, c)

rawDescription: Python logic - how do I code the maximum weight for two roads that have a variety of maximum weight values?


code:
import re

f = open("machinelist.txt", 'r')
lines = f.readlines()
for host in lines:
    hostnames = host.strip()
    if hostnames.startswith('\\'):
        print(re.match(r'\\\\(\S+)',hostnames).group(1))

rawDescription: Find all lines that match regex pattern and grab part of string


code:
n = 6

# generate some data
gdp = np.array(np.random.randint(10,500,n))
countries = np.array(['Country%i' % (i+1) for i in range(n)])
matr = np.random.randint(0,10,(n,n))

# get the x and y arrays
y = np.insert(gdp.cumsum(),0,0)
xx,yy = np.meshgrid(np.arange(n+1),y)

# plot the matrix
fig, axs = plt.subplots(figsize=(6,6))

axs.pcolormesh(xx,yy,matr.T, cmap=plt.cm.Reds, edgecolors='k')

axs.set_ylim(y.min(),y.max())

# set the yticks + labels
axs.set_yticks(y[1:] - np.diff(y) / 2)
axs.set_yticklabels(countries)

#set xticks + labels
axs.xaxis.set_ticks_position('top')
axs.set_xticks(np.arange(n)+0.5)
axs.set_xticklabels(np.arange(n))

rawDescription: matplotlib matshow: How to change each row height based on a scaling vector?

description: Matplotlib matshow: How to change each row height based on a scaling vector


code:
import numpy
import scipy.ndimage
import numexpr as ne

def main(x=None):
    if x is None:
        ni, nj = 10000, 10000
        x = numpy.arange(ni*nj, dtype=numpy.float32).reshape(ni,nj)
    filtsize = 3
    nlooks = 10.0
    dfactor = 10.0
    x = enh_lee(x, filtsize, nlooks, dfactor)
    return x

def moving_average(Ic, filtsize):
    Im = numpy.empty(Ic.shape, dtype='Float32')
    scipy.ndimage.filters.uniform_filter(Ic, filtsize, output=Im)
    return Im

def moving_stddev(Ic, filtsize):
    Im = numpy.empty(Ic.shape, dtype='Float32')
    scipy.ndimage.filters.uniform_filter(Ic, filtsize, output=Im)
    Im = ne.evaluate('((Ic-Im) ** 2)')
    scipy.ndimage.filters.uniform_filter(Im, filtsize, output=Im)
    return ne.evaluate('sqrt(Im)')

def enh_lee(Ic, filtsize, nlooks, dfactor):
    # Implementation based on PCI Geomatica's FELEE function documentation
    Ci = moving_stddev(Ic, filtsize)
    Im = moving_average(Ic, filtsize)
    Ci /= Im

    Cu = numpy.sqrt(1 / nlooks).astype(numpy.float32)
    Cmax = numpy.sqrt(1 + (2 * nlooks)).astype(numpy.float32)

    W = ne.evaluate('exp(-dfactor * (Ci - Cu) / (Cmax - Ci))')
    If = ne.evaluate('Im * W + Ic * (1 - W)')
    del W

    out = ne.evaluate('where(Ci <= Cu, Im, If)')
    del Im
    del If

    out = ne.evaluate('where(Ci >= Cmax, Ic, out)')
    return out

if __name__ == '__main__':
    main()

rawDescription: Improving memory usage in an array-wide filter to avoid block-processing


code: re.split(r': | - | -|- ', string)

rawDescription: Python - defining string split delimiter?


code:
matrix = [[-5, -6, 2], [3, 1, -7], [8, -4, 9]]
for row in matrix:
    if all(x - y > 0 for x, y in zip(row[:-1], row[1:])):
        print(list(reversed(row)))
        break

rawDescription: Find in the matrix the first row, in which all elements are arranged in descending order.


rawDescription: better way to find pattern in string?

description: Better way to find pattern in string


code: get_most_popular_gender_ambiguous_name(2014)  # assuming df is dataframe var name

rawDescription: comparing column values based on other column values in pandas

description: Comparing column values based on other column values in pandas


code:
fig, axes = plt.subplots(ncols=3, figsize=(10, 2))
axes[0].contour(values)
axes[1].contour(x_values, y_values, values)
axes[2].contour(X, Y, Z)

rawDescription: Setting arbitrary axis value for a contour plot of form (x,y,f(x,y))?


code:
def anti_vowel(text):
    text = list(text)
    index = 0
    while index < len(text):
        if text[index].lower() in vowels:
            del text[index]
        else:
            index += 1
    return ''.join(text)

rawDescription: pop() function not functioning right in a for loop

description: Pop() function not functioning right in a for loop


code:
def return_movie_html(environ, start_response):
    request_uri = environ.get('REQUEST_URI')
    movie_uri = request_uri[request_uri.rfind('/')+1:]
    start_response('200 OK', [('Content-Type', 'text/html')])
    return ['''
            <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
                                  "http://www.w3.org/TR/html4/strict.dtd">
            <html>
            ...
            <object ...>
            <param name="allowScriptAccess" value="all" />
            <param name="flashvars" value= />
            <param name="movie" value="%(movie)s" />
            <param name="loop" value="false" />
            <param name="quality" value="high" />
            <param name="bgcolor" value="#eeeeee" />
            <embed src="%(movie)s" loop="false" ... />
            </object>
            ...
            </html>
            ''' % {'movie': movie_uri}]

rawDescription: Convert param into python?

description: Convert param into python


code:
def readlines(f, bufsize):
    buf = ""
    data = True
    while data:
        data = f.read(bufsize)
        buf += data
        lines = buf.split('\x00')
        buf = lines.pop()
        for line in lines:
            yield line + '\x00'
    yield buf + '\x00'

rawDescription: How to find null byte in a string in Python?

description: Find null byte in a string in Python


code:
col = 1
m[np.array(m[:,col].argsort(axis=0).tolist()).ravel()]

rawDescription: Sorting numpy matrix for a given column

description: Sorting numpy matrix for a given column


code:
dev-python/h5py
dev-python/matplotlib
dev-python/pillow
sys-libs/glibc

rawDescription: Retrieve list of external C/Fortran dependencies for Python libraries within a virtualenv


code:
plans = []
plans_selector = '.wm20_planspage_planDetails_sub_detailsDiv_ul_li'
plans = d(plans_selector).each(lambda i, n: plans.append(pq(n).text()))

rawDescription: How do I send a POST request to the page after it has been opened using Python?

description: Send a POST request to the page after it has been opened using Python


code:
import os, sys
sys.path.insert(0, path)
from environment import *

# Optional. Probably harmless to leave it in your path.
del sys.path[0]

rawDescription: python import specific file

description: Python import specific file


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

fig, ax = plt.subplots()
ax.plot([-29, 31], [-29, 31])

multiplier = 5.0
for axis, setter in [(ax.xaxis, ax.set_xlim), (ax.yaxis, ax.set_ylim)]:
    vmin, vmax = axis.get_data_interval()
    vmin = multiplier * np.floor(vmin / multiplier)
    vmax = multiplier * np.ceil(vmax / multiplier)
    setter([vmin, vmax])

plt.show()

rawDescription: Matplotlib - change automatic axis range


rawDescription: Loading pickled python object use enormous amount of memory


code: map(lambda t: map(lambda v: float(v) / 10000, t), b)

rawDescription: How can I apply a math operation on a list of tuples with `map()`?

description: Apply a math operation on a list of tuples with `map()`


code:
from functools import partial
def add(self):
   return self.a + self.b
class whatever:
      def __init__(self,fn,a,b):
         self.__dict__[fn.__name__] = partial(fn,self)
         self.a,self.b = a,b

x = whatever(add,5,6)
x.add()

rawDescription: How to pass a function as a parameter to a class in python

description: Pass a function as a parameter to a class in python


rawDescription: How to convert the data extracted from a file to bytes in python?

description: Convert the data extracted from a file to bytes in python


rawDescription: Access next sibling <li> element with BeautifulSoup


code: result = (y, x)[a>b]

rawDescription: What does this python expression mean

description: What does this python expression mean


code:
x_0 = 0 # We already know this as it was set earlier
y_0 = 0

rawDescription: Adding a line to a matplotlib scatterplot based on a slope


code: addition("myvar", 1, 2)

rawDescription: re-naming data frame output given input parameter to class in python

description: Re-naming data frame output given input parameter to class in python


rawDescription: How can i search a array from a large array by numpy

description: Search a array from a large array by numpy


code:
class OneAttribute:
    def __init__(self,a=1):
        self.a = a

class TwoAttributes:
    def __init__(self,b=2,c=3):
        self.b = b
        self.c = c

rawDescription: Initializing a class in another class, but passing only set attributes


code:
import io
import numpy as np
import pandas as pd

content = '''Trader     Buy/Sell
  A           1
  A           0
  B           1
  B           1
  B           0
  C           1
  C           0
  C           0'''

df = pd.read_table(io.BytesIO(content), sep='\s+')
def categorize(x):
    m = x.mean()
    return 1 if m > 0.5 else 0 if m < 0.5 else np.nan
result = df.groupby(['Trader'])['Buy/Sell'].agg([categorize, 'sum', 'count'])
result = result.rename(columns={'categorize' : 'Buy/Sell'})
print(result)

rawDescription: Applying a custom groupby aggregate function to output a binary outcome in pandas python


code: data = [x for x in data if any(x)]

rawDescription: How do I remove an empty column in a two dimensional list in python?

description: Remove an empty column in a two dimensional list in python


code:
list(generate_sequences([1,2,3], 9))
list(generate_sequences([1,1,1], 9))

rawDescription: Generating specific bit sequences in Python


code:
s = pd.Series(["3 4", "2 3 4 5"])
s.str.get_dummies(sep=" ")

rawDescription: Pandas: Convert array column to numpy Matrix


code:
pgrp = os.getpgid(process_Festival.pid)
os.killpg(pgrp, signal.SIGINT)

rawDescription: how to kill a process group using Python subprocess

description: Kill a process group using Python subprocess


code:
# select all the fellow players objects who belong to other model with pk=1
FellowPlayer.objects.filter(match_history__pk=1)

rawDescription: How to store variable length list of dict-type objects with FKs in Django SQL DB

description: Store variable length list of dict-type objects with FKs in Django SQL DB


code:
TC = P*(MktFrac+PayFrac) + C
TP = P*(1-MktFrac-PayFrac) - C
PM = 1-MktFrac-PayFrac - C/P

rawDescription: Calculate product price based on multiple percentage factors


code:
from collections import Counter, defaultdict, namedtuple
from fractions import Fraction
from heapq import heappop, heappush
from math import ceil
from operator import itemgetter

class _BestFirstSearchDepthFirstBacktracking:
    def optimize(self):
        node = self._make_root_node()
        heap = []
        upper_bound = None
        while True:
            lower_bound = ceil(node.lower_bound)
            if upper_bound is None or lower_bound < upper_bound:
                child_nodes = list(self._make_child_nodes(node))
                if child_nodes:
                    i, node = min(enumerate(child_nodes), key=itemgetter(1))
                    del child_nodes[i]
                    for child_node in child_nodes:
                        heappush(heap, child_node)
                    continue
                upper_bound = lower_bound
                solution = node
            if not heap:
                return (upper_bound, solution)
            node = heappop(heap)

Node = namedtuple('Node', ('lower_bound', 'index', 'maybes', 'yeses', 'variable'))

class UnsolvableException(Exception):
    pass

class _Optimizer(_BestFirstSearchDepthFirstBacktracking):
    def __init__(self, tuples, min_freq):
        self._index = 0
        self._tuples = set(tuples)
        self._min_freq = min_freq
        self._elements = set()
        for t in self._tuples:
            self._elements.update(t)

    def _propagate(self, maybes, yeses):
        upper_count = Counter()
        for t in maybes:
            upper_count.update(t)
        for t in yeses:
            upper_count.update(t)
        if any(upper_count[e] < self._min_freq for e in self._elements):
            raise UnsolvableException()
        forced_yeses = set()
        forced_yeses = {t for t in maybes if any(upper_count[e] - k < self._min_freq for e, k in Counter(t).items())}
        maybes = maybes - forced_yeses
        yeses = yeses | forced_yeses
        lower_count = Counter()
        for t in yeses:
            lower_count.update(t)
        residual = {e for e in self._elements if lower_count[e] < self._min_freq}
        maybes = {t for t in maybes if any(e in residual for e in t)}
        return (maybes, yeses)

    def _compute_heuristic(self, maybes, yeses):
        lower_count = Counter()
        for t in yeses:
            lower_count.update(t)
        residual_count = {e: max(self._min_freq - lower_count[e], 0) for e in self._elements}
        y = defaultdict(int)
        z = defaultdict(int)
        variable = None
        while True:
            slack = {t: 1 + z[t] - sum(y[e] for e in t) for t in maybes}
            assert all(s >= 0 for s in slack.values())
            inactive_maybes = {t for t, s in slack.items() if s > 0}
            if not inactive_maybes:
                break
            active_maybes = {t for t, s in slack.items() if s == 0}
            active_count = Counter()
            for t in active_maybes:
                active_count.update(t)
            dy = {e: 1 for e, k in residual_count.items() if active_count[e] < k}
            if not dy:
                break
            delta_inverse, variable = max(((Fraction(sum(dy.get(e, 0) for e in t), slack[t]), t) for t in inactive_maybes), key=itemgetter(0))
            delta = Fraction(1, delta_inverse)
            for e, dy_e in dy.items():
                y[e] += delta * dy_e
            for t in active_maybes:
                z[t] += delta * sum(dy.get(e, 0) for e in t)
        return (sum(residual_count[e] * y_e for e, y_e in y.items()) - sum(z.values()), variable)

    def _make_node(self, maybes, yeses):
        maybes, yeses = self._propagate(maybes, yeses)
        heuristic, variable = self._compute_heuristic(maybes, yeses)
        node = Node(len(yeses) + heuristic, self._index, maybes, yeses, variable)
        self._index += 1
        return node

    def _make_root_node(self):
        return self._make_node(self._tuples, set())

    def _make_child_nodes(self, node):
        if node.variable is None:
            return
        variable = {node.variable}
        maybes = node.maybes - variable
        yield self._make_node(maybes, node.yeses)
        yield self._make_node(maybes, node.yeses | variable)

def optimize(tuples, min_freq):
    optimizer = _Optimizer(tuples, min_freq)
    node = optimizer.optimize()[1]
    print('Nodes examined:', optimizer._index)
    return node.yeses

print(optimize({(2,), (3,), (1, 4), (1, 2, 3), (2, 3), (3, 4), (2, 4)}, 2))
print(optimize({(1, 2, 3, 4, 5, 6, 7), (8, 9, 10, 11, 12, 13, 14), (1, 2, 3, 4, 8, 9, 10, 11), (5, 6, 12, 13), (7, 14)}, 1))

rawDescription: Reduce set size while preserving minimum frequency


code:
if env.get('env') == 'prod':
    env.roledefs['nginx'] = [ 'www@tnginx01', 'www@tnginx02' ]
    env.roledefs['middle'] = [ 'www@tmiddle01', 'www@tmiddle02' ]
elif env.get('env') == 'preprod':
    env.roledefs['nginx'] = [ 'www@pnginx01', 'www@pnginx02' ]
    env.roledefs['middle'] = [ 'www@pmiddle01', 'www@pmiddle02' ]
else:
    puts(red("This environment doesn't exist. Possible values are 'preprod' and 'prod'", True))
    sys.exit()

    env.first_middle = env.roledefs['middle'][0]

@task
@roles(env.first_middle)
def deploy():
    run('pwd')

rawDescription: How to dynamically edit env.roledefs in Fabric?

description: Dynamically edit env.roledefs in Fabric


code:
def key_value():
    a = A()
    return a.x, a

random.seed(42)
d = dict(key_value() for i in xrange(1000000))

rawDescription: Python: Retrieve items from a set

description: Python: Retrieve items from a set


code:
import numpy as np
a = np.random.random(10)*10
a
output = np.array([True, True, False, False, False, False, False, False, False, False])
a[output]
a[~output]

rawDescription: Python - Splitting an array into two using an optimized for loop


code:
from os import mkdir, chdir
from shutil import move, copy, rmtree, copytree
from subprocess import call

rawDescription: Need to write python script to execute linux commands in cygwin


rawDescription: Manipulation with arrays in numpy

description: Manipulation with arrays in numpy


rawDescription: terminate python while loop in php

description: Terminate python while loop in php


rawDescription: csv import sqlite3 without specifying column types

description: Csv import sqlite3 without specifying column types


code:
p = re.compile(r'{PakBusPort_(.*?)}')
p.findall(res)

rawDescription: Trying to extract strings using regex - Python


code:
class MyClass(object):
    def someFunc():
        thatDict={} # recreated every function call

rawDescription: What is more efficient? A dict inside the class definition or dict inside a func definition?


code: upper, lower = split_upper_lower('AbBZxYp')

rawDescription: How to separate upper and lower case letters in a string

description: Separate upper and lower case letters in a string


code:
for line in os.popen("ps xa"):
    fields = line.split()

    if vProcessName  in fields[4]:
        print("Found")
        break # <----

rawDescription: Python Issue with Values

description: Python Issue with Values


code: re.search("(ABC)+\d+", s).group()

rawDescription: Regular Expression: Include Text After (...) Group


code:
class MainPage(webapp2.RequestHandler):
  def get(self):
    images = Stocks.all().fetch(100)
    html = ['<img src="/image?key=%s" />' % img.key() for img in images]
    self.response.out.write(html)

rawDescription: GAE python display multiple images in on page


code:
import random
try:
    import tkinter as tk
except ImportError:
    import Tkinter as tk

class Choices(tk.Frame):
    def __init__(self, choice_a, choice_b, callback):
        super().__init__()

        self._choice = tk.StringVar()

        self.left_button = tk.Radiobutton(
            self,
            variable=self._choice,
            text=choice_a,
            value=choice_a,
        )
        self.left_button.grid(row=0, column=0, sticky=tk.W)

        self.right_button = tk.Radiobutton(
            self,
            variable=self._choice,
            text=choice_b,
            value=choice_b
        )
        self.right_button.grid(row=0, column=1, sticky=tk.E)

        self._choice.set(choice_a)

        self.next_button = tk.Button(self, text='Next', command=callback)
        self.next_button.grid(row=1, column=0, columnspan=2)

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)

    @property
    def choice(self):
        return self._choice.get()

    @property
    def choice_a(self):
        return self.left_button['text']

    @choice_a.setter
    def choice_a(self, value):
        self.left_button.config(text=value, value=value)

    @property
    def choice_b(self):
        return self.right_button['text']

    @choice_b.setter
    def choice_b(self, value):
        self.right_button.config(text=value, value=value)

class PossibleSelections(tk.Frame):
    def __init__(self, root, selections, command):
        super().__init__(root)
        self.command = command
        self.show_selections(selections)

    def show_selections(self, selections):
        for widget in self.winfo_children():
            widget.destroy()

        for selection in selections:
            tk.Label(self, text=selection).pack()

        tk.Button(self, command=self.command).pack()

class Example(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title('Example Chooser')

        self.choice_frame = Choices(
            'Do you like this?',
            'Do you like that?',
            self.show_options,
        )
        self.choice_frame.pack()
        self.selections_frame = PossibleSelections(self, [], self.show_choices)

    def show_options(self):
        self.choice_frame.pack_forget()

        self.selections_frame.show_selections(
            random.sample('ABCDEF', 3)+[self.choice_frame.choice],
        )
        self.selections_frame.pack()

    def show_choices(self):
        self.selections_frame.pack_forget()
        options = random.sample([
            'My favorite color is blue',
            'My favorite color is yellow',
            'My favorite color is blu-no, yelloooooow!',
            'I seek the grail',
            'My name is Arthur, King of the Britons',
        ], 2)
        self.choice_frame.choice_a = options[0]
        self.choice_frame.choice_b = options[1]
        self.choice_frame.pack()

if __name__ == '__main__':
    Example().mainloop()

rawDescription: Displaying Label widget based on Radio Button answer


rawDescription: How to change array layout?

description: Change array layout


code:
from collections import defaultdict
d = defaultdict(list)
for row in data:
    d[row[1]].append(row[:1] + row[2:])

d
dict(d)  # to convert it back to dict

rawDescription: Convert list to dictionary of tuples based on column value


rawDescription: How do I make my post form handling more flexible

description: Make my post form handling more flexible


rawDescription: Python - Pandas — How to check which column a DataFrame is grouped by?


rawDescription: How to replace the nth element of multi dimension lists in Python?

description: Replace the nth element of multi dimension lists in Python


code:
filepointer = open("INPUT.txt")
text = filepointer.read()
text = re.sub(r"\n\s{20,}", "\t", text)

rawDescription: How to join second line to end of first line in python?

description: Join second line to end of first line in python


code:
root = Tk()

marco = Frame(root, padx=100, pady=50)
marco.pack()

lf = fase3(marco)
lf.pack()

root.mainloop()

rawDescription: Selecting values simultaneously from different Tkinter Listbox widgets in Python 3.5


code: #! /usr/bin/python - u

rawDescription: Python script not able to read user input when run remotely


code:
from django.template.defaultfilters import slugify
class MyModel(models.Model):
    def class_name(self):
        return "%s"%(slugify(self.name)) #or whatever field has the specific instance name

rawDescription: Unique HTML element IDs for each model with Django


code:
def clip(self, lower=None, upper=None, out=None, axis=None):
    ...
    result = self
    if lower is not None:
        result = result.clip_lower(lower, axis)
    if upper is not None:
        result = result.clip_upper(upper, axis)
    return result

rawDescription: Why np.clip(pd.Series(range(10)), 2,3) returns a Series?


rawDescription: How to get the first N sentences from text?

description: Get the first N sentences from text


code:
# Have the tabs as this dialog's class properties
self.tab1 = Tab1(image)
self.tab2 = Tab2()

tab_widget.addTab(self.tab1, "1")
tab_widget.addTab(self.tab2, "2")

rawDescription: Passing changing data from tab to tab

description: Passing changing data from tab to tab


code:
nbins = 20
colors = plt.cm.spectral(np.linspace(nbins))

rawDescription: How to add colorbar to a histogram?

description: Add colorbar to a histogram


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('subparser', choices=['foo','bar'])

def foo_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('fooval', choices='123')
    return parser

def bar_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('barval', choices='ABC')
    return parser

dispatch = {'foo':foo_parser, 'bar':bar_parser}
args, unknown = parser.parse_known_args()
args = dispatch[args.subparser]().parse_args(unknown)
print(args)

rawDescription: argparse on demand imports for types, choices etc

description: Argparse on demand imports for types, choices etc


code: errors_list.sort(key=lambda x: (x, find_pos(x, search_terms)))

rawDescription: What is the pythonic way to print values right aligned?


code:
def testforoo(x):
    for j in range(0,len(x)):
        if x[j]=='oo'.lower():
            return True
    return False

rawDescription: Python 3.3.3 TypeError : Can't convert 'NoneType' object to str implicitly


code:
parser.add_argument(
    "-option1", type=int, nargs='?', default=1,
    choices=xrange(1, 10), help="option 1 message")

rawDescription: Reading default arguments with argparse

description: Reading default arguments with argparse


code:
{'End Date': 'c', 'Start Date': 'b', 'Event': 'a'}
{'End Date': 'f', 'Start Date': 'e', 'Event': 'd'}
{'End Date': 'i', 'Start Date': 'h', 'Event': 'g'}

rawDescription: Parse HTML table to Python list?

description: Parse HTML table to Python list


code:
'acmod21_I0D0CRC.ec3 -#tm1_m28_switch.cfg'
'acmod_2_252_ddp.ec3 -#tm1_m7_switch_every_3frames.cfg'

rawDescription: How to remove a directory path from a text file

description: Remove a directory path from a text file


code:
mask = pygame.mask.Mask(self.getNextFrame().get_size())
mask.fill()

rawDescription: How to get Mask with transparency in pygame?

description: Get Mask with transparency in pygame


rawDescription: Numpy: checking if an element in a multidimensional array is in a tuple


code: {key:val for key, val in myDict.items() if val != 42}

rawDescription: What is the best way to remove a dictionary item by value in python?


code:
filename = r'E:\AirborneLidarData\IntensFirst\325115401.asc'
outfilename = r'E:\AirborneLidarData\LaserFirst\325115401.asc'

rawDescription: how to separate a column of one ASCII file and add it to the last column of another ASCII file in Python?

description: Separate a column of one ASCII file and add it to the last column of another ASCII file in Python


code:
class MyProg():

  def Run(self):
    # create a commandline argument parser
    MainParser = argparse.ArgumentParser(
      description = textwrap.dedent('''This is the User Service Tool.'''),
      formatter_class = argparse.RawDescriptionHelpFormatter,
      add_help=False)

    MainParser.add_argument('-v', '--verbose', dest="verbose", help='print out detailed messages', action='store_const', const=True, default=False)
    MainParser.add_argument('-d', '--debug', dest="debug", help='enable debug mode', action='store_const', const=True, default=False)
    MainParser.set_defaults(func=self.HandleDefault)
    subParsers = MainParser.add_subparsers(help='sub-command help')

    # UserManagement commads
    # create the sub-parser for the "create-user" command
    CreateUserParser = subParsers.add_parser('create-user', help='create-user help')
    CreateUserParser.add_argument(metavar='<Username>', dest="Users", type=str, nargs='+', help='todo help')
    CreateUserParser.set_defaults(func=self.HandleCreateUser)

    # create the sub-parser for the "remove-user" command
    RemoveUserParser = subParsers.add_parser('remove-user', help='remove-user help')
    RemoveUserParser.add_argument(metavar='<UserID>', dest="UserIDs", type=str, nargs='+', help='todo help')
    RemoveUserParser.set_defaults(func=self.HandleRemoveUser)

  def HandleDefault(self, args):
    print("HandleDefault:")

  def HandleCreateUser(self, args):
    print("HandleCreateUser: {0}".format(str(args.Users)))

  def HandleRemoveUser(self, args):
    print("HandleRemoveUser: {0}".format(str(args.UserIDs)))

my = MyProg()
my.Run()

rawDescription: Is it possible to implement .NET-like attributes in Python?


code:
import ctypes
...

thing = Secret("gibberish")
cell = ctypes.py_object(thing.__init__.__func__.__closure__[0])
new_value = ctypes.py_object('whatever')
ctypes.pythonapi.PyCell_Set(cell, new_value)

thing.getSecret()

rawDescription: Python private instance data revisited

description: Python private instance data revisited


code:
from rest_framework.pagination import PageNumberPagination
@csrf_exempt
def app_berria_list(request):
    if request.method == 'GET':
        berriak = Berria.objects.all()
        paginator = PageNumberPagination()
        page = paginator.paginate_queryset(berriak, request)
        serializer = BerriaSerializer(page, many=True, context={'request': request})
        return paginator.get_paginated_response(serializer.data)

rawDescription: django-rest-framework, how to paginate

description: Django-rest-framework, how to paginate


rawDescription: how to sort python dict by its value?

description: Sort python dict by its value


code:
WEEKDAYS = BitChoices((('mon', 'Monday'), ('tue', 'Tuesday'), ('wed', 'Wednesday'),
               ('thu', 'Thursday'), ('fri', 'Friday'), ('sat', 'Saturday'),
               ('sun', 'Sunday')
           ))

rawDescription: Representing a multi-select field for weekdays in a Django model


rawDescription: How to find all Python built-in private variables such as __file__, __name__

description: Find all Python built-in private variables such as __file__, __name__


code: numbers = [int(line) for line in email_lines]

rawDescription: Change Series of Numbers to List, python


rawDescription: Most efficient way to recode these multiple if statements


rawDescription: How to reverse sub arrays in numpy?

description: Reverse sub arrays in numpy


code: tf.truncated_normal(tf.shape(input_tensor), mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)

rawDescription: Cannot convert a partially converted tensor in TensorFlow


code: print(line_number, a_line, end="")

rawDescription: How can I prevent my program from adding unwanted blank lines when reading and printing from text file - Python3

description: Prevent my program from adding unwanted blank lines when reading and printing from text file - Python3


code: mylist = [sublist for sublist in mylist if sublist]

rawDescription: dealing with an empty list inside a list

description: Dealing with an empty list inside a list


code: corners = a[tuple(slice(None, None, j-1) for j in a.shape)]

rawDescription: Get corner values in Python numpy ndarray


rawDescription: Frequency count unique values Pandas

description: Frequency count unique values Pandas


rawDescription: Basic Formatting Issue

description: Basic Formatting Issue


code: list(chain.from_iterable(pe.split() for pe in prodemployees))

rawDescription: Python : split a list dynamically

description: Python : split a list dynamically


code:
class Car(object):
    pass
class Ferrari(Car):
    pass
class Volkswagen(Car):
    pass
def car_factory(blueprint, *args, **kwargs):
    if blueprint == "Ferrari":
        return Ferrari(*args, **kwargs)
    if blueprint == "Volkswagen":
        return Volkswagen(*args, **kwargs)

rawDescription: Create sub class by calling super class python


code:
from datetime import datetime
import numpy
numpy.datetime64('2002-06-28T01:00:00.000000000+0100').astype(datetime)
numpy.__version__

rawDescription: Converting between datetime, Timestamp and datetime64


code:
{
  'three': ['five', 'four'],
  'two':   ['four', 'three', 'five'],
  'four':  [],
  'zero':  ['one'],
  'five':  [],
  'one':   ['two', 'four', 'three', 'four']
}

rawDescription: Merge sequences of unique elements

description: Merge sequences of unique elements


code:
objPointShape = 100
objectpoints = np.random.rand(objPointShape, 3)
ipxShape = 100
ipx = np.random.rand(1, ipxShape)
ipyShape = 100
ipy = np.random.rand(1, ipyShape)
k = 1
hologram = np.zeros((ipxShape,ipyShape))
hologram = hologram+0j

rawDescription: Performance issues using nested for loops for image processing


code:
temp_df = ga.read_ga(metrics,
              dimensions=dimensions,
              start_date=start_date,
              end_date=end_date,
              index_col=0,
              filters=filters,
              account_id=account,
              property_id=property,
              profile_id=profile,
              start_index=start_index)

rawDescription: Pandas google analytics API - how to switch account?


code: clock = pygame.time.Clock()

rawDescription: Setting a fixed FPS on a Python 3 game

description: Setting a fixed FPS on a Python 3 game


code: {key: [color, sum(t[2] for t in value if t[0] == color)] for key, value in Dict.iteritems()}

rawDescription: Sum Values in a Dictionary w/ respect to the Key - Python 2.7


rawDescription: How can I additionally zip list into already zipped list?

description: Additionally zip list into already zipped list


code: A.sum(axis=0, skipna=True)

rawDescription: Improving performance of operations on a NumPy array


code:
class City(object):
    def __init__(self, name):
        self.name = name

    def __eq__(self, other):
        return self.name == other

    def __hash__(self):
        return hash(self.name)

rawDescription: Having two keys for each value in dictionary


code:
import os, io, sh
stream = io.BytesIO()
sh.cat('some/file', _out=stream)
sh.ls('some/folder', _out=stream)
stream.seek(0)
sh.wc('-l', _in=stream)

rawDescription: Python sh: merge results and pipe

description: Python sh: merge results and pipe


code:
soup = BeautifulSoup(response, 'html5lib')
soup = BeautifulSoup(response, 'lxml')

rawDescription: Extracting <a> tags using BeautifulSoup

description: Extracting <a> tags using BeautifulSoup


code:
for val in doh.split():
    if val.startswith("@"):  # this is a command
        do_commandy_stuff(val)
    else:   # this is a word
        do_wordy_stuff(val)

rawDescription: hmm, lists, tuples, arrays, sets or dicts for this data structure?

description: Hmm, lists, tuples, arrays, sets or dicts for this data structure


code:
import collections
import itertools as IT

def find_shortest_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if start not in graph:
        return None
    shortest = None
    for node in graph[start]:
        if node not in path:
            newpath = find_shortest_path(graph, node, end, path)
            if newpath:
                if not shortest or len(newpath) < len(shortest):
                    shortest = newpath
    return shortest

G={'a':['b','c'], 'c':['d']}

for node1, node2 in IT.combinations(list('abcd'), 2):
    print('{} -> {}: {}'.format(node1, node2, find_shortest_path(G, node1, node2)))

rawDescription: Python: path between nodes in directed graph


code: MyMessageBox(None, "Hello world!", "Title", MB_OK, "favicon.ico")

rawDescription: How to include image in Message Box using ctypes in python

description: Include image in Message Box using ctypes in python


code:
top_row = 0
bottom_row = 0
left_column = 0
right_column = 1
sheet.write_merge(top_row, bottom_row, left_column, right_column, 'Long Cell')

rawDescription: How to write a cell with multiple columns in xlwt?

description: Write a cell with multiple columns in xlwt


code:
def build(self):
    layout = BoxLayout(spacing=10, orientation='vertical')
    b = BoxLayout(spacing=0)

    self.btn1 = Button(text='opacity 40%', size_hint=(.2, .2))
    self.btn3 = Button(text='opacity 20%', size_hint=(.2, .2))
    self.btn4 = Button(text='opacity 10%', size_hint=(.2, .2))
    self.btn5 = Button(text='opacity 0%', size_hint=(.2, .2))

    b.add_widget(self.btn1)
    b.add_widget(self.btn3)
    b.add_widget(self.btn4)
    b.add_widget(self.btn5)
    layout.add_widget(b)

    self.background = MyBackground(size_hint=(1, 10))

    layout.add_widget(self.background)
    painter = MyPaintWidget()
    layout.add_widget(painter)

    self.btn1.bind(on_press=self.set_opacity)
    self.btn3.bind(on_press=self.set_opacity)
    self.btn4.bind(on_press=self.set_opacity)
    self.btn5.bind(on_press=self.set_opacity)

    return layout

def set_opacity(self,widget):
    if widget is self.btn1:
        self.background.opacity = 0.40
    elif widget is self.btn3:
        self.background.opacity = 0.20
    elif widget is self.btn4:
        self.background.opacity = 0.10
    elif widget is self.btn5:
        self.background.opacity = 0.00

rawDescription: How to change opacity when pressing buttons on kivy

description: Change opacity when pressing buttons on kivy


code:
def myDecorator (f):
    print('Decorated {0}'.format(f.__name__))
    return f

rawDescription: Does a python decorator just decorate the following function or all functions beneath?


code:
name = 'John'
surname = 'Smith'
age = 87
'My name is %(surname)s, %(name)s %(surname)s. I am %(age)i.' % locals()

rawDescription: String formatting options: pros and cons


code:
tmp = test[0]
tmp[0] = 1
test[0] = tmp

rawDescription: Python: Using a multidimensional multiprocessing.manager.list()


code:
def __repr__(self):
    return "<Token %s>" % self.id   # or wherever `X9999` is stored

Token.__repr__ = __repr__

rawDescription: Debugger attribute view for python

description: Debugger attribute view for python


code:
def handle(self):
    mycustomdata = self.server.mycustomdata()

rawDescription: Passing extra metadata to a RequestHandler using python's SocketServer and Children


rawDescription: numpy.nextafter decrementing instead of incrementing

description: Numpy.nextafter decrementing instead of incrementing


code: matrixK = zip(*[row for i, row in enumerate(zip(*matrixK)) if i % 2])

rawDescription: Delete columns from matrix according to its index


code: professor = lambda x: [line for line in x if line[1] == "Professor"]

rawDescription: Trying to filter a list to bring back lines with a specific word


code:
def __hash__(self):
    return hash(self.name)

rawDescription: Python, represent non-string object as string?


code:
from gi.repository import Gtk

def draw_cb(widget, cr):
  cr.set_source_rgba(0,0,0,0.5)
  cr.rectangle(50,75,100,100)
  cr.fill()
  return False

win = Gtk.Window()

win.set_title("test")
win.set_default_size(800,600)
win.connect('delete-event', Gtk.main_quit)
da=Gtk.DrawingArea()
da.connect('draw', draw_cb)
win.add(da)
win.show_all()
Gtk.main()

rawDescription: Cairo and Gdk.Window with Gtk.DrawingArea using python gobject-introspection and gtk3


code:
def erase_supply():
    '''Clear the list of supply values'''
    global S1Vals
    S1Vals = []

rawDescription: Python 2.7: Function accessing a list

description: Python 2.7: Function accessing a list


code:
[
    { '_id': 'mydata.number', 'next': 5 }
]

rawDescription: Atomically determine the "next" number in a MongoDB collection and assign it to a new document


code:
def worker():
    while True:
        crunchData()

# ... somewhere in the daemon startup code ...
t = threading.Thread(target=worker)
t.daemon = True
t.start()

rawDescription: How to use Daemon that has a while loop?

description: Use Daemon that has a while loop


rawDescription: How can we change data type of a dataframe row in pandas?


code:
from subprocess import call
retcode = call(["/full/path/myscript.py", "arg1"])

rawDescription: django- run a script from admin

description: Django- run a script from admin


code: response = urllib.urlopen(url)

rawDescription: Display Specific Fields (Through Parse) from JSON response in Python


rawDescription: Pushing all elements of a python list one element earlier


code:
pyplot.plot(time, bananas, 'k-', linewidth='2')
pyplot.show()

rawDescription: How to set limits to specific components of an equation when plotting them?

description: Set limits to specific components of an equation when plotting them


code:
try:
    import argparse
except ImportError:
    import optparse
    parser = optparse.OptionParser()
    add_func = parser.add_option
else:
    parser = argparse.ArgumentParser()
    add_func = parser.add_argument

for arg in args:
    add_func(*arg["args"], **arg["kwargs"])

rawDescription: Python: how to write code that looks nicely and works with argparse or optparse?


code: new = [{k.upper(): v for k, v in r.iteritems()} for r in reader]

rawDescription: DictReader change keys to upper

description: DictReader change keys to upper


code:
with open("test.txt") as f:
    for line in f:
        if "Get location" in line:
            data = line.rsplit(None,1)[1]
            print(data.strip("()").split(",", 2)[:2])

rawDescription: Python - extracting particular numbers from each line in a file


code:
n = len(sentences)

values = []
for i in range(0, n):
  inner = []
  for j in range(0, n):
    inner.append(self.sentences_intersection(sentences[i], sentences[j]))
  values.append(inner)

rawDescription: How is this 2D array being sized by FOR loops?


code:
new_result = pandas.DataFrame(
    result.values.tolist(),
    index=df.index,
    columns=('column1', 'column2'))

rawDescription: Getting specific list element from a series


code:
def die():
    raise Exception()

whatever() or die()

rawDescription: Terse error-checking in Python

description: Terse error-checking in Python


code:
for line in page:
    for word in line.split():
        word

rawDescription: Complex Python List Comprehension

description: Complex Python List Comprehension


code:
words = MyWords()
words.pick_starting_point()
...

rawDescription: Accessing List from outside function

description: Accessing List from outside function


code:
from twisted.test.proto_helpers import MemoryReactor
from twisted.web.client import Agent
fake_reactor = MemoryReactor()
agent = Agent(fake_reactor)
d = agentGetPage(agent, "http://example.com")

assert fake_reactor.tcpClients  # or some such, exercise the code by manipulating the reactor

rawDescription: Twisted / perform asynchronous http requests


rawDescription: Why does Elixir/SQLAlchemy's session.bind get set to None within threads?


code:
import csv

links = []

with open('urls.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    # Simple example where only a single column of URL's is present
    links = list(csv_reader)

rawDescription: Using multiple web pages in a web scraper


code:
print('lastname\tpersontype\taffiliation\n')
for last in lastname:
    if last in names:
        full = names[last]
        if full in affiliations:
            comp = affiliations[full]
            if comp in companies:
                print(full+'\t1\t'+comp)
            else:
                print(full+'\t0\tNone')
        else:
            print(full+' is not listed in affiliations.')
    else:
        print(last+' has no matches in names.')
    print('\n')

rawDescription: In python: How to find match of string in same row, compare part of (fuzzy) matched string to list?


code:
dict[a] = requests.get(url1)
dict[a] = requests.get(url2)

rawDescription: Does response from requests.get() use the same memory or allocates new memory each time in python?


code:
import geetree
t = geetree.GeeTree('foo.xml')
t.xml_api_reply.weather.forecast_information.city['data']
t.xml_api_reply.weather.current_conditions.temp_f['data']

rawDescription: Really simple way to deal with XML in Python?


code:
import android #for bluetooth functions
import time #for waiting

#get everything setup
droid = android.Android()

#turn on bluetooth
droid.toggleBluetoothState(True)

#ask user
droid.dialogCreateAlert('Be a server?')
droid.dialogSetPositiveButtonText('Yes')
droid.dialogSetNegativeButtonText('No')
droid.dialogShow()

#get user response to question
result = droid.dialogGetResponse()

#if the result is 'Yes' ('positive') then is_server is set to True
is_server = result.result['which'] == 'positive'

if is_server:
  #so if is_server is true make the device discoverable and accept the next connection
  droid.bluetoothMakeDiscoverable()
  droid.bluetoothAccept()
else:
  #attempts to connect to a device over bluetooth, the logic being that if the phone
  #is not receiving a connection then the user is attempting to connect to something
  droid.bluetoothConnect()

if is_server:
  result = droid.getInput('Chat', 'Enter a message').result #Gets a message to send
  #via bluetooth
  if result is None:
    droid.exit() #exit if nothing is in the message
  droid.bluetoothWrite(result + '\n') #otherwise write the message

while True: #receives a message
  message = droid.bluetoothReadLine().result
  droid.dialogCreateAlert('Chat Received', message)
  droid.dialogSetPositiveButtonText('Ok')
  droid.dialogShow()
  droid.dialogGetResponse()
  result = droid.getInput('Chat', 'Enter a message').result
  if result is None:
    break
  droid.bluetoothWrite(result + '\n')

droid.exit()

rawDescription: Using SL4A (Python) and bluetooth

description: Using SL4A (Python) and bluetooth


rawDescription: binary to hex dictionary

description: Binary to hex dictionary


rawDescription: How to find the index of n largest elements in a list or np.array, Python

description: Find the index of n largest elements in a list or np.array, Python


code: "long sentence"

rawDescription: Pythonically remove the first X words of a string


rawDescription: Django templates: model.image.url gets relative url, how to get full domain url?


code:
with open(outfile, 'wb') as out_strm:
    dill.dump(datastruct, out_strm)

rawDescription: Loading a pkl file using dill

description: Loading a pkl file using dill


code: make_fn = RandomItemGenerator([sword_fn, dagger_fn, wand_fn], [80, 19, 1])

rawDescription: Pythonic way of percentagechance

description: Pythonic way of percentagechance


code:
df['game_count'] = 1
rolling_games_count = df.set_index('Date').groupby('Team').apply(lambda x: pd.rolling_count(x, window=5, freq='D')).reset_index()
df = df.drop('game_count', axis=1).merge(rolling_games_count, on=['Team', 'Date'], how='left')

rawDescription: count of last n days per group

description: Count of last n days per group


code:
ellipse = lambda x0, y0, r_x, r_y: lambda x, y: ((x - x0) / r_x)**2 + ((y - y0) / r_y)**2

def gen_ellipse(el, lower, upper, step):
    coords = np.arange(lower, upper, step)
    x, y = np.meshgrid(coords, coords)
    mask = el(x, y)
    mask[np.where(mask > 1)] = 0
    return 1 - mask

rawDescription: computing weight based on distance from centre of ellipse

description: Computing weight based on distance from centre of ellipse


rawDescription: Numpy: How to elementwise-multiply two vectors, shape (n,1) and (n,)?


code:
sorted(['hello', 'foo', 'bar'], key=str.lower)
sorted(['hello', 'foo', 'bar'], key=len)

rawDescription: Discuss the "sorted" function in Python

description: Discuss the "sorted" function in Python


code:
X = range(4, 7)
X
X[-1]    # 1st element from last
X[-3]    # 3rd element from last

rawDescription: Explain the output of this code with nested ranges


rawDescription: InputFile Loops Handling Two data

description: InputFile Loops Handling Two data


code:
import numpy as np
import pandas as pd
np.random.seed(2015)

defT = pd.DataFrame({'AgeGrp': [1, 2, 3, 4, 5, 6, 7],
                     'MaxAge': [18, 21, 24, 34, 44, 54, 65],
                     'MinAge': [14, 19, 22, 25, 35, 45, 55]})

cutoff = np.hstack([np.array(defT['MinAge'][0]), defT['MaxAge'].values])
labels = defT['AgeGrp']

N = 50
df = pd.DataFrame(np.random.randint(100, size=(N,2)), columns=['Age', 'Year'])
df['ageGrp'] = pd.cut(df['Age'], bins=cutoff, labels=labels, include_lowest=True)

grouped = df.groupby(['Year', 'ageGrp'], as_index=False)
final = grouped.agg(np.sum)
print(final)
#              Year  ageGrp  Age
# Year ageGrp
# 3    1        NaN     NaN  NaN
#      2        NaN     NaN  NaN
# ...
# 97   1        NaN     NaN  NaN
#      2        NaN     NaN  NaN
# [294 rows x 3 columns]

rawDescription: Python pandas.cut

description: Python pandas.cut


rawDescription: Smart way to remove mutual edges with python-igraph 0.7


rawDescription: Select random element from "non uniform" python dictionary


code: timestr + 'lognew.html'

rawDescription: I would like to copy a file to a new directory and then rename it using the datetime :: Python


code: sum([sum(len(sent) for sent in inaugural.sents(fileids=[fileid])) for fileid in inaugural.fileids()]) / len(inaugural.fileids())

rawDescription: Average sentence length for every text in corpus (python3 & nltk)


code: value in dictionary or any(value == dictionary[key] for key in dictionary)

rawDescription: Using 'if in' with a dictionary

description: Using 'if in' with a dictionary


key: value

rawDescription: mongodb: insert if not exists

description: Mongodb: insert if not exists


rawDescription: Extraction Specific Lines From A Website


rawDescription: Create multi-level index pandas dataframe from delimited string column


code:
[list(map(str, i)) for i in [sorted(map(int, i)) for i in lst]]
[sorted(i, key=lambda x: int(x)) for i in lst]

rawDescription: How do I get the correct result in the list of lists sorting in python

description: Get the correct result in the list of lists sorting in python


code:
a = np.ones((2,2,2))
a = a[None, :]  # Adds an dimension as first

rawDescription: adding matrices to n dimensional array with numpy

description: Adding matrices to n dimensional array with numpy


rawDescription: Exporting a 2D array with 0-values into a txt/csv file


code:
import matplotlib.pyplot as plt
import pyscreenshot as ImageGrab

def saveSnapshot():
    im = ImageGrab.grab()
    plt.imshow(im)
    plt.show()

rawDescription: how to directly convert wxpython image to pyplot image without saving

description: Directly convert wxpython image to pyplot image without saving


code: os.chown(path, uid, gid)

rawDescription: How to set a files owner in python?

description: Set a files owner in python


code: pprint(["http://www.fetise.com/" + i if "http://www.fetise.com/" not in i else i for i in lista])

rawDescription: How to use Python condensed For loop with if else

description: Use Python condensed For loop with if else


code:
import re
import sys

for line in sys.stdin:
    sys.stdout.write(re.sub(r'(<something>)REPLACEME(</something>)',
                            r'\1NEWWORD\2',
                            line))

rawDescription: Manipulating stdin and redirect to stdout in Python


rawDescription: Efficiently check if numpy ndarray values are strictly increasing


code:
if all((numpy.all(array_to_add != a) for a in array_list)):
    array_list.append(array_to_add)

rawDescription: Better way to find existence of arrays in list of arrays


code: from java.lang import Math

rawDescription: Instantiating object in Python same as Java using jython


code:
my_dict = {'a': 2}
my_dict.get('a', False)
my_dict.get('b', False)

rawDescription: a python function that returns the value of a dictionary

description: A python function that returns the value of a dictionary


code:
def tearDown(self):
    for filename in self.to_be_removed:
        os.unlink(filename)

rawDescription: Unittest tearDown() method depends on finished test


code:
a = np.arange(2*2*2).reshape((2,2,2))
a
a.flatten()
np.swapaxes(a,2,1).flatten()

rawDescription: Numpy: Striding a multiple channel image


code:
#!/usr/bin/env python2

from __future__ import print_function
import time, sys

print('Header')
print('some text')
print('some text')
print('-' * 40)
print('Progress:')
print('')
print('I want this line too')

sys.stdout.write('\x1b[1A' * 2)
i = 1
while True:
        if i > 40: break

        print('\r', '*' * i, sep='')
        sys.stdout.write('\x1b[1A')
        sys.stdout.flush()
        i += 1
        time.sleep(2)

rawDescription: Subprocess– showing X lines of output

description: Subprocess– showing X lines of output


rawDescription: Preprocessing form data before using it

description: Preprocessing form data before using it


code: i

rawDescription: How to obtain different types of range in an array

description: Obtain different types of range in an array


code: g.filter(lambda x: x['B'].sum() == 5)

rawDescription: pandas: what is the equivalent of SQL group by having?

description: Pandas: what is the equivalent of SQL group by having


code:
# custom_pipeline.py

from social.pipeline.partial import partial
from django.contrib import messages
from django.shortcuts import redirect

def clean_pipeline(strategy, *args, **kwargs):
        _register = strategy.session.get('register', None)
        strategy.session.flush()
        strategy.session['register'] = _register

@partial
def redirect_to_join_form(strategy, details, user=None, is_new=False, *args, **kwargs):
    if user and user.username:
        return
    if is_new and strategy.session_get('register', False) == '1':
        strategy.session.pop('register')
        return redirect('users_join_form')
    if is_new and strategy.session_get('saved_username'):
        return {'username': strategy.session_get('saved_username')}
    messages.add_message(
        strategy.request, messages.ERROR,
        "Error. Account not registered %s (%s), " %
        (strategy.backend.name.capitalize(), details['username'])
    )
    return redirect('users_login')

rawDescription: Login vs Register in PythonSocialAuth

description: Login vs Register in PythonSocialAuth


code:
import matplotlib.pyplot as plt
import networkx as nx

G = nx.balanced_tree(2,5)
length = nx.shortest_path_length(G, source=0)
nodelist,hops = zip(*length.items())
positions = nx.graphviz_layout(G, prog='twopi', root=0)
nx.draw(G, positions, nodelist = nodelist, node_color=hops, cmap=plt.cm.Blues)
plt.axis('equal')
plt.show()

rawDescription: Python: Network Spring Layout with different color nodes


rawDescription: comparing ndarray with values in 1D array to get a mask

description: Comparing ndarray with values in 1D array to get a mask


code:
X
Y

rawDescription: Splitting pandas data frame based on column name


code:
class Spam(models.Model):
    foo_type = models.WhateverFieldType(editable=False, choices=FOO_TYPE_CHOICES)
    # ... other fields

rawDescription: Django Different form validation when adding and changing instance


code: '%s, %s, %s, and a %s' % tuple(cars)

rawDescription: Pass dbf data to sentence and save as text file using Python 2.7


rawDescription: Best way to hash ordered permutation of [1,9]

description: Hash ordered permutation of [1,9]


code:
COLS = ['CUST', 'MODEL', 'SN', 'DATE', 'CHARGE', 'QTY', 'TOTAL']
with open('UserfeeInvoicing.csv', 'r') as infile:
    reader = csv.DictReader(infile, fieldnames=COLS)
    ranpak_dict = {row['SN']: row for row in reader}

rawDescription: Add key/values to dictionary using condition


code:
x = Thing(5)
print(x.id)      #prints 5
y = Thing()
print(y.id)      #prints 6

rawDescription: initialize itertools count in library from database query

description: Initialize itertools count in library from database query


rawDescription: Looping over a tuple in jinja2

description: Looping over a tuple in jinja2


code:
def iterate(i):
    for value in i:
        yield value
    return

rawDescription: Using for...else in Python generators

description: Using for...else in Python generators


code:
#!/usr/bin/python3
import time

ID = slice(17,24)
Voltage = slice(25,29)

with open("output.json", "r") as f:  # use with block to open the file
    k = f.readlines()                # read the entire file

line = k[-1]                     # take the last line only
i, v = line[ID].strip(), line[Voltage].strip()   # unpack the line contents

if i or v:                       # ensure there is something to print
    print("ID: {}\tVoltage: {}".format(i, v))

rawDescription: Python, reading and slicing text in realtime and uploading to online


code:
import git
r = git.Repo()
short = r.git.rev_parse(r.head, short=True)
print(short)
# u'f360ecd'

rawDescription: How to get the unique part of a ref ID with GitPython?

description: Get the unique part of a ref ID with GitPython


code:
def mutate_arr(arr, done, stop):
    with done:
        arr[::4096] = 1
        S = np.sum(arr)
        print(S)
        done.notify()
    while not stop.is_set():
        sleep(1)

rawDescription: Why does my loop require more memory on each iteration?


code: db = create_engine('sqlite:///CDR.db',echo=True) # Change `echo` from False to True

rawDescription: How to implement session.add on this code:

description: Implement session.add on this code:


code:
def reverse_sentences(text):
    sentences = text.split('.')
    reversed_words = (reversed(words.split()) for words in sentences)
    rejoined_words = (' '.join(words) for words in reversed_words)
    capitalized_sentences = (sentence.capitalize() for sentence in rejoined_words)
    return '. '.join(capitalized_sentences)

reverse_sentences("One two three. Four five six.")

rawDescription: Faster and more consise way to reverse sentences in a string?


code:
import csv
from itertools import groupby
grouper = lambda rec: len(rec) > 0
with open("data.txt") as f:
    reader = csv.reader(f, delimiter=" ")
    res = [list(items) for group, items in groupby(reader, key=grouper) if group]
res

rawDescription: Dealing with a list of lists in Python and selecting a subset of lists


code:
df['marks'] = df.apply(lambda x: [x[['chemistry', 'physics']].to_dict()], axis=1)
df

rawDescription: Merging 2 list of dicts based on common values


code:
import re

from bs4 import BeautifulSoup, Comment

data = """

 Name of Article

First Paragraph I want

More Html I'm interested in

 Subheading in the article I also want

Even more Html i want blah blah blah

 References

Html I want commented out

"""

soup = BeautifulSoup(data, "lxml")
elm = soup.find("h2", text=re.compile("References"))
elm.replace_with(Comment(str(elm)))

print(soup.prettify())

rawDescription: Beautiful Soup: Best ways to comment out a tag instead of extracting it?


code: health = wordfont.render(("Your health: ", self.a,), 1, (255, 9, 12))

rawDescription: pygame text variables

description: Pygame text variables


code:
drives = ['{}:\\' for letter in 'CDEFGHIJKLMNOPQRSTUVWXYZ']
for drive in drives:
    if os.path.isdir(drive):
        filepath = find_file(target, drive)
        if filepath is not None:
            break

rawDescription: Search all drives for a file

description: Search all drives for a file


code: A.SetParameters(a = 2.2, d = 4.3, b = 9.3)

rawDescription: Boost::Python- possible to automatically convert from dict --> std::map?


code:
import numpy as np

num_vars = 10**4
cov = np.zeros((num_vars, num_vars), dtype=float)

rawDescription: Building a covariance matrix in Python

description: Building a covariance matrix in Python


code:
{"string": "test",
 "number": 42,
 "array": [1, 2, 3],
 "js_object": {foo: "bar"}}

rawDescription: django: control json serialization

description: Django: control json serialization


rawDescription: Django cannot access all objects in a model


code:
import xlrd, itertools

with xlrd.open_workbook("test.xlsx") as workbook:
    sheet = workbook.sheet_by_index(0)

    flat_data = (sheet.cell_value(i, 0) for i in range(sheet.nrows))
    grouped_data = [list(group) for key, group in itertools.groupby(flat_data)]

rawDescription: Grouping equal values from an array into subarrays


code:
validLine = dblQuotedString("key") + COMMA + dblQuotedString("title") + COMMA + \
        integer("qty") + COMMA + floatnum("price") + LineEnd()

rawDescription: Verify CSV against given format

description: Verify CSV against given format


code:
import pickle
sys.stdout = open('demo.txt',"w");
from nltk.tokenize import word_tokenize
from textblob.classifiers import NaiveBayesClassifier
cl = pickle.load( open( "classifier.pickle", "rb" ) )
print(cl.classify("text to classify"))

rawDescription: python textblob and text classification

description: Python textblob and text classification


code:
def prev_dates(g):
    g.sort(columns=['date'])
    g['prev'] = g.date.shift(-1)
    return g

rawDescription: Pandas get previous dataframe row by date


code:
[item                         #result = []
    for subl in m             #for subl in m:
        for item in subl]     #    for item in subl:
                              #        result.append(item)

rawDescription: Converting matrix to an array in python

description: Converting matrix to an array in python


code:
for ul in soup.find_all('ul', class_='listing'):
    for li in ul.find_all('li'):
        a = li.find('a')
        print(a['href'], a.get_text())

rawDescription: python BeautifulSoup get all href in Children of div

description: Python BeautifulSoup get all href in Children of div


rawDescription: Sorting data for plotting in mplot3d

description: Sorting data for plotting in mplot3d


rawDescription: Running exactly x number of commands

description: Running exactly x number of commands


code:
list_of_tuples = [('day1', 'name1', 'value1'), ('day2', 'name2', 'value2'), ('day3', 'name3', 'value3')]
[list(t) for t in zip(*list_of_tuples)]

rawDescription: Most pythonic way to convert a list of tuples


rawDescription: How do you convert a string to a function in python?

description: Convert a string to a function in python


code:
FLOW = flow_from_clientsecrets(
    CLIENT_SECRETS,
    scope=[ GOOGLE_PLUS_SCOPE, YOUTUBE_READONLY_SCOPE ],
    redirect_uri='http://127.0.0.1:8000/youtube/oauth2callback')

rawDescription: Get user info from YouTube Google API in Python (API v3)


code:
import re
if matches:
    extracted = [(re.search(m, postal_addr).start() , m) for m in matches ]
    extracted = sorted( extracted )[-1][1]

rawDescription: Python - match a word in a string with a list of strings


rawDescription: Python Pandas merge two data frames based on multiple values field


code:
class FormA(forms.Form):
    first = forms.DecimalField()
    second = forms.CharField(max_length = 4)

class FormB(forms.Form):
    third = forms.CharField(max_length = 1)

rawDescription: Django formset - Creating a formset of just ONE form


code:
# Original inputs
calcF(G,A)
vectorized_calcF(G,A) # Posted solution

rawDescription: Product of a sequence in NumPy

description: Product of a sequence in NumPy


code:
with open('file.txt', 'r') as f: #open the file
    contents = f.readlines() #put the lines to a variable (list).
    print(contents)

rawDescription: How to Open a file through python

description: Open a file through python


code:
def getBufferRow(self, index):
   row = {}
   for key in self.columns:
       row[key] = self.columns[key][index]
   return Row(self, index, row)

rawDescription: __getitem__, __setitem__ multiple keys Python


code:
def antonyms():
    f = open('antonyms.txt', 'r+')
    for line in f:
        a = line.split(' || ') # Think you also need surrounding spaces here.
        x = a[0]
        y = a[1]
        yield x, y

rawDescription: Reading from a python file

description: Reading from a python file


code:
from django import template

register = template.Library()

class IsProductionAreaNode(template.Node):
    def __init__(self, nodelist):
        self.nodelist = nodelist

    def render(self, context):
        if settings.SETTINGS_MODE == 'Production':
            return self.nodelist.render(context)
        else:
            return ''

def do_is_production(parser, token):
    nodelist = parser.parse(('endis_production',))
    parser.delete_first_token()
    return IsProductionAreaNode(nodelist)

register.tag('is_production', do_is_production)

rawDescription: Template tag is not working as intended in if-sentence


code: any_in = lambda a, b: bool(set(a).intersection(b))

rawDescription: one-liner to check if at least one item in list exists in another list?

description: One-liner to check if at least one item in list exists in another list


rawDescription: Best way to regroup a string into a list of 2-character string

description: Regroup a string into a list of 2-character string


code:
assert aware.tzinfo is not None and aware.utcoffset() is not None
# local time = utc time + utc offset (by definition)
# -> utc = local - offset
naive_utc = aware.replace(tzinfo=None) - aware.utcoffset()

rawDescription: How to remove the tzinfo completely from the time after converting to UTC in Python?

description: Remove the tzinfo completely from the time after converting to UTC in Python


code:
mylist[0][1] == 'Bob'  # True
mylist[1][2] == 'Alice'  # True

rawDescription: How to store two different values returned from query into list data types to be used later(plpy python)

description: Store two different values returned from query into list data types to be used later(plpy python)


code:
se = ((x, x+1) for x in range(5))
next(se)
next(se)

rawDescription: Getting two values from one range

description: Getting two values from one range


code:
def strip_ns_prefix(tree):
    #xpath query for selecting all element nodes in namespace
    query = "descendant-or-self::*[namespace-uri()!='']"
    #for each element returned by the above xpath query...
    for element in tree.xpath(query):
        #replace element name with it's local name
        element.tag = etree.QName(element).localname
    return tree

rawDescription: How can I strip namespaces out of an lxml tree?

description: Strip namespaces out of an lxml tree


code: x, y = data_final

rawDescription: Assign part of a string to a variable [Python]


code:
sort_map = {d['sortkey']: d['value'] for d in secondlist}

sorted(firstlist, key=lambda d: sort_map[d['sortkey']])

rawDescription: Sorting list of dictionaries using the values from another list of dictionaries


code:
hand = [{'rank':10, 'suit':'Spade'}, {'rank':11, 'suit':'Heart'}, {'rank':9, 'suit':'Spade'}, {'rank':12, 'suit':'Spade'}, {'rank':8, 'suit':'Spade'}]
rank_set = set([card['rank'] for card in hand])
rank_set
is_straight = (max(rank_set) - min(rank_set) + 1) == len(hand) and len(rank_set) == len(hand)
is_straight

rawDescription: Identifying a 'straight' (from Poker) using Python


code:
def withrepr(reprfun):
    def _wrap(func):
        return reprwrapper(reprfun, func)
    return _wrap

rawDescription: Possible to change a function's repr in python?


code:
def function(**kwargs):
    values = dict([i for i in kwargs.iteritems() if i[1] != None])
    if not values:
        raise Exception("foo")
    return values

rawDescription: What is an elegant way to select all non-None elements from parameters and place them in a python dictionary?


code: file_qs = file_qs.order_by('order')

rawDescription: How do you get Django's filer app to list new files at the top of the list?

description: Get Django's filer app to list new files at the top of the list


code: shortword.sub('', anytext)

rawDescription: Remove small words using Python

description: Remove small words using Python


rawDescription: How to switch tasks between queues in Celery

description: Switch tasks between queues in Celery


code:
for key in newvars:
    if key in oldvars:
        # this copies the value from the old file if the key exists in there
        value =  oldvars[key]
    else:
        # ask the user for a new value
        value = raw_input("Enter the value ")
    # update the value in newvars
    newvars[key] = value
# and write the update mapping back
with open("/home/ubuntu/tmp/deploy/all", 'w') as f2:
     ruamel.yaml.round_trip_dump(newvars, f2)

rawDescription: Copy content from one YAML to another YAML after comparison of keys


code:
## swigMock.py ##
def aFunc(aString):
    return aString

rawDescription: how do I create a in-line module

description: Create a in-line module


code:
class Base(object):
    __metaclass__ = Meta

    subclasses = {}

    @classmethod
    def extending(cls, subclass):
        cls.subclasses[subclass.__name__] = subclass

class Extend1(Base):
    pass

class Extend2(Base):
    pass

rawDescription: Execute code when extending a class in Python


code: http = urllib3.PoolManager(10, header=user_agent)

rawDescription: urllib3 download a file using specified user agent

description: Urllib3 download a file using specified user agent


code:
lista=('a','b','c')
listb=('a1','b1','c1','d1','a2','b2','c2','d2','a3','b3','c3','d3')

def gen_combos(li, keepers, builder=tuple()):
    if not keepers:
        yield builder
    else:
        for i,x in enumerate(li):
            if x.startswith(keepers[0]):
                for combo in gen_combos(li[i+1:], keepers[1:], builder + (x,)):
                    yield combo

rawDescription: Python Permutation with Limits and Directionality


code: line == 'hello  there!'

rawDescription: Removing specific strings

description: Removing specific strings


code:
# main.py
import socket
from functions import *

sock = socket.socket ()
sock.connect ((config['server']['host'], config['server']['poort']))
sendMessage (sock, receiver, config['nick'] + ' is here!')

rawDescription: NameError: global name 'sock' is not defined


code:
def bases(words):
    base = next(words)
    yield base
    for word in words:
        if word and not word.startswith(base):
            yield word
            base = word

def get_bases(infile, outfile):
    with open(infile) as f_in:
        words = (line.strip() for line in f_in)
        with open(outfile, 'w') as f_out:
            f_out.writelines(word + '\n' for word in bases(words))

rawDescription: Python- need fast algorithm that removes all words in a file that are derivatives in other words


code:
import numpy as np
import scipy.sparse as sps

data = np.genfromtxt('data.txt', dtype=[('from', np.intp),
                                        ('to', np.intp),
                                        ('weight', np.float)])

rawDescription: How to read a sparse directed graph in scipy

description: Read a sparse directed graph in scipy


code:
from itertools import takewhile
val = ''.join(takewhile(lambda c: c.isdigit() or c in ',.', val))

rawDescription: how to clean or convert unknown characters in an otherwise integer field in python?

description: Clean or convert unknown characters in an otherwise integer field in python


code:
def contains(a, b):
    for v in b:
        for u in a:
            if v == u:
                break
        else:
            return False
    return True

rawDescription: How can I use python code which will iterate into two list and will find out whether they matches or not

description: Use python code which will iterate into two list and will find out whether they matches or not


code:
# x axis: one point per key in the Counter (=unique tuple)
x=range(len(c))
# y axis: count for each tuple, sorted by tuple value
y=[c[key] for key in sorted(c)]
# labels for x axis: tuple as strings
xlabels=[str(t) for t in sorted(c)]

# plot
plt.bar(x,y,width=1)
# set the labels at the middle of the bars
plt.xticks([x+0.5 for x in x],xlabels)

rawDescription: Plotting histogram of list of tuplets matplotlib


code:
res = obfuscation(character_list)
res
len(res)
all(len(v) == 63 for v in res.values())

rawDescription: itertools.izip (and _longest) dictionary incomplete

description: Itertools.izip (and _longest) dictionary incomplete


code:
from timeit import Timer

def testCustomHeapStartUp(*args):
    h = MinHeap(args[0])
    return True

if __name__ == "__main__":
    for i in range(3):
        testList = random.sample(range(100), 100)
        t = Timer(
            "testCustomHeapStartUp(testList)",
            "from __main__ import testCustomHeapStartUp; from __main__ import testList; gc.enabled()",
            )
        print(t.timeit())

rawDescription: Timeit not returning actual time

description: Timeit not returning actual time


code:
def show_dialog(self, line_edit):
    ...
    line_edit.setText(...)

for button, line_edit in zip(buttons, line_edits):
    button.clicked.connect(functools.partial(self.show_dialog, line_edit))

rawDescription: pyside / pyqt: simple way to bind multiple buttons that shares the same functionality

description: Pyside / pyqt: simple way to bind multiple buttons that shares the same functionality


code:
WM_KEYDOWN = 0x0100
WM_KEYUP = 0x0101

def point_to_long(x, y):
    return (y * 0x10000) + x

def show_menu(handle):
    target_pos = point_to_long(30, 40)
    send_message(window_handle, WM_LBUTTONDOWN, 0, target_pos)
    send_message(window_handle, WM_LBUTTONUP, 0, target_pos)

rawDescription: Display menu bar items of IE using Python


rawDescription: Finding the two closest numbers in a list using sorting


code:
first_part_dict
second_part_dict

rawDescription: Getting index of structured elements of a list into dictionaries based on regex


code:
it = iter(my_list)
dict(enumerate(zip(it, it), start=1))

rawDescription: Create ranked dict with list comprehension


code:
import urllib2
key = "mykey"
URL = "https://sb-ssl.google.com/safebrowsing/api/lookup?client=python&apikey={key}&appver=1.0&pver=3.0&url={url}"

def is_safe(key, url):
    response = urllib2.urlopen(URL.format(key=key, url=url))
    return response.read().decode("utf8") != 'malware'

print(is_safe(key, "http://www.gumblar.cn/599"))

rawDescription: Unable to use google search browsing api lookup in python


rawDescription: Newick tree representation to scipy.cluster.hierarchy linkage matrix format


code:
import random
[int(random.expovariate(0.001)) for i in range(10)]

rawDescription: how to generate integer inter arrival times using random.expovariate() in python

description: Generate integer inter arrival times using random.expovariate() in python


code:
complete_list = {'x': [[]], 'y': [], 'z': [[1]]}
{k: v for k, v in complete_list.iteritems() if v and v[0]}
# returns {'z': [[1]]}

rawDescription: Removing empty dictionary elements in Python


code:
import datetime
from dateutil.relativedelta import relativedelta
today = datetime.date.today()
start = datetime.date(2007, 1, 31)
period = relativedelta(months=1)
delta = period
while start + delta < today:
    delta += period

delta
start + delta

rawDescription: Divide two timespans by eachother in Python/dateutil


code:
d = mydict
for index in lst[:i+1]:
  d = d[index]

rawDescription: Python: loop through a list using all previous indexes with each index


code:
due_date_expr = '(implementation of your logic in SQL)'
taskList = Task.objects.all().extra(select={'due_date': due_date_expr}).order_by('priority_id', 'due_date', 'title')

rawDescription: How to sort a Django QuerySet by (field, custom function, field)

description: Sort a Django QuerySet by (field, custom function, field)


code:
import funcy
from functools import partial

composition = funcy.rcompose(
    partial(func1, additional_arg_name=something),
    ...
)

rawDescription: Python 3 control flow in script with lots of steps


rawDescription: Cartesian product that returns outputs of varied lengths


code:
import numpy as np
help(np.loadtxt)

rawDescription: numpy.loadtxt Skipping multiple rows

description: Numpy.loadtxt Skipping multiple rows


code:
center_y[nrow-1,:] = 0.5*deltay[nrow-1]
center_y[:nrow-1, :] = 0.5*deltay[1:] + 0.5*deltay[:nrow-1]
# expl: deltay[i+1] in the loop skips the first element, deltay[i] skips the last element
for i in range(nrow-2,-1,-1): # can't move this part since center_y[i,:] depends on center_y[i+1,:]
    center_y[i,:] = center_y[i+1,:]

rawDescription: Python: Help in optimizing code

description: Python: Help in optimizing code


rawDescription: Manually constructing dataframe from transposed data


code:
ditance = [] ##declare my array
distance.append([0,1,2,3.5,4.2])
distance

rawDescription: Nested float arrays in Python

description: Nested float arrays in Python


code:
def has_repeats(L):
    return len(L)>1 and L[0]==L[1] or has_repeats([L[0]]+L[2:]) or has_repeats(L[1:])

rawDescription: Python Recursively check for repeats

description: Python Recursively check for repeats


code:
def flatten(items):
    non_list_items = []

    for item in items:
        if isinstance(item, list):
            for inner_item in flatten(item):
                yield inner_item
        else:
            non_list_items.append(item)

    yield non_list_items

rawDescription: How to flatten a nested list in python?

description: Flatten a nested list in python


rawDescription: GtkIconView Right Click Activate

description: GtkIconView Right Click Activate


code:
A = np.vstack([a,b,c])
np.average(A, axis=0, weights=A.astype(bool))

rawDescription: average of a number of arrays with numpy without considering zero values

description: Average of a number of arrays with numpy without considering zero values


code:
import pandas as pd
import datetime as DT
nfp = pd.read_csv("NFP.csv",
                  sep=r'[\s,]',              # 1
                  header=None, skiprows=1,
                  converters={               # 2
                      0: lambda x: DT.datetime.strptime(x, '%Y%m%d'),
                      1: lambda x: DT.time(*map(int, x.split(':')))},
                  names=['Date', 'Time', 'Actual', 'Consensus', 'Previous'])

print(nfp)

rawDescription: Split datetime64 column into a date and time column in pandas dataframe


rawDescription: Pandas lookup values from different columns


rawDescription: Python Pandas, groupby() and sum() values without column values


code:
op.add_option('-t', '--test', action='callback', callback=store_test, default='test',
    dest='test', help='test!', type='str')

rawDescription: Optparse callback not consuming argument


code:
def decorator(*a):
    def real_decorator(function):
        def wrapper(*args, **kwargs):
            function.flag = False
            function(*args, **kwargs)
            function.flag = True
        return wrapper
    return real_decorator

rawDescription: Changing values in decorator for nested functions


code:
import BeautifulSoup

doc = '''<title>Page title</title>
This is paragraph one.
This is paragraph two.'''
soup = BeautifulSoup.BeautifulSoup(doc)

for tag in soup.recursiveChildGenerator():
    if isinstance(tag,BeautifulSoup.Tag) and tag.name in ('a','b','i'):
        print(tag)

rawDescription: Using Beautiful Soup to strip html tags from a string


rawDescription: Group spark dataframe by date

description: Group spark dataframe by date


code:
my_data = NP.random.random_integers(0, 9, 16).reshape(4, 4)
# the line to add--does not depend on array dimensions
new_col = NP.zeros_like(my_data[:,-1]).reshape(-1, 1)
res = NP.hstack((my_data, new_col))

rawDescription: Growing matrices columnwise in NumPy

description: Growing matrices columnwise in NumPy


code: lines[1] # etc.

rawDescription: Ways to read/edit multiple lines in python


rawDescription: modelling the google datastore/python

description: Modelling the google datastore/python


rawDescription: How to find and select a table in html code with xpath

description: Find and select a table in html code with xpath


rawDescription: PyGame: Economic way of handling game loops


rawDescription: match strings in tuples - python

description: Match strings in tuples - python


code: os.system('ls /Users/user/Desktop > out.txt')

rawDescription: writing command line output to file

description: Writing command line output to file


rawDescription: Missing information in nested dictionary python


code:
kernel = np.ones((10,10),np.uint8)
opening = cv2.morphologyEx(img_thresholded, cv2.MORPH_OPEN, kernel)

rawDescription: How to detect bullet holes on the target using python

description: Detect bullet holes on the target using python


rawDescription: How to convert a python string

description: Convert a python string