code:
[{'applied_discounts': [{'amount': 99, 'id': 'total-coupon'}],
  'base_price': '99.0000',
  'base_total': '99.0000',
  'id': 3,
  'is_bundled_product ': False,
  'name': 'University of Timbuktu Bachelor Set',
  'option_set_id': 15,
  'order_address_id': 2,
  'order_id': 614534,
  'price_ex_tax': '99.0000',
  'price_inc_tax': '99.0000',
  'product_id': 83,
  'product_options': [{'display_name': 'Gown size',
                       'display_style': 'Pick list',
                       'display_value': 'Cambridge-Style Bachelor Gown, '
                                        'Size L',
                       'id': 2,
                       'name': 'Bachelor gown size',
                       'option_id': 19,
                       'order_product_id': 3,
                       'product_option_id': 95,
                       'type': 'Product list',
                       'value': '77'},
                      {'display_name': 'Trencher size',
                       'display_style': 'Pick list',
                       'display_value': 'Bachelor and Masters Trencher, '
                                        'Size L',
                       'id': 3,
                       'name': 'Trencher size',
                       'option_id': 20,
                       'order_product_id': 3,
                       'product_option_id': 97,
                       'type': 'Product list',
                       'value': '80'}],
  'quantity': 1,
  'sku': 'S-TIM-BAC-STD',
  'total_ex_tax': '99.0000',
  'total_inc_tax': '99.0000',
  'weight': '3.0000'},
 {'id': 4,
  'name': 'Cambridge-Style Bachelor Gown, Size L',
  'order_address_id': 2,
  'order_id': 614534,
  'parent_order_product_id': 3,
  'product_id': 80,
  'quantity': 1,
  'sku': 'G-CAM-BAC-L'},
 {'id': 5,
  'name': 'Bachelor and Masters Trencher, Size L',
  'order_address_id': 2,
  'order_id': 614534,
  'parent_order_product_id': 3,
  'product_id': 87,
  'quantity': 1,
  'sku': 'C-STD-B&M-L'}]

rawDescription: Converting an unknown data structure to a known data structure in Python


code: del im_ani # this _should_ stop the animation by letting the gc do it's job

rawDescription: Matplotlib save individual "ims" (animation parts) as image


code: file.write(html_doc + '\n')

rawDescription: Trouble with writing separate JSON entries Python


rawDescription: How do I create a colour histogram of a custom colour palette in OpenCV?

description: Create a colour histogram of a custom colour palette in OpenCV


rawDescription: Numpy arange over numpy arrays

description: Numpy arange over numpy arrays


rawDescription: Build a dictionary with a regular expression


code:
A.shape
A.dtype

rawDescription: 2D Numpy Array of Strings WITH column access


code:
if w == l:
    print(c)
    emptylist[c] = 1
    ## then write emptylist to the csv with csv.writerow(emtptylist)
    continue

rawDescription: Writing to a specific cell in csv using python


code:
outfile = open('log.txt','a')
out = output + '\n'
outfile.write(out)

rawDescription: Output and Import list of lists to Pandas DataFrame


code:
@staticmethod
def thread_is_spawning():
    return False

rawDescription: Understanding Multiprocessing: Shared Memory Management, Locks and Queues in Python


code:
import urllib
urllib.quote("$cammer")

rawDescription: Python url construction: escape characters other than regular letters


code: min(li[a:b + 1])

rawDescription: Inclusive range of list Python

description: Inclusive range of list Python


code:
import numpy as np
mask = np.zeros((10,10))
mask[3:-3, 3:-3] = 1 # white square in black background
im = mask + np.random.randn(10,10) * 0.01 # random image
masked = np.ma.masked_where(mask == 0, mask)

import matplotlib.pyplot as plt
plt.figure()
plt.subplot(1,2,1)
plt.imshow(im, 'gray', interpolation='none')
plt.subplot(1,2,2)
plt.imshow(im, 'gray', interpolation='none')
plt.imshow(masked, 'jet', interpolation='none', alpha=0.7)
plt.show()

rawDescription: Overlay an image segmentation with numpy and matplotlib


code: [None, None, 'http://example.com/12/12.jpg', None, 'http://example.com/23/23.jpg', None, None, None]

rawDescription: Sorting a list and adding None values in the right positions


rawDescription: Finding the closest date given a date in a groupby dataframe (Python)


code:
import re

d, regex = {}, re.compile('stage-(\\d+)')
with open('file2') as f2:
    for line in f2:
        value = int(regex.match(line).group(1))
        if value not in d: d[value] = []
        d[value].append(line[:-1])

regex = re.compile('.*track-(\\d+)')

with open('file1') as f1:
    for line in f1:
        value = int(regex.match(line).group(1))
        print(line[:-1])
        if value not in d: print('  no matches')
        else:
            for x in d[value]: print('  MATCH: ' + x)

rawDescription: Fast process each line of one file for each line in another file


code:
r = requests.get('http://www.pharmacy295.gr/el/products/autocomplete.json',data = payload ,headers = headers)
print(r.json())

rawDescription: Using Python to use a website's search function


code:
import re

def get_filament_value(filename):
    with open(filename, 'r') as f_gcode:
        data = f_gcode.read()
        re_value = re.search('filament used = .*? \(([0-9.]+)', data)

        if re_value:
            value = float(re_value.group(1))
        else:
            print('filament not found in {}'.format(filename))
            value = 0.0
        return value

print(get_filament_value('test.gcode'))

rawDescription: Simple python program to read . gcode file


code:
def solve(smin, smax, coef):
    """
    Return a list of lists of non-negative integers `n` that satisfy
    the inequalities,

    sum([coef[i] * n[i] for i in range(len(coef)]) > smin
    sum([(coef[i]+1) * n[i] for i in range(len(coef)]) < smax

    where coef is a list of positive integer coefficients, ordered
    from highest to lowest.
    """
    if smax <= smin:
        return []
    if smin < 0 and smax <= coef[-1]+1:
        return [[0] * len(coef)]

    c0 = coef[0]
    c1 = c0 + 1
    n_max = ((smax-1) // c1)
    solutions = []
    if len(coef) > 1:
        for n0 in range(n_max + 1):
            for solution in solve(smin - n0 * c0,
                                  smax - n0 * c1,
                                  coef[1:]):
                solutions.append([n0] + solution)
    else:
        n_min = max(0, (smin // c0) + 1)
        for n0 in range(n_min, n_max + 1):
            solutions.append([n0])
    return solutions

rawDescription: find the set of integers for which two linear equalities holds true

description: Find the set of integers for which two linear equalities holds true


rawDescription: Build dictionary from list of lists and maintain position of elements


code:
import collections

somelist = list('ABRACADABRA')
dups = collections.defaultdict(list)
for index, item in enumerate(somelist):
    dups[item].append(index)
print(dups)

rawDescription: Find index of item with duplicates

description: Find index of item with duplicates


code:
df['pct_ch'] = df['prod_count'] / df.groupby('product_desc')['prod_count'].shift(1)
df.sort('product_desc')

rawDescription: How to create rolling percentage for groupby DataFrame

description: Create rolling percentage for groupby DataFrame


code:
import re

def extract_next_state(s):
    p = re.compile('(next_state=)|(\()|(\))')
    depth = 0
    startindex = None
    for m in p.finditer(s):
        if m.group(1):            # next_state=
            startindex = m.end()
        elif startindex is None:  # haven't found 'next_state=' yet
            continue
        elif m.group(2):          # (
            depth += 1
        elif m.group(3):          # )
            depth -= 1
            if depth == 0:
                return s[startindex:m.end()]
            elif depth < 0:
                return s[startindex:m.start()]
    if startindex is None: return None
    return s[startindex:] + ')' * depth

a = '[(next_state=(!SE&((!B2&D)|(B2&lq))|(SE&SI'
print(extract_next_state(a))
b = '[(next_state=(!SE&((!B2&D)|(B2&lq))|(SE&SI)),clear=B2&lqn,preset=B2&lq)))]'
print(extract_next_state(b))

rawDescription: Parenthesis matching in Python

description: Parenthesis matching in Python


code:
from matplotlib import pyplot as plt
from matplotlib.patches import Polygon
import numpy as np

x = np.linspace(0,5,100)
y = np.sin(x)

plt.plot(x,y)
ax = plt.gca()

dta_pts = [[.5,-.75],[1.5,-.6],[1,-.4]]

# coordinates converters:
#ax_to_display = ax.transAxes.transform
display_to_ax = ax.transAxes.inverted().transform
data_to_display = ax.transData.transform
#display_to_data = ax.transData.inverted().transform

ax_pts = display_to_ax(data_to_display(dta_pts))

# this triangle will move with the plot
ax.add_patch(Polygon(dta_pts, True))
# this triangle will stay put relative to the axes bounds
ax.add_patch(Polygon(ax_pts, True, transform=ax.transAxes))

plt.show()

rawDescription: Matplotlib artists to stay the same size when zoomed in?


code: new_matrix = a[:,b==1]

rawDescription: simple way to select numpy subarray using boolean conditional vector in python 3

description: Simple way to select numpy subarray using boolean conditional vector in python 3


rawDescription: How do I view a model produced using scikit-learn?

description: View a model produced using scikit-learn


rawDescription: taking the average of two histograms in python

description: Taking the average of two histograms in python


code: max(i for i in s.index if s[i] != 0) # will work only if index is sorted

rawDescription: Find last non-zero element's index in pandas series


code:
def Collection_is_cheap(C, price):
    result = set()
    for rest in C:
        for dish in rest.menu:
            if dish.price <= price:
                result.add(rest)
    return list(result)

rawDescription: Iterating over list of namedtuples, selecting restaurants


code:
target.write("%r\n%r\n%r" % (line1, line2, line3))
#                                              --^

rawDescription: Why is target.write ignoring my %r formatting?


rawDescription: How to convert any ip address to a slash 24 prefix

description: Convert any ip address to a slash 24 prefix


code:
import numpy as np
import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt

arr = np.random.randint(0, 100, (100000,1))

df = pd.DataFrame(arr)

cnt = Counter(df[0])

df_p = pd.DataFrame(cnt, index=['data'])

df_p.T.plot(kind='hist')

plt.show()

rawDescription: Python: faster way of counting occurences in numpy arrays (large dataset)


code:
class PermanentMenu(QtGui.QMenu):
    def hideEvent(self, event):
        self.show()

rawDescription: Qt/PyQt: How do I use a QMenu as a permanent widget?


code:
byteswapped = bytearray(len(original))
byteswapped[0::2] = original[1::2]
byteswapped[1::2] = original[0::2]

rawDescription: Efficient way to swap bytes in python

description: Efficient way to swap bytes in python


code:
def accumulating():
    list = []
    strings = input("Please enter a list of strings(seperated by a white space): ")
    list = strings.split(" ")
    return list

rawDescription: Write a function that takes as a parameter a list of strings and returns a list containing the lengths of each of the strings


code:
if apptDate not in appointments:
       newAppt = apptTime + '\t' + apptDesc
       appointments[apptDate] = [newAppt]
else:
       newAppt = apptTime + '\t' + apptDesc
       appointments[apptDate].append(newAppt)

rawDescription: Need to add appointments into empty dictionary


code:
False
True

rawDescription: Find if char precedes substring

description: Find if char precedes substring


rawDescription: How to Cleanup Django Orphan Foreign Key Values?


code:
import setuptools
from pip.req import parse_requirements

requirements = [str(ir.req)
                for ir in parse_requirements("requirements.txt", session=uuid.uuid1())
                    if ir.req is not None]
setuptools.setup(..., install_requires=requirements)

rawDescription: Packaging Your Python Code

description: Packaging Your Python Code


code:
import os
import glob

filename = glob.glob(os.path.join(folder, name + '.*'))[0]

rawDescription: Open existing file of unknown extension

description: Open existing file of unknown extension


code:
type(me.rebound)
me.rebound()
# Not true any more!

rawDescription: Why isn't self being automatically passed to a method that is set on an object after its instantiation?


rawDescription: regular expression split also includes empty string result

description: Regular expression split also includes empty string result


code: ['cat', 'apple']

rawDescription: Printing items in a list that occur a certain number of times?


code:
foo = StringVar()
foo.set(30)
a_time_label = Label(root,textvariable=foo)
def decrement_label():
    foo.set(str(int(foo.get())-1))
root.after(1000,decrement_label)

rawDescription: Timer or stopwatch in python

description: Timer or stopwatch in python


rawDescription: Printing a list with string.format rounding for float members


code:
matched = [f for f in files if f.fname in link_ids]
# -> [File(fname='222', fext='.txt')]

rawDescription: Python efficient way to compare list item with partial item from other list


code:
from collections import defaultdict
some_dict = { 'abc':'a', 'cdf':'b', 'gh':'a', 'fh':'g', 'hfz':'g' }
new_dict = defaultdict(list)
for k, v in some_dict.iteritems():
    new_dict[v].append(k)

rawDescription: Find all Key-Elements by the same Value in Dicts


code:
res = getelements(l, 'PackageDto')
for n, e in enumerate(res):
    print(n, e)

rawDescription: Python Navigate Through Nested List Like Tree


code:
import seaborn as sns
sns.factorplot('ids', 'data', hue='var', kind='bar', data=df)

rawDescription: How to iterate over a pandas dataframe and compare certain columns based on a third column?

description: Iterate over a pandas dataframe and compare certain columns based on a third column


code:
# Unpythonic
size = len(z)
while a < (size - 1):
    if z[a] % 2 == 0:
        d.append(z[a])
    a += 1

# Pythonic
for num in z:
    if not num % 2:
        d.append(num)

# Even more pythonic
d = [num for num in z if not num % 2]

rawDescription: Project Euler #2

description: Project Euler #2


code:
wiz = Wizard()
[x for x in dir(wiz) if not x.startswith("_")]
wiz.addmana()
[x for x in dir(wiz) if not x.startswith("_")]
wiz.domagic()
[x for x in dir(wiz) if not x.startswith("_")]
wiz.domagic()

rawDescription: Is it possible to delete a method from an object (not class) in python?


code:
re.escape(motif)
re.escape('\n [hello world!]')

rawDescription: Convert user input strings to raw string literal to construct regular expression


code:
new_list = []
for element in something:
    new_list.append(element)

rawDescription: Convert custom class to standard Python type


code: filter(lambda a: not a.startswith('__'), dir(obj))

rawDescription: Iterate over object attributes in python


code:
class MyObject(object):
    ID = 0

    def __init__(self):
       self.id = MyObject.ID = MyObject.ID + 1

rawDescription: One int for every python object

description: One int for every python object


code:
test2
test4

rawDescription: Python / Excel - Conditional cell printing with xlrd


code: Xs = numpy.vstack((Xs,EMOV_n))

rawDescription: How to predict time series in scikit-learn?

description: Predict time series in scikit-learn


code:
with open('data.csv', 'rt') as f:
    reader = csv.reader(f)
    for row in reader:
        if row[0] == username:
            print(row)

rawDescription: Retrieving a specific row from a CSV file based on input


code:
import itertools

class ExtendedGenerator:

    def __init__(self, gen):
        self.gen = iter(gen)

    def __iter__(self):
        return self

    def __next__(self):
        return next(self.gen)

    def __add__(self, other):
        try:
            return ExtendedGenerator(itertools.chain(self.gen, iter(other)))
        except TypeError:
            return NotImplemented

    def __radd__(self, other):
        try:
            return ExtendedGenerator(itertools.chain(iter(other), self.gen))
        except TypeError:
            return NotImplemented

x = ExtendedGenerator(range(3))
y = range(3, 6)
z = x + y
a = list(x)
b = list(z) # what should the contents of z be?

print("a:", a)
print("b:", b)

rawDescription: Concatenate generators in python 3 with +-operator


code:
result = []
for xs in lst:
    temp = []
    for x in xs:
        temp.append(str(x))
    result.append(tuple(temp))
result

rawDescription: Convert list of tuples of mixed data types into all string


code:
from sqlalchemy import Column, types
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Model(Base):
    __tablename__ = "model"
    id = Column(types.Integer, primary_key=True)
    col = Column(HashColumn(20))

    def __repr__(self):
        return "Model(col=%r)" % self.col

rawDescription: Python-Sqlalchemy Binary Column Type HEX() and UNHEX()


code:
import html
html.unescape('Suzy & John')
# 'Suzy & John'

html.unescape('"')
# '"'

rawDescription: How do I unescape HTML entities in a string in Python 3.1?

description: Unescape HTML entities in a string in Python 3.1


code:
import wx

def handle(e):
    wx.MessageBox("Hello","world")

a = wx.App(redirect=False)
t = wx.Timer()
t.Bind(wx.EVT_TIMER,handle)
t.Start(3000)
f = wx.Frame(None)
a.MainLoop()

rawDescription: Simultaneous Message Boxes

description: Simultaneous Message Boxes


code:
#groupby and sum over columns C and D
df_1 = df.groupby(['A']).sum()

rawDescription: Preserve the non-numerical columns when doing pandas.DataFrame.groupby().sum()


code:
import requests
resp = requests.get(URL)
mydict = json.loads(resp.content)

rawDescription: Httplib2 : Processing Response String

description: Httplib2 : Processing Response String


code:
te['item'].isin(tr['item']) & te['user'].isin(tr['user'])
te[te['item'].isin(tr['item']) & te['user'].isin(tr['user'])]

rawDescription: Python Pandas - Remove values from first dataframe if not in second dataframe


rawDescription: Given an iterable, how to apply a function in every possible combination?


code:
import json

def convert_load(*args, **kwargs):
    json_obj = json.load(*args, **kwargs)
    return convert_json(json_obj, camel_to_underscore)

def convert_dump(*args, **kwargs):
    args = (convert_json(args[0], underscore_to_camel),) + args[1:]
    json.dump(*args, **kwargs)

rawDescription: Converting identifier naming between camelCase and underscores during JSON serialization/deserialization


code:
final_distances,predecessors = ShortestPath(graph,start)
path = [end]
while end != start:
    end = predecessors[end]
    path = [end] + path
return path

rawDescription: Finding nodes between two nodes

description: Finding nodes between two nodes


code:
def save(self):
    image = Image.open(self.full_image_large)
    (w, h) = image.size
    r900 = 900.0/w
    im900 = image.resize((int(math.floor(r900*w)), int(math.floor(r900*h))), Image.ANTIALIAS)
    im900.save(self.full_image_large)

    r350 = 350.0/w
    im350 = image.resize((int(math.floor(r350*w)), int(math.floor(r350*h))), Image.ANTIALIAS)
    im350.save(self.full_image)

    r120 = 120.0/w
    im120 = image.resize((int(math.floor(r120*w)), int(math.floor(r120*h))), Image.ANTIALIAS)
    im120.save(self.thumbnail_image)

    super(Artwork, self).save()

rawDescription: How to use Django to resize a user's image and upload to Amazon S3?

description: Use Django to resize a user's image and upload to Amazon S3


code:
def activeHostsQuery():
    cmd = 'curl -s -k -H \'X-Requested-With: curl demoapp\' -u username:password \'https://qualysapi.qualys.com/api/2.0/fo/scan/?action=fetch&scan_ref=scan/1111111.22222&mode=brief&output_format=csv\' | cut -d, -f1 | sort | uniq | grep -E \'"[[:digit:]]{1,3}\\.[[:digit:]]{1,3}\\.[[:digit:]]{1,3}\\.[[:digit:]]{1,3}"\' | wc -l'

    ctiveHostsNumber = subprocess.Popen(cmd, shell = True, stdout = subprocess.PIPE).communicate()[0]
    return activeHostsNumber

rawDescription: Subprocess Python.. Stringing together commands


code: return [[''.join(x)] for x in old_list]

rawDescription: Unable to perform join in the inner lists of a list of lists


code: records = [[rec[7].replace(' ', '')] + rec[9:12] + rec[3:4] for rec in records]

rawDescription: Python - Replacing characters in a list

description: Python - Replacing characters in a list


code:
df = DataFrame(randn(5, 2), columns=['a', 'b'])
df
formulas = [ ('c','a+b'), ('d', 'a*c')]

rawDescription: How to create lazy_evaluated dataframe columns in Pandas

description: Create lazy_evaluated dataframe columns in Pandas


code: from gevent import monkey; monkey.patch_all()

rawDescription: Making an asynchronous call synchronous in tornado


code:
class SortFilterProxyModel(QSortFilterProxyModel):

    class FilterSyntax:
        RegExp, Wildcard, FixedString = range(3)

    Q_ENUMS(FilterSyntax)

    def __init__(self, parent):
        super().__init__(parent)

    @pyqtProperty(QAbstractItemModel)
    def source(self):
        return super().sourceModel()

    @source.setter
    def source(self, source):
        self.setSourceModel(source)

    @pyqtProperty(int)
    def sortOrder(self):
        return self._order

    @sortOrder.setter
    def sortOrder(self, order):
        self._order = order
        super().sort(0, order)

    @pyqtProperty(QByteArray)
    def sortRole(self):
        return self._roleNames().get(super().sortRole())

    @sortRole.setter
    def sortRole(self, role):
        super().setSortRole(self._roleKey(role))

    @pyqtProperty(QByteArray)
    def filterRole(self):
        return self._roleNames().get(super().filterRole())

    @filterRole.setter
    def filterRole(self, role):
        super().setFilterRole(self._roleKey(role))

    @pyqtProperty(str)
    def filterString(self):
        return super().filterRegExp().pattern()

    @filterString.setter
    def filterString(self, filter):
        super().setFilterRegExp(QRegExp(filter, super().filterCaseSensitivity(), self.filterSyntax))

    @pyqtProperty(int)
    def filterSyntax(self):
        return super().filterRegExp().patternSyntax()

    @filterSyntax.setter
    def filterSyntax(self, syntax):
        super().setFilterRegExp(QRegExp(self.filterString, super().filterCaseSensitivity(), syntax))

    def filterAcceptsRow(self, sourceRow, sourceParent):
        rx = super().filterRegExp()
        if not rx or rx.isEmpty():
            return True
        model = super().sourceModel()
        sourceIndex = model.index(sourceRow, 0, sourceParent)
        # skip invalid indexes
        if not sourceIndex.isValid():
            return True
        # If no filterRole is set, iterate through all keys
        if not self.filterRole or self.filterRole == "":
            roles = self._roleNames()
            for key, value in roles.items():
                data = model.data(sourceIndex, key)
                if rx.indexIn(data) != -1:
                    return True
            return False
        # Here we have a filterRole set so only search in that
        data = model.data(sourceIndex, self._roleKey(self.filterRole))
        return rx.indexIn(data) != -1

    def _roleKey(self, role):
        roles = self.roleNames()
        for key, value in roles.items():
            if value == role:
                return key
        return -1

    def _roleNames(self):
        source = super().sourceModel()
        if source:
            return source.roleNames()
        return {}

rawDescription: Use a QSortFilterProxyModel from QML with PyQt5


code: max({k:sum(v)/float(len(v)) for k, v in d.items()}.items(), key=lambda x:x[1])

rawDescription: Averaging column 2D array python

description: Averaging column 2D array python


rawDescription: Getting data arrays from CSV with loops

description: Getting data arrays from CSV with loops


rawDescription: arithmetic comparisons on numpy arrays

description: Arithmetic comparisons on numpy arrays


code:
import logging
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', datefmt='%H:%M:%S')
logging.info('hello')
logging.info('\n')
logging.warning('new hello')

rawDescription: How to insert newline in python logging?

description: Insert newline in python logging


rawDescription: Create python array from first element of array 1, first element of array 2, second element of array 1, second element of array 2, etc


code: delta =  d - b_d if d > b_d else timedelta.max

rawDescription: Getting the closest date to a given date


code:
original_file_name = my_file_name
file_category = my_images, children, fun
file_type = image, video, application
key = uniqueID

rawDescription: Amazon S3 and Cloudfront - Publish file uploaded as hashed filename


code: lst = fread.read().strip().split()

rawDescription: python variable contains three lists not one

description: Python variable contains three lists not one


code:
for x in c:
    np.where(np.abs(c-x)<5)

rawDescription: Numpy data points region/circle

description: Numpy data points region/circle


code:
# some fake data
gen = np.random.RandomState(0)
ni, nj, nk = 10, 20, 100
U = gen.randn(ni, nj, nk)
V = gen.randn(nj, nk)

res1 = np.zeros((ni, nk))
for k in range(nk):
    res1[:,k] = U[:,:,k].dot(V[:,k])

res2 = np.einsum('ijk,jk->ik', U, V)

print(np.allclose(res1, res2))
# True

rawDescription: Tensor multiplication with numpy tensordot


code: df2.columns = df2.columns.swaplevel('Location', None)

rawDescription: How to use Pandas to take multi year average in Python

description: Use Pandas to take multi year average in Python


rawDescription: Suppressing scientific notation in pandas?


rawDescription: How to use infix operators as higher order functions?

description: Use infix operators as higher order functions


code:
id = browse_record.id
name = browse_record.name

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

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


code: {k: v for k, v in d.iteritems() if x1<k[0]<x2 and y1<k[1]<y2}

rawDescription: Get the subdictionary based on range

description: Get the subdictionary based on range


code:
fighters = [(playerspeed, 'player'), (enemyspeed, enemyname)]
fighters.sort()
for speed, fighter in fighters:
    attack(fighter)

rawDescription: Do functions in ordered by values

description: Do functions in ordered by values


code: win32api.MessageBox(0, 'hello', 'title', 0x00001000)

rawDescription: Alert boxes in Python?

description: Alert boxes in Python


code:
# sample of data
df = pd.DataFrame({'word0': list('aabb'), 'link': list('llll'), 'word1': list('cdcd'),'counts': [10, 20, 30, 40]})

# caching total count
total_cnt = df['counts'].sum()

# two series with sums for all combinations of ('word0', 'link') and ('word1', 'link')
grouped_w0_l = df.groupby(['word0', 'link'])['counts'].sum()/total_cnt
grouped_w1_l = df.groupby(['word1', 'link'])['counts'].sum()/total_cnt

# join sums for grouped ('word0', 'link') to original df
merged_w0 = df.set_index(['word0', 'link']).join(grouped_w0_l, how='left', rsuffix='_w0').reset_index()

# join sums for grouped ('word1', 'link') to merged df
merged_w0_w1 = merged_w0.set_index(['word1', 'link']).join(grouped_w1_l, how='left', rsuffix='_w1').reset_index()

# merged_w0_w1 has enough data for calculation new_score
# check here - I transform the expression
merged_w0_w1['new_score'] = np.log(merged_w0_w1['counts'] * total_cnt / (merged_w0_w1['counts_w0'] * merged_w0_w1['counts_w1']))

# export results to dict (don't know is it really needed or not - you can continue manipulate data with dataframes)
big_dict = merged_w0_w1.set_index(['word0', 'link', 'word1'])['new_score'].to_dict()

rawDescription: Python pandas tensor access is extremely slow


code:
datetime.datetime.combine(datetime.date.min, t) - datetime.datetime.min
(datetime.datetime.combine(datetime.date.min, t) - datetime.datetime.min).total_seconds

rawDescription: How do I convert a timestamp to seconds-since-midnight?

description: Convert a timestamp to seconds-since-midnight


code:
from pyscreenshot import grab

im = grab(bbox=(100, 200, 300, 400))
im.show()

rawDescription: How to do a screenshot of a tkinter application?

description: Do a screenshot of a tkinter application


code:
def triangle(n):
    for i in range(n, 0, -1):
        print('o' * i)

rawDescription: Printing an upside down triangle in Python 3.4.2?


code:
j = { name : "mongo" };
t = { x : 3 };
db.things.save(j);
db.things.save(t);

rawDescription: What is the proper way to perform a contextual search against NoSQL key-value pairs?


code:
results = {}
counter = 1
while True:
    response = input("What number? (done to quit) ")
    if response == 'done':
        break
    results[counter] = response
    counter += 1

rawDescription: Python - Save user inputs in new variables


code:
import getpass
username = getpass.getuser()

rawDescription: How to get access to git commit variables (python)?

description: Get access to git commit variables (python)


rawDescription: what is the most effective way to find the modal values of a list?

description: What is the most effective way to find the modal values of a list


code:
[
    {
        'type': 'folder',
        'name': 'TopLevel folder',
        'id': '0',
        'children': [
            {
                'type': 'folder',
                'name': 'MidLevel folder',
                'parent': '0',
                'id': '1',
                'children': [
                    {
                        'type': 'folder',
                        'name': 'Bottom Level folder',
                        'parent': '1',
                        'id': '2',
                        'children': [
                            {
                                'type': 'jpg',
                                'name': 'Vacation Picture',
                                'parent': '2',
                                'id': '3'
                            }
                        ]
                    }
                ]
            }
        ]
    }
]

rawDescription: Sorting JSON object(s) into a Hierarchy

description: Sorting JSON object(s) into a Hierarchy


code: new_list = [i for i in new_list if i]

rawDescription: Delete all occurrences of specific values from list of lists python


code:
import numpy as np
from scipy.signal import freqz
w, h = freqz(range(1,6), 1, worN=512)
h[:6]
w[:6]
f = 12.5*w/(2*np.pi)
f[:6]

rawDescription: Matlab freqz function in Python

description: Matlab freqz function in Python


code: data/macro

rawDescription: Is there a way to incorporate python code into moinmoin pages?


rawDescription: python convert string of lists into a list of lists

description: Python convert string of lists into a list of lists


code:
files = []
for item in mylist:
  if item == 'video':
    files.append('../download/video.html')
  elif item == 'audio':
    files.append('../download/audio.html')
zip(files)

rawDescription: python django dynamic zipping and download

description: Python django dynamic zipping and download


code:
def is_leap_year(y):
    return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)

rawDescription: Is there a simpler code for defining next_date?


rawDescription: Python - How do I write an array to a text file?


code:
text = '4 3 1 4 5 5 2 4 6 2 3'
result = sentence(text)
print(result)

rawDescription: How do I recreate a nested list from a long string of information in Python?

description: Recreate a nested list from a long string of information in Python


code:
TEMPLATE_CONTEXT_PROCESSORS += {
    'projectname.appname.context_processors.booleans',
}

rawDescription: Django custom template tag which accepts a boolean parameter


code: sqft=dict(ticketing_sqft=600, galleries_sqft=12500, auditorium_sqft=2000, conference_sgft=1600)

rawDescription: What type of list is best for calling specific items?


rawDescription: how to read numpy 2D array from string?

description: Read numpy 2D array from string


code:
from employee import Employee

class Staff:

    def __init__(self):
        self.EmployeeList = []

    def addEmployee(self, name, number, YearsWorked, Salary):
        employee_obj = Employee(name, number, YearsWorked, Salary)
        employee_obj.print_employee_details()
        self.EmployeeList.append(employee_obj)

name = input("Name")
number = input("Number")
years = input("Years Worked")
salary = input("salary")
staff_obj = Staff()
new = staff_obj.addEmployee(name,number,years,salary)

rawDescription: python classes and values

description: Python classes and values


code:
assert data[0] == "(" and data[-1] == ")"
elements = data[1:-1].split(",")
mytuple = tuple(elements)

rawDescription: converting string to tuple in python

description: Converting string to tuple in python


code:
import sklearn.cluster as cluster
import pandas as pd
import numpy as np
np.random.seed(2016)

X = pd.DataFrame(np.random.random((100, 2)))
est = cluster.KMeans(n_clusters=10)
Y = pd.DataFrame(est.fit_predict(X), columns=['cluster ID'])
Z = pd.DataFrame(est.cluster_centers_[Y['cluster ID']],
                 columns=['centroid_x', 'centroid_y'])
result = pd.concat([X, Y, Z], axis=1)

print(result.head())

rawDescription: How to retrieve the cluster centroids in sic-kit learn's K-means?

description: Retrieve the cluster centroids in sic-kit learn's K-means


code:
import random

def roll_die():
    return random.randint(1,6)

rawDescription: How to detect certain numbers from a dice roller?

description: Detect certain numbers from a dice roller


code:
a = numpy.zeros(2, dtype=([('int',numpy.int32),('dbl',numpy.float64)]))
a

rawDescription: How to create struct for passing between nodes using mpi4py

description: Create struct for passing between nodes using mpi4py


code:
import itertools as it
src="hello\n#foo\n#bar\n#baz\nworld\n"
line_gen = (''.join(j) for i,j in it.groupby(src, "\n".__ne__) if i)
'\n'.join(s for s in line_gen if s[0]!="#")

rawDescription: How do I split a string and rejoin it without creating an intermediate list in Python?

description: Split a string and rejoin it without creating an intermediate list in Python


rawDescription: Compare values of two arrays in python

description: Compare values of two arrays in python


rawDescription: Pandas: Error when merging two tables, Error with set_index


code:
from sklearn.cross_validation import cross_val_score
scores = cross_val_score(your_classifier, X, y, cv=cv, scoring= ...)

rawDescription: Grabbing two different sections of a list


code:
menu = [
    # TODO: define your encrypt, decrypt and secure_encrypt functions
    ("Encrypt message", encrypt),
    ("Decrypt message", decrypt),
    ("Secure Encrypt Message", secure_encrypt),
    ("Exit", sys.exit),
    ]
for n, (label, _) in enumerate(menu, start=1):
    print("{}) {}".format(n, label))
selection = input("Please select: ")
assert 1 <= selection <= len(menu), "TODO: better error handling"
menu[selection - 1][1]()

rawDescription: How to stop a dictionary shuffling? (Python)

description: Stop a dictionary shuffling? (Python)


code:
import wx
[n for n in dir(wx) if n.startswith("ID_")]

rawDescription: Using wxPython Menus, ID: What does it mean and Which should I use for X?


code: [x.room_number() for x in people if check(x)]

rawDescription: Python, Filter a List of Objects, but return a specific attribute?


rawDescription: Pandas: get the most count label

description: Pandas: get the most count label


rawDescription: python list / numpy array indexing using tuple unpacking possible?

description: Python list / numpy array indexing using tuple unpacking possible


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://matrix.itasoftware.com/')
elem = driver.find_element_by_xpath(
    './/input[@id="ita_form_date_DateTextBox_0"]'
    '/following-sibling::input[@type="hidden"]')

value = driver.execute_script('return arguments[0].value;', elem)
print("Before update, hidden input value = {}".format(value))

driver.execute_script('''
    var elem = arguments[0];
    var value = arguments[1];
    elem.value = value;
''', elem, '2013-11-26')

value = driver.execute_script('return arguments[0].value;', elem)
print("After update, hidden input value = {}".format(value))

rawDescription: Selenium (Python): How to insert value on a hidden input?


code: rpi_data["Lui"].data_plot.x = 10         #or the 99 one.

rawDescription: Creating classes in dictionaries - values being duplicated between classes?


code:
def call_tesseract(input_filename, output_filename):
    """Calls external tesseract.exe on input file (restrictions on types),
    outputting output_filename+'txt'"""
    args = [tesseract_exe_name, input_filename, output_filename]
    proc = subprocess.Popen(args)
    retcode = proc.wait()
    if retcode!=0:
        errors.check_for_errors()

rawDescription: How to remove "Tesseract Open Source OCR Engine v3.02 with Leptonica" message

description: Remove "Tesseract Open Source OCR Engine v3.02 with Leptonica" message


code:
import scipy as sc
import matplotlib.pyplot as plt

def graph(x):
    plt.ion()
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    lines = []
    D = (0.133e-4, 0.243e-4, 0.283e-4)
    temperatures = ('T = 273','T = 293','T = 298')
    N = 2000
    linestyles = ('ob', '-r', '+m')
    for dval, linestyle, temp in zip(D, linestyles, temperatures):
        line, = ax.plot([], [], linestyle, label = temp)
        lines.append(line)
    plt.xlim((0, N*0.02*1000))
    if x == 1:
        plt.ylim((0.7, 1.0))
    else:
        plt.ylim((1.0, 1.6))
    plt.legend(loc = 'best')
    for dval, line in zip(D, lines):
        A = 1.67e-6
        V0 = 88e-12
        Vw_n1 = 71.7/100*V0
        Pw = 0.22
        L = 4e-4
        B1 = V0-Vw_n1
        C7 = 0.447e-3
        dt = 0.2e-4
        M = 0.759e-1
        C_n1 = sc.zeros(7)
        C_n1[0:6] = 0.290e-3
        C_n1[6] = 0.447e-3
        C0 = C_n1[0]
        Vw_0 = Vw_n1

        tvals = []
        yvals = []
        dx = sc.sqrt(dval*dt/M)
        for n in range(1, N+1, 1):
            Vw_n = Vw_n1
            C_n = C_n1
            R2 = (Vw_n+B1)/(Vw_0+B1)
            Cc = C_n1[0]/C0
            F2_1 = 10000/3*Pw*A*(C0*Vw_0/Vw_n1-C_n[1])
            dV = F2_1*dt
            Vw_n1 = Vw_n+dV
            C_n1[0] = C0*Vw_0/Vw_n1
            F_i_2 = -dval/dx*(C_n[1:7]-C_n[0:6])
            C_n1[0:6] = C_n[0:6]-F_i_2*A*dt/(L/(V0/A)*V0/5)
            tvals.append(n*0.02*1000)
            yvals.append(R2 if x == 1 else Cc)
            if not len(yvals) % 50:
                line.set_xdata(tvals)
                line.set_ydata(yvals)
                fig.canvas.draw()

if __name__ == "__main__":
    flag = False
    while not flag:
        try:
            x = int(raw_input("Give a choice 1  or 2  : "))
            flag = True
            if x == 1:
                plt.title('Change in cell volume ratio as a function of time \n\
                at various temperatures')
                plt.xlabel('Time')
                plt.ylabel('Ceil volume ratio (V/V0)')
                graph(x)
            elif x == 2:
                plt.title('Increase of solute concentration at various temperatures')
                plt.xlabel('Time')
                plt.ylabel('Solute concentration in the Ceil (Cc)')
                graph(x)
            else:
                flag = False
                print("You must input 1 or 2")
        except ValueError:
            print("You must input 1 or 2")
    raw_input('Press a key when done')

rawDescription: refactor code in order to use 3 values to make plot & tuple indices must be integers, not float

description: Refactor code in order to use 3 values to make plot & tuple indices must be integers, not float


code:
import fileinput
header_over = False
with open("out_file","w") as outfile:
    for line in fileinput.input():
        if line.startswith("#") and not header_over:
            outfile.write(line)
        elif not line.startswith("#"):
            outfile.write(line)
            header_over = True

rawDescription: concatenate several file remove header lines

description: Concatenate several file remove header lines


code:
from collections import defaultdict
_database_variants = defaultdict(list)
_search_regions = defaultdict(list)
for i in database_variants.keys():
    _chromosome = i.split(":")[0]
    _start = int(i.split(":")[1].split("-")[0])
    _database_variants[_chromosome].append(_start)
_search_regions = defaultdict(list)
for i in search_regions.keys():
    _chromosome = i.split(":")[0]
    _start = int(i.split(":")[1].split("-")[0])
    _end = int(i.split(":")[1].split("-")[1])
    _search_regions[_chromosome].append((_start, _end))

def _search(_database_variants, _search_regions):
    for key, values in _database_variants.items():
        for value in values:
            for search_area in _search_regions[key]:
                if (value >= search_area[0]) and (value <= search_area[1]):
                    yield(key, search_area)

rawDescription: Matching values in nested dictionaries

description: Matching values in nested dictionaries


rawDescription: adding text ticklabels to pcolor heatmap

description: Adding text ticklabels to pcolor heatmap


code: sl = slice(0,4)

rawDescription: Python slice how-to, I know the Python slice but how can I use built-in slice object for it?


code:
django
numpy
lxml
#.... so on

rawDescription: python auto install package

description: Python auto install package


rawDescription: Split numpy array into similar array based on its content


rawDescription: Matplotlib: Plotting two graphs within a specified x-axis range


code:
import calendar

def get_periods():
    year = int(input('Enter a year: '))
    list_of_periods = []
    for month in range(1, 13):
        last_day = calendar.monthrange(year, month)[1]
        list_of_periods.append({'start_date': '{0}-{1:02}-01'.format(year, month),
                                'end_date': '{0}-{1:02}-{2}'.format(year, month, last_day)})

    return list_of_periods

print(get_periods())

rawDescription: python generate period of a year in a list of dictionary

description: Python generate period of a year in a list of dictionary


code:
for xml_data in get_clientresponses_2():
     xml_dat =  dict(flatten_dict(xml_data))

rawDescription: How to pass a function within another function when using Python

description: Pass a function within another function when using Python


code:
import urllib2
opener = urllib2.build_opener()
external_sites_html = opener.open(external_sites_url).read()

rawDescription: Get Title and Description of external URL using Django


code:
def round_of_rating(number):
    """Round a number to the closest half integer.
    >>> round_of_rating(1.3)
    1.5
    >>> round_of_rating(2.6)
    2.5
    >>> round_of_rating(3.0)
    3.0
    >>> round_of_rating(4.1)
    4.0"""

    return round(number * 2) / 2

rawDescription: round off float to nearest 0.5 in python

description: Round off float to nearest 0.5 in python


code: df['mask'] = (df[key].diff() / np.timedelta64(1, 'm')) != 1

rawDescription: Generate a multi-indexed dataframe from a dictionary with different length of values


rawDescription: Scipy sparse matrix assignment using only stored elements


code:
P1 = [ (0.5*m.tanh( (2.0 - B(rb1,drs1) ) * x / rb1 + B(rb1,drs1) ) + 0.5) for x in r]

P1 = [ -2.5*m.log10(x) if x!=0.0 else np.inf for x in P1 ] # band-aid for problem

rawDescription: Floating point problems in asymptotic functions approaching zero - Python


code:
for sentence in sent_tokenize(paragraph):
    for highlight in highlights:
        if highlight in sentence:
            sentencesWithHighlights.append(sentence)
            break

rawDescription: Finding the surrounding sentence of a char/word in a string


code:
from collections import OrderedDict
import datetime
from pprint import pprint
import time
from dateutil.rrule import rrule, MONTHLY

data = [{u'count': 1, u'_id': {u'year': 2010, u'month': 4}}, {u'count': 1, u'_id': {u'year': 2010, u'month': 5}},
        {u'count': 2, u'_id': {u'year': 2010, u'month': 7}}, {u'count': 1, u'_id': {u'year': 2010, u'month': 9}},
        {u'count': 1, u'_id': {u'year': 2010, u'month': 10}}, {u'count': 4, u'_id': {u'year': 2010, u'month': 12}}]

new_data = OrderedDict()
for item in data:
    year, month = item['_id']['year'], item['_id']['month']
    d = datetime.datetime.strptime(str(year) + "-" + str(month), '%Y-%m')
    new_data[d] = item['count']

chart = {}
last_added = None
for d, count in new_data.iteritems():
    date_start = last_added if last_added else d
    for dt in rrule(MONTHLY, dtstart=date_start, until=d):
        key = time.mktime(dt.timetuple()) * 1000
        if key not in chart:
            chart[key] = count if dt == d else 0
    last_added = d

pprint(sorted(chart.items()))

rawDescription: Fill missing values in a list of dictionaries with months and years


code:
def sublist(ls1, ls2):
    '''
    >>> sublist([], [1,2,3])
    True
    >>> sublist([1,2,3,4], [2,5,3])
    True
    >>> sublist([1,2,3,4], [0,3,2])
    False
    >>> sublist([1,2,3,4], [1,2,5,6,7,8,5,76,4,3])
    False
    '''
    def get_all_in(one, another):
        for element in one:
            if element in another:
                yield element

    for x1, x2 in zip(get_all_in(ls1, ls2), get_all_in(ls2, ls1)):
        if x1 != x2:
            return False

    return True

rawDescription: Checking if list is a sublist

description: Checking if list is a sublist


code: answer = time2sec(1, 15, 0)

rawDescription: Define a python function time2sec with three optional keyword arguments hour minute and second


rawDescription: Python - Return y coordinates of polygon path given x


code:
alphabet = set('abcdef01234567890')
compute_neighborhoods(data, alphabet)
data

rawDescription: Faster alternative to for loop in for loop


code:
from collections import deque
d=deque()
d.append((1,'a'))
d.append((4,'t'))
d
d.appendleft((8,'p'))
d

rawDescription: Add object to start of dictionary

description: Add object to start of dictionary


code:
max(lis,key=lambda item:item[1])
max(lis,key=lambda item:item[1])[0]

rawDescription: Find the maximum value in a list of tuples in Python


code:
X, Y, Z = density_estimation(m1, m2)

fig, ax = plt.subplots()

# Show density
ax.imshow(np.rot90(Z), cmap=plt.cm.gist_earth_r,
          extent=[xmin, xmax, ymin, ymax])

# Add contour lines
plt.contour(X, Y, Z)

ax.plot(m1, m2, 'k.', markersize=2)

ax.set_xlim([xmin, xmax])
ax.set_ylim([ymin, ymax])
plt.show()

rawDescription: Pyplot Scatter to Contour plot

description: Pyplot Scatter to Contour plot


code:
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=4, sharex=True)
yranges = [(-1000, 100), (-0.001, 0.002), (0, 5), (0, 20)]
labels = ['$P_{EUC}[mm]$', '$P_z[mm]$', '$P_Y[mm]$', '$P_X[mm]$']

for ax, yrange, label in zip(axes, yranges, labels):
    ax.set(ylim=yrange)
    ax.annotate(label, xy=(0, 0.5), xytext=(5, 0), rotation=90,
                xycoords=('figure fraction', 'axes fraction'),
                textcoords='offset points', va='center', ha='left')

plt.show()

rawDescription: Python Numpy Matplotlib Set Y-Label inline


code: titlelist

rawDescription: Searching for one-word string occupying a line of a text with Python 2.7


code:
from itertools import combinations_with_replacement, permutations
from operator import mul
from functools import reduce

results = set()
for digits in combinations_with_replacement(range(1, 10), 5):
    if sum(digits) == reduce(mul, digits):
        # add unique permutations of the digits as a new integer
        results.update(int(''.join(map(str, p))) for p in permutations(digits))

for result in sorted(results):
    print(result)

rawDescription: Count numbers in range which sum of digits is same as product


rawDescription: Pythonic way to extract specific values from a dictionary based on a subset of keys


code:
pair_dist = d.cdist(position, position)
pair_d = pair_dist<=4
for i in range(len(pair_d)):
    for j in range(i):
        # Only looking at upper triangular matrix (not inc. diagonal)
        if pair_d[i,j] ==True:
            # If two particles are too close then swap velocities
            # It's a bad hack but it'll work for now.
            vel_1 = velocity[j][:]
            velocity[j] = velocity[i][:]*0.9
            velocity[i] = vel_1*0.9

rawDescription: Many particles in box - physics simulation


code:
def readD(val):
    if 'C' in val:
        return numpy.nan
    return val

rawDescription: How do I get nan_values in pandas' read.csv to say "Set as NaN if it contains the character 'C' in any cell"

description: Get nan_values in pandas' read.csv to say "Set as NaN if it contains the character 'C' in any cell"


code:
import socket
import os

HOST = 'localhost'
PORT = 1024
downloadDir = "/tmp"

filename = raw_input('Enter your filename: ')
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(filename)
with open(os.path.join(downloadDir, filename), 'wb') as file_to_write:
    while True:
        data = socket1.recv(1024)
        if not data:
            break
        file_to_write.write(data)
    file_to_write.close()
socket1.close()

rawDescription: How to download file from local server in Python

description: Download file from local server in Python


code:
def maybe_replace_corgi(corgi):
    if corgi.cuteness > threshold:
        corgi.will_keep = True
        return corgi
    else:
        return Corgi(name="Woofus")

my_corgi = Corgi(name="Rudolf")
my_corgi = maybe_replace_corgi(my_corgi)

rawDescription: How do I change where a variable is pointing to within a function?

description: Change where a variable is pointing to within a function


code: v = input().split()

rawDescription: Declare and assign an amount of variables from an input?


code:
shape = grid.shape[0]

first_col  = (i for i,col in enumerate(grid.T) if np.isfinite(col).any() == True).next()
last_col  = (shape-i-1 for i,col in enumerate(grid.T[::-1]) if np.isfinite(col).any() == True).next()
first_row = (i for i,row in enumerate(grid) if np.isfinite(row).any() == True).next()
last_row  = (shape-i-1 for i,row in enumerate(grid[::-1]) if np.isfinite(row).any() == True).next()

row_len = last_row - first_row
col_len = last_col - first_col
delta_len = row_len - col_len
if delta_len == 0:
    pass
elif delta_len < 0:
    first_row = first_row - abs(delta_len)
    if first_row < 0:
        delta_len = first_row
        first_row = 0
        last_row += abs(delta_len)
elif delta_len > 0:
    first_col -= abs(delta_len)
    if first_col < 0:
        delta_len = first_col
        first_col = 0
        last_col += abs(delta_len)

grid =  grid[first_row:last_row+1, first_col:last_col+1]

rawDescription: Crop nan rows and columns of a matrix, but keep it square


code: min(x[1] for x in gen)

rawDescription: minimum of list of lists

description: Minimum of list of lists


rawDescription: Why implement two so similar data structures like List and Tuple


code: {u'type_of_event': u'goal', u'player': u'Benzema', u'id': 283, u'time': u'67'}

rawDescription: How to find which item in a JSON list has the greatest value for a given attribute in Python?

description: Find which item in a JSON list has the greatest value for a given attribute in Python


code:
import pyMyDB

def GetTachometerReading(self):
    # self here is the db instance, as if this was a method on the db
    print(self.db_stuff)

pyMyDB.MyDB.submodule_methods["Driving"] = {"GetTachometerReading":GetTachometerReading}

rawDescription: Access parent object from submodule

description: Access parent object from submodule


code:
def mystringlist():
    yield 'foo'
    yield 'bar'
    yield 'hello'
if any(s in mystring for s in mystringlist()):
    pass

rawDescription: Is there any nicer way to write successive "or" statements in Python?


code:
lbl, n = label(img)
lbl
n

rawDescription: Why ndimage.label(image) labels extra shapes among the considered ones?


code:
xmin, xmax = g.ax_marg_y.get_xlim()
g.ax_marg_y.set_xlim(xmin,xmax*2)

rawDescription: Rescale axis on Seaborn JointGrid KDE marginal plots


rawDescription: python sort list based on key sorted list

description: Python sort list based on key sorted list


rawDescription: How to get all mappings between two lists?

description: Get all mappings between two lists


code:
def boolList2BinString(lst):
    return '0b' + ''.join(['1' if x else '0' for x in lst])
boolList2BinString([True, True, False])

rawDescription: Python: Boolean List to Binary String

description: Python: Boolean List to Binary String


rawDescription: python Binary string to binary data

description: Python Binary string to binary data


code:
urlpatterns = [
    url(r'^account/$', account_redirect, name='account-redirect'),
]

rawDescription: Django - Login and redirect to user profile page


rawDescription: simulate time python

description: Simulate time python


code:
BibliographyData(entries=OrderedCaseInsensitiveDict({
    'article': Entry(
        'article',
        fields={
            'volume': '4',
            'title': 'The title of the work',
            'journal': 'The name of the journal',
            'number': '2',
            'month': '7',
            'note': 'An optional note',
            'year': '1993',
            'pages': '201-213'},
        persons={
            'author': [Person(u'Adams, Peter')]})
    }), preamble=[])

rawDescription: Pybtex does not recogonize bibtex entry

description: Pybtex does not recogonize bibtex entry


code:
f = csv.writer(open("test.csv", "w"))

# Write CSV Header
f.writerow(["name", "qty"])

for k, v in d.items(): # iteritems python2
    if v:
        f.writerow([k.split(".")[0]]+[s.split(".")[0] for s in v])

rawDescription: How to save JSON string into CSV or TXT in Python?

description: Save JSON string into CSV or TXT in Python


code:
class RemoteApiTest(AppTest, ApiTestMixin):
    @classmethod
    def setUpClass(cls):
        super(RemoteApiTest, cls).setUpClass()
        cls.kwargs = config.FLASK_CLIENT_CONFIG
        cls.base_url = cls.kwargs.get('base_url')
        cls.content_type = cls.kwargs.get('content_type')
        cls.client = requests
        cls.db = db
        cls.db.create_all()

    @classmethod
    def tearDownClass(cls):
        super(RemoteApiTest, cls).tearDownClass()
        cls.db.session.remove()
        cls.db.drop_all()
        #cls.db.get_engine(cls.app).dispose()

    @property
    def base_url(self):
        return self.__class__.base_url

    @property
    def content_type(self):
        return self.__class__.content_type

    def get_json(self, r):
        return r.json()

    @property
    def headers(self):
        headers = {'content-type': self.content_type}
        if self.api_key:
            headers.update({'X-consumer-apiKey': self.api_key})
        return headers

    def basic_checks(self, rv):
        eq_(rv.status_code, 200)
        r = rv.json()
        assert rv is not None
        assert r is not None
        assert r.get('correlationID') is not None
        return r

    def setUp(self):
        super(RemoteApiTest, self).setUp()
        self.api_key = None

        r = self.client.post('{0}/account/register'.format(self.base_url), data=json.dumps(account_register),
                             headers=self.headers)
        j = r.json()
        self.api_key = j['apiKey']

    def tearDown(self):
        rv = self.client.delete('{0}/account'.format(self.base_url), headers=self.headers)
        super(RemoteApiTest, self).tearDown()

rawDescription: Run Flask tests against a remote server

description: Run Flask tests against a remote server


rawDescription: Split a string of Emojis into single Emoji character


rawDescription: Get permutation with specified degree by index number


code:
ss = values.searchsorted(items)

print(all(original(values, items) == ss))
# True

print(all(peter_e(values, items) == ss))
# True

rawDescription: searching sorted items into a sorted sequence

description: Searching sorted items into a sorted sequence


code: [itm for itm in lst if all(friend not in blacklist for friend in itm["friends"])]

rawDescription: Delete items from a list if the item contains an entry in a blacklist


code: result = numpy.rollaxis(A.dot(u), 1)

rawDescription: Multiplying matrix A times multi-dimensional matrix "matrix-wise?"


rawDescription: Python: Find-replace on lists

description: Python: Find-replace on lists


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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
nbins = 50
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
    ys = np.random.normal(loc=10, scale=10, size=2000)

    hist, bins = np.histogram(ys, bins=nbins)
    xs = (bins[:-1] + bins[1:])/2

    ax.bar(xs, hist, zs=z, zdir='y', color=c, ec=c, alpha=0.8)

ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.show()

rawDescription: Can I plot several histograms in 3d?

description: Plot several histograms in 3d


code:
import re
pattern = re.compile(r'"Postal Code":(\d+),')
source = '"State":"NC","Postal Code":27605,"Description":null,'
pattern.search(source).group(1)

rawDescription: Python capture group and quote it with regex


code:
from contextlib import contextmanager
import inspect

class some_class:
    def test(self):
        print("test!")

@contextmanager
def map_to_local(inst, locals):
    methods = inspect.getmembers(inst, inspect.ismethod)
    for name, method in methods:
        locals[name] = method
    yield
    for name, method in methods:
        del locals[name]

inst = some_class()
with map_to_local(inst, locals()):
    test()

rawDescription: Calling multiple functions from a class in Python without repeating the class name every time


code:
def permutateIndexes(array, perm):
    return array[np.ix_(perm, perm)]

rawDescription: Permuting numpy's 2d array indexes

description: Permuting numpy's 2d array indexes


code:
money = 1000000

def luckyrollgame():
    global money
    from random import choice
    print('You are in the game lobby of Lucky Roll.')
    print('Choose either \'rules,\' \'play,\' or \'back\'')
    lobby = input()
    if lobby == 'rules':
        luckyrollgamerules()
    elif lobby == 'play':
        die = [1, 2, 3, 4, 5, 6]
        number1 = choice(die)
        prediction = input('Please type your prediction number: ')
######################### This too
        try: prediction = int(prediction)
        except ValueError: prediction = -10
#########################
        if prediction == number1:
            print('Good job! You guessed right!')
            money = money + 3
            print('You now have ' + str(dollars) + 'dollars.')
        elif prediction == number1 - 1:
            print('Good job! You guessed right!')
            money = money + 3
            print('You now have ' + str(dollars) + 'dollars.')
        elif prediction == number1 + 1:
            print('Good job! You guessed right!')
            money = money + 3
            print('You now have ' + str(dollars) + 'dollars.')
        else:
            print('I\'m sorry. You didn\'t get the number right.')
            print('The number was ' + str(number1) + '.')
            money = money - 1
            print('You now have ' + str(money) + 'dollars.')
            print('--------------------------------------------------')
            altluckyrollgame()
    elif lobby == 'back':
        altvillagescene()
    else:
        print('Please type a valid option.')
        print('--------------------------------')
        altluckyrollgame()

rawDescription: Condition always evaluates to else branch


code: [('age', 29), ('name', 'ehsan'), ('family', 'shirzadi')]

rawDescription: How to access a class field values in its base class?

description: Access a class field values in its base class


rawDescription: how to implement a list of paragraph word lengths using a for loop

description: Implement a list of paragraph word lengths using a for loop


code:
from io import StringIO
...
s = configfile.read()
s.replace("#","_")
f = StringIO(unicode(s))
configparser.readfp(f)

rawDescription: Python: How to ignore # so that the line is not a comment?


rawDescription: Django JSONField filtering

description: Django JSONField filtering


code:
with open ('~/abc.csv', 'w') as f:
    with open ('~/def.csv', 'w') as g:
        writer1 = csv.writer(f)
        writer2 = csv.writer(g)
        ...

rawDescription: how to write results in a for loop to multiple CSV files

description: Write results in a for loop to multiple CSV files


code:
# Collect entire line instead of letter
text_line_letters = ''
for [x, y, dx, dy, r], letter in letters_positions:
    text_line_letters = text_line_letters + letter
    # Skip rest of for loop
    continue

rawDescription: Digital cursor movement recorded in PDF creation visible in CorelDraw


code:
# /dupefilters.py

from scrapy.dupefilters import RFPDupeFilter

class MyRFPDupeFilter(RFPDupeFilter):

    def request_seen(self, request, spider):
        fp = self.request_fingerprint(request)
        if fp in self.fingerprints:
            return True
        self.fingerprints.add(fp)
        if self.file:
            self.file.write(fp + os.linesep)

        # Do things with spider

rawDescription: Scrapy - Retrieve spider object in dupefilter


code:
def sameChars(s1, s2):
    if set(s1) == set(s2):
        return True
    else:
        return False

rawDescription: Function sameChars doesn't work properly


code:
from config import *

print(accounts['acc1']['OAUTH_TOKEN'])

rawDescription: How do I import only a few lines from a python script?

description: Import only a few lines from a python script


code:
my_csv_data = list(reader)
print(my_csv_data[N])

rawDescription: Best way to access the Nth line of csv file

description: Access the Nth line of csv file


code:
import logging

class OneLineExceptionFormatter(logging.Formatter):
    def formatException(self, exc_info):
        result = super(OneLineExceptionFormatter, self).formatException(exc_info)
        return repr(result) # or format into one line however you want to

    def format(self, record):
        s = super(OneLineExceptionFormatter, self).format(record)
        if record.exc_text:
            s = s.replace('\n', '') + '|'
        return s

fh = logging.FileHandler('output.txt', 'w')
f = OneLineExceptionFormatter('%(asctime)s|%(levelname)s|%(message)s|', '%m/%d/%Y %I:%M:%S %p')
fh.setFormatter(f)
root = logging.getLogger()
root.setLevel(logging.DEBUG)
root.addHandler(fh)
logging.info('Sample message')

try:
    x = 1 / 0
except ZeroDivisionError as e:
    logging.exception('ZeroDivisionError: {0}'.format(e))

rawDescription: How do I can format exception stacktraces in Python logging?

description: Can format exception stacktraces in Python logging


code:
for foo in generator:
    directories.append(foo['name'])
    yield foo

rawDescription: Capture-and-yield in a list comprehension


code:
s >= a
n <= b

rawDescription: Finding a loop invariant for this power function


code:
data3 = np.array(tupleli, dtype=dt)
data3.shape
data3[2]
data3['start date']
data3['n']

rawDescription: Equivalent of named tuple in NumPy?

description: Equivalent of named tuple in NumPy


code:
from xml.etree import ElementTree as ET
elem = ET.fromstring('''<Atom3d ID="18" Mapping="43" Parent="2" Name="C7"
XYZ="0.0148299997672439,0.283699989318848,1.0291999578476" Connections="33,39"
TemperatureType="Isotropic" IsotropicTemperature="0.0677"
AnisotropicTemperature="0,0,0,0,0,0,0,0,0" Occupancy="0.708" Components="C"/>
''')

rawDescription: Extracting XML Element and Attribute Data with Python 3


rawDescription: Can pip (or setuptools, distribute etc...) list the license used by each installed package?


rawDescription: Check if multple variables greater than zero in python


code:
import numpy as np

def using_for_loop(hog, sobel_Y, sobel_X):
    for y in xrange(0, sobel_Y.shape[0]):
        for x in xrange(0, sobel_X.shape[1]):
            base_angle = np.arctan2(sobel_Y[y, x], sobel_X[y, x]) * 180 / np.pi
            if base_angle < 0:
                base_angle += 360
            angle = int(round(base_angle / 45))
            if angle == 8:
                angle = 0
            hog[y, x, angle] += np.sqrt(sobel_X[y, x] ** 2 +
                                        sobel_Y[y, x] ** 2)
    return hog

def using_indexing(hog, sobel_Y, sobel_X):
    base_angle = np.arctan2(sobel_Y, sobel_X) * 180 / np.pi
    base_angle[base_angle < 0] += 360
    angle = (base_angle / 45).round().astype(np.uint8)
    angle[angle == bins] = 0
    magnitude = np.sqrt(sobel_X ** 2 + sobel_Y ** 2)
    Y, X = np.ogrid[0:angle.shape[0], 0:angle.shape[1]]
    hog[Y, X, angle] += magnitude
    return hog

bins = 8
sobel_Y, sobel_X = np.meshgrid([1, 2, 3], [4, 5, 6, 7])
# hog = np.zeros(sobel_X.shape + (bins,))
hog = np.random.random(sobel_X.shape + (bins,))
answer = using_for_loop(hog, sobel_Y, sobel_X)
result = using_indexing(hog, sobel_Y, sobel_X)
assert np.allclose(answer, result)

rawDescription: numpy 2d array (coordinates) need to assign into 3D array, to some particular bin

description: Numpy 2d array (coordinates) need to assign into 3D array, to some particular bin


rawDescription: Proper way of using properties with try and except


code: y_pred = [True, False, True, False, False]

rawDescription: Correctly calculating the F1 score in Sklearn


code:
def get_foo(self):
    self._foo = self._foo or Bar()
    return self._foo

rawDescription: What's Python equivalent to or equals expression, to get return foo or foo = 'bar' working?


code: c_list = [temp[a['category_name']] for a in a_list]

rawDescription: Combine two lists which have the same item in dict


code:
from pprint import pprint
import urllib2

from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://www.livescore.com/soccer/champions-league/'))

data = []
for match in soup.select('table.league-table tr'):
    try:
        team1, team2 = match.find_all('td', class_=['fh', 'fa'])
    except ValueError:  # helps to skip irrelevant rows
        continue

    score = match.find('a', class_='scorelink').text.strip()
    data.append({
        'team1': team1.text.strip(),
        'team2': team2.text.strip(),
        'score': score
    })

pprint(data)

rawDescription: BeautifulSoup data scrapping and database


rawDescription: Python regexp to capture numbers and dashes separated by spaces and comma


code:
num1, num2, Q_3 = map(raw_input, ["What will be your first number? ",
    "What will be your second number? ", "What will be your operation? "])
if Q_3 in ("+", "-", "/", "*", "%", "**"):
    print(eval("%s %s %s" % (float(num1), Q_3, float(num2))))

rawDescription: Simple Python Calculator Challenge 2.7

description: Simple Python Calculator Challenge 2.7


rawDescription: What Python Module extracts certain chars from raw input?


code: from src.model.somefile import Something

rawDescription: How do I make relative importing work in Python using Eclipse with PyDev?

description: Make relative importing work in Python using Eclipse with PyDev


code:
def invert_string(s):
    return dict((v, i) for i, v in enumerate(s))

dvowels = invert_string(vowels)
dconsonants = invert_string(consonants)

def wordtopin(s):
    ''' Convert string s of alternating consonants and vowels into an integer '''
    num = 0
    for c, v in zip(*[iter(s)]*2):
        num = 100 * num + 5 * dconsonants[c] + dvowels[v]
    return num

rawDescription: converting numbers to consonant-vowel pairs

description: Converting numbers to consonant-vowel pairs


rawDescription: Identifying groups of similar numbers in a list


code:
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import numpy as np
import math

def euler(df, f0, x):
    h = x[1] - x[0]
    y = [f0]
    for i in xrange(len(x) - 1):
        y.append(y[i] + h * df(y[i], x[i]))
    return y

def i(df, f0, x):
    h = x[1] - x[0]
    y = [f0]
    y.append(y[0] + h * df(y[0], x[0]))
    for i in xrange(1, len(x) - 1):
        fn = df(y[i], x[i])
        fn1 = df(y[i - 1], x[i - 1])
        y.append(y[i] + (3 * fn - fn1) * h / 2)
    return y

def df(y, x):
   return 2.0 / np.sqrt(np.pi) * np.exp(-x * x)

if __name__ == "__main__":
    f0 = 0.0
    x = np.linspace(-10.0, 10.0, 10000)

    y1 = euler(df, f0, x)
    y2 = i(df, f0, x)
    y3 = integrate.odeint(df, f0, x, tcrit = [0])

    plt.plot(x, y1)
    plt.plot(x, y2)
    plt.plot(x, y3)
    plt.legend(["euler", "modified", "odeint"], loc='best')
    plt.grid(True)
    plt.show()

rawDescription: scipy.odeint strange behavior

description: Scipy.odeint strange behavior


code:
from collections import defaultdict

merged = defaultdict(lambda: defaultdict(list))
for L in listoflistsofdicts:
  for d in L:
    for k in d:
      for competition, medal in d[k].iteritems():
          merged[k][competition].append(medal)

rawDescription: How would I merged nested dictionaries in a list in python?


code:
from collections import defaultdict
teams = defaultdict(list)
for line in fobj_in:
    if not line.strip():
        continue
    items = [entry.strip() for entry in line.split('\t') if entry]
    if len(items) == 2:
        name = items[0]
        team = items[1]
    else:
        team = items[0]
    teams[team].append(name)
for team_name in sorted(teams.keys()):
    fobj_out.write(team_name + ', ')
    for name in teams[team_name][:-1]:
        fobj_out.write('{}, '.format(name))
    name = teams[team_name][-1]
    fobj_out.write('{}\n'.format(name))

rawDescription: Aggregate text field from several lines (javascript/python)


code: ع: ain

rawDescription: How to map a arabic character to english string using python

description: Map a arabic character to english string using python


code:
df['item_number'] = df.groupby('ticket_number').cumcount()
df

rawDescription: Pandas pivot or groupby for dynamically generated columns


code:
import subprocess
subprocess(['notepad', r'd:\example.txt'])

rawDescription: How to display or show notepad file using python

description: Display or show notepad file using python


code:
import re
s = "104412=Trident of Corrupted Waters"
re.findall(r'^(\d+)', s)[0]

rawDescription: python plain text regex parsing

description: Python plain text regex parsing


code:
import sys
print(int(sys.argv[1]) + int(sys.argv[2]))

rawDescription: I want to create python script file: i am new to it


code:
from itertools import permutations
grouped = df.groupby('alpha')
resultlist = []

for key,group in grouped:
    for b,g in permutations(group['beta'].tolist(),2):
        resultlist.append([key,b,g])

result = pd.DataFrame(resultlist,columns=['alpha','beta','gamma'])

rawDescription: pandas dataframe group by with permutations

description: Pandas dataframe group by with permutations


code:
lompg = str('newlist.txt')

mpgList = open(lompg, "r")
listData = mpgList.read()
mpgList.close()
listData=listData.split()
listLength = (len(listData))
data = sum(map(float, listData))
avg = data /listLength
print(avg)

rawDescription: Trying to extract text from a txt file between 2 symbols and store in a list


code:
s = '---abd-d--'
mid = s.strip('-')
si = s.index(mid[0])
si, si + len(mid) - 1

rawDescription: How to get index of a substring padded with a special character

description: Get index of a substring padded with a special character


code: subprocess.call(r'cat <<< "\u0061"', shell=True, executable='/bin/bash')

rawDescription: Using subprocess to get output

description: Using subprocess to get output


code:
L = [(['A','B'], 5), (['A'], 6), (['C'], 1)]

# sort by descending value
L.sort(key=lambda s:s[1], reverse=True)

# keep track of what members have already occurred
seen = set()

# Cull L - ignore members already in `seen`
# (Because it is presorted, already-seen members must have had a higher value)
L = [seen.update(i) or (i,j) for i,j in L if seen.isdisjoint(i)]

rawDescription: Culling list to find greatest non-intersecting members in Python


code:
def pubsub_publish(self, msg):
    # An event message could contain multiple items, but we break them up into
    # separate events for you to make it a bit easier.
    item = msg['pubsub_event']['items']['item']
    # Process item depending on application, like item['tune'],
    # or the generic item['payload']

rawDescription: sleekxmpp pubsub example

description: Sleekxmpp pubsub example


rawDescription: Smart rewriting of expressions in sympy

description: Smart rewriting of expressions in sympy


code:
performances = []  # list of dicts, one per performance
for tr in rows:
    # extract the data-* using dictionary key lookup on tr
    p = dict(
        lat=float(tr['data-lat']),
        lng=float(tr['data-lng']),
        zipcode=tr['data-zip']
    )
    # extract the td children into a list called tds
    tds = [child for child in tr.children if child != "\n"]
    # the class of each td indicates what type of content it holds
    for td in tds:
       key = td['class'][0] # get first element of class list
       p[key] = td.string  # get the string inside the td tag
    # add to our list of performances
    performances.append(p)

rawDescription: Using Python to Automate Web Searches

description: Using Python to Automate Web Searches


code:
suffix = '.pdf'
os.path.join(dir_name, base_filename + suffix)

rawDescription: building full path filename in python,

description: Building full path filename in python,


code:
u1 = u.groupby('dates')['dates'].count().cumsum()
u1

rawDescription: How to get an accumulative counting of rows in a data frame?

description: Get an accumulative counting of rows in a data frame


code:
from bokeh.models import Span

p = figure(plot_width = 800, plot_height=400,
       title ='Monthly Mean Temperature Anomaly (1951-1980 baseline)',
       title_text_font_size='14pt', x_axis_type="datetime")

p.line(df2['Date'], df2['Value'])

hline = Span(location=0, dimension='width',
             line_color='red',
             line_width=1) #red line at 0

p.renderers.extend([hline]) #add line to the plot
p.xaxis.axis_label = 'Year'
p.yaxis.axis_label = 'Temperature (Degrees C)'

rawDescription: Bokeh line plot is merging data on graph


rawDescription: Convert point to line data using a list of point indices


code: dd.groupby( dd.index ).mean()

rawDescription: Average of a groupby or a groupby of an average on a dataframe with duplicated indexes


code:
for k,v in mydict.items():
    print(k,v)

rawDescription: How to print dictionary keys and values in python

description: Print dictionary keys and values in python


code:
import numpy as np
D = 3
n_bins =  100*np.ones(D)
bounds = np.repeat([(0,1)], D, axis = 0)

result = np.mgrid[[slice(row[0], row[1], n*1j) for row, n in zip(bounds, n_bins)]]
ans = np.mgrid[0:1:100j,0:1:100j,0:1:100j]

assert np.allclose(result, ans)

rawDescription: How to create multidimensional array with numpy.mgrid

description: Create multidimensional array with numpy.mgrid


code:
from ctypes import *
my_dll = windll.Script
my_dll.Script_GetFindedList.restype = None
size = c_uint()
my_dll.Script_GetFindedList(None, byref(size))
result = (c_uint*(size.value//4))()
my_dll.Script_GetFindedList(result, byref(size))
result = list(result)

rawDescription: How do I access wity python ctypes to array values returned with a pointer from a dll coded in Delphi?

description: Access wity python ctypes to array values returned with a pointer from a dll coded in Delphi


code:
if abs(len(string1) - len(string2)) > 1: return False
if len(string1) < len(string2):
    string1, string2 = string2, string1

rawDescription: Returns True if the two strings only differ by one character


rawDescription: Webscrapping using beautiful soup giving multiple results


code:
def confirmSub(match):
    print("Going to replace", match.string[match.start()-5:match.end()+5])
    x = raw_input("OK?")
    if x.lower().startswith("y"):
        return match.group() + "m"
    return match.group()

rawDescription: Interactive substitution - re.sub() with pos?


code:
if self_compose (lambda x: x+x, 3) ('B') == "BBBBBBBB":
   print ("SUCCESS")

rawDescription: Python lambda self composing function: How to return a function that is repeated n amount of times?


rawDescription: Multiply scipy.lti transfer functions

description: Multiply scipy.lti transfer functions


code:
item2
item1

rawDescription: How to put items into priority queues?

description: Put items into priority queues


code:
for x in chain(list1, list2):
  doSomething(x)

rawDescription: Is there a way to have parallel for-each loops?


code:
import random

d = 3
n = 1000

f = open('input.txt', 'w')

for i in range(n):
    nums = []
    for j in range(d):
        nums.append(str(round(random.uniform(0, 1000), 3)))
    s = ' '.join(nums)
    f.write(s)
    f.write('\n')

f.close()

rawDescription: How to create a big file quickly with Python

description: Create a big file quickly with Python


code: p = db.people.find({"some": "condition", "comments.type": "image"})

rawDescription: PyMongo - Querying list of embedded documents


rawDescription: Python (2.7) - Replacing multiple patterns in a string using re


code:
import MySQLdb
import MySQLdb.cursors as cursors
import config

connection = MySQLdb.connect(
    host=config.HOST, user=config.USER,
    passwd=config.PASS, db=config.MYDB,
    cursorclass=cursors.DictCursor)

with connection as cursor:
    cursor.execute('DROP TABLE IF EXISTS test')
    cursor.execute("""CREATE TABLE test (foo int, bar int, baz int)""")
    cursor.execute("""INSERT INTO test (foo, bar, baz) VALUES (%s,%s,%s)""", (1,2,3))
    cursor.execute('SELECT * FROM test')
    data = cursor.fetchone()
    fields = [item[0] for item in cursor.description]

rawDescription: fetching mysql data as python dictionary

description: Fetching mysql data as python dictionary


code:
def find_key(input_dict, value):
    return {k for k, v in input_dict.items() if v == value}

rawDescription: return key by value in dictionary

description: Return key by value in dictionary


rawDescription: Sql filter query with join objects

description: Sql filter query with join objects


code:
import audiere
d = audiere.open_device()
t = d.create_tone(17000) # 17 KHz
t.play() # non-blocking call
import time
time.sleep(5)
t.stop()

rawDescription: Python library for playing fixed-frequency sound


code:
for iRow, stVa in enumerate(dLocP):

    stVb,stVc,stVd = dLocP[stVa]

    Cworksheet.write(iRow + 1,0,stVa)
    Cworksheet.write(iRow + 1,1,stVb)
    Cworksheet.write(iRow + 1,2,stVc)
    Cworksheet.write(iRow + 1,3,stVd)

    formula = '=IF(E{}>0,(G{}+H{})/E{},0)'.format(*([iRow + 2] * 4))
    Cworksheet.write_formula(iRow + 1, 4, formula)

rawDescription: Python xlsxwriter: Adjust excel reference cells in loop when creating formula


rawDescription: count occurrences of number by column in pandas data frame

description: Count occurrences of number by column in pandas data frame


code:
def func(x):
    if 0 < x <= 10:
        return 'xxx'
    elif 10 < x <= 50:
        return 'yyy'
    return 'zzz'

df['col2'] = df['col1'].apply(func)

rawDescription: How to create categorical variable based on a numerical variable

description: Create categorical variable based on a numerical variable


code:
class NotifyList(UserList):
    def __init__(self, inilist=None, parent=None, id=None):
        self.parent = parent
        self.id = id
        # remainder of __init__()...

rawDescription: How to detect what element of a nested list has changed? (python)

description: Detect what element of a nested list has changed? (python)


code:
import times
times.to_universal('2012-02-03 11:59:03', 'Europe/Amsterdam')
times.to_local(_, 'Europe/Amsterdam')

rawDescription: Python: Parsing out publication dates from html pages


code: ['text', 'text', '', '', 'text', 'text', 'text', 'text', 'text', 'text']

rawDescription: find an empty value gap in a list and allocate a group of strings

description: Find an empty value gap in a list and allocate a group of strings


code: edge = random.choice(l3)

rawDescription: Constant time random selection and deletion


code:
import subprocess
subprocess.call(['vpn-connect'], shell = True)

rawDescription: How to call a self-defined command line function in Python

description: Call a self-defined command line function in Python


code:
loc = locals()
glob = globals()

for key in loc:
    glob[key] = loc[key]

rawDescription: Importing a shared library and the global namespace


code:
list_of_lists = [[1, 2], [3, 4]]
list_of_lists

rawDescription: Can I put a tuple into an array in python?

description: Put a tuple into an array in python


code: [list(gen()) for gen in generator_of_generator_functions]

rawDescription: python generator of generators?

description: Python generator of generators


rawDescription: How can I match regular expression for this url?

description: Match regular expression for this url


code:
import re
p = r'\s*(?:\(\{[^/]*/\s*/\s*}\)|NULL)\s*'
test_str = "NULL ({ / / }) Regina ({ 4 p1 p2 / / }) Shueller ({ 5 p1 p2 / / }) works ({ / / }) for ({ / / }) Italy ({ 14 / / }) 's ({ 15 / / }) La ({ 16 / / }) Repubblica ({ 17 / / }) newspaper ({ 18 / / }) . ({ 38 / / })"
result = re.sub(p, " ", test_str)
print(result.strip())
# => Regina Shueller works for Italy 's La Repubblica newspaper .

rawDescription: Python regex removing word with regex

description: Python regex removing word with regex


code: df.loc[:, mask]

rawDescription: Conditionally grabbing column headings in pandas dataframe


code:
import maya.cmds as cmds

# Get index value of last key
keyIndex = (cmds.keyframe("myObject.attribute", indexValue=True, q=True))[-1]

# Get time of key index
keyFrame = cmds.keyframe("myObject.attribute", q=True, index=(1, keyIndex))

rawDescription: How do I find the time of a particular keyframe using cmds.selectKey?

description: Find the time of a particular keyframe using cmds.selectKey


code: hands = Nplayers*[[]]

rawDescription: Card Deal Function Issue

description: Card Deal Function Issue


rawDescription: What does int() function with 2 args do in Python


code:
from dateutil.relativedelta import relativedelta
import datetime
TODAY = datetime.date.today()
TODAY

rawDescription: How do you add "3 months" to a datetime.date object in python?

description: Add "3 months" to a datetime.date object in python


code:
import pandas as pd

df = pd.read_csv('file_name.csv')
y  =  df[['gini']]
X  =  df[df.columns.difference(['gini'])]

rawDescription: Creating a X input matrix and y output vector via Python


code:
Namespace(A=True, B=True)
Namespace(C=True, D=True, file='file1', variable_list=None)
Namespace(C=True, D=False, file='file2', variable_list='a,b,c')

rawDescription: Python argparse: separate options for positional arguments


code:
def to_dict(self):
   return helper.mongo_to_dict(self)

rawDescription: Flask Jsonify mongoengine query

description: Flask Jsonify mongoengine query


code:
def has_consensus(l):
    return Counter(l).most_common(1)[0][1] * 2 > len(l)

rawDescription: How to find if consensus on answer

description: Find if consensus on answer


code:
def results(funcs, xs, ys):
  out = []
  for f in funcs:
    for x in xs:
      for y in ys:
        try:
          out.append(f(x,y))
        except ZeroDivisionError:
          pass
  return out

rawDescription: Building a variable that combines several enumerations in an enormous list


code:
@jit
def parakeet_dist(x, y, z, L, periodicX, periodicY, periodicZ):
  # perform all-pairs computations more explicitly
  # instead of tile + broadcasting
  def periodic_diff(x1, x2, periodic):
    diff = x1 - x2
    if periodic:
      if diff > (L / 2): diff -= L
      if diff < (-L/2): diff += L
    return diff
  dx = np.array([[periodic_diff(x1, x2, periodicX) for x1 in x] for x2 in x])
  dy = np.array([[periodic_diff(y1, y2, periodicY) for y1 in y] for y2 in y])
  dz = np.array([[periodic_diff(z1, z2, periodicZ) for z1 in z] for z2 in z])
  d= np.sqrt(dx**2 + dy**2 + dz**2)

  # since we can't yet use boolean indexing for masking out zero distances
  # have to fall back on explicit loops instead
  for i in xrange(len(x)):
    for j in xrange(len(x)):
      if d[i,j] == 0: d[i,j] = -1
  return d, dx, dy, dz

rawDescription: Optimizing Python function with Parakeet


code:
for i in filarr:
    for j in buiarr:
        for l in datarr:
            a = data[l][(i, j)]
            np.putmask(a, np.abs(a)<.01, np.nan)
            data[l].update({(i, j):a})

rawDescription: looping dictionaries of {tuple:NumPy.array}

description: Looping dictionaries of {tuple:NumPy.array}


code:
def Spin3(n, N) :           # n - current state, N - highest state
    value = n + 1
    value[value>N] = 0
    return value

rawDescription: Numpy broadcasting with comparison operator; cyclic iteration


rawDescription: merge two lists to make list of lists

description: Merge two lists to make list of lists


code: list(that for this, that in pairs(li) if this=='she')

rawDescription: Getting a sub-list containing list[i+1] where list[i] is a specific value


code:
import pandas as pd
from StringIO import StringIO
s = """sample  category_a  category_b  value
1       A           Z           3.92
2       A           Y           12.43
3       B           Z           5.87
4       B           Y           6.71"""

df = pd.read_csv(StringIO(s), sep="\s+", index_col=0)

rawDescription: Filter, group, and calculate statistics for Numpy matrix data


rawDescription: Pivot String column on Pyspark Dataframe


code:
import shelve

myShelve = shelve.open('my.shelve')
myShelve.update(bigd)
myShelve.close()

rawDescription: Pickle versus shelve storing large dictionaries in Python


code: [x+y for x, y in zip(a, b)]

rawDescription: Python adding values from one list to those of another


rawDescription: get the value without ' '

description: Get the value without ' '


code:
with open('word_list.txt') as f:
    word_list = f.readlines()

# Make sure words don't end with a newline character ('\n')
word_list = [word.strip() for word in word_list]

rawDescription: Check RSS feed titles for words. Print only titles that contain word


rawDescription: extract main diagonal of a sparse matrix in scipy.sparse python

description: Extract main diagonal of a sparse matrix in scipy.sparse python


code:
try:
  with dblink.CommittingSession() as session:
    session.add(...)
except ...:
  # at this point, session.rollback has been called
  log.error('We failed!')

rawDescription: How to manage this pattern this sqlalchemy

description: Manage this pattern this sqlalchemy


code: filtered = [d for d in data if not any(dropped in d[1].split() for dropped in drop)]

rawDescription: Filtering a list based on another list

description: Filtering a list based on another list


code: tuple([e for e in l if e][:3] for l in data)

rawDescription: Removing blank objects within a tuple

description: Removing blank objects within a tuple


rawDescription: Solving Puzzle in Python

description: Solving Puzzle in Python


rawDescription: Defining a function that prints dictionaries neatly


rawDescription: Python 2D-cluster finder

description: Python 2D-cluster finder


code:
columns = [Column(catalog, col) for col in data.keys()]

sql = catalog.insert(
     columns=columns,
      values=[data.values()]
)

rawDescription: Improve MySQLdb query

description: Improve MySQLdb query


code: ['the', 'apple']

rawDescription: Returning the words from a string that occur a number of times or more in python 3?


code:
@app.route('/', methods=['GET', 'POST'])
def index(result=None):
    if request.args.get('mail', None):
        result = process_text(request.args['mail'])
    return render_template('index.html', result=result)

def process_text(text):
    return "FOO" + text

rawDescription: How to build a get-form post in flask

description: Build a get-form post in flask


rawDescription: Matlab equivalent of Python's 'reduce' function


code: map (lambda t: (t[1], t[0]), mylist)

rawDescription: swap values in a tuple/list inside a list in python?

description: Swap values in a tuple/list inside a list in python


code: cars = [car(driver, sponsor) for driver, sponsor in drivers.items()]

rawDescription: Assignment: Python 3.3: add keys and values from dictionary to class


code:
def curp(x): return 'AB' not in x
def prevp(xp): return 'CD' in xp

rawDescription: "If...or..." statement inside list comprehension?


rawDescription: Python 2d interpolation of 3d array

description: Python 2d interpolation of 3d array


code:
def MplusMT(M):
    msk=M.row!=M.col;
    data=np.concatenate([M.data, M.data[msk]])
    rows=np.concatenate([M.row, M.col[msk]])
    cols=np.concatenate([M.col, M.row[msk]])
    MM=sparse.coo_matrix((data, (rows, cols)), shape=M.shape)
    return MM

# alt version with a more explicit D
#    msk=M.row==M.col;
#    data=np.concatenate([M.data, M.data,-M.data[msk]])

rawDescription: Diagonal sparse matrix obtained from a sparse coo_matrix


code:
class MyProperty( property ): pass

class Test( object ):
    def __init__( self ):
        self._x = 10

    def get_x( self ):
        return self._x

    @MyProperty
    def x( self ):
        return self.get_x()

test = Test()

rawDescription: Can you change a python descriptor's __get__ method at runtime?

description: Change a python descriptor's __get__ method at runtime


code:
import tkinter as tk
from tkinter import ttk

# Top-level frame
root = tk.Tk()
root.title( "Double scrollbar with tkinter" )
root.minsize(width = 600, height = 600)
frame = ttk.Frame(root, relief="sunken")

# Canvas creation with double scrollbar
hscrollbar = ttk.Scrollbar(frame, orient = tk.HORIZONTAL)
vscrollbar = ttk.Scrollbar(frame, orient = tk.VERTICAL)
sizegrip = ttk.Sizegrip(frame)
canvas = tk.Canvas(frame, bd=0, highlightthickness=0, yscrollcommand = vscrollbar.set, xscrollcommand = hscrollbar.set)
vscrollbar.config(command = canvas.yview)
hscrollbar.config(command = canvas.xview)

# Add controls here
subframe = ttk.Frame(canvas)

#Packing everything
subframe.pack(padx   = 15, pady   = 15, fill = tk.BOTH, expand = tk.TRUE)
hscrollbar.pack( fill=tk.X, side=tk.BOTTOM, expand=tk.FALSE)
vscrollbar.pack( fill=tk.Y, side=tk.RIGHT, expand=tk.FALSE)
sizegrip.pack(in_ = hscrollbar, side = tk.BOTTOM, anchor = "se")
canvas.pack(side = tk.LEFT, padx  = 5, pady   = 5, fill = tk.BOTH, expand= tk.TRUE)
frame.pack( padx   = 5, pady   = 5, expand = True, fill = tk.BOTH)

canvas.create_window(0,0, window = subframe)
root.update_idletasks() # update geometry
canvas.config(scrollregion = canvas.bbox("all"))
canvas.xview_moveto(0)
canvas.yview_moveto(0)

# launch the GUI
root.mainloop()

rawDescription: How to add 2 scrollbars with tkinter in python 3.4?

description: Add 2 scrollbars with tkinter in python 3.4


code:
def getlocation(self, cellindex):
    res = []
    for size in reversed(self.dimensions):
        res.append(cellindex % size)
        cellindex /= size
    return res[::-1]

rawDescription: Python Multidimensional Array as a single List


code: result = [grouped[hour] for hour in sorted(grouped)]

rawDescription: Split list of datetime by hours using python


rawDescription: How can I attach an in-memory SQLite database in Python?

description: Attach an in-memory SQLite database in Python


code:
from requests import Session, Request

s = Session()
p = Request('GET', 'http://someurl.com', params=request_parameters).prepare()
log.append(p.url)

rawDescription: Create url without request execution

description: Create url without request execution


code:
import sys
normalize([sys.float_info.max, sys.float_info.min])
normalize([sys.float_info.max, sys.float_info.min])[-1] == 0

rawDescription: Normalize Small Probabilities in Python

description: Normalize Small Probabilities in Python


code:
class view_item:
    def GET(self, itemID):
        item_info = sqlitedb.detailInfo(itemID)
        return render_template('view_item.html', item = item_info)

rawDescription: Passing variables from Jinja to database


rawDescription: python regular expression also match special characters

description: Python regular expression also match special characters


rawDescription: Filtering a DataFrame based on multiple column criteria


code:
from django.db.models import Count, Case, When, IntegerField

...

queryset = Parent.objects.annotate(
               num_ok=Count(Case(
                            When(children__status='ok', then=1),
                                output_field=IntegerField()))
           ).annotate(
               num_fail=Count(Case(
                              When(children__status='fail', then=1),
                                output_field=IntegerField())))

rawDescription: Django ORM grouped count of children

description: Django ORM grouped count of children


code:
people = People.objects.order_by(name).filter(age__gt=65) # unevaluated
people.query.set_limits(start, stop)  # still unevaluated
for person in people:  # now its evaluated
    person.do_the_thing()

rawDescription: Limiting the number of results from a Django QuerySet, without using slice


code: return letters == letters[::-1]

rawDescription: Can I make a code in python that ignores special characters such as commas, spaces, exclamation points, etc?

description: Make a code in python that ignores special characters such as commas, spaces, exclamation points, etc


code:
s = 'format db "this is string a", 0, 0Ah'

import shlex

shlex.split(s)
Out[18]: ['format', 'db', 'this is string a,', '0,', '0Ah']

rawDescription: How to divide string like this into items in Python

description: Divide string like this into items in Python


code:
a_disjoint_b = set(list_a) - set(list_b)
for a in list_a:
    if a in a_disjoint_b:
        writeFile(...)

rawDescription: Comparing large list of hashes to other large list of hashes


code:
CURRENCY = {
    '¥': 'JPY', 'yen': 'JPY', 'jpy': 'JPY',
    '€': 'EUR', 'euro': 'EUR', 'eur': 'EUR',
    '$': 'USD', 'dollar': 'USD', 'usd': 'USD',
    '£': 'GBP', 'pound': 'GBP', 'gbp': 'GBP',
}

def read_currency(prompt):
    """Prompt the user to enter a currency.

    Returns a currency code.
    """
    while True:
        x = input(prompt)
        try:
            return CURRENCY[x.lower()]
        except KeyError:
            print('Unknown currency: {!r}'.format(x))

rawDescription: Make sure input is limited to variables

description: Make sure input is limited to variables


code: time_difference = time_in_transit[j] - time_in_transit[i]

rawDescription: Convert a 12 hour time format to 24 hour time format (keeping record of the day) in python


rawDescription: Parse list of numbers into list in python


code:
from sqlalchemy import Column, ForeignKey, Integer, String, Table, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import backref, relationship, sessionmaker
from sqlalchemy.orm.collections import attribute_mapped_collection

Base = declarative_base()

class A(Base):
    __tablename__ = 'a'

    id = Column(Integer, primary_key=True)

a_b_association_table = Table(
    'a_b_association', Base.metadata,
    Column('a_id', Integer, ForeignKey('a.id')),
    Column('b_id', Integer, ForeignKey('b.id'))
)

class B(Base):
    __tablename__ = 'b'

    id = Column(String, primary_key=True)

    a_instances = relationship(
        A,
        backref = backref(
            'b_instances',
            collection_class = attribute_mapped_collection('id'),
        ),
        secondary = a_b_association_table,
        collection_class = attribute_mapped_collection('id'),
    )

engine = create_engine('sqlite://')
Base.metadata.bind = engine
Base.metadata.create_all()

Session = sessionmaker(bind=engine)

session = Session()

a1, a2, a3 = A(id=1), A(id=2), A(id=3)
b1, b2, b3 = B(id='a'), B(id='b'), B(id='c')

session.add_all([a1, a2, a3, b1, b2, b3])
session.flush()

print(a1.b_instances)
print(b1.a_instances)
a1.b_instances[b1.id] = b1
a1.b_instances[b2.id] = b2
b1.a_instances[a1.id] = a1
b1.a_instances[a2.id] = a2
session.flush()
session.expunge_all()
a1 = session.query(A).get(1)
b1 = session.query(B).get('a')
print(a1.b_instances)
print(b1.a_instances)

rawDescription: Bidirectional many-to-many attribute_mapped_collection, sqlalchemy


rawDescription: Python tkinter find_overlapping tuple?

description: Python tkinter find_overlapping tuple


code: min_val, min_key = min((D[k], k) for k in S)

rawDescription: Python: iterating over subset of dictionary


code: a = m.group(1) if m else some_default_value

rawDescription: Redundant If Statement and Regex

description: Redundant If Statement and Regex


code:
# run.py
import sys
problem = __import__(sys.argv[1], fromlist=["main"])         # I have also tired 'from problem import main' w/ same result
problem.main()

rawDescription: How can I import a python file through a command prompt?

description: Import a python file through a command prompt


code: all( type(i) is int for i in lst )

rawDescription: if all in list == something

description: If all in list == something


rawDescription: Python: Extracting float values from array of lists


code: string = "The brown fox jumped over the red barn, and found 10 chickens."

rawDescription: Python regex endline

description: Python regex endline


code:
arrs = [atleast_1d(_m) for _m in tup]
[atleast_2d(_m) for _m in tup]

rawDescription: Numpy: get 1D array as 2D array without reshape


code:
from itertools import takewhile
maxValue = c.most_common(1)[0][1]
list(takewhile(lambda x: x[1] == maxValue, c.most_common()))

rawDescription: Python Dict more than one Max value

description: Python Dict more than one Max value


code:
one
two

rawDescription: Passing inputs from a text file to python program using batch file


code:
import timeit

def foo_tuple():
    return (2, 3, 4)

def foo_list():
    return [2, 3, 4]

assert foo_tuple() is foo_tuple()

number = 10000000
t_interned_tuple = timeit.timeit('foo_tuple()', setup='from __main__ import foo_tuple', number=number)
t_list = (timeit.timeit('foo_list()', setup='from __main__ import foo_list', number=number))

print(t_interned_tuple)
print(t_list)
print(t_interned_tuple / t_list)
print('*' * 80)

def tuple_creation(x):
    return (x,)

def list_creation(x):
    return [x]

t_create_tuple = timeit.timeit('tuple_creation(2)', setup='from __main__ import tuple_creation', number=number)
t_create_list = timeit.timeit('list_creation(2)', setup='from __main__ import list_creation', number=number)
print(t_create_tuple)
print(t_create_list)
print(t_create_tuple / t_create_list)

rawDescription: In Python, when are two objects the same?


code:
for func, param in zip(string1, string2):
    func(param)

rawDescription: python execute list and list of functions

description: Python execute list and list of functions


code:
if callback:
    callback(file_info.st_size, file_size)
else:
    print('{0} of {1} downloaded'.format(file_info.st_size, file_size))

rawDescription: Parsing print in python

description: Parsing print in python