code:
import numpy as np
from scipy import signal

# Inputs
a = [[1,2,3],[3,4,5],[5,6,7],[4,8,9]]

# Convert to numpy array
arr = np.asarray(a,float)

# Define kernel for convolution
kernel = np.array([[0,1,0],
                   [1,0,1],
                   [0,1,0]])

# Perform 2D convolution with input data and kernel
conv_out = signal.convolve2d(arr, kernel, boundary='wrap', mode='same')/kernel.sum()

# Initialize output array as a copy of input array
arr_out = arr.copy()

# Setup a mask of zero elements in input array and
# replace those in output array with the convolution output
mask = arr==0
arr_out[mask] = conv_out[mask]

rawDescription: Python get get average of neighbours in matrix with na value


code:
import itertools

def do_the_needful(a,b):
    try:
        zipped = zip(a,b)
    except TypeError:
        # a and b are ints, not lists of ints
        zipped = [(a,b)]
    return itertools.chain.from_iterable(zip(*[[aa+bb, aa-bb] for aa,bb in zipped]))

def recurse_and_stuff(x):
    if len(x) == 1:
        return list(x[0])
        # if you only have to iterate through this, there's no
        # need to call `list(...)` here.
    return recurse_and_stuff([do_the_needful(x[i], x[i+1]) for i in range(0, len(x), 2)])

rawDescription: Retaining information through recursion under strict conditions (Python)


code: '[{}]'.format(', '.join(['{{{0[score]}-{0[numrep]}}}'.format(d) for d in lst]))

rawDescription: List of dictionaries - how to format print output


rawDescription: Persisting sha256 hash objects?

description: Persisting sha256 hash objects


rawDescription: Drag and drop application-created file to explorer window


code:
df.groupby(df['dates'].apply(lambda x: x.dayofweek)).sum()
df.groupby(df['dates'].apply(lambda x: 0 if x.dayofweek in [5,6] else 1)).sum()

rawDescription: How to group time series data by Monday, Tuesday .. ? pandas

description: Group time series data by Monday, Tuesday .. ? pandas


code:
import re
[int(x) if re.match(r'[-+]?\d+$', x) else 0 for x in values]

rawDescription: list comprehension that converts the numbers to integers and turns the non-numeric values into 0

description: List comprehension that converts the numbers to integers and turns the non-numeric values into 0


code: grouped.sum()[grouped.size() > 1]

rawDescription: better method to aggregate pandas dataframe by non matching criteria

description: Better method to aggregate pandas dataframe by non matching criteria


code:
new_band = np.zeros_like(myArray[0])

new_band[increasing_pixels==True] = 1
new_band[decreasing_pixels==True] = 2

rawDescription: python array processing: how to generate new values on pixel by pixel basis

description: Python array processing: how to generate new values on pixel by pixel basis


code:
def transposeListOfDicts(listOfDicts):
    keys = {}
    for d in listOfDicts:
        keys.update(d.iterkeys())

    return {key: [d.get(key, None) for d in listOfDicts] for key in keys}

rawDescription: Python: DictReader returning a list of dictionaries?


code:
file = open('FilePath/OUTPUT.01')
lines = file.read()
file.close()
with open("output.txt","w") as f:
    for match in re.finditer(r"(?m)^\s*-+\s+\S+\s+(-?[\d.]+E[+-]\d+)", lines):
        f.write(match.group(1)+"\n")

rawDescription: How to print out the line after the line found in re.compile()

description: Print out the line after the line found in re.compile()


code:
import pandas as pd
df = pd.read_csv("dup.csv")
ids = df["ID"]
df[ids.isin(ids[ids.duplicated()])].sort("ID")

rawDescription: How do I get a list of all the duplicate items using pandas in python?

description: Get a list of all the duplicate items using pandas in python


code:
a
b
out

rawDescription: Label regions with unique combinations of values in two numpy arrays?


code:
engrossment
graffiti
pathology

rawDescription: How to convert xml objects to python objects?

description: Convert xml objects to python objects


rawDescription: Python Regex to extract relative href links


code:
from operator import itemgetter
map(itemgetter('path'), T.itervalues())

rawDescription: Get all values from child elements of a dict as a list


rawDescription: matplotlib get axis-relative tick positions

description: Matplotlib get axis-relative tick positions


code:
def YYMMDD0FtoYYYYMMDD(date):
    return dt.datetime.strftime(dt.datetime.strptime(date, "%y%m%d0F"), "%Y-%m-%d")

rawDescription: python string to date ISO 8601

description: Python string to date ISO 8601


code:
index_map
master

rawDescription: make new python lists with indexes from items in a single list

description: Make new python lists with indexes from items in a single list


code:
point_type = [('x', float), ('y', float)]
points = np.array([(1,2), (3,4), (5,6)], dtype=point_type)
points
points[0]+points[1]

rawDescription: Namedtuple in Numpy

description: Namedtuple in Numpy


code:
from itertools import ifilterfalse
with open('/home/reserve/Desktop/s.txt', 'r+') as f:
    b = ifilterfalse(lambda x: x.startswith("%s:%s"%(args[1],sender.getName())),\
                    f.readlines())
    f.seek(0)
    f.truncate()
    f.writelines(list(x.strip() for x in b))

rawDescription: Deleting line that startswith in txt file?


code:
import pickle
d = pickle.load(open('hash_db.pickle', 'rb'))
d['3gcdshj754']['last scanned time'] = '11:30 11/10/2015'
pickle.dump(d, open('hash_db.pickle', 'wb'))

rawDescription: use pickle to save dictionary in python

description: Use pickle to save dictionary in python


code:
@app.route('/event/<int:id>/logo')
def event_logo(id):
    event = Event.query.get_or_404(id)
    return app.response_class(event.logo, mimetype='application/octet-stream')

rawDescription: Serve image stored in SQLAlchemy LargeBinary column


code:
class OverrideTests(threading.local):

    def __init__(self):
        super(OverrideTests, self).__init__()
        self.override = 0

    # rest of class same as before

override_tests = OverrideTests()

rawDescription: how do I make a 2.7 python context manager threadsafe

description: Make a 2.7 python context manager threadsafe


code:
from collections import OrderedDict
dct = OrderedDict((('light', ['on', 'off']), ('lock',['lock', 'unlock'])))
dct

rawDescription: PHP like array handling in Python: Indexing multidimensional array


code:
cmds.rowColumnLayout( numberOfColumns = 5 )
with neat_indent(".."):
    cmds.text( label="", width = 1 )
    cmds.text( label="Column 1", enable = False, width = 250 )
    cmds.text( label="", width = 1 )
    cmds.text( label="Column 2", enable = False, width = 250 )
    cmds.text( label="", width = 1 )

    cmds.text( label="" )

    cmds.rowColumnLayout( numberOfColumns = 4 )
    with neat_indent(".."):
        cmds.text( label="   Input data:", align="left" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.textField( text = "Text here" )
        cmds.text( label="" )
        cmds.text( label="" )
        cmds.text( label="" )

    cmds.text( label="" )
    cmds.rowColumnLayout( numberOfColumns = 4 )
    with neat_indent(".."):
        cmds.rowColumnLayout( numberOfColumns = 5 )
        with neat_indent(".."):
            cmds.radioButton( label = "Read file from path", width = 100 )
            cmds.text( label="" )
            cmds.button( label = "Browse" )
            cmds.text( label="" )
            cmds.button( label = "Validate" )

        cmds.text( label="" )
        cmds.text( label="" )
        cmds.text( label="" )

rawDescription: Is there a way to indent Python without affecting the code


code:
from django.dispatch import receiver
from django.db.models.signals import post_save
from datetime import datetime, timedelta

@receiver(post_save, sender=MyModel)
def model_expiration(sender, instance, created, **kwargs):
    if created:
         delete_model.apply_async(
            args=(instance.pk,),
            eta=datetime.utcnow() + timedelta(hours=24)
         )

rawDescription: Django Scheduled Deletion

description: Django Scheduled Deletion


code:
self.Size = QTableWidgetDisabledItem(self.MyTable)
self.MyTable.setItemDelegateForColumn(4,self.Size)

rawDescription: Set a whole column in `QTableWidget` read-only in python


code:
ns = range(2,8)
cm = plt.cm.get_cmap('spectral')
cmap = [cm(1.*i/len(ns)) for i in range(len(ns))]
for i,n in enumerate(ns):
    x = np.linspace(0, 10, num=n)
    y = np.zeros(n) + i
    c = np.tile(cmap[i], (len(x), 1))
    plt.scatter(x, y, c=c, edgecolor='none', s=50, label=n)
plt.legend(loc='lower left')
plt.show()

rawDescription: Matplotlib colormap bug with length-4 arrays


code:
cursor = self.ui.editor_window.textCursor()
textSelected = cursor.selectedText()

rawDescription: Select text of textEdit object with QTextCursor, QTextEdit


code:
import netifaces
netifaces.interfaces()

rawDescription: How can I get a list of network adapters with Python, on all OS platforms?

description: Get a list of network adapters with Python, on all OS platforms


code:
from nltk.corpus import wordnet as wn
dog = wn.synset('dog.n.1')
cat = wn.synset('cat.n.1')
car = wn.synset('car.n.1')
wn.path_similarity(dog, cat)
wn.path_similarity(dog, car)
wn.wup_similarity(dog, cat)
wn.wup_similarity(dog, car)
wn.lch_similarity(dog, car)
wn.lch_similarity(dog, cat)

rawDescription: How do I calculate the shortest path (geodesic) distance between two adjectives in WordNet using Python NLTK?

description: Calculate the shortest path (geodesic) distance between two adjectives in WordNet using Python NLTK


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

x = np.linspace(0, 2*np.pi, 100)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(x, np.sin(x))

ax.grid(True)
for tic in ax.xaxis.get_major_ticks():
    tic.tick1On = tic.tick2On = False
    tic.label1On = tic.label2On = False

plt.show()

rawDescription: Remove the x-axis ticks while keeping the grids (matplotlib)


code:
for elm in favs.getchildren()[0]:
    title = elm.getchildren()[0].text
    print ("id: %s secret: %s setname: %s") %(elm.get('id'), elm.get('secret'), title)

rawDescription: flickAPI: How do I list the sets for my user account?

description: FlickAPI: How do I list the sets for my user account


code:
import random
vec=[1,2,3,4,5]
for i in range(5):
    vec.append(10)
Matpreferences=[]
for i in range(10):
    v = vec[:]
    random.shuffle(v)
    Matpreferences.append(v)

rawDescription: Having problems with python's random.shuffle


code:
v = Vector(10, 20)
v
str(v)
v.x
v[0]

rawDescription: How do you control how an object is "seen" by other functions when passed as an argument?

description: Control how an object is "seen" by other functions when passed as an argument


code:
replacewith.update({'Potato':'Fish', 'Tomato':'Chips', '&': '&',})
replace_char("Potato & Tomato", replacewith)

rawDescription: Replacing characters in a string and returning in python


code:
# This assumes that you have a 2-dimensional array
zeros = np.zeros(shape, dtype=np.int32)
zeros[:sigma.shape[0], :sigma.shape[1]] = sigma

rawDescription: Python: Resize an existing array and fill with zeros


code: import f_file_handling

rawDescription: using Crontab to run simple Python file

description: Using Crontab to run simple Python file


code:
form_year = YearForm()
form_gender = GenderForm()
return render_to_response('report.html',
                            {
                                'form_year': form_year,
                                'form_gender': form_gender,
                                })

rawDescription: how to redirect form after submit

description: Redirect form after submit


code:
iprange = '192.0.0.2-4'
iprange.partition('-')
iprange.partition('-')[0].rpartition('.')
ip_start, _, end_value = iprange.partition('-')
first_three = ip_start.rpartition('.')[0]
ip_end = '{}.{}'.format(first_three, end_value)
ip_start
ip_end

rawDescription: Python Beginner split String in two strings


code:
# select region of interest from largest contour
ind1=where((x1>190.) & (y1>200.) & (y1<900.))[0]
ind2=where((x2>190.) & (y2>200.) & (y2<900.))[0]
figure(figsize=(10,10))
imshow(gray1,cmap=cm.gray, alpha=0.5);plot(x1[ind1],y1[ind1],'b-')
imshow(gray2,cmap=cm.gray, alpha=0.5);plot(x2[ind2],y2[ind2],'g-')
axis([0,1500,1000,0])

rawDescription: Affine transformation between contours in OpenCV


code:
mycwd = os.getcwd()
os.chdir("..")
#do stuff in parent directory
os.chdir(mycwd)     # go back where you came from

rawDescription: Is it possible to specify the previous directory python?


code:
for x, y in points:
    p = Point(x, y)

rawDescription: How to parse an item in a list containing two floats and omit its parentheses in Python

description: Parse an item in a list containing two floats and omit its parentheses in Python


rawDescription: summing the number of occurrences per day pandas

description: Summing the number of occurrences per day pandas


rawDescription: Stripping an dynamic url content

description: Stripping an dynamic url content


code:
from decimal import Decimal
"{0:.20f}".format(Decimal('0.1'))

rawDescription: Indexing float values in Python

description: Indexing float values in Python


code: html = browser.page_source

rawDescription: How can i get html from selenium.webdriver in Python?

description: Get html from selenium.webdriver in Python


rawDescription: Convert string to integer using map()

description: Convert string to integer using map()


code:
message = []

for c, k in zip(cipherText1.split(), key1.split()):
    newval = int(c, 2) ^ int(k, 2)
    message.append(format(newval, '08b'))

print(' '.join(message))

rawDescription: "IndexError: string index out of range" with a Python Program


code: val = cache.setdefault('the-key', calculate_value('the-key'))

rawDescription: Best idom to get and set a value in a python dict


code:
line = reader.next()
like_this = check_how_is_my(line)
if like_this == 'something_long':
    spaces = 23
else:
    spaces = 0

while True:
    try:
        print_with_spaces(line, spaces)
        reader.next()
    except StopIteration:
        break

rawDescription: Python csvreader separate lines

description: Python csvreader separate lines


code:
with open(filename, 'r') as f:
    data = f.read()
# fix image links
img = re.compile(r'src="[\./]*static/([^"]*)"')
data = img.sub(lambda m: (r'src="' + prefix + 'static/images/' +
                          m.group(1) + r'"'), data)
with open(filename, 'w+') as of:
    of.write(data)

rawDescription: Converting Script from Powershell to Python-Regex Not Working as Expected


code:
sprite = pyglet.sprite.Sprite(pyglet.image.load('./roar.png'))
sprite.draw() # This is instead of blit. Position is done via sprite.x = ...

rawDescription: Pyglet Image Rendering

description: Pyglet Image Rendering


code:
clf.tree_.children_left #array of left children
clf.tree_.children_right #array of right children
clf.tree_.feature #array of nodes splitting feature
clf.tree_.threshold #array of nodes splitting points
clf.tree_.value #array of nodes values

rawDescription: How do I find which attributes my tree splits on, when using scikit-learn?

description: Find which attributes my tree splits on, when using scikit-learn


code: result =  attribute_a + attribute_b if isinstance(attribute_a,(int,float)) else numpy.array([ attribute_a[i] + attribute_b[i] for i in range(len(attribute_a)) ])

rawDescription: python: automatically differentiate between list / tuple / array and int / float

description: Python: automatically differentiate between list / tuple / array and int / float


rawDescription: Determine if given class attribute is a property or not, Python object


code:
def generate(start=0, stop=None):
    i = start

    if stop == None:
        condition = lambda _: True
    else:
        condition = lambda x: x <= stop

    while condition(i):
        yield i
        i += 1

rawDescription: Assigning a condition to a variable in Python


code:
import os.path
p = "/tmp/999/123.tif"
dir, filename = os.path.basename(os.path.dirname(p)), os.path.basename(p)

rawDescription: Directory Name + File Name to Text File

description: Directory Name + File Name to Text File


code:
from django.db import models

class MyModel(models.Model):
    firstname = models.CharField(max_length=20)
    lastname = models.CharField(max_length=20)

rawDescription: django poplulate html form

description: Django poplulate html form


rawDescription: Can someone explain to me what python is doing here?


code:
import random

name = ['Hans', 'Peter', 'Eliza']
print('Your name is {}!'.format(random.choice(name)))

rawDescription: How to save a random string from a list of strings?

description: Save a random string from a list of strings


code:
def my_autopct(pct):
    return ('%.2f' % pct) if pct > 20 else ''

ax.pie(df[col], labels=df.index, autopct=my_autopct, colors=colors)

rawDescription: Conditional removal of labels in Matplotlib pie chart


rawDescription: How can I sum an interval of elements on an array in python / numpy?

description: Sum an interval of elements on an array in python / numpy


rawDescription: Making a wxPython application multilingual


code:
def merge_pairs(a):
    out = []
    i = 0
    while i < len(a):
        if i < len(a) - 1 and a[i] == a[i + 1]:
            out.append(a[i] + a[i + 1])
            i += 2
        else:
            out.append(a[i])
            i += 1
    out += [0] * (len(a) - len(out))
    return out

rawDescription: merge values in list

description: Merge values in list


code:
self.stat_lbl.setStyleSheet('QLabel {color: #112233;}')
self.stat_lbl.setText('This is colored text')

rawDescription: Set label font color from hex value

description: Set label font color from hex value


code:
parser = qparser.QueryParser("fieldname", my_index.schema)
parser.add_plugin(qparser.FuzzyTermPlugin())

rawDescription: python fuzzy text search

description: Python fuzzy text search


code:
self.stim = (
    (firstParam, secondparam, thirdparam),
    (firstParam2, secondparam2, thirdparam2),
    (firstParam3, secondParam3, thirdParam3)
)

rawDescription: Is there a more pythonic way of storing parameters so they can be used in a function call?


code:
import numpy as np

from scipy.io.netcdf import netcdf_file

# Define some dummy data
time_arr = range(10)
lat_arr = np.array([30.5, 40., 40.5])
lon_arr = np.array([200., 203., 206.])
ntim, nlat, nlon = len(time_arr), len(lat_arr), len(lon_arr)

fog_arr = np.random.randn(ntim,nlat,nlon)

# Write out data to a new netCDF file with some attributes
filename = netcdf_file('./tmp_netcdf.nc', 'w')

# Dimensions
filename.createDimension('time', ntim)
filename.createDimension('lat', nlat)
filename.createDimension('lon', nlon)

# Variables
time = filename.createVariable('time', 'i', ('time',))
lat = filename.createVariable('lat', 'f4', ('lat',))
lon = filename.createVariable('lon', 'f4', ('lon',))
fog = filename.createVariable('fog', 'f4', ('time', 'lat', 'lon',))

# Attributes
time.units = 'decades since 1950'
lat.units = 'degrees north'
lon.units = 'degrees east'
fog.units = 'change in hours'
fog.missing_val = 1e20
fog.valid_min = np.min(fog_arr)

# Populate the variables with data
time[:] = time_arr
lat[:] = lat_arr
lon[:] = lon_arr
fog[:,:,:] = fog_arr[:,:,:]

filename.close()

rawDescription: How to write variable attributes in NetCDF file using python

description: Write variable attributes in NetCDF file using python


code: my_function(*map(int, list))

rawDescription: Unpack list and cast at the same time

description: Unpack list and cast at the same time


rawDescription: how to create a sub list for a specific string in a nested list

description: Create a sub list for a specific string in a nested list


code: a_s, b_s, c_s = map(list, u)

rawDescription: Sort multiple lists simultaneously

description: Sort multiple lists simultaneously


rawDescription: Rescale a numpy array

description: Rescale a numpy array


rawDescription: python - web scraping - return attributes from inside a class

description: Python - web scraping - return attributes from inside a class


rawDescription: Format APNS-style JSON message in Python for use with Amazon SNS


code:
nouns = load_nouns()

def load_nouns():
    infile = open('Noun.txt', 'r')
    nouns = infile.readlines()
    infile.close()
    return nouns

def get_noun():
    index = 0
    while index < len(nouns):
        nouns[index] = nouns[index].rstrip('\n')
        index += 1
    noun = random.choice(nouns)
    return noun

def Cake():
    print("The", get_noun(), "is a", get_noun())

def XistheNew():
    print(get_noun(), "is the new", get_noun())

def get_Sentence():
    num = random.randrange(1, 3)
    if num == 1:
        Cake()
    elif num == 2:
        XistheNew()

rawDescription: Using a loop to make a random sentence generator


code:
# Split the 'Name' column as a Series, setting the appropriate name and index.
split_names = df['Name'].str.split(', ', expand=True).stack()
split_names.name = 'Name'
split_names.index = split_names.index.get_level_values(0)

# Drop the existing 'Name' column, and join the split names.
df.drop('Name', axis=1, inplace=True)
df = df.join(split_names)

rawDescription: DataFrame transformation in Python Pandas


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.plot(range(10), color='red', lw=3)
# Placing the text in data coordinates...
ax.text(5, 5, 'Test', color='white', fontsize=45,
        bbox={'facecolor':'black', 'pad':12})

plt.show()

rawDescription: How to put pylab.plot line over pylab.figtext?

description: Put pylab.plot line over pylab.figtext


code:
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

fig, ax = plt.subplots()

ax.xaxis_date()
ax.set_xlim(dt.datetime(2015, 1, 1), dt.datetime(2015, 6, 1))

ax.format_xdata = lambda d: mdates.num2date(d).strftime('%d/%m/%y %H:%M')

plt.show()

rawDescription: Matplotlib : Default Resolution of Plot Mouse-over Values


code:
inputlist = '''\
city:NewYork population:30 area:1000
city:LosAngles population:3 area:500
'''.splitlines()
[dict(item.split(':') for item in value.split()) for value in inputlist]

rawDescription: how to convert list containing ' : ' to dictionary in python

description: Convert list containing ' : ' to dictionary in python


rawDescription: Flask redirecting multiple routes

description: Flask redirecting multiple routes


code: df1 = df.set_index('Date/Time')

rawDescription: Getting the average of a certain hour on weekdays over several years in a pandas dataframe


code:
from subprocess import PIPE,Popen

p = Popen(["sudo", "-s", "-S"], stdin=PIPE, stdout=PIPE, universal_newlines=True)

p.stdin.write("password\n")
p.stdin.write("mkdir foo\n")
p.stdin.write("id -u")

rawDescription: run Python file with root permission via php

description: Run Python file with root permission via php


code:
a = numpy.float64(42.)
numpy.isnan(a).any()
a = numpy.float64(numpy.nan)
numpy.isnan(a).any()

rawDescription: Detect if a NumPy array contains at least one non-numeric value?


code:
espf_atual = 0
...
espf_atual += 1
...
espf2 += [espf_atual]

rawDescription: Sum of specific elements in a list, if they are consecutive (python)


code:
def write(self, cr, uid, ids, vals, context=None):
        partner_id=vals.get('partner_id')
        quotation_obj=self.browse(cr, uid, ids,context=context)

        if not partner_id:
            #if partner id not found, find the employee ids
            emp_ids=vals.get('employee_ids')
            if emp_ids:
#                 for line in emp_ids:
#                     employee_ids=line[2]
#             else:#update the employee ids
#                 employee_ids=quotation_obj.employee_ids
                for line in emp_ids:
                    self.pool.get('res.partner').write(cr, uid, quotation_obj.partner_id.id, {'employee_ids': [(4, line[2])]}, context=context)
        if partner_id:
            emp_ids=vals.get('employee_ids')
            if emp_ids:
                for line in emp_ids:
                    self.pool.get('res.partner').write(cr, uid, partner_id, {'employee_ids': [(4, line[2])]}, context=context)

        if partner_id:
            count = quotation_obj.number_of_edits + 1
            vals.update({'number_of_edits': count})

        return super(sale_order, self).write(cr, uid, ids, vals, context=context)

rawDescription: How to count the 'number of time a field is edited or updated' in Odoo 8?

description: Count the 'number of time a field is edited or updated' in Odoo 8


rawDescription: python matplotlib save plot

description: Python matplotlib save plot


code: function = lambda x: expression_here

rawDescription: Python string vowel counter

description: Python string vowel counter


rawDescription: Reversing names in pandas

description: Reversing names in pandas


code:
user_haslocations = has_location.objects.filter(user_has=user)
locations = Location.objects.filter(id__in=user_haslocations.values('location_id'))

rawDescription: django model object filter

description: Django model object filter


code:
g = df.groupby("node")
g["comp"].value_counts()
g["precedingWord"].value_counts()

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


code:
@route('/locations/:lat/:lng', method='GET')
def get_location(lat,lng):
    response.content_type = 'application/json'
    objdb = db.locations.find({'coordinate2d': {'$near': [lat,lng]}}, {'coordinate2d':bool(1)}).skip(0).limit(3)
    entries = [entry for entry in objdb]
    return MongoEncoder().encode(entries)

rawDescription: Python/Bottle/MongoDB: Unsupported response type: <type 'dict'>


code: df['increasing'] = np.select(conditions, choices, default=2)

rawDescription: New colum in pandas, based on another colums last value


rawDescription: Understanding the syntax of numpy.r_() concatenation


code:
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import matplotlib.ticker as ticker

def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues, labels=None):
    fig = plt.figure()
    ax = fig.add_subplot(111)

    # I also added cmap=cmap here, to make use of the
    # colormap you specify in the function call
    cax = ax.matshow(cm,cmap=cmap)
    plt.title(title)
    fig.colorbar(cax)
    if labels:
        ax.set_xticklabels([''] + labels)
        ax.set_yticklabels([''] + labels)

    ax.xaxis.set_major_locator(ticker.MultipleLocator(1))
    ax.yaxis.set_major_locator(ticker.MultipleLocator(1))

    plt.xlabel('Predicted')
    plt.ylabel('True')
    plt.savefig('confusionmatrix.png')

rawDescription: Matplotlib matshow with many string labels


rawDescription: Using Xpath in Scrapy to select any text below paragraph


code:
#foo.py
def some_fn():
    return 'some_fn'

class Foo(object):
    def method_1(self):
        return some_fn()

#bar.py
import foo
class Bar(object):
    def method_2(self):
        tmp = foo.Foo()
        return tmp.method_1()

#test_case_1.py
import bar
from mock import patch

@patch('foo.some_fn')
def test_bar(mock_some_fn):
    mock_some_fn.return_value = 'test-val-1'
    tmp = bar.Bar()
    assert tmp.method_2() == 'test-val-1'
    mock_some_fn.return_value = 'test-val-2'
    assert tmp.method_2() == 'test-val-2'

rawDescription: Using python's mock patch.object to change the return value of a method called within another method


code: critics = {i:sales_dict.copy() for i in ID}

rawDescription: re reading a csv file in python without loading it again

description: Re reading a csv file in python without loading it again


code:
def click_1(text):
    key_1 = word.index [letter]
    # word.index(letter) calls the function,
    # word.index[letter] tries to treat the function like a dictionary
    # and pull up its value attached to the key `letter`
    hidden_word[key_1] = letter
    print (hidden_word)

rawDescription: How to reference a string in a list in python

description: Reference a string in a list in python


code:
from cartopy.mpl.patch import geos_to_path
import itertools

paths = list(itertools.chain.from_iterable(geos_to_path(geom)
                                             for geom in geoms))

rawDescription: 3D CartoPy similar to Matplotlib-Basemap


code:
expected_list = [1, 2, 3, 4]
output_list = calc_mortgage([10, 20, 30, 42])
self.assertEqual(expected_list, output_list)

rawDescription: Using Python Unittest to test results in an array


code: result = members.merge(df, on="groupID", suffixes=("_member", "_group"))

rawDescription: using pandas to create new columns based on intra-group rank-order

description: Using pandas to create new columns based on intra-group rank-order


code:
def get_even_lists(lst):
    """ (list of list of int) -> list of list of int

    Return a list of the lists in lst that contain only even integers.

    >>> only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]])
    [[4, 0, 6], [2]]
    """
    return [sublst for sublst in lst if all(i % 2 == 0 for i in sublst)]

rawDescription: How to get only even numbers from list

description: Get only even numbers from list


code: format(7, 'b')

rawDescription: Taking a binary input from the user in python for bitwise operations


rawDescription: How to efficiently convert Matlab engine arrays to numpy ndarray?

description: Efficiently convert Matlab engine arrays to numpy ndarray


code: print(v.get_text(' ', strip=True))

rawDescription: Unable to scrape the text from a certain LI element


code:
A=sparse.csr_matrix([0,1,2,0,0,1])
B=sparse.csr_matrix([0,0,0,1,0,1])
C=sparse.csr_matrix([1,0,0,0,1,0])
sparse.vstack([A,B,C])
sparse.vstack([A,B,C]).A
sparse.hstack([A,B,C]).A
np.vstack([A.A,B.A,C.A])

rawDescription: How to hstack several sparse matrices (feature matrices)?

description: Hstack several sparse matrices (feature matrices)


rawDescription: Interchange ordering of 4-D Numpy array

description: Interchange ordering of 4-D Numpy array


code:
for key in sorted(d):
    value = d[key]

rawDescription: Recurse through dictionary of dictionaries, always starting from the top


code:
def vectorized_app1(A, w, Lx, Ly, Lz ):
    M,N,R = A.shape
    p1 = np.arange(M)[:,None,None]/Lx
    p2 = np.arange(N)[:,None]/Ly
    p3 = np.arange(R)/Lz
    return A/(w*(p1 + p2 + p3))

def vectorized_app2(A, w, Lx, Ly, Lz ):
    M,N,R = A.shape
    X,Y,Z = np.ix_(np.arange(M),np.arange(N),np.arange(R))
    return A/(w*((X/Lx) + (Y/Ly) + (Z/Lz)))

def original_app(A, w, Lx, Ly, Lz ):
    out = np.empty_like(A)
    M,N,R = A.shape
    for i in range(M):
        for j in range(N):
            for k in range(R):
                out[i,j,k] = A[i,j,k]/(w*( (i / Lx) + (j / Ly) + (k / Lz) ))
    return out

rawDescription: Applying function that cares about index to every element of numpy array


code:
s = ',>,<[>[->+>+<<]>>[-<<+>>]<<<-]>>.'

def brainfuck2list(brainfuck):
  while brainfuck:               #if list is empty then finish
    e = brainfuck.pop(0)
    if e not in ("[","]"):
      yield e
    elif e == "[":
      yield list(brainfuck2list(brainfuck))
    else:
      break

[_ for _ in brainfuck2list(list(s))]

rawDescription: Tokenizing a string into a list of nested arrays with Python


code:
import binascii
binascii.hexlify(x)

rawDescription: Python string in pure hex form

description: Python string in pure hex form


code: results = [ x for x in j if x["parentSubject"]["code"] == "soggetto1" ]

rawDescription: JSON GET Request with Python

description: JSON GET Request with Python


code:
@hybrid_property
def has_a_boy_child(self):
    return any(child.is_boy for child in self.children)

@has_a_boy_child.expression
def has_a_boy_child(cls):
    return (
        select([func.count(Child.id)])
        .where(Child.parent_id == cls.id)
        .where(Child.is_boy == True)
        .label("number_of_boy_children")
    )

rawDescription: How do I write a Hybrid Property that depends on a column in children relationship?

description: Write a Hybrid Property that depends on a column in children relationship


rawDescription: Why are hex digits not passed correctly in python subprocess


rawDescription: Save a subdomain name to String

description: Save a subdomain name to String


code: image = self.create_image(spinner)

rawDescription: Using Gtk.spinner with a long time function


code: df

rawDescription: python dataframe convert week number to month

description: Python dataframe convert week number to month


code:
parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.parse_known_args(['--foo', '42', '--spam', 'eggs'])

rawDescription: How can I use python command line arguments that change at run time?

description: Use python command line arguments that change at run time


code: keys = sorted(var.keys(), key=lambda k: int(k[3:]))

rawDescription: Pythonic iteration over multiple lists in parallel


code:
field_names = [field.name for field in Ether.fields_desc]
fields = {field_name: getattr(frame, field_name) for field_name in field_names}

rawDescription: Iterating over fields of a layer in Scapy


code: newList = [elem for word in myList for elem in word.partition('\n') if elem]

rawDescription: Extend a list based on its contents

description: Extend a list based on its contents


code:
def ticker():
    x = input('Ticker: ')
    if x in d.keys():
        return d[x]
    else:
        return 'No entry'

rawDescription: Printing a dictionary value of a function in another function


code:
final_lines = final.splitlines()
final = final_lines[0] + '\n' + ''.join(final_lines[1:])

rawDescription: How to remove the unwanted character like white spaces and newline from a string

description: Remove the unwanted character like white spaces and newline from a string


code:
stacks = [[[1, 2, 3]], [[4, 5, 6], [1, 2, 3]]]
total = [sum(x[1] for x in w) for w in stacks]
total

rawDescription: Sum concisely particular elements in a list of lists


code: re.sub(pattern, repl, string, count=0, flags=0)

rawDescription: Replacing multiple similar strings

description: Replacing multiple similar strings


rawDescription: Setting aspect ratio of 3D plot

description: Setting aspect ratio of 3D plot


code:
search_string = '; Q8CCS6'
search_string.replace(' ', '')
search_string = search_string.replace(' ', '')
search_string
df
df[df['Proteins'].str.contains(search_string, na=False)]

rawDescription: python - pandas dataframe string search - problems with ";" ?

description: Python - pandas dataframe string search - problems with ";"


code:
import numpy as np

L = 80.0
N = 2 ** np.arange(-4, 10, dtype=np.float64)
dx = L / N

rawDescription: python: dividing a number by a numpy array

description: Python: dividing a number by a numpy array


code:
class CourseDetail(models.Model):
    course      = models.ForeignKey(Course)
    date        = models.DateField(blank=True, null=True)
    renew_date  = models.DateField(blank=True, null=True, default=None)
    attendance  = models.ManyToManyField(Employee, through='CourseDetailAttendance')

    class Meta:
        unique_together = ('course', 'date')

rawDescription: Queryset across fours models

description: Queryset across fours models


code:
@app.route("/user", methods=("POST",))
def save_user():
    data = request.form
    # ... etc. ...

rawDescription: Getting Form data with Flask

description: Getting Form data with Flask


code:
import datetime
datetime.datetime.now()
datetime.datetime.now().day
datetime.datetime.now() - datetime.timedelta(days=3)

rawDescription: In Python Create A Numeric Date/Time Representation


code:
@register.filter
def up_voted_by(obj, user):
    return obj.upvoted_by(user)

rawDescription: How to check if some post was voted for by the current user in a list

description: Check if some post was voted for by the current user in a list


code:
def window_stack(a, stepsize=1, width=3):
    n = a.shape[0]
    return np.hstack( a[i:1+n+i-width:stepsize] for i in range(0,width) )

rawDescription: sliding window in numpy

description: Sliding window in numpy


code:
from sqlalchemy.sql.functions import ReturnTypeFromArgs

class unaccent(ReturnTypeFromArgs):
    pass

rawDescription: SQLALCHEMY ignore accents on query

description: SQLALCHEMY ignore accents on query


code: thing1 = MyThing(lambda t, y, u: my_ode(t, y, u, 10.0, 0.5), 0.0)

rawDescription: Passing parameterized function handle in Python


code: print ("You entered: %s"%input('Enter something:'))

rawDescription: print variable and string

description: Print variable and string


code:
import re
text = 'school.department.classes[cost=15.00].name'
re.split(r'\.(?!\d)', text)

rawDescription: splitting a dot delimited string into words but with a special case

description: Splitting a dot delimited string into words but with a special case


code:
def sct(from_date=datetime.datetime.now().date()):
    value = getValueByDate(from_date)

rawDescription: datetime.datetime.now() returns old value

description: Datetime.datetime.now() returns old value


rawDescription: Converting Decimal to %

description: Converting Decimal to %


code:
unq_idx = np.split(sort_idx, np.cumsum(unq_count))
unq_idx

rawDescription: Grouping indices of unique elements in numpy


rawDescription: Using Python to manipulate data from a CSV only applying it to the first result


rawDescription: Pandas: run length of NaN holes

description: Pandas: run length of NaN holes


code:
class CorrectionHandler(webapp2.RequestHandler):
    def post(self):
        polyhedron_object_key = self.request.get("key")
        polyhedron_object = ndb.Key(urlsafe=polyhedron_object_key).get()
        polyhedron_object.color = self.request.get('color')

rawDescription: How do I return the key of an appengine datastore object from the template in index.html?

description: Return the key of an appengine datastore object from the template in index.html


code: return result[1], result[0][1], result[0][0]

rawDescription: Find the row and column with the min value in python?


code:
comp = re.compile("Identifier #: \s* (.*tif)")
def get_id_from_string(s):
    ids = re.search(comp, s)
    return ids[0]
paragraphs.sort(key=get_id_from_string)

rawDescription: Sort paragraphs in a text file alphabetically using Python


code:
window.addstr()
window.refresh()

rawDescription: Highlighting and Selecting text with Python curses


rawDescription: How do I order a file of scores in Python?

description: Order a file of scores in Python


code:
ugly =  (1,2,4,3)
for combo in product(*map(set, zip(good, bad, ugly))):
    print(combo)

rawDescription: all combinations of differences of two lists

description: All combinations of differences of two lists


code:
def onload(sender, args):
    time.sleep(2)
    Program.SetState(state)
    raw_input()

def main():
    ...
    Program.RunGUI(onload)

rawDescription: Controlling a C# Winforms GUI with IronPython


code:
from django import forms
from django.contrib import admin
from models import Contest, Contestant, ContestResults

# Generates a function that sequentially calls the two functions that were
# passed to it
def func_concat(old_func, new_func):
    def function():
        old_func()
        new_func()
    return function

# A dummy widget to be replaced with your own.
class OrderedManyToManyWidget(forms.widgets.TextInput):
    pass

# A simple CharField that shows a comma-separated list of contestant IDs.
class ResultsField(forms.CharField):
    widget = OrderedManyToManyWidget()

class ContestAdminForm(forms.models.ModelForm):
    # Any fields declared here can be referred to in the "fieldsets" or
    # "fields" of the ModelAdmin. It is crucial that our custom field does not
    # use the same name as the m2m field field in the model ("contestants" in
    # our example).
    results = ResultsField()

    # Be sure to specify your model here.
    class Meta:
        model = Contest

    # Override init so we can populate the form field with the existing data.
    def __init__(self, *args, **kwargs):
        instance = kwargs.get('instance', None)
        # See if we are editing an existing Contest. If not, there is nothing
        # to be done.
        if instance and instance.pk:
            # Get a list of all the IDs of the contestants already specified
            # for this contest.
            contestants = ContestResults.objects.filter(contest=instance).order_by('rank').values_list('contestant_id', flat=True)
            # Make them into a comma-separated string, and put them in our
            # custom field.
            self.base_fields['results'].initial = ','.join(map(str, contestants))
            # Depending on how you've written your widget, you can pass things
            # like a list of available contestants to it here, if necessary.
        super(ContestAdminForm, self).__init__(*args, **kwargs)

    def save(self, *args, **kwargs):
        # This "commit" business complicates things somewhat. When true, it
        # means that the model instance will actually be saved and all is
        # good. When false, save() returns an unsaved instance of the model.
        # When save() calls are made by the Django admin, commit is pretty
        # much invariably false, though I'm not sure why. This is a problem
        # because when creating a new Contest instance, it needs to have been
        # saved in the DB and have a PK, before we can create ContestResults.
        # Fortunately, all models have a built-in method called save_m2m()
        # which will always be executed after save(), and we can append our
        # ContestResults-creating code to the existing same_m2m() method.
        commit = kwargs.get('commit', True)
        # Save the Contest and get an instance of the saved model
        instance = super(ContestAdminForm, self).save(*args, **kwargs)
        # This is known as a lexical closure, which means that if we store
        # this function and execute it later on, it will execute in the same
        # context (i.e. it will have access to the current instance and self).
        def save_m2m():
            # This is really naive code and should be improved upon,
            # especially in terms of validation, but the basic gist is to make
            # the needed ContestResults. For now, we'll just delete any
            # existing ContestResults for this Contest and create them anew.
            ContestResults.objects.filter(contest=instance).delete()
            # Make a list of (rank, contestant ID) tuples from the comma-
            # -separated list of contestant IDs we get from the results field.
            formdata = enumerate(map(int, self.cleaned_data['results'].split(',')), 1)
            for rank, contestant in formdata:
                ContestResults.objects.create(contest=instance, contestant_id=contestant, rank=rank)
        if commit:
            # If we're committing (fat chance), simply run the closure.
            save_m2m()
        else:
            # Using a function concatenator, ensure our save_m2m closure is
            # called after the existing save_m2m function (which will be
            # called later on if commit is False).
            self.save_m2m = func_concat(self.save_m2m, save_m2m)
        # Return the instance like a good save() method.
        return instance

class ContestAdmin(admin.ModelAdmin):
    # The precious fieldsets.
    fieldsets = (
        ('Basic Info', {
            'fields': ('name', 'results',)
        }),)
    # Here's where we override our form
    form = ContestAdminForm

admin.site.register(Contest, ContestAdmin)

rawDescription: Ordered ManyToManyField that can be used in fieldsets


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

data = (('a','b',50), ('b','c',60), ('b','e',25),
        ('e','f',20), ('z','n',10), ('x','m',25),
        ('v','p',15))

G = nx.DiGraph()
for node1, node2, weight1 in data:
    G.add_edge(node1, node2, weight=-1)

min_lenght = 2
F = nx.DiGraph()   #filtered graphs

# check all edges with bellman_ford
for u, v in G.edges():
    vals, distances = nx.bellman_ford(G, u)
    if min(distances.values()) < - min_lenght:
        for u, v in vals.items():
            if v:
                F.add_edge(v, u)

nx.draw(F)
plt.show()

rawDescription: Python NetworkX MatplotLib DiGraph Find all Trees with a path longer than two


code: df.merge(df2, on=["First", "Last"], how='outer', suffixes=('', '_new'), right_index=True)

rawDescription: Combining data with overlap

description: Combining data with overlap


code: Нұрсұлтан_Әбішұлы_Назарбаев

rawDescription: Convert string saved in hex format to its previous form in python


code:
app = ExampleApp(root)
app.pack()

rawDescription: Tkinter: Draw rectangle using a mouse

description: Tkinter: Draw rectangle using a mouse


code:
import os
import tempfile
import zipfile

new_files = []
for _ in range(10):
    file_descriptor, file_path = tempfile.mkstemp(".txt", "prefix-", "/tmp")
    file_handle = open(file_path, "wb")
    file_handle.write("HELLO")
    os.close(file_descriptor)
    file_handle.close()
    new_files.append(file_path)

with zipfile.ZipFile("/tmp/zipped.zip", "w") as zipped:
    for file_path in new_files:
        zipped.write(file_path, os.path.basename(file_path))

rawDescription: Create multiply amount of files with random names in python and zip them


code:
if day.find('Sat') > -1:
    print('Sat')

rawDescription: Checking if today is a Wed or Sat with java.util.Calendar


code:
A = [1,2,3,4,5,6,7,8,9,10]
B = [11,12,13,14,15]
N = ['a','b','c','d','e','f','g','h','i','j']
for a,name in zip(A,N):
    results = []
    for b in B:
        result = a + b
        results.append(result)
    filename = '{}.txt'.format(name)
    with open( filename , 'w') as f:
       for res in results:
           f.write(str(res)+'\n')

rawDescription: writing multiple out files from for loop

description: Writing multiple out files from for loop


rawDescription: Quick Method for Sorting User Defined Classes


code:
# global variable
gold = 500

def level1() :
  # specify that you want to use the global instance of gold
  global gold
  # do your stuff here

def level2() :
  global gold
  # do your stuff here

rawDescription: Variables in Python: Add and change variables


rawDescription: urlparse.urlparse returning 3 '/' instead of 2 after scheme

description: Urlparse.urlparse returning 3 '/' instead of 2 after scheme


rawDescription: Replacing characters in string by whitespace except digits


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.colors as colors

n_points = 100
x = np.random.normal(0, 2, n_points)
y = np.random.normal(0, 2, n_points)

hist, xedges, yedges = np.histogram2d(x, y, bins=np.sqrt(n_points))

# Following your data reduction process
xpos, ypos = np.meshgrid(xedges[:-1], yedges[:-1])

length, width = 0.4, 0.4
xpos = xpos.flatten()
ypos = ypos.flatten()
zpos = np.zeros(n_points)
dx = np.ones(n_points) * length
dy = np.ones(n_points) * width
dz = hist.flatten()

# This is where the colorbar customization comes in
dz_normed = dz / dz.max()
normed_cbar = colors.Normalize(dz_normed.min(), dz_normed.max())
# Using jet, but should work with any colorbar
color = cm.jet(normed_cbar(dz_normed))

fig3D = plt.figure()
ax3D = fig3D.add_subplot(111, projection='3d')
ax3D.bar3d(xpos, ypos, zpos, dx, dy, dz, color=color)
plt.show()

rawDescription: 3D histograms and Contour plots Python

description: 3D histograms and Contour plots Python


code: file_text = (lambda default, inp: default if inp.lower() == default else inp)("a.txt", raw_input("File name(a.txt):"))

rawDescription: Python Input validation

description: Python Input validation


code:
full_index = []
for g in all_genders:
  for s in all_states:
    for m in all_months:
      full_index.append((g, s, m))
df = df.set_index(['Gender', 'State', 'Month'])
df = df.reindex(full_index) # fill in all missing values

rawDescription: value from a past, potentially missing month in dataframe

description: Value from a past, potentially missing month in dataframe


code:
if match("hello world how are you what are you doing",
         include_words=["world", "how are"],
         exclude_words=["tigers", "bye bye"]):
    print('matches')

rawDescription: Python text search library

description: Python text search library


rawDescription: Make a list of 50 random numbers in the range 1-50, such that adjacent numbers are not within 15 of each other


code:
for i in forrange(10):
    print(i)
    if i == 3:
        i.update(7)

rawDescription: How do I use a C-style for loop in Python?

description: Use a C-style for loop in Python


code: isinstance(currentValue, (int, long, float))

rawDescription: Python: integer precision and type checking


code: results = [x[1] for x in re.findall(r"href *= *(\"|\')(.*?)\1", lines)]

rawDescription: Python Regex returning Empty Strings instead of Results


code:
import csv
from collections import defaultdict
from dateutil import parser

def test_results(filename):
    with open(filename, "rU") as f:
        reader = csv.reader(f, delimiter="\t")
        result = defaultdict(list)
        # Skip header line
        next(reader)
        for row in reader:
            result[row[0]].append(parser.parse(' '.join(row[1:])))

rawDescription: Appending input from csv file to a dictionary including duplicate values for a unique key


rawDescription: How to check if a list has an empty string

description: Check if a list has an empty string


rawDescription: Fast matrix transposition in Python

description: Fast matrix transposition in Python


code:
class IntArray(ctypes.Array):
    _type_ = ctypes.c_int
    _length_ = 10

a = IntArray(*range(10))
a_list = a[:]

rawDescription: Determining whether an object is a ctypes array


rawDescription: rearranging an array of arrays (python)

description: Rearranging an array of arrays (python)


code:
def remove_vowels(text): # function names should start with verbs! :)
    return ''.join(ch for ch in text if ch.lower() not in 'aeiou')

rawDescription: Loop "Forgets" to Remove Some Items

description: Loop "Forgets" to Remove Some Items


rawDescription: Why and how does python truncate numerical data?


code:
points = np.array([.5, .5, 1, 1.5]).reshape(2, 2)
points
p.contains_points(points)

rawDescription: inpolygon for Python - Examples of matplotlib.path.Path contains_points() method?

description: Inpolygon for Python - Examples of matplotlib.path.Path contains_points() method


code:
for line, pattern0, pattern1 in zip(new_listes(poem_lines), pattern[0], pattern[1]):
    i = 0
    for word in line.split():
        for sylables in word_to_phonemes[word]:
            i += sum(number_count(char) for char in sylables)

    if i != pattern0:
        yield line

rawDescription: Counting Syllables In String

description: Counting Syllables In String


code:
date_in = u'2015-01-02T00:00'
date_out = datetime.datetime(*[int(v) for v in date_in.replace('T', '-').replace(':', '-').split('-')])

rawDescription: How convert datetime-local to datetime in Python?


code:
class GenreForm(forms.Form):
    genre = forms.ModelChoiceField(
        queryset=Genre.objects.filter(parent__is_null=True))
    sub_genre = forms.ModelChoiceField(
        queryset=Genre.objects.filter(
            parent__is_null=False, parent__parent__is_null=True))

rawDescription: Conditional form display logic with Django ModelForm


code:
float_mw = []
for symbol, coeff in lst_mw:
    weight = weights.get(symbol, 0.0) # assume zero if unknown
    number = int(coeff) if coeff else 1 # one if not specified
    float_mw.append(weight * number)

rawDescription: turn a number in an element of a string into a coefficient python

description: Turn a number in an element of a string into a coefficient python


code:
@decorated_by_class
class C(object):
    pass

rawDescription: Subclass from a class decorated by a class


code:
"""
Hello
.
1-methyl-4-phenylpyridinium
is
ultra
-
bad
.
However
,
1-methyl-4-phenyl-1,(2,3),6-tetrahydropyridine
is
worse
.
"""

rawDescription: Python: question about parsing human-readable text


code:
import os
import csv
from itertools import groupby

data_list = []
with open("table.csv") as csv_file:
    data_reader = csv.reader(csv_file, dialect='excel-tab')
    for row in data_reader:
        # read and convert data
        data_list.append((int(row[0]), float(row[1]), float(row[2])))

def classify(row):
    # returns classification of row based on third value, then first value
    # i.e. [549, 648.077, 0.01] -> (0.0, 540)
    #      [572, 648.141, 0.3]  -> (0.3, 570)
    first, second, third = row
    for level3 in (0.2, 0.4, 0.6, 0.8):
        if third <= level3:
            break
    else:
        level3 = 1.0
    for level1 in range(10, 1100, 10):
        if first <= level1:
            break
    else:
        level1 = 1100
    return level3, level1

data_list.sort(key=classify)

plot_values = []

for key, group in groupby(data_list, classify):
    group = list(group)
    number_of_elements = len(group)
    mean = sum([r[2] for r in group]) / number_of_elements
    plot_values.append((key, mean))

print('\n'.join(['%-10s -> %s' % (k, m) for k, m in plot_values]))

rawDescription: Sorting multi column .csv File Python

description: Sorting multi column .csv File Python


rawDescription: How to use the quick sort to sort by index in a list of a list

description: Use the quick sort to sort by index in a list of a list


code:
from rest_framework import viewsets
from rest_framework.decorators import detail_route

class NumViewSet(viewsets.ModelViewSet):
    queryset = Num.objects.all()
    serializer_class = NumSerializer

    # This method will return the sum of num1 and num2
    @detail_route(methods=['get'], permission_classes=[])
    def add_num(self, request, pk=None):
        num = Num.objects.get(pk=pk)
        sum = num.num1 + num.num2
        return HttpResponse(content=sum, status=200)

rawDescription: Django Rest Framework adding 2 numbers

description: Django Rest Framework adding 2 numbers


code:
[v for lvl0 in mult_dict.itervalues()
   for lvl1 in lvl0.itervalues()
   for lvl2 in lvl1.itervalues()
   for lvl3 in lvl2.itervalues()
   for v in lvl3.itervalues()]

rawDescription: extract multidimensional dictionary to list

description: Extract multidimensional dictionary to list


rawDescription: Python Shift Scheduling Optimization

description: Python Shift Scheduling Optimization


code:
def resize_colobar(event):
    # Tell matplotlib to re-draw everything, so that we can get
    # the correct location from get_position.
    plt.draw()

    posn = ax.get_position()
    colorbar_ax.set_position([posn.x0 + posn.width + 0.01, posn.y0,
                             0.04, axpos.height])

fig.canvas.mpl_connect('resize_event', resize_colobar)

rawDescription: Correct placement of colorbar relative to geo axes (cartopy)


code:
tuned_parameters = {'alpha': [10 ** a for a in range(-6, -2)]}
clf = GridSearchCV(SGDClassifier(loss='hinge', penalty='elasticnet',l1_ratio=0.15, n_iter=5, shuffle=True, verbose=False, n_jobs=10, average=False, class_weight='balanced')
                  , tuned_parameters, cv=10, scoring='f1_macro')

#now clf is the best classifier found given the search space
clf.fit(X_train, Y_train)
#you can find the best alpha here
print(clf.best_params_)

rawDescription: Finding optimal feature using Lasso regression in binary classification


code:
return '.' in domain and not \
    (domain.startswith('.') or domain.endswith('.') or '..' in domain)

rawDescription: Python regex for finding dots in email address


code: #! /usr/bin/env python

rawDescription: Python shebang problems with importing modules (and choosing the correct interpreter)


code:
def irc_JOIN(self, prefix, params):
    """
    Called when a user joins a channel.
    """
    nick = string.split(prefix,'!')[0]
    channel = params[-1]
    if nick == self.nickname:
        self.joined(channel)
    else:
        self.userJoined(nick, channel)

rawDescription: 'METHODNAME' as Client method versus irc_'METHODNAME' in twisted


code:
[u'"The Exam Room" is a new series ...',
 u'In our second episode: ...',
 u'Produced & Hosted by Noah Golden']

rawDescription: Separate text from nested OrderedDict in Python


code:
import itertools
for i,j in itertools.product(range(1, 100), repeat=2):
  break

rawDescription: break two for loops

description: Break two for loops


code: df[['Time', 'Experiment']] = df['Sample'].str.extract(r'(.+)-(\d+)')

rawDescription: Reorganizing a Pandas DataFrame

description: Reorganizing a Pandas DataFrame


code: dict([(i,l.count(i)) for i in l if l.count(i)<(0.1*len(l))])

rawDescription: How do you tally the amount of times a item in appears from a randomly list?

description: Tally the amount of times a item in appears from a randomly list


code:
dst_tz = pytz.timezone('EST')
dt = dt.astimezone(dst_tz)

rawDescription: Converting GMT to EST from CSV file using Python


code:
FileSession.setup(**kwargs)
cherrypy.session = cherrypy._ThreadLocalProxy('session')

rawDescription: Initializing cherrypy.session early

description: Initializing cherrypy.session early


code:
class GdataJSON(gdata.contacts.client.ContactsClient):
    """
    gdata ContactsClient to give json result
    """

    def get_contacts(self, uri=None, desired_class=None,
                     auth_token=None, **kwargs):
        """
        Provided a converter function so that default xmlconvertor is not used
        """
        uri = uri or self.GetFeedUri()
        return_same = lambda x: x
        return self.get_feed(uri, auth_token=auth_token, converter=return_same,
                             desired_class=desired_class, **kwargs)
    GetContacts = get_contacts

rawDescription: Use Google Contacts library (gdata) to fetch json response?


code:
def generate_numbers():
    while True:
        ...
    return comp_list

rawDescription: Generating a list of numbers based on a constraint-step procedure


code:
import re
import datetime

def yield_valid_dates(dateStr):
    for match in re.finditer(r"\d{1,2}-\d{1,2}-\d{4}", dateStr):
        try:
            date = datetime.datetime.strptime(match.group(0), "%m-%d-%Y")
            yield date
            # or you can yield match.group(0) if you just want to
            # yield the date as the string it was found like 05-04-1999
        except ValueError:
            # date couldn't be parsed by datetime... invalid date
            pass

testStr = """05-04-1999 here is some filler text in between the two dates 4-5-2016 then finally an invalid
 date 32-2-2016 here is also another invalid date, there is no 32d day of the month 6-32-2016. You can also not
 include the leading zeros like 4-2-2016 and it will still be detected"""

for date in yield_valid_dates(testStr):
    print(date)

rawDescription: Python Regex Date

description: Python Regex Date


code:
mydict1
{'h18_84pp_3A_MVP2_GoodiesT1-HKJ-DFG-CMVP2_Y1000-FIX.txt': 8,
 'h18_84pp_3A_MVP3_GoodiesT1-HKJ-DFG-CMVP3_Y1000-FIX.txt': 9,
 'h18_84pp_3A_MVP1_GoodiesT1-HKJ-DFG-CMVP1_Y1000-FIX.txt': 6}

mydict0
{'g18_84pp_2A_MVP1_GoodiesT0-HKJ-DFG_MIX-CMVP1_Y1000-MIX.txt': 0,
 'g18_84pp_2A_MVP2_GoodiesT0-HKJ-DFG_MIX-CMVP2_Y1000-MIX.txt': 1,
 'g18_84pp_2A_MVP4_GoodiesT0-HKJ-DFG_MIX-CMVP4_Y1000-MIX.txt': 3,
 'g18_84pp_2A_MVP5_GoodiesT0-HKJ-DFG_MIX-CMVP5_Y1000-MIX.txt': 4,
 'g18_84pp_2A_MVP3_GoodiesT0-HKJ-DFG_MIX-CMVP3_Y1000-MIX.txt': 2,
 'g18_84pp_2A_MVP6_GoodiesT0-HKJ-DFG_MIX-CMVP6_Y1000-MIX.txt': 5,
 'g18_84pp_2A_MVP7_GoodiesT0-HKJ-DFG_MIX-CMVP7_Y1000-MIX.txt': 7}

mydict2
{'p18_84pp_2B_MVP1_GoodiesT2-HKJ-DFG-CMVP3_Y1000-FIX.txt': 10}

rawDescription: how to group new dictionaries by using common strings from my dictionary

description: Group new dictionaries by using common strings from my dictionary


code:
import csv

...

mlist = ['sample','XXX','YYY']
sep = ' '
with open('out.txt', 'w') as f:
    csv.writer(f, delimiter=sep, lineterminator='\n').writerow(mlist)
    dfp_prc.to_csv(f, sep=sep, index=True)

rawDescription: Appending a list to the top of Pandas DataFrame output


code:
def polyval(p, x):
    y = np.zeros_like(x)
    for i in range(len(p)):
        y = x * y + p[i]
    return y

rawDescription: A faster numpy.polynomial?

description: A faster numpy.polynomial


code:
def grandKids(generation, kidsFunc, val):
  layer = [val]
  for i in xrange(generation):
    layer = itertools.chain.from_iterable(itertools.imap(kidsFunc, layer))
  return layer

rawDescription: Generate from generators

description: Generate from generators


code: help(myClass)

rawDescription: What is the Pythonic way to create informative comments in Python 2.x?


code:
with open('configfile.cfg') as f:
    data = f.readlines()

    config = {}
    current_section = None
    for line in data:
        line = line.strip()
        if line == 'end' or not line:
            continue

        if line.startswith('@'):
            current_section = line[1:-1]
            config[current_section] = {}
        else:
            key, value = line.split('=')
            config[current_section][key.strip()] = value.strip().strip("'")

    print(config)

rawDescription: Coding a parser in Python

description: Coding a parser in Python


code: t1.merge(q2, on="TripDate")

rawDescription: Filter Data Frame by dates in another dataframe


code: Choose_Item = eval(input("Select your item:  "))

rawDescription: Python 3: Get value of variable entered from user input


code:
def get_occupancy_intervals(OCC, fill_gap_days=0):
    """
    Find the runs in the OCC array corresponding
    to the 'dilated' consecutive positions, and then
    'erode' back to the correct end dates by subtracting
    the fill_gap_days.
    """
    starts = np.flatnonzero(np.diff(OCC) > 0)  # where runs of nonzeros start
    ends = np.flatnonzero(np.diff(OCC) < 0)  # where runs of nonzeros end
    ends -= fill_gap_days  # erode back to original length prior to dilation
    return [(s, e) for (s, e) in zip(starts, ends)]

rawDescription: How to combine records based on date using python connected components?

description: Combine records based on date using python connected components


code:
replacements = {
    'Apple':['Iphone','Ipod'],
    'Samsung':['Galaxy','Nexus']
}

rawDescription: Python, SQlite and string substitution

description: Python, SQlite and string substitution


code:
import ast
ast.literal_eval("['11', '20', '0']")

rawDescription: How to convert a string that already looks like a list into a list?

description: Convert a string that already looks like a list into a list


code:
rooms = ['r1', 'r2', 'r3', 'r4']
room_file = "room_dict.txt"
pickle_dict(create_dict(rooms), room_file)

rawDescription: save and update a dictionary

description: Save and update a dictionary


code:
requests_dict = {
    'location1': 'Please enter xxx: ',
    'location2': 'Do you do X or Y: ',    # and so on
}

rawDescription: Python: How to store a REQUEST for input in a variable?


rawDescription: Lists aggregation in python

description: Lists aggregation in python


rawDescription: Same color bar range for different plots - Matplotlib


rawDescription: List comprehension expression showing none value insted of sublist


code:
@fix_docs
class Dog(Animal):
    def walk(self):
        pass

rawDescription: Inheriting methods' docstrings in Python


code:
def foo():
    return (functionONE,somearray,1,3)

command = foo()
command[0](*command[1:])

rawDescription: return variable name from outside of function, as string inside python function

description: Return variable name from outside of function, as string inside python function


code:
b = example.B_t()
a_thing = example.get_thing(b, 0)
example.set_thing(b,0,999)

rawDescription: Accessing C struct array to Python with SWIG


code:
class demo(object):
    def a(self):
        print("{0}.a called!".format(self))

    @bind_args
    def b(self, param=a):
        param()

def other():
    print("other called")

demo().b()
demo().b(other)

rawDescription: Make a membermethod a default parameter

description: Make a membermethod a default parameter


code: df.loc[df['product']=='a', ['market_penetration_rate', 'success_rate']] *= 100

rawDescription: Pandas conditional multiplication

description: Pandas conditional multiplication


code: map(lambda x: x+170, list1)

rawDescription: Increase all of a lists values by an increment


code: invoice_no = models.CharField(max_length = 500, default = increment_invoice_number, null = True, blank = True)

rawDescription: Auto increament the invoice number in django backend for new invoice


code:
from sqlalchemy import select, func

class Interval(Base):
    ...

    @hybrid_property
    def time_spent(self):
        return (self.end or datetime.now()) - self.start

    @time_spent.expression
    def time_spent(cls):
        return func.coalesce(cls.end, func.current_timestamp()) - cls.start

class Task(Base):
    ...

    @hybrid_property
    def time_spent(self):
        return sum((i.time_spent for i in self.intervals), timedelta(0))

    @time_spent.expression
    def hours_spent(cls):
        return (select([func.sum(Interval.time_spent)])
            .where(cls.id==Interval.task_id)
            .label('time_spent'))

rawDescription: How do I implement a null coalescing operator in SQLAlchemy?

description: Implement a null coalescing operator in SQLAlchemy


code: trial = test

rawDescription: How to create a simple function within a class in Python?

description: Create a simple function within a class in Python


rawDescription: Python: Read hex from file into list?

description: Python: Read hex from file into list


rawDescription: A more optimized code in recursion exercise


code:
from heapq import nlargest

shufflatored = []
while any(items_by_brand):
    items1, items2 = nlargest(2, items_by_brand, key=len)

    if items1: shufflatored.append(items1.pop())
    if items2: shufflatored.append(items2.pop())

rawDescription: python sort with adjacent difference

description: Python sort with adjacent difference


rawDescription: One-to-many Flask | SQLAlchemy

description: One-to-many Flask | SQLAlchemy


rawDescription: Prevent a file from being opened

description: Prevent a file from being opened


code:
sensor = {
    'id': 'aaaaa',
    'name': 'temp001',
    'quantity': 'temperature',
    'unit': 'C',
    'charlength': 4,
    'convert': {
        'linear': (3, 2, 6),
        'quadratic': (2, 4, 7, 8)
    }
}

linear_function_parameters = sensor["convert"]["linear"]
globals()["linear"](*linear_function_parameters)

rawDescription: Can I store Python function on a MongoDB collection?

description: Store Python function on a MongoDB collection


code: df.loc[df.issuer.str.contains(w).fillna(False), "website"] = issuer[w]

rawDescription: Key to Value to Key in Python Dictionary


code: import utils

rawDescription: How to write Unit Test in Django

description: Write Unit Test in Django


code:
for dealt_cards in itertools.combinations(deck_of_cards, 6):
    for hand1 in itertools.combinations(dealt_cards, 3):
        hand2 = tuple(card for card in dealt_cards if card not in hand1)

rawDescription: generate two sets of combination with one list in python

description: Generate two sets of combination with one list in python


code: [id(i) for i in g.vs['foo']]

rawDescription: How to assign values to individual elements of python igraph list attributes?

description: Assign values to individual elements of python igraph list attributes


rawDescription: Python pandas equivalent for replace

description: Python pandas equivalent for replace


code:
import matplotlib.font_manager as fm
set([f.name for f in fm.fontManager.ttflist])

rawDescription: matplotlib show works while savefig fails for unicode

description: Matplotlib show works while savefig fails for unicode


code:
#!/usr/bin/python

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import sys
import StringIO
import atexit

# Back up stdout and stderr. We'll overwrite them by StringIO to save the
# output to a string.
stdout_copy = sys.stdout
stderr_copy = sys.stderr

f = StringIO.StringIO()

sys.stdout = f
sys.stderr = f

# The MIME message we're going to wrap the program's output in.
msg = MIMEMultipart()

# This is the boundary I set in my crontab file. Kludgy, but I knew no other
# way to send multipart files from cron. To reproduce it, add the following
# to your crontab:
#
# CONTENT_TYPE='multipart/mixed; boundary="------------040907050602020300000601"'

msg.set_boundary('------------040907050602020300000601')

# At exit, print f's contents as a MIME message.
def flush_f():

    # Rewind the f StringIO so that f.read() will read all the data.
    f.seek(0)

    # Restore stdout and stderr - this will let us print to the program's
    # standard output. Note that we overwrite stderr with the stdout - this
    # will let us see the error messages in crontab e-mails.
    sys.stdout = stdout_copy
    sys.stderr = stdout_copy

    # Add the stdout contents to the message body.
    stdout_contents = MIMEText(f.read(), "plain")
    msg.attach(stdout_contents)

    # Attach the attachments. We use "unknown" to trick Thunderbird into
    # thinking that the file is binary.
    for filename in filenames:
        if filename.endswith(".png"):
            attachment = MIMEBase("image", "png")
        else:
            attachment = MIMEBase("application", "unknown")
        attachment.set_payload(open(filename).read())
        attachment.add_header('Content-Disposition', 'attachment',
                              filename=filename)
        encoders.encode_base64(attachment)
        msg.attach(attachment)

    # Print the final message.
    print(msg.as_string())
atexit.register(flush_f)

print("Hello, world!")
filenames = ["/etc/redhat-release"]

rawDescription: Python script as a cron job - how to format the output as an e-mail with attachments?


code:
partner_id = sale_order_object.partner_id.id
partner_name = sale_order_object.partner_id.name

rawDescription: how to fetch a column in browse_record_list in orm browse method in openERP

description: Fetch a column in browse_record_list in orm browse method in openERP


code:
def bla(*args, profile='system', **kwargs):
    print('profile', profile)
    print('args', args)
    print('kwargs', kwargs)

rawDescription: Mixing default arguments in Python 2.x

description: Mixing default arguments in Python 2.x


code:
str1 = "a    b     c      d"
re.split(" +", str1)

rawDescription: python split string based on regular expression

description: Python split string based on regular expression


code:
read_data = []

with open('test.csv', 'r') as f:
    for line in f:
        read_data.append(line)

with open('test.csv', 'w') as f:
    for line in read_data:
        key,value = line.split(',')
        new_line = line

        if key == 'b':
            value = value.strip() + 'added\n'
            new_line = ','.join([key,value])

        f.write(new_line)

rawDescription: Appending to the end of a certain line

description: Appending to the end of a certain line


code:
from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl != '':
            yield nl.strip('\n')
        else:
            raise StopIteration

rawDescription: Iterate over the lines of a string

description: Iterate over the lines of a string


code:
import os
import hashlib
import Crypto.Cipher.AES as AES

class Cipher:

        @staticmethod
        def md5sum( raw ):
                m = hashlib.md5()
                m.update(raw)
                return m.hexdigest()

        BS = AES.block_size

        @staticmethod
        def pad( s ):
                """note that the padding is no necessary"""
                """return s + (Cipher.BS - len(s) % Cipher.BS) * chr(Cipher.BS - len(s) % Cipher.BS)"""
                return s

        @staticmethod
        def unpad( s ):
                """return s[0:-ord(s[-1])]"""
                return s

        def __init__(self, key):
                self.key = Cipher.md5sum(key)
                #the state of the counter callback
                self.cnter_cb_called = 0
                self.secret = None

        def _reset_counter_callback_state( self, secret ):
                self.cnter_cb_called = 0
                self.secret = secret

        def _counter_callback( self ):
                """
                this function should be stateful
                """
                self.cnter_cb_called += 1
                return self.secret[self.cnter_cb_called % Cipher.BS] * Cipher.BS

        def encrypt(self, raw):
                secret = os.urandom( Cipher.BS ) #random choose a "secret" which is not secret
                self._reset_counter_callback_state( secret )
                cipher = AES.new( self.key, AES.MODE_CTR, counter = self._counter_callback )
                raw_padded = Cipher.pad( raw )
                enc_padded = cipher.encrypt( raw_padded )
                return secret+enc_padded #yes, it is not secret

        def decrypt(self, enc):
                secret = enc[:Cipher.BS]
                self._reset_counter_callback_state( secret )
                cipher = AES.new( self.key, AES.MODE_CTR, counter = self._counter_callback )
                enc_padded = enc[Cipher.BS:] #we didn't encrypt the secret, so don't decrypt it
                raw_padded = cipher.decrypt( enc_padded )
                return Cipher.unpad( raw_padded )

rawDescription: How AES in CTR works for Python with PyCrypto?


code:
for p in largest_primes_under(10, 10**9):
    print(p)

rawDescription: Finding the n largest primes under m

description: Finding the n largest primes under m


code:
class A:
    def __init__(self,value):
        self.value=value

    def function(self,a):
        """function returns a+1 and caches the value for future calls."""
        # Add a default value of empty string to avoid key errors,
        # check if we already have the value cached
        if self.function.cache.get(a,''):
            return self.function.cache[a]
        else:
            result = a + 1
            self.function.cache[a] = result
            return result
    function.cache = {}

a=A(12)
print(a.function(12))
print(a.function.cache)

rawDescription: How to assign cache to a method in an OOP fashion?

description: Assign cache to a method in an OOP fashion


code:
def with_loop(l):
    x_min = float('-inf')
    x_max = float('+inf')
    for el in l:
        if el < x_min:
            x_min = el
        elif el > x_max:
            x_max = el
    return x_min, x_max
timeit.timeit('with_loop(range(6000000))', 'from __main__ import with_loop', number=5)

rawDescription: List Comprehensions in Python to compute minimum and maximum values of a list


code: [sum(x) for x in zip(list1, list2)]

rawDescription: Add two lists of integers together into a 3rd list?


code: filter(time_filt, os.listdir(your_dir))

rawDescription: python find all file names in folder that follows a pattern

description: Python find all file names in folder that follows a pattern


code:
indentation = ';' + ' ' * 11
params = {
    'width': 80,
    'initial_indent': indentation,
    'subsequent_indent': indentation
}
result = '\n'.join([textwrap.fill(line, **params)
                    for line in input_text.splitlines()])

rawDescription: In Python, is there a way to insert a line break and spaces every 68 characters of a string?


rawDescription: Print file passed in as argument

description: Print file passed in as argument


code:
from sympy import poly
from sympy.abc import x
p = poly(x**2 + 1)
p.root(0)
p.root(1)

rawDescription: .eigenvals creates a new variable

description: .eigenvals creates a new variable


code:
import csv
from itertools import groupby
import numpy as np

with open('data.csv') as in_file, open('out.csv', 'wb') as out_file:
    reader = csv.reader(in_file, delimiter=' ', skipinitialspace=True)
    writer = csv.writer(out_file, delimiter='\t')
    for key, group in groupby(reader, key=lambda r: r[1:6]):
        col0, col6 = np.array(list(group))[:, [0, 6]].transpose().astype(float)
        writer.writerow([min(col0)] + key + [int(min(col6)), int(max(col6)),
                                             np.mean(col6)])

rawDescription: average of groupby elements python

description: Average of groupby elements python


somestring: myfunction

rawDescription: Clean way to manage parse-dictionaries that contain function names


code:
def someview(request):
    if request.method == 'POST':
        form = UserForm(request.POST, user=request.user)
        if form.is_valid():
            # Do something with the data
            pass
    else:
        form = UserForm(user=request.user)
    # Rest of your view follows

rawDescription: get request data in Django form

description: Get request data in Django form


code:
neuter = ["t", "het", "dat"]
non_neuter = ["de","die"]
freqDf = pd.DataFrame()

freqDf["neuter"] = ct[neuter].sum(axis=1)
ct.drop(neuter, axis=1, inplace=1)

freqDf["non_neuter"] = ct[non_neuter].sum(axis=1)
ct.drop(non_neuter, axis=1, inplace=1)

freqDf["rest"] = ct.sum(axis=1)

rawDescription: Create advanced frequency table with Python


code:
def mapInToOutDecode(inChar):
    index = 0
    found = 0
    for char in keyString:
        if(char == inChar):
            found = index #remember it in a variable found
            break
        else:
            index +=1
    outChar = alphabet[found]
    return(outChar)

rawDescription: Generalizing two similar functions into one


code:
for word in words:
    if word in fullstrings:
        "Match! do something"
    for n in prefixes_by_length:
        if word[:n] in prefixes_by_length[n]:
            "Match! do something"

rawDescription: Efficiently checking if a word matches patterns in set (Python)


rawDescription: Python - map() to split and get first part only


code:
import csv

rates={}
with open(ur_file) as f:
    for line in csv.reader(f, skipinitialspace=True, quotechar="'"):
        rates.setdefault(line[0],{})[line[1]]=[float(e) for e in line[2:]]

print(rates)

rawDescription: Efficiently Searching Nested Lists

description: Efficiently Searching Nested Lists


code:
try:
    N = float(N)
except (ValueError, TypeError):
    pass

rawDescription: How can I verify if a string is a valid float?

description: Verify if a string is a valid float


code:
# -*- coding: utf-8 -*-
from collections import defaultdict

values = [["a", 1], ["b", 2], ["c", 3], ["d", 1]]
d = defaultdict(list)
for x, y in values:
    d[y].append([x, y])

rawDescription: Python List To Dictionary - Without Value Overwrite


rawDescription: Python, optimal way of looping through a file, match two lines after a pattern and then join them


code:
var = np.array([t.replace(':',',') for t in time], dtype=float)
var -= float(str(book[0]).replace(":", ","))

rawDescription: Replacing loop with List Comprehension instead of loop getting a function to return a new array within the list comprehension


code:
def find_window_for_pid(pid):
    result = None
    def callback(hwnd, _):
        nonlocal result
        ctid, cpid = win32process.GetWindowThreadProcessId(hwnd)
        if cpid == pid:
            result = hwnd
            return False
        return True
    win32gui.EnumWindows(callback, None)
    return result

rawDescription: How to run a file and get the hwnd using win32 in python?

description: Run a file and get the hwnd using win32 in python


rawDescription: Are there standard rules and practices for Date serialization between two languages or frameworks?


code:
from nltk.parse.malt import MaltParser
mp = MaltParser('maltparser-1.8.1', 'engmalt.linear-1.7.mco')
mp.parse_one('I shot an elephant in my pajamas .'.split()).tree()

rawDescription: Step by step to getting malt parser in NLTK to work?


rawDescription: How do I do extract information from two different indices in two different data frames in Python?

description: Do extract information from two different indices in two different data frames in Python


code: df.apply(lambda x: int(ids[x.UsedFName, x.UsedLName]), axis=1)

rawDescription: matching between two columns and taking value from another in pandas

description: Matching between two columns and taking value from another in pandas


code:
import scipy.ndimage as nd
import numpy as np
import matplotlib.pyplot as plt

im = scipy.ndimage.imread('ygqCd.jpg', True)
im = im.astype('int32')
dx = nd.sobel(im,1)
dy = nd.sobel(im,0)
mag = np.hypot(dx,dy)
mag *= 255.0/np.max(mag)

fig, ax = plt.subplots()
ax.imshow(mag, cmap = 'gray')
plt.xticks([]), plt.yticks([])
plt.show()

rawDescription: applying sobel filter on image

description: Applying sobel filter on image


code:
import functools
import itertools
import operator

lines = [[23, 52, 63, 76, 23, 45],
         [39, 52, 83, 33, 35, 23]]

# Set this variable before use!
permlength = 2

uniq = [set() for _ in range(len(lines))]
freq = [{} for _ in range(len(lines))]

for index, line in enumerate(lines):
    for j in line:
        freq[index][j] = freq[index].get(j, 0) + 1
        uniq[index].add(j)

counter = {}

print("Total number of lines: {}".format(len(lines)))

for i in range(len(lines)):
    print("Line {}...".format(i + 1))

    for j in itertools.combinations(uniq[i], permlength):

        freqp = [freq[i].get(j[x], 0) for x in range(permlength)]
        counter[j] = counter.get(j, 0) + functools.reduce(operator.mul, freqp)

sol = sorted(counter.items(), key=lambda value: value[1], reverse=True)

print(sol)

rawDescription: Finding the most common pair, trio, etc. in a list of 20 random numbers, played 100 times


code: print(ffile)

rawDescription: Python to read \n and \r in a txt file

description: Python to read \n and \r in a txt file


code: [startVertex, startIntermediateEdge, intermediateVertex, intermediateTargetEdge, targetVertex]

rawDescription: Gremlin querying through groovy script using bulbs


code:
from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        print(request.form.getlist('hello'))

    return '''<form method="post">
<input type="checkbox" name="hello" value="world" checked>
<input type="checkbox" name="hello" value="davidism" checked>
<input type="submit">
</form>'''

app.run()

rawDescription: Get the value of a checkbox in Flask

description: Get the value of a checkbox in Flask


code:
import os
os.system("notepad")

rawDescription: Emulating a Windows shortcut in Python

description: Emulating a Windows shortcut in Python


code:
import numpy as np
from scipy.sparse import csc_matrix

# create some matrices
M = csc_matrix(np.random.rand(5, 5))
B = np.random.rand(5, 4)

X, info = bicg_solve(M, B)
print(X.shape)
# (5, 4)

rawDescription: Iterative solving of sparse systems of linear equations with (M, N) right-hand size matrix


code:
class TestFoo1(unittest.TestCase):
    impl = staticmethod(foo1)
    def test_1(self):
        self.assertEqual(self.impl(0, 0), 0)
    def test_2(self):
        self.assertEqual(self.impl(1, 2), 3)

class TestFoo2(TestFoo1):
    impl = staticmethod(foo2)

rawDescription: running the same test against multiple implementations

description: Running the same test against multiple implementations


code:
def bar():
    return 3
foo = {
    'bar': bar
}
eval('bar()', globals(), foo)

rawDescription: How do you do a python 'eval' only within an object context?

description: Do a python 'eval' only within an object context


rawDescription: Find possible bijection between characters and digits


rawDescription: difficulty matching single letter programming languages with regex

description: Difficulty matching single letter programming languages with regex


code: json_string = '[{"a":"value", "b":"value"},{"a":"value", "b":"value"}]'

rawDescription: Python -- get at JSON info that's written like XML


code:
import sys, imp
ipython_path = r"/path/to/ipython-script"

sys.argv = [ ipython_path, "notebook" ]
_ipython = imp.load_source('__main__', ipython_path)

rawDescription: Launching ipython notebook via the api (script)


code: x, y = zip(*sset)

rawDescription: How to get a list of Xth elements from a list of tuples?

description: Get a list of Xth elements from a list of tuples


code:
import shlex
words = shlex.split(long_string)
words

rawDescription: Python to Transforming elements in a list when split


code:
def setMaxWidth(stringList, element):
    f = tkFont.nametofont(element.cget("font"))
    zerowidth=f.measure("0")
    w=max([f.measure(i) for i in stringList])/zerowidth

    element.config(width=w)

rawDescription: Tkinter OptionMenu: setting the width by the longest menu item in the list


code:
from functools import wraps

def xhr_request_check(template=None):

    def decorator_request_parser(f):
        @wraps(f)
        def decorator_request(*args, **kwargs):
            func_data = f(*args, **kwargs)
            if request.is_xhr or not template:
                return jsonify(func_data)
            else:
                return render_template(template, **func_data)
        return decorator_request
    return decorator_request_parser

rawDescription: Efficient way of handling XHR request in Python Flask


rawDescription: Subset of a Pandas DataFrame keeping MultipleIndex with Condition


rawDescription: Python lxml xpath XPathEvalError: Invalid expression -- why?


code:
try:
    from local_settings import *
except ImportError:
    pass

rawDescription: Django settings.py: Separate local and global configuration


code:
q = (session.query(Parent)
     .filter(Parent.children.any(Child.age >= 10))
     )

for p in q:
    print("{}".format(p))
    for c in p.children:
        print("  {}".format(c))

rawDescription: How to use a subquery to filter a sqlalchemy query on a one to many relationship?

description: Use a subquery to filter a sqlalchemy query on a one to many relationship


rawDescription: Numpy array slicing vs. for-loop results


rawDescription: Operations on 'N' dimensional numpy arrays


code:
import os
with open('inputFile.txt', 'r') as inp, open('outfile.txt', 'w') as out:
    for line in inp:
        out.write(line.replace('blah', '!blah!'))
# Windows doesn't let you overwrite a file, remove it old input first
os.unlink('inputFile.txt')
os.rename('outfile.txt', 'inputFile.txt')

rawDescription: How to write before & after certain substrings in an Open file in python?

description: Write before & after certain substrings in an Open file in python


code:
inputtext = 'Some example containing a newline.\nRight there.\n'
replchars.sub(replchars_to_hex, inputtext)
print(replchars.sub(replchars_to_hex, inputtext))

rawDescription: Show non printable characters in a string


rawDescription: How to generalize elementwise matrix operations in numpy

description: Generalize elementwise matrix operations in numpy


code:
d = {}
for dte, val in zip(dates,values):
    d.setdefault(dte,0)
    d[dte] += val

rawDescription: Python dictionary from two lists

description: Python dictionary from two lists


code: from excel_report import make_report

rawDescription: tkinter - ask the user for files directory and then run a script

description: Tkinter - ask the user for files directory and then run a script


code:
class Login:
    def __init__(self,method):
        self.authmethod=method()

rawDescription: Python Class structure to allow multiple authentication methods


rawDescription: Filtering values after a string using regex


code: new_function = partial(bar, 2, 3)

rawDescription: Passing function returns as method parameters in Python


code:
def TestHostRecordCreation(self):
    @mock.patch('lib.mymodule.ClassC')
    @mock.patch('lib.mymodule.ClassB')
    @mock.patch('lib.mymodule.ClassA')
    def test_create_record(self, MockClassA, MockClassB, MockClassC):
        f = MyClass("host", "user", "password")
        self.assertEqual(f, "bogus result")

rawDescription: Good approach to mocking objects in Python?


code:
buffer = ''
while True:
    line = raw_input()
    if not line: break

    buffer += '\n' + line
print(buffer)

rawDescription: Python how to read lines and how to output the new lines