code:
import cv2 # Import relevant libraries
import cv
import numpy as np

img = cv2.imread('cameraman.png', 0) # Read in image

height = img.shape[0] # Get the dimensions
width = img.shape[1]

# Define mask
mask = 255*np.ones(img.shape, dtype='uint8')

# Draw circle at x = 100, y = 70 of radius 25 and fill this in with 0
cv2.circle(mask, (100, 70), 25, 0, -1)

# Apply distance transform to mask
out = cv2.distanceTransform(mask, cv.CV_DIST_L2, 3)

# Define scale factor
scale_factor = 10

# Create output image that is the same as the original
filtered = img.copy()

# Create floating point copy for precision
img_float = img.copy().astype('float')

# Number of channels
if len(img_float.shape) == 3:
  num_chan = img_float.shape[2]
else:
  # If there is a single channel, make the images 3D with a singleton
  # dimension to allow for loop to work properly
  num_chan = 1
  img_float = img_float[:,:,None]
  filtered = filtered[:,:,None]

# For each pixel in the input...
for y in range(height):
  for x in range(width):

    # If distance transform is 0, skip
    if out[y,x] == 0.0:
      continue

    # Calculate M = d / S
    mask_val = np.ceil(out[y,x] / scale_factor)

    # If M is too small, set the mask size to the smallest possible value
    if mask_val <= 3:
      mask_val = 3

    # Get beginning and ending x and y coordinates for neighbourhood
    # and ensure they are within bounds
    beginx = x-int(mask_val/2)
    if beginx < 0:
      beginx = 0

    beginy = y-int(mask_val/2)
    if beginy < 0:
      beginy = 0

    endx = x+int(mask_val/2)
    if endx >= width:
      endx = width-1

    endy = y+int(mask_val/2)
    if endy >= height:
      endy = height-1

    # Get the coordinates of where we need to grab pixels
    xvals = np.arange(beginx, endx+1)
    yvals = np.arange(beginy, endy+1)
    (col_neigh,row_neigh) = np.meshgrid(xvals, yvals)
    col_neigh = col_neigh.astype('int')
    row_neigh = row_neigh.astype('int')

    # Get the pixels now
    # For each channel, do the foveation
    for ii in range(num_chan):
      chan = img_float[:,:,ii]
      pix = chan[row_neigh, col_neigh].ravel()

      # Calculate the average and set it to be the output
      filtered[y,x,ii] = int(np.mean(pix))

# Remove singleton dimension if required for display and saving
if num_chan == 1:
  filtered = filtered[:,:,0]

# Show the image
cv2.imshow('Output', filtered)
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: Image foveation in Python

description: Image foveation in Python


code:
l = [df1, df2, df3, ...]
panel = pd.Panel({i: df for i, df in enumerate(l)})
panel

rawDescription: Pandas: Take the median accross multiple dataframe


code:
#!/usr/bin/env python
import re

open('output.html', 'w').write(re.sub('href="http://en.wikipedia.org', 'href="/home/fergus/wikiget/wiki/Absinthe', open('file.html').read()))

rawDescription: Find and append each reference to a html link - Python


code:
import lxml.html, lxml.etree

url_cooking = 'http://cooking.stackexchange.com/feeds'

#lxml.etree version
data = lxml.etree.parse(url_cooking)
summary_nodes = data.xpath('.//feed/entry/summary')
print('Found ' + str(len(summary_nodes)) + ' summary nodes')

#lxml.html version
data = lxml.html.parse(url_cooking)
summary_nodes = data.xpath('.//feed/entry/summary')
print('Found ' + str(len(summary_nodes)) + ' summary nodes')

rawDescription: lxml - difficulty parsing stackexchange rss feed

description: Lxml - difficulty parsing stackexchange rss feed


code: (df.salary.diff() <= 0).cumsum()

rawDescription: How to split DataFrame using some constraint?

description: Split DataFrame using some constraint


rawDescription: Peewee syntax for selecting on null field


code:
def get_with_default(colour, L, default=''):
    temp = None
    for d in L:
        if d['color'] == colour:
            return d
        elif d['color'] == default:
            temp = d
    return temp

rawDescription: Filter a list of dictionaries to always return a single dictionary, given a default key value to lookup


rawDescription: Pivoted pandas dataframe to dictionary

description: Pivoted pandas dataframe to dictionary


code:
tags = tag_table
tag_id_query = select([tags.c.tagname, tags.c.id], tags.c.tagname.in_(hashtags))
tag_ids = dict(conn.execute(tag_id_query).fetchall())
for tag in hashtags:
    if tag not in tag_ids:
        result = conn.execute(tags.insert(), {'tagname': tag})
        tag_ids[tag] = result.last_inserted_ids()[0]

rawDescription: Setting up/Inserting into Many-to-Many Database with Python, SQLALchemy, Sqlite


code:
l1, l2 = [[],[]]

with open('in.txt', 'r') as f:
    for i in f:
        # will loudly fail if more than two columns on a line
        left, right = i.split('\t')
        l1.append(left)
        l2.append(right)

print("\n".join(l1))
print("\n".join(l2))

rawDescription: How to split csv files into multiple files using the delimiter? python

description: Split csv files into multiple files using the delimiter? python


code:
class Meta(type):

    def __new__(cls, clsname, bases, dct):
       fields = ('doSomething', ) #Fields on which you want to apply the decorator
       for name, val in dct.items():
           if name in fields:
               dct[name] = accepts(cls)(val)
       return type.__new__(cls, clsname, bases, dct)

class ClassA(object):
    __metaclass__ = Meta
    def doSomething(otherObject):
        pass

rawDescription: Pass current class to decorator function


code:
array([[False, False, False, False,  True],
       [False, False, False, False, False],
       [False,  True, False, False, False],
       [False, False,  True, False, False],
       [False, False, False,  True, False]], dtype=bool)

rawDescription: Find indexes of matching rows in two 2-D arrays


rawDescription: Regexp - find a value between a part of the string and a second part of the string OR end of line


rawDescription: Is there a standard Python function that takes any number of arguments and does nothing?


code:
class PicAdjuster(cls):
    def adjust_pic(self, image_filename, factor_red = 1., factor_green = 1., factor_blue = 1., factor_alpha = 1.):
        original_img = wx.Image(image_filename)
        adjusted_img = original_img.AdjustChannels(factor_red, factor_green, factor_blue, factor_alpha)
        return wx.BitmapFromImage(adjusted_img)

rawDescription: wxOGL wx.ShapeCanvas images

description: WxOGL wx.ShapeCanvas images


code:
from twisted.internet.protocol import Factory, Protocol
from twisted.internet.endpoints import TCP4ServerEndpoint
from twisted.internet import reactor

class QOTD(Protocol):

    def connectionMade(self):
        # self.factory was set by the factory's default buildProtocol:
        self.transport.write(self.factory.quote + '\r\n')
        self.transport.loseConnection()

class QOTDFactory(Factory):

    # This will be used by the default buildProtocol to create new protocols:
    protocol = QOTD

    def __init__(self, quote=None):
        self.quote = quote or 'An apple a day keeps the doctor away'

endpoint = TCP4ServerEndpoint(reactor, 8007)
endpoint.listen(QOTDFactory("configurable quote"))

endpoint2 = TCP4ServerEndpoint(reactor, 8008)
endpoint2.listen(QOTDFactory("another configurable quote"))

reactor.run()

rawDescription: Twisted with multiple ports, protocols, and reactors


code:
# Media files
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

rawDescription: Show an image from models in Django

description: Show an image from models in Django


code:
data = {'AttrA': [2, 4, 1, 3], 'AttrB': [12, 43, 23, 25], 'AttrC': ['a', 'd', 'f', 'z']}
base = data['AttrA']
for key in data:
    data[key] = [x for (y,x) in sorted(zip(base, data[key]))]

data

rawDescription: Sorting values of a dictionary based on a list


rawDescription: PANDAS drop a range of rows from df

description: PANDAS drop a range of rows from df


rawDescription: DataFrame.index.levels shows "extra" values after paring down dataframe


code:
data.extend(["bla", "fool"])
clf.predict([[3], [4]])

rawDescription: How to use string kernels in scikit-learn?

description: Use string kernels in scikit-learn


code:
import netifaces as ni
ni.interfaces()
ni.ifaddresses('eth0')

ni.ifaddresses.__doc__
# for the IPv4 address of eth0
ni.ifaddresses('eth0')[2][0]['addr']

rawDescription: Python, How to get all external ip addresses with multiple NICs


rawDescription: Plot surfaces on a cube

description: Plot surfaces on a cube


code:
import numpy as np
import itertools
import matplotlib.pyplot as plt
m = 5
n = 5
x = np.zeros(shape=(m, n))
plt.figure(figsize=(5.15, 5.15))
plt.clf()
plt.subplot(111)
marker = itertools.cycle(('o', 'v', '^', '<', '>', 's', '8', 'p'))

ax = plt.gca()
for i in range(1, n):
    x = np.dot(i, [1, 1.1, 1.2, 1.3])
    y = x ** 2
    color = next(ax._get_lines.color_cycle)
    plt.plot(x, y, linestyle='', markeredgecolor='none', marker=marker.next(), color=color)
    plt.plot(x, y, linestyle='-', color = color)
plt.ylabel(r'$y$', labelpad=6)
plt.xlabel(r'$x$', labelpad=6)
plt.savefig('test2.png')

rawDescription: How to set same color for markers and lines in a matplotlib plot loop?

description: Set same color for markers and lines in a matplotlib plot loop


code: ['{}_{}'.format(a, b) for b in b_list for a in a_list]

rawDescription: Python: How do I add a suffix to the end of each list element?


code:
import pickle
import types

with open('data.pickle', 'rb') as f:    #On client you load and unpickle function
    code = pickle.load(f)

test2 = types.FunctionType(code, globals())

print(test2())    #Result will be True

rawDescription: Sending function pointer over network in python


rawDescription: Hollow Diamond in python

description: Hollow Diamond in python


code:
df.loc[df.index < roll_date, ['Open','High','Low','Settle']] = (
         df.loc[df.index < roll_date, ['Open','High','Low','Settle']] + roll_gap)

rawDescription: Build Back Adjusted Continous Futures contract from Historical Data


code:
files = ['manifest.xml', 'Test.java', 'Foo.java', 'MyExclusion.java']
[f for f in fnmatch.filter(files, '*.java')
    if f not in ('MyExclusion.java', 'Bad.java')]

rawDescription: Filter for file extensions using os.walk but with restrictions on file name


rawDescription: How can I check for unicode or escape sequences in a string?

description: Check for unicode or escape sequences in a string


code:
def save(self, path=None):
    # Show a loading dialog while the document is staving.
    progress = shared.show_loading(self, 'Saving document')

    try:
        if not path:
            self.document.save()
        else:
            self.document.save_to_file(path)
    except IOError as e:
        message = 'Failed to save file:\n\n{}'.format(e.message)
        wx.MessageBox(message, 'Error', wx.OK | wx.ICON_ERROR)
    finally:
        progress.done()

rawDescription: How can I get the ProgressDialog to close before I open my MessageBox?

description: Get the ProgressDialog to close before I open my MessageBox


code: [row for row in myRows if row[0] == item[0]]

rawDescription: how to make a efficient filter in python

description: Make a efficient filter in python


code: string = resp.decode('utf-8')

rawDescription: writing persian text into a text file in the way which could be read in python

description: Writing persian text into a text file in the way which could be read in python


code: i1 = EdgeDetect[i, 10]

rawDescription: Square detection with aberrations in edges and 1 missing corner


code:
timeit.timeit('for i in nums:pass', setup='nums = range(0,100)')
timeit.timeit(';'.join('nums[%s]' % i for i in range(0,100)), setup='nums = range(0,100)')

rawDescription: Why is direct indexing of an array significantly faster than iteration?


code: parser.add_argument('--example', nargs='?', const=1, type=int, default=1)

rawDescription: Python argparse: default value or specified value


code:
for p in place:
    if any(item in US for item in p):
        c = "US"
    else:
        c = "Non-US"
    country.append(c)

rawDescription: Check if items in one list exists in another list


code: from PySide.QtCore import QTimer, SIGNAL

rawDescription: Qt4 w/ PySide: How to Create Animation Loop for a Widget?


rawDescription: Python: Cannot import name/IndexError: List index out of range


code:
for i in j.split():
    stack.push(i)

rawDescription: Reverse the order of words in python using stack


rawDescription: Python - get all in order splits of a string


code:
df['evtId'] = np.where(df['labeled'] > 0, df['labeled']-1, np.nan)
#      RF   mask dilation erosion  labeled  evtId
# 0   0.3   True     True    True        1      0
# 1   1.1   True     True    True        1      0
# 2   0.2   True     True    True        1      0
# 3   0.0  False     True    True        1      0
# 4   0.0  False     True    True        1      0
# 5   0.0  False     True    True        1      0
# 6   0.0  False     True    True        1      0
# 7   0.0  False     True    True        1      0
# 8   1.1   True     True    True        1      0
# 9   0.6   True     True    True        1      0
# 10  0.0  False     True   False        0    NaN
# 11  0.0  False     True   False        0    NaN
# 12  0.0  False    False   False        0    NaN
# 13  0.0  False     True   False        0    NaN
# 14  0.0  False     True   False        0    NaN
# 15  0.0  False     True   False        0    NaN
# 16  0.8   True     True    True        2      1
# 17  1.1   True     True    True        2      1
# 18  2.3   True     True    True        2      1
# 19  1.4   True     True    True        2      1
# 20  0.4   True     True    True        2      1
# 21  0.2   True     True    True        2      1
# 22  0.0  False     True   False        0    NaN
# 23  0.0  False     True   False        0    NaN
# 24  0.0  False    False   False        0    NaN
# 25  0.0  False    False   False        0    NaN
# 26  0.0  False    False   False        0    NaN
# 27  0.0  False    False   False        0    NaN

rawDescription: How to identify approximately (threshold defined) continuous non null data using pandas?

description: Identify approximately (threshold defined) continuous non null data using pandas


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

# Generate some random data
xy = np.random.random((2**15, 2))
z = np.sin(10*xy[:,0]) * np.cos(10*xy[:,1])

grid = np.meshgrid(
    np.linspace(0, 1, 512),
    np.linspace(0, 1, 512)
)

# Interpolate
result1 = scipy.interpolate.griddata(xy, z, tuple(grid), 'linear')

# Show
plt.figimage(result1)
plt.show()

# Remove rectangular window
mask = np.logical_and.reduce((xy[:,0] > 0.2, xy[:,0] < 0.8, xy[:,1] > 0.2, xy[:,1] < 0.8))
xy, z = xy[~mask], z[~mask]

# Interpolate
result2 = scipy.interpolate.griddata(xy, z, tuple(grid), 'linear')

# Show
plt.figimage(result2)
plt.show()

rawDescription: How to set a maximum distance between points for interpolation when using scipy.interpolate.griddata?

description: Set a maximum distance between points for interpolation when using scipy.interpolate.griddata


code:
fmt = '%02i.txt'
targets = {fmt % i for i in range(1, 25+1)}

rawDescription: How to match a python formatstring to elements in a list?

description: Match a python formatstring to elements in a list


code:
if True:
    @property
    def foo(self):
        return self._foo
    @foo.setter
    def foo(self, val):
        self._foo = val

rawDescription: Overriding properties in python

description: Overriding properties in python


rawDescription: Cleaning HTML tables with Pandas

description: Cleaning HTML tables with Pandas


code: count = Counter([x.lower() for x in rdd.split()])

rawDescription: Storing the content from for loop in the list python


code:
import numpy as np
from scipy.stats import logistic

def func3(y, X, thresholds):
    y_0 = y == 0
    y_end = y == len(thresholds)
    y_rest = ~(y_0 | y_end)

    ll_1 = logistic.logcdf(thresholds[0] - X[ y_0 ])
    ll_2 = logistic.logcdf(X[ y_end ] - thresholds[-1])
    ll_3 = np.log(
        np.maximum(
            10 ** -5,
            logistic.cdf(thresholds[y[ y_rest ]] - X[ y_rest ]) -
              logistic.cdf(thresholds[ y[y_rest] - 1 ] - X[ y_rest])
        )
    )
    return np.sum(ll_1) + np.sum(ll_2) + np.sum(ll_3)

y = np.array([0, 1, 2])
X = np.array([2, 2, 2])
thresholds = np.array([2, 3])
print(func3(y, X, thresholds))

rawDescription: How to speed up my numpy loop using numpy.where()

description: Speed up my numpy loop using numpy.where()


code: binascii.hexlify('Dummy String')

rawDescription: PHP to python pack('H')

description: PHP to python pack('H')


code:
from decorator import decorator

@decorator
def another_decorator(func, *args, **kwargs):
    return func(*args, **kwargs)

@decorator
@another_decorator
def some_abstract_decorator(func, *args, **kwargs):
    # ... details omitted
    return func(*args, **kwargs)

@some_abstract_decorator
def test(x):
    """ this is a docstring that should be on the decorated function """
    pass

rawDescription: Python - correct order of the application of decorators


code:
from docutils.core import publish_doctree, publish_from_doctree

rst = '*NB:* just an example.'

# step 1
tree = publish_doctree(rst)

# step 2
# do something with the tree

# step 3
html = publish_from_doctree(tree, writer_name='html').decode()
print(html)

rawDescription: How do I convert a docutils document tree into an HTML string?

description: Convert a docutils document tree into an HTML string


code:
wordinput = input('Enter a list of words: ').split()

def keep_secret(l: wordinput) -> list:
    for i in wordinput:
        if i == 'secret':
            continue
        else:
            print (i)

rawDescription: Avoiding to print out a certain word in a list


code:
songdata = [
    SongData('song1', 'artist1', 'dir1'),
    SongData('song2', 'artist2', 'dir2'),
    SongData('song3', 'artist3', 'dir3')
]

rawDescription: How to print out __str__ for each instance of a class in a loop

description: Print out __str__ for each instance of a class in a loop


code:
# Don't even think about using this for negative powers :-)

def isPower (num, base):
    if base == 1 and num != 1: return False
    if base == 1 and num == 1: return True
    if base == 0 and num != 1: return False
    power = int (math.log (num, base) + 0.5)
    return base ** power == num

rawDescription: how to check if a number is a power of base b?

description: Check if a number is a power of base b


code:
class HistoryTrackedModel(models.Model):
    def save(self):
        ...
        history_model = globals()["Historical" + self.__class__.__name__]
        h = history_model(...)

rawDescription: Storing related model references in Django?


code: return type('OrderForm', (StaticForm,), form_fields)

rawDescription: How to subclass from a dynamic WTForm?

description: Subclass from a dynamic WTForm


code:
with open (input_file_name) as fi, open(output_file_name, 'w') as fo:
    fo.writelines(reversed(fi.readlines()))

rawDescription: Python 3 Writing Input file in reverse order to output file


code: my_float_field = cmds.floatField(enable = False)

rawDescription: enable or disable a field in maya ui with python

description: Enable or disable a field in maya ui with python


code: list(itertools.product(*(('*', x) for x in "abc")))

rawDescription: Looking for a tuple substitution algorithm


code: line = map(int, line)

rawDescription: Class and Array Problems

description: Class and Array Problems


code:
seq = "0101"
swapped = ''.join(['1' if b in '0' else '0' for b in seq]) # or maketrans
print(swapped)  # => 1010
print(int(swapped, 2))  # => 10

rawDescription: How to bypass base-8 number identification in python?

description: Bypass base-8 number identification in python


code:
from django.contrib.auth.decorators import user_passes_test
@user_pass_test(lambda u: u.get_profile().type == 'client')
def view_for_client(request):
    ...

rawDescription: How to handle multiple user type in Django

description: Handle multiple user type in Django


code:
a = sel.xpath('//div[@class="result-item-header"]//h2/a')
a.xpath('text()').extract()
a.xpath('@href').extract()

rawDescription: Why can i not crawl this website with Scrapy


code: flights = {f.pop('flight_id'): f for f in flights}

rawDescription: How do I use a dictionary value as a key name in another dictionary?

description: Use a dictionary value as a key name in another dictionary


code:
mylist = [['Installation', '64%'], ['C2', '14%'], ['NA', '14%'], ['C2', '14%'], ['NA', '14%'], ['na', '7%']]
seen = set()
newlist = []
for item in mylist:
    t = tuple(item)
    if t not in seen:
        newlist.append(item)
        seen.add(t)
newlist

rawDescription: Remove Duplicates in two-dimensional array while maintaining sequence


rawDescription: Python. How to make list from another list by mark?


code:
len22seqs = [s for s in data['Sequences'] if len(s)==22]
# alternatively:
len22seqs = filter(lambda s: len(s)==22, data['Sequences'])

rawDescription: Split string into list, then split list into list of lists


code: my_arr = np.array(itertools.islice(f(), 3))

rawDescription: Get a fixed number of items from a generator


rawDescription: Get the commands distutils passes to the compiler


rawDescription: Dividing an Dataframe by an measure with overlapping indexes results in NAN


code:
from ast import literal_eval

lis

rawDescription: How to load a nested list from a file without quotation marks?

description: Load a nested list from a file without quotation marks


rawDescription: summing nested dictionary entries

description: Summing nested dictionary entries


code: re.findall('%%.*?%%', s, re.DOTALL) # Even this works !!!

rawDescription: How to make Python's findall regular expression method inclusive

description: Make Python's findall regular expression method inclusive


rawDescription: is TensorSharedVariable in theano initilized twice in function?

description: Is TensorSharedVariable in theano initilized twice in function


code:
if 'video' in mylist:
    files.append('/home/dbs/public_html/download/codex/codex.html')
if 'audio' in mylist:
    files.append('/home/dbs/public_html/download/audio/audio_player.html')
if 'visual' in mylist:
    files.append('/home/dbs/public_html/download/visual/visual.html')

rawDescription: Python "and if" equivalent

description: Python "and if" equivalent


code:
import numpy as np
np.arange(80., 90., .5)

rawDescription: How to get list of the range consisting of floats?

description: Get list of the range consisting of floats


code:
d = {"A":"some_string",
     "B":12,
     "C":83,
     "D":56}

# Map your validation functions to the keys
validations = {
    "A": lambda x: isinstance(x, str),
    "B": lambda x: isinstance(x, int) and 1 <= x <= 20,
    "C": lambda x: isinstance(x, int) and 1 <= x <= 100,
}

for k, v in d.items():
    print(validations.get(k, lambda x: False)(v))  # Default validation just returns False (invalid)

rawDescription: Python: Validating each values in dictionary


code:
from itertools import product
prod = list(product(*l)) # get all possible products of the elements

def grouper(n, iterable):
    args = [iter(iterable)] * n
    return zip(*args) # izip is gone in python3 as zip now returns an iterator instead of a list

groups = grouper(len(prod)// 4,prod) # group prod in 4 equal groups(len of each sub list)

count = 0
flatten_y = []  # keep list of elements of all products that equal 34
for comb in groups:
    # check if any product is equal to 34 in groups
    check = [c for c in comb if sum(c) == 34]
    flatten_y += [y for x in check for y in x]
    if check:
       count += 1 # if at least one of the products for each comb equals 34 add 1 to counter
flatten_l = [ x for y in l for x in y] # flatten original list to compare elements
# if each comb had a product that equaled 34 count should equal 4
# if we used all elements in l we satisfied our requirement
if count == 4 and all(item in flatten_y for item in flatten_l):
    print (l) # print original list as we have met

rawDescription: How to do a three level for loop

description: Do a three level for loop


code:
class BaseHandler(tornado.web.RequestHandler):
    @tornado.web.removeslash
    def get_current_user(self):
         return self.get_secure_cookie("name_of_your_cookie")

rawDescription: WebService with Tornado.web and Authentication. Do you have Example?


code:
def func3(file):
    for x in range(10):
        x = str(x)
        with open(file, "a") as k:
            k.write(x)

rawDescription: Python: when writing to a large file, keep the file open or to open it and append to it as needed?


code:
l = num_replace(easy,0)
l

''.join(num_replace(l,1))

rawDescription: Replacing items in a list one at a time

description: Replacing items in a list one at a time


code:
dict.fromkeys('abc')
D.fromkeys('abc')

rawDescription: How would I implement a dict with Abstract Base Classes in Python?


code: data = [[]] * number_of_needed_lists

rawDescription: Dynamically size list of lists

description: Dynamically size list of lists


rawDescription: How to sort a string alphabetically, with lower case letters coming before their upper case equivalents?

description: Sort a string alphabetically, with lower case letters coming before their upper case equivalents


code:
combined = dict()
for name in set(dictOne.keys() + dictTwo.keys() + dictThree.keys()):
  combined[name] = [ dictOne.get(name, 0), dictTwo.get(name, 0), dictThree.get(name, 0) ]

rawDescription: Merging 2d arrays

description: Merging 2d arrays


rawDescription: Adjust Choice in Django CharField using Current Date


rawDescription: Parsing a Moses config file

description: Parsing a Moses config file


rawDescription: Insert a new action only if the loop restart because of the while


rawDescription: Scrapy: How to extract all words that are inside HTML-tags?


code:
from sensors import *
from actuators import *

class AbstractNode:
    sensors = [] # Set of classes.
    actuators = [] # Set of classes.
    def __init__(self):
        self.composite_sensor = CompositeSensor(self.sensors)
        self.composite_actuator = CompositeActuator(self.actuators)

class MyNode(AbstractNode):
    sensors = [UltrasonicSensor, SickLaserSensor]
    actuators = [MovementActuator, CommunicationActuator]

    def think(self):
        measurement_map = self.composite_sensor.read()
        while self.composite_actuator.get_position()[1] >= 0:
            self.composite_actuator.move(100, -100)

my_node = MyNode()
my_node.think()

rawDescription: Discussion of multiple inheritance vs Composition for a project (+other things)


code: reverse = OD(attributes.items()[::-1])

rawDescription: Reverse AND inverse python3.x OrderedDict efficiently


code:
def flatten(seq):
    for item in seq:
        if not isinstance(item, str): #Use `basestring` in 2.x
            yield from item
            #For Python <3.3
            #for subitem in item:
            #    yield subitem
        else:
            yield item

rawDescription: Python: print list of list in a specified format


code:
import contextlib
with contextlib.closing(h5py.h5f.open(
                        filename, flags=h5py.h5f.ACC_RDWR, fapl=propfaid)) as fid:
    # <h5py.h5f.FileID object at 0x9abc694>
    settings = list(fid.get_access_plist().get_cache())
    print(settings)
    # [0, 521, 5242880, 0.75]

rawDescription: How to set cache settings while using h5py high level interface?

description: Set cache settings while using h5py high level interface


rawDescription: Plot specific column after DataFrame aggregation


code: [''.join(combo) for combo in set(permutations(x * 2))]

rawDescription: Python permutations of x unique characters repeated y times each


code:
for filename in os.listdir('.'):
    for pattern in ['buffer*', 'grid*', 'OSMroads*',
                    'newCostSurface*','standsLine*', 'standsReprojected*']:
        if fnmatch.fnmatch(filename, pattern):
            os.remove(filename)

rawDescription: Delete files with different names in Python


code:
import numpy as np
x = x=np.arange(0,15,0.01)
from numpy import exp,pi
y=exp(-0.3*x)*exp(x*pi*20j)+exp(-0.9*x)*exp(x*pi*25j)+exp(-0.9*x)*exp(x*pi*15j)
ft = np.fft.fft(y)
np.trapz(ft[105:121])
sum(ft[105:121])

rawDescription: Calculating Area Under Individual Peaks in Python After FFT


code:
class SFTPConnection(SSHConnection):
    def serviceStarted(self):
        self.openChannel(SFTPSession())

rawDescription: twisted conch filetransfer

description: Twisted conch filetransfer


code:
def checkQuarter(self):
    self.quarterIndex = 0
    for i in xrange(4):
        if self.quarterMins[i] > 0:
            self.quarterIndex = i
            self.playerMins = -4 + i
            break
    else:
        return False

rawDescription: How would you code this? Should I use a loop or keep it how I have it coded?


rawDescription: Extract data with BeautifulSoup

description: Extract data with BeautifulSoup


code:
import os
from multiprocessing import Pool

print(os.getpid(), 'parent')

def func(i):
    print(os.getpid(), 'first', end=" | ")
    if 'func' in globals():
        print(globals()['func'], end=" | ")
    else:
        print("no func in globals", end=" | ")
    if 'func2' in globals():
        print(globals()['func2'])
    else:
        print("no func2 in globals")

print('------ map-1')
pool1 = Pool(2)
pool1.map(func, range(2))         #map-1

def func2(i):
    print(os.getpid(), 'second', end=" | ")
    if 'func' in globals():
        print(globals()['func'], end=" | ")
    else:
        print("no func in globals", end=" | ")
    if 'func2' in globals():
        print(globals()['func2'])
    else:
        print("no func2 in globals")

func2.__qualname__ = func.__qualname__

func = func2

print('------ map-2')
pool1.map(func,  range(2))        #map-2
print('------ map-3')
pool1.map(func2,  range(2))       #map-3

pool2 = Pool(2)
print('------ map-4')
pool2.map(func,   range(2))       #map-4
print('------ map-5')
pool2.map(func2,  range(2))       #map-5

rawDescription: Python multiprocessing Pool Interaction With Namespace At Creation


code:
def level_for_accel(accel):
    # return next matching log level for the given accel value
    return next(lev[1] for lev in levels if lev[0] <= accel)

logging.log(level_for_accel(accel), "Collision with %0.1fG impact.", accel)

rawDescription: Python logging level based on variable value?


code:
# pass the selected school id form template to your view
url(r'^school/(?P<school_id>\d+)/$', schoolDetails),

rawDescription: Django, How to pass data object from one template to another template


rawDescription: can we code time in text widget?

description: Can we code time in text widget


code: INIT = open(os.path.join(HERE, PACKAGE_NAME, '__init__.py')).read()

rawDescription: setuptools dependency and import issue

description: Setuptools dependency and import issue


code: dist = np.einsum('ijk,ijk->ij', deltas, deltas)

rawDescription: more efficient way to calculate distance in numpy?

description: More efficient way to calculate distance in numpy


rawDescription: Python/Regex - Expansion of Parentheses and Slashes


code: ['heavy lorry', 'crashed into the building']

rawDescription: Text alignment: extracting matching sequence using python


code:
from django.contrib.sitemaps.views import sitemap

def locale_sitemaps(request):
    # assuming you make a "sitemaps" dict here of {language_code: sitemap}
    return sitemap(request, sitemaps=sitemaps[request.LANGUAGE_CODE])

rawDescription: Django: Change URL's keyword argument on current language


code:
sample = ['AS6.json', 'AS7.json', 'AS8.json', 'AS9.json', 'BS1.json', 'BS2.json', 'BS3.json', 'BS4.json', 'BS5.json', 'CS1.json', 'CS2.json', 'CS3.json', 'CS4.json', 'CS5.json', 'CS6.json', 'DS10.json', 'DS11.json', 'DS4.json', 'DS5.json', 'DS6.json', 'DS7.json', 'DS8.json', 'DS9.json', 'ES4.json', 'ES5.json', 'ES6.json', 'FS5.json', 'FS6.json', 'FS7.json', 'FS8.json', 'MS4.json', 'MS5.json', 'MS6.json', 'MS7.json', 'MS8.json', 'MS9.json', 'NR1.json', 'NR2.json', 'NR3.json', 'NR4.json', 'NR5.json', 'NR6.json', 'NR7.json', 'NR8.json', 'VR1.json', 'VR2.json', 'VR3.json', 'VR4.json', 'VR5.json', 'VR6.json', 'VR7.json', 'VR8.json', 'XS11.json', 'XS9.json']
def find_latest(lst):
    prefixes = {}
    for entry in lst:
        code, value = entry[:2], int(entry.partition('.')[0][2:])
        if value > prefixes.get(code, (float('-inf'), ''))[0]:
            prefixes[code] = (value, entry)
    return [entry for value, entry in prefixes.values()]

find_latest(sample)

rawDescription: maximum value of a unique string in a list

description: Maximum value of a unique string in a list


code: filelist = output.splitlines()

rawDescription: How do i get list of subdirectories contains specific file (ie. '__main__.py) using Python

description: Get list of subdirectories contains specific file (ie. '__main__.py) using Python


code: g['B'].tolist()  # shorthand for .apply(lambda s: s.tolist()) "automatic delegation"

rawDescription: How to create multiple value dictionary from pandas data frame

description: Create multiple value dictionary from pandas data frame


code:
def extract_xml_from_zip(zip_file,this_xml):
    # extract the request xml file from the given zip_file
    return result

class XMLzip(object):
    def __init__(self, xzipfile):
        self.xzipfile = xzipfile
        self.xml1 = extract_xml_from_zip(xzipfile,"xml1")
        self.xml2 = extract_xml_from_zip(xzipfile,"xml2")

    def do_stuff(self):
        ...

rawDescription: Can I add methods into def __init__?

description: Add methods into def __init__


code:
def get_primes(my_nums):
    '''
    Return only prime numbers from inputted list.
    '''
    my_primes = pickle.load(open('primes_set.pkl', 'rb'))
    return [num for num in my_nums if num in my_primes]

rawDescription: How to save a list and access values in a list in Python--- .txt file

description: Save a list and access values in a list in Python--- .txt file


code:
'''
    HTTP/1.0 200 OK\r\n
    Content-Type:text/html\r\n'''

rawDescription: Why is my Python sockets web-server code failing?


code: start += end

rawDescription: Python: Range() as a dictionary value

description: Python: Range() as a dictionary value


code: [a+b for a,b in itertools.izip(l,k)]

rawDescription: correct style for element-wise operations on lists without numpy (python)

description: Correct style for element-wise operations on lists without numpy (python)


code: bln = x.getColN(n)

rawDescription: In python 3, how can I convert a function into an attribute


code:
import re
s = "Back in BLACK, I hit the sAck, I've been too LOng I'm glad to be back."
regex = re.compile(r'black', flags=re.IGNORECASE)
regex.sub('b***', s)

rawDescription: How to replace multiple words in a string through Python in a case insensitive way?

description: Replace multiple words in a string through Python in a case insensitive way


code:
c2 = C(name='c2')
c2.a = a1
c2.b = b1

sess = create_session(name)
sess.add(c2)
sess.commit()
sess.close()

rawDescription: Adding related data to a MySQL database with sqlalchemy


code:
from ui_objects import Ui_Objects  # this is class created with QtDesigner, name of class is a 'Ui_' + name of main Object in QtDesigner

class Objects(QtGui.QWidget):

    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.ui = Ui_Objects()
        self.ui.setupUi(self)

    # then you can add your own code, in example connect your own methods to actions for widgets

rawDescription: Creating widgets in a different class

description: Creating widgets in a different class


code:
if mile_conv > min_mile :
    print ('The result would be', format(mile_conv,'.2f'),'kilometers.')
    return True

else:
    return False

rawDescription: python 3 - limiting invalid inputs

description: Python 3 - limiting invalid inputs


rawDescription: Python: Find subsets across many-to-many mapping


code:
from matplotlib import pyplot as PLT

v_hist = NP.ravel(v)   # 'flatten' v
fig = PLT.figure()
ax1 = fig.add_subplot(111)

n, bins, patches = ax1.hist(v_hist, bins=50, normed=1, facecolor='green')
PLT.show()

rawDescription: Histogram in Matplotlib with input file

description: Histogram in Matplotlib with input file


rawDescription: What is the proper way to format a multi-line dict in Python?


code:
parser.add_argument('-p', '--path',
                    help="The path to a file to read")

rawDescription: Can I check if a value was supplied by the default or by the user?

description: Check if a value was supplied by the default or by the user


rawDescription: How to separate nested JSON

description: Separate nested JSON


rawDescription: Python: place a characters in string

description: Python: place a characters in string


code:
#!/usr/bin/python

import Image            # basic image processing/manipulation, just what we want

im = Image.open('img.png')       # open the image file as a python image object
with open('data.dat', 'w') as f: # open the data file to be written
    for i in range(im.size[0]):  # loop over columns
        counter = sum(im.getpixel((i,j)) for j in range(im.size[1]))
        f.write(str(i)+'\t'+str(counter)+'\n')  # write to data file

rawDescription: Histogram of an Image's "Black Ink Level" by Horizontal Axis


code:
import functools

def trackcalls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.has_been_called = True
        return func(*args, **kwargs)
    wrapper.has_been_called = False
    return wrapper

@trackcalls
def example():
    pass

example()

#Actual Code!:
if example.has_been_called:
   print("foo bar")

rawDescription: Find Out If a Function has been Called

description: Find Out If a Function has been Called


code:
myclass1 = MyClass(5)
id(myclass1)
example.Add(myclass1)
myclass1 = MyClass(3)
id(myclass1)
example.Add(myclass1)
example.container
hex(id(myclass1))
myclass1 is example.container[1]
example.Remove(myclass1)
example.container

rawDescription: Is Python Object Instance a unique object in the language?


code: print('Hello!', end='')

rawDescription: Practical difference between keyword "print" and function "print" in Python


code:
import requests

newUrl = "http://www.bseindia.com/Msource/IndexMovers.aspx?ln=en"
response = requests.get(newUrl).text
commaItems = response.split(",")

#create list of stocks, each one containing information
#index 0 is the name, index 1 is the price
#the last item is not included because for some reason it has no price info on indexMovers page
stockInformation = []
for i, item in enumerate(commaItems[:-1]):
    if i % 6 == 0:
        newList = [item, commaItems[i+1]]
        stockInformation.append(newList)

#print each item and its price from your list
for item in stockInformation:
    print(item[0], "has a price of", item[1])

rawDescription: Extract using Beautiful Soup

description: Extract using Beautiful Soup


code:
import numpy as np
P=2.45
S=[22, 33, 45.6, 21.6, 51.8]
SP = P*np.array(S)
SP_LIST =list(SP)

rawDescription: Python - multiple list by a scalar

description: Python - multiple list by a scalar


code:
def resume_download(fileurl, resume_byte_pos):
    resume_header = {'Range': 'bytes=%d-' % resume_byte_pos}
    return requests.get(fileurl, headers=resume_header, stream=True,  verify=False, allow_redirects=True)

rawDescription: How to resume file download in Python?

description: Resume file download in Python


code: return int(frac * (2 ** adc_res))

rawDescription: What is causing a negative bias in my super-sampling simulation?


code:
#!/usr/bin/env python
# encoding: utf-8
import scrapy

class MySpider(scrapy.Spider):
    name = 'redditscraper'
    allowed_domains = ['reddit.com', 'imgur.com']
    start_urls = ['https://www.reddit.com/r/nsfw']

    def request(self, url, callback):
        """
         wrapper for scrapy.request
        """
        request = scrapy.Request(url=url, callback=callback)
        request.cookies['over18'] = 1
        request.headers['User-Agent'] = (
            'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, '
            'like Gecko) Chrome/45.0.2454.85 Safari/537.36')
        return request

    def start_requests(self):
        for i, url in enumerate(self.start_urls):
            yield self.request(url, self.parse_item)

    def parse_item(self, response):
        titleList = response.css('a.title')

        for title in titleList:
            item = {}
            item['url'] = title.xpath('@href').extract()
            item['title'] = title.xpath('text()').extract()
            yield item
        url = response.xpath('//a[@rel="nofollow next"]/@href').extract_first()
        if url:
            yield self.request(url, self.parse_item)
        # you may consider scrapy.pipelines.images.ImagesPipeline :D

rawDescription: How to send cookie with scrapy CrawlSpider requests?

description: Send cookie with scrapy CrawlSpider requests


code: out.write('{}, {}, {}, {}\n'.format(key, *tuple(counts)))

rawDescription: Merge three csv files with same headers in Python


code:
from numpy.linalg import norm
norm(X, axis=1, ord=1)
norm(X, axis=1, ord=2)
norm(X, axis=1, ord=np.inf)

rawDescription: Normalizing rows of a matrix python

description: Normalizing rows of a matrix python


code:
ww2 = []
for mp in mayorPowers:
    ww2.extend(mp)
ww2

rawDescription: Adding Lists Elements to 'Mega List'

description: Adding Lists Elements to 'Mega List'


rawDescription: How to start a batch file from within a python script and detach from it

description: Start a batch file from within a python script and detach from it


code:
import matplotlib.pyplot as plt

fig = plt.figure()

fig.patch.set_facecolor('blue')
fig.patch.set_alpha(0.7)

ax = fig.add_subplot(111)

ax.plot(range(10))

ax.patch.set_facecolor('red')
ax.patch.set_alpha(0.5)

# If we don't specify the edgecolor and facecolor for the figure when
# saving with savefig, it will override the value we set earlier!
fig.savefig('temp.png', facecolor=fig.get_facecolor(), edgecolor='none')

plt.show()

rawDescription: How to set opacity of background colour of graph wit Matplotlib

description: Set opacity of background colour of graph wit Matplotlib


code:
if __name__ == "__main__":
    print_nested_count(rules)
    for line in string_rules: print(line)

rawDescription: Recursively getting all nested elements from a Dictionary


rawDescription: Filling Many2many field (odoo 8)

description: Filling Many2many field (odoo 8)


code:
whole_data = []
grab_lines = False
with open('input','r') as atom_file:
    molecule_data = ['23\n\n']
    for line in atom_file:
        if line.startswith('coordinates'):
            grab_lines = True
            continue
        elif line.startswith('velocities'):
            grab_lines = False
            if molecule_data:
                #just checks that we aren't appending an empty list.
                molecule_data.append('\n')
                whole_data.append(molecule_data)
                molecule_data = ['23\n\n']
        if grab_lines: #in python 'is True' is implicit for many types.
            molecule_data.append(line)

with open('output','w') as out_file:
    for molecule in whole_data:
        out_file.write(''.join(molecule))

rawDescription: How to extract data from a text file with python script?

description: Extract data from a text file with python script


code: myPanel.SetScrollbar(wx.VERTICAL, 0, 0, 2, 0)

rawDescription: Disablling scrolling of a scroll bar while keeping it visible in wxPython


code:
def is_unbound_method(func):
    return getattr(func, '__self__', 'sentinel') is None

rawDescription: How to test if an object is a function vs. an unbound method?

description: Test if an object is a function vs. an unbound method


code:
import logging
logging.info('I am saying hi in a thread-safe manner')

rawDescription: run a python program on a new thread

description: Run a python program on a new thread


code:
stuff = []
for f in glob.glob("*/*.py"):
    stuff.append((os.path.join("Folder1/Folder2", os.path.dirname(f)), [os.path.join(os.path.dirname(f),os.path.basename(f))] ))
stuff.append( ('esri/toolboxes', ["Master.foo"]))

rawDescription: How to deploy to a new directory structure with setuptools

description: Deploy to a new directory structure with setuptools


code: zero = filter(lambda i: '0' in x[i], range(len(x)))

rawDescription: Placing a for loop within map?

description: Placing a for loop within map


code: x = [(lambda: x) for x in range(3)]

rawDescription: `x = [lambda: x for x in range(3)]`, what will `x[0]()` return?


code:
for sublist in lst:
    condition = True
    for num in sublist:
        if num % 2 != 0:
            condition = False
            break

rawDescription: Python - return the list of lists in lst that contain only integers?


rawDescription: compare file line by line python

description: Compare file line by line python


code:
#!/usr/bin/env python3
import sys
from datetime import date, timedelta

def gen_calendar(year=None):
    if year is None:
        year = date.today().year

    current = date(year, 1, 1)
    delta   = timedelta(days=1)

    while current.year == year:
        yield current.strftime('%a %b %d')
        current += delta

if __name__ == '__main__':
    year = None
    if len(sys.argv) > 1:
        year = int(sys.argv[1])

    for str_date in gen_calendar(year):
        print(str_date)

rawDescription: Making a .txt file calendar in Python 3.2 WITHOUT using .calendar


code:
for word, number in templist:
    if word in compare_dict['word']:
        compare_dict['idf'][word] = number
    else:
        compare_dict['idf'][word] = 0

rawDescription: Compare list with multiple values

description: Compare list with multiple values


code:
server = xmlrpclib.ServerProxy("http://admin:admin@localhost:8080/plone")
server.get_schema('Document')
baduser_server = xmlrpclib.ServerProxy("http://bad:bad@localhost:8080/plone")
baduser_server.get_schema('Document')

rawDescription: xmlrpclib, wsapi4plone - check username and password

description: Xmlrpclib, wsapi4plone - check username and password


code:
count = {}

def recur(n):
    if n not in count:  # memoize
        if n == 1:
            count[n] = 0  # finished
        else:
            count[n] = recur(n//2 if n % 2 == 0 else 3*n + 1)
        count[n] += 1  # this step
    return count[n]

for i in range(1, 100):
    recur(i)

for item in sorted(count.items()):
    print(item)

rawDescription: Longest Collatz Sequence- Memoization- Python- Iterative vs Recursive


code:
class OAuthRemoteApp(object):
    def authorized_handler(self, f):
        def decorated(*args, **kwargs):
            data = 'resp'
            args = args[:1] + (data,) + args[1:]
            return f(*args, **kwargs)
        return decorated

vk = OAuthRemoteApp()

class ClientView(object):
    @vk.authorized_handler
    def authorized(self, resp):
        print(self, resp)

cv = ClientView()
cv.authorized()

rawDescription: Python - Use decorated function in class


code:
def heapsort(sqc):
    def down_heap(sqc, k, n):
        parent = sqc[k]

        while 2*k+1 < n:
            child = 2*k+1
            if child+1 < n and sqc[child] < sqc[child+1]:
                child += 1
            if parent >= sqc[child]:
                break
            sqc[k] = sqc[child]
            k = child
        sqc[k] = parent

    size = len(sqc)

    for i in range(size/2-1, -1, -1):
        down_heap(sqc, i, size)

    for i in range(size-1, 0, -1):
        sqc[0], sqc[i] = sqc[i], sqc[0]
        down_heap(sqc, 0, i)

rawDescription: Heap Sort: how to sort?

description: Heap Sort: how to sort


code:
class Card:
    def __init__(self,pos):
        self.flipping = false
        self.images = loadImages()
        self.frame = 0
        self.pos = pos
    def flip():
        self.flipping = true
    def update():
        if self.flipping:
            self.frame += 1
            self.frame %= len(self.images)
    def draw(screen):
        screen.blit(self.images[self.frame],self.pos)

rawDescription: Short animation class in Pygame?

description: Short animation class in Pygame


code:
sql = 'INSERT INTO aprtable (neighborhood, income, risk_factor, apr) value (?,?,?,?)'
args = ['Brighton', 20000, 10, 0.196]
cursor.execute(sql, args)

rawDescription: Dynamically fill a python dictionary

description: Dynamically fill a python dictionary


code:
sql = "SELECT ProjectMembership.idProjectGroup FROM ProjectMembership \
    WHERE ProjectMembership.idPersonnel = " + str(PersonnelNo)
cursor.execute(sql)
row = cursor.fetchall()

rawDescription: Setting CheckListBox From MySQL Query

description: Setting CheckListBox From MySQL Query


rawDescription: String in a list doesn't accept assignment


code:
f3.pack(side="bottom", fill="x")
f1.pack(side="left", fill="both", expand=True)
f2.pack(side="right", fill="both", expand=True)

rawDescription: Python tkinter place put frame to the bottom


code:
import os
files = []
def Test1(rootDir):
    files.append(rootDir)
    list_dirs = os.walk(rootDir)
    for root, dirs, files in list_dirs:
        for d in dirs:
            files.append(os.path.join(root, d))
        for f in files:
            files.append(os.path.join(root, f))

import os
files = [rootDir]
def Test2(rootDir):
    for lists in os.listdir(rootDir):
        path = os.path.join(rootDir, lists)
        files.append(path)
        if os.path.isdir(path):
            Test2(path)

rawDescription: Print out the whole directory tree

description: Print out the whole directory tree


code:
pat = re.compile(r'\\##### To extract from here ####'
                 '.*?'
                 r'(?=\\##### To extract till here ####)',
                 re.DOTALL)

rawDescription: how to match lines between pattern using re module in python

description: Match lines between pattern using re module in python


code:
dist = scipy.random.permutation(pos*pos)[:c*pos]
grid1D[dist] = myzeros1D[:c*pos]

rawDescription: scipy -- how to insert an array of zeros into another array with different dimensions

description: Scipy -- how to insert an array of zeros into another array with different dimensions


code: vel_x = np.where(np.diff(data['path#'])==0, np.diff(data['x_Pos']), np.inf)

rawDescription: Calculating velocities and acceleration in python for large numpy arrays


code: ws1['D18'] = str(equipment)

rawDescription: Saving an OptionMenu selection to a variable in Tkinter for python 2.7


rawDescription: Regex with end of line in group

description: Regex with end of line in group


rawDescription: Webscraping with Xpath in Python

description: Webscraping with Xpath in Python


rawDescription: How to find mean value for a given part of an Image

description: Find mean value for a given part of an Image


code: d = {"hello": "world"}

rawDescription: How do you read in a text (.txt) file as a .py file in Python 2.7?

description: Read in a text (.txt) file as a .py file in Python 2.7


code:
def split(number, length):
    result = [number//length]*length
    for i in range(number%length):
        result[i] += 1
    return result

rawDescription: Python Intelligent rounding of numbers

description: Python Intelligent rounding of numbers


code:
d = {"B" : ["mangos", "oranges", "apples"]}
df = pd.DataFrame(d)

rawDescription: Pandas: Iterate on a column one row at a time to automate a google search?


code:
foo1 = Foo('ham', 'eggs')
foo2 = Foo('ham', 'eggs')
foo3 = Foo('spam', 'vikings')
foo1 == foo2
foo1 == foo3
hash(foo1)
hash(foo1) == hash(foo2)
hash(foo1) == hash(foo3)
mapping = {}
mapping[foo1] = 'Monty Python'
foo1 in mapping
foo2 in mapping
foo3 in mapping
mapping[foo2]

rawDescription: Creating hashtable in Python 3 for my class


code:
from somemodule import foo
import somemodule
reload(somemodule)
foo()

rawDescription: Python twisted web server caching and executing outdated code


rawDescription: Python slice notation to take only the start and the end part of a list?


code: df.Date1 = pd.to_datetime(df.Date1)

rawDescription: Divide entire DataFrame based on dates in specific columns into quarterly dataframes


code:
#convert merge date and time colums and convert to datetime objects
df['Datetime'] = pd.to_datetime(df['Date'] + ' ' + df['Time'])
df.set_index(pd.DatetimeIndex(df['Datetime'],inplace=True))
df.drop(['Date','Time'], axis=1, inplace=True)

#put last column first
cols = df.columns.tolist()
cols = cols[-1:] + cols[:-1]
df = df[cols]
df = df.dropna()

rawDescription: Sklearn.KMeans() : Get class centroid labels and reference to a dataset


code:
import itertools

# Puts the quoted strings in the odd indices and the unquoted in the even
splitstr = re.split(r'("[^"]*")', myString)

# Process only the even indices
for i, x in itertools.islice(enumerate(splitstr), None, None, 2):
    splitstr[i] = re.sub(r'\bstring', 'foo', x)

# Put it all back together and print
newstring = ''.join(splitstr)
print(newstring)

rawDescription: re.match return match object only if pattern is not inside escaped string

description: Re.match return match object only if pattern is not inside escaped string


code:
def save(obj):
    obj.id = 1

rawDescription: How do I use TDD to create a database representation of existing objects?

description: Use TDD to create a database representation of existing objects


code: type(type('hi'))

rawDescription: Why isn't type(string) equal to "<class 'str'>"?


code: numpy.argwhere(numpy.any(np_array[:, :100] > 1, axis=1) & (np_array[:, 100] < 0))

rawDescription: Numpy argwhere inequality conditions

description: Numpy argwhere inequality conditions


rawDescription: Synchronizing windows clock using GPS

description: Synchronizing windows clock using GPS


code:
import sys

import requests

from my_module import print_smth

print_smth(requests.get('https://google.com'))
print_smth(sys.version)

rawDescription: Import order coding standard

description: Import order coding standard


code:
def save(self, force_insert=False, force_update=False, commit=True):
    # Prep the data
    obj = super(MyClassForm, self).save(commit=False)

    if obj.has_changed():

        # If we're down with commitment, save this shit
        if commit:
            obj.save(force_insert=True)

    return obj

rawDescription: django - comparing old and new field value before saving

description: Django - comparing old and new field value before saving


rawDescription: Plot different DataFrames in the same figure


rawDescription: How can I filter a Haystack SearchQuerySet for None on an IntegerField

description: Filter a Haystack SearchQuerySet for None on an IntegerField


code:
class SubClassWithoutDocstring(ParentWithDocstring):
    def __init__(self):
        try:
            self.__doc__ = next(cls.__doc__ for cls in inspect.getmro(type(self)) if cls.__doc__ is not None)
        except StopIteration:
            pass

SubClassWithoutDocstring().__doc__

rawDescription: Inherit a parent class docstring as __doc__ attribute


code: re.compile("(" + "|".join(regex_strings) + ")")

rawDescription: Python regex list using list

description: Python regex list using list


code:
items = {}
for k, v in zip(priorities, program_names):
    items.setdefault(k, []).append(v)

rawDescription: Python: Split a list into smaller jsons based on another list


code:
d = {}
for assignment in s.split(","):
    name, value = assignment.split("=")
    d[name.strip()] = float(value)

rawDescription: python - break string into variables

description: Python - break string into variables


code:
df.loc[testdate,:] = pd.Series(adddata, dtype='object')
df.dtypes

rawDescription: replacing a pandas dataframe row overwrites all columns' dtypes

description: Replacing a pandas dataframe row overwrites all columns' dtypes


rawDescription: pandas plot dataframe barplot with colors by category

description: Pandas plot dataframe barplot with colors by category


code: lines = raw_input().split(";")

rawDescription: Python equivalent of C++ getline()

description: Python equivalent of C++ getline()


code:
def powerprod(iterable):
    s = list(iterable)
    for r in itertools.count(1):
        for c in itertools.product(s, repeat=r):
            yield c

rawDescription: finding nth combination (incremental approach) of letters (list)

description: Finding nth combination (incremental approach) of letters (list)


rawDescription: How can I write arrays to a file with one column of int values and another float

description: Write arrays to a file with one column of int values and another float


code:
def are_close(users, company, delta):
    from math import cos, pi
    # uses angles in degrees, uses Equirectangular projection
    rx = 6.371E6*pi/180.*cos(company[0]*pi/180)
    ry = 6.371E6*pi/180.
    close = []
    for user in users:
        dx = (user[1]-company[1])*rx
        dy = (user[0]-company[0])*ry
        close.append(True if dx*dx+dy*dy-r*r <= 0 else False)
    return close

rawDescription: Is the User's lat/lng inside the Company's lat/lng boundary


rawDescription: matplotlib PdfPages - storing a lossy copy of a plot with lots of data

description: Matplotlib PdfPages - storing a lossy copy of a plot with lots of data


rawDescription: pandas re-indexing with missing dates

description: Pandas re-indexing with missing dates


code:
data = []
for d in myjson:
    d = d.copy()
    d['tagnames'] = [tagnames_map[t] for t in tagnames_map.viewkeys() & d['tags']]
    data.append(d)

rawDescription: Faster way to do a correspondence replace operation in python?


code: g = df.groupby(['id', 'page'])  # perhaps use as_index=False

rawDescription: validate rows before computing values using python/pandas DataFrame

description: Validate rows before computing values using python/pandas DataFrame


code:
import re
sample = '''\
Vix_CPD c8:d7:19:fb:97:ee -93  149,+1  Y  -- WPA(PSK/AES,TKIP/TKIP) WPA2(PSK/AES,TKIP/TKIP)
Prixvisitante 0a:27:22:f3:3d:e5 -67  1       Y  -- WPA(PSK/AES/AES) WPA2(PSK/AES/AES)
Superprix 06:27:22:f3:3d:e5 -70  1       Y  -- WPA(PSK/AES/AES) WPA2(PSK/AES/AES)
Vivo 4G Plus 08:63:61:8d:95:dc -85  11      Y  -- WPA(PSK/AES,TKIP/TKIP) WPA2(PSK/AES,TKIP/TKIP)
@n18u$Ch@c@l 58:8d:09:1d:c5:a1 -81  11      N  US WPA2(802.1x/AES/AES)
ASM Wifi 00:1a:3f:4b:b4:b2 -79  11      N  BR WPA(PSK/TKIP,AES/TKIP) WPA2(PSK/TKIP,AES/TKIP)
Visitantes 58:8d:09:1d:c5:a0 -79  11      N  US NONE
LEMON 74:ea:3a:fc:a9:68 -81  10,-1   Y  -- WPA(PSK/AES,TKIP/TKIP) WPA2(PSK/AES,TKIP/TKIP)
Superprix 06:27:22:f3:80:9b -33  6       Y  -- WPA(PSK/AES/AES) WPA2(PSK/AES/AES)
Prixvisitante 0a:27:22:f3:80:9b -34  6       Y  -- WPA(PSK/AES/AES) WPA2(PSK/AES/AES)
'''.splitlines()
pattern = re.compile(r'(?P<ssid>.*?)\s+(?P<mac>(?:[a-zA-Z\d]{2}:){5}[a-zA-Z\d]{2})\s+(?P<signal>[-\d]+)')
for line in sample:
    print(pattern.match(line).groupdict())

rawDescription: Can't properly split Wi-Fi signal string by space


code:
parser = argparse.ArgumentParser(
    description='My first argparse attempt',
    epilog='Example of use')

output = parser.parse_args()

rawDescription: Print program usage example with argparse module


code:
#threadHandler.py, save this file in the same folder as tester.py

import threading, time

class MyThreadHandler(object):
    def __init__(self):
        self.oneShots = []
        self.timers = []
        self.oldOneShots = []
        self.latest = None
        self.cleaning = False

        self._startCleaner()

    def _startCleaner(self):
        print('-'*20+'Starting cleaner'+'-'*20)
        self.cleaner = self.createTimer(1, self._cleanupThreads)

    def _stopCleaner(self):
        print('-'*20+'Stopping cleaner'+'-'*20)
        self.cleaner.stop()

    def getNumThreads(self):
        return len(self.oneShots)

    def getNumOldThreads(self):
        return len(self.oldOneShots)

    def end(self):
        for i,timer in enumerate(self.timers):
            timer.stop()
            self.timers.pop(i)

    def createTimer(self, interval, func, *args, **kwargs):
        timer = myTimer(interval, func, args, kwargs)
        self.timers.append(timer)
        return timer

    def createOneShot(self, func, *args, **kwargs):
        oneshot = myOneShot(func, args, kwargs)
        self.oneShots.append(oneshot)
        self.latest = oneshot

    def isLastDone(self):
        if not self.latest is None:
            return not self.latest.running()
        else:
            return None

    def getLastResult(self):
        if self.latest is None:
            raise ValueError('There have not been any oneshots created.')
        while self.latest.running():
            pass
        result = self.latest.getResult()
        if len(self.oneShots) > 0:
            self.oldOneShots.append(myOneShot(self._cleanAll, (self.oneShots,)))
        self.oneShots = []
        return result

    def _cleanAll(self, toClean):
        # loop through toClean and pop up anything that's done. this DOES lock
        while len(toClean) > 0:
            toClean = self._cleanup(toClean)

    def _cleanup(self, toCleanup):
        while not self.cleaning:
            self.cleaning = True
            for i, thread in enumerate(toCleanup):
                if not thread.running():
                    toCleanup.pop(i)
        self.cleaning = False
        return toCleanup

    def _cleanupThreads(self):
        # check each of these lists and pop out any threads that are done. This
        # does not lock. This function should really only be called by the
        # cleaner, which is set up in __init__
        self.oneShots = self._cleanup(self.oneShots)
        self.timers = self._cleanup(self.timers)
        self.oldOneShots = self._cleanup(self.oldOneShots)

class myTimer(object):
    def __init__(self, delay, func, args=tuple(), kwargs={}):
        self.delay  = delay
        self.func   = func
        self.loop   = True
        self.args   = args
        self.kwargs = kwargs
        self.thread = threading.Thread(target=self.run, daemon=True)
        self.thread.start()
        self.output = None

    def run(self):
        while self.loop:
            self.output = self.func(*self.args, **self.kwargs)
            if self.delay > 0.1:
                count = 0
                while count <= self.delay:
                    count += 0.1
                    time.sleep(0.1)
            else:
                time.sleep(self.delay)

    def stop(self):
        self.loop = False

    def running(self):
        return self.loop

    def getResult(self):
        return self.output

class myOneShot(object):
    def __init__(self, func, args=tuple(), kwargs={}):
        self.func = func
        self.args = args
        self.kwargs = kwargs
        self.thread = threading.Thread(target=self.run, daemon=True)
        self.thread.start()
        self.output = None

    def run(self):
        self.output = self.func(*self.args, **self.kwargs)

    def running(self):
        return self.thread.is_alive()

    def getResult(self):
        return self.output

if __name__ == '__main__':
    import random
    random.seed()

    def longFunc(num):
        delay = random.randint(5,8)
        if num in (3, 6):
            delay = 2
        print('-'*30+'func {} has sleep {}'.format(num, delay))
        time.sleep(delay)
        print('-'*30+'func {} is done'.format(num))
        return num

    def checker(handler):
        if handler.isLastDone():
            return handler.getLastResult()
        else:
            return None

    myHandler = MyThreadHandler()

    # The 'checker' function simulates something in my program that uses the
    # data generated by the 'longFunc'. It waits until there are no more threads
    # in the threadHandler, as that would indicate that the user is done
    # switching back-and-forth between different values
    checkTimer = myHandler.createTimer(1, checker, myHandler)

    # create 10 one-shot threads that take a 'long' time. The delay is to keep
    # them in order, as this loop is meant to simulate a user switching between
    # items using a keyboard or mouse, which I imagine they couldn't do any
    # faster than every 1/10th of a second
    start = time.time()
    for i in range(4):
        myHandler.createOneShot(longFunc, i)
        time.sleep(0.1)

    # wait until there are no more threads executing
    last = myHandler.getLastResult()

    print('result from last = {}'.format(last))

    for i in range(4, 7):
        myHandler.createOneShot(longFunc, i)
        time.sleep(0.1)

    last = myHandler.getLastResult()
    print('result from last = {}'.format(last))

    while myHandler.getNumOldThreads() >0 or myHandler.getNumThreads() > 0:
        pass

    myHandler.end()
    print('done ending')

rawDescription: How can I stop a long-running function when it is called multiple times?

description: Stop a long-running function when it is called multiple times


code:
import re
s = 'a12b34'
total = sum(map(int,re.findall(r'-?\d+', s))) # -? is to cover negative values

rawDescription: Splitting a string and adding the digits inside of the string


code:
l = [l1, l2]
for i in itertools.chain.from_iterable(l):
    print(i, end= " ")

rawDescription: Iterating over two lists one after one

description: Iterating over two lists one after one


rawDescription: Python: take the content of a list and append it to another list


rawDescription: What would you use for `n to n` relations in python?


code:
import sys
sys.maxsize
hash('asdf')
hash('asdf') % ((sys.maxsize + 1) * 2)

rawDescription: Positive integer from Python hash() function


rawDescription: pd.apply(pd.Series.interpolate) with more arguments

description: Pd.apply(pd.Series.interpolate) with more arguments


code:
def assignId(val):
    return (idgen.next(), val)

rawDescription: Spark: Using iterator lambda function in RDD map()


code:
def wanted(character):
    return character.isalnum() or character in '\\/'

ascii_characters = [chr(ordinal) for ordinal in range(128)]
ascii_code_point_filter = [c if wanted(c) else None for c in ascii_characters]

def fast_replace(string):
    # Remove all non-ASCII characters. Heavily optimised.
    string = string.encode('ascii', errors='ignore').decode('ascii')

    # Remove unwanted ASCII characters
    return string.translate(ascii_code_point_filter)

rawDescription: How to replace all characters except letters, numbers, forward and back slashes

description: Replace all characters except letters, numbers, forward and back slashes


code: [i * j for i, j in zip(xrange(40, 100), xrange(60))]

rawDescription: What is correct python syntax for this kind of list comprehension?


code: SiteText.objects.create(name="greeting", text="Welcome to my site!")

rawDescription: Django: how to handle data that doesn't fit in a model


code:
for grade in ('A', 'B', 'C', 'D'):
    print("There were %d %s passes" % (gradescount.get(grade, 0), grade))
print("There were %d fails" % (gradescount.get('No grade', 0),))

rawDescription: Counting number of "passes" within a loop


code:
query = MyModel.all(keys_only=True).filter('unique_property', value_to_be_used)
entity = query.get()
if entity:
    raise Exception('unique_property must have a unique value!')

rawDescription: How do I define a unique property for a Model in Google App Engine?

description: Define a unique property for a Model in Google App Engine


code:
class Wrapper:
    def __init__(self, fobj):
        self.fobj = fobj

    def __iter__(self):
        return self

    def __next__(self):
        return parse(next(self.fobj))

rawDescription: types.MethodType and the for loop

description: Types.MethodType and the for loop


code:
blue = Color(name='blue')
blue.save()
red = Color(name='red')
red.save()
my_product = Product()
my_product.save()
my_product.colors.add(blue)

rawDescription: Django filter filter with lists

description: Django filter filter with lists


code:
mask = df['business'].apply(pd.Series).isin(restaurant_categories_list).sum(axis=1) > 0
print(mask)

rawDescription: Filter DataFrame rows that are lists

description: Filter DataFrame rows that are lists


code:
from baseconverter import BaseConverter
from otherconverter import OtherConverter

rawDescription: Organizing Python classes in modules and/or packages


code: thetext = re.sub(r"\(.*?\)", "", thetext)

rawDescription: longest match in python

description: Longest match in python


code: s = 'Error - unexpected string' + 42

rawDescription: Speed vs security vs compatibility over methods to do string concatenation in Python


code:
def create_app(self):
    ...
    app.config['TESTING'] = True  # should off csrf
    ...

def test_root_route(self):
    self.client.post(settings.LOGIN_URL, data={'login': 'l', 'password': 'p'})
    resp = self.client.get('/')
    self.assert_template_used('index.html')

rawDescription: Flask-Testing: issues with session management with unittests


code:
response.content_type = 'application/octet-stream;'
response.set_header('Content-Disposition', 'attachment; filename=myexport.xlsx')
response.body = save_virtual_workbook(workbook)

rawDescription: Return openpyxl workbook object as HttpResponse in django. Is it possible?


code:
#!/usr/bin/env python
import itertools
import re
import sys

try:
    from future_builtins import map, zip
except ImportError: # Python 3 (or old Python versions)
    map, zip = map, zip
from operator import methodcaller

import nltk  # $ pip install nltk
from nltk.corpus import cmudict  # >>> nltk.download('cmudict')

def starts_with_vowel_sound(word, pronunciations=cmudict.dict()):
    for syllables in pronunciations.get(word, []):
        return syllables[0][-1].isdigit()  # use only the first one

def check_a_an_usage(words):
    # iterate over words pairwise (recipe from itertools)
    #note: ignore Unicode case-folding (`.casefold()`)
    a, b = itertools.tee(map(methodcaller('lower'), words))
    next(b, None)
    for a, w in zip(a, b):
        if (a == 'a' or a == 'an') and re.match('\w+$', w):
            valid = (a == 'an') if starts_with_vowel_sound(w) else (a == 'a')
            yield valid, a, w

#note: you could use nltk to split text in paragraphs,sentences, words
pairs = ((a, w)
         for sentence in sys.stdin.readlines() if sentence.strip()
         for valid, a, w in check_a_an_usage(nltk.wordpunct_tokenize(sentence))
         if not valid)

print("Invalid indefinite article usage:")
print('\n'.join(map(" ".join, pairs)))

rawDescription: Verify correct use of "a" and "an" in English texts - Python


code:
for xs in itertools.product(*tuple_grps):
    print(xs)

rawDescription: Python combinations no repeat by constraint


code:
for i in range(30):
    plt.plot(x2[i+0],y2[i+0],'go-',label='HAlpha'if i == 0 else "")

rawDescription: unable to join markers

description: Unable to join markers


rawDescription: numpy.bincount and numpy.argmax function pseudocodes

description: Numpy.bincount and numpy.argmax function pseudocodes


code: a-b-c-d

rawDescription: Python ASCII Graph Drawing

description: Python ASCII Graph Drawing


code:
import tkinter as tk

root = tk.Tk()

TIMEOUT = 3000
i = 0
def task():
    global i
    i += 1
    print('In task(), i={}'.format(i))
    root.after(TIMEOUT, task)
    print('Called root.after() and exiting task()')

root.after(TIMEOUT, task)
root.mainloop()

rawDescription: Will Tkinter after cause waste of resource?


code:
class Foo(object):

  @property
  def BA(self):
      return self.AB

  @BA.setter
  def BA(self, value):
      self.AB = value

rawDescription: 2 names for a same attribute

description: 2 names for a same attribute


code:
def python_inner(n):
    survivors = []
    for row in itertools.product([-1,1], repeat = 2*n):
        if (sum(map(operator.mul, row[0:n], row[n:2*n])) == 0):
            survivors.append(row)
    return len(survivors)

In [2]: python_inner(8)
Out[2]: 17920

In [3]: bitwise_inner(8)
Out[3]: 17920

rawDescription: How to speed up a large number of inner products

description: Speed up a large number of inner products


code: values['Results'] = [x for x in values['Results'] if x[1] is not None]

rawDescription: Removing an list from a list of list

description: Removing an list from a list of list


code:
text = '12121'
result = []

result

rawDescription: Confused by the enumerate() function in tutorials


code:
...
for line in collected_lines:
    child = ET.SubElement(top, line[0])
    child.text = line[1]
...

rawDescription: Append to XML structure in python

description: Append to XML structure in python


code:
class KeyHandlerProxy(BaseProxy):
    _exposed_ = ('next', 'get')

    def __iter__(self):
        return self

    def next(self):
        o = self._callmethod('get')
        if object() == o:
            raise StopIteration
        return o

rawDescription: Python multiprocessing passing refrence

description: Python multiprocessing passing refrence


code:
import ast
with open("name.txt", 'r') as f:
    data = [ast.literal_eval(line) for line in f]

rawDescription: Reading file with lists to list

description: Reading file with lists to list


code:
listOfPlays = [{'title': x, 'author': x, 'year': 1611} for x in ('Shakespeare', 'someone')]
listOfPlays

[x for x in listOfPlays if x['author'] == 'Shakespeare' and x['year'] == 1611]

rawDescription: javascript's _.where in python

description: Javascript's _.where in python


code:
class Player(object):
    def print_cards(self):
        print('I am in Player\'s class.')

class Dealer(Player):
    def print_cards(self):
        print('I am in Dealer\'s class.')
    def print_player(self):
        super(Dealer, self).print_cards()

rawDescription: Use class A method in class B, where B overwrites this method


code:
# Read file, convert strings to lists
fin = open("path/to/file")
lines = fin.readlines()
line2, line4 = list(lines[1]), list(lines[3])

# Make the changes to our lists
for i, c in enumerate(line4):
   if( ord(c) > 53 ):
      line2[i] = 'N'

# Overwrite line 2
lines[1] = ''.join(line2)

# Save back to the file
fin.seek(0)
for line in lines:
   fin.write(line)

fin.close()

rawDescription: iterating over characters in a line and replacing them

description: Iterating over characters in a line and replacing them


code:
if not all(required_options):
    ...

rawDescription: Optparse and a lot of if not

description: Optparse and a lot of if not


code:
df1_melt = pd.melt(df1, id_vars='eID').dropna()
df1_melt

rawDescription: Averaging values between Pandas dataframes with keys existing in one and data in the other


code:
from weakref import ref

class CounterDescriptor(object):

    def __init__(self) -> None:
        self.counts = {}
        self.refs = {}

    def _clean_up(self):
        for id_, ref in self.refs.items():
            if ref() is None:
                del self.counts[id_]

    def __get__(self, instance: object, owner: type) -> object:
        self._clean_up()
        inst_id = id(instance)
        if instance is None:
            return self.counts
        if inst_id not in self.counts:
            self.counts[inst_id] = 0
            self.refs[inst_id] = ref(instance)
        self.counts[inst_id] += 1
        return self.counts[inst_id]

    def __set__(self, instance: object, value: int) -> None:
        self._clean_up()
        inst_id = id(instance)
        self.counts[inst_id] = int(value)
        self.refs[inst_id] = ref(instance)

class SomethingUsingTheCounterDescriptor(object):
    x = CounterDescriptor()
s = SomethingUsingTheCounterDescriptor()
s.x
s.x
print(SomethingUsingTheCounterDescriptor.x)
del s
print(SomethingUsingTheCounterDescriptor.x)

rawDescription: How to let the python descriptor know that an instance of the owning class was deleted

description: Let the python descriptor know that an instance of the owning class was deleted


code:
from scipy import interp, arange, exp
x = arange(0,10)
y = exp(-x/3.0)
interp([9,10], x, y)

rawDescription: How to make scipy.interpolate give an extrapolated result beyond the input range?

description: Make scipy.interpolate give an extrapolated result beyond the input range


code: grouped = df.groupby(lambda x: x[0].lower(), axis=1)

rawDescription: Pandas stack/groupby to make a new dataframe


code:
arr = {}
for x in xs:
    arr[x.index] = x

rawDescription: Dynamically growing a python array when assigning to it


code:
def test_check_with_too_high_pressure(self):
    with patch('tire_pressure_monitoring.Sensor') as test_sensor_class:
        mockSensor = MagicMock()
        mockSensor.sample_pressure.return_value = 22
        test_sensor_class.return_value = mockSensor
        alarm = Alarm()
        alarm.check()
        self.assertTrue(alarm.is_alarm_on)

rawDescription: unittest.mock.patch a class instance, and set method return values

description: Unittest.mock.patch a class instance, and set method return values


code: from PIL import ExifTags, Image

rawDescription: Using Python to extract EXIF tags added by Windows Photo Gallery 2012


rawDescription: How to extract the location of shorter sequence based on longer sequence using Python?

description: Extract the location of shorter sequence based on longer sequence using Python


code:
import random

user_words = input("Enter a word or sentence: ") #Gets user input

word = user_words.split()  #no need of list()

def Jumble_One_Word(x):

    if len(x) > 2: #Only need to change words longer than 2

      first_letter = x[0] #Takes the first letter out and defines it

      last_letter = x[-1] #Takes the last letter out and defines it

      letters = list(x[1:-1]) #Takes the rest and puts them into a list

      random.shuffle(letters) #shuffles the list above

      middle_letters = "".join(letters) #Joins the shuffled list

      final_word = "".join([first_letter, middle_letters, last_letter]) #Puts finalword all back  in place as a list

      return final_word # better return from function inste

for i in word:                 #you can iterate this way too
    print (Jumble_One_Word(i))

rawDescription: Python, defining a function and accessing it


code:
for k in dict:
    user = k
    params = {
    'token': app,
    'user': user,
    'title': 'lala',
    'message': 'test',
    'retry': 300,
    'expire': 40,
    'priority': 2 ,
    'sound': 'siren',
    'ack': False
    }

rawDescription: python acknowlage in pushover using dict

description: Python acknowlage in pushover using dict


code:
import requests
from lxml import html

page = requests.get("http://www.w3schools.com/xpath/")
root = html.fromstring(page.text)
tree = root.getroottree()
result = root.xpath('//*[. = "XML"]')
for r in result:
    print(tree.getpath(r))

rawDescription: python - find xpath of element containing string

description: Python - find xpath of element containing string


code:
{'something_else': 'blah', 'foo': ['bar', 'baz', 'bah']}
{'bar': 'yet_another_thing'}

rawDescription: YAML list -> Python generator?

description: YAML list -> Python generator


code:
LOCALE_PATHS = (
'templates/locale',
)

rawDescription: Django translation and py2exe

description: Django translation and py2exe


code: result = [r for r, in result]

rawDescription: How to retrieve python list of SQLAlchemy result set?

description: Retrieve python list of SQLAlchemy result set


code:
import timeit
timeit.timeit('a = 5')
timeit.timeit('foo()', 'def foo(): a = 5')

rawDescription: Python Function calls are really slow

description: Python Function calls are really slow


code:
def recursive_me(mystring, total = 0):
    if mystring: # recursive case
        return recursive_me(mystring[1:], total + int(mystring[0]))
    else:        # base case
        return total

rawDescription: Python recursive function that retain variable values


code:
_Framework.DB.cursor        #changes made in other module will have effect
_Framework.DB.environment   #changes made in other module will have effect

rawDescription: python package structure and global variables

description: Python package structure and global variables


code:
import colander

class AgentRegistration(colander.Schema):
    """schema for agent registration with email validation

    Note the form validator is invoked only if none of the individual field validators raise an error.
    """

    first_name = colander.SchemaNode(colander.String())
    number = colander.SchemaNode(colander.Integer(), validator=can_register_agent)
    email = colander.SchemaNode(colander.String(), validator=colander.Email())
    verify_email = colander.SchemaNode(colander.String(), validator=colander.Email())

    validator = verify_email_validator

class AgentDeals(colander.Schema):
    "schema for managing agent deals"
    first_name = colander.SchemaNode(colander.String())
    number = colander.SchemaNode(colander.Integer(), validator=validateID)
    email = colander.SchemaNode(colander.String(), validator=colander.Email())

rawDescription: Deform Inter-Field Validation not highlighting field


code:
# In a chart, the palette now has access to all 8
fig, ax1 = plt.subplots(1,1,figsize=(4,3))
df.plot(ax=ax1)
ax1.legend(bbox_to_anchor=(1.2, 1)) ;

rawDescription: Seaborn palettes - prevent recycling of colors


code:
parse('1/2/3/some text and 5/4=3')
None is parse('12/a/412/3/4/Here is some random text, like 5/4=3')

rawDescription: How to convert string input into tuple with integers and a string

description: Convert string input into tuple with integers and a string


code: open('file.txt', 'a')

rawDescription: Python: Putting Charater in front or behind a file


code:
d = 'COADREAD ATF7 Missense_Mutation NGXA-AZ-3984 P17544 A436T'
myid, token = d.rsplit(' ', 2)[1:] # will except if can't be unpacked so you know you've got exactly 2 elements...
token = token[1:-1]

rawDescription: Is there way to find the pharse and capture next token value


code:
import pyPdf
def getPDFContent(path):
    content = ""
    num_pages = 10
    p = file(path, "rb")
    pdf = pyPdf.PdfFileReader(p)
    for i in range(0, num_pages):
        content += pdf.getPage(i).extractText() + "\n"
    content = " ".join(content.replace(u"\xa0", " ").strip().split())
    return content

rawDescription: How to use Python to pick up texts on PDF documents

description: Use Python to pick up texts on PDF documents


rawDescription: Python 2.7: Evaluating pairs in a 2D Python Array


code:
tableData = [['apples', 'oranges', 'cherries', 'banana'],
             ['Alice', 'Bob', 'Carol', 'David'],
             ['dogs', 'cats', 'moose', 'goose']]

# Find the max length of the word in each row
lens = [max(len(col) for col in row) for row in tableData]

# zip(*list) transposes a list...rows become columns
for row in zip(*tableData):
    # Pass the column widths dynamically.
    print('{:>{lens[0]}} {:>{lens[1]}} {:>{lens[2]}}'.format(*row,lens=lens))

rawDescription: nested list displayed in a column

description: Nested list displayed in a column


code:
@register.filter(name='chr')
def chr_(value):
    return chr(value + 65)

rawDescription: Convert int to ascii [chr()] in django template


rawDescription: How to add and compute (based on other columns) a sub-column in a pandas dataframe with hierarchical index?

description: Add and compute (based on other columns) a sub-column in a pandas dataframe with hierarchical index


code:
import matplotlib as mpl
mpl.rcParams['keymap.back'].remove('left')
mpl.rcParams['keymap.forward'].remove('right')

rawDescription: Disable matplotlib's default arrow key bindings


code:
import re

token_pattern = re.compile(r'"csrf_token":\s*"([^"]+)"')

token = token_pattern.search(requests.post(OAuthURL).content).group(1)

rawDescription: Parse request response for key, value pairs


code:
dic = {'Sally':['1346','A','April', {'1346': ('week', 6)}],
       'Annie': ['1347', 'A', 'April', {'1346': ('week', 5)}],
       'Marie': ['0', 'Absent', 'Fall', {}]}

for value in dic.values():
    for element in value:
         if isinstance(element, dict) and '1346' in element:
             element['1346'] = ('month',6)

rawDescription: Scanning and replacing values inside nested dictionary


rawDescription: replace numbers on X axis with dates when using line plot in matplotlib

description: Replace numbers on X axis with dates when using line plot in matplotlib


code:
for e in category.entry_set.select_related('extentry').exlude(extentry=None):
    e.extentry # now this definitely is something, not None

rawDescription: Django ForeignKey _set on an inherited model


code:
S = set(y2) # collect unique label names
D = dict( zip(S, range(len(S))) ) # assign each string an integer, and put it in a dict
Y = [D[y2_] for y2_ in y2] # store class labels as ints

rawDescription: Sklearn trying to convert string list to floats


code:
import pandas as pd
foo = pd.DataFrame([
    ['USA',1,2],
    ['Canada',3,4],
    ['Canada',5,6]
], columns=('Country', 'x', 'y'))
z = foo['x'].where(foo['Country'] == 'USA', foo['y'])
pd.concat([foo['Country'], z], axis=1)

rawDescription: Pandas - conditionally select column based on row value


code:
class Whitelabel(models.Model):
    name = models.CharField(max_length=255, null=False)
    logo = models.CharField(max_length=255, null=True, blank=True)
    primary_domain = models.CharField(max_length=256, null=False)

rawDescription: What is the common practice for white labeling a Django site?


rawDescription: Find count of unique column elements after using groupby with pandas


code: import foo

rawDescription: What is the purpose of __name__?

description: What is the purpose of __name__


code: re.findall('abc.*?xyz', s)

rawDescription: Extracting part of a string

description: Extracting part of a string


code: [key for key in d if '500002' in d[key]]

rawDescription: print corresponding key of dictionary for each element in a set

description: Print corresponding key of dictionary for each element in a set


code:
frequency = {'This': 1, 'is': 2, 'a': 1, 'python': 5, 'dictionary': 1}
frequency2 = [{"key": i, "value": j} for i,j in frequency.items()]

rawDescription: Adding labels to Key Value Pairs in JSON


code:
answer  = [] # final answer
partial = [] # partial answer
for e in lst:
    if e == '':           # if current element is an empty string …
        if partial:       # … and there's a partial answer
            answer.append(''.join(partial)) # join and append partial answer
            partial = []  # reset partial answer
    else:                 # otherwise it's a new element of partial answer
        partial.append(e) # add it to partial answer
else:                     # this part executes after the loop exits
    if partial:           # if one partial answer is left
        answer.append(''.join(partial)) # add it to final answer

rawDescription: How to join certain items in list

description: Join certain items in list


code:
EXTENSIONS = {
    # SpiderDetails class is in the file mybot/extensions.py
    'mybot.extensions.SpiderDetails': 1000,
}

rawDescription: How to get Python Scrapy Crawler details?

description: Get Python Scrapy Crawler details


code: pd.DataFrame([df[k]==v for k,v in di.iteritems()]).all()

rawDescription: pandas: select all rows matching multiple conditions

description: Pandas: select all rows matching multiple conditions


code:
case_top = soup.find_all(style=re.compile("border-top:solid 1px #666"))
for case in case_top:
    wrapper = soup.new_tag('div', **{'class': 'case'})
    case.insert_before(wrapper)
    while wrapper.next_sibling:
        wrapper.append(wrapper.next_sibling)
        if wrapper.find('table', class_='bookinfo'):
            # moved over the bookinfo table, time to stop
            break

rawDescription: How to insert unescaped html fragment in Beautiful Soup 4

description: Insert unescaped html fragment in Beautiful Soup 4


rawDescription: How do to tighten the bounds of my 'matplotlib' figures to be closer to my axes?


code:
['accggt', 'gggatc']
['gggatc', 'accggt']
['gggatc', 'ccttgg']
['ccttgg', 'gggatc']

rawDescription: Compare strings and just keep those who have on same positions different characters


code: APIMethod(api, 'users')

rawDescription: Why can I call all these methods that aren't explicitly defined in a class?


code:
list = name_list(file)
for name in list:
    print('Name: {0} {1}'.format(name._first, name._last))

rawDescription: How to implement list of names into a pre-made class?

description: Implement list of names into a pre-made class


code: ar = [('four' if i % 4 == 0 else ('six' if i % 6 == 0 else i)) for i in range(1, n)]

rawDescription: Multiple IF conditions in a python list comprehension


code: all_sents = file_sent.read().replace('\n', ' ')

rawDescription: formatted Input from file in Python

description: Formatted Input from file in Python


code:
from wtforms.fields import Field

class PlainTextWidget(object):
    def __call__(self, field, **kwargs):
        return field.data if field.data else ''

rawDescription: WTForms - display property value instead of HTML field


code:
polls = Poll.objects.select_related('pollchoice__poll').all()
return render(request, 'test_poll.html', {'polls': polls})

rawDescription: 'Tree-like' dropdown list traversing ForeignKeys in Django


code: result = rows[:1] + sorted(rows[1:], key=itemgetter(1))

rawDescription: Python - Remove list(s) from list of lists (Similar functionality to .pop() )


code:
def afunc(some_param_name):
    assert isinstance(some_param_name, SomeClassName), (
           'some_param_name must be an instance of SomeClassName, '
           'silly goose!')

rawDescription: How to format a python assert statement that complies with PEP8?

description: Format a python assert statement that complies with PEP8


code: report = "Total gold acquired: " + str(self.gold_total)

rawDescription: Why does this python method return a memory address?


code: show(ptr, 0)

rawDescription: Windows Common Item Dialog: ctypes + COM access violation


code:
class Stack:
    def __init__(self):
        self.items = []

    def push(self,item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def show(self):
        print (self.items)

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

stack = Stack()

stack.push('World!')
stack.push('Hello')

while stack:  # tests the length through __len__
    print(stack.pop())

rawDescription: Stacks iteration python3

description: Stacks iteration python3


code:
@someDecorator()
def someMethod():
    pass

rawDescription: Using python decorator with or without parentheses


rawDescription: Mapping diagonal elements recursively and check for condition, Python


code:
output
0
2
4

rawDescription: Control a separate process in python using multiprocessing module


code:
aggs = pd.DataFrame({'zero_count': (df == 0).sum(), 'sum': df.sum()})
col_order = aggs.sort(['zero_count', 'sum'], inplace=False).index
df[col_order]

rawDescription: Order columns of DataFrame according to values


code:
for line in file:
   print(line)

rawDescription: Trying to read all lines in a file and pick out the ones that begin with 'H' or 'S'


code: csv_input = csv.reader(f_input, delimiter=' ', skipinitialspace=True)

rawDescription: Create a list of lists / matrices from a text file in Python 3.4


code:
import pandas
a=[['Date', 'letters', 'numbers', 'mixed'], \
   ['1/2/2014', 'a', '6', 'z1'],\
   ['1/2/2014', 'a', '3', 'z1'],\
   ['1/3/2014', 'c', '1', 'x3']]
df = pandas.DataFrame.from_records(a[1:],columns=a[0])
df['new'] = df['Date'] + ' ' + df['letters']

n = len(df.columns)
b = [['NA'] * n]
df_a = pandas.DataFrame.from_records(b,columns=df.columns)
df_b = pandas.concat([df,df_a])

rawDescription: pandas dataframe concat with 'NA'

description: Pandas dataframe concat with 'NA'


code:
class SomeDictSetterType(type):
    def __init__(self, name, bases, attrs):
        self.some_dict[self] = True
        super(SomeDictSetterType, self).__init__(name, bases, attrs)

class Test(object):
    __metaclass__ = SomeDictSetterType
    some_dict = {}

rawDescription: class __init__ (not instance __init__)

description: Class __init__ (not instance __init__)


code:
# assumes Python 2.7

PARAMETERS_FILE = "parameter_values.pc"
PATTERN_FILE    = "pattern.pc"
OUTPUT_NAME     = "pattern_p1_{p1}_p2_{p2}.pc"

def strs(line, split_on=None):
    return [s.strip() for s in line.split(split_on)]

def main():
    with open(PATTERN_FILE) as inf:
        template = inf.read()

    with open(PARAMETERS_FILE) as inf:
        p1_lst = strs(next(inf, ""), ",")
        p2_lst = strs(next(inf, ""), ",")

    for p1, p2 in zip(p1_lst, p2_lst):
        fname = OUTPUT_NAME.format(p1=p1, p2=p2)
        data = template.replace("<p1>", p1).replace("<p2>", p2)
        with open(fname, "w") as outf:
            outf.write(data)

if __name__=="__main__":
    main()

rawDescription: Parameter study using python

description: Parameter study using python


code: apple

rawDescription: compare two file and find matching words in python

description: Compare two file and find matching words in python


code:
import matplotlib.pyplot as plt
import pandas as pd
import pandas.io.data as web

start = pd.datetime(2013, 1, 1)
end = pd.datetime(2013, 1, 10)

eon = web.DataReader("EOAN.DE", 'yahoo', start, end)
rwe = web.DataReader("RWE.DE", 'yahoo', start, end)
closes = pd.concat({ "eon" : eon["Close"], "rwe" : rwe["Close"]}, axis=1)
closes.plot()

rawDescription: Trying to merge dataFrame

description: Trying to merge dataFrame


rawDescription: select rows in pandas DataFrame using comparisons against two columns

description: Select rows in pandas DataFrame using comparisons against two columns


code:
s
s.reset_index()

rawDescription: Pandas reset index on series to remove multiindex


code:
from tvtk.api import tvtk; from mayavi import mlab; import numpy as np

x,y,z=np.random.random((3,nr_points)) #some data
colors=np.random.randint(256,size=(100,3)) #some RGB or RGBA colors

pts=mlab.points3d(x,y,z)
sc=tvtk.UnsignedCharArray()
sc.from_array(colors)

pts.mlab_source.dataset.point_data.scalars=sc
pts.mlab_source.dataset.modified()

rawDescription: How to directly set RGB/RGBA colors in mayavi

description: Directly set RGB/RGBA colors in mayavi


code:
from datetime import datetime, timedelta
from calendar import monthrange

today = datetime.today()
dt = "02/08/2015"

fut = datetime.strptime(dt, "%d/%m/%Y")
fut = fut + timedelta(days=monthrange(fut.day,fut.month)[1]-fut.day)
diff = 0
while today < fut:
    mon = today.month
    today += timedelta(days=1)
    if today.month != mon:
        diff += 1
print(diff)

rawDescription: How to calculate months left to particular date?

description: Calculate months left to particular date


code:
from scipy import sparse
import textmining
import lda

# a small example matrix
tdm = textmining.TermDocumentMatrix()
tdm.add_doc("here's a bunch of words in a sentence")
tdm.add_doc("here's some more words")
tdm.add_doc("and another sentence")
tdm.add_doc("have some more words")

# tdm.sparse is a list of dicts, where each dict contains {word:count} for a single
# document
ndocs = len(tdm.sparse)
nwords = len(tdm.doc_count)
words = tdm.doc_count.keys()

# initialize output sparse matrix
X = sparse.lil_matrix((ndocs, nwords),dtype=int)

# iterate over documents, fill in rows of X
for ii, doc in enumerate(tdm.sparse):
    for word, count in doc.iteritems():
        jj = words.index(word)
        X[ii, jj] = count

rawDescription: Is there a more efficient way to append lines from a large file to a numpy array? - MemoryError


code:
class Art:
    ...
    def __eq__(self, other):
        return self.c1 == other.c1
    def __lt__(self, other):
        return self.c1 < other.c1

rawDescription: How do i apply a class structure to a csv and then sort it?

description: Apply a class structure to a csv and then sort it


code:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

plt.plot([1,2,3])
plt.savefig('/tmp/test.png')

rawDescription: Calling pylab.savefig without display in ipython


code: from django.shortcuts import render

rawDescription: Django : Passing api's json to template for use in a table


code:
for i in re.split('\nclass ', a)[1:]:                      # will match the main code block and the class name of all classes
    if re.search('\n\s*public static void main', i):              # check if 'public static void main' in a class
        print(re.search('(\w*)', i).group(1))       # and print out the class name

rawDescription: Extracting java main class name in python


code:
from scrapy.exceptions import DropItem
import re

class DropIfEmptyFieldPipeline(object):

    # case-insensitive search for string "nurse"
    REGEX_NURSE = re.compile(r'nurse', re.IGNORECASE)

    def process_item(self, item, spider):
        # user .search() and not .match() to test for substring match
        if not(self.REGEX_NURSE.search(item["job_id"])):
            raise DropItem()
        else:
            return item

rawDescription: remove scraped data with an empty value

description: Remove scraped data with an empty value


code:
lst = [6, 8, 95, 2, 12, 152, 4, 78, 621, 45]

total = 0
for x in lst:
    if x % 2:    # odd
        total -= x
    else:        # even
        total += x

rawDescription: Add even numbers, subtract uneven numbers in Python


code:
def f(l):
    return list(product(*(range(i) for i in l)))

rawDescription: Python: how to get this elegantly?

description: Python: how to get this elegantly


code: ['Viktor Leis* (Technische Universitt Mnchen)', ' Alfons Kemper (Technische Universitt Mnchen)', ' Thomas Neumann (Technische Universitt Mnchen, Germany)']

rawDescription: Python - Split String with Parenthesis based off a Pattern


code:
class Base (object):
    class Protected (object):
        def __init__ (self, target):
            self.target = target

        def get_message (self):
            try:
                return self.target.get_message ()
            except Exception as detail:
                print ("error:", detail)
            return None

    def __init__ (self):
        self.protected = self.Protected (self)

    def get_message (self):
        raise Exception ("Not Implemented")

rawDescription: How can I wrap an empty function to be implemented by a child class in a try-except block?

description: Wrap an empty function to be implemented by a child class in a try-except block


code:
X = NBA['W']
y = NBA[['PTS', 'oppPTS']]

rawDescription: Multiple linear regression in pandas statsmodels: ValueError


code: groupby(a, [0, 1])

rawDescription: How do I get the indexes of unique row for a specified column in a two dimensional array

description: Get the indexes of unique row for a specified column in a two dimensional array


code:
session.get_something(*args)
# <==>
get_something.__call__(session, *args)

rawDescription: Python decorator, self is mixed up

description: Python decorator, self is mixed up


code:
values = 3, 100, 50000
width = max(len('%0d' % value) for value in values)
', '.join('%0*d' % (width, value) for value in values)

rawDescription: How to pad leading zero (in a function) dynamically?

description: Pad leading zero (in a function) dynamically