code:
from __future__ import with_statement
with open(filename1) as f1:
   with open(filename2) as f2:
      if f1.read() == f2.read():
         ...

rawDescription: In Python, is there a concise way of comparing whether the contents of two text files are the same?


code:
import csv
from collections import defaultdict

with open("file.csv") as f:
    csvfile = csv.reader(f)
    names = defaultdict(list)
    for row in csvfile:
        curname = row[0]
        new_nums = row[1:4]
        name_nums = names.get(curname)
        if name_nums:
            del name_nums[:len(new_nums)]
        names[curname].extend(new_nums)

print(names)

rawDescription: How do i append a list with new data?

description: Append a list with new data


code:
ax1 = fig.add_subplot(N11)
ax2 = fig.add_subplot(N12)
...
axN = fig.add_subplot(N1N)

plt.setp([a.get_xticklabels() for a in (ax1, ..., axN-1)], visible=False)

rawDescription: How can I remove xtics from an axis in matplotlib?

description: Remove xtics from an axis in matplotlib


code:
data= socket.recv( struct.calcsize('!BBBBHHII') )
P2P_h.version, P2P_h.ttl, P2P_h.msgType, P2P_h.reserved, P2P_h.sendPort, P2P_h.payloadLength, P2P_h.ipSrc, P2P_h.messageId= unpack('!BBBBHHII', data)
data= socket.recv( struct.calcsize("!I") )
body_size= unpack("!I", data)
body= socket.recv( body_size )

rawDescription: struct.pack() Python unknown fields length to send through a socket

description: Struct.pack() Python unknown fields length to send through a socket


code: name + r'\b'

rawDescription: Deleting a line in file containing exact string (Python)


code: re.search(r'(?<=[|])[^|]*(?=[|]Ab Initio Software)', name, re.IGNORECASE).group()

rawDescription: Anyone offer a better solution? Right to left regex. using python


rawDescription: Nicer way to compute means of a set with numpy


code:
def foo(x, y, set_result):
    set_result(x + y)

def bar():
    res = None
    def set_res(x):
        nonlocal res
        res = x
    foo(10, 20, set_res)
    print(res)

rawDescription: why can't I change the variables using kwargs inside a function?

description: Why can't I change the variables using kwargs inside a function


code: dType= [str, str, str, int, float, float, str]

rawDescription: Convert list items to defined data type

description: Convert list items to defined data type


rawDescription: How to find the path of a changing directory name?

description: Find the path of a changing directory name


code:
import random
import string

sports = ('football', 'baseball', 'basketball',)
video_games = ('counter strike', 'doom', 'wolfenstein',)
movies = ('star wars', 'indiana jones', 'lord of the rings',)

def pick_category():
    print("For sports type 1, for video games type 2, for movies type 3")
    choice = input("Choose a category: ")
    if choice == '1':
        word = random.choice(sports)
    elif choice == '2':
        word = random.choice(video_games)
    elif choice == '3':
        word = random.choice(movies)
    else:
        print("Invalid input")
    return word

def draw(word, guesses):
    missing = set(string.ascii_lowercase) - set(guesses)
    masked = "".join([l if l not in missing else '_' for l in word])
    print(masked)
    return masked

def main():
    word = pick_category()
    guesses = []
    lives = 9

    while lives:
        masked = draw(word, guesses)

        if masked == word:
            print('You won!')
            return 0

        n = input("Guess a letter: ").lower()
        if n in string.ascii_lowercase:
            if n in guesses:
                print("That letter is already in use.")
            elif n not in word:
                guesses.append(n)
                lives = lives - 1
            else:
                guesses.append(n)
        else:
            print("Invalid input, try again")

        print("Used letters: ", ', '.join(guesses))
        print("Life counter: ", lives)

    print('You lost!')
    return 1

if __name__ == '__main__':
    main()

rawDescription: How can I replace specific characters in python?

description: Replace specific characters in python


code:
import argparse
import datetime as DT

parser = argparse.ArgumentParser()
parser.add_argument(
    "date"
    , type=lambda x: DT.datetime.strptime(x, '%Y-%m-%d')
    , help="date to check dependencies")
args = parser.parse_args()

date = args.date
one_day = DT.timedelta(days=1)
date1 = date - one_day
date2 = date + one_day
print(date1)
print(date2)

rawDescription: adding and subtracting from a date

description: Adding and subtracting from a date


code:
import random

with open('questions.txt', 'r') as question_file:
    questions = [line.strip() for line in question_file]

with open('answers.txt', 'r') as answer_file:
    answers = [line.strip() for line in answer_file]

# Make a list of tuples: [(q0, a0), (q1, a1), ...]
trivia = zip(questions, answers)
# Shuffle it in place
random.shuffle(trivia)
# Then iterate over it
for question, answer in trivia:
    # play the game
    pass

rawDescription: Attempting to have a trivia game by randomly taking certain choices


code:
from bs4 import BeautifulSoup
sample = '''\
<monograph>

        Test Heading

Here's a paragraph with some text in it.

</monograph>
'''
soup = BeautifulSoup(sample, 'xml')
str(soup.p)
print(soup.p.find_parent(id=True).prettify())
print(soup.p.find_parent(id=False).prettify())

rawDescription: Python - BeautifulSoup findParent by attribute


rawDescription: Get all elements in a list where the value is equal to certain value


code: tot = np.einsum('ijk, k -> ij', arr, wts)

rawDescription: Sum of colorvalues of an image

description: Sum of colorvalues of an image


code:
img = []
for x in range (0, width):
    for y in range (0, height):
        img.append(rgb[random.randint(0,2)])
return img

rawDescription: Assigning random colour from RGB into a image


rawDescription: Generate sequences of adjecent subsets (from a list of lists)


code:
fred = Fred()
fred.test(10)
import numpy
[fred.f(x, 10) for x in numpy.linspace(54, 55, 10)]

rawDescription: Solving an equation with scipy's fsolve

description: Solving an equation with scipy's fsolve


code: print(["FizzBuzz" if x%15 == 0 else "Fizz" if x%3 == 0 else "Buzz" if x % 5 == 0 else x for x in range(1,101)])

rawDescription: Python - Using ifs, elifs and else in list comprehensions with their respective results


code: min(f.viewkeys() & o, key=f.get)

rawDescription: Most efficient way to find the key of the smallest value in a dictionary from a subset of the dictionary


rawDescription: How Do I Queue My Python Locks?

description: How Do I Queue My Python Locks


code: data

rawDescription: How to parse the header files of the pcap file?

description: Parse the header files of the pcap file


code:
import argparse

usage = '%(prog)s [A | [B ? C]]'
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument('-a')
parser.add_argument('-b')
parser.add_argument('-c')
args=parser.parse_args()

print(args)
if args.a is not None:
   if not(args.b is None and args.c is None):
      parser.error('Cannot use b or c with a')

rawDescription: Group in a group ArgParse

description: Group in a group ArgParse


code:
def capacity():
    return int(input("input the capacity of your node: "))

rawDescription: i have a formula, trying to put it into python and this is what i have so far, whats the issue with it?

description: I have a formula, trying to put it into python and this is what i have so far, whats the issue with it


rawDescription: Applying cell wise function in a dataframe


code:
from django.apps import apps
apps.get_models()

rawDescription: Get a list of all installed applications in Django and their attributes


code:
from pyspark.rdd import RDD
from concurrent.futures import ThreadPoolExecutor

executor = ThreadPoolExecutor(max_workers=4)

def submit_to_gui(*args): ...

def submit_if_success(f):
    if not f.exception():
        executor.submit(submit_to_gui, f.result())

rawDescription: How to avoid one Spark Streaming window blocking another window with both running some native Python code

description: Avoid one Spark Streaming window blocking another window with both running some native Python code


code:
def get_data_locations():
    """ Find data locations from the first sheet in document. """
    first_sheet = Range('Sheet1', 'A1:Z200').value
    coordinates = []
    for x, row in enumerate(first_sheet, 1):
        coordinates.extend([[x, y] for y, z in enumerate(row, 1) if z == 'CO'])
    return coordinates

rawDescription: Uncool List Comprehension

description: Uncool List Comprehension


code: background_disabled_normal: str(False)

rawDescription: Kivy clickable image that replaced a button


code:
for d in data:
    # compute covariance for each triangle
    cov = np.cov(d, ddof=0, rowvar=False)

rawDescription: Quickly compute eigenvectors for each element of an array in python


code: DictTable(d)

rawDescription: Python dictionary as html table in ipython notebook


code:
coords = enclosing_box(x,y,radius)
w.create_oval(*coords)

rawDescription: Python - basics - how to make a 'class('?) function for a simple set of maths based variables


code:
params = {'path[]': ['/empty', '/Burns.docx', '/Byron.doc']}
headers = {'Some-header', 'Header value'}
response = requests.get(url, params=params, headers=headers)

rawDescription: sending html input array with requests lib

description: Sending html input array with requests lib


code:
from collections import MutableMapping

class SingleAssignDict(MutableMapping):
    def __init__(self, *args, **kwargs):
        self._d = dict(*args, **kwargs)

    def __getitem__(self, key):
        return self._d[key]

    def __setitem__(self, key, value):
        if key in self._d:
            raise ValueError(
                'Key {!r} already exists in SingleAssignDict'.format(key)
            )
        else:
            self._d[key] = value

    def __delitem__(self, key):
        del self._d[key]

    def __iter__(self):
        return iter(self._d)

    def __len__(self):
        return len(self._d)

    def __contains__(self, key):
        return key in self._d

    def __repr__(self):
        return '{}({!r})'.format(type(self).__name__, self._d)

class RedefBlocker(type):
    @classmethod
    def __prepare__(metacls, name, bases, **kwargs):
        return SingleAssignDict()

    def __new__(metacls, name, bases, sad):
        return super().__new__(metacls, name, bases, dict(sad))

class Okay(metaclass=RedefBlocker):
    a = 1
    b = 2

class Boom(metaclass=RedefBlocker):
    a = 1
    b = 2
    a = 3

rawDescription: Python metaclasses: Why isn't __setattr__ called for attributes set during class definition?


code:
def f():
    a = "foo"
    b = "foo"
    print(a is b)   # True, because a and b refer to the same constant
    x = "f" + "oo"
    print(a is x)   # True, because the addition is optimized away
    y = "f"
    z = y + "oo"    #
    print(a is z)   # False, because z is actually a different object

rawDescription: python: string comparison do not work as expected

description: Python: string comparison do not work as expected


code: imshow(z, origin='lower', extent=[-4,4,-1,1], aspect=4)

rawDescription: How do I change the scale of imshow in matplotlib without stretching the image?

description: Change the scale of imshow in matplotlib without stretching the image


code:
new_array = np.empty((len(uinqPos), 4))
new_array[:, 0] = uinqPos
index = a['position'].searchsorted(uinqPos)
new_array[:, 1] = a['score'][index]
index = b['position'].searchsorted(uinqPos)
new_array[:, 2] = b['score'][index]
index = c['position'].searchsorted(uinqPos)
new_array[:, 3] = c['score'][index]

rawDescription: create intersection from two or more 2d numpy arrays based on common value in one column

description: Create intersection from two or more 2d numpy arrays based on common value in one column


rawDescription: parse commands with regex and python

description: Parse commands with regex and python


code: matlabpath = [s for s in pathlist if all(x in s for x in ['MATLAB','R','bin']) and not 'polyspace' in s]

rawDescription: What is the Matlab install directory on 64bit or how to get it in Python?


code:
obj = TP1_Simply_supported_beam_class()
obj.TP1_Simply_supported_beam(**newvars)

rawDescription: Include user named variables in existing python script


code:
def update(x, **entries):
    """Update a dict; or an object with slots; according to entries.
    >>> update({'a': 1}, a=10, b=20)
    {'a': 10, 'b': 20}
    >>> update(Struct(a=1), a=10, b=20)
    Struct(a=10, b=20)
    """
    if isinstance(x, dict):
        x.update(entries)
    else:
        x.__dict__.update(entries)
    return x

rawDescription: update fct in python constructors

description: Update fct in python constructors


code:
from bs4 import BeautifulSoup
from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://www.vogue.com/fashion-shows/fall-2016-menswear/fendi#collection")
html_source = browser.page_source
soup = BeautifulSoup(html_source, "html.parser")

for item in soup.find_all("img", {"class":"grid-item--image"}):
    print(item.get('srcset'))

rawDescription: How to parse Web pages that don't return results initially in Python?

description: Parse Web pages that don't return results initially in Python


code:
lst = ["Something", "This no", "This Yes", "not this"]
list(filter(lambda s: all(x[0].isupper() for x in s.split()), lst))

rawDescription: Remove any phrase in a list based on capitalization (Python 3)


rawDescription: Should I assign a range outside of a loop in Python?


rawDescription: Splitting a filename into words and numbers in Python


code: d.get(letter, letter)

rawDescription: Special chacacters in python 3.3

description: Special chacacters in python 3.3


rawDescription: isolate data from a string

description: Isolate data from a string


rawDescription: python ObjectListView has a single un-editable column

description: Python ObjectListView has a single un-editable column


code: all_valid = all(ArticleForm(fm).is_valid() for fm in some_list_of_dictionaries)

rawDescription: Django: validating forms declared on client side with angularjs


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

def get_ax_size(ax):
    bbox = ax.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    width, height = bbox.width, bbox.height
    width *= fig.dpi
    height *= fig.dpi
    return width, height

data = np.arange(9).reshape((3, 3))
fig = plt.figure(figsize=(8,6), dpi=80)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(data, aspect='normal')
print(get_ax_size(ax))
# (640.0, 480.0)
plt.savefig('/tmp/test.png', dpi=80)

rawDescription: determine matplotlib axis size in pixels

description: Determine matplotlib axis size in pixels


code:
a = [{'a':1},{'b':2},{'c':3},{'a':-2},{'b':4}]
b = {}

for x in a:
    k,v = x.popitem()

    # Check if the key is already in our output dict
    if k in b.keys():
        b[k] += v

    # If not, create it
    else:
        b[k] = v

rawDescription: Add dictionary values where keys match

description: Add dictionary values where keys match


rawDescription: Get the last index with same max values in a list


code:
import re
max(re.findall("g+", "fggfggggfggfg"), key=len)

rawDescription: Python - finding the longest sequence with findall


code:
source = Company_Position_Person.objects.get( pk = 12 )
targets = Company_Position_Person.filter( startDate__lte = target.endDate ,
                                          endDate__gte = target.startDate )

rawDescription: query to get date overlaping

description: Query to get date overlaping


code:
import itertools
import pprint
pprint.pprint(list(itertools.permutations("spam")))

rawDescription: python: shuffle characters in string to get all possible string combinations

description: Python: shuffle characters in string to get all possible string combinations


code:
import chardet
chartype = chardet.detect(mystring)

# perhaps you may want to check the confidence that it is that encoding first?
# if chartype['confidence'] > 0.5 or something

mystring = mystring.decode(chartype['encoding']).encode('utf-8')

rawDescription: How to print out ascii characters from 0 to 255 in C, displayed in a webpage through Django?

description: Print out ascii characters from 0 to 255 in C, displayed in a webpage through Django


code:
class Md5Value(Transform):
    lookup_name = 'md5'
    output_field = CharField()

    def as_sql(self, compiler, connectino):
        lhs, params = compiler.compile(self.lhs)
        return "MD5(cast(%s as text))"  % lhs, params

AutoField.register_lookup(MD5Value)

rawDescription: Django queryset model apply function in field


code:
class Books():
    def __init__(self):
        self.__dict__['referTable'] = 1
    @property
    def referTable(self):
        try:
            return self.__dict__['referTable']
        except KeyError:
            return 2

a = Books()
a.referTable
del a.__dict__['referTable']
a.referTable

rawDescription: Built-in non-data version of property?

description: Built-in non-data version of property


code:
def MyGlob(pattern, ondisk=True, source=True, strings=False, recursive=False):
    if not recursive:
        return Glob(pattern, ondisk, source, strings)

    matches = []
    # Instead of using os.getcwd() consider passing-in a path
    for root, dirnames, filenames in os.walk(os.getcwd()):
        cwd = Dir(root)
        # Glob() returns a list, so using extend() instead of append()
        # The cwd param isnt documented, (look at the code) but its
        # how you tell SCons what directory to look in.
        matches.extend(Glob(pattern, ondisk, source, strings, cwd))

    return matches

rawDescription: Use a Glob() in VariantDir() einvironment to find files recursively in Python?


code:
board = [1]*16 + 48*[0]
random.shuffle(board)
board = [board[i:i+8] for i in xrange(0, 64, 8)]

rawDescription: Python — Randomly fill 2D array with set number of 1's


code:
from itertools import groupby

food1 = [[" vegetable", "tomato"], [" vegetable", "spinach"], [" fruit", "watermelon"], [" fruit", "grapes"], [" meat", "beef"]]

data={}
for key, group in groupby(sorted(food1), key=lambda x: x[0]):
    data[key.strip()]=[v[1] for v in group]

rawDescription: Python group and splice: splicing the result returned from itertools.groupby


code:
pd.set_option('display.float_format', lambda x: locale.format('%.2f', x, grouping=True) if abs(x)>10000 else locale.format('%.0f', x))
s

rawDescription: How can I format a float to separate by thousands, inverting dot and commas?

description: Format a float to separate by thousands, inverting dot and commas


code:
my_string = re.sub(r'^(.*?) \(The\)$', r'The \1', my_string, 1)
my_string = re.sub(r'\bL\.? ?L\.? ?C\.?\b', '', my_string, 1)
my_string = re.sub(r'[(),]', '', my_string)

rawDescription: Convert this perl replacement to python

description: Convert this perl replacement to python


code: {k:sorted(v,key=lambda x: tuple(x.values())) for k,v in d.items()}

rawDescription: sort sub-dicts in a dict by value of the sub-dict

description: Sort sub-dicts in a dict by value of the sub-dict


code: re.search(r'\S*_file\S*', s).group()

rawDescription: Get everything between two spaces including a word stem


code:
x=5
import second

rawDescription: Pass variable between python scripts

description: Pass variable between python scripts


code:
class NegTuple(tuple):
    def __neg__(self):
        return slice(0)

rawDescription: python/numpy: negate or complement a slice

description: Python/numpy: negate or complement a slice


rawDescription: How do you divide list into equal parts?

description: Divide list into equal parts


code:
dispatcher = {'foobar': [foo, bar], 'bazcat': [baz, cat]}

def fire_all(func_list):
    for f in func_list:
        f()

fire_all(dispatcher['foobar'])

rawDescription: python - Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function?

description: Python - Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function


code:
x = np.random_integers(0, 1, (3, 3, 3))
np.where(x) # you want np.where(x==0)
zip(*np.where(x))

rawDescription: Iterate over the output of `np.where`

description: Iterate over the output of `np.where`


code:
result = []
names = ['link', 'zelda', 'saria', 'ganon', 'volvagia']
lines = iter(data)
for line in lines:
    while line.startswith(">") and any(name in line for name in names):
        name = line
        upper_seq = []
        for line in lines:
            if not line.isupper():
                break
            upper_seq.append(line)
        else:
            line = "" # guard against infinite loop at EOF

        result.append((name, ''.join(upper_seq)))

rawDescription: Search for word (from list of words) in line (from list of lines) and append values to new list. Python


code:
frame.pack()
# force drawing of the window
win.update_idletasks()

rawDescription: Display realtime output of a subprocess in a tkinter widget


code:
urls = ['url1.com','url2.com','url3.com','url4.com']
for i in urls:
    requests.get(archive + i)

rawDescription: Send data and get the response

description: Send data and get the response


rawDescription: Get data points from Seaborn distplot

description: Get data points from Seaborn distplot


code:
from django.shortcuts import render
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import components

def simple_chart(request):
    plot = figure()
    plot.circle([1,2], [3,4])

    script, div = components(plot, CDN)

    return render(request, "simple_chart.html", {"the_script": script, "the_div": div})

rawDescription: how to embed bokeh graphs into django templates without using the "bokeh-server executable"?

description: Embed bokeh graphs into django templates without using the "bokeh-server executable"


code:
L = [['spear', 'pears', 'reaps'], ['monster', 'sternom']]
max(L, key=lambda xs: len(xs[0]))

rawDescription: Length of string in sublist within a list python


rawDescription: Finding most recent datetime in list before a given datetime


code:
x = 5
mylist = [ 1, 2, 3]
y = myfunc(4)
z = myfunc(x)

rawDescription: Parse python setup file

description: Parse python setup file


code:
data = parse.parse(template, out_string)
print(data.named)
print(data.fixed)

rawDescription: Reversing C-style format strings in Python (`%`)


code:
def mask_all_zero_rows_numpy(df):
    """
    Take a dataframe, find all the rows that contain only zeros
    and mask them. Return a dataframe of the same shape with all
    Nan rows in place of the all zero rows.
    """
    no_data = -99
    arr = df.as_matrix().astype(int16)
    # make a row full of the 'no data' value
    replacement_row = np.array([no_data for x in range(arr.shape[1])], dtype=int16)
    # find out what rows are all zeros
    mask_rows = ~arr.any(axis=1)
    # replace those all zero rows with all 'no_data' rows
    arr[mask_rows] = replacement_row
    # create a masked array with the no_data value masked
    marr = np.ma.masked_where(arr==no_data,arr)
    # turn masked array into a data frame
    mdf = pd.DataFrame(marr,columns=df.columns)
    return mdf

rawDescription: Masking a Pandas DataFrame rows based on the whole row


code: isinstance(vars(C)['st'], staticmethod)

rawDescription: Detecting bound method in classes (not instances) in Python 3


code: max_score_ids = g.score.agg('idxmax')

rawDescription: Find maximum value in python dataframe combining several rows


code:
import ujson
import pandas as pd

data_list = []

with open('data.json') as f:
    for line in f:
        d = ujson.loads(line)
        data_list.append(
            {"id":d["id"],
             "name":d["name"],
             "region":d["address"]["region"],
             "street-address":d["address"]["street-address"]
            }
        )

df = pd.DataFrame(data_list)

pd.set_option('display.expand_frame_repr', False)
print(df)

rawDescription: pandas slicing nested values along with other columns

description: Pandas slicing nested values along with other columns


code:
from sqlalchemy import func, distinct

result = session.query(distinct(func.date_part('YEAR', Topic.date_created)))
for row in result:
    print(row[0])

rawDescription: How to retrieve only the year from timestamp column?

description: Retrieve only the year from timestamp column


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

df = pd.DataFrame({'Total': [20,15,13,1],
                   'lat': [40,0,-30,50],
                   'lon': [40,50,60,70], },
                  index=['Location {}'.format(i) for i in range(1,5)])

cmap = plt.get_cmap('gist_rainbow_r')
df.plot(kind='scatter', x='lon', y='lat', s=df['Total']*50, c=df['Total'], cmap=cmap)

for idx, row in df.iterrows():
    x, y = row[['lon','lat']]
    plt.annotate(
        str(idx),
        xy = (x, y), xytext = (-20, 20),
        textcoords = 'offset points', ha = 'right', va = 'bottom',
        bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
        arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))

plt.show()

rawDescription: Draw different sized circles on a map

description: Draw different sized circles on a map


code: regex = re.compile("[.-]+ *")

rawDescription: remove periods from fasta file using python

description: Remove periods from fasta file using python


code:
items = []
i = 0
for key in sorted(a):
    items.append((i, i+a[key], key))
    i += a[key]

rawDescription: Generate tuples of intervals from dict in Python


rawDescription: generate min combining multiple lists, return lowest uncombined list?

description: Generate min combining multiple lists, return lowest uncombined list


code:
from Bio import SeqIO
SeqIO.write(data, handle, format)

rawDescription: Using Bio.SeqIO to write single-line FASTA


code:
s="""NetRange:       8.8.8.0 - 8.8.8.255

CIDR:           8.8.8.0/24

NetName:        LVLT-GOGL-8-8-8

NetHandle:      NET-8-8-8-0-1

Parent:         LVLT-ORG-8-8 (NET-8-0-0-0-1)

NetType:        Reallocated

NetType:        Reallocated

OriginAS:

Organization:   Google Inc. (GOGL)

RegDate:        2014-03-14

Updated:        2014-03-14

Ref:            http://whois.arin.net/rest/net/NET-8-8-8-0-1"""
import re
re.search(r'NetName:\s+(.*)',s).group(1)

rawDescription: How to find text in a column with Python

description: Find text in a column with Python


rawDescription: Numpy array, fill empty values for a single column


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

# Generation of 100000 numbers using the [0:8] + [0:8] technique
res1 = np.empty(shape=100000, dtype=int)
for i in xrange(res1.size):
    tmp = str(uuid.uuid4().int>>64)[0:8] + str(uuid.uuid4().int>>64)[0:8]
    res1[i] = int(tmp)

# Generation of 100000 numbers using the [0:16] technique
res2 = np.empty(shape=100000, dtype=int)
for i in xrange(res1.size):
    tmp = str(uuid.uuid4().int>>64)[0:16]
    res2[i] = int(tmp)

# Histogram plot
plt.setp(patches, 'facecolor', 'g', 'alpha', 0.75)
n, bins, patches = plt.hist(res1, 100, normed=1, histtype='stepfilled')
n, bins, patches = plt.hist(res2, 100, normed=1, histtype='stepfilled')

rawDescription: Generating random 16 digit number in Python


code:
s = sorted(student_tuples, key=itemgetter(1))
s.sort(key=itemgetter(0),reversed=True)
s.sort(key=itemgetter(2,4))

rawDescription: Sorting tuples in python using different orders for different fields


code:
def run(origin):
    # Load image file from url.
    try:
        #make a temp filename that is valid on your machine
        tmp_filename = "/tmp/temp.png"
        #fetch the image in this file
        request.urlretrieve("https://www.google.com/images/srpr/logo4w.png", tmp_filename)
        #create a blender datablock of it
        img = bpy.data.images.load(tmp_filename)
        #pack the image in the blender file so...
        img.pack()
        #...we can delete the temp image
        os.remove(tmp_filename)
    except Exception as e:
        raise NameError("Cannot load image: {0}".format(e))
    # Create image texture from image
    cTex = bpy.data.textures.new('ColorTex', type='IMAGE')
    cTex.image = img
    # Create material
    mat = bpy.data.materials.new('TexMat')
    # Add texture slot for color texture
    mtex = mat.texture_slots.add()
    mtex.texture = cTex
    # Create new cube
    bpy.ops.mesh.primitive_cube_add(location=origin)
    # Add material to created cube
    ob = bpy.context.object
    me = ob.data
    me.materials.append(mat)

run((0,0,0))

rawDescription: Blender material from URL

description: Blender material from URL


rawDescription: Finding letters in a string

description: Finding letters in a string


code:
letter_score = {letter: score for score, letters in scrabble_scores
                              for letter in letters.split()}

rawDescription: dict comprehensions for mapping scrabble letter distribution

description: Dict comprehensions for mapping scrabble letter distribution


code:
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

body = MIMEMultipart()
for name, (filename, contents, mimetype) in files.items():
    part = MIMEText(contents, _subtype=mimetype.partition('/')[-1], _charset='utf8')
    part.add_header('Content-Disposition', 'attachment', filename=filename)
    body.attach(part)

post_body = body.as_string().partition('\n\n')[-1]
content_type = body['content-type']

headers = {'Content-Type': content_type}
requests.post('http://example.com', data=post_body, headers=headers, params=params)

rawDescription: how to POST multipart list of JSON/xml files using python requests


code:
import shelve
d = shelve.open('score.txt') # here you will save the score variable
d['score'] = score           # thats all, now it is saved on disk.
d.close()

rawDescription: Saving the highscore for a python game

description: Saving the highscore for a python game


code:
# First case:
soup.find_all(attrs={"limit":True})

# Second case:
soup.find_all("div", attrs={"limit":True})

rawDescription: Is it possible to find all elements with a custom html attribute in Beautiful Soup?


code: channel_views.filter(lambda x: "XYZ" == x[1])  # Exact matches

rawDescription: Subsetting data in Spark

description: Subsetting data in Spark


code: from numpy import *

rawDescription: matplotlib.pyplot vs matplotlib.pylab

description: Matplotlib.pyplot vs matplotlib.pylab


code:
class MainWindow(QMainWindow):
    def __init__(self, *args):
        QMainWindow.__init__(self, *args)
        self.cw = QWidget(self)
        self.setCentralWidget(self.cw)
        self.btn1 = QPushButton("Click me", self.cw)
        self.btn1.setGeometry(QRect(50, 50, 100, 30))
        self.btn1.clicked.connect(lambda: self.printWow(self.btn1))

        self.btn2 = QPushButton("Click me", self.cw)
        self.btn2.setGeometry(QRect(50, 20, 100, 30))
        self.btn2.clicked.connect(lambda: self.printText(self.btn2, "Yay!"))

    def printText(self, target, text="wow"):
        target.setText(text)

rawDescription: Writing modular codes in python

description: Writing modular codes in python


code:
s = s[~s.index.isin(list('BDE'))]
s

rawDescription: Exclude one or more items from pandas Series


code:
a = [1,2,3,4,5,6,7,8]
a[2:6]     #this gets the elements from index 2 to 5
a[-1]      #this gets the last element of the list

rawDescription: Extract tuple from list

description: Extract tuple from list


code:
d = {}
for key, value in l:
    try:
        d[key] += value
    except KeyError:
        d[key] = value

rawDescription: List of list increment if exists otherwise extend


code:
import numpy
numpy.array([10])
numpy.array([10])**100
numpy.array([10], dtype=object)
numpy.array([10], dtype=object)**100

rawDescription: numpy beginner array plain python vs. numpy vectors: faulty results

description: Numpy beginner array plain python vs. numpy vectors: faulty results


code:
import heapq

list1=[1,15,9,3,6,21,10,11]

print(heapq.nsmallest(2,list1))

rawDescription: Smallest n numbers from a list

description: Smallest n numbers from a list


code:
# same preamble
for mol in mols:
    lines = []
    for energy, density in data:
        ax.cla() # or ax.clear()
        p, = ax.plot(density, energy, 'ro')
        lines.append(p)

        fig.savefig(mol+".png")
    [p.remove() for p in lines]

rawDescription: Looping over data and creating individual figures


code:
ax1.plot(df.index, df.iloc[:, :2])  # Columns 0 and 1.
ax2.plot(df.index, df.iloc[:, 2])   # Column 2.

rawDescription: Unable to control scale of second y-axis on df.plot()


code:
from collections import namedtuple
City = namedtuple('City', 'name lat long elev') # or whatever your actual fields are

cities = [City('New York', 54.9, 49.94, 2534.7),
          City('Los Angeles',65.4, 14.93, 3254.2),
          ...
]

rawDescription: Sorting a List of Tuples (Python)

description: Sorting a List of Tuples (Python)


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.gridspec as gridspec

X = np.array([0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4.])
X2 = np.array([122, 85, 63, 50, 23, 12, 7, 5, 2])
Y = np.cos(X*20)
Z = np.sin(X*20)

fig = plt.figure()
gs = gridspec.GridSpec(1, 2)
ax1 = plt.subplot(gs[1])
ax2 = ax1.twiny()

ax1.set_xlim(-0.2, max(X)+0.2)
plt.tick_params(axis='both', which='major', labelsize=10)
ax1.minorticks_on()
ax1.grid(b=True, which='major', color='gray', linestyle='--', lw=0.3)

SC = ax1.scatter(X, Y, c=Z, cmap='viridis')
ax1.set_xlabel("Original x-axis")

ax2.set_xlim(ax1.get_xlim())
ax2.set_xticks(X)
ax2.set_xticklabels(X2)
ax2.set_xlabel("Second x-axis")

# Colorbar.
cbar = plt.colorbar(SC, ax=[ax1, ax2])
cbar.set_label('B', fontsize=10, labelpad=4, y=0.5)
cbar.ax.tick_params(labelsize=10)

plt.show()

rawDescription: Matplotlib colorbar moves second x axis

description: Matplotlib colorbar moves second x axis


code:
class A2 (object):
    def __init__ (self):
        print('A2')

class B2 (A2):
    def __init__ (self):
        A2.__init__(self)
        print('B2')

class C2 (A2):
    def __init__ (self):
        A2.__init__(self)
        print('C2')

class D2 (C2, B2):
    def __init__ (self):
        B2.__init__(self)
        C2.__init__(self)
        print('D2')

rawDescription: Difference between super() and calling directly


code:
for ftp_file in f.nlst():
    if ftp_file not in os.listdir("path_where_files_exist"):
        print('Downloading file: %s', ftp_file)
        f.retrbinary('RETR '+ ftp_file ,open(ftp_file,'wb').write,rest=0)
        f.quit()

rawDescription: Downloading FTP Files Skipping similar files


code:
# Lets create a generic pixel class for easy color management
class MyPixel(object):
    red = 0
    green = 0
    blue = 0
    def __init__(self, red=0, green=0, blue=0):
        self.red = red
        self.green = green
        self.blue = blue
    def __repr__(self):
        return u'#{0.red:02X}{0.green:02X}{0.blue:02X}'.format(self)

# Extend wand.image.Image and add a new `img.pixels` pseudo-attribute
class MyImage(Image):
    # Repeat above example
    @property
    def pixels(self):
        pixels = []
        self.depth = 8
        blob = self.make_blob(format='RGB')
        for cursor in range(0, self.width * self.height * 3, 3):
            pixel = MyPixel(red=blob[cursor],
                            green=blob[cursor + 1],
                            blue=blob[cursor + 2])
            pixels.append(pixel)
        return pixels

# Call your custom class; which, collects your custom pixels
with MyImage(filename=filename) as img:
    print(img.pixels)
#=> [#FF0000, #0000FF, #008000, #FFFFFF]

rawDescription: Get all pixels of an Image [Wand]

description: Get all pixels of an Image [Wand]


code: sorted(i for i in xrange(10))

rawDescription: list(file) appends \n to each line

description: List(file) appends \n to each line


rawDescription: or statement in list python 3

description: Or statement in list python 3


rawDescription: How to send a file through Soap in python?

description: Send a file through Soap in python


code:
mydict = {'Car':'BMW','Speed':'kph','Range':33}
for keys in mydict:
    print(keys,":",mydict[keys])

rawDescription: Return only a few keys in a dictionary? Python


code: from mako.filters import html_escape as h

rawDescription: Lookup escape filter method

description: Lookup escape filter method


rawDescription: python maya: How do i create a linear bezier curve?

description: Python maya: How do i create a linear bezier curve


code:
s = Spam()
s.oneFunction(lists)
s.anotherFunction()

rawDescription: Calling variable defined inside one function from another function


code:
import flask
app = flask.Flask(__name__)

def cinema_url(cinema):
    return '/%s/%s/%s' % (
            cinema['language'],
            cinema['genre'],
            cinema['name'],
            )

# Register this function as a Jinja2 filter
app.jinja_env.filters['cinema_url'] = cinema_url

@app.route('/')
def home():
    cinemas = [
            {'name': 'Movie1', 'language': 'English', 'genre': 'action'},
            {'name': 'Movie2', 'language': 'Spanish', 'genre': 'comedy'},
        ]
    return flask.render_template('home.html', cinemas=cinemas)

app.run()

rawDescription: Jinja2 filter for URL pattern generation in flask views


code:
import sys
sys.stdout.write("foo")

rawDescription: difference between sys.stdout.write and print when printing variables

description: Difference between sys.stdout.write and print when printing variables


rawDescription: Issue with Decryption Algorithm

description: Issue with Decryption Algorithm


code:
class Foo(object):
    do_map = dict(this='do_this', that='do_that')

    def my_func(self, item, value):
        if item in do_map:
            getattr(self, do_map[item])(value)

rawDescription: Using a class dictionary to map to instance methods in Python


code:
def unicode_truncate(s, length, encoding='utf-8'):
    encoded = s.encode(encoding)[:length]
    return encoded.decode(encoding, 'ignore')

rawDescription: Truncating unicode so it fits a maximum size when encoded for wire transfer


code: a <= x and b <= y and c <= z

rawDescription: merging tuples in heap module in python

description: Merging tuples in heap module in python


code:
s = requests.Session()
response = s.get('http://wiki.company.com/wiki_page', allow_redirects=False)
if response.status_code in (302, 303):
    target = response.headers['location']
    authenticated = s.get(target, auth=(username, password))
    # continue on to the wiki again
    response = s.get('http://wiki.company.com/wiki_page')

rawDescription: Unable to retain login credentials across pages while using requests


rawDescription: Python wav format parsing: Non-standard data frame output


code:
import os
basedir = os.path.abspath(os.path.dirname(__file__))

SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.sqlite')
SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')

rawDescription: Create an sqlite db and save it by means of python and flask


code:
prog = ["printf", "%s", "<", "/etc/passwd"]
subprocess.call(prog)

rawDescription: Why is subprocess.Popen not waiting until the child process terminates?


code:
from ttk import *
from Tkinter import *

root = Tk()

choices = ['GB', 'MB', 'KB']
variable = StringVar(root)
variable.set('GB')

w = Combobox(root, values = choices)
w.pack(); root.mainloop()

rawDescription: Tkinter: How to create choice box

description: Tkinter: How to create choice box


rawDescription: Difference of consecutive float numbers in a column


code:
import itertools
d = dict.fromkeys(range(5),0)
list(itertools.combinations(d,2))

rawDescription: Compare a dictionary to itself in Python


code:
from moviepy.video.VideoClip import DataVideoClip

def data_to_frame(time):
    xn = x + np.sin(2 * np.pi * time / 10.0)
    yn = y + np.cos(2 * np.pi * time / 8.0)
    p[0].set_data(xn, yn)
    return mplfig_to_npimage(fig)

times = np.arange(2341973, 2342373)
clip = DataVideoClip(times, data_to_frame, fps=1) # one plot per second

#final animation is 15 fps, but still displays 1 plot per second
animation.write_videofile("test2.mp4", fps=15)

rawDescription: Difficulty animating a matplotlib graph with moviepy


rawDescription: Search for an XML node in a parent by string with python


code:
def colorvec(rootsmatrix, known_roots):
    dist = abs(rootsmatrix - known_roots[:, None, None])

rawDescription: Finding minimum value element-wise in three 2d submatrices


rawDescription: Converting one string to a int in a list


code:
for idx, item in enumerate(alist):
   if 123 in item:
       alist[idx] = 2014

rawDescription: How to 'update' or 'overwrite' a python list

description: 'update' or 'overwrite' a python list


code:
{u'member_amt_recvd': None, u'member_amt_pledged': u'10.00', u'name': u'Murray Hight', u'member_id': u'1'}
{u'member_amt_recvd': None, u'member_amt_pledged': u'10.00', u'name': u'Martin Tunis', u'member_id': u'4'}

rawDescription: Retrieving items from a dictionary data type created from a JSON request


rawDescription: Python string parsing from .txt

description: Python string parsing from .txt


code:
while True:
    row = cursor.fetchone()
    if row is None:
        break
    process(row)

rawDescription: How to use Python list comprehension (or such) for retrieving rows when using MySQLdb?

description: Use Python list comprehension (or such) for retrieving rows when using MySQLdb


rawDescription: Regex to help split up list into two-tuples


code:
class C(object):
    pass

def a(s):
    return 12

a = a.__get__(C)

rawDescription: How works pre-defined descriptors in functions?


code:
from numpy import median

values    = [1,2,3,4,5,6]
med       = median([values[0], values[len(values)/2], values[-1]]) # calculate median of first, middle and last element in the list
values[0] = med # replace first element with median

rawDescription: python if elif different result

description: Python if elif different result


code:
all_active_polls = Poll.active.all()
num_of_active_polls = len(all_active_polls)

all_inactive_polls = Poll.inactive.all()
num_of_inactive_polls = len(all_inactive_polls)

latest_poll_list = Poll.latest.all()[:5]

rawDescription: Organizing code in Django views

description: Organizing code in Django views


code:
#I delete follow line:
from sqlalchemy.databases.mysql import MSBinary

rawDescription: Storing UUIDs in sqlite using Pylons and SQLalchemy


code:
import pandas as pd
import pickle

with open('pyramidanalysis/temp/reversal_data.txt','rb') as handle:
  b=pickle.loads(handle.read())

data=dict()

keys=b.keys()
for key in keys:
  data[key]=pd.DataFrame(b[key])

rawDescription: Configure Blaze and start Bokeh server from Pyramid web-application


rawDescription: Sparksql filtering (selecting with where clause) with multiple conditions


code:
class ModelA(models.Model):
    key = models.PositiveIntegerField()
    fk = models.ForeignKey(ModelB)

    def Meta(self):
        unique_together = ("key", "fk")

    def save(self, *args, **kwargs):
        key = cal_key(self.fk)
        self.key = key
        super(ModelA, self).save(*args, **kwargs)

rawDescription: Django Model Auto Increment Primary Key Based on Foreign Key


code: plt.plot(x,y, marker='.', color='k', linestyle='none')

rawDescription: What is purpose of meshgrid in Python?

description: What is purpose of meshgrid in Python


code:
import asyncio

class arange:
    def __init__(self, n):
        self.n = n
        self.i = 0

    async def __aiter__(self):
        return self

    async def __anext__(self):
        i = self.i
        self.i += 1
        if self.i <= self.n:
            await asyncio.sleep(0)  # insert yield point
            return i
        else:
            raise StopAsyncIteration

class MapFilter:
    def __init__(self, aiterable, p, func):
        self.aiterable = aiterable
        self.p = p
        self.func = func

    async def __aiter__(self):
        return self

    async def __anext__(self):
        while True:
            payload = await self.aiterable.__anext__()
            if self.p(payload):
                return self.func(payload)

async def main():
    aiterable = arange(5)
    p = lambda x: bool(x>2)
    func = lambda x: x*2

    async for i in MapFilter(aiterable, p, func):
        print(i)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

rawDescription: how can I asynchronously map/filter an asynchronous iterable?

description: Asynchronously map/filter an asynchronous iterable


code:
import types
def hasmethod(obj, name):
    return hasattr(obj, name) and type(getattr(obj, name)) == types.MethodType

def loggify(theclass):
  for x in filter(lambda x:"__" not in x, dir(theclass)):
     if hasmethod(theclass,x):
        print(x)
        setattr(theclass,x,logging(getattr(theclass,x)))
  return theclass

rawDescription: How to cast object in Python

description: Cast object in Python


code:
from robot.libraries.BuiltIn import BuiltIn

def get_webdriver_instance():
    se2lib = BuiltIn().get_library_instance('Selenium2Library')
    return se2lib._current_browser()

rawDescription: Pass existing Webdriver object to custom Python library for Robot Framework


code:
import ipaddr
it = ipaddr.IPNetwork('10.0.0.0/8').subnet(new_prefix=22)
networks = [(str(n.network), str(n.broadcast)) for n in it]
len(networks)
networks[0]
networks[-1]

rawDescription: Get a list of subnets matching a given CIDR


rawDescription: Make a thread wait for either a Timer or a Signal?


code:
s = 'Check highlight function'
l = ['check']
re.sub('(?i)(' + '|'.join(map(re.escape, l)) + ')', r'<mark>\1</mark>', s)

rawDescription: python replace multiple words retaining case

description: Python replace multiple words retaining case


code:
import timeit
c1='''
num = 600851475143
while num % 2 == 0:
    num /= 2
if num == 1:
    i = 2
else:
    i = 3
    while num > 1:
        if num % i == 0:
            num /= i
        else:
            i += 2
'''
timeit.timeit(c1, number=10000)

rawDescription: Why is function-less slower?

description: Why is function-less slower


code: project_data = []

rawDescription: Insert post data into MongoDB

description: Insert post data into MongoDB


code:
def text_capture(self):
        mtext = self.test.get()
        print(self.test)
        print(mtext)
        print(self.test.get())

rawDescription: Store data from Entry widget tkinter

description: Store data from Entry widget tkinter


code:
n = 15 # the larger n is, the smoother curve will be
b = [1.0 / n] * n
a = 1
yy = lfilter(b,a,y)
plt.plot(x, yy, linewidth=2, linestyle="-", c="b") # smooth by filter

rawDescription: Reducing noise on Data

description: Reducing noise on Data


rawDescription: get file size before downloading using HTTP header not matching with one retrieved from urlopen

description: Get file size before downloading using HTTP header not matching with one retrieved from urlopen


code:
with open("B.txt") as file:
    B = dict(line.strip().split() for line in file)

rawDescription: How to replace a particular value of a field (column) in a file with a value from another file in shell scripting?

description: Replace a particular value of a field (column) in a file with a value from another file in shell scripting


code: corpus.flatMap(lambda doc: [(x, 1) for x in doc.split(' ')]).reduceByKey(add)

rawDescription: Pyspark, perform word count in an RDD comprised of arrays of strings.


code:
camera = [0,0]
...
def update(self, dx=0, dy=0):
    newpos = (self.pos[0] + dx, self.pos[1] + dy)  # Calculates a new position
    entityrect = pygame.Rect(newpos, self.surface.get_size())
    camera[0] += dx
    camera[1] += dy
    ...

rawDescription: Python Pygame Camera Movement

description: Python Pygame Camera Movement


code:
s = frozenset("kapow")
[next(iter(s)) for _ in range(10)]

rawDescription: How to get an arbitrary element from a frozenset?

description: Get an arbitrary element from a frozenset


rawDescription: Comparing two lists and inserting Nulls where necessary


code:
def so_called_combs(data):
    for sublist in data:
        for sbl in data:
            if sbl==sublist:
                yield sbl
                continue
            for i in range(len(sublist)):
                c = sublist[:]
                c[i] = sbl[i]
                yield c

rawDescription: Combine all elements of n lists in python


code:
from collections import Counter

msgs = [{('white', 'man'): 114}, {('white', 'woman'): 91}, {('red', 'man'): 114}, {('red', 'woman'): 114}, {('blu', 'man'): 114}, {('blu', 'woman'): 114}]

Counter(word for msg in msgs for words in msg for word in words)

rawDescription: count the dictionary keys in a list

description: Count the dictionary keys in a list


code:
def np_to_int(np_val):
    return np.asscalar(np.int16(np_val))

def rect_for_contour(con):
    # Get coordinates of a rectangle around the contour
    leftmost = tuple(con[con[:,:,0].argmin()][0])
    topmost = tuple(con[con[:,:,1].argmin()][0])
    bottommost = tuple(con[con[:,:,1].argmax()][0])
    rightmost = tuple(con[con[:,:,0].argmax()][0])

    return leftmost[0], topmost[1], rightmost[0], bottommost[1]

rawDescription: OpenCV - Drawing contours as they are

description: OpenCV - Drawing contours as they are


code:
egroup = (df["event"] != df["event"].shift()).cumsum()
df["prev_occur"] = egroup.groupby(df["event"]).rank(method="dense") - 1
df

rawDescription: Find recurring events in time series with pandas


code:
a = numpy.array([False,True,False])
~a
numpy.logical_not(a)
a = numpy.array([0,1,0])
~a
numpy.logical_not(a)

rawDescription: Numpy inverse mask

description: Numpy inverse mask


code: content = text.get(1.0, "end-1c")

rawDescription: Validation on Tkinter.Text widget?

description: Validation on Tkinter.Text widget


code:
geo = soup.select_one("div[itemprop=geo]")
lat, lon = geo.select_one("meta[itemprop=latitude]")["content"], geo.select_one("meta[itemprop=longitude]")["content"]
print(lat,lon)

rawDescription: get attribute value BeautifulSoup

description: Get attribute value BeautifulSoup


code: from django.contrib.auth.decorators import permission_required

rawDescription: Django Users that cannot access Admin and Customizing Admin


code: cursor.execute(sql, field_values)

rawDescription: How to handle apostrophes in MySQL-Python?

description: Handle apostrophes in MySQL-Python


rawDescription: Create colour picture from greyscale picture


code:
example = ""
for i in range(1,4):
    example = example + str(i)+". " +input("enter the example !") +"\n"
print (example)

rawDescription: connecting and separating string inputs

description: Connecting and separating string inputs


code:
from inspect import ismethod, getargspec

def exclude_self(func):
    args = getargspec(func)
    if ismethod(func):
        args[0].pop(0)
    return args

exclude_self(c.f) # ArgSpec(args=['a', 'b'], ...)

rawDescription: Is there a way to get function parameter names, including bound-methods excluding `self`?


rawDescription: Relooping the list

description: Relooping the list


rawDescription: Counting "page views" or "hits" when using cache


code:
raw_location = 'C:/Users/OneDrive/raw/'
output_location = 'C:/Users/OneDrive/output/'
mtd_location = 'C:/Users/OneDrive/modified/'
py_location = 'C:/Users/OneDrive/py_files/'

rawDescription: Creating a file to lookup paths and file names?


code: mynotes['datasource']['filter']['contract'] = { '$in': account['contracts'] }

rawDescription: User dependend resource filter in Python-eve RestApi Framework


rawDescription: Get python install path from running script


code: arr = numpy.array(mat)

rawDescription: Summation of every row, column and diagonal in a 3x3 matrix numpy


code: min(list_of_dictionaries, key=lambda d: min(d.values()))

rawDescription: Python: file oldest date value in a list of objects


code: kFirstColumns= int(sys.argv[1])

rawDescription: How to pass parameters to Python streaming script in Hive?

description: Pass parameters to Python streaming script in Hive


rawDescription: Is there a statistics module for Python 2.7?


code:
def get_items(request):
    return {} # values that you can pick and choose from in each view

@view_config(route_name='name', permission='perm', xhr=True, renderer='json')
def r_ajax(request):
    items = get_items(request)
    return {
        'data1': 1, 'data2': 2, 'data3': 3,
        'html': renderers.render('shortr.mako', {'items': items}, request),
    }

@view_config(route_name='name', permission='perm', renderer='r.mako')
def r_html(request):
    items = get_items(request)
    return items

rawDescription: A better pattern for ajax loading with pyramid?


rawDescription: How to *not* display 'NaN' in ipython notebook (html table of pandas dataframe)?


code: was_pressed = set()

rawDescription: Python pygame, moving an object

description: Python pygame, moving an object


code:
from django import forms
from haystack.forms import ModelSearchForm
from haystack.query import SearchQuerySet

class AutocompleteSearchForm(ModelSearchForm):

  def search(self):
    if not self.is_valid():
      return self.no_query_found()

    if not self.cleaned_data.get('q'):
      return self.no_query_found()

    sqs = self.searchqueryset.filter(autocompletetext=self.cleaned_data.get('q'))

    sqs = sqs.models(*self.get_models())

    if self.load_all:
      sqs = sqs.load_all()

    return sqs

rawDescription: django haystack module search with whoosh

description: Django haystack module search with whoosh


code:
import numpy as np
import matplotlib.pyplot as plt
angles = np.random.rand(100)

length = 1.
vectors_2d = np.vstack((length * np.cos(angles), length * np.sin(angles))).T

for x, y in vectors_2d:
    plt.plot([0, x], [0, y])
plt.show()

rawDescription: Plot stack of unit vectors in cylindrical coordinates - matplotlib


code:
from bs4 import BeautifulSoup

content = '''
Courtney, John  (Dem)
Clinton, Hilary  (Dem),
Lee, Kevin  (Rep)
'''

politicians = []
soup = BeautifulSoup(content)
for item in soup.find_all('a'):
    name, party = item.text.strip().rsplit('(')
    politicians.append((name.strip(), party.strip()[:-1]))

rawDescription: web scraping using beautifulsoup: separating values

description: Web scraping using beautifulsoup: separating values


rawDescription: Using Argparse and Json together

description: Using Argparse and Json together


code:
items = [list(item.strip()) for item in items]
board_list.extend(items)

rawDescription: list of list of str

description: List of list of str


code: all(n <= c2[k] for k, n in c1.items())

rawDescription: How to check if all items in a list are there in another list?

description: Check if all items in a list are there in another list


code:
N = 3
result = pd.DataFrame(df['y'].values.reshape(-1, N).T)

rawDescription: Pandas dataframe: how to group by values in a column and create new columns out of grouped values


code:
self.user = User.objects.create(username='testuser',password='!')
self.user.set_password('some_password')
self.user.save() # <--- You need this ;)

rawDescription: Create a simple password for unittest user using PASSWORD_HASHERS


code:
from _example import *

import inspect
import sys

def _force_locals(old_frame, new_locals):
    ''' Force a new set of locals on a given frame.

    :param old_frame: The frame to which locals will be applied.
    :type old_frame: frame.
    :param new_locals: What locals() should return for old_frame.
    :type new_locals: dict.

    .. note:: This function will force a custom trace function onto
              the old_frame.  Within the context of a trace function
              (often used for debugging), a frame's f_locals is
              modifiable.  In most execution paths, f_locals is
              writable but not modifiable.

    '''
    # Force tracing by setting the global tracing function to
    # any non-None function.
    if not sys.gettrace():
        sys.settrace(lambda *args, **keys: None)

    # Custom trace function that will force locals.
    def trace(frame, event, arg):
        # Update the frame's locals.
        frame.f_locals.update(new_locals)
        # Set frame to use default trace, preventing this trace
        # function from resetting the locals on each trace call.
        del frame.f_trace

    # Set the old frame's trace function to the custom trace.
    old_frame.f_trace = trace

def _update_locals(frame, *refs):
    ''' Modifies a frame's locals based on the provided references.

    :param frame: The frame from which a locals will be updated.
    :type frame: frame.
    :param refs: Iterable pair of (old_ref, new_ref) tuples.
    :type refs: Iterable type of pairs.

    '''
    new_locals = frame.f_locals.copy()
    has_changes = False

    # If a frame's local has an identity patch with a provided
    # reference, then update new_locals with the new reference.
    for key, ref in new_locals.iteritems():
        for old_ref, new_ref in refs:
            if ref is old_ref:
                new_locals[key] = new_ref
                has_changes = True

    # If new_locals has changes, then force them onto the frame.
    if has_changes:
        _force_locals(frame, new_locals)

def _patch_fun():
    old_fun = fun
    # Create a function that will perform custom operations then
    # delegate to the original function.
    def patch(spam, *args, **kwargs):
        if isinstance(spam, str):
            old_spam, spam = spam, Spam(spam)

            # In the caller's frame, force the variables that reference
            # old_spam to now reference spam.
            _update_locals(
                inspect.currentframe(1), # Caller's frame.
                (old_spam, spam))

        return old_fun(spam, *args, **kwargs)
    return patch

fun = _patch_fun()

rawDescription: Boost.python automatically convert parameter


rawDescription: why does python add another backslash to \i

description: Why does python add another backslash to \i


code:
from nltk.corpus import state_union
train_text = state_union.raw("2005-GWBush.txt").split('\n')
train_text[11]

rawDescription: Use of PunktSentenceTokenizer in NLTK

description: Use of PunktSentenceTokenizer in NLTK


code:
from pprint import pprint
pprint(init_data)

rawDescription: Change json object data by reference in Python


code:
all([True, 10, 'name'])
all([True, 0, 'name'])

rawDescription: AND operation for Boolean array's elements


code:
q = testClass()
q.setValue(q.red)

rawDescription: Using an Enum as a flag in a class, Python


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-#

import wxversion
wxversion.select('2.9.5')

import wx
import wx.lib.sized_controls as SC

class AltFrame(SC.SizedFrame):

    def __init__(self, *args, **kwds):
        super(AltFrame, self).__init__(*args, **kwds)

        paneCont = self.GetContentsPane()

        paneControls = SC.SizedPanel(paneCont)
        paneControls.SetSizerType('grid', options={'cols': 2,})
        paneControls.SetSizerProps(expand=True, proportion=1)
        paneButtons = SC.SizedPanel(paneCont)
        paneButtons.SetSizerType('grid', options={'cols': 3,})
        paneButtons.SetSizerProps(align='center')

        self.button1 = wx.Button(paneButtons, label='Clear',
              name='button1')

        self.button2 = wx.Button(paneButtons, label='Convert',
              name='button2')

        self.button3 = wx.Button(paneButtons, label='Now',
              name='button3')

        self.staticText1 = wx.StaticText(paneControls, label=u'2^10 * Hex',
                                         name='staticText1',
                                         style=wx.ALIGN_RIGHT)
        self.textCtrl1 = wx.TextCtrl(paneControls, name='textCtrl1',
                                     value='textCtrl1')

        self.staticText2 = wx.StaticText(paneControls, label=u'Hex Time',
                                         name='staticText2',
                                         style=wx.ALIGN_RIGHT)
        self.textCtrl2 = wx.TextCtrl(paneControls, name='textCtrl2',
                                     value='textCtrl2')

        self.staticText3 = wx.StaticText(paneControls,
              label=u'Epoch Time', name='staticText3')
        self.textCtrl3 = wx.TextCtrl(paneControls, name='textCtrl3')

        self.staticText4 = wx.StaticText(paneControls,
              label=u'Date And Time', name='staticText4')
        self.textCtrl4 = wx.TextCtrl(paneControls, name='textCtrl4')

        self.statusBar2 = wx.StatusBar(self, name='statusBar2')
        self.statusBar2.SetStatusText(u'Current status...')
        self.statusBar2.SetToolTipString(u'statusBar2')

        self.SetStatusBar(self.statusBar2)

if __name__ == "__main__":
    import wx.lib.mixins.inspection as WIT

    app = WIT.InspectableApp()
    frame = AltFrame(None)
    frame.Show()
    app.MainLoop()

rawDescription: Unable to get wxPython Sizers to work correctly


code:
d = {}

# Create a 1-to-1 mapping for the first n-1 items in `one`
for i in one[:-1]:
    d[i] = [elements.pop(0)]

# Append the remainder of `elements`
d[one[-1]] = [elements]

rawDescription: python- combining list and making them a dictionary

description: Python- combining list and making them a dictionary


code:
from IPython.display import HTML
table = "

bar	bar

foo	foo

"
HTML(table)

rawDescription: CSS Styling of HTML in IPython Notebook output


code:
def bfs(graph, start):
    path = []

rawDescription: BFS algorithm in Python

description: BFS algorithm in Python


code:
def undo_double_counting(d):
    sorted_features = sorted(d, key=lambda f: f.count('-'), reverse=True)
    for f in sorted_features:
        if '-' not in f:
            return d
        feature_below, _ = f.rsplit('-', 1)
        while True:
            try:
                d[feature_below] -= d[f]
            except KeyError:
                # if the feature one degree below isn't actually in d,
                # we keep trying lower degrees until we know that we
                # can't go lower any more (by hitting ValueError)
                try:
                    feature_below, _ = feature_below.rsplit('-', 1)
                except ValueError:
                    break
            else:
                break
    # if there are no degree-1 features in d, return here
    return d

rawDescription: How to perform the following ordered subset element test in Python?

description: Perform the following ordered subset element test in Python


code:
def day_name(day):
    return weekdays[day]

rawDescription: In Python i need a day_name function

description: In Python i need a day_name function


code:
nx.draw(X, pos)
plt.show()

rawDescription: networkx add_node with specific position

description: Networkx add_node with specific position


code: json1_data = json.loads(json1_str)[0]

rawDescription: Converting JSON String to Dictionary, Not List (Python)


code:
matrix = origin_matrix

for i in range(N_times):
    matrix = operation(matrix)

return matrix

rawDescription: how to determine the period of a function

description: Determine the period of a function


code:
from abc import ABCMeta, abstractproperty
class SingletonABCMeta(ABCMeta):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(SingletonABCMeta, cls).__call__(*args, **kwargs)
        return cls._instances[cls]
class GenericLogger(object):
    __metaclass__ = SingletonABCMeta
    @abstractproperty
    def SearchLink(self): pass
class Logger(GenericLogger):
    @property
    def SearchLink(self): return ''
Logger()
Logger()
class IncompleteLogger(GenericLogger):
    pass
IncompleteLogger()

rawDescription: Python implementing Singleton as metaclass , but for abstract classes


code:
from bs4 import BeautifulSoup
import re

soup = BeautifulSoup(html_page_source)
script_tag = soup.find('script', text=re.compile('window\._sharedData'))
shared_data = script_tag.string.partition('=')[-1].strip(' ;')

rawDescription: Get a dict between tags from html request


rawDescription: How do I save an image in python 3 using PIL?

description: Save an image in python 3 using PIL


rawDescription: Python: Produce increments from a list to form an array


code: nonscripttags = htmlDom.findAll(lambda t: t.name != 'script', recursive=False)

rawDescription: Extracting readable text from HTML using Python?


rawDescription: Python - how to count number of uppercase letters in a string that is in a list


code:
def strip_unprintable(data):
    return ''.join(c for c in data if c in string.printable)

rawDescription: How to detect undecoded characters in python?

description: Detect undecoded characters in python


rawDescription: How to point to python dictionary value?

description: Point to python dictionary value


code: sortedColumn = sorted(csv_opener, key=lambda row: (row[0], -int(row[1])))

rawDescription: How to sort two columns at once using sorted()

description: Sort two columns at once using sorted()


code:
def pascals(row, column):
    if column == 0:
        return 1
    if row == 0:
        return 1
    if row < 0:
        return 0
    if column < 0:
        return 0
    if column > row:
        return 0
    if column == row:
        return 1
    else:
        return pascals(row - 1, column - 1) + pascals(row - 1, column) # Your brackets should be like this
# generate the first 10 rows of Pascal's Triangle
for row in range(10):
    print('{: ^45}'.format(' '.join(str(pascals(row, col)) for col in range(row+1)))) # you left out one bracket here

rawDescription: Pascals Triangle Displaying All 1s

description: Pascals Triangle Displaying All 1s


rawDescription: Best way to encode tuples with json

description: Encode tuples with json


code:
if 500 <= amount:
    while 500 <= amount:
        amount -= 500
        fivehundreds += 1

rawDescription: All cash change is only for one bill

description: All cash change is only for one bill


rawDescription: How to reduce the duplicated characters in a string using Python

description: Reduce the duplicated characters in a string using Python


code: coords = list(zip(A,B,C))

rawDescription: how to sort the following

description: Sort the following


code:
import mod1
import mod2

rawDescription: how to avoid shared module dependency in python

description: Avoid shared module dependency in python


code:
def print_i():
     print(i)

for i in range(5):
    pass

print_i()

rawDescription: Problems with a bind function from tkinter in Python


code:
import matplotlib.pyplot as plt
import numpy as np
x = np.random.rand(2,3)
plt.imshow(x, interpolation='nearest', extent=[0,3,0,2])

rawDescription: plotting imshow and line plot together in python

description: Plotting imshow and line plot together in python


code:
list(split_into('abcd', 3))
list(split_into('abcde', 3))
list(split_into('abcdef', 3))
list(split_into('abcdefg', 3))
list(split_into('abcdefgh', 3))

rawDescription: Split a string into exactly N pieces

description: Split a string into exactly N pieces


rawDescription: Using numpy to Obtain Submatrix

description: Using numpy to Obtain Submatrix


code:
def existsOnce3(aDict):
    vals = {}
    # create dict to sum all value counts
    for i in aDict.values():
        vals.setdefault(i,0)
        vals[i] += 1
    # use each v/val from aDict as the key to vals
    # keeping each k/key from aDict if the count is 1
    return sorted(k for k, v in aDict.items() if vals[v] == 1)

rawDescription: Check for unique values in a dictionary and return a list


rawDescription: How to use ndb.OR in a loop?

description: Use ndb.OR in a loop


code:
from django.contrib.auth.models import update_last_login

class TokenAuthenticationView(ObtainAuthToken):
    """Implementation of ObtainAuthToken with last_login update"""

    def post(self, request):
        result = super(TokenAuthenticationView, self).post(request)
        try:
            request_user, data = requests.get_parameters(request)
            user = requests.get_user_by_username(data['username'])
            update_last_login(None, user)
        except Exception as exc:
            return None
        return result

rawDescription: last_login field is not updated when authenticating using Tokenauthentication in Django Rest Framework

description: Last_login field is not updated when authenticating using Tokenauthentication in Django Rest Framework


code:
from  availableDates import avDates
printTest = avDates()
print ("These are the dates - %s" % ', '.join(map(str, printTest)))

rawDescription: Having some problems printing out an array in Python3


code: lambda t: tuple(list(t[0]) + [t[1]])

rawDescription: How to flatten tuple created using zip transformation in PySpark

description: Flatten tuple created using zip transformation in PySpark


code:
url_search('', 'test')
url_search('', 'te')
url_search('this is a ', 'test')

rawDescription: how to test for a regex match

description: Test for a regex match


code:
import zipfile
import os
import sys

zipped_files_dir = 'Z:\Dev\some_files'

def get_folder_names():
    path_list = []
    for folder_name in os.listdir(zipped_files_dir):
        path_list.append(os.path.join(zipped_files_dir, folder_name))
    return path_list

def get_folder_directories(folder_list):
    for folder in folder_list:
        pathname = os.path.abspath(folder)
        print(pathname)

def main():
    get_folder_directories(get_folder_names())

rawDescription: full file path for zipped folder in python

description: Full file path for zipped folder in python


code:
t = [[100, 'str_1'], [200, 'str_2'], [300, 'str_3']]
list(enumerate(t))
[n for n, (i, s) in enumerate(t)]
[n for n, (i, s) in enumerate(t) if s == 'str_3']
[n for n, (i, s) in enumerate(t) if s == 'str_1234']

rawDescription: Python Nested lists and iteration

description: Python Nested lists and iteration


rawDescription: Using a Python dict to replace/clean data in a Pandas DataFrame


code:
import argparse

class NegateAction(argparse.Action):
    def __call__(self, parser, ns, values, option):
        setattr(ns, self.dest, option[2:4] != 'no')

ap = argparse.ArgumentParser()
ap.add_argument('--toggle', '--no-toggle', dest='toggle', action=NegateAction, nargs=0)

rawDescription: Python argparse --toggle --no-toggle flag


code:
def click_1 (key):
    if key in word:
        for index, character in enumerate(word):
            if character == key:
                hidden_word[index] = character
        print (hidden_word)
    else:
        print ("Nope")

rawDescription: Trying to find the same item in a list with the context of hangman


code:
@singleton
class cls(object):
   pass

rawDescription: Why isn't the instances variable lost after executing the function?


code: z.swapaxes(1,2).reshape(2*3, 3)

rawDescription: numpy reshaping multdimensional array through arbitrary axis

description: Numpy reshaping multdimensional array through arbitrary axis


rawDescription: Convert a RDD of Tuples of Varying Sizes to a DataFrame in Spark


code:
from Tkinter import *
import subprocess

root = Tk()
root.geometry("850x500+300+300")

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
    def initUI(self):

        self.parent.title("Windows")
        #self.style = Style()
        #self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)

        lbl = Label(self, text="Windows")
        lbl.grid(sticky=W, pady=4, padx=5)

        abtn = Button(self, text="Check Wired Connections",command = self.checkconnections)
        abtn.grid(row=1, column=3)

        cbtn = Button(self, text="Check Wireless Connections")
        cbtn.grid(row=3, column=3, pady=4)

        obtn = Button(self, text="OK")
        obtn.grid(row=5, column=3)
        self.v = StringVar()
        messagelabel=Label(self, textvariable=self.v)
        messagelabel.grid(row=1, column=0, pady=0)

    def checkconnections(self):
        self.v.set("hai")

def main():

    app = Example(root)
    root.mainloop()
main()

rawDescription: How can I place the output of different button functions in tkinter in a particular frame?

description: Place the output of different button functions in tkinter in a particular frame


code:
df = pd.DataFrame(np.random.randint(1, 10, (5, 3)))
df
df.apply(np.prod, axis=1)

rawDescription: Multiply all columns in a Pandas dataframe together


rawDescription: Efficient way of appending / extracting list elements


code:
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

rawDescription: (python/boto sqs) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 5: ordinal not in range(128)


rawDescription: Rotating a 5D array in the last 2 dimensions


code:
df.index = pd.MultiIndex.from_tuples(df.index)
df
df.index.names = ['id', 'act_type']
df

rawDescription: Converting tuples to multiple indices in a Pandas Dataframe


code:
headers = {
    'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language' : 'en-US,en;q=0.5',
    'Connection' : 'keep-alive',
    'Host' : 'www.ssa.gov',
    'Referer' : 'http://www.ssa.gov/cgi-bin/popularnames.cgi',
    'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0'
    }

# With POST data:
urllib.urlopen(url, post_args, headers)

rawDescription: a (presumably basic) web scraping of http://www.ssa.gov/cgi-bin/popularnames.cgi in urllib

description: A (presumably basic) web scraping of http://www.ssa.gov/cgi-bin/popularnames.cgi in urllib


code:
def f3_simple(n):
    i = n
    condition = i>0
    while condition:
        r1 = range(i)
        for j in r1:
            r2 = range(j, 10**5)
            for k in r2:
                print(i)
        i -= 2
        condition = i>0

rawDescription: python complexity calculation

description: Python complexity calculation


code:
while True:
    msg = q.get()
    process_message(msg)

rawDescription: How to wakeup thread from thread pool in python?

description: Wakeup thread from thread pool in python


rawDescription: how to extract asin from an amazon product page

description: Extract asin from an amazon product page


code:
for row in islice(rowlist, 6, 12):
    if row[0] == "data_type":
        continue
    elif row[0] == "fields":
         fileobj.write(islice(rowlist, 1,None))
    else:
        fileobj.write(row)

rawDescription: python: how to delete row and modify specific list string from CSV

description: Python: how to delete row and modify specific list string from CSV


code: [{'number':i,'other_number':j} for i,j in zip(range(0,4),range(3,6))]

rawDescription: Update dictionary from two yield functions


rawDescription: Python: Combining two CSV files with header row and matched values with DictReader and DictWriter


code:
from pyspark.sql.functions import from_unixtime, unix_timestamp
from pyspark.sql.types import TimestampType

df.select((from_unixtime(unix_timestamp(
    df.datetime, "yy-MMM-dd h.mm.ss.SSSSSS aa"
))).cast(TimestampType()).alias("datetime"))

rawDescription: Column filtering in PySpark

description: Column filtering in PySpark


code:
from __future__ import print_function
from timeit import Timer
from math import factorial

try:
    range = xrange
except:
    pass

def perms(s):
    s = tuple(s)
    N = len(s)
    if N <= 1:
        yield s[:]
        raise StopIteration()
    for x in perms(s[1:]):
        for i in range(0,N):
            yield x[:i] + (s[0],) + x[i:]

def testcase(s):
    for x in perms(s):
        pass

def test():
    for i in range(1,11):
        s = "".join(["%d" % x for x in range(i)])
        s = "testcase(\"%s\")" % s
        t = Timer(s,"from __main__ import testcase")
        factor = 100000
        factor = int(factor/factorial(i))
        factor = (factor>0) and factor or 1
        yield (i,(1000*min(t.repeat(5,factor))/factor))

if __name__=="__main__":
    print("args\ttime[ms]")
    for x in test():
        print("%i\t%f" % x)

rawDescription: Slightly different execution times between python2 and python3


rawDescription: nested classes in Python

description: Nested classes in Python


code: anything_goes_in_here = [1, 'one', lambda one: one / 1, {1: 'one'}, [1, 1]]

rawDescription: Storing the result of Minhash

description: Storing the result of Minhash


code:
mygreen = make_colormap([c('burnt red'),
                         c('yellow green'), idx[1], c('yellow green'),
                         (0,1,0), idx[2], (0,1,0),  # RGB (0,1,0) is standard green?
                         c('dark green')])

rawDescription: Discrete then linear colormap in matplotlib


code:
args = ['foo', 'bar']
kwargs = {'c': 2, 'd': 3}
f(*args, **kwargs)

rawDescription: How to build arguments for a python function in a variable

description: Build arguments for a python function in a variable


code:
class Expr(ParsedObject):
    def queryString(self):
        return '(%s)' % self.tokens[0].queryString()
expr.setParseAction(Expr)

rawDescription: pyparsing one query format to another one

description: Pyparsing one query format to another one


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

x = np.linspace(0, 10, 5)

fig, ax = plt.subplots()
for i in range(1, 6):
    ax.plot(x, i*x + x, marker='o', markersize=20,
            label='$y={i}x + {i}$'.format(i=i))
ax.legend(loc='upper left', handlelength=5, borderpad=1.2, labelspacing=1.2)
plt.show()

rawDescription: How to adjust the size of matplotlib legend box?

description: Adjust the size of matplotlib legend box


code: myInstance = myClass(lambda:None)

rawDescription: Is there a python construct that is a dummy function?


code:
s = 4
i,j = np.indices((s,s))
(abs(i-j) <= 1).astype(int)

rawDescription: Constructing a special matrix in numpy dynamically


code:
def makelist(table):
  result = []
  allrows = table.findAll('tr')
  for row in allrows:
    result.append([])
    allcols = row.findAll('td')
    for col in allcols:
      thestrings = [unicode(s) for s in col.findAll(text=True)]
      thetext = ''.join(thestrings)
      result[-1].append(thetext)
  return result

rawDescription: How to convert an HTML table to an array in python

description: Convert an HTML table to an array in python


code: ser[len(ser)] = ser.iloc[-1]

rawDescription: Plotting CDF of a pandas series in python


rawDescription: Plotting implicit equations in 3d

description: Plotting implicit equations in 3d


code:
for ing in ingredients:
    print(re.search(r'[a-z][^.,]*(?![^,])(?i)', ing).group())

rawDescription: Regex in Python 3: match everything after a number or optional period but before an optional comma


code:
sentinel = []
sentinel = {}

rawDescription: Using None as parameter to keyword argument


code:
class staticandinstancemethod(object):
     def __init__(self, f):
          self.f = f

     def __get__(self, obj, klass=None):
          def newfunc(*args, **kw):
               return self.f(obj, *args, **kw)
          return newfunc

rawDescription: Can a method be used as either a staticmethod or instance method?


code:
class BaseWithOrderedFields(type):
  """ Metaclass, which provides an attribute "ordered_fields", being an ordered
      list of class attributes that have a "creation_counter" attribute. """

  def __new__(cls, name, bases, attrs):
    new_class = super(BaseWithOrderedFields, cls).__new__(cls, name, bases, attrs)
    # Add an attribute to access ordered, orderable fields
    new_class._ordered_items = [(name, attrs.pop(name)) for name, obj in attrs.items()
                                    if hasattr(obj, "creation_counter")]
    new_class._ordered_items.sort(key=lambda item: item[1].creation_counter)
    return new_class

rawDescription: How can I get fields in an original order?

description: Get fields in an original order


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.network.urlrequest import UrlRequest
from kivy.uix.gridlayout import GridLayout
import urllib

class MainLayout(GridLayout):

    count = 1

    def send_message(self, message):
        POST_data = self._prepare_data(message)
        self._send_message(POST_data)

    def _prepare_data(self, message):
        auth_data = {'message': message}
        auth_data = urllib.urlencode(auth_data)
        headers = {
            'Content-type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
        }
        return {'auth_data': auth_data, 'headers': headers}

    def _send_message(self, POST_data):
        UrlRequest(
            url='http://localhost:5000/',
            req_body=POST_data['auth_data'],
            req_headers=POST_data['headers'],
            on_failure=self._on_connection_failure,
            on_error=self._on_connection_error,
            on_success=self._on_connection_success,
        )

    def _on_connection_success(self, request, result):
        self.ids.status_label.text =\
            'message %s delivered' % self.count
        self.count += 1

    def _on_connection_failure(self, request, result):
        self.ids.status_label.text = 'connection fail'

    def _on_connection_error(self, request, result):
        self.ids.status_label.text = 'connection error'

class Test(App):
    pass

Test().run()

rawDescription: How do I comunicate with my computer through Kivy?

description: Comunicate with my computer through Kivy


code:
specs = {}
for path, spec in paths:
    parts = path.split('.')
    d = specs
    for p in parts[:-1]:
        d = d.setdefault(p, {})
    d[parts[-1]] = spec

rawDescription: Python: Created nested dictionary from list of paths


code:
import random
random_sum = random.randint(10**3, 10**4)
result = get_min_coin_configuration(sum = random_sum, coins = random.sample(range(10**3), 200))
assert sum(result) == random_sum

rawDescription: recursively implementing 'minimum number of coins' in python

description: Recursively implementing 'minimum number of coins' in python


rawDescription: Execute manage.py from python shell

description: Execute manage.py from python shell


code:
import datetime
today = datetime.date.today()
today + datetime.timedelta(days=-today.weekday(), weeks=1)

rawDescription: Find Monday's date with Python

description: Find Monday's date with Python


code:
data = []
for line in input_file:
    data.append(line.strip().split(' ', 3))

rawDescription: Python file string comparison

description: Python file string comparison


code:
data.pop()
data.add(new_value)

rawDescription: What are the pythonic way to replace a specific set element?


code:
def foo():
    pass
foo = dec(foo)

rawDescription: Is it possible to apply my own decorators to builtin methods in Python?


code:
def palplot(pal, size=1):
    """Plot the values in a color palette as a horizontal array.

    Parameters
    ----------
    pal : sequence of matplotlib colors
        colors, i.e. as returned by seaborn.color_palette()
    size :
        scaling factor for size of plot

    """
    n = len(pal)
    f, ax = plt.subplots(1, 1, figsize=(n * size, size))
    ax.imshow(np.arange(n).reshape(1, n),
              cmap=mpl.colors.ListedColormap(list(pal)),
              interpolation="nearest", aspect="auto")
    ax.set_xticks(np.arange(n) - .5)
    ax.set_yticks([-.5, .5])
    ax.set_xticklabels([])
    ax.set_yticklabels([])

rawDescription: Displaying matrix-like image with RGB-colored cells in matplotlib


code:
import sys
sys.path.append( "d:/zrodla/stack/mydir" )
mymod2
mymod2 == mydir.mymod

rawDescription: how do python module variables work?

description: How do python module variables work


code:
dill.dumps(f, byref=False)
dill.dumps(f, byref=True)

rawDescription: Why dill dumps external classes by reference, no matter what?


code:
def two_tier_dict_init(tier1, tier2, value_factory):
    dict_name = {}
    for t1 in tier1:
        dict_name[t1] = {}
        for t2 in tier2:
            dict_name[t1][t2] = value_factory()
    return dict_name

rawDescription: Why are values of a two-level dictionary all pointing to the same object in Python 2.7?


code:
import re

def remove_between_anchors(text, anchor):
    return re.sub(r'{0}.+?{0}'.format(anchor), '', text)

remove_between_anchors('123aa456aa789', 'aa') # returns '123789'

rawDescription: Remove character starting with x and ending with x and everything between it in a string


code:
indexers = np.unique(np.concatenate([ np.arange(max(i-n,0),min(i+n,len(df))) for i in df[df.event=='ping'].index ]))
indexers

rawDescription: How can I select all DataFrame rows that are within a certain distance of a given value in a specific column?

description: Select all DataFrame rows that are within a certain distance of a given value in a specific column


rawDescription: How to unset or disable hyperlinkctrl in wxpython only on some conditions

description: Unset or disable hyperlinkctrl in wxpython only on some conditions


rawDescription: Function when entered in text box?

description: Function when entered in text box


rawDescription: How to assign equal scaling on the x-axis in Matplotlib?

description: Assign equal scaling on the x-axis in Matplotlib


code:
upper = 20
x = x[x<upper]  # only values where x < upper

rawDescription: How to generate random numbers in specyfic range using pareto distribution in Python

description: Generate random numbers in specyfic range using pareto distribution in Python


code:
import pygame.cdrom as cdrom

cdrom.init()
cd = cdrom.CD(0)
cd.init()
cd.eject()
cd.quit()
cdrom.quit()

rawDescription: How can I eject a CD from MacOS with Python?

description: Eject a CD from MacOS with Python


code:
me = Human("Jane", "Doe")
print(me.last_name)

rawDescription: Representation for a method applied on a class in Python


code:
def common_substr(a, b, k):
  substrs = set(a[i:i+k] for i in range(len(a)-k+1))
  for substr in (b[i:i+k] for i in range(len(b)-k+1)):
    if substr in substrs:
      return substr

rawDescription: Common substring of length k

description: Common substring of length k


code: PyIID = IID(iidString, is_bytes )

rawDescription: How to control windows master audio in python script

description: Control windows master audio in python script


rawDescription: Split a string and add into `tuple`

description: Split a string and add into `tuple`


rawDescription: How to give multiple values to a single key using a dictionary?

description: Give multiple values to a single key using a dictionary


code: [reduce(lambda a, x: a * 10**(len(str(x))) + x, t) for t in tuples]

rawDescription: How to turn a tuple into an integer in Python (examples inside)?

description: Turn a tuple into an integer in Python (examples inside)


code: bar = __import__("foo")

rawDescription: Where does __import__ get alias names from?


code:
list1 = ['e', 'd', 'u', 'd']
list2 = ['m', 'o', 'b', 'b', 'e', 'd']
def reverse(L, num):
    new_list=[]
    for i in reversed(range(num)):
         new_list+=L[i]
    for i in range(num, len(L)):
         new_list+=L[i]
    return new_list

reverse(list1, 4)
reverse(list2, 3)

rawDescription: Returns a copy of the list with the first number of items reversed


rawDescription: How do you remove a sublist if a certain element is not found at a specific position across all sublists?

description: Remove a sublist if a certain element is not found at a specific position across all sublists


code:
if hasattr(self.model, 'documents'):
    doStuff(self.model.documents)

rawDescription: Django how to check if the object has property in view


code:
if kind in ['zero', 'slinear', 'quadratic', 'cubic']:
    order = {'nearest': 0, 'zero': 0,'slinear': 1,
             'quadratic': 2, 'cubic': 3}[kind]
    kind = 'spline'

rawDescription: In SciPy, what is 'slinear' interpolation?


code:
new_labels = ['{0:.0%}'.format(float(x.get_text())) for x in ax.get_yticklabels()]
ax.set_yticklabels(new_labels)

rawDescription: How to create a bar chart/histogram with bar per discrete value?

description: Create a bar chart/histogram with bar per discrete value


code:
print('this','is', 'a', 'test')  # default single space between items
print('this','is', 'a', 'test', sep="") # no spaces between items
print('this','is', 'a', 'test', sep="--*--") # user specified separation

rawDescription: How can I suppress the newline after a print statement?

description: Suppress the newline after a print statement


rawDescription: Numpy array subtraction creates a matrix with different dimension. How to correct that?


code:
def get_download_url(self):
    if user.username == 'user1':
        download_url = '/downloads/user1/'
    elif user.username == 'user2':
        download_url = '/downloads/user2/'
    else:
        download_url = None

rawDescription: Django restrict pages to certain users

description: Django restrict pages to certain users


rawDescription: Remove matched tags in html files?

description: Remove matched tags in html files


code:
subtracted_data = np.empty_like(data)
for i in range(len(data)):
    subtracted_data[i] = data[i] - avgs[i]

subtracted_data

rawDescription: Trouble indexing lists of NUMPY arrays properly


rawDescription: Curency Rate Conversion Wrong Base Currency


rawDescription: Numpy sum function returns 1.67772e+07

description: Numpy sum function returns 1.67772e+07


rawDescription: How do I manipulate pandas DataFrame with a column that has rows with strings that needs spliting

description: Manipulate pandas DataFrame with a column that has rows with strings that needs spliting


code:
import logging
logFormatter = logging.Formatter("%(asctime)s [%(threadName)-12.12s] [%(levelname)-5.5s]  %(message)s")
rootLogger = logging.getLogger()

fileHandler = logging.FileHandler("{0}/{1}.log".format(logPath, fileName))
fileHandler.setFormatter(logFormatter)
rootLogger.addHandler(fileHandler)

consoleHandler = logging.StreamHandler()
consoleHandler.setFormatter(logFormatter)
rootLogger.addHandler(consoleHandler)

rawDescription: logger configuration to log to file and print to stdout

description: Logger configuration to log to file and print to stdout


code:
L = ['a', 'b', 'c', 'd']
{letter: i for i,letter in enumerate(L, start=1)}

rawDescription: Python dictionary comprehension example

description: Python dictionary comprehension example


code:
def rec_split(s):
    rest, tail = os.path.split(s)
    if rest == '':
        return tail,
    return rec_split(rest) + (tail,)
rec_split(s)

rawDescription: Python Split path recursively

description: Python Split path recursively


code: output1 + output2

rawDescription: How to concatenate multiple unicode string?

description: Concatenate multiple unicode string


rawDescription: Loop through netcdf files and run calculations - Python or R


code:
l = []
for line in data:
     l.extend(map(int,(w for w in line.split() if w.isdigit())))

rawDescription: Find all occurrences of integer within text in Python


code:
a = np.array(['True', 'False', 'True', 'False'])
a
a == "True"

rawDescription: Numpy Convert String Representation of Boolean Array To Boolean Array


code:
class EZTcomm(bytearray):

    def __init__(self, *args, **kwargs):
        super(EZTcomm, self).__init__(*args, **kwargs)
        # super().__init__(*args, **kwargs)  # python3.x only.
        self.check = CRC(self)

rawDescription: Inheriting and modifying __init__() method


code:
import random
[random.choice(['[', ']', '[]']) for _ in range(random.randint(1, 10))]
[random.choice(['[', ']', '[]']) for _ in range(random.randint(1, 10))]

rawDescription: which random am i looking for to achieve this:

description: Which random am i looking for to achieve this:


code:
import pandas as pnd # external, installation required

# returns a dataframe, specify cols, index et cetera
df = pnd.read_csv(StringIO(csv),
    header=0,
    index_col=["col1", "col3"],
    usecols=["col1", "col2", "col3"],
    parse_dates=["col2"])

# do dirty things with it.

rawDescription: Reading and writing CSV files into a data structure suitable for Excel-style column/row manipulations


code:
import random
import networkx as nx
z=[int(random.gammavariate(alpha=9.0,beta=2.0)) for i in range(100)]
G=nx.configuration_model(z)

rawDescription: Generating a graph with certain degree distribution?


code:
df
df.to_records()

rawDescription: How to get record numpy array with dates from pandas data frame?

description: Get record numpy array with dates from pandas data frame


code:
if len(answers) < len(questions):
    print("Too bad, slowpoke. GAME OVER!")

rawDescription: How to change number in Mad Libs game?

description: Change number in Mad Libs game


code:
import pandas as pd
from numba import jit
from numpy import nan, full
import numpy as np

@jit
def movingAverage(adj_close, maxMA):
    ma = full([len(adj_close), maxMA], nan, dtype=np.float64)
    ind = range( 1, len(adj_close)+1 )
    for d in ind:
        m = max( 0, d-maxMA-1)
        adj = adj_close[d-1:m:-1] if (m or d==maxMA+1) else adj_close[d-1::-1]
        cs = adj.cumsum()
        for i in range( len(adj) ):
            ma[d-1][i] = ( cs[i] / (i+1) )
        if d == ind[-1]:
            return ma # notice that I return it after the last loop but before the loop terminates.
    #return ma

rawDescription: Numba JIT changing results if values are printed


code:
buttonImageName = "image.png"
buttons = findAll(button)

rawDescription: How do I click on an image outside the defined region?

description: Click on an image outside the defined region


rawDescription: Python analogue of Matlab's interval numbers like 1:2:5


rawDescription: How to simplify an expression for a complex constant using sympy?

description: Simplify an expression for a complex constant using sympy


code:
import csv
from itertools import izip_longest

N = 5 # adapt as needed
values = range(1, 23) # use real values here

with open(path, 'wb') as fout:
    csvout = csv.writer(fout)
    rows = izip_longest(*[iter(values)] * N, fillvalue='')
    csvout.writerows(rows)

rawDescription: write 5M data to a csv file using file write operation

description: Write 5M data to a csv file using file write operation


code:
def does_segment_exist(seq, sublist):
    first = sublist[0]
    i = 0
    n = len(sublist)
    while True:
        try:
            i = seq.index(first, i)
        except ValueError:
            return False
        if sublist == seq[i:i+n]:
            return True
        i += 1

print(does_segment_exist([1,3,4,5,2], [3,4,5]))

rawDescription: Finding consecutive values within a list


code:
import nltk
t = nltk.tree.Tree.fromstring("(S (NP I) (VP (V saw) (NP him)))")
print(t)
for index, st in enumerate(t.subtrees()):
    if st.label() == 'VP':
        st.insert(index, nltk.tree.Tree('ADV', ['yesterday']))
print(t)

rawDescription: Insert child node in nltk tree

description: Insert child node in nltk tree


code:
class MyAdmin(models.ModelAdmin):
    list_display = ('other_field', 'delete_link', 'edit_link')

    def delete_link(self, obj):
        info = obj._meta.app_label, obj._meta.module_name
        url = reverse('admin:%s_%s_delete' % info, args=(obj.id,))
        return 'Delete' % url
    delete_link.allow_tags = True
    delete_link.short_description = 'Delete'

    def edit_link(self,obj):
        return u'Edit' % (
             obj._meta.app_label, obj._meta.module_name, obj.id)
    edit_link.allow_tags = True
    edit_link.short_description = "Edit"

rawDescription: How can i have delete and edit link in django admin change list page

description: Have delete and edit link in django admin change list page


code:
import sys
from xml.sax.saxutils import XMLGenerator

class MyXMLGenerator(XMLGenerator):
    def __init__(self, out=sys.stdout, encoding="UTF-8"):
        XMLGenerator.__init__(self, out, encoding)
        self.out = out

    def write (self,s):
        self.out.write(s)

def writexml(out):
    xmlwriter = MyXMLGenerator(out)
    xmlwriter.startDocument()
    xmlwriter.write("<!DOCTYPE test SYSTEM 'test.dtd'>\n")
    xmlwriter.startElement('test', {"a": "1"})
    xmlwriter.characters('abc123')
    xmlwriter.endElement('test')
    xmlwriter.endDocument()

if __name__ == '__main__':
    writexml(out=open("out.xml", "w"))

rawDescription: How to insert DTD DOCTYPE content when using SAX to generate XML output in Python

description: Insert DTD DOCTYPE content when using SAX to generate XML output in Python


rawDescription: Python replace year mentions like '85 with 1985


code: k, _, _, _ = np.linalg.lstsq(M, y)

rawDescription: numpy.polyfit with adapted parameters

description: Numpy.polyfit with adapted parameters


code:
def make_movement(Properties):
    X = Properties[0] * 20
    Disk_List = Properties[4]
    Act_Colour = 'white'
    Inact_Colour = 'black'

    def movement(x, y):
        global Steps
        Y = (Properties[1] + len(Disk_List)) * 20 + 45

        if len(Selected) == 0 and len(Disk_List) > 0:
            Properties[5].fillcolor(Act_Colour)
            Selected.append(Disk_List) #Adds the list with disks to the selected tower
            Selected.append(Properties[5]) #To reset the color of the botton
        elif len(Selected) == 2 and len(Disk_List) > 0 and Selected[0][-1].shapesize()[1] == Disk_List[-1].shapesize()[1]: #To deselect toe button
            Selected[1].fillcolor(Inact_Colour)
            del Selected[0]
            del Selected[0]
        elif len(Selected) == 2 and (len(Disk_List) == 0 or Selected[0][-1].shapesize()[1] < Disk_List[-1].shapesize()[1]): #Lazy function
            Selected[1].fillcolor(Inact_Colour)
            Selected[0][-1].goto(X, Y) #Highest disk of thelist
            Disk_List.append(Selected[0][-1]) #Put the highest disk of the list in the correct place in the list

            del Selected[0][-1] #del the disk from the tower and selected
            del Selected[0] #del the lost from 'Selected', the list of the tower remains
            del Selected[0] #del thebutton

            Steps = Steps + 1

    return movement

rawDescription: Towers of hanoi in python with turtle graphics moving disks