code:
from django import http

class PermissionMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        # you should somehow derive this from the view function and/or view args/kwargs
        your_object = SomeThing.objects.get(...)

        if not request.user.has_perm('name_of_your_object.permission'):
            return http.HttpResponseForbidden()

rawDescription: How can i have aspect oriented programming thing in django python

description: Have aspect oriented programming thing in django python


code: f = open('test{}.txt'.format(i), 'ab')

rawDescription: How to create and write to multiple files in Python?

description: Create and write to multiple files in Python


code:
# content of conftest.py
import pytest

def pytest_addoption(parser):
    parser.addoption("--device", action="store",
        help="device: A or B")

@pytest.fixture
def param(request):
    device = request.config.getoption("--device")
    if device == 'A':
        return X()
    elif device == 'B':
        return Y()

rawDescription: Py.Test with configuration files

description: Py.Test with configuration files


code:
class Result():
    def __init__(self, result, notes=None):
        self.Res = result
        self.Notes  = notes if notes is not None else []  # List of strings
    # ...

rawDescription: How do I live with variables not being local in for loop in Python

description: Live with variables not being local in for loop in Python


code: new_list = [b for b in results if not any(word in str(b) for word in words)]

rawDescription: Loop - If one from several conditions is True append to new list


code:
with open("lib_install.log", "w") as pip_log:
    p = subprocess.Popen(["pip", "show", "pytest"], stdout=pip_log, stderr=pip_log)
    p.wait()

rawDescription: Python: with open does not read anything the second time


code:
soup = BeautifulSoup.BeautifulSoup('

 ...

</html')
soup.find("div", {"id": "articlebody"})

rawDescription: Beautiful Soup and extracting a div and its contents by ID


rawDescription: Most efficient way to find all factors with GMPY2 (or GMP)?


rawDescription: find previous max index in data frame with conditional statement

description: Find previous max index in data frame with conditional statement


code:
from collections import Counter
from pylab import *
data = randint(20,size=1000)
res = Counter(data)
vals = arange(20)
ax = gca()
ax.bar(vals-0.4, [ res[i] for i in vals ], width=0.8)
ax.set_xlim( min(data)-1, None )
show()

rawDescription: Add padding between bars and Y-Axis

description: Add padding between bars and Y-Axis


code:
import cv2
import numpy as np

# ============================================================================

INPUT_WIDTH = 160
INPUT_HEIGHT = 120

OUTPUT_TILE_WIDTH = 10
OUTPUT_TILE_HEIGHT = 12

TILE_COUNT = OUTPUT_TILE_WIDTH * OUTPUT_TILE_HEIGHT

# ============================================================================

def stitch_images(input_format, output_filename):
    output_shape = (INPUT_HEIGHT * OUTPUT_TILE_HEIGHT
        , INPUT_WIDTH * OUTPUT_TILE_WIDTH
        , 3)
    output = np.zeros(output_shape, np.uint8)

    for i in range(TILE_COUNT):
        img = cv2.imread(input_format % i)
        cv2.rectangle(img, (0, 0), (INPUT_WIDTH - 1, INPUT_HEIGHT - 1), (0, 0, 255), 1)
        # Draw the frame number
        cv2.putText(img, str(i), (2, 10)
            , cv2.FONT_HERSHEY_PLAIN, 0.7, (255, 255, 255), 1)
        x = i % OUTPUT_TILE_WIDTH * INPUT_WIDTH
        y = i / OUTPUT_TILE_WIDTH * INPUT_HEIGHT
        output[y:y+INPUT_HEIGHT, x:x+INPUT_WIDTH,:] = img

    cv2.imwrite(output_filename, output)

# ============================================================================

stitch_images("images/frame_%04d.png", "stitched_frames.png")
stitch_images("images/mask_%04d.png", "stitched_masks.png")
stitch_images("images/processed_%04d.png", "stitched_processed.png")

rawDescription: Counting Cars OpenCV + Python Issue

description: Counting Cars OpenCV + Python Issue


code:
def ngrams(input, n):
  input = input.split(' ')
  output = []
  for i in range(len(input)-n+1):
    output.append(input[i:i+n])
  return output

ngrams('a b c d', 2) # [['a', 'b'], ['b', 'c'], ['c', 'd']]

rawDescription: Computing N Grams using Python

description: Computing N Grams using Python


rawDescription: how to work with strings and integers as bit strings in python?

description: Work with strings and integers as bit strings in python


code:
testVar = []
def testFunc1():
    testVar = [2] # Will create a local testVar and assign it [2], but will not change the global variable.

def testFunc2():
    global testVar
    testVar = [2] # Will change the global variable.

def testFunc3():
    testVar.append(2) # Will change the global variable.

rawDescription: Local and global variables in python functions


code:
style.layout("Tab",
[('Notebook.tab', {'sticky': 'nswe', 'children':
    [('Notebook.padding', {'side': 'top', 'sticky': 'nswe', 'children':
        #[('Notebook.focus', {'side': 'top', 'sticky': 'nswe', 'children':
            [('Notebook.label', {'side': 'top', 'sticky': ''})],
        #})],
    })],
})]
)

rawDescription: Removing Ttk Notebook Tab Dashed Line

description: Removing Ttk Notebook Tab Dashed Line


code: all(elem[2] in ('', None) for elem in test.values())

rawDescription: evaluating values of a dictionary

description: Evaluating values of a dictionary


rawDescription: Regex : match a string containing only one alphabet


code:
new_na = np.reshape(na, (na.shape[0], -1))
new_na.shape

rawDescription: Numpy Convert N dimensional array into two dimensional array


code: meth = lambda self : self.__dict__[key]

rawDescription: python scope issue with anonymous lambda in metaclass

description: Python scope issue with anonymous lambda in metaclass


code:
def foo(*x):
    print(x)
    for i in x:
        print(i)

rawDescription: How can i use multiple lists as arguments in a function and receive them differently?

description: Use multiple lists as arguments in a function and receive them differently


code: dflist = [df1, df2, df3, df4, df5, df6, df7, df8]

rawDescription: Merging multiple, unaligned data-frames into single pandas data-frame


code:
example = [['b',1],['b',2],['a',2]]
sorted(example, key=sorted)

rawDescription: How to sort list depending on values in sublists?

description: Sort list depending on values in sublists


code:
# pyhton2
import sys
do_run = True
while do_run:
  i = ''
  line = ''
  while i != '\n':   # read one char at a time until RETURN
    i = sys.stdin.read(1)
    line += i
  #
  if line.startswith("END"):
    do_run = False
  else:
    sys.stdout.write("printing : " + line)  # RET already in line
    sys.stdout.flush()

rawDescription: pipe input to and read output from another executable

description: Pipe input to and read output from another executable


code:
fd_A = fd.create_group('A')
fs.copy('A/B', fd_A)

rawDescription: How to partially copy using python an Hdf5 file into a new one keeping the same structure?

description: Partially copy using python an Hdf5 file into a new one keeping the same structure


code:
# equivalence
Something.objects.filter(data={'a': '1', 'b': '2'})

# subset by key/value mapping
Something.objects.filter(data__a='1')

# subset by list of keys
Something.objects.filter(data__has_keys=['a', 'b'])

# subset by single key
Something.objects.filter(data__has_key='a')

rawDescription: Django dynamic model fields

description: Django dynamic model fields


code: lettconv = [0 if lett == ' ' else ord(lett) - 96 for lett in msg]

rawDescription: Replacing spaces by 0's in an array (Python)


code:
arg_list = [{'key':self.key, 'foo':False}, {'key':self.key}, ... ]
handlers = [KeyReleaseEvent, KeyToggleEvent, ...]
for handler, args in zip(arg_list, handlers):
    g_events, r_events = handler(*args)
    self.GameEvents.extend(g_events)
    self.RealEvents.extend(r_events)
self.GameEvents.sort()
self.RealEvents.sort()

rawDescription: Gathering multiple multiple lists together


code:
defaultValue = 'these are not the values you are looking for'
key1, key2 = '1C', '2C'
values.get(key1, {}).get(key2, defaultValue)
key1, key2 = '1A', '2B'
values.get(key1, {}).get(key2, defaultValue)

rawDescription: Python dict of dicts with default value

description: Python dict of dicts with default value


code:
prev = history.prev()
if prev is not None:
    stringvar.set(prev)

rawDescription: Undo and Redo in an Tkinter Entry widget?


code:
#
# Try making some callable types picklable
#

from pickle import Pickler
class ForkingPickler(Pickler):
    dispatch = Pickler.dispatch.copy()

    @classmethod
    def register(cls, type, reduce):
        def dispatcher(self, obj):
            rv = reduce(obj)
            self.save_reduce(obj=obj, *rv)
        cls.dispatch[type] = dispatcher

def _reduce_method(m):
    if m.im_self is None:
        return getattr, (m.im_class, m.im_func.func_name)
    else:
        return getattr, (m.im_self, m.im_func.func_name)
ForkingPickler.register(type(ForkingPickler.save), _reduce_method)

rawDescription: Why can I pass an instance method to multiprocessing.Process, but not a multiprocessing.Pool?


code: new = df.loc[mask].copy()

rawDescription: Insert rows according to value of columns in pandas dataframes


code:
df2 = df.reset_index().groupby(['Name', 'Purchase']).count().unstack('Purchase').fillna(0)
df2.columns.rename('Value',level=0, inplace=True)
df2.columns = df2.columns.set_levels(['Count'], level=0)
totals = df2.sum(axis=1)
totals.name = ('Count', 'all')
df3 = df2.divide(df2.sum(axis=1), axis=0)
df3.columns = df3.columns.set_levels(['Percent'], level=0)
dff = pd.concat([totals, df2, df3], axis=1)
print(dff)

rawDescription: Generating Count Table in Python pandas

description: Generating Count Table in Python pandas


code: abcdef

rawDescription: Unable to read huge (20GB) file from CPython


code:
import pandas as pd
import urllib
from bs4 import BeautifulSoup

html = urllib.urlopen("http://owww.met.hu/eghajlat/eghajlati_adatsorok/bp/Navig/202_EN.htm");
soup = BeautifulSoup(html)
#print soup

fontTags = soup.findAll('font')
#print fontTags

#get text from tags fonts
li = [x.text for x in soup.findAll('font')]

#remove first 13 tags, before not contain necessary data
df = pd.DataFrame(li[13:], columns=['a'])

#split data by arbitrary whitspace
df = df.a.str.split(r'\s+', expand=True)

#set column names
df.columns = columns=['idx','m_ta','m_tax','m_taxd', 'm_tan','m_tand']

#convert column idx to period
df['idx'] = pd.to_datetime(df['idx']).dt.to_period('M')

#convert columns to datetime
df['m_taxd'] = pd.to_datetime(df['m_taxd'])
df['m_tand'] = pd.to_datetime(df['m_tand'])

#set column idx to index, remove index name
df = df.set_index('idx').rename_axis(None)

rawDescription: fetching data from the web page using DataFrame

description: Fetching data from the web page using DataFrame


code:
def validate_input(val, min_v=100, max_v=500):
    try:
        val = float(val)
    except ValueError:
        print("Not a valid entry")
    else:
        if not min_v < val <= max_v:
            print("Value should be between {} and {}".format(min_v, max_v))
        else:
            return val
    return False

rawDescription: Python input datatype handling

description: Python input datatype handling


code: return subs.filter(subscribed_to=related_object).count() > 0

rawDescription: Check if objects is foreign key of queryset result


code: #sTrinGMe

rawDescription: Ordering a string based on another string


rawDescription: Can't get selenium click to work on python


code:
sentence = 'Black bananas and green tomatos are red.'
longest_words(sentence.strip('.'))

rawDescription: Longest word in sentence, potential equality of lengths


code:
# full path to your Maya file to OPEN
maya_file_to_open = r"C:/Where/Ever/Your/Maya_Scene_Files/Are/your_main_maya_file.mb"

# Open your file
opened_file = cmds.file(maya_file_to_open, o=True)

# full path to your Maya file to IMPORT
maya_file_to_import = r"C:/Where/Ever/Your/Maya_Scene_Files/Are/your_maya_file.mb"

# Have a namespace if you want (recommended)
namespace = "SomeNamespaceThatIsNotAnnoying"

# Import the file. the variable "nodes" will hold the names of all nodes imported, just in case.
nodes = cmds.file(maya_file_to_import, i=True,
                          renameAll=True,
                          mergeNamespacesOnClash=False,
                          namespace=namespace,
                          returnNewNodes=True,
                          options="v=0;",
                          type="mayaBinary" # any file type you want. this is just an example.
                          )

#TODO: Do all your scene setup/ positioning etc. if needed here...
#Tip: you can use cmds.viewFit(cam_name, fitFactor=1) to fit your camera on to selected objects

rawDescription: use external python script to open maya and run another script inside maya

description: Use external python script to open maya and run another script inside maya


code:
from datetime import datetime

def binaryDisplay (num, bits):
    return ' '.join ('X' if num & (1 << b) else ' ' for b in range (bits - 1, -1, -1) )

now = datetime.now ().time ()
h, m, s = now.hour, now.minute, now.second
print (' : '.join ( (binaryDisplay (h, 5), binaryDisplay (m, 6), binaryDisplay (s, 6) ) ) )

rawDescription: How to push this six-line code in to list comprehension in Python

description: Push this six-line code in to list comprehension in Python


rawDescription: Pyplot line with numerical month labels

description: Pyplot line with numerical month labels


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

lev1 = ['foo', 'bar', 'baz']
lev2 = list('abc')

n = 6

df = pd.DataFrame(
    {k: np.random.randn(n) for k in itertools.product(lev1,lev2)},
    index=pd.DatetimeIndex(start='2015-01-01', periods=n, freq='11D'))
groups = df.groupby(pd.TimeGrouper('MS'))
funcs = {'bar': np.sum, 'baz': np.mean, 'foo': np.min}
result = groups.agg(
    {(k1, k2): funcs[k1] for k1, k2 in itertools.product(lev1,lev2)})
result = result.sortlevel(axis=1)
print(result)

rawDescription: Aggregate group with multi-level columns


code:
url(r'^results/$', views.results, name='results'),
url(r'^results/(\d+)/$', views.user_results, name='user_results')

rawDescription: Django: url dispatcher

description: Django: url dispatcher


code:
prices = df[['PRICE1','PRICE2', 'PRICE3']].stack()
prices.index = prices.index.droplevel(2)
hours = df[['HOUR1', 'HOUR2', 'HOUR3']].stack()
hours.index = hours.index.droplevel(2)

rawDescription: Re-shape pandas dataframe stack/unstack

description: Re-shape pandas dataframe stack/unstack


code: y = numpy.log10(numpy.arange(1, 101)) * 20

rawDescription: Can Python perform vectorized operations?


code:
Output
['text0', 'text1', ['item1', 'item2'], 'text2', 'sib']

rawDescription: Python, lxml - access text

description: Python, lxml - access text


code:
import numpy as np
np.array(a1.B)

rawDescription: Output pandas grouped dataframe without aggregation


code:
files = glob.glob('temp.txt')
for f in files:
    os.remove(f)

rawDescription: Read/Write File : Write to line in certain order - Python


code:
def rhyme(inp, level):
     entries = nltk.corpus.cmudict.entries()
     syllables = [(word, syl) for word, syl in entries if word == inp]
     rhymes = []
     for (word, syllable) in syllables:
             rhymes += [word for word, pron in entries if pron[-level:] == syllable[-level:]]
     return set(rhymes)

rawDescription: Find rhyme using NLTK in Python

description: Find rhyme using NLTK in Python


rawDescription: How to get nbest predictions from sklearn naive bayes classifier? -python

description: Get nbest predictions from sklearn naive bayes classifier? -python


code: Content(container)

rawDescription: Parent error when Inserting new page in Gtk.Notebook containing a TreeView widget


code:
from argparse import ArgumentParser
from random import random
from subprocess import Popen
from sys import exit
from time import sleep

def add_something(i):

    # Sleep to simulate the long calculation
    sleep(random() * 30)
    return i + 1

def run_my_process():

    # Start up all of the processes, pass i as command line argument
    # since you have your function in the same file, we'll have to handle that
    # inside 'main' below
    processes = []
    for i in range(100):
        processes.append(Popen(['python', 'thisfile.py', str(i)]))

    # Wait for your desired process result
    # Might want to add a short sleep to the loop
    done = False
    while not done:
       for proc in processes:
            returncode = proc.poll()
            if returncode == 90:
                done = True
                break

    # Kill any process that are still running
    for proc in processes:

        if proc.returncode is None:

            # Might run into a race condition here,
            # so might want to wrap with try block
            proc.kill()

if __name__ == '__main__':

    # Look for optional i argument here
    parser = ArgumentParser()
    parser.add_argument('i', type=int, nargs='?')
    i = parser.parse_args().i

    # If there isn't an i, then run the whole thing
    if i is None:
        run_my_process()

    else:
        # Otherwise, run your expensive calculation and return the result
        returncode = add_something(i)
        print(returncode)
        exit(returncode)

rawDescription: Python Multiprocessing help exit on condition


code:
def wantMethod(self, method):
        """Is the method a test method?
        """
        try:
            method_name = method.__name__
        except AttributeError:
            # not a method
            return False
        if method_name.startswith('_'):
            # never collect 'private' methods
            return False
        declared = getattr(method, '__test__', None)
        if declared is not None:
            wanted = declared
        else:
            wanted = self.matches(method_name)
        plug_wants = self.plugins.wantMethod(method)
        if plug_wants is not None:
            wanted = plug_wants
        log.debug("wantMethod %s? %s", method, wanted)
        return wanted

rawDescription: Run specific Django tests (with django-nose?)


rawDescription: SocketServer ThreadingTCPServer & Asyncore Dispatcher


code:
variable = {}
x = 0
variable[x] = 4
x = 1
variable[x] = 7
print(variable[0])
print(variable[1])

rawDescription: How to create continuously changing variables in Python

description: Create continuously changing variables in Python


code:
request.session['grade'] = 5
request.session['teacher'] = 'smith'

rawDescription: Sending parameters to view when submitting a form in Django


code:
gender_weights = gender_dist / df.gender.groupby(df.gender).count()
age_weights = age_dist / df.age.groupby(df.age).count()
age_weights

rawDescription: Weighting values based on variables

description: Weighting values based on variables


code:
def __getitem__(self, idx):
    if isinstance(idx, numbers.Integral):
        idx = (idx, slice(None, None, None))
    # now the rest of your code only needs to handle tuples

rawDescription: Implementing 2D slicing in Python

description: Implementing 2D slicing in Python


code:
series =df.groupby('A').apply(f)
series.name = 'metric'
series.reset_index()

rawDescription: Collapse mutiple rows of a dataframe into one row - based on a unique key


code:
UP, DOWN, LEFT, RIGHT = 'up', 'down', 'left', 'right'

def shift(direction, number, matrix):
    ''' shift given 2D matrix in-place the given number of rows or columns
        in the specified (UP, DOWN, LEFT, RIGHT) direction and return it
    '''
    if direction in (UP, DOWN):
        n =  (number % len(matrix) if direction == UP else
            -(number % len(matrix)))
        h = matrix[:n]
        del matrix[:n]
        matrix.extend(h)
        return matrix
    elif direction in (LEFT, RIGHT):
        n =  (number % len(matrix[0]) if direction == LEFT else
            -(number % len(matrix[0])))
        temp = zip(*matrix)
        h = temp[:n]
        del temp[:n]
        temp.extend(h)
        matrix[:] = map(list, zip(*temp))
        return matrix
    else:
        return matrix

if __name__ == '__main__':
    def print_shifted_matrix(direction, number, matrix):
        print(direction + ': ' + (10-2-len(direction))*' ' +
              ('\n' + 10*' ').join(str(row)
                                  for row in shift(direction, number, matrix)))
        print

    matrix1 = [[1, 2, 3, 4],
               [5, 6, 7, 8],
               [9, 10, 11, 12]]

    matrix2 = [[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9],
               [10, 11, 12]]

    for matrix in matrix1, matrix2:
        print_shifted_matrix('original', 0, matrix)
        print_shifted_matrix(UP, 1, matrix)
        print_shifted_matrix(DOWN, 1, matrix)
        print_shifted_matrix(LEFT, 1, matrix)
        print_shifted_matrix(RIGHT, 1, matrix)

rawDescription: Efficient way to shift 2D-matrixes in python in both directions


code: p = out_param[0]

rawDescription: Plotting resulting fitted curve with scipy


code:
import io
import pandas as pd

text = '''\
control  dose_high  dose_low gender  participant
0      4          6         4      m            1
1      3          5         5      f            2
1      2          8         6      m            3'''

df = pd.read_csv(io.BytesIO(text), sep='\s+')
result = pd.melt(df, id_vars=['participant', 'gender'])
print(result)

rawDescription: Repeated measures transform in Pandas

description: Repeated measures transform in Pandas


code:
f.write('> %s\n' % (alignment.title,))
f.write('%s\n' % (hsp.sbjct,))

rawDescription: Saving output of a for-loop to file

description: Saving output of a for-loop to file


code:
while True:
  word = input('Enter a word: ')
  if word.isupper() and word.isalpha():
    break
  else:
    print('Please enter only uppercase letters, no spaces or punctuation.')

rawDescription: How to only allow capital letters to be input to a variable

description: Only allow capital letters to be input to a variable


rawDescription: Looking for a Python shorthand way of parsing a url encoded string into tuples


code: bar(**{key1:value1, key2:value2})

rawDescription: numpy, scipy, pass large number of variables between functions, modules, easily

description: Numpy, scipy, pass large number of variables between functions, modules, easily


rawDescription: Calculate two values and calculate difference in percentage in Django


code: streetno = dict({"1":"Sachine Tendulkar", "2":"Dravid"})

rawDescription: Hash Map in Python

description: Hash Map in Python


rawDescription: Running python 64 with shebang (#!) on Mac


code:
font = QFont('', -1, QFont.Bold, True)
for item in listWidget.selectedItems():
    item.setFont(font)

rawDescription: Is it possible to highlight (not select) multiple rows in QListWidget?? (Python/PyQt)


code:
class MyMeta(type):
    _names = set()

    @classmethod
    def as_metaclass(meta, *bases):
        '''Create a base class with "this metaclass" as metaclass

        Meant to be used in the definition of classes for Py2/3 syntax equality

        Args:
          bases: a list of base classes to apply (object if none given)
        '''
        class metaclass(meta):
            def __new__(cls, name, this_bases, d):
                # subclass to ensure super works with our methods
                return meta(name, bases, d)
        return type.__new__(metaclass, str('tmpcls'), (), {})

    def __call__(cls, name, *args, **kwargs):
        if name in cls._names:
            raise AttributeError('Duplicate Name')

        cls._names.add(name)
        return type.__call__(cls, name, *args, **kwargs)

class MyClass(MyMeta.as_metaclass()):
    def __init__(self, name, *args, **kwargs):
        self.name = name

a = MyClass('hello')
print('a.name:', a.name)
b = MyClass('goodbye')
print('b.name:', b.name)

try:
    c = MyClass('hello')
except AttributeError:
    print('Duplicate Name caught')
else:
    print('c.name:', c.name)

rawDescription: Ensure uniqueness of instance attribute in python


code:
#!python3
import os

def processChunk(f, pos, chunk_size):
    print('faked f: seek({}) and read({})'.format(pos, chunk_size))

fname = 'a.txt'
sz = os.path.getsize(fname)     # not checking existence for simplicity
chunk = 16

with open(fname, 'rb') as f:
    for pos in range(sz - chunk, 0, -chunk):
        processChunk(f, pos, chunk)

    if pos > 0:
        processChunk(f, 0, pos)

rawDescription: Reading a binary file on backwards using python


code:
def get_count_query(self):
    return self.session.query(func.count('*')).select_from(Asset).join(StatusLabel)\
                                              .filter(StatusLabel.status == 'Deployable', or_(
                                                      Asset.assigned_to.isnot(None),
                                                      Asset.deleted_at.is_(None)))

rawDescription: SQLAlchemy func.count with filter

description: SQLAlchemy func.count with filter


code:
import xml.etree.ElementTree as etree
# or for a faster C implementation
# import xml.etree.cElementTree as etree

tree = etree.parse('input.xml')
elem = tree.find('//tag-Name') # finds the first occurrence of element tag-Name
elem.text = 'newName'
tree.write('output.xml')

rawDescription: Python Manipulate and save XML without third-party libraries


rawDescription: Using python requests on a simple form

description: Using python requests on a simple form


code:
data = "chdir /"
a = data.split(" ")
a
a[-1]

rawDescription: Python split data from socket

description: Python split data from socket


code:
import SocketServer

response = """HTTP/1.0 500 Internal Server Error
Content-type: text/html

Invalid Server Error"""

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        self.request.sendall(response)

if __name__ == "__main__":
    HOST, PORT = "localhost", 8000
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
    server.serve_forever()

rawDescription: Minimal HTTP server with Werkzeug - Internal Server Error


code:
contains_meta(r"example")
contains_meta(r"ex.mple")
contains_meta(r"ex\.mple")
contains_meta(r"ex\\.mple")
contains_meta(r"ex[.]mple")  # single-character charclass --> literal
contains_meta(r"ex[a-z]mple")
contains_meta(r"ex[.,]mple")

rawDescription: How to find if a regex contains non-escaped metacharacters?

description: Find if a regex contains non-escaped metacharacters


code:
class DataAdmin(admin.ModelAdmin):
    ...
    list_display = ('subject', 'get_current_year_sales', 'get_last_year_sales', 'get_current_quarter_sales', 'get_last_quarter_sales')

rawDescription: Custom columns using Django admin

description: Custom columns using Django admin


code:
from a import quickSort
a = [3223,1,321,2,43,54,65,1]
quickSort(a,0,7)
a

rawDescription: How to finish off these python functions for a 'quick Sort'?

description: Finish off these python functions for a 'quick Sort'


code:
# Desired Module:

desired_object = None
def my_func():
    global desired_object
    desired_object = SomeObject()

rawDescription: Accessing an object created in another module using python


code:
import matplotlib.pyplot as plt
plt.plot(l1)
plt.plot(l2)
plt.plot(l3)
plt.show()

rawDescription: Basic plotting of wavelet analysis output in matplotlib


rawDescription: pandas get entries from Series B that are also in Series A; but entries unique only in Series A shall have a fill value of 0

description: Pandas get entries from Series B that are also in Series A; but entries unique only in Series A shall have a fill value of 0


code:
def AIenemyTurn(enemy,playerPos):
    startPos = list(enemy)
    print(startPos)
    potEnemyPos = enemy
    if playerPos[0] > enemy[0]:
        potEnemyPos[0] += 1
    elif playerPos[0] < enemy[0]:
        potEnemyPos[0] -= 1
    elif playerPos[1] > enemy[1]:
        potEnemyPos[1] += 1
    elif playerPos[1] < enemy[1]:
        potEnemyPos[1] -= 1
    if potEnemyPos not in rocks:
        print(potEnemyPos)
        print(startPos)
        return potEnemyPos
    else:
        return startPos

rawDescription: python function incrementing variable in list for no obvious reason

description: Python function incrementing variable in list for no obvious reason


code: k = np.cumsum(s).searchsorted(retained_variance*s_sum) + 1

rawDescription: Is there are more pythonic way to write a while loop that only updates a variable?


code: count.setdefault('a', 0)

rawDescription: How do I pythonically set a value in a dictionary if it is None?

description: Pythonically set a value in a dictionary if it is None


rawDescription: dir and help not showing all attributes of an object in python?

description: Dir and help not showing all attributes of an object in python


code:
import pandas as pd
data = pd.DataFrame({'winner':[0,0,1,0]}, index=pd.Series(['Steve', 'Joe', 'Marsha', 'Kent'], name='runner_name'), )
data['weighted'] = 0.0
data.ix['Steve', 'weighted'] = 45.88
print(data)

rawDescription: Updating DataFrame Value

description: Updating DataFrame Value


rawDescription: getting the opposite diagonal of a numpy array

description: Getting the opposite diagonal of a numpy array


code:
class DummyArray(object):
    """Dummy object that just exists to hang __array_interface__ dictionaries
    and possibly keep alive a reference to a base array.
    """

    def __init__(self, interface, base=None):
        self.__array_interface__ = interface
        self.base = base

rawDescription: Size of numpy strided array/broadcast array in memory?


code:
freq_diffs  = np.abs(table[:,2:6] - table[:,-4:])  # 4 columns, n rows

mean_freq_diff = freq_diffs.mean(axis=0) # holds 4 numbers, these are the means over all the rows
std_freq_diff = freq_diffs.std(axis=0) # similar: std over all the rows

condition = freq_diffs > (mean_freq_diff + 2*std_freq_diff)

rawDescription: How can I assign scores to a list of datapoints and then output values > 2 standard deviations from the mean in python?

description: Assign scores to a list of datapoints and then output values > 2 standard deviations from the mean in python


code: return charge

rawDescription: trying to call a string that is assigned within a function

description: Trying to call a string that is assigned within a function


code:
import re

class SasTranslator:
    def __init__(self):
        # modes:
        #   0   not in START..END
        #   1   in START..END, no CASE seen yet
        #   2   in START..END, CASE already found
        self.mode   = 0
        self.offset = -1   # input line #

    def handle_blank(self, match):
        return ""

    def handle_start(self, match):
        if self.mode == 0:
            self.mode = 1
            return None
        else:
            raise ValueError("Found 'select;' in select block, line {}".format(self.offset))

    def handle_end(self, match):
        if self.mode == 0:
            raise ValueError("Found 'end;' with no opening 'select;', line {}".format(self.offset))
        elif self.mode == 1:
            raise ValueError("Found empty 'select;' .. 'end;', line {}".format(self.offset))
        elif self.mode == 2:
            self.mode = 0
            return None

    def handle_case(self, match):
        if self.mode == 0:
            raise ValueError("Found 'when' clause outside 'select;' .. 'end;', line {}".format(self.offset))
        elif self.mode == 1:
            test = "if"
            self.mode = 2
            # note: code continues after if..else block
        elif self.mode == 2:
            test = "elif"
            # note: code continues after if..else block

        test_var, op, test_val, assign_var, assign_val = match.groups()
        return (
            "{test} {test_var} {op} {test_val}:\n"
            "    {assign_var} = {assign_val}".format(
                test       = test,
                test_var   = test_var,
                op         = op,
                test_val   = test_val,
                assign_var = assign_var,
                assign_val = assign_val
            )
        )

    #
    # Build a dispatch table for the handlers
    #

    BLANK    = re.compile("\s*$")
    START    = re.compile("select;\s*$")
    END      = re.compile("end;\s*$")
    CASE     = re.compile("\s*when\((\w+)\s*([<>=]+)\s*([\d.-]+)\s*\)\s*(\w+)\s*=\s*([\d.-]+)\s*;\s*$")

    dispatch_table = [
        (BLANK, handle_blank),
        (START, handle_start),
        (END,   handle_end),
        (CASE,  handle_case)
    ]

    def __call__(self, line):
        """
        Translate a single line of input
        """
        self.offset += 1

        for test,handler in SasTranslator.dispatch_table:
            match = test.match(line)
            if match is not None:
                return handler(self, match)

        # nothing matched!
        return None

def main():
    with open("my_file.sas") as inf:
        trans = SasTranslator()
        for line in inf:
            result = trans(line)
            if result is not None:
                print(result)
            else:
                print("***unknown*** {}".format(line.rstrip()))

if __name__=="__main__":
    main()

rawDescription: Text parsing convert equation blocks to Python statements


code:
import csv

with open(filename, 'r') as f:
    headers = next(f, None) # the header
    lists = [row for row in csv.reader(f, delimiter=';', skipinitialspace=True)]

    print(lists[-1])
    # Output
    ['5', '54', 'JOE BLOGGS', '123456789']

rawDescription: Iterate through list in python and get highest value for a given element


rawDescription: How to use async/await in Python 3.5?

description: Use async/await in Python 3.5


code:
def _exit_function(info=info, debug=debug, _run_finalizers=_run_finalizers,
                   active_children=active_children,
                   current_process=current_process):
    # NB: we hold on to references to functions in the arglist due to the
    # situation described below, where this function is called after this
    # module's globals are destroyed.

    global _exiting

    info('process shutting down')
    debug('running all "atexit" finalizers with priority >= 0')  # Very interesting!
    _run_finalizers(0)

rawDescription: Context managers and multiprocessing pools


code:
from collections import Iterable

_typetest = lambda t: isinstance(t, Iterable) and not isinstance(t, basestring)

def flattenlen(a):
    return sum(flattenlen(i) if _typetest(i) else 1 for i in a)

rawDescription: Retrieving the length of a list after flattening


code:
from collections import OrderedDict
t = "never gonna give you up"
OrderedDict.fromkeys(t).keys()

rawDescription: Python list comprehension, with unique items


code:
with open('path/to/file') as infile:
    keys = infile.readline().split()
    values = infile.readline().split('\t')

    answer = dict(zip(keys, values))

rawDescription: Reading key value pair from a tab delimited file in python


code:
@inline_requests
def parse_summary(self, response):
    # ...
    for link in chap_summary_links:
        try:
            response = yield Request(link)
        except Exception:
            # TODO: handle the error, log or something
            pass
        else:
            # extract the summary as in parse_chap_summary_link ...
            item['chapter_summaries'] += [text]

    # Must use yield at the end as this callback is a generator
    # due the previous yield statements.
    yield item

rawDescription: Multiple Data Under One Heading with Scrapy


code:
from datetime import date, timedelta

month, year = 2, 2008

day = timedelta(days=1)
date1 = date(year, month, 1)
dates = []
d = date1
while d.month == month:
    dates.append(d)
    d += day

rawDescription: Generate dates for a particular month?

description: Generate dates for a particular month


code:
def transcribe(dna):
    dna = dna.replace("a", "u")
    dna = dna.replace("t", "a")
    dna = dna.replace('g', '_')
    dna = dna.replace('c', 'g')
    dna = dna.replace('_', 'c')
    return dna

rawDescription: transcribe mRNA code from DNA strand

description: Transcribe mRNA code from DNA strand


rawDescription: function and classes, usage of __str__

description: Function and classes, usage of __str__


code:
temp_list = []
for c in Phrase:
    if c.isalpha():
        # shift if the c is alphabet
        temp_list.append(chr(ord(c)+shiftValue))
    else:
        # no shift if c is no alphabet
        temp_list.append(c)

# join the list to form a string
stringCoded = ''.join(temp_list)

rawDescription: Selecting specific int values from list and changing them


code:
n_pixel_x = n_pixel_y = 1000
pixel_x = np.linspace(0.0, 10.0, n_pixel_x)
pixel_y = np.linspace(0.0, 10.0, n_pixel_y)
pixel_x, pixel_y = np.meshgrid(pixel_x, pixel_y)

rawDescription: Issues with isolating color channels in Pylab


code:
import pytz
eastern = pytz.timezone('US/Eastern')
observationTime = observationTime.astimezone(eastern)
print(observationTime.strftime('%b %d %Y %H:%M %p %Z'))
# Dec 13 2014 13:52 PM EST
print(observationTime.strftime('%b %d %Y %H:%M %z'))
# Dec 13 2014 13:52 -0500

bogota = pytz.timezone('America/Bogota')
observationTime = observationTime.astimezone(bogota)
print(observationTime.strftime('%b %d %Y %H:%M %p %Z'))
# Dec 13 2014 13:52 PM COT
print(observationTime.strftime('%b %d %Y %H:%M %z'))
# Dec 13 2014 13:52 -0500

rawDescription: Date parsing and formating in Python 2.7


code:
#!/usr/bin/python
import os
os.system("shutdown -h now")

rawDescription: Computer Shut Off Python 3.4

description: Computer Shut Off Python 3.4


code:
import NetworkManager

for conn in NetworkManager.NetworkManager.ActiveConnections:
    print('Name: %s; vpn?: %s' % (conn.Id, conn.Vpn))

rawDescription: Getting Connected VPN Name in Python

description: Getting Connected VPN Name in Python


rawDescription: Getting the row index for a 2D numPy array when multiple column values are known


code:
input_ = """
------------------------------------------------------------------------
r12345 | debajyoti.das@email.com | 2013-02-06 01:40:23 -0800 (Wed, 06 Feb 2013) | 1 line
Changed paths:
   M /PROJECT/SHARED/branches/DEV_Branch/extensibility/src/main/java/com/companyname/extensibility/NamedExtensionPoint.java
   M /PROJECT/SHARED/branches/DEV_Branch/extensibility/src/main/java/com/companyname/extensibility/PrePostExtensionPoint.java
   M /PROJECT/SHARED/branches/DEV_Branch/extensibility/src/main/java/com/companyname/extensibility/helper/ExtensionConfigurationHelper.java
   M /PROJECT/SRE/branches/DEV_Branch/ext/src/main/java/com/companyname/ext/DocumentGeneratorExt.java
   M /PROJECT/SRE/branches/DEV_Branch/ext/src/main/java/com/companyname/ext/NamedExtensionPoint.java
   M /PROJECT/SRE/branches/DEV_Branch/ext/src/main/java/com/companyname/ext/SystemDateBll.java

BUG 12345678 - BLAH IMPLEMENTATION
------------------------------------------------------------------------
r12346 | debajyoti.das@email.com | 2013-02-06 01:40:23 -0800 (Wed, 06 Feb 2013) | 1 line
Changed paths:
   M /MODULE/CYCLE/branches/DEV_Branch/extensibility/src/main/java/com/companyname/extensibility/FileCycle1.java
   M /MODULE/CYCLE/branches/DEV_Branch/extensibility/src/main/java/com/companyname/extensibility/FileCycle2.java

BUG 12345679 - BLAH IMPLEMENTATION
------------------------------------------------------------------------
"""

modified_prefix = "   M "

projects = set(map(lambda x: ".".join(x.split("/")[1:3]),
               filter(lambda x: x.startswith(modified_prefix),
                      (input_.split("\n")))))

rawDescription: Finding the modules where changes were checked with svn


rawDescription: Python 2.7, AT command response, strange HEX


code:
import pandas as pd
import io

data = """
    col1   col2
1   True   False
2   False  True
3   True   True
    """

df = pd.read_csv(io.StringIO(data), delimiter='\s+')

print(df*1)

rawDescription: Write boolean dataframe to csv with 1s and 0s


code:
def DFS(G,v,seen=None,path=None):
    if seen is None: seen = []
    if path is None: path = [v]

    seen.append(v)

    paths = []
    for t in G[v]:
        if t not in seen:
            t_path = path + [t]
            paths.append(tuple(t_path))
            paths.extend(DFS(G, t, seen, t_path))
    return paths

rawDescription: finding longest path in a graph

description: Finding longest path in a graph


code:
template_response = super(
    ExtendedUserAdmin, self
).render_change_form(*args, **kwargs)

rawDescription: How to wrap long super() call to be compliant with PEP-8?

description: Wrap long super() call to be compliant with PEP-8


rawDescription: Python: can isinstance(i, type(i)) evaluate to False?


code:
import operator
max(lis, key=operator.itemgetter(1))

rawDescription: max second element in tuples python

description: Max second element in tuples python


rawDescription: Put in a column this phrases

description: Put in a column this phrases


code:
def broadcast(msg):
    with lock:
        for client in clients:
            client.send(msg)

rawDescription: Multiplayer Gaming via python

description: Multiplayer Gaming via python


code:
_data = {"version":"v6"}
my_dict = "{version}".format(**_data)
my_dict
type(my_dict)

rawDescription: python dictionary parsing using format and get new data

description: Python dictionary parsing using format and get new data


code:
s = 'a=b=2'
exec(s)    #executes the string as a python command

rawDescription: How to convert string to variable in python

description: Convert string to variable in python


code: MyClass("the string").myfunc()

rawDescription: making "string".functions() functions python

description: Making "string".functions() functions python


code:
for test, message in myconditions:
    if test(i):
        return message

rawDescription: How to map a series of conditions as keys in a dictionary?

description: Map a series of conditions as keys in a dictionary


code:
import os
print(os.environ['PATH'])

rawDescription: How to add a folder to the Windows PATH temporarily with Python?

description: Add a folder to the Windows PATH temporarily with Python


code: np.digitize(days, bins=np.linspace(1, np.nextafter(10,np.inf), 6))

rawDescription: Assigning histogram bin to each data point


code:
import dis

dis.dis(dis)

rawDescription: How to see the assembly code of a Python file?

description: See the assembly code of a Python file


code:
smallest = np.min(df['strike'])
largest = np.max(df['strike'])
num_edges = 3
# np.digitize(input_array, bin_edges)
ind = np.digitize(df['strike'], np.linspace(smallest, largest, num_edges))

rawDescription: How to group by a range of values in pandas?

description: Group by a range of values in pandas


code: readings = ser.readline().rstrip().split(':', 2)

rawDescription: leading zero / zero padding doesn't work properly

description: Leading zero / zero padding doesn't work properly


code: k

rawDescription: Implementation of numpy in1d for 2D arrays?


code: type('myclass', (), {})

rawDescription: Why is my metaclass not behaving as expected


code: print(*(i for i in range(1, 101)))

rawDescription: python 3 print generator

description: Python 3 print generator


code:
import matplotlib.pyplot as plt
import pandas

x = pandas.Series([1, 2, 3])
y = pandas.Series([1, 2, None])
plt.scatter(x, y)
plt.show()

rawDescription: Draw / Create Scatterplots of datasets with NaN


code:
data = []
with open('path_to_file.json', 'a') as file:
    for line in file:
        data_item = json.loads(line)
        data.append(data_item)
file.close()

rawDescription: How to cache in IPython Notebook?

description: Cache in IPython Notebook


rawDescription: Basic celery task function call from inside a django function


code:
A = ['A', 'B', 'C']
B = ['24']
import itertools
list(zip(itertools.cycle(map(int, B)), A))

rawDescription: Merge lists with different size. Fill with smallest


code:
lb = Label(root, image=play)
lb.bind('<Button-1>', lambda e: on_button)
lb.pack()

rawDescription: Button made of an image - Tkinter

description: Button made of an image - Tkinter


code:
line = line.replace('^A', '\a')
line
line.split('\a')

rawDescription: re.split not working on ^A

description: Re.split not working on ^A


rawDescription: product of two functions

description: Product of two functions


rawDescription: calculating 2D rms in python

description: Calculating 2D rms in python


code:
import subprocess

print(subprocess.check_output(['xclip', '-o', '-selection', 'PRIMARY']))

rawDescription: Accessing selection clipboard from ipython


code:
map("world")
lapply(gg2,lines)

rawDescription: How to show lines connecting latitude and longitude points in world map?

description: Show lines connecting latitude and longitude points in world map


code:
import glob
glob.glob('/etc/r*.conf')

rawDescription: Python subprocess Popen: Why does "ls *.txt" not work?


code:
for tag in soup.findAll(id=lambda value: value in ['footer', 'content', 'links']):
    tag.extract()

rawDescription: Can I combine two 'findAll' search blocks in beautifulsoup, into one?

description: Combine two 'findAll' search blocks in beautifulsoup, into one


rawDescription: Get MM-DD-YYYY from pandas Timestamp

description: Get MM-DD-YYYY from pandas Timestamp


code:
y_mean = np.mean(y)
TSS=sum((y - y_mean)**2)

rawDescription: How to make my code calculate q2-LOO faster?

description: Make my code calculate q2-LOO faster


code:
with open("file.txt", "w") as fd:
    print >> fd, "Hello World!"

rawDescription: Better method of writing stdout to file

description: Better method of writing stdout to file


code:
character = pygame.Rect(10, 10, 20, 30)
character_image = pygame.image.load(...)
screen.blit(character_image, character)  # screen is you surface

rawDescription: Pygame move object position from one point to another at constant speed


code:
class Comment(models.Model):
    text = models.TextField()
    created = models.DateTimeField(default=datetime.now())

rawDescription: how to auto-update a Django page only when required?

description: Auto-update a Django page only when required


code:
s = 'abcdefghijklmnopqrstuvwxyz'
alphaDict = dict.fromkeys(s,0)
alphaDict

rawDescription: Convert every character in a String to a Dictionary Key


rawDescription: Multiprocessing of summing 2 lists doesn't work in python


code:
c= compile('lambda: a', '<stdin>', 'eval')
c.co_consts[0]
dis.dis(c.co_consts[0])

rawDescription: Why are closures broken within exec?

description: Why are closures broken within exec


code:
s="this is224$# a ths"
import re
w=['this','a']
boundary_words=['\b{}\b'.format(i) for i in w]
reg='|'.join(oundary_words)
new_text=re.sub(reg,'',s).translate(None,punctuation)
new_text

rawDescription: How to delete certain words from a variable or a list python

description: Delete certain words from a variable or a list python


code:
import shutil

...

self.send_response(200)
self.send_header('Content-type', 'image/jpeg')
self.end_headers()
with open(content_path, 'rb') as content:
    shutil.copyfileobj(content, self.wfile)

rawDescription: How to transfer images to client using Python BaseHttpRequestHandler in Windows?

description: Transfer images to client using Python BaseHttpRequestHandler in Windows


rawDescription: y-axis scaling in seaborn vs pandas

description: Y-axis scaling in seaborn vs pandas


rawDescription: Remove HTML child inside its parent

description: Remove HTML child inside its parent


code:
from tkinter import *

class App:
    def __init__(self,master):
        master.geometry("400x200")

        photo = PhotoImage(file="C:/programs/Python34/temimage.png")
        self.w = w = Label (master, image=photo)
        w.photo = photo
        w.pack()

        self.hello_b = Button(master,text="ME",command=sys.exit, height=1,
                              width=3,fg= "white",bg = "green")
        self.hello_b.place(x=200, y=5)

root = Tk()
app = App(root)
root.mainloop()

rawDescription: Background image using Tkinter - Python 2.7


code: index = myList.index(chosen_element)

rawDescription: Removing an element from a list and a corresponding value


rawDescription: Accessing grouped items in arrays

description: Accessing grouped items in arrays


code:
print("Log Created:", grab_date, file=f)
print("Log deleted and recreated.", file=f)

rawDescription: Writing variables with .write() Python 3


code:
from __future__ import print_function

import ruamel.yaml

inp = """\
features:
  show: true
  items:
    - widget: full_width.html  # full width 1
      title: Some Title
      description: >
          Foobar.
      vimeo_id: 20913
      zoom_image: some_url.png
    - widget: 3x_container.html
      items:
          - widget: 3x.html
            title: Some Widget Title
            image: 'foobar.png'
            description: >
                Some Description.
          - widget: 3x.html
            title: Some new title here
            image: ajax_uploads/png1_2.png
            description: >
                Some Description.
"""

code = ruamel.yaml.load(inp, ruamel.yaml.RoundTripLoader)

res = ruamel.yaml.dump(code, Dumper= ruamel.yaml.RoundTripDumper)
print(res, end='')

rawDescription: Popular data exchange format that preserves input order even to represent unordered/unused elements?


code:
def equal_ignore_order(a, b):
    """ Use only when elements are neither hashable nor sortable! """
    unmatched = list(b)
    for element in a:
        try:
            unmatched.remove(element)
        except ValueError:
            return False
    return not unmatched

rawDescription: Determine if 2 lists have the same elements, regardless of order?


code:
# Estimate P(value|class,dim)
nb.p_conditional[i][j] = _contents(values, True)

rawDescription: Laplacian smoothing to Biopython

description: Laplacian smoothing to Biopython


code:
[('Rami', 'PERSON'), ('Eid', 'PERSON'), ('is', 'O'), ('studying', 'O'),
('at', 'O'), ('Stony', 'ORGANIZATION'), ('Brook', 'ORGANIZATION'),
('University', 'ORGANIZATION'), ('in', 'O'), ('NY', 'LOCATION')]

rawDescription: Extract list of Persons and Organizations using Stanford NER Tagger in NLTK


code: data[data==ref] = 0

rawDescription: Replace array values from the reference list


code:
from collections import Counter

corpus.flatMap(lambda doc: Counter(doc.split(' ')).items()).reduceByKey(add)

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


code: result = PyObject_IsTrue(res);

rawDescription: Hack the in operator to return non booleans


code:
@pause_wrapper(x, n)
def function(a, b, c):
    ...

rawDescription: Dynamically pass parameters to function

description: Dynamically pass parameters to function


code: KLCDEFGHIJ

rawDescription: Python mmap.move()

description: Python mmap.move()


code: printObj

rawDescription: What is the difference between these codes, and what does the repr do?


code:
import bson
obj_id = bson.ObjectId(obj_id)

rawDescription: update not working with pymongo

description: Update not working with pymongo


code:
#!/usr/bin/env python3
import smtplib
from contextlib import contextmanager
from datetime   import datetime
from email.mime.text import MIMEText
from netrc      import netrc
from timeit     import default_timer as timer

@contextmanager
def logined(sender, password, smtp_host='smtp.gmail.com', smtp_port=587):
    start = timer(); smtp_serv = smtplib.SMTP(smtp_host, smtp_port, timeout=10)
    try: # make smtp server and login
        smtp_serv.ehlo_or_helo_if_needed()
        smtp_serv.starttls()
        smtp_serv.ehlo()
        print('smtp setup took (%.2f seconds passed)' % (timer()-start,))
        start = timer(); smtp_serv.login(sender, password)
        print('login took %.2f seconds' % (timer()-start,))
        start = timer(); yield smtp_serv
    finally:
        print('Operations with smtp_serv took %.2f seconds' % (timer()-start,))
        start = timer(); smtp_serv.quit()
        print('Quiting took %.2f seconds' % (timer()-start,))

smtp_host = 'smtp.gmail.com'
login, _, password = netrc().authenticators(smtp_host)
with logined(login, password, smtp_host) as smtp_serv:
    for i in range(10):
        msg = MIMEText('#%d timestamp %s' % (i, datetime.utcnow()))
        msg['Subject'] = 'test #%d' % i
        msg['From'] = login
        msg['To'] = login
        smtp_serv.send_message(msg)

rawDescription: Python sending email too slow

description: Python sending email too slow


code:
'{number:0{width}d}'.format(width=2, number=4)
'{number:0{width}d}'.format(width=8, number=4)

rawDescription: Dynamically calculated zero padding in format string in python


code:
def transpose_matrix(matrix):
    return list(map(list, zip_longest(*matrix, fillvalue=0)))

rawDescription: Transpose this matrix(python3)

description: Transpose this matrix(python3)


code:
import datetime as DT
import calendar

timestamp = 1425508527
offset = -6

date = DT.datetime(1970,1,1) + DT.timedelta(seconds=timestamp)
print(date)
# 2015-03-04 22:35:27

localdate = date + DT.timedelta(hours=offset)
print(localdate)
# 2015-03-04 16:35:27

rawDescription: Python datetime and utc offset conversion ignoring timezone/daylight savings


code:
x=np.ones((25,25,25,25))
x.reshape(x.shape[0],-1).shape  # like Joe's
x.reshape(x.shape[:-2]+(-1,)).shape

rawDescription: Easy way to collapse trailing dimensions of numpy array?


code:
class PerInstancePropertyProxy(object):
    def __init__(self, prop):
        self.prop = prop
    def __get__(self, instance, owner):
        if instance is None:
            return self
        return instance.__dict__[self.prop].__get__(instance, owner)
    def __set__(self, instance, value):
        instance.__dict__[self.prop].__set__(instance, value)
class Prop(object):
    def __init__(self, value, multiplier):
        self.value = value
        self.multiplier = multiplier
    def __get__(self, instance, owner):
        if instance is None:
            return self
        return self.value * self.multiplier
    def __set__(self, instance, value):
        self.value = value
class Obj(object):
    val = PerInstancePropertyProxy('val')
    def __init__(self):
        self.__dict__['val'] = Prop(1.0, 10.0)
    def prop(self, attr_name):
        return self.__dict__[attr_name]

rawDescription: Descriptors as instance attributes in python


code: [x.title() for x in ["JAMES", "jack","HArry"]]

rawDescription: Function to return a list of strings as a proper case


code: re.findall(r'\b[this]{4,4}\b', st)

rawDescription: Python Regex: set combinations of prefix length


code:
newlist =[]
for item in oldlist:
    newlist.append(item)
    newlist.append(item+'.')
    newlist.append(item+',')
    newlist.append(item+'?')
    newlist.append(item+'!')
    newlist.append(item+':')

rawDescription: Extend every single string in a list with punctuation


code:
def bracketed_find(s, start, end, startat=0):
    startloc=s.find(start, startat)
    if startloc==-1:
    	return []
    endloc=s.find(end, startloc+len(start))
    if endloc == -1:
    	return [s[startloc+len(start):]]
    return [s[startloc+len(start):endloc]] + bracketed_find(s, start, end, endloc+len(end))

rawDescription: Finding content between two words withou RegEx, BeautifulSoup, lXml ... etc


code: [x for x in re.split('[^\d]+', a) if x]

rawDescription: I want to get numeric data from string. How to do that in python?


rawDescription: If without else - Python lists

description: If without else - Python lists


rawDescription: In Python how can I check how many times a digit appears in an input?


code:
with other_instance:
    print(other_instance.level)
    with other_instance:
        print(other_instance.level)
    print(other_instance.level)

rawDescription: Context manager inside a class instance

description: Context manager inside a class instance


code:
def rename(path):
    """ Renames all the files to be cropped-%d.xxx """
    count = 0
    for thing in os.listdir(path):
        root, ext = os.path.splitext(thing)
        old = os.path.join(path, thing)
        while True:
            new = os.path.join(path, sys.argv[1] + ".cropped{0}".format(count) + ext)
            if not os.path.exists(new):
                break
            count += 1
        print("rename from {} to {}".format(old, new))
        os.rename(old, new)
        count += 1

rawDescription: Python renaming files being weird

description: Python renaming files being weird


rawDescription: OR style permissions for DjangoRestFramework


code: Product(tags=['Household', 'Bedroom', 'Bed', 'Pillows'], name='Best pillow case')

rawDescription: Hierarchical Tags in Google App Engine ndb


rawDescription: Pythonify Some Simple Loops

description: Pythonify Some Simple Loops


code:
def x(data):
    return data % 3 == 0
def y(data):
    return data % 5 == 0

rawDescription: Logical and of two functions

description: Logical and of two functions


code:
def pairs(iterable):
    """A generate over pairs of items in iterable

    >>> list(pairs([0, 8, 2, 1, 3]))
    [(0, 8), (8, 2), (2, 1), (1, 3)]

    """
    iterator = iter(iterable)
    prev = next(iterator)
    for j in iterator:
        yield prev, j
        prev = j

rawDescription: Python, efficient way to operate on pair of coordinates


code: ['Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']

rawDescription: Comparing string lists to find missing value of sequence


code:
import numpy as np
np.random.seed(0)

#create the table
def rotated(s):
    for i in range(len(s)):
        s2 = s[i:] + s[:i]
        if s2[-1] == "1":
            yield int(s2, 2)

bitmap = []
for i in range(256):
    s = "{:08b}".format(i)
    try:
        r = min(rotated(s))
    except ValueError:
        r = i
    bitmap.append(r)

bitmap = np.array(bitmap, np.uint8)

rawDescription: How to rotate a binary vector to minimum in Python

description: Rotate a binary vector to minimum in Python


code:
from django.http import HttpResponseForbidden

...

if not request.user == user:
    return HttpResponseForbidden()

rawDescription: Django - View Other user profile

description: Django - View Other user profile


code:
def union(self,p,q):
    pid = self.id[p]
    qid = self.id[q]
    for i in range(len(self.id)):
        if self.id[i] == pid:
            self.id[i] = qid

rawDescription: python too many self in class

description: Python too many self in class


code:
import random
random_word = random.choice(words)

rawDescription: How to make random.shuffle truly random?

description: Make random.shuffle truly random


rawDescription: Contour plot data (lat,lon,value) within boundaries and export GeoJSON


code:
curr_file = open('myfile',w)
curr_file.write('hello world')
curr_file.close()

rawDescription: Appending lines for existing file in python


code: list(mix_lists('abcdef', [1, 2, 3]))

rawDescription: Homogeneous mix of two lists

description: Homogeneous mix of two lists


rawDescription: BeautifulSoup: scrape HTML only accessible after clicking "Accept" in the same URL


rawDescription: Area of Polygon - spyder

description: Area of Polygon - spyder


code:
List1 = []
List1.append("Blah")
List1.append("Blah1")
List1.append("Blah2")
List1.append("Blah3")

rawDescription: Importing lists from another file

description: Importing lists from another file


code:
import matplotlib.pyplot as plt
plt.figure()
values = [3, 12, 5, 8]
labels = ['a', 'b', 'c', 'd']
plt.pie(values, labels=labels, autopct='%.2f')
plt.show()

rawDescription: How do I use matplotlib autopct?

description: Use matplotlib autopct


rawDescription: Pyparsing sequence of repeating pattern

description: Pyparsing sequence of repeating pattern


code:
names = ['apple', 'banana', 'orange']
prices1 = ['0.40', '1.20', '0.35']
prices2 = ['0.43', '1.21', '0.34']
fruits = []
for i in range(len(names)):
    fruits.append( [ names[i], [prices1[i], prices2[i]] ] )
fruits

rawDescription: How do I generate a list for each list item

description: Generate a list for each list item


rawDescription: Pandas: Generate Sequential Timestamp with Jump


code:
for file in dirs:
    data = csv.reader(open(file, 'rb'), delimiter=";", quotechar='|')
    column = []
    for idx,row in enumerate(data):
        output_rows[idx].append(row[15])

rawDescription: CSV files and Python

description: CSV files and Python


code:
Master =[23, 5, 6, 34, 11, 23, 23, 11, 6]
List_check = [23, 6, 11]

Location = []
for element in List_check:
    if element in Master:
        for k in range(len(Master)):
            if Master[k] == element:
                Location.append(k)
                break

rawDescription: Append index of items in one list to another in Python 2.7


code:
C(1)
C(2)
C(1).print_num()
C(2).print_num()
type(C(1)) == type(C(2))
type(C(1)) == type(C(1))
isinstance(C(1), type(B(1)))

rawDescription: Changing the bases of an object based on arguments to __init__


code:
self.xPos -= diff[0]
self.yPos -= diff[1]

rawDescription: Python - PyGame - Learning vectors/animation


rawDescription: Make random choice from string

description: Make random choice from string


code:
args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)'
in_p=', '.join(list(map(lambda x: '%s', args)))
sql = sql % in_p
cursor.execute(sql, args)

rawDescription: Executing "SELECT ... WHERE ... IN ..." using MySQLdb


code:
def my_handler(self, event):
    QtGui.QPlainTextEdit.focusOutEvent(self.my_text_edit, event)
    # my own handling follows...

rawDescription: How can I intercept when a widget loses its focus

description: Intercept when a widget loses its focus


code:
def comb(S):
    if not '?' in S:
        yield S
    else:
        for i in comb(S.replace('?','0',1)):
            yield i
        for i in comb(S.replace('?','1',1)):
            yield i

rawDescription: Replace a character with multiple characters using Python


code:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

caps = DesiredCapabilities.CHROME
caps['loggingPrefs'] = {'performance': 'ALL'}
driver = webdriver.Chrome(desired_capabilities=caps)

driver.get('https://stackoverflow.com')

logs = [json.loads(log['message'])['message'] for log in driver.get_log('performance')]

with open('devtools.json', 'wb') as f:
    json.dump(logs, f)

driver.close()

rawDescription: Browser performance tests through selenium


code: ['This is a test1', 'This is a test2', 'This is a test1', 'This is a test1', 'This is a test3']

rawDescription: Python regex list using list

description: Python regex list using list


rawDescription: django- How to filter the database based on the submitted form data

description: Django- How to filter the database based on the submitted form data


code:
lstresult = []
for el in result:
    # print k, v
    lstresult.append(el)
    if result[el] > 1:
        lstresult.append(result[el] - 1)

rawDescription: Duplicates counting with order order preserving in Python lists


code: unified = numpy.concatenate((dates.reshape(len(dates), 1), values), axis=1)

rawDescription: Numpy sorting by increasing datetime

description: Numpy sorting by increasing datetime


code: # viewKeysGroup.pack(padx=10, pady=10)

rawDescription: Why isn't my tkinter scrollbar working?

description: Why isn't my tkinter scrollbar working


code: match = re.compile(r'at ((\w+ ){3})')

rawDescription: Regex - Python: Capture three (3) words after a specific word


code:
x = np.linspace(-50, 50, fits_data1.shape[0])
y = np.linspace(-50, 50, fits_data1.shape[1])
X, Y = np.meshgrid(x, y)
plt.contour(X, Y, fits_data1, origin='lower', colors=line_colours)

rawDescription: Subtracting values to contour map axis python


code:
model = hmm.GaussianHMM(n_components=3, n_iter=100, init_params="t")
model.startprob_ = np.array([0.6, 0.3, 0.1])
model.means_ = np.array([[0.0, 0.0], [3.0, -3.0], [5.0, 10.0]])
model.covars_ = np.tile(np.identity(2), (3, 1, 1))

rawDescription: HMMlearn Gaussian Mixture: set mean, weight and variance of each mixture component


rawDescription: Python create list from list

description: Python create list from list


code:
states =  {
        'AK': 'Alaska',
        'AL': 'Alabama',
        'AR': 'Arkansas',
        'AS': 'American Samoa',
        'AZ': 'Arizona',
        'CA': 'California',
        'CO': 'Colorado',
        'CT': 'Connecticut',
        'DC': 'District of Columbia',
        'DE': 'Delaware',
        'FL': 'Florida',
        'GA': 'Georgia',
        'GU': 'Guam',
        'HI': 'Hawaii',
        'IA': 'Iowa',
        'ID': 'Idaho',
        'IL': 'Illinois',
        'IN': 'Indiana',
        'KS': 'Kansas',
        'KY': 'Kentucky',
        'LA': 'Louisiana',
        'MA': 'Massachusetts',
        'MD': 'Maryland',
        'ME': 'Maine',
        'MI': 'Michigan',
        'MN': 'Minnesota',
        'MO': 'Missouri',
        'MP': 'Northern Mariana Islands',
        'MS': 'Mississippi',
        'MT': 'Montana',
        'NA': 'National',
        'NC': 'North Carolina',
        'ND': 'North Dakota',
        'NE': 'Nebraska',
        'NH': 'New Hampshire',
        'NJ': 'New Jersey',
        'NM': 'New Mexico',
        'NV': 'Nevada',
        'NY': 'New York',
        'OH': 'Ohio',
        'OK': 'Oklahoma',
        'OR': 'Oregon',
        'PA': 'Pennsylvania',
        'PR': 'Puerto Rico',
        'RI': 'Rhode Island',
        'SC': 'South Carolina',
        'SD': 'South Dakota',
        'TN': 'Tennessee',
        'TX': 'Texas',
        'UT': 'Utah',
        'VA': 'Virginia',
        'VI': 'Virgin Islands',
        'VT': 'Vermont',
        'WA': 'Washington',
        'WI': 'Wisconsin',
        'WV': 'West Virginia',
        'WY': 'Wyoming'
}

# sample DF
data = """\
location
Indiana, USA
Burlington, VT
United States
Saint Paul - Minneapolis, MN
Inland Valley, The Pass, S. CA
In the Dreamatorium
Nova Scotia;Canada
North Carolina, USA
INTP. West Michigan
Los Angeles, California
Waterbury Connecticut
Right side of the tracks
"""
df = pd.read_csv(io.StringIO(data), sep=r'\|')

re_states = r'.*,\s*(?:' + '|'.join(states.keys()) + ')'

df.ix[df.location.str.contains(re_states), 'location'].to_csv('filtered.csv', index=False)

rawDescription: writing to CSV in python

description: Writing to CSV in python


code:
def callback(self):
    self.my_button.config(state=tk.DISABLED)
    # other actions
    self.my_button.config(state=tk.NORMAL)

rawDescription: Prevent a function being called twice when a user double-clicks a button?


code:
class Basic(object):
    def __add__(self, other):
        return Add(self, other)
    def __radd__(self, other): # if other hasn't implemented __add__() for Symbols
        return Add(other, self)
    def __mul__(self, other):
        return Mul(self, other)
    def __rmul__(self, other):
        return Mul(other, self)
    # ...

class Symbol(Basic):
    def __init__(self, name):
        self.name = name
    def __repr__(self):
        return self.name

class Operator(Basic):
    def __init__(self, symbol, left, right):
        self.symbol = symbol
        self.left = left
        self.right = right
    def __repr__(self):
        return '{0}{1}{2}'.format(self.left, self.symbol, self.right)

class Add(Operator):
    def __init__(self, left, right):
        self.left = left
        self.right = right
        Operator.__init__(self, '+', left, right)

class Mul(Operator):
    def __init__(self, left, right):
        self.left = left
        self.right = right
        Operator.__init__(self, '*', left, right)

# ...

rawDescription: How does sympy work? How does it interact with the interactive Python shell, and how does the interactive Python shell work?


code:
data_temp = json.loads(data)
if data_temp['entities']['hashtags']:
    tweet_text = data_temp["text"].encode('utf-8')

rawDescription: Extracting only tweets of a particular # hastag


code:
#views.py
from . import forms as entryform
from zinnia.models.entry import Entry

def add_entry(request):
    form = entryform.EntryForm(request.POST or None)
    if not (request.method == 'POST' and form.is_valid()):
        return render_to_response("forms.html", {'form': form})
    title = request.POST['title']
    content = request.POST['content']
    #...many more..
    Entry.objects.create(title=title, content=content)
    return render_to_response('success.html', {'form': form,})

rawDescription: Create a entry object in zinnia for the view function -basic python


rawDescription: how to keep the precision when convert string to double value

description: Keep the precision when convert string to double value


code: words = words1.union(words2)

rawDescription: Extend or Append for String in method

description: Extend or Append for String in method


code:
def GroupFunc(x, df, col, Value):
    if df[col][x] == Value:
        return "Group 1"
    else:
        return "Group 2"

DFGrouped = df2.groupby(lambda x: GroupFunc(x, df2, 'X', 'A'))

rawDescription: Pandas GroupBy by Element and everything else


code:
x = int(input("Please enter a x: "))
y = int(input("Please enter a y: "))

product = x * y

numbers = []
for i in range(1, product + 1):
    numbers.append(i)

num_cols, num_rows = x, y

for row in range(num_rows):
    print('row {}: values: {}'.format(row, numbers[num_cols * row:num_cols * row + num_cols]))

rawDescription: I need help splitting a list into equal parts


code:
class Foo:
    def bar(self):
        pass

bound_bar = Foo().bar
bound_bar
bound_bar.__self__

rawDescription: How to extract the attributes of a function of an instance passed as a function?

description: Extract the attributes of a function of an instance passed as a function


rawDescription: Black voodoo of NumPy Einsum

description: Black voodoo of NumPy Einsum


code:
timeArray = numpy.arange(1000)
timeArray *= deltaTime

rawDescription: Confused with arrays in python

description: Confused with arrays in python


code:
Player_list = [{'FirstName': 'Rad', 'AId': 178518, 'LastName': 'Nain'},
               {'FirstName': 'Lad', 'AId': 178519, 'LastName': 'Rain'},
               {'FirstName': 'Mad', 'AId': 178520, 'LastName': 'Tain'}]
rais = [i for i,d in enumerate(Player_list) if d['LastName'].startswith("Rai")]
rais

rawDescription: python list of dict find value starts with

description: Python list of dict find value starts with


rawDescription: Dividing all but first element of a matrix


code:
class missingdict(dict):
    def __missing__(self, key):
        return 'default'  # note, does *not* set self[key]

rawDescription: Python defaultdict that does not insert missing values


rawDescription: Complex dataframe plotting with Pandas / Matplotlib


code:
new_data = data[np.in1d(arr1, arr2)]
new_data

rawDescription: boolean indexing from a subset of a list in python

description: Boolean indexing from a subset of a list in python


code:
def isnull1(list1, list2):
    res = []
    for i, x in enumerate(list1):
        if not x:
            res.append(list2[i])
        else:
            res.append(x)
    return res

isnull1(list1, list2)

rawDescription: Python: merge lists or data frames and overwrite missing values


code:
for i in range(1,5):
     print(i)
     print("Fred"*(5-i))

rawDescription: Produce the following output (for and while loops) in python?


code:
class A(base):
    def calc(self, x, a=a):
        return a(x)

rawDescription: Python dynamically generate dependencies between class instances


rawDescription: Python Add Elements of a List (or Set, or whatever Data Type is appropriate)


rawDescription: Remove special character and apostrophe and unwanted space in string using re.sub function in python


code: f1_a = [[t.strip() for t in x.split(',', 1)] for x in lst]

rawDescription: Nested maps in Python 3

description: Nested maps in Python 3


code:
from mymodel import MANUFACTURERS
mdict = dict(MANUFACTURERS)

def myview(request, manufacturer):
    if not (manufacturer in mdict):
        raise Http404

    #--> do what you need to do

rawDescription: Django how to validate requested URL against a choices field?


code:
import io
import json

def append(filename, data):
    with open(filename, 'r+b') as f:
        f.seek(-2, 2)
        f.write(b',\n')
        f.write(b'   ' + json.dumps(data).encode('utf-8'))
        f.write(b'\n]')

rawDescription: Python update json file

description: Python update json file


code:
# create some dummy data to make a histogram of
import numpy as np
x = np.random.randn(1000)
nbins = 10
# use _ to assign the patches to a dummy variable since we don't need them
n, bins, _ = plt.hist(x, nbins)

# get the width of each bin
bin_width = bins[1] - bins[0]
# sum over number in each bin and mult by bin width, which can be factored out
integral = bin_width * sum(n[bin1:bin2])

rawDescription: Integrate histogram in python?

description: Integrate histogram in python


code:
# define module_name somewhere
import types
module = types.ModuleType(module_name)

rawDescription: python importing code from a string

description: Python importing code from a string


code: "".join(format(ord(c),"02x") for c in text)

rawDescription: Convert Python string to its ASCII representants


code:
for comment in comments:
    cmnt_soup = BeautifulSoup(comment)
    divs = cmnt_soup.find_all('div', attrs={"id": re.compile(r'IAMCOMMENT_\d+')})

    # do things with the divs

rawDescription: How do I only select DIV with similar ID

description: Only select DIV with similar ID


code:
def test(lst, start, end):
    lst.insert(start+1, lst[start])
    lst.insert(end+2, lst[end+1])
    lst[start], lst[end+1] = lst[end+2], lst[start+1]
    del lst[start+1]
    del lst[end+1]

rawDescription: Replacing two elements of a list in place with a function [python 3]


code: l = [i.get('src') for i in soup.find_all('script') if i.get('src')]

rawDescription: Get all the javascript file name and its contents in python perfectly


rawDescription: Reshaping a numpy array in python

description: Reshaping a numpy array in python


code:
request = Q(name_contains='franz')

if condition1:
  request |= Q(birthdate_date=date(2005, 5, 2))

if condition2:
  request |= Q(param3_contains='lorem')

rawDescription: How to join multiple params dynamically for django Q object

description: Join multiple params dynamically for django Q object


code: answer = add(4,7)

rawDescription: What does it mean to "call" a function in Python?


code:
log_op.search(expression).group().lower()
log_op.search(expression).group().lower() is "not"
log_op.search(expression).group().lower() == "not"

rawDescription: Python: how to compare not operator with 'not' string?


code:
from collections import Counter
counter = Counter()
counter.update({'a':10,'b':10,'c':1,'d':1,'e':5,'f':1})
counter
counter['a'] += 5
counter['a']
counter.most_common(3)

rawDescription: What is an efficient way to increase and set the value of a dictionary key using python?


rawDescription: Connect to MSSQL Server 2008 on linux

description: Connect to MSSQL Server 2008 on linux


code:
class Simon:
    name = 'Simon'
    @classmethod
    def says(cls, sentence):
        return '%s says: %s' % (cls.name, sentence)

class Eva(Simon):
    name = 'Eva'
    def to_past_tense(self, func):
        def wrapper(*arg, **kw):
            present_tense = func(*arg, **kw)
            past_tense = present_tense.replace('says', 'said')
            return past_tense
        return wrapper
    @classmethod
    def says(cls, *arg, **kw):
        return cls.to_past_tense(cls, super().says)(*arg, **kw)

Eva.says('Hello')

rawDescription: Override the value of a static variable while using decorator


code:
#sorts each element of seq and returns it
def orderedInnerLists(seq):
    return map(sorted, seq)

#returns a copy of seq with duplicates removed
def removeDuplicates(seq):
    ret = []
    for value in seq:
        if value not in ret:
            ret.append(value)
    return ret

memoizedResults = {}
def orderedPossibleSplits(value,validIncrements):
    memoizeKey = (value, tuple(validIncrements))
    if memoizeKey in memoizedResults:
        return memoizedResults[memoizeKey]
    ret = []
    for increment in validIncrements:
        if increment > value:
            continue
        if increment == value:
            ret.append([increment])
            continue
        if increment < value:
            remainder = value - increment
            toAdd = orderedPossibleSplits(remainder, validIncrements)
            for a in toAdd:
                ret.append([increment] + a)
    memoizeValue = removeDuplicates(orderedInnerLists(ret))
    memoizedResults[memoizeKey] = memoizeValue
    return memoizeValue

rawDescription: How to break down a number with another from list?

description: Break down a number with another from list


code:
import bottle
# Put your bottle code here, following the docs on the Bottle site
bottle.run(server=bottle.CGIServer)

rawDescription: Web Python Question

description: Web Python Question


code: '\n'.join(a.strip() for a in s1.split(':'))

rawDescription: Parsing string in Python

description: Parsing string in Python


code:
from mutagen.flac import File, Picture, FLAC

def add_flac_cover(filename, albumart):
    audio = File(filename)

    image = Picture()
    image.type = 3
    if albumart.endswith('png'):
        mime = 'image/png'
    else:
        mime = 'image/jpeg'
    image.desc = 'front cover'
    with open(albumart, 'rb') as f: # better than open(albumart, 'rb').read() ?
        image.data = f.read()

    audio.add_picture(image)
    audio.save()

rawDescription: mutagen: how to detect and embed album art in mp3, flac and mp4

description: Mutagen: how to detect and embed album art in mp3, flac and mp4


code:
s = requests.Session()
s.send(prepared)

rawDescription: Python requests - print entire http request (raw)?


rawDescription: Build in function for computing covariance


rawDescription: What is the best way to create a moving window in 2D array ond order pixels


code:
r = re.compile('^((?P<fixed>\d+)|-(?P<endonly>\d+)|(?P<begin>\d+)(?:-(?P<end>\d+)?))$')
r.match('123').groupdict()
r.match('123-').groupdict()
r.match('-456').groupdict()
r.match('123-456').groupdict()
r.match('-') is None

rawDescription: Python regular expressions: match a range of numbers with a separator


code: df['a'] = df['a'].apply(lambda x: x + 1)

rawDescription: Pandas: How can I use the apply() function for a single column?


code:
text = self.font.render(message, True, color)
text_rect = text.get_rect()
text_rect.right = 150 # align to right to 150px

self.screen.blit(text, text_rect)

rawDescription: Pygame Text Anchor Right

description: Pygame Text Anchor Right


code:
some_start = 0
some_end = 1720

rawDescription: conditionly selecting a portion of a dataframe rows

description: Conditionly selecting a portion of a dataframe rows


rawDescription: Placing a numpy record array inside another record array python


code:
class SomeObject(object):
    def __init__(self, x, y, data=None):
        if data:
            self.deserialize(data)
        else:
            self.x = x
            self.y = y
    def serialize(self):
        return dict(x=self.x, y=self.y)
    def deserialize(self, data):
        self.x = data['x']
        self.y = data['y']

rawDescription: Define object from text file

description: Define object from text file


code:
import numpy as np
import pandas as pd
import csv
df = pd.DataFrame({
                'A': ['group1', 'group2', 'group3'],
                'B': ['foo', 'foo', 'foo'] })
df['Status'] = 'Active'
df.to_csv('test.csv', index=False, quoting=csv.QUOTE_NONE)

rawDescription: Pandas Dataframe CSV export, how to prevent additional double-quote characters


code:
files = [f for dirpath, dirnames, file in os.walk(path) for f in
         iglob(os.path.join(next(iglob(os.path.join(dirpath, "2*")),
                                 '\\\\'), "*.{}".format(ext)))]
print(files)

rawDescription: Recursively expand and search pattern of specific subdirectories


rawDescription: How to convert numpy datetime64 into datetime

description: Convert numpy datetime64 into datetime


code:
def my_splitext(path):
    """splitext for paths with directories that may contain dots."""
    li = []
    path_without_extensions = os.path.join(os.path.dirname(path), os.path.basename(path).split(os.extsep)[0])
    extensions = os.path.basename(path).split(os.extsep)[1:]
    li.append(path_without_extensions)
    # li.append(extensions) if you want extensions in another list inside the list that is returned.
    li.extend(extensions)
    return li

my_splitext('/path.with/dots./filename.ext1.ext2')

rawDescription: Separating file extensions using python os.path module


rawDescription: create dictionary from list of variables

description: Create dictionary from list of variables


code:
import csv

# Store all the info about the employees
all_employees = {}
output_headers = []

# First, get all employee record info
with open('employees.csv', 'rU') as npr_employees:
    employees = csv.DictReader(npr_employees)
    for employee in employees:
        ext = employee['Extension']
        all_employees[ext] = employee
    # Add headers from "all employees"
    output_headers.extend(employees.fieldnames)

# Then, get all info from social, and update employee info
with open('social.csv', 'rU') as social_employees:
    social_employees = csv.DictReader(social_employees)
    for social_employee in social_employees:
        ext = social_employee['Extension']

        # Combine the two dictionaries.
        all_employees[ext] = dict(
                all_employees[ext].items() + social_employee.items()
        )

    # Add headers from "social employees", but don't add duplicate fields
    output_headers.extend(
            [field for field in social_employees.fieldnames
            if field not in output_headers]
    )

# Finally, output the records ordered by extension
with open('output.csv', 'wb') as f:
    writer = csv.writer(f)
    writer.writerow(output_headers)

    # Write the new employee rows.  If a field doesn't exist,
    # write an empty string.
    for employee in sorted(all_employees.values()):
        writer.writerow(
                [employee.get(field, '') for field in output_headers]
        )

rawDescription: How do I merge two csv files?

description: Merge two csv files


code:
statemachine = StateMachine()

def calculate(*args):
    if statemachine.state == statemachine.STATE_ON:
        do_something
    if statemachine.state == statemachine.STATE_OFF:
        do_something_else

def switch_state(*args):
    do_something  # and...
    statemachine.change_state()

rawDescription: Reading current iterator value without incrementing in Python


rawDescription: Why is list.append(x) more efficient than list += l[x]?


code:
def decorate_run(cls):
    run = getattr(cls, 'run')
    def new_run(self):
        print('before')
        run(self)
        print('after')
    setattr(cls, 'run', new_run)
    return cls

class Task(object): pass

@decorate_run
class MyTask(Task):
    def run(self):
        pass

task = MyTask()
task.run()

# prints:
# before
# after

rawDescription: Python: Decorating a class method that is intended to be overwritten when inherited


code: averages = dict([(key, float(sum(values)) / len(values)) for key, values in pairs])

rawDescription: python: access multiple values in the value portion of a key:value pair

description: Python: access multiple values in the value portion of a key:value pair


code: from util import utilities

rawDescription: How do I get the current path of a project in Python?

description: Get the current path of a project in Python


code:
import numpy as np

wall = np.zeros((10,10),dtype=np.int)
block = np.arange(1,7).reshape(2,3)

x = 2
y = 3
wall[x:x+block.shape[0], y:y+block.shape[1]] = block

rawDescription: How to "embed" a small numpy array into a predefined block of a large numpy array?


rawDescription: Delete the \n and following letters in the end of words in a list


code:
class TagField(ModelMultipleChoiceField):
    widget = TagWidget

    def __init__(self, queryset, *args, **kwargs):
        self.widget.queryset = queryset
        super(TagField, self).__init__(queryset, *args, **kwargs)

    def clean(self, value):
        if self.required and not value:
            raise ValidationError(self.error_messages['required'])
        elif not self.required and not value:
            return []
        if not isinstance(value, (list, tuple)):
            raise ValidationError(self.error_messages['list'])
        # Since this overrides the inherited ModelChoiceField.clean
        # we run custom validators here
        self.run_validators(value)
        return value

rawDescription: Django model pre save for custom ManyToManyField


code: ['Barack Obama', 'Bill Gates']

rawDescription: Python regex findall

description: Python regex findall


code:
class MyClass:
    def __init__(self, create):
        if create:
            self.set_child(create=False)

    def set_child(self,child = None, create = True):
        child = MyClass(create) if child is None else child
        self.child=child

mc=MyClass()

rawDescription: create instance of a class in the same class's definition in python

description: Create instance of a class in the same class's definition in python


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

import os
import tempfile
import shutil

import cherrypy

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8,
    # remove any limit on the request body size; cherrypy's default is 100MB
    'server.max_request_body_size' : 0,
    # increase server socket timeout to 60s; cherrypy's defult is 10s
    'server.socket_timeout' : 60
  }
}

class App:

  @cherrypy.config(**{'response.timeout': 3600}) # default is 300s
  @cherrypy.expose()
  def upload(self):
    '''Handle non-multipart upload'''

    destination = os.path.join('/home/user/test-upload')
    with open(destination, 'wb') as f:
      shutil.copyfileobj(cherrypy.request.body, f)

    return 'Okay'

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: Streaming POST a large file to CherryPy by Python client


code:
def three_tokens(s):
    tokens = s.split('-', 2)
    while len(tokens) < 3:
        tokens.append('')
    return tokens

rawDescription: Concise way to split a string into a list of fixed number of tokens


code: sys.stdout = backup

rawDescription: Python, logging print statements while having them print to stdout


code:
all(ord(char) < 128 for char in 'string')
True
all(ord(char) < 128 for char in 'строка')
False

rawDescription: Check that a string contains only ASCII characters?


code:
df.index = pd.to_datetime(df.index)
df.FinishDate = pd.to_datetime(df.FinishDate)

rawDescription: Subtracting index dates from dates in a column in pandas python


code:
from itertools import combinations_with_replacement
[comb for i in range(1, 20) for comb in combinations_with_replacement(vals, i) if sum(comb) == target]
 # result takes too long ...

rawDescription: Finding Combinations to the provided Sum value


code:
b = np.pad(a, (0, k - a.size%k), mode='constant').reshape(-1, k)
b

rawDescription: Way of easily finding the average of every nth element over a window of size k in a pandas.Series? (not the rolling mean)


code:
from datetime import timedelta

def relative_date(reference, weekday, timevalue):
    hour, minute = divmod(timevalue, 1)
    minute *= 60
    days = reference.weekday() - weekday
    return (reference - timedelta(days=days)).replace(
        hour=int(hour), minute=int(minute), second=0, microsecond=0)

rawDescription: Python construct datetime having weekday with other time parameters


code:
if time_delta >= limit_timedelta:
    state = "expired"

rawDescription: time delta parameter in python script

description: Time delta parameter in python script


rawDescription: Flatten and create new columns in Pandas


code: type(A)

rawDescription: Scipy.sparse test for sparse matrix returns False for a diagonal matrix. Why?


code:
data = {"_id" : "123", "study_type" : "research", "study_name" : "Statistical analysis"}
doc = Study(**data)

rawDescription: How to update from json a Mongoengine DynamicDocument

description: Update from json a Mongoengine DynamicDocument


code: df = pd.read_csv('/path/to/data.csv', delim_whitespace=True, index_col=[0,1])

rawDescription: python pandas - map using 2 columns as reference

description: Python pandas - map using 2 columns as reference


rawDescription: Assigning a range to an array in Python

description: Assigning a range to an array in Python


code:
import importlib
module = importlib.import_module("foo")
obj = getattr(module, "bar")

rawDescription: Is there a way to import an object from python module programatically?


code:
import functools

class Memoized(object):
    """Decorator that caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned, and
    not re-evaluated.
    """

    cache = {}

    def __init__(self, func):
        self.func = func
        self.key = (func.__module__, func.__name__)
        self.cache[self.key] = {}

    def __call__(self, *args):
      try:
          return Memoized.cache[self.key][args]
      except KeyError:
          value = self.func(*args)
          Memoized.cache[self.key][args] = value
          return value
      except TypeError:
          # uncachable -- for instance, passing a list as an argument.
          # Better to not cache than to blow up entirely.
          return self.func(*args)

    def __get__(self, obj, objtype):
        """Support instance methods."""
        return functools.partial(self.__call__, obj)

    @staticmethod
    def reset():
        Memoized.cache = {}

rawDescription: What can be done to speed up this memoization decorator?


rawDescription: Pythonic way to add a list of vectors

description: Pythonic way to add a list of vectors


rawDescription: Implementation of TFIDF weighting scheme


code: root.bind("<Unmap>", lambda e: root.deiconify())

rawDescription: Remaximize Tkinter window in Python

description: Remaximize Tkinter window in Python


code:
import re

from django.conf import settings
from django.contrib.auth.decorators import login_required

class RequireLoginMiddleware(object):
    """
    Middleware component that wraps the login_required decorator around
    matching URL patterns. To use, add the class to MIDDLEWARE_CLASSES and
    define LOGIN_REQUIRED_URLS and LOGIN_REQUIRED_URLS_EXCEPTIONS in your
    settings.py. For example:
    ------
    LOGIN_REQUIRED_URLS = (
        r'/topsecret/(.*)$',
    )
    LOGIN_REQUIRED_URLS_EXCEPTIONS = (
        r'/topsecret/login(.*)$',
        r'/topsecret/logout(.*)$',
    )
    ------
    LOGIN_REQUIRED_URLS is where you define URL patterns; each pattern must
    be a valid regex.

    LOGIN_REQUIRED_URLS_EXCEPTIONS is, conversely, where you explicitly
    define any exceptions (like login and logout URLs).
    """
    def __init__(self):
        self.required = tuple(re.compile(url) for url in settings.LOGIN_REQUIRED_URLS)
        self.exceptions = tuple(re.compile(url) for url in settings.LOGIN_REQUIRED_URLS_EXCEPTIONS)

    def process_view(self, request, view_func, view_args, view_kwargs):
        # No need to process URLs if user already logged in
        if request.user.is_authenticated():
            return None

        # An exception match should immediately return None
        for url in self.exceptions:
            if url.match(request.path):
                return None

        # Requests matching a restricted URL pattern are returned
        # wrapped with the login_required decorator
        for url in self.required:
            if url.match(request.path):
                return login_required(view_func)(request, *view_args, **view_kwargs)

        # Explicitly return None for all non-matching requests
        return None

rawDescription: Best way to make Django's login_required the default

description: Make Django's login_required the default


rawDescription: Plotting two different arrays of different lengths


code:
present = Person.objects.values_list('Name', flat=True)
absent = set(names) - set(present)
# or, if you prefer named functions to the set operator '-'
absent = set(names).difference(present)

rawDescription: Can I filter a django model with a python list?

description: Filter a django model with a python list


code:
self.radio1 = wx.RadioButton(self, label="1 sec",pos=(35,35),)
self.Bind(wx.EVT_RADIOBUTTON, self.SetLab1, id=self.radio1.GetId())

self.radio2 = wx.RadioButton(self, label="2 sec",pos=(35,55))
self.Bind(wx.EVT_RADIOBUTTON, self.SetLab2, id=self.radio2.GetId())

self.radio3 = wx.RadioButton(self, label="4 sec",pos=(35,75))
self.Bind(wx.EVT_RADIOBUTTON, self.SetLab3, id=self.radio3.GetId())
global Delay
if Delay is not None:
     getattr(self,"radio"+str(int(Delay[1])-1)).SetValue(True)

rawDescription: wxPython: How the radio buttons can remember my choice when I close the frame

description: WxPython: How the radio buttons can remember my choice when I close the frame


code:
import logging
import inspect
import functools

def log_begin_end(func):
    """This is a decorator that logs the name of `func` (in capital letters).

    The name is logged at the beginning and end of the function execution.

    """
    @functools.wraps(func)
    def new_func(*args, **kwargs):

        logging.info("Start task " + func.__name__.upper())
        result = func(*args, **kwargs)
        logging.info("End task " + func.__name__.upper())
        return result

    return new_func

rawDescription: How to simplify python logging code

description: Simplify python logging code


code:
# create query
user_bf = db.aliased(users, name='user_bf')
userList = (
    users.query
    .add_column(db.func.count(friendships.user_id).label("total"))
    .add_column(user_bf.id.label("best_friend"))
    .add_column(user_bf.userName.label("best_friend_name"))
    .outerjoin(friendships, users.id == friendships.user_id)
    .outerjoin(user_bf, users.best_friend)
    .group_by(users.id)
    .order_by(db.func.count(friendships.user_id).desc())
    .paginate(1, 10, False)
)
for user in userList.items:
    print(user)

rawDescription: Build Model.query of a related model

description: Build Model.query of a related model


rawDescription: Remove elements from the array

description: Remove elements from the array


code:
from itertools import chain
print(*chain.from_iterable(a))

rawDescription: Python - How to transform a list of tuple to a tuple


code:
from itertools import takewhile
lis = ['Amazon', 'Apple', 'Microsoft', 'Google', 'Amazon', 'Ebay', 'Apple', 'Paypal', 'Google']
c = Counter(lis)
items = c.most_common()

rawDescription: Selecting all top words in Python list using Counter


code:
P = [1, 2, 0, 3]
Q = [7, 8]
[x+y for x,y in izip_longest(P, Q, fillvalue=0)]

rawDescription: Add two lists of different lengths in python, start from the right


rawDescription: Pandas: find column name and value with max (and second max) value for each row


code: r = re.match(r'(?P<File>.+?\.(?:cpp|h|c)) (?P<Function>\w+) (?P<Linenum>[0-9]+) (?P<Content>.*)$', line)

rawDescription: regular expression for tokenizing a white-space-delimitated string

description: Regular expression for tokenizing a white-space-delimitated string


code:
class BookView(FormView):
    form_class = BookForm

    def form_valid(self, form):
        book = form.save(commit=False)
        book.author = self.request.user
        book.save()

rawDescription: Django - 'Created by'-Field

description: Django - 'Created by'-Field


code:
done = False;
key_value_pairs = []
while not done:
    col_name = input("Enter the Column Name: ")
    if col_name == "":
         done = True
    col_type = input("Enter the Column Type: ")
    if col_type == "":
        done = True

    key_value_pairs.append((col_name, col_type))

rawDescription: Ask user for key:value pair in Python

description: Ask user for key:value pair in Python


rawDescription: Get URL and port number from view

description: Get URL and port number from view


code:
m2=[]
for i, (csum, counter) in enumerate(zip(countersum, gmcounter)):
    if csum == 2 and 2 in counter:
        m2.append(i)

rawDescription: return list indices if two conditions met in python

description: Return list indices if two conditions met in python


code:
def check_Results(board, win_comb):
    for each in win_comb:
        if (board[each[0]] == board[each[1]] and board[each[1]]== board[each[2]]):
            return 1
    return -1

rawDescription: Tic-tac-toe win detection system-Python

description: Tic-tac-toe win detection system-Python


code:
from Tkinter import *

def hide_me(event):
    event.widget.pack_forget()

root = Tk()
btn=Button(root, text="Click")
btn.bind('<Button-1>', hide_me)
btn.pack()
btn2=Button(root, text="Click too")
btn2.bind('<Button-1>', hide_me)
btn2.pack()
root.mainloop()

rawDescription: Lift and raise a Canvas over a Canvas in tkinter


code:
readers = []
devices = map(InputDevice, list_devices())
for dev in devices:
   if "深" in dev.name or "Barcode" in dev.name:
      readers.append(dev.fn)

devices = map(InputDevice, (readers))

rawDescription: Parameters of a function in python

description: Parameters of a function in python


rawDescription: split ndarray into chunks - whilst maintaining order

description: Split ndarray into chunks - whilst maintaining order


code:
expected = [False, False, True, True, False, False, False, False]
results = [character.isdigit() for character in numberplate]
if results == expected:
    # the digits are where we expect...
    pass

rawDescription: (Python 2.7) Data validation using try not working as expected


code: blobKey = blobstore.create_gs_key('/gs' + gcs_filename)

rawDescription: Get Public URL for File - Google Cloud Storage - App Engine (Python)


code: displayScore(score)

rawDescription: Adding Score Clock to Game in Python

description: Adding Score Clock to Game in Python


rawDescription: Python - append VS extend efficiency

description: Python - append VS extend efficiency


code:
def get_queryset(self):
    account_id = self.kwargs['account_id']

    # raise 404 if no account is found for the current user
    account = get_object_or_404(Account, pk=account_id, user=self.request.user)

    queryset = Transaction.objects.filter(account=account)
    return queryset

rawDescription: Restricting access to Django generic views


code: result = next(filter(None, text.rpartition('(')))

rawDescription: Exclude last matching portion of the text


rawDescription: Comparing and substitution of opposite

description: Comparing and substitution of opposite


code:
layout = QtGui.QHBoxLayout()
Right = QtGui.QVBoxLayout()
Left = QtGui.QVBoxLayout()

rawDescription: Change my Qdialog to QMainWindow

description: Change my Qdialog to QMainWindow