code:
import csv
date = input('Enter date: ').strip()

A = csv.reader( open('csvA.csv', newline=''), delimiter=',')
matches = 0

# reads each row of csvA
for row_of_A in A:

    # removes whitespace before and after of each string in each row of csvA
    row_of_A = [string.strip() for string in row_of_A]

    # if date of row in csvA has equal value to the inputted date
    if row_of_A[1] == date:
        B = csv.reader( open('csvB.csv', newline=''), delimiter=',')

        # reads each row of csvB
        for row_of_B in B:

            # removes whitespace before and after of each string in each row of csvB
            row_of_B = [string.strip() for string in row_of_B]

            # if value of row in csvA is equal to the value of row in csvB
            if row_of_A[2] == row_of_B[0]:

                # if csvC.csv does not exist
                try:
                    open('csvC.csv', 'r')
                except:
                    C = open('csvC.csv', 'a')
                    print('Name,', 'Score', file=C)

                C = open('csvC.csv', 'a')

                # writes name from csvA and value from csvB to csvC
                print(row_of_A[0] + ', ' + row_of_B[1], file=C)

m = 'matches' if matches > 1 else 'match'
print('Found', matches, m)

rawDescription: Matching parts of two csv files to return certain elements


code:
with open('out.txt', 'w') as fout:
    fout.write(''.join(lines))

rawDescription: Replace certain element in only first line of the text file


code:
d = {w: s.count(w) for w in p_words if w in s}
# -> {'cash': 1, 'limited time offer': 1}

rawDescription: Python: How to find n-gram patterns in the text?


code:
width = 10
height = 20
xs = range(1,201)
w = 2
h = 3

rawDescription: Slicing python lists

description: Slicing python lists


code: map(lambda *row: list(row), *mult_list)

rawDescription: How to get the list of lists

description: Get the list of lists


code:
import matplotlib.pyplot as plt
table=plt.table(cellText=[' ', ' ', ' ', ' ', ' '], #rows of data values
          rowLabels=['1','2','3','4','5'],
          cellLoc="left",
          rowLoc='left',
          bbox=[0,0,.2,1],#[left,bottom,width,height]
          edges="")

# iterate through cells of a table
table_props = table.properties()
table_cells = table_props['child_artists']
for cell in table_cells:
        cell._text.set_fontsize(20)
        cell._text.set_color('grey')
plt.show()

rawDescription: Matplotlib Table Row Label Font Color and Size


code:
def get_waveforms(data, spiketimes, lookback=100, lookahead=100) :
    offsets = np.arange(-lookback, lookahead)
    indices = spiketimes + offsets[:, None]
    ret = np.take(data, indices, mode='clip')
    ret[:, spiketimes < lookback] = 0
    ret[:, spiketimes + lookahead >= len(data)] = 0
    return ret

rawDescription: Most efficient way to extract parts of one array based on another


code:
def make_two_pairs(all_pairs):
  all_two_pairs = set()
  # uniqify the pairs list
  all_pairs = list(set(all_pairs))
  for i in range(len(all_pairs)-1):
    for j in range(i+1, len(all_pairs)):
      all_two_pairs.add(TwoPairs(all_pairs[i], all_pairs[j]))

  return all_two_pairs

rawDescription: Efficient way to make two pairs in python


rawDescription: Split Pandas Dataframe into separate pieces based on column values


code:
("Chapter 3 Convex Functions 97" "#97")
("3.1 Definitions 98" "#98")
("3.2 Basic Properties 103" "#103")

rawDescription: How to manipulate the following text

description: Manipulate the following text


code: value = find_interface(self, ResourceA if some_condition else ResourceB).method()

rawDescription: Pythonic shortcut (syntax sugar) for nested self.__parent__.__parent__


code: WeightedArc = namedtuple('WeightedArc', Arc._fields + ('weight',))

rawDescription: How do I create a tuple with an attribute using Python?

description: Create a tuple with an attribute using Python


code:
setup(
    # other arguments here...
    entry_points={
        'console_scripts': [
            'mrbob = my_package.some_module:main_func',
        ]
    }
)

rawDescription: How can one enable a shell command line argument for a python package installed for pip?


code: parser.add_argument('-i', '--inputdir', help="Specify the input directory")

rawDescription: How to make a short and long version of a required argument using Python Argparse?

description: Make a short and long version of a required argument using Python Argparse


code:
N = 2
data
H = np.zeros((N,N,Nt),dtype=data.dtype)
H
data.reshape(N,Nt,N).transpose(0,2,1)

rawDescription: Copy 2D array to a 3D one - Python / NumPy


code:
with open('spam.json') as f:
    things = [json.loads(line) for line in f]

rawDescription: Combining JSON values based on key

description: Combining JSON values based on key


code:
import ablib
ablib.Pin
ablib.Pin
ablib.Pin()
ablib.Pin()
p = ablib.Pin()
p.set_value(3)
p.kernel_id

rawDescription: How to mock path like `module.Class`? using Python's Mock module?

description: Mock path like `module.Class`? using Python's Mock module


code:
f = [os.path.splitext(x)[0] for x in os.listdir(r'C:\Users\username\Desktop\FOLDER')
     if os.path.isfile(os.path.join(r'C:\Users\username\Desktop\FOLDER', x))]

rawDescription: remove extension in list python

description: Remove extension in list python


code:
with open("test.txt",encoding="utf-8") as f:
    rep = re.compile(r"""
                        http[s]?://.*?\s
                        |www.*?\s
                        |(\n)
                        """, re.X)
    for line in f:
        m = rep.search(line)
        try:
            if m:
                line = line.replace(m.group(), "")
                line.encode("ascii")
        except UnicodeEncodeError:
            continue
        if line.strip():
            print(line.strip())

rawDescription: Remove urls, empty lines, and unicode characters in python


code:
from itertools import product
import time

d = { "N": ["A", "G", "T", "C"], "R": ["C", "A", "T", "G"] }
seq = "RNRN"

# using list comprehensions
lst_start = time.time()
[ "".join(i) for i in product(*[ d[j] for j in seq ]) ]
lst_end = time.time()

# using map
map_start = time.time()
[ list(map("".join, product(*map(d.get, seq)))) ]
map_end = time.time()

lst_delay = (lst_end - lst_start) * 1000
map_delay = (map_end - map_start) * 1000

print("List delay: {} ms".format(round(lst_delay, 2)))
print("Map delay: {} ms".format(round(map_delay, 2)))

rawDescription: how to extend ambiguous dna sequence

description: Extend ambiguous dna sequence


rawDescription: pandas: filter intraday df by non-consecutive list of dates

description: Pandas: filter intraday df by non-consecutive list of dates


code:
class user_class(object):
    @staticmethod # staticmethod so that it can be called on the class
    def __call__(x, y, z):
        return anything_with(x, y, z)

rawDescription: Python: Passing function with arguments to a function


code:
import binascii

data = binascii.unhexlify(hexstr)
with open('outputfile.bin', 'wb') as f:
    f.write(data)

rawDescription: ascii txt file to binary bin file

description: Ascii txt file to binary bin file


code: tester(*returner())

rawDescription: accepting return values for arguments to a function

description: Accepting return values for arguments to a function


code:
# If you just want to fix the ownership of a file without opening it
fix_ownership("myfile.txt")

# if you want to create a file with the correct rights
myfile = get_file(path)

rawDescription: Creating a file with python using sudo makes its owner root


code:
import os
def is_ssh():
    return "SSH_CLIENT" in os.environ or "SSH_TTY" in os.environ

rawDescription: Calling pythons webbrowser without stderr and in headless mode


code:
image_path = os.path.join(settings.MEDIA_ROOT, instance.image.path)
source_file = open(image_path)
image_generator = Thumbnail(source=source_file)

rawDescription: Saving base64 string with Django

description: Saving base64 string with Django


rawDescription: How to generate continuous record from incomplete data in Pandas Dataframe

description: Generate continuous record from incomplete data in Pandas Dataframe


code:
hashcontents = bencode.bencode(metadata['info'])
import hashlib
digest = hashlib.sha1(hashcontents).digest()
import base64
b32hash = base64.b32encode(digest)
b32hash

rawDescription: Given a .torrent file how do I generate a magnet link in python?


code:
pattern = '\s*\([0-9]+\)(?=\.mp3$)'
processed = re.sub(pattern, '', string)

rawDescription: Python regex replace string

description: Python regex replace string


code: forest = cv2.RTree(...)

rawDescription: Random Trees in OpenCV from python

description: Random Trees in OpenCV from python


code:
array([ True,  True,  True,  True,  True,
      False, False, False, False, False], dtype=bool)
array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5])

rawDescription: How to get attribute list from fitted model in Scikit-learn?

description: Get attribute list from fitted model in Scikit-learn


code:
import heapq
files = open('a.txt'), open('b.txt')
with open('merged.txt', 'w') as out:
    int_streams = (map(int, f) for f in files)
    int_stream = heapq.merge(*int_streams)
    line_stream = map('{}\n'.format, int_stream)
    out.writelines(line_stream)

rawDescription: Implementing an external merge sort

description: Implementing an external merge sort


code:
from ConfigParser import RawConfigParser
import datetime
import ast

i = 6
t_delta = datetime.timedelta(0, 9, 520000)

config = RawConfigParser()
config.add_section('Section')
config.set('Section', 'option_for_eval', (i, t_delta.total_seconds()))
config.set('Section', 'option_for_cast', '%s,%f' % (i, t_delta.total_seconds()))
config.write(open('/tmp/config.ini', 'w'))

config = RawConfigParser()
config.read('/tmp/config.ini')
option_for_eval = config.get('Section', 'option_for_eval')
option_for_eval
i, t_delta = ast.literal_eval(option_for_eval)
i, t_delta

option_for_cast = config.get('Section', 'option_for_cast')
stat = option_for_cast.split(',')
i = int(stat[0])
t_delta = datetime.timedelta(seconds=float(stat[1]))
i, t_delta

rawDescription: Correct way of getting time delta value from config file


code: yield line.strip('\n')

rawDescription: Remove new line character from lines in Python


rawDescription: Parsing a semi colon delimited file in python to create a CSV


code:
myrect = pygame.Rect(0, 0, 10, 10)
myrect.move_ip(100, 50)

rawDescription: How to Make the Ball Bounce only if it Hits the Paddle in Python, Pygame (Breakout Recreation)


rawDescription: Python bind an event from a different file


code:
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.1')

rawDescription: Can I compare a template variable to an integer in Django/App Engine templates?

description: Compare a template variable to an integer in Django/App Engine templates


code:
import pandas as pd
df = pd.DataFrame({'ID': ['a1', 'a1', 'a2', 'a2', 'a3'],
                   'Type': ['y', 'y', 'y', 'n', 'n']})
df['Subindex'] = df.groupby('ID').cumcount()+1
print(df)

rawDescription: Pandas multiIndex: add new indexes for each existing index


code:
import pickle

with open("top_scores.pickle", "rb") as scores:
    top_scores = pickle.load(scores)

rawDescription: Saving data in pickle

description: Saving data in pickle


code:
import sys, pygame
from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((1000,600))

screen.fill((255,255,255))

brush1 = pygame.image.load("redbrush.png")
brush1 = pygame.transform.scale(brush1,(45,45))
pos1 = (0, 32)

brush2 = pygame.image.load("bluebrush.png")
brush2 = pygame.transform.scale(brush2,(45,45))
brush2 = pygame.transform.scale(brush2,(45,45))
pos2 = (0, 64)

brush = brush1

pygame.display.update()

clock = pygame.time.Clock()

z = 0

while 1:
    screen.blit(brush1, pos1)
    screen.blit(brush2, pos2)
    pygame.display.update()
    clock.tick(60)
    x,y = pygame.mouse.get_pos()

    for event in pygame.event.get():
        if event.type ==pygame.QUIT:
            pygame.quit()
            sys.exit()
        elif event.type ==MOUSEBUTTONDOWN:
            z=1
        elif event.type ==MOUSEBUTTONUP:
            z=0
        if z==1:
            if brush1.get_rect(center=pos1).collidepoint(pygame.mouse.get_pos()):
                brush = brush1
            if brush2.get_rect(center=pos2).collidepoint(pygame.mouse.get_pos()):
                brush = brush2
            screen.blit(brush, (x -23.5,y-23.5))
            pygame.display.update()

rawDescription: paint application - python

description: Paint application - python


code:
t1 = [a/2+b/2+c/2+d/2]
tl=np.reshape(map(lambda tc: '$'+latex(tc)+'$',np.ravel(t1)),np.shape(t1))
df = DataFrame(tl, index=['Situation 1'], columns=['Answer 1'])
df

rawDescription: How to Render Math Table Properly in IPython Notebook


code:
df = df.sort(["ID", "Year", "Term"])
df["Previous_Rating"] = df.groupby("ID")["Rating"].shift()
df

rawDescription: Pandas Time-Series: Find previous value for each ID based on year and semester


code:
from django.db import models

class Blog(models.Model):
    title = models.CharField(max_length=60)
    body = models.TextField()
    created = models.DateTimeField("Date Created")
    updated = models.DateTimeField("Date Updated")

    def __unicode__(self):
        return self.title

class Comment(models.Model):
    body = models.TextField()
    author = models.CharField(max_length=60)
    created = models.DateTimeField("Date Created")
    updated = models.DateTimeField("Date Updated")
    post = models.ForeignKey(Blog)

    def __unicode__(self):
        return self.body

rawDescription: How to add  Search_fields in Django

description: Add  Search_fields in Django


code:
# each instance of the process should have a different filename here
process_lockfile = '/path/to/hostname.pid.lock'
# all processes should have the same filename here
global_lockfile = '/path/to/lockfile'
# create the file if necessary (only once, at the beginning of each process)
with open(process_lockfile, 'w') as f:
    f.write('\n') # or maybe write the hostname and pid

# now, each time you have to lock the file:
lock_acquired = False
while not lock_acquired:
    try:
        link(process_lockfile, global_lockfile)
    except:
        lock_acquired = (stat(process_lockfile).st_nlinks == 2)
    else:
        lock_acquired = True
# do your writing
unlink(global_lockfile)
lock_acquired = False

rawDescription: Is this method of file locking acceptable?


code:
from sympy.parsing.sympy_parser import (parse_expr,
standard_transformations, implicit_multiplication_application)
parse_expr("10sin**2 x**2 + 3xyz + tan theta",
           transformations=(standard_transformations +
                            (implicit_multiplication_application,)))

rawDescription: How to parse and simplify a string like '3cm/µs² + 4e-4 sqmiles/km/h**2' treating physical units correctly?

description: Parse and simplify a string like '3cm/µs² + 4e-4 sqmiles/km/h**2' treating physical units correctly


rawDescription: Match all names with exactly 5 digits at the end


code: rules = dict(rule.split('=', 1) for rule in recurrence.split(';'))

rawDescription: Add a 2 value tuple to dict as key:value


code:
conditions = (lambda x: 10 < x.cost < 20, lambda x: 0 < x.risk < 10)
filter(lambda x: all(cond(x) for cond in conditions), result)

rawDescription: Is there an elegant alternative to filtering these results without using lots of if statements?


code:
from multiprocessing import Pool

def joinRow(row):
    return ' '.join(str(cell) for cell in row)

def inputsToFile(inputs, filepath):
    # in python3 you can do:
    # with Pool() as p:
    #     lines = p.map(joinRow, inputs, chunksize=1000)
    # instead of code from here...
    p = Pool()
    try:
        lines = p.map(joinRow, inputs, chunksize=1000)
    finally:
        p.close()
    # ...to here. But this works for both.

    with open(filepath,'w') as f:
        f.write('\n'.join(lines)) # joining already created strings goes fast

rawDescription: How to write the ndarray to text file in python?

description: Write the ndarray to text file in python


code:
import os
os.get_terminal_size()
os.get_terminal_size().columns
os.get_terminal_size().columns  # after I changed my console's width

rawDescription: Is it possible to align a print statement to the center in Python?


rawDescription: split a string at a certain index

description: Split a string at a certain index


code:
g = Graph.Ring(4)
g.vs["name"] = ["A", "B", "C", "D"]
g.degree("C")
g.delete_vertices(["B"])
g.degree("C")

rawDescription: python, igraph coping with vertex renumbering

description: Python, igraph coping with vertex renumbering


code:
def process_blog(blogid):
    return get_blog(blogid)

rawDescription: What does return alone do in python?

description: What does return alone do in python


code:
A
n
x
S = sum([A[i]*x**n[i] for i in range(len(n))])
S
np.sum(A * x.reshape(-1, 1)**n, axis=1)

rawDescription: How can I efficiently use numpy to carry out iterated summation

description: Efficiently use numpy to carry out iterated summation


code: return len(p) != len(set(p))

rawDescription: Python Lists: How can I search for another element or duplicate item in a list


rawDescription: displaying subscript/superscripts in python tkinter listbox with unicode

description: Displaying subscript/superscripts in python tkinter listbox with unicode


code:
try:
    unicode
    _unicode = True
except NameError:
    _unicode = False

class CursesHandler(logging.Handler):
    def __init__(self, screen):
        logging.Handler.__init__(self)
        self.screen = screen
    def emit(self, record):
        try:
            msg = self.format(record)
            screen = self.screen
            fs = "\n%s"
            if not _unicode: #if no unicode support...
                screen.addstr(fs % msg)
                screen.refresh()
            else:
                try:
                    if (isinstance(msg, unicode) ):
                        ufs = u'\n%s'
                        try:
                            screen.addstr(ufs % msg)
                            screen.refresh()
                        except UnicodeEncodeError:
                            screen.addstr((ufs % msg).encode(code))
                            screen.refresh()
                    else:
                        screen.addstr(fs % msg)
                        screen.refresh()
                except UnicodeError:
                    screen.addstr(fs % msg.encode("UTF-8"))
                    screen.refresh()
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)

rawDescription: How to manage logging in curses

description: Manage logging in curses


code:
pattern = '{0}: [{1:1.3f}, {2:1.3f})'
count = 1 # a counter to keep track of the index

pre_p = distribution[0]
p = distribution[1]

# Here we will print it out at the end in the format you said in the question
for entry in my_list:
    print(pattern.format(entry[0], pre_p, p))
    pre_p += distribution[count]
    p += distribution[count+1]
    count = count + 1

rawDescription: what is a good way of setting up ranges on a number line?

description: What is a good way of setting up ranges on a number line


rawDescription: Converting a String to List in Python

description: Converting a String to List in Python


code:
class SmartArgWrapper(object):
    def __init__(self, *args):
        self.args = args

class Resize(SmartArgWrapper):
    def __call__(self, target):
        do_resize(target, *self.args)
# etc.

class ImageProcessor(object):
    def preprocess(self, *args):
        for arg in args:
            arg(self)

rawDescription: Handling arguments in order for preprocessing in Python, when order matters


code: from pandas.util.testing import makeCustomDataframe

rawDescription: Creating random multi-index dataframes in Pandas


rawDescription: Python - Split String Containing '\x'

description: Python - Split String Containing '\x'


rawDescription: How multiarray.correlate2(a, v, mode) is actually implemented?


code:
a = numpy.array([1,2,3])
b = numpy.array([4,5])

with open(filename,"w") as f:
    f.write("\n".join(" ".join(map(str, x)) for x in (a,b)))

# gives:
# 1 2 3
# 4 5

rawDescription: Saving numpy array to txt file row wise

description: Saving numpy array to txt file row wise


code:
# Arrays use the type name "array" and support a single attribute:
#
# items: the schema of the array's items.
# For example, an array of strings is declared with:

{"type": "array", "items": "int"}

rawDescription: repeating fields in avro (python)

description: Repeating fields in avro (python)


code:
from operator import itemgetter

generator = map(itemgetter('value'), test_data)

rawDescription: How do I extract all the values of a specific key from a list of dictionaries?

description: Extract all the values of a specific key from a list of dictionaries


rawDescription: Adding Vector Class Definition

description: Adding Vector Class Definition


code:
class Matrix(dict):
    def __getitem__(self, index):
        return super(Matrix, self).__getitem__(tuple(sorted(index)))
    def __setitem__(self, index, value):
        return super(Matrix, self).__setitem__(tuple(sorted(index)), value)

rawDescription: Symmetrically adressable matrix

description: Symmetrically adressable matrix


code:
array([[    nan,     nan,     nan,     nan,     nan,     nan,     nan,     nan],
       [    nan,  1.    ,  1.6667,  2.3333,  3.    ,     nan,     nan,     nan],
       [    nan,     nan,     nan,     nan,     nan,     nan,     nan,     nan],
       [    nan,     nan,     nan,     nan,     nan,     nan,     nan,     nan],
       [    nan,     nan,     nan,     nan,     nan,     nan,     nan,     nan],
       [    nan,  5.    ,  4.    ,  4.    ,  4.    , 4.     ,  4.    ,     nan],
       [    nan,  5.    ,  3.    ,     nan,     nan,     nan,     nan,     nan],
       [    nan,     nan,  2.    ,     nan,     nan,     nan,     nan,     nan],
       [    nan,     nan,  1.    ,     nan,     nan,     nan,     nan,     nan],
       [    nan,     nan,     nan,     nan,     nan,     nan,     nan,     nan]])

rawDescription: Interpolation of numpy array with a maximum interpolation distance


rawDescription: what is the best way to represent a char in its bits representation(Python)

description: What is the best way to represent a char in its bits representation(Python)


code:
highest_grade = max(grades.values())
print('highest_grade: {}'.format(highest_grade))
tie = list(grades.values()).count(highest_grade) > 1
print('student{} with highest grade:'.format('s' if tie else ''))
for student, grade in sorted(grades.items(), key=
                             lambda s: s[0].split()[::-1]): # Sort by lname
    if grade == highest_grade:
        print('  ', student)

rawDescription: Creating a dictionary from csv

description: Creating a dictionary from csv


code:
operand1 = random.choice(numbers)
operand2 = random.choice(numbers)
operator = random.choice(operators)

if operator == '+':
    answer = operand1 + operand2
elif operator == '-':
    answer = operand1 - operand2
else:
    answer = operand1 * operand2

user_input = input(str(operand1) + operator + str(operand2) + "? ")

if str(answer) == user_input:
    print('Correct!')
else:
    print('Wrong!')

rawDescription: Make python ask questions from strings

description: Make python ask questions from strings


code:
m = np.ma.masked_array(x, np.isnan(x))
m

rawDescription: Numpy masked operations

description: Numpy masked operations


rawDescription: Assign scientific notation to variable in Python


code:
main_counts =[[10,  20,  30]]

for idx in range(len(main_counts[0])):
    canvas.create_rectangle(idx*10, 200 -main_counts[0][idx], 10 +(idx*10), 200, fill = "medium sea green", outline = "firebrick")
    canvas.create_text(idx*10 + 8, 210, text = idx + 1, font = ("Comic sans MS",8), fill = "firebrick")

rawDescription: tkinter histogram prints downwards

description: Tkinter histogram prints downwards


rawDescription: Class based directional indicator

description: Class based directional indicator


code:
for x in range(5):
    score = input("score: ")
    score_file.write( score + "\n")

rawDescription: Looping test scores in file input/output


code:
a = A()
assert a.a.__self__ is a

rawDescription: Why the id of an object would change depending on the line in the python shell


code:
from operator import itemgetter
Z = [itemgetter(*'xy')(max(lst, key=itemgetter('y'))) for lst in A]

rawDescription: Select highest value from python list of dicts


rawDescription: Python Unicode string to Javascript

description: Python Unicode string to Javascript


code:
@app.errorhandler(404)
def not_found_error(error):
    return render_template('404.html', pic=pic), 404

rawDescription: How to generate dynamic urls in flask?

description: Generate dynamic urls in flask


code:
text_we_want = [(nodes_we_want[h].text.strip('\r\n'),
                 nodes_we_want[h+1].text.replace('\r\n              ',''))
                 for h in range(0,len(nodes_we_want)-1,2)]

rawDescription: How can I find my desired table inside a set of nested tables, using bs4/python, if there are no class or id attributes?

description: Find my desired table inside a set of nested tables, using bs4/python, if there are no class or id attributes


code: maskedarr = np.ma.array(test, mask=np.isnan(test))

rawDescription: numpy.ma.cov - pairwise correlations for with missing values?

description: Numpy.ma.cov - pairwise correlations for with missing values


code:
def makeints(x):
    return {k : int(v) for k, v in x.iteritems()}

def total(seq):
    result = Counter()
    for s in seq:
        result.update(s)
    return result

counts = {k : total(makeints(x) for x in v) for k, v in input.iteritems()}

rawDescription: Python Collections Counter for a List of Dictionaries


code:
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required

@login_required
def file(request, filename):
    file = get_object_or_404(File, user=request.user, filename=filename)
    return HttpResponse(file.data)

rawDescription: View function is not being called in Django


code:
a_t = np.vstack((a, np.zeros_like(a)))
b_t = np.vstack((b, np.ones_like(b)))

rawDescription: Interleaving two numpy index arrays, one item from each array


code:
import time

def play_game():
    """ play a game and return name, finalscore;
        return None to mean no more games, program finished.
        THIS function you'd better code yourself!-)
    """

def scoreToFile(name, finalScore):
    """ Add a name and score to the high-scores file. """
    currentTime = time.strftime("%c")
    fileOutput = finalScore, "-", name, currentTime
    line = ' '.join(str(x) for x in fileOutput)
    with open("highscores.txt", "a") as f:
        f.write(line + "\n")

def minus_score(line):
    """ just for sorting purposes, not called directly. """
    return -int(line.split()[0])

def sorted_by_score():
    """ return list of score lines sorted in descending order of score. """
    with open("highscores.txt", "r") as f:
        return sorted(f, key=minus_score)

def main():
    while True:
        game_result = play_game()
        if game_result is None: break
        scoreToFile(*game_result)
    for line in sorted_by_score:
        print(line.strip())

rawDescription: Write to file python - Linebreak issue (\n)


code:
url = 'http://view.example.com/candidates'
params = { 'cand_id': 4 }
requests.get(url, params=params)

rawDescription: How to embed "input(id)" into URL in GET request using Python?

description: Embed "input(id)" into URL in GET request using Python


code:
def tabulate(function, start=0):
    "Return function(0), function(1), ..."
    return imap(function, count(start))

rawDescription: Are there already python generators that do these basic things?


code:
import numpy as np
import pandas as pd
np.random.seed(2016)
N = 50
df = pd.DataFrame({'FRST_NM':np.random.choice(['Charles','Edgar Allan','Agatha'], N),
                   'LAST_NM':np.random.choice(['Dickens', 'Poe', 'Christie'], N),
                   'BRTH_DT':np.random.choice([1812, 1809, 1890], N),
                   'ADDRESS':np.random.choice(['Landport','Boston','Torquay'], N)})

result = pd.DataFrame(
    {'num_unique' : (df.drop_duplicates()
                       .groupby(['FRST_NM','LAST_NM'])['ADDRESS']
                       .count()),
     'count' : df.groupby(['FRST_NM', 'LAST_NM'])['ADDRESS'].count()})
result['percent'] = result['num_unique'] / result['count']
print(result)

rawDescription: Pandas count number of rows that match on certain fields but don't match on other fields


code:
def encode(s, ROT_number=13):
    """Encodes a string (s) using ROT (ROT_number) encoding."""
    ROT_number %= 26  # To avoid IndexErrors
    alpha = "abcdefghijklmnopqrstuvwxyz" * 2
    alpha += alpha.upper()
    def get_i():
        for i in range(26):
            yield i  # indexes of the lowercase letters
        for i in range(53, 78):
            yield i  # indexes of the uppercase letters
    ROT = {alpha[i]: alpha[i + ROT_number] for i in get_i()}
    return "".join(ROT.get(i, i) for i in s)

def decode(s, ROT_number=13):
    """Decodes a string (s) using ROT (ROT_number) encoding."""
    return encrypt(s, abs(ROT_number % 26 - 26))

rawDescription: Determine ROT encoding

description: Determine ROT encoding


code:
parser.parse("10-09-2003")
parser.parse("10-09-2003", dayfirst = True)
parser.parse("10-09-03", yearfirst = True)

rawDescription: Convert "unknown format" strings to datetime objects?


code: [[u'Changhua', u'47'], [u'Keelung', u'2'], etc]

rawDescription: Extracting data in table using BeautifulSoup


code:
import os

dataDir = "/some/folder/containing/data/"
mats = []
for file in os.listdir( dataDir ) :
    mats.append( scipy.io.loadmat( dataDir+file ) )

rawDescription: python loading several matlab files

description: Python loading several matlab files


code:
pivoted = df.pivot(index="cid", columns="num", values="price")
pivoted

rawDescription: Pivot each group in Pandas

description: Pivot each group in Pandas


code:
def onDoubleClick(self, event):
    ''' Executed, when a row is double-clicked. Opens
    read-only EntryPopup above the item's column, so it is possible
    to select text '''

    # close previous popups
    self.destroyPopups()

    # what row and column was clicked on
    rowid = self._tree.identify_row(event.y)
    column = self._tree.identify_column(event.x)

    # clicked row parent id
    parent = self._tree.parent(rowid)

    # do nothing if item is top-level
    if parent == '':
        return

    # get column position info
    x,y,width,height = self._tree.bbox(rowid, column)

    # y-axis offset
    pady = height // 2

    # place Entry popup properly
    url = self._tree.item(rowid, 'text')
    self.entryPopup = EntryPopup(self._tree, url)
    self.entryPopup.place( x=0, y=y+pady, anchor=W, relwidth=1)

rawDescription: How to make ttk.Treeview's rows editable?

description: Make ttk.Treeview's rows editable


code:
def foo(): pass

foo.__str__

rawDescription: Nature of Python Values, need a clarification


rawDescription: Python3.4 - math with index numbers

description: Python3.4 - math with index numbers


code:
import gevent
import time

for i in range(10):
        test_duration = 0.1 ** i
        start_time = time.time()
        gevent.sleep(test_duration)
        end_time = time.time()

        gevent_duration = end_time - start_time

        err = (gevent_duration - test_duration) / test_duration
        print("test_duration: %.10f secs, err: %%%.10f" % (test_duration, err))

rawDescription: Can we use gevent.sleep() for precise timings?


code:
SC:132
vrm:foobar

rawDescription: manipulating web forms in python

description: Manipulating web forms in python


code: {{ product.description | truncate(150) }}

rawDescription: python flask template return first 150 characters

description: Python flask template return first 150 characters


rawDescription: numpy 2d boolean array indexing with reduce along one axis

description: Numpy 2d boolean array indexing with reduce along one axis


code:
ipify.org
from json import load
from urllib2 import urlopen

my_ip = load(urlopen('https://api.ipify.org/?format=json'))['ip']

rawDescription: How can I get the public IP using python2.7?

description: Get the public IP using python2.7


rawDescription: Extract a larger slice than the numpy array's size


code:
def func(name):
    matches = df.apply(lambda row: (partial_ratio(row['name'], name) >= 85), axis=1)
    return [i for i, x in enumerate(matches) if x]

rawDescription: Pandas compare each row with all rows in data frame and save results in list for each row


code:
listLen = 10 # generate lists of length 10
low = 0 # the lower bound of the numbers you want to walk
high = random.randint(0,100) # the upper bound of the numbers you want to walk
for L in itertools.product(range(low, high+1), repeat=listLen):
  print(L)

rawDescription: Python: Algorithm to walk all the integers in a list and come up with all possible values?


code:
f1 = Foo()
f2 = Foo()
Foo.ls.append(1)
Foo.ls
f1.ls
f2.ls

rawDescription: some confusion with variables declared by python class

description: Some confusion with variables declared by python class


code:
def find_parent_keys(d, target_key, parent_key=None):
  for k, v in d.items():
    if k == target_key:
      yield parent_key
    if isinstance(v, dict):
      for res in find_parent_keys(v, target_key, k):
        yield res

rawDescription: Finding a parent key from a dict given an intermediate key using python


code: record_file.write("Record_Id    Record_Seq    Record_Qal\n")

rawDescription: How to save output from python like tsv

description: Save output from python like tsv


code:
wbOne.Close()
wbTwo.Close()

rawDescription: Working with multiple excel workbooks in python


rawDescription: Efficient way to multiply/add/devide each element of a list with each element of another list in Python


code:
from __future__ import print_function

import numpy as np
from scipy.integrate import ode

def func(t, u, mu):
    tvals.append(t)
    u1 = u[1]
    u2 = mu*(1 - u[0]*u[0])*u[1] - u[0]
    return np.array([u1, u2])

def jac(t, u, mu):
    j = np.empty((2, 2))
    j[0, 0] = 0.0
    j[0, 1] = 1.0
    j[1, 0] = -mu*2*u[0]*u[1] - 1
    j[1, 1] = mu*(1 - u[0]*u[0])
    return j

mu = 10000.0
u0 = [2, 0]
t0 = 0.0
tf = 10

for name, kwargs in [('vode', dict(method='adams')),
                     ('vode', dict(method='bdf')),
                     ('lsoda', {})]:
    for j in [None, jac]:
        solver = ode(func, jac=j)
        solver.set_integrator(name, atol=1e-8, rtol=1e-6, **kwargs)
        solver.set_f_params(mu)
        solver.set_jac_params(mu)
        solver.set_initial_value(u0, t0)

        tvals = []
        i = 0
        while solver.successful() and solver.t < tf:
            solver.integrate(tf, step=True)
            i += 1

        print("%-6s %-8s jac=%-5s " %
              (name, kwargs.get('method', ''), j.func_name if j else None),
              end='')

        tvals = np.unique(tvals)
        print("len(tvals) =", len(tvals))

rawDescription: Stiff ODE-solver

description: Stiff ODE-solver


code:
new_d = {}
for k,v in d.items():
    new_d.setdefault(v, []).append(k)

new_d

rawDescription: Fliping dictionary key value Python

description: Fliping dictionary key value Python


rawDescription: Python Subset dataframe with another dataframe


code:
for review in response.css("tr"):
    review_detail = review.css("td.complaint-detail::text").extract_first()
    print(review_detail)

rawDescription: How I can download the content of a dynamic page?


code:
z.reshape(3,3,2).ravel()
z.reshape(3,2,3).ravel()
z.reshape(3*2,3).ravel()
z.reshape(3*3,2).ravel()

rawDescription: numpy reshaping multdimensional array through arbitrary axis

description: Numpy reshaping multdimensional array through arbitrary axis


code:
# django.forms.models.py
if commit:
    # If we are committing, save the instance and the m2m data immediately.
    instance.save()
    save_m2m()

rawDescription: Django autocategorize in m2m field

description: Django autocategorize in m2m field


rawDescription: Python Pandas value-dependent column creation


code:
sorted_student_list = sorted(student_list, key=lambda x: int(x[-1]), reverse=True)

print(sorted_student_list)

rawDescription: How to sort a list of strings by highest number

description: Sort a list of strings by highest number


code:
a=np.random.randint(0,5,(3,3))
a
ua,uind=np.unique(a,return_inverse=True)
count=np.bincount(uind)
ua
count

rawDescription: Count number of elements in numpy ndarray


code:
from django.utils import simplejson

json_data_string = simplejson.dumps(your_data)

rawDescription: passing unicode strings from django to javascript

description: Passing unicode strings from django to javascript


code: Result = {key: result.data(paths[key]) for key in paths}

rawDescription: Python post-processing

description: Python post-processing


code:
def graph(formula, x_range):
    x = np.array(x_range)
    y = formula(x)  # <-----
    plt.plot(x, y, 'r--')
    plt.show()

graph(lambda x: (x-3) * (x-2), range(-3,3))  # <---

rawDescription: Graphs in python using matplotlib

description: Graphs in python using matplotlib


code:
driver = webdriver.Firefox() #First FF window
second_driver = webdriver.Firefox() #The new window you wanted to open

rawDescription: How to open a new window on a browser using Selenium WebDriver for python?

description: Open a new window on a browser using Selenium WebDriver for python


code:
import numpy as np
import pandas as pd
from pandas import Series
from pandas import DataFrame
import numpy.lib.stride_tricks as stride
np.random.seed(1)

n = 10
rng = pd.date_range('1/1/2000 00:00:00', periods=n, freq='5min')
df = DataFrame(np.random.rand(n, 1), columns=['a'], index=rng)

m = 4
rng = pd.date_range('1/1/2000 00:10:00', periods=m, freq='5min')
patch = DataFrame(np.arange(m), columns=['a'], index=rng)

def orig(df, patch):
    patch.reset_index(inplace=True, drop=True)

    df['corr'] = np.nan

    for i in range(df.shape[0]):
        window = df[i : i+patch.shape[0]]
        if window.shape[0] != patch.shape[0] :
            break
        else:
            window.reset_index(inplace=True, drop=True)
            corr = window.corrwith(patch)

            df['corr'][i] = corr.a

    return df

def using_numpy(df, patch):
    left = df['a'].values
    itemsize = left.itemsize
    left = stride.as_strided(left, shape=(n-m+1, m), strides = (itemsize, itemsize))

    right = patch['a'].values

    ldem = left - left.mean(axis=1)[:, None]
    rdem = right - right.mean()

    num = (ldem * rdem).sum(axis=1)
    dom = (m - 1) * np.sqrt(left.var(axis=1, ddof=1) * right.var(ddof=1))
    correl = num/dom

    df.ix[:len(correl), 'corr'] = correl
    return df

expected = orig(df.copy(), patch.copy())
result = using_numpy(df.copy(), patch.copy())

print(expected)
print(result)

rawDescription: pandas: Rolling correlation with fixed patch for pattern-matching

description: Pandas: Rolling correlation with fixed patch for pattern-matching


code:
string1 = 'aacc'
string2 = string1

rawDescription: Python: place a characters in string

description: Python: place a characters in string


code:
alist = ['A','B','C','D']
anotherList = ['D','A','C','B']
alist == anotherList
sorted(alist) == sorted(anotherList)

rawDescription: Efficiently test if two lists have the same elements and length


code:
with tempfile.NamedTemporary("w", dir=".", delete=False) as tmp:
    with open("test-original.txt", "r") as file, open("test-change.txt", "r") as change:
        for origline, changeline in zip(file, change):
            if link in origline:
                isbn = origline.strip("856 http://www.example.com/")
                tmp.write(origline.replace("com/", "com/" + isbn))
            else:
                tmp.write(changeline)
os.replace(tmp.name, "test-change.txt")

rawDescription: Append/replace string from one file with information from another


code: df = records.toDF(["user", "item", "value"])

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


code:
def pwr(d,r):
    out = []
    for n in range(2**d):
        p = [r*int(i) for i in list(bin(n)[2:])]
        while len(p) < d:
            p = [0] + p
        out.append(p)
    return out
    print(out)

print(pwr(2,1))

rawDescription: Converting an array containing the power set of a positive integer d to an array with standard elementary vectors in d-dimensional space


code:
with open("oplist.txt") as f: # with opens and closes the file automtically
    templist = [x.rstrip() for x in f] # strip new line char from every word

rawDescription: Removing data from a list from a raw_input variable


code:
import ruamel.yaml

yaml_str = """\
# trying to round-trip preserve empty scalar
attrs:
  first:
  second: value2
"""

data = ruamel.yaml.round_trip_load(yaml_str)
assert ruamel.yaml.round_trip_dump(data) == yaml_str

rawDescription: Can I dump blank instead of null in yaml/pyyaml?

description: Dump blank instead of null in yaml/pyyaml


code:
from BTrees.OOBTree import BTree
from BTrees.Length import Length

if not hasattr(dbroot, 'dictionary'):
    dbroot.dictionary = BTree()
    dbroot.dict_length = Length()

# add objects into the dictionary? Add to the length as well:
for i in range(count):
    dbroot.dictionary[keys[i]] = value[i]
dbroot.dict_length.change(count)

rawDescription: Counting len() of BTree saved in ZODB takes much time


rawDescription: Python matplotlib animation randomly jumping to initial position


code: a = int(1)

rawDescription: Overflowing ints in python

description: Overflowing ints in python


code: len(set(list1) & set(list2))

rawDescription: How To Compare Items In Two Lists Python 3.3


code: (ts > c).argmax() if (ts > c).any() else -1

rawDescription: First element of series to cross threshold in numpy, with handling of series that never cross


code:
L = list(data)
A = list(data)
data_frame = pd.DataFrame(L)
data_frame['A'] = pd.Series(A, index=data_frame.index)

rawDescription: Append a list of arrays as column to pandas Data Frame with same column indices


rawDescription: XLRD/Python: Reading Excel file into dict with for-loops


rawDescription: Merge dictionaries with key combinations


code:
features = data[:, :3]
targets = data[:, 3]   # The last column is identified as the target

rawDescription: Using prepared data for Sci-kit classification


code:
C.f1
C.f1 is f1

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


code:
import cv2
import multiprocessing as mp
import numpy as np
import psutil

img = cv2.imread('test.tiff', cv2.IMREAD_ANYDEPTH) # here I'm using a indexed 16-bit tiff as an example.
num_processes = 4
kernel_size = 11
tile_size = img.shape[0]/num_processes  # Assuming img.shape[0] is divisible by 4 in this case

output = mp.Queue()

def mp_filter(x, output):
    print(psutil.virtual_memory())  # monitor memory usage
    output.put(x, cv2.GaussianBlue(img[img.shape[0]/num_processes*x:img.shape[0]/num_processes*(x+1), :],
               (kernel_size, kernel_size), kernel_size/5))
    # note that you actually have to process a slightly larger block and leave out the border.

if __name__ == 'main':
    processes = [mp.Processes(target=mp_slice, args=(x, output)) for x in range(num_processes)]

    for p in processes:
        p.start()

    result = []
    for ii in range(num_processes):
        result.append(output.get(True))

    for p in processes:
        p.join()

rawDescription: How to use Python and OpenCV with multiprocessing?

description: Use Python and OpenCV with multiprocessing


code:
# handle_click will receive additional url arg along with the button
button.connect('clicked', handle_click, url)

rawDescription: Storing custom information in a widget, gobject-introspect


code:
m,n,r = a.shape
a.reshape(-1,r)[np.arange(m*n),indices.ravel()] = -1

rawDescription: Index multiple dimensions of a multi-dimensional array with another - NumPy/ Python


code:
def setup():
    rundeck_api.jobs_import(test_job_def, uuidOption='preserve')

rawDescription: Create Job using Rundeckrun?

description: Create Job using Rundeckrun


rawDescription: How to add a statement that checks for numbers or punctuation in a string

description: Add a statement that checks for numbers or punctuation in a string


code:
retval = subprocess.Popen(['rsync', '--list-only', source],
                           stdout=subprocess.PIPE,
                           env={'RSYNC_PASSWORD': password}).communicate()[0]
retval = retval.split(' ')[-1]

rawDescription: Remove file permissions, creation date from rsync listing command in python?


code: dict_of_lists_values[(list_a, list_b)] = lista.index(list_a) *  listb.index(list_b)

rawDescription: What approach can I take if I can't have similar names in a dict?


code:
block = ["damn", "shit"]
msg = "test masf to check shit or damn"
flag = False
for i in block:
  if i in msg:
     flag = True
     break

flag

rawDescription: Find similar word for word in the list

description: Find similar word for word in the list


code:
values = [('tens', 10), ('fives', 5), ('ones', 1), ('tenths', 0.1)]

def get_digits(num):
    num = int(num * 10)
    num = float(num) / 10

    output_dict = {}
    for place, value in values:
        output_dict[place] = num // value
        num = num % value
    return(output_dict)

get_digits(123.456)

rawDescription: python breaking numbers in to 10s 5s 1s and .1s

description: Python breaking numbers in to 10s 5s 1s and .1s


code:
df['count'] = df['col_1'].apply(count_fx)
df

rawDescription: pandas: count string criteria across down rows

description: Pandas: count string criteria across down rows


code: user = models.ForeignKey(User)

rawDescription: Generic object "ownership" in Django

description: Generic object "ownership" in Django


code:
s = " hello "
s.strip()
s.strip

rawDescription: Generic methods in python

description: Generic methods in python


code:
def foo():
    if not var:
        return

rawDescription: Execute function only if a variable is True


code:
tuple = 'one', 'two'

def function(old_tuple, string):
    global tuple
    if new_string not in old_tuple:
        tuple = (new_string,) + old_tuple

function(tuple, 'add this')

rawDescription: Python changing modifying via imported function


rawDescription: List as Function Arguments in Python

description: List as Function Arguments in Python


code: OrderedDict(sorted(d.items(), key=lambda item: item[1][0]['selling_price']))

rawDescription: In an OrderedDict how to sort by a particular attribute?


code: indices = [i for i, s in enumerate(p) if ('1','2') == (s[1],s[2])]

rawDescription: Return index position in array based on a partial string in Python


code:
@ops.RegisterGradient("MatrixDeterminant")
def _MatrixDeterminantGrad(op, grad):
  """Gradient for MatrixDeterminant. Use formula from 2.2.4 from
  An extended collection of matrix derivative results for forward and reverse
  mode algorithmic differentiation by Mike Giles
  -- http://eprints.maths.ox.ac.uk/1079/1/NA-08-01.pdf
"""
  A = op.inputs[0]
  C = op.outputs[0]
  Ainv = tf.matrix_inverse(A)
  return grad*C*tf.transpose(Ainv)

rawDescription: matrix determinant differentiation in tensorflow

description: Matrix determinant differentiation in tensorflow


code:
# for all the docstrings, let multi = Multi(2)
class Multi(object):
    def __init__(self, attribute):
        """When instantiated, set self.attribute to attribute"""
        self.attribute = attribute

    @property
    def attribute_times_ten(self):
        """accessed via multi.attribute_times_ten
        and will return 20. Use properties to signify
        a variable that requires some work done to it
        that needs to calculated each time it's called."""
        return attribute_times_ten

    @classmethod
    def times_ten(cls, num):
        """Not the best example, but a @classmethod will
        give the class as its first argument, NOT the
        instance. This is useful in lots of constructor
        settings, e.g. CreateClass.fromstring("attributes")"""
        return num * 5

    def generate_number(self, multiplier):
        """This is just a normal method. This is what I think
        you want, tbh, and you should probably call it in your
        __init__ method since you NEED this to run in your OTC
        for it to work as intended. Methods (like properties)
        are automagically passed the instance as the first
        argument, so we can CHANGE self.attribute with that."""
        self.attribute = self.attribute * multiplier

rawDescription: Property set correctly inside an object but not accessible outside


code: y = np.cumsum(arr)

rawDescription: plotting the sum of an array array[0:i] vs i

description: Plotting the sum of an array array[0:i] vs i


code:
files = {'file': ('advertise_A.png', open(asset_file, 'rb'), 'image/x-png'), 'creative_id': ('', '1727968', 'text/plain;charset=ISO-8859-1'), 'file_role': ('', 'PRIMARY', 'text/plain;charset=ISO-8859-1'), 'Filename': ('', 'advertise_A.png', 'text/plain;charset=ISO-8859-1')}
r = requests.post(url, files=files)

rawDescription: sending different 'Content-Type' for each single input param one file and other data params

description: Sending different 'Content-Type' for each single input param one file and other data params


code:
x_reshaped = np.array(x[3:], dtype=object).reshape((-1, 3))
df = pd.DataFrame(x_reshaped, columns=x[:3])
df['Sat Indx'] = df['Sat Indx'].astype(float)

rawDescription: Converting and reshaping a list into a DataFrame in Pandas


code:
z="string"
rot=3
z[rot:]+z[:rot]

rawDescription: How to "convert" a dequed object to string in Python?


rawDescription: Is accepting special characters for a range within a regex pattern possible?


code:
from itertools import chain
list(chain.from_iterable(sample))

rawDescription: List of list to string

description: List of list to string


rawDescription: Selecting specific rows from a python dataframe for an ols regression in PANDAS


code:
def Foo(arg1, arg2):
    return something_that_is_an_instance

rawDescription: Can a class in python behave like a specified class based on a passed parameter?


code:
set2 = [item for item in set1 if filtCheck(item, "Hi")]

# or simply

set2 = [item for item in set1 if "Hi" in item]

rawDescription: Passing a parameter through a python filter function


rawDescription: Django simple math captcha , how to pass custom string as argument?


code: converted_times = map(convert_pair, orig_times)

rawDescription: Converting time from (mm:ss.ddd) to (ss.ddd)


code:
if  cmd == curses.KEY_DOWN:
    mypad_pos += 1
    mypad.refresh(mypad_pos, 0, 5, 5, 10, 60)
elif cmd == curses.KEY_UP:
    mypad_pos -= 1
    mypad.refresh(mypad_pos, 0, 5, 5, 10, 60)

rawDescription: How to scroll text in Python/Curses subwindow?

description: Scroll text in Python/Curses subwindow


code:
class Foo(object):
    def __init__(self):
        self.some_attr = ''
        self.a_list = []
    @property
    def empty_check(self):
        return bool(self.a_list)
myFoo = Foo()
print(myFoo.empty_check)
myFoo.a_list.append(1)
print(myFoo.empty_check)

rawDescription: attribute that updates based on the value of another attribute in python 3

description: Attribute that updates based on the value of another attribute in python 3


code:
import io
import logging
import os
import select
import subprocess
import time
import threading

LOG_FILENAME = 'output.log'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)

class StreamLogger(io.IOBase):
    def __init__(self, level):
        self.level = level
        self.pipe = os.pipe()
        self.thread = threading.Thread(target=self._flusher)
        self.thread.start()

    def _flusher(self):
        self._run = True
        buf = b''
        while self._run:
            for fh in select.select([self.pipe[0]], [], [], 0)[0]:
                buf += os.read(fh, 1024)
                while b'\n' in buf:
                    data, buf = buf.split(b'\n', 1)
                    self.write(data.decode())
            time.sleep(1)
        self._run = None

    def write(self, data):
        return logging.log(self.level, data)

    def fileno(self):
        return self.pipe[1]

    def close(self):
        if self._run:
            self._run = False
            while self._run is not None:
                time.sleep(1)
            os.close(self.pipe[0])
            os.close(self.pipe[1])

rawDescription: Decorate \ delegate a File object to add functionality


code:
from sklearn.metrics import euclidean_distances
from scipy.spatial import distance_matrix

rawDescription: Vectorize over only one axis in a 2D array with numpy vectorize


rawDescription: Provide default values for python dictionary while keeping reference to original object


rawDescription: No handler found for library with logging configured


code:
...
labels = ['foo','bar','snafu','swag','s-fus','tarfu']
for r, bar, ll in zip(theta, bars, labels):
    bar.set_facecolor(plt.cm.jet(r / np.pi / 2))
    bar.set_alpha(0.8)
    bar.set_label(ll)

ax.legend()
...

rawDescription: Matplotlib polar bar-plot legend

description: Matplotlib polar bar-plot legend


code:
# No extra indentation.
if (this
    and that):
    do_something()

# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this
    and that):
    # Since both conditions are true, we can frobnicate.
    do_something()

# Add some extra indentation on the conditional continuation line.
if (this
        and that):
    do_something()

rawDescription: Style when indenting a wrapped, parenthesized if condition


code: global score

rawDescription: Making a simple card game in python 2.7

description: Making a simple card game in python 2.7


code:
env = Environment()
env.filters["RANDOM_INT"] = random_int

rawDescription: Python 3 - Replacing part of a string with imformation from the string


code:
def shorten_title2(x, y):
    if len(x) <= y:
        return x
    elif ' ' not in x[:y]:
        return x[:y]
    else:
        return x[:x.rindex(' ', 0, y + 1)]

rawDescription: Shorten title to a certain length

description: Shorten title to a certain length


code:
class MyVar(object):
    def __init__(self, initial=0):
        self._var1 = initial

    @property
    def var1(self):
        self._var1 += 1
        return self._var1

    def __str__(self):
        return str(self.var1)

var1 = MyVar()
print(var1)  # 1
print(var1)  # 2
print(var1.var1)  # 3

rawDescription: How to recalculate a variable value every time it is used?

description: Recalculate a variable value every time it is used


code:
def f(x):
    return x['ONE']+x['TWO']+x['Three']

rawDescription: How to pass on variable to function in different script file

description: Pass on variable to function in different script file


code:
foo = Foo()
foo.spam.bar
foo.ham.bar

rawDescription: Is there a way to pass arguments using the dot operator in python?


code:
np.dtype((bytes, 1)) # 2.7
np.dtype((bytes, 1)) # 3.2

rawDescription: ASCII string as dtype for numpy array of strings in Python 3


code:
import threading
import subprocess
import uuid
from flask import Flask
from flask import render_template, url_for, abort, jsonify, request
app = Flask(__name__)

background_scripts = {}

def run_script(id):
    subprocess.call(["/path/to/yourscript.py", "argument1", "argument2"])
    background_scripts[id] = True

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/generate')
def generate():
    id = str(uuid.uuid4())
    background_scripts[id] = False
    threading.Thread(target=lambda: run_script(id)).start()
    return render_template('processing.html', id=id)

@app.route('/is_done')
def is_done():
    id = request.args.get('id', None)
    if id not in background_scripts:
        abort(404)
    return jsonify(done=background_scripts[id])

rawDescription: Create a hyperlink (or button) that executes a python script and then redirects when script completes


code:
list(powerset_generator([1, 2, 3]))
list(powerset_generator([1, 2, 3],True))

rawDescription: Python inverse power set generator

description: Python inverse power set generator


code:
from sympy import *
from sympy.tensor.array import *
var("a,b,c,d,e,f")
X = Array([[a, b, c], [d, e, f]])
var("w1,w2,w3")
W = Array([w1, w2, w3])

rawDescription: python symbolic summation and differentiation of a vector of parametric size

description: Python symbolic summation and differentiation of a vector of parametric size


code:
(1, 42, None)
(1, None, None)

rawDescription: Pass keyword argument to another function where the keyword has a default value


code:
def decode_safely(s, charset='ascii'):
    """Return s decoded according to charset, but do so safely."""
    try:
        return s.decode(charset or 'ascii', 'replace')
    except LookupError: # bogus charset
        return s.decode('ascii', 'replace')

def decode_rfc2047_header(h):
    return ' '.join(decode_safely(s, charset)
                   for s, charset in email.header.decode_header(h))

rawDescription: Get python getaddresses() to decode encoded-word encoding


rawDescription: Printing the sublist in which the required number is found


code:
import numpy as np
from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt

# Generate some random points for the demo.
np.random.seed(4321)
pts = 0.1 + 0.8*np.random.rand(15, 2)

ch = ConvexHull(pts)

# hull_indices = ch.vertices   # This will work in the scipy 0.13
hull_indices = np.unique(ch.simplices.flat)
hull_pts = pts[hull_indices, :]

plt.plot(pts[:, 0], pts[:, 1], 'ko', markersize=10)
plt.plot(hull_pts[:, 0], hull_pts[:, 1], 'ro', alpha=.25, markersize=20)
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.show()

rawDescription: get the index of point which create ConvexHull

description: Get the index of point which create ConvexHull


code:
for sheet_name in EF.sheet_names:
    temp_df = EF.parse(sheet_name)
    #perform your calculations
    #export to SQL

rawDescription: Loop through Dataframes in Dict of Dataframes


code:
df = pd.read_csv("bondstack.csv")
df["b"] = df["open"].shift(-1).where(df["MA10"] > df["MA100"])

rawDescription: Pandas list comprehension in a dataframe


code:
def _filter_or_exclude(self, negate, *args, **kwargs):
    try:
        value = kwargs.pop('address__dst')
        matches = self.nearby(*map(float, value.split(',')))
        pks = [m.pk for m in matches]
        kwargs.update({ 'pk__in': pks })
    except:
        pass
    return super(ReportQuerySet, self)._filter_or_exclude(
            negate, *args, **kwargs)

rawDescription: Django admin filter list with custom model manager extra methods


code:
def business(request, name='unknown'):
    name = name.replace('-', ' ').capitalize()
    return render_to_response('business.html',
                             {'business': business.objects.get(name=name) })

rawDescription: Django URL Variables - Business Name in URL in stead of ID


rawDescription: Implementing Kruskal's Algorithm in Python on images


rawDescription: Replace contents of lxml StringElement with starting a namespace war?


code: '\none\ntwo\n\nthree\n'

rawDescription: Set the wrap width for python docs in a terminal


rawDescription: Pandas: Number of unique days in a timestamp Series


code: [{"k": k, "v": v} for k,v in d.items()]

rawDescription: Iterating over keys and values of a dictionary in mustache / pystache


code:
import sqlite3

con = sqlite3.connect('database')
cur = con.Cursor()

cur.execute('select table1.column, table2.column, table3.column from table1, table2, table3')
# result should look like ((25, 30, 20), (30,)), if I remember correctly
results = cur.fetchall()

output = '\n'.join(','.join(str(i) for i in line) for line in results)

rawDescription: don't get duplicated values when exporting sqlite3 file to csv using python?

description: Don't get duplicated values when exporting sqlite3 file to csv using python


code:
def islice_to_last(it):
    prev_value = next(it)
    for value in it:
        yield prev_value
        prev_value = value

rawDescription: Python modify generator

description: Python modify generator


code:
from multiprocessing import Manager
manager = Manager()

rawDescription: Python: Update Widgets from outside function using multipocessing Pool


code:
def numba3(vec_obj, vec_ps, cos_maxsep):
    nps = len(vec_ps)
    nobj = len(vec_obj)
    out = np.zeros(nobj, bool)
    numba3_helper(vec_obj, vec_ps, cos_maxsep, out, nps, nobj)
    return np.flatnonzero(out)

@jit(nopython=True)
def numba3_helper(vec_obj, vec_ps, cos_maxsep, out, nps, nobj):
    for i in range(nobj):
        for j in range(nps):
            cos = (vec_obj[i,0]*vec_ps[j,0] +
                   vec_obj[i,1]*vec_ps[j,1] +
                   vec_obj[i,2]*vec_ps[j,2])
            if cos > cos_maxsep:
                out[i] = True
                break
    return out

rawDescription: Numpy optimization with Numba

description: Numpy optimization with Numba


code:
t2 = tuple(map(lambda x: isinstance(x, float) and round(x, 2) or x, t))
t2

rawDescription: rounding-up numbers within a tuple

description: Rounding-up numbers within a tuple


code:
x,y,z = popt
h_fit = h(x,y,z,t_meas)

rawDescription: Reducing difference between two graphs by optimizing more than one variable in MATLAB/Python?


code: {{ object.current_auction_price }}

rawDescription: Creating an auction model a la eBay max bid style


code:
with open('output.txt', 'w') as f:
  subprocess.Popen([spawned.py, parameter1, parameter2], stdout = f)

rawDescription: Python: Spawning another program

description: Python: Spawning another program


code:
def add_wedding_context(request):
    id_ = request.GET.get('wedding_id', None)
    wedding = None
    if id_ is not None:
        try:
            wedding = Wedding.objects.get(id=id_)
        except Wedding.DoesNotExist:
            pass
    return {'wedding':wedding}

rawDescription: Context Processor for Django Site

description: Context Processor for Django Site


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

from math import *
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

def Plongeon():
    h = float(input("height = "))
    g = 9.81

    #calculate air time, Tc
    Tc = sqrt(2 * h / g)

    # First set up the figure, the axis, and the plot element we want to animate
    fig = plt.figure()
    ax = plt.axes(xlim=(0, 2), ylim=(-2, h+1))  #ymax : initial height+1
    line, = ax.plot([], [], ' o', lw=2)

    step = 0.01  # animation step
    xs = [1]  # the vertical position is fixed on x-axis
    ys = [h]

    # animation function.  This is called sequentially
    def animate(y):
        ys[-1] = y
        line.set_data(xs, ys)
        return line,

    def get_y():
        t = 0
        while t <= Tc:
            y = -0.5 * g * t**2 + h  # the equation of diver's displacement on y axis
            yield y
            t += step

    # call the animator.  blit=True means only re-draw the parts that have changed.
    anim = animation.FuncAnimation(fig, animate, frames=get_y, interval=100)

    plt.show()
Plongeon()

rawDescription: How to plot real-time graph, with both axis dependent on time?

description: Plot real-time graph, with both axis dependent on time


code:
def compareValues():
        number = randrange(10)
        name = threading.current_thread().name
        if number >= 5:
             yield "%s: Greater than or equal to 5: %d  "%(name, number)
        else:
             yield "%s: Less than 5: %d  "%(name, number)

rawDescription: Confusion regarding the output of threads in python


code: int(random.random() < 0.8)

rawDescription: Generate random numbers according to a specific distribution


rawDescription: How to make a CSV file from a number of lists?

description: Make a CSV file from a number of lists


code:
import re
text = '1. first slice 2. second slice 3. slice number 3 4. the next one 5 that will not work but belong to no four 5. and this should be 5 and so one...'
re.findall(r"\d\. (?:\D+|\d(?!\.))*", text)

rawDescription: Specific Python pattern for the string that can help to slice


code: print(ddda)  ###This is giving my value let's/cool

rawDescription: how do i get this python function to return a value?

description: Get this python function to return a value


code:
import itertools
output_list = list(set(itertools.chain(first_list, second_list)))

rawDescription: Fastest Way To Remove Duplicates In Lists Python


rawDescription: How to use groupby objects to get sums of other columns?

description: Use groupby objects to get sums of other columns


code:
q = (session.query(Store, func.ST_AsGeoJSON(Store.location).label('geo_location'))
        .outerjoin(Store.images) # load images
        .options(contains_eager(Store.images)) # tell SA that we hav loaded them so that it will not perform another query
        .filter(Store.is_flagship == True)
    ).all()

# patch values in the instances of Store:
for store, geo_location in q:
    store.geo_location = geo_location

rawDescription: KeyedTuple with a list of related data

description: KeyedTuple with a list of related data


code: resultlist = [elem + ['end'] for elem in resultlist]

rawDescription: Keeping rows in Pandas where the same ID appears more than n times and convert to list per ID


code:
class Foo(object):
    attr1=1
    attr2=2
    def __init__(self,attr1,attr2):
        self.attr1 = attr1
        self.attr2 = attr2

rawDescription: Python: Pokemon battle (classes, functions)


code:
with open('document') as doc:
    with open('sed_script', 'w') as sed_script:
        sed_script.writelines(['s/\<{}\>//g\n'.format(word) for word in stopwords])
    with open('sed_document', 'w') as sed_doc:
        subprocess.call(['sed', '-f', 'sed_script'], stdout=sed_doc, stdin=doc)

rawDescription: Removing stopwords with Python - quickly and efficiently


code:
indexer = s.index.to_series().order().diff().fillna(0).astype('timedelta64[s]')
indexer

rawDescription: Pandas group by time windows

description: Pandas group by time windows


rawDescription: having trouble understanding this code

description: Having trouble understanding this code


code:
import sys
import os
from subprocess import Popen

class MonitoredStream():
    def __init__(self, stream, callback):
        self.stream = stream
        self.callback = callback
        self._read, self._write = os.pipe()

    def fileno(self):
        return self._write

    def process(self):
        os.close(self._write)
        with os.fdopen(self._read) as f:
            for line in f:
                self.callback(line)
                self.stream.write(line)

def f(s):
    print("Write")

stream = MonitoredStream(sys.stdout, f)
p = Popen(["ls"], stdout=stream)
p.communicate()
print(stream.process())

rawDescription: Monitored stream class

description: Monitored stream class


code: vocab_counter = {vocabLine.strip().lower(): 0 for vocabLine in vocabOutFile}

rawDescription: Trying to find word count in a text file using a different text file as "dictionary"


code: pd.rolling_mean(df.T, 3).shift(-2)

rawDescription: Mean in group of columns

description: Mean in group of columns


code:
class DictWrapper(Wrapper):
    __wraps__ = dict

wrapped_dict = DictWrapper(dict(a=1, b=2, c=3))

# make sure it worked....
assert "b" in wrapped_dict                        # __contains__
assert wrapped_dict == dict(a=1, b=2, c=3)        # __eq__
assert "'a': 1" in str(wrapped_dict)              # __str__
assert wrapped_dict.__doc__.startswith("dict()")  # __doc__

rawDescription: How can I intercept calls to python's "magic" methods in new style classes?

description: Intercept calls to python's "magic" methods in new style classes


rawDescription: Pack function arguments into a dictionary - opposite to **kwargs


code: if '-v' in sys.argv: ...

rawDescription: What is the canonical way of handling sys arguments in Python?


code: new_columns = [ first+ '_' + second for first in first_level_names  for second in second_level_names ]

rawDescription: Transforming DataFrame (pivot)

description: Transforming DataFrame (pivot)


rawDescription: time.time() overflow/rollover

description: Time.time() overflow/rollover


code:
def draw_random_card():
    """
    whatever function returns a new card. Might be in a Deck object, depends on
    your design
    """
    # some code here

class Player:
    def __init__(self):
        self.hands = []

    def deal(self):
        """add a random hand"""
        self.hands.append(Hand([draw_random_card(), draw_random_card()]))

    def split(self, hand):
        """split the given hand"""
        self.hands.remove(hand)
        self.hands += hand.split()

class Hand:
    def __init__(self, cards):
        self.cards = cards

    def hit(self):
        """add a random card"""
        self.cards.append(draw_random_card())

    def split(self):
        """split and return a pair of Hand objects"""
        return [Hand(self.cards[0], draw_random_card()),
                Hand(self.cards[1], draw_random_card())]

rawDescription: dynamic class instantiation confusion in python

description: Dynamic class instantiation confusion in python


rawDescription: Comparing Python dicts with floating point values included


code:
import pandas as pd

df = pd.DataFrame({'faculty A': [2,4], 'faculty B':[7,3]},
                  index=['male students', 'female students'])
df.columns = [re.sub(r'faculty ', '', col) for col in df.columns]
df.index = ['m', 'f']
series = df.stack()
df = pd.DataFrame(
    (key for key, val in series.iteritems() for i in range(val)),
    columns=['gender','faculty'])

rawDescription: Pandas: creating dataframe rows from other dataframe information


code:
def sendnext(packets):
    for i, (number, data, sent) in enumerate(packets):
        if not sent:
            sendsegment(number, data)
            packets[i] = (number, data, True)
            break

rawDescription: Changing a single element of a list while iterating in python


code:
import time
import datetime

rawDescription: Is there a IPython notebook api?

description: Is there a IPython notebook api


code:
from itertools import tee, izip
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

tuple(pairwise(f))

rawDescription: Expand a Tuple Into Semi-Repeating Pairs


rawDescription: Python 2.7.1, codecs, and MySQLdb; why is setting file encoding not needed


rawDescription: Largest weakly connected component in networkX


code: max(arg1, arg2, arg3, key=lambda x: -x)

rawDescription: Python inspect module: keyword only args


code:
from collections import defaultdict

my_dict = defaultdict()

my_dict[1]=[1,2,3]
my_dict[2]=[4,5,6]

my_dict

2 in my_dict

my_dict.get(2)

my_dict.get(7, None)
bool(my_dict.get(7, None))

rawDescription: python defaultdict get method return value

description: Python defaultdict get method return value


code: french, english, prob = result[0]

rawDescription: Python: separate results of re.findall

description: Python: separate results of re.findall


code:
import os,sys
try:
    assert 'DISPLAY' in os.environ
except AssertionError:
    sys.exit(1)

rawDescription: How to check graphical mode in Python PyGame?

description: Check graphical mode in Python PyGame


code:
formatters  = ['{: >9.2f}'.format, '{: >7.1f}'.format,
               '{: >11.2f}'.format,'{: >10.3f}'.format,
               lambda x: ' '*27 if np.isnan(x) else '{: >27.1f}'.format(x)]

lines = df.to_string(index=False, header=False, formatters=formatters)

with open('out.dat', 'w') as outfile:
    outfile.write(lines)

rawDescription: Read and save data file with variable number of columns in python


rawDescription: How would I scale a 2-dimensional array in python?


code:
for i in range(3):
    y[i] = Normal(mu[i], sigma[i], observed=somedata[i])

rawDescription: pymc3 generate stochastic variables with array of parameters

description: Pymc3 generate stochastic variables with array of parameters


rawDescription: Copy numpy array from one (2-D) to another (3-D)


code:
import pandas as pd
import yaml

with open('legislators-historical.yaml', 'r') as f:
    df = pd.io.json.json_normalize(yaml.load(f))

print(df.head())

rawDescription: Retrieving data from a yaml file based on a Python list


code:
import re

# regular expression for matching a (node1,node2;cost)
EDGE = re.compile(r'\((\d+),(\d+);(\d+)\)')

def parse(s):
    # Separate size from the list of edges
    size, edges = s.split(':')

    # Build a dictionary
    edges = dict(
        # ...where key is (node1,node2) and value is (cost)
        # (all converted to integers)
        ((int(node1),int(node2)),int(cost))

        # ...by iterating the edges using the regular expression
        for node1,node2,cost in EDGE.findall(edges))

    return int(size),edges

rawDescription: Is there a nicer way to convert a string into a data set in python?


code:
import h_yacc
import h_lexer
import collections
import struct

class Named_struct(object):
    yacc = h_yacc.yacc.yacc(module = h_yacc)
    lexer = h_lexer.lex.lex(module = h_lexer)

    def __init__(self, desc_str, name='_X_', struc_typ = '='):
        l = self.__class__.yacc.parse(desc_str, self.__class__.lexer)
        if l is None:
            col, line = h_lexer.getpos(self.__class__.lexer)
            raise Exception(
                "Syntax error in description string near line %d col %d" %
                (line, col - 1))
        fmts = []
        self.t = self.__make_named(l, fmts, name)
        self.fmt = struc_typ + ''.join(fmts)
        self.struct = struct.Struct(self.fmt)
        self.name = name
        self.l = l

    def __make_named(self, l, fmts, name):
        names = []
        values = []
        for elt in l:
            if elt[0] is None:
                fmts.append(elt[1])
            else:
                val = None
                names.append(elt[0])
                if isinstance(elt[1], str):
                    fmts.append(elt[1])
                elif isinstance(elt[1], tuple):
                    val = self.__make_array(elt[1], fmts, elt[0])
                else:
                    val = self.__make_named(elt[1], fmts, elt[0])
                values.append(val)
        t = collections.namedtuple(name, names)
        return t, t(*values)

    def __make_array(self, l, fmts, name):
        values = []
        for elt in l:
            if isinstance(elt, str):
                fmts.append(elt)
                values.append(None)
            else:
                val = self.__make_named(elt, fmts, "x")
                values.append(val)
        t = self.__class__.__lister
        return t, t(*values)

    staticmethod
    def __lister(*l):
        return list(l)

    def __gen(self, t, it):
        l = []
        for g in t[1]:
            if g is None:
                l.append(next(it))
            else:
                l.append(self.__gen(g, it))
        return t[0](*l)

    def unpack(self, buffer):
        l = struct.unpack(self.fmt, buffer)
        t = self.__gen(self.t, iter(l))
        return t

rawDescription: Unpacking deeply nested struct with given C header into dictionary?


code:
import io

with io.open(path, newline='\r\n') as infh:
    for line in infh:
        row = line.strip().split('\t')

rawDescription: Python: Read a file separated strictly on 0x0a, not '\n' string


code:
with open(filename, 'r') as inputfile:
    key_def_pairs = dict(pairwise(inputfile))

rawDescription: Linking two items from two seperate lists together. python


code:
import dis
dis.dis(foo)

rawDescription: why using multiple threading to get the sum is correct?

description: Why using multiple threading to get the sum is correct


rawDescription: Split a string into a list, leaving accented chars and emoticons but removing punctuation


code: tuple(map(int, tup2)) == tup1

rawDescription: Python compare tuples with different data types but same values


code:
from setuptools import setup

setup(
    name = 'umbrella',
    packages = [
        'umbrella.common_utils'
        ],
    package_dir = {
        'umbrella.common_utils': './common_utils'
        }
    )

rawDescription: Is there a way to add a namespace prefix setuptools package distributions?


code:
class Person(object):
    def __init__(self, firstName, lastName, age):
        self.firstName = firstName
        self.lastName = lastName
        self.age = None

person = Person('Peter', 'Smith', 21)

rawDescription: Automatically setting getter, setter and deleter in python


code:
class Foo:
    pass

f = Foo()
type(f)
f.__class__    # Note that the __class__ attribute still works

rawDescription: Idiomatic Python for generating a new object from within a class


code:
os.path.basename(path) # To get the name of the file with extension.
os.path.basename(path).split('.')[0] # To get just the name.
os.path.dirname(path) # To get the directory leading to the file.

rawDescription: What is the most stable and Pythonic cross-platform way to separate a string of path,filename,ext into three separate variables?


code: not any(search in s for s in myList)

rawDescription: Check if none of list elements contain searched substring


code: from urlparse import urlparse

rawDescription: Python: Returning only hosts/a href with my HTML parser


code:
from itertools import groupby

def min_max_per_hour(iterable):
    for dayhour, grouped in groupby(iterable, lambda dt: (dt.date(), dt.hour)):
        minimum = next(grouped)  # first object is the minimum for this hour
        maximum = minimum  # starting value
        for dt in grouped:
            maximum = dt   # last assignment is the maximum within this hour
        yield (minimum, maximum)

rawDescription: Minimum and maximum timestamps per hour bucket


code:
a = [8, 8, 1, 1, 5, 8, 9]

popularity = sorted(set(a), key=lambda x: -a.count(x))

[8, 1, 5, 9]

rawDescription: Take a list, sort by popularity and then remove duplicates


code: r, x, x, x = color()

rawDescription: Is there some kind of tuple wildcart in Python?


code:
#Uncomment the next line to get the print() function of python 3
#from __future__ import print_function
import os
import subprocess
from subprocess import Popen
command = "echo \"something\""
env = os.environ.copy()
try:
    po = Popen(command, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE,
        universal_newlines=True, env=env)
    po.wait()
    output, error_output = po.communicate()

    if po.returncode:
        print(error_output)
    else:
        print(output)

except OSError as e:
    print('Execution failed:', e, file=sys.stderr)

rawDescription: Best Way of redirecting output to a VTE terminal


rawDescription: Interpolating an array within an astropy table column


code:
# By list comprehension
names = [ x["name"] for x in temp_list for temp_list in first_list ]

# If you don't know the how the key is named
names = [ x.values()[0] for x in temp_list for temp_list in first_list ]

rawDescription: How to literate my list

description: Literate my list


rawDescription: How to avoid user to click outside popup Dialog window using Qt and Python?

description: Avoid user to click outside popup Dialog window using Qt and Python


code:
def MyUsefulFunction(price):
    return price*10/100

rawDescription: Calling django template tags from a normal function


code: np.concatenate((a, b, c)).reshape((-1, 3), order='F')

rawDescription: combining vectors as column matrix in numpy

description: Combining vectors as column matrix in numpy


code:
def deleteContent(fName):
    with open(fName, "w"):
        pass

rawDescription: How to delete only the content of file in python

description: Delete only the content of file in python


code:
prioritylist = ('r','u','d','l')
for direction in prioritylist:
  if move(direction, location): break

rawDescription: Python - 2 Questions: Editing a variable in a function and changing the order of if else statements internally/during runtime


code:
class SQLUserFromToken(TokenInterface):
    def getUserFromToken(self, token):
        # load the user from the database
        return user

class ClientFrameworkClass(FrameworkClass, SQLUserFromToken):
    pass

framework_instance = ClientFrameworkClass()
framework_instance.do_the_job(...)

rawDescription: What is a Pythonic way for Dependency Injection?


code: cln['Record Number'] = cln['Record Number'].astype(float)

rawDescription: python drop non-integer rows, convert to int

description: Python drop non-integer rows, convert to int


code:
idx = pd.date_range('2012-01-01 00:00:00', freq='5min', periods=24*12*3)
s = pd.Series(np.arange(len(idx)), index=idx)
s.resample('24h', base=5)

rawDescription: Resample daily pandas timeseries with start at time other than midnight


code:
#!/usr/bin/env python3
import struct
import alsaaudio

sound_out = alsaaudio.PCM()  # open default sound output
sound_out.setchannels(1)  # use only one channel of audio (aka mono)
sound_out.setperiodsize(5) # buffer size, default is 32

sound_in = alsaaudio.PCM(type=alsaaudio.PCM_CAPTURE)  # default recording device
sound_in.setchannels(1)  # use only one channel of audio (aka mono)
sound_in.setperiodsize(5) # buffer size, default is 32

while True:
    sample_lenght, sample = sound_in.read()
    sound_out.write(sample)

rawDescription: How to play a sound onto a input stream

description: Play a sound onto a input stream


rawDescription: Python: is index() buggy at all?

description: Python: is index() buggy at all


code:
class Stored(object):
    """A data descriptor that stores instance values in itself.
    """
    instances = dict()
    def __init__(self, val):
        self.instances[self, None] = val
    def __get__(self, obj, objtype):
        return self.instances[self, obj]
    def __set__(self, obj, val):
        self.instances[self, obj] = val

class MyClass(object):
    x = Stored(3)
    y = Stored(9)

print(MyClass.x)
print(MyClass.y)
m = MyClass()
m.x = 42
print(m.x)
m.y = 19
print(m.y)
print(m.x)

rawDescription: Where does a python descriptor's state go?


rawDescription: using numpy reshape for column major in multi-dimensional array in python

description: Using numpy reshape for column major in multi-dimensional array in python


code:
outputs_info=[tensor.alloc(numpy_floatX(0.),
                           n_samples,
                           dim_proj)],

rawDescription: GRU implementation in Theano

description: GRU implementation in Theano


code:
client = SSHClient()
client.load_system_host_keys()
client.connect('ssh.example.com')
stdin, stdout, stderr = client.exec_command('ls -l')

rawDescription: paramiko ssh.connect - what arguments to send?

description: Paramiko ssh.connect - what arguments to send


code: newImg = img[x]

rawDescription: Indexing numpy arrays with numpy arrays, in arbitrary dimension


code: day_max = df.resample('D', how='max')

rawDescription: Hourly frequency count with Python

description: Hourly frequency count with Python


code:
from model_utils.managers import InheritanceManager

class MyBaseModel(models.Model):
    objects = InheritanceManager()

rawDescription: Getting the object from just an object id


code:
ax_list=df.hist(layout=(2,1),bins=np.histogram(df.values.ravel())[1])
ax_list[0][0].set_xlim((0.01, 0.07))
ax_list[1][0].set_xlim((0.01, 0.07))

rawDescription: how to set bounds for the x-axis in one figure containing multiple matplotlib histograms and create just one column of graphs?

description: Set bounds for the x-axis in one figure containing multiple matplotlib histograms and create just one column of graphs


code: C = [obj.Bar for obj in (A, B) if hasattr(obj, 'Bar')]

rawDescription: Python: Get attribute from a list of objects of the same type in the most efficient way


code:
class Vehicule(object):
    def __init__(self):
        self._spatials = 1
    def _getSpatials(self):
        print("Calling Vehicule's spatials getter")
        return self._spatials
    def _setSpatials(self,value):
        print("Calling Vehicule's spatials setter")
        self._spatials=value
    spatials=property(_getSpatials,_setSpatials)

class Car(Vehicule):
    def __init__(self):
        super(Car,self).__init__()
    def _getSpatials(self):
        print("Calling Car's spatials getter")
        return super(Car,self).spatials
    spatials=property(_getSpatials)

v=Vehicule()
c=Car()
print(c.spatials)
# Calling Car's spatials getter
# Calling Vehicule's spatials getter
# 1

rawDescription: Overwrite property using Python

description: Overwrite property using Python


code:
s = """<w:rPr><w:rFonts w:eastAsia="Times New Roman" w:cs="Arial" w:ascii="Arial" w:hAnsi="Arial"/><w:color w:val="00000A"/><w:sz w:val="22"/><w:szCs w:val="22"/><w:US" w:eastAsia="en-US" w:bidi="ar-SA"/></w:rPr><w:t>{{form.</w:t></w:r><w:r><w:rPr><w:rFonts w:eastAsia="Times New Roman" w:cs="Arial" w:ascii="Arial" w:hAnsi="Arial"/><e"/><w:bCs w:val="false"/><w:color w:val="00000A"/><w:sz w:val="22"/><w:szCs w:val="22"/><w:lang w:val="en-US" w:eastAsia="en-US" w:bidi="ar-SA"/></w:rPr><w:t>L</w:t></w<w:rFonts w:eastAsia="Times New Roman" w:cs="Arial" w:ascii="Arial" w:hAnsi="Arial"/><w:color w:val="00000A"/><w:sz w:val="22"/><w:szCs w:val="22"/><w:lang w:val="en-US"-US" w:bidi="ar-SA"/></w:rPr><w:t>etterDate.value|date:"Y-m-d"}}</w:t></w:r>"""
re.sub(r"(\{\{[^}]+}\})", lambda m: re.sub("<[^>]+>", "", m.group(1)), s)

rawDescription: Between double curly braces: replace particular text


code:
prev_day = "2016-01-11 01:00:01.504424"
prev_day_date = datetime.strptime(prev_day, "%Y-%m-%d %H:%M:%S.%f")
prev_day_date.date()
prev_day_date.strftime("%Y-%m-%d")

rawDescription: python date on file want to strip off microseconds

description: Python date on file want to strip off microseconds


code:
with open('card.html') as f:
    card = f.read()

with open('text.txt') as f:
    text = f.read()

with open('input.html', 'w') as f:
    f.write(card.replace('{{ text }}', text))

rawDescription: Assistance on automated image/text Document


code:
import re
list_of_strings = ["3He2l2lo Wo45rld!", "Hello World- -number two-", "Hello    World    number .. three"]
for str in list_of_strings:
    print(re.sub(r'((?:[^A-Za-z\s]|\s)+)', lambda x: ' ' if ' ' in x.group(0) else '' , str))

rawDescription: Python Regex for Words & single space

description: Python Regex for Words & single space


rawDescription: How do I create a recursion of multiple for loops of lists in Python to get combination?

description: Create a recursion of multiple for loops of lists in Python to get combination


code:
# added constants
LEFT_KEY = K_a
RIGHT_KEY = K_d
LURU, LDRU, LURD, LDRD = range(4)  # velocity states
LD, RD, LU, RU = range(4)  # velocity key events
VEL_EVENTS = {LD, RD, LU, RU}  # every velocity key event value
NEW_VELOCITY_GOAL, NEW_STATE = range(2)  # indices of EVENT_DECISION_TABLE entries
MAX_VELOCITY = 200

# non-None entries represent new velocity_goal and state value for each event for each state
EVENT_DECISION_TABLE = [
# event       LD                     RD                    LU                    RU             # cur state
    [[-MAX_VELOCITY, LDRU], [MAX_VELOCITY, LURD], [None,         None], [None,          None]], # LURU
    [[None,          None], [None,         LDRD], [0,            LURU], [None,          None]], # LDRU
    [[None,          LDRD], [None,         None], [None,         None], [0,             LURU]], # LURD
    [[None,          None], [None,         None], [MAX_VELOCITY, LURD], [-MAX_VELOCITY, LDRU]], # LDRD
]

class EventManagement(object):
    ''' Handles keyboard event's.
    Toggles player variables according to the event's.
    '''
    def __init__(self, player):
        self.player = player
        self.state = LURU

    def is_doneloop(self, flag):
        global is_doneloop
        is_doneloop = flag
        return is_doneloop

    def listen(self):
        ''' Toggles player variables according to keyboard/mouse input.
        '''
        for event in pygame.event.get():
            vel_event = None

            if event.type == QUIT:
                self.is_doneloop(True)
                break
            elif event.type == KEYDOWN:
                if event.key == LEFT_KEY:
                    vel_event = LD
                elif event.key == RIGHT_KEY:
                    vel_event = RD
            elif event.type == KEYUP:
                if event.key == K_ESCAPE:
                    self.is_doneloop(True)
                    break
                elif event.key == LEFT_KEY:
                    vel_event = LU
                elif event.key == RIGHT_KEY:
                    vel_event = RU

            if vel_event in VEL_EVENTS:
                entry = EVENT_DECISION_TABLE[self.state][vel_event]
                if entry[NEW_VELOCITY_GOAL] is not None:
                    self.player.velocity_goal.x = entry[NEW_VELOCITY_GOAL]
                if entry[NEW_STATE] is not None:
                    self.state = entry[NEW_STATE]

    #-------------------------------------------------------------------------

rawDescription: lerp movement and keyboard movement buttons - fast pressing cause a character stuck in place

description: Lerp movement and keyboard movement buttons - fast pressing cause a character stuck in place


rawDescription: using variable limits in gnuplot command "set yrange [min:max] if called from python script

description: Using variable limits in gnuplot command "set yrange [min:max] if called from python script


code: list =  [i[0] for i in anotherArray]  # get the first item from tuples in anotherArray

rawDescription: Python List Indexing or Appending?

description: Python List Indexing or Appending


code:
class Foo(object):
    @autoargs()
    def __init__(self,x,path,debug=False,*args,**kw):
        pass
foo=Foo('bar','/tmp',True, 100, 101,verbose=True)

rawDescription: Automatically setting class member variables in Python


code:
#!/usr/bin/env python
from timeit import default_timer as timer
import xmlrpclib

s = xmlrpclib.Server('http://localhost:9657/')

def report_delay(func, *args):
    start = timer()
    print("Result %r took us %.2f seconds" % (func(*args), timer() - start))

report_delay(s.echo, "Mor-ee-air-teeeee") # should be instant
report_delay(s.getoutput) # should be ~10 seconds

rawDescription: Client/server on python-twisted

description: Client/server on python-twisted


rawDescription: How to increment in python-maya?

description: Increment in python-maya


code:
from yahoo_finance import Share
stock = Share('XLV')
data, = stock.get_historical('2016-05-12','2016-05-12')
data['Close']

rawDescription: Incorrect close data from yahoo_finance in python


code:
inputs = {'fw': 'hello', 'lw': 'world'}
'{fw} {lw}'.format(**inputs)

rawDescription: How to map word combinations in python

description: Map word combinations in python


code:
from itertools import takewhile
usefullines = takewhile(lambda x: not re.search(stopterm, x), lines)

from itertools import takewhile
usefullines = takewhile(lambda x: stopterm not in x, lines)

rawDescription: Python: item for item until stopterm in item?


rawDescription: I want to write a code that can take two numbers and create a txt file between those numbers in decreasing order


code: var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy')

rawDescription: Output formatting in Python: replacing several %s with the same variable


code:
partial_derivative(foo, 0, [3,1])
partial_derivative(foo, 1, [3,1])

rawDescription: scipy.misc.derivative for mutiple argument function

description: Scipy.misc.derivative for mutiple argument function


code:
import bottle
from bottle import response, template, run

app = bottle.Bottle()

@app.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'

# a simple json test main page
str = "Hello"
@app.route('/')                   #irrelevant to this question. Used this to check server...
def test():
    return template('file', str)

@app.get('/check')
def showAll():
    return str

run(app=app, host='localhost', port=8080)

rawDescription: using AJAX to get data from Bottlepy server

description: Using AJAX to get data from Bottlepy server


code:
import re
postcode = re.compile("[a-z]{1,2}[0-9][a-z0-9]?(?=/?$)")
string1= "www.xyz.com/abcdab15/"
string2 = "www.xyz.com/adbdd9"
re.findall(postcode, string1)
re.findall(postcode, string2)

rawDescription: Python Regular Expression for Outward UK Post Code


code:
d = collections.OrderedDict()
for key, group in itertools.groupby(x):
    runlength = len(list(group))
    if runlength > d.get(key, 0):
        d.pop(key, None)
        d[key] = runlength
x = ''.join(d)

rawDescription: How to remove duplicate characters in a string and print according to the longest occurrence

description: Remove duplicate characters in a string and print according to the longest occurrence


code: list(chunked(6, data))

rawDescription: Chunking bytes (not strings) in Python 2 and 3


code:
from ConfigParser import ConfigParser

config = ConfigParser()
config.read('myconfig.cfg')
print(config.get('Section Name', 'my_string'))

rawDescription: How do you store formatted strings in a config file in Python?

description: Store formatted strings in a config file in Python


code: lounge

rawDescription: searching dictionary for string and returning other value

description: Searching dictionary for string and returning other value


code:
init = [5,0,0]
time = np.linspace(0, 10, 101)
soln  = odeint(decay, init ,time)

rawDescription: using scipy.integrate.odeint with dictionary [Python]

description: Using scipy.integrate.odeint with dictionary [Python]


code:
probe = "ACTG.*ACTG"
sequence = "ACTGTTGACATTGAACTGCATATAATACTG"
mismatches = 0

rawDescription: Python regex : overlapping sequences position


code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler

# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
    rpc_paths = ('/RPC2',)

# Create server
server = SimpleXMLRPCServer(("localhost", 8000),
                            requestHandler=RequestHandler)
server.register_introspection_functions()

# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)

# Register a function under a different name
def adder_function(x,y):
    return x + y
server.register_function(adder_function, 'add')

# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'div').
class MyFuncs:
    def div(self, x, y):
        return x // y

server.register_instance(MyFuncs())

# Run the server's main loop
server.serve_forever()

rawDescription: Receiving XML document with python via HTTP


code:
import pandas as pd
pd.set_option('display.max_columns', None)

rawDescription: data editor in Python?

description: Data editor in Python


rawDescription: Use ElementTree's findall() to match text of elements


code:
from functools import wraps
from threading import local

def recursion_detector(func):
    func._thread_locals = local()

    @wraps(func)
    def wrapper(*args, **kwargs):
        params = tuple(args) + tuple(kwargs.items())

        if not hasattr(func._thread_locals, 'seen'):
            func._thread_locals.seen = set()
        if params in func._thread_locals.seen:
            raise RuntimeError('Already called this function with the same arguments')

        func._thread_locals.seen.add(params)
        try:
            res = func(*args, **kwargs)
        finally:
            func._thread_locals.seen.remove(params)

        return res

    return wrapper

rawDescription: Detecting infinite recursion

description: Detecting infinite recursion


code:
b = spynner.Browser()
b.runjs("jQuery('#someAnchorId').get(0).click()")
b.wait(1)

rawDescription: Use Python Spynner to download a file with a JavaScript doPostBack link


rawDescription: How python and the regex module handle backslashes


code:
data_final.columns = ['medicine', 'disease_1', 'disease_2']
data_final

rawDescription: Transposing one column in python pandas with the simplest index possible


code:
class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value

rawDescription: What is the best way to implement nested dictionaries in Python?


code:
def recursive(n):
    if n > 0:
        return recursive(n-1)
    else:
        return 0

rawDescription: Python profiling - What are the columns in runsnakerun output?


code:
rtype = np.dtype((np.void, A.dtype.itemsize * A.shape[1]))
_, first_idx = np.unique(A.view(rtype), return_index=True)

rawDescription: Detect the first unique rows in multiple numpy 2-d arrays


rawDescription: Renaming of files for a given pattern

description: Renaming of files for a given pattern


code:
per_line = int(input("How many numbers per line would you like: "))

for number in range(1, 1001):
    print(number, end = " " if number % per_line else "\n")

rawDescription: Python 3.4.3 - printing multiple ints per line


code:
def collide(self,enemy,enemy_list):
    if self.rect.colliderect(enemy.rect):  # Tests if the player is touching an enemy
        enemy_list.remove(enemy)  # Removes the enemy from the enemy list (Explained lower)

rawDescription: Python Pygame Enemy Collision

description: Python Pygame Enemy Collision


code:
#!/usr/bin/env python
"""Execute main module twice."""
import time

timestamp = time.strftime('%S')

def print_timestamp(prefix):
    print(prefix + timestamp)

if __name__ == '__main__':
    print_timestamp('main')
    time.sleep(3)
    import test_exec_main_twice
    test_exec_main_twice.print_timestamp('module')

rawDescription: Python - String with timestamp changing

description: Python - String with timestamp changing


code:
L1 = [{'domain': 'www.google.com', 'visits': 100, 'sessions': 50},
      {'domain': 'www.youtube.com', 'visits': 50, 'sessions': 20}]
L2 = [{'domain': 'www.google.com', 'visits': 120, 'sessions': 55},
      {'domain': 'www.facebook.com', 'visits': 30, 'sessions': 10}]

res = {}

for counter, item in enumerate([L1, L2], 1):
    for entry in item:
        domain = entry['domain']
        domain_dict = res.setdefault(domain, {})
        domain_dict['Visits{}'.format(counter)] = entry['visits']
        domain_dict['Sessions{}'.format(counter)] = entry['sessions']

rawDescription: Comparing and Printing values from two dictionaries


code: a[[slice(None)]*axis + [slice(None, None, -1)] + [Ellipsis]]

rawDescription: Reverse an arbitrary dimension in an ndarray